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