2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 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.
29 #include <sys/resource.h>
33 #include "dynamic-string.h"
34 #include "fatal-signal.h"
40 #ifndef HAVE_EXECINFO_H
41 #define HAVE_EXECINFO_H 0
44 VLOG_DEFINE_THIS_MODULE(timeval
);
46 /* The clock to use for measuring time intervals. This is CLOCK_MONOTONIC by
47 * preference, but on systems that don't have a monotonic clock we fall back
48 * to CLOCK_REALTIME. */
49 static clockid_t monotonic_clock
;
51 /* Has a timer tick occurred? Only relevant if CACHE_TIME is true.
53 * We initialize these to true to force time_init() to get called on the first
54 * call to time_msec() or another function that queries the current time. */
55 static volatile sig_atomic_t wall_tick
= true;
56 static volatile sig_atomic_t monotonic_tick
= true;
58 /* The current time, as of the last refresh. */
59 static struct timespec wall_time
;
60 static struct timespec monotonic_time
;
62 /* The monotonic time at which the time module was initialized. */
63 static long long int boot_time
;
65 /* features for use by unit tests. */
66 static struct timespec warp_offset
; /* Offset added to monotonic_time. */
67 static bool time_stopped
; /* Disables real-time updates, if true. */
69 /* Time in milliseconds at which to die with SIGALRM (if not LLONG_MAX). */
70 static long long int deadline
= LLONG_MAX
;
73 void *backtrace
[32]; /* Populated by backtrace(). */
74 size_t n_frames
; /* Number of frames in 'backtrace'. */
78 static struct trace traces
[MAX_TRACES
];
79 static size_t trace_head
= 0;
81 static void set_up_timer(void);
82 static void set_up_signal(int flags
);
83 static void sigalrm_handler(int);
84 static void refresh_wall_if_ticked(void);
85 static void refresh_monotonic_if_ticked(void);
86 static void block_sigalrm(sigset_t
*);
87 static void unblock_sigalrm(const sigset_t
*);
88 static void log_poll_interval(long long int last_wakeup
);
89 static struct rusage
*get_recent_rusage(void);
90 static void refresh_rusage(void);
91 static void timespec_add(struct timespec
*sum
,
92 const struct timespec
*a
, const struct timespec
*b
);
93 static unixctl_cb_func backtrace_cb
;
95 /* Initializes the timetracking module, if not already initialized. */
106 memset(traces
, 0, sizeof traces
);
108 if (HAVE_EXECINFO_H
&& CACHE_TIME
) {
109 unixctl_command_register("backtrace", "", 0, 0, backtrace_cb
, NULL
);
114 if (!clock_gettime(CLOCK_MONOTONIC
, &monotonic_time
)) {
115 monotonic_clock
= CLOCK_MONOTONIC
;
117 monotonic_clock
= CLOCK_REALTIME
;
118 VLOG_DBG("monotonic timer not available");
121 set_up_signal(SA_RESTART
);
124 boot_time
= time_msec();
128 set_up_signal(int flags
)
132 memset(&sa
, 0, sizeof sa
);
133 sa
.sa_handler
= sigalrm_handler
;
134 sigemptyset(&sa
.sa_mask
);
136 xsigaction(SIGALRM
, &sa
, NULL
);
139 /* Remove SA_RESTART from the flags for SIGALRM, so that any system call that
140 * is interrupted by the periodic timer interrupt will return EINTR instead of
141 * continuing after the signal handler returns.
143 * time_disable_restart() and time_enable_restart() may be usefully wrapped
144 * around function calls that might otherwise block forever unless interrupted
147 * time_disable_restart();
148 * fcntl(fd, F_SETLKW, &lock);
149 * time_enable_restart();
152 time_disable_restart(void)
158 /* Add SA_RESTART to the flags for SIGALRM, so that any system call that
159 * is interrupted by the periodic timer interrupt will continue after the
160 * signal handler returns instead of returning EINTR. */
162 time_enable_restart(void)
165 set_up_signal(SA_RESTART
);
171 static timer_t timer_id
; /* "static" to avoid apparent memory leak. */
172 struct itimerspec itimer
;
178 if (timer_create(monotonic_clock
, NULL
, &timer_id
)) {
179 VLOG_FATAL("timer_create failed (%s)", strerror(errno
));
182 itimer
.it_interval
.tv_sec
= 0;
183 itimer
.it_interval
.tv_nsec
= TIME_UPDATE_INTERVAL
* 1000 * 1000;
184 itimer
.it_value
= itimer
.it_interval
;
186 if (timer_settime(timer_id
, 0, &itimer
, NULL
)) {
187 VLOG_FATAL("timer_settime failed (%s)", strerror(errno
));
191 /* Set up the interval timer, to ensure that time advances even without calling
194 * A child created with fork() does not inherit the parent's interval timer, so
195 * this function needs to be called from the child after fork(). */
207 clock_gettime(CLOCK_REALTIME
, &wall_time
);
212 refresh_monotonic(void)
217 if (monotonic_clock
== CLOCK_MONOTONIC
) {
218 clock_gettime(monotonic_clock
, &monotonic_time
);
220 refresh_wall_if_ticked();
221 monotonic_time
= wall_time
;
223 timespec_add(&monotonic_time
, &monotonic_time
, &warp_offset
);
225 monotonic_tick
= false;
229 /* Forces a refresh of the current time from the kernel. It is not usually
230 * necessary to call this function, since the time will be refreshed
231 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. If
232 * CACHE_TIME is false, we will always refresh the current time so this
233 * function has no effect. */
237 wall_tick
= monotonic_tick
= true;
240 /* Returns a monotonic timer, in seconds. */
244 refresh_monotonic_if_ticked();
245 return monotonic_time
.tv_sec
;
248 /* Returns the current time, in seconds. */
252 refresh_wall_if_ticked();
253 return wall_time
.tv_sec
;
256 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
260 refresh_monotonic_if_ticked();
261 return timespec_to_msec(&monotonic_time
);
264 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
268 refresh_wall_if_ticked();
269 return timespec_to_msec(&wall_time
);
272 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
275 time_timespec(struct timespec
*ts
)
277 refresh_monotonic_if_ticked();
278 *ts
= monotonic_time
;
281 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
284 time_wall_timespec(struct timespec
*ts
)
286 refresh_wall_if_ticked();
290 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
291 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
293 time_alarm(unsigned int secs
)
306 block_sigalrm(&oldsigs
);
307 deadline
= now
< LLONG_MAX
- msecs
? now
+ msecs
: LLONG_MAX
;
308 unblock_sigalrm(&oldsigs
);
311 /* Like poll(), except:
313 * - The timeout is specified as an absolute time, as defined by
314 * time_msec(), instead of a duration.
316 * - On error, returns a negative error code (instead of setting errno).
318 * - If interrupted by a signal, retries automatically until the original
319 * timeout is reached. (Because of this property, this function will
320 * never return -EINTR.)
322 * - As a side effect, refreshes the current time (like time_refresh()).
324 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
326 time_poll(struct pollfd
*pollfds
, int n_pollfds
, long long int timeout_when
,
329 static long long int last_wakeup
= 0;
337 log_poll_interval(last_wakeup
);
343 timeout_when
= MIN(timeout_when
, deadline
);
346 long long int now
= time_msec();
349 if (now
>= timeout_when
) {
351 } else if ((unsigned long long int) timeout_when
- now
> INT_MAX
) {
354 time_left
= timeout_when
- now
;
357 retval
= poll(pollfds
, n_pollfds
, time_left
);
363 if (deadline
<= time_msec()) {
364 fatal_signal_handler(SIGALRM
);
371 if (retval
!= -EINTR
) {
375 if (!blocked
&& CACHE_TIME
) {
376 block_sigalrm(&oldsigs
);
381 unblock_sigalrm(&oldsigs
);
383 last_wakeup
= time_msec();
385 *elapsed
= last_wakeup
- start
;
390 sigalrm_handler(int sig_nr OVS_UNUSED
)
393 monotonic_tick
= true;
397 struct trace
*trace
= &traces
[trace_head
];
399 trace
->n_frames
= backtrace(trace
->backtrace
,
400 ARRAY_SIZE(trace
->backtrace
));
401 trace_head
= (trace_head
+ 1) % MAX_TRACES
;
407 refresh_wall_if_ticked(void)
409 if (!CACHE_TIME
|| wall_tick
) {
415 refresh_monotonic_if_ticked(void)
417 if (!CACHE_TIME
|| monotonic_tick
) {
423 block_sigalrm(sigset_t
*oldsigs
)
426 sigemptyset(&sigalrm
);
427 sigaddset(&sigalrm
, SIGALRM
);
428 xsigprocmask(SIG_BLOCK
, &sigalrm
, oldsigs
);
432 unblock_sigalrm(const sigset_t
*oldsigs
)
434 xsigprocmask(SIG_SETMASK
, oldsigs
, NULL
);
438 timespec_to_msec(const struct timespec
*ts
)
440 return (long long int) ts
->tv_sec
* 1000 + ts
->tv_nsec
/ (1000 * 1000);
444 timeval_to_msec(const struct timeval
*tv
)
446 return (long long int) tv
->tv_sec
* 1000 + tv
->tv_usec
/ 1000;
449 /* Returns the monotonic time at which the "time" module was initialized, in
459 xgettimeofday(struct timeval
*tv
)
461 if (gettimeofday(tv
, NULL
) == -1) {
462 VLOG_FATAL("gettimeofday failed (%s)", strerror(errno
));
467 timeval_diff_msec(const struct timeval
*a
, const struct timeval
*b
)
469 return timeval_to_msec(a
) - timeval_to_msec(b
);
473 timespec_add(struct timespec
*sum
,
474 const struct timespec
*a
,
475 const struct timespec
*b
)
479 tmp
.tv_sec
= a
->tv_sec
+ b
->tv_sec
;
480 tmp
.tv_nsec
= a
->tv_nsec
+ b
->tv_nsec
;
481 if (tmp
.tv_nsec
>= 1000 * 1000 * 1000) {
482 tmp
.tv_nsec
-= 1000 * 1000 * 1000;
490 log_poll_interval(long long int last_wakeup
)
492 long long int interval
= time_msec() - last_wakeup
;
494 if (interval
>= 1000) {
495 const struct rusage
*last_rusage
= get_recent_rusage();
496 struct rusage rusage
;
498 getrusage(RUSAGE_SELF
, &rusage
);
499 VLOG_WARN("Unreasonably long %lldms poll interval"
500 " (%lldms user, %lldms system)",
502 timeval_diff_msec(&rusage
.ru_utime
,
503 &last_rusage
->ru_utime
),
504 timeval_diff_msec(&rusage
.ru_stime
,
505 &last_rusage
->ru_stime
));
506 if (rusage
.ru_minflt
> last_rusage
->ru_minflt
507 || rusage
.ru_majflt
> last_rusage
->ru_majflt
) {
508 VLOG_WARN("faults: %ld minor, %ld major",
509 rusage
.ru_minflt
- last_rusage
->ru_minflt
,
510 rusage
.ru_majflt
- last_rusage
->ru_majflt
);
512 if (rusage
.ru_inblock
> last_rusage
->ru_inblock
513 || rusage
.ru_oublock
> last_rusage
->ru_oublock
) {
514 VLOG_WARN("disk: %ld reads, %ld writes",
515 rusage
.ru_inblock
- last_rusage
->ru_inblock
,
516 rusage
.ru_oublock
- last_rusage
->ru_oublock
);
518 if (rusage
.ru_nvcsw
> last_rusage
->ru_nvcsw
519 || rusage
.ru_nivcsw
> last_rusage
->ru_nivcsw
) {
520 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
521 rusage
.ru_nvcsw
- last_rusage
->ru_nvcsw
,
522 rusage
.ru_nivcsw
- last_rusage
->ru_nivcsw
);
528 /* CPU usage tracking. */
531 long long int when
; /* Time that this sample was taken. */
532 unsigned long long int cpu
; /* Total user+system CPU usage when sampled. */
535 static struct rusage recent_rusage
;
536 static struct cpu_usage older
= { LLONG_MIN
, 0 };
537 static struct cpu_usage newer
= { LLONG_MIN
, 0 };
538 static int cpu_usage
= -1;
540 static struct rusage
*
541 get_recent_rusage(void)
543 return &recent_rusage
;
552 getrusage(RUSAGE_SELF
, &recent_rusage
);
554 if (now
>= newer
.when
+ 3 * 1000) {
557 newer
.cpu
= (timeval_to_msec(&recent_rusage
.ru_utime
) +
558 timeval_to_msec(&recent_rusage
.ru_stime
));
560 if (older
.when
!= LLONG_MIN
&& newer
.cpu
> older
.cpu
) {
561 unsigned int dividend
= newer
.cpu
- older
.cpu
;
562 unsigned int divisor
= (newer
.when
- older
.when
) / 100;
563 cpu_usage
= divisor
> 0 ? dividend
/ divisor
: -1;
570 /* Returns an estimate of this process's CPU usage, as a percentage, over the
571 * past few seconds of wall-clock time. Returns -1 if no estimate is available
572 * (which will happen if the process has not been running long enough to have
573 * an estimate, and can happen for other reasons as well). */
581 format_backtraces(struct ds
*ds
)
590 block_sigalrm(&oldsigs
);
592 for (i
= 0; i
< MAX_TRACES
; i
++) {
593 struct trace
*trace
= &traces
[i
];
597 if (!trace
->n_frames
) {
601 frame_strs
= backtrace_symbols(trace
->backtrace
, trace
->n_frames
);
603 ds_put_format(ds
, "Backtrace %zu\n", i
+ 1);
604 for (j
= 0; j
< trace
->n_frames
; j
++) {
605 ds_put_format(ds
, "%s\n", frame_strs
[j
]);
607 ds_put_cstr(ds
, "\n");
612 unblock_sigalrm(&oldsigs
);
617 /* Unixctl interface. */
619 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
620 * advancing, except due to later calls to "time/warp". */
622 timeval_stop_cb(struct unixctl_conn
*conn
,
623 int argc OVS_UNUSED
, const char *argv
[] OVS_UNUSED
,
624 void *aux OVS_UNUSED
)
627 unixctl_command_reply(conn
, NULL
);
630 /* "time/warp MSECS" advances the current monotonic time by the specified
631 * number of milliseconds. Unless "time/stop" has also been executed, the
632 * monotonic clock continues to tick forward at the normal rate afterward.
634 * Does not affect wall clock readings. */
636 timeval_warp_cb(struct unixctl_conn
*conn
,
637 int argc OVS_UNUSED
, const char *argv
[], void *aux OVS_UNUSED
)
642 msecs
= atoi(argv
[1]);
644 unixctl_command_reply_error(conn
, "invalid MSECS");
648 ts
.tv_sec
= msecs
/ 1000;
649 ts
.tv_nsec
= (msecs
% 1000) * 1000 * 1000;
650 timespec_add(&warp_offset
, &warp_offset
, &ts
);
651 timespec_add(&monotonic_time
, &monotonic_time
, &ts
);
652 unixctl_command_reply(conn
, "warped");
656 backtrace_cb(struct unixctl_conn
*conn
,
657 int argc OVS_UNUSED
, const char *argv
[] OVS_UNUSED
,
658 void *aux OVS_UNUSED
)
660 struct ds ds
= DS_EMPTY_INITIALIZER
;
662 assert(HAVE_EXECINFO_H
&& CACHE_TIME
);
663 format_backtraces(&ds
);
664 unixctl_command_reply(conn
, ds_cstr(&ds
));
669 timeval_dummy_register(void)
671 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb
, NULL
);
672 unixctl_command_register("time/warp", "MSECS", 1, 1,
673 timeval_warp_cb
, NULL
);