acinclude: Always assume buggy strtok_r() for glibc < 2.8.
[cascardo/ovs.git] / lib / timeval.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 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-rcu.h"
35 #include "ovs-thread.h"
36 #include "signals.h"
37 #include "seq.h"
38 #include "unixctl.h"
39 #include "util.h"
40 #include "vlog.h"
41
42 VLOG_DEFINE_THIS_MODULE(timeval);
43
44 #ifdef _WIN32
45 typedef unsigned int clockid_t;
46
47 #ifndef CLOCK_MONOTONIC
48 #define CLOCK_MONOTONIC 1
49 #endif
50
51 #ifndef CLOCK_REALTIME
52 #define CLOCK_REALTIME 2
53 #endif
54
55 /* Number of 100 ns intervals from January 1, 1601 till January 1, 1970. */
56 static ULARGE_INTEGER unix_epoch;
57 #endif /* _WIN32 */
58
59 struct clock {
60     clockid_t id;               /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
61
62     /* Features for use by unit tests.  Protected by 'mutex'. */
63     struct ovs_mutex mutex;
64     atomic_bool slow_path;             /* True if warped or stopped. */
65     struct timespec warp OVS_GUARDED;  /* Offset added for unit tests. */
66     bool stopped OVS_GUARDED;          /* Disable real-time updates if true. */
67     struct timespec cache OVS_GUARDED; /* Last time read from kernel. */
68 };
69
70 /* Our clocks. */
71 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
72 static struct clock wall_clock;      /* CLOCK_REALTIME. */
73
74 /* The monotonic time at which the time module was initialized. */
75 static long long int boot_time;
76
77 /* True only when timeval_dummy_register() is called. */
78 static bool timewarp_enabled;
79 /* Reference to the seq struct.  Threads other than main thread can
80  * wait on timewarp_seq and be waken up when time is warped. */
81 static struct seq *timewarp_seq;
82 /* Last value of 'timewarp_seq'. */
83 DEFINE_STATIC_PER_THREAD_DATA(uint64_t, last_seq, 0);
84
85 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
86  * LLONG_MAX). */
87 static long long int deadline = LLONG_MAX;
88
89 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
90  * up. */
91 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup, 0);
92
93 static void log_poll_interval(long long int last_wakeup);
94 static struct rusage *get_recent_rusage(void);
95 static int getrusage_thread(struct rusage *);
96 static void refresh_rusage(void);
97 static void timespec_add(struct timespec *sum,
98                          const struct timespec *a, const struct timespec *b);
99
100 static void
101 init_clock(struct clock *c, clockid_t id)
102 {
103     memset(c, 0, sizeof *c);
104     c->id = id;
105     ovs_mutex_init(&c->mutex);
106     atomic_init(&c->slow_path, false);
107     xclock_gettime(c->id, &c->cache);
108     timewarp_seq = seq_create();
109 }
110
111 static void
112 do_init_time(void)
113 {
114     struct timespec ts;
115
116 #ifdef _WIN32
117     /* Calculate number of 100-nanosecond intervals till 01/01/1970. */
118     SYSTEMTIME unix_epoch_st = { 1970, 1, 0, 1, 0, 0, 0, 0};
119     FILETIME unix_epoch_ft;
120
121     SystemTimeToFileTime(&unix_epoch_st, &unix_epoch_ft);
122     unix_epoch.LowPart = unix_epoch_ft.dwLowDateTime;
123     unix_epoch.HighPart = unix_epoch_ft.dwHighDateTime;
124 #endif
125
126     coverage_init();
127
128     init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
129                                   ? CLOCK_MONOTONIC
130                                   : CLOCK_REALTIME));
131     init_clock(&wall_clock, CLOCK_REALTIME);
132     boot_time = timespec_to_msec(&monotonic_clock.cache);
133 }
134
135 /* Initializes the timetracking module, if not already initialized. */
136 static void
137 time_init(void)
138 {
139     static pthread_once_t once = PTHREAD_ONCE_INIT;
140     pthread_once(&once, do_init_time);
141 }
142
143 static void
144 time_timespec__(struct clock *c, struct timespec *ts)
145 {
146     bool slow_path;
147
148     time_init();
149
150     atomic_read_explicit(&c->slow_path, &slow_path, memory_order_relaxed);
151     if (!slow_path) {
152         xclock_gettime(c->id, ts);
153     } else {
154         struct timespec warp;
155         struct timespec cache;
156         bool stopped;
157
158         ovs_mutex_lock(&c->mutex);
159         stopped = c->stopped;
160         warp = c->warp;
161         cache = c->cache;
162         ovs_mutex_unlock(&c->mutex);
163
164         if (!stopped) {
165             xclock_gettime(c->id, &cache);
166         }
167         timespec_add(ts, &cache, &warp);
168     }
169 }
170
171 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
172  * '*ts'. */
173 void
174 time_timespec(struct timespec *ts)
175 {
176     time_timespec__(&monotonic_clock, ts);
177 }
178
179 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
180  * '*ts'. */
181 void
182 time_wall_timespec(struct timespec *ts)
183 {
184     time_timespec__(&wall_clock, ts);
185 }
186
187 static time_t
188 time_sec__(struct clock *c)
189 {
190     struct timespec ts;
191
192     time_timespec__(c, &ts);
193     return ts.tv_sec;
194 }
195
196 /* Returns a monotonic timer, in seconds. */
197 time_t
198 time_now(void)
199 {
200     return time_sec__(&monotonic_clock);
201 }
202
203 /* Returns the current time, in seconds. */
204 time_t
205 time_wall(void)
206 {
207     return time_sec__(&wall_clock);
208 }
209
210 static long long int
211 time_msec__(struct clock *c)
212 {
213     struct timespec ts;
214
215     time_timespec__(c, &ts);
216     return timespec_to_msec(&ts);
217 }
218
219 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
220 long long int
221 time_msec(void)
222 {
223     return time_msec__(&monotonic_clock);
224 }
225
226 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
227 long long int
228 time_wall_msec(void)
229 {
230     return time_msec__(&wall_clock);
231 }
232
233 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
234  * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
235 void
236 time_alarm(unsigned int secs)
237 {
238     long long int now;
239     long long int msecs;
240
241     assert_single_threaded();
242     time_init();
243
244     now = time_msec();
245     msecs = secs * 1000LL;
246     deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
247 }
248
249 /* Like poll(), except:
250  *
251  *      - The timeout is specified as an absolute time, as defined by
252  *        time_msec(), instead of a duration.
253  *
254  *      - On error, returns a negative error code (instead of setting errno).
255  *
256  *      - If interrupted by a signal, retries automatically until the original
257  *        timeout is reached.  (Because of this property, this function will
258  *        never return -EINTR.)
259  *
260  * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
261 int
262 time_poll(struct pollfd *pollfds, int n_pollfds, HANDLE *handles OVS_UNUSED,
263           long long int timeout_when, int *elapsed)
264 {
265     long long int *last_wakeup = last_wakeup_get();
266     long long int start;
267     bool quiescent;
268     int retval = 0;
269
270     time_init();
271     coverage_clear();
272     coverage_run();
273     if (*last_wakeup) {
274         log_poll_interval(*last_wakeup);
275     }
276     start = time_msec();
277
278     timeout_when = MIN(timeout_when, deadline);
279     quiescent = ovsrcu_is_quiescent();
280
281     for (;;) {
282         long long int now = time_msec();
283         int time_left;
284
285         if (now >= timeout_when) {
286             time_left = 0;
287         } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
288             time_left = INT_MAX;
289         } else {
290             time_left = timeout_when - now;
291         }
292
293         if (!quiescent) {
294             if (!time_left) {
295                 ovsrcu_quiesce();
296             } else {
297                 ovsrcu_quiesce_start();
298             }
299         }
300
301 #ifndef _WIN32
302         retval = poll(pollfds, n_pollfds, time_left);
303         if (retval < 0) {
304             retval = -errno;
305         }
306 #else
307         if (n_pollfds > MAXIMUM_WAIT_OBJECTS) {
308             VLOG_ERR("Cannot handle more than maximum wait objects\n");
309         } else if (n_pollfds != 0) {
310             retval = WaitForMultipleObjects(n_pollfds, handles, FALSE,
311                                             time_left);
312         }
313         if (retval < 0) {
314             /* XXX This will be replace by a win error to errno
315                conversion function */
316             retval = -WSAGetLastError();
317             retval = -EINVAL;
318         }
319 #endif
320
321         if (!quiescent && time_left) {
322             ovsrcu_quiesce_end();
323         }
324
325         if (deadline <= time_msec()) {
326 #ifndef _WIN32
327             fatal_signal_handler(SIGALRM);
328 #else
329             VLOG_ERR("wake up from WaitForMultipleObjects after deadline");
330             fatal_signal_handler(SIGTERM);
331 #endif
332             if (retval < 0) {
333                 retval = 0;
334             }
335             break;
336         }
337
338         if (retval != -EINTR) {
339             break;
340         }
341     }
342     *last_wakeup = time_msec();
343     refresh_rusage();
344     *elapsed = *last_wakeup - start;
345     return retval;
346 }
347
348 long long int
349 timespec_to_msec(const struct timespec *ts)
350 {
351     return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
352 }
353
354 long long int
355 timeval_to_msec(const struct timeval *tv)
356 {
357     return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
358 }
359
360 /* Returns the monotonic time at which the "time" module was initialized, in
361  * milliseconds. */
362 long long int
363 time_boot_msec(void)
364 {
365     time_init();
366     return boot_time;
367 }
368
369 #ifdef _WIN32
370 static ULARGE_INTEGER
371 xgetfiletime(void)
372 {
373     ULARGE_INTEGER current_time;
374     FILETIME current_time_ft;
375
376     /* Returns current time in UTC as a 64-bit value representing the number
377      * of 100-nanosecond intervals since January 1, 1601 . */
378     GetSystemTimePreciseAsFileTime(&current_time_ft);
379     current_time.LowPart = current_time_ft.dwLowDateTime;
380     current_time.HighPart = current_time_ft.dwHighDateTime;
381
382     return current_time;
383 }
384
385 static int
386 clock_gettime(clock_t id, struct timespec *ts)
387 {
388     if (id == CLOCK_MONOTONIC) {
389         static LARGE_INTEGER freq;
390         LARGE_INTEGER count;
391         long long int ns;
392
393         if (!freq.QuadPart) {
394             /* Number of counts per second. */
395             QueryPerformanceFrequency(&freq);
396         }
397         /* Total number of counts from a starting point. */
398         QueryPerformanceCounter(&count);
399
400         /* Total nano seconds from a starting point. */
401         ns = (double) count.QuadPart / freq.QuadPart * 1000000000;
402
403         ts->tv_sec = count.QuadPart / freq.QuadPart;
404         ts->tv_nsec = ns % 1000000000;
405     } else if (id == CLOCK_REALTIME) {
406         ULARGE_INTEGER current_time = xgetfiletime();
407
408         /* Time from Epoch to now. */
409         ts->tv_sec = (current_time.QuadPart - unix_epoch.QuadPart) / 10000000;
410         ts->tv_nsec = ((current_time.QuadPart - unix_epoch.QuadPart) %
411                        10000000) * 100;
412     } else {
413         return -1;
414     }
415 }
416 #endif /* _WIN32 */
417
418 void
419 xgettimeofday(struct timeval *tv)
420 {
421 #ifndef _WIN32
422     if (gettimeofday(tv, NULL) == -1) {
423         VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
424     }
425 #else
426     ULARGE_INTEGER current_time = xgetfiletime();
427
428     tv->tv_sec = (current_time.QuadPart - unix_epoch.QuadPart) / 10000000;
429     tv->tv_usec = ((current_time.QuadPart - unix_epoch.QuadPart) %
430                    10000000) / 10;
431 #endif
432 }
433
434 void
435 xclock_gettime(clock_t id, struct timespec *ts)
436 {
437     if (clock_gettime(id, ts) == -1) {
438         /* It seems like a bad idea to try to use vlog here because it is
439          * likely to try to check the current time. */
440         ovs_abort(errno, "xclock_gettime() failed");
441     }
442 }
443
444 /* Makes threads wait on timewarp_seq and be waken up when time is warped.
445  * This function will be no-op unless timeval_dummy_register() is called. */
446 void
447 timewarp_wait(void)
448 {
449     if (timewarp_enabled) {
450         uint64_t *last_seq = last_seq_get();
451
452         *last_seq = seq_read(timewarp_seq);
453         seq_wait(timewarp_seq, *last_seq);
454     }
455 }
456
457 static long long int
458 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
459 {
460     return timeval_to_msec(a) - timeval_to_msec(b);
461 }
462
463 static void
464 timespec_add(struct timespec *sum,
465              const struct timespec *a,
466              const struct timespec *b)
467 {
468     struct timespec tmp;
469
470     tmp.tv_sec = a->tv_sec + b->tv_sec;
471     tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
472     if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
473         tmp.tv_nsec -= 1000 * 1000 * 1000;
474         tmp.tv_sec++;
475     }
476
477     *sum = tmp;
478 }
479
480 static bool
481 is_warped(const struct clock *c)
482 {
483     bool warped;
484
485     ovs_mutex_lock(&c->mutex);
486     warped = monotonic_clock.warp.tv_sec || monotonic_clock.warp.tv_nsec;
487     ovs_mutex_unlock(&c->mutex);
488
489     return warped;
490 }
491
492 static void
493 log_poll_interval(long long int last_wakeup)
494 {
495     long long int interval = time_msec() - last_wakeup;
496
497     if (interval >= 1000 && !is_warped(&monotonic_clock)) {
498         const struct rusage *last_rusage = get_recent_rusage();
499         struct rusage rusage;
500
501         if (!getrusage_thread(&rusage)) {
502             VLOG_WARN("Unreasonably long %lldms poll interval"
503                       " (%lldms user, %lldms system)",
504                       interval,
505                       timeval_diff_msec(&rusage.ru_utime,
506                                         &last_rusage->ru_utime),
507                       timeval_diff_msec(&rusage.ru_stime,
508                                         &last_rusage->ru_stime));
509
510             if (rusage.ru_minflt > last_rusage->ru_minflt
511                 || rusage.ru_majflt > last_rusage->ru_majflt) {
512                 VLOG_WARN("faults: %ld minor, %ld major",
513                           rusage.ru_minflt - last_rusage->ru_minflt,
514                           rusage.ru_majflt - last_rusage->ru_majflt);
515             }
516             if (rusage.ru_inblock > last_rusage->ru_inblock
517                 || rusage.ru_oublock > last_rusage->ru_oublock) {
518                 VLOG_WARN("disk: %ld reads, %ld writes",
519                           rusage.ru_inblock - last_rusage->ru_inblock,
520                           rusage.ru_oublock - last_rusage->ru_oublock);
521             }
522             if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
523                 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
524                 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
525                           rusage.ru_nvcsw - last_rusage->ru_nvcsw,
526                           rusage.ru_nivcsw - last_rusage->ru_nivcsw);
527             }
528         } else {
529             VLOG_WARN("Unreasonably long %lldms poll interval", interval);
530         }
531         coverage_log();
532     }
533 }
534 \f
535 /* CPU usage tracking. */
536
537 struct cpu_usage {
538     long long int when;         /* Time that this sample was taken. */
539     unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
540 };
541
542 struct cpu_tracker {
543     struct cpu_usage older;
544     struct cpu_usage newer;
545     int cpu_usage;
546
547     struct rusage recent_rusage;
548 };
549 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
550
551 static struct cpu_tracker *
552 get_cpu_tracker(void)
553 {
554     struct cpu_tracker *t = cpu_tracker_var_get();
555     if (!t) {
556         t = xzalloc(sizeof *t);
557         t->older.when = LLONG_MIN;
558         t->newer.when = LLONG_MIN;
559         cpu_tracker_var_set_unsafe(t);
560     }
561     return t;
562 }
563
564 static struct rusage *
565 get_recent_rusage(void)
566 {
567     return &get_cpu_tracker()->recent_rusage;
568 }
569
570 static int
571 getrusage_thread(struct rusage *rusage OVS_UNUSED)
572 {
573 #ifdef RUSAGE_THREAD
574     return getrusage(RUSAGE_THREAD, rusage);
575 #else
576     errno = EINVAL;
577     return -1;
578 #endif
579 }
580
581 static void
582 refresh_rusage(void)
583 {
584     struct cpu_tracker *t = get_cpu_tracker();
585     struct rusage *recent_rusage = &t->recent_rusage;
586
587     if (!getrusage_thread(recent_rusage)) {
588         long long int now = time_msec();
589         if (now >= t->newer.when + 3 * 1000) {
590             t->older = t->newer;
591             t->newer.when = now;
592             t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
593                             timeval_to_msec(&recent_rusage->ru_stime));
594
595             if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
596                 unsigned int dividend = t->newer.cpu - t->older.cpu;
597                 unsigned int divisor = (t->newer.when - t->older.when) / 100;
598                 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
599             } else {
600                 t->cpu_usage = -1;
601             }
602         }
603     }
604 }
605
606 /* Returns an estimate of this process's CPU usage, as a percentage, over the
607  * past few seconds of wall-clock time.  Returns -1 if no estimate is available
608  * (which will happen if the process has not been running long enough to have
609  * an estimate, and can happen for other reasons as well). */
610 int
611 get_cpu_usage(void)
612 {
613     return get_cpu_tracker()->cpu_usage;
614 }
615 \f
616 /* Unixctl interface. */
617
618 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
619  * advancing, except due to later calls to "time/warp". */
620 static void
621 timeval_stop_cb(struct unixctl_conn *conn,
622                  int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
623                  void *aux OVS_UNUSED)
624 {
625     ovs_mutex_lock(&monotonic_clock.mutex);
626     atomic_store(&monotonic_clock.slow_path, true);
627     monotonic_clock.stopped = true;
628     xclock_gettime(monotonic_clock.id, &monotonic_clock.cache);
629     ovs_mutex_unlock(&monotonic_clock.mutex);
630
631     unixctl_command_reply(conn, NULL);
632 }
633
634 /* "time/warp MSECS" advances the current monotonic time by the specified
635  * number of milliseconds.  Unless "time/stop" has also been executed, the
636  * monotonic clock continues to tick forward at the normal rate afterward.
637  *
638  * Does not affect wall clock readings. */
639 static void
640 timeval_warp_cb(struct unixctl_conn *conn,
641                 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
642 {
643     struct timespec ts;
644     int msecs;
645
646     msecs = atoi(argv[1]);
647     if (msecs <= 0) {
648         unixctl_command_reply_error(conn, "invalid MSECS");
649         return;
650     }
651
652     ts.tv_sec = msecs / 1000;
653     ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
654
655     ovs_mutex_lock(&monotonic_clock.mutex);
656     atomic_store(&monotonic_clock.slow_path, true);
657     timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
658     ovs_mutex_unlock(&monotonic_clock.mutex);
659     seq_change(timewarp_seq);
660     /* give threads (eg. monitor) some chances to run */
661 #ifndef _WIN32
662     poll(NULL, 0, 10);
663 #else
664     Sleep(10);
665 #endif
666     unixctl_command_reply(conn, "warped");
667 }
668
669 void
670 timeval_dummy_register(void)
671 {
672     timewarp_enabled = true;
673     unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
674     unixctl_command_register("time/warp", "MSECS", 1, 1,
675                              timeval_warp_cb, NULL);
676 }
677
678
679
680 /* strftime() with an extension for high-resolution timestamps.  Any '#'s in
681  * 'format' will be replaced by subseconds, e.g. use "%S.###" to obtain results
682  * like "01.123".  */
683 size_t
684 strftime_msec(char *s, size_t max, const char *format,
685               const struct tm_msec *tm)
686 {
687     size_t n;
688
689     /* Visual Studio 2013's behavior is to crash when 0 is passed as second
690      * argument to strftime. */
691     n = max ? strftime(s, max, format, &tm->tm) : 0;
692     if (n) {
693         char decimals[4];
694         char *p;
695
696         sprintf(decimals, "%03d", tm->msec);
697         for (p = strchr(s, '#'); p; p = strchr(p, '#')) {
698             char *d = decimals;
699             while (*p == '#')  {
700                 *p++ = *d ? *d++ : '0';
701             }
702         }
703     }
704
705     return n;
706 }
707
708 struct tm_msec *
709 localtime_msec(long long int now, struct tm_msec *result)
710 {
711   time_t now_sec = now / 1000;
712   localtime_r(&now_sec, &result->tm);
713   result->msec = now % 1000;
714   return result;
715 }
716
717 struct tm_msec *
718 gmtime_msec(long long int now, struct tm_msec *result)
719 {
720   time_t now_sec = now / 1000;
721   gmtime_r(&now_sec, &result->tm);
722   result->msec = now % 1000;
723   return result;
724 }