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 const static unsigned long long unix_epoch = 116444736000000000;
59 /* Structure set by unixctl time/warp command. */
61 struct unixctl_conn *conn; /* Connection waiting for warp response. */
62 long long int total_warp; /* Total offset to be added to monotonic time. */
63 long long int warp; /* 'total_warp' offset done in steps of 'warp'. */
64 unsigned int main_thread_id; /* Identification for the main thread. */
68 clockid_t id; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
70 /* Features for use by unit tests. Protected by 'mutex'. */
71 struct ovs_mutex mutex;
72 atomic_bool slow_path; /* True if warped or stopped. */
73 struct timespec warp OVS_GUARDED; /* Offset added for unit tests. */
74 bool stopped OVS_GUARDED; /* Disable real-time updates if true. */
75 struct timespec cache OVS_GUARDED; /* Last time read from kernel. */
76 struct large_warp large_warp OVS_GUARDED; /* Connection information waiting
81 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
82 static struct clock wall_clock; /* CLOCK_REALTIME. */
84 /* The monotonic time at which the time module was initialized. */
85 static long long int boot_time;
87 /* True only when timeval_dummy_register() is called. */
88 static bool timewarp_enabled;
89 /* Reference to the seq struct. Threads other than main thread can
90 * wait on timewarp_seq and be waken up when time is warped. */
91 static struct seq *timewarp_seq;
92 /* Last value of 'timewarp_seq'. */
93 DEFINE_STATIC_PER_THREAD_DATA(uint64_t, last_seq, 0);
95 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
97 static long long int deadline = LLONG_MAX;
99 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
101 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup, 0);
103 static void log_poll_interval(long long int last_wakeup);
104 static struct rusage *get_recent_rusage(void);
105 static void refresh_rusage(void);
106 static void timespec_add(struct timespec *sum,
107 const struct timespec *a, const struct timespec *b);
110 init_clock(struct clock *c, clockid_t id)
112 memset(c, 0, sizeof *c);
114 ovs_mutex_init(&c->mutex);
115 atomic_init(&c->slow_path, false);
116 xclock_gettime(c->id, &c->cache);
117 memset(&c->large_warp, 0, sizeof(c->large_warp));
127 timewarp_seq = seq_create();
128 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
131 init_clock(&wall_clock, CLOCK_REALTIME);
132 boot_time = timespec_to_msec(&monotonic_clock.cache);
135 /* Initializes the timetracking module, if not already initialized. */
139 static pthread_once_t once = PTHREAD_ONCE_INIT;
140 pthread_once(&once, do_init_time);
144 time_timespec__(struct clock *c, struct timespec *ts)
150 atomic_read_relaxed(&c->slow_path, &slow_path);
152 xclock_gettime(c->id, ts);
154 struct timespec warp;
155 struct timespec cache;
158 ovs_mutex_lock(&c->mutex);
159 stopped = c->stopped;
162 ovs_mutex_unlock(&c->mutex);
165 xclock_gettime(c->id, &cache);
167 timespec_add(ts, &cache, &warp);
171 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
174 time_timespec(struct timespec *ts)
176 time_timespec__(&monotonic_clock, ts);
179 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
182 time_wall_timespec(struct timespec *ts)
184 time_timespec__(&wall_clock, ts);
188 time_sec__(struct clock *c)
192 time_timespec__(c, &ts);
196 /* Returns a monotonic timer, in seconds. */
200 return time_sec__(&monotonic_clock);
203 /* Returns the current time, in seconds. */
207 return time_sec__(&wall_clock);
211 time_msec__(struct clock *c)
215 time_timespec__(c, &ts);
216 return timespec_to_msec(&ts);
219 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
223 return time_msec__(&monotonic_clock);
226 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
230 return time_msec__(&wall_clock);
233 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
234 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
236 time_alarm(unsigned int secs)
241 assert_single_threaded();
245 msecs = secs * 1000LL;
246 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
249 /* Like poll(), except:
251 * - The timeout is specified as an absolute time, as defined by
252 * time_msec(), instead of a duration.
254 * - On error, returns a negative error code (instead of setting errno).
256 * - If interrupted by a signal, retries automatically until the original
257 * timeout is reached. (Because of this property, this function will
258 * never return -EINTR.)
260 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
262 time_poll(struct pollfd *pollfds, int n_pollfds, HANDLE *handles OVS_UNUSED,
263 long long int timeout_when, int *elapsed)
265 long long int *last_wakeup = last_wakeup_get();
274 log_poll_interval(*last_wakeup);
278 timeout_when = MIN(timeout_when, deadline);
279 quiescent = ovsrcu_is_quiescent();
282 long long int now = time_msec();
285 if (now >= timeout_when) {
287 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
290 time_left = timeout_when - now;
297 ovsrcu_quiesce_start();
302 retval = poll(pollfds, n_pollfds, time_left);
307 if (n_pollfds > MAXIMUM_WAIT_OBJECTS) {
308 VLOG_ERR("Cannot handle more than maximum wait objects\n");
309 } else if (n_pollfds != 0) {
310 retval = WaitForMultipleObjects(n_pollfds, handles, FALSE,
314 /* XXX This will be replace by a win error to errno
315 conversion function */
316 retval = -WSAGetLastError();
321 if (!quiescent && time_left) {
322 ovsrcu_quiesce_end();
325 if (deadline <= time_msec()) {
327 fatal_signal_handler(SIGALRM);
329 VLOG_ERR("wake up from WaitForMultipleObjects after deadline");
330 fatal_signal_handler(SIGTERM);
338 if (retval != -EINTR) {
342 *last_wakeup = time_msec();
344 *elapsed = *last_wakeup - start;
349 timespec_to_msec(const struct timespec *ts)
351 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
355 timeval_to_msec(const struct timeval *tv)
357 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
360 /* Returns the monotonic time at which the "time" module was initialized, in
370 static ULARGE_INTEGER
373 ULARGE_INTEGER current_time;
374 FILETIME current_time_ft;
376 /* Returns current time in UTC as a 64-bit value representing the number
377 * of 100-nanosecond intervals since January 1, 1601 . */
378 GetSystemTimePreciseAsFileTime(¤t_time_ft);
379 current_time.LowPart = current_time_ft.dwLowDateTime;
380 current_time.HighPart = current_time_ft.dwHighDateTime;
386 clock_gettime(clock_t id, struct timespec *ts)
388 if (id == CLOCK_MONOTONIC) {
389 static LARGE_INTEGER freq;
393 if (!freq.QuadPart) {
394 /* Number of counts per second. */
395 QueryPerformanceFrequency(&freq);
397 /* Total number of counts from a starting point. */
398 QueryPerformanceCounter(&count);
400 /* Total nano seconds from a starting point. */
401 ns = (double) count.QuadPart / freq.QuadPart * 1000000000;
403 ts->tv_sec = count.QuadPart / freq.QuadPart;
404 ts->tv_nsec = ns % 1000000000;
405 } else if (id == CLOCK_REALTIME) {
406 ULARGE_INTEGER current_time = xgetfiletime();
408 /* Time from Epoch to now. */
409 ts->tv_sec = (current_time.QuadPart - unix_epoch) / 10000000;
410 ts->tv_nsec = ((current_time.QuadPart - unix_epoch) %
421 xgettimeofday(struct timeval *tv)
424 if (gettimeofday(tv, NULL) == -1) {
425 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
428 ULARGE_INTEGER current_time = xgetfiletime();
430 tv->tv_sec = (current_time.QuadPart - unix_epoch) / 10000000;
431 tv->tv_usec = ((current_time.QuadPart - unix_epoch) %
437 xclock_gettime(clock_t id, struct timespec *ts)
439 if (clock_gettime(id, ts) == -1) {
440 /* It seems like a bad idea to try to use vlog here because it is
441 * likely to try to check the current time. */
442 ovs_abort(errno, "xclock_gettime() failed");
447 msec_to_timespec(long long int ms, struct timespec *ts)
449 ts->tv_sec = ms / 1000;
450 ts->tv_nsec = (ms % 1000) * 1000 * 1000;
456 struct clock *c = &monotonic_clock;
457 struct timespec warp;
459 ovs_mutex_lock(&c->mutex);
460 if (!c->large_warp.conn) {
461 ovs_mutex_unlock(&c->mutex);
465 if (c->large_warp.total_warp >= c->large_warp.warp) {
466 msec_to_timespec(c->large_warp.warp, &warp);
467 timespec_add(&c->warp, &c->warp, &warp);
468 c->large_warp.total_warp -= c->large_warp.warp;
469 } else if (c->large_warp.total_warp) {
470 msec_to_timespec(c->large_warp.total_warp, &warp);
471 timespec_add(&c->warp, &c->warp, &warp);
472 c->large_warp.total_warp = 0;
474 /* c->large_warp.total_warp is 0. */
475 msec_to_timespec(c->large_warp.warp, &warp);
476 timespec_add(&c->warp, &c->warp, &warp);
479 if (!c->large_warp.total_warp) {
480 unixctl_command_reply(c->large_warp.conn, "warped");
481 c->large_warp.conn = NULL;
484 ovs_mutex_unlock(&c->mutex);
485 seq_change(timewarp_seq);
487 /* give threads (eg. monitor) some chances to run */
495 /* Perform work needed for "timewarp_seq"'s producer and consumers. */
499 /* The function is a no-op unless timeval_dummy_register() is called. */
500 if (timewarp_enabled) {
501 unsigned int thread_id;
502 ovs_mutex_lock(&monotonic_clock.mutex);
503 thread_id = monotonic_clock.large_warp.main_thread_id;
504 ovs_mutex_unlock(&monotonic_clock.mutex);
506 if (thread_id != ovsthread_id_self()) {
507 /* For threads other than the thread that changes the sequence,
509 uint64_t *last_seq = last_seq_get();
511 *last_seq = seq_read(timewarp_seq);
512 seq_wait(timewarp_seq, *last_seq);
514 /* Work on adding the remaining warps. */
521 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
523 return timeval_to_msec(a) - timeval_to_msec(b);
527 timespec_add(struct timespec *sum,
528 const struct timespec *a,
529 const struct timespec *b)
533 tmp.tv_sec = a->tv_sec + b->tv_sec;
534 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
535 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
536 tmp.tv_nsec -= 1000 * 1000 * 1000;
544 is_warped(const struct clock *c)
548 ovs_mutex_lock(&c->mutex);
549 warped = monotonic_clock.warp.tv_sec || monotonic_clock.warp.tv_nsec;
550 ovs_mutex_unlock(&c->mutex);
556 log_poll_interval(long long int last_wakeup)
558 long long int interval = time_msec() - last_wakeup;
560 if (interval >= 1000 && !is_warped(&monotonic_clock)) {
561 const struct rusage *last_rusage = get_recent_rusage();
562 struct rusage rusage;
564 getrusage(RUSAGE_SELF, &rusage);
565 VLOG_WARN("Unreasonably long %lldms poll interval"
566 " (%lldms user, %lldms system)",
568 timeval_diff_msec(&rusage.ru_utime,
569 &last_rusage->ru_utime),
570 timeval_diff_msec(&rusage.ru_stime,
571 &last_rusage->ru_stime));
572 if (rusage.ru_minflt > last_rusage->ru_minflt
573 || rusage.ru_majflt > last_rusage->ru_majflt) {
574 VLOG_WARN("faults: %ld minor, %ld major",
575 rusage.ru_minflt - last_rusage->ru_minflt,
576 rusage.ru_majflt - last_rusage->ru_majflt);
578 if (rusage.ru_inblock > last_rusage->ru_inblock
579 || rusage.ru_oublock > last_rusage->ru_oublock) {
580 VLOG_WARN("disk: %ld reads, %ld writes",
581 rusage.ru_inblock - last_rusage->ru_inblock,
582 rusage.ru_oublock - last_rusage->ru_oublock);
584 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
585 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
586 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
587 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
588 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
594 /* CPU usage tracking. */
597 long long int when; /* Time that this sample was taken. */
598 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
602 struct cpu_usage older;
603 struct cpu_usage newer;
606 struct rusage recent_rusage;
608 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
610 static struct cpu_tracker *
611 get_cpu_tracker(void)
613 struct cpu_tracker *t = cpu_tracker_var_get();
615 t = xzalloc(sizeof *t);
616 t->older.when = LLONG_MIN;
617 t->newer.when = LLONG_MIN;
618 cpu_tracker_var_set_unsafe(t);
623 static struct rusage *
624 get_recent_rusage(void)
626 return &get_cpu_tracker()->recent_rusage;
630 getrusage_thread(struct rusage *rusage OVS_UNUSED)
633 return getrusage(RUSAGE_THREAD, rusage);
643 struct cpu_tracker *t = get_cpu_tracker();
644 struct rusage *recent_rusage = &t->recent_rusage;
646 if (!getrusage_thread(recent_rusage)) {
647 long long int now = time_msec();
648 if (now >= t->newer.when + 3 * 1000) {
651 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
652 timeval_to_msec(&recent_rusage->ru_stime));
654 if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
655 unsigned int dividend = t->newer.cpu - t->older.cpu;
656 unsigned int divisor = (t->newer.when - t->older.when) / 100;
657 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
665 /* Returns an estimate of this process's CPU usage, as a percentage, over the
666 * past few seconds of wall-clock time. Returns -1 if no estimate is available
667 * (which will happen if the process has not been running long enough to have
668 * an estimate, and can happen for other reasons as well). */
672 return get_cpu_tracker()->cpu_usage;
675 /* Unixctl interface. */
677 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
678 * advancing, except due to later calls to "time/warp". */
680 timeval_stop_cb(struct unixctl_conn *conn,
681 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
682 void *aux OVS_UNUSED)
684 ovs_mutex_lock(&monotonic_clock.mutex);
685 atomic_store_relaxed(&monotonic_clock.slow_path, true);
686 monotonic_clock.stopped = true;
687 xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
688 ovs_mutex_unlock(&monotonic_clock.mutex);
690 unixctl_command_reply(conn, NULL);
693 /* "time/warp MSECS" advances the current monotonic time by the specified
694 * number of milliseconds. Unless "time/stop" has also been executed, the
695 * monotonic clock continues to tick forward at the normal rate afterward.
697 * "time/warp LARGE_MSECS MSECS" is a variation of the above command. It
698 * advances the current monotonic time by LARGE_MSECS. This is done MSECS
699 * at a time in each run of the main thread. This gives other threads
700 * time to run after the clock has been advanced by MSECS.
702 * Does not affect wall clock readings. */
704 timeval_warp_cb(struct unixctl_conn *conn,
705 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
707 long long int total_warp = argc > 2 ? atoll(argv[1]) : 0;
708 long long int msecs = argc > 2 ? atoll(argv[2]) : atoll(argv[1]);
709 if (msecs <= 0 || total_warp < 0) {
710 unixctl_command_reply_error(conn, "invalid MSECS");
714 ovs_mutex_lock(&monotonic_clock.mutex);
715 if (monotonic_clock.large_warp.conn) {
716 ovs_mutex_unlock(&monotonic_clock.mutex);
717 unixctl_command_reply_error(conn, "A previous warp in progress");
720 atomic_store_relaxed(&monotonic_clock.slow_path, true);
721 monotonic_clock.large_warp.conn = conn;
722 monotonic_clock.large_warp.total_warp = total_warp;
723 monotonic_clock.large_warp.warp = msecs;
724 monotonic_clock.large_warp.main_thread_id = ovsthread_id_self();
725 ovs_mutex_unlock(&monotonic_clock.mutex);
731 timeval_dummy_register(void)
733 timewarp_enabled = true;
734 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
735 unixctl_command_register("time/warp", "[large_msecs] msecs", 1, 2,
736 timeval_warp_cb, NULL);
741 /* strftime() with an extension for high-resolution timestamps. Any '#'s in
742 * 'format' will be replaced by subseconds, e.g. use "%S.###" to obtain results
745 strftime_msec(char *s, size_t max, const char *format,
746 const struct tm_msec *tm)
750 /* Visual Studio 2013's behavior is to crash when 0 is passed as second
751 * argument to strftime. */
752 n = max ? strftime(s, max, format, &tm->tm) : 0;
757 sprintf(decimals, "%03d", tm->msec);
758 for (p = strchr(s, '#'); p; p = strchr(p, '#')) {
761 *p++ = *d ? *d++ : '0';
770 localtime_msec(long long int now, struct tm_msec *result)
772 time_t now_sec = now / 1000;
773 localtime_r(&now_sec, &result->tm);
774 result->msec = now % 1000;
779 gmtime_msec(long long int now, struct tm_msec *result)
781 time_t now_sec = now / 1000;
782 gmtime_r(&now_sec, &result->tm);
783 result->msec = now % 1000;