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