blob: 0ed5ba90bf3713824820196c919dbe5f7f8d972f [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;
David 'Digit' Turner6b512812010-10-15 15:05:04 +0200592
David Turner6a9ef172010-09-09 22:54:36 +0200593 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{
Ot ten Thije1091d5d2010-09-15 13:52:29 +0100697 register_savevm("timer", 0, 2, timer_save, timer_load, &timers_state);
David Turner6a9ef172010-09-09 22:54:36 +0200698
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
David 'Digit' Turner6b512812010-10-15 15:05:04 +0200746static int timer_alarm_pending = 1;
747
748int qemu_timer_alarm_pending(void)
749{
750 int ret = timer_alarm_pending;
751 timer_alarm_pending = 0;
752 return ret;
753}
754
David Turner6a9ef172010-09-09 22:54:36 +0200755#ifdef _WIN32
756static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
757 DWORD_PTR dwUser, DWORD_PTR dw1,
758 DWORD_PTR dw2)
759#else
760static void host_alarm_handler(int host_signum)
761#endif
762{
763 struct qemu_alarm_timer *t = alarm_timer;
764 if (!t)
765 return;
766
767#if 0
768#define DISP_FREQ 1000
769 {
770 static int64_t delta_min = INT64_MAX;
771 static int64_t delta_max, delta_cum, last_clock, delta, ti;
772 static int count;
773 ti = qemu_get_clock(vm_clock);
774 if (last_clock != 0) {
775 delta = ti - last_clock;
776 if (delta < delta_min)
777 delta_min = delta;
778 if (delta > delta_max)
779 delta_max = delta;
780 delta_cum += delta;
781 if (++count == DISP_FREQ) {
782 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
783 muldiv64(delta_min, 1000000, get_ticks_per_sec()),
784 muldiv64(delta_max, 1000000, get_ticks_per_sec()),
785 muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
786 (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
787 count = 0;
788 delta_min = INT64_MAX;
789 delta_max = 0;
790 delta_cum = 0;
791 }
792 }
793 last_clock = ti;
794 }
795#endif
796 if (alarm_has_dynticks(t) ||
797 (!use_icount &&
798 qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
799 qemu_get_clock(vm_clock))) ||
800 qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
801 qemu_get_clock(rt_clock)) ||
802 qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
803 qemu_get_clock(host_clock))) {
804
805 t->expired = alarm_has_dynticks(t);
806 t->pending = 1;
David 'Digit' Turner6b512812010-10-15 15:05:04 +0200807 timer_alarm_pending = 1;
David Turner6a9ef172010-09-09 22:54:36 +0200808 qemu_notify_event();
809 }
810}
811
812int64_t qemu_next_deadline(void)
813{
814 /* To avoid problems with overflow limit this to 2^32. */
815 int64_t delta = INT32_MAX;
816
817 if (active_timers[QEMU_CLOCK_VIRTUAL]) {
818 delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
819 qemu_get_clock(vm_clock);
820 }
821 if (active_timers[QEMU_CLOCK_HOST]) {
822 int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
823 qemu_get_clock(host_clock);
824 if (hdelta < delta)
825 delta = hdelta;
826 }
827
828 if (delta < 0)
829 delta = 0;
830
831 return delta;
832}
833
834#ifndef _WIN32
835
836#if defined(__linux__)
837
838#define RTC_FREQ 1024
839
840static uint64_t qemu_next_deadline_dyntick(void)
841{
842 int64_t delta;
843 int64_t rtdelta;
844
845 if (use_icount)
846 delta = INT32_MAX;
847 else
848 delta = (qemu_next_deadline() + 999) / 1000;
849
850 if (active_timers[QEMU_CLOCK_REALTIME]) {
851 rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
852 qemu_get_clock(rt_clock))*1000;
853 if (rtdelta < delta)
854 delta = rtdelta;
855 }
856
857 if (delta < MIN_TIMER_REARM_US)
858 delta = MIN_TIMER_REARM_US;
859
860 return delta;
861}
862
863static void enable_sigio_timer(int fd)
864{
865 struct sigaction act;
866
867 /* timer signal */
868 sigfillset(&act.sa_mask);
869 act.sa_flags = 0;
870 act.sa_handler = host_alarm_handler;
871
872 sigaction(SIGIO, &act, NULL);
873 fcntl_setfl(fd, O_ASYNC);
874 fcntl(fd, F_SETOWN, getpid());
875}
876
877static int hpet_start_timer(struct qemu_alarm_timer *t)
878{
879 struct hpet_info info;
880 int r, fd;
881
882 fd = open("/dev/hpet", O_RDONLY);
883 if (fd < 0)
884 return -1;
885
886 /* Set frequency */
887 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
888 if (r < 0) {
889 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
890 "error, but for better emulation accuracy type:\n"
891 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
892 goto fail;
893 }
894
895 /* Check capabilities */
896 r = ioctl(fd, HPET_INFO, &info);
897 if (r < 0)
898 goto fail;
899
900 /* Enable periodic mode */
901 r = ioctl(fd, HPET_EPI, 0);
902 if (info.hi_flags && (r < 0))
903 goto fail;
904
905 /* Enable interrupt */
906 r = ioctl(fd, HPET_IE_ON, 0);
907 if (r < 0)
908 goto fail;
909
910 enable_sigio_timer(fd);
911 t->priv = (void *)(long)fd;
912
913 return 0;
914fail:
915 close(fd);
916 return -1;
917}
918
919static void hpet_stop_timer(struct qemu_alarm_timer *t)
920{
921 int fd = (long)t->priv;
922
923 close(fd);
924}
925
926static int rtc_start_timer(struct qemu_alarm_timer *t)
927{
928 int rtc_fd;
929 unsigned long current_rtc_freq = 0;
930
931 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
932 if (rtc_fd < 0)
933 return -1;
934 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
935 if (current_rtc_freq != RTC_FREQ &&
936 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
937 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
938 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
939 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
940 goto fail;
941 }
942 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
943 fail:
944 close(rtc_fd);
945 return -1;
946 }
947
948 enable_sigio_timer(rtc_fd);
949
950 t->priv = (void *)(long)rtc_fd;
951
952 return 0;
953}
954
955static void rtc_stop_timer(struct qemu_alarm_timer *t)
956{
957 int rtc_fd = (long)t->priv;
958
959 close(rtc_fd);
960}
961
962static int dynticks_start_timer(struct qemu_alarm_timer *t)
963{
964 struct sigevent ev;
965 timer_t host_timer;
966 struct sigaction act;
967
968 sigfillset(&act.sa_mask);
969 act.sa_flags = 0;
970 act.sa_handler = host_alarm_handler;
971
972 sigaction(SIGALRM, &act, NULL);
973
David 'Digit' Turner6b512812010-10-15 15:05:04 +0200974 /*
David Turner6a9ef172010-09-09 22:54:36 +0200975 * Initialize ev struct to 0 to avoid valgrind complaining
976 * about uninitialized data in timer_create call
977 */
978 memset(&ev, 0, sizeof(ev));
979 ev.sigev_value.sival_int = 0;
980 ev.sigev_notify = SIGEV_SIGNAL;
981 ev.sigev_signo = SIGALRM;
982
983 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
984 perror("timer_create");
985
986 /* disable dynticks */
987 fprintf(stderr, "Dynamic Ticks disabled\n");
988
989 return -1;
990 }
991
992 t->priv = (void *)(long)host_timer;
993
994 return 0;
995}
996
997static void dynticks_stop_timer(struct qemu_alarm_timer *t)
998{
999 timer_t host_timer = (timer_t)(long)t->priv;
1000
1001 timer_delete(host_timer);
1002}
1003
1004static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1005{
1006 timer_t host_timer = (timer_t)(long)t->priv;
1007 struct itimerspec timeout;
1008 int64_t nearest_delta_us = INT64_MAX;
1009 int64_t current_us;
1010
1011 assert(alarm_has_dynticks(t));
1012 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1013 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1014 !active_timers[QEMU_CLOCK_HOST])
1015 return;
1016
1017 nearest_delta_us = qemu_next_deadline_dyntick();
1018
1019 /* check whether a timer is already running */
1020 if (timer_gettime(host_timer, &timeout)) {
1021 perror("gettime");
1022 fprintf(stderr, "Internal timer error: aborting\n");
1023 exit(1);
1024 }
1025 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1026 if (current_us && current_us <= nearest_delta_us)
1027 return;
1028
1029 timeout.it_interval.tv_sec = 0;
1030 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1031 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1032 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1033 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1034 perror("settime");
1035 fprintf(stderr, "Internal timer error: aborting\n");
1036 exit(1);
1037 }
1038}
1039
1040#endif /* defined(__linux__) */
1041
1042static int unix_start_timer(struct qemu_alarm_timer *t)
1043{
1044 struct sigaction act;
1045 struct itimerval itv;
1046 int err;
1047
1048 /* timer signal */
1049 sigfillset(&act.sa_mask);
1050 act.sa_flags = 0;
1051 act.sa_handler = host_alarm_handler;
1052
1053 sigaction(SIGALRM, &act, NULL);
1054
1055 itv.it_interval.tv_sec = 0;
1056 /* for i386 kernel 2.6 to get 1 ms */
1057 itv.it_interval.tv_usec = 999;
1058 itv.it_value.tv_sec = 0;
1059 itv.it_value.tv_usec = 10 * 1000;
1060
1061 err = setitimer(ITIMER_REAL, &itv, NULL);
1062 if (err)
1063 return -1;
1064
1065 return 0;
1066}
1067
1068static void unix_stop_timer(struct qemu_alarm_timer *t)
1069{
1070 struct itimerval itv;
1071
1072 memset(&itv, 0, sizeof(itv));
1073 setitimer(ITIMER_REAL, &itv, NULL);
1074}
1075
1076#endif /* !defined(_WIN32) */
1077
1078
1079#ifdef _WIN32
1080
1081static int win32_start_timer(struct qemu_alarm_timer *t)
1082{
1083 TIMECAPS tc;
1084 struct qemu_alarm_win32 *data = t->priv;
1085 UINT flags;
1086
1087 memset(&tc, 0, sizeof(tc));
1088 timeGetDevCaps(&tc, sizeof(tc));
1089
1090 data->period = tc.wPeriodMin;
1091 timeBeginPeriod(data->period);
1092
1093 flags = TIME_CALLBACK_FUNCTION;
1094 if (alarm_has_dynticks(t))
1095 flags |= TIME_ONESHOT;
1096 else
1097 flags |= TIME_PERIODIC;
1098
1099 data->timerId = timeSetEvent(1, // interval (ms)
1100 data->period, // resolution
1101 host_alarm_handler, // function
1102 (DWORD)t, // parameter
1103 flags);
1104
1105 if (!data->timerId) {
1106 fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1107 GetLastError());
1108 timeEndPeriod(data->period);
1109 return -1;
1110 }
1111
1112 return 0;
1113}
1114
1115static void win32_stop_timer(struct qemu_alarm_timer *t)
1116{
1117 struct qemu_alarm_win32 *data = t->priv;
1118
1119 timeKillEvent(data->timerId);
1120 timeEndPeriod(data->period);
1121}
1122
1123static void win32_rearm_timer(struct qemu_alarm_timer *t)
1124{
1125 struct qemu_alarm_win32 *data = t->priv;
1126
1127 assert(alarm_has_dynticks(t));
1128 if (!active_timers[QEMU_CLOCK_REALTIME] &&
1129 !active_timers[QEMU_CLOCK_VIRTUAL] &&
1130 !active_timers[QEMU_CLOCK_HOST])
1131 return;
1132
1133 timeKillEvent(data->timerId);
1134
1135 data->timerId = timeSetEvent(1,
1136 data->period,
1137 host_alarm_handler,
1138 (DWORD)t,
1139 TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1140
1141 if (!data->timerId) {
1142 fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1143 GetLastError());
1144
1145 timeEndPeriod(data->period);
1146 exit(1);
1147 }
1148}
1149
1150#endif /* _WIN32 */
1151
1152static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1153{
1154 if (running)
1155 qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1156}
1157
1158int init_timer_alarm(void)
1159{
1160 struct qemu_alarm_timer *t = NULL;
1161 int i, err = -1;
1162
1163 for (i = 0; alarm_timers[i].name; i++) {
1164 t = &alarm_timers[i];
1165
1166 err = t->start(t);
1167 if (!err)
1168 break;
1169 }
1170
1171 if (err) {
1172 err = -ENOENT;
1173 goto fail;
1174 }
1175
1176 /* first event is at time 0 */
1177 t->pending = 1;
1178 alarm_timer = t;
1179 qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1180
1181 return 0;
1182
1183fail:
1184 return err;
1185}
1186
1187void quit_timers(void)
1188{
1189 struct qemu_alarm_timer *t = alarm_timer;
1190 alarm_timer = NULL;
1191 t->stop(t);
1192}
1193
David 'Digit' Turner6b512812010-10-15 15:05:04 +02001194extern int tcg_has_work(void);
1195
David Turner6a9ef172010-09-09 22:54:36 +02001196int qemu_calculate_timeout(void)
1197{
1198#ifndef CONFIG_IOTHREAD
1199 int timeout;
1200
1201 if (!vm_running)
1202 timeout = 5000;
David 'Digit' Turner6b512812010-10-15 15:05:04 +02001203 else if (tcg_has_work())
1204 timeout = 0;
1205 else if (!use_icount) {
1206#ifdef WIN32
1207 /* This corresponds to the case where the emulated system is
1208 * totally idle and waiting for i/o. The problem is that on
1209 * Windows, the default value will prevent Windows user events
1210 * to be delivered in less than 5 seconds.
1211 *
1212 * Upstream contains a different way to handle this, for now
1213 * this hack should be sufficient until we integrate it into
1214 * our tree.
1215 */
1216 timeout = 1000/15; /* deliver user events every 15/th of second */
1217#else
1218 timeout = 5000;
1219#endif
1220 } else {
David Turner6a9ef172010-09-09 22:54:36 +02001221 /* XXX: use timeout computed from timers */
1222 int64_t add;
1223 int64_t delta;
1224 /* Advance virtual time to the next event. */
1225 delta = qemu_icount_delta();
1226 if (delta > 0) {
1227 /* If virtual time is ahead of real time then just
1228 wait for IO. */
1229 timeout = (delta + 999999) / 1000000;
1230 } else {
1231 /* Wait for either IO to occur or the next
1232 timer event. */
1233 add = qemu_next_deadline();
1234 /* We advance the timer before checking for IO.
1235 Limit the amount we advance so that early IO
1236 activity won't get the guest too far ahead. */
1237 if (add > 10000000)
1238 add = 10000000;
1239 delta += add;
1240 qemu_icount += qemu_icount_round (add);
1241 timeout = delta / 1000000;
1242 if (timeout < 0)
1243 timeout = 0;
1244 }
1245 }
1246
1247 return timeout;
1248#else /* CONFIG_IOTHREAD */
1249 return 1000;
1250#endif
1251}
1252
1253/* Return the virtual CPU time, based on the instruction counter. */
1254int64_t cpu_get_icount(void)
1255{
1256 int64_t icount;
1257 CPUState *env = cpu_single_env;;
1258
1259 icount = qemu_icount;
1260 if (env) {
1261 if (!can_do_io(env)) {
1262 fprintf(stderr, "Bad clock read\n");
1263 }
1264 icount -= (env->icount_decr.u16.low + env->icount_extra);
1265 }
1266 return qemu_icount_bias + (icount << icount_time_shift);
1267}