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