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