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