2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
26 #include <sys/resource.h>
30 #include "dynamic-string.h"
31 #include "fatal-signal.h"
34 #include "ovs-thread.h"
41 VLOG_DEFINE_THIS_MODULE(timeval
);
44 clockid_t id
; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
46 /* Features for use by unit tests. Protected by 'mutex'. */
47 struct ovs_mutex mutex
;
48 atomic_bool slow_path
; /* True if warped or stopped. */
49 struct timespec warp OVS_GUARDED
; /* Offset added for unit tests. */
50 bool stopped OVS_GUARDED
; /* Disable real-time updates if true. */
51 struct timespec cache OVS_GUARDED
; /* Last time read from kernel. */
55 static struct clock monotonic_clock
; /* CLOCK_MONOTONIC, if available. */
56 static struct clock wall_clock
; /* CLOCK_REALTIME. */
58 /* The monotonic time at which the time module was initialized. */
59 static long long int boot_time
;
61 /* True only when timeval_dummy_register() is called. */
62 static bool timewarp_enabled
;
63 /* Reference to the seq struct. Threads other than main thread can
64 * wait on timewarp_seq and be waken up when time is warped. */
65 static struct seq
*timewarp_seq
;
66 /* Last value of 'timewarp_seq'. */
67 DEFINE_STATIC_PER_THREAD_DATA(uint64_t, last_seq
, 0);
69 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
71 static long long int deadline
= LLONG_MAX
;
73 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
75 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup
, 0);
77 static void log_poll_interval(long long int last_wakeup
);
78 static struct rusage
*get_recent_rusage(void);
79 static void refresh_rusage(void);
80 static void timespec_add(struct timespec
*sum
,
81 const struct timespec
*a
, const struct timespec
*b
);
84 init_clock(struct clock
*c
, clockid_t id
)
86 memset(c
, 0, sizeof *c
);
88 ovs_mutex_init(&c
->mutex
);
89 atomic_init(&c
->slow_path
, false);
90 xclock_gettime(c
->id
, &c
->cache
);
91 timewarp_seq
= seq_create();
101 init_clock(&monotonic_clock
, (!clock_gettime(CLOCK_MONOTONIC
, &ts
)
104 init_clock(&wall_clock
, CLOCK_REALTIME
);
105 boot_time
= timespec_to_msec(&monotonic_clock
.cache
);
108 /* Initializes the timetracking module, if not already initialized. */
112 static pthread_once_t once
= PTHREAD_ONCE_INIT
;
113 pthread_once(&once
, do_init_time
);
117 time_timespec__(struct clock
*c
, struct timespec
*ts
)
123 atomic_read_explicit(&c
->slow_path
, &slow_path
, memory_order_relaxed
);
125 xclock_gettime(c
->id
, ts
);
127 struct timespec warp
;
128 struct timespec cache
;
131 ovs_mutex_lock(&c
->mutex
);
132 stopped
= c
->stopped
;
135 ovs_mutex_unlock(&c
->mutex
);
138 xclock_gettime(c
->id
, &cache
);
140 timespec_add(ts
, &cache
, &warp
);
144 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
147 time_timespec(struct timespec
*ts
)
149 time_timespec__(&monotonic_clock
, ts
);
152 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
155 time_wall_timespec(struct timespec
*ts
)
157 time_timespec__(&wall_clock
, ts
);
161 time_sec__(struct clock
*c
)
165 time_timespec__(c
, &ts
);
169 /* Returns a monotonic timer, in seconds. */
173 return time_sec__(&monotonic_clock
);
176 /* Returns the current time, in seconds. */
180 return time_sec__(&wall_clock
);
184 time_msec__(struct clock
*c
)
188 time_timespec__(c
, &ts
);
189 return timespec_to_msec(&ts
);
192 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
196 return time_msec__(&monotonic_clock
);
199 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
203 return time_msec__(&wall_clock
);
206 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
207 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
209 time_alarm(unsigned int secs
)
214 assert_single_threaded();
218 msecs
= secs
* 1000LL;
219 deadline
= now
< LLONG_MAX
- msecs
? now
+ msecs
: LLONG_MAX
;
222 /* Like poll(), except:
224 * - The timeout is specified as an absolute time, as defined by
225 * time_msec(), instead of a duration.
227 * - On error, returns a negative error code (instead of setting errno).
229 * - If interrupted by a signal, retries automatically until the original
230 * timeout is reached. (Because of this property, this function will
231 * never return -EINTR.)
233 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
235 time_poll(struct pollfd
*pollfds
, int n_pollfds
, long long int timeout_when
,
238 long long int *last_wakeup
= last_wakeup_get();
246 log_poll_interval(*last_wakeup
);
250 timeout_when
= MIN(timeout_when
, deadline
);
253 long long int now
= time_msec();
256 if (now
>= timeout_when
) {
258 } else if ((unsigned long long int) timeout_when
- now
> INT_MAX
) {
261 time_left
= timeout_when
- now
;
264 retval
= poll(pollfds
, n_pollfds
, time_left
);
269 if (deadline
<= time_msec()) {
270 fatal_signal_handler(SIGALRM
);
277 if (retval
!= -EINTR
) {
281 *last_wakeup
= time_msec();
283 *elapsed
= *last_wakeup
- start
;
288 timespec_to_msec(const struct timespec
*ts
)
290 return (long long int) ts
->tv_sec
* 1000 + ts
->tv_nsec
/ (1000 * 1000);
294 timeval_to_msec(const struct timeval
*tv
)
296 return (long long int) tv
->tv_sec
* 1000 + tv
->tv_usec
/ 1000;
299 /* Returns the monotonic time at which the "time" module was initialized, in
309 xgettimeofday(struct timeval
*tv
)
311 if (gettimeofday(tv
, NULL
) == -1) {
312 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno
));
317 xclock_gettime(clock_t id
, struct timespec
*ts
)
319 if (clock_gettime(id
, ts
) == -1) {
320 /* It seems like a bad idea to try to use vlog here because it is
321 * likely to try to check the current time. */
322 ovs_abort(errno
, "xclock_gettime() failed");
326 /* Makes threads wait on timewarp_seq and be waken up when time is warped.
327 * This function will be no-op unless timeval_dummy_register() is called. */
331 if (timewarp_enabled
) {
332 uint64_t *last_seq
= last_seq_get();
334 *last_seq
= seq_read(timewarp_seq
);
335 seq_wait(timewarp_seq
, *last_seq
);
340 timeval_diff_msec(const struct timeval
*a
, const struct timeval
*b
)
342 return timeval_to_msec(a
) - timeval_to_msec(b
);
346 timespec_add(struct timespec
*sum
,
347 const struct timespec
*a
,
348 const struct timespec
*b
)
352 tmp
.tv_sec
= a
->tv_sec
+ b
->tv_sec
;
353 tmp
.tv_nsec
= a
->tv_nsec
+ b
->tv_nsec
;
354 if (tmp
.tv_nsec
>= 1000 * 1000 * 1000) {
355 tmp
.tv_nsec
-= 1000 * 1000 * 1000;
363 is_warped(const struct clock
*c
)
367 ovs_mutex_lock(&c
->mutex
);
368 warped
= monotonic_clock
.warp
.tv_sec
|| monotonic_clock
.warp
.tv_nsec
;
369 ovs_mutex_unlock(&c
->mutex
);
375 log_poll_interval(long long int last_wakeup
)
377 long long int interval
= time_msec() - last_wakeup
;
379 if (interval
>= 1000 && !is_warped(&monotonic_clock
)) {
380 const struct rusage
*last_rusage
= get_recent_rusage();
381 struct rusage rusage
;
383 getrusage(RUSAGE_SELF
, &rusage
);
384 VLOG_WARN("Unreasonably long %lldms poll interval"
385 " (%lldms user, %lldms system)",
387 timeval_diff_msec(&rusage
.ru_utime
,
388 &last_rusage
->ru_utime
),
389 timeval_diff_msec(&rusage
.ru_stime
,
390 &last_rusage
->ru_stime
));
391 if (rusage
.ru_minflt
> last_rusage
->ru_minflt
392 || rusage
.ru_majflt
> last_rusage
->ru_majflt
) {
393 VLOG_WARN("faults: %ld minor, %ld major",
394 rusage
.ru_minflt
- last_rusage
->ru_minflt
,
395 rusage
.ru_majflt
- last_rusage
->ru_majflt
);
397 if (rusage
.ru_inblock
> last_rusage
->ru_inblock
398 || rusage
.ru_oublock
> last_rusage
->ru_oublock
) {
399 VLOG_WARN("disk: %ld reads, %ld writes",
400 rusage
.ru_inblock
- last_rusage
->ru_inblock
,
401 rusage
.ru_oublock
- last_rusage
->ru_oublock
);
403 if (rusage
.ru_nvcsw
> last_rusage
->ru_nvcsw
404 || rusage
.ru_nivcsw
> last_rusage
->ru_nivcsw
) {
405 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
406 rusage
.ru_nvcsw
- last_rusage
->ru_nvcsw
,
407 rusage
.ru_nivcsw
- last_rusage
->ru_nivcsw
);
413 /* CPU usage tracking. */
416 long long int when
; /* Time that this sample was taken. */
417 unsigned long long int cpu
; /* Total user+system CPU usage when sampled. */
421 struct cpu_usage older
;
422 struct cpu_usage newer
;
425 struct rusage recent_rusage
;
427 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker
*, cpu_tracker_var
);
429 static struct cpu_tracker
*
430 get_cpu_tracker(void)
432 struct cpu_tracker
*t
= cpu_tracker_var_get();
434 t
= xzalloc(sizeof *t
);
435 t
->older
.when
= LLONG_MIN
;
436 t
->newer
.when
= LLONG_MIN
;
437 cpu_tracker_var_set_unsafe(t
);
442 static struct rusage
*
443 get_recent_rusage(void)
445 return &get_cpu_tracker()->recent_rusage
;
449 getrusage_thread(struct rusage
*rusage OVS_UNUSED
)
452 return getrusage(RUSAGE_THREAD
, rusage
);
462 struct cpu_tracker
*t
= get_cpu_tracker();
463 struct rusage
*recent_rusage
= &t
->recent_rusage
;
465 if (!getrusage_thread(recent_rusage
)) {
466 long long int now
= time_msec();
467 if (now
>= t
->newer
.when
+ 3 * 1000) {
470 t
->newer
.cpu
= (timeval_to_msec(&recent_rusage
->ru_utime
) +
471 timeval_to_msec(&recent_rusage
->ru_stime
));
473 if (t
->older
.when
!= LLONG_MIN
&& t
->newer
.cpu
> t
->older
.cpu
) {
474 unsigned int dividend
= t
->newer
.cpu
- t
->older
.cpu
;
475 unsigned int divisor
= (t
->newer
.when
- t
->older
.when
) / 100;
476 t
->cpu_usage
= divisor
> 0 ? dividend
/ divisor
: -1;
484 /* Returns an estimate of this process's CPU usage, as a percentage, over the
485 * past few seconds of wall-clock time. Returns -1 if no estimate is available
486 * (which will happen if the process has not been running long enough to have
487 * an estimate, and can happen for other reasons as well). */
491 return get_cpu_tracker()->cpu_usage
;
494 /* Unixctl interface. */
496 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
497 * advancing, except due to later calls to "time/warp". */
499 timeval_stop_cb(struct unixctl_conn
*conn
,
500 int argc OVS_UNUSED
, const char *argv
[] OVS_UNUSED
,
501 void *aux OVS_UNUSED
)
503 ovs_mutex_lock(&monotonic_clock
.mutex
);
504 atomic_store(&monotonic_clock
.slow_path
, true);
505 monotonic_clock
.stopped
= true;
506 xclock_gettime(monotonic_clock
.id
, &monotonic_clock
.cache
);
507 ovs_mutex_unlock(&monotonic_clock
.mutex
);
509 unixctl_command_reply(conn
, NULL
);
512 /* "time/warp MSECS" advances the current monotonic time by the specified
513 * number of milliseconds. Unless "time/stop" has also been executed, the
514 * monotonic clock continues to tick forward at the normal rate afterward.
516 * Does not affect wall clock readings. */
518 timeval_warp_cb(struct unixctl_conn
*conn
,
519 int argc OVS_UNUSED
, const char *argv
[], void *aux OVS_UNUSED
)
524 msecs
= atoi(argv
[1]);
526 unixctl_command_reply_error(conn
, "invalid MSECS");
530 ts
.tv_sec
= msecs
/ 1000;
531 ts
.tv_nsec
= (msecs
% 1000) * 1000 * 1000;
533 ovs_mutex_lock(&monotonic_clock
.mutex
);
534 atomic_store(&monotonic_clock
.slow_path
, true);
535 timespec_add(&monotonic_clock
.warp
, &monotonic_clock
.warp
, &ts
);
536 ovs_mutex_unlock(&monotonic_clock
.mutex
);
537 seq_change(timewarp_seq
);
538 poll(NULL
, 0, 10); /* give threads (eg. monitor) some chances to run */
539 unixctl_command_reply(conn
, "warped");
543 timeval_dummy_register(void)
545 timewarp_enabled
= true;
546 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb
, NULL
);
547 unixctl_command_register("time/warp", "MSECS", 1, 1,
548 timeval_warp_cb
, NULL
);
553 /* strftime() with an extension for high-resolution timestamps. Any '#'s in
554 * 'format' will be replaced by subseconds, e.g. use "%S.###" to obtain results
557 strftime_msec(char *s
, size_t max
, const char *format
,
558 const struct tm_msec
*tm
)
562 n
= strftime(s
, max
, format
, &tm
->tm
);
567 sprintf(decimals
, "%03d", tm
->msec
);
568 for (p
= strchr(s
, '#'); p
; p
= strchr(p
, '#')) {
571 *p
++ = *d
? *d
++ : '0';
580 localtime_msec(long long int now
, struct tm_msec
*result
)
582 time_t now_sec
= now
/ 1000;
583 localtime_r(&now_sec
, &result
->tm
);
584 result
->msec
= now
% 1000;
589 gmtime_msec(long long int now
, struct tm_msec
*result
)
591 time_t now_sec
= now
/ 1000;
592 gmtime_r(&now_sec
, &result
->tm
);
593 result
->msec
= now
% 1000;