]> git.proxmox.com Git - ovs.git/blob - lib/timeval.c
Replace most uses of assert by ovs_assert.
[ovs.git] / lib / timeval.c
1 /*
2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 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 #if HAVE_EXECINFO_H
21 #include <execinfo.h>
22 #endif
23 #include <poll.h>
24 #include <signal.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/time.h>
28 #include <sys/resource.h>
29 #include <unistd.h>
30 #include "coverage.h"
31 #include "dummy.h"
32 #include "dynamic-string.h"
33 #include "fatal-signal.h"
34 #include "hash.h"
35 #include "hmap.h"
36 #include "signals.h"
37 #include "unixctl.h"
38 #include "util.h"
39 #include "vlog.h"
40
41 VLOG_DEFINE_THIS_MODULE(timeval);
42
43 /* The clock to use for measuring time intervals. This is CLOCK_MONOTONIC by
44 * preference, but on systems that don't have a monotonic clock we fall back
45 * to CLOCK_REALTIME. */
46 static clockid_t monotonic_clock;
47
48 /* Has a timer tick occurred? Only relevant if CACHE_TIME is true.
49 *
50 * We initialize these to true to force time_init() to get called on the first
51 * call to time_msec() or another function that queries the current time. */
52 static volatile sig_atomic_t wall_tick = true;
53 static volatile sig_atomic_t monotonic_tick = true;
54
55 /* The current time, as of the last refresh. */
56 static struct timespec wall_time;
57 static struct timespec monotonic_time;
58
59 /* The monotonic time at which the time module was initialized. */
60 static long long int boot_time;
61
62 /* features for use by unit tests. */
63 static struct timespec warp_offset; /* Offset added to monotonic_time. */
64 static bool time_stopped; /* Disables real-time updates, if true. */
65
66 /* Time in milliseconds at which to die with SIGALRM (if not LLONG_MAX). */
67 static long long int deadline = LLONG_MAX;
68
69 struct trace {
70 void *backtrace[32]; /* Populated by backtrace(). */
71 size_t n_frames; /* Number of frames in 'backtrace'. */
72
73 /* format_backtraces() helper data. */
74 struct hmap_node node;
75 size_t count;
76 };
77
78 #define MAX_TRACES 50
79 static struct trace traces[MAX_TRACES];
80 static size_t trace_head = 0;
81
82 static void set_up_timer(void);
83 static void set_up_signal(int flags);
84 static void sigalrm_handler(int);
85 static void refresh_wall_if_ticked(void);
86 static void refresh_monotonic_if_ticked(void);
87 static void block_sigalrm(sigset_t *);
88 static void unblock_sigalrm(const sigset_t *);
89 static void log_poll_interval(long long int last_wakeup);
90 static struct rusage *get_recent_rusage(void);
91 static void refresh_rusage(void);
92 static void timespec_add(struct timespec *sum,
93 const struct timespec *a, const struct timespec *b);
94 static unixctl_cb_func backtrace_cb;
95
96 #ifndef HAVE_EXECINFO_H
97 #define HAVE_EXECINFO_H 0
98
99 static int
100 backtrace(void **buffer OVS_UNUSED, int size OVS_UNUSED)
101 {
102 NOT_REACHED();
103 }
104
105 static char **
106 backtrace_symbols(void *const *buffer OVS_UNUSED, int size OVS_UNUSED)
107 {
108 NOT_REACHED();
109 }
110 #endif
111
112 /* Initializes the timetracking module, if not already initialized. */
113 static void
114 time_init(void)
115 {
116 static bool inited;
117
118 if (inited) {
119 return;
120 }
121 inited = true;
122
123 /* The implementation of backtrace() in glibc does some one time
124 * initialization which is not signal safe. This can cause deadlocks if
125 * run from the signal handler. As a workaround, force the initialization
126 * to happen here. */
127 if (HAVE_EXECINFO_H) {
128 void *bt[1];
129
130 backtrace(bt, ARRAY_SIZE(bt));
131 }
132
133 memset(traces, 0, sizeof traces);
134
135 if (HAVE_EXECINFO_H && CACHE_TIME) {
136 unixctl_command_register("backtrace", "", 0, 0, backtrace_cb, NULL);
137 }
138
139 coverage_init();
140
141 if (!clock_gettime(CLOCK_MONOTONIC, &monotonic_time)) {
142 monotonic_clock = CLOCK_MONOTONIC;
143 } else {
144 monotonic_clock = CLOCK_REALTIME;
145 VLOG_DBG("monotonic timer not available");
146 }
147
148 set_up_signal(SA_RESTART);
149 set_up_timer();
150
151 boot_time = time_msec();
152 }
153
154 static void
155 set_up_signal(int flags)
156 {
157 struct sigaction sa;
158
159 memset(&sa, 0, sizeof sa);
160 sa.sa_handler = sigalrm_handler;
161 sigemptyset(&sa.sa_mask);
162 sa.sa_flags = flags;
163 xsigaction(SIGALRM, &sa, NULL);
164 }
165
166 /* Remove SA_RESTART from the flags for SIGALRM, so that any system call that
167 * is interrupted by the periodic timer interrupt will return EINTR instead of
168 * continuing after the signal handler returns.
169 *
170 * time_disable_restart() and time_enable_restart() may be usefully wrapped
171 * around function calls that might otherwise block forever unless interrupted
172 * by a signal, e.g.:
173 *
174 * time_disable_restart();
175 * fcntl(fd, F_SETLKW, &lock);
176 * time_enable_restart();
177 */
178 void
179 time_disable_restart(void)
180 {
181 time_init();
182 set_up_signal(0);
183 }
184
185 /* Add SA_RESTART to the flags for SIGALRM, so that any system call that
186 * is interrupted by the periodic timer interrupt will continue after the
187 * signal handler returns instead of returning EINTR. */
188 void
189 time_enable_restart(void)
190 {
191 time_init();
192 set_up_signal(SA_RESTART);
193 }
194
195 static void
196 set_up_timer(void)
197 {
198 static timer_t timer_id; /* "static" to avoid apparent memory leak. */
199 struct itimerspec itimer;
200
201 if (!CACHE_TIME) {
202 return;
203 }
204
205 if (timer_create(monotonic_clock, NULL, &timer_id)) {
206 VLOG_FATAL("timer_create failed (%s)", strerror(errno));
207 }
208
209 itimer.it_interval.tv_sec = 0;
210 itimer.it_interval.tv_nsec = TIME_UPDATE_INTERVAL * 1000 * 1000;
211 itimer.it_value = itimer.it_interval;
212
213 if (timer_settime(timer_id, 0, &itimer, NULL)) {
214 VLOG_FATAL("timer_settime failed (%s)", strerror(errno));
215 }
216 }
217
218 /* Set up the interval timer, to ensure that time advances even without calling
219 * time_refresh().
220 *
221 * A child created with fork() does not inherit the parent's interval timer, so
222 * this function needs to be called from the child after fork(). */
223 void
224 time_postfork(void)
225 {
226 time_init();
227 set_up_timer();
228 }
229
230 static void
231 refresh_wall(void)
232 {
233 time_init();
234 clock_gettime(CLOCK_REALTIME, &wall_time);
235 wall_tick = false;
236 }
237
238 static void
239 refresh_monotonic(void)
240 {
241 time_init();
242
243 if (!time_stopped) {
244 if (monotonic_clock == CLOCK_MONOTONIC) {
245 clock_gettime(monotonic_clock, &monotonic_time);
246 } else {
247 refresh_wall_if_ticked();
248 monotonic_time = wall_time;
249 }
250 timespec_add(&monotonic_time, &monotonic_time, &warp_offset);
251
252 monotonic_tick = false;
253 }
254 }
255
256 /* Forces a refresh of the current time from the kernel. It is not usually
257 * necessary to call this function, since the time will be refreshed
258 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. If
259 * CACHE_TIME is false, we will always refresh the current time so this
260 * function has no effect. */
261 void
262 time_refresh(void)
263 {
264 wall_tick = monotonic_tick = true;
265 }
266
267 /* Returns a monotonic timer, in seconds. */
268 time_t
269 time_now(void)
270 {
271 refresh_monotonic_if_ticked();
272 return monotonic_time.tv_sec;
273 }
274
275 /* Returns the current time, in seconds. */
276 time_t
277 time_wall(void)
278 {
279 refresh_wall_if_ticked();
280 return wall_time.tv_sec;
281 }
282
283 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
284 long long int
285 time_msec(void)
286 {
287 refresh_monotonic_if_ticked();
288 return timespec_to_msec(&monotonic_time);
289 }
290
291 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
292 long long int
293 time_wall_msec(void)
294 {
295 refresh_wall_if_ticked();
296 return timespec_to_msec(&wall_time);
297 }
298
299 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
300 * '*ts'. */
301 void
302 time_timespec(struct timespec *ts)
303 {
304 refresh_monotonic_if_ticked();
305 *ts = monotonic_time;
306 }
307
308 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
309 * '*ts'. */
310 void
311 time_wall_timespec(struct timespec *ts)
312 {
313 refresh_wall_if_ticked();
314 *ts = wall_time;
315 }
316
317 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
318 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
319 void
320 time_alarm(unsigned int secs)
321 {
322 long long int now;
323 long long int msecs;
324
325 sigset_t oldsigs;
326
327 time_init();
328 time_refresh();
329
330 now = time_msec();
331 msecs = secs * 1000;
332
333 block_sigalrm(&oldsigs);
334 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
335 unblock_sigalrm(&oldsigs);
336 }
337
338 /* Like poll(), except:
339 *
340 * - The timeout is specified as an absolute time, as defined by
341 * time_msec(), instead of a duration.
342 *
343 * - On error, returns a negative error code (instead of setting errno).
344 *
345 * - If interrupted by a signal, retries automatically until the original
346 * timeout is reached. (Because of this property, this function will
347 * never return -EINTR.)
348 *
349 * - As a side effect, refreshes the current time (like time_refresh()).
350 *
351 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
352 int
353 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
354 int *elapsed)
355 {
356 static long long int last_wakeup = 0;
357 long long int start;
358 sigset_t oldsigs;
359 bool blocked;
360 int retval;
361
362 time_refresh();
363 if (last_wakeup) {
364 log_poll_interval(last_wakeup);
365 }
366 coverage_clear();
367 start = time_msec();
368 blocked = false;
369
370 timeout_when = MIN(timeout_when, deadline);
371
372 for (;;) {
373 long long int now = time_msec();
374 int time_left;
375
376 if (now >= timeout_when) {
377 time_left = 0;
378 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
379 time_left = INT_MAX;
380 } else {
381 time_left = timeout_when - now;
382 }
383
384 retval = poll(pollfds, n_pollfds, time_left);
385 if (retval < 0) {
386 retval = -errno;
387 }
388
389 time_refresh();
390 if (deadline <= time_msec()) {
391 fatal_signal_handler(SIGALRM);
392 if (retval < 0) {
393 retval = 0;
394 }
395 break;
396 }
397
398 if (retval != -EINTR) {
399 break;
400 }
401
402 if (!blocked && CACHE_TIME) {
403 block_sigalrm(&oldsigs);
404 blocked = true;
405 }
406 }
407 if (blocked) {
408 unblock_sigalrm(&oldsigs);
409 }
410 last_wakeup = time_msec();
411 refresh_rusage();
412 *elapsed = last_wakeup - start;
413 return retval;
414 }
415
416 static void
417 sigalrm_handler(int sig_nr OVS_UNUSED)
418 {
419 wall_tick = true;
420 monotonic_tick = true;
421
422 if (HAVE_EXECINFO_H && CACHE_TIME) {
423 struct trace *trace = &traces[trace_head];
424
425 trace->n_frames = backtrace(trace->backtrace,
426 ARRAY_SIZE(trace->backtrace));
427 trace_head = (trace_head + 1) % MAX_TRACES;
428 }
429 }
430
431 static void
432 refresh_wall_if_ticked(void)
433 {
434 if (!CACHE_TIME || wall_tick) {
435 refresh_wall();
436 }
437 }
438
439 static void
440 refresh_monotonic_if_ticked(void)
441 {
442 if (!CACHE_TIME || monotonic_tick) {
443 refresh_monotonic();
444 }
445 }
446
447 static void
448 block_sigalrm(sigset_t *oldsigs)
449 {
450 sigset_t sigalrm;
451 sigemptyset(&sigalrm);
452 sigaddset(&sigalrm, SIGALRM);
453 xsigprocmask(SIG_BLOCK, &sigalrm, oldsigs);
454 }
455
456 static void
457 unblock_sigalrm(const sigset_t *oldsigs)
458 {
459 xsigprocmask(SIG_SETMASK, oldsigs, NULL);
460 }
461
462 long long int
463 timespec_to_msec(const struct timespec *ts)
464 {
465 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
466 }
467
468 long long int
469 timeval_to_msec(const struct timeval *tv)
470 {
471 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
472 }
473
474 /* Returns the monotonic time at which the "time" module was initialized, in
475 * milliseconds(). */
476 long long int
477 time_boot_msec(void)
478 {
479 time_init();
480 return boot_time;
481 }
482
483 void
484 xgettimeofday(struct timeval *tv)
485 {
486 if (gettimeofday(tv, NULL) == -1) {
487 VLOG_FATAL("gettimeofday failed (%s)", strerror(errno));
488 }
489 }
490
491 static long long int
492 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
493 {
494 return timeval_to_msec(a) - timeval_to_msec(b);
495 }
496
497 static void
498 timespec_add(struct timespec *sum,
499 const struct timespec *a,
500 const struct timespec *b)
501 {
502 struct timespec tmp;
503
504 tmp.tv_sec = a->tv_sec + b->tv_sec;
505 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
506 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
507 tmp.tv_nsec -= 1000 * 1000 * 1000;
508 tmp.tv_sec++;
509 }
510
511 *sum = tmp;
512 }
513
514 static void
515 log_poll_interval(long long int last_wakeup)
516 {
517 long long int interval = time_msec() - last_wakeup;
518
519 if (interval >= 1000) {
520 const struct rusage *last_rusage = get_recent_rusage();
521 struct rusage rusage;
522
523 getrusage(RUSAGE_SELF, &rusage);
524 VLOG_WARN("Unreasonably long %lldms poll interval"
525 " (%lldms user, %lldms system)",
526 interval,
527 timeval_diff_msec(&rusage.ru_utime,
528 &last_rusage->ru_utime),
529 timeval_diff_msec(&rusage.ru_stime,
530 &last_rusage->ru_stime));
531 if (rusage.ru_minflt > last_rusage->ru_minflt
532 || rusage.ru_majflt > last_rusage->ru_majflt) {
533 VLOG_WARN("faults: %ld minor, %ld major",
534 rusage.ru_minflt - last_rusage->ru_minflt,
535 rusage.ru_majflt - last_rusage->ru_majflt);
536 }
537 if (rusage.ru_inblock > last_rusage->ru_inblock
538 || rusage.ru_oublock > last_rusage->ru_oublock) {
539 VLOG_WARN("disk: %ld reads, %ld writes",
540 rusage.ru_inblock - last_rusage->ru_inblock,
541 rusage.ru_oublock - last_rusage->ru_oublock);
542 }
543 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
544 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
545 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
546 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
547 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
548 }
549 coverage_log();
550 }
551 }
552 \f
553 /* CPU usage tracking. */
554
555 struct cpu_usage {
556 long long int when; /* Time that this sample was taken. */
557 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
558 };
559
560 static struct rusage recent_rusage;
561 static struct cpu_usage older = { LLONG_MIN, 0 };
562 static struct cpu_usage newer = { LLONG_MIN, 0 };
563 static int cpu_usage = -1;
564
565 static struct rusage *
566 get_recent_rusage(void)
567 {
568 return &recent_rusage;
569 }
570
571 static void
572 refresh_rusage(void)
573 {
574 long long int now;
575
576 now = time_msec();
577 getrusage(RUSAGE_SELF, &recent_rusage);
578
579 if (now >= newer.when + 3 * 1000) {
580 older = newer;
581 newer.when = now;
582 newer.cpu = (timeval_to_msec(&recent_rusage.ru_utime) +
583 timeval_to_msec(&recent_rusage.ru_stime));
584
585 if (older.when != LLONG_MIN && newer.cpu > older.cpu) {
586 unsigned int dividend = newer.cpu - older.cpu;
587 unsigned int divisor = (newer.when - older.when) / 100;
588 cpu_usage = divisor > 0 ? dividend / divisor : -1;
589 } else {
590 cpu_usage = -1;
591 }
592 }
593 }
594
595 /* Returns an estimate of this process's CPU usage, as a percentage, over the
596 * past few seconds of wall-clock time. Returns -1 if no estimate is available
597 * (which will happen if the process has not been running long enough to have
598 * an estimate, and can happen for other reasons as well). */
599 int
600 get_cpu_usage(void)
601 {
602 return cpu_usage;
603 }
604
605 static uint32_t
606 hash_trace(struct trace *trace)
607 {
608 return hash_bytes(trace->backtrace,
609 trace->n_frames * sizeof *trace->backtrace, 0);
610 }
611
612 static struct trace *
613 trace_map_lookup(struct hmap *trace_map, struct trace *key)
614 {
615 struct trace *value;
616
617 HMAP_FOR_EACH_WITH_HASH (value, node, hash_trace(key), trace_map) {
618 if (key->n_frames == value->n_frames
619 && !memcmp(key->backtrace, value->backtrace,
620 key->n_frames * sizeof *key->backtrace)) {
621 return value;
622 }
623 }
624 return NULL;
625 }
626
627 /* Appends a string to 'ds' representing backtraces recorded at regular
628 * intervals in the recent past. This information can be used to get a sense
629 * of what the process has been spending the majority of time doing. Will
630 * ommit any backtraces which have not occurred at least 'min_count' times. */
631 void
632 format_backtraces(struct ds *ds, size_t min_count)
633 {
634 time_init();
635
636 if (HAVE_EXECINFO_H && CACHE_TIME) {
637 struct hmap trace_map = HMAP_INITIALIZER(&trace_map);
638 struct trace *trace, *next;
639 sigset_t oldsigs;
640 size_t i;
641
642 block_sigalrm(&oldsigs);
643
644 for (i = 0; i < MAX_TRACES; i++) {
645 struct trace *trace = &traces[i];
646 struct trace *map_trace;
647
648 if (!trace->n_frames) {
649 continue;
650 }
651
652 map_trace = trace_map_lookup(&trace_map, trace);
653 if (map_trace) {
654 map_trace->count++;
655 } else {
656 hmap_insert(&trace_map, &trace->node, hash_trace(trace));
657 trace->count = 1;
658 }
659 }
660
661 HMAP_FOR_EACH_SAFE (trace, next, node, &trace_map) {
662 char **frame_strs;
663 size_t j;
664
665 hmap_remove(&trace_map, &trace->node);
666
667 if (trace->count < min_count) {
668 continue;
669 }
670
671 frame_strs = backtrace_symbols(trace->backtrace, trace->n_frames);
672
673 ds_put_format(ds, "Count %zu\n", trace->count);
674 for (j = 0; j < trace->n_frames; j++) {
675 ds_put_format(ds, "%s\n", frame_strs[j]);
676 }
677 ds_put_cstr(ds, "\n");
678
679 free(frame_strs);
680 }
681 hmap_destroy(&trace_map);
682
683 ds_chomp(ds, '\n');
684 unblock_sigalrm(&oldsigs);
685 }
686 }
687 \f
688 /* Unixctl interface. */
689
690 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
691 * advancing, except due to later calls to "time/warp". */
692 static void
693 timeval_stop_cb(struct unixctl_conn *conn,
694 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
695 void *aux OVS_UNUSED)
696 {
697 time_stopped = true;
698 unixctl_command_reply(conn, NULL);
699 }
700
701 /* "time/warp MSECS" advances the current monotonic time by the specified
702 * number of milliseconds. Unless "time/stop" has also been executed, the
703 * monotonic clock continues to tick forward at the normal rate afterward.
704 *
705 * Does not affect wall clock readings. */
706 static void
707 timeval_warp_cb(struct unixctl_conn *conn,
708 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
709 {
710 struct timespec ts;
711 int msecs;
712
713 msecs = atoi(argv[1]);
714 if (msecs <= 0) {
715 unixctl_command_reply_error(conn, "invalid MSECS");
716 return;
717 }
718
719 ts.tv_sec = msecs / 1000;
720 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
721 timespec_add(&warp_offset, &warp_offset, &ts);
722 timespec_add(&monotonic_time, &monotonic_time, &ts);
723 unixctl_command_reply(conn, "warped");
724 }
725
726 static void
727 backtrace_cb(struct unixctl_conn *conn,
728 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
729 void *aux OVS_UNUSED)
730 {
731 struct ds ds = DS_EMPTY_INITIALIZER;
732
733 ovs_assert(HAVE_EXECINFO_H && CACHE_TIME);
734 format_backtraces(&ds, 0);
735 unixctl_command_reply(conn, ds_cstr(&ds));
736 ds_destroy(&ds);
737 }
738
739 void
740 timeval_dummy_register(void)
741 {
742 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
743 unixctl_command_register("time/warp", "MSECS", 1, 1,
744 timeval_warp_cb, NULL);
745 }