notifier: Pass data argument to callback
[qemu/stefanha.git] / qemu-timer.c
blob67c2974959891ff022f47307671afb46127a81cf
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);
221 static void unix_rearm_timer(struct qemu_alarm_timer *t);
223 #ifdef __linux__
225 static int dynticks_start_timer(struct qemu_alarm_timer *t);
226 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
227 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
229 #endif /* __linux__ */
231 #endif /* _WIN32 */
233 /* Correlation between real and virtual time is always going to be
234 fairly approximate, so ignore small variation.
235 When the guest is idle real and virtual time will be aligned in
236 the IO wait loop. */
237 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
239 static void icount_adjust(void)
241 int64_t cur_time;
242 int64_t cur_icount;
243 int64_t delta;
244 static int64_t last_delta;
245 /* If the VM is not running, then do nothing. */
246 if (!vm_running)
247 return;
249 cur_time = cpu_get_clock();
250 cur_icount = qemu_get_clock_ns(vm_clock);
251 delta = cur_icount - cur_time;
252 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
253 if (delta > 0
254 && last_delta + ICOUNT_WOBBLE < delta * 2
255 && icount_time_shift > 0) {
256 /* The guest is getting too far ahead. Slow time down. */
257 icount_time_shift--;
259 if (delta < 0
260 && last_delta - ICOUNT_WOBBLE > delta * 2
261 && icount_time_shift < MAX_ICOUNT_SHIFT) {
262 /* The guest is getting too far behind. Speed time up. */
263 icount_time_shift++;
265 last_delta = delta;
266 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
269 static void icount_adjust_rt(void * opaque)
271 qemu_mod_timer(icount_rt_timer,
272 qemu_get_clock_ms(rt_clock) + 1000);
273 icount_adjust();
276 static void icount_adjust_vm(void * opaque)
278 qemu_mod_timer(icount_vm_timer,
279 qemu_get_clock_ns(vm_clock) + get_ticks_per_sec() / 10);
280 icount_adjust();
283 int64_t qemu_icount_round(int64_t count)
285 return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
288 static struct qemu_alarm_timer alarm_timers[] = {
289 #ifndef _WIN32
290 #ifdef __linux__
291 {"dynticks", dynticks_start_timer,
292 dynticks_stop_timer, dynticks_rearm_timer},
293 #endif
294 {"unix", unix_start_timer, unix_stop_timer, unix_rearm_timer},
295 #else
296 {"mmtimer", mm_start_timer, mm_stop_timer, NULL},
297 {"mmtimer2", mm_start_timer, mm_stop_timer, mm_rearm_timer},
298 {"dynticks", win32_start_timer, win32_stop_timer, win32_rearm_timer},
299 {"win32", win32_start_timer, win32_stop_timer, NULL},
300 #endif
301 {NULL, }
304 static void show_available_alarms(void)
306 int i;
308 printf("Available alarm timers, in order of precedence:\n");
309 for (i = 0; alarm_timers[i].name; i++)
310 printf("%s\n", alarm_timers[i].name);
313 void configure_alarms(char const *opt)
315 int i;
316 int cur = 0;
317 int count = ARRAY_SIZE(alarm_timers) - 1;
318 char *arg;
319 char *name;
320 struct qemu_alarm_timer tmp;
322 if (!strcmp(opt, "?")) {
323 show_available_alarms();
324 exit(0);
327 arg = qemu_strdup(opt);
329 /* Reorder the array */
330 name = strtok(arg, ",");
331 while (name) {
332 for (i = 0; i < count && alarm_timers[i].name; i++) {
333 if (!strcmp(alarm_timers[i].name, name))
334 break;
337 if (i == count) {
338 fprintf(stderr, "Unknown clock %s\n", name);
339 goto next;
342 if (i < cur)
343 /* Ignore */
344 goto next;
346 /* Swap */
347 tmp = alarm_timers[i];
348 alarm_timers[i] = alarm_timers[cur];
349 alarm_timers[cur] = tmp;
351 cur++;
352 next:
353 name = strtok(NULL, ",");
356 qemu_free(arg);
358 if (cur) {
359 /* Disable remaining timers */
360 for (i = cur; i < count; i++)
361 alarm_timers[i].name = NULL;
362 } else {
363 show_available_alarms();
364 exit(1);
368 #define QEMU_NUM_CLOCKS 3
370 QEMUClock *rt_clock;
371 QEMUClock *vm_clock;
372 QEMUClock *host_clock;
374 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
376 static QEMUClock *qemu_new_clock(int type)
378 QEMUClock *clock;
379 clock = qemu_mallocz(sizeof(QEMUClock));
380 clock->type = type;
381 clock->enabled = 1;
382 return clock;
385 void qemu_clock_enable(QEMUClock *clock, int enabled)
387 clock->enabled = enabled;
390 static int64_t vm_clock_warp_start;
392 static void icount_warp_rt(void *opaque)
394 if (vm_clock_warp_start == -1) {
395 return;
398 if (vm_running) {
399 int64_t clock = qemu_get_clock_ns(rt_clock);
400 int64_t warp_delta = clock - vm_clock_warp_start;
401 if (use_icount == 1) {
402 qemu_icount_bias += warp_delta;
403 } else {
405 * In adaptive mode, do not let the vm_clock run too
406 * far ahead of real time.
408 int64_t cur_time = cpu_get_clock();
409 int64_t cur_icount = qemu_get_clock_ns(vm_clock);
410 int64_t delta = cur_time - cur_icount;
411 qemu_icount_bias += MIN(warp_delta, delta);
413 if (qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
414 qemu_get_clock_ns(vm_clock))) {
415 qemu_notify_event();
418 vm_clock_warp_start = -1;
421 void qemu_clock_warp(QEMUClock *clock)
423 int64_t deadline;
425 if (!clock->warp_timer) {
426 return;
430 * There are too many global variables to make the "warp" behavior
431 * applicable to other clocks. But a clock argument removes the
432 * need for if statements all over the place.
434 assert(clock == vm_clock);
437 * If the CPUs have been sleeping, advance the vm_clock timer now. This
438 * ensures that the deadline for the timer is computed correctly below.
439 * This also makes sure that the insn counter is synchronized before the
440 * CPU starts running, in case the CPU is woken by an event other than
441 * the earliest vm_clock timer.
443 icount_warp_rt(NULL);
444 if (!all_cpu_threads_idle() || !active_timers[clock->type]) {
445 qemu_del_timer(clock->warp_timer);
446 return;
449 vm_clock_warp_start = qemu_get_clock_ns(rt_clock);
450 deadline = qemu_next_icount_deadline();
451 if (deadline > 0) {
453 * Ensure the vm_clock proceeds even when the virtual CPU goes to
454 * sleep. Otherwise, the CPU might be waiting for a future timer
455 * interrupt to wake it up, but the interrupt never comes because
456 * the vCPU isn't running any insns and thus doesn't advance the
457 * vm_clock.
459 * An extreme solution for this problem would be to never let VCPUs
460 * sleep in icount mode if there is a pending vm_clock timer; rather
461 * time could just advance to the next vm_clock event. Instead, we
462 * do stop VCPUs and only advance vm_clock after some "real" time,
463 * (related to the time left until the next event) has passed. This
464 * rt_clock timer will do this. This avoids that the warps are too
465 * visible externally---for example, you will not be sending network
466 * packets continously instead of every 100ms.
468 qemu_mod_timer(clock->warp_timer, vm_clock_warp_start + deadline);
469 } else {
470 qemu_notify_event();
474 QEMUTimer *qemu_new_timer(QEMUClock *clock, int scale,
475 QEMUTimerCB *cb, void *opaque)
477 QEMUTimer *ts;
479 ts = qemu_mallocz(sizeof(QEMUTimer));
480 ts->clock = clock;
481 ts->cb = cb;
482 ts->opaque = opaque;
483 ts->scale = scale;
484 return ts;
487 void qemu_free_timer(QEMUTimer *ts)
489 qemu_free(ts);
492 /* stop a timer, but do not dealloc it */
493 void qemu_del_timer(QEMUTimer *ts)
495 QEMUTimer **pt, *t;
497 /* NOTE: this code must be signal safe because
498 qemu_timer_expired() can be called from a signal. */
499 pt = &active_timers[ts->clock->type];
500 for(;;) {
501 t = *pt;
502 if (!t)
503 break;
504 if (t == ts) {
505 *pt = t->next;
506 break;
508 pt = &t->next;
512 /* modify the current timer so that it will be fired when current_time
513 >= expire_time. The corresponding callback will be called. */
514 static void qemu_mod_timer_ns(QEMUTimer *ts, int64_t expire_time)
516 QEMUTimer **pt, *t;
518 qemu_del_timer(ts);
520 /* add the timer in the sorted list */
521 /* NOTE: this code must be signal safe because
522 qemu_timer_expired() can be called from a signal. */
523 pt = &active_timers[ts->clock->type];
524 for(;;) {
525 t = *pt;
526 if (!qemu_timer_expired_ns(t, expire_time)) {
527 break;
529 pt = &t->next;
531 ts->expire_time = expire_time;
532 ts->next = *pt;
533 *pt = ts;
535 /* Rearm if necessary */
536 if (pt == &active_timers[ts->clock->type]) {
537 if (!alarm_timer->pending) {
538 qemu_rearm_alarm_timer(alarm_timer);
540 /* Interrupt execution to force deadline recalculation. */
541 qemu_clock_warp(ts->clock);
542 if (use_icount) {
543 qemu_notify_event();
548 /* modify the current timer so that it will be fired when current_time
549 >= expire_time. The corresponding callback will be called. */
550 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
552 qemu_mod_timer_ns(ts, expire_time * ts->scale);
555 int qemu_timer_pending(QEMUTimer *ts)
557 QEMUTimer *t;
558 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
559 if (t == ts)
560 return 1;
562 return 0;
565 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
567 return qemu_timer_expired_ns(timer_head, current_time * timer_head->scale);
570 static void qemu_run_timers(QEMUClock *clock)
572 QEMUTimer **ptimer_head, *ts;
573 int64_t current_time;
575 if (!clock->enabled)
576 return;
578 current_time = qemu_get_clock_ns(clock);
579 ptimer_head = &active_timers[clock->type];
580 for(;;) {
581 ts = *ptimer_head;
582 if (!qemu_timer_expired_ns(ts, current_time)) {
583 break;
585 /* remove timer from the list before calling the callback */
586 *ptimer_head = ts->next;
587 ts->next = NULL;
589 /* run the callback (the timer list can be modified) */
590 ts->cb(ts->opaque);
594 int64_t qemu_get_clock_ns(QEMUClock *clock)
596 switch(clock->type) {
597 case QEMU_CLOCK_REALTIME:
598 return get_clock();
599 default:
600 case QEMU_CLOCK_VIRTUAL:
601 if (use_icount) {
602 return cpu_get_icount();
603 } else {
604 return cpu_get_clock();
606 case QEMU_CLOCK_HOST:
607 return get_clock_realtime();
611 void init_clocks(void)
613 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
614 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
615 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
617 rtc_clock = host_clock;
620 /* save a timer */
621 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
623 uint64_t expire_time;
625 if (qemu_timer_pending(ts)) {
626 expire_time = ts->expire_time;
627 } else {
628 expire_time = -1;
630 qemu_put_be64(f, expire_time);
633 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
635 uint64_t expire_time;
637 expire_time = qemu_get_be64(f);
638 if (expire_time != -1) {
639 qemu_mod_timer_ns(ts, expire_time);
640 } else {
641 qemu_del_timer(ts);
645 static const VMStateDescription vmstate_timers = {
646 .name = "timer",
647 .version_id = 2,
648 .minimum_version_id = 1,
649 .minimum_version_id_old = 1,
650 .fields = (VMStateField []) {
651 VMSTATE_INT64(cpu_ticks_offset, TimersState),
652 VMSTATE_INT64(dummy, TimersState),
653 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
654 VMSTATE_END_OF_LIST()
658 void configure_icount(const char *option)
660 vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
661 if (!option)
662 return;
664 #ifdef CONFIG_IOTHREAD
665 vm_clock->warp_timer = qemu_new_timer_ns(rt_clock, icount_warp_rt, NULL);
666 #endif
668 if (strcmp(option, "auto") != 0) {
669 icount_time_shift = strtol(option, NULL, 0);
670 use_icount = 1;
671 return;
674 use_icount = 2;
676 /* 125MIPS seems a reasonable initial guess at the guest speed.
677 It will be corrected fairly quickly anyway. */
678 icount_time_shift = 3;
680 /* Have both realtime and virtual time triggers for speed adjustment.
681 The realtime trigger catches emulated time passing too slowly,
682 the virtual time trigger catches emulated time passing too fast.
683 Realtime triggers occur even when idle, so use them less frequently
684 than VM triggers. */
685 icount_rt_timer = qemu_new_timer_ms(rt_clock, icount_adjust_rt, NULL);
686 qemu_mod_timer(icount_rt_timer,
687 qemu_get_clock_ms(rt_clock) + 1000);
688 icount_vm_timer = qemu_new_timer_ns(vm_clock, icount_adjust_vm, NULL);
689 qemu_mod_timer(icount_vm_timer,
690 qemu_get_clock_ns(vm_clock) + get_ticks_per_sec() / 10);
693 void qemu_run_all_timers(void)
695 alarm_timer->pending = 0;
697 /* rearm timer, if not periodic */
698 if (alarm_timer->expired) {
699 alarm_timer->expired = 0;
700 qemu_rearm_alarm_timer(alarm_timer);
703 /* vm time timers */
704 if (vm_running) {
705 qemu_run_timers(vm_clock);
708 qemu_run_timers(rt_clock);
709 qemu_run_timers(host_clock);
712 static int64_t qemu_next_alarm_deadline(void);
714 #ifdef _WIN32
715 static void CALLBACK host_alarm_handler(PVOID lpParam, BOOLEAN unused)
716 #else
717 static void host_alarm_handler(int host_signum)
718 #endif
720 struct qemu_alarm_timer *t = alarm_timer;
721 if (!t)
722 return;
724 #if 0
725 #define DISP_FREQ 1000
727 static int64_t delta_min = INT64_MAX;
728 static int64_t delta_max, delta_cum, last_clock, delta, ti;
729 static int count;
730 ti = qemu_get_clock_ns(vm_clock);
731 if (last_clock != 0) {
732 delta = ti - last_clock;
733 if (delta < delta_min)
734 delta_min = delta;
735 if (delta > delta_max)
736 delta_max = delta;
737 delta_cum += delta;
738 if (++count == DISP_FREQ) {
739 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
740 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
741 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
742 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
743 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
744 count = 0;
745 delta_min = INT64_MAX;
746 delta_max = 0;
747 delta_cum = 0;
750 last_clock = ti;
752 #endif
753 if (alarm_has_dynticks(t) ||
754 qemu_next_alarm_deadline () <= 0) {
755 t->expired = alarm_has_dynticks(t);
756 t->pending = 1;
757 qemu_notify_event();
761 int64_t qemu_next_icount_deadline(void)
763 /* To avoid problems with overflow limit this to 2^32. */
764 int64_t delta = INT32_MAX;
766 assert(use_icount);
767 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
768 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
769 qemu_get_clock_ns(vm_clock);
772 if (delta < 0)
773 delta = 0;
775 return delta;
778 static int64_t qemu_next_alarm_deadline(void)
780 int64_t delta;
781 int64_t rtdelta;
783 if (!use_icount && active_timers[QEMU_CLOCK_VIRTUAL]) {
784 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
785 qemu_get_clock_ns(vm_clock);
786 } else {
787 delta = INT32_MAX;
789 if (active_timers[QEMU_CLOCK_HOST]) {
790 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
791 qemu_get_clock_ns(host_clock);
792 if (hdelta < delta)
793 delta = hdelta;
795 if (active_timers[QEMU_CLOCK_REALTIME]) {
796 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
797 qemu_get_clock_ns(rt_clock));
798 if (rtdelta < delta)
799 delta = rtdelta;
802 return delta;
805 #if defined(__linux__)
807 static int dynticks_start_timer(struct qemu_alarm_timer *t)
809 struct sigevent ev;
810 timer_t host_timer;
811 struct sigaction act;
813 sigfillset(&act.sa_mask);
814 act.sa_flags = 0;
815 act.sa_handler = host_alarm_handler;
817 sigaction(SIGALRM, &act, NULL);
820 * Initialize ev struct to 0 to avoid valgrind complaining
821 * about uninitialized data in timer_create call
823 memset(&ev, 0, sizeof(ev));
824 ev.sigev_value.sival_int = 0;
825 ev.sigev_notify = SIGEV_SIGNAL;
826 ev.sigev_signo = SIGALRM;
828 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
829 perror("timer_create");
831 /* disable dynticks */
832 fprintf(stderr, "Dynamic Ticks disabled\n");
834 return -1;
837 t->timer = host_timer;
839 return 0;
842 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
844 timer_t host_timer = t->timer;
846 timer_delete(host_timer);
849 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
851 timer_t host_timer = t->timer;
852 struct itimerspec timeout;
853 int64_t nearest_delta_ns = INT64_MAX;
854 int64_t current_ns;
856 assert(alarm_has_dynticks(t));
857 if (!active_timers[QEMU_CLOCK_REALTIME] &&
858 !active_timers[QEMU_CLOCK_VIRTUAL] &&
859 !active_timers[QEMU_CLOCK_HOST])
860 return;
862 nearest_delta_ns = qemu_next_alarm_deadline();
863 if (nearest_delta_ns < MIN_TIMER_REARM_NS)
864 nearest_delta_ns = MIN_TIMER_REARM_NS;
866 /* check whether a timer is already running */
867 if (timer_gettime(host_timer, &timeout)) {
868 perror("gettime");
869 fprintf(stderr, "Internal timer error: aborting\n");
870 exit(1);
872 current_ns = timeout.it_value.tv_sec * 1000000000LL + timeout.it_value.tv_nsec;
873 if (current_ns && current_ns <= nearest_delta_ns)
874 return;
876 timeout.it_interval.tv_sec = 0;
877 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
878 timeout.it_value.tv_sec = nearest_delta_ns / 1000000000;
879 timeout.it_value.tv_nsec = nearest_delta_ns % 1000000000;
880 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
881 perror("settime");
882 fprintf(stderr, "Internal timer error: aborting\n");
883 exit(1);
887 #endif /* defined(__linux__) */
889 #if !defined(_WIN32)
891 static int unix_start_timer(struct qemu_alarm_timer *t)
893 struct sigaction act;
895 /* timer signal */
896 sigfillset(&act.sa_mask);
897 act.sa_flags = 0;
898 act.sa_handler = host_alarm_handler;
900 sigaction(SIGALRM, &act, NULL);
901 return 0;
904 static void unix_rearm_timer(struct qemu_alarm_timer *t)
906 struct itimerval itv;
907 int64_t nearest_delta_ns = INT64_MAX;
908 int err;
910 assert(alarm_has_dynticks(t));
911 if (!active_timers[QEMU_CLOCK_REALTIME] &&
912 !active_timers[QEMU_CLOCK_VIRTUAL] &&
913 !active_timers[QEMU_CLOCK_HOST])
914 return;
916 nearest_delta_ns = qemu_next_alarm_deadline();
917 if (nearest_delta_ns < MIN_TIMER_REARM_NS)
918 nearest_delta_ns = MIN_TIMER_REARM_NS;
920 itv.it_interval.tv_sec = 0;
921 itv.it_interval.tv_usec = 0; /* 0 for one-shot timer */
922 itv.it_value.tv_sec = nearest_delta_ns / 1000000000;
923 itv.it_value.tv_usec = (nearest_delta_ns % 1000000000) / 1000;
924 err = setitimer(ITIMER_REAL, &itv, NULL);
925 if (err) {
926 perror("setitimer");
927 fprintf(stderr, "Internal timer error: aborting\n");
928 exit(1);
932 static void unix_stop_timer(struct qemu_alarm_timer *t)
934 struct itimerval itv;
936 memset(&itv, 0, sizeof(itv));
937 setitimer(ITIMER_REAL, &itv, NULL);
940 #endif /* !defined(_WIN32) */
943 #ifdef _WIN32
945 static MMRESULT mm_timer;
946 static unsigned mm_period;
948 static void CALLBACK mm_alarm_handler(UINT uTimerID, UINT uMsg,
949 DWORD_PTR dwUser, DWORD_PTR dw1,
950 DWORD_PTR dw2)
952 struct qemu_alarm_timer *t = alarm_timer;
953 if (!t) {
954 return;
956 if (alarm_has_dynticks(t) || qemu_next_alarm_deadline() <= 0) {
957 t->expired = alarm_has_dynticks(t);
958 t->pending = 1;
959 qemu_notify_event();
963 static int mm_start_timer(struct qemu_alarm_timer *t)
965 TIMECAPS tc;
966 UINT flags;
968 memset(&tc, 0, sizeof(tc));
969 timeGetDevCaps(&tc, sizeof(tc));
971 mm_period = tc.wPeriodMin;
972 timeBeginPeriod(mm_period);
974 flags = TIME_CALLBACK_FUNCTION;
975 if (alarm_has_dynticks(t)) {
976 flags |= TIME_ONESHOT;
977 } else {
978 flags |= TIME_PERIODIC;
981 mm_timer = timeSetEvent(1, /* interval (ms) */
982 mm_period, /* resolution */
983 mm_alarm_handler, /* function */
984 (DWORD_PTR)t, /* parameter */
985 flags);
987 if (!mm_timer) {
988 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
989 GetLastError());
990 timeEndPeriod(mm_period);
991 return -1;
994 return 0;
997 static void mm_stop_timer(struct qemu_alarm_timer *t)
999 timeKillEvent(mm_timer);
1000 timeEndPeriod(mm_period);
1003 static void mm_rearm_timer(struct qemu_alarm_timer *t)
1005 int nearest_delta_ms;
1007 assert(alarm_has_dynticks(t));
1008 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1009 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1010 !active_timers[QEMU_CLOCK_HOST]) {
1011 return;
1014 timeKillEvent(mm_timer);
1016 nearest_delta_ms = (qemu_next_alarm_deadline() + 999999) / 1000000;
1017 if (nearest_delta_ms < 1) {
1018 nearest_delta_ms = 1;
1020 mm_timer = timeSetEvent(nearest_delta_ms,
1021 mm_period,
1022 mm_alarm_handler,
1023 (DWORD_PTR)t,
1024 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1026 if (!mm_timer) {
1027 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1028 GetLastError());
1030 timeEndPeriod(mm_period);
1031 exit(1);
1035 static int win32_start_timer(struct qemu_alarm_timer *t)
1037 HANDLE hTimer;
1038 BOOLEAN success;
1040 /* If you call ChangeTimerQueueTimer on a one-shot timer (its period
1041 is zero) that has already expired, the timer is not updated. Since
1042 creating a new timer is relatively expensive, set a bogus one-hour
1043 interval in the dynticks case. */
1044 success = CreateTimerQueueTimer(&hTimer,
1045 NULL,
1046 host_alarm_handler,
1049 alarm_has_dynticks(t) ? 3600000 : 1,
1050 WT_EXECUTEINTIMERTHREAD);
1052 if (!success) {
1053 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1054 GetLastError());
1055 return -1;
1058 t->timer = hTimer;
1059 return 0;
1062 static void win32_stop_timer(struct qemu_alarm_timer *t)
1064 HANDLE hTimer = t->timer;
1066 if (hTimer) {
1067 DeleteTimerQueueTimer(NULL, hTimer, NULL);
1071 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1073 HANDLE hTimer = t->timer;
1074 int nearest_delta_ms;
1075 BOOLEAN success;
1077 assert(alarm_has_dynticks(t));
1078 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1079 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1080 !active_timers[QEMU_CLOCK_HOST])
1081 return;
1083 nearest_delta_ms = (qemu_next_alarm_deadline() + 999999) / 1000000;
1084 if (nearest_delta_ms < 1) {
1085 nearest_delta_ms = 1;
1087 success = ChangeTimerQueueTimer(NULL,
1088 hTimer,
1089 nearest_delta_ms,
1090 3600000);
1092 if (!success) {
1093 fprintf(stderr, "Failed to rearm win32 alarm timer: %ld\n",
1094 GetLastError());
1095 exit(-1);
1100 #endif /* _WIN32 */
1102 static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1104 if (running)
1105 qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1108 int init_timer_alarm(void)
1110 struct qemu_alarm_timer *t = NULL;
1111 int i, err = -1;
1113 for (i = 0; alarm_timers[i].name; i++) {
1114 t = &alarm_timers[i];
1116 err = t->start(t);
1117 if (!err)
1118 break;
1121 if (err) {
1122 err = -ENOENT;
1123 goto fail;
1126 /* first event is at time 0 */
1127 t->pending = 1;
1128 alarm_timer = t;
1129 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1131 return 0;
1133 fail:
1134 return err;
1137 void quit_timers(void)
1139 struct qemu_alarm_timer *t = alarm_timer;
1140 alarm_timer = NULL;
1141 t->stop(t);
1144 int qemu_calculate_timeout(void)
1146 #ifndef CONFIG_IOTHREAD
1147 int timeout;
1149 if (!vm_running)
1150 timeout = 5000;
1151 else {
1152 /* XXX: use timeout computed from timers */
1153 int64_t add;
1154 int64_t delta;
1155 /* Advance virtual time to the next event. */
1156 delta = qemu_icount_delta();
1157 if (delta > 0) {
1158 /* If virtual time is ahead of real time then just
1159 wait for IO. */
1160 timeout = (delta + 999999) / 1000000;
1161 } else {
1162 /* Wait for either IO to occur or the next
1163 timer event. */
1164 add = qemu_next_icount_deadline();
1165 /* We advance the timer before checking for IO.
1166 Limit the amount we advance so that early IO
1167 activity won't get the guest too far ahead. */
1168 if (add > 10000000)
1169 add = 10000000;
1170 delta += add;
1171 qemu_icount += qemu_icount_round (add);
1172 timeout = delta / 1000000;
1173 if (timeout < 0)
1174 timeout = 0;
1178 return timeout;
1179 #else /* CONFIG_IOTHREAD */
1180 return 1000;
1181 #endif