Prepare Open vSwitch 1.1.2 release.
[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 <string.h>
24 #include <sys/time.h>
25 #include <sys/resource.h>
26 #include <unistd.h>
27 #include "coverage.h"
28 #include "fatal-signal.h"
29 #include "signals.h"
30 #include "util.h"
31 #include "vlog.h"
32
33 VLOG_DEFINE_THIS_MODULE(timeval);
34
35 /* The clock to use for measuring time intervals.  This is CLOCK_MONOTONIC by
36  * preference, but on systems that don't have a monotonic clock we fall back
37  * to CLOCK_REALTIME. */
38 static clockid_t monotonic_clock;
39
40 /* Has a timer tick occurred?
41  *
42  * We initialize these to true to force time_init() to get called on the first
43  * call to time_msec() or another function that queries the current time. */
44 static volatile sig_atomic_t wall_tick = true;
45 static volatile sig_atomic_t monotonic_tick = true;
46
47 /* The current time, as of the last refresh. */
48 static struct timespec wall_time;
49 static struct timespec monotonic_time;
50
51 /* Time at which to die with SIGALRM (if not TIME_MIN). */
52 static time_t deadline = TIME_MIN;
53
54 static void set_up_timer(void);
55 static void set_up_signal(int flags);
56 static void sigalrm_handler(int);
57 static void refresh_wall_if_ticked(void);
58 static void refresh_monotonic_if_ticked(void);
59 static time_t time_add(time_t, time_t);
60 static void block_sigalrm(sigset_t *);
61 static void unblock_sigalrm(const sigset_t *);
62 static void log_poll_interval(long long int last_wakeup,
63                               const struct rusage *last_rusage);
64
65 /* Initializes the timetracking module.
66  *
67  * It is not necessary to call this function directly, because other time
68  * functions will call it automatically, but it doesn't hurt. */
69 static void
70 time_init(void)
71 {
72     static bool inited;
73     if (inited) {
74         return;
75     }
76     inited = true;
77
78     coverage_init();
79
80     if (!clock_gettime(CLOCK_MONOTONIC, &monotonic_time)) {
81         monotonic_clock = CLOCK_MONOTONIC;
82     } else {
83         monotonic_clock = CLOCK_REALTIME;
84         VLOG_DBG("monotonic timer not available");
85     }
86
87     set_up_signal(SA_RESTART);
88     set_up_timer();
89 }
90
91 static void
92 set_up_signal(int flags)
93 {
94     struct sigaction sa;
95
96     memset(&sa, 0, sizeof sa);
97     sa.sa_handler = sigalrm_handler;
98     sigemptyset(&sa.sa_mask);
99     sa.sa_flags = flags;
100     xsigaction(SIGALRM, &sa, NULL);
101 }
102
103 /* Remove SA_RESTART from the flags for SIGALRM, so that any system call that
104  * is interrupted by the periodic timer interrupt will return EINTR instead of
105  * continuing after the signal handler returns.
106  *
107  * time_disable_restart() and time_enable_restart() may be usefully wrapped
108  * around function calls that might otherwise block forever unless interrupted
109  * by a signal, e.g.:
110  *
111  *   time_disable_restart();
112  *   fcntl(fd, F_SETLKW, &lock);
113  *   time_enable_restart();
114  */
115 void
116 time_disable_restart(void)
117 {
118     time_init();
119     set_up_signal(0);
120 }
121
122 /* Add SA_RESTART to the flags for SIGALRM, so that any system call that
123  * is interrupted by the periodic timer interrupt will continue after the
124  * signal handler returns instead of returning EINTR. */
125 void
126 time_enable_restart(void)
127 {
128     time_init();
129     set_up_signal(SA_RESTART);
130 }
131
132 static void
133 set_up_timer(void)
134 {
135     static timer_t timer_id;    /* "static" to avoid apparent memory leak. */
136     struct itimerspec itimer;
137
138     if (timer_create(monotonic_clock, NULL, &timer_id)) {
139         VLOG_FATAL("timer_create failed (%s)", strerror(errno));
140     }
141
142     itimer.it_interval.tv_sec = 0;
143     itimer.it_interval.tv_nsec = TIME_UPDATE_INTERVAL * 1000 * 1000;
144     itimer.it_value = itimer.it_interval;
145
146     if (timer_settime(timer_id, 0, &itimer, NULL)) {
147         VLOG_FATAL("timer_settime failed (%s)", strerror(errno));
148     }
149 }
150
151 /* Set up the interval timer, to ensure that time advances even without calling
152  * time_refresh().
153  *
154  * A child created with fork() does not inherit the parent's interval timer, so
155  * this function needs to be called from the child after fork(). */
156 void
157 time_postfork(void)
158 {
159     time_init();
160     set_up_timer();
161 }
162
163 static void
164 refresh_wall(void)
165 {
166     time_init();
167     clock_gettime(CLOCK_REALTIME, &wall_time);
168     wall_tick = false;
169 }
170
171 static void
172 refresh_monotonic(void)
173 {
174     time_init();
175
176     if (monotonic_clock == CLOCK_MONOTONIC) {
177         clock_gettime(monotonic_clock, &monotonic_time);
178     } else {
179         refresh_wall_if_ticked();
180         monotonic_time = wall_time;
181     }
182
183     monotonic_tick = false;
184 }
185
186 /* Forces a refresh of the current time from the kernel.  It is not usually
187  * necessary to call this function, since the time will be refreshed
188  * automatically at least every TIME_UPDATE_INTERVAL milliseconds. */
189 void
190 time_refresh(void)
191 {
192     wall_tick = monotonic_tick = true;
193 }
194
195 /* Returns a monotonic timer, in seconds. */
196 time_t
197 time_now(void)
198 {
199     refresh_monotonic_if_ticked();
200     return monotonic_time.tv_sec;
201 }
202
203 /* Same as time_now() except does not write to static variables, for use in
204  * signal handlers.  */
205 static time_t
206 time_now_sig(void)
207 {
208     struct timespec cur_time;
209
210     clock_gettime(monotonic_clock, &cur_time);
211     return cur_time.tv_sec;
212 }
213
214 /* Returns the current time, in seconds. */
215 time_t
216 time_wall(void)
217 {
218     refresh_wall_if_ticked();
219     return wall_time.tv_sec;
220 }
221
222 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
223 long long int
224 time_msec(void)
225 {
226     refresh_monotonic_if_ticked();
227     return timespec_to_msec(&monotonic_time);
228 }
229
230 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
231 long long int
232 time_wall_msec(void)
233 {
234     refresh_wall_if_ticked();
235     return timespec_to_msec(&wall_time);
236 }
237
238 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
239  * '*ts'. */
240 void
241 time_timespec(struct timespec *ts)
242 {
243     refresh_monotonic_if_ticked();
244     *ts = monotonic_time;
245 }
246
247 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
248  * '*ts'. */
249 void
250 time_wall_timespec(struct timespec *ts)
251 {
252     refresh_wall_if_ticked();
253     *ts = wall_time;
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     sigset_t oldsigs;
262
263     time_init();
264     block_sigalrm(&oldsigs);
265     deadline = secs ? time_add(time_now(), secs) : TIME_MIN;
266     unblock_sigalrm(&oldsigs);
267 }
268
269 /* Like poll(), except:
270  *
271  *      - On error, returns a negative error code (instead of setting errno).
272  *
273  *      - If interrupted by a signal, retries automatically until the original
274  *        'timeout' expires.  (Because of this property, this function will
275  *        never return -EINTR.)
276  *
277  *      - As a side effect, refreshes the current time (like time_refresh()).
278  */
279 int
280 time_poll(struct pollfd *pollfds, int n_pollfds, int timeout)
281 {
282     static long long int last_wakeup;
283     static struct rusage last_rusage;
284     long long int start;
285     sigset_t oldsigs;
286     bool blocked;
287     int retval;
288
289     time_refresh();
290     log_poll_interval(last_wakeup, &last_rusage);
291     coverage_clear();
292     start = time_msec();
293     blocked = false;
294     for (;;) {
295         int time_left;
296         if (timeout > 0) {
297             long long int elapsed = time_msec() - start;
298             time_left = timeout >= elapsed ? timeout - elapsed : 0;
299         } else {
300             time_left = timeout;
301         }
302
303         retval = poll(pollfds, n_pollfds, time_left);
304         if (retval < 0) {
305             retval = -errno;
306         }
307         time_refresh();
308         if (retval != -EINTR) {
309             break;
310         }
311
312         if (!blocked && deadline == TIME_MIN) {
313             block_sigalrm(&oldsigs);
314             blocked = true;
315         }
316     }
317     if (blocked) {
318         unblock_sigalrm(&oldsigs);
319     }
320     last_wakeup = time_msec();
321     getrusage(RUSAGE_SELF, &last_rusage);
322     return retval;
323 }
324
325 /* Returns the sum of 'a' and 'b', with saturation on overflow or underflow. */
326 static time_t
327 time_add(time_t a, time_t b)
328 {
329     return (a >= 0
330             ? (b > TIME_MAX - a ? TIME_MAX : a + b)
331             : (b < TIME_MIN - a ? TIME_MIN : a + b));
332 }
333
334 static void
335 sigalrm_handler(int sig_nr)
336 {
337     wall_tick = true;
338     monotonic_tick = true;
339     if (deadline != TIME_MIN && time_now_sig() > deadline) {
340         fatal_signal_handler(sig_nr);
341     }
342 }
343
344 static void
345 refresh_wall_if_ticked(void)
346 {
347     if (wall_tick) {
348         refresh_wall();
349     }
350 }
351
352 static void
353 refresh_monotonic_if_ticked(void)
354 {
355     if (monotonic_tick) {
356         refresh_monotonic();
357     }
358 }
359
360 static void
361 block_sigalrm(sigset_t *oldsigs)
362 {
363     sigset_t sigalrm;
364     sigemptyset(&sigalrm);
365     sigaddset(&sigalrm, SIGALRM);
366     xsigprocmask(SIG_BLOCK, &sigalrm, oldsigs);
367 }
368
369 static void
370 unblock_sigalrm(const sigset_t *oldsigs)
371 {
372     xsigprocmask(SIG_SETMASK, oldsigs, NULL);
373 }
374
375 long long int
376 timespec_to_msec(const struct timespec *ts)
377 {
378     return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
379 }
380
381 long long int
382 timeval_to_msec(const struct timeval *tv)
383 {
384     return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
385 }
386
387 void
388 xgettimeofday(struct timeval *tv)
389 {
390     if (gettimeofday(tv, NULL) == -1) {
391         VLOG_FATAL("gettimeofday failed (%s)", strerror(errno));
392     }
393 }
394
395 static long long int
396 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
397 {
398     return timeval_to_msec(a) - timeval_to_msec(b);
399 }
400
401 static void
402 log_poll_interval(long long int last_wakeup, const struct rusage *last_rusage)
403 {
404     static unsigned int mean_interval; /* In 16ths of a millisecond. */
405     static unsigned int n_samples;
406
407     long long int now;
408     unsigned int interval;      /* In 16ths of a millisecond. */
409
410     /* Compute interval from last wakeup to now in 16ths of a millisecond,
411      * capped at 10 seconds (16000 in this unit). */
412     now = time_msec();
413     interval = MIN(10000, now - last_wakeup) << 4;
414
415     /* Warn if we took too much time between polls: at least 50 ms and at least
416      * 8X the mean interval. */
417     if (n_samples > 10 && interval > mean_interval * 8 && interval > 50 * 16) {
418         struct rusage rusage;
419
420         getrusage(RUSAGE_SELF, &rusage);
421         VLOG_WARN("%lld ms poll interval (%lld ms user, %lld ms system) "
422                   "is over %u times the weighted mean interval %u ms "
423                   "(%u samples)",
424                   now - last_wakeup,
425                   timeval_diff_msec(&rusage.ru_utime, &last_rusage->ru_utime),
426                   timeval_diff_msec(&rusage.ru_stime, &last_rusage->ru_stime),
427                   interval / mean_interval,
428                   (mean_interval + 8) / 16, n_samples);
429         if (rusage.ru_minflt > last_rusage->ru_minflt
430             || rusage.ru_majflt > last_rusage->ru_majflt) {
431             VLOG_WARN("faults: %ld minor, %ld major",
432                       rusage.ru_minflt - last_rusage->ru_minflt,
433                       rusage.ru_majflt - last_rusage->ru_majflt);
434         }
435         if (rusage.ru_inblock > last_rusage->ru_inblock
436             || rusage.ru_oublock > last_rusage->ru_oublock) {
437             VLOG_WARN("disk: %ld reads, %ld writes",
438                       rusage.ru_inblock - last_rusage->ru_inblock,
439                       rusage.ru_oublock - last_rusage->ru_oublock);
440         }
441         if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
442             || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
443             VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
444                       rusage.ru_nvcsw - last_rusage->ru_nvcsw,
445                       rusage.ru_nivcsw - last_rusage->ru_nivcsw);
446         }
447
448         /* Care should be taken in the value chosen for logging.  Depending
449          * on the configuration, syslog can write changes synchronously,
450          * which can cause the coverage messages to take longer to log
451          * than the processing delay that triggered it. */
452         coverage_log(VLL_INFO, true);
453     }
454
455     /* Update exponentially weighted moving average.  With these parameters, a
456      * given value decays to 1% of its value in about 100 time steps.  */
457     if (n_samples++) {
458         mean_interval = (mean_interval * 122 + interval * 6 + 64) / 128;
459     } else {
460         mean_interval = interval;
461     }
462 }