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 'rwlock'. */
46 struct ovs_rwlock rwlock;
47 struct timespec warp; /* Offset added for unit tests. */
48 bool stopped; /* Disables real-time updates if true. */
50 struct timespec cache; /* 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 xclock_gettime(c->id, &c->cache);
89 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
92 init_clock(&wall_clock, CLOCK_REALTIME);
93 boot_time = timespec_to_msec(&monotonic_clock.cache);
96 /* Initializes the timetracking module, if not already initialized. */
100 static pthread_once_t once = PTHREAD_ONCE_INIT;
101 pthread_once(&once, do_init_time);
105 time_timespec__(struct clock *c, struct timespec *ts)
110 xclock_gettime(c->id, ts);
112 ovs_rwlock_rdlock(&c->rwlock);
113 timespec_add(ts, &c->cache, &c->warp);
114 ovs_rwlock_unlock(&c->rwlock);
118 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
121 time_timespec(struct timespec *ts)
123 time_timespec__(&monotonic_clock, ts);
126 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
129 time_wall_timespec(struct timespec *ts)
131 time_timespec__(&wall_clock, ts);
135 time_sec__(struct clock *c)
139 time_timespec__(c, &ts);
143 /* Returns a monotonic timer, in seconds. */
147 return time_sec__(&monotonic_clock);
150 /* Returns the current time, in seconds. */
154 return time_sec__(&wall_clock);
158 time_msec__(struct clock *c)
162 time_timespec__(c, &ts);
163 return timespec_to_msec(&ts);
166 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
170 return time_msec__(&monotonic_clock);
173 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
177 return time_msec__(&wall_clock);
180 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
181 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
183 time_alarm(unsigned int secs)
188 assert_single_threaded();
192 msecs = secs * 1000LL;
193 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
196 /* Like poll(), except:
198 * - The timeout is specified as an absolute time, as defined by
199 * time_msec(), instead of a duration.
201 * - On error, returns a negative error code (instead of setting errno).
203 * - If interrupted by a signal, retries automatically until the original
204 * timeout is reached. (Because of this property, this function will
205 * never return -EINTR.)
207 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
209 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
212 long long int *last_wakeup = last_wakeup_get();
218 log_poll_interval(*last_wakeup);
223 timeout_when = MIN(timeout_when, deadline);
226 long long int now = time_msec();
229 if (now >= timeout_when) {
231 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
234 time_left = timeout_when - now;
237 retval = poll(pollfds, n_pollfds, time_left);
242 if (deadline <= time_msec()) {
243 fatal_signal_handler(SIGALRM);
250 if (retval != -EINTR) {
254 *last_wakeup = time_msec();
256 *elapsed = *last_wakeup - start;
261 timespec_to_msec(const struct timespec *ts)
263 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
267 timeval_to_msec(const struct timeval *tv)
269 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
272 /* Returns the monotonic time at which the "time" module was initialized, in
282 xgettimeofday(struct timeval *tv)
284 if (gettimeofday(tv, NULL) == -1) {
285 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
290 xclock_gettime(clock_t id, struct timespec *ts)
292 if (clock_gettime(id, ts) == -1) {
293 /* It seems like a bad idea to try to use vlog here because it is
294 * likely to try to check the current time. */
295 ovs_abort(errno, "xclock_gettime() failed");
300 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
302 return timeval_to_msec(a) - timeval_to_msec(b);
306 timespec_add(struct timespec *sum,
307 const struct timespec *a,
308 const struct timespec *b)
312 tmp.tv_sec = a->tv_sec + b->tv_sec;
313 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
314 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
315 tmp.tv_nsec -= 1000 * 1000 * 1000;
323 log_poll_interval(long long int last_wakeup)
325 long long int interval = time_msec() - last_wakeup;
328 && !monotonic_clock.warp.tv_sec
329 && !monotonic_clock.warp.tv_nsec) {
330 const struct rusage *last_rusage = get_recent_rusage();
331 struct rusage rusage;
333 getrusage(RUSAGE_SELF, &rusage);
334 VLOG_WARN("Unreasonably long %lldms poll interval"
335 " (%lldms user, %lldms system)",
337 timeval_diff_msec(&rusage.ru_utime,
338 &last_rusage->ru_utime),
339 timeval_diff_msec(&rusage.ru_stime,
340 &last_rusage->ru_stime));
341 if (rusage.ru_minflt > last_rusage->ru_minflt
342 || rusage.ru_majflt > last_rusage->ru_majflt) {
343 VLOG_WARN("faults: %ld minor, %ld major",
344 rusage.ru_minflt - last_rusage->ru_minflt,
345 rusage.ru_majflt - last_rusage->ru_majflt);
347 if (rusage.ru_inblock > last_rusage->ru_inblock
348 || rusage.ru_oublock > last_rusage->ru_oublock) {
349 VLOG_WARN("disk: %ld reads, %ld writes",
350 rusage.ru_inblock - last_rusage->ru_inblock,
351 rusage.ru_oublock - last_rusage->ru_oublock);
353 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
354 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
355 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
356 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
357 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
363 /* CPU usage tracking. */
366 long long int when; /* Time that this sample was taken. */
367 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
371 struct cpu_usage older;
372 struct cpu_usage newer;
375 struct rusage recent_rusage;
377 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
379 static struct cpu_tracker *
380 get_cpu_tracker(void)
382 struct cpu_tracker *t = cpu_tracker_var_get();
384 t = xzalloc(sizeof *t);
385 t->older.when = LLONG_MIN;
386 t->newer.when = LLONG_MIN;
387 cpu_tracker_var_set_unsafe(t);
392 static struct rusage *
393 get_recent_rusage(void)
395 return &get_cpu_tracker()->recent_rusage;
399 getrusage_thread(struct rusage *rusage OVS_UNUSED)
402 return getrusage(RUSAGE_THREAD, rusage);
412 struct cpu_tracker *t = get_cpu_tracker();
413 struct rusage *recent_rusage = &t->recent_rusage;
415 if (!getrusage_thread(recent_rusage)) {
416 long long int now = time_msec();
417 if (now >= t->newer.when + 3 * 1000) {
420 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
421 timeval_to_msec(&recent_rusage->ru_stime));
423 if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
424 unsigned int dividend = t->newer.cpu - t->older.cpu;
425 unsigned int divisor = (t->newer.when - t->older.when) / 100;
426 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
434 /* Returns an estimate of this process's CPU usage, as a percentage, over the
435 * past few seconds of wall-clock time. Returns -1 if no estimate is available
436 * (which will happen if the process has not been running long enough to have
437 * an estimate, and can happen for other reasons as well). */
441 return get_cpu_tracker()->cpu_usage;
444 /* Unixctl interface. */
446 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
447 * advancing, except due to later calls to "time/warp". */
449 timeval_stop_cb(struct unixctl_conn *conn,
450 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
451 void *aux OVS_UNUSED)
453 ovs_rwlock_wrlock(&monotonic_clock.rwlock);
454 monotonic_clock.stopped = true;
455 xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
456 ovs_rwlock_unlock(&monotonic_clock.rwlock);
458 unixctl_command_reply(conn, NULL);
461 /* "time/warp MSECS" advances the current monotonic time by the specified
462 * number of milliseconds. Unless "time/stop" has also been executed, the
463 * monotonic clock continues to tick forward at the normal rate afterward.
465 * Does not affect wall clock readings. */
467 timeval_warp_cb(struct unixctl_conn *conn,
468 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
473 msecs = atoi(argv[1]);
475 unixctl_command_reply_error(conn, "invalid MSECS");
479 ts.tv_sec = msecs / 1000;
480 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
482 ovs_rwlock_wrlock(&monotonic_clock.rwlock);
483 timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
484 ovs_rwlock_unlock(&monotonic_clock.rwlock);
486 unixctl_command_reply(conn, "warped");
490 timeval_dummy_register(void)
492 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
493 unixctl_command_register("time/warp", "MSECS", 1, 1,
494 timeval_warp_cb, NULL);