2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 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"
35 #include "ovs-thread.h"
42 VLOG_DEFINE_THIS_MODULE(timeval);
45 typedef unsigned int clockid_t;
47 #ifndef CLOCK_MONOTONIC
48 #define CLOCK_MONOTONIC 1
51 #ifndef CLOCK_REALTIME
52 #define CLOCK_REALTIME 2
55 /* Number of 100 ns intervals from January 1, 1601 till January 1, 1970. */
56 static ULARGE_INTEGER unix_epoch;
60 clockid_t id; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
62 /* Features for use by unit tests. Protected by 'mutex'. */
63 struct ovs_mutex mutex;
64 atomic_bool slow_path; /* True if warped or stopped. */
65 struct timespec warp OVS_GUARDED; /* Offset added for unit tests. */
66 bool stopped OVS_GUARDED; /* Disable real-time updates if true. */
67 struct timespec cache OVS_GUARDED; /* Last time read from kernel. */
71 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
72 static struct clock wall_clock; /* CLOCK_REALTIME. */
74 /* The monotonic time at which the time module was initialized. */
75 static long long int boot_time;
77 /* True only when timeval_dummy_register() is called. */
78 static bool timewarp_enabled;
79 /* Reference to the seq struct. Threads other than main thread can
80 * wait on timewarp_seq and be waken up when time is warped. */
81 static struct seq *timewarp_seq;
82 /* Last value of 'timewarp_seq'. */
83 DEFINE_STATIC_PER_THREAD_DATA(uint64_t, last_seq, 0);
85 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
87 static long long int deadline = LLONG_MAX;
89 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
91 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup, 0);
93 static void log_poll_interval(long long int last_wakeup);
94 static struct rusage *get_recent_rusage(void);
95 static void refresh_rusage(void);
96 static void timespec_add(struct timespec *sum,
97 const struct timespec *a, const struct timespec *b);
100 init_clock(struct clock *c, clockid_t id)
102 memset(c, 0, sizeof *c);
104 ovs_mutex_init(&c->mutex);
105 atomic_init(&c->slow_path, false);
106 xclock_gettime(c->id, &c->cache);
107 timewarp_seq = seq_create();
116 /* Calculate number of 100-nanosecond intervals till 01/01/1970. */
117 SYSTEMTIME unix_epoch_st = { 1970, 1, 0, 1, 0, 0, 0, 0};
118 FILETIME unix_epoch_ft;
120 SystemTimeToFileTime(&unix_epoch_st, &unix_epoch_ft);
121 unix_epoch.LowPart = unix_epoch_ft.dwLowDateTime;
122 unix_epoch.HighPart = unix_epoch_ft.dwHighDateTime;
127 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
130 init_clock(&wall_clock, CLOCK_REALTIME);
131 boot_time = timespec_to_msec(&monotonic_clock.cache);
134 /* Initializes the timetracking module, if not already initialized. */
138 static pthread_once_t once = PTHREAD_ONCE_INIT;
139 pthread_once(&once, do_init_time);
143 time_timespec__(struct clock *c, struct timespec *ts)
149 atomic_read_explicit(&c->slow_path, &slow_path, memory_order_relaxed);
151 xclock_gettime(c->id, ts);
153 struct timespec warp;
154 struct timespec cache;
157 ovs_mutex_lock(&c->mutex);
158 stopped = c->stopped;
161 ovs_mutex_unlock(&c->mutex);
164 xclock_gettime(c->id, &cache);
166 timespec_add(ts, &cache, &warp);
170 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
173 time_timespec(struct timespec *ts)
175 time_timespec__(&monotonic_clock, ts);
178 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
181 time_wall_timespec(struct timespec *ts)
183 time_timespec__(&wall_clock, ts);
187 time_sec__(struct clock *c)
191 time_timespec__(c, &ts);
195 /* Returns a monotonic timer, in seconds. */
199 return time_sec__(&monotonic_clock);
202 /* Returns the current time, in seconds. */
206 return time_sec__(&wall_clock);
210 time_msec__(struct clock *c)
214 time_timespec__(c, &ts);
215 return timespec_to_msec(&ts);
218 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
222 return time_msec__(&monotonic_clock);
225 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
229 return time_msec__(&wall_clock);
232 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
233 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
235 time_alarm(unsigned int secs)
240 assert_single_threaded();
244 msecs = secs * 1000LL;
245 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
248 /* Like poll(), except:
250 * - The timeout is specified as an absolute time, as defined by
251 * time_msec(), instead of a duration.
253 * - On error, returns a negative error code (instead of setting errno).
255 * - If interrupted by a signal, retries automatically until the original
256 * timeout is reached. (Because of this property, this function will
257 * never return -EINTR.)
259 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
261 time_poll(struct pollfd *pollfds, int n_pollfds, HANDLE *handles OVS_UNUSED,
262 long long int timeout_when, int *elapsed)
264 long long int *last_wakeup = last_wakeup_get();
272 log_poll_interval(*last_wakeup);
276 timeout_when = MIN(timeout_when, deadline);
279 long long int now = time_msec();
282 if (now >= timeout_when) {
284 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
287 time_left = timeout_when - now;
293 ovsrcu_quiesce_start();
297 retval = poll(pollfds, n_pollfds, time_left);
302 if (n_pollfds > MAXIMUM_WAIT_OBJECTS) {
303 VLOG_ERR("Cannot handle more than maximum wait objects\n");
304 } else if (n_pollfds != 0) {
305 retval = WaitForMultipleObjects(n_pollfds, handles, FALSE,
309 /* XXX This will be replace by a win error to errno
310 conversion function */
311 retval = -WSAGetLastError();
317 ovsrcu_quiesce_end();
320 if (deadline <= time_msec()) {
322 fatal_signal_handler(SIGALRM);
324 VLOG_ERR("wake up from WaitForMultipleObjects after deadline");
325 fatal_signal_handler(SIGTERM);
333 if (retval != -EINTR) {
337 *last_wakeup = time_msec();
339 *elapsed = *last_wakeup - start;
344 timespec_to_msec(const struct timespec *ts)
346 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
350 timeval_to_msec(const struct timeval *tv)
352 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
355 /* Returns the monotonic time at which the "time" module was initialized, in
365 static ULARGE_INTEGER
368 ULARGE_INTEGER current_time;
369 FILETIME current_time_ft;
371 /* Returns current time in UTC as a 64-bit value representing the number
372 * of 100-nanosecond intervals since January 1, 1601 . */
373 GetSystemTimePreciseAsFileTime(¤t_time_ft);
374 current_time.LowPart = current_time_ft.dwLowDateTime;
375 current_time.HighPart = current_time_ft.dwHighDateTime;
381 clock_gettime(clock_t id, struct timespec *ts)
383 if (id == CLOCK_MONOTONIC) {
384 static LARGE_INTEGER freq;
388 if (!freq.QuadPart) {
389 /* Number of counts per second. */
390 QueryPerformanceFrequency(&freq);
392 /* Total number of counts from a starting point. */
393 QueryPerformanceCounter(&count);
395 /* Total nano seconds from a starting point. */
396 ns = (double) count.QuadPart / freq.QuadPart * 1000000000;
398 ts->tv_sec = count.QuadPart / freq.QuadPart;
399 ts->tv_nsec = ns % 1000000000;
400 } else if (id == CLOCK_REALTIME) {
401 ULARGE_INTEGER current_time = xgetfiletime();
403 /* Time from Epoch to now. */
404 ts->tv_sec = (current_time.QuadPart - unix_epoch.QuadPart) / 10000000;
405 ts->tv_nsec = ((current_time.QuadPart - unix_epoch.QuadPart) %
414 xgettimeofday(struct timeval *tv)
417 if (gettimeofday(tv, NULL) == -1) {
418 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
421 ULARGE_INTEGER current_time = xgetfiletime();
423 tv->tv_sec = (current_time.QuadPart - unix_epoch.QuadPart) / 10000000;
424 tv->tv_usec = ((current_time.QuadPart - unix_epoch.QuadPart) %
430 xclock_gettime(clock_t id, struct timespec *ts)
432 if (clock_gettime(id, ts) == -1) {
433 /* It seems like a bad idea to try to use vlog here because it is
434 * likely to try to check the current time. */
435 ovs_abort(errno, "xclock_gettime() failed");
439 /* Makes threads wait on timewarp_seq and be waken up when time is warped.
440 * This function will be no-op unless timeval_dummy_register() is called. */
444 if (timewarp_enabled) {
445 uint64_t *last_seq = last_seq_get();
447 *last_seq = seq_read(timewarp_seq);
448 seq_wait(timewarp_seq, *last_seq);
453 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
455 return timeval_to_msec(a) - timeval_to_msec(b);
459 timespec_add(struct timespec *sum,
460 const struct timespec *a,
461 const struct timespec *b)
465 tmp.tv_sec = a->tv_sec + b->tv_sec;
466 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
467 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
468 tmp.tv_nsec -= 1000 * 1000 * 1000;
476 is_warped(const struct clock *c)
480 ovs_mutex_lock(&c->mutex);
481 warped = monotonic_clock.warp.tv_sec || monotonic_clock.warp.tv_nsec;
482 ovs_mutex_unlock(&c->mutex);
488 log_poll_interval(long long int last_wakeup)
490 long long int interval = time_msec() - last_wakeup;
492 if (interval >= 1000 && !is_warped(&monotonic_clock)) {
493 const struct rusage *last_rusage = get_recent_rusage();
494 struct rusage rusage;
496 getrusage(RUSAGE_SELF, &rusage);
497 VLOG_WARN("Unreasonably long %lldms poll interval"
498 " (%lldms user, %lldms system)",
500 timeval_diff_msec(&rusage.ru_utime,
501 &last_rusage->ru_utime),
502 timeval_diff_msec(&rusage.ru_stime,
503 &last_rusage->ru_stime));
504 if (rusage.ru_minflt > last_rusage->ru_minflt
505 || rusage.ru_majflt > last_rusage->ru_majflt) {
506 VLOG_WARN("faults: %ld minor, %ld major",
507 rusage.ru_minflt - last_rusage->ru_minflt,
508 rusage.ru_majflt - last_rusage->ru_majflt);
510 if (rusage.ru_inblock > last_rusage->ru_inblock
511 || rusage.ru_oublock > last_rusage->ru_oublock) {
512 VLOG_WARN("disk: %ld reads, %ld writes",
513 rusage.ru_inblock - last_rusage->ru_inblock,
514 rusage.ru_oublock - last_rusage->ru_oublock);
516 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
517 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
518 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
519 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
520 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
526 /* CPU usage tracking. */
529 long long int when; /* Time that this sample was taken. */
530 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
534 struct cpu_usage older;
535 struct cpu_usage newer;
538 struct rusage recent_rusage;
540 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
542 static struct cpu_tracker *
543 get_cpu_tracker(void)
545 struct cpu_tracker *t = cpu_tracker_var_get();
547 t = xzalloc(sizeof *t);
548 t->older.when = LLONG_MIN;
549 t->newer.when = LLONG_MIN;
550 cpu_tracker_var_set_unsafe(t);
555 static struct rusage *
556 get_recent_rusage(void)
558 return &get_cpu_tracker()->recent_rusage;
562 getrusage_thread(struct rusage *rusage OVS_UNUSED)
565 return getrusage(RUSAGE_THREAD, rusage);
575 struct cpu_tracker *t = get_cpu_tracker();
576 struct rusage *recent_rusage = &t->recent_rusage;
578 if (!getrusage_thread(recent_rusage)) {
579 long long int now = time_msec();
580 if (now >= t->newer.when + 3 * 1000) {
583 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
584 timeval_to_msec(&recent_rusage->ru_stime));
586 if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
587 unsigned int dividend = t->newer.cpu - t->older.cpu;
588 unsigned int divisor = (t->newer.when - t->older.when) / 100;
589 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
597 /* Returns an estimate of this process's CPU usage, as a percentage, over the
598 * past few seconds of wall-clock time. Returns -1 if no estimate is available
599 * (which will happen if the process has not been running long enough to have
600 * an estimate, and can happen for other reasons as well). */
604 return get_cpu_tracker()->cpu_usage;
607 /* Unixctl interface. */
609 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
610 * advancing, except due to later calls to "time/warp". */
612 timeval_stop_cb(struct unixctl_conn *conn,
613 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
614 void *aux OVS_UNUSED)
616 ovs_mutex_lock(&monotonic_clock.mutex);
617 atomic_store(&monotonic_clock.slow_path, true);
618 monotonic_clock.stopped = true;
619 xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
620 ovs_mutex_unlock(&monotonic_clock.mutex);
622 unixctl_command_reply(conn, NULL);
625 /* "time/warp MSECS" advances the current monotonic time by the specified
626 * number of milliseconds. Unless "time/stop" has also been executed, the
627 * monotonic clock continues to tick forward at the normal rate afterward.
629 * Does not affect wall clock readings. */
631 timeval_warp_cb(struct unixctl_conn *conn,
632 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
637 msecs = atoi(argv[1]);
639 unixctl_command_reply_error(conn, "invalid MSECS");
643 ts.tv_sec = msecs / 1000;
644 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
646 ovs_mutex_lock(&monotonic_clock.mutex);
647 atomic_store(&monotonic_clock.slow_path, true);
648 timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
649 ovs_mutex_unlock(&monotonic_clock.mutex);
650 seq_change(timewarp_seq);
651 /* give threads (eg. monitor) some chances to run */
657 unixctl_command_reply(conn, "warped");
661 timeval_dummy_register(void)
663 timewarp_enabled = true;
664 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
665 unixctl_command_register("time/warp", "MSECS", 1, 1,
666 timeval_warp_cb, NULL);
671 /* strftime() with an extension for high-resolution timestamps. Any '#'s in
672 * 'format' will be replaced by subseconds, e.g. use "%S.###" to obtain results
675 strftime_msec(char *s, size_t max, const char *format,
676 const struct tm_msec *tm)
680 n = strftime(s, max, format, &tm->tm);
685 sprintf(decimals, "%03d", tm->msec);
686 for (p = strchr(s, '#'); p; p = strchr(p, '#')) {
689 *p++ = *d ? *d++ : '0';
698 localtime_msec(long long int now, struct tm_msec *result)
700 time_t now_sec = now / 1000;
701 localtime_r(&now_sec, &result->tm);
702 result->msec = now % 1000;
707 gmtime_msec(long long int now, struct tm_msec *result)
709 time_t now_sec = now / 1000;
710 gmtime_r(&now_sec, &result->tm);
711 result->msec = now % 1000;