]> git.proxmox.com Git - mirror_ovs.git/blob - lib/timeval.c
timeval: Workaround for threaded test failures
[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 "seq.h"
37 #include "unixctl.h"
38 #include "util.h"
39 #include "vlog.h"
40
41 VLOG_DEFINE_THIS_MODULE(timeval);
42
43 struct clock {
44 clockid_t id; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
45
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. */
52 };
53
54 /* Our clocks. */
55 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
56 static struct clock wall_clock; /* CLOCK_REALTIME. */
57
58 /* The monotonic time at which the time module was initialized. */
59 static long long int boot_time;
60
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);
68
69 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
70 * LLONG_MAX). */
71 static long long int deadline = LLONG_MAX;
72
73 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
74 * up. */
75 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup, 0);
76
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);
82
83 static void
84 init_clock(struct clock *c, clockid_t id)
85 {
86 memset(c, 0, sizeof *c);
87 c->id = id;
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();
92 }
93
94 static void
95 do_init_time(void)
96 {
97 struct timespec ts;
98
99 coverage_init();
100
101 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
102 ? CLOCK_MONOTONIC
103 : CLOCK_REALTIME));
104 init_clock(&wall_clock, CLOCK_REALTIME);
105 boot_time = timespec_to_msec(&monotonic_clock.cache);
106 }
107
108 /* Initializes the timetracking module, if not already initialized. */
109 static void
110 time_init(void)
111 {
112 static pthread_once_t once = PTHREAD_ONCE_INIT;
113 pthread_once(&once, do_init_time);
114 }
115
116 static void
117 time_timespec__(struct clock *c, struct timespec *ts)
118 {
119 bool slow_path;
120
121 time_init();
122
123 atomic_read_explicit(&c->slow_path, &slow_path, memory_order_relaxed);
124 if (!slow_path) {
125 xclock_gettime(c->id, ts);
126 } else {
127 struct timespec warp;
128 struct timespec cache;
129 bool stopped;
130
131 ovs_mutex_lock(&c->mutex);
132 stopped = c->stopped;
133 warp = c->warp;
134 cache = c->cache;
135 ovs_mutex_unlock(&c->mutex);
136
137 if (!stopped) {
138 xclock_gettime(c->id, &cache);
139 }
140 timespec_add(ts, &cache, &warp);
141 }
142 }
143
144 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
145 * '*ts'. */
146 void
147 time_timespec(struct timespec *ts)
148 {
149 time_timespec__(&monotonic_clock, ts);
150 }
151
152 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
153 * '*ts'. */
154 void
155 time_wall_timespec(struct timespec *ts)
156 {
157 time_timespec__(&wall_clock, ts);
158 }
159
160 static time_t
161 time_sec__(struct clock *c)
162 {
163 struct timespec ts;
164
165 time_timespec__(c, &ts);
166 return ts.tv_sec;
167 }
168
169 /* Returns a monotonic timer, in seconds. */
170 time_t
171 time_now(void)
172 {
173 return time_sec__(&monotonic_clock);
174 }
175
176 /* Returns the current time, in seconds. */
177 time_t
178 time_wall(void)
179 {
180 return time_sec__(&wall_clock);
181 }
182
183 static long long int
184 time_msec__(struct clock *c)
185 {
186 struct timespec ts;
187
188 time_timespec__(c, &ts);
189 return timespec_to_msec(&ts);
190 }
191
192 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
193 long long int
194 time_msec(void)
195 {
196 return time_msec__(&monotonic_clock);
197 }
198
199 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
200 long long int
201 time_wall_msec(void)
202 {
203 return time_msec__(&wall_clock);
204 }
205
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. */
208 void
209 time_alarm(unsigned int secs)
210 {
211 long long int now;
212 long long int msecs;
213
214 assert_single_threaded();
215 time_init();
216
217 now = time_msec();
218 msecs = secs * 1000LL;
219 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
220 }
221
222 /* Like poll(), except:
223 *
224 * - The timeout is specified as an absolute time, as defined by
225 * time_msec(), instead of a duration.
226 *
227 * - On error, returns a negative error code (instead of setting errno).
228 *
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.)
232 *
233 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
234 int
235 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
236 int *elapsed)
237 {
238 long long int *last_wakeup = last_wakeup_get();
239 long long int start;
240 int retval;
241
242 time_init();
243 coverage_clear();
244 coverage_run();
245 if (*last_wakeup) {
246 log_poll_interval(*last_wakeup);
247 }
248 start = time_msec();
249
250 timeout_when = MIN(timeout_when, deadline);
251
252 for (;;) {
253 long long int now = time_msec();
254 int time_left;
255
256 if (now >= timeout_when) {
257 time_left = 0;
258 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
259 time_left = INT_MAX;
260 } else {
261 time_left = timeout_when - now;
262 }
263
264 retval = poll(pollfds, n_pollfds, time_left);
265 if (retval < 0) {
266 retval = -errno;
267 }
268
269 if (deadline <= time_msec()) {
270 fatal_signal_handler(SIGALRM);
271 if (retval < 0) {
272 retval = 0;
273 }
274 break;
275 }
276
277 if (retval != -EINTR) {
278 break;
279 }
280 }
281 *last_wakeup = time_msec();
282 refresh_rusage();
283 *elapsed = *last_wakeup - start;
284 return retval;
285 }
286
287 long long int
288 timespec_to_msec(const struct timespec *ts)
289 {
290 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
291 }
292
293 long long int
294 timeval_to_msec(const struct timeval *tv)
295 {
296 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
297 }
298
299 /* Returns the monotonic time at which the "time" module was initialized, in
300 * milliseconds. */
301 long long int
302 time_boot_msec(void)
303 {
304 time_init();
305 return boot_time;
306 }
307
308 void
309 xgettimeofday(struct timeval *tv)
310 {
311 if (gettimeofday(tv, NULL) == -1) {
312 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
313 }
314 }
315
316 void
317 xclock_gettime(clock_t id, struct timespec *ts)
318 {
319 if (clock_gettime(id, ts) == -1) {
320 /* It seems like a bad idea to try to use vlog here because it is
321 * likely to try to check the current time. */
322 ovs_abort(errno, "xclock_gettime() failed");
323 }
324 }
325
326 /* Makes threads wait on timewarp_seq and be waken up when time is warped.
327 * This function will be no-op unless timeval_dummy_register() is called. */
328 void
329 timewarp_wait(void)
330 {
331 if (timewarp_enabled) {
332 uint64_t *last_seq = last_seq_get();
333
334 *last_seq = seq_read(timewarp_seq);
335 seq_wait(timewarp_seq, *last_seq);
336 }
337 }
338
339 static long long int
340 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
341 {
342 return timeval_to_msec(a) - timeval_to_msec(b);
343 }
344
345 static void
346 timespec_add(struct timespec *sum,
347 const struct timespec *a,
348 const struct timespec *b)
349 {
350 struct timespec tmp;
351
352 tmp.tv_sec = a->tv_sec + b->tv_sec;
353 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
354 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
355 tmp.tv_nsec -= 1000 * 1000 * 1000;
356 tmp.tv_sec++;
357 }
358
359 *sum = tmp;
360 }
361
362 static bool
363 is_warped(const struct clock *c)
364 {
365 bool warped;
366
367 ovs_mutex_lock(&c->mutex);
368 warped = monotonic_clock.warp.tv_sec || monotonic_clock.warp.tv_nsec;
369 ovs_mutex_unlock(&c->mutex);
370
371 return warped;
372 }
373
374 static void
375 log_poll_interval(long long int last_wakeup)
376 {
377 long long int interval = time_msec() - last_wakeup;
378
379 if (interval >= 1000 && !is_warped(&monotonic_clock)) {
380 const struct rusage *last_rusage = get_recent_rusage();
381 struct rusage rusage;
382
383 getrusage(RUSAGE_SELF, &rusage);
384 VLOG_WARN("Unreasonably long %lldms poll interval"
385 " (%lldms user, %lldms system)",
386 interval,
387 timeval_diff_msec(&rusage.ru_utime,
388 &last_rusage->ru_utime),
389 timeval_diff_msec(&rusage.ru_stime,
390 &last_rusage->ru_stime));
391 if (rusage.ru_minflt > last_rusage->ru_minflt
392 || rusage.ru_majflt > last_rusage->ru_majflt) {
393 VLOG_WARN("faults: %ld minor, %ld major",
394 rusage.ru_minflt - last_rusage->ru_minflt,
395 rusage.ru_majflt - last_rusage->ru_majflt);
396 }
397 if (rusage.ru_inblock > last_rusage->ru_inblock
398 || rusage.ru_oublock > last_rusage->ru_oublock) {
399 VLOG_WARN("disk: %ld reads, %ld writes",
400 rusage.ru_inblock - last_rusage->ru_inblock,
401 rusage.ru_oublock - last_rusage->ru_oublock);
402 }
403 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
404 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
405 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
406 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
407 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
408 }
409 coverage_log();
410 }
411 }
412 \f
413 /* CPU usage tracking. */
414
415 struct cpu_usage {
416 long long int when; /* Time that this sample was taken. */
417 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
418 };
419
420 struct cpu_tracker {
421 struct cpu_usage older;
422 struct cpu_usage newer;
423 int cpu_usage;
424
425 struct rusage recent_rusage;
426 };
427 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
428
429 static struct cpu_tracker *
430 get_cpu_tracker(void)
431 {
432 struct cpu_tracker *t = cpu_tracker_var_get();
433 if (!t) {
434 t = xzalloc(sizeof *t);
435 t->older.when = LLONG_MIN;
436 t->newer.when = LLONG_MIN;
437 cpu_tracker_var_set_unsafe(t);
438 }
439 return t;
440 }
441
442 static struct rusage *
443 get_recent_rusage(void)
444 {
445 return &get_cpu_tracker()->recent_rusage;
446 }
447
448 static int
449 getrusage_thread(struct rusage *rusage OVS_UNUSED)
450 {
451 #ifdef RUSAGE_THREAD
452 return getrusage(RUSAGE_THREAD, rusage);
453 #else
454 errno = EINVAL;
455 return -1;
456 #endif
457 }
458
459 static void
460 refresh_rusage(void)
461 {
462 struct cpu_tracker *t = get_cpu_tracker();
463 struct rusage *recent_rusage = &t->recent_rusage;
464
465 if (!getrusage_thread(recent_rusage)) {
466 long long int now = time_msec();
467 if (now >= t->newer.when + 3 * 1000) {
468 t->older = t->newer;
469 t->newer.when = now;
470 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
471 timeval_to_msec(&recent_rusage->ru_stime));
472
473 if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
474 unsigned int dividend = t->newer.cpu - t->older.cpu;
475 unsigned int divisor = (t->newer.when - t->older.when) / 100;
476 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
477 } else {
478 t->cpu_usage = -1;
479 }
480 }
481 }
482 }
483
484 /* Returns an estimate of this process's CPU usage, as a percentage, over the
485 * past few seconds of wall-clock time. Returns -1 if no estimate is available
486 * (which will happen if the process has not been running long enough to have
487 * an estimate, and can happen for other reasons as well). */
488 int
489 get_cpu_usage(void)
490 {
491 return get_cpu_tracker()->cpu_usage;
492 }
493 \f
494 /* Unixctl interface. */
495
496 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
497 * advancing, except due to later calls to "time/warp". */
498 static void
499 timeval_stop_cb(struct unixctl_conn *conn,
500 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
501 void *aux OVS_UNUSED)
502 {
503 ovs_mutex_lock(&monotonic_clock.mutex);
504 atomic_store(&monotonic_clock.slow_path, true);
505 monotonic_clock.stopped = true;
506 xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
507 ovs_mutex_unlock(&monotonic_clock.mutex);
508
509 unixctl_command_reply(conn, NULL);
510 }
511
512 /* "time/warp MSECS" advances the current monotonic time by the specified
513 * number of milliseconds. Unless "time/stop" has also been executed, the
514 * monotonic clock continues to tick forward at the normal rate afterward.
515 *
516 * Does not affect wall clock readings. */
517 static void
518 timeval_warp_cb(struct unixctl_conn *conn,
519 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
520 {
521 struct timespec ts;
522 int msecs;
523
524 msecs = atoi(argv[1]);
525 if (msecs <= 0) {
526 unixctl_command_reply_error(conn, "invalid MSECS");
527 return;
528 }
529
530 ts.tv_sec = msecs / 1000;
531 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
532
533 ovs_mutex_lock(&monotonic_clock.mutex);
534 atomic_store(&monotonic_clock.slow_path, true);
535 timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
536 ovs_mutex_unlock(&monotonic_clock.mutex);
537 seq_change(timewarp_seq);
538 poll(NULL, 0, 10); /* give threads (eg. monitor) some chances to run */
539 unixctl_command_reply(conn, "warped");
540 }
541
542 void
543 timeval_dummy_register(void)
544 {
545 timewarp_enabled = true;
546 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
547 unixctl_command_register("time/warp", "MSECS", 1, 1,
548 timeval_warp_cb, NULL);
549 }
550
551
552
553 /* strftime() with an extension for high-resolution timestamps. Any '#'s in
554 * 'format' will be replaced by subseconds, e.g. use "%S.###" to obtain results
555 * like "01.123". */
556 size_t
557 strftime_msec(char *s, size_t max, const char *format,
558 const struct tm_msec *tm)
559 {
560 size_t n;
561
562 n = strftime(s, max, format, &tm->tm);
563 if (n) {
564 char decimals[4];
565 char *p;
566
567 sprintf(decimals, "%03d", tm->msec);
568 for (p = strchr(s, '#'); p; p = strchr(p, '#')) {
569 char *d = decimals;
570 while (*p == '#') {
571 *p++ = *d ? *d++ : '0';
572 }
573 }
574 }
575
576 return n;
577 }
578
579 struct tm_msec *
580 localtime_msec(long long int now, struct tm_msec *result)
581 {
582 time_t now_sec = now / 1000;
583 localtime_r(&now_sec, &result->tm);
584 result->msec = now % 1000;
585 return result;
586 }
587
588 struct tm_msec *
589 gmtime_msec(long long int now, struct tm_msec *result)
590 {
591 time_t now_sec = now / 1000;
592 gmtime_r(&now_sec, &result->tm);
593 result->msec = now % 1000;
594 return result;
595 }