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