blob: 6ad2858c7b7bfca7dffcfd1bde4d8fb540d204f2 [file] [log] [blame]
David Turner6a9ef172010-09-09 22:54:36 +02001/*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
24
25#include "sysemu.h"
26#include "net.h"
27#include "monitor.h"
28#include "console.h"
29
30#include "hw/hw.h"
31
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
41
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
50
51#ifdef _WIN32
52#include <windows.h>
53#include <mmsystem.h>
54#endif
55
56#include "qemu-timer.h"
57
58/* Conversion factor from emulated instructions to virtual clock ticks. */
59int 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. */
63int64_t qemu_icount_bias;
64static QEMUTimer *icount_rt_timer;
65static QEMUTimer *icount_vm_timer;
66
67
68/***********************************************************/
69/* real time host monotonic timer */
70
71
72static int64_t get_clock_realtime(void)
73{
74 struct timeval tv;
75
76 gettimeofday(&tv, NULL);
77 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
78}
79
80#ifdef WIN32
81
82static int64_t clock_freq;
83
84static void init_get_clock(void)
85{
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);
92 }
93 clock_freq = freq.QuadPart;
94}
95
96static int64_t get_clock(void)
97{
98 LARGE_INTEGER ti;
99 QueryPerformanceCounter(&ti);
100 return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
101}
102
103#else
104
105static int use_rt_clock;
106
107static void init_get_clock(void)
108{
109 use_rt_clock = 0;
110#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
111 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
112 {
113 struct timespec ts;
114 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
115 use_rt_clock = 1;
116 }
117 }
118#endif
119}
120
121static int64_t get_clock(void)
122{
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
131 {
132 /* XXX: using gettimeofday leads to problems if the date
133 changes, so it should be avoided. */
134 return get_clock_realtime();
135 }
136}
137#endif
138
139/***********************************************************/
140/* guest cycle counter */
141
142typedef 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;
149
150static void timer_save(QEMUFile *f, void *opaque)
151{
152 TimersState *s = opaque;
153
154 if (s->cpu_ticks_enabled) {
155 hw_error("cannot save state if virtual timers are running");
156 }
157 qemu_put_be64(f, s->cpu_ticks_prev);
158 qemu_put_be64(f, s->cpu_ticks_offset);
159 qemu_put_be64(f, s->cpu_clock_offset);
160 }
161
162static int timer_load(QEMUFile *f, void *opaque, int version_id)
163{
164 TimersState *s = opaque;
165
166 if (version_id != 1 && version_id != 2)
167 return -EINVAL;
168 if (s->cpu_ticks_enabled) {
169 return -EINVAL;
170 }
171 s->cpu_ticks_prev = qemu_get_sbe64(f);
172 s->cpu_ticks_offset = qemu_get_sbe64(f);
173 if (version_id == 2) {
174 s->cpu_clock_offset = qemu_get_sbe64(f);
175 }
176 return 0;
177}
178
179
180TimersState timers_state;
181
182/* return the host CPU cycle counter and handle stop/restart */
183int64_t cpu_get_ticks(void)
184{
185 if (use_icount) {
186 return cpu_get_icount();
187 }
188 if (!timers_state.cpu_ticks_enabled) {
189 return timers_state.cpu_ticks_offset;
190 } else {
191 int64_t ticks;
192 ticks = cpu_get_real_ticks();
193 if (timers_state.cpu_ticks_prev > ticks) {
194 /* Note: non increasing ticks may happen if the host uses
195 software suspend */
196 timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
197 }
198 timers_state.cpu_ticks_prev = ticks;
199 return ticks + timers_state.cpu_ticks_offset;
200 }
201}
202
203/* return the host CPU monotonic timer and handle stop/restart */
204static int64_t cpu_get_clock(void)
205{
206 int64_t ti;
207 if (!timers_state.cpu_ticks_enabled) {
208 return timers_state.cpu_clock_offset;
209 } else {
210 ti = get_clock();
211 return ti + timers_state.cpu_clock_offset;
212 }
213}
214
215#ifndef CONFIG_IOTHREAD
216static int64_t qemu_icount_delta(void)
217{
218 if (!use_icount) {
219 return 5000 * (int64_t) 1000000;
220 } else if (use_icount == 1) {
221 /* When not using an adaptive execution frequency
222 we tend to get badly out of sync with real time,
223 so just delay for a reasonable amount of time. */
224 return 0;
225 } else {
226 return cpu_get_icount() - cpu_get_clock();
227 }
228}
229#endif
230
231/* enable cpu_get_ticks() */
232void cpu_enable_ticks(void)
233{
234 if (!timers_state.cpu_ticks_enabled) {
235 timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
236 timers_state.cpu_clock_offset -= get_clock();
237 timers_state.cpu_ticks_enabled = 1;
238 }
239}
240
241/* disable cpu_get_ticks() : the clock is stopped. You must not call
242 cpu_get_ticks() after that. */
243void cpu_disable_ticks(void)
244{
245 if (timers_state.cpu_ticks_enabled) {
246 timers_state.cpu_ticks_offset = cpu_get_ticks();
247 timers_state.cpu_clock_offset = cpu_get_clock();
248 timers_state.cpu_ticks_enabled = 0;
249 }
250}
251
252/***********************************************************/
253/* timers */
254
255#define QEMU_CLOCK_REALTIME 0
256#define QEMU_CLOCK_VIRTUAL 1
257#define QEMU_CLOCK_HOST 2
258
259struct QEMUClock {
260 int type;
261 int enabled;
262 /* XXX: add frequency */
263};
264
265struct QEMUTimer {
266 QEMUClock *clock;
267 int64_t expire_time;
268 QEMUTimerCB *cb;
269 void *opaque;
270 struct QEMUTimer *next;
271};
272
273struct qemu_alarm_timer {
274 char const *name;
275 int (*start)(struct qemu_alarm_timer *t);
276 void (*stop)(struct qemu_alarm_timer *t);
277 void (*rearm)(struct qemu_alarm_timer *t);
278 void *priv;
279
280 char expired;
281 char pending;
282};
283
284static struct qemu_alarm_timer *alarm_timer;
285
286int qemu_alarm_pending(void)
287{
288 return alarm_timer->pending;
289}
290
291static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
292{
293 return !!t->rearm;
294}
295
296static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
297{
298 if (!alarm_has_dynticks(t))
299 return;
300
301 t->rearm(t);
302}
303
304/* TODO: MIN_TIMER_REARM_US should be optimized */
305#define MIN_TIMER_REARM_US 250
306
307#ifdef _WIN32
308
309struct qemu_alarm_win32 {
310 MMRESULT timerId;
311 unsigned int period;
312} alarm_win32_data = {0, 0};
313
314static int win32_start_timer(struct qemu_alarm_timer *t);
315static void win32_stop_timer(struct qemu_alarm_timer *t);
316static void win32_rearm_timer(struct qemu_alarm_timer *t);
317
318#else
319
320static int unix_start_timer(struct qemu_alarm_timer *t);
321static void unix_stop_timer(struct qemu_alarm_timer *t);
322
323#ifdef __linux__
324
325static int dynticks_start_timer(struct qemu_alarm_timer *t);
326static void dynticks_stop_timer(struct qemu_alarm_timer *t);
327static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
328
329static int hpet_start_timer(struct qemu_alarm_timer *t);
330static void hpet_stop_timer(struct qemu_alarm_timer *t);
331
332static int rtc_start_timer(struct qemu_alarm_timer *t);
333static void rtc_stop_timer(struct qemu_alarm_timer *t);
334
335#endif /* __linux__ */
336
337#endif /* _WIN32 */
338
339/* Correlation between real and virtual time is always going to be
340 fairly approximate, so ignore small variation.
341 When the guest is idle real and virtual time will be aligned in
342 the IO wait loop. */
343#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
344
345static void icount_adjust(void)
346{
347 int64_t cur_time;
348 int64_t cur_icount;
349 int64_t delta;
350 static int64_t last_delta;
351 /* If the VM is not running, then do nothing. */
352 if (!vm_running)
353 return;
354
355 cur_time = cpu_get_clock();
356 cur_icount = qemu_get_clock(vm_clock);
357 delta = cur_icount - cur_time;
358 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
359 if (delta > 0
360 && last_delta + ICOUNT_WOBBLE < delta * 2
361 && icount_time_shift > 0) {
362 /* The guest is getting too far ahead. Slow time down. */
363 icount_time_shift--;
364 }
365 if (delta < 0
366 && last_delta - ICOUNT_WOBBLE > delta * 2
367 && icount_time_shift < MAX_ICOUNT_SHIFT) {
368 /* The guest is getting too far behind. Speed time up. */
369 icount_time_shift++;
370 }
371 last_delta = delta;
372 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
373}
374
375static void icount_adjust_rt(void * opaque)
376{
377 qemu_mod_timer(icount_rt_timer,
378 qemu_get_clock(rt_clock) + 1000);
379 icount_adjust();
380}
381
382static void icount_adjust_vm(void * opaque)
383{
384 qemu_mod_timer(icount_vm_timer,
385 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
386 icount_adjust();
387}
388
389int64_t qemu_icount_round(int64_t count)
390{
391 return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
392}
393
394static struct qemu_alarm_timer alarm_timers[] = {
395#ifndef _WIN32
396#ifdef __linux__
397 {"dynticks", dynticks_start_timer,
398 dynticks_stop_timer, dynticks_rearm_timer, NULL},
399 /* HPET - if available - is preferred */
400 {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
401 /* ...otherwise try RTC */
402 {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
403#endif
404 {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
405#else
406 {"dynticks", win32_start_timer,
407 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
408 {"win32", win32_start_timer,
409 win32_stop_timer, NULL, &alarm_win32_data},
410#endif
411 {NULL, }
412};
413
414static void show_available_alarms(void)
415{
416 int i;
417
418 printf("Available alarm timers, in order of precedence:\n");
419 for (i = 0; alarm_timers[i].name; i++)
420 printf("%s\n", alarm_timers[i].name);
421}
422
423void configure_alarms(char const *opt)
424{
425 int i;
426 int cur = 0;
427 int count = ARRAY_SIZE(alarm_timers) - 1;
428 char *arg;
429 char *name;
430 struct qemu_alarm_timer tmp;
431
432 if (!strcmp(opt, "?")) {
433 show_available_alarms();
434 exit(0);
435 }
436
437 arg = qemu_strdup(opt);
438
439 /* Reorder the array */
440 name = strtok(arg, ",");
441 while (name) {
442 for (i = 0; i < count && alarm_timers[i].name; i++) {
443 if (!strcmp(alarm_timers[i].name, name))
444 break;
445 }
446
447 if (i == count) {
448 fprintf(stderr, "Unknown clock %s\n", name);
449 goto next;
450 }
451
452 if (i < cur)
453 /* Ignore */
454 goto next;
455
456 /* Swap */
457 tmp = alarm_timers[i];
458 alarm_timers[i] = alarm_timers[cur];
459 alarm_timers[cur] = tmp;
460
461 cur++;
462next:
463 name = strtok(NULL, ",");
464 }
465
466 qemu_free(arg);
467
468 if (cur) {
469 /* Disable remaining timers */
470 for (i = cur; i < count; i++)
471 alarm_timers[i].name = NULL;
472 } else {
473 show_available_alarms();
474 exit(1);
475 }
476}
477
478#define QEMU_NUM_CLOCKS 3
479
480QEMUClock *rt_clock;
481QEMUClock *vm_clock;
482QEMUClock *host_clock;
483
484static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
485
486static QEMUClock *qemu_new_clock(int type)
487{
488 QEMUClock *clock;
489 clock = qemu_mallocz(sizeof(QEMUClock));
490 clock->type = type;
491 clock->enabled = 1;
492 return clock;
493}
494
495void qemu_clock_enable(QEMUClock *clock, int enabled)
496{
497 clock->enabled = enabled;
498}
499
500QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
501{
502 QEMUTimer *ts;
503
504 ts = qemu_mallocz(sizeof(QEMUTimer));
505 ts->clock = clock;
506 ts->cb = cb;
507 ts->opaque = opaque;
508 return ts;
509}
510
511void qemu_free_timer(QEMUTimer *ts)
512{
513 qemu_free(ts);
514}
515
516/* stop a timer, but do not dealloc it */
517void qemu_del_timer(QEMUTimer *ts)
518{
519 QEMUTimer **pt, *t;
520
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 (!t)
527 break;
528 if (t == ts) {
529 *pt = t->next;
530 break;
531 }
532 pt = &t->next;
533 }
534}
535
536/* modify the current timer so that it will be fired when current_time
537 >= expire_time. The corresponding callback will be called. */
538void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
539{
540 QEMUTimer **pt, *t;
541
542 qemu_del_timer(ts);
543
544 /* add the timer in the sorted list */
545 /* NOTE: this code must be signal safe because
546 qemu_timer_expired() can be called from a signal. */
547 pt = &active_timers[ts->clock->type];
548 for(;;) {
549 t = *pt;
550 if (!t)
551 break;
552 if (t->expire_time > expire_time)
553 break;
554 pt = &t->next;
555 }
556 ts->expire_time = expire_time;
557 ts->next = *pt;
558 *pt = ts;
559
560 /* Rearm if necessary */
561 if (pt == &active_timers[ts->clock->type]) {
562 if (!alarm_timer->pending) {
563 qemu_rearm_alarm_timer(alarm_timer);
564 }
565 /* Interrupt execution to force deadline recalculation. */
566 if (use_icount)
567 qemu_notify_event();
568 }
569}
570
571int qemu_timer_pending(QEMUTimer *ts)
572{
573 QEMUTimer *t;
574 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
575 if (t == ts)
576 return 1;
577 }
578 return 0;
579}
580
581int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
582{
583 if (!timer_head)
584 return 0;
585 return (timer_head->expire_time <= current_time);
586}
587
588static void qemu_run_timers(QEMUClock *clock)
589{
590 QEMUTimer **ptimer_head, *ts;
591 int64_t current_time;
592
593 if (!clock->enabled)
594 return;
595
596 current_time = qemu_get_clock (clock);
597 ptimer_head = &active_timers[clock->type];
598 for(;;) {
599 ts = *ptimer_head;
600 if (!ts || ts->expire_time > current_time)
601 break;
602 /* remove timer from the list before calling the callback */
603 *ptimer_head = ts->next;
604 ts->next = NULL;
605
606 /* run the callback (the timer list can be modified) */
607 ts->cb(ts->opaque);
608 }
609}
610
611int64_t qemu_get_clock(QEMUClock *clock)
612{
613 switch(clock->type) {
614 case QEMU_CLOCK_REALTIME:
615 return get_clock() / 1000000;
616 default:
617 case QEMU_CLOCK_VIRTUAL:
618 if (use_icount) {
619 return cpu_get_icount();
620 } else {
621 return cpu_get_clock();
622 }
623 case QEMU_CLOCK_HOST:
624 return get_clock_realtime();
625 }
626}
627
628int64_t qemu_get_clock_ns(QEMUClock *clock)
629{
630 switch(clock->type) {
631 case QEMU_CLOCK_REALTIME:
632 return get_clock();
633 default:
634 case QEMU_CLOCK_VIRTUAL:
635 if (use_icount) {
636 return cpu_get_icount();
637 } else {
638 return cpu_get_clock();
639 }
640 case QEMU_CLOCK_HOST:
641 return get_clock_realtime();
642 }
643}
644
645void init_clocks(void)
646{
647 init_get_clock();
648 rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
649 vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
650 host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
651
652 rtc_clock = host_clock;
653}
654
655/* save a timer */
656void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
657{
658 uint64_t expire_time;
659
660 if (qemu_timer_pending(ts)) {
661 expire_time = ts->expire_time;
662 } else {
663 expire_time = -1;
664 }
665 qemu_put_be64(f, expire_time);
666}
667
668void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
669{
670 uint64_t expire_time;
671
672 expire_time = qemu_get_be64(f);
673 if (expire_time != -1) {
674 qemu_mod_timer(ts, expire_time);
675 } else {
676 qemu_del_timer(ts);
677 }
678}
679
680#if 0
681static const VMStateDescription vmstate_timers = {
682 .name = "timer",
683 .version_id = 2,
684 .minimum_version_id = 1,
685 .minimum_version_id_old = 1,
686 .fields = (VMStateField []) {
687 VMSTATE_INT64(cpu_ticks_offset, TimersState),
688 VMSTATE_INT64(dummy, TimersState),
689 VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
690 VMSTATE_END_OF_LIST()
691 }
692};
693#endif
694
695void configure_icount(const char *option)
696{
697 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
698
699 if (!option)
700 return;
701
702 if (strcmp(option, "auto") != 0) {
703 icount_time_shift = strtol(option, NULL, 0);
704 use_icount = 1;
705 return;
706 }
707
708 use_icount = 2;
709
710 /* 125MIPS seems a reasonable initial guess at the guest speed.
711 It will be corrected fairly quickly anyway. */
712 icount_time_shift = 3;
713
714 /* Have both realtime and virtual time triggers for speed adjustment.
715 The realtime trigger catches emulated time passing too slowly,
716 the virtual time trigger catches emulated time passing too fast.
717 Realtime triggers occur even when idle, so use them less frequently
718 than VM triggers. */
719 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
720 qemu_mod_timer(icount_rt_timer,
721 qemu_get_clock(rt_clock) + 1000);
722 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
723 qemu_mod_timer(icount_vm_timer,
724 qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
725}
726
727void qemu_run_all_timers(void)
728{
729 alarm_timer->pending = 0;
730
731 /* rearm timer, if not periodic */
732 if (alarm_timer->expired) {
733 alarm_timer->expired = 0;
734 qemu_rearm_alarm_timer(alarm_timer);
735 }
736
737 /* vm time timers */
738 if (vm_running) {
739 qemu_run_timers(vm_clock);
740 }
741
742 qemu_run_timers(rt_clock);
743 qemu_run_timers(host_clock);
744}
745
746#ifdef _WIN32
747static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
748 DWORD_PTR dwUser, DWORD_PTR dw1,
749 DWORD_PTR dw2)
750#else
751static void host_alarm_handler(int host_signum)
752#endif
753{
754 struct qemu_alarm_timer *t = alarm_timer;
755 if (!t)
756 return;
757
758#if 0
759#define DISP_FREQ 1000
760 {
761 static int64_t delta_min = INT64_MAX;
762 static int64_t delta_max, delta_cum, last_clock, delta, ti;
763 static int count;
764 ti = qemu_get_clock(vm_clock);
765 if (last_clock != 0) {
766 delta = ti - last_clock;
767 if (delta < delta_min)
768 delta_min = delta;
769 if (delta > delta_max)
770 delta_max = delta;
771 delta_cum += delta;
772 if (++count == DISP_FREQ) {
773 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
774 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
775 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
776 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
777 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
778 count = 0;
779 delta_min = INT64_MAX;
780 delta_max = 0;
781 delta_cum = 0;
782 }
783 }
784 last_clock = ti;
785 }
786#endif
787 if (alarm_has_dynticks(t) ||
788 (!use_icount &&
789 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
790 qemu_get_clock(vm_clock))) ||
791 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
792 qemu_get_clock(rt_clock)) ||
793 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
794 qemu_get_clock(host_clock))) {
795
796 t->expired = alarm_has_dynticks(t);
797 t->pending = 1;
798 qemu_notify_event();
799 }
800}
801
802int64_t qemu_next_deadline(void)
803{
804 /* To avoid problems with overflow limit this to 2^32. */
805 int64_t delta = INT32_MAX;
806
807 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
808 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
809 qemu_get_clock(vm_clock);
810 }
811 if (active_timers[QEMU_CLOCK_HOST]) {
812 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
813 qemu_get_clock(host_clock);
814 if (hdelta < delta)
815 delta = hdelta;
816 }
817
818 if (delta < 0)
819 delta = 0;
820
821 return delta;
822}
823
824#ifndef _WIN32
825
826#if defined(__linux__)
827
828#define RTC_FREQ 1024
829
830static uint64_t qemu_next_deadline_dyntick(void)
831{
832 int64_t delta;
833 int64_t rtdelta;
834
835 if (use_icount)
836 delta = INT32_MAX;
837 else
838 delta = (qemu_next_deadline() + 999) / 1000;
839
840 if (active_timers[QEMU_CLOCK_REALTIME]) {
841 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
842 qemu_get_clock(rt_clock))*1000;
843 if (rtdelta < delta)
844 delta = rtdelta;
845 }
846
847 if (delta < MIN_TIMER_REARM_US)
848 delta = MIN_TIMER_REARM_US;
849
850 return delta;
851}
852
853static void enable_sigio_timer(int fd)
854{
855 struct sigaction act;
856
857 /* timer signal */
858 sigfillset(&act.sa_mask);
859 act.sa_flags = 0;
860 act.sa_handler = host_alarm_handler;
861
862 sigaction(SIGIO, &act, NULL);
863 fcntl_setfl(fd, O_ASYNC);
864 fcntl(fd, F_SETOWN, getpid());
865}
866
867static int hpet_start_timer(struct qemu_alarm_timer *t)
868{
869 struct hpet_info info;
870 int r, fd;
871
872 fd = open("/dev/hpet", O_RDONLY);
873 if (fd < 0)
874 return -1;
875
876 /* Set frequency */
877 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
878 if (r < 0) {
879 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
880 "error, but for better emulation accuracy type:\n"
881 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
882 goto fail;
883 }
884
885 /* Check capabilities */
886 r = ioctl(fd, HPET_INFO, &info);
887 if (r < 0)
888 goto fail;
889
890 /* Enable periodic mode */
891 r = ioctl(fd, HPET_EPI, 0);
892 if (info.hi_flags && (r < 0))
893 goto fail;
894
895 /* Enable interrupt */
896 r = ioctl(fd, HPET_IE_ON, 0);
897 if (r < 0)
898 goto fail;
899
900 enable_sigio_timer(fd);
901 t->priv = (void *)(long)fd;
902
903 return 0;
904fail:
905 close(fd);
906 return -1;
907}
908
909static void hpet_stop_timer(struct qemu_alarm_timer *t)
910{
911 int fd = (long)t->priv;
912
913 close(fd);
914}
915
916static int rtc_start_timer(struct qemu_alarm_timer *t)
917{
918 int rtc_fd;
919 unsigned long current_rtc_freq = 0;
920
921 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
922 if (rtc_fd < 0)
923 return -1;
924 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
925 if (current_rtc_freq != RTC_FREQ &&
926 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
927 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
928 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
929 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
930 goto fail;
931 }
932 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
933 fail:
934 close(rtc_fd);
935 return -1;
936 }
937
938 enable_sigio_timer(rtc_fd);
939
940 t->priv = (void *)(long)rtc_fd;
941
942 return 0;
943}
944
945static void rtc_stop_timer(struct qemu_alarm_timer *t)
946{
947 int rtc_fd = (long)t->priv;
948
949 close(rtc_fd);
950}
951
952static int dynticks_start_timer(struct qemu_alarm_timer *t)
953{
954 struct sigevent ev;
955 timer_t host_timer;
956 struct sigaction act;
957
958 sigfillset(&act.sa_mask);
959 act.sa_flags = 0;
960 act.sa_handler = host_alarm_handler;
961
962 sigaction(SIGALRM, &act, NULL);
963
964 /*
965 * Initialize ev struct to 0 to avoid valgrind complaining
966 * about uninitialized data in timer_create call
967 */
968 memset(&ev, 0, sizeof(ev));
969 ev.sigev_value.sival_int = 0;
970 ev.sigev_notify = SIGEV_SIGNAL;
971 ev.sigev_signo = SIGALRM;
972
973 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
974 perror("timer_create");
975
976 /* disable dynticks */
977 fprintf(stderr, "Dynamic Ticks disabled\n");
978
979 return -1;
980 }
981
982 t->priv = (void *)(long)host_timer;
983
984 return 0;
985}
986
987static void dynticks_stop_timer(struct qemu_alarm_timer *t)
988{
989 timer_t host_timer = (timer_t)(long)t->priv;
990
991 timer_delete(host_timer);
992}
993
994static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
995{
996 timer_t host_timer = (timer_t)(long)t->priv;
997 struct itimerspec timeout;
998 int64_t nearest_delta_us = INT64_MAX;
999 int64_t current_us;
1000
1001 assert(alarm_has_dynticks(t));
1002 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1003 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1004 !active_timers[QEMU_CLOCK_HOST])
1005 return;
1006
1007 nearest_delta_us = qemu_next_deadline_dyntick();
1008
1009 /* check whether a timer is already running */
1010 if (timer_gettime(host_timer, &timeout)) {
1011 perror("gettime");
1012 fprintf(stderr, "Internal timer error: aborting\n");
1013 exit(1);
1014 }
1015 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1016 if (current_us && current_us <= nearest_delta_us)
1017 return;
1018
1019 timeout.it_interval.tv_sec = 0;
1020 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1021 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1022 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1023 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1024 perror("settime");
1025 fprintf(stderr, "Internal timer error: aborting\n");
1026 exit(1);
1027 }
1028}
1029
1030#endif /* defined(__linux__) */
1031
1032static int unix_start_timer(struct qemu_alarm_timer *t)
1033{
1034 struct sigaction act;
1035 struct itimerval itv;
1036 int err;
1037
1038 /* timer signal */
1039 sigfillset(&act.sa_mask);
1040 act.sa_flags = 0;
1041 act.sa_handler = host_alarm_handler;
1042
1043 sigaction(SIGALRM, &act, NULL);
1044
1045 itv.it_interval.tv_sec = 0;
1046 /* for i386 kernel 2.6 to get 1 ms */
1047 itv.it_interval.tv_usec = 999;
1048 itv.it_value.tv_sec = 0;
1049 itv.it_value.tv_usec = 10 * 1000;
1050
1051 err = setitimer(ITIMER_REAL, &itv, NULL);
1052 if (err)
1053 return -1;
1054
1055 return 0;
1056}
1057
1058static void unix_stop_timer(struct qemu_alarm_timer *t)
1059{
1060 struct itimerval itv;
1061
1062 memset(&itv, 0, sizeof(itv));
1063 setitimer(ITIMER_REAL, &itv, NULL);
1064}
1065
1066#endif /* !defined(_WIN32) */
1067
1068
1069#ifdef _WIN32
1070
1071static int win32_start_timer(struct qemu_alarm_timer *t)
1072{
1073 TIMECAPS tc;
1074 struct qemu_alarm_win32 *data = t->priv;
1075 UINT flags;
1076
1077 memset(&tc, 0, sizeof(tc));
1078 timeGetDevCaps(&tc, sizeof(tc));
1079
1080 data->period = tc.wPeriodMin;
1081 timeBeginPeriod(data->period);
1082
1083 flags = TIME_CALLBACK_FUNCTION;
1084 if (alarm_has_dynticks(t))
1085 flags |= TIME_ONESHOT;
1086 else
1087 flags |= TIME_PERIODIC;
1088
1089 data->timerId = timeSetEvent(1, // interval (ms)
1090 data->period, // resolution
1091 host_alarm_handler, // function
1092 (DWORD)t, // parameter
1093 flags);
1094
1095 if (!data->timerId) {
1096 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1097 GetLastError());
1098 timeEndPeriod(data->period);
1099 return -1;
1100 }
1101
1102 return 0;
1103}
1104
1105static void win32_stop_timer(struct qemu_alarm_timer *t)
1106{
1107 struct qemu_alarm_win32 *data = t->priv;
1108
1109 timeKillEvent(data->timerId);
1110 timeEndPeriod(data->period);
1111}
1112
1113static void win32_rearm_timer(struct qemu_alarm_timer *t)
1114{
1115 struct qemu_alarm_win32 *data = t->priv;
1116
1117 assert(alarm_has_dynticks(t));
1118 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1119 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1120 !active_timers[QEMU_CLOCK_HOST])
1121 return;
1122
1123 timeKillEvent(data->timerId);
1124
1125 data->timerId = timeSetEvent(1,
1126 data->period,
1127 host_alarm_handler,
1128 (DWORD)t,
1129 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1130
1131 if (!data->timerId) {
1132 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1133 GetLastError());
1134
1135 timeEndPeriod(data->period);
1136 exit(1);
1137 }
1138}
1139
1140#endif /* _WIN32 */
1141
1142static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1143{
1144 if (running)
1145 qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1146}
1147
1148int init_timer_alarm(void)
1149{
1150 struct qemu_alarm_timer *t = NULL;
1151 int i, err = -1;
1152
1153 for (i = 0; alarm_timers[i].name; i++) {
1154 t = &alarm_timers[i];
1155
1156 err = t->start(t);
1157 if (!err)
1158 break;
1159 }
1160
1161 if (err) {
1162 err = -ENOENT;
1163 goto fail;
1164 }
1165
1166 /* first event is at time 0 */
1167 t->pending = 1;
1168 alarm_timer = t;
1169 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1170
1171 return 0;
1172
1173fail:
1174 return err;
1175}
1176
1177void quit_timers(void)
1178{
1179 struct qemu_alarm_timer *t = alarm_timer;
1180 alarm_timer = NULL;
1181 t->stop(t);
1182}
1183
1184int qemu_calculate_timeout(void)
1185{
1186#ifndef CONFIG_IOTHREAD
1187 int timeout;
1188
1189 if (!vm_running)
1190 timeout = 5000;
1191 else {
1192 /* XXX: use timeout computed from timers */
1193 int64_t add;
1194 int64_t delta;
1195 /* Advance virtual time to the next event. */
1196 delta = qemu_icount_delta();
1197 if (delta > 0) {
1198 /* If virtual time is ahead of real time then just
1199 wait for IO. */
1200 timeout = (delta + 999999) / 1000000;
1201 } else {
1202 /* Wait for either IO to occur or the next
1203 timer event. */
1204 add = qemu_next_deadline();
1205 /* We advance the timer before checking for IO.
1206 Limit the amount we advance so that early IO
1207 activity won't get the guest too far ahead. */
1208 if (add > 10000000)
1209 add = 10000000;
1210 delta += add;
1211 qemu_icount += qemu_icount_round (add);
1212 timeout = delta / 1000000;
1213 if (timeout < 0)
1214 timeout = 0;
1215 }
1216 }
1217
1218 return timeout;
1219#else /* CONFIG_IOTHREAD */
1220 return 1000;
1221#endif
1222}
1223
1224/* Return the virtual CPU time, based on the instruction counter. */
1225int64_t cpu_get_icount(void)
1226{
1227 int64_t icount;
1228 CPUState *env = cpu_single_env;;
1229
1230 icount = qemu_icount;
1231 if (env) {
1232 if (!can_do_io(env)) {
1233 fprintf(stderr, "Bad clock read\n");
1234 }
1235 icount -= (env->icount_decr.u16.low + env->icount_extra);
1236 }
1237 return qemu_icount_bias + (icount << icount_time_shift);
1238}