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