]> git.proxmox.com Git - mirror_ovs.git/blob - lib/timeval.c
timeval: Make CPU usage and wakeup tracking per-thread.
[mirror_ovs.git] / lib / timeval.c
1 /*
2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 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 "dynamic-string.h"
31 #include "fatal-signal.h"
32 #include "hash.h"
33 #include "hmap.h"
34 #include "ovs-thread.h"
35 #include "signals.h"
36 #include "unixctl.h"
37 #include "util.h"
38 #include "vlog.h"
39
40 VLOG_DEFINE_THIS_MODULE(timeval);
41
42 struct clock {
43 clockid_t id; /* CLOCK_MONOTONIC or CLOCK_REALTIME. */
44 pthread_rwlock_t rwlock; /* Mutual exclusion for 'cache'. */
45
46 /* Features for use by unit tests. Protected by 'rwlock'. */
47 struct timespec warp; /* Offset added for unit tests. */
48 bool stopped; /* Disables real-time updates if true. */
49
50 /* Relevant only if CACHE_TIME is true. */
51 volatile sig_atomic_t tick; /* Has the timer ticked? Set by signal. */
52 struct timespec cache; /* Last time read from kernel. */
53 };
54
55 /* Our clocks. */
56 static struct clock monotonic_clock; /* CLOCK_MONOTONIC, if available. */
57 static struct clock wall_clock; /* CLOCK_REALTIME. */
58
59 /* The monotonic time at which the time module was initialized. */
60 static long long int boot_time;
61
62 /* Monotonic time in milliseconds at which to die with SIGALRM (if not
63 * LLONG_MAX). */
64 static long long int deadline = LLONG_MAX;
65
66 /* Monotonic time, in milliseconds, at which the last call to time_poll() woke
67 * up. */
68 DEFINE_PER_THREAD_DATA(long long int, last_wakeup, 0);
69
70 static void set_up_timer(void);
71 static void set_up_signal(int flags);
72 static void sigalrm_handler(int);
73 static void block_sigalrm(sigset_t *);
74 static void unblock_sigalrm(const sigset_t *);
75 static void log_poll_interval(long long int last_wakeup);
76 static struct rusage *get_recent_rusage(void);
77 static void refresh_rusage(void);
78 static void timespec_add(struct timespec *sum,
79 const struct timespec *a, const struct timespec *b);
80
81 static void
82 init_clock(struct clock *c, clockid_t id)
83 {
84 memset(c, 0, sizeof *c);
85 c->id = id;
86 xpthread_rwlock_init(&c->rwlock, NULL);
87 xclock_gettime(c->id, &c->cache);
88 }
89
90 static void
91 do_init_time(void)
92 {
93 struct timespec ts;
94
95 coverage_init();
96
97 init_clock(&monotonic_clock, (!clock_gettime(CLOCK_MONOTONIC, &ts)
98 ? CLOCK_MONOTONIC
99 : CLOCK_REALTIME));
100 init_clock(&wall_clock, CLOCK_REALTIME);
101 boot_time = timespec_to_msec(&monotonic_clock.cache);
102
103 set_up_signal(SA_RESTART);
104 set_up_timer();
105 }
106
107 /* Initializes the timetracking module, if not already initialized. */
108 static void
109 time_init(void)
110 {
111 static pthread_once_t once = PTHREAD_ONCE_INIT;
112 pthread_once(&once, do_init_time);
113 }
114
115 static void
116 set_up_signal(int flags)
117 {
118 struct sigaction sa;
119
120 memset(&sa, 0, sizeof sa);
121 sa.sa_handler = sigalrm_handler;
122 sigemptyset(&sa.sa_mask);
123 sa.sa_flags = flags;
124 xsigaction(SIGALRM, &sa, NULL);
125 }
126
127 static void
128 set_up_timer(void)
129 {
130 static timer_t timer_id; /* "static" to avoid apparent memory leak. */
131 struct itimerspec itimer;
132
133 if (!CACHE_TIME) {
134 return;
135 }
136
137 if (timer_create(monotonic_clock.id, NULL, &timer_id)) {
138 VLOG_FATAL("timer_create failed (%s)", ovs_strerror(errno));
139 }
140
141 itimer.it_interval.tv_sec = 0;
142 itimer.it_interval.tv_nsec = TIME_UPDATE_INTERVAL * 1000 * 1000;
143 itimer.it_value = itimer.it_interval;
144
145 if (timer_settime(timer_id, 0, &itimer, NULL)) {
146 VLOG_FATAL("timer_settime failed (%s)", ovs_strerror(errno));
147 }
148 }
149
150 /* Set up the interval timer, to ensure that time advances even without calling
151 * time_refresh().
152 *
153 * A child created with fork() does not inherit the parent's interval timer, so
154 * this function needs to be called from the child after fork(). */
155 void
156 time_postfork(void)
157 {
158 assert_single_threaded();
159 time_init();
160 set_up_timer();
161 }
162
163 /* Forces a refresh of the current time from the kernel. It is not usually
164 * necessary to call this function, since the time will be refreshed
165 * automatically at least every TIME_UPDATE_INTERVAL milliseconds. If
166 * CACHE_TIME is false, we will always refresh the current time so this
167 * function has no effect. */
168 void
169 time_refresh(void)
170 {
171 monotonic_clock.tick = wall_clock.tick = true;
172 }
173
174 static void
175 time_timespec__(struct clock *c, struct timespec *ts)
176 {
177 time_init();
178 for (;;) {
179 /* Use the cached time by preference, but fall through if there's been
180 * a clock tick. */
181 xpthread_rwlock_rdlock(&c->rwlock);
182 if (c->stopped || !c->tick) {
183 timespec_add(ts, &c->cache, &c->warp);
184 xpthread_rwlock_unlock(&c->rwlock);
185 return;
186 }
187 xpthread_rwlock_unlock(&c->rwlock);
188
189 /* Refresh the cache. */
190 xpthread_rwlock_wrlock(&c->rwlock);
191 if (c->tick) {
192 c->tick = false;
193 xclock_gettime(c->id, &c->cache);
194 }
195 xpthread_rwlock_unlock(&c->rwlock);
196 }
197 }
198
199 /* Stores a monotonic timer, accurate within TIME_UPDATE_INTERVAL ms, into
200 * '*ts'. */
201 void
202 time_timespec(struct timespec *ts)
203 {
204 time_timespec__(&monotonic_clock, ts);
205 }
206
207 /* Stores the current time, accurate within TIME_UPDATE_INTERVAL ms, into
208 * '*ts'. */
209 void
210 time_wall_timespec(struct timespec *ts)
211 {
212 time_timespec__(&wall_clock, ts);
213 }
214
215 static time_t
216 time_sec__(struct clock *c)
217 {
218 struct timespec ts;
219
220 time_timespec__(c, &ts);
221 return ts.tv_sec;
222 }
223
224 /* Returns a monotonic timer, in seconds. */
225 time_t
226 time_now(void)
227 {
228 return time_sec__(&monotonic_clock);
229 }
230
231 /* Returns the current time, in seconds. */
232 time_t
233 time_wall(void)
234 {
235 return time_sec__(&wall_clock);
236 }
237
238 static long long int
239 time_msec__(struct clock *c)
240 {
241 struct timespec ts;
242
243 time_timespec__(c, &ts);
244 return timespec_to_msec(&ts);
245 }
246
247 /* Returns a monotonic timer, in ms (within TIME_UPDATE_INTERVAL ms). */
248 long long int
249 time_msec(void)
250 {
251 return time_msec__(&monotonic_clock);
252 }
253
254 /* Returns the current time, in ms (within TIME_UPDATE_INTERVAL ms). */
255 long long int
256 time_wall_msec(void)
257 {
258 return time_msec__(&wall_clock);
259 }
260
261 /* Configures the program to die with SIGALRM 'secs' seconds from now, if
262 * 'secs' is nonzero, or disables the feature if 'secs' is zero. */
263 void
264 time_alarm(unsigned int secs)
265 {
266 long long int now;
267 long long int msecs;
268
269 assert_single_threaded();
270 time_init();
271 time_refresh();
272
273 now = time_msec();
274 msecs = secs * 1000LL;
275 deadline = now < LLONG_MAX - msecs ? now + msecs : LLONG_MAX;
276 }
277
278 /* Like poll(), except:
279 *
280 * - The timeout is specified as an absolute time, as defined by
281 * time_msec(), instead of a duration.
282 *
283 * - On error, returns a negative error code (instead of setting errno).
284 *
285 * - If interrupted by a signal, retries automatically until the original
286 * timeout is reached. (Because of this property, this function will
287 * never return -EINTR.)
288 *
289 * - As a side effect, refreshes the current time (like time_refresh()).
290 *
291 * Stores the number of milliseconds elapsed during poll in '*elapsed'. */
292 int
293 time_poll(struct pollfd *pollfds, int n_pollfds, long long int timeout_when,
294 int *elapsed)
295 {
296 long long int *last_wakeup = last_wakeup_get();
297 long long int start;
298 sigset_t oldsigs;
299 bool blocked;
300 int retval;
301
302 time_init();
303 time_refresh();
304 if (*last_wakeup) {
305 log_poll_interval(*last_wakeup);
306 }
307 coverage_clear();
308 start = time_msec();
309 blocked = false;
310
311 timeout_when = MIN(timeout_when, deadline);
312
313 for (;;) {
314 long long int now = time_msec();
315 int time_left;
316
317 if (now >= timeout_when) {
318 time_left = 0;
319 } else if ((unsigned long long int) timeout_when - now > INT_MAX) {
320 time_left = INT_MAX;
321 } else {
322 time_left = timeout_when - now;
323 }
324
325 retval = poll(pollfds, n_pollfds, time_left);
326 if (retval < 0) {
327 retval = -errno;
328 }
329
330 time_refresh();
331 if (deadline <= time_msec()) {
332 fatal_signal_handler(SIGALRM);
333 if (retval < 0) {
334 retval = 0;
335 }
336 break;
337 }
338
339 if (retval != -EINTR) {
340 break;
341 }
342
343 if (!blocked && CACHE_TIME) {
344 block_sigalrm(&oldsigs);
345 blocked = true;
346 }
347 }
348 if (blocked) {
349 unblock_sigalrm(&oldsigs);
350 }
351 *last_wakeup = time_msec();
352 refresh_rusage();
353 *elapsed = *last_wakeup - start;
354 return retval;
355 }
356
357 static void
358 sigalrm_handler(int sig_nr OVS_UNUSED)
359 {
360 monotonic_clock.tick = wall_clock.tick = true;
361 }
362
363 static void
364 block_sigalrm(sigset_t *oldsigs)
365 {
366 sigset_t sigalrm;
367 sigemptyset(&sigalrm);
368 sigaddset(&sigalrm, SIGALRM);
369 xpthread_sigmask(SIG_BLOCK, &sigalrm, oldsigs);
370 }
371
372 static void
373 unblock_sigalrm(const sigset_t *oldsigs)
374 {
375 xpthread_sigmask(SIG_SETMASK, oldsigs, NULL);
376 }
377
378 long long int
379 timespec_to_msec(const struct timespec *ts)
380 {
381 return (long long int) ts->tv_sec * 1000 + ts->tv_nsec / (1000 * 1000);
382 }
383
384 long long int
385 timeval_to_msec(const struct timeval *tv)
386 {
387 return (long long int) tv->tv_sec * 1000 + tv->tv_usec / 1000;
388 }
389
390 /* Returns the monotonic time at which the "time" module was initialized, in
391 * milliseconds. */
392 long long int
393 time_boot_msec(void)
394 {
395 time_init();
396 return boot_time;
397 }
398
399 void
400 xgettimeofday(struct timeval *tv)
401 {
402 if (gettimeofday(tv, NULL) == -1) {
403 VLOG_FATAL("gettimeofday failed (%s)", ovs_strerror(errno));
404 }
405 }
406
407 void
408 xclock_gettime(clock_t id, struct timespec *ts)
409 {
410 if (clock_gettime(id, ts) == -1) {
411 /* It seems like a bad idea to try to use vlog here because it is
412 * likely to try to check the current time. */
413 ovs_abort(errno, "xclock_gettime() failed");
414 }
415 }
416
417 static long long int
418 timeval_diff_msec(const struct timeval *a, const struct timeval *b)
419 {
420 return timeval_to_msec(a) - timeval_to_msec(b);
421 }
422
423 static void
424 timespec_add(struct timespec *sum,
425 const struct timespec *a,
426 const struct timespec *b)
427 {
428 struct timespec tmp;
429
430 tmp.tv_sec = a->tv_sec + b->tv_sec;
431 tmp.tv_nsec = a->tv_nsec + b->tv_nsec;
432 if (tmp.tv_nsec >= 1000 * 1000 * 1000) {
433 tmp.tv_nsec -= 1000 * 1000 * 1000;
434 tmp.tv_sec++;
435 }
436
437 *sum = tmp;
438 }
439
440 static void
441 log_poll_interval(long long int last_wakeup)
442 {
443 long long int interval = time_msec() - last_wakeup;
444
445 if (interval >= 1000
446 && !monotonic_clock.warp.tv_sec
447 && !monotonic_clock.warp.tv_nsec) {
448 const struct rusage *last_rusage = get_recent_rusage();
449 struct rusage rusage;
450
451 getrusage(RUSAGE_SELF, &rusage);
452 VLOG_WARN("Unreasonably long %lldms poll interval"
453 " (%lldms user, %lldms system)",
454 interval,
455 timeval_diff_msec(&rusage.ru_utime,
456 &last_rusage->ru_utime),
457 timeval_diff_msec(&rusage.ru_stime,
458 &last_rusage->ru_stime));
459 if (rusage.ru_minflt > last_rusage->ru_minflt
460 || rusage.ru_majflt > last_rusage->ru_majflt) {
461 VLOG_WARN("faults: %ld minor, %ld major",
462 rusage.ru_minflt - last_rusage->ru_minflt,
463 rusage.ru_majflt - last_rusage->ru_majflt);
464 }
465 if (rusage.ru_inblock > last_rusage->ru_inblock
466 || rusage.ru_oublock > last_rusage->ru_oublock) {
467 VLOG_WARN("disk: %ld reads, %ld writes",
468 rusage.ru_inblock - last_rusage->ru_inblock,
469 rusage.ru_oublock - last_rusage->ru_oublock);
470 }
471 if (rusage.ru_nvcsw > last_rusage->ru_nvcsw
472 || rusage.ru_nivcsw > last_rusage->ru_nivcsw) {
473 VLOG_WARN("context switches: %ld voluntary, %ld involuntary",
474 rusage.ru_nvcsw - last_rusage->ru_nvcsw,
475 rusage.ru_nivcsw - last_rusage->ru_nivcsw);
476 }
477 coverage_log();
478 }
479 }
480 \f
481 /* CPU usage tracking. */
482
483 struct cpu_usage {
484 long long int when; /* Time that this sample was taken. */
485 unsigned long long int cpu; /* Total user+system CPU usage when sampled. */
486 };
487
488 struct cpu_tracker {
489 struct cpu_usage older;
490 struct cpu_usage newer;
491 int cpu_usage;
492
493 struct rusage recent_rusage;
494 };
495 DEFINE_PER_THREAD_MALLOCED_DATA(struct cpu_tracker *, cpu_tracker_var);
496
497 static struct cpu_tracker *
498 get_cpu_tracker(void)
499 {
500 struct cpu_tracker *t = cpu_tracker_var_get();
501 if (!t) {
502 t = xzalloc(sizeof *t);
503 t->older.when = LLONG_MIN;
504 t->newer.when = LLONG_MIN;
505 cpu_tracker_var_set_unsafe(t);
506 }
507 return t;
508 }
509
510 static struct rusage *
511 get_recent_rusage(void)
512 {
513 return &get_cpu_tracker()->recent_rusage;
514 }
515
516 static int
517 getrusage_thread(struct rusage *rusage OVS_UNUSED)
518 {
519 #ifdef RUSAGE_THREAD
520 return getrusage(RUSAGE_THREAD, rusage);
521 #else
522 errno = EINVAL;
523 return -1;
524 #endif
525 }
526
527 static void
528 refresh_rusage(void)
529 {
530 struct cpu_tracker *t = get_cpu_tracker();
531 struct rusage *recent_rusage = &t->recent_rusage;
532
533 if (!getrusage_thread(recent_rusage)) {
534 long long int now = time_msec();
535 if (now >= t->newer.when + 3 * 1000) {
536 t->older = t->newer;
537 t->newer.when = now;
538 t->newer.cpu = (timeval_to_msec(&recent_rusage->ru_utime) +
539 timeval_to_msec(&recent_rusage->ru_stime));
540
541 if (t->older.when != LLONG_MIN && t->newer.cpu > t->older.cpu) {
542 unsigned int dividend = t->newer.cpu - t->older.cpu;
543 unsigned int divisor = (t->newer.when - t->older.when) / 100;
544 t->cpu_usage = divisor > 0 ? dividend / divisor : -1;
545 } else {
546 t->cpu_usage = -1;
547 }
548 }
549 }
550 }
551
552 /* Returns an estimate of this process's CPU usage, as a percentage, over the
553 * past few seconds of wall-clock time. Returns -1 if no estimate is available
554 * (which will happen if the process has not been running long enough to have
555 * an estimate, and can happen for other reasons as well). */
556 int
557 get_cpu_usage(void)
558 {
559 return get_cpu_tracker()->cpu_usage;
560 }
561 \f
562 /* Unixctl interface. */
563
564 /* "time/stop" stops the monotonic time returned by e.g. time_msec() from
565 * advancing, except due to later calls to "time/warp". */
566 static void
567 timeval_stop_cb(struct unixctl_conn *conn,
568 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
569 void *aux OVS_UNUSED)
570 {
571 xpthread_rwlock_wrlock(&monotonic_clock.rwlock);
572 monotonic_clock.stopped = true;
573 xpthread_rwlock_unlock(&monotonic_clock.rwlock);
574
575 unixctl_command_reply(conn, NULL);
576 }
577
578 /* "time/warp MSECS" advances the current monotonic time by the specified
579 * number of milliseconds. Unless "time/stop" has also been executed, the
580 * monotonic clock continues to tick forward at the normal rate afterward.
581 *
582 * Does not affect wall clock readings. */
583 static void
584 timeval_warp_cb(struct unixctl_conn *conn,
585 int argc OVS_UNUSED, const char *argv[], void *aux OVS_UNUSED)
586 {
587 struct timespec ts;
588 int msecs;
589
590 msecs = atoi(argv[1]);
591 if (msecs <= 0) {
592 unixctl_command_reply_error(conn, "invalid MSECS");
593 return;
594 }
595
596 ts.tv_sec = msecs / 1000;
597 ts.tv_nsec = (msecs % 1000) * 1000 * 1000;
598
599 xpthread_rwlock_wrlock(&monotonic_clock.rwlock);
600 timespec_add(&monotonic_clock.warp, &monotonic_clock.warp, &ts);
601 xpthread_rwlock_unlock(&monotonic_clock.rwlock);
602
603 unixctl_command_reply(conn, "warped");
604 }
605
606 void
607 timeval_dummy_register(void)
608 {
609 unixctl_command_register("time/stop", "", 0, 0, timeval_stop_cb, NULL);
610 unixctl_command_register("time/warp", "MSECS", 1, 1,
611 timeval_warp_cb, NULL);
612 }