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 struct ovs_rwlock 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 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
68 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup, 0);
70 static void set_up_timer(void);
71 static void set_up_signal(int flags);
72 static void sigalrm_handler(int);
73 static void block_sigalrm(sigset_t *);
74 static void unblock_sigalrm(const sigset_t *);
75 static void log_poll_interval(long long int last_wakeup);
76 static struct rusage *get_recent_rusage(void);
77 static void refresh_rusage(void);
78 static void timespec_add(struct timespec *sum,
79 const struct timespec *a, const struct timespec *b);
82 init_clock(struct clock *c, clockid_t id)
84 memset(c, 0, sizeof *c);
86 ovs_rwlock_init(&c->rwlock);
87 xclock_gettime(c->id, &c->cache);
97 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
100 init_clock(&wall_clock, CLOCK_REALTIME);
101 boot_time = timespec_to_msec(&monotonic_clock.cache);
103 set_up_signal(SA_RESTART);
107 /* Initializes the timetracking module, if not already initialized. */
111 static pthread_once_t once = PTHREAD_ONCE_INIT;
112 pthread_once(&once, do_init_time);
116 set_up_signal(int flags)
120 memset(&sa, 0, sizeof sa);
121 sa.sa_handler = sigalrm_handler;
122 sigemptyset(&sa.sa_mask);
124 xsigaction(SIGALRM, &sa, NULL);
130 static timer_t timer_id; /* "static" to avoid apparent memory leak. */
131 struct itimerspec itimer;
137 if (timer_create(monotonic_clock.id, NULL, &timer_id)) {
138 VLOG_FATAL("timer_create failed (%s)", ovs_strerror(errno));
141 itimer.it_interval.tv_sec = 0;
142 itimer.it_interval.tv_nsec = TIME_UPDATE_INTERVAL * 1000 * 1000;
143 itimer.it_value = itimer.it_interval;
145 if (timer_settime(timer_id, 0, &itimer, NULL)) {
146 VLOG_FATAL("timer_settime failed (%s)", ovs_strerror(errno));
150 /* Set up the interval timer, to ensure that time advances even without calling
153 * A child created with fork() does not inherit the parent's interval timer, so
154 * this function needs to be called from the child after fork(). */
158 assert_single_threaded();
163 /* Forces a refresh of the current time from the kernel. It is not usually
164 * necessary to call this function, since the time will be refreshed
165 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. If
166 * CACHE_TIME is false, we will always refresh the current time so this
167 * function has no effect. */
171 monotonic_clock.tick = wall_clock.tick = true;
175 time_timespec__(struct clock *c, struct timespec *ts)
179 /* Use the cached time by preference, but fall through if there's been
181 ovs_rwlock_rdlock(&c->rwlock);
182 if (c->stopped || !c->tick) {
183 timespec_add(ts, &c->cache, &c->warp);
184 ovs_rwlock_unlock(&c->rwlock);
187 ovs_rwlock_unlock(&c->rwlock);
189 /* Refresh the cache. */
190 ovs_rwlock_wrlock(&c->rwlock);
193 xclock_gettime(c->id, &c->cache);
195 ovs_rwlock_unlock(&c->rwlock);
199 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
202 time_timespec(struct timespec *ts)
204 time_timespec__(&monotonic_clock, ts);
207 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
210 time_wall_timespec(struct timespec *ts)
212 time_timespec__(&wall_clock, ts);
216 time_sec__(struct clock *c)
220 time_timespec__(c, &ts);
224 /* Returns a monotonic timer, in seconds. */
228 return time_sec__(&monotonic_clock);
231 /* Returns the current time, in seconds. */
235 return time_sec__(&wall_clock);
239 time_msec__(struct clock *c)
243 time_timespec__(c, &ts);
244 return timespec_to_msec(&ts);
247 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
251 return time_msec__(&monotonic_clock);
254 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
258 return time_msec__(&wall_clock);
261 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
262 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
264 time_alarm(unsigned int secs)
269 assert_single_threaded();
274 msecs = secs * 1000LL;
275 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
278 /* Like poll(), except:
280 * - The timeout is specified as an absolute time, as defined by
281 * time_msec(), instead of a duration.
283 * - On error, returns a negative error code (instead of setting errno).
285 * - If interrupted by a signal, retries automatically until the original
286 * timeout is reached. (Because of this property, this function will
287 * never return -EINTR.)
289 * - As a side effect, refreshes the current time (like time_refresh()).
291 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
293 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
296 long long int *last_wakeup = last_wakeup_get();
305 log_poll_interval(*last_wakeup);
311 timeout_when = MIN(timeout_when, deadline);
314 long long int now = time_msec();
317 if (now >= timeout_when) {
319 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
322 time_left = timeout_when - now;
325 retval = poll(pollfds, n_pollfds, time_left);
331 if (deadline <= time_msec()) {
332 fatal_signal_handler(SIGALRM);
339 if (retval != -EINTR) {
343 if (!blocked && CACHE_TIME) {
344 block_sigalrm(&oldsigs);
349 unblock_sigalrm(&oldsigs);
351 *last_wakeup = time_msec();
353 *elapsed = *last_wakeup - start;
358 sigalrm_handler(int sig_nr OVS_UNUSED)
360 monotonic_clock.tick = wall_clock.tick = true;
364 block_sigalrm(sigset_t *oldsigs)
367 sigemptyset(&sigalrm);
368 sigaddset(&sigalrm, SIGALRM);
369 xpthread_sigmask(SIG_BLOCK, &sigalrm, oldsigs);
373 unblock_sigalrm(const sigset_t *oldsigs)
375 xpthread_sigmask(SIG_SETMASK, oldsigs, NULL);
379 timespec_to_msec(const struct timespec *ts)
381 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
385 timeval_to_msec(const struct timeval *tv)
387 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
390 /* Returns the monotonic time at which the "time" module was initialized, in
400 xgettimeofday(struct timeval *tv)
402 if (gettimeofday(tv, NULL) == -1) {
403 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
408 xclock_gettime(clock_t id, struct timespec *ts)
410 if (clock_gettime(id, ts) == -1) {
411 /* It seems like a bad idea to try to use vlog here because it is
412 * likely to try to check the current time. */
413 ovs_abort(errno, "xclock_gettime() failed");
418 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
420 return timeval_to_msec(a) - timeval_to_msec(b);
424 timespec_add(struct timespec *sum,
425 const struct timespec *a,
426 const struct timespec *b)
430 tmp.tv_sec = a->tv_sec + b->tv_sec;
431 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
432 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
433 tmp.tv_nsec -= 1000 * 1000 * 1000;
441 log_poll_interval(long long int last_wakeup)
443 long long int interval = time_msec() - last_wakeup;
446 && !monotonic_clock.warp.tv_sec
447 && !monotonic_clock.warp.tv_nsec) {
448 const struct rusage *last_rusage = get_recent_rusage();
449 struct rusage rusage;
451 getrusage(RUSAGE_SELF, &rusage);
452 VLOG_WARN("Unreasonably long %lldms poll interval"
453 " (%lldms user, %lldms system)",
455 timeval_diff_msec(&rusage.ru_utime,
456 &last_rusage->ru_utime),
457 timeval_diff_msec(&rusage.ru_stime,
458 &last_rusage->ru_stime));
459 if (rusage.ru_minflt > last_rusage->ru_minflt
460 || rusage.ru_majflt > last_rusage->ru_majflt) {
461 VLOG_WARN("faults: %ld minor, %ld major",
462 rusage.ru_minflt - last_rusage->ru_minflt,
463 rusage.ru_majflt - last_rusage->ru_majflt);
465 if (rusage.ru_inblock > last_rusage->ru_inblock
466 || rusage.ru_oublock > last_rusage->ru_oublock) {
467 VLOG_WARN("disk: %ld reads, %ld writes",
468 rusage.ru_inblock - last_rusage->ru_inblock,
469 rusage.ru_oublock - last_rusage->ru_oublock);
471 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
472 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
473 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
474 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
475 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
481 /* CPU usage tracking. */
484 long long int when; /* Time that this sample was taken. */
485 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
489 struct cpu_usage older;
490 struct cpu_usage newer;
493 struct rusage recent_rusage;
495 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
497 static struct cpu_tracker *
498 get_cpu_tracker(void)
500 struct cpu_tracker *t = cpu_tracker_var_get();
502 t = xzalloc(sizeof *t);
503 t->older.when = LLONG_MIN;
504 t->newer.when = LLONG_MIN;
505 cpu_tracker_var_set_unsafe(t);
510 static struct rusage *
511 get_recent_rusage(void)
513 return &get_cpu_tracker()->recent_rusage;
517 getrusage_thread(struct rusage *rusage OVS_UNUSED)
520 return getrusage(RUSAGE_THREAD, rusage);
530 struct cpu_tracker *t = get_cpu_tracker();
531 struct rusage *recent_rusage = &t->recent_rusage;
533 if (!getrusage_thread(recent_rusage)) {
534 long long int now = time_msec();
535 if (now >= t->newer.when + 3 * 1000) {
538 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
539 timeval_to_msec(&recent_rusage->ru_stime));
541 if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
542 unsigned int dividend = t->newer.cpu - t->older.cpu;
543 unsigned int divisor = (t->newer.when - t->older.when) / 100;
544 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
552 /* Returns an estimate of this process's CPU usage, as a percentage, over the
553 * past few seconds of wall-clock time. Returns -1 if no estimate is available
554 * (which will happen if the process has not been running long enough to have
555 * an estimate, and can happen for other reasons as well). */
559 return get_cpu_tracker()->cpu_usage;
562 /* Unixctl interface. */
564 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
565 * advancing, except due to later calls to "time/warp". */
567 timeval_stop_cb(struct unixctl_conn *conn,
568 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
569 void *aux OVS_UNUSED)
571 ovs_rwlock_wrlock(&monotonic_clock.rwlock);
572 monotonic_clock.stopped = true;
573 ovs_rwlock_unlock(&monotonic_clock.rwlock);
575 unixctl_command_reply(conn, NULL);
578 /* "time/warp MSECS" advances the current monotonic time by the specified
579 * number of milliseconds. Unless "time/stop" has also been executed, the
580 * monotonic clock continues to tick forward at the normal rate afterward.
582 * Does not affect wall clock readings. */
584 timeval_warp_cb(struct unixctl_conn *conn,
585 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
590 msecs = atoi(argv[1]);
592 unixctl_command_reply_error(conn, "invalid MSECS");
596 ts.tv_sec = msecs / 1000;
597 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
599 ovs_rwlock_wrlock(&monotonic_clock.rwlock);
600 timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
601 ovs_rwlock_unlock(&monotonic_clock.rwlock);
603 unixctl_command_reply(conn, "warped");
607 timeval_dummy_register(void)
609 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
610 unixctl_command_register("time/warp", "MSECS", 1, 1,
611 timeval_warp_cb, NULL);