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.
29 #include <sys/resource.h>
33 #include "dynamic-string.h"
34 #include "fatal-signal.h"
42 VLOG_DEFINE_THIS_MODULE(timeval
);
44 /* The clock to use for measuring time intervals. This is CLOCK_MONOTONIC by
45 * preference, but on systems that don't have a monotonic clock we fall back
46 * to CLOCK_REALTIME. */
47 static clockid_t monotonic_clock
;
49 /* Has a timer tick occurred? Only relevant if CACHE_TIME is true.
51 * We initialize these to true to force time_init() to get called on the first
52 * call to time_msec() or another function that queries the current time. */
53 static volatile sig_atomic_t wall_tick
= true;
54 static volatile sig_atomic_t monotonic_tick
= true;
56 /* The current time, as of the last refresh. */
57 static struct timespec wall_time
;
58 static struct timespec monotonic_time
;
60 /* The monotonic time at which the time module was initialized. */
61 static long long int boot_time
;
63 /* features for use by unit tests. */
64 static struct timespec warp_offset
; /* Offset added to monotonic_time. */
65 static bool time_stopped
; /* Disables real-time updates, if true. */
67 /* Time in milliseconds at which to die with SIGALRM (if not LLONG_MAX). */
68 static long long int deadline
= LLONG_MAX
;
71 void *backtrace
[32]; /* Populated by backtrace(). */
72 size_t n_frames
; /* Number of frames in 'backtrace'. */
74 /* format_backtraces() helper data. */
75 struct hmap_node node
;
80 static struct trace traces
[MAX_TRACES
];
81 static size_t trace_head
= 0;
83 static void set_up_timer(void);
84 static void set_up_signal(int flags
);
85 static void sigalrm_handler(int);
86 static void refresh_wall_if_ticked(void);
87 static void refresh_monotonic_if_ticked(void);
88 static void block_sigalrm(sigset_t
*);
89 static void unblock_sigalrm(const sigset_t
*);
90 static void log_poll_interval(long long int last_wakeup
);
91 static struct rusage
*get_recent_rusage(void);
92 static void refresh_rusage(void);
93 static void timespec_add(struct timespec
*sum
,
94 const struct timespec
*a
, const struct timespec
*b
);
95 static unixctl_cb_func backtrace_cb
;
97 #ifndef HAVE_EXECINFO_H
98 #define HAVE_EXECINFO_H 0
101 backtrace(void **buffer OVS_UNUSED
, int size OVS_UNUSED
)
107 backtrace_symbols(void *const *buffer OVS_UNUSED
, int size OVS_UNUSED
)
113 /* Initializes the timetracking module, if not already initialized. */
124 /* The implementation of backtrace() in glibc does some one time
125 * initialization which is not signal safe. This can cause deadlocks if
126 * run from the signal handler. As a workaround, force the initialization
128 if (HAVE_EXECINFO_H
) {
131 backtrace(bt
, ARRAY_SIZE(bt
));
134 memset(traces
, 0, sizeof traces
);
136 if (HAVE_EXECINFO_H
&& CACHE_TIME
) {
137 unixctl_command_register("backtrace", "", 0, 0, backtrace_cb
, NULL
);
142 if (!clock_gettime(CLOCK_MONOTONIC
, &monotonic_time
)) {
143 monotonic_clock
= CLOCK_MONOTONIC
;
145 monotonic_clock
= CLOCK_REALTIME
;
146 VLOG_DBG("monotonic timer not available");
149 set_up_signal(SA_RESTART
);
152 boot_time
= time_msec();
156 set_up_signal(int flags
)
160 memset(&sa
, 0, sizeof sa
);
161 sa
.sa_handler
= sigalrm_handler
;
162 sigemptyset(&sa
.sa_mask
);
164 xsigaction(SIGALRM
, &sa
, NULL
);
167 /* Remove SA_RESTART from the flags for SIGALRM, so that any system call that
168 * is interrupted by the periodic timer interrupt will return EINTR instead of
169 * continuing after the signal handler returns.
171 * time_disable_restart() and time_enable_restart() may be usefully wrapped
172 * around function calls that might otherwise block forever unless interrupted
175 * time_disable_restart();
176 * fcntl(fd, F_SETLKW, &lock);
177 * time_enable_restart();
180 time_disable_restart(void)
186 /* Add SA_RESTART to the flags for SIGALRM, so that any system call that
187 * is interrupted by the periodic timer interrupt will continue after the
188 * signal handler returns instead of returning EINTR. */
190 time_enable_restart(void)
193 set_up_signal(SA_RESTART
);
199 static timer_t timer_id
; /* "static" to avoid apparent memory leak. */
200 struct itimerspec itimer
;
206 if (timer_create(monotonic_clock
, NULL
, &timer_id
)) {
207 VLOG_FATAL("timer_create failed (%s)", strerror(errno
));
210 itimer
.it_interval
.tv_sec
= 0;
211 itimer
.it_interval
.tv_nsec
= TIME_UPDATE_INTERVAL
* 1000 * 1000;
212 itimer
.it_value
= itimer
.it_interval
;
214 if (timer_settime(timer_id
, 0, &itimer
, NULL
)) {
215 VLOG_FATAL("timer_settime failed (%s)", strerror(errno
));
219 /* Set up the interval timer, to ensure that time advances even without calling
222 * A child created with fork() does not inherit the parent's interval timer, so
223 * this function needs to be called from the child after fork(). */
235 clock_gettime(CLOCK_REALTIME
, &wall_time
);
240 refresh_monotonic(void)
245 if (monotonic_clock
== CLOCK_MONOTONIC
) {
246 clock_gettime(monotonic_clock
, &monotonic_time
);
248 refresh_wall_if_ticked();
249 monotonic_time
= wall_time
;
251 timespec_add(&monotonic_time
, &monotonic_time
, &warp_offset
);
253 monotonic_tick
= false;
257 /* Forces a refresh of the current time from the kernel. It is not usually
258 * necessary to call this function, since the time will be refreshed
259 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. If
260 * CACHE_TIME is false, we will always refresh the current time so this
261 * function has no effect. */
265 wall_tick
= monotonic_tick
= true;
268 /* Returns a monotonic timer, in seconds. */
272 refresh_monotonic_if_ticked();
273 return monotonic_time
.tv_sec
;
276 /* Returns the current time, in seconds. */
280 refresh_wall_if_ticked();
281 return wall_time
.tv_sec
;
284 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
288 refresh_monotonic_if_ticked();
289 return timespec_to_msec(&monotonic_time
);
292 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
296 refresh_wall_if_ticked();
297 return timespec_to_msec(&wall_time
);
300 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
303 time_timespec(struct timespec
*ts
)
305 refresh_monotonic_if_ticked();
306 *ts
= monotonic_time
;
309 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
312 time_wall_timespec(struct timespec
*ts
)
314 refresh_wall_if_ticked();
318 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
319 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
321 time_alarm(unsigned int secs
)
334 block_sigalrm(&oldsigs
);
335 deadline
= now
< LLONG_MAX
- msecs
? now
+ msecs
: LLONG_MAX
;
336 unblock_sigalrm(&oldsigs
);
339 /* Like poll(), except:
341 * - The timeout is specified as an absolute time, as defined by
342 * time_msec(), instead of a duration.
344 * - On error, returns a negative error code (instead of setting errno).
346 * - If interrupted by a signal, retries automatically until the original
347 * timeout is reached. (Because of this property, this function will
348 * never return -EINTR.)
350 * - As a side effect, refreshes the current time (like time_refresh()).
352 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
354 time_poll(struct pollfd
*pollfds
, int n_pollfds
, long long int timeout_when
,
357 static long long int last_wakeup
= 0;
365 log_poll_interval(last_wakeup
);
371 timeout_when
= MIN(timeout_when
, deadline
);
374 long long int now
= time_msec();
377 if (now
>= timeout_when
) {
379 } else if ((unsigned long long int) timeout_when
- now
> INT_MAX
) {
382 time_left
= timeout_when
- now
;
385 retval
= poll(pollfds
, n_pollfds
, time_left
);
391 if (deadline
<= time_msec()) {
392 fatal_signal_handler(SIGALRM
);
399 if (retval
!= -EINTR
) {
403 if (!blocked
&& CACHE_TIME
) {
404 block_sigalrm(&oldsigs
);
409 unblock_sigalrm(&oldsigs
);
411 last_wakeup
= time_msec();
413 *elapsed
= last_wakeup
- start
;
418 sigalrm_handler(int sig_nr OVS_UNUSED
)
421 monotonic_tick
= true;
423 if (HAVE_EXECINFO_H
&& CACHE_TIME
) {
424 struct trace
*trace
= &traces
[trace_head
];
426 trace
->n_frames
= backtrace(trace
->backtrace
,
427 ARRAY_SIZE(trace
->backtrace
));
428 trace_head
= (trace_head
+ 1) % MAX_TRACES
;
433 refresh_wall_if_ticked(void)
435 if (!CACHE_TIME
|| wall_tick
) {
441 refresh_monotonic_if_ticked(void)
443 if (!CACHE_TIME
|| monotonic_tick
) {
449 block_sigalrm(sigset_t
*oldsigs
)
452 sigemptyset(&sigalrm
);
453 sigaddset(&sigalrm
, SIGALRM
);
454 xsigprocmask(SIG_BLOCK
, &sigalrm
, oldsigs
);
458 unblock_sigalrm(const sigset_t
*oldsigs
)
460 xsigprocmask(SIG_SETMASK
, oldsigs
, NULL
);
464 timespec_to_msec(const struct timespec
*ts
)
466 return (long long int) ts
->tv_sec
* 1000 + ts
->tv_nsec
/ (1000 * 1000);
470 timeval_to_msec(const struct timeval
*tv
)
472 return (long long int) tv
->tv_sec
* 1000 + tv
->tv_usec
/ 1000;
475 /* Returns the monotonic time at which the "time" module was initialized, in
485 xgettimeofday(struct timeval
*tv
)
487 if (gettimeofday(tv
, NULL
) == -1) {
488 VLOG_FATAL("gettimeofday failed (%s)", strerror(errno
));
493 timeval_diff_msec(const struct timeval
*a
, const struct timeval
*b
)
495 return timeval_to_msec(a
) - timeval_to_msec(b
);
499 timespec_add(struct timespec
*sum
,
500 const struct timespec
*a
,
501 const struct timespec
*b
)
505 tmp
.tv_sec
= a
->tv_sec
+ b
->tv_sec
;
506 tmp
.tv_nsec
= a
->tv_nsec
+ b
->tv_nsec
;
507 if (tmp
.tv_nsec
>= 1000 * 1000 * 1000) {
508 tmp
.tv_nsec
-= 1000 * 1000 * 1000;
516 log_poll_interval(long long int last_wakeup
)
518 long long int interval
= time_msec() - last_wakeup
;
520 if (interval
>= 1000) {
521 const struct rusage
*last_rusage
= get_recent_rusage();
522 struct rusage rusage
;
524 getrusage(RUSAGE_SELF
, &rusage
);
525 VLOG_WARN("Unreasonably long %lldms poll interval"
526 " (%lldms user, %lldms system)",
528 timeval_diff_msec(&rusage
.ru_utime
,
529 &last_rusage
->ru_utime
),
530 timeval_diff_msec(&rusage
.ru_stime
,
531 &last_rusage
->ru_stime
));
532 if (rusage
.ru_minflt
> last_rusage
->ru_minflt
533 || rusage
.ru_majflt
> last_rusage
->ru_majflt
) {
534 VLOG_WARN("faults: %ld minor, %ld major",
535 rusage
.ru_minflt
- last_rusage
->ru_minflt
,
536 rusage
.ru_majflt
- last_rusage
->ru_majflt
);
538 if (rusage
.ru_inblock
> last_rusage
->ru_inblock
539 || rusage
.ru_oublock
> last_rusage
->ru_oublock
) {
540 VLOG_WARN("disk: %ld reads, %ld writes",
541 rusage
.ru_inblock
- last_rusage
->ru_inblock
,
542 rusage
.ru_oublock
- last_rusage
->ru_oublock
);
544 if (rusage
.ru_nvcsw
> last_rusage
->ru_nvcsw
545 || rusage
.ru_nivcsw
> last_rusage
->ru_nivcsw
) {
546 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
547 rusage
.ru_nvcsw
- last_rusage
->ru_nvcsw
,
548 rusage
.ru_nivcsw
- last_rusage
->ru_nivcsw
);
554 /* CPU usage tracking. */
557 long long int when
; /* Time that this sample was taken. */
558 unsigned long long int cpu
; /* Total user+system CPU usage when sampled. */
561 static struct rusage recent_rusage
;
562 static struct cpu_usage older
= { LLONG_MIN
, 0 };
563 static struct cpu_usage newer
= { LLONG_MIN
, 0 };
564 static int cpu_usage
= -1;
566 static struct rusage
*
567 get_recent_rusage(void)
569 return &recent_rusage
;
578 getrusage(RUSAGE_SELF
, &recent_rusage
);
580 if (now
>= newer
.when
+ 3 * 1000) {
583 newer
.cpu
= (timeval_to_msec(&recent_rusage
.ru_utime
) +
584 timeval_to_msec(&recent_rusage
.ru_stime
));
586 if (older
.when
!= LLONG_MIN
&& newer
.cpu
> older
.cpu
) {
587 unsigned int dividend
= newer
.cpu
- older
.cpu
;
588 unsigned int divisor
= (newer
.when
- older
.when
) / 100;
589 cpu_usage
= divisor
> 0 ? dividend
/ divisor
: -1;
596 /* Returns an estimate of this process's CPU usage, as a percentage, over the
597 * past few seconds of wall-clock time. Returns -1 if no estimate is available
598 * (which will happen if the process has not been running long enough to have
599 * an estimate, and can happen for other reasons as well). */
607 hash_trace(struct trace
*trace
)
609 return hash_bytes(trace
->backtrace
,
610 trace
->n_frames
* sizeof *trace
->backtrace
, 0);
613 static struct trace
*
614 trace_map_lookup(struct hmap
*trace_map
, struct trace
*key
)
618 HMAP_FOR_EACH_WITH_HASH (value
, node
, hash_trace(key
), trace_map
) {
619 if (key
->n_frames
== value
->n_frames
620 && !memcmp(key
->backtrace
, value
->backtrace
,
621 key
->n_frames
* sizeof *key
->backtrace
)) {
628 /* Appends a string to 'ds' representing backtraces recorded at regular
629 * intervals in the recent past. This information can be used to get a sense
630 * of what the process has been spending the majority of time doing. Will
631 * ommit any backtraces which have not occurred at least 'min_count' times. */
633 format_backtraces(struct ds
*ds
, size_t min_count
)
637 if (HAVE_EXECINFO_H
&& CACHE_TIME
) {
638 struct hmap trace_map
= HMAP_INITIALIZER(&trace_map
);
639 struct trace
*trace
, *next
;
643 block_sigalrm(&oldsigs
);
645 for (i
= 0; i
< MAX_TRACES
; i
++) {
646 struct trace
*trace
= &traces
[i
];
647 struct trace
*map_trace
;
649 if (!trace
->n_frames
) {
653 map_trace
= trace_map_lookup(&trace_map
, trace
);
657 hmap_insert(&trace_map
, &trace
->node
, hash_trace(trace
));
662 HMAP_FOR_EACH_SAFE (trace
, next
, node
, &trace_map
) {
666 hmap_remove(&trace_map
, &trace
->node
);
668 if (trace
->count
< min_count
) {
672 frame_strs
= backtrace_symbols(trace
->backtrace
, trace
->n_frames
);
674 ds_put_format(ds
, "Count %zu\n", trace
->count
);
675 for (j
= 0; j
< trace
->n_frames
; j
++) {
676 ds_put_format(ds
, "%s\n", frame_strs
[j
]);
678 ds_put_cstr(ds
, "\n");
682 hmap_destroy(&trace_map
);
685 unblock_sigalrm(&oldsigs
);
689 /* Unixctl interface. */
691 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
692 * advancing, except due to later calls to "time/warp". */
694 timeval_stop_cb(struct unixctl_conn
*conn
,
695 int argc OVS_UNUSED
, const char *argv
[] OVS_UNUSED
,
696 void *aux OVS_UNUSED
)
699 unixctl_command_reply(conn
, NULL
);
702 /* "time/warp MSECS" advances the current monotonic time by the specified
703 * number of milliseconds. Unless "time/stop" has also been executed, the
704 * monotonic clock continues to tick forward at the normal rate afterward.
706 * Does not affect wall clock readings. */
708 timeval_warp_cb(struct unixctl_conn
*conn
,
709 int argc OVS_UNUSED
, const char *argv
[], void *aux OVS_UNUSED
)
714 msecs
= atoi(argv
[1]);
716 unixctl_command_reply_error(conn
, "invalid MSECS");
720 ts
.tv_sec
= msecs
/ 1000;
721 ts
.tv_nsec
= (msecs
% 1000) * 1000 * 1000;
722 timespec_add(&warp_offset
, &warp_offset
, &ts
);
723 timespec_add(&monotonic_time
, &monotonic_time
, &ts
);
724 unixctl_command_reply(conn
, "warped");
728 backtrace_cb(struct unixctl_conn
*conn
,
729 int argc OVS_UNUSED
, const char *argv
[] OVS_UNUSED
,
730 void *aux OVS_UNUSED
)
732 struct ds ds
= DS_EMPTY_INITIALIZER
;
734 assert(HAVE_EXECINFO_H
&& CACHE_TIME
);
735 format_backtraces(&ds
, 0);
736 unixctl_command_reply(conn
, ds_cstr(&ds
));
741 timeval_dummy_register(void)
743 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb
, NULL
);
744 unixctl_command_register("time/warp", "MSECS", 1, 1,
745 timeval_warp_cb
, NULL
);