timeval: Add ability to fast-forward time, for unit testing.
[sliver-openvswitch.git] / lib / timeval.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
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?
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 /* Fixed monotonic time offset, for use by unit tests. */
55 static struct timespec warp_offset;
56
57 /* Time at which to die with SIGALRM (if not TIME_MIN). */
58 static time_t deadline = TIME_MIN;
59
60 static void set_up_timer(void);
61 static void set_up_signal(int flags);
62 static void sigalrm_handler(int);
63 static void refresh_wall_if_ticked(void);
64 static void refresh_monotonic_if_ticked(void);
65 static time_t time_add(time_t, time_t);
66 static void block_sigalrm(sigset_t *);
67 static void unblock_sigalrm(const sigset_t *);
68 static void log_poll_interval(long long int last_wakeup);
69 static struct rusage *get_recent_rusage(void);
70 static void refresh_rusage(void);
71 static void timespec_add(struct timespec *sum,
72                          const struct timespec *a, const struct timespec *b);
73
74 /* Initializes the timetracking module.
75  *
76  * It is not necessary to call this function directly, because other time
77  * functions will call it automatically, but it doesn't hurt. */
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     set_up_signal(SA_RESTART);
97     set_up_timer();
98 }
99
100 static void
101 set_up_signal(int flags)
102 {
103     struct sigaction sa;
104
105     memset(&sa, 0, sizeof sa);
106     sa.sa_handler = sigalrm_handler;
107     sigemptyset(&sa.sa_mask);
108     sa.sa_flags = flags;
109     xsigaction(SIGALRM, &sa, NULL);
110 }
111
112 /* Remove SA_RESTART from the flags for SIGALRM, so that any system call that
113  * is interrupted by the periodic timer interrupt will return EINTR instead of
114  * continuing after the signal handler returns.
115  *
116  * time_disable_restart() and time_enable_restart() may be usefully wrapped
117  * around function calls that might otherwise block forever unless interrupted
118  * by a signal, e.g.:
119  *
120  *   time_disable_restart();
121  *   fcntl(fd, F_SETLKW, &lock);
122  *   time_enable_restart();
123  */
124 void
125 time_disable_restart(void)
126 {
127     time_init();
128     set_up_signal(0);
129 }
130
131 /* Add SA_RESTART to the flags for SIGALRM, so that any system call that
132  * is interrupted by the periodic timer interrupt will continue after the
133  * signal handler returns instead of returning EINTR. */
134 void
135 time_enable_restart(void)
136 {
137     time_init();
138     set_up_signal(SA_RESTART);
139 }
140
141 static void
142 set_up_timer(void)
143 {
144     static timer_t timer_id;    /* "static" to avoid apparent memory leak. */
145     struct itimerspec itimer;
146
147     if (timer_create(monotonic_clock, NULL, &timer_id)) {
148         VLOG_FATAL("timer_create failed (%s)", strerror(errno));
149     }
150
151     itimer.it_interval.tv_sec = 0;
152     itimer.it_interval.tv_nsec = TIME_UPDATE_INTERVAL * 1000 * 1000;
153     itimer.it_value = itimer.it_interval;
154
155     if (timer_settime(timer_id, 0, &itimer, NULL)) {
156         VLOG_FATAL("timer_settime failed (%s)", strerror(errno));
157     }
158 }
159
160 /* Set up the interval timer, to ensure that time advances even without calling
161  * time_refresh().
162  *
163  * A child created with fork() does not inherit the parent's interval timer, so
164  * this function needs to be called from the child after fork(). */
165 void
166 time_postfork(void)
167 {
168     time_init();
169     set_up_timer();
170 }
171
172 static void
173 refresh_wall(void)
174 {
175     time_init();
176     clock_gettime(CLOCK_REALTIME, &wall_time);
177     wall_tick = false;
178 }
179
180 static void
181 refresh_monotonic(void)
182 {
183     time_init();
184
185     if (monotonic_clock == CLOCK_MONOTONIC) {
186         clock_gettime(monotonic_clock, &monotonic_time);
187     } else {
188         refresh_wall_if_ticked();
189         monotonic_time = wall_time;
190     }
191     timespec_add(&monotonic_time, &monotonic_time, &warp_offset);
192
193     monotonic_tick = false;
194 }
195
196 /* Forces a refresh of the current time from the kernel.  It is not usually
197  * necessary to call this function, since the time will be refreshed
198  * automatically at least every TIME_UPDATE_INTERVAL milliseconds. */
199 void
200 time_refresh(void)
201 {
202     wall_tick = monotonic_tick = true;
203 }
204
205 /* Returns a monotonic timer, in seconds. */
206 time_t
207 time_now(void)
208 {
209     refresh_monotonic_if_ticked();
210     return monotonic_time.tv_sec;
211 }
212
213 /* Same as time_now() except does not write to static variables, for use in
214  * signal handlers.  */
215 static time_t
216 time_now_sig(void)
217 {
218     struct timespec cur_time;
219
220     clock_gettime(monotonic_clock, &cur_time);
221     return cur_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     sigset_t oldsigs;
272
273     time_init();
274     block_sigalrm(&oldsigs);
275     deadline = secs ? time_add(time_now(), secs) : TIME_MIN;
276     unblock_sigalrm(&oldsigs);
277 }
278
279 /* Like poll(), except:
280  *
281  *      - The timeout is specified as an absolute time, as defined by
282  *        time_msec(), instead of a duration.
283  *
284  *      - On error, returns a negative error code (instead of setting errno).
285  *
286  *      - If interrupted by a signal, retries automatically until the original
287  *        timeout is reached.  (Because of this property, this function will
288  *        never return -EINTR.)
289  *
290  *      - As a side effect, refreshes the current time (like time_refresh()).
291  *
292  * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
293 int
294 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
295           int *elapsed)
296 {
297     static long long int last_wakeup;
298     long long int start;
299     sigset_t oldsigs;
300     bool blocked;
301     int retval;
302
303     time_refresh();
304     log_poll_interval(last_wakeup);
305     coverage_clear();
306     start = time_msec();
307     blocked = false;
308     for (;;) {
309         long long int now = time_msec();
310         int time_left;
311
312         if (now >= timeout_when) {
313             time_left = 0;
314         } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
315             time_left = INT_MAX;
316         } else {
317             time_left = timeout_when - now;
318         }
319
320         retval = poll(pollfds, n_pollfds, time_left);
321         if (retval < 0) {
322             retval = -errno;
323         }
324         time_refresh();
325         if (retval != -EINTR) {
326             break;
327         }
328
329         if (!blocked && deadline == TIME_MIN) {
330             block_sigalrm(&oldsigs);
331             blocked = true;
332         }
333     }
334     if (blocked) {
335         unblock_sigalrm(&oldsigs);
336     }
337     last_wakeup = time_msec();
338     refresh_rusage();
339     *elapsed = last_wakeup - start;
340     return retval;
341 }
342
343 /* Returns the sum of 'a' and 'b', with saturation on overflow or underflow. */
344 static time_t
345 time_add(time_t a, time_t b)
346 {
347     return (a >= 0
348             ? (b > TIME_MAX - a ? TIME_MAX : a + b)
349             : (b < TIME_MIN - a ? TIME_MIN : a + b));
350 }
351
352 static void
353 sigalrm_handler(int sig_nr)
354 {
355     wall_tick = true;
356     monotonic_tick = true;
357     if (deadline != TIME_MIN && time_now_sig() > deadline) {
358         fatal_signal_handler(sig_nr);
359     }
360 }
361
362 static void
363 refresh_wall_if_ticked(void)
364 {
365     if (wall_tick) {
366         refresh_wall();
367     }
368 }
369
370 static void
371 refresh_monotonic_if_ticked(void)
372 {
373     if (monotonic_tick) {
374         refresh_monotonic();
375     }
376 }
377
378 static void
379 block_sigalrm(sigset_t *oldsigs)
380 {
381     sigset_t sigalrm;
382     sigemptyset(&sigalrm);
383     sigaddset(&sigalrm, SIGALRM);
384     xsigprocmask(SIG_BLOCK, &sigalrm, oldsigs);
385 }
386
387 static void
388 unblock_sigalrm(const sigset_t *oldsigs)
389 {
390     xsigprocmask(SIG_SETMASK, oldsigs, NULL);
391 }
392
393 long long int
394 timespec_to_msec(const struct timespec *ts)
395 {
396     return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
397 }
398
399 long long int
400 timeval_to_msec(const struct timeval *tv)
401 {
402     return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
403 }
404
405 void
406 xgettimeofday(struct timeval *tv)
407 {
408     if (gettimeofday(tv, NULL) == -1) {
409         VLOG_FATAL("gettimeofday failed (%s)", strerror(errno));
410     }
411 }
412
413 static long long int
414 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
415 {
416     return timeval_to_msec(a) - timeval_to_msec(b);
417 }
418
419 static void
420 timespec_add(struct timespec *sum,
421              const struct timespec *a,
422              const struct timespec *b)
423 {
424     struct timespec tmp;
425
426     tmp.tv_sec = a->tv_sec + b->tv_sec;
427     tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
428     if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
429         tmp.tv_nsec -= 1000 * 1000 * 1000;
430         tmp.tv_sec++;
431     }
432
433     *sum = tmp;
434 }
435
436 static void
437 log_poll_interval(long long int last_wakeup)
438 {
439     static unsigned int mean_interval; /* In 16ths of a millisecond. */
440     static unsigned int n_samples;
441
442     long long int now;
443     unsigned int interval;      /* In 16ths of a millisecond. */
444
445     /* Compute interval from last wakeup to now in 16ths of a millisecond,
446      * capped at 10 seconds (16000 in this unit). */
447     now = time_msec();
448     interval = MIN(10000, now - last_wakeup) << 4;
449
450     /* Warn if we took too much time between polls: at least 50 ms and at least
451      * 8X the mean interval. */
452     if (n_samples > 10 && interval > mean_interval * 8 && interval > 50 * 16) {
453         const struct rusage *last_rusage = get_recent_rusage();
454         struct rusage rusage;
455
456         getrusage(RUSAGE_SELF, &rusage);
457         VLOG_WARN("%lld ms poll interval (%lld ms user, %lld ms system) "
458                   "is over %u times the weighted mean interval %u ms "
459                   "(%u samples)",
460                   now - last_wakeup,
461                   timeval_diff_msec(&rusage.ru_utime, &last_rusage->ru_utime),
462                   timeval_diff_msec(&rusage.ru_stime, &last_rusage->ru_stime),
463                   interval / mean_interval,
464                   (mean_interval + 8) / 16, n_samples);
465         if (rusage.ru_minflt > last_rusage->ru_minflt
466             || rusage.ru_majflt > last_rusage->ru_majflt) {
467             VLOG_WARN("faults: %ld minor, %ld major",
468                       rusage.ru_minflt - last_rusage->ru_minflt,
469                       rusage.ru_majflt - last_rusage->ru_majflt);
470         }
471         if (rusage.ru_inblock > last_rusage->ru_inblock
472             || rusage.ru_oublock > last_rusage->ru_oublock) {
473             VLOG_WARN("disk: %ld reads, %ld writes",
474                       rusage.ru_inblock - last_rusage->ru_inblock,
475                       rusage.ru_oublock - last_rusage->ru_oublock);
476         }
477         if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
478             || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
479             VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
480                       rusage.ru_nvcsw - last_rusage->ru_nvcsw,
481                       rusage.ru_nivcsw - last_rusage->ru_nivcsw);
482         }
483
484         /* Care should be taken in the value chosen for logging.  Depending
485          * on the configuration, syslog can write changes synchronously,
486          * which can cause the coverage messages to take longer to log
487          * than the processing delay that triggered it. */
488         coverage_log(VLL_INFO, true);
489     }
490
491     /* Update exponentially weighted moving average.  With these parameters, a
492      * given value decays to 1% of its value in about 100 time steps.  */
493     if (n_samples++) {
494         mean_interval = (mean_interval * 122 + interval * 6 + 64) / 128;
495     } else {
496         mean_interval = interval;
497     }
498 }
499 \f
500 /* CPU usage tracking. */
501
502 struct cpu_usage {
503     long long int when;         /* Time that this sample was taken. */
504     unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
505 };
506
507 static struct rusage recent_rusage;
508 static struct cpu_usage older = { LLONG_MIN, 0 };
509 static struct cpu_usage newer = { LLONG_MIN, 0 };
510 static int cpu_usage = -1;
511
512 static struct rusage *
513 get_recent_rusage(void)
514 {
515     return &recent_rusage;
516 }
517
518 static void
519 refresh_rusage(void)
520 {
521     long long int now;
522
523     now = time_msec();
524     getrusage(RUSAGE_SELF, &recent_rusage);
525
526     if (now >= newer.when + 3 * 1000) {
527         older = newer;
528         newer.when = now;
529         newer.cpu = (timeval_to_msec(&recent_rusage.ru_utime) +
530                      timeval_to_msec(&recent_rusage.ru_stime));
531
532         if (older.when != LLONG_MIN && newer.cpu > older.cpu) {
533             unsigned int dividend = newer.cpu - older.cpu;
534             unsigned int divisor = (newer.when - older.when) / 100;
535             cpu_usage = divisor > 0 ? dividend / divisor : -1;
536         } else {
537             cpu_usage = -1;
538         }
539     }
540 }
541
542 /* Returns an estimate of this process's CPU usage, as a percentage, over the
543  * past few seconds of wall-clock time.  Returns -1 if no estimate is available
544  * (which will happen if the process has not been running long enough to have
545  * an estimate, and can happen for other reasons as well). */
546 int
547 get_cpu_usage(void)
548 {
549     return cpu_usage;
550 }
551 \f
552 /* Unixctl interface. */
553
554 static void
555 timeval_warp_cb(struct unixctl_conn *conn,
556                 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
557 {
558     struct timespec ts;
559     int msecs;
560
561     msecs = atoi(argv[1]);
562     if (msecs <= 0) {
563         unixctl_command_reply(conn, 501, "invalid MSECS");
564         return;
565     }
566
567     ts.tv_sec = msecs / 1000;
568     ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
569     timespec_add(&warp_offset, &warp_offset, &ts);
570     unixctl_command_reply(conn, 200, "warped");
571 }
572
573 void
574 timeval_dummy_register(void)
575 {
576     unixctl_command_register("time/warp", "MSECS", 1, 1,
577                              timeval_warp_cb, NULL);
578 }