2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 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 "openvswitch/dynamic-string.h"
31 #include "fatal-signal.h"
33 #include "openvswitch/hmap.h"
35 #include "ovs-thread.h"
40 #include "openvswitch/vlog.h"
42 VLOG_DEFINE_THIS_MODULE(timeval
);
44 #if !defined(HAVE_CLOCK_GETTIME)
45 typedef unsigned int clockid_t
;
46 static int clock_gettime(clock_t id
, struct timespec
*ts
);
48 #ifndef CLOCK_MONOTONIC
49 #define CLOCK_MONOTONIC 1
52 #ifndef CLOCK_REALTIME
53 #define CLOCK_REALTIME 2
55 #endif /* !defined(HAVE_CLOCK_GETTIME) */
58 /* Number of 100 ns intervals from January 1, 1601 till January 1, 1970. */
59 const static unsigned long long unix_epoch
= 116444736000000000;
62 /* Structure set by unixctl time/warp command. */
64 struct unixctl_conn
*conn
; /* Connection waiting for warp response. */
65 long long int total_warp
; /* Total offset to be added to monotonic time. */
66 long long int warp
; /* 'total_warp' offset done in steps of 'warp'. */
67 unsigned int main_thread_id
; /* Identification for the main thread. */
71 clockid_t id
; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
73 /* Features for use by unit tests. Protected by 'mutex'. */
74 atomic_bool slow_path
; /* True if warped or stopped. */
75 bool stopped OVS_GUARDED
; /* Disable real-time updates if true. */
76 struct ovs_mutex mutex
;
77 struct timespec warp OVS_GUARDED
; /* Offset added for unit tests. */
78 struct timespec cache OVS_GUARDED
; /* Last time read from kernel. */
79 struct large_warp large_warp OVS_GUARDED
; /* Connection information waiting
84 static struct clock monotonic_clock
; /* CLOCK_MONOTONIC, if available. */
85 static struct clock wall_clock
; /* CLOCK_REALTIME. */
87 /* The monotonic time at which the time module was initialized. */
88 static long long int boot_time
;
90 /* True only when timeval_dummy_register() is called. */
91 static bool timewarp_enabled
;
92 /* Reference to the seq struct. Threads other than main thread can
93 * wait on timewarp_seq and be waken up when time is warped. */
94 static struct seq
*timewarp_seq
;
95 /* Last value of 'timewarp_seq'. */
96 DEFINE_STATIC_PER_THREAD_DATA(uint64_t, last_seq
, 0);
98 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
100 static long long int deadline
= LLONG_MAX
;
102 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
104 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup
, 0);
106 static void log_poll_interval(long long int last_wakeup
);
107 static struct rusage
*get_recent_rusage(void);
108 static int getrusage_thread(struct rusage
*);
109 static void refresh_rusage(void);
110 static void timespec_add(struct timespec
*sum
,
111 const struct timespec
*a
, const struct timespec
*b
);
114 init_clock(struct clock
*c
, clockid_t id
)
116 memset(c
, 0, sizeof *c
);
118 ovs_mutex_init(&c
->mutex
);
119 atomic_init(&c
->slow_path
, false);
120 xclock_gettime(c
->id
, &c
->cache
);
130 timewarp_seq
= seq_create();
131 init_clock(&monotonic_clock
, (!clock_gettime(CLOCK_MONOTONIC
, &ts
)
134 init_clock(&wall_clock
, CLOCK_REALTIME
);
135 boot_time
= timespec_to_msec(&monotonic_clock
.cache
);
138 /* Initializes the timetracking module, if not already initialized. */
142 static pthread_once_t once
= PTHREAD_ONCE_INIT
;
143 pthread_once(&once
, do_init_time
);
147 time_timespec__(struct clock
*c
, struct timespec
*ts
)
153 atomic_read_relaxed(&c
->slow_path
, &slow_path
);
155 xclock_gettime(c
->id
, ts
);
157 struct timespec warp
;
158 struct timespec cache
;
161 ovs_mutex_lock(&c
->mutex
);
162 stopped
= c
->stopped
;
165 ovs_mutex_unlock(&c
->mutex
);
168 xclock_gettime(c
->id
, &cache
);
170 timespec_add(ts
, &cache
, &warp
);
174 /* Stores a monotonic timer into '*ts'. */
176 time_timespec(struct timespec
*ts
)
178 time_timespec__(&monotonic_clock
, ts
);
181 /* Stores the current time into '*ts'. */
183 time_wall_timespec(struct timespec
*ts
)
185 time_timespec__(&wall_clock
, ts
);
189 time_sec__(struct clock
*c
)
193 time_timespec__(c
, &ts
);
197 /* Returns a monotonic timer, in seconds. */
201 return time_sec__(&monotonic_clock
);
204 /* Returns the current time, in seconds. */
208 return time_sec__(&wall_clock
);
212 time_msec__(struct clock
*c
)
216 time_timespec__(c
, &ts
);
217 return timespec_to_msec(&ts
);
220 /* Returns a monotonic timer, in ms. */
224 return time_msec__(&monotonic_clock
);
227 /* Returns the current time, in ms. */
231 return time_msec__(&wall_clock
);
235 time_usec__(struct clock
*c
)
239 time_timespec__(c
, &ts
);
240 return timespec_to_usec(&ts
);
243 /* Returns a monotonic timer, in microseconds. */
247 return time_usec__(&monotonic_clock
);
250 /* Returns the current time, in microseconds. */
254 return time_usec__(&wall_clock
);
257 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
258 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
260 time_alarm(unsigned int secs
)
265 assert_single_threaded();
269 msecs
= secs
* 1000LL;
270 deadline
= now
< LLONG_MAX
- msecs
? now
+ msecs
: LLONG_MAX
;
273 /* Like poll(), except:
275 * - The timeout is specified as an absolute time, as defined by
276 * time_msec(), instead of a duration.
278 * - On error, returns a negative error code (instead of setting errno).
280 * - If interrupted by a signal, retries automatically until the original
281 * timeout is reached. (Because of this property, this function will
282 * never return -EINTR.)
284 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
286 time_poll(struct pollfd
*pollfds
, int n_pollfds
, HANDLE
*handles OVS_UNUSED
,
287 long long int timeout_when
, int *elapsed
)
289 long long int *last_wakeup
= last_wakeup_get();
297 if (*last_wakeup
&& !thread_is_pmd()) {
298 log_poll_interval(*last_wakeup
);
302 timeout_when
= MIN(timeout_when
, deadline
);
303 quiescent
= ovsrcu_is_quiescent();
306 long long int now
= time_msec();
309 if (now
>= timeout_when
) {
311 } else if ((unsigned long long int) timeout_when
- now
> INT_MAX
) {
314 time_left
= timeout_when
- now
;
321 ovsrcu_quiesce_start();
326 retval
= poll(pollfds
, n_pollfds
, time_left
);
331 if (n_pollfds
> MAXIMUM_WAIT_OBJECTS
) {
332 VLOG_ERR("Cannot handle more than maximum wait objects\n");
333 } else if (n_pollfds
!= 0) {
334 retval
= WaitForMultipleObjects(n_pollfds
, handles
, FALSE
,
338 /* XXX This will be replace by a win error to errno
339 conversion function */
340 retval
= -WSAGetLastError();
345 if (!quiescent
&& time_left
) {
346 ovsrcu_quiesce_end();
349 if (deadline
<= time_msec()) {
351 fatal_signal_handler(SIGALRM
);
353 VLOG_ERR("wake up from WaitForMultipleObjects after deadline");
354 fatal_signal_handler(SIGTERM
);
362 if (retval
!= -EINTR
) {
366 *last_wakeup
= time_msec();
368 *elapsed
= *last_wakeup
- start
;
373 timespec_to_msec(const struct timespec
*ts
)
375 return (long long int) ts
->tv_sec
* 1000 + ts
->tv_nsec
/ (1000 * 1000);
379 timeval_to_msec(const struct timeval
*tv
)
381 return (long long int) tv
->tv_sec
* 1000 + tv
->tv_usec
/ 1000;
385 timespec_to_usec(const struct timespec
*ts
)
387 return (long long int) ts
->tv_sec
* 1000 * 1000 + ts
->tv_nsec
/ 1000;
391 timeval_to_usec(const struct timeval
*tv
)
393 return (long long int) tv
->tv_sec
* 1000 * 1000 + tv
->tv_usec
;
396 /* Returns the monotonic time at which the "time" module was initialized, in
406 static ULARGE_INTEGER
409 ULARGE_INTEGER current_time
;
410 FILETIME current_time_ft
;
412 /* Returns current time in UTC as a 64-bit value representing the number
413 * of 100-nanosecond intervals since January 1, 1601 . */
414 GetSystemTimePreciseAsFileTime(¤t_time_ft
);
415 current_time
.LowPart
= current_time_ft
.dwLowDateTime
;
416 current_time
.HighPart
= current_time_ft
.dwHighDateTime
;
422 clock_gettime(clock_t id
, struct timespec
*ts
)
424 if (id
== CLOCK_MONOTONIC
) {
425 static LARGE_INTEGER freq
;
429 if (!freq
.QuadPart
) {
430 /* Number of counts per second. */
431 QueryPerformanceFrequency(&freq
);
433 /* Total number of counts from a starting point. */
434 QueryPerformanceCounter(&count
);
436 /* Total nano seconds from a starting point. */
437 ns
= (double) count
.QuadPart
/ freq
.QuadPart
* 1000000000;
439 ts
->tv_sec
= count
.QuadPart
/ freq
.QuadPart
;
440 ts
->tv_nsec
= ns
% 1000000000;
441 } else if (id
== CLOCK_REALTIME
) {
442 ULARGE_INTEGER current_time
= xgetfiletime();
444 /* Time from Epoch to now. */
445 ts
->tv_sec
= (current_time
.QuadPart
- unix_epoch
) / 10000000;
446 ts
->tv_nsec
= ((current_time
.QuadPart
- unix_epoch
) %
456 #if defined(__MACH__) && !defined(HAVE_CLOCK_GETTIME)
457 #include <mach/clock.h>
458 #include <mach/mach.h>
460 clock_gettime(clock_t id
, struct timespec
*ts
)
466 if (id
== CLOCK_MONOTONIC
) {
468 } else if (id
== CLOCK_REALTIME
) {
469 cid
= CALENDAR_CLOCK
;
474 host_get_clock_service(mach_host_self(), cid
, &clk
);
475 clock_get_time(clk
, &mts
);
476 mach_port_deallocate(mach_task_self(), clk
);
477 ts
->tv_sec
= mts
.tv_sec
;
478 ts
->tv_nsec
= mts
.tv_nsec
;
485 xgettimeofday(struct timeval
*tv
)
488 if (gettimeofday(tv
, NULL
) == -1) {
489 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno
));
492 ULARGE_INTEGER current_time
= xgetfiletime();
494 tv
->tv_sec
= (current_time
.QuadPart
- unix_epoch
) / 10000000;
495 tv
->tv_usec
= ((current_time
.QuadPart
- unix_epoch
) %
501 xclock_gettime(clock_t id
, struct timespec
*ts
)
503 if (clock_gettime(id
, ts
) == -1) {
504 /* It seems like a bad idea to try to use vlog here because it is
505 * likely to try to check the current time. */
506 ovs_abort(errno
, "xclock_gettime() failed");
511 msec_to_timespec(long long int ms
, struct timespec
*ts
)
513 ts
->tv_sec
= ms
/ 1000;
514 ts
->tv_nsec
= (ms
% 1000) * 1000 * 1000;
518 nsec_to_timespec(long long int nsec
, struct timespec
*ts
)
521 ts
->tv_sec
= ts
->tv_nsec
= 0;
524 ts
->tv_sec
= nsec
/ (1000 * 1000 * 1000);
526 nsec
= nsec
% (1000 * 1000 * 1000);
527 /* This is to handle dates before epoch. */
528 if (OVS_UNLIKELY(nsec
< 0)) {
529 nsec
+= 1000 * 1000 * 1000;
539 struct clock
*c
= &monotonic_clock
;
540 struct timespec warp
;
542 ovs_mutex_lock(&c
->mutex
);
543 if (!c
->large_warp
.conn
) {
544 ovs_mutex_unlock(&c
->mutex
);
548 if (c
->large_warp
.total_warp
>= c
->large_warp
.warp
) {
549 msec_to_timespec(c
->large_warp
.warp
, &warp
);
550 timespec_add(&c
->warp
, &c
->warp
, &warp
);
551 c
->large_warp
.total_warp
-= c
->large_warp
.warp
;
552 } else if (c
->large_warp
.total_warp
) {
553 msec_to_timespec(c
->large_warp
.total_warp
, &warp
);
554 timespec_add(&c
->warp
, &c
->warp
, &warp
);
555 c
->large_warp
.total_warp
= 0;
557 /* c->large_warp.total_warp is 0. */
558 msec_to_timespec(c
->large_warp
.warp
, &warp
);
559 timespec_add(&c
->warp
, &c
->warp
, &warp
);
562 if (!c
->large_warp
.total_warp
) {
563 unixctl_command_reply(c
->large_warp
.conn
, "warped");
564 c
->large_warp
.conn
= NULL
;
567 ovs_mutex_unlock(&c
->mutex
);
568 seq_change(timewarp_seq
);
570 /* give threads (eg. monitor) some chances to run */
578 /* Perform work needed for "timewarp_seq"'s producer and consumers. */
582 /* The function is a no-op unless timeval_dummy_register() is called. */
583 if (timewarp_enabled
) {
584 unsigned int thread_id
;
585 ovs_mutex_lock(&monotonic_clock
.mutex
);
586 thread_id
= monotonic_clock
.large_warp
.main_thread_id
;
587 ovs_mutex_unlock(&monotonic_clock
.mutex
);
589 if (thread_id
!= ovsthread_id_self()) {
590 /* For threads other than the thread that changes the sequence,
592 uint64_t *last_seq
= last_seq_get();
594 *last_seq
= seq_read(timewarp_seq
);
595 seq_wait(timewarp_seq
, *last_seq
);
597 /* Work on adding the remaining warps. */
604 timeval_diff_msec(const struct timeval
*a
, const struct timeval
*b
)
606 return timeval_to_msec(a
) - timeval_to_msec(b
);
610 timespec_add(struct timespec
*sum
,
611 const struct timespec
*a
,
612 const struct timespec
*b
)
616 tmp
.tv_sec
= a
->tv_sec
+ b
->tv_sec
;
617 tmp
.tv_nsec
= a
->tv_nsec
+ b
->tv_nsec
;
618 if (tmp
.tv_nsec
>= 1000 * 1000 * 1000) {
619 tmp
.tv_nsec
-= 1000 * 1000 * 1000;
627 is_warped(const struct clock
*c
)
631 ovs_mutex_lock(&c
->mutex
);
632 warped
= monotonic_clock
.warp
.tv_sec
|| monotonic_clock
.warp
.tv_nsec
;
633 ovs_mutex_unlock(&c
->mutex
);
639 log_poll_interval(long long int last_wakeup
)
641 long long int interval
= time_msec() - last_wakeup
;
643 if (interval
>= 1000 && !is_warped(&monotonic_clock
)) {
644 const struct rusage
*last_rusage
= get_recent_rusage();
645 struct rusage rusage
;
647 if (!getrusage_thread(&rusage
)) {
648 VLOG_WARN("Unreasonably long %lldms poll interval"
649 " (%lldms user, %lldms system)",
651 timeval_diff_msec(&rusage
.ru_utime
,
652 &last_rusage
->ru_utime
),
653 timeval_diff_msec(&rusage
.ru_stime
,
654 &last_rusage
->ru_stime
));
656 if (rusage
.ru_minflt
> last_rusage
->ru_minflt
657 || rusage
.ru_majflt
> last_rusage
->ru_majflt
) {
658 VLOG_WARN("faults: %ld minor, %ld major",
659 rusage
.ru_minflt
- last_rusage
->ru_minflt
,
660 rusage
.ru_majflt
- last_rusage
->ru_majflt
);
662 if (rusage
.ru_inblock
> last_rusage
->ru_inblock
663 || rusage
.ru_oublock
> last_rusage
->ru_oublock
) {
664 VLOG_WARN("disk: %ld reads, %ld writes",
665 rusage
.ru_inblock
- last_rusage
->ru_inblock
,
666 rusage
.ru_oublock
- last_rusage
->ru_oublock
);
668 if (rusage
.ru_nvcsw
> last_rusage
->ru_nvcsw
669 || rusage
.ru_nivcsw
> last_rusage
->ru_nivcsw
) {
670 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
671 rusage
.ru_nvcsw
- last_rusage
->ru_nvcsw
,
672 rusage
.ru_nivcsw
- last_rusage
->ru_nivcsw
);
675 VLOG_WARN("Unreasonably long %lldms poll interval", interval
);
681 /* CPU usage tracking. */
684 long long int when
; /* Time that this sample was taken. */
685 unsigned long long int cpu
; /* Total user+system CPU usage when sampled. */
689 struct cpu_usage older
;
690 struct cpu_usage newer
;
693 struct rusage recent_rusage
;
695 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker
*, cpu_tracker_var
);
697 static struct cpu_tracker
*
698 get_cpu_tracker(void)
700 struct cpu_tracker
*t
= cpu_tracker_var_get();
702 t
= xzalloc(sizeof *t
);
703 t
->older
.when
= LLONG_MIN
;
704 t
->newer
.when
= LLONG_MIN
;
705 cpu_tracker_var_set_unsafe(t
);
710 static struct rusage
*
711 get_recent_rusage(void)
713 return &get_cpu_tracker()->recent_rusage
;
717 getrusage_thread(struct rusage
*rusage OVS_UNUSED
)
720 return getrusage(RUSAGE_THREAD
, rusage
);
730 struct cpu_tracker
*t
= get_cpu_tracker();
731 struct rusage
*recent_rusage
= &t
->recent_rusage
;
733 if (!getrusage_thread(recent_rusage
)) {
734 long long int now
= time_msec();
735 if (now
>= t
->newer
.when
+ 3 * 1000) {
738 t
->newer
.cpu
= (timeval_to_msec(&recent_rusage
->ru_utime
) +
739 timeval_to_msec(&recent_rusage
->ru_stime
));
741 if (t
->older
.when
!= LLONG_MIN
&& t
->newer
.cpu
> t
->older
.cpu
) {
742 unsigned int dividend
= t
->newer
.cpu
- t
->older
.cpu
;
743 unsigned int divisor
= (t
->newer
.when
- t
->older
.when
) / 100;
744 t
->cpu_usage
= divisor
> 0 ? dividend
/ divisor
: -1;
752 /* Returns an estimate of this process's CPU usage, as a percentage, over the
753 * past few seconds of wall-clock time. Returns -1 if no estimate is available
754 * (which will happen if the process has not been running long enough to have
755 * an estimate, and can happen for other reasons as well). */
759 return get_cpu_tracker()->cpu_usage
;
762 /* Unixctl interface. */
764 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
765 * advancing, except due to later calls to "time/warp". */
767 timeval_stop_cb(struct unixctl_conn
*conn
,
768 int argc OVS_UNUSED
, const char *argv
[] OVS_UNUSED
,
769 void *aux OVS_UNUSED
)
771 ovs_mutex_lock(&monotonic_clock
.mutex
);
772 atomic_store_relaxed(&monotonic_clock
.slow_path
, true);
773 monotonic_clock
.stopped
= true;
774 xclock_gettime(monotonic_clock
.id
, &monotonic_clock
.cache
);
775 ovs_mutex_unlock(&monotonic_clock
.mutex
);
777 unixctl_command_reply(conn
, NULL
);
780 /* "time/warp MSECS" advances the current monotonic time by the specified
781 * number of milliseconds. Unless "time/stop" has also been executed, the
782 * monotonic clock continues to tick forward at the normal rate afterward.
784 * "time/warp LARGE_MSECS MSECS" is a variation of the above command. It
785 * advances the current monotonic time by LARGE_MSECS. This is done MSECS
786 * at a time in each run of the main thread. This gives other threads
787 * time to run after the clock has been advanced by MSECS.
789 * Does not affect wall clock readings. */
791 timeval_warp_cb(struct unixctl_conn
*conn
,
792 int argc OVS_UNUSED
, const char *argv
[], void *aux OVS_UNUSED
)
794 long long int total_warp
= argc
> 2 ? atoll(argv
[1]) : 0;
795 long long int msecs
= argc
> 2 ? atoll(argv
[2]) : atoll(argv
[1]);
796 if (msecs
<= 0 || total_warp
< 0) {
797 unixctl_command_reply_error(conn
, "invalid MSECS");
801 ovs_mutex_lock(&monotonic_clock
.mutex
);
802 if (monotonic_clock
.large_warp
.conn
) {
803 ovs_mutex_unlock(&monotonic_clock
.mutex
);
804 unixctl_command_reply_error(conn
, "A previous warp in progress");
807 atomic_store_relaxed(&monotonic_clock
.slow_path
, true);
808 monotonic_clock
.large_warp
.conn
= conn
;
809 monotonic_clock
.large_warp
.total_warp
= total_warp
;
810 monotonic_clock
.large_warp
.warp
= msecs
;
811 monotonic_clock
.large_warp
.main_thread_id
= ovsthread_id_self();
812 ovs_mutex_unlock(&monotonic_clock
.mutex
);
818 timeval_dummy_register(void)
820 timewarp_enabled
= true;
821 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb
, NULL
);
822 unixctl_command_register("time/warp", "[large_msecs] msecs", 1, 2,
823 timeval_warp_cb
, NULL
);
828 /* strftime() with an extension for high-resolution timestamps. Any '#'s in
829 * 'format' will be replaced by subseconds, e.g. use "%S.###" to obtain results
832 strftime_msec(char *s
, size_t max
, const char *format
,
833 const struct tm_msec
*tm
)
837 /* Visual Studio 2013's behavior is to crash when 0 is passed as second
838 * argument to strftime. */
839 n
= max
? strftime(s
, max
, format
, &tm
->tm
) : 0;
844 sprintf(decimals
, "%03d", tm
->msec
);
845 for (p
= strchr(s
, '#'); p
; p
= strchr(p
, '#')) {
848 *p
++ = *d
? *d
++ : '0';
857 localtime_msec(long long int now
, struct tm_msec
*result
)
859 time_t now_sec
= now
/ 1000;
860 localtime_r(&now_sec
, &result
->tm
);
861 result
->msec
= now
% 1000;
866 gmtime_msec(long long int now
, struct tm_msec
*result
)
868 time_t now_sec
= now
/ 1000;
869 gmtime_r(&now_sec
, &result
->tm
);
870 result
->msec
= now
% 1000;