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"
33 #include "ovs-thread.h"
39 VLOG_DEFINE_THIS_MODULE(timeval);
41 /* The clock to use for measuring time intervals. This is CLOCK_MONOTONIC by
42 * preference, but on systems that don't have a monotonic clock we fall back
43 * to CLOCK_REALTIME. */
44 static clockid_t monotonic_clock;
46 /* Has a timer tick occurred? Only relevant if CACHE_TIME is true.
48 * We initialize these to true to force time_init() to get called on the first
49 * call to time_msec() or another function that queries the current time. */
50 static volatile sig_atomic_t wall_tick = true;
51 static volatile sig_atomic_t monotonic_tick = true;
53 /* The current time, as of the last refresh. */
54 static struct timespec wall_time;
55 static struct timespec monotonic_time;
57 /* The monotonic time at which the time module was initialized. */
58 static long long int boot_time;
60 /* features for use by unit tests. */
61 static struct timespec warp_offset; /* Offset added to monotonic_time. */
62 static bool time_stopped; /* Disables real-time updates, if true. */
64 /* Time in milliseconds at which to die with SIGALRM (if not LLONG_MAX). */
65 static long long int deadline = LLONG_MAX;
67 static void set_up_timer(void);
68 static void set_up_signal(int flags);
69 static void sigalrm_handler(int);
70 static void refresh_wall_if_ticked(void);
71 static void refresh_monotonic_if_ticked(void);
72 static void block_sigalrm(sigset_t *);
73 static void unblock_sigalrm(const sigset_t *);
74 static void log_poll_interval(long long int last_wakeup);
75 static struct rusage *get_recent_rusage(void);
76 static void refresh_rusage(void);
77 static void timespec_add(struct timespec *sum,
78 const struct timespec *a, const struct timespec *b);
80 /* Initializes the timetracking module, if not already initialized. */
93 if (!clock_gettime(CLOCK_MONOTONIC, &monotonic_time)) {
94 monotonic_clock = CLOCK_MONOTONIC;
96 monotonic_clock = CLOCK_REALTIME;
97 VLOG_DBG("monotonic timer not available");
100 set_up_signal(SA_RESTART);
103 boot_time = time_msec();
107 set_up_signal(int flags)
111 memset(&sa, 0, sizeof sa);
112 sa.sa_handler = sigalrm_handler;
113 sigemptyset(&sa.sa_mask);
115 xsigaction(SIGALRM, &sa, NULL);
121 static timer_t timer_id; /* "static" to avoid apparent memory leak. */
122 struct itimerspec itimer;
128 if (timer_create(monotonic_clock, NULL, &timer_id)) {
129 VLOG_FATAL("timer_create failed (%s)", ovs_strerror(errno));
132 itimer.it_interval.tv_sec = 0;
133 itimer.it_interval.tv_nsec = TIME_UPDATE_INTERVAL * 1000 * 1000;
134 itimer.it_value = itimer.it_interval;
136 if (timer_settime(timer_id, 0, &itimer, NULL)) {
137 VLOG_FATAL("timer_settime failed (%s)", ovs_strerror(errno));
141 /* Set up the interval timer, to ensure that time advances even without calling
144 * A child created with fork() does not inherit the parent's interval timer, so
145 * this function needs to be called from the child after fork(). */
157 xclock_gettime(CLOCK_REALTIME, &wall_time);
162 refresh_monotonic(void)
167 if (monotonic_clock == CLOCK_MONOTONIC) {
168 xclock_gettime(monotonic_clock, &monotonic_time);
170 refresh_wall_if_ticked();
171 monotonic_time = wall_time;
173 timespec_add(&monotonic_time, &monotonic_time, &warp_offset);
175 monotonic_tick = false;
179 /* Forces a refresh of the current time from the kernel. It is not usually
180 * necessary to call this function, since the time will be refreshed
181 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. If
182 * CACHE_TIME is false, we will always refresh the current time so this
183 * function has no effect. */
187 wall_tick = monotonic_tick = true;
190 /* Returns a monotonic timer, in seconds. */
194 refresh_monotonic_if_ticked();
195 return monotonic_time.tv_sec;
198 /* Returns the current time, in seconds. */
202 refresh_wall_if_ticked();
203 return wall_time.tv_sec;
206 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
210 refresh_monotonic_if_ticked();
211 return timespec_to_msec(&monotonic_time);
214 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
218 refresh_wall_if_ticked();
219 return timespec_to_msec(&wall_time);
222 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
225 time_timespec(struct timespec *ts)
227 refresh_monotonic_if_ticked();
228 *ts = monotonic_time;
231 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
234 time_wall_timespec(struct timespec *ts)
236 refresh_wall_if_ticked();
240 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
241 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
243 time_alarm(unsigned int secs)
248 assert_single_threaded();
253 msecs = secs * 1000LL;
254 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
257 /* Like poll(), except:
259 * - The timeout is specified as an absolute time, as defined by
260 * time_msec(), instead of a duration.
262 * - On error, returns a negative error code (instead of setting errno).
264 * - If interrupted by a signal, retries automatically until the original
265 * timeout is reached. (Because of this property, this function will
266 * never return -EINTR.)
268 * - As a side effect, refreshes the current time (like time_refresh()).
270 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
272 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
275 static long long int last_wakeup = 0;
283 log_poll_interval(last_wakeup);
289 timeout_when = MIN(timeout_when, deadline);
292 long long int now = time_msec();
295 if (now >= timeout_when) {
297 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
300 time_left = timeout_when - now;
303 retval = poll(pollfds, n_pollfds, time_left);
309 if (deadline <= time_msec()) {
310 fatal_signal_handler(SIGALRM);
317 if (retval != -EINTR) {
321 if (!blocked && CACHE_TIME) {
322 block_sigalrm(&oldsigs);
327 unblock_sigalrm(&oldsigs);
329 last_wakeup = time_msec();
331 *elapsed = last_wakeup - start;
336 sigalrm_handler(int sig_nr OVS_UNUSED)
339 monotonic_tick = true;
343 refresh_wall_if_ticked(void)
345 if (!CACHE_TIME || wall_tick) {
351 refresh_monotonic_if_ticked(void)
353 if (!CACHE_TIME || monotonic_tick) {
359 block_sigalrm(sigset_t *oldsigs)
362 sigemptyset(&sigalrm);
363 sigaddset(&sigalrm, SIGALRM);
364 xpthread_sigmask(SIG_BLOCK, &sigalrm, oldsigs);
368 unblock_sigalrm(const sigset_t *oldsigs)
370 xpthread_sigmask(SIG_SETMASK, oldsigs, NULL);
374 timespec_to_msec(const struct timespec *ts)
376 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
380 timeval_to_msec(const struct timeval *tv)
382 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
385 /* Returns the monotonic time at which the "time" module was initialized, in
395 xgettimeofday(struct timeval *tv)
397 if (gettimeofday(tv, NULL) == -1) {
398 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
403 xclock_gettime(clock_t id, struct timespec *ts)
405 if (clock_gettime(id, ts) == -1) {
406 /* It seems like a bad idea to try to use vlog here because it is
407 * likely to try to check the current time. */
408 ovs_abort(errno, "xclock_gettime() failed");
413 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
415 return timeval_to_msec(a) - timeval_to_msec(b);
419 timespec_add(struct timespec *sum,
420 const struct timespec *a,
421 const struct timespec *b)
425 tmp.tv_sec = a->tv_sec + b->tv_sec;
426 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
427 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
428 tmp.tv_nsec -= 1000 * 1000 * 1000;
436 log_poll_interval(long long int last_wakeup)
438 long long int interval = time_msec() - last_wakeup;
440 if (interval >= 1000 && !warp_offset.tv_sec && !warp_offset.tv_nsec) {
441 const struct rusage *last_rusage = get_recent_rusage();
442 struct rusage rusage;
444 getrusage(RUSAGE_SELF, &rusage);
445 VLOG_WARN("Unreasonably long %lldms poll interval"
446 " (%lldms user, %lldms system)",
448 timeval_diff_msec(&rusage.ru_utime,
449 &last_rusage->ru_utime),
450 timeval_diff_msec(&rusage.ru_stime,
451 &last_rusage->ru_stime));
452 if (rusage.ru_minflt > last_rusage->ru_minflt
453 || rusage.ru_majflt > last_rusage->ru_majflt) {
454 VLOG_WARN("faults: %ld minor, %ld major",
455 rusage.ru_minflt - last_rusage->ru_minflt,
456 rusage.ru_majflt - last_rusage->ru_majflt);
458 if (rusage.ru_inblock > last_rusage->ru_inblock
459 || rusage.ru_oublock > last_rusage->ru_oublock) {
460 VLOG_WARN("disk: %ld reads, %ld writes",
461 rusage.ru_inblock - last_rusage->ru_inblock,
462 rusage.ru_oublock - last_rusage->ru_oublock);
464 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
465 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
466 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
467 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
468 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
474 /* CPU usage tracking. */
477 long long int when; /* Time that this sample was taken. */
478 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
481 static struct rusage recent_rusage;
482 static struct cpu_usage older = { LLONG_MIN, 0 };
483 static struct cpu_usage newer = { LLONG_MIN, 0 };
484 static int cpu_usage = -1;
486 static struct rusage *
487 get_recent_rusage(void)
489 return &recent_rusage;
498 getrusage(RUSAGE_SELF, &recent_rusage);
500 if (now >= newer.when + 3 * 1000) {
503 newer.cpu = (timeval_to_msec(&recent_rusage.ru_utime) +
504 timeval_to_msec(&recent_rusage.ru_stime));
506 if (older.when != LLONG_MIN && newer.cpu > older.cpu) {
507 unsigned int dividend = newer.cpu - older.cpu;
508 unsigned int divisor = (newer.when - older.when) / 100;
509 cpu_usage = divisor > 0 ? dividend / divisor : -1;
516 /* Returns an estimate of this process's CPU usage, as a percentage, over the
517 * past few seconds of wall-clock time. Returns -1 if no estimate is available
518 * (which will happen if the process has not been running long enough to have
519 * an estimate, and can happen for other reasons as well). */
526 /* Unixctl interface. */
528 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
529 * advancing, except due to later calls to "time/warp". */
531 timeval_stop_cb(struct unixctl_conn *conn,
532 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
533 void *aux OVS_UNUSED)
536 unixctl_command_reply(conn, NULL);
539 /* "time/warp MSECS" advances the current monotonic time by the specified
540 * number of milliseconds. Unless "time/stop" has also been executed, the
541 * monotonic clock continues to tick forward at the normal rate afterward.
543 * Does not affect wall clock readings. */
545 timeval_warp_cb(struct unixctl_conn *conn,
546 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
551 msecs = atoi(argv[1]);
553 unixctl_command_reply_error(conn, "invalid MSECS");
557 ts.tv_sec = msecs / 1000;
558 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
559 timespec_add(&warp_offset, &warp_offset, &ts);
560 timespec_add(&monotonic_time, &monotonic_time, &ts);
561 unixctl_command_reply(conn, "warped");
565 timeval_dummy_register(void)
567 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
568 unixctl_command_register("time/warp", "MSECS", 1, 1,
569 timeval_warp_cb, NULL);