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"
34 #include "ovs-thread.h"
41 VLOG_DEFINE_THIS_MODULE(timeval);
44 clockid_t id; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
46 /* Features for use by unit tests. Protected by 'mutex'. */
47 struct ovs_mutex mutex;
48 atomic_bool slow_path; /* True if warped or stopped. */
49 struct timespec warp OVS_GUARDED; /* Offset added for unit tests. */
50 bool stopped OVS_GUARDED; /* Disable real-time updates if true. */
51 struct timespec cache OVS_GUARDED; /* Last time read from kernel. */
55 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
56 static struct clock wall_clock; /* CLOCK_REALTIME. */
58 /* The monotonic time at which the time module was initialized. */
59 static long long int boot_time;
61 /* True only when timeval_dummy_register() is called. */
62 static bool timewarp_enabled;
63 /* Reference to the seq struct. Threads other than main thread can
64 * wait on timewarp_seq and be waken up when time is warped. */
65 static struct seq *timewarp_seq;
66 /* Last value of 'timewarp_seq'. */
67 DEFINE_STATIC_PER_THREAD_DATA(uint64_t, last_seq, 0);
69 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
71 static long long int deadline = LLONG_MAX;
73 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
75 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup, 0);
77 static void log_poll_interval(long long int last_wakeup);
78 static struct rusage *get_recent_rusage(void);
79 static void refresh_rusage(void);
80 static void timespec_add(struct timespec *sum,
81 const struct timespec *a, const struct timespec *b);
84 init_clock(struct clock *c, clockid_t id)
86 memset(c, 0, sizeof *c);
88 ovs_mutex_init(&c->mutex);
89 atomic_init(&c->slow_path, false);
90 xclock_gettime(c->id, &c->cache);
91 timewarp_seq = seq_create();
101 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
104 init_clock(&wall_clock, CLOCK_REALTIME);
105 boot_time = timespec_to_msec(&monotonic_clock.cache);
108 /* Initializes the timetracking module, if not already initialized. */
112 static pthread_once_t once = PTHREAD_ONCE_INIT;
113 pthread_once(&once, do_init_time);
117 time_timespec__(struct clock *c, struct timespec *ts)
123 atomic_read_explicit(&c->slow_path, &slow_path, memory_order_relaxed);
125 xclock_gettime(c->id, ts);
127 struct timespec warp;
128 struct timespec cache;
131 ovs_mutex_lock(&c->mutex);
132 stopped = c->stopped;
135 ovs_mutex_unlock(&c->mutex);
138 xclock_gettime(c->id, &cache);
140 timespec_add(ts, &cache, &warp);
144 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
147 time_timespec(struct timespec *ts)
149 time_timespec__(&monotonic_clock, ts);
152 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
155 time_wall_timespec(struct timespec *ts)
157 time_timespec__(&wall_clock, ts);
161 time_sec__(struct clock *c)
165 time_timespec__(c, &ts);
169 /* Returns a monotonic timer, in seconds. */
173 return time_sec__(&monotonic_clock);
176 /* Returns the current time, in seconds. */
180 return time_sec__(&wall_clock);
184 time_msec__(struct clock *c)
188 time_timespec__(c, &ts);
189 return timespec_to_msec(&ts);
192 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
196 return time_msec__(&monotonic_clock);
199 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
203 return time_msec__(&wall_clock);
206 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
207 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
209 time_alarm(unsigned int secs)
214 assert_single_threaded();
218 msecs = secs * 1000LL;
219 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
222 /* Like poll(), except:
224 * - The timeout is specified as an absolute time, as defined by
225 * time_msec(), instead of a duration.
227 * - On error, returns a negative error code (instead of setting errno).
229 * - If interrupted by a signal, retries automatically until the original
230 * timeout is reached. (Because of this property, this function will
231 * never return -EINTR.)
233 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
235 time_poll(struct pollfd *pollfds, int n_pollfds, HANDLE *handles OVS_UNUSED,
236 long long int timeout_when, int *elapsed)
238 long long int *last_wakeup = last_wakeup_get();
246 log_poll_interval(*last_wakeup);
250 timeout_when = MIN(timeout_when, deadline);
253 long long int now = time_msec();
256 if (now >= timeout_when) {
258 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
261 time_left = timeout_when - now;
265 retval = poll(pollfds, n_pollfds, time_left);
270 if (n_pollfds > MAXIMUM_WAIT_OBJECTS) {
271 VLOG_ERR("Cannot handle more than maximum wait objects\n");
272 } else if (n_pollfds != 0) {
273 retval = WaitForMultipleObjects(n_pollfds, handles, FALSE,
277 /* XXX This will be replace by a win error to errno
278 conversion function */
279 retval = -WSAGetLastError();
284 if (deadline <= time_msec()) {
286 fatal_signal_handler(SIGALRM);
288 VLOG_ERR("wake up from WaitForMultipleObjects after deadline");
289 fatal_signal_handler(SIGTERM);
297 if (retval != -EINTR) {
301 *last_wakeup = time_msec();
303 *elapsed = *last_wakeup - start;
308 timespec_to_msec(const struct timespec *ts)
310 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
314 timeval_to_msec(const struct timeval *tv)
316 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
319 /* Returns the monotonic time at which the "time" module was initialized, in
329 xgettimeofday(struct timeval *tv)
331 if (gettimeofday(tv, NULL) == -1) {
332 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
337 xclock_gettime(clock_t id, struct timespec *ts)
339 if (clock_gettime(id, ts) == -1) {
340 /* It seems like a bad idea to try to use vlog here because it is
341 * likely to try to check the current time. */
342 ovs_abort(errno, "xclock_gettime() failed");
346 /* Makes threads wait on timewarp_seq and be waken up when time is warped.
347 * This function will be no-op unless timeval_dummy_register() is called. */
351 if (timewarp_enabled) {
352 uint64_t *last_seq = last_seq_get();
354 *last_seq = seq_read(timewarp_seq);
355 seq_wait(timewarp_seq, *last_seq);
360 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
362 return timeval_to_msec(a) - timeval_to_msec(b);
366 timespec_add(struct timespec *sum,
367 const struct timespec *a,
368 const struct timespec *b)
372 tmp.tv_sec = a->tv_sec + b->tv_sec;
373 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
374 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
375 tmp.tv_nsec -= 1000 * 1000 * 1000;
383 is_warped(const struct clock *c)
387 ovs_mutex_lock(&c->mutex);
388 warped = monotonic_clock.warp.tv_sec || monotonic_clock.warp.tv_nsec;
389 ovs_mutex_unlock(&c->mutex);
395 log_poll_interval(long long int last_wakeup)
397 long long int interval = time_msec() - last_wakeup;
399 if (interval >= 1000 && !is_warped(&monotonic_clock)) {
400 const struct rusage *last_rusage = get_recent_rusage();
401 struct rusage rusage;
403 getrusage(RUSAGE_SELF, &rusage);
404 VLOG_WARN("Unreasonably long %lldms poll interval"
405 " (%lldms user, %lldms system)",
407 timeval_diff_msec(&rusage.ru_utime,
408 &last_rusage->ru_utime),
409 timeval_diff_msec(&rusage.ru_stime,
410 &last_rusage->ru_stime));
411 if (rusage.ru_minflt > last_rusage->ru_minflt
412 || rusage.ru_majflt > last_rusage->ru_majflt) {
413 VLOG_WARN("faults: %ld minor, %ld major",
414 rusage.ru_minflt - last_rusage->ru_minflt,
415 rusage.ru_majflt - last_rusage->ru_majflt);
417 if (rusage.ru_inblock > last_rusage->ru_inblock
418 || rusage.ru_oublock > last_rusage->ru_oublock) {
419 VLOG_WARN("disk: %ld reads, %ld writes",
420 rusage.ru_inblock - last_rusage->ru_inblock,
421 rusage.ru_oublock - last_rusage->ru_oublock);
423 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
424 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
425 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
426 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
427 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
433 /* CPU usage tracking. */
436 long long int when; /* Time that this sample was taken. */
437 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
441 struct cpu_usage older;
442 struct cpu_usage newer;
445 struct rusage recent_rusage;
447 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
449 static struct cpu_tracker *
450 get_cpu_tracker(void)
452 struct cpu_tracker *t = cpu_tracker_var_get();
454 t = xzalloc(sizeof *t);
455 t->older.when = LLONG_MIN;
456 t->newer.when = LLONG_MIN;
457 cpu_tracker_var_set_unsafe(t);
462 static struct rusage *
463 get_recent_rusage(void)
465 return &get_cpu_tracker()->recent_rusage;
469 getrusage_thread(struct rusage *rusage OVS_UNUSED)
472 return getrusage(RUSAGE_THREAD, rusage);
482 struct cpu_tracker *t = get_cpu_tracker();
483 struct rusage *recent_rusage = &t->recent_rusage;
485 if (!getrusage_thread(recent_rusage)) {
486 long long int now = time_msec();
487 if (now >= t->newer.when + 3 * 1000) {
490 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
491 timeval_to_msec(&recent_rusage->ru_stime));
493 if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
494 unsigned int dividend = t->newer.cpu - t->older.cpu;
495 unsigned int divisor = (t->newer.when - t->older.when) / 100;
496 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
504 /* Returns an estimate of this process's CPU usage, as a percentage, over the
505 * past few seconds of wall-clock time. Returns -1 if no estimate is available
506 * (which will happen if the process has not been running long enough to have
507 * an estimate, and can happen for other reasons as well). */
511 return get_cpu_tracker()->cpu_usage;
514 /* Unixctl interface. */
516 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
517 * advancing, except due to later calls to "time/warp". */
519 timeval_stop_cb(struct unixctl_conn *conn,
520 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
521 void *aux OVS_UNUSED)
523 ovs_mutex_lock(&monotonic_clock.mutex);
524 atomic_store(&monotonic_clock.slow_path, true);
525 monotonic_clock.stopped = true;
526 xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
527 ovs_mutex_unlock(&monotonic_clock.mutex);
529 unixctl_command_reply(conn, NULL);
532 /* "time/warp MSECS" advances the current monotonic time by the specified
533 * number of milliseconds. Unless "time/stop" has also been executed, the
534 * monotonic clock continues to tick forward at the normal rate afterward.
536 * Does not affect wall clock readings. */
538 timeval_warp_cb(struct unixctl_conn *conn,
539 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
544 msecs = atoi(argv[1]);
546 unixctl_command_reply_error(conn, "invalid MSECS");
550 ts.tv_sec = msecs / 1000;
551 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
553 ovs_mutex_lock(&monotonic_clock.mutex);
554 atomic_store(&monotonic_clock.slow_path, true);
555 timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
556 ovs_mutex_unlock(&monotonic_clock.mutex);
557 seq_change(timewarp_seq);
558 poll(NULL, 0, 10); /* give threads (eg. monitor) some chances to run */
559 unixctl_command_reply(conn, "warped");
563 timeval_dummy_register(void)
565 timewarp_enabled = true;
566 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
567 unixctl_command_register("time/warp", "MSECS", 1, 1,
568 timeval_warp_cb, NULL);
573 /* strftime() with an extension for high-resolution timestamps. Any '#'s in
574 * 'format' will be replaced by subseconds, e.g. use "%S.###" to obtain results
577 strftime_msec(char *s, size_t max, const char *format,
578 const struct tm_msec *tm)
582 n = strftime(s, max, format, &tm->tm);
587 sprintf(decimals, "%03d", tm->msec);
588 for (p = strchr(s, '#'); p; p = strchr(p, '#')) {
591 *p++ = *d ? *d++ : '0';
600 localtime_msec(long long int now, struct tm_msec *result)
602 time_t now_sec = now / 1000;
603 localtime_r(&now_sec, &result->tm);
604 result->msec = now % 1000;
609 gmtime_msec(long long int now, struct tm_msec *result)
611 time_t now_sec = now / 1000;
612 gmtime_r(&now_sec, &result->tm);
613 result->msec = now % 1000;