Merge remote-tracking branch 'kraxel/usb.59' into staging
[qemu.git] / qemu-timer.c
blob5aea94e8e00ffb4ba6e93cfbfd2172e8d82ac787
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "sysemu.h"
26 #include "net.h"
27 #include "monitor.h"
28 #include "console.h"
30 #include "hw/hw.h"
32 #include "qemu-timer.h"
34 #ifdef _WIN32
35 #include <mmsystem.h>
36 #endif
38 /***********************************************************/
39 /* timers */
41 #define QEMU_CLOCK_REALTIME 0
42 #define QEMU_CLOCK_VIRTUAL 1
43 #define QEMU_CLOCK_HOST 2
45 struct QEMUClock {
46 QEMUTimer *active_timers;
48 NotifierList reset_notifiers;
49 int64_t last;
51 int type;
52 bool enabled;
55 struct QEMUTimer {
56 int64_t expire_time; /* in nanoseconds */
57 QEMUClock *clock;
58 QEMUTimerCB *cb;
59 void *opaque;
60 QEMUTimer *next;
61 int scale;
64 struct qemu_alarm_timer {
65 char const *name;
66 int (*start)(struct qemu_alarm_timer *t);
67 void (*stop)(struct qemu_alarm_timer *t);
68 void (*rearm)(struct qemu_alarm_timer *t, int64_t nearest_delta_ns);
69 #if defined(__linux__)
70 timer_t timer;
71 int fd;
72 #elif defined(_WIN32)
73 HANDLE timer;
74 #endif
75 bool expired;
76 bool pending;
79 static struct qemu_alarm_timer *alarm_timer;
81 static bool qemu_timer_expired_ns(QEMUTimer *timer_head, int64_t current_time)
83 return timer_head && (timer_head->expire_time <= current_time);
86 static int64_t qemu_next_alarm_deadline(void)
88 int64_t delta = INT64_MAX;
89 int64_t rtdelta;
91 if (!use_icount && vm_clock->enabled && vm_clock->active_timers) {
92 delta = vm_clock->active_timers->expire_time -
93 qemu_get_clock_ns(vm_clock);
95 if (host_clock->enabled && host_clock->active_timers) {
96 int64_t hdelta = host_clock->active_timers->expire_time -
97 qemu_get_clock_ns(host_clock);
98 if (hdelta < delta) {
99 delta = hdelta;
102 if (rt_clock->enabled && rt_clock->active_timers) {
103 rtdelta = (rt_clock->active_timers->expire_time -
104 qemu_get_clock_ns(rt_clock));
105 if (rtdelta < delta) {
106 delta = rtdelta;
110 return delta;
113 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
115 int64_t nearest_delta_ns = qemu_next_alarm_deadline();
116 if (nearest_delta_ns < INT64_MAX) {
117 t->rearm(t, nearest_delta_ns);
121 /* TODO: MIN_TIMER_REARM_NS should be optimized */
122 #define MIN_TIMER_REARM_NS 250000
124 #ifdef _WIN32
126 static int mm_start_timer(struct qemu_alarm_timer *t);
127 static void mm_stop_timer(struct qemu_alarm_timer *t);
128 static void mm_rearm_timer(struct qemu_alarm_timer *t, int64_t delta);
130 static int win32_start_timer(struct qemu_alarm_timer *t);
131 static void win32_stop_timer(struct qemu_alarm_timer *t);
132 static void win32_rearm_timer(struct qemu_alarm_timer *t, int64_t delta);
134 #else
136 static int unix_start_timer(struct qemu_alarm_timer *t);
137 static void unix_stop_timer(struct qemu_alarm_timer *t);
138 static void unix_rearm_timer(struct qemu_alarm_timer *t, int64_t delta);
140 #ifdef __linux__
142 static int dynticks_start_timer(struct qemu_alarm_timer *t);
143 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
144 static void dynticks_rearm_timer(struct qemu_alarm_timer *t, int64_t delta);
146 #endif /* __linux__ */
148 #endif /* _WIN32 */
150 static struct qemu_alarm_timer alarm_timers[] = {
151 #ifndef _WIN32
152 #ifdef __linux__
153 {"dynticks", dynticks_start_timer,
154 dynticks_stop_timer, dynticks_rearm_timer},
155 #endif
156 {"unix", unix_start_timer, unix_stop_timer, unix_rearm_timer},
157 #else
158 {"mmtimer", mm_start_timer, mm_stop_timer, mm_rearm_timer},
159 {"dynticks", win32_start_timer, win32_stop_timer, win32_rearm_timer},
160 #endif
161 {NULL, }
164 static void show_available_alarms(void)
166 int i;
168 printf("Available alarm timers, in order of precedence:\n");
169 for (i = 0; alarm_timers[i].name; i++)
170 printf("%s\n", alarm_timers[i].name);
173 void configure_alarms(char const *opt)
175 int i;
176 int cur = 0;
177 int count = ARRAY_SIZE(alarm_timers) - 1;
178 char *arg;
179 char *name;
180 struct qemu_alarm_timer tmp;
182 if (is_help_option(opt)) {
183 show_available_alarms();
184 exit(0);
187 arg = g_strdup(opt);
189 /* Reorder the array */
190 name = strtok(arg, ",");
191 while (name) {
192 for (i = 0; i < count && alarm_timers[i].name; i++) {
193 if (!strcmp(alarm_timers[i].name, name))
194 break;
197 if (i == count) {
198 fprintf(stderr, "Unknown clock %s\n", name);
199 goto next;
202 if (i < cur)
203 /* Ignore */
204 goto next;
206 /* Swap */
207 tmp = alarm_timers[i];
208 alarm_timers[i] = alarm_timers[cur];
209 alarm_timers[cur] = tmp;
211 cur++;
212 next:
213 name = strtok(NULL, ",");
216 g_free(arg);
218 if (cur) {
219 /* Disable remaining timers */
220 for (i = cur; i < count; i++)
221 alarm_timers[i].name = NULL;
222 } else {
223 show_available_alarms();
224 exit(1);
228 QEMUClock *rt_clock;
229 QEMUClock *vm_clock;
230 QEMUClock *host_clock;
232 static QEMUClock *qemu_new_clock(int type)
234 QEMUClock *clock;
236 clock = g_malloc0(sizeof(QEMUClock));
237 clock->type = type;
238 clock->enabled = true;
239 clock->last = INT64_MIN;
240 notifier_list_init(&clock->reset_notifiers);
241 return clock;
244 void qemu_clock_enable(QEMUClock *clock, bool enabled)
246 bool old = clock->enabled;
247 clock->enabled = enabled;
248 if (enabled && !old) {
249 qemu_rearm_alarm_timer(alarm_timer);
253 int64_t qemu_clock_has_timers(QEMUClock *clock)
255 return !!clock->active_timers;
258 int64_t qemu_clock_expired(QEMUClock *clock)
260 return (clock->active_timers &&
261 clock->active_timers->expire_time < qemu_get_clock_ns(clock));
264 int64_t qemu_clock_deadline(QEMUClock *clock)
266 /* To avoid problems with overflow limit this to 2^32. */
267 int64_t delta = INT32_MAX;
269 if (clock->active_timers) {
270 delta = clock->active_timers->expire_time - qemu_get_clock_ns(clock);
272 if (delta < 0) {
273 delta = 0;
275 return delta;
278 QEMUTimer *qemu_new_timer(QEMUClock *clock, int scale,
279 QEMUTimerCB *cb, void *opaque)
281 QEMUTimer *ts;
283 ts = g_malloc0(sizeof(QEMUTimer));
284 ts->clock = clock;
285 ts->cb = cb;
286 ts->opaque = opaque;
287 ts->scale = scale;
288 return ts;
291 void qemu_free_timer(QEMUTimer *ts)
293 g_free(ts);
296 /* stop a timer, but do not dealloc it */
297 void qemu_del_timer(QEMUTimer *ts)
299 QEMUTimer **pt, *t;
301 /* NOTE: this code must be signal safe because
302 qemu_timer_expired() can be called from a signal. */
303 pt = &ts->clock->active_timers;
304 for(;;) {
305 t = *pt;
306 if (!t)
307 break;
308 if (t == ts) {
309 *pt = t->next;
310 break;
312 pt = &t->next;
316 /* modify the current timer so that it will be fired when current_time
317 >= expire_time. The corresponding callback will be called. */
318 void qemu_mod_timer_ns(QEMUTimer *ts, int64_t expire_time)
320 QEMUTimer **pt, *t;
322 qemu_del_timer(ts);
324 /* add the timer in the sorted list */
325 /* NOTE: this code must be signal safe because
326 qemu_timer_expired() can be called from a signal. */
327 pt = &ts->clock->active_timers;
328 for(;;) {
329 t = *pt;
330 if (!qemu_timer_expired_ns(t, expire_time)) {
331 break;
333 pt = &t->next;
335 ts->expire_time = expire_time;
336 ts->next = *pt;
337 *pt = ts;
339 /* Rearm if necessary */
340 if (pt == &ts->clock->active_timers) {
341 if (!alarm_timer->pending) {
342 qemu_rearm_alarm_timer(alarm_timer);
344 /* Interrupt execution to force deadline recalculation. */
345 qemu_clock_warp(ts->clock);
346 if (use_icount) {
347 qemu_notify_event();
352 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
354 qemu_mod_timer_ns(ts, expire_time * ts->scale);
357 bool qemu_timer_pending(QEMUTimer *ts)
359 QEMUTimer *t;
360 for (t = ts->clock->active_timers; t != NULL; t = t->next) {
361 if (t == ts) {
362 return true;
365 return false;
368 bool qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
370 return qemu_timer_expired_ns(timer_head, current_time * timer_head->scale);
373 void qemu_run_timers(QEMUClock *clock)
375 QEMUTimer **ptimer_head, *ts;
376 int64_t current_time;
378 if (!clock->enabled)
379 return;
381 current_time = qemu_get_clock_ns(clock);
382 ptimer_head = &clock->active_timers;
383 for(;;) {
384 ts = *ptimer_head;
385 if (!qemu_timer_expired_ns(ts, current_time)) {
386 break;
388 /* remove timer from the list before calling the callback */
389 *ptimer_head = ts->next;
390 ts->next = NULL;
392 /* run the callback (the timer list can be modified) */
393 ts->cb(ts->opaque);
397 int64_t qemu_get_clock_ns(QEMUClock *clock)
399 int64_t now, last;
401 switch(clock->type) {
402 case QEMU_CLOCK_REALTIME:
403 return get_clock();
404 default:
405 case QEMU_CLOCK_VIRTUAL:
406 if (use_icount) {
407 return cpu_get_icount();
408 } else {
409 return cpu_get_clock();
411 case QEMU_CLOCK_HOST:
412 now = get_clock_realtime();
413 last = clock->last;
414 clock->last = now;
415 if (now < last) {
416 notifier_list_notify(&clock->reset_notifiers, &now);
418 return now;
422 void qemu_register_clock_reset_notifier(QEMUClock *clock, Notifier *notifier)
424 notifier_list_add(&clock->reset_notifiers, notifier);
427 void qemu_unregister_clock_reset_notifier(QEMUClock *clock, Notifier *notifier)
429 notifier_remove(notifier);
432 void init_clocks(void)
434 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
435 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
436 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
439 uint64_t qemu_timer_expire_time_ns(QEMUTimer *ts)
441 return qemu_timer_pending(ts) ? ts->expire_time : -1;
444 void qemu_run_all_timers(void)
446 alarm_timer->pending = false;
448 /* vm time timers */
449 qemu_run_timers(vm_clock);
450 qemu_run_timers(rt_clock);
451 qemu_run_timers(host_clock);
453 /* rearm timer, if not periodic */
454 if (alarm_timer->expired) {
455 alarm_timer->expired = false;
456 qemu_rearm_alarm_timer(alarm_timer);
460 #ifdef _WIN32
461 static void CALLBACK host_alarm_handler(PVOID lpParam, BOOLEAN unused)
462 #else
463 static void host_alarm_handler(int host_signum)
464 #endif
466 struct qemu_alarm_timer *t = alarm_timer;
467 if (!t)
468 return;
470 t->expired = true;
471 t->pending = true;
472 qemu_notify_event();
475 #if defined(__linux__)
477 #include "compatfd.h"
479 static int dynticks_start_timer(struct qemu_alarm_timer *t)
481 struct sigevent ev;
482 timer_t host_timer;
483 struct sigaction act;
485 sigfillset(&act.sa_mask);
486 act.sa_flags = 0;
487 act.sa_handler = host_alarm_handler;
489 sigaction(SIGALRM, &act, NULL);
492 * Initialize ev struct to 0 to avoid valgrind complaining
493 * about uninitialized data in timer_create call
495 memset(&ev, 0, sizeof(ev));
496 ev.sigev_value.sival_int = 0;
497 ev.sigev_notify = SIGEV_SIGNAL;
498 #ifdef SIGEV_THREAD_ID
499 if (qemu_signalfd_available()) {
500 ev.sigev_notify = SIGEV_THREAD_ID;
501 ev._sigev_un._tid = qemu_get_thread_id();
503 #endif /* SIGEV_THREAD_ID */
504 ev.sigev_signo = SIGALRM;
506 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
507 perror("timer_create");
508 return -1;
511 t->timer = host_timer;
513 return 0;
516 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
518 timer_t host_timer = t->timer;
520 timer_delete(host_timer);
523 static void dynticks_rearm_timer(struct qemu_alarm_timer *t,
524 int64_t nearest_delta_ns)
526 timer_t host_timer = t->timer;
527 struct itimerspec timeout;
528 int64_t current_ns;
530 if (nearest_delta_ns < MIN_TIMER_REARM_NS)
531 nearest_delta_ns = MIN_TIMER_REARM_NS;
533 /* check whether a timer is already running */
534 if (timer_gettime(host_timer, &timeout)) {
535 perror("gettime");
536 fprintf(stderr, "Internal timer error: aborting\n");
537 exit(1);
539 current_ns = timeout.it_value.tv_sec * 1000000000LL + timeout.it_value.tv_nsec;
540 if (current_ns && current_ns <= nearest_delta_ns)
541 return;
543 timeout.it_interval.tv_sec = 0;
544 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
545 timeout.it_value.tv_sec = nearest_delta_ns / 1000000000;
546 timeout.it_value.tv_nsec = nearest_delta_ns % 1000000000;
547 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
548 perror("settime");
549 fprintf(stderr, "Internal timer error: aborting\n");
550 exit(1);
554 #endif /* defined(__linux__) */
556 #if !defined(_WIN32)
558 static int unix_start_timer(struct qemu_alarm_timer *t)
560 struct sigaction act;
562 /* timer signal */
563 sigfillset(&act.sa_mask);
564 act.sa_flags = 0;
565 act.sa_handler = host_alarm_handler;
567 sigaction(SIGALRM, &act, NULL);
568 return 0;
571 static void unix_rearm_timer(struct qemu_alarm_timer *t,
572 int64_t nearest_delta_ns)
574 struct itimerval itv;
575 int err;
577 if (nearest_delta_ns < MIN_TIMER_REARM_NS)
578 nearest_delta_ns = MIN_TIMER_REARM_NS;
580 itv.it_interval.tv_sec = 0;
581 itv.it_interval.tv_usec = 0; /* 0 for one-shot timer */
582 itv.it_value.tv_sec = nearest_delta_ns / 1000000000;
583 itv.it_value.tv_usec = (nearest_delta_ns % 1000000000) / 1000;
584 err = setitimer(ITIMER_REAL, &itv, NULL);
585 if (err) {
586 perror("setitimer");
587 fprintf(stderr, "Internal timer error: aborting\n");
588 exit(1);
592 static void unix_stop_timer(struct qemu_alarm_timer *t)
594 struct itimerval itv;
596 memset(&itv, 0, sizeof(itv));
597 setitimer(ITIMER_REAL, &itv, NULL);
600 #endif /* !defined(_WIN32) */
603 #ifdef _WIN32
605 static MMRESULT mm_timer;
606 static TIMECAPS mm_tc;
608 static void CALLBACK mm_alarm_handler(UINT uTimerID, UINT uMsg,
609 DWORD_PTR dwUser, DWORD_PTR dw1,
610 DWORD_PTR dw2)
612 struct qemu_alarm_timer *t = alarm_timer;
613 if (!t) {
614 return;
616 t->expired = true;
617 t->pending = true;
618 qemu_notify_event();
621 static int mm_start_timer(struct qemu_alarm_timer *t)
623 timeGetDevCaps(&mm_tc, sizeof(mm_tc));
625 timeBeginPeriod(mm_tc.wPeriodMin);
627 mm_timer = timeSetEvent(mm_tc.wPeriodMin, /* interval (ms) */
628 mm_tc.wPeriodMin, /* resolution */
629 mm_alarm_handler, /* function */
630 (DWORD_PTR)t, /* parameter */
631 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
633 if (!mm_timer) {
634 fprintf(stderr, "Failed to initialize win32 alarm timer\n");
635 timeEndPeriod(mm_tc.wPeriodMin);
636 return -1;
639 return 0;
642 static void mm_stop_timer(struct qemu_alarm_timer *t)
644 timeKillEvent(mm_timer);
645 timeEndPeriod(mm_tc.wPeriodMin);
648 static void mm_rearm_timer(struct qemu_alarm_timer *t, int64_t delta)
650 int64_t nearest_delta_ms = delta / 1000000;
651 if (nearest_delta_ms < mm_tc.wPeriodMin) {
652 nearest_delta_ms = mm_tc.wPeriodMin;
653 } else if (nearest_delta_ms > mm_tc.wPeriodMax) {
654 nearest_delta_ms = mm_tc.wPeriodMax;
657 timeKillEvent(mm_timer);
658 mm_timer = timeSetEvent((UINT)nearest_delta_ms,
659 mm_tc.wPeriodMin,
660 mm_alarm_handler,
661 (DWORD_PTR)t,
662 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
664 if (!mm_timer) {
665 fprintf(stderr, "Failed to re-arm win32 alarm timer\n");
666 timeEndPeriod(mm_tc.wPeriodMin);
667 exit(1);
671 static int win32_start_timer(struct qemu_alarm_timer *t)
673 HANDLE hTimer;
674 BOOLEAN success;
676 /* If you call ChangeTimerQueueTimer on a one-shot timer (its period
677 is zero) that has already expired, the timer is not updated. Since
678 creating a new timer is relatively expensive, set a bogus one-hour
679 interval in the dynticks case. */
680 success = CreateTimerQueueTimer(&hTimer,
681 NULL,
682 host_alarm_handler,
685 3600000,
686 WT_EXECUTEINTIMERTHREAD);
688 if (!success) {
689 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
690 GetLastError());
691 return -1;
694 t->timer = hTimer;
695 return 0;
698 static void win32_stop_timer(struct qemu_alarm_timer *t)
700 HANDLE hTimer = t->timer;
702 if (hTimer) {
703 DeleteTimerQueueTimer(NULL, hTimer, NULL);
707 static void win32_rearm_timer(struct qemu_alarm_timer *t,
708 int64_t nearest_delta_ns)
710 HANDLE hTimer = t->timer;
711 int64_t nearest_delta_ms;
712 BOOLEAN success;
714 nearest_delta_ms = nearest_delta_ns / 1000000;
715 if (nearest_delta_ms < 1) {
716 nearest_delta_ms = 1;
718 /* ULONG_MAX can be 32 bit */
719 if (nearest_delta_ms > ULONG_MAX) {
720 nearest_delta_ms = ULONG_MAX;
722 success = ChangeTimerQueueTimer(NULL,
723 hTimer,
724 (unsigned long) nearest_delta_ms,
725 3600000);
727 if (!success) {
728 fprintf(stderr, "Failed to rearm win32 alarm timer: %ld\n",
729 GetLastError());
730 exit(-1);
735 #endif /* _WIN32 */
737 static void quit_timers(void)
739 struct qemu_alarm_timer *t = alarm_timer;
740 alarm_timer = NULL;
741 t->stop(t);
744 int init_timer_alarm(void)
746 struct qemu_alarm_timer *t = NULL;
747 int i, err = -1;
749 for (i = 0; alarm_timers[i].name; i++) {
750 t = &alarm_timers[i];
752 err = t->start(t);
753 if (!err)
754 break;
757 if (err) {
758 err = -ENOENT;
759 goto fail;
762 /* first event is at time 0 */
763 atexit(quit_timers);
764 t->pending = true;
765 alarm_timer = t;
767 return 0;
769 fail:
770 return err;