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