Add test to ensure that time advances both normally and in a daemon.
[sliver-openvswitch.git] / lib / timeval.c
1 /*
2  * Copyright (c) 2008, 2009 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 /* Has a timer tick occurred? */
38 static volatile sig_atomic_t tick;
39
40 /* The current time, as of the last refresh. */
41 static struct timeval now;
42
43 /* Time at which to die with SIGALRM (if not TIME_MIN). */
44 static time_t deadline = TIME_MIN;
45
46 static void setup_timer(void);
47 static void sigalrm_handler(int);
48 static void refresh_if_ticked(void);
49 static time_t time_add(time_t, time_t);
50 static void block_sigalrm(sigset_t *);
51 static void unblock_sigalrm(const sigset_t *);
52 static void log_poll_interval(long long int last_wakeup,
53                               const struct rusage *last_rusage);
54
55 /* Initializes the timetracking module. */
56 void
57 time_init(void)
58 {
59     struct sigaction sa;
60     if (inited) {
61         return;
62     }
63
64     coverage_init();
65
66     inited = true;
67     gettimeofday(&now, NULL);
68     tick = false;
69
70     /* Set up signal handler. */
71     memset(&sa, 0, sizeof sa);
72     sa.sa_handler = sigalrm_handler;
73     sigemptyset(&sa.sa_mask);
74     sa.sa_flags = SA_RESTART;
75     if (sigaction(SIGALRM, &sa, NULL)) {
76         ovs_fatal(errno, "sigaction(SIGALRM) failed");
77     }
78
79     /* Set up periodic signal. */
80     setup_timer();
81 }
82
83 static void
84 setup_timer(void)
85 {
86     struct itimerval itimer;
87
88     itimer.it_interval.tv_sec = 0;
89     itimer.it_interval.tv_usec = TIME_UPDATE_INTERVAL * 1000;
90     itimer.it_value = itimer.it_interval;
91     if (setitimer(ITIMER_REAL, &itimer, NULL)) {
92         ovs_fatal(errno, "setitimer failed");
93     }
94 }
95
96 /* Set up the interval timer, to ensure that time advances even without calling
97  * time_refresh().
98  *
99  * A child created with fork() does not inherit the parent's interval timer, so
100  * this function needs to be called from the child after fork(). */
101 void
102 time_postfork(void)
103 {
104     setup_timer();
105 }
106
107 /* Forces a refresh of the current time from the kernel.  It is not usually
108  * necessary to call this function, since the time will be refreshed
109  * automatically at least every TIME_UPDATE_INTERVAL milliseconds. */
110 void
111 time_refresh(void)
112 {
113     gettimeofday(&now, NULL);
114     tick = false;
115 }
116
117 /* Returns the current time, in seconds. */
118 time_t
119 time_now(void)
120 {
121     refresh_if_ticked();
122     return now.tv_sec;
123 }
124
125 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
126 long long int
127 time_msec(void)
128 {
129     refresh_if_ticked();
130     return timeval_to_msec(&now);
131 }
132
133 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
134  * '*tv'. */
135 void
136 time_timeval(struct timeval *tv)
137 {
138     refresh_if_ticked();
139     *tv = now;
140 }
141
142 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
143  * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
144 void
145 time_alarm(unsigned int secs)
146 {
147     sigset_t oldsigs;
148
149     time_init();
150     block_sigalrm(&oldsigs);
151     deadline = secs ? time_add(time_now(), secs) : TIME_MIN;
152     unblock_sigalrm(&oldsigs);
153 }
154
155 /* Like poll(), except:
156  *
157  *      - On error, returns a negative error code (instead of setting errno).
158  *
159  *      - If interrupted by a signal, retries automatically until the original
160  *        'timeout' expires.  (Because of this property, this function will
161  *        never return -EINTR.)
162  *
163  *      - As a side effect, refreshes the current time (like time_refresh()).
164  */
165 int
166 time_poll(struct pollfd *pollfds, int n_pollfds, int timeout)
167 {
168     static long long int last_wakeup;
169     static struct rusage last_rusage;
170     long long int start;
171     sigset_t oldsigs;
172     bool blocked;
173     int retval;
174
175     time_refresh();
176     log_poll_interval(last_wakeup, &last_rusage);
177     coverage_clear();
178     start = time_msec();
179     blocked = false;
180     for (;;) {
181         int time_left;
182         if (timeout > 0) {
183             long long int elapsed = time_msec() - start;
184             time_left = timeout >= elapsed ? timeout - elapsed : 0;
185         } else {
186             time_left = timeout;
187         }
188
189         retval = poll(pollfds, n_pollfds, time_left);
190         if (retval < 0) {
191             retval = -errno;
192         }
193         time_refresh();
194         if (retval != -EINTR) {
195             break;
196         }
197
198         if (!blocked && deadline == TIME_MIN) {
199             block_sigalrm(&oldsigs);
200             blocked = true;
201         }
202     }
203     if (blocked) {
204         unblock_sigalrm(&oldsigs);
205     }
206     last_wakeup = time_msec();
207     getrusage(RUSAGE_SELF, &last_rusage);
208     return retval;
209 }
210
211 /* Returns the sum of 'a' and 'b', with saturation on overflow or underflow. */
212 static time_t
213 time_add(time_t a, time_t b)
214 {
215     return (a >= 0
216             ? (b > TIME_MAX - a ? TIME_MAX : a + b)
217             : (b < TIME_MIN - a ? TIME_MIN : a + b));
218 }
219
220 static void
221 sigalrm_handler(int sig_nr)
222 {
223     tick = true;
224     if (deadline != TIME_MIN && time(0) > deadline) {
225         fatal_signal_handler(sig_nr);
226     }
227 }
228
229 static void
230 refresh_if_ticked(void)
231 {
232     assert(inited);
233     if (tick) {
234         time_refresh();
235     }
236 }
237
238 static void
239 block_sigalrm(sigset_t *oldsigs)
240 {
241     sigset_t sigalrm;
242     sigemptyset(&sigalrm);
243     sigaddset(&sigalrm, SIGALRM);
244     if (sigprocmask(SIG_BLOCK, &sigalrm, oldsigs)) {
245         ovs_fatal(errno, "sigprocmask");
246     }
247 }
248
249 static void
250 unblock_sigalrm(const sigset_t *oldsigs)
251 {
252     if (sigprocmask(SIG_SETMASK, oldsigs, NULL)) {
253         ovs_fatal(errno, "sigprocmask");
254     }
255 }
256
257 long long int
258 timeval_to_msec(const struct timeval *tv)
259 {
260     return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
261 }
262
263 static long long int
264 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
265 {
266     return timeval_to_msec(a) - timeval_to_msec(b);
267 }
268
269 static void
270 log_poll_interval(long long int last_wakeup, const struct rusage *last_rusage)
271 {
272     static unsigned int mean_interval; /* In 16ths of a millisecond. */
273     static unsigned int n_samples;
274
275     long long int now;
276     unsigned int interval;      /* In 16ths of a millisecond. */
277
278     /* Compute interval from last wakeup to now in 16ths of a millisecond,
279      * capped at 10 seconds (16000 in this unit). */
280     now = time_msec();
281     interval = MIN(10000, now - last_wakeup) << 4;
282
283     /* Warn if we took too much time between polls. */
284     if (n_samples > 10 && interval > mean_interval * 8) {
285         struct rusage rusage;
286
287         getrusage(RUSAGE_SELF, &rusage);
288         VLOG_WARN("%u ms poll interval (%lld ms user, %lld ms system) "
289                   "is over %u times the weighted mean interval %u ms "
290                   "(%u samples)",
291                   (interval + 8) / 16,
292                   timeval_diff_msec(&rusage.ru_utime, &last_rusage->ru_utime),
293                   timeval_diff_msec(&rusage.ru_stime, &last_rusage->ru_stime),
294                   interval / mean_interval,
295                   (mean_interval + 8) / 16, n_samples);
296         if (rusage.ru_minflt > last_rusage->ru_minflt
297             || rusage.ru_majflt > last_rusage->ru_majflt) {
298             VLOG_WARN("faults: %ld minor, %ld major",
299                       rusage.ru_minflt - last_rusage->ru_minflt,
300                       rusage.ru_majflt - last_rusage->ru_majflt);
301         }
302         if (rusage.ru_inblock > last_rusage->ru_inblock
303             || rusage.ru_oublock > last_rusage->ru_oublock) {
304             VLOG_WARN("disk: %ld reads, %ld writes",
305                       rusage.ru_inblock - last_rusage->ru_inblock,
306                       rusage.ru_oublock - last_rusage->ru_oublock);
307         }
308         if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
309             || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
310             VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
311                       rusage.ru_nvcsw - last_rusage->ru_nvcsw,
312                       rusage.ru_nivcsw - last_rusage->ru_nivcsw);
313         }
314
315         /* Care should be taken in the value chosen for logging.  Depending 
316          * on the configuration, syslog can write changes synchronously, 
317          * which can cause the coverage messages to take longer to log 
318          * than the processing delay that triggered it. */
319         coverage_log(VLL_INFO, true);
320     }
321
322     /* Update exponentially weighted moving average.  With these parameters, a
323      * given value decays to 1% of its value in about 100 time steps.  */
324     if (n_samples++) {
325         mean_interval = (mean_interval * 122 + interval * 6 + 64) / 128;
326     } else {
327         mean_interval = interval;
328     }
329 }