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 unixctl_conn
*backtrace_conn
= NULL
;
79 static struct trace
*traces
= NULL
;
80 static size_t n_traces
= 0;
82 static void set_up_timer(void);
83 static void set_up_signal(int flags
);
84 static void sigalrm_handler(int);
85 static void refresh_wall_if_ticked(void);
86 static void refresh_monotonic_if_ticked(void);
87 static void block_sigalrm(sigset_t
*);
88 static void unblock_sigalrm(const sigset_t
*);
89 static void log_poll_interval(long long int last_wakeup
);
90 static struct rusage
*get_recent_rusage(void);
91 static void refresh_rusage(void);
92 static void timespec_add(struct timespec
*sum
,
93 const struct timespec
*a
, const struct timespec
*b
);
94 static void trace_run(void);
95 static unixctl_cb_func backtrace_cb
;
97 /* Initializes the timetracking module, if not already initialized. */
103 /* The best place to do this is probably a timeval_run() function.
104 * However, none exists and this function is usually so fast that doing it
105 * here seems fine for now. */
113 if (HAVE_EXECINFO_H
&& CACHE_TIME
) {
114 unixctl_command_register("backtrace", "", 0, 0, backtrace_cb
, NULL
);
119 if (!clock_gettime(CLOCK_MONOTONIC
, &monotonic_time
)) {
120 monotonic_clock
= CLOCK_MONOTONIC
;
122 monotonic_clock
= CLOCK_REALTIME
;
123 VLOG_DBG("monotonic timer not available");
126 set_up_signal(SA_RESTART
);
129 boot_time
= time_msec();
133 set_up_signal(int flags
)
137 memset(&sa
, 0, sizeof sa
);
138 sa
.sa_handler
= sigalrm_handler
;
139 sigemptyset(&sa
.sa_mask
);
141 xsigaction(SIGALRM
, &sa
, NULL
);
144 /* Remove SA_RESTART from the flags for SIGALRM, so that any system call that
145 * is interrupted by the periodic timer interrupt will return EINTR instead of
146 * continuing after the signal handler returns.
148 * time_disable_restart() and time_enable_restart() may be usefully wrapped
149 * around function calls that might otherwise block forever unless interrupted
152 * time_disable_restart();
153 * fcntl(fd, F_SETLKW, &lock);
154 * time_enable_restart();
157 time_disable_restart(void)
163 /* Add SA_RESTART to the flags for SIGALRM, so that any system call that
164 * is interrupted by the periodic timer interrupt will continue after the
165 * signal handler returns instead of returning EINTR. */
167 time_enable_restart(void)
170 set_up_signal(SA_RESTART
);
176 static timer_t timer_id
; /* "static" to avoid apparent memory leak. */
177 struct itimerspec itimer
;
183 if (timer_create(monotonic_clock
, NULL
, &timer_id
)) {
184 VLOG_FATAL("timer_create failed (%s)", strerror(errno
));
187 itimer
.it_interval
.tv_sec
= 0;
188 itimer
.it_interval
.tv_nsec
= TIME_UPDATE_INTERVAL
* 1000 * 1000;
189 itimer
.it_value
= itimer
.it_interval
;
191 if (timer_settime(timer_id
, 0, &itimer
, NULL
)) {
192 VLOG_FATAL("timer_settime failed (%s)", strerror(errno
));
196 /* Set up the interval timer, to ensure that time advances even without calling
199 * A child created with fork() does not inherit the parent's interval timer, so
200 * this function needs to be called from the child after fork(). */
212 clock_gettime(CLOCK_REALTIME
, &wall_time
);
217 refresh_monotonic(void)
222 if (monotonic_clock
== CLOCK_MONOTONIC
) {
223 clock_gettime(monotonic_clock
, &monotonic_time
);
225 refresh_wall_if_ticked();
226 monotonic_time
= wall_time
;
228 timespec_add(&monotonic_time
, &monotonic_time
, &warp_offset
);
230 monotonic_tick
= false;
234 /* Forces a refresh of the current time from the kernel. It is not usually
235 * necessary to call this function, since the time will be refreshed
236 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. If
237 * CACHE_TIME is false, we will always refresh the current time so this
238 * function has no effect. */
242 wall_tick
= monotonic_tick
= true;
245 /* Returns a monotonic timer, in seconds. */
249 refresh_monotonic_if_ticked();
250 return monotonic_time
.tv_sec
;
253 /* Returns the current time, in seconds. */
257 refresh_wall_if_ticked();
258 return wall_time
.tv_sec
;
261 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
265 refresh_monotonic_if_ticked();
266 return timespec_to_msec(&monotonic_time
);
269 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
273 refresh_wall_if_ticked();
274 return timespec_to_msec(&wall_time
);
277 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
280 time_timespec(struct timespec
*ts
)
282 refresh_monotonic_if_ticked();
283 *ts
= monotonic_time
;
286 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
289 time_wall_timespec(struct timespec
*ts
)
291 refresh_wall_if_ticked();
295 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
296 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
298 time_alarm(unsigned int secs
)
311 block_sigalrm(&oldsigs
);
312 deadline
= now
< LLONG_MAX
- msecs
? now
+ msecs
: LLONG_MAX
;
313 unblock_sigalrm(&oldsigs
);
316 /* Like poll(), except:
318 * - The timeout is specified as an absolute time, as defined by
319 * time_msec(), instead of a duration.
321 * - On error, returns a negative error code (instead of setting errno).
323 * - If interrupted by a signal, retries automatically until the original
324 * timeout is reached. (Because of this property, this function will
325 * never return -EINTR.)
327 * - As a side effect, refreshes the current time (like time_refresh()).
329 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
331 time_poll(struct pollfd
*pollfds
, int n_pollfds
, long long int timeout_when
,
334 static long long int last_wakeup
= 0;
342 log_poll_interval(last_wakeup
);
348 timeout_when
= MIN(timeout_when
, deadline
);
351 long long int now
= time_msec();
354 if (now
>= timeout_when
) {
356 } else if ((unsigned long long int) timeout_when
- now
> INT_MAX
) {
359 time_left
= timeout_when
- now
;
362 retval
= poll(pollfds
, n_pollfds
, time_left
);
368 if (deadline
<= time_msec()) {
369 fatal_signal_handler(SIGALRM
);
376 if (retval
!= -EINTR
) {
380 if (!blocked
&& CACHE_TIME
&& !backtrace_conn
) {
381 block_sigalrm(&oldsigs
);
386 unblock_sigalrm(&oldsigs
);
388 last_wakeup
= time_msec();
390 *elapsed
= last_wakeup
- start
;
395 sigalrm_handler(int sig_nr OVS_UNUSED
)
398 monotonic_tick
= true;
401 if (backtrace_conn
&& n_traces
< MAX_TRACES
) {
402 struct trace
*trace
= &traces
[n_traces
++];
403 trace
->n_frames
= backtrace(trace
->backtrace
,
404 ARRAY_SIZE(trace
->backtrace
));
410 refresh_wall_if_ticked(void)
412 if (!CACHE_TIME
|| wall_tick
) {
418 refresh_monotonic_if_ticked(void)
420 if (!CACHE_TIME
|| monotonic_tick
) {
426 block_sigalrm(sigset_t
*oldsigs
)
429 sigemptyset(&sigalrm
);
430 sigaddset(&sigalrm
, SIGALRM
);
431 xsigprocmask(SIG_BLOCK
, &sigalrm
, oldsigs
);
435 unblock_sigalrm(const sigset_t
*oldsigs
)
437 xsigprocmask(SIG_SETMASK
, oldsigs
, NULL
);
441 timespec_to_msec(const struct timespec
*ts
)
443 return (long long int) ts
->tv_sec
* 1000 + ts
->tv_nsec
/ (1000 * 1000);
447 timeval_to_msec(const struct timeval
*tv
)
449 return (long long int) tv
->tv_sec
* 1000 + tv
->tv_usec
/ 1000;
452 /* Returns the monotonic time at which the "time" module was initialized, in
462 xgettimeofday(struct timeval
*tv
)
464 if (gettimeofday(tv
, NULL
) == -1) {
465 VLOG_FATAL("gettimeofday failed (%s)", strerror(errno
));
470 timeval_diff_msec(const struct timeval
*a
, const struct timeval
*b
)
472 return timeval_to_msec(a
) - timeval_to_msec(b
);
476 timespec_add(struct timespec
*sum
,
477 const struct timespec
*a
,
478 const struct timespec
*b
)
482 tmp
.tv_sec
= a
->tv_sec
+ b
->tv_sec
;
483 tmp
.tv_nsec
= a
->tv_nsec
+ b
->tv_nsec
;
484 if (tmp
.tv_nsec
>= 1000 * 1000 * 1000) {
485 tmp
.tv_nsec
-= 1000 * 1000 * 1000;
493 log_poll_interval(long long int last_wakeup
)
495 long long int interval
= time_msec() - last_wakeup
;
497 if (interval
>= 1000) {
498 const struct rusage
*last_rusage
= get_recent_rusage();
499 struct rusage rusage
;
501 getrusage(RUSAGE_SELF
, &rusage
);
502 VLOG_WARN("Unreasonably long %lldms poll interval"
503 " (%lldms user, %lldms system)",
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 if (rusage
.ru_minflt
> last_rusage
->ru_minflt
510 || rusage
.ru_majflt
> last_rusage
->ru_majflt
) {
511 VLOG_WARN("faults: %ld minor, %ld major",
512 rusage
.ru_minflt
- last_rusage
->ru_minflt
,
513 rusage
.ru_majflt
- last_rusage
->ru_majflt
);
515 if (rusage
.ru_inblock
> last_rusage
->ru_inblock
516 || rusage
.ru_oublock
> last_rusage
->ru_oublock
) {
517 VLOG_WARN("disk: %ld reads, %ld writes",
518 rusage
.ru_inblock
- last_rusage
->ru_inblock
,
519 rusage
.ru_oublock
- last_rusage
->ru_oublock
);
521 if (rusage
.ru_nvcsw
> last_rusage
->ru_nvcsw
522 || rusage
.ru_nivcsw
> last_rusage
->ru_nivcsw
) {
523 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
524 rusage
.ru_nvcsw
- last_rusage
->ru_nvcsw
,
525 rusage
.ru_nivcsw
- last_rusage
->ru_nivcsw
);
531 /* CPU usage tracking. */
534 long long int when
; /* Time that this sample was taken. */
535 unsigned long long int cpu
; /* Total user+system CPU usage when sampled. */
538 static struct rusage recent_rusage
;
539 static struct cpu_usage older
= { LLONG_MIN
, 0 };
540 static struct cpu_usage newer
= { LLONG_MIN
, 0 };
541 static int cpu_usage
= -1;
543 static struct rusage
*
544 get_recent_rusage(void)
546 return &recent_rusage
;
555 getrusage(RUSAGE_SELF
, &recent_rusage
);
557 if (now
>= newer
.when
+ 3 * 1000) {
560 newer
.cpu
= (timeval_to_msec(&recent_rusage
.ru_utime
) +
561 timeval_to_msec(&recent_rusage
.ru_stime
));
563 if (older
.when
!= LLONG_MIN
&& newer
.cpu
> older
.cpu
) {
564 unsigned int dividend
= newer
.cpu
- older
.cpu
;
565 unsigned int divisor
= (newer
.when
- older
.when
) / 100;
566 cpu_usage
= divisor
> 0 ? dividend
/ divisor
: -1;
573 /* Returns an estimate of this process's CPU usage, as a percentage, over the
574 * past few seconds of wall-clock time. Returns -1 if no estimate is available
575 * (which will happen if the process has not been running long enough to have
576 * an estimate, and can happen for other reasons as well). */
587 if (backtrace_conn
&& n_traces
>= MAX_TRACES
) {
588 struct unixctl_conn
*reply_conn
= backtrace_conn
;
589 struct ds ds
= DS_EMPTY_INITIALIZER
;
593 block_sigalrm(&oldsigs
);
595 for (i
= 0; i
< n_traces
; i
++) {
596 struct trace
*trace
= &traces
[i
];
600 frame_strs
= backtrace_symbols(trace
->backtrace
, trace
->n_frames
);
602 ds_put_format(&ds
, "Backtrace %zu\n", i
+ 1);
603 for (j
= 0; j
< trace
->n_frames
; j
++) {
604 ds_put_format(&ds
, "%s\n", frame_strs
[j
]);
606 ds_put_cstr(&ds
, "\n");
614 backtrace_conn
= NULL
;
616 unblock_sigalrm(&oldsigs
);
618 unixctl_command_reply(reply_conn
, ds_cstr(&ds
));
624 /* Unixctl interface. */
626 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
627 * advancing, except due to later calls to "time/warp". */
629 timeval_stop_cb(struct unixctl_conn
*conn
,
630 int argc OVS_UNUSED
, const char *argv
[] OVS_UNUSED
,
631 void *aux OVS_UNUSED
)
634 unixctl_command_reply(conn
, NULL
);
637 /* "time/warp MSECS" advances the current monotonic time by the specified
638 * number of milliseconds. Unless "time/stop" has also been executed, the
639 * monotonic clock continues to tick forward at the normal rate afterward.
641 * Does not affect wall clock readings. */
643 timeval_warp_cb(struct unixctl_conn
*conn
,
644 int argc OVS_UNUSED
, const char *argv
[], void *aux OVS_UNUSED
)
649 msecs
= atoi(argv
[1]);
651 unixctl_command_reply_error(conn
, "invalid MSECS");
655 ts
.tv_sec
= msecs
/ 1000;
656 ts
.tv_nsec
= (msecs
% 1000) * 1000 * 1000;
657 timespec_add(&warp_offset
, &warp_offset
, &ts
);
658 timespec_add(&monotonic_time
, &monotonic_time
, &ts
);
659 unixctl_command_reply(conn
, "warped");
663 backtrace_cb(struct unixctl_conn
*conn
,
664 int argc OVS_UNUSED
, const char *argv
[] OVS_UNUSED
,
665 void *aux OVS_UNUSED
)
669 assert(HAVE_EXECINFO_H
&& CACHE_TIME
);
671 if (backtrace_conn
) {
672 unixctl_command_reply_error(conn
, "In Use");
677 block_sigalrm(&oldsigs
);
678 backtrace_conn
= conn
;
679 traces
= xmalloc(MAX_TRACES
* sizeof *traces
);
681 unblock_sigalrm(&oldsigs
);
685 timeval_dummy_register(void)
687 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb
, NULL
);
688 unixctl_command_register("time/warp", "MSECS", 1, 1,
689 timeval_warp_cb
, NULL
);