lib/timeval: don't forget to initialize a rwlock
[sliver-openvswitch.git] / lib / timeval.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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 <errno.h>
20 #include <poll.h>
21 #include <pthread.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/time.h>
26 #include <sys/resource.h>
27 #include <unistd.h>
28 #include "coverage.h"
29 #include "dummy.h"
30 #include "dynamic-string.h"
31 #include "fatal-signal.h"
32 #include "hash.h"
33 #include "hmap.h"
34 #include "ovs-thread.h"
35 #include "signals.h"
36 #include "unixctl.h"
37 #include "util.h"
38 #include "vlog.h"
39
40 VLOG_DEFINE_THIS_MODULE(timeval);
41
42 struct clock {
43     clockid_t id;               /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
44
45     /* Features for use by unit tests.  Protected by 'rwlock'. */
46     struct ovs_rwlock rwlock;
47     struct timespec warp;       /* Offset added for unit tests. */
48     bool stopped;               /* Disables real-time updates if true.  */
49
50     struct timespec cache;      /* Last time read from kernel. */
51 };
52
53 /* Our clocks. */
54 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
55 static struct clock wall_clock;      /* CLOCK_REALTIME. */
56
57 /* The monotonic time at which the time module was initialized. */
58 static long long int boot_time;
59
60 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
61  * LLONG_MAX). */
62 static long long int deadline = LLONG_MAX;
63
64 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
65  * up. */
66 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup, 0);
67
68 static void log_poll_interval(long long int last_wakeup);
69 static struct rusage *get_recent_rusage(void);
70 static void refresh_rusage(void);
71 static void timespec_add(struct timespec *sum,
72                          const struct timespec *a, const struct timespec *b);
73
74 static void
75 init_clock(struct clock *c, clockid_t id)
76 {
77     memset(c, 0, sizeof *c);
78     c->id = id;
79     ovs_rwlock_init(&c->rwlock);
80     xclock_gettime(c->id, &c->cache);
81 }
82
83 static void
84 do_init_time(void)
85 {
86     struct timespec ts;
87
88     coverage_init();
89
90     init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
91                                   ? CLOCK_MONOTONIC
92                                   : CLOCK_REALTIME));
93     init_clock(&wall_clock, CLOCK_REALTIME);
94     boot_time = timespec_to_msec(&monotonic_clock.cache);
95 }
96
97 /* Initializes the timetracking module, if not already initialized. */
98 static void
99 time_init(void)
100 {
101     static pthread_once_t once = PTHREAD_ONCE_INIT;
102     pthread_once(&once, do_init_time);
103 }
104
105 static void
106 time_timespec__(struct clock *c, struct timespec *ts)
107 {
108     time_init();
109
110     if (!c->stopped) {
111         xclock_gettime(c->id, ts);
112     } else {
113         ovs_rwlock_rdlock(&c->rwlock);
114         timespec_add(ts, &c->cache, &c->warp);
115         ovs_rwlock_unlock(&c->rwlock);
116     }
117 }
118
119 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
120  * '*ts'. */
121 void
122 time_timespec(struct timespec *ts)
123 {
124     time_timespec__(&monotonic_clock, ts);
125 }
126
127 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
128  * '*ts'. */
129 void
130 time_wall_timespec(struct timespec *ts)
131 {
132     time_timespec__(&wall_clock, ts);
133 }
134
135 static time_t
136 time_sec__(struct clock *c)
137 {
138     struct timespec ts;
139
140     time_timespec__(c, &ts);
141     return ts.tv_sec;
142 }
143
144 /* Returns a monotonic timer, in seconds. */
145 time_t
146 time_now(void)
147 {
148     return time_sec__(&monotonic_clock);
149 }
150
151 /* Returns the current time, in seconds. */
152 time_t
153 time_wall(void)
154 {
155     return time_sec__(&wall_clock);
156 }
157
158 static long long int
159 time_msec__(struct clock *c)
160 {
161     struct timespec ts;
162
163     time_timespec__(c, &ts);
164     return timespec_to_msec(&ts);
165 }
166
167 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
168 long long int
169 time_msec(void)
170 {
171     return time_msec__(&monotonic_clock);
172 }
173
174 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
175 long long int
176 time_wall_msec(void)
177 {
178     return time_msec__(&wall_clock);
179 }
180
181 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
182  * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
183 void
184 time_alarm(unsigned int secs)
185 {
186     long long int now;
187     long long int msecs;
188
189     assert_single_threaded();
190     time_init();
191
192     now = time_msec();
193     msecs = secs * 1000LL;
194     deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
195 }
196
197 /* Like poll(), except:
198  *
199  *      - The timeout is specified as an absolute time, as defined by
200  *        time_msec(), instead of a duration.
201  *
202  *      - On error, returns a negative error code (instead of setting errno).
203  *
204  *      - If interrupted by a signal, retries automatically until the original
205  *        timeout is reached.  (Because of this property, this function will
206  *        never return -EINTR.)
207  *
208  * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
209 int
210 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
211           int *elapsed)
212 {
213     long long int *last_wakeup = last_wakeup_get();
214     long long int start;
215     int retval;
216
217     time_init();
218     if (*last_wakeup) {
219         log_poll_interval(*last_wakeup);
220     }
221     coverage_clear();
222     start = time_msec();
223
224     timeout_when = MIN(timeout_when, deadline);
225
226     for (;;) {
227         long long int now = time_msec();
228         int time_left;
229
230         if (now >= timeout_when) {
231             time_left = 0;
232         } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
233             time_left = INT_MAX;
234         } else {
235             time_left = timeout_when - now;
236         }
237
238         retval = poll(pollfds, n_pollfds, time_left);
239         if (retval < 0) {
240             retval = -errno;
241         }
242
243         if (deadline <= time_msec()) {
244             fatal_signal_handler(SIGALRM);
245             if (retval < 0) {
246                 retval = 0;
247             }
248             break;
249         }
250
251         if (retval != -EINTR) {
252             break;
253         }
254     }
255     *last_wakeup = time_msec();
256     refresh_rusage();
257     *elapsed = *last_wakeup - start;
258     return retval;
259 }
260
261 long long int
262 timespec_to_msec(const struct timespec *ts)
263 {
264     return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
265 }
266
267 long long int
268 timeval_to_msec(const struct timeval *tv)
269 {
270     return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
271 }
272
273 /* Returns the monotonic time at which the "time" module was initialized, in
274  * milliseconds. */
275 long long int
276 time_boot_msec(void)
277 {
278     time_init();
279     return boot_time;
280 }
281
282 void
283 xgettimeofday(struct timeval *tv)
284 {
285     if (gettimeofday(tv, NULL) == -1) {
286         VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
287     }
288 }
289
290 void
291 xclock_gettime(clock_t id, struct timespec *ts)
292 {
293     if (clock_gettime(id, ts) == -1) {
294         /* It seems like a bad idea to try to use vlog here because it is
295          * likely to try to check the current time. */
296         ovs_abort(errno, "xclock_gettime() failed");
297     }
298 }
299
300 static long long int
301 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
302 {
303     return timeval_to_msec(a) - timeval_to_msec(b);
304 }
305
306 static void
307 timespec_add(struct timespec *sum,
308              const struct timespec *a,
309              const struct timespec *b)
310 {
311     struct timespec tmp;
312
313     tmp.tv_sec = a->tv_sec + b->tv_sec;
314     tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
315     if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
316         tmp.tv_nsec -= 1000 * 1000 * 1000;
317         tmp.tv_sec++;
318     }
319
320     *sum = tmp;
321 }
322
323 static void
324 log_poll_interval(long long int last_wakeup)
325 {
326     long long int interval = time_msec() - last_wakeup;
327
328     if (interval >= 1000
329         && !monotonic_clock.warp.tv_sec
330         && !monotonic_clock.warp.tv_nsec) {
331         const struct rusage *last_rusage = get_recent_rusage();
332         struct rusage rusage;
333
334         getrusage(RUSAGE_SELF, &rusage);
335         VLOG_WARN("Unreasonably long %lldms poll interval"
336                   " (%lldms user, %lldms system)",
337                   interval,
338                   timeval_diff_msec(&rusage.ru_utime,
339                                     &last_rusage->ru_utime),
340                   timeval_diff_msec(&rusage.ru_stime,
341                                     &last_rusage->ru_stime));
342         if (rusage.ru_minflt > last_rusage->ru_minflt
343             || rusage.ru_majflt > last_rusage->ru_majflt) {
344             VLOG_WARN("faults: %ld minor, %ld major",
345                       rusage.ru_minflt - last_rusage->ru_minflt,
346                       rusage.ru_majflt - last_rusage->ru_majflt);
347         }
348         if (rusage.ru_inblock > last_rusage->ru_inblock
349             || rusage.ru_oublock > last_rusage->ru_oublock) {
350             VLOG_WARN("disk: %ld reads, %ld writes",
351                       rusage.ru_inblock - last_rusage->ru_inblock,
352                       rusage.ru_oublock - last_rusage->ru_oublock);
353         }
354         if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
355             || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
356             VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
357                       rusage.ru_nvcsw - last_rusage->ru_nvcsw,
358                       rusage.ru_nivcsw - last_rusage->ru_nivcsw);
359         }
360         coverage_log();
361     }
362 }
363 \f
364 /* CPU usage tracking. */
365
366 struct cpu_usage {
367     long long int when;         /* Time that this sample was taken. */
368     unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
369 };
370
371 struct cpu_tracker {
372     struct cpu_usage older;
373     struct cpu_usage newer;
374     int cpu_usage;
375
376     struct rusage recent_rusage;
377 };
378 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
379
380 static struct cpu_tracker *
381 get_cpu_tracker(void)
382 {
383     struct cpu_tracker *t = cpu_tracker_var_get();
384     if (!t) {
385         t = xzalloc(sizeof *t);
386         t->older.when = LLONG_MIN;
387         t->newer.when = LLONG_MIN;
388         cpu_tracker_var_set_unsafe(t);
389     }
390     return t;
391 }
392
393 static struct rusage *
394 get_recent_rusage(void)
395 {
396     return &get_cpu_tracker()->recent_rusage;
397 }
398
399 static int
400 getrusage_thread(struct rusage *rusage OVS_UNUSED)
401 {
402 #ifdef RUSAGE_THREAD
403     return getrusage(RUSAGE_THREAD, rusage);
404 #else
405     errno = EINVAL;
406     return -1;
407 #endif
408 }
409
410 static void
411 refresh_rusage(void)
412 {
413     struct cpu_tracker *t = get_cpu_tracker();
414     struct rusage *recent_rusage = &t->recent_rusage;
415
416     if (!getrusage_thread(recent_rusage)) {
417         long long int now = time_msec();
418         if (now >= t->newer.when + 3 * 1000) {
419             t->older = t->newer;
420             t->newer.when = now;
421             t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
422                             timeval_to_msec(&recent_rusage->ru_stime));
423
424             if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
425                 unsigned int dividend = t->newer.cpu - t->older.cpu;
426                 unsigned int divisor = (t->newer.when - t->older.when) / 100;
427                 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
428             } else {
429                 t->cpu_usage = -1;
430             }
431         }
432     }
433 }
434
435 /* Returns an estimate of this process's CPU usage, as a percentage, over the
436  * past few seconds of wall-clock time.  Returns -1 if no estimate is available
437  * (which will happen if the process has not been running long enough to have
438  * an estimate, and can happen for other reasons as well). */
439 int
440 get_cpu_usage(void)
441 {
442     return get_cpu_tracker()->cpu_usage;
443 }
444 \f
445 /* Unixctl interface. */
446
447 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
448  * advancing, except due to later calls to "time/warp". */
449 static void
450 timeval_stop_cb(struct unixctl_conn *conn,
451                  int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
452                  void *aux OVS_UNUSED)
453 {
454     ovs_rwlock_wrlock(&monotonic_clock.rwlock);
455     monotonic_clock.stopped = true;
456     xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
457     ovs_rwlock_unlock(&monotonic_clock.rwlock);
458
459     unixctl_command_reply(conn, NULL);
460 }
461
462 /* "time/warp MSECS" advances the current monotonic time by the specified
463  * number of milliseconds.  Unless "time/stop" has also been executed, the
464  * monotonic clock continues to tick forward at the normal rate afterward.
465  *
466  * Does not affect wall clock readings. */
467 static void
468 timeval_warp_cb(struct unixctl_conn *conn,
469                 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
470 {
471     struct timespec ts;
472     int msecs;
473
474     msecs = atoi(argv[1]);
475     if (msecs <= 0) {
476         unixctl_command_reply_error(conn, "invalid MSECS");
477         return;
478     }
479
480     ts.tv_sec = msecs / 1000;
481     ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
482
483     ovs_rwlock_wrlock(&monotonic_clock.rwlock);
484     timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
485     ovs_rwlock_unlock(&monotonic_clock.rwlock);
486
487     unixctl_command_reply(conn, "warped");
488 }
489
490 void
491 timeval_dummy_register(void)
492 {
493     unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
494     unixctl_command_register("time/warp", "MSECS", 1, 1,
495                              timeval_warp_cb, NULL);
496 }