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