2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
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.
26 #include <sys/resource.h>
30 #include "fatal-signal.h"
36 VLOG_DEFINE_THIS_MODULE(timeval);
38 /* The clock to use for measuring time intervals. This is CLOCK_MONOTONIC by
39 * preference, but on systems that don't have a monotonic clock we fall back
40 * to CLOCK_REALTIME. */
41 static clockid_t monotonic_clock;
43 /* Controls whether or not calls to clock_gettime() are cached. See
44 * time_cached() for a detailed explanation. */
45 #if defined __x86_64__ && defined __linux__
46 static bool cache_time = false;
48 static bool cache_time = true;
51 /* Has a timer tick occurred? Only relevant if cache_time is true.
53 * We initialize these to true to force time_init() to get called on the first
54 * call to time_msec() or another function that queries the current time. */
55 static volatile sig_atomic_t wall_tick = true;
56 static volatile sig_atomic_t monotonic_tick = true;
58 /* The current time, as of the last refresh. */
59 static struct timespec wall_time;
60 static struct timespec monotonic_time;
62 /* The monotonic time at which the time module was initialized. */
63 static long long int boot_time;
65 /* features for use by unit tests. */
66 static struct timespec warp_offset; /* Offset added to monotonic_time. */
67 static bool time_stopped; /* Disables real-time updates, if true. */
69 /* Time in milliseconds at which to die with SIGALRM (if not LLONG_MAX). */
70 static long long int deadline = LLONG_MAX;
72 static void set_up_timer(void);
73 static void set_up_signal(int flags);
74 static void sigalrm_handler(int);
75 static void refresh_wall_if_ticked(void);
76 static void refresh_monotonic_if_ticked(void);
77 static void block_sigalrm(sigset_t *);
78 static void unblock_sigalrm(const sigset_t *);
79 static void log_poll_interval(long long int last_wakeup);
80 static struct rusage *get_recent_rusage(void);
81 static void refresh_rusage(void);
82 static void timespec_add(struct timespec *sum,
83 const struct timespec *a, const struct timespec *b);
85 /* Initializes the timetracking module, if not already initialized. */
97 if (!clock_gettime(CLOCK_MONOTONIC, &monotonic_time)) {
98 monotonic_clock = CLOCK_MONOTONIC;
100 monotonic_clock = CLOCK_REALTIME;
101 VLOG_DBG("monotonic timer not available");
104 set_up_signal(SA_RESTART);
107 boot_time = time_msec();
111 set_up_signal(int flags)
115 memset(&sa, 0, sizeof sa);
116 sa.sa_handler = sigalrm_handler;
117 sigemptyset(&sa.sa_mask);
119 xsigaction(SIGALRM, &sa, NULL);
122 /* Remove SA_RESTART from the flags for SIGALRM, so that any system call that
123 * is interrupted by the periodic timer interrupt will return EINTR instead of
124 * continuing after the signal handler returns.
126 * time_disable_restart() and time_enable_restart() may be usefully wrapped
127 * around function calls that might otherwise block forever unless interrupted
130 * time_disable_restart();
131 * fcntl(fd, F_SETLKW, &lock);
132 * time_enable_restart();
135 time_disable_restart(void)
141 /* Add SA_RESTART to the flags for SIGALRM, so that any system call that
142 * is interrupted by the periodic timer interrupt will continue after the
143 * signal handler returns instead of returning EINTR. */
145 time_enable_restart(void)
148 set_up_signal(SA_RESTART);
154 static timer_t timer_id; /* "static" to avoid apparent memory leak. */
155 struct itimerspec itimer;
161 if (timer_create(monotonic_clock, NULL, &timer_id)) {
162 VLOG_WARN("timer_create failed (%s), disabling cached timing",
168 itimer.it_interval.tv_sec = 0;
169 itimer.it_interval.tv_nsec = TIME_UPDATE_INTERVAL * 1000 * 1000;
170 itimer.it_value = itimer.it_interval;
172 if (timer_settime(timer_id, 0, &itimer, NULL)) {
173 VLOG_FATAL("timer_settime failed (%s)", strerror(errno));
177 /* Set up the interval timer, to ensure that time advances even without calling
180 * A child created with fork() does not inherit the parent's interval timer, so
181 * this function needs to be called from the child after fork(). */
193 clock_gettime(CLOCK_REALTIME, &wall_time);
198 refresh_monotonic(void)
203 if (monotonic_clock == CLOCK_MONOTONIC) {
204 clock_gettime(monotonic_clock, &monotonic_time);
206 refresh_wall_if_ticked();
207 monotonic_time = wall_time;
209 timespec_add(&monotonic_time, &monotonic_time, &warp_offset);
211 monotonic_tick = false;
215 /* Forces a refresh of the current time from the kernel. It is not usually
216 * necessary to call this function, since the time will be refreshed
217 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. If
218 * cache_time is false, we will always refresh the current time so this
219 * function has no effect. */
223 wall_tick = monotonic_tick = true;
226 /* Returns a monotonic timer, in seconds. */
230 refresh_monotonic_if_ticked();
231 return monotonic_time.tv_sec;
234 /* Returns the current time, in seconds. */
238 refresh_wall_if_ticked();
239 return wall_time.tv_sec;
242 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
246 refresh_monotonic_if_ticked();
247 return timespec_to_msec(&monotonic_time);
250 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
254 refresh_wall_if_ticked();
255 return timespec_to_msec(&wall_time);
258 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
261 time_timespec(struct timespec *ts)
263 refresh_monotonic_if_ticked();
264 *ts = monotonic_time;
267 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
270 time_wall_timespec(struct timespec *ts)
272 refresh_wall_if_ticked();
276 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
277 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
279 time_alarm(unsigned int secs)
292 block_sigalrm(&oldsigs);
293 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
294 unblock_sigalrm(&oldsigs);
297 /* Like poll(), except:
299 * - The timeout is specified as an absolute time, as defined by
300 * time_msec(), instead of a duration.
302 * - On error, returns a negative error code (instead of setting errno).
304 * - If interrupted by a signal, retries automatically until the original
305 * timeout is reached. (Because of this property, this function will
306 * never return -EINTR.)
308 * - As a side effect, refreshes the current time (like time_refresh()).
310 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
312 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
315 static long long int last_wakeup;
322 log_poll_interval(last_wakeup);
327 timeout_when = MIN(timeout_when, deadline);
330 long long int now = time_msec();
333 if (now >= timeout_when) {
335 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
338 time_left = timeout_when - now;
341 retval = poll(pollfds, n_pollfds, time_left);
347 if (deadline <= time_msec()) {
348 fatal_signal_handler(SIGALRM);
355 if (retval != -EINTR) {
359 if (!blocked && !cache_time) {
360 block_sigalrm(&oldsigs);
365 unblock_sigalrm(&oldsigs);
367 last_wakeup = time_msec();
369 *elapsed = last_wakeup - start;
373 /* True on systems (particularly x86-64 Linux) where clock_gettime() is
374 * inexpensive. On these systems, we don't bother caching the current time.
375 * Instead, we consult clock_gettime() directly when needed.
377 * False on systems where clock_gettime() is relatively expensive. On these
378 * systems, we cache the current time and set up a periodic SIGALRM to remind
381 * Also false on systems (e.g. ESX) that don't support setting up timers based
382 * on a monotonically increasing clock. */
391 sigalrm_handler(int sig_nr OVS_UNUSED)
394 monotonic_tick = true;
398 refresh_wall_if_ticked(void)
400 if (!cache_time || wall_tick) {
406 refresh_monotonic_if_ticked(void)
408 if (!cache_time || monotonic_tick) {
414 block_sigalrm(sigset_t *oldsigs)
417 sigemptyset(&sigalrm);
418 sigaddset(&sigalrm, SIGALRM);
419 xsigprocmask(SIG_BLOCK, &sigalrm, oldsigs);
423 unblock_sigalrm(const sigset_t *oldsigs)
425 xsigprocmask(SIG_SETMASK, oldsigs, NULL);
429 timespec_to_msec(const struct timespec *ts)
431 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
435 timeval_to_msec(const struct timeval *tv)
437 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
440 /* Returns the monotonic time at which the "time" module was initialized, in
450 xgettimeofday(struct timeval *tv)
452 if (gettimeofday(tv, NULL) == -1) {
453 VLOG_FATAL("gettimeofday failed (%s)", strerror(errno));
458 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
460 return timeval_to_msec(a) - timeval_to_msec(b);
464 timespec_add(struct timespec *sum,
465 const struct timespec *a,
466 const struct timespec *b)
470 tmp.tv_sec = a->tv_sec + b->tv_sec;
471 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
472 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
473 tmp.tv_nsec -= 1000 * 1000 * 1000;
481 log_poll_interval(long long int last_wakeup)
483 static unsigned int mean_interval; /* In 16ths of a millisecond. */
484 static unsigned int n_samples;
487 unsigned int interval; /* In 16ths of a millisecond. */
489 /* Compute interval from last wakeup to now in 16ths of a millisecond,
490 * capped at 10 seconds (16000 in this unit). */
492 interval = MIN(10000, now - last_wakeup) << 4;
494 /* Warn if we took too much time between polls: at least 50 ms and at least
495 * 8X the mean interval. */
496 if (n_samples > 10 && interval > mean_interval * 8 && interval > 50 * 16) {
497 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 3);
499 if (!VLOG_DROP_WARN(&rl)) {
500 const struct rusage *last_rusage = get_recent_rusage();
501 struct rusage rusage;
503 getrusage(RUSAGE_SELF, &rusage);
504 VLOG_WARN("%lld ms poll interval (%lld ms user, %lld ms system) "
505 "is over %u times the weighted mean interval %u ms "
508 timeval_diff_msec(&rusage.ru_utime,
509 &last_rusage->ru_utime),
510 timeval_diff_msec(&rusage.ru_stime,
511 &last_rusage->ru_stime),
512 interval / mean_interval,
513 (mean_interval + 8) / 16, n_samples);
514 if (rusage.ru_minflt > last_rusage->ru_minflt
515 || rusage.ru_majflt > last_rusage->ru_majflt) {
516 VLOG_WARN("faults: %ld minor, %ld major",
517 rusage.ru_minflt - last_rusage->ru_minflt,
518 rusage.ru_majflt - last_rusage->ru_majflt);
520 if (rusage.ru_inblock > last_rusage->ru_inblock
521 || rusage.ru_oublock > last_rusage->ru_oublock) {
522 VLOG_WARN("disk: %ld reads, %ld writes",
523 rusage.ru_inblock - last_rusage->ru_inblock,
524 rusage.ru_oublock - last_rusage->ru_oublock);
526 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
527 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
528 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
529 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
530 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
536 /* Update exponentially weighted moving average. With these parameters, a
537 * given value decays to 1% of its value in about 100 time steps. */
539 mean_interval = (mean_interval * 122 + interval * 6 + 64) / 128;
541 mean_interval = interval;
545 /* CPU usage tracking. */
548 long long int when; /* Time that this sample was taken. */
549 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
552 static struct rusage recent_rusage;
553 static struct cpu_usage older = { LLONG_MIN, 0 };
554 static struct cpu_usage newer = { LLONG_MIN, 0 };
555 static int cpu_usage = -1;
557 static struct rusage *
558 get_recent_rusage(void)
560 return &recent_rusage;
569 getrusage(RUSAGE_SELF, &recent_rusage);
571 if (now >= newer.when + 3 * 1000) {
574 newer.cpu = (timeval_to_msec(&recent_rusage.ru_utime) +
575 timeval_to_msec(&recent_rusage.ru_stime));
577 if (older.when != LLONG_MIN && newer.cpu > older.cpu) {
578 unsigned int dividend = newer.cpu - older.cpu;
579 unsigned int divisor = (newer.when - older.when) / 100;
580 cpu_usage = divisor > 0 ? dividend / divisor : -1;
587 /* Returns an estimate of this process's CPU usage, as a percentage, over the
588 * past few seconds of wall-clock time. Returns -1 if no estimate is available
589 * (which will happen if the process has not been running long enough to have
590 * an estimate, and can happen for other reasons as well). */
597 /* Unixctl interface. */
599 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
600 * advancing, except due to later calls to "time/warp". */
602 timeval_stop_cb(struct unixctl_conn *conn,
603 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
604 void *aux OVS_UNUSED)
607 unixctl_command_reply(conn, NULL);
610 /* "time/warp MSECS" advances the current monotonic time by the specified
611 * number of milliseconds. Unless "time/stop" has also been executed, the
612 * monotonic clock continues to tick forward at the normal rate afterward.
614 * Does not affect wall clock readings. */
616 timeval_warp_cb(struct unixctl_conn *conn,
617 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
622 msecs = atoi(argv[1]);
624 unixctl_command_reply_error(conn, "invalid MSECS");
628 ts.tv_sec = msecs / 1000;
629 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
630 timespec_add(&warp_offset, &warp_offset, &ts);
631 timespec_add(&monotonic_time, &monotonic_time, &ts);
632 unixctl_command_reply(conn, "warped");
636 timeval_dummy_register(void)
638 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
639 unixctl_command_register("time/warp", "MSECS", 1, 1,
640 timeval_warp_cb, NULL);