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