2 * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
25 #include <sys/resource.h>
28 #include "fatal-signal.h"
33 VLOG_DEFINE_THIS_MODULE(timeval);
35 /* The clock to use for measuring time intervals. This is CLOCK_MONOTONIC by
36 * preference, but on systems that don't have a monotonic clock we fall back
37 * to CLOCK_REALTIME. */
38 static clockid_t monotonic_clock;
40 /* Has a timer tick occurred?
42 * We initialize these to true to force time_init() to get called on the first
43 * call to time_msec() or another function that queries the current time. */
44 static volatile sig_atomic_t wall_tick = true;
45 static volatile sig_atomic_t monotonic_tick = true;
47 /* The current time, as of the last refresh. */
48 static struct timespec wall_time;
49 static struct timespec monotonic_time;
51 /* Time at which to die with SIGALRM (if not TIME_MIN). */
52 static time_t deadline = TIME_MIN;
54 static void set_up_timer(void);
55 static void set_up_signal(int flags);
56 static void sigalrm_handler(int);
57 static void refresh_wall_if_ticked(void);
58 static void refresh_monotonic_if_ticked(void);
59 static time_t time_add(time_t, time_t);
60 static void block_sigalrm(sigset_t *);
61 static void unblock_sigalrm(const sigset_t *);
62 static void log_poll_interval(long long int last_wakeup);
63 static struct rusage *get_recent_rusage(void);
64 static void refresh_rusage(void);
66 /* Initializes the timetracking module.
68 * It is not necessary to call this function directly, because other time
69 * functions will call it automatically, but it doesn't hurt. */
81 if (!clock_gettime(CLOCK_MONOTONIC, &monotonic_time)) {
82 monotonic_clock = CLOCK_MONOTONIC;
84 monotonic_clock = CLOCK_REALTIME;
85 VLOG_DBG("monotonic timer not available");
88 set_up_signal(SA_RESTART);
93 set_up_signal(int flags)
97 memset(&sa, 0, sizeof sa);
98 sa.sa_handler = sigalrm_handler;
99 sigemptyset(&sa.sa_mask);
101 xsigaction(SIGALRM, &sa, NULL);
104 /* Remove SA_RESTART from the flags for SIGALRM, so that any system call that
105 * is interrupted by the periodic timer interrupt will return EINTR instead of
106 * continuing after the signal handler returns.
108 * time_disable_restart() and time_enable_restart() may be usefully wrapped
109 * around function calls that might otherwise block forever unless interrupted
112 * time_disable_restart();
113 * fcntl(fd, F_SETLKW, &lock);
114 * time_enable_restart();
117 time_disable_restart(void)
123 /* Add SA_RESTART to the flags for SIGALRM, so that any system call that
124 * is interrupted by the periodic timer interrupt will continue after the
125 * signal handler returns instead of returning EINTR. */
127 time_enable_restart(void)
130 set_up_signal(SA_RESTART);
136 static timer_t timer_id; /* "static" to avoid apparent memory leak. */
137 struct itimerspec itimer;
139 if (timer_create(monotonic_clock, NULL, &timer_id)) {
140 VLOG_FATAL("timer_create failed (%s)", strerror(errno));
143 itimer.it_interval.tv_sec = 0;
144 itimer.it_interval.tv_nsec = TIME_UPDATE_INTERVAL * 1000 * 1000;
145 itimer.it_value = itimer.it_interval;
147 if (timer_settime(timer_id, 0, &itimer, NULL)) {
148 VLOG_FATAL("timer_settime failed (%s)", strerror(errno));
152 /* Set up the interval timer, to ensure that time advances even without calling
155 * A child created with fork() does not inherit the parent's interval timer, so
156 * this function needs to be called from the child after fork(). */
168 clock_gettime(CLOCK_REALTIME, &wall_time);
173 refresh_monotonic(void)
177 if (monotonic_clock == CLOCK_MONOTONIC) {
178 clock_gettime(monotonic_clock, &monotonic_time);
180 refresh_wall_if_ticked();
181 monotonic_time = wall_time;
184 monotonic_tick = false;
187 /* Forces a refresh of the current time from the kernel. It is not usually
188 * necessary to call this function, since the time will be refreshed
189 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. */
193 wall_tick = monotonic_tick = true;
196 /* Returns a monotonic timer, in seconds. */
200 refresh_monotonic_if_ticked();
201 return monotonic_time.tv_sec;
204 /* Same as time_now() except does not write to static variables, for use in
205 * signal handlers. */
209 struct timespec cur_time;
211 clock_gettime(monotonic_clock, &cur_time);
212 return cur_time.tv_sec;
215 /* Returns the current time, in seconds. */
219 refresh_wall_if_ticked();
220 return wall_time.tv_sec;
223 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
227 refresh_monotonic_if_ticked();
228 return timespec_to_msec(&monotonic_time);
231 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
235 refresh_wall_if_ticked();
236 return timespec_to_msec(&wall_time);
239 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
242 time_timespec(struct timespec *ts)
244 refresh_monotonic_if_ticked();
245 *ts = monotonic_time;
248 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
251 time_wall_timespec(struct timespec *ts)
253 refresh_wall_if_ticked();
257 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
258 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
260 time_alarm(unsigned int secs)
265 block_sigalrm(&oldsigs);
266 deadline = secs ? time_add(time_now(), secs) : TIME_MIN;
267 unblock_sigalrm(&oldsigs);
270 /* Like poll(), except:
272 * - On error, returns a negative error code (instead of setting errno).
274 * - If interrupted by a signal, retries automatically until the original
275 * 'timeout' expires. (Because of this property, this function will
276 * never return -EINTR.)
278 * - As a side effect, refreshes the current time (like time_refresh()).
281 time_poll(struct pollfd *pollfds, int n_pollfds, int timeout)
283 static long long int last_wakeup;
290 log_poll_interval(last_wakeup);
297 long long int elapsed = time_msec() - start;
298 time_left = timeout >= elapsed ? timeout - elapsed : 0;
303 retval = poll(pollfds, n_pollfds, time_left);
308 if (retval != -EINTR) {
312 if (!blocked && deadline == TIME_MIN) {
313 block_sigalrm(&oldsigs);
318 unblock_sigalrm(&oldsigs);
320 last_wakeup = time_msec();
325 /* Returns the sum of 'a' and 'b', with saturation on overflow or underflow. */
327 time_add(time_t a, time_t b)
330 ? (b > TIME_MAX - a ? TIME_MAX : a + b)
331 : (b < TIME_MIN - a ? TIME_MIN : a + b));
335 sigalrm_handler(int sig_nr)
338 monotonic_tick = true;
339 if (deadline != TIME_MIN && time_now_sig() > deadline) {
340 fatal_signal_handler(sig_nr);
345 refresh_wall_if_ticked(void)
353 refresh_monotonic_if_ticked(void)
355 if (monotonic_tick) {
361 block_sigalrm(sigset_t *oldsigs)
364 sigemptyset(&sigalrm);
365 sigaddset(&sigalrm, SIGALRM);
366 xsigprocmask(SIG_BLOCK, &sigalrm, oldsigs);
370 unblock_sigalrm(const sigset_t *oldsigs)
372 xsigprocmask(SIG_SETMASK, oldsigs, NULL);
376 timespec_to_msec(const struct timespec *ts)
378 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
382 timeval_to_msec(const struct timeval *tv)
384 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
388 xgettimeofday(struct timeval *tv)
390 if (gettimeofday(tv, NULL) == -1) {
391 VLOG_FATAL("gettimeofday failed (%s)", strerror(errno));
396 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
398 return timeval_to_msec(a) - timeval_to_msec(b);
402 log_poll_interval(long long int last_wakeup)
404 static unsigned int mean_interval; /* In 16ths of a millisecond. */
405 static unsigned int n_samples;
408 unsigned int interval; /* In 16ths of a millisecond. */
410 /* Compute interval from last wakeup to now in 16ths of a millisecond,
411 * capped at 10 seconds (16000 in this unit). */
413 interval = MIN(10000, now - last_wakeup) << 4;
415 /* Warn if we took too much time between polls: at least 50 ms and at least
416 * 8X the mean interval. */
417 if (n_samples > 10 && interval > mean_interval * 8 && interval > 50 * 16) {
418 const struct rusage *last_rusage = get_recent_rusage();
419 struct rusage rusage;
421 getrusage(RUSAGE_SELF, &rusage);
422 VLOG_WARN("%lld ms poll interval (%lld ms user, %lld ms system) "
423 "is over %u times the weighted mean interval %u ms "
426 timeval_diff_msec(&rusage.ru_utime, &last_rusage->ru_utime),
427 timeval_diff_msec(&rusage.ru_stime, &last_rusage->ru_stime),
428 interval / mean_interval,
429 (mean_interval + 8) / 16, n_samples);
430 if (rusage.ru_minflt > last_rusage->ru_minflt
431 || rusage.ru_majflt > last_rusage->ru_majflt) {
432 VLOG_WARN("faults: %ld minor, %ld major",
433 rusage.ru_minflt - last_rusage->ru_minflt,
434 rusage.ru_majflt - last_rusage->ru_majflt);
436 if (rusage.ru_inblock > last_rusage->ru_inblock
437 || rusage.ru_oublock > last_rusage->ru_oublock) {
438 VLOG_WARN("disk: %ld reads, %ld writes",
439 rusage.ru_inblock - last_rusage->ru_inblock,
440 rusage.ru_oublock - last_rusage->ru_oublock);
442 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
443 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
444 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
445 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
446 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
449 /* Care should be taken in the value chosen for logging. Depending
450 * on the configuration, syslog can write changes synchronously,
451 * which can cause the coverage messages to take longer to log
452 * than the processing delay that triggered it. */
453 coverage_log(VLL_INFO, true);
456 /* Update exponentially weighted moving average. With these parameters, a
457 * given value decays to 1% of its value in about 100 time steps. */
459 mean_interval = (mean_interval * 122 + interval * 6 + 64) / 128;
461 mean_interval = interval;
465 /* CPU usage tracking. */
468 long long int when; /* Time that this sample was taken. */
469 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
472 static struct rusage recent_rusage;
473 static struct cpu_usage older = { LLONG_MIN, 0 };
474 static struct cpu_usage newer = { LLONG_MIN, 0 };
475 static int cpu_usage = -1;
477 static struct rusage *
478 get_recent_rusage(void)
480 return &recent_rusage;
489 getrusage(RUSAGE_SELF, &recent_rusage);
491 if (now >= newer.when + 3 * 1000) {
494 newer.cpu = (timeval_to_msec(&recent_rusage.ru_utime) +
495 timeval_to_msec(&recent_rusage.ru_stime));
497 if (older.when != LLONG_MIN && newer.cpu > older.cpu) {
498 unsigned int dividend = newer.cpu - older.cpu;
499 unsigned int divisor = (newer.when - older.when) / 100;
500 cpu_usage = divisor > 0 ? dividend / divisor : -1;
507 /* Returns an estimate of this process's CPU usage, as a percentage, over the
508 * past few seconds of wall-clock time. Returns -1 if no estimate is available
509 * (which will happen if the process has not been running long enough to have
510 * an estimate, and can happen for other reasons as well). */