Don't launch guest if -no-kvm when tcg is not configured in
[qemu/qemu-dev-zwu.git] / qemu-timer.c
blob77185656e72457e6d830b64f31979d20651f98db
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 __linux__
43 #include <sys/ioctl.h>
44 #include <linux/rtc.h>
45 /* For the benefit of older linux systems which don't supply it,
46 we use a local copy of hpet.h. */
47 /* #include <linux/hpet.h> */
48 #include "hpet.h"
49 #endif
51 #ifdef _WIN32
52 #include <windows.h>
53 #include <mmsystem.h>
54 #endif
56 #include "qemu-timer.h"
58 /* Conversion factor from emulated instructions to virtual clock ticks. */
59 int icount_time_shift;
60 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
61 #define MAX_ICOUNT_SHIFT 10
62 /* Compensate for varying guest execution speed. */
63 int64_t qemu_icount_bias;
64 static QEMUTimer *icount_rt_timer;
65 static QEMUTimer *icount_vm_timer;
68 /***********************************************************/
69 /* real time host monotonic timer */
72 static int64_t get_clock_realtime(void)
74 struct timeval tv;
76 gettimeofday(&tv, NULL);
77 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
80 #ifdef WIN32
82 static int64_t clock_freq;
84 static void init_get_clock(void)
86 LARGE_INTEGER freq;
87 int ret;
88 ret = QueryPerformanceFrequency(&freq);
89 if (ret == 0) {
90 fprintf(stderr, "Could not calibrate ticks\n");
91 exit(1);
93 clock_freq = freq.QuadPart;
96 static int64_t get_clock(void)
98 LARGE_INTEGER ti;
99 QueryPerformanceCounter(&ti);
100 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
103 #else
105 static int use_rt_clock;
107 static void init_get_clock(void)
109 use_rt_clock = 0;
110 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
111 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
113 struct timespec ts;
114 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
115 use_rt_clock = 1;
118 #endif
121 static int64_t get_clock(void)
123 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
124 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
125 if (use_rt_clock) {
126 struct timespec ts;
127 clock_gettime(CLOCK_MONOTONIC, &ts);
128 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
129 } else
130 #endif
132 /* XXX: using gettimeofday leads to problems if the date
133 changes, so it should be avoided. */
134 return get_clock_realtime();
137 #endif
139 /***********************************************************/
140 /* guest cycle counter */
142 typedef struct TimersState {
143 int64_t cpu_ticks_prev;
144 int64_t cpu_ticks_offset;
145 int64_t cpu_clock_offset;
146 int32_t cpu_ticks_enabled;
147 int64_t dummy;
148 } TimersState;
150 TimersState timers_state;
152 /* return the host CPU cycle counter and handle stop/restart */
153 int64_t cpu_get_ticks(void)
155 if (use_icount) {
156 return cpu_get_icount();
158 if (!timers_state.cpu_ticks_enabled) {
159 return timers_state.cpu_ticks_offset;
160 } else {
161 int64_t ticks;
162 ticks = cpu_get_real_ticks();
163 if (timers_state.cpu_ticks_prev > ticks) {
164 /* Note: non increasing ticks may happen if the host uses
165 software suspend */
166 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
168 timers_state.cpu_ticks_prev = ticks;
169 return ticks + timers_state.cpu_ticks_offset;
173 /* return the host CPU monotonic timer and handle stop/restart */
174 static int64_t cpu_get_clock(void)
176 int64_t ti;
177 if (!timers_state.cpu_ticks_enabled) {
178 return timers_state.cpu_clock_offset;
179 } else {
180 ti = get_clock();
181 return ti + timers_state.cpu_clock_offset;
185 /* FIXME: qemu-kvm hack */
186 #define CONFIG_IOTHREAD 1
187 #ifndef CONFIG_IOTHREAD
188 static int64_t qemu_icount_delta(void)
190 if (!use_icount) {
191 return 5000 * (int64_t) 1000000;
192 } else if (use_icount == 1) {
193 /* When not using an adaptive execution frequency
194 we tend to get badly out of sync with real time,
195 so just delay for a reasonable amount of time. */
196 return 0;
197 } else {
198 return cpu_get_icount() - cpu_get_clock();
201 #endif
203 /* enable cpu_get_ticks() */
204 void cpu_enable_ticks(void)
206 if (!timers_state.cpu_ticks_enabled) {
207 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
208 timers_state.cpu_clock_offset -= get_clock();
209 timers_state.cpu_ticks_enabled = 1;
213 /* disable cpu_get_ticks() : the clock is stopped. You must not call
214 cpu_get_ticks() after that. */
215 void cpu_disable_ticks(void)
217 if (timers_state.cpu_ticks_enabled) {
218 timers_state.cpu_ticks_offset = cpu_get_ticks();
219 timers_state.cpu_clock_offset = cpu_get_clock();
220 timers_state.cpu_ticks_enabled = 0;
224 /***********************************************************/
225 /* timers */
227 #define QEMU_CLOCK_REALTIME 0
228 #define QEMU_CLOCK_VIRTUAL 1
229 #define QEMU_CLOCK_HOST 2
231 struct QEMUClock {
232 int type;
233 int enabled;
234 /* XXX: add frequency */
237 struct QEMUTimer {
238 QEMUClock *clock;
239 int64_t expire_time;
240 QEMUTimerCB *cb;
241 void *opaque;
242 struct QEMUTimer *next;
245 struct qemu_alarm_timer {
246 char const *name;
247 int (*start)(struct qemu_alarm_timer *t);
248 void (*stop)(struct qemu_alarm_timer *t);
249 void (*rearm)(struct qemu_alarm_timer *t);
250 void *priv;
252 char expired;
253 char pending;
256 static struct qemu_alarm_timer *alarm_timer;
258 int qemu_alarm_pending(void)
260 return alarm_timer->pending;
263 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
265 return !!t->rearm;
268 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
270 if (!alarm_has_dynticks(t))
271 return;
273 t->rearm(t);
276 /* TODO: MIN_TIMER_REARM_US should be optimized */
277 #define MIN_TIMER_REARM_US 250
279 #ifdef _WIN32
281 struct qemu_alarm_win32 {
282 MMRESULT timerId;
283 unsigned int period;
284 } alarm_win32_data = {0, 0};
286 static int win32_start_timer(struct qemu_alarm_timer *t);
287 static void win32_stop_timer(struct qemu_alarm_timer *t);
288 static void win32_rearm_timer(struct qemu_alarm_timer *t);
290 #else
292 static int unix_start_timer(struct qemu_alarm_timer *t);
293 static void unix_stop_timer(struct qemu_alarm_timer *t);
295 #ifdef __linux__
297 static int dynticks_start_timer(struct qemu_alarm_timer *t);
298 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
299 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
301 static int hpet_start_timer(struct qemu_alarm_timer *t);
302 static void hpet_stop_timer(struct qemu_alarm_timer *t);
304 static int rtc_start_timer(struct qemu_alarm_timer *t);
305 static void rtc_stop_timer(struct qemu_alarm_timer *t);
307 #endif /* __linux__ */
309 #endif /* _WIN32 */
311 /* Correlation between real and virtual time is always going to be
312 fairly approximate, so ignore small variation.
313 When the guest is idle real and virtual time will be aligned in
314 the IO wait loop. */
315 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
317 static void icount_adjust(void)
319 int64_t cur_time;
320 int64_t cur_icount;
321 int64_t delta;
322 static int64_t last_delta;
323 /* If the VM is not running, then do nothing. */
324 if (!vm_running)
325 return;
327 cur_time = cpu_get_clock();
328 cur_icount = qemu_get_clock(vm_clock);
329 delta = cur_icount - cur_time;
330 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
331 if (delta > 0
332 && last_delta + ICOUNT_WOBBLE < delta * 2
333 && icount_time_shift > 0) {
334 /* The guest is getting too far ahead. Slow time down. */
335 icount_time_shift--;
337 if (delta < 0
338 && last_delta - ICOUNT_WOBBLE > delta * 2
339 && icount_time_shift < MAX_ICOUNT_SHIFT) {
340 /* The guest is getting too far behind. Speed time up. */
341 icount_time_shift++;
343 last_delta = delta;
344 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
347 static void icount_adjust_rt(void * opaque)
349 qemu_mod_timer(icount_rt_timer,
350 qemu_get_clock(rt_clock) + 1000);
351 icount_adjust();
354 static void icount_adjust_vm(void * opaque)
356 qemu_mod_timer(icount_vm_timer,
357 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
358 icount_adjust();
361 int64_t qemu_icount_round(int64_t count)
363 return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
366 static struct qemu_alarm_timer alarm_timers[] = {
367 #ifndef _WIN32
368 #ifdef __linux__
369 {"dynticks", dynticks_start_timer,
370 dynticks_stop_timer, dynticks_rearm_timer, NULL},
371 /* HPET - if available - is preferred */
372 {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
373 /* ...otherwise try RTC */
374 {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
375 #endif
376 {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
377 #else
378 {"dynticks", win32_start_timer,
379 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
380 {"win32", win32_start_timer,
381 win32_stop_timer, NULL, &alarm_win32_data},
382 #endif
383 {NULL, }
386 static void show_available_alarms(void)
388 int i;
390 printf("Available alarm timers, in order of precedence:\n");
391 for (i = 0; alarm_timers[i].name; i++)
392 printf("%s\n", alarm_timers[i].name);
395 void configure_alarms(char const *opt)
397 int i;
398 int cur = 0;
399 int count = ARRAY_SIZE(alarm_timers) - 1;
400 char *arg;
401 char *name;
402 struct qemu_alarm_timer tmp;
404 if (!strcmp(opt, "?")) {
405 show_available_alarms();
406 exit(0);
409 arg = qemu_strdup(opt);
411 /* Reorder the array */
412 name = strtok(arg, ",");
413 while (name) {
414 for (i = 0; i < count && alarm_timers[i].name; i++) {
415 if (!strcmp(alarm_timers[i].name, name))
416 break;
419 if (i == count) {
420 fprintf(stderr, "Unknown clock %s\n", name);
421 goto next;
424 if (i < cur)
425 /* Ignore */
426 goto next;
428 /* Swap */
429 tmp = alarm_timers[i];
430 alarm_timers[i] = alarm_timers[cur];
431 alarm_timers[cur] = tmp;
433 cur++;
434 next:
435 name = strtok(NULL, ",");
438 qemu_free(arg);
440 if (cur) {
441 /* Disable remaining timers */
442 for (i = cur; i < count; i++)
443 alarm_timers[i].name = NULL;
444 } else {
445 show_available_alarms();
446 exit(1);
450 #define QEMU_NUM_CLOCKS 3
452 QEMUClock *rt_clock;
453 QEMUClock *vm_clock;
454 QEMUClock *host_clock;
456 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
458 static QEMUClock *qemu_new_clock(int type)
460 QEMUClock *clock;
461 clock = qemu_mallocz(sizeof(QEMUClock));
462 clock->type = type;
463 clock->enabled = 1;
464 return clock;
467 void qemu_clock_enable(QEMUClock *clock, int enabled)
469 clock->enabled = enabled;
472 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
474 QEMUTimer *ts;
476 ts = qemu_mallocz(sizeof(QEMUTimer));
477 ts->clock = clock;
478 ts->cb = cb;
479 ts->opaque = opaque;
480 return ts;
483 void qemu_free_timer(QEMUTimer *ts)
485 qemu_free(ts);
488 /* stop a timer, but do not dealloc it */
489 void qemu_del_timer(QEMUTimer *ts)
491 QEMUTimer **pt, *t;
493 /* NOTE: this code must be signal safe because
494 qemu_timer_expired() can be called from a signal. */
495 pt = &active_timers[ts->clock->type];
496 for(;;) {
497 t = *pt;
498 if (!t)
499 break;
500 if (t == ts) {
501 *pt = t->next;
502 break;
504 pt = &t->next;
508 /* modify the current timer so that it will be fired when current_time
509 >= expire_time. The corresponding callback will be called. */
510 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
512 QEMUTimer **pt, *t;
514 qemu_del_timer(ts);
516 /* add the timer in the sorted list */
517 /* NOTE: this code must be signal safe because
518 qemu_timer_expired() can be called from a signal. */
519 pt = &active_timers[ts->clock->type];
520 for(;;) {
521 t = *pt;
522 if (!t)
523 break;
524 if (t->expire_time > expire_time)
525 break;
526 pt = &t->next;
528 ts->expire_time = expire_time;
529 ts->next = *pt;
530 *pt = ts;
532 /* Rearm if necessary */
533 if (pt == &active_timers[ts->clock->type]) {
534 if (!alarm_timer->pending) {
535 qemu_rearm_alarm_timer(alarm_timer);
537 /* Interrupt execution to force deadline recalculation. */
538 if (use_icount)
539 qemu_notify_event();
543 int qemu_timer_pending(QEMUTimer *ts)
545 QEMUTimer *t;
546 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
547 if (t == ts)
548 return 1;
550 return 0;
553 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
555 if (!timer_head)
556 return 0;
557 return (timer_head->expire_time <= current_time);
560 static void qemu_run_timers(QEMUClock *clock)
562 QEMUTimer **ptimer_head, *ts;
563 int64_t current_time;
565 if (!clock->enabled)
566 return;
568 current_time = qemu_get_clock (clock);
569 ptimer_head = &active_timers[clock->type];
570 for(;;) {
571 ts = *ptimer_head;
572 if (!ts || ts->expire_time > current_time)
573 break;
574 /* remove timer from the list before calling the callback */
575 *ptimer_head = ts->next;
576 ts->next = NULL;
578 /* run the callback (the timer list can be modified) */
579 ts->cb(ts->opaque);
583 int64_t qemu_get_clock(QEMUClock *clock)
585 switch(clock->type) {
586 case QEMU_CLOCK_REALTIME:
587 return get_clock() / 1000000;
588 default:
589 case QEMU_CLOCK_VIRTUAL:
590 if (use_icount) {
591 return cpu_get_icount();
592 } else {
593 return cpu_get_clock();
595 case QEMU_CLOCK_HOST:
596 return get_clock_realtime();
600 int64_t qemu_get_clock_ns(QEMUClock *clock)
602 switch(clock->type) {
603 case QEMU_CLOCK_REALTIME:
604 return get_clock();
605 default:
606 case QEMU_CLOCK_VIRTUAL:
607 if (use_icount) {
608 return cpu_get_icount();
609 } else {
610 return cpu_get_clock();
612 case QEMU_CLOCK_HOST:
613 return get_clock_realtime();
617 void init_clocks(void)
619 init_get_clock();
620 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
621 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
622 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
624 rtc_clock = host_clock;
627 /* save a timer */
628 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
630 uint64_t expire_time;
632 if (qemu_timer_pending(ts)) {
633 expire_time = ts->expire_time;
634 } else {
635 expire_time = -1;
637 qemu_put_be64(f, expire_time);
640 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
642 uint64_t expire_time;
644 expire_time = qemu_get_be64(f);
645 if (expire_time != -1) {
646 qemu_mod_timer(ts, expire_time);
647 } else {
648 qemu_del_timer(ts);
652 static const VMStateDescription vmstate_timers = {
653 .name = "timer",
654 .version_id = 2,
655 .minimum_version_id = 1,
656 .minimum_version_id_old = 1,
657 .fields = (VMStateField []) {
658 VMSTATE_INT64(cpu_ticks_offset, TimersState),
659 VMSTATE_INT64(dummy, TimersState),
660 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
661 VMSTATE_END_OF_LIST()
665 void configure_icount(const char *option)
667 vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
668 if (!option)
669 return;
671 if (strcmp(option, "auto") != 0) {
672 icount_time_shift = strtol(option, NULL, 0);
673 use_icount = 1;
674 return;
677 use_icount = 2;
679 /* 125MIPS seems a reasonable initial guess at the guest speed.
680 It will be corrected fairly quickly anyway. */
681 icount_time_shift = 3;
683 /* Have both realtime and virtual time triggers for speed adjustment.
684 The realtime trigger catches emulated time passing too slowly,
685 the virtual time trigger catches emulated time passing too fast.
686 Realtime triggers occur even when idle, so use them less frequently
687 than VM triggers. */
688 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
689 qemu_mod_timer(icount_rt_timer,
690 qemu_get_clock(rt_clock) + 1000);
691 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
692 qemu_mod_timer(icount_vm_timer,
693 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
696 void qemu_run_all_timers(void)
698 alarm_timer->pending = 0;
700 /* rearm timer, if not periodic */
701 if (alarm_timer->expired) {
702 alarm_timer->expired = 0;
703 qemu_rearm_alarm_timer(alarm_timer);
706 /* vm time timers */
707 if (vm_running) {
708 qemu_run_timers(vm_clock);
711 qemu_run_timers(rt_clock);
712 qemu_run_timers(host_clock);
715 #ifdef _WIN32
716 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
717 DWORD_PTR dwUser, DWORD_PTR dw1,
718 DWORD_PTR dw2)
719 #else
720 static void host_alarm_handler(int host_signum)
721 #endif
723 struct qemu_alarm_timer *t = alarm_timer;
724 if (!t)
725 return;
727 #if 0
728 #define DISP_FREQ 1000
730 static int64_t delta_min = INT64_MAX;
731 static int64_t delta_max, delta_cum, last_clock, delta, ti;
732 static int count;
733 ti = qemu_get_clock(vm_clock);
734 if (last_clock != 0) {
735 delta = ti - last_clock;
736 if (delta < delta_min)
737 delta_min = delta;
738 if (delta > delta_max)
739 delta_max = delta;
740 delta_cum += delta;
741 if (++count == DISP_FREQ) {
742 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
743 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
744 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
745 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
746 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
747 count = 0;
748 delta_min = INT64_MAX;
749 delta_max = 0;
750 delta_cum = 0;
753 last_clock = ti;
755 #endif
756 if (alarm_has_dynticks(t) ||
757 (!use_icount &&
758 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
759 qemu_get_clock(vm_clock))) ||
760 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
761 qemu_get_clock(rt_clock)) ||
762 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
763 qemu_get_clock(host_clock))) {
765 t->expired = alarm_has_dynticks(t);
766 t->pending = 1;
767 qemu_notify_event();
771 int64_t qemu_next_deadline(void)
773 /* To avoid problems with overflow limit this to 2^32. */
774 int64_t delta = INT32_MAX;
776 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
777 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
778 qemu_get_clock(vm_clock);
780 if (active_timers[QEMU_CLOCK_HOST]) {
781 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
782 qemu_get_clock(host_clock);
783 if (hdelta < delta)
784 delta = hdelta;
787 if (delta < 0)
788 delta = 0;
790 return delta;
793 #ifndef _WIN32
795 #if defined(__linux__)
797 #define RTC_FREQ 1024
799 static uint64_t qemu_next_deadline_dyntick(void)
801 int64_t delta;
802 int64_t rtdelta;
804 if (use_icount)
805 delta = INT32_MAX;
806 else
807 delta = (qemu_next_deadline() + 999) / 1000;
809 if (active_timers[QEMU_CLOCK_REALTIME]) {
810 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
811 qemu_get_clock(rt_clock))*1000;
812 if (rtdelta < delta)
813 delta = rtdelta;
816 if (delta < MIN_TIMER_REARM_US)
817 delta = MIN_TIMER_REARM_US;
819 return delta;
822 static void enable_sigio_timer(int fd)
824 struct sigaction act;
826 /* timer signal */
827 sigfillset(&act.sa_mask);
828 act.sa_flags = 0;
829 act.sa_handler = host_alarm_handler;
831 sigaction(SIGIO, &act, NULL);
832 fcntl_setfl(fd, O_ASYNC);
833 fcntl(fd, F_SETOWN, getpid());
836 static int hpet_start_timer(struct qemu_alarm_timer *t)
838 struct hpet_info info;
839 int r, fd;
841 fd = qemu_open("/dev/hpet", O_RDONLY);
842 if (fd < 0)
843 return -1;
845 /* Set frequency */
846 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
847 if (r < 0) {
848 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
849 "error, but for better emulation accuracy type:\n"
850 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
851 goto fail;
854 /* Check capabilities */
855 r = ioctl(fd, HPET_INFO, &info);
856 if (r < 0)
857 goto fail;
859 /* Enable periodic mode */
860 r = ioctl(fd, HPET_EPI, 0);
861 if (info.hi_flags && (r < 0))
862 goto fail;
864 /* Enable interrupt */
865 r = ioctl(fd, HPET_IE_ON, 0);
866 if (r < 0)
867 goto fail;
869 enable_sigio_timer(fd);
870 t->priv = (void *)(long)fd;
872 return 0;
873 fail:
874 close(fd);
875 return -1;
878 static void hpet_stop_timer(struct qemu_alarm_timer *t)
880 int fd = (long)t->priv;
882 close(fd);
885 static int rtc_start_timer(struct qemu_alarm_timer *t)
887 int rtc_fd;
888 unsigned long current_rtc_freq = 0;
890 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
891 if (rtc_fd < 0)
892 return -1;
893 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
894 if (current_rtc_freq != RTC_FREQ &&
895 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
896 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
897 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
898 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
899 goto fail;
901 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
902 fail:
903 close(rtc_fd);
904 return -1;
907 enable_sigio_timer(rtc_fd);
909 t->priv = (void *)(long)rtc_fd;
911 return 0;
914 static void rtc_stop_timer(struct qemu_alarm_timer *t)
916 int rtc_fd = (long)t->priv;
918 close(rtc_fd);
921 static int dynticks_start_timer(struct qemu_alarm_timer *t)
923 struct sigevent ev;
924 timer_t host_timer;
925 struct sigaction act;
927 sigfillset(&act.sa_mask);
928 act.sa_flags = 0;
929 act.sa_handler = host_alarm_handler;
931 sigaction(SIGALRM, &act, NULL);
934 * Initialize ev struct to 0 to avoid valgrind complaining
935 * about uninitialized data in timer_create call
937 memset(&ev, 0, sizeof(ev));
938 ev.sigev_value.sival_int = 0;
939 ev.sigev_notify = SIGEV_SIGNAL;
940 ev.sigev_signo = SIGALRM;
942 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
943 perror("timer_create");
945 /* disable dynticks */
946 fprintf(stderr, "Dynamic Ticks disabled\n");
948 return -1;
951 t->priv = (void *)(long)host_timer;
953 return 0;
956 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
958 timer_t host_timer = (timer_t)(long)t->priv;
960 timer_delete(host_timer);
963 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
965 timer_t host_timer = (timer_t)(long)t->priv;
966 struct itimerspec timeout;
967 int64_t nearest_delta_us = INT64_MAX;
968 int64_t current_us;
970 assert(alarm_has_dynticks(t));
971 if (!active_timers[QEMU_CLOCK_REALTIME] &&
972 !active_timers[QEMU_CLOCK_VIRTUAL] &&
973 !active_timers[QEMU_CLOCK_HOST])
974 return;
976 nearest_delta_us = qemu_next_deadline_dyntick();
978 /* check whether a timer is already running */
979 if (timer_gettime(host_timer, &timeout)) {
980 perror("gettime");
981 fprintf(stderr, "Internal timer error: aborting\n");
982 exit(1);
984 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
985 if (current_us && current_us <= nearest_delta_us)
986 return;
988 timeout.it_interval.tv_sec = 0;
989 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
990 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
991 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
992 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
993 perror("settime");
994 fprintf(stderr, "Internal timer error: aborting\n");
995 exit(1);
999 #endif /* defined(__linux__) */
1001 static int unix_start_timer(struct qemu_alarm_timer *t)
1003 struct sigaction act;
1004 struct itimerval itv;
1005 int err;
1007 /* timer signal */
1008 sigfillset(&act.sa_mask);
1009 act.sa_flags = 0;
1010 act.sa_handler = host_alarm_handler;
1012 sigaction(SIGALRM, &act, NULL);
1014 itv.it_interval.tv_sec = 0;
1015 /* for i386 kernel 2.6 to get 1 ms */
1016 itv.it_interval.tv_usec = 999;
1017 itv.it_value.tv_sec = 0;
1018 itv.it_value.tv_usec = 10 * 1000;
1020 err = setitimer(ITIMER_REAL, &itv, NULL);
1021 if (err)
1022 return -1;
1024 return 0;
1027 static void unix_stop_timer(struct qemu_alarm_timer *t)
1029 struct itimerval itv;
1031 memset(&itv, 0, sizeof(itv));
1032 setitimer(ITIMER_REAL, &itv, NULL);
1035 #endif /* !defined(_WIN32) */
1038 #ifdef _WIN32
1040 static int win32_start_timer(struct qemu_alarm_timer *t)
1042 TIMECAPS tc;
1043 struct qemu_alarm_win32 *data = t->priv;
1044 UINT flags;
1046 memset(&tc, 0, sizeof(tc));
1047 timeGetDevCaps(&tc, sizeof(tc));
1049 data->period = tc.wPeriodMin;
1050 timeBeginPeriod(data->period);
1052 flags = TIME_CALLBACK_FUNCTION;
1053 if (alarm_has_dynticks(t))
1054 flags |= TIME_ONESHOT;
1055 else
1056 flags |= TIME_PERIODIC;
1058 data->timerId = timeSetEvent(1, // interval (ms)
1059 data->period, // resolution
1060 host_alarm_handler, // function
1061 (DWORD)t, // parameter
1062 flags);
1064 if (!data->timerId) {
1065 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1066 GetLastError());
1067 timeEndPeriod(data->period);
1068 return -1;
1071 return 0;
1074 static void win32_stop_timer(struct qemu_alarm_timer *t)
1076 struct qemu_alarm_win32 *data = t->priv;
1078 timeKillEvent(data->timerId);
1079 timeEndPeriod(data->period);
1082 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1084 struct qemu_alarm_win32 *data = t->priv;
1086 assert(alarm_has_dynticks(t));
1087 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1088 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1089 !active_timers[QEMU_CLOCK_HOST])
1090 return;
1092 timeKillEvent(data->timerId);
1094 data->timerId = timeSetEvent(1,
1095 data->period,
1096 host_alarm_handler,
1097 (DWORD)t,
1098 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1100 if (!data->timerId) {
1101 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1102 GetLastError());
1104 timeEndPeriod(data->period);
1105 exit(1);
1109 #endif /* _WIN32 */
1111 static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1113 if (running)
1114 qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1117 int init_timer_alarm(void)
1119 struct qemu_alarm_timer *t = NULL;
1120 int i, err = -1;
1122 for (i = 0; alarm_timers[i].name; i++) {
1123 t = &alarm_timers[i];
1125 err = t->start(t);
1126 if (!err)
1127 break;
1130 if (err) {
1131 err = -ENOENT;
1132 goto fail;
1135 /* first event is at time 0 */
1136 t->pending = 1;
1137 alarm_timer = t;
1138 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1140 return 0;
1142 fail:
1143 return err;
1146 void quit_timers(void)
1148 struct qemu_alarm_timer *t = alarm_timer;
1149 alarm_timer = NULL;
1150 t->stop(t);
1153 int qemu_calculate_timeout(void)
1155 #ifndef CONFIG_IOTHREAD
1156 int timeout;
1158 if (!vm_running)
1159 timeout = 5000;
1160 else {
1161 /* XXX: use timeout computed from timers */
1162 int64_t add;
1163 int64_t delta;
1164 /* Advance virtual time to the next event. */
1165 delta = qemu_icount_delta();
1166 if (delta > 0) {
1167 /* If virtual time is ahead of real time then just
1168 wait for IO. */
1169 timeout = (delta + 999999) / 1000000;
1170 } else {
1171 /* Wait for either IO to occur or the next
1172 timer event. */
1173 add = qemu_next_deadline();
1174 /* We advance the timer before checking for IO.
1175 Limit the amount we advance so that early IO
1176 activity won't get the guest too far ahead. */
1177 if (add > 10000000)
1178 add = 10000000;
1179 delta += add;
1180 qemu_icount += qemu_icount_round (add);
1181 timeout = delta / 1000000;
1182 if (timeout < 0)
1183 timeout = 0;
1187 return timeout;
1188 #else /* CONFIG_IOTHREAD */
1189 return 1000;
1190 #endif