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.
26 #include <sys/resource.h>
30 #include "dynamic-string.h"
31 #include "fatal-signal.h"
34 #include "ovs-thread.h"
40 VLOG_DEFINE_THIS_MODULE(timeval);
43 clockid_t id; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
44 pthread_rwlock_t rwlock; /* Mutual exclusion for 'cache'. */
46 /* Features for use by unit tests. Protected by 'rwlock'. */
47 struct timespec warp; /* Offset added for unit tests. */
48 bool stopped; /* Disables real-time updates if true. */
50 /* Relevant only if CACHE_TIME is true. */
51 volatile sig_atomic_t tick; /* Has the timer ticked? Set by signal. */
52 struct timespec cache; /* Last time read from kernel. */
56 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
57 static struct clock wall_clock; /* CLOCK_REALTIME. */
59 /* The monotonic time at which the time module was initialized. */
60 static long long int boot_time;
62 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
64 static long long int deadline = LLONG_MAX;
66 static void set_up_timer(void);
67 static void set_up_signal(int flags);
68 static void sigalrm_handler(int);
69 static void block_sigalrm(sigset_t *);
70 static void unblock_sigalrm(const sigset_t *);
71 static void log_poll_interval(long long int last_wakeup);
72 static struct rusage *get_recent_rusage(void);
73 static void refresh_rusage(void);
74 static void timespec_add(struct timespec *sum,
75 const struct timespec *a, const struct timespec *b);
78 init_clock(struct clock *c, clockid_t id)
80 memset(c, 0, sizeof *c);
82 xpthread_rwlock_init(&c->rwlock, NULL);
83 xclock_gettime(c->id, &c->cache);
93 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
96 init_clock(&wall_clock, CLOCK_REALTIME);
97 boot_time = timespec_to_msec(&monotonic_clock.cache);
99 set_up_signal(SA_RESTART);
103 /* Initializes the timetracking module, if not already initialized. */
107 static pthread_once_t once = PTHREAD_ONCE_INIT;
108 pthread_once(&once, do_init_time);
112 set_up_signal(int flags)
116 memset(&sa, 0, sizeof sa);
117 sa.sa_handler = sigalrm_handler;
118 sigemptyset(&sa.sa_mask);
120 xsigaction(SIGALRM, &sa, NULL);
126 static timer_t timer_id; /* "static" to avoid apparent memory leak. */
127 struct itimerspec itimer;
133 if (timer_create(monotonic_clock.id, NULL, &timer_id)) {
134 VLOG_FATAL("timer_create failed (%s)", ovs_strerror(errno));
137 itimer.it_interval.tv_sec = 0;
138 itimer.it_interval.tv_nsec = TIME_UPDATE_INTERVAL * 1000 * 1000;
139 itimer.it_value = itimer.it_interval;
141 if (timer_settime(timer_id, 0, &itimer, NULL)) {
142 VLOG_FATAL("timer_settime failed (%s)", ovs_strerror(errno));
146 /* Set up the interval timer, to ensure that time advances even without calling
149 * A child created with fork() does not inherit the parent's interval timer, so
150 * this function needs to be called from the child after fork(). */
158 /* Forces a refresh of the current time from the kernel. It is not usually
159 * necessary to call this function, since the time will be refreshed
160 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. If
161 * CACHE_TIME is false, we will always refresh the current time so this
162 * function has no effect. */
166 monotonic_clock.tick = wall_clock.tick = true;
170 time_timespec__(struct clock *c, struct timespec *ts)
174 /* Use the cached time by preference, but fall through if there's been
176 xpthread_rwlock_rdlock(&c->rwlock);
177 if (c->stopped || !c->tick) {
178 timespec_add(ts, &c->cache, &c->warp);
179 xpthread_rwlock_unlock(&c->rwlock);
182 xpthread_rwlock_unlock(&c->rwlock);
184 /* Refresh the cache. */
185 xpthread_rwlock_wrlock(&c->rwlock);
188 xclock_gettime(c->id, &c->cache);
190 xpthread_rwlock_unlock(&c->rwlock);
194 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
197 time_timespec(struct timespec *ts)
199 time_timespec__(&monotonic_clock, ts);
202 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
205 time_wall_timespec(struct timespec *ts)
207 time_timespec__(&wall_clock, ts);
211 time_sec__(struct clock *c)
215 time_timespec__(c, &ts);
219 /* Returns a monotonic timer, in seconds. */
223 return time_sec__(&monotonic_clock);
226 /* Returns the current time, in seconds. */
230 return time_sec__(&wall_clock);
234 time_msec__(struct clock *c)
238 time_timespec__(c, &ts);
239 return timespec_to_msec(&ts);
242 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
246 return time_msec__(&monotonic_clock);
249 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
253 return time_msec__(&wall_clock);
256 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
257 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
259 time_alarm(unsigned int secs)
264 assert_single_threaded();
269 msecs = secs * 1000LL;
270 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
273 /* Like poll(), except:
275 * - The timeout is specified as an absolute time, as defined by
276 * time_msec(), instead of a duration.
278 * - On error, returns a negative error code (instead of setting errno).
280 * - If interrupted by a signal, retries automatically until the original
281 * timeout is reached. (Because of this property, this function will
282 * never return -EINTR.)
284 * - As a side effect, refreshes the current time (like time_refresh()).
286 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
288 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
291 static long long int last_wakeup = 0;
299 log_poll_interval(last_wakeup);
305 timeout_when = MIN(timeout_when, deadline);
308 long long int now = time_msec();
311 if (now >= timeout_when) {
313 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
316 time_left = timeout_when - now;
319 retval = poll(pollfds, n_pollfds, time_left);
325 if (deadline <= time_msec()) {
326 fatal_signal_handler(SIGALRM);
333 if (retval != -EINTR) {
337 if (!blocked && CACHE_TIME) {
338 block_sigalrm(&oldsigs);
343 unblock_sigalrm(&oldsigs);
345 last_wakeup = time_msec();
347 *elapsed = last_wakeup - start;
352 sigalrm_handler(int sig_nr OVS_UNUSED)
354 monotonic_clock.tick = wall_clock.tick = true;
358 block_sigalrm(sigset_t *oldsigs)
361 sigemptyset(&sigalrm);
362 sigaddset(&sigalrm, SIGALRM);
363 xpthread_sigmask(SIG_BLOCK, &sigalrm, oldsigs);
367 unblock_sigalrm(const sigset_t *oldsigs)
369 xpthread_sigmask(SIG_SETMASK, oldsigs, NULL);
373 timespec_to_msec(const struct timespec *ts)
375 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
379 timeval_to_msec(const struct timeval *tv)
381 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
384 /* Returns the monotonic time at which the "time" module was initialized, in
394 xgettimeofday(struct timeval *tv)
396 if (gettimeofday(tv, NULL) == -1) {
397 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
402 xclock_gettime(clock_t id, struct timespec *ts)
404 if (clock_gettime(id, ts) == -1) {
405 /* It seems like a bad idea to try to use vlog here because it is
406 * likely to try to check the current time. */
407 ovs_abort(errno, "xclock_gettime() failed");
412 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
414 return timeval_to_msec(a) - timeval_to_msec(b);
418 timespec_add(struct timespec *sum,
419 const struct timespec *a,
420 const struct timespec *b)
424 tmp.tv_sec = a->tv_sec + b->tv_sec;
425 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
426 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
427 tmp.tv_nsec -= 1000 * 1000 * 1000;
435 log_poll_interval(long long int last_wakeup)
437 long long int interval = time_msec() - last_wakeup;
440 && !monotonic_clock.warp.tv_sec
441 && !monotonic_clock.warp.tv_nsec) {
442 const struct rusage *last_rusage = get_recent_rusage();
443 struct rusage rusage;
445 getrusage(RUSAGE_SELF, &rusage);
446 VLOG_WARN("Unreasonably long %lldms poll interval"
447 " (%lldms user, %lldms system)",
449 timeval_diff_msec(&rusage.ru_utime,
450 &last_rusage->ru_utime),
451 timeval_diff_msec(&rusage.ru_stime,
452 &last_rusage->ru_stime));
453 if (rusage.ru_minflt > last_rusage->ru_minflt
454 || rusage.ru_majflt > last_rusage->ru_majflt) {
455 VLOG_WARN("faults: %ld minor, %ld major",
456 rusage.ru_minflt - last_rusage->ru_minflt,
457 rusage.ru_majflt - last_rusage->ru_majflt);
459 if (rusage.ru_inblock > last_rusage->ru_inblock
460 || rusage.ru_oublock > last_rusage->ru_oublock) {
461 VLOG_WARN("disk: %ld reads, %ld writes",
462 rusage.ru_inblock - last_rusage->ru_inblock,
463 rusage.ru_oublock - last_rusage->ru_oublock);
465 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
466 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
467 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
468 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
469 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
475 /* CPU usage tracking. */
478 long long int when; /* Time that this sample was taken. */
479 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
482 static struct rusage recent_rusage;
483 static struct cpu_usage older = { LLONG_MIN, 0 };
484 static struct cpu_usage newer = { LLONG_MIN, 0 };
485 static int cpu_usage = -1;
487 static struct rusage *
488 get_recent_rusage(void)
490 return &recent_rusage;
499 getrusage(RUSAGE_SELF, &recent_rusage);
501 if (now >= newer.when + 3 * 1000) {
504 newer.cpu = (timeval_to_msec(&recent_rusage.ru_utime) +
505 timeval_to_msec(&recent_rusage.ru_stime));
507 if (older.when != LLONG_MIN && newer.cpu > older.cpu) {
508 unsigned int dividend = newer.cpu - older.cpu;
509 unsigned int divisor = (newer.when - older.when) / 100;
510 cpu_usage = divisor > 0 ? dividend / divisor : -1;
517 /* Returns an estimate of this process's CPU usage, as a percentage, over the
518 * past few seconds of wall-clock time. Returns -1 if no estimate is available
519 * (which will happen if the process has not been running long enough to have
520 * an estimate, and can happen for other reasons as well). */
527 /* Unixctl interface. */
529 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
530 * advancing, except due to later calls to "time/warp". */
532 timeval_stop_cb(struct unixctl_conn *conn,
533 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
534 void *aux OVS_UNUSED)
536 xpthread_rwlock_wrlock(&monotonic_clock.rwlock);
537 monotonic_clock.stopped = true;
538 xpthread_rwlock_unlock(&monotonic_clock.rwlock);
540 unixctl_command_reply(conn, NULL);
543 /* "time/warp MSECS" advances the current monotonic time by the specified
544 * number of milliseconds. Unless "time/stop" has also been executed, the
545 * monotonic clock continues to tick forward at the normal rate afterward.
547 * Does not affect wall clock readings. */
549 timeval_warp_cb(struct unixctl_conn *conn,
550 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
555 msecs = atoi(argv[1]);
557 unixctl_command_reply_error(conn, "invalid MSECS");
561 ts.tv_sec = msecs / 1000;
562 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
564 xpthread_rwlock_wrlock(&monotonic_clock.rwlock);
565 timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
566 xpthread_rwlock_unlock(&monotonic_clock.rwlock);
568 unixctl_command_reply(conn, "warped");
572 timeval_dummy_register(void)
574 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
575 unixctl_command_register("time/warp", "MSECS", 1, 1,
576 timeval_warp_cb, NULL);