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"
40 VLOG_DEFINE_THIS_MODULE(timeval
);
43 clockid_t id
; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
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. */
54 static struct clock monotonic_clock
; /* CLOCK_MONOTONIC, if available. */
55 static struct clock wall_clock
; /* CLOCK_REALTIME. */
57 /* The monotonic time at which the time module was initialized. */
58 static long long int boot_time
;
60 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
62 static long long int deadline
= LLONG_MAX
;
64 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
66 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup
, 0);
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
);
75 init_clock(struct clock
*c
, clockid_t id
)
77 memset(c
, 0, sizeof *c
);
79 ovs_mutex_init(&c
->mutex
);
80 atomic_init(&c
->slow_path
, false);
81 xclock_gettime(c
->id
, &c
->cache
);
91 init_clock(&monotonic_clock
, (!clock_gettime(CLOCK_MONOTONIC
, &ts
)
94 init_clock(&wall_clock
, CLOCK_REALTIME
);
95 boot_time
= timespec_to_msec(&monotonic_clock
.cache
);
98 /* Initializes the timetracking module, if not already initialized. */
102 static pthread_once_t once
= PTHREAD_ONCE_INIT
;
103 pthread_once(&once
, do_init_time
);
107 time_timespec__(struct clock
*c
, struct timespec
*ts
)
113 atomic_read_explicit(&c
->slow_path
, &slow_path
, memory_order_relaxed
);
115 xclock_gettime(c
->id
, ts
);
117 struct timespec warp
;
118 struct timespec cache
;
121 ovs_mutex_lock(&c
->mutex
);
122 stopped
= c
->stopped
;
125 ovs_mutex_unlock(&c
->mutex
);
128 xclock_gettime(c
->id
, &cache
);
130 timespec_add(ts
, &cache
, &warp
);
134 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
137 time_timespec(struct timespec
*ts
)
139 time_timespec__(&monotonic_clock
, ts
);
142 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
145 time_wall_timespec(struct timespec
*ts
)
147 time_timespec__(&wall_clock
, ts
);
151 time_sec__(struct clock
*c
)
155 time_timespec__(c
, &ts
);
159 /* Returns a monotonic timer, in seconds. */
163 return time_sec__(&monotonic_clock
);
166 /* Returns the current time, in seconds. */
170 return time_sec__(&wall_clock
);
174 time_msec__(struct clock
*c
)
178 time_timespec__(c
, &ts
);
179 return timespec_to_msec(&ts
);
182 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
186 return time_msec__(&monotonic_clock
);
189 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
193 return time_msec__(&wall_clock
);
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. */
199 time_alarm(unsigned int secs
)
204 assert_single_threaded();
208 msecs
= secs
* 1000LL;
209 deadline
= now
< LLONG_MAX
- msecs
? now
+ msecs
: LLONG_MAX
;
212 /* Like poll(), except:
214 * - The timeout is specified as an absolute time, as defined by
215 * time_msec(), instead of a duration.
217 * - On error, returns a negative error code (instead of setting errno).
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.)
223 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
225 time_poll(struct pollfd
*pollfds
, int n_pollfds
, long long int timeout_when
,
228 long long int *last_wakeup
= last_wakeup_get();
234 log_poll_interval(*last_wakeup
);
240 timeout_when
= MIN(timeout_when
, deadline
);
243 long long int now
= time_msec();
246 if (now
>= timeout_when
) {
248 } else if ((unsigned long long int) timeout_when
- now
> INT_MAX
) {
251 time_left
= timeout_when
- now
;
254 retval
= poll(pollfds
, n_pollfds
, time_left
);
259 if (deadline
<= time_msec()) {
260 fatal_signal_handler(SIGALRM
);
267 if (retval
!= -EINTR
) {
271 *last_wakeup
= time_msec();
273 *elapsed
= *last_wakeup
- start
;
278 timespec_to_msec(const struct timespec
*ts
)
280 return (long long int) ts
->tv_sec
* 1000 + ts
->tv_nsec
/ (1000 * 1000);
284 timeval_to_msec(const struct timeval
*tv
)
286 return (long long int) tv
->tv_sec
* 1000 + tv
->tv_usec
/ 1000;
289 /* Returns the monotonic time at which the "time" module was initialized, in
299 xgettimeofday(struct timeval
*tv
)
301 if (gettimeofday(tv
, NULL
) == -1) {
302 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno
));
307 xclock_gettime(clock_t id
, struct timespec
*ts
)
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");
317 timeval_diff_msec(const struct timeval
*a
, const struct timeval
*b
)
319 return timeval_to_msec(a
) - timeval_to_msec(b
);
323 timespec_add(struct timespec
*sum
,
324 const struct timespec
*a
,
325 const struct timespec
*b
)
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;
340 is_warped(const struct clock
*c
)
344 ovs_mutex_lock(&c
->mutex
);
345 warped
= monotonic_clock
.warp
.tv_sec
|| monotonic_clock
.warp
.tv_nsec
;
346 ovs_mutex_unlock(&c
->mutex
);
352 log_poll_interval(long long int last_wakeup
)
354 long long int interval
= time_msec() - last_wakeup
;
356 if (interval
>= 1000 && !is_warped(&monotonic_clock
)) {
357 const struct rusage
*last_rusage
= get_recent_rusage();
358 struct rusage rusage
;
360 getrusage(RUSAGE_SELF
, &rusage
);
361 VLOG_WARN("Unreasonably long %lldms poll interval"
362 " (%lldms user, %lldms system)",
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
);
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
);
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
);
390 /* CPU usage tracking. */
393 long long int when
; /* Time that this sample was taken. */
394 unsigned long long int cpu
; /* Total user+system CPU usage when sampled. */
398 struct cpu_usage older
;
399 struct cpu_usage newer
;
402 struct rusage recent_rusage
;
404 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker
*, cpu_tracker_var
);
406 static struct cpu_tracker
*
407 get_cpu_tracker(void)
409 struct cpu_tracker
*t
= cpu_tracker_var_get();
411 t
= xzalloc(sizeof *t
);
412 t
->older
.when
= LLONG_MIN
;
413 t
->newer
.when
= LLONG_MIN
;
414 cpu_tracker_var_set_unsafe(t
);
419 static struct rusage
*
420 get_recent_rusage(void)
422 return &get_cpu_tracker()->recent_rusage
;
426 getrusage_thread(struct rusage
*rusage OVS_UNUSED
)
429 return getrusage(RUSAGE_THREAD
, rusage
);
439 struct cpu_tracker
*t
= get_cpu_tracker();
440 struct rusage
*recent_rusage
= &t
->recent_rusage
;
442 if (!getrusage_thread(recent_rusage
)) {
443 long long int now
= time_msec();
444 if (now
>= t
->newer
.when
+ 3 * 1000) {
447 t
->newer
.cpu
= (timeval_to_msec(&recent_rusage
->ru_utime
) +
448 timeval_to_msec(&recent_rusage
->ru_stime
));
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;
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). */
468 return get_cpu_tracker()->cpu_usage
;
471 /* Unixctl interface. */
473 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
474 * advancing, except due to later calls to "time/warp". */
476 timeval_stop_cb(struct unixctl_conn
*conn
,
477 int argc OVS_UNUSED
, const char *argv
[] OVS_UNUSED
,
478 void *aux OVS_UNUSED
)
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
);
486 unixctl_command_reply(conn
, NULL
);
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.
493 * Does not affect wall clock readings. */
495 timeval_warp_cb(struct unixctl_conn
*conn
,
496 int argc OVS_UNUSED
, const char *argv
[], void *aux OVS_UNUSED
)
501 msecs
= atoi(argv
[1]);
503 unixctl_command_reply_error(conn
, "invalid MSECS");
507 ts
.tv_sec
= msecs
/ 1000;
508 ts
.tv_nsec
= (msecs
% 1000) * 1000 * 1000;
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
);
515 unixctl_command_reply(conn
, "warped");
519 timeval_dummy_register(void)
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
);
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
532 strftime_msec(char *s
, size_t max
, const char *format
,
533 const struct tm_msec
*tm
)
537 n
= strftime(s
, max
, format
, &tm
->tm
);
542 sprintf(decimals
, "%03d", tm
->msec
);
543 for (p
= strchr(s
, '#'); p
; p
= strchr(p
, '#')) {
546 *p
++ = *d
? *d
++ : '0';
555 localtime_msec(long long int now
, struct tm_msec
*result
)
557 time_t now_sec
= now
/ 1000;
558 localtime_r(&now_sec
, &result
->tm
);
559 result
->msec
= now
% 1000;
564 gmtime_msec(long long int now
, struct tm_msec
*result
)
566 time_t now_sec
= now
/ 1000;
567 gmtime_r(&now_sec
, &result
->tm
);
568 result
->msec
= now
% 1000;