sm501: convert to memory API
[qemu.git] / qemu-timer.c
blobad1fc8b8711c2c3b8c9a353d471f5e259e60dc52
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 <unistd.h>
33 #include <fcntl.h>
34 #include <time.h>
35 #include <errno.h>
36 #include <sys/time.h>
37 #include <signal.h>
38 #ifdef __FreeBSD__
39 #include <sys/param.h>
40 #endif
42 #ifdef _WIN32
43 #include <windows.h>
44 #include <mmsystem.h>
45 #endif
47 #include "qemu-timer.h"
49 /* Conversion factor from emulated instructions to virtual clock ticks. */
50 int icount_time_shift;
51 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
52 #define MAX_ICOUNT_SHIFT 10
53 /* Compensate for varying guest execution speed. */
54 int64_t qemu_icount_bias;
55 static QEMUTimer *icount_rt_timer;
56 static QEMUTimer *icount_vm_timer;
58 /***********************************************************/
59 /* guest cycle counter */
61 typedef struct TimersState {
62 int64_t cpu_ticks_prev;
63 int64_t cpu_ticks_offset;
64 int64_t cpu_clock_offset;
65 int32_t cpu_ticks_enabled;
66 int64_t dummy;
67 } TimersState;
69 TimersState timers_state;
71 /* return the host CPU cycle counter and handle stop/restart */
72 int64_t cpu_get_ticks(void)
74 if (use_icount) {
75 return cpu_get_icount();
77 if (!timers_state.cpu_ticks_enabled) {
78 return timers_state.cpu_ticks_offset;
79 } else {
80 int64_t ticks;
81 ticks = cpu_get_real_ticks();
82 if (timers_state.cpu_ticks_prev > ticks) {
83 /* Note: non increasing ticks may happen if the host uses
84 software suspend */
85 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
87 timers_state.cpu_ticks_prev = ticks;
88 return ticks + timers_state.cpu_ticks_offset;
92 /* return the host CPU monotonic timer and handle stop/restart */
93 static int64_t cpu_get_clock(void)
95 int64_t ti;
96 if (!timers_state.cpu_ticks_enabled) {
97 return timers_state.cpu_clock_offset;
98 } else {
99 ti = get_clock();
100 return ti + timers_state.cpu_clock_offset;
104 /* enable cpu_get_ticks() */
105 void cpu_enable_ticks(void)
107 if (!timers_state.cpu_ticks_enabled) {
108 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
109 timers_state.cpu_clock_offset -= get_clock();
110 timers_state.cpu_ticks_enabled = 1;
114 /* disable cpu_get_ticks() : the clock is stopped. You must not call
115 cpu_get_ticks() after that. */
116 void cpu_disable_ticks(void)
118 if (timers_state.cpu_ticks_enabled) {
119 timers_state.cpu_ticks_offset = cpu_get_ticks();
120 timers_state.cpu_clock_offset = cpu_get_clock();
121 timers_state.cpu_ticks_enabled = 0;
125 /***********************************************************/
126 /* timers */
128 #define QEMU_CLOCK_REALTIME 0
129 #define QEMU_CLOCK_VIRTUAL 1
130 #define QEMU_CLOCK_HOST 2
132 struct QEMUClock {
133 int type;
134 int enabled;
136 QEMUTimer *warp_timer;
138 NotifierList reset_notifiers;
139 int64_t last;
142 struct QEMUTimer {
143 QEMUClock *clock;
144 int64_t expire_time; /* in nanoseconds */
145 int scale;
146 QEMUTimerCB *cb;
147 void *opaque;
148 struct QEMUTimer *next;
151 struct qemu_alarm_timer {
152 char const *name;
153 int (*start)(struct qemu_alarm_timer *t);
154 void (*stop)(struct qemu_alarm_timer *t);
155 void (*rearm)(struct qemu_alarm_timer *t);
156 #if defined(__linux__)
157 int fd;
158 timer_t timer;
159 #elif defined(_WIN32)
160 HANDLE timer;
161 #endif
162 char expired;
163 char pending;
166 static struct qemu_alarm_timer *alarm_timer;
168 static bool qemu_timer_expired_ns(QEMUTimer *timer_head, int64_t current_time)
170 return timer_head && (timer_head->expire_time <= current_time);
173 int qemu_alarm_pending(void)
175 return alarm_timer->pending;
178 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
180 return !!t->rearm;
183 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
185 if (!alarm_has_dynticks(t))
186 return;
188 t->rearm(t);
191 /* TODO: MIN_TIMER_REARM_NS should be optimized */
192 #define MIN_TIMER_REARM_NS 250000
194 #ifdef _WIN32
196 static int mm_start_timer(struct qemu_alarm_timer *t);
197 static void mm_stop_timer(struct qemu_alarm_timer *t);
198 static void mm_rearm_timer(struct qemu_alarm_timer *t);
200 static int win32_start_timer(struct qemu_alarm_timer *t);
201 static void win32_stop_timer(struct qemu_alarm_timer *t);
202 static void win32_rearm_timer(struct qemu_alarm_timer *t);
204 #else
206 static int unix_start_timer(struct qemu_alarm_timer *t);
207 static void unix_stop_timer(struct qemu_alarm_timer *t);
208 static void unix_rearm_timer(struct qemu_alarm_timer *t);
210 #ifdef __linux__
212 static int dynticks_start_timer(struct qemu_alarm_timer *t);
213 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
214 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
216 #endif /* __linux__ */
218 #endif /* _WIN32 */
220 /* Correlation between real and virtual time is always going to be
221 fairly approximate, so ignore small variation.
222 When the guest is idle real and virtual time will be aligned in
223 the IO wait loop. */
224 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
226 static void icount_adjust(void)
228 int64_t cur_time;
229 int64_t cur_icount;
230 int64_t delta;
231 static int64_t last_delta;
232 /* If the VM is not running, then do nothing. */
233 if (!runstate_is_running())
234 return;
236 cur_time = cpu_get_clock();
237 cur_icount = qemu_get_clock_ns(vm_clock);
238 delta = cur_icount - cur_time;
239 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
240 if (delta > 0
241 && last_delta + ICOUNT_WOBBLE < delta * 2
242 && icount_time_shift > 0) {
243 /* The guest is getting too far ahead. Slow time down. */
244 icount_time_shift--;
246 if (delta < 0
247 && last_delta - ICOUNT_WOBBLE > delta * 2
248 && icount_time_shift < MAX_ICOUNT_SHIFT) {
249 /* The guest is getting too far behind. Speed time up. */
250 icount_time_shift++;
252 last_delta = delta;
253 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
256 static void icount_adjust_rt(void * opaque)
258 qemu_mod_timer(icount_rt_timer,
259 qemu_get_clock_ms(rt_clock) + 1000);
260 icount_adjust();
263 static void icount_adjust_vm(void * opaque)
265 qemu_mod_timer(icount_vm_timer,
266 qemu_get_clock_ns(vm_clock) + get_ticks_per_sec() / 10);
267 icount_adjust();
270 int64_t qemu_icount_round(int64_t count)
272 return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
275 static struct qemu_alarm_timer alarm_timers[] = {
276 #ifndef _WIN32
277 #ifdef __linux__
278 {"dynticks", dynticks_start_timer,
279 dynticks_stop_timer, dynticks_rearm_timer},
280 #endif
281 {"unix", unix_start_timer, unix_stop_timer, unix_rearm_timer},
282 #else
283 {"mmtimer", mm_start_timer, mm_stop_timer, NULL},
284 {"mmtimer2", mm_start_timer, mm_stop_timer, mm_rearm_timer},
285 {"dynticks", win32_start_timer, win32_stop_timer, win32_rearm_timer},
286 {"win32", win32_start_timer, win32_stop_timer, NULL},
287 #endif
288 {NULL, }
291 static void show_available_alarms(void)
293 int i;
295 printf("Available alarm timers, in order of precedence:\n");
296 for (i = 0; alarm_timers[i].name; i++)
297 printf("%s\n", alarm_timers[i].name);
300 void configure_alarms(char const *opt)
302 int i;
303 int cur = 0;
304 int count = ARRAY_SIZE(alarm_timers) - 1;
305 char *arg;
306 char *name;
307 struct qemu_alarm_timer tmp;
309 if (!strcmp(opt, "?")) {
310 show_available_alarms();
311 exit(0);
314 arg = g_strdup(opt);
316 /* Reorder the array */
317 name = strtok(arg, ",");
318 while (name) {
319 for (i = 0; i < count && alarm_timers[i].name; i++) {
320 if (!strcmp(alarm_timers[i].name, name))
321 break;
324 if (i == count) {
325 fprintf(stderr, "Unknown clock %s\n", name);
326 goto next;
329 if (i < cur)
330 /* Ignore */
331 goto next;
333 /* Swap */
334 tmp = alarm_timers[i];
335 alarm_timers[i] = alarm_timers[cur];
336 alarm_timers[cur] = tmp;
338 cur++;
339 next:
340 name = strtok(NULL, ",");
343 g_free(arg);
345 if (cur) {
346 /* Disable remaining timers */
347 for (i = cur; i < count; i++)
348 alarm_timers[i].name = NULL;
349 } else {
350 show_available_alarms();
351 exit(1);
355 #define QEMU_NUM_CLOCKS 3
357 QEMUClock *rt_clock;
358 QEMUClock *vm_clock;
359 QEMUClock *host_clock;
361 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
363 static QEMUClock *qemu_new_clock(int type)
365 QEMUClock *clock;
367 clock = g_malloc0(sizeof(QEMUClock));
368 clock->type = type;
369 clock->enabled = 1;
370 notifier_list_init(&clock->reset_notifiers);
371 /* required to detect & report backward jumps */
372 if (type == QEMU_CLOCK_HOST) {
373 clock->last = get_clock_realtime();
375 return clock;
378 void qemu_clock_enable(QEMUClock *clock, int enabled)
380 clock->enabled = enabled;
383 static int64_t vm_clock_warp_start;
385 static void icount_warp_rt(void *opaque)
387 if (vm_clock_warp_start == -1) {
388 return;
391 if (runstate_is_running()) {
392 int64_t clock = qemu_get_clock_ns(rt_clock);
393 int64_t warp_delta = clock - vm_clock_warp_start;
394 if (use_icount == 1) {
395 qemu_icount_bias += warp_delta;
396 } else {
398 * In adaptive mode, do not let the vm_clock run too
399 * far ahead of real time.
401 int64_t cur_time = cpu_get_clock();
402 int64_t cur_icount = qemu_get_clock_ns(vm_clock);
403 int64_t delta = cur_time - cur_icount;
404 qemu_icount_bias += MIN(warp_delta, delta);
406 if (qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
407 qemu_get_clock_ns(vm_clock))) {
408 qemu_notify_event();
411 vm_clock_warp_start = -1;
414 void qemu_clock_warp(QEMUClock *clock)
416 int64_t deadline;
418 if (!clock->warp_timer) {
419 return;
423 * There are too many global variables to make the "warp" behavior
424 * applicable to other clocks. But a clock argument removes the
425 * need for if statements all over the place.
427 assert(clock == vm_clock);
430 * If the CPUs have been sleeping, advance the vm_clock timer now. This
431 * ensures that the deadline for the timer is computed correctly below.
432 * This also makes sure that the insn counter is synchronized before the
433 * CPU starts running, in case the CPU is woken by an event other than
434 * the earliest vm_clock timer.
436 icount_warp_rt(NULL);
437 if (!all_cpu_threads_idle() || !active_timers[clock->type]) {
438 qemu_del_timer(clock->warp_timer);
439 return;
442 vm_clock_warp_start = qemu_get_clock_ns(rt_clock);
443 deadline = qemu_next_icount_deadline();
444 if (deadline > 0) {
446 * Ensure the vm_clock proceeds even when the virtual CPU goes to
447 * sleep. Otherwise, the CPU might be waiting for a future timer
448 * interrupt to wake it up, but the interrupt never comes because
449 * the vCPU isn't running any insns and thus doesn't advance the
450 * vm_clock.
452 * An extreme solution for this problem would be to never let VCPUs
453 * sleep in icount mode if there is a pending vm_clock timer; rather
454 * time could just advance to the next vm_clock event. Instead, we
455 * do stop VCPUs and only advance vm_clock after some "real" time,
456 * (related to the time left until the next event) has passed. This
457 * rt_clock timer will do this. This avoids that the warps are too
458 * visible externally---for example, you will not be sending network
459 * packets continously instead of every 100ms.
461 qemu_mod_timer(clock->warp_timer, vm_clock_warp_start + deadline);
462 } else {
463 qemu_notify_event();
467 QEMUTimer *qemu_new_timer(QEMUClock *clock, int scale,
468 QEMUTimerCB *cb, void *opaque)
470 QEMUTimer *ts;
472 ts = g_malloc0(sizeof(QEMUTimer));
473 ts->clock = clock;
474 ts->cb = cb;
475 ts->opaque = opaque;
476 ts->scale = scale;
477 return ts;
480 void qemu_free_timer(QEMUTimer *ts)
482 g_free(ts);
485 /* stop a timer, but do not dealloc it */
486 void qemu_del_timer(QEMUTimer *ts)
488 QEMUTimer **pt, *t;
490 /* NOTE: this code must be signal safe because
491 qemu_timer_expired() can be called from a signal. */
492 pt = &active_timers[ts->clock->type];
493 for(;;) {
494 t = *pt;
495 if (!t)
496 break;
497 if (t == ts) {
498 *pt = t->next;
499 break;
501 pt = &t->next;
505 /* modify the current timer so that it will be fired when current_time
506 >= expire_time. The corresponding callback will be called. */
507 static void qemu_mod_timer_ns(QEMUTimer *ts, int64_t expire_time)
509 QEMUTimer **pt, *t;
511 qemu_del_timer(ts);
513 /* add the timer in the sorted list */
514 /* NOTE: this code must be signal safe because
515 qemu_timer_expired() can be called from a signal. */
516 pt = &active_timers[ts->clock->type];
517 for(;;) {
518 t = *pt;
519 if (!qemu_timer_expired_ns(t, expire_time)) {
520 break;
522 pt = &t->next;
524 ts->expire_time = expire_time;
525 ts->next = *pt;
526 *pt = ts;
528 /* Rearm if necessary */
529 if (pt == &active_timers[ts->clock->type]) {
530 if (!alarm_timer->pending) {
531 qemu_rearm_alarm_timer(alarm_timer);
533 /* Interrupt execution to force deadline recalculation. */
534 qemu_clock_warp(ts->clock);
535 if (use_icount) {
536 qemu_notify_event();
541 /* modify the current timer so that it will be fired when current_time
542 >= expire_time. The corresponding callback will be called. */
543 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
545 qemu_mod_timer_ns(ts, expire_time * ts->scale);
548 int qemu_timer_pending(QEMUTimer *ts)
550 QEMUTimer *t;
551 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
552 if (t == ts)
553 return 1;
555 return 0;
558 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
560 return qemu_timer_expired_ns(timer_head, current_time * timer_head->scale);
563 static void qemu_run_timers(QEMUClock *clock)
565 QEMUTimer **ptimer_head, *ts;
566 int64_t current_time;
568 if (!clock->enabled)
569 return;
571 current_time = qemu_get_clock_ns(clock);
572 ptimer_head = &active_timers[clock->type];
573 for(;;) {
574 ts = *ptimer_head;
575 if (!qemu_timer_expired_ns(ts, current_time)) {
576 break;
578 /* remove timer from the list before calling the callback */
579 *ptimer_head = ts->next;
580 ts->next = NULL;
582 /* run the callback (the timer list can be modified) */
583 ts->cb(ts->opaque);
587 int64_t qemu_get_clock_ns(QEMUClock *clock)
589 int64_t now, last;
591 switch(clock->type) {
592 case QEMU_CLOCK_REALTIME:
593 return get_clock();
594 default:
595 case QEMU_CLOCK_VIRTUAL:
596 if (use_icount) {
597 return cpu_get_icount();
598 } else {
599 return cpu_get_clock();
601 case QEMU_CLOCK_HOST:
602 now = get_clock_realtime();
603 last = clock->last;
604 clock->last = now;
605 if (now < last) {
606 notifier_list_notify(&clock->reset_notifiers, &now);
608 return now;
612 void qemu_register_clock_reset_notifier(QEMUClock *clock, Notifier *notifier)
614 notifier_list_add(&clock->reset_notifiers, notifier);
617 void qemu_unregister_clock_reset_notifier(QEMUClock *clock, Notifier *notifier)
619 notifier_list_remove(&clock->reset_notifiers, notifier);
622 void init_clocks(void)
624 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
625 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
626 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
628 rtc_clock = host_clock;
631 /* save a timer */
632 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
634 uint64_t expire_time;
636 if (qemu_timer_pending(ts)) {
637 expire_time = ts->expire_time;
638 } else {
639 expire_time = -1;
641 qemu_put_be64(f, expire_time);
644 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
646 uint64_t expire_time;
648 expire_time = qemu_get_be64(f);
649 if (expire_time != -1) {
650 qemu_mod_timer_ns(ts, expire_time);
651 } else {
652 qemu_del_timer(ts);
656 static const VMStateDescription vmstate_timers = {
657 .name = "timer",
658 .version_id = 2,
659 .minimum_version_id = 1,
660 .minimum_version_id_old = 1,
661 .fields = (VMStateField []) {
662 VMSTATE_INT64(cpu_ticks_offset, TimersState),
663 VMSTATE_INT64(dummy, TimersState),
664 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
665 VMSTATE_END_OF_LIST()
669 void configure_icount(const char *option)
671 vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
672 if (!option)
673 return;
675 vm_clock->warp_timer = qemu_new_timer_ns(rt_clock, icount_warp_rt, NULL);
677 if (strcmp(option, "auto") != 0) {
678 icount_time_shift = strtol(option, NULL, 0);
679 use_icount = 1;
680 return;
683 use_icount = 2;
685 /* 125MIPS seems a reasonable initial guess at the guest speed.
686 It will be corrected fairly quickly anyway. */
687 icount_time_shift = 3;
689 /* Have both realtime and virtual time triggers for speed adjustment.
690 The realtime trigger catches emulated time passing too slowly,
691 the virtual time trigger catches emulated time passing too fast.
692 Realtime triggers occur even when idle, so use them less frequently
693 than VM triggers. */
694 icount_rt_timer = qemu_new_timer_ms(rt_clock, icount_adjust_rt, NULL);
695 qemu_mod_timer(icount_rt_timer,
696 qemu_get_clock_ms(rt_clock) + 1000);
697 icount_vm_timer = qemu_new_timer_ns(vm_clock, icount_adjust_vm, NULL);
698 qemu_mod_timer(icount_vm_timer,
699 qemu_get_clock_ns(vm_clock) + get_ticks_per_sec() / 10);
702 void qemu_run_all_timers(void)
704 alarm_timer->pending = 0;
706 /* rearm timer, if not periodic */
707 if (alarm_timer->expired) {
708 alarm_timer->expired = 0;
709 qemu_rearm_alarm_timer(alarm_timer);
712 /* vm time timers */
713 if (runstate_is_running()) {
714 qemu_run_timers(vm_clock);
717 qemu_run_timers(rt_clock);
718 qemu_run_timers(host_clock);
721 static int64_t qemu_next_alarm_deadline(void);
723 #ifdef _WIN32
724 static void CALLBACK host_alarm_handler(PVOID lpParam, BOOLEAN unused)
725 #else
726 static void host_alarm_handler(int host_signum)
727 #endif
729 struct qemu_alarm_timer *t = alarm_timer;
730 if (!t)
731 return;
733 #if 0
734 #define DISP_FREQ 1000
736 static int64_t delta_min = INT64_MAX;
737 static int64_t delta_max, delta_cum, last_clock, delta, ti;
738 static int count;
739 ti = qemu_get_clock_ns(vm_clock);
740 if (last_clock != 0) {
741 delta = ti - last_clock;
742 if (delta < delta_min)
743 delta_min = delta;
744 if (delta > delta_max)
745 delta_max = delta;
746 delta_cum += delta;
747 if (++count == DISP_FREQ) {
748 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
749 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
750 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
751 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
752 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
753 count = 0;
754 delta_min = INT64_MAX;
755 delta_max = 0;
756 delta_cum = 0;
759 last_clock = ti;
761 #endif
762 if (alarm_has_dynticks(t) ||
763 qemu_next_alarm_deadline () <= 0) {
764 t->expired = alarm_has_dynticks(t);
765 t->pending = 1;
766 qemu_notify_event();
770 int64_t qemu_next_icount_deadline(void)
772 /* To avoid problems with overflow limit this to 2^32. */
773 int64_t delta = INT32_MAX;
775 assert(use_icount);
776 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
777 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
778 qemu_get_clock_ns(vm_clock);
781 if (delta < 0)
782 delta = 0;
784 return delta;
787 static int64_t qemu_next_alarm_deadline(void)
789 int64_t delta;
790 int64_t rtdelta;
792 if (!use_icount && active_timers[QEMU_CLOCK_VIRTUAL]) {
793 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
794 qemu_get_clock_ns(vm_clock);
795 } else {
796 delta = INT32_MAX;
798 if (active_timers[QEMU_CLOCK_HOST]) {
799 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
800 qemu_get_clock_ns(host_clock);
801 if (hdelta < delta)
802 delta = hdelta;
804 if (active_timers[QEMU_CLOCK_REALTIME]) {
805 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
806 qemu_get_clock_ns(rt_clock));
807 if (rtdelta < delta)
808 delta = rtdelta;
811 return delta;
814 #if defined(__linux__)
816 #include "compatfd.h"
818 static int dynticks_start_timer(struct qemu_alarm_timer *t)
820 struct sigevent ev;
821 timer_t host_timer;
822 struct sigaction act;
824 sigfillset(&act.sa_mask);
825 act.sa_flags = 0;
826 act.sa_handler = host_alarm_handler;
828 sigaction(SIGALRM, &act, NULL);
831 * Initialize ev struct to 0 to avoid valgrind complaining
832 * about uninitialized data in timer_create call
834 memset(&ev, 0, sizeof(ev));
835 ev.sigev_value.sival_int = 0;
836 ev.sigev_notify = SIGEV_SIGNAL;
837 #ifdef SIGEV_THREAD_ID
838 if (qemu_signalfd_available()) {
839 ev.sigev_notify = SIGEV_THREAD_ID;
840 ev._sigev_un._tid = qemu_get_thread_id();
842 #endif /* SIGEV_THREAD_ID */
843 ev.sigev_signo = SIGALRM;
845 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
846 perror("timer_create");
848 /* disable dynticks */
849 fprintf(stderr, "Dynamic Ticks disabled\n");
851 return -1;
854 t->timer = host_timer;
856 return 0;
859 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
861 timer_t host_timer = t->timer;
863 timer_delete(host_timer);
866 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
868 timer_t host_timer = t->timer;
869 struct itimerspec timeout;
870 int64_t nearest_delta_ns = INT64_MAX;
871 int64_t current_ns;
873 assert(alarm_has_dynticks(t));
874 if (!active_timers[QEMU_CLOCK_REALTIME] &&
875 !active_timers[QEMU_CLOCK_VIRTUAL] &&
876 !active_timers[QEMU_CLOCK_HOST])
877 return;
879 nearest_delta_ns = qemu_next_alarm_deadline();
880 if (nearest_delta_ns < MIN_TIMER_REARM_NS)
881 nearest_delta_ns = MIN_TIMER_REARM_NS;
883 /* check whether a timer is already running */
884 if (timer_gettime(host_timer, &timeout)) {
885 perror("gettime");
886 fprintf(stderr, "Internal timer error: aborting\n");
887 exit(1);
889 current_ns = timeout.it_value.tv_sec * 1000000000LL + timeout.it_value.tv_nsec;
890 if (current_ns && current_ns <= nearest_delta_ns)
891 return;
893 timeout.it_interval.tv_sec = 0;
894 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
895 timeout.it_value.tv_sec = nearest_delta_ns / 1000000000;
896 timeout.it_value.tv_nsec = nearest_delta_ns % 1000000000;
897 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
898 perror("settime");
899 fprintf(stderr, "Internal timer error: aborting\n");
900 exit(1);
904 #endif /* defined(__linux__) */
906 #if !defined(_WIN32)
908 static int unix_start_timer(struct qemu_alarm_timer *t)
910 struct sigaction act;
912 /* timer signal */
913 sigfillset(&act.sa_mask);
914 act.sa_flags = 0;
915 act.sa_handler = host_alarm_handler;
917 sigaction(SIGALRM, &act, NULL);
918 return 0;
921 static void unix_rearm_timer(struct qemu_alarm_timer *t)
923 struct itimerval itv;
924 int64_t nearest_delta_ns = INT64_MAX;
925 int err;
927 assert(alarm_has_dynticks(t));
928 if (!active_timers[QEMU_CLOCK_REALTIME] &&
929 !active_timers[QEMU_CLOCK_VIRTUAL] &&
930 !active_timers[QEMU_CLOCK_HOST])
931 return;
933 nearest_delta_ns = qemu_next_alarm_deadline();
934 if (nearest_delta_ns < MIN_TIMER_REARM_NS)
935 nearest_delta_ns = MIN_TIMER_REARM_NS;
937 itv.it_interval.tv_sec = 0;
938 itv.it_interval.tv_usec = 0; /* 0 for one-shot timer */
939 itv.it_value.tv_sec = nearest_delta_ns / 1000000000;
940 itv.it_value.tv_usec = (nearest_delta_ns % 1000000000) / 1000;
941 err = setitimer(ITIMER_REAL, &itv, NULL);
942 if (err) {
943 perror("setitimer");
944 fprintf(stderr, "Internal timer error: aborting\n");
945 exit(1);
949 static void unix_stop_timer(struct qemu_alarm_timer *t)
951 struct itimerval itv;
953 memset(&itv, 0, sizeof(itv));
954 setitimer(ITIMER_REAL, &itv, NULL);
957 #endif /* !defined(_WIN32) */
960 #ifdef _WIN32
962 static MMRESULT mm_timer;
963 static unsigned mm_period;
965 static void CALLBACK mm_alarm_handler(UINT uTimerID, UINT uMsg,
966 DWORD_PTR dwUser, DWORD_PTR dw1,
967 DWORD_PTR dw2)
969 struct qemu_alarm_timer *t = alarm_timer;
970 if (!t) {
971 return;
973 if (alarm_has_dynticks(t) || qemu_next_alarm_deadline() <= 0) {
974 t->expired = alarm_has_dynticks(t);
975 t->pending = 1;
976 qemu_notify_event();
980 static int mm_start_timer(struct qemu_alarm_timer *t)
982 TIMECAPS tc;
983 UINT flags;
985 memset(&tc, 0, sizeof(tc));
986 timeGetDevCaps(&tc, sizeof(tc));
988 mm_period = tc.wPeriodMin;
989 timeBeginPeriod(mm_period);
991 flags = TIME_CALLBACK_FUNCTION;
992 if (alarm_has_dynticks(t)) {
993 flags |= TIME_ONESHOT;
994 } else {
995 flags |= TIME_PERIODIC;
998 mm_timer = timeSetEvent(1, /* interval (ms) */
999 mm_period, /* resolution */
1000 mm_alarm_handler, /* function */
1001 (DWORD_PTR)t, /* parameter */
1002 flags);
1004 if (!mm_timer) {
1005 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1006 GetLastError());
1007 timeEndPeriod(mm_period);
1008 return -1;
1011 return 0;
1014 static void mm_stop_timer(struct qemu_alarm_timer *t)
1016 timeKillEvent(mm_timer);
1017 timeEndPeriod(mm_period);
1020 static void mm_rearm_timer(struct qemu_alarm_timer *t)
1022 int nearest_delta_ms;
1024 assert(alarm_has_dynticks(t));
1025 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1026 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1027 !active_timers[QEMU_CLOCK_HOST]) {
1028 return;
1031 timeKillEvent(mm_timer);
1033 nearest_delta_ms = (qemu_next_alarm_deadline() + 999999) / 1000000;
1034 if (nearest_delta_ms < 1) {
1035 nearest_delta_ms = 1;
1037 mm_timer = timeSetEvent(nearest_delta_ms,
1038 mm_period,
1039 mm_alarm_handler,
1040 (DWORD_PTR)t,
1041 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1043 if (!mm_timer) {
1044 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1045 GetLastError());
1047 timeEndPeriod(mm_period);
1048 exit(1);
1052 static int win32_start_timer(struct qemu_alarm_timer *t)
1054 HANDLE hTimer;
1055 BOOLEAN success;
1057 /* If you call ChangeTimerQueueTimer on a one-shot timer (its period
1058 is zero) that has already expired, the timer is not updated. Since
1059 creating a new timer is relatively expensive, set a bogus one-hour
1060 interval in the dynticks case. */
1061 success = CreateTimerQueueTimer(&hTimer,
1062 NULL,
1063 host_alarm_handler,
1066 alarm_has_dynticks(t) ? 3600000 : 1,
1067 WT_EXECUTEINTIMERTHREAD);
1069 if (!success) {
1070 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1071 GetLastError());
1072 return -1;
1075 t->timer = hTimer;
1076 return 0;
1079 static void win32_stop_timer(struct qemu_alarm_timer *t)
1081 HANDLE hTimer = t->timer;
1083 if (hTimer) {
1084 DeleteTimerQueueTimer(NULL, hTimer, NULL);
1088 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1090 HANDLE hTimer = t->timer;
1091 int nearest_delta_ms;
1092 BOOLEAN success;
1094 assert(alarm_has_dynticks(t));
1095 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1096 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1097 !active_timers[QEMU_CLOCK_HOST])
1098 return;
1100 nearest_delta_ms = (qemu_next_alarm_deadline() + 999999) / 1000000;
1101 if (nearest_delta_ms < 1) {
1102 nearest_delta_ms = 1;
1104 success = ChangeTimerQueueTimer(NULL,
1105 hTimer,
1106 nearest_delta_ms,
1107 3600000);
1109 if (!success) {
1110 fprintf(stderr, "Failed to rearm win32 alarm timer: %ld\n",
1111 GetLastError());
1112 exit(-1);
1117 #endif /* _WIN32 */
1119 static void alarm_timer_on_change_state_rearm(void *opaque, int running,
1120 RunState state)
1122 if (running)
1123 qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1126 int init_timer_alarm(void)
1128 struct qemu_alarm_timer *t = NULL;
1129 int i, err = -1;
1131 for (i = 0; alarm_timers[i].name; i++) {
1132 t = &alarm_timers[i];
1134 err = t->start(t);
1135 if (!err)
1136 break;
1139 if (err) {
1140 err = -ENOENT;
1141 goto fail;
1144 /* first event is at time 0 */
1145 t->pending = 1;
1146 alarm_timer = t;
1147 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1149 return 0;
1151 fail:
1152 return err;
1155 void quit_timers(void)
1157 struct qemu_alarm_timer *t = alarm_timer;
1158 alarm_timer = NULL;
1159 t->stop(t);
1162 int qemu_calculate_timeout(void)
1164 return 1000;