2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 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.
25 #include <sys/resource.h>
29 #include "dynamic-string.h"
30 #include "fatal-signal.h"
38 /* backtrace() from <execinfo.h> is really useful, but it is not signal safe
39 * everywhere, such as on x86-64. */
40 #if HAVE_BACKTRACE && !defined __x86_64__
41 # define USE_BACKTRACE 1
42 # include <execinfo.h>
44 # define USE_BACKTRACE 0
47 VLOG_DEFINE_THIS_MODULE(timeval);
49 /* The clock to use for measuring time intervals. This is CLOCK_MONOTONIC by
50 * preference, but on systems that don't have a monotonic clock we fall back
51 * to CLOCK_REALTIME. */
52 static clockid_t monotonic_clock;
54 /* Has a timer tick occurred? Only relevant if CACHE_TIME is true.
56 * We initialize these to true to force time_init() to get called on the first
57 * call to time_msec() or another function that queries the current time. */
58 static volatile sig_atomic_t wall_tick = true;
59 static volatile sig_atomic_t monotonic_tick = true;
61 /* The current time, as of the last refresh. */
62 static struct timespec wall_time;
63 static struct timespec monotonic_time;
65 /* The monotonic time at which the time module was initialized. */
66 static long long int boot_time;
68 /* features for use by unit tests. */
69 static struct timespec warp_offset; /* Offset added to monotonic_time. */
70 static bool time_stopped; /* Disables real-time updates, if true. */
72 /* Time in milliseconds at which to die with SIGALRM (if not LLONG_MAX). */
73 static long long int deadline = LLONG_MAX;
76 void *backtrace[32]; /* Populated by backtrace(). */
77 size_t n_frames; /* Number of frames in 'backtrace'. */
79 /* format_backtraces() helper data. */
80 struct hmap_node node;
85 static struct trace traces[MAX_TRACES];
86 static size_t trace_head = 0;
88 static void set_up_timer(void);
89 static void set_up_signal(int flags);
90 static void sigalrm_handler(int);
91 static void refresh_wall_if_ticked(void);
92 static void refresh_monotonic_if_ticked(void);
93 static void block_sigalrm(sigset_t *);
94 static void unblock_sigalrm(const sigset_t *);
95 static void log_poll_interval(long long int last_wakeup);
96 static struct rusage *get_recent_rusage(void);
97 static void refresh_rusage(void);
98 static void timespec_add(struct timespec *sum,
99 const struct timespec *a, const struct timespec *b);
100 static unixctl_cb_func backtrace_cb;
104 backtrace(void **buffer OVS_UNUSED, int size OVS_UNUSED)
110 backtrace_symbols(void *const *buffer OVS_UNUSED, int size OVS_UNUSED)
114 #endif /* !USE_BACKTRACE */
116 /* Initializes the timetracking module, if not already initialized. */
127 /* The implementation of backtrace() in glibc does some one time
128 * initialization which is not signal safe. This can cause deadlocks if
129 * run from the signal handler. As a workaround, force the initialization
134 backtrace(bt, ARRAY_SIZE(bt));
137 memset(traces, 0, sizeof traces);
139 if (USE_BACKTRACE && CACHE_TIME) {
140 unixctl_command_register("backtrace", "", 0, 0, backtrace_cb, NULL);
145 if (!clock_gettime(CLOCK_MONOTONIC, &monotonic_time)) {
146 monotonic_clock = CLOCK_MONOTONIC;
148 monotonic_clock = CLOCK_REALTIME;
149 VLOG_DBG("monotonic timer not available");
152 set_up_signal(SA_RESTART);
155 boot_time = time_msec();
159 set_up_signal(int flags)
163 memset(&sa, 0, sizeof sa);
164 sa.sa_handler = sigalrm_handler;
165 sigemptyset(&sa.sa_mask);
167 xsigaction(SIGALRM, &sa, NULL);
170 /* Remove SA_RESTART from the flags for SIGALRM, so that any system call that
171 * is interrupted by the periodic timer interrupt will return EINTR instead of
172 * continuing after the signal handler returns.
174 * time_disable_restart() and time_enable_restart() may be usefully wrapped
175 * around function calls that might otherwise block forever unless interrupted
178 * time_disable_restart();
179 * fcntl(fd, F_SETLKW, &lock);
180 * time_enable_restart();
183 time_disable_restart(void)
189 /* Add SA_RESTART to the flags for SIGALRM, so that any system call that
190 * is interrupted by the periodic timer interrupt will continue after the
191 * signal handler returns instead of returning EINTR. */
193 time_enable_restart(void)
196 set_up_signal(SA_RESTART);
202 static timer_t timer_id; /* "static" to avoid apparent memory leak. */
203 struct itimerspec itimer;
209 if (timer_create(monotonic_clock, NULL, &timer_id)) {
210 VLOG_FATAL("timer_create failed (%s)", strerror(errno));
213 itimer.it_interval.tv_sec = 0;
214 itimer.it_interval.tv_nsec = TIME_UPDATE_INTERVAL * 1000 * 1000;
215 itimer.it_value = itimer.it_interval;
217 if (timer_settime(timer_id, 0, &itimer, NULL)) {
218 VLOG_FATAL("timer_settime failed (%s)", strerror(errno));
222 /* Set up the interval timer, to ensure that time advances even without calling
225 * A child created with fork() does not inherit the parent's interval timer, so
226 * this function needs to be called from the child after fork(). */
238 clock_gettime(CLOCK_REALTIME, &wall_time);
243 refresh_monotonic(void)
248 if (monotonic_clock == CLOCK_MONOTONIC) {
249 clock_gettime(monotonic_clock, &monotonic_time);
251 refresh_wall_if_ticked();
252 monotonic_time = wall_time;
254 timespec_add(&monotonic_time, &monotonic_time, &warp_offset);
256 monotonic_tick = false;
260 /* Forces a refresh of the current time from the kernel. It is not usually
261 * necessary to call this function, since the time will be refreshed
262 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. If
263 * CACHE_TIME is false, we will always refresh the current time so this
264 * function has no effect. */
268 wall_tick = monotonic_tick = true;
271 /* Returns a monotonic timer, in seconds. */
275 refresh_monotonic_if_ticked();
276 return monotonic_time.tv_sec;
279 /* Returns the current time, in seconds. */
283 refresh_wall_if_ticked();
284 return wall_time.tv_sec;
287 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
291 refresh_monotonic_if_ticked();
292 return timespec_to_msec(&monotonic_time);
295 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
299 refresh_wall_if_ticked();
300 return timespec_to_msec(&wall_time);
303 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
306 time_timespec(struct timespec *ts)
308 refresh_monotonic_if_ticked();
309 *ts = monotonic_time;
312 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
315 time_wall_timespec(struct timespec *ts)
317 refresh_wall_if_ticked();
321 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
322 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
324 time_alarm(unsigned int secs)
333 msecs = secs * 1000LL;
334 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
337 /* Like poll(), except:
339 * - The timeout is specified as an absolute time, as defined by
340 * time_msec(), instead of a duration.
342 * - On error, returns a negative error code (instead of setting errno).
344 * - If interrupted by a signal, retries automatically until the original
345 * timeout is reached. (Because of this property, this function will
346 * never return -EINTR.)
348 * - As a side effect, refreshes the current time (like time_refresh()).
350 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
352 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
355 static long long int last_wakeup = 0;
363 log_poll_interval(last_wakeup);
369 timeout_when = MIN(timeout_when, deadline);
372 long long int now = time_msec();
375 if (now >= timeout_when) {
377 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
380 time_left = timeout_when - now;
383 retval = poll(pollfds, n_pollfds, time_left);
389 if (deadline <= time_msec()) {
390 fatal_signal_handler(SIGALRM);
397 if (retval != -EINTR) {
401 if (!blocked && CACHE_TIME) {
402 block_sigalrm(&oldsigs);
407 unblock_sigalrm(&oldsigs);
409 last_wakeup = time_msec();
411 *elapsed = last_wakeup - start;
416 sigalrm_handler(int sig_nr OVS_UNUSED)
419 monotonic_tick = true;
421 if (USE_BACKTRACE && CACHE_TIME) {
422 struct trace *trace = &traces[trace_head];
424 trace->n_frames = backtrace(trace->backtrace,
425 ARRAY_SIZE(trace->backtrace));
426 trace_head = (trace_head + 1) % MAX_TRACES;
431 refresh_wall_if_ticked(void)
433 if (!CACHE_TIME || wall_tick) {
439 refresh_monotonic_if_ticked(void)
441 if (!CACHE_TIME || monotonic_tick) {
447 block_sigalrm(sigset_t *oldsigs)
450 sigemptyset(&sigalrm);
451 sigaddset(&sigalrm, SIGALRM);
452 xpthread_sigmask(SIG_BLOCK, &sigalrm, oldsigs);
456 unblock_sigalrm(const sigset_t *oldsigs)
458 xpthread_sigmask(SIG_SETMASK, oldsigs, NULL);
462 timespec_to_msec(const struct timespec *ts)
464 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
468 timeval_to_msec(const struct timeval *tv)
470 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
473 /* Returns the monotonic time at which the "time" module was initialized, in
483 xgettimeofday(struct timeval *tv)
485 if (gettimeofday(tv, NULL) == -1) {
486 VLOG_FATAL("gettimeofday failed (%s)", strerror(errno));
491 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
493 return timeval_to_msec(a) - timeval_to_msec(b);
497 timespec_add(struct timespec *sum,
498 const struct timespec *a,
499 const struct timespec *b)
503 tmp.tv_sec = a->tv_sec + b->tv_sec;
504 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
505 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
506 tmp.tv_nsec -= 1000 * 1000 * 1000;
514 log_poll_interval(long long int last_wakeup)
516 long long int interval = time_msec() - last_wakeup;
518 if (interval >= 1000 && !warp_offset.tv_sec && !warp_offset.tv_nsec) {
519 const struct rusage *last_rusage = get_recent_rusage();
520 struct rusage rusage;
522 getrusage(RUSAGE_SELF, &rusage);
523 VLOG_WARN("Unreasonably long %lldms poll interval"
524 " (%lldms user, %lldms system)",
526 timeval_diff_msec(&rusage.ru_utime,
527 &last_rusage->ru_utime),
528 timeval_diff_msec(&rusage.ru_stime,
529 &last_rusage->ru_stime));
530 if (rusage.ru_minflt > last_rusage->ru_minflt
531 || rusage.ru_majflt > last_rusage->ru_majflt) {
532 VLOG_WARN("faults: %ld minor, %ld major",
533 rusage.ru_minflt - last_rusage->ru_minflt,
534 rusage.ru_majflt - last_rusage->ru_majflt);
536 if (rusage.ru_inblock > last_rusage->ru_inblock
537 || rusage.ru_oublock > last_rusage->ru_oublock) {
538 VLOG_WARN("disk: %ld reads, %ld writes",
539 rusage.ru_inblock - last_rusage->ru_inblock,
540 rusage.ru_oublock - last_rusage->ru_oublock);
542 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
543 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
544 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
545 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
546 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
552 /* CPU usage tracking. */
555 long long int when; /* Time that this sample was taken. */
556 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
559 static struct rusage recent_rusage;
560 static struct cpu_usage older = { LLONG_MIN, 0 };
561 static struct cpu_usage newer = { LLONG_MIN, 0 };
562 static int cpu_usage = -1;
564 static struct rusage *
565 get_recent_rusage(void)
567 return &recent_rusage;
576 getrusage(RUSAGE_SELF, &recent_rusage);
578 if (now >= newer.when + 3 * 1000) {
581 newer.cpu = (timeval_to_msec(&recent_rusage.ru_utime) +
582 timeval_to_msec(&recent_rusage.ru_stime));
584 if (older.when != LLONG_MIN && newer.cpu > older.cpu) {
585 unsigned int dividend = newer.cpu - older.cpu;
586 unsigned int divisor = (newer.when - older.when) / 100;
587 cpu_usage = divisor > 0 ? dividend / divisor : -1;
594 /* Returns an estimate of this process's CPU usage, as a percentage, over the
595 * past few seconds of wall-clock time. Returns -1 if no estimate is available
596 * (which will happen if the process has not been running long enough to have
597 * an estimate, and can happen for other reasons as well). */
605 hash_trace(struct trace *trace)
607 return hash_bytes(trace->backtrace,
608 trace->n_frames * sizeof *trace->backtrace, 0);
611 static struct trace *
612 trace_map_lookup(struct hmap *trace_map, struct trace *key)
616 HMAP_FOR_EACH_WITH_HASH (value, node, hash_trace(key), trace_map) {
617 if (key->n_frames == value->n_frames
618 && !memcmp(key->backtrace, value->backtrace,
619 key->n_frames * sizeof *key->backtrace)) {
626 /* Appends a string to 'ds' representing backtraces recorded at regular
627 * intervals in the recent past. This information can be used to get a sense
628 * of what the process has been spending the majority of time doing. Will
629 * ommit any backtraces which have not occurred at least 'min_count' times. */
631 format_backtraces(struct ds *ds, size_t min_count)
635 if (USE_BACKTRACE && CACHE_TIME) {
636 struct hmap trace_map = HMAP_INITIALIZER(&trace_map);
637 struct trace *trace, *next;
641 block_sigalrm(&oldsigs);
643 for (i = 0; i < MAX_TRACES; i++) {
644 struct trace *trace = &traces[i];
645 struct trace *map_trace;
647 if (!trace->n_frames) {
651 map_trace = trace_map_lookup(&trace_map, trace);
655 hmap_insert(&trace_map, &trace->node, hash_trace(trace));
660 HMAP_FOR_EACH_SAFE (trace, next, node, &trace_map) {
664 hmap_remove(&trace_map, &trace->node);
666 if (trace->count < min_count) {
670 frame_strs = backtrace_symbols(trace->backtrace, trace->n_frames);
672 ds_put_format(ds, "Count %zu\n", trace->count);
673 for (j = 0; j < trace->n_frames; j++) {
674 ds_put_format(ds, "%s\n", frame_strs[j]);
676 ds_put_cstr(ds, "\n");
680 hmap_destroy(&trace_map);
683 unblock_sigalrm(&oldsigs);
687 /* Unixctl interface. */
689 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
690 * advancing, except due to later calls to "time/warp". */
692 timeval_stop_cb(struct unixctl_conn *conn,
693 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
694 void *aux OVS_UNUSED)
697 unixctl_command_reply(conn, NULL);
700 /* "time/warp MSECS" advances the current monotonic time by the specified
701 * number of milliseconds. Unless "time/stop" has also been executed, the
702 * monotonic clock continues to tick forward at the normal rate afterward.
704 * Does not affect wall clock readings. */
706 timeval_warp_cb(struct unixctl_conn *conn,
707 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
712 msecs = atoi(argv[1]);
714 unixctl_command_reply_error(conn, "invalid MSECS");
718 ts.tv_sec = msecs / 1000;
719 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
720 timespec_add(&warp_offset, &warp_offset, &ts);
721 timespec_add(&monotonic_time, &monotonic_time, &ts);
722 unixctl_command_reply(conn, "warped");
726 backtrace_cb(struct unixctl_conn *conn,
727 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
728 void *aux OVS_UNUSED)
730 struct ds ds = DS_EMPTY_INITIALIZER;
732 ovs_assert(USE_BACKTRACE && CACHE_TIME);
733 format_backtraces(&ds, 0);
734 unixctl_command_reply(conn, ds_cstr(&ds));
739 timeval_dummy_register(void)
741 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
742 unixctl_command_register("time/warp", "MSECS", 1, 1,
743 timeval_warp_cb, NULL);