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