]> git.proxmox.com Git - mirror_ovs.git/blob - lib/timeval.c
timeval: Restore ability to warp time forward when time is not stopped.
[mirror_ovs.git] / lib / timeval.c
1 /*
2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3 *
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:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 #include <config.h>
18 #include "timeval.h"
19 #include <errno.h>
20 #include <poll.h>
21 #include <pthread.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/time.h>
26 #include <sys/resource.h>
27 #include <unistd.h>
28 #include "coverage.h"
29 #include "dummy.h"
30 #include "dynamic-string.h"
31 #include "fatal-signal.h"
32 #include "hash.h"
33 #include "hmap.h"
34 #include "ovs-thread.h"
35 #include "signals.h"
36 #include "unixctl.h"
37 #include "util.h"
38 #include "vlog.h"
39
40 VLOG_DEFINE_THIS_MODULE(timeval);
41
42 struct clock {
43 clockid_t id; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
44
45 /* Features for use by unit tests. Protected by 'rwlock'. */
46 struct ovs_rwlock rwlock;
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. */
51 };
52
53 /* Our clocks. */
54 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
55 static struct clock wall_clock; /* CLOCK_REALTIME. */
56
57 /* The monotonic time at which the time module was initialized. */
58 static long long int boot_time;
59
60 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
61 * LLONG_MAX). */
62 static long long int deadline = LLONG_MAX;
63
64 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
65 * up. */
66 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup, 0);
67
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);
73
74 static void
75 init_clock(struct clock *c, clockid_t id)
76 {
77 memset(c, 0, sizeof *c);
78 c->id = id;
79 ovs_rwlock_init(&c->rwlock);
80 atomic_init(&c->slow_path, false);
81 xclock_gettime(c->id, &c->cache);
82 }
83
84 static void
85 do_init_time(void)
86 {
87 struct timespec ts;
88
89 coverage_init();
90
91 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
92 ? CLOCK_MONOTONIC
93 : CLOCK_REALTIME));
94 init_clock(&wall_clock, CLOCK_REALTIME);
95 boot_time = timespec_to_msec(&monotonic_clock.cache);
96 }
97
98 /* Initializes the timetracking module, if not already initialized. */
99 static void
100 time_init(void)
101 {
102 static pthread_once_t once = PTHREAD_ONCE_INIT;
103 pthread_once(&once, do_init_time);
104 }
105
106 static void
107 time_timespec__(struct clock *c, struct timespec *ts)
108 {
109 bool slow_path;
110
111 time_init();
112
113 atomic_read_explicit(&c->slow_path, &slow_path, memory_order_relaxed);
114 if (!slow_path) {
115 xclock_gettime(c->id, ts);
116 } else {
117 struct timespec warp;
118 struct timespec cache;
119 bool stopped;
120
121 ovs_rwlock_rdlock(&c->rwlock);
122 stopped = c->stopped;
123 warp = c->warp;
124 cache = c->cache;
125 ovs_rwlock_unlock(&c->rwlock);
126
127 if (!stopped) {
128 xclock_gettime(c->id, &cache);
129 }
130 timespec_add(ts, &cache, &warp);
131 }
132 }
133
134 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
135 * '*ts'. */
136 void
137 time_timespec(struct timespec *ts)
138 {
139 time_timespec__(&monotonic_clock, ts);
140 }
141
142 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
143 * '*ts'. */
144 void
145 time_wall_timespec(struct timespec *ts)
146 {
147 time_timespec__(&wall_clock, ts);
148 }
149
150 static time_t
151 time_sec__(struct clock *c)
152 {
153 struct timespec ts;
154
155 time_timespec__(c, &ts);
156 return ts.tv_sec;
157 }
158
159 /* Returns a monotonic timer, in seconds. */
160 time_t
161 time_now(void)
162 {
163 return time_sec__(&monotonic_clock);
164 }
165
166 /* Returns the current time, in seconds. */
167 time_t
168 time_wall(void)
169 {
170 return time_sec__(&wall_clock);
171 }
172
173 static long long int
174 time_msec__(struct clock *c)
175 {
176 struct timespec ts;
177
178 time_timespec__(c, &ts);
179 return timespec_to_msec(&ts);
180 }
181
182 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
183 long long int
184 time_msec(void)
185 {
186 return time_msec__(&monotonic_clock);
187 }
188
189 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
190 long long int
191 time_wall_msec(void)
192 {
193 return time_msec__(&wall_clock);
194 }
195
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. */
198 void
199 time_alarm(unsigned int secs)
200 {
201 long long int now;
202 long long int msecs;
203
204 assert_single_threaded();
205 time_init();
206
207 now = time_msec();
208 msecs = secs * 1000LL;
209 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
210 }
211
212 /* Like poll(), except:
213 *
214 * - The timeout is specified as an absolute time, as defined by
215 * time_msec(), instead of a duration.
216 *
217 * - On error, returns a negative error code (instead of setting errno).
218 *
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.)
222 *
223 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
224 int
225 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
226 int *elapsed)
227 {
228 long long int *last_wakeup = last_wakeup_get();
229 long long int start;
230 int retval;
231
232 time_init();
233 if (*last_wakeup) {
234 log_poll_interval(*last_wakeup);
235 }
236 coverage_clear();
237 start = time_msec();
238
239 timeout_when = MIN(timeout_when, deadline);
240
241 for (;;) {
242 long long int now = time_msec();
243 int time_left;
244
245 if (now >= timeout_when) {
246 time_left = 0;
247 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
248 time_left = INT_MAX;
249 } else {
250 time_left = timeout_when - now;
251 }
252
253 retval = poll(pollfds, n_pollfds, time_left);
254 if (retval < 0) {
255 retval = -errno;
256 }
257
258 if (deadline <= time_msec()) {
259 fatal_signal_handler(SIGALRM);
260 if (retval < 0) {
261 retval = 0;
262 }
263 break;
264 }
265
266 if (retval != -EINTR) {
267 break;
268 }
269 }
270 *last_wakeup = time_msec();
271 refresh_rusage();
272 *elapsed = *last_wakeup - start;
273 return retval;
274 }
275
276 long long int
277 timespec_to_msec(const struct timespec *ts)
278 {
279 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
280 }
281
282 long long int
283 timeval_to_msec(const struct timeval *tv)
284 {
285 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
286 }
287
288 /* Returns the monotonic time at which the "time" module was initialized, in
289 * milliseconds. */
290 long long int
291 time_boot_msec(void)
292 {
293 time_init();
294 return boot_time;
295 }
296
297 void
298 xgettimeofday(struct timeval *tv)
299 {
300 if (gettimeofday(tv, NULL) == -1) {
301 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
302 }
303 }
304
305 void
306 xclock_gettime(clock_t id, struct timespec *ts)
307 {
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");
312 }
313 }
314
315 static long long int
316 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
317 {
318 return timeval_to_msec(a) - timeval_to_msec(b);
319 }
320
321 static void
322 timespec_add(struct timespec *sum,
323 const struct timespec *a,
324 const struct timespec *b)
325 {
326 struct timespec tmp;
327
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;
332 tmp.tv_sec++;
333 }
334
335 *sum = tmp;
336 }
337
338 static bool
339 is_warped(const struct clock *c)
340 {
341 bool warped;
342
343 ovs_rwlock_rdlock(&c->rwlock);
344 warped = monotonic_clock.warp.tv_sec || monotonic_clock.warp.tv_nsec;
345 ovs_rwlock_unlock(&c->rwlock);
346
347 return warped;
348 }
349
350 static void
351 log_poll_interval(long long int last_wakeup)
352 {
353 long long int interval = time_msec() - last_wakeup;
354
355 if (interval >= 1000 && !is_warped(&monotonic_clock)) {
356 const struct rusage *last_rusage = get_recent_rusage();
357 struct rusage rusage;
358
359 getrusage(RUSAGE_SELF, &rusage);
360 VLOG_WARN("Unreasonably long %lldms poll interval"
361 " (%lldms user, %lldms system)",
362 interval,
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);
372 }
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);
378 }
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);
384 }
385 coverage_log();
386 }
387 }
388 \f
389 /* CPU usage tracking. */
390
391 struct cpu_usage {
392 long long int when; /* Time that this sample was taken. */
393 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
394 };
395
396 struct cpu_tracker {
397 struct cpu_usage older;
398 struct cpu_usage newer;
399 int cpu_usage;
400
401 struct rusage recent_rusage;
402 };
403 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
404
405 static struct cpu_tracker *
406 get_cpu_tracker(void)
407 {
408 struct cpu_tracker *t = cpu_tracker_var_get();
409 if (!t) {
410 t = xzalloc(sizeof *t);
411 t->older.when = LLONG_MIN;
412 t->newer.when = LLONG_MIN;
413 cpu_tracker_var_set_unsafe(t);
414 }
415 return t;
416 }
417
418 static struct rusage *
419 get_recent_rusage(void)
420 {
421 return &get_cpu_tracker()->recent_rusage;
422 }
423
424 static int
425 getrusage_thread(struct rusage *rusage OVS_UNUSED)
426 {
427 #ifdef RUSAGE_THREAD
428 return getrusage(RUSAGE_THREAD, rusage);
429 #else
430 errno = EINVAL;
431 return -1;
432 #endif
433 }
434
435 static void
436 refresh_rusage(void)
437 {
438 struct cpu_tracker *t = get_cpu_tracker();
439 struct rusage *recent_rusage = &t->recent_rusage;
440
441 if (!getrusage_thread(recent_rusage)) {
442 long long int now = time_msec();
443 if (now >= t->newer.when + 3 * 1000) {
444 t->older = t->newer;
445 t->newer.when = now;
446 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
447 timeval_to_msec(&recent_rusage->ru_stime));
448
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;
453 } else {
454 t->cpu_usage = -1;
455 }
456 }
457 }
458 }
459
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). */
464 int
465 get_cpu_usage(void)
466 {
467 return get_cpu_tracker()->cpu_usage;
468 }
469 \f
470 /* Unixctl interface. */
471
472 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
473 * advancing, except due to later calls to "time/warp". */
474 static void
475 timeval_stop_cb(struct unixctl_conn *conn,
476 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
477 void *aux OVS_UNUSED)
478 {
479 ovs_rwlock_wrlock(&monotonic_clock.rwlock);
480 atomic_store(&monotonic_clock.slow_path, true);
481 monotonic_clock.stopped = true;
482 xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
483 ovs_rwlock_unlock(&monotonic_clock.rwlock);
484
485 unixctl_command_reply(conn, NULL);
486 }
487
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.
491 *
492 * Does not affect wall clock readings. */
493 static void
494 timeval_warp_cb(struct unixctl_conn *conn,
495 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
496 {
497 struct timespec ts;
498 int msecs;
499
500 msecs = atoi(argv[1]);
501 if (msecs <= 0) {
502 unixctl_command_reply_error(conn, "invalid MSECS");
503 return;
504 }
505
506 ts.tv_sec = msecs / 1000;
507 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
508
509 ovs_rwlock_wrlock(&monotonic_clock.rwlock);
510 atomic_store(&monotonic_clock.slow_path, true);
511 timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
512 ovs_rwlock_unlock(&monotonic_clock.rwlock);
513
514 unixctl_command_reply(conn, "warped");
515 }
516
517 void
518 timeval_dummy_register(void)
519 {
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);
523 }
524
525
526
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
529 * like "01.123". */
530 size_t
531 strftime_msec(char *s, size_t max, const char *format,
532 const struct tm_msec *tm)
533 {
534 size_t n;
535
536 n = strftime(s, max, format, &tm->tm);
537 if (n) {
538 char decimals[4];
539 char *p;
540
541 sprintf(decimals, "%03d", tm->msec);
542 for (p = strchr(s, '#'); p; p = strchr(p, '#')) {
543 char *d = decimals;
544 while (*p == '#') {
545 *p++ = *d ? *d++ : '0';
546 }
547 }
548 }
549
550 return n;
551 }
552
553 struct tm_msec *
554 localtime_msec(long long int now, struct tm_msec *result)
555 {
556 time_t now_sec = now / 1000;
557 localtime_r(&now_sec, &result->tm);
558 result->msec = now % 1000;
559 return result;
560 }
561
562 struct tm_msec *
563 gmtime_msec(long long int now, struct tm_msec *result)
564 {
565 time_t now_sec = now / 1000;
566 gmtime_r(&now_sec, &result->tm);
567 result->msec = now % 1000;
568 return result;
569 }