Merge branch 'mainstream'
[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 'mutex'. */
46     struct ovs_mutex mutex;
47     atomic_bool slow_path;             /* True if warped or stopped. */
48     struct timespec warp OVS_GUARDED;  /* Offset added for unit tests. */
49     bool stopped OVS_GUARDED;          /* Disable real-time updates if true. */
50     struct timespec cache OVS_GUARDED; /* 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_mutex_init(&c->mutex);
80     atomic_init(&c->slow_path, false);
81     xclock_gettime(c->id, &c->cache);
82 }
83
84 static void
85 do_init_time(void)
86 {
87     struct timespec ts;
88
89     coverage_init();
90
91     init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
92                                   ? CLOCK_MONOTONIC
93                                   : CLOCK_REALTIME));
94     init_clock(&wall_clock, CLOCK_REALTIME);
95     boot_time = timespec_to_msec(&monotonic_clock.cache);
96 }
97
98 /* Initializes the timetracking module, if not already initialized. */
99 static void
100 time_init(void)
101 {
102     static pthread_once_t once = PTHREAD_ONCE_INIT;
103     pthread_once(&once, do_init_time);
104 }
105
106 static void
107 time_timespec__(struct clock *c, struct timespec *ts)
108 {
109     bool slow_path;
110
111     time_init();
112
113     atomic_read_explicit(&c->slow_path, &slow_path, memory_order_relaxed);
114     if (!slow_path) {
115         xclock_gettime(c->id, ts);
116     } else {
117         struct timespec warp;
118         struct timespec cache;
119         bool stopped;
120
121         ovs_mutex_lock(&c->mutex);
122         stopped = c->stopped;
123         warp = c->warp;
124         cache = c->cache;
125         ovs_mutex_unlock(&c->mutex);
126
127         if (!stopped) {
128             xclock_gettime(c->id, &cache);
129         }
130         timespec_add(ts, &cache, &warp);
131     }
132 }
133
134 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
135  * '*ts'. */
136 void
137 time_timespec(struct timespec *ts)
138 {
139     time_timespec__(&monotonic_clock, ts);
140 }
141
142 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
143  * '*ts'. */
144 void
145 time_wall_timespec(struct timespec *ts)
146 {
147     time_timespec__(&wall_clock, ts);
148 }
149
150 static time_t
151 time_sec__(struct clock *c)
152 {
153     struct timespec ts;
154
155     time_timespec__(c, &ts);
156     return ts.tv_sec;
157 }
158
159 /* Returns a monotonic timer, in seconds. */
160 time_t
161 time_now(void)
162 {
163     return time_sec__(&monotonic_clock);
164 }
165
166 /* Returns the current time, in seconds. */
167 time_t
168 time_wall(void)
169 {
170     return time_sec__(&wall_clock);
171 }
172
173 static long long int
174 time_msec__(struct clock *c)
175 {
176     struct timespec ts;
177
178     time_timespec__(c, &ts);
179     return timespec_to_msec(&ts);
180 }
181
182 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
183 long long int
184 time_msec(void)
185 {
186     return time_msec__(&monotonic_clock);
187 }
188
189 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
190 long long int
191 time_wall_msec(void)
192 {
193     return time_msec__(&wall_clock);
194 }
195
196 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
197  * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
198 void
199 time_alarm(unsigned int secs)
200 {
201     long long int now;
202     long long int msecs;
203
204     assert_single_threaded();
205     time_init();
206
207     now = time_msec();
208     msecs = secs * 1000LL;
209     deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
210 }
211
212 /* Like poll(), except:
213  *
214  *      - The timeout is specified as an absolute time, as defined by
215  *        time_msec(), instead of a duration.
216  *
217  *      - On error, returns a negative error code (instead of setting errno).
218  *
219  *      - If interrupted by a signal, retries automatically until the original
220  *        timeout is reached.  (Because of this property, this function will
221  *        never return -EINTR.)
222  *
223  * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
224 int
225 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
226           int *elapsed)
227 {
228     long long int *last_wakeup = last_wakeup_get();
229     long long int start;
230     int retval;
231
232     time_init();
233     if (*last_wakeup) {
234         log_poll_interval(*last_wakeup);
235     }
236     coverage_clear();
237     coverage_run();
238     start = time_msec();
239
240     timeout_when = MIN(timeout_when, deadline);
241
242     for (;;) {
243         long long int now = time_msec();
244         int time_left;
245
246         if (now >= timeout_when) {
247             time_left = 0;
248         } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
249             time_left = INT_MAX;
250         } else {
251             time_left = timeout_when - now;
252         }
253
254         retval = poll(pollfds, n_pollfds, time_left);
255         if (retval < 0) {
256             retval = -errno;
257         }
258
259         if (deadline <= time_msec()) {
260             fatal_signal_handler(SIGALRM);
261             if (retval < 0) {
262                 retval = 0;
263             }
264             break;
265         }
266
267         if (retval != -EINTR) {
268             break;
269         }
270     }
271     *last_wakeup = time_msec();
272     refresh_rusage();
273     *elapsed = *last_wakeup - start;
274     return retval;
275 }
276
277 long long int
278 timespec_to_msec(const struct timespec *ts)
279 {
280     return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
281 }
282
283 long long int
284 timeval_to_msec(const struct timeval *tv)
285 {
286     return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
287 }
288
289 /* Returns the monotonic time at which the "time" module was initialized, in
290  * milliseconds. */
291 long long int
292 time_boot_msec(void)
293 {
294     time_init();
295     return boot_time;
296 }
297
298 void
299 xgettimeofday(struct timeval *tv)
300 {
301     if (gettimeofday(tv, NULL) == -1) {
302         VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
303     }
304 }
305
306 void
307 xclock_gettime(clock_t id, struct timespec *ts)
308 {
309     if (clock_gettime(id, ts) == -1) {
310         /* It seems like a bad idea to try to use vlog here because it is
311          * likely to try to check the current time. */
312         ovs_abort(errno, "xclock_gettime() failed");
313     }
314 }
315
316 static long long int
317 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
318 {
319     return timeval_to_msec(a) - timeval_to_msec(b);
320 }
321
322 static void
323 timespec_add(struct timespec *sum,
324              const struct timespec *a,
325              const struct timespec *b)
326 {
327     struct timespec tmp;
328
329     tmp.tv_sec = a->tv_sec + b->tv_sec;
330     tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
331     if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
332         tmp.tv_nsec -= 1000 * 1000 * 1000;
333         tmp.tv_sec++;
334     }
335
336     *sum = tmp;
337 }
338
339 static bool
340 is_warped(const struct clock *c)
341 {
342     bool warped;
343
344     ovs_mutex_lock(&c->mutex);
345     warped = monotonic_clock.warp.tv_sec || monotonic_clock.warp.tv_nsec;
346     ovs_mutex_unlock(&c->mutex);
347
348     return warped;
349 }
350
351 static void
352 log_poll_interval(long long int last_wakeup)
353 {
354     long long int interval = time_msec() - last_wakeup;
355
356     if (interval >= 1000 && !is_warped(&monotonic_clock)) {
357         const struct rusage *last_rusage = get_recent_rusage();
358         struct rusage rusage;
359
360         getrusage(RUSAGE_SELF, &rusage);
361         VLOG_WARN("Unreasonably long %lldms poll interval"
362                   " (%lldms user, %lldms system)",
363                   interval,
364                   timeval_diff_msec(&rusage.ru_utime,
365                                     &last_rusage->ru_utime),
366                   timeval_diff_msec(&rusage.ru_stime,
367                                     &last_rusage->ru_stime));
368         if (rusage.ru_minflt > last_rusage->ru_minflt
369             || rusage.ru_majflt > last_rusage->ru_majflt) {
370             VLOG_WARN("faults: %ld minor, %ld major",
371                       rusage.ru_minflt - last_rusage->ru_minflt,
372                       rusage.ru_majflt - last_rusage->ru_majflt);
373         }
374         if (rusage.ru_inblock > last_rusage->ru_inblock
375             || rusage.ru_oublock > last_rusage->ru_oublock) {
376             VLOG_WARN("disk: %ld reads, %ld writes",
377                       rusage.ru_inblock - last_rusage->ru_inblock,
378                       rusage.ru_oublock - last_rusage->ru_oublock);
379         }
380         if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
381             || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
382             VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
383                       rusage.ru_nvcsw - last_rusage->ru_nvcsw,
384                       rusage.ru_nivcsw - last_rusage->ru_nivcsw);
385         }
386         coverage_log();
387     }
388 }
389 \f
390 /* CPU usage tracking. */
391
392 struct cpu_usage {
393     long long int when;         /* Time that this sample was taken. */
394     unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
395 };
396
397 struct cpu_tracker {
398     struct cpu_usage older;
399     struct cpu_usage newer;
400     int cpu_usage;
401
402     struct rusage recent_rusage;
403 };
404 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
405
406 static struct cpu_tracker *
407 get_cpu_tracker(void)
408 {
409     struct cpu_tracker *t = cpu_tracker_var_get();
410     if (!t) {
411         t = xzalloc(sizeof *t);
412         t->older.when = LLONG_MIN;
413         t->newer.when = LLONG_MIN;
414         cpu_tracker_var_set_unsafe(t);
415     }
416     return t;
417 }
418
419 static struct rusage *
420 get_recent_rusage(void)
421 {
422     return &get_cpu_tracker()->recent_rusage;
423 }
424
425 static int
426 getrusage_thread(struct rusage *rusage OVS_UNUSED)
427 {
428 #ifdef RUSAGE_THREAD
429     return getrusage(RUSAGE_THREAD, rusage);
430 #else
431     errno = EINVAL;
432     return -1;
433 #endif
434 }
435
436 static void
437 refresh_rusage(void)
438 {
439     struct cpu_tracker *t = get_cpu_tracker();
440     struct rusage *recent_rusage = &t->recent_rusage;
441
442     if (!getrusage_thread(recent_rusage)) {
443         long long int now = time_msec();
444         if (now >= t->newer.when + 3 * 1000) {
445             t->older = t->newer;
446             t->newer.when = now;
447             t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
448                             timeval_to_msec(&recent_rusage->ru_stime));
449
450             if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
451                 unsigned int dividend = t->newer.cpu - t->older.cpu;
452                 unsigned int divisor = (t->newer.when - t->older.when) / 100;
453                 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
454             } else {
455                 t->cpu_usage = -1;
456             }
457         }
458     }
459 }
460
461 /* Returns an estimate of this process's CPU usage, as a percentage, over the
462  * past few seconds of wall-clock time.  Returns -1 if no estimate is available
463  * (which will happen if the process has not been running long enough to have
464  * an estimate, and can happen for other reasons as well). */
465 int
466 get_cpu_usage(void)
467 {
468     return get_cpu_tracker()->cpu_usage;
469 }
470 \f
471 /* Unixctl interface. */
472
473 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
474  * advancing, except due to later calls to "time/warp". */
475 static void
476 timeval_stop_cb(struct unixctl_conn *conn,
477                  int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
478                  void *aux OVS_UNUSED)
479 {
480     ovs_mutex_lock(&monotonic_clock.mutex);
481     atomic_store(&monotonic_clock.slow_path, true);
482     monotonic_clock.stopped = true;
483     xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
484     ovs_mutex_unlock(&monotonic_clock.mutex);
485
486     unixctl_command_reply(conn, NULL);
487 }
488
489 /* "time/warp MSECS" advances the current monotonic time by the specified
490  * number of milliseconds.  Unless "time/stop" has also been executed, the
491  * monotonic clock continues to tick forward at the normal rate afterward.
492  *
493  * Does not affect wall clock readings. */
494 static void
495 timeval_warp_cb(struct unixctl_conn *conn,
496                 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
497 {
498     struct timespec ts;
499     int msecs;
500
501     msecs = atoi(argv[1]);
502     if (msecs <= 0) {
503         unixctl_command_reply_error(conn, "invalid MSECS");
504         return;
505     }
506
507     ts.tv_sec = msecs / 1000;
508     ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
509
510     ovs_mutex_lock(&monotonic_clock.mutex);
511     atomic_store(&monotonic_clock.slow_path, true);
512     timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
513     ovs_mutex_unlock(&monotonic_clock.mutex);
514
515     unixctl_command_reply(conn, "warped");
516 }
517
518 void
519 timeval_dummy_register(void)
520 {
521     unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
522     unixctl_command_register("time/warp", "MSECS", 1, 1,
523                              timeval_warp_cb, NULL);
524 }
525
526
527
528 /* strftime() with an extension for high-resolution timestamps.  Any '#'s in
529  * 'format' will be replaced by subseconds, e.g. use "%S.###" to obtain results
530  * like "01.123".  */
531 size_t
532 strftime_msec(char *s, size_t max, const char *format,
533               const struct tm_msec *tm)
534 {
535     size_t n;
536
537     n = strftime(s, max, format, &tm->tm);
538     if (n) {
539         char decimals[4];
540         char *p;
541
542         sprintf(decimals, "%03d", tm->msec);
543         for (p = strchr(s, '#'); p; p = strchr(p, '#')) {
544             char *d = decimals;
545             while (*p == '#')  {
546                 *p++ = *d ? *d++ : '0';
547             }
548         }
549     }
550
551     return n;
552 }
553
554 struct tm_msec *
555 localtime_msec(long long int now, struct tm_msec *result)
556 {
557   time_t now_sec = now / 1000;
558   localtime_r(&now_sec, &result->tm);
559   result->msec = now % 1000;
560   return result;
561 }
562
563 struct tm_msec *
564 gmtime_msec(long long int now, struct tm_msec *result)
565 {
566   time_t now_sec = now / 1000;
567   gmtime_r(&now_sec, &result->tm);
568   result->msec = now % 1000;
569   return result;
570 }