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 ovs_rwlock_init(&c->rwlock);
80 xclock_gettime(c->id, &c->cache);
90 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
93 init_clock(&wall_clock, CLOCK_REALTIME);
94 boot_time = timespec_to_msec(&monotonic_clock.cache);
97 /* Initializes the timetracking module, if not already initialized. */
101 static pthread_once_t once = PTHREAD_ONCE_INIT;
102 pthread_once(&once, do_init_time);
106 time_timespec__(struct clock *c, struct timespec *ts)
111 xclock_gettime(c->id, ts);
113 ovs_rwlock_rdlock(&c->rwlock);
114 timespec_add(ts, &c->cache, &c->warp);
115 ovs_rwlock_unlock(&c->rwlock);
119 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
122 time_timespec(struct timespec *ts)
124 time_timespec__(&monotonic_clock, ts);
127 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
130 time_wall_timespec(struct timespec *ts)
132 time_timespec__(&wall_clock, ts);
136 time_sec__(struct clock *c)
140 time_timespec__(c, &ts);
144 /* Returns a monotonic timer, in seconds. */
148 return time_sec__(&monotonic_clock);
151 /* Returns the current time, in seconds. */
155 return time_sec__(&wall_clock);
159 time_msec__(struct clock *c)
163 time_timespec__(c, &ts);
164 return timespec_to_msec(&ts);
167 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
171 return time_msec__(&monotonic_clock);
174 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
178 return time_msec__(&wall_clock);
181 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
182 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
184 time_alarm(unsigned int secs)
189 assert_single_threaded();
193 msecs = secs * 1000LL;
194 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
197 /* Like poll(), except:
199 * - The timeout is specified as an absolute time, as defined by
200 * time_msec(), instead of a duration.
202 * - On error, returns a negative error code (instead of setting errno).
204 * - If interrupted by a signal, retries automatically until the original
205 * timeout is reached. (Because of this property, this function will
206 * never return -EINTR.)
208 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
210 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
213 long long int *last_wakeup = last_wakeup_get();
219 log_poll_interval(*last_wakeup);
224 timeout_when = MIN(timeout_when, deadline);
227 long long int now = time_msec();
230 if (now >= timeout_when) {
232 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
235 time_left = timeout_when - now;
238 retval = poll(pollfds, n_pollfds, time_left);
243 if (deadline <= time_msec()) {
244 fatal_signal_handler(SIGALRM);
251 if (retval != -EINTR) {
255 *last_wakeup = time_msec();
257 *elapsed = *last_wakeup - start;
262 timespec_to_msec(const struct timespec *ts)
264 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
268 timeval_to_msec(const struct timeval *tv)
270 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
273 /* Returns the monotonic time at which the "time" module was initialized, in
283 xgettimeofday(struct timeval *tv)
285 if (gettimeofday(tv, NULL) == -1) {
286 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
291 xclock_gettime(clock_t id, struct timespec *ts)
293 if (clock_gettime(id, ts) == -1) {
294 /* It seems like a bad idea to try to use vlog here because it is
295 * likely to try to check the current time. */
296 ovs_abort(errno, "xclock_gettime() failed");
301 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
303 return timeval_to_msec(a) - timeval_to_msec(b);
307 timespec_add(struct timespec *sum,
308 const struct timespec *a,
309 const struct timespec *b)
313 tmp.tv_sec = a->tv_sec + b->tv_sec;
314 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
315 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
316 tmp.tv_nsec -= 1000 * 1000 * 1000;
324 log_poll_interval(long long int last_wakeup)
326 long long int interval = time_msec() - last_wakeup;
329 && !monotonic_clock.warp.tv_sec
330 && !monotonic_clock.warp.tv_nsec) {
331 const struct rusage *last_rusage = get_recent_rusage();
332 struct rusage rusage;
334 getrusage(RUSAGE_SELF, &rusage);
335 VLOG_WARN("Unreasonably long %lldms poll interval"
336 " (%lldms user, %lldms system)",
338 timeval_diff_msec(&rusage.ru_utime,
339 &last_rusage->ru_utime),
340 timeval_diff_msec(&rusage.ru_stime,
341 &last_rusage->ru_stime));
342 if (rusage.ru_minflt > last_rusage->ru_minflt
343 || rusage.ru_majflt > last_rusage->ru_majflt) {
344 VLOG_WARN("faults: %ld minor, %ld major",
345 rusage.ru_minflt - last_rusage->ru_minflt,
346 rusage.ru_majflt - last_rusage->ru_majflt);
348 if (rusage.ru_inblock > last_rusage->ru_inblock
349 || rusage.ru_oublock > last_rusage->ru_oublock) {
350 VLOG_WARN("disk: %ld reads, %ld writes",
351 rusage.ru_inblock - last_rusage->ru_inblock,
352 rusage.ru_oublock - last_rusage->ru_oublock);
354 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
355 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
356 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
357 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
358 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
364 /* CPU usage tracking. */
367 long long int when; /* Time that this sample was taken. */
368 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
372 struct cpu_usage older;
373 struct cpu_usage newer;
376 struct rusage recent_rusage;
378 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
380 static struct cpu_tracker *
381 get_cpu_tracker(void)
383 struct cpu_tracker *t = cpu_tracker_var_get();
385 t = xzalloc(sizeof *t);
386 t->older.when = LLONG_MIN;
387 t->newer.when = LLONG_MIN;
388 cpu_tracker_var_set_unsafe(t);
393 static struct rusage *
394 get_recent_rusage(void)
396 return &get_cpu_tracker()->recent_rusage;
400 getrusage_thread(struct rusage *rusage OVS_UNUSED)
403 return getrusage(RUSAGE_THREAD, rusage);
413 struct cpu_tracker *t = get_cpu_tracker();
414 struct rusage *recent_rusage = &t->recent_rusage;
416 if (!getrusage_thread(recent_rusage)) {
417 long long int now = time_msec();
418 if (now >= t->newer.when + 3 * 1000) {
421 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
422 timeval_to_msec(&recent_rusage->ru_stime));
424 if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
425 unsigned int dividend = t->newer.cpu - t->older.cpu;
426 unsigned int divisor = (t->newer.when - t->older.when) / 100;
427 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
435 /* Returns an estimate of this process's CPU usage, as a percentage, over the
436 * past few seconds of wall-clock time. Returns -1 if no estimate is available
437 * (which will happen if the process has not been running long enough to have
438 * an estimate, and can happen for other reasons as well). */
442 return get_cpu_tracker()->cpu_usage;
445 /* Unixctl interface. */
447 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
448 * advancing, except due to later calls to "time/warp". */
450 timeval_stop_cb(struct unixctl_conn *conn,
451 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
452 void *aux OVS_UNUSED)
454 ovs_rwlock_wrlock(&monotonic_clock.rwlock);
455 monotonic_clock.stopped = true;
456 xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
457 ovs_rwlock_unlock(&monotonic_clock.rwlock);
459 unixctl_command_reply(conn, NULL);
462 /* "time/warp MSECS" advances the current monotonic time by the specified
463 * number of milliseconds. Unless "time/stop" has also been executed, the
464 * monotonic clock continues to tick forward at the normal rate afterward.
466 * Does not affect wall clock readings. */
468 timeval_warp_cb(struct unixctl_conn *conn,
469 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
474 msecs = atoi(argv[1]);
476 unixctl_command_reply_error(conn, "invalid MSECS");
480 ts.tv_sec = msecs / 1000;
481 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
483 ovs_rwlock_wrlock(&monotonic_clock.rwlock);
484 timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
485 ovs_rwlock_unlock(&monotonic_clock.rwlock);
487 unixctl_command_reply(conn, "warped");
491 timeval_dummy_register(void)
493 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
494 unixctl_command_register("time/warp", "MSECS", 1, 1,
495 timeval_warp_cb, NULL);