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