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