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