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