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