Fix OpenBSD build warning
[qemu/lumag.git] / qemu-timer.c
blobbc5f207bb6e5c4cac2edb686286235f7464f772b
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 #ifndef CONFIG_IOTHREAD
186 static int64_t qemu_icount_delta(void)
188 if (!use_icount) {
189 return 5000 * (int64_t) 1000000;
190 } else if (use_icount == 1) {
191 /* When not using an adaptive execution frequency
192 we tend to get badly out of sync with real time,
193 so just delay for a reasonable amount of time. */
194 return 0;
195 } else {
196 return cpu_get_icount() - cpu_get_clock();
199 #endif
201 /* enable cpu_get_ticks() */
202 void cpu_enable_ticks(void)
204 if (!timers_state.cpu_ticks_enabled) {
205 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
206 timers_state.cpu_clock_offset -= get_clock();
207 timers_state.cpu_ticks_enabled = 1;
211 /* disable cpu_get_ticks() : the clock is stopped. You must not call
212 cpu_get_ticks() after that. */
213 void cpu_disable_ticks(void)
215 if (timers_state.cpu_ticks_enabled) {
216 timers_state.cpu_ticks_offset = cpu_get_ticks();
217 timers_state.cpu_clock_offset = cpu_get_clock();
218 timers_state.cpu_ticks_enabled = 0;
222 /***********************************************************/
223 /* timers */
225 #define QEMU_CLOCK_REALTIME 0
226 #define QEMU_CLOCK_VIRTUAL 1
227 #define QEMU_CLOCK_HOST 2
229 struct QEMUClock {
230 int type;
231 int enabled;
232 /* XXX: add frequency */
235 struct QEMUTimer {
236 QEMUClock *clock;
237 int64_t expire_time;
238 QEMUTimerCB *cb;
239 void *opaque;
240 struct QEMUTimer *next;
243 struct qemu_alarm_timer {
244 char const *name;
245 int (*start)(struct qemu_alarm_timer *t);
246 void (*stop)(struct qemu_alarm_timer *t);
247 void (*rearm)(struct qemu_alarm_timer *t);
248 void *priv;
250 char expired;
251 char pending;
254 static struct qemu_alarm_timer *alarm_timer;
256 int qemu_alarm_pending(void)
258 return alarm_timer->pending;
261 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
263 return !!t->rearm;
266 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
268 if (!alarm_has_dynticks(t))
269 return;
271 t->rearm(t);
274 /* TODO: MIN_TIMER_REARM_US should be optimized */
275 #define MIN_TIMER_REARM_US 250
277 #ifdef _WIN32
279 struct qemu_alarm_win32 {
280 MMRESULT timerId;
281 unsigned int period;
282 } alarm_win32_data = {0, 0};
284 static int win32_start_timer(struct qemu_alarm_timer *t);
285 static void win32_stop_timer(struct qemu_alarm_timer *t);
286 static void win32_rearm_timer(struct qemu_alarm_timer *t);
288 #else
290 static int unix_start_timer(struct qemu_alarm_timer *t);
291 static void unix_stop_timer(struct qemu_alarm_timer *t);
293 #ifdef __linux__
295 static int dynticks_start_timer(struct qemu_alarm_timer *t);
296 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
297 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
299 static int hpet_start_timer(struct qemu_alarm_timer *t);
300 static void hpet_stop_timer(struct qemu_alarm_timer *t);
302 static int rtc_start_timer(struct qemu_alarm_timer *t);
303 static void rtc_stop_timer(struct qemu_alarm_timer *t);
305 #endif /* __linux__ */
307 #endif /* _WIN32 */
309 /* Correlation between real and virtual time is always going to be
310 fairly approximate, so ignore small variation.
311 When the guest is idle real and virtual time will be aligned in
312 the IO wait loop. */
313 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
315 static void icount_adjust(void)
317 int64_t cur_time;
318 int64_t cur_icount;
319 int64_t delta;
320 static int64_t last_delta;
321 /* If the VM is not running, then do nothing. */
322 if (!vm_running)
323 return;
325 cur_time = cpu_get_clock();
326 cur_icount = qemu_get_clock(vm_clock);
327 delta = cur_icount - cur_time;
328 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
329 if (delta > 0
330 && last_delta + ICOUNT_WOBBLE < delta * 2
331 && icount_time_shift > 0) {
332 /* The guest is getting too far ahead. Slow time down. */
333 icount_time_shift--;
335 if (delta < 0
336 && last_delta - ICOUNT_WOBBLE > delta * 2
337 && icount_time_shift < MAX_ICOUNT_SHIFT) {
338 /* The guest is getting too far behind. Speed time up. */
339 icount_time_shift++;
341 last_delta = delta;
342 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
345 static void icount_adjust_rt(void * opaque)
347 qemu_mod_timer(icount_rt_timer,
348 qemu_get_clock(rt_clock) + 1000);
349 icount_adjust();
352 static void icount_adjust_vm(void * opaque)
354 qemu_mod_timer(icount_vm_timer,
355 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
356 icount_adjust();
359 int64_t qemu_icount_round(int64_t count)
361 return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
364 static struct qemu_alarm_timer alarm_timers[] = {
365 #ifndef _WIN32
366 #ifdef __linux__
367 {"dynticks", dynticks_start_timer,
368 dynticks_stop_timer, dynticks_rearm_timer, NULL},
369 /* HPET - if available - is preferred */
370 {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
371 /* ...otherwise try RTC */
372 {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
373 #endif
374 {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
375 #else
376 {"dynticks", win32_start_timer,
377 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
378 {"win32", win32_start_timer,
379 win32_stop_timer, NULL, &alarm_win32_data},
380 #endif
381 {NULL, }
384 static void show_available_alarms(void)
386 int i;
388 printf("Available alarm timers, in order of precedence:\n");
389 for (i = 0; alarm_timers[i].name; i++)
390 printf("%s\n", alarm_timers[i].name);
393 void configure_alarms(char const *opt)
395 int i;
396 int cur = 0;
397 int count = ARRAY_SIZE(alarm_timers) - 1;
398 char *arg;
399 char *name;
400 struct qemu_alarm_timer tmp;
402 if (!strcmp(opt, "?")) {
403 show_available_alarms();
404 exit(0);
407 arg = qemu_strdup(opt);
409 /* Reorder the array */
410 name = strtok(arg, ",");
411 while (name) {
412 for (i = 0; i < count && alarm_timers[i].name; i++) {
413 if (!strcmp(alarm_timers[i].name, name))
414 break;
417 if (i == count) {
418 fprintf(stderr, "Unknown clock %s\n", name);
419 goto next;
422 if (i < cur)
423 /* Ignore */
424 goto next;
426 /* Swap */
427 tmp = alarm_timers[i];
428 alarm_timers[i] = alarm_timers[cur];
429 alarm_timers[cur] = tmp;
431 cur++;
432 next:
433 name = strtok(NULL, ",");
436 qemu_free(arg);
438 if (cur) {
439 /* Disable remaining timers */
440 for (i = cur; i < count; i++)
441 alarm_timers[i].name = NULL;
442 } else {
443 show_available_alarms();
444 exit(1);
448 #define QEMU_NUM_CLOCKS 3
450 QEMUClock *rt_clock;
451 QEMUClock *vm_clock;
452 QEMUClock *host_clock;
454 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
456 static QEMUClock *qemu_new_clock(int type)
458 QEMUClock *clock;
459 clock = qemu_mallocz(sizeof(QEMUClock));
460 clock->type = type;
461 clock->enabled = 1;
462 return clock;
465 void qemu_clock_enable(QEMUClock *clock, int enabled)
467 clock->enabled = enabled;
470 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
472 QEMUTimer *ts;
474 ts = qemu_mallocz(sizeof(QEMUTimer));
475 ts->clock = clock;
476 ts->cb = cb;
477 ts->opaque = opaque;
478 return ts;
481 void qemu_free_timer(QEMUTimer *ts)
483 qemu_free(ts);
486 /* stop a timer, but do not dealloc it */
487 void qemu_del_timer(QEMUTimer *ts)
489 QEMUTimer **pt, *t;
491 /* NOTE: this code must be signal safe because
492 qemu_timer_expired() can be called from a signal. */
493 pt = &active_timers[ts->clock->type];
494 for(;;) {
495 t = *pt;
496 if (!t)
497 break;
498 if (t == ts) {
499 *pt = t->next;
500 break;
502 pt = &t->next;
506 /* modify the current timer so that it will be fired when current_time
507 >= expire_time. The corresponding callback will be called. */
508 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
510 QEMUTimer **pt, *t;
512 qemu_del_timer(ts);
514 /* add the timer in the sorted list */
515 /* NOTE: this code must be signal safe because
516 qemu_timer_expired() can be called from a signal. */
517 pt = &active_timers[ts->clock->type];
518 for(;;) {
519 t = *pt;
520 if (!t)
521 break;
522 if (t->expire_time > expire_time)
523 break;
524 pt = &t->next;
526 ts->expire_time = expire_time;
527 ts->next = *pt;
528 *pt = ts;
530 /* Rearm if necessary */
531 if (pt == &active_timers[ts->clock->type]) {
532 if (!alarm_timer->pending) {
533 qemu_rearm_alarm_timer(alarm_timer);
535 /* Interrupt execution to force deadline recalculation. */
536 if (use_icount)
537 qemu_notify_event();
541 int qemu_timer_pending(QEMUTimer *ts)
543 QEMUTimer *t;
544 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
545 if (t == ts)
546 return 1;
548 return 0;
551 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
553 if (!timer_head)
554 return 0;
555 return (timer_head->expire_time <= current_time);
558 static void qemu_run_timers(QEMUClock *clock)
560 QEMUTimer **ptimer_head, *ts;
561 int64_t current_time;
563 if (!clock->enabled)
564 return;
566 current_time = qemu_get_clock (clock);
567 ptimer_head = &active_timers[clock->type];
568 for(;;) {
569 ts = *ptimer_head;
570 if (!ts || ts->expire_time > current_time)
571 break;
572 /* remove timer from the list before calling the callback */
573 *ptimer_head = ts->next;
574 ts->next = NULL;
576 /* run the callback (the timer list can be modified) */
577 ts->cb(ts->opaque);
581 int64_t qemu_get_clock(QEMUClock *clock)
583 switch(clock->type) {
584 case QEMU_CLOCK_REALTIME:
585 return get_clock() / 1000000;
586 default:
587 case QEMU_CLOCK_VIRTUAL:
588 if (use_icount) {
589 return cpu_get_icount();
590 } else {
591 return cpu_get_clock();
593 case QEMU_CLOCK_HOST:
594 return get_clock_realtime();
598 int64_t qemu_get_clock_ns(QEMUClock *clock)
600 switch(clock->type) {
601 case QEMU_CLOCK_REALTIME:
602 return get_clock();
603 default:
604 case QEMU_CLOCK_VIRTUAL:
605 if (use_icount) {
606 return cpu_get_icount();
607 } else {
608 return cpu_get_clock();
610 case QEMU_CLOCK_HOST:
611 return get_clock_realtime();
615 void init_clocks(void)
617 init_get_clock();
618 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
619 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
620 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
622 rtc_clock = host_clock;
625 /* save a timer */
626 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
628 uint64_t expire_time;
630 if (qemu_timer_pending(ts)) {
631 expire_time = ts->expire_time;
632 } else {
633 expire_time = -1;
635 qemu_put_be64(f, expire_time);
638 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
640 uint64_t expire_time;
642 expire_time = qemu_get_be64(f);
643 if (expire_time != -1) {
644 qemu_mod_timer(ts, expire_time);
645 } else {
646 qemu_del_timer(ts);
650 static const VMStateDescription vmstate_timers = {
651 .name = "timer",
652 .version_id = 2,
653 .minimum_version_id = 1,
654 .minimum_version_id_old = 1,
655 .fields = (VMStateField []) {
656 VMSTATE_INT64(cpu_ticks_offset, TimersState),
657 VMSTATE_INT64(dummy, TimersState),
658 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
659 VMSTATE_END_OF_LIST()
663 void configure_icount(const char *option)
665 vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
666 if (!option)
667 return;
669 if (strcmp(option, "auto") != 0) {
670 icount_time_shift = strtol(option, NULL, 0);
671 use_icount = 1;
672 return;
675 use_icount = 2;
677 /* 125MIPS seems a reasonable initial guess at the guest speed.
678 It will be corrected fairly quickly anyway. */
679 icount_time_shift = 3;
681 /* Have both realtime and virtual time triggers for speed adjustment.
682 The realtime trigger catches emulated time passing too slowly,
683 the virtual time trigger catches emulated time passing too fast.
684 Realtime triggers occur even when idle, so use them less frequently
685 than VM triggers. */
686 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
687 qemu_mod_timer(icount_rt_timer,
688 qemu_get_clock(rt_clock) + 1000);
689 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
690 qemu_mod_timer(icount_vm_timer,
691 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
694 void qemu_run_all_timers(void)
696 alarm_timer->pending = 0;
698 /* rearm timer, if not periodic */
699 if (alarm_timer->expired) {
700 alarm_timer->expired = 0;
701 qemu_rearm_alarm_timer(alarm_timer);
704 /* vm time timers */
705 if (vm_running) {
706 qemu_run_timers(vm_clock);
709 qemu_run_timers(rt_clock);
710 qemu_run_timers(host_clock);
713 #ifdef _WIN32
714 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
715 DWORD_PTR dwUser, DWORD_PTR dw1,
716 DWORD_PTR dw2)
717 #else
718 static void host_alarm_handler(int host_signum)
719 #endif
721 struct qemu_alarm_timer *t = alarm_timer;
722 if (!t)
723 return;
725 #if 0
726 #define DISP_FREQ 1000
728 static int64_t delta_min = INT64_MAX;
729 static int64_t delta_max, delta_cum, last_clock, delta, ti;
730 static int count;
731 ti = qemu_get_clock(vm_clock);
732 if (last_clock != 0) {
733 delta = ti - last_clock;
734 if (delta < delta_min)
735 delta_min = delta;
736 if (delta > delta_max)
737 delta_max = delta;
738 delta_cum += delta;
739 if (++count == DISP_FREQ) {
740 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
741 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
742 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
743 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
744 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
745 count = 0;
746 delta_min = INT64_MAX;
747 delta_max = 0;
748 delta_cum = 0;
751 last_clock = ti;
753 #endif
754 if (alarm_has_dynticks(t) ||
755 (!use_icount &&
756 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
757 qemu_get_clock(vm_clock))) ||
758 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
759 qemu_get_clock(rt_clock)) ||
760 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
761 qemu_get_clock(host_clock))) {
763 t->expired = alarm_has_dynticks(t);
764 t->pending = 1;
765 qemu_notify_event();
769 int64_t qemu_next_deadline(void)
771 /* To avoid problems with overflow limit this to 2^32. */
772 int64_t delta = INT32_MAX;
774 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
775 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
776 qemu_get_clock(vm_clock);
778 if (active_timers[QEMU_CLOCK_HOST]) {
779 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
780 qemu_get_clock(host_clock);
781 if (hdelta < delta)
782 delta = hdelta;
785 if (delta < 0)
786 delta = 0;
788 return delta;
791 #ifndef _WIN32
793 #if defined(__linux__)
795 #define RTC_FREQ 1024
797 static uint64_t qemu_next_deadline_dyntick(void)
799 int64_t delta;
800 int64_t rtdelta;
802 if (use_icount)
803 delta = INT32_MAX;
804 else
805 delta = (qemu_next_deadline() + 999) / 1000;
807 if (active_timers[QEMU_CLOCK_REALTIME]) {
808 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
809 qemu_get_clock(rt_clock))*1000;
810 if (rtdelta < delta)
811 delta = rtdelta;
814 if (delta < MIN_TIMER_REARM_US)
815 delta = MIN_TIMER_REARM_US;
817 return delta;
820 static void enable_sigio_timer(int fd)
822 struct sigaction act;
824 /* timer signal */
825 sigfillset(&act.sa_mask);
826 act.sa_flags = 0;
827 act.sa_handler = host_alarm_handler;
829 sigaction(SIGIO, &act, NULL);
830 fcntl_setfl(fd, O_ASYNC);
831 fcntl(fd, F_SETOWN, getpid());
834 static int hpet_start_timer(struct qemu_alarm_timer *t)
836 struct hpet_info info;
837 int r, fd;
839 fd = qemu_open("/dev/hpet", O_RDONLY);
840 if (fd < 0)
841 return -1;
843 /* Set frequency */
844 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
845 if (r < 0) {
846 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
847 "error, but for better emulation accuracy type:\n"
848 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
849 goto fail;
852 /* Check capabilities */
853 r = ioctl(fd, HPET_INFO, &info);
854 if (r < 0)
855 goto fail;
857 /* Enable periodic mode */
858 r = ioctl(fd, HPET_EPI, 0);
859 if (info.hi_flags && (r < 0))
860 goto fail;
862 /* Enable interrupt */
863 r = ioctl(fd, HPET_IE_ON, 0);
864 if (r < 0)
865 goto fail;
867 enable_sigio_timer(fd);
868 t->priv = (void *)(long)fd;
870 return 0;
871 fail:
872 close(fd);
873 return -1;
876 static void hpet_stop_timer(struct qemu_alarm_timer *t)
878 int fd = (long)t->priv;
880 close(fd);
883 static int rtc_start_timer(struct qemu_alarm_timer *t)
885 int rtc_fd;
886 unsigned long current_rtc_freq = 0;
888 TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
889 if (rtc_fd < 0)
890 return -1;
891 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
892 if (current_rtc_freq != RTC_FREQ &&
893 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
894 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
895 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
896 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
897 goto fail;
899 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
900 fail:
901 close(rtc_fd);
902 return -1;
905 enable_sigio_timer(rtc_fd);
907 t->priv = (void *)(long)rtc_fd;
909 return 0;
912 static void rtc_stop_timer(struct qemu_alarm_timer *t)
914 int rtc_fd = (long)t->priv;
916 close(rtc_fd);
919 static int dynticks_start_timer(struct qemu_alarm_timer *t)
921 struct sigevent ev;
922 timer_t host_timer;
923 struct sigaction act;
925 sigfillset(&act.sa_mask);
926 act.sa_flags = 0;
927 act.sa_handler = host_alarm_handler;
929 sigaction(SIGALRM, &act, NULL);
932 * Initialize ev struct to 0 to avoid valgrind complaining
933 * about uninitialized data in timer_create call
935 memset(&ev, 0, sizeof(ev));
936 ev.sigev_value.sival_int = 0;
937 ev.sigev_notify = SIGEV_SIGNAL;
938 ev.sigev_signo = SIGALRM;
940 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
941 perror("timer_create");
943 /* disable dynticks */
944 fprintf(stderr, "Dynamic Ticks disabled\n");
946 return -1;
949 t->priv = (void *)(long)host_timer;
951 return 0;
954 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
956 timer_t host_timer = (timer_t)(long)t->priv;
958 timer_delete(host_timer);
961 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
963 timer_t host_timer = (timer_t)(long)t->priv;
964 struct itimerspec timeout;
965 int64_t nearest_delta_us = INT64_MAX;
966 int64_t current_us;
968 assert(alarm_has_dynticks(t));
969 if (!active_timers[QEMU_CLOCK_REALTIME] &&
970 !active_timers[QEMU_CLOCK_VIRTUAL] &&
971 !active_timers[QEMU_CLOCK_HOST])
972 return;
974 nearest_delta_us = qemu_next_deadline_dyntick();
976 /* check whether a timer is already running */
977 if (timer_gettime(host_timer, &timeout)) {
978 perror("gettime");
979 fprintf(stderr, "Internal timer error: aborting\n");
980 exit(1);
982 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
983 if (current_us && current_us <= nearest_delta_us)
984 return;
986 timeout.it_interval.tv_sec = 0;
987 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
988 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
989 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
990 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
991 perror("settime");
992 fprintf(stderr, "Internal timer error: aborting\n");
993 exit(1);
997 #endif /* defined(__linux__) */
999 static int unix_start_timer(struct qemu_alarm_timer *t)
1001 struct sigaction act;
1002 struct itimerval itv;
1003 int err;
1005 /* timer signal */
1006 sigfillset(&act.sa_mask);
1007 act.sa_flags = 0;
1008 act.sa_handler = host_alarm_handler;
1010 sigaction(SIGALRM, &act, NULL);
1012 itv.it_interval.tv_sec = 0;
1013 /* for i386 kernel 2.6 to get 1 ms */
1014 itv.it_interval.tv_usec = 999;
1015 itv.it_value.tv_sec = 0;
1016 itv.it_value.tv_usec = 10 * 1000;
1018 err = setitimer(ITIMER_REAL, &itv, NULL);
1019 if (err)
1020 return -1;
1022 return 0;
1025 static void unix_stop_timer(struct qemu_alarm_timer *t)
1027 struct itimerval itv;
1029 memset(&itv, 0, sizeof(itv));
1030 setitimer(ITIMER_REAL, &itv, NULL);
1033 #endif /* !defined(_WIN32) */
1036 #ifdef _WIN32
1038 static int win32_start_timer(struct qemu_alarm_timer *t)
1040 TIMECAPS tc;
1041 struct qemu_alarm_win32 *data = t->priv;
1042 UINT flags;
1044 memset(&tc, 0, sizeof(tc));
1045 timeGetDevCaps(&tc, sizeof(tc));
1047 data->period = tc.wPeriodMin;
1048 timeBeginPeriod(data->period);
1050 flags = TIME_CALLBACK_FUNCTION;
1051 if (alarm_has_dynticks(t))
1052 flags |= TIME_ONESHOT;
1053 else
1054 flags |= TIME_PERIODIC;
1056 data->timerId = timeSetEvent(1, // interval (ms)
1057 data->period, // resolution
1058 host_alarm_handler, // function
1059 (DWORD)t, // parameter
1060 flags);
1062 if (!data->timerId) {
1063 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1064 GetLastError());
1065 timeEndPeriod(data->period);
1066 return -1;
1069 return 0;
1072 static void win32_stop_timer(struct qemu_alarm_timer *t)
1074 struct qemu_alarm_win32 *data = t->priv;
1076 timeKillEvent(data->timerId);
1077 timeEndPeriod(data->period);
1080 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1082 struct qemu_alarm_win32 *data = t->priv;
1084 assert(alarm_has_dynticks(t));
1085 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1086 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1087 !active_timers[QEMU_CLOCK_HOST])
1088 return;
1090 timeKillEvent(data->timerId);
1092 data->timerId = timeSetEvent(1,
1093 data->period,
1094 host_alarm_handler,
1095 (DWORD)t,
1096 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1098 if (!data->timerId) {
1099 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1100 GetLastError());
1102 timeEndPeriod(data->period);
1103 exit(1);
1107 #endif /* _WIN32 */
1109 static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1111 if (running)
1112 qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1115 int init_timer_alarm(void)
1117 struct qemu_alarm_timer *t = NULL;
1118 int i, err = -1;
1120 for (i = 0; alarm_timers[i].name; i++) {
1121 t = &alarm_timers[i];
1123 err = t->start(t);
1124 if (!err)
1125 break;
1128 if (err) {
1129 err = -ENOENT;
1130 goto fail;
1133 /* first event is at time 0 */
1134 t->pending = 1;
1135 alarm_timer = t;
1136 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1138 return 0;
1140 fail:
1141 return err;
1144 void quit_timers(void)
1146 struct qemu_alarm_timer *t = alarm_timer;
1147 alarm_timer = NULL;
1148 t->stop(t);
1151 int qemu_calculate_timeout(void)
1153 #ifndef CONFIG_IOTHREAD
1154 int timeout;
1156 if (!vm_running)
1157 timeout = 5000;
1158 else {
1159 /* XXX: use timeout computed from timers */
1160 int64_t add;
1161 int64_t delta;
1162 /* Advance virtual time to the next event. */
1163 delta = qemu_icount_delta();
1164 if (delta > 0) {
1165 /* If virtual time is ahead of real time then just
1166 wait for IO. */
1167 timeout = (delta + 999999) / 1000000;
1168 } else {
1169 /* Wait for either IO to occur or the next
1170 timer event. */
1171 add = qemu_next_deadline();
1172 /* We advance the timer before checking for IO.
1173 Limit the amount we advance so that early IO
1174 activity won't get the guest too far ahead. */
1175 if (add > 10000000)
1176 add = 10000000;
1177 delta += add;
1178 qemu_icount += qemu_icount_round (add);
1179 timeout = delta / 1000000;
1180 if (timeout < 0)
1181 timeout = 0;
1185 return timeout;
1186 #else /* CONFIG_IOTHREAD */
1187 return 1000;
1188 #endif