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