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. */
45 /* Features for use by unit tests. Protected by 'mutex'. */
46 struct ovs_mutex mutex;
47 atomic_bool slow_path; /* True if warped or stopped. */
48 struct timespec warp OVS_GUARDED; /* Offset added for unit tests. */
49 bool stopped OVS_GUARDED; /* Disable real-time updates if true. */
50 struct timespec cache OVS_GUARDED; /* Last time read from kernel. */
54 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
55 static struct clock wall_clock; /* CLOCK_REALTIME. */
57 /* The monotonic time at which the time module was initialized. */
58 static long long int boot_time;
60 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
62 static long long int deadline = LLONG_MAX;
64 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
66 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup, 0);
68 static void log_poll_interval(long long int last_wakeup);
69 static struct rusage *get_recent_rusage(void);
70 static void refresh_rusage(void);
71 static void timespec_add(struct timespec *sum,
72 const struct timespec *a, const struct timespec *b);
75 init_clock(struct clock *c, clockid_t id)
77 memset(c, 0, sizeof *c);
79 ovs_mutex_init(&c->mutex);
80 atomic_init(&c->slow_path, false);
81 xclock_gettime(c->id, &c->cache);
91 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
94 init_clock(&wall_clock, CLOCK_REALTIME);
95 boot_time = timespec_to_msec(&monotonic_clock.cache);
98 /* Initializes the timetracking module, if not already initialized. */
102 static pthread_once_t once = PTHREAD_ONCE_INIT;
103 pthread_once(&once, do_init_time);
107 time_timespec__(struct clock *c, struct timespec *ts)
113 atomic_read_explicit(&c->slow_path, &slow_path, memory_order_relaxed);
115 xclock_gettime(c->id, ts);
117 struct timespec warp;
118 struct timespec cache;
121 ovs_mutex_lock(&c->mutex);
122 stopped = c->stopped;
125 ovs_mutex_unlock(&c->mutex);
128 xclock_gettime(c->id, &cache);
130 timespec_add(ts, &cache, &warp);
134 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
137 time_timespec(struct timespec *ts)
139 time_timespec__(&monotonic_clock, ts);
142 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
145 time_wall_timespec(struct timespec *ts)
147 time_timespec__(&wall_clock, ts);
151 time_sec__(struct clock *c)
155 time_timespec__(c, &ts);
159 /* Returns a monotonic timer, in seconds. */
163 return time_sec__(&monotonic_clock);
166 /* Returns the current time, in seconds. */
170 return time_sec__(&wall_clock);
174 time_msec__(struct clock *c)
178 time_timespec__(c, &ts);
179 return timespec_to_msec(&ts);
182 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
186 return time_msec__(&monotonic_clock);
189 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
193 return time_msec__(&wall_clock);
196 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
197 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
199 time_alarm(unsigned int secs)
204 assert_single_threaded();
208 msecs = secs * 1000LL;
209 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
212 /* Like poll(), except:
214 * - The timeout is specified as an absolute time, as defined by
215 * time_msec(), instead of a duration.
217 * - On error, returns a negative error code (instead of setting errno).
219 * - If interrupted by a signal, retries automatically until the original
220 * timeout is reached. (Because of this property, this function will
221 * never return -EINTR.)
223 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
225 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
228 long long int *last_wakeup = last_wakeup_get();
234 log_poll_interval(*last_wakeup);
239 timeout_when = MIN(timeout_when, deadline);
242 long long int now = time_msec();
245 if (now >= timeout_when) {
247 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
250 time_left = timeout_when - now;
253 retval = poll(pollfds, n_pollfds, time_left);
258 if (deadline <= time_msec()) {
259 fatal_signal_handler(SIGALRM);
266 if (retval != -EINTR) {
270 *last_wakeup = time_msec();
272 *elapsed = *last_wakeup - start;
277 timespec_to_msec(const struct timespec *ts)
279 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
283 timeval_to_msec(const struct timeval *tv)
285 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
288 /* Returns the monotonic time at which the "time" module was initialized, in
298 xgettimeofday(struct timeval *tv)
300 if (gettimeofday(tv, NULL) == -1) {
301 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
306 xclock_gettime(clock_t id, struct timespec *ts)
308 if (clock_gettime(id, ts) == -1) {
309 /* It seems like a bad idea to try to use vlog here because it is
310 * likely to try to check the current time. */
311 ovs_abort(errno, "xclock_gettime() failed");
316 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
318 return timeval_to_msec(a) - timeval_to_msec(b);
322 timespec_add(struct timespec *sum,
323 const struct timespec *a,
324 const struct timespec *b)
328 tmp.tv_sec = a->tv_sec + b->tv_sec;
329 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
330 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
331 tmp.tv_nsec -= 1000 * 1000 * 1000;
339 is_warped(const struct clock *c)
343 ovs_mutex_lock(&c->mutex);
344 warped = monotonic_clock.warp.tv_sec || monotonic_clock.warp.tv_nsec;
345 ovs_mutex_unlock(&c->mutex);
351 log_poll_interval(long long int last_wakeup)
353 long long int interval = time_msec() - last_wakeup;
355 if (interval >= 1000 && !is_warped(&monotonic_clock)) {
356 const struct rusage *last_rusage = get_recent_rusage();
357 struct rusage rusage;
359 getrusage(RUSAGE_SELF, &rusage);
360 VLOG_WARN("Unreasonably long %lldms poll interval"
361 " (%lldms user, %lldms system)",
363 timeval_diff_msec(&rusage.ru_utime,
364 &last_rusage->ru_utime),
365 timeval_diff_msec(&rusage.ru_stime,
366 &last_rusage->ru_stime));
367 if (rusage.ru_minflt > last_rusage->ru_minflt
368 || rusage.ru_majflt > last_rusage->ru_majflt) {
369 VLOG_WARN("faults: %ld minor, %ld major",
370 rusage.ru_minflt - last_rusage->ru_minflt,
371 rusage.ru_majflt - last_rusage->ru_majflt);
373 if (rusage.ru_inblock > last_rusage->ru_inblock
374 || rusage.ru_oublock > last_rusage->ru_oublock) {
375 VLOG_WARN("disk: %ld reads, %ld writes",
376 rusage.ru_inblock - last_rusage->ru_inblock,
377 rusage.ru_oublock - last_rusage->ru_oublock);
379 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
380 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
381 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
382 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
383 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
389 /* CPU usage tracking. */
392 long long int when; /* Time that this sample was taken. */
393 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
397 struct cpu_usage older;
398 struct cpu_usage newer;
401 struct rusage recent_rusage;
403 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
405 static struct cpu_tracker *
406 get_cpu_tracker(void)
408 struct cpu_tracker *t = cpu_tracker_var_get();
410 t = xzalloc(sizeof *t);
411 t->older.when = LLONG_MIN;
412 t->newer.when = LLONG_MIN;
413 cpu_tracker_var_set_unsafe(t);
418 static struct rusage *
419 get_recent_rusage(void)
421 return &get_cpu_tracker()->recent_rusage;
425 getrusage_thread(struct rusage *rusage OVS_UNUSED)
428 return getrusage(RUSAGE_THREAD, rusage);
438 struct cpu_tracker *t = get_cpu_tracker();
439 struct rusage *recent_rusage = &t->recent_rusage;
441 if (!getrusage_thread(recent_rusage)) {
442 long long int now = time_msec();
443 if (now >= t->newer.when + 3 * 1000) {
446 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
447 timeval_to_msec(&recent_rusage->ru_stime));
449 if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
450 unsigned int dividend = t->newer.cpu - t->older.cpu;
451 unsigned int divisor = (t->newer.when - t->older.when) / 100;
452 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
460 /* Returns an estimate of this process's CPU usage, as a percentage, over the
461 * past few seconds of wall-clock time. Returns -1 if no estimate is available
462 * (which will happen if the process has not been running long enough to have
463 * an estimate, and can happen for other reasons as well). */
467 return get_cpu_tracker()->cpu_usage;
470 /* Unixctl interface. */
472 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
473 * advancing, except due to later calls to "time/warp". */
475 timeval_stop_cb(struct unixctl_conn *conn,
476 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
477 void *aux OVS_UNUSED)
479 ovs_mutex_lock(&monotonic_clock.mutex);
480 atomic_store(&monotonic_clock.slow_path, true);
481 monotonic_clock.stopped = true;
482 xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
483 ovs_mutex_unlock(&monotonic_clock.mutex);
485 unixctl_command_reply(conn, NULL);
488 /* "time/warp MSECS" advances the current monotonic time by the specified
489 * number of milliseconds. Unless "time/stop" has also been executed, the
490 * monotonic clock continues to tick forward at the normal rate afterward.
492 * Does not affect wall clock readings. */
494 timeval_warp_cb(struct unixctl_conn *conn,
495 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
500 msecs = atoi(argv[1]);
502 unixctl_command_reply_error(conn, "invalid MSECS");
506 ts.tv_sec = msecs / 1000;
507 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
509 ovs_mutex_lock(&monotonic_clock.mutex);
510 atomic_store(&monotonic_clock.slow_path, true);
511 timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
512 ovs_mutex_unlock(&monotonic_clock.mutex);
514 unixctl_command_reply(conn, "warped");
518 timeval_dummy_register(void)
520 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
521 unixctl_command_register("time/warp", "MSECS", 1, 1,
522 timeval_warp_cb, NULL);
527 /* strftime() with an extension for high-resolution timestamps. Any '#'s in
528 * 'format' will be replaced by subseconds, e.g. use "%S.###" to obtain results
531 strftime_msec(char *s, size_t max, const char *format,
532 const struct tm_msec *tm)
536 n = strftime(s, max, format, &tm->tm);
541 sprintf(decimals, "%03d", tm->msec);
542 for (p = strchr(s, '#'); p; p = strchr(p, '#')) {
545 *p++ = *d ? *d++ : '0';
554 localtime_msec(long long int now, struct tm_msec *result)
556 time_t now_sec = now / 1000;
557 localtime_r(&now_sec, &result->tm);
558 result->msec = now % 1000;
563 gmtime_msec(long long int now, struct tm_msec *result)
565 time_t now_sec = now / 1000;
566 gmtime_r(&now_sec, &result->tm);
567 result->msec = now % 1000;