]> git.proxmox.com Git - mirror_ovs.git/blob - lib/timeval.c
dpctl: Add the option 'pmd' for dump-flows.
[mirror_ovs.git] / lib / timeval.c
1 /*
2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Nicira, Inc.
3 *
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:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 #include <config.h>
18 #include "timeval.h"
19 #include <errno.h>
20 #include <poll.h>
21 #include <pthread.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/time.h>
26 #include <sys/resource.h>
27 #include <unistd.h>
28 #include "coverage.h"
29 #include "dummy.h"
30 #include "openvswitch/dynamic-string.h"
31 #include "fatal-signal.h"
32 #include "hash.h"
33 #include "openvswitch/hmap.h"
34 #include "ovs-rcu.h"
35 #include "ovs-thread.h"
36 #include "signals.h"
37 #include "seq.h"
38 #include "unixctl.h"
39 #include "util.h"
40 #include "openvswitch/vlog.h"
41
42 VLOG_DEFINE_THIS_MODULE(timeval);
43
44 #if !defined(HAVE_CLOCK_GETTIME)
45 typedef unsigned int clockid_t;
46 static int clock_gettime(clock_t id, struct timespec *ts);
47
48 #ifndef CLOCK_MONOTONIC
49 #define CLOCK_MONOTONIC 1
50 #endif
51
52 #ifndef CLOCK_REALTIME
53 #define CLOCK_REALTIME 2
54 #endif
55 #endif /* !defined(HAVE_CLOCK_GETTIME) */
56
57 #ifdef _WIN32
58 /* Number of 100 ns intervals from January 1, 1601 till January 1, 1970. */
59 const static unsigned long long unix_epoch = 116444736000000000;
60 #endif /* _WIN32 */
61
62 /* Structure set by unixctl time/warp command. */
63 struct large_warp {
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. */
68 };
69
70 struct clock {
71 clockid_t id; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
72
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
80 for warp response. */
81 };
82
83 /* Our clocks. */
84 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
85 static struct clock wall_clock; /* CLOCK_REALTIME. */
86
87 /* The monotonic time at which the time module was initialized. */
88 static long long int boot_time;
89
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);
97
98 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
99 * LLONG_MAX). */
100 static long long int deadline = LLONG_MAX;
101
102 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
103 * up. */
104 DEFINE_STATIC_PER_THREAD_DATA(long long int, last_wakeup, 0);
105
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);
112
113 static void
114 init_clock(struct clock *c, clockid_t id)
115 {
116 memset(c, 0, sizeof *c);
117 c->id = id;
118 ovs_mutex_init(&c->mutex);
119 atomic_init(&c->slow_path, false);
120 xclock_gettime(c->id, &c->cache);
121 }
122
123 static void
124 do_init_time(void)
125 {
126 struct timespec ts;
127
128 coverage_init();
129
130 timewarp_seq = seq_create();
131 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
132 ? CLOCK_MONOTONIC
133 : CLOCK_REALTIME));
134 init_clock(&wall_clock, CLOCK_REALTIME);
135 boot_time = timespec_to_msec(&monotonic_clock.cache);
136 }
137
138 /* Initializes the timetracking module, if not already initialized. */
139 static void
140 time_init(void)
141 {
142 static pthread_once_t once = PTHREAD_ONCE_INIT;
143 pthread_once(&once, do_init_time);
144 }
145
146 static void
147 time_timespec__(struct clock *c, struct timespec *ts)
148 {
149 bool slow_path;
150
151 time_init();
152
153 atomic_read_relaxed(&c->slow_path, &slow_path);
154 if (!slow_path) {
155 xclock_gettime(c->id, ts);
156 } else {
157 struct timespec warp;
158 struct timespec cache;
159 bool stopped;
160
161 ovs_mutex_lock(&c->mutex);
162 stopped = c->stopped;
163 warp = c->warp;
164 cache = c->cache;
165 ovs_mutex_unlock(&c->mutex);
166
167 if (!stopped) {
168 xclock_gettime(c->id, &cache);
169 }
170 timespec_add(ts, &cache, &warp);
171 }
172 }
173
174 /* Stores a monotonic timer into '*ts'. */
175 void
176 time_timespec(struct timespec *ts)
177 {
178 time_timespec__(&monotonic_clock, ts);
179 }
180
181 /* Stores the current time into '*ts'. */
182 void
183 time_wall_timespec(struct timespec *ts)
184 {
185 time_timespec__(&wall_clock, ts);
186 }
187
188 static time_t
189 time_sec__(struct clock *c)
190 {
191 struct timespec ts;
192
193 time_timespec__(c, &ts);
194 return ts.tv_sec;
195 }
196
197 /* Returns a monotonic timer, in seconds. */
198 time_t
199 time_now(void)
200 {
201 return time_sec__(&monotonic_clock);
202 }
203
204 /* Returns the current time, in seconds. */
205 time_t
206 time_wall(void)
207 {
208 return time_sec__(&wall_clock);
209 }
210
211 static long long int
212 time_msec__(struct clock *c)
213 {
214 struct timespec ts;
215
216 time_timespec__(c, &ts);
217 return timespec_to_msec(&ts);
218 }
219
220 /* Returns a monotonic timer, in ms. */
221 long long int
222 time_msec(void)
223 {
224 return time_msec__(&monotonic_clock);
225 }
226
227 /* Returns the current time, in ms. */
228 long long int
229 time_wall_msec(void)
230 {
231 return time_msec__(&wall_clock);
232 }
233
234 static long long int
235 time_usec__(struct clock *c)
236 {
237 struct timespec ts;
238
239 time_timespec__(c, &ts);
240 return timespec_to_usec(&ts);
241 }
242
243 /* Returns a monotonic timer, in microseconds. */
244 long long int
245 time_usec(void)
246 {
247 return time_usec__(&monotonic_clock);
248 }
249
250 /* Returns the current time, in microseconds. */
251 long long int
252 time_wall_usec(void)
253 {
254 return time_usec__(&wall_clock);
255 }
256
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. */
259 void
260 time_alarm(unsigned int secs)
261 {
262 long long int now;
263 long long int msecs;
264
265 assert_single_threaded();
266 time_init();
267
268 now = time_msec();
269 msecs = secs * 1000LL;
270 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
271 }
272
273 /* Like poll(), except:
274 *
275 * - The timeout is specified as an absolute time, as defined by
276 * time_msec(), instead of a duration.
277 *
278 * - On error, returns a negative error code (instead of setting errno).
279 *
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.)
283 *
284 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
285 int
286 time_poll(struct pollfd *pollfds, int n_pollfds, HANDLE *handles OVS_UNUSED,
287 long long int timeout_when, int *elapsed)
288 {
289 long long int *last_wakeup = last_wakeup_get();
290 long long int start;
291 bool quiescent;
292 int retval = 0;
293
294 time_init();
295 coverage_clear();
296 coverage_run();
297 if (*last_wakeup && !thread_is_pmd()) {
298 log_poll_interval(*last_wakeup);
299 }
300 start = time_msec();
301
302 timeout_when = MIN(timeout_when, deadline);
303 quiescent = ovsrcu_is_quiescent();
304
305 for (;;) {
306 long long int now = time_msec();
307 int time_left;
308
309 if (now >= timeout_when) {
310 time_left = 0;
311 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
312 time_left = INT_MAX;
313 } else {
314 time_left = timeout_when - now;
315 }
316
317 if (!quiescent) {
318 if (!time_left) {
319 ovsrcu_quiesce();
320 } else {
321 ovsrcu_quiesce_start();
322 }
323 }
324
325 #ifndef _WIN32
326 retval = poll(pollfds, n_pollfds, time_left);
327 if (retval < 0) {
328 retval = -errno;
329 }
330 #else
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,
335 time_left);
336 }
337 if (retval < 0) {
338 /* XXX This will be replace by a win error to errno
339 conversion function */
340 retval = -WSAGetLastError();
341 retval = -EINVAL;
342 }
343 #endif
344
345 if (!quiescent && time_left) {
346 ovsrcu_quiesce_end();
347 }
348
349 if (deadline <= time_msec()) {
350 #ifndef _WIN32
351 fatal_signal_handler(SIGALRM);
352 #else
353 VLOG_ERR("wake up from WaitForMultipleObjects after deadline");
354 fatal_signal_handler(SIGTERM);
355 #endif
356 if (retval < 0) {
357 retval = 0;
358 }
359 break;
360 }
361
362 if (retval != -EINTR) {
363 break;
364 }
365 }
366 *last_wakeup = time_msec();
367 refresh_rusage();
368 *elapsed = *last_wakeup - start;
369 return retval;
370 }
371
372 long long int
373 timespec_to_msec(const struct timespec *ts)
374 {
375 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
376 }
377
378 long long int
379 timeval_to_msec(const struct timeval *tv)
380 {
381 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
382 }
383
384 long long int
385 timespec_to_usec(const struct timespec *ts)
386 {
387 return (long long int) ts->tv_sec * 1000 * 1000 + ts->tv_nsec / 1000;
388 }
389
390 long long int
391 timeval_to_usec(const struct timeval *tv)
392 {
393 return (long long int) tv->tv_sec * 1000 * 1000 + tv->tv_usec;
394 }
395
396 /* Returns the monotonic time at which the "time" module was initialized, in
397 * milliseconds. */
398 long long int
399 time_boot_msec(void)
400 {
401 time_init();
402 return boot_time;
403 }
404
405 #ifdef _WIN32
406 static ULARGE_INTEGER
407 xgetfiletime(void)
408 {
409 ULARGE_INTEGER current_time;
410 FILETIME current_time_ft;
411
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(&current_time_ft);
415 current_time.LowPart = current_time_ft.dwLowDateTime;
416 current_time.HighPart = current_time_ft.dwHighDateTime;
417
418 return current_time;
419 }
420
421 static int
422 clock_gettime(clock_t id, struct timespec *ts)
423 {
424 if (id == CLOCK_MONOTONIC) {
425 static LARGE_INTEGER freq;
426 LARGE_INTEGER count;
427 long long int ns;
428
429 if (!freq.QuadPart) {
430 /* Number of counts per second. */
431 QueryPerformanceFrequency(&freq);
432 }
433 /* Total number of counts from a starting point. */
434 QueryPerformanceCounter(&count);
435
436 /* Total nano seconds from a starting point. */
437 ns = (double) count.QuadPart / freq.QuadPart * 1000000000;
438
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();
443
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) %
447 10000000) * 100;
448 } else {
449 return -1;
450 }
451
452 return 0;
453 }
454 #endif /* _WIN32 */
455
456 #if defined(__MACH__) && !defined(HAVE_CLOCK_GETTIME)
457 #include <mach/clock.h>
458 #include <mach/mach.h>
459 static int
460 clock_gettime(clock_t id, struct timespec *ts)
461 {
462 mach_timespec_t mts;
463 clock_serv_t clk;
464 clock_id_t cid;
465
466 if (id == CLOCK_MONOTONIC) {
467 cid = SYSTEM_CLOCK;
468 } else if (id == CLOCK_REALTIME) {
469 cid = CALENDAR_CLOCK;
470 } else {
471 return -1;
472 }
473
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;
479
480 return 0;
481 }
482 #endif
483
484 void
485 xgettimeofday(struct timeval *tv)
486 {
487 #ifndef _WIN32
488 if (gettimeofday(tv, NULL) == -1) {
489 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
490 }
491 #else
492 ULARGE_INTEGER current_time = xgetfiletime();
493
494 tv->tv_sec = (current_time.QuadPart - unix_epoch) / 10000000;
495 tv->tv_usec = ((current_time.QuadPart - unix_epoch) %
496 10000000) / 10;
497 #endif
498 }
499
500 void
501 xclock_gettime(clock_t id, struct timespec *ts)
502 {
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");
507 }
508 }
509
510 static void
511 msec_to_timespec(long long int ms, struct timespec *ts)
512 {
513 ts->tv_sec = ms / 1000;
514 ts->tv_nsec = (ms % 1000) * 1000 * 1000;
515 }
516
517 void
518 nsec_to_timespec(long long int nsec, struct timespec *ts)
519 {
520 if (!nsec) {
521 ts->tv_sec = ts->tv_nsec = 0;
522 return;
523 }
524 ts->tv_sec = nsec / (1000 * 1000 * 1000);
525
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;
530 ts->tv_sec--;
531 }
532
533 ts->tv_nsec = nsec;
534 }
535
536 static void
537 timewarp_work(void)
538 {
539 struct clock *c = &monotonic_clock;
540 struct timespec warp;
541
542 ovs_mutex_lock(&c->mutex);
543 if (!c->large_warp.conn) {
544 ovs_mutex_unlock(&c->mutex);
545 return;
546 }
547
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;
556 } else {
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);
560 }
561
562 if (!c->large_warp.total_warp) {
563 unixctl_command_reply(c->large_warp.conn, "warped");
564 c->large_warp.conn = NULL;
565 }
566
567 ovs_mutex_unlock(&c->mutex);
568 seq_change(timewarp_seq);
569
570 /* give threads (eg. monitor) some chances to run */
571 #ifndef _WIN32
572 poll(NULL, 0, 10);
573 #else
574 Sleep(10);
575 #endif
576 }
577
578 /* Perform work needed for "timewarp_seq"'s producer and consumers. */
579 void
580 timewarp_run(void)
581 {
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);
588
589 if (thread_id != ovsthread_id_self()) {
590 /* For threads other than the thread that changes the sequence,
591 * wait on it. */
592 uint64_t *last_seq = last_seq_get();
593
594 *last_seq = seq_read(timewarp_seq);
595 seq_wait(timewarp_seq, *last_seq);
596 } else {
597 /* Work on adding the remaining warps. */
598 timewarp_work();
599 }
600 }
601 }
602
603 static long long int
604 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
605 {
606 return timeval_to_msec(a) - timeval_to_msec(b);
607 }
608
609 static void
610 timespec_add(struct timespec *sum,
611 const struct timespec *a,
612 const struct timespec *b)
613 {
614 struct timespec tmp;
615
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;
620 tmp.tv_sec++;
621 }
622
623 *sum = tmp;
624 }
625
626 static bool
627 is_warped(const struct clock *c)
628 {
629 bool warped;
630
631 ovs_mutex_lock(&c->mutex);
632 warped = monotonic_clock.warp.tv_sec || monotonic_clock.warp.tv_nsec;
633 ovs_mutex_unlock(&c->mutex);
634
635 return warped;
636 }
637
638 static void
639 log_poll_interval(long long int last_wakeup)
640 {
641 long long int interval = time_msec() - last_wakeup;
642
643 if (interval >= 1000 && !is_warped(&monotonic_clock)) {
644 const struct rusage *last_rusage = get_recent_rusage();
645 struct rusage rusage;
646
647 if (!getrusage_thread(&rusage)) {
648 VLOG_WARN("Unreasonably long %lldms poll interval"
649 " (%lldms user, %lldms system)",
650 interval,
651 timeval_diff_msec(&rusage.ru_utime,
652 &last_rusage->ru_utime),
653 timeval_diff_msec(&rusage.ru_stime,
654 &last_rusage->ru_stime));
655
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);
661 }
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);
667 }
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);
673 }
674 } else {
675 VLOG_WARN("Unreasonably long %lldms poll interval", interval);
676 }
677 coverage_log();
678 }
679 }
680 \f
681 /* CPU usage tracking. */
682
683 struct cpu_usage {
684 long long int when; /* Time that this sample was taken. */
685 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
686 };
687
688 struct cpu_tracker {
689 struct cpu_usage older;
690 struct cpu_usage newer;
691 int cpu_usage;
692
693 struct rusage recent_rusage;
694 };
695 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
696
697 static struct cpu_tracker *
698 get_cpu_tracker(void)
699 {
700 struct cpu_tracker *t = cpu_tracker_var_get();
701 if (!t) {
702 t = xzalloc(sizeof *t);
703 t->older.when = LLONG_MIN;
704 t->newer.when = LLONG_MIN;
705 cpu_tracker_var_set_unsafe(t);
706 }
707 return t;
708 }
709
710 static struct rusage *
711 get_recent_rusage(void)
712 {
713 return &get_cpu_tracker()->recent_rusage;
714 }
715
716 static int
717 getrusage_thread(struct rusage *rusage OVS_UNUSED)
718 {
719 #ifdef RUSAGE_THREAD
720 return getrusage(RUSAGE_THREAD, rusage);
721 #else
722 errno = EINVAL;
723 return -1;
724 #endif
725 }
726
727 static void
728 refresh_rusage(void)
729 {
730 struct cpu_tracker *t = get_cpu_tracker();
731 struct rusage *recent_rusage = &t->recent_rusage;
732
733 if (!getrusage_thread(recent_rusage)) {
734 long long int now = time_msec();
735 if (now >= t->newer.when + 3 * 1000) {
736 t->older = t->newer;
737 t->newer.when = now;
738 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
739 timeval_to_msec(&recent_rusage->ru_stime));
740
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;
745 } else {
746 t->cpu_usage = -1;
747 }
748 }
749 }
750 }
751
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). */
756 int
757 get_cpu_usage(void)
758 {
759 return get_cpu_tracker()->cpu_usage;
760 }
761 \f
762 /* Unixctl interface. */
763
764 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
765 * advancing, except due to later calls to "time/warp". */
766 static void
767 timeval_stop_cb(struct unixctl_conn *conn,
768 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
769 void *aux OVS_UNUSED)
770 {
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);
776
777 unixctl_command_reply(conn, NULL);
778 }
779
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.
783 *
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.
788 *
789 * Does not affect wall clock readings. */
790 static void
791 timeval_warp_cb(struct unixctl_conn *conn,
792 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
793 {
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");
798 return;
799 }
800
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");
805 return;
806 }
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);
813
814 timewarp_work();
815 }
816
817 void
818 timeval_dummy_register(void)
819 {
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);
824 }
825
826
827
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
830 * like "01.123". */
831 size_t
832 strftime_msec(char *s, size_t max, const char *format,
833 const struct tm_msec *tm)
834 {
835 size_t n;
836
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;
840 if (n) {
841 char decimals[4];
842 char *p;
843
844 sprintf(decimals, "%03d", tm->msec);
845 for (p = strchr(s, '#'); p; p = strchr(p, '#')) {
846 char *d = decimals;
847 while (*p == '#') {
848 *p++ = *d ? *d++ : '0';
849 }
850 }
851 }
852
853 return n;
854 }
855
856 struct tm_msec *
857 localtime_msec(long long int now, struct tm_msec *result)
858 {
859 time_t now_sec = now / 1000;
860 localtime_r(&now_sec, &result->tm);
861 result->msec = now % 1000;
862 return result;
863 }
864
865 struct tm_msec *
866 gmtime_msec(long long int now, struct tm_msec *result)
867 {
868 time_t now_sec = now / 1000;
869 gmtime_r(&now_sec, &result->tm);
870 result->msec = now % 1000;
871 return result;
872 }