guest agent: qemu-ga daemon
[qemu-kvm.git] / qemu-timer.c
blob72066c7c50551db216783b9c1b02a57130b177ff
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 #ifndef CONFIG_IOTHREAD
105 static int64_t qemu_icount_delta(void)
107 if (!use_icount) {
108 return 5000 * (int64_t) 1000000;
109 } else if (use_icount == 1) {
110 /* When not using an adaptive execution frequency
111 we tend to get badly out of sync with real time,
112 so just delay for a reasonable amount of time. */
113 return 0;
114 } else {
115 return cpu_get_icount() - cpu_get_clock();
118 #endif
120 /* enable cpu_get_ticks() */
121 void cpu_enable_ticks(void)
123 if (!timers_state.cpu_ticks_enabled) {
124 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
125 timers_state.cpu_clock_offset -= get_clock();
126 timers_state.cpu_ticks_enabled = 1;
130 /* disable cpu_get_ticks() : the clock is stopped. You must not call
131 cpu_get_ticks() after that. */
132 void cpu_disable_ticks(void)
134 if (timers_state.cpu_ticks_enabled) {
135 timers_state.cpu_ticks_offset = cpu_get_ticks();
136 timers_state.cpu_clock_offset = cpu_get_clock();
137 timers_state.cpu_ticks_enabled = 0;
141 /***********************************************************/
142 /* timers */
144 #define QEMU_CLOCK_REALTIME 0
145 #define QEMU_CLOCK_VIRTUAL 1
146 #define QEMU_CLOCK_HOST 2
148 struct QEMUClock {
149 int type;
150 int enabled;
152 QEMUTimer *warp_timer;
155 struct QEMUTimer {
156 QEMUClock *clock;
157 int64_t expire_time; /* in nanoseconds */
158 int scale;
159 QEMUTimerCB *cb;
160 void *opaque;
161 struct QEMUTimer *next;
164 struct qemu_alarm_timer {
165 char const *name;
166 int (*start)(struct qemu_alarm_timer *t);
167 void (*stop)(struct qemu_alarm_timer *t);
168 void (*rearm)(struct qemu_alarm_timer *t);
169 #if defined(__linux__)
170 int fd;
171 timer_t timer;
172 #elif defined(_WIN32)
173 HANDLE timer;
174 #endif
175 char expired;
176 char pending;
179 static struct qemu_alarm_timer *alarm_timer;
181 static bool qemu_timer_expired_ns(QEMUTimer *timer_head, int64_t current_time)
183 return timer_head && (timer_head->expire_time <= current_time);
186 int qemu_alarm_pending(void)
188 return alarm_timer->pending;
191 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
193 return !!t->rearm;
196 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
198 if (!alarm_has_dynticks(t))
199 return;
201 t->rearm(t);
204 /* TODO: MIN_TIMER_REARM_NS should be optimized */
205 #define MIN_TIMER_REARM_NS 250000
207 #ifdef _WIN32
209 static int mm_start_timer(struct qemu_alarm_timer *t);
210 static void mm_stop_timer(struct qemu_alarm_timer *t);
211 static void mm_rearm_timer(struct qemu_alarm_timer *t);
213 static int win32_start_timer(struct qemu_alarm_timer *t);
214 static void win32_stop_timer(struct qemu_alarm_timer *t);
215 static void win32_rearm_timer(struct qemu_alarm_timer *t);
217 #else
219 static int unix_start_timer(struct qemu_alarm_timer *t);
220 static void unix_stop_timer(struct qemu_alarm_timer *t);
222 #ifdef __linux__
224 static int dynticks_start_timer(struct qemu_alarm_timer *t);
225 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
226 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
228 #endif /* __linux__ */
230 #endif /* _WIN32 */
232 /* Correlation between real and virtual time is always going to be
233 fairly approximate, so ignore small variation.
234 When the guest is idle real and virtual time will be aligned in
235 the IO wait loop. */
236 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
238 static void icount_adjust(void)
240 int64_t cur_time;
241 int64_t cur_icount;
242 int64_t delta;
243 static int64_t last_delta;
244 /* If the VM is not running, then do nothing. */
245 if (!vm_running)
246 return;
248 cur_time = cpu_get_clock();
249 cur_icount = qemu_get_clock_ns(vm_clock);
250 delta = cur_icount - cur_time;
251 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
252 if (delta > 0
253 && last_delta + ICOUNT_WOBBLE < delta * 2
254 && icount_time_shift > 0) {
255 /* The guest is getting too far ahead. Slow time down. */
256 icount_time_shift--;
258 if (delta < 0
259 && last_delta - ICOUNT_WOBBLE > delta * 2
260 && icount_time_shift < MAX_ICOUNT_SHIFT) {
261 /* The guest is getting too far behind. Speed time up. */
262 icount_time_shift++;
264 last_delta = delta;
265 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
268 static void icount_adjust_rt(void * opaque)
270 qemu_mod_timer(icount_rt_timer,
271 qemu_get_clock_ms(rt_clock) + 1000);
272 icount_adjust();
275 static void icount_adjust_vm(void * opaque)
277 qemu_mod_timer(icount_vm_timer,
278 qemu_get_clock_ns(vm_clock) + get_ticks_per_sec() / 10);
279 icount_adjust();
282 int64_t qemu_icount_round(int64_t count)
284 return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
287 static struct qemu_alarm_timer alarm_timers[] = {
288 #ifndef _WIN32
289 #ifdef __linux__
290 {"dynticks", dynticks_start_timer,
291 dynticks_stop_timer, dynticks_rearm_timer},
292 #endif
293 {"unix", unix_start_timer, unix_stop_timer, NULL},
294 #else
295 {"mmtimer", mm_start_timer, mm_stop_timer, NULL},
296 {"mmtimer2", mm_start_timer, mm_stop_timer, mm_rearm_timer},
297 {"dynticks", win32_start_timer, win32_stop_timer, win32_rearm_timer},
298 {"win32", win32_start_timer, win32_stop_timer, NULL},
299 #endif
300 {NULL, }
303 static void show_available_alarms(void)
305 int i;
307 printf("Available alarm timers, in order of precedence:\n");
308 for (i = 0; alarm_timers[i].name; i++)
309 printf("%s\n", alarm_timers[i].name);
312 void configure_alarms(char const *opt)
314 int i;
315 int cur = 0;
316 int count = ARRAY_SIZE(alarm_timers) - 1;
317 char *arg;
318 char *name;
319 struct qemu_alarm_timer tmp;
321 if (!strcmp(opt, "?")) {
322 show_available_alarms();
323 exit(0);
326 arg = qemu_strdup(opt);
328 /* Reorder the array */
329 name = strtok(arg, ",");
330 while (name) {
331 for (i = 0; i < count && alarm_timers[i].name; i++) {
332 if (!strcmp(alarm_timers[i].name, name))
333 break;
336 if (i == count) {
337 fprintf(stderr, "Unknown clock %s\n", name);
338 goto next;
341 if (i < cur)
342 /* Ignore */
343 goto next;
345 /* Swap */
346 tmp = alarm_timers[i];
347 alarm_timers[i] = alarm_timers[cur];
348 alarm_timers[cur] = tmp;
350 cur++;
351 next:
352 name = strtok(NULL, ",");
355 qemu_free(arg);
357 if (cur) {
358 /* Disable remaining timers */
359 for (i = cur; i < count; i++)
360 alarm_timers[i].name = NULL;
361 } else {
362 show_available_alarms();
363 exit(1);
367 #define QEMU_NUM_CLOCKS 3
369 QEMUClock *rt_clock;
370 QEMUClock *vm_clock;
371 QEMUClock *host_clock;
373 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
375 static QEMUClock *qemu_new_clock(int type)
377 QEMUClock *clock;
378 clock = qemu_mallocz(sizeof(QEMUClock));
379 clock->type = type;
380 clock->enabled = 1;
381 return clock;
384 void qemu_clock_enable(QEMUClock *clock, int enabled)
386 clock->enabled = enabled;
389 static int64_t vm_clock_warp_start;
391 static void icount_warp_rt(void *opaque)
393 if (vm_clock_warp_start == -1) {
394 return;
397 if (vm_running) {
398 int64_t clock = qemu_get_clock_ns(rt_clock);
399 int64_t warp_delta = clock - vm_clock_warp_start;
400 if (use_icount == 1) {
401 qemu_icount_bias += warp_delta;
402 } else {
404 * In adaptive mode, do not let the vm_clock run too
405 * far ahead of real time.
407 int64_t cur_time = cpu_get_clock();
408 int64_t cur_icount = qemu_get_clock_ns(vm_clock);
409 int64_t delta = cur_time - cur_icount;
410 qemu_icount_bias += MIN(warp_delta, delta);
412 if (qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
413 qemu_get_clock_ns(vm_clock))) {
414 qemu_notify_event();
417 vm_clock_warp_start = -1;
420 void qemu_clock_warp(QEMUClock *clock)
422 int64_t deadline;
424 if (!clock->warp_timer) {
425 return;
429 * There are too many global variables to make the "warp" behavior
430 * applicable to other clocks. But a clock argument removes the
431 * need for if statements all over the place.
433 assert(clock == vm_clock);
436 * If the CPUs have been sleeping, advance the vm_clock timer now. This
437 * ensures that the deadline for the timer is computed correctly below.
438 * This also makes sure that the insn counter is synchronized before the
439 * CPU starts running, in case the CPU is woken by an event other than
440 * the earliest vm_clock timer.
442 icount_warp_rt(NULL);
443 if (!all_cpu_threads_idle() || !active_timers[clock->type]) {
444 qemu_del_timer(clock->warp_timer);
445 return;
448 vm_clock_warp_start = qemu_get_clock_ns(rt_clock);
449 deadline = qemu_next_icount_deadline();
450 if (deadline > 0) {
452 * Ensure the vm_clock proceeds even when the virtual CPU goes to
453 * sleep. Otherwise, the CPU might be waiting for a future timer
454 * interrupt to wake it up, but the interrupt never comes because
455 * the vCPU isn't running any insns and thus doesn't advance the
456 * vm_clock.
458 * An extreme solution for this problem would be to never let VCPUs
459 * sleep in icount mode if there is a pending vm_clock timer; rather
460 * time could just advance to the next vm_clock event. Instead, we
461 * do stop VCPUs and only advance vm_clock after some "real" time,
462 * (related to the time left until the next event) has passed. This
463 * rt_clock timer will do this. This avoids that the warps are too
464 * visible externally---for example, you will not be sending network
465 * packets continously instead of every 100ms.
467 qemu_mod_timer(clock->warp_timer, vm_clock_warp_start + deadline);
468 } else {
469 qemu_notify_event();
473 QEMUTimer *qemu_new_timer(QEMUClock *clock, int scale,
474 QEMUTimerCB *cb, void *opaque)
476 QEMUTimer *ts;
478 ts = qemu_mallocz(sizeof(QEMUTimer));
479 ts->clock = clock;
480 ts->cb = cb;
481 ts->opaque = opaque;
482 ts->scale = scale;
483 return ts;
486 void qemu_free_timer(QEMUTimer *ts)
488 qemu_free(ts);
491 /* stop a timer, but do not dealloc it */
492 void qemu_del_timer(QEMUTimer *ts)
494 QEMUTimer **pt, *t;
496 /* NOTE: this code must be signal safe because
497 qemu_timer_expired() can be called from a signal. */
498 pt = &active_timers[ts->clock->type];
499 for(;;) {
500 t = *pt;
501 if (!t)
502 break;
503 if (t == ts) {
504 *pt = t->next;
505 break;
507 pt = &t->next;
511 /* modify the current timer so that it will be fired when current_time
512 >= expire_time. The corresponding callback will be called. */
513 static void qemu_mod_timer_ns(QEMUTimer *ts, int64_t expire_time)
515 QEMUTimer **pt, *t;
517 qemu_del_timer(ts);
519 /* add the timer in the sorted list */
520 /* NOTE: this code must be signal safe because
521 qemu_timer_expired() can be called from a signal. */
522 pt = &active_timers[ts->clock->type];
523 for(;;) {
524 t = *pt;
525 if (!qemu_timer_expired_ns(t, expire_time)) {
526 break;
528 pt = &t->next;
530 ts->expire_time = expire_time;
531 ts->next = *pt;
532 *pt = ts;
534 /* Rearm if necessary */
535 if (pt == &active_timers[ts->clock->type]) {
536 if (!alarm_timer->pending) {
537 qemu_rearm_alarm_timer(alarm_timer);
539 /* Interrupt execution to force deadline recalculation. */
540 qemu_clock_warp(ts->clock);
541 if (use_icount) {
542 qemu_notify_event();
547 /* modify the current timer so that it will be fired when current_time
548 >= expire_time. The corresponding callback will be called. */
549 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
551 qemu_mod_timer_ns(ts, expire_time * ts->scale);
554 int qemu_timer_pending(QEMUTimer *ts)
556 QEMUTimer *t;
557 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
558 if (t == ts)
559 return 1;
561 return 0;
564 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
566 return qemu_timer_expired_ns(timer_head, current_time * timer_head->scale);
569 static void qemu_run_timers(QEMUClock *clock)
571 QEMUTimer **ptimer_head, *ts;
572 int64_t current_time;
574 if (!clock->enabled)
575 return;
577 current_time = qemu_get_clock_ns(clock);
578 ptimer_head = &active_timers[clock->type];
579 for(;;) {
580 ts = *ptimer_head;
581 if (!qemu_timer_expired_ns(ts, current_time)) {
582 break;
584 /* remove timer from the list before calling the callback */
585 *ptimer_head = ts->next;
586 ts->next = NULL;
588 /* run the callback (the timer list can be modified) */
589 ts->cb(ts->opaque);
593 int64_t qemu_get_clock_ns(QEMUClock *clock)
595 switch(clock->type) {
596 case QEMU_CLOCK_REALTIME:
597 return get_clock();
598 default:
599 case QEMU_CLOCK_VIRTUAL:
600 if (use_icount) {
601 return cpu_get_icount();
602 } else {
603 return cpu_get_clock();
605 case QEMU_CLOCK_HOST:
606 return get_clock_realtime();
610 void init_clocks(void)
612 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
613 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
614 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
616 rtc_clock = host_clock;
619 /* save a timer */
620 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
622 uint64_t expire_time;
624 if (qemu_timer_pending(ts)) {
625 expire_time = ts->expire_time;
626 } else {
627 expire_time = -1;
629 qemu_put_be64(f, expire_time);
632 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
634 uint64_t expire_time;
636 expire_time = qemu_get_be64(f);
637 if (expire_time != -1) {
638 qemu_mod_timer_ns(ts, expire_time);
639 } else {
640 qemu_del_timer(ts);
644 static const VMStateDescription vmstate_timers = {
645 .name = "timer",
646 .version_id = 2,
647 .minimum_version_id = 1,
648 .minimum_version_id_old = 1,
649 .fields = (VMStateField []) {
650 VMSTATE_INT64(cpu_ticks_offset, TimersState),
651 VMSTATE_INT64(dummy, TimersState),
652 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
653 VMSTATE_END_OF_LIST()
657 void configure_icount(const char *option)
659 vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
660 if (!option)
661 return;
663 #ifdef CONFIG_IOTHREAD
664 vm_clock->warp_timer = qemu_new_timer_ns(rt_clock, icount_warp_rt, NULL);
665 #endif
667 if (strcmp(option, "auto") != 0) {
668 icount_time_shift = strtol(option, NULL, 0);
669 use_icount = 1;
670 return;
673 use_icount = 2;
675 /* 125MIPS seems a reasonable initial guess at the guest speed.
676 It will be corrected fairly quickly anyway. */
677 icount_time_shift = 3;
679 /* Have both realtime and virtual time triggers for speed adjustment.
680 The realtime trigger catches emulated time passing too slowly,
681 the virtual time trigger catches emulated time passing too fast.
682 Realtime triggers occur even when idle, so use them less frequently
683 than VM triggers. */
684 icount_rt_timer = qemu_new_timer_ms(rt_clock, icount_adjust_rt, NULL);
685 qemu_mod_timer(icount_rt_timer,
686 qemu_get_clock_ms(rt_clock) + 1000);
687 icount_vm_timer = qemu_new_timer_ns(vm_clock, icount_adjust_vm, NULL);
688 qemu_mod_timer(icount_vm_timer,
689 qemu_get_clock_ns(vm_clock) + get_ticks_per_sec() / 10);
692 void qemu_run_all_timers(void)
694 alarm_timer->pending = 0;
696 /* rearm timer, if not periodic */
697 if (alarm_timer->expired) {
698 alarm_timer->expired = 0;
699 qemu_rearm_alarm_timer(alarm_timer);
702 /* vm time timers */
703 if (vm_running) {
704 qemu_run_timers(vm_clock);
707 qemu_run_timers(rt_clock);
708 qemu_run_timers(host_clock);
711 static int64_t qemu_next_alarm_deadline(void);
713 #ifdef _WIN32
714 static void CALLBACK host_alarm_handler(PVOID lpParam, BOOLEAN unused)
715 #else
716 static void host_alarm_handler(int host_signum)
717 #endif
719 struct qemu_alarm_timer *t = alarm_timer;
720 if (!t)
721 return;
723 #if 0
724 #define DISP_FREQ 1000
726 static int64_t delta_min = INT64_MAX;
727 static int64_t delta_max, delta_cum, last_clock, delta, ti;
728 static int count;
729 ti = qemu_get_clock_ns(vm_clock);
730 if (last_clock != 0) {
731 delta = ti - last_clock;
732 if (delta < delta_min)
733 delta_min = delta;
734 if (delta > delta_max)
735 delta_max = delta;
736 delta_cum += delta;
737 if (++count == DISP_FREQ) {
738 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
739 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
740 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
741 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
742 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
743 count = 0;
744 delta_min = INT64_MAX;
745 delta_max = 0;
746 delta_cum = 0;
749 last_clock = ti;
751 #endif
752 if (alarm_has_dynticks(t) ||
753 qemu_next_alarm_deadline () <= 0) {
754 t->expired = alarm_has_dynticks(t);
755 t->pending = 1;
756 qemu_notify_event();
760 int64_t qemu_next_icount_deadline(void)
762 /* To avoid problems with overflow limit this to 2^32. */
763 int64_t delta = INT32_MAX;
765 assert(use_icount);
766 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
767 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
768 qemu_get_clock_ns(vm_clock);
771 if (delta < 0)
772 delta = 0;
774 return delta;
777 static int64_t qemu_next_alarm_deadline(void)
779 int64_t delta;
780 int64_t rtdelta;
782 if (!use_icount && active_timers[QEMU_CLOCK_VIRTUAL]) {
783 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
784 qemu_get_clock_ns(vm_clock);
785 } else {
786 delta = INT32_MAX;
788 if (active_timers[QEMU_CLOCK_HOST]) {
789 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
790 qemu_get_clock_ns(host_clock);
791 if (hdelta < delta)
792 delta = hdelta;
794 if (active_timers[QEMU_CLOCK_REALTIME]) {
795 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
796 qemu_get_clock_ns(rt_clock));
797 if (rtdelta < delta)
798 delta = rtdelta;
801 return delta;
804 #if defined(__linux__)
806 static int dynticks_start_timer(struct qemu_alarm_timer *t)
808 struct sigevent ev;
809 timer_t host_timer;
810 struct sigaction act;
812 sigfillset(&act.sa_mask);
813 act.sa_flags = 0;
814 act.sa_handler = host_alarm_handler;
816 sigaction(SIGALRM, &act, NULL);
819 * Initialize ev struct to 0 to avoid valgrind complaining
820 * about uninitialized data in timer_create call
822 memset(&ev, 0, sizeof(ev));
823 ev.sigev_value.sival_int = 0;
824 ev.sigev_notify = SIGEV_SIGNAL;
825 ev.sigev_signo = SIGALRM;
827 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
828 perror("timer_create");
830 /* disable dynticks */
831 fprintf(stderr, "Dynamic Ticks disabled\n");
833 return -1;
836 t->timer = host_timer;
838 return 0;
841 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
843 timer_t host_timer = t->timer;
845 timer_delete(host_timer);
848 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
850 timer_t host_timer = t->timer;
851 struct itimerspec timeout;
852 int64_t nearest_delta_ns = INT64_MAX;
853 int64_t current_ns;
855 assert(alarm_has_dynticks(t));
856 if (!active_timers[QEMU_CLOCK_REALTIME] &&
857 !active_timers[QEMU_CLOCK_VIRTUAL] &&
858 !active_timers[QEMU_CLOCK_HOST])
859 return;
861 nearest_delta_ns = qemu_next_alarm_deadline();
862 if (nearest_delta_ns < MIN_TIMER_REARM_NS)
863 nearest_delta_ns = MIN_TIMER_REARM_NS;
865 /* check whether a timer is already running */
866 if (timer_gettime(host_timer, &timeout)) {
867 perror("gettime");
868 fprintf(stderr, "Internal timer error: aborting\n");
869 exit(1);
871 current_ns = timeout.it_value.tv_sec * 1000000000LL + timeout.it_value.tv_nsec;
872 if (current_ns && current_ns <= nearest_delta_ns)
873 return;
875 timeout.it_interval.tv_sec = 0;
876 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
877 timeout.it_value.tv_sec = nearest_delta_ns / 1000000000;
878 timeout.it_value.tv_nsec = nearest_delta_ns % 1000000000;
879 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
880 perror("settime");
881 fprintf(stderr, "Internal timer error: aborting\n");
882 exit(1);
886 #endif /* defined(__linux__) */
888 #if !defined(_WIN32)
890 static int unix_start_timer(struct qemu_alarm_timer *t)
892 struct sigaction act;
893 struct itimerval itv;
894 int err;
896 /* timer signal */
897 sigfillset(&act.sa_mask);
898 act.sa_flags = 0;
899 act.sa_handler = host_alarm_handler;
901 sigaction(SIGALRM, &act, NULL);
903 itv.it_interval.tv_sec = 0;
904 /* for i386 kernel 2.6 to get 1 ms */
905 itv.it_interval.tv_usec = 999;
906 itv.it_value.tv_sec = 0;
907 itv.it_value.tv_usec = 10 * 1000;
909 err = setitimer(ITIMER_REAL, &itv, NULL);
910 if (err)
911 return -1;
913 return 0;
916 static void unix_stop_timer(struct qemu_alarm_timer *t)
918 struct itimerval itv;
920 memset(&itv, 0, sizeof(itv));
921 setitimer(ITIMER_REAL, &itv, NULL);
924 #endif /* !defined(_WIN32) */
927 #ifdef _WIN32
929 static MMRESULT mm_timer;
930 static unsigned mm_period;
932 static void CALLBACK mm_alarm_handler(UINT uTimerID, UINT uMsg,
933 DWORD_PTR dwUser, DWORD_PTR dw1,
934 DWORD_PTR dw2)
936 struct qemu_alarm_timer *t = alarm_timer;
937 if (!t) {
938 return;
940 if (alarm_has_dynticks(t) || qemu_next_alarm_deadline() <= 0) {
941 t->expired = alarm_has_dynticks(t);
942 t->pending = 1;
943 qemu_notify_event();
947 static int mm_start_timer(struct qemu_alarm_timer *t)
949 TIMECAPS tc;
950 UINT flags;
952 memset(&tc, 0, sizeof(tc));
953 timeGetDevCaps(&tc, sizeof(tc));
955 mm_period = tc.wPeriodMin;
956 timeBeginPeriod(mm_period);
958 flags = TIME_CALLBACK_FUNCTION;
959 if (alarm_has_dynticks(t)) {
960 flags |= TIME_ONESHOT;
961 } else {
962 flags |= TIME_PERIODIC;
965 mm_timer = timeSetEvent(1, /* interval (ms) */
966 mm_period, /* resolution */
967 mm_alarm_handler, /* function */
968 (DWORD_PTR)t, /* parameter */
969 flags);
971 if (!mm_timer) {
972 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
973 GetLastError());
974 timeEndPeriod(mm_period);
975 return -1;
978 return 0;
981 static void mm_stop_timer(struct qemu_alarm_timer *t)
983 timeKillEvent(mm_timer);
984 timeEndPeriod(mm_period);
987 static void mm_rearm_timer(struct qemu_alarm_timer *t)
989 int nearest_delta_ms;
991 assert(alarm_has_dynticks(t));
992 if (!active_timers[QEMU_CLOCK_REALTIME] &&
993 !active_timers[QEMU_CLOCK_VIRTUAL] &&
994 !active_timers[QEMU_CLOCK_HOST]) {
995 return;
998 timeKillEvent(mm_timer);
1000 nearest_delta_ms = (qemu_next_alarm_deadline() + 999999) / 1000000;
1001 if (nearest_delta_ms < 1) {
1002 nearest_delta_ms = 1;
1004 mm_timer = timeSetEvent(nearest_delta_ms,
1005 mm_period,
1006 mm_alarm_handler,
1007 (DWORD_PTR)t,
1008 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1010 if (!mm_timer) {
1011 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1012 GetLastError());
1014 timeEndPeriod(mm_period);
1015 exit(1);
1019 static int win32_start_timer(struct qemu_alarm_timer *t)
1021 HANDLE hTimer;
1022 BOOLEAN success;
1024 /* If you call ChangeTimerQueueTimer on a one-shot timer (its period
1025 is zero) that has already expired, the timer is not updated. Since
1026 creating a new timer is relatively expensive, set a bogus one-hour
1027 interval in the dynticks case. */
1028 success = CreateTimerQueueTimer(&hTimer,
1029 NULL,
1030 host_alarm_handler,
1033 alarm_has_dynticks(t) ? 3600000 : 1,
1034 WT_EXECUTEINTIMERTHREAD);
1036 if (!success) {
1037 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1038 GetLastError());
1039 return -1;
1042 t->timer = hTimer;
1043 return 0;
1046 static void win32_stop_timer(struct qemu_alarm_timer *t)
1048 HANDLE hTimer = t->timer;
1050 if (hTimer) {
1051 DeleteTimerQueueTimer(NULL, hTimer, NULL);
1055 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1057 HANDLE hTimer = t->timer;
1058 int nearest_delta_ms;
1059 BOOLEAN success;
1061 assert(alarm_has_dynticks(t));
1062 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1063 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1064 !active_timers[QEMU_CLOCK_HOST])
1065 return;
1067 nearest_delta_ms = (qemu_next_alarm_deadline() + 999999) / 1000000;
1068 if (nearest_delta_ms < 1) {
1069 nearest_delta_ms = 1;
1071 success = ChangeTimerQueueTimer(NULL,
1072 hTimer,
1073 nearest_delta_ms,
1074 3600000);
1076 if (!success) {
1077 fprintf(stderr, "Failed to rearm win32 alarm timer: %ld\n",
1078 GetLastError());
1079 exit(-1);
1084 #endif /* _WIN32 */
1086 static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1088 if (running)
1089 qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1092 int init_timer_alarm(void)
1094 struct qemu_alarm_timer *t = NULL;
1095 int i, err = -1;
1097 for (i = 0; alarm_timers[i].name; i++) {
1098 t = &alarm_timers[i];
1100 err = t->start(t);
1101 if (!err)
1102 break;
1105 if (err) {
1106 err = -ENOENT;
1107 goto fail;
1110 /* first event is at time 0 */
1111 t->pending = 1;
1112 alarm_timer = t;
1113 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1115 return 0;
1117 fail:
1118 return err;
1121 void quit_timers(void)
1123 struct qemu_alarm_timer *t = alarm_timer;
1124 alarm_timer = NULL;
1125 t->stop(t);
1128 int qemu_calculate_timeout(void)
1130 #ifndef CONFIG_IOTHREAD
1131 int timeout;
1133 if (!vm_running)
1134 timeout = 5000;
1135 else {
1136 /* XXX: use timeout computed from timers */
1137 int64_t add;
1138 int64_t delta;
1139 /* Advance virtual time to the next event. */
1140 delta = qemu_icount_delta();
1141 if (delta > 0) {
1142 /* If virtual time is ahead of real time then just
1143 wait for IO. */
1144 timeout = (delta + 999999) / 1000000;
1145 } else {
1146 /* Wait for either IO to occur or the next
1147 timer event. */
1148 add = qemu_next_icount_deadline();
1149 /* We advance the timer before checking for IO.
1150 Limit the amount we advance so that early IO
1151 activity won't get the guest too far ahead. */
1152 if (add > 10000000)
1153 add = 10000000;
1154 delta += add;
1155 qemu_icount += qemu_icount_round (add);
1156 timeout = delta / 1000000;
1157 if (timeout < 0)
1158 timeout = 0;
1162 return timeout;
1163 #else /* CONFIG_IOTHREAD */
1164 return 1000;
1165 #endif