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