pci: Remove pci_enable_capability_support()
[qemu-kvm/stefanha.git] / qemu-timer.c
blobd29d2cd3b716f49f8ba6ce97f678a198cd10914f
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;
67 /***********************************************************/
68 /* guest cycle counter */
70 typedef struct TimersState {
71 int64_t cpu_ticks_prev;
72 int64_t cpu_ticks_offset;
73 int64_t cpu_clock_offset;
74 int32_t cpu_ticks_enabled;
75 int64_t dummy;
76 } TimersState;
78 TimersState timers_state;
80 /* return the host CPU cycle counter and handle stop/restart */
81 int64_t cpu_get_ticks(void)
83 if (use_icount) {
84 return cpu_get_icount();
86 if (!timers_state.cpu_ticks_enabled) {
87 return timers_state.cpu_ticks_offset;
88 } else {
89 int64_t ticks;
90 ticks = cpu_get_real_ticks();
91 if (timers_state.cpu_ticks_prev > ticks) {
92 /* Note: non increasing ticks may happen if the host uses
93 software suspend */
94 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
96 timers_state.cpu_ticks_prev = ticks;
97 return ticks + timers_state.cpu_ticks_offset;
101 /* return the host CPU monotonic timer and handle stop/restart */
102 static int64_t cpu_get_clock(void)
104 int64_t ti;
105 if (!timers_state.cpu_ticks_enabled) {
106 return timers_state.cpu_clock_offset;
107 } else {
108 ti = get_clock();
109 return ti + timers_state.cpu_clock_offset;
113 /* FIXME: qemu-kvm hack */
114 #define CONFIG_IOTHREAD 1
115 #ifndef CONFIG_IOTHREAD
116 static int64_t qemu_icount_delta(void)
118 if (!use_icount) {
119 return 5000 * (int64_t) 1000000;
120 } else if (use_icount == 1) {
121 /* When not using an adaptive execution frequency
122 we tend to get badly out of sync with real time,
123 so just delay for a reasonable amount of time. */
124 return 0;
125 } else {
126 return cpu_get_icount() - cpu_get_clock();
129 #endif
131 /* enable cpu_get_ticks() */
132 void cpu_enable_ticks(void)
134 if (!timers_state.cpu_ticks_enabled) {
135 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
136 timers_state.cpu_clock_offset -= get_clock();
137 timers_state.cpu_ticks_enabled = 1;
141 /* disable cpu_get_ticks() : the clock is stopped. You must not call
142 cpu_get_ticks() after that. */
143 void cpu_disable_ticks(void)
145 if (timers_state.cpu_ticks_enabled) {
146 timers_state.cpu_ticks_offset = cpu_get_ticks();
147 timers_state.cpu_clock_offset = cpu_get_clock();
148 timers_state.cpu_ticks_enabled = 0;
152 /***********************************************************/
153 /* timers */
155 #define QEMU_CLOCK_REALTIME 0
156 #define QEMU_CLOCK_VIRTUAL 1
157 #define QEMU_CLOCK_HOST 2
159 struct QEMUClock {
160 int type;
161 int enabled;
162 /* XXX: add frequency */
165 struct QEMUTimer {
166 QEMUClock *clock;
167 int64_t expire_time;
168 QEMUTimerCB *cb;
169 void *opaque;
170 struct QEMUTimer *next;
173 struct qemu_alarm_timer {
174 char const *name;
175 int (*start)(struct qemu_alarm_timer *t);
176 void (*stop)(struct qemu_alarm_timer *t);
177 void (*rearm)(struct qemu_alarm_timer *t);
178 void *priv;
180 char expired;
181 char pending;
184 static struct qemu_alarm_timer *alarm_timer;
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_US should be optimized */
205 #define MIN_TIMER_REARM_US 250
207 #ifdef _WIN32
209 struct qemu_alarm_win32 {
210 MMRESULT timerId;
211 unsigned int period;
212 } alarm_win32_data = {0, 0};
214 static int win32_start_timer(struct qemu_alarm_timer *t);
215 static void win32_stop_timer(struct qemu_alarm_timer *t);
216 static void win32_rearm_timer(struct qemu_alarm_timer *t);
218 #else
220 static int unix_start_timer(struct qemu_alarm_timer *t);
221 static void unix_stop_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 static int hpet_start_timer(struct qemu_alarm_timer *t);
230 static void hpet_stop_timer(struct qemu_alarm_timer *t);
232 static int rtc_start_timer(struct qemu_alarm_timer *t);
233 static void rtc_stop_timer(struct qemu_alarm_timer *t);
235 #endif /* __linux__ */
237 #endif /* _WIN32 */
239 /* Correlation between real and virtual time is always going to be
240 fairly approximate, so ignore small variation.
241 When the guest is idle real and virtual time will be aligned in
242 the IO wait loop. */
243 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
245 static void icount_adjust(void)
247 int64_t cur_time;
248 int64_t cur_icount;
249 int64_t delta;
250 static int64_t last_delta;
251 /* If the VM is not running, then do nothing. */
252 if (!vm_running)
253 return;
255 cur_time = cpu_get_clock();
256 cur_icount = qemu_get_clock(vm_clock);
257 delta = cur_icount - cur_time;
258 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
259 if (delta > 0
260 && last_delta + ICOUNT_WOBBLE < delta * 2
261 && icount_time_shift > 0) {
262 /* The guest is getting too far ahead. Slow time down. */
263 icount_time_shift--;
265 if (delta < 0
266 && last_delta - ICOUNT_WOBBLE > delta * 2
267 && icount_time_shift < MAX_ICOUNT_SHIFT) {
268 /* The guest is getting too far behind. Speed time up. */
269 icount_time_shift++;
271 last_delta = delta;
272 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
275 static void icount_adjust_rt(void * opaque)
277 qemu_mod_timer(icount_rt_timer,
278 qemu_get_clock(rt_clock) + 1000);
279 icount_adjust();
282 static void icount_adjust_vm(void * opaque)
284 qemu_mod_timer(icount_vm_timer,
285 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
286 icount_adjust();
289 int64_t qemu_icount_round(int64_t count)
291 return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
294 static struct qemu_alarm_timer alarm_timers[] = {
295 #ifndef _WIN32
296 #ifdef __linux__
297 {"dynticks", dynticks_start_timer,
298 dynticks_stop_timer, dynticks_rearm_timer, NULL},
299 /* HPET - if available - is preferred */
300 {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
301 /* ...otherwise try RTC */
302 {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
303 #endif
304 {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
305 #else
306 {"dynticks", win32_start_timer,
307 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
308 {"win32", win32_start_timer,
309 win32_stop_timer, NULL, &alarm_win32_data},
310 #endif
311 {NULL, }
314 static void show_available_alarms(void)
316 int i;
318 printf("Available alarm timers, in order of precedence:\n");
319 for (i = 0; alarm_timers[i].name; i++)
320 printf("%s\n", alarm_timers[i].name);
323 void configure_alarms(char const *opt)
325 int i;
326 int cur = 0;
327 int count = ARRAY_SIZE(alarm_timers) - 1;
328 char *arg;
329 char *name;
330 struct qemu_alarm_timer tmp;
332 if (!strcmp(opt, "?")) {
333 show_available_alarms();
334 exit(0);
337 arg = qemu_strdup(opt);
339 /* Reorder the array */
340 name = strtok(arg, ",");
341 while (name) {
342 for (i = 0; i < count && alarm_timers[i].name; i++) {
343 if (!strcmp(alarm_timers[i].name, name))
344 break;
347 if (i == count) {
348 fprintf(stderr, "Unknown clock %s\n", name);
349 goto next;
352 if (i < cur)
353 /* Ignore */
354 goto next;
356 /* Swap */
357 tmp = alarm_timers[i];
358 alarm_timers[i] = alarm_timers[cur];
359 alarm_timers[cur] = tmp;
361 cur++;
362 next:
363 name = strtok(NULL, ",");
366 qemu_free(arg);
368 if (cur) {
369 /* Disable remaining timers */
370 for (i = cur; i < count; i++)
371 alarm_timers[i].name = NULL;
372 } else {
373 show_available_alarms();
374 exit(1);
378 #define QEMU_NUM_CLOCKS 3
380 QEMUClock *rt_clock;
381 QEMUClock *vm_clock;
382 QEMUClock *host_clock;
384 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
386 static QEMUClock *qemu_new_clock(int type)
388 QEMUClock *clock;
389 clock = qemu_mallocz(sizeof(QEMUClock));
390 clock->type = type;
391 clock->enabled = 1;
392 return clock;
395 void qemu_clock_enable(QEMUClock *clock, int enabled)
397 clock->enabled = enabled;
400 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
402 QEMUTimer *ts;
404 ts = qemu_mallocz(sizeof(QEMUTimer));
405 ts->clock = clock;
406 ts->cb = cb;
407 ts->opaque = opaque;
408 return ts;
411 void qemu_free_timer(QEMUTimer *ts)
413 qemu_free(ts);
416 /* stop a timer, but do not dealloc it */
417 void qemu_del_timer(QEMUTimer *ts)
419 QEMUTimer **pt, *t;
421 /* NOTE: this code must be signal safe because
422 qemu_timer_expired() can be called from a signal. */
423 pt = &active_timers[ts->clock->type];
424 for(;;) {
425 t = *pt;
426 if (!t)
427 break;
428 if (t == ts) {
429 *pt = t->next;
430 break;
432 pt = &t->next;
436 /* modify the current timer so that it will be fired when current_time
437 >= expire_time. The corresponding callback will be called. */
438 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
440 QEMUTimer **pt, *t;
442 qemu_del_timer(ts);
444 /* add the timer in the sorted list */
445 /* NOTE: this code must be signal safe because
446 qemu_timer_expired() can be called from a signal. */
447 pt = &active_timers[ts->clock->type];
448 for(;;) {
449 t = *pt;
450 if (!t)
451 break;
452 if (t->expire_time > expire_time)
453 break;
454 pt = &t->next;
456 ts->expire_time = expire_time;
457 ts->next = *pt;
458 *pt = ts;
460 /* Rearm if necessary */
461 if (pt == &active_timers[ts->clock->type]) {
462 if (!alarm_timer->pending) {
463 qemu_rearm_alarm_timer(alarm_timer);
465 /* Interrupt execution to force deadline recalculation. */
466 if (use_icount)
467 qemu_notify_event();
471 int qemu_timer_pending(QEMUTimer *ts)
473 QEMUTimer *t;
474 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
475 if (t == ts)
476 return 1;
478 return 0;
481 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
483 if (!timer_head)
484 return 0;
485 return (timer_head->expire_time <= current_time);
488 static void qemu_run_timers(QEMUClock *clock)
490 QEMUTimer **ptimer_head, *ts;
491 int64_t current_time;
493 if (!clock->enabled)
494 return;
496 current_time = qemu_get_clock (clock);
497 ptimer_head = &active_timers[clock->type];
498 for(;;) {
499 ts = *ptimer_head;
500 if (!ts || ts->expire_time > current_time)
501 break;
502 /* remove timer from the list before calling the callback */
503 *ptimer_head = ts->next;
504 ts->next = NULL;
506 /* run the callback (the timer list can be modified) */
507 ts->cb(ts->opaque);
511 int64_t qemu_get_clock(QEMUClock *clock)
513 switch(clock->type) {
514 case QEMU_CLOCK_REALTIME:
515 return get_clock() / 1000000;
516 default:
517 case QEMU_CLOCK_VIRTUAL:
518 if (use_icount) {
519 return cpu_get_icount();
520 } else {
521 return cpu_get_clock();
523 case QEMU_CLOCK_HOST:
524 return get_clock_realtime();
528 int64_t qemu_get_clock_ns(QEMUClock *clock)
530 switch(clock->type) {
531 case QEMU_CLOCK_REALTIME:
532 return get_clock();
533 default:
534 case QEMU_CLOCK_VIRTUAL:
535 if (use_icount) {
536 return cpu_get_icount();
537 } else {
538 return cpu_get_clock();
540 case QEMU_CLOCK_HOST:
541 return get_clock_realtime();
545 void init_clocks(void)
547 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
548 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
549 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
551 rtc_clock = host_clock;
554 /* save a timer */
555 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
557 uint64_t expire_time;
559 if (qemu_timer_pending(ts)) {
560 expire_time = ts->expire_time;
561 } else {
562 expire_time = -1;
564 qemu_put_be64(f, expire_time);
567 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
569 uint64_t expire_time;
571 expire_time = qemu_get_be64(f);
572 if (expire_time != -1) {
573 qemu_mod_timer(ts, expire_time);
574 } else {
575 qemu_del_timer(ts);
579 static const VMStateDescription vmstate_timers = {
580 .name = "timer",
581 .version_id = 2,
582 .minimum_version_id = 1,
583 .minimum_version_id_old = 1,
584 .fields = (VMStateField []) {
585 VMSTATE_INT64(cpu_ticks_offset, TimersState),
586 VMSTATE_INT64(dummy, TimersState),
587 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
588 VMSTATE_END_OF_LIST()
592 void configure_icount(const char *option)
594 vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
595 if (!option)
596 return;
598 if (strcmp(option, "auto") != 0) {
599 icount_time_shift = strtol(option, NULL, 0);
600 use_icount = 1;
601 return;
604 use_icount = 2;
606 /* 125MIPS seems a reasonable initial guess at the guest speed.
607 It will be corrected fairly quickly anyway. */
608 icount_time_shift = 3;
610 /* Have both realtime and virtual time triggers for speed adjustment.
611 The realtime trigger catches emulated time passing too slowly,
612 the virtual time trigger catches emulated time passing too fast.
613 Realtime triggers occur even when idle, so use them less frequently
614 than VM triggers. */
615 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
616 qemu_mod_timer(icount_rt_timer,
617 qemu_get_clock(rt_clock) + 1000);
618 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
619 qemu_mod_timer(icount_vm_timer,
620 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
623 void qemu_run_all_timers(void)
625 alarm_timer->pending = 0;
627 /* rearm timer, if not periodic */
628 if (alarm_timer->expired) {
629 alarm_timer->expired = 0;
630 qemu_rearm_alarm_timer(alarm_timer);
633 /* vm time timers */
634 if (vm_running) {
635 qemu_run_timers(vm_clock);
638 qemu_run_timers(rt_clock);
639 qemu_run_timers(host_clock);
642 #ifdef _WIN32
643 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
644 DWORD_PTR dwUser, DWORD_PTR dw1,
645 DWORD_PTR dw2)
646 #else
647 static void host_alarm_handler(int host_signum)
648 #endif
650 struct qemu_alarm_timer *t = alarm_timer;
651 if (!t)
652 return;
654 #if 0
655 #define DISP_FREQ 1000
657 static int64_t delta_min = INT64_MAX;
658 static int64_t delta_max, delta_cum, last_clock, delta, ti;
659 static int count;
660 ti = qemu_get_clock(vm_clock);
661 if (last_clock != 0) {
662 delta = ti - last_clock;
663 if (delta < delta_min)
664 delta_min = delta;
665 if (delta > delta_max)
666 delta_max = delta;
667 delta_cum += delta;
668 if (++count == DISP_FREQ) {
669 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
670 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
671 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
672 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
673 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
674 count = 0;
675 delta_min = INT64_MAX;
676 delta_max = 0;
677 delta_cum = 0;
680 last_clock = ti;
682 #endif
683 if (alarm_has_dynticks(t) ||
684 (!use_icount &&
685 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
686 qemu_get_clock(vm_clock))) ||
687 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
688 qemu_get_clock(rt_clock)) ||
689 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
690 qemu_get_clock(host_clock))) {
692 t->expired = alarm_has_dynticks(t);
693 t->pending = 1;
694 qemu_notify_event();
698 int64_t qemu_next_deadline(void)
700 /* To avoid problems with overflow limit this to 2^32. */
701 int64_t delta = INT32_MAX;
703 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
704 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
705 qemu_get_clock(vm_clock);
707 if (active_timers[QEMU_CLOCK_HOST]) {
708 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
709 qemu_get_clock(host_clock);
710 if (hdelta < delta)
711 delta = hdelta;
714 if (delta < 0)
715 delta = 0;
717 return delta;
720 #ifndef _WIN32
722 #if defined(__linux__)
724 #define RTC_FREQ 1024
726 static uint64_t qemu_next_deadline_dyntick(void)
728 int64_t delta;
729 int64_t rtdelta;
731 if (use_icount)
732 delta = INT32_MAX;
733 else
734 delta = (qemu_next_deadline() + 999) / 1000;
736 if (active_timers[QEMU_CLOCK_REALTIME]) {
737 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
738 qemu_get_clock(rt_clock))*1000;
739 if (rtdelta < delta)
740 delta = rtdelta;
743 if (delta < MIN_TIMER_REARM_US)
744 delta = MIN_TIMER_REARM_US;
746 return delta;
749 static void enable_sigio_timer(int fd)
751 struct sigaction act;
753 /* timer signal */
754 sigfillset(&act.sa_mask);
755 act.sa_flags = 0;
756 act.sa_handler = host_alarm_handler;
758 sigaction(SIGIO, &act, NULL);
759 fcntl_setfl(fd, O_ASYNC);
760 fcntl(fd, F_SETOWN, getpid());
763 static int hpet_start_timer(struct qemu_alarm_timer *t)
765 struct hpet_info info;
766 int r, fd;
768 fd = qemu_open("/dev/hpet", O_RDONLY);
769 if (fd < 0)
770 return -1;
772 /* Set frequency */
773 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
774 if (r < 0) {
775 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
776 "error, but for better emulation accuracy type:\n"
777 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
778 goto fail;
781 /* Check capabilities */
782 r = ioctl(fd, HPET_INFO, &info);
783 if (r < 0)
784 goto fail;
786 /* Enable periodic mode */
787 r = ioctl(fd, HPET_EPI, 0);
788 if (info.hi_flags && (r < 0))
789 goto fail;
791 /* Enable interrupt */
792 r = ioctl(fd, HPET_IE_ON, 0);
793 if (r < 0)
794 goto fail;
796 enable_sigio_timer(fd);
797 t->priv = (void *)(long)fd;
799 return 0;
800 fail:
801 close(fd);
802 return -1;
805 static void hpet_stop_timer(struct qemu_alarm_timer *t)
807 int fd = (long)t->priv;
809 close(fd);
812 static int rtc_start_timer(struct qemu_alarm_timer *t)
814 int rtc_fd;
815 unsigned long current_rtc_freq = 0;
817 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
818 if (rtc_fd < 0)
819 return -1;
820 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
821 if (current_rtc_freq != RTC_FREQ &&
822 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
823 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
824 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
825 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
826 goto fail;
828 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
829 fail:
830 close(rtc_fd);
831 return -1;
834 enable_sigio_timer(rtc_fd);
836 t->priv = (void *)(long)rtc_fd;
838 return 0;
841 static void rtc_stop_timer(struct qemu_alarm_timer *t)
843 int rtc_fd = (long)t->priv;
845 close(rtc_fd);
848 static int dynticks_start_timer(struct qemu_alarm_timer *t)
850 struct sigevent ev;
851 timer_t host_timer;
852 struct sigaction act;
854 sigfillset(&act.sa_mask);
855 act.sa_flags = 0;
856 act.sa_handler = host_alarm_handler;
858 sigaction(SIGALRM, &act, NULL);
861 * Initialize ev struct to 0 to avoid valgrind complaining
862 * about uninitialized data in timer_create call
864 memset(&ev, 0, sizeof(ev));
865 ev.sigev_value.sival_int = 0;
866 ev.sigev_notify = SIGEV_SIGNAL;
867 ev.sigev_signo = SIGALRM;
869 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
870 perror("timer_create");
872 /* disable dynticks */
873 fprintf(stderr, "Dynamic Ticks disabled\n");
875 return -1;
878 t->priv = (void *)(long)host_timer;
880 return 0;
883 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
885 timer_t host_timer = (timer_t)(long)t->priv;
887 timer_delete(host_timer);
890 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
892 timer_t host_timer = (timer_t)(long)t->priv;
893 struct itimerspec timeout;
894 int64_t nearest_delta_us = INT64_MAX;
895 int64_t current_us;
897 assert(alarm_has_dynticks(t));
898 if (!active_timers[QEMU_CLOCK_REALTIME] &&
899 !active_timers[QEMU_CLOCK_VIRTUAL] &&
900 !active_timers[QEMU_CLOCK_HOST])
901 return;
903 nearest_delta_us = qemu_next_deadline_dyntick();
905 /* check whether a timer is already running */
906 if (timer_gettime(host_timer, &timeout)) {
907 perror("gettime");
908 fprintf(stderr, "Internal timer error: aborting\n");
909 exit(1);
911 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
912 if (current_us && current_us <= nearest_delta_us)
913 return;
915 timeout.it_interval.tv_sec = 0;
916 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
917 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
918 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
919 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
920 perror("settime");
921 fprintf(stderr, "Internal timer error: aborting\n");
922 exit(1);
926 #endif /* defined(__linux__) */
928 static int unix_start_timer(struct qemu_alarm_timer *t)
930 struct sigaction act;
931 struct itimerval itv;
932 int err;
934 /* timer signal */
935 sigfillset(&act.sa_mask);
936 act.sa_flags = 0;
937 act.sa_handler = host_alarm_handler;
939 sigaction(SIGALRM, &act, NULL);
941 itv.it_interval.tv_sec = 0;
942 /* for i386 kernel 2.6 to get 1 ms */
943 itv.it_interval.tv_usec = 999;
944 itv.it_value.tv_sec = 0;
945 itv.it_value.tv_usec = 10 * 1000;
947 err = setitimer(ITIMER_REAL, &itv, NULL);
948 if (err)
949 return -1;
951 return 0;
954 static void unix_stop_timer(struct qemu_alarm_timer *t)
956 struct itimerval itv;
958 memset(&itv, 0, sizeof(itv));
959 setitimer(ITIMER_REAL, &itv, NULL);
962 #endif /* !defined(_WIN32) */
965 #ifdef _WIN32
967 static int win32_start_timer(struct qemu_alarm_timer *t)
969 TIMECAPS tc;
970 struct qemu_alarm_win32 *data = t->priv;
971 UINT flags;
973 memset(&tc, 0, sizeof(tc));
974 timeGetDevCaps(&tc, sizeof(tc));
976 data->period = tc.wPeriodMin;
977 timeBeginPeriod(data->period);
979 flags = TIME_CALLBACK_FUNCTION;
980 if (alarm_has_dynticks(t))
981 flags |= TIME_ONESHOT;
982 else
983 flags |= TIME_PERIODIC;
985 data->timerId = timeSetEvent(1, // interval (ms)
986 data->period, // resolution
987 host_alarm_handler, // function
988 (DWORD)t, // parameter
989 flags);
991 if (!data->timerId) {
992 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
993 GetLastError());
994 timeEndPeriod(data->period);
995 return -1;
998 return 0;
1001 static void win32_stop_timer(struct qemu_alarm_timer *t)
1003 struct qemu_alarm_win32 *data = t->priv;
1005 timeKillEvent(data->timerId);
1006 timeEndPeriod(data->period);
1009 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1011 struct qemu_alarm_win32 *data = t->priv;
1013 assert(alarm_has_dynticks(t));
1014 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1015 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1016 !active_timers[QEMU_CLOCK_HOST])
1017 return;
1019 timeKillEvent(data->timerId);
1021 data->timerId = timeSetEvent(1,
1022 data->period,
1023 host_alarm_handler,
1024 (DWORD)t,
1025 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1027 if (!data->timerId) {
1028 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1029 GetLastError());
1031 timeEndPeriod(data->period);
1032 exit(1);
1036 #endif /* _WIN32 */
1038 static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1040 if (running)
1041 qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1044 int init_timer_alarm(void)
1046 struct qemu_alarm_timer *t = NULL;
1047 int i, err = -1;
1049 for (i = 0; alarm_timers[i].name; i++) {
1050 t = &alarm_timers[i];
1052 err = t->start(t);
1053 if (!err)
1054 break;
1057 if (err) {
1058 err = -ENOENT;
1059 goto fail;
1062 /* first event is at time 0 */
1063 t->pending = 1;
1064 alarm_timer = t;
1065 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1067 return 0;
1069 fail:
1070 return err;
1073 void quit_timers(void)
1075 struct qemu_alarm_timer *t = alarm_timer;
1076 alarm_timer = NULL;
1077 t->stop(t);
1080 int qemu_calculate_timeout(void)
1082 #ifndef CONFIG_IOTHREAD
1083 int timeout;
1085 if (!vm_running)
1086 timeout = 5000;
1087 else {
1088 /* XXX: use timeout computed from timers */
1089 int64_t add;
1090 int64_t delta;
1091 /* Advance virtual time to the next event. */
1092 delta = qemu_icount_delta();
1093 if (delta > 0) {
1094 /* If virtual time is ahead of real time then just
1095 wait for IO. */
1096 timeout = (delta + 999999) / 1000000;
1097 } else {
1098 /* Wait for either IO to occur or the next
1099 timer event. */
1100 add = qemu_next_deadline();
1101 /* We advance the timer before checking for IO.
1102 Limit the amount we advance so that early IO
1103 activity won't get the guest too far ahead. */
1104 if (add > 10000000)
1105 add = 10000000;
1106 delta += add;
1107 qemu_icount += qemu_icount_round (add);
1108 timeout = delta / 1000000;
1109 if (timeout < 0)
1110 timeout = 0;
1114 return timeout;
1115 #else /* CONFIG_IOTHREAD */
1116 return 1000;
1117 #endif