xref: /illumos-kvm-cmd/qemu-timer.c (revision 95921e41)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  * Portions Copyright 2011 Joyent, Inc.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #include "sysemu.h"
27 #include "net.h"
28 #include "monitor.h"
29 #include "console.h"
30 #include "trace.h"
31 
32 #include "hw/hw.h"
33 
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <time.h>
37 #include <errno.h>
38 #include <sys/time.h>
39 #include <signal.h>
40 #ifdef __FreeBSD__
41 #include <sys/param.h>
42 #endif
43 
44 #ifdef __linux__
45 #include <sys/ioctl.h>
46 #include <linux/rtc.h>
47 /* For the benefit of older linux systems which don't supply it,
48    we use a local copy of hpet.h. */
49 /* #include <linux/hpet.h> */
50 #include "hpet.h"
51 #endif
52 
53 #ifdef _WIN32
54 #include <windows.h>
55 #include <mmsystem.h>
56 #endif
57 
58 #include "qemu-timer.h"
59 
60 /* Conversion factor from emulated instructions to virtual clock ticks.  */
61 int icount_time_shift;
62 /* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
63 #define MAX_ICOUNT_SHIFT 10
64 /* Compensate for varying guest execution speed.  */
65 int64_t qemu_icount_bias;
66 static QEMUTimer *icount_rt_timer;
67 static QEMUTimer *icount_vm_timer;
68 
69 /***********************************************************/
70 /* guest cycle counter */
71 
72 typedef struct TimersState {
73     int64_t cpu_ticks_prev;
74     int64_t cpu_ticks_offset;
75     int64_t cpu_clock_offset;
76     int32_t cpu_ticks_enabled;
77     int64_t dummy;
78 } TimersState;
79 
80 TimersState timers_state;
81 
82 /* return the host CPU cycle counter and handle stop/restart */
cpu_get_ticks(void)83 int64_t cpu_get_ticks(void)
84 {
85     if (use_icount) {
86         return cpu_get_icount();
87     }
88     if (!timers_state.cpu_ticks_enabled) {
89         return timers_state.cpu_ticks_offset;
90     } else {
91         int64_t ticks;
92         ticks = cpu_get_real_ticks();
93         if (timers_state.cpu_ticks_prev > ticks) {
94             /* Note: non increasing ticks may happen if the host uses
95                software suspend */
96             timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
97         }
98         timers_state.cpu_ticks_prev = ticks;
99         return ticks + timers_state.cpu_ticks_offset;
100     }
101 }
102 
103 /* return the host CPU monotonic timer and handle stop/restart */
cpu_get_clock(void)104 static int64_t cpu_get_clock(void)
105 {
106     int64_t ti;
107     if (!timers_state.cpu_ticks_enabled) {
108         return timers_state.cpu_clock_offset;
109     } else {
110         ti = get_clock();
111         return ti + timers_state.cpu_clock_offset;
112     }
113 }
114 
qemu_icount_delta(void)115 static int64_t qemu_icount_delta(void)
116 {
117     if (!use_icount) {
118         return 5000 * (int64_t) 1000000;
119     } else if (use_icount == 1) {
120         /* When not using an adaptive execution frequency
121            we tend to get badly out of sync with real time,
122            so just delay for a reasonable amount of time.  */
123         return 0;
124     } else {
125         return cpu_get_icount() - cpu_get_clock();
126     }
127 }
128 
129 /* enable cpu_get_ticks() */
cpu_enable_ticks(void)130 void cpu_enable_ticks(void)
131 {
132     if (!timers_state.cpu_ticks_enabled) {
133         timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
134         timers_state.cpu_clock_offset -= get_clock();
135         timers_state.cpu_ticks_enabled = 1;
136     }
137 }
138 
139 /* disable cpu_get_ticks() : the clock is stopped. You must not call
140    cpu_get_ticks() after that.  */
cpu_disable_ticks(void)141 void cpu_disable_ticks(void)
142 {
143     if (timers_state.cpu_ticks_enabled) {
144         timers_state.cpu_ticks_offset = cpu_get_ticks();
145         timers_state.cpu_clock_offset = cpu_get_clock();
146         timers_state.cpu_ticks_enabled = 0;
147     }
148 }
149 
150 /***********************************************************/
151 /* timers */
152 
153 #define QEMU_CLOCK_REALTIME 0
154 #define QEMU_CLOCK_VIRTUAL  1
155 #define QEMU_CLOCK_HOST     2
156 
157 struct QEMUClock {
158     int type;
159     int enabled;
160     /* XXX: add frequency */
161 };
162 
163 struct QEMUTimer {
164     QEMUClock *clock;
165     int64_t expire_time;
166     int64_t interval;
167     QEMUTimerCB *cb;
168     void *opaque;
169     void *source;
170     struct QEMUTimer *next;
171 };
172 
173 struct qemu_alarm_timer {
174     char const *name;
175     int (*start)(struct qemu_alarm_timer *t);
176     void (*stop)(struct qemu_alarm_timer *t);
177     void (*rearm)(struct qemu_alarm_timer *t);
178     void *priv;
179 
180     char expired;
181     char pending;
182 };
183 
184 static struct qemu_alarm_timer *alarm_timer;
185 
qemu_alarm_pending(void)186 int qemu_alarm_pending(void)
187 {
188     return alarm_timer->pending;
189 }
190 
alarm_has_dynticks(struct qemu_alarm_timer * t)191 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
192 {
193     return !!t->rearm;
194 }
195 
qemu_rearm_alarm_timer(struct qemu_alarm_timer * t)196 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
197 {
198     if (!alarm_has_dynticks(t))
199         return;
200 
201     t->rearm(t);
202 }
203 
204 /* TODO: MIN_TIMER_REARM_NS should be optimized */
205 #define MIN_TIMER_REARM_NS 250000
206 
207 #ifdef _WIN32
208 
209 struct qemu_alarm_win32 {
210     MMRESULT timerId;
211     unsigned int period;
212 } alarm_win32_data = {0, 0};
213 
214 static int win32_start_timer(struct qemu_alarm_timer *t);
215 static void win32_stop_timer(struct qemu_alarm_timer *t);
216 static void win32_rearm_timer(struct qemu_alarm_timer *t);
217 
218 #else
219 
220 static int unix_start_timer(struct qemu_alarm_timer *t);
221 static void unix_stop_timer(struct qemu_alarm_timer *t);
222 
223 #if defined(__sun__)
224 
225 static int multiticks_start_timer(struct qemu_alarm_timer *t);
226 static void multiticks_stop_timer(struct qemu_alarm_timer *t);
227 static void multiticks_rearm_timer(struct qemu_alarm_timer *t);
228 
229 #endif
230 
231 #if defined(__linux__) || defined(__sun__)
232 
233 static int dynticks_start_timer(struct qemu_alarm_timer *t);
234 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
235 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
236 
237 #endif
238 
239 #ifdef __linux__
240 
241 static int hpet_start_timer(struct qemu_alarm_timer *t);
242 static void hpet_stop_timer(struct qemu_alarm_timer *t);
243 
244 static int rtc_start_timer(struct qemu_alarm_timer *t);
245 static void rtc_stop_timer(struct qemu_alarm_timer *t);
246 
247 #endif /* __linux__ */
248 
249 #endif /* _WIN32 */
250 
251 /* Correlation between real and virtual time is always going to be
252    fairly approximate, so ignore small variation.
253    When the guest is idle real and virtual time will be aligned in
254    the IO wait loop.  */
255 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
256 
icount_adjust(void)257 static void icount_adjust(void)
258 {
259     int64_t cur_time;
260     int64_t cur_icount;
261     int64_t delta;
262     static int64_t last_delta;
263     /* If the VM is not running, then do nothing.  */
264     if (!vm_running)
265         return;
266 
267     cur_time = cpu_get_clock();
268     cur_icount = qemu_get_clock(vm_clock);
269     delta = cur_icount - cur_time;
270     /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
271     if (delta > 0
272         && last_delta + ICOUNT_WOBBLE < delta * 2
273         && icount_time_shift > 0) {
274         /* The guest is getting too far ahead.  Slow time down.  */
275         icount_time_shift--;
276     }
277     if (delta < 0
278         && last_delta - ICOUNT_WOBBLE > delta * 2
279         && icount_time_shift < MAX_ICOUNT_SHIFT) {
280         /* The guest is getting too far behind.  Speed time up.  */
281         icount_time_shift++;
282     }
283     last_delta = delta;
284     qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
285 }
286 
icount_adjust_rt(void * opaque)287 static void icount_adjust_rt(void * opaque)
288 {
289     qemu_mod_timer(icount_rt_timer,
290                    qemu_get_clock(rt_clock) + 1000);
291     icount_adjust();
292 }
293 
icount_adjust_vm(void * opaque)294 static void icount_adjust_vm(void * opaque)
295 {
296     qemu_mod_timer(icount_vm_timer,
297                    qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
298     icount_adjust();
299 }
300 
qemu_icount_round(int64_t count)301 int64_t qemu_icount_round(int64_t count)
302 {
303     return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
304 }
305 
306 static struct qemu_alarm_timer alarm_timers[] = {
307 #ifndef _WIN32
308 #if defined(__sun__)
309     {"multiticks", multiticks_start_timer,
310      multiticks_stop_timer, multiticks_rearm_timer, NULL},
311 #endif
312 #if defined(__linux__) || defined(__sun__)
313     {"dynticks", dynticks_start_timer,
314      dynticks_stop_timer, dynticks_rearm_timer, NULL},
315 #endif
316 #ifdef __linux__
317     /* HPET - if available - is preferred */
318     {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
319     /* ...otherwise try RTC */
320     {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
321 #endif
322     {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
323 #else
324     {"dynticks", win32_start_timer,
325      win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
326     {"win32", win32_start_timer,
327      win32_stop_timer, NULL, &alarm_win32_data},
328 #endif
329     {NULL, }
330 };
331 
show_available_alarms(void)332 static void show_available_alarms(void)
333 {
334     int i;
335 
336     printf("Available alarm timers, in order of precedence:\n");
337     for (i = 0; alarm_timers[i].name; i++)
338         printf("%s\n", alarm_timers[i].name);
339 }
340 
configure_alarms(char const * opt)341 void configure_alarms(char const *opt)
342 {
343     int i;
344     int cur = 0;
345     int count = ARRAY_SIZE(alarm_timers) - 1;
346     char *arg;
347     char *name;
348     struct qemu_alarm_timer tmp;
349 
350     if (!strcmp(opt, "?")) {
351         show_available_alarms();
352         exit(0);
353     }
354 
355     arg = qemu_strdup(opt);
356 
357     /* Reorder the array */
358     name = strtok(arg, ",");
359     while (name) {
360         for (i = 0; i < count && alarm_timers[i].name; i++) {
361             if (!strcmp(alarm_timers[i].name, name))
362                 break;
363         }
364 
365         if (i == count) {
366             fprintf(stderr, "Unknown clock %s\n", name);
367             goto next;
368         }
369 
370         if (i < cur)
371             /* Ignore */
372             goto next;
373 
374 	/* Swap */
375         tmp = alarm_timers[i];
376         alarm_timers[i] = alarm_timers[cur];
377         alarm_timers[cur] = tmp;
378 
379         cur++;
380 next:
381         name = strtok(NULL, ",");
382     }
383 
384     qemu_free(arg);
385 
386     if (cur) {
387         /* Disable remaining timers */
388         for (i = cur; i < count; i++)
389             alarm_timers[i].name = NULL;
390     } else {
391         show_available_alarms();
392         exit(1);
393     }
394 }
395 
396 #define QEMU_NUM_CLOCKS 3
397 
398 QEMUClock *rt_clock;
399 QEMUClock *vm_clock;
400 QEMUClock *host_clock;
401 
402 static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
403 
qemu_new_clock(int type)404 static QEMUClock *qemu_new_clock(int type)
405 {
406     QEMUClock *clock;
407     clock = qemu_mallocz(sizeof(QEMUClock));
408     clock->type = type;
409     clock->enabled = 1;
410     return clock;
411 }
412 
qemu_clock_enable(QEMUClock * clock,int enabled)413 void qemu_clock_enable(QEMUClock *clock, int enabled)
414 {
415     clock->enabled = enabled;
416 }
417 
qemu_new_timer(QEMUClock * clock,QEMUTimerCB * cb,void * opaque)418 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
419 {
420     QEMUTimer *ts;
421 
422     ts = qemu_mallocz(sizeof(QEMUTimer));
423     ts->clock = clock;
424     ts->cb = cb;
425     ts->opaque = opaque;
426     return ts;
427 }
428 
qemu_free_timer(QEMUTimer * ts)429 void qemu_free_timer(QEMUTimer *ts)
430 {
431     qemu_free(ts);
432 }
433 
434 /* stop a timer, but do not dealloc it */
qemu_del_timer(QEMUTimer * ts)435 void qemu_del_timer(QEMUTimer *ts)
436 {
437     QEMUTimer **pt, *t;
438 
439     /* NOTE: this code must be signal safe because
440        qemu_timer_expired() can be called from a signal. */
441     pt = &active_timers[ts->clock->type];
442     for(;;) {
443         t = *pt;
444         if (!t)
445             break;
446         if (t == ts) {
447             *pt = t->next;
448             break;
449         }
450         pt = &t->next;
451     }
452 }
453 
454 /* modify the current timer so that it will be fired when current_time
455    >= expire_time. The corresponding callback will be called. */
qemu_mod_timer(QEMUTimer * ts,int64_t expire_time)456 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
457 {
458     QEMUTimer **pt, *t;
459 
460     qemu_del_timer(ts);
461 
462     /* add the timer in the sorted list */
463     /* NOTE: this code must be signal safe because
464        qemu_timer_expired() can be called from a signal. */
465     pt = &active_timers[ts->clock->type];
466     for(;;) {
467         t = *pt;
468         if (!t)
469             break;
470         if (t->expire_time > expire_time)
471             break;
472         pt = &t->next;
473     }
474 
475     if (ts->expire_time && expire_time > ts->expire_time) {
476         ts->interval = expire_time - ts->expire_time;
477     } else {
478         ts->interval = 0;
479     }
480 
481     ts->expire_time = expire_time;
482     ts->next = *pt;
483     *pt = ts;
484 
485     trace_qemu_mod_timer(ts, expire_time, ts->interval);
486 
487     /* Rearm if necessary  */
488     if (pt == &active_timers[ts->clock->type]) {
489         if (!alarm_timer->pending) {
490             qemu_rearm_alarm_timer(alarm_timer);
491         }
492         /* Interrupt execution to force deadline recalculation.  */
493         if (use_icount)
494             qemu_notify_event();
495     }
496 }
497 
qemu_timer_pending(QEMUTimer * ts)498 int qemu_timer_pending(QEMUTimer *ts)
499 {
500     QEMUTimer *t;
501     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
502         if (t == ts)
503             return 1;
504     }
505     return 0;
506 }
507 
qemu_timer_expired(QEMUTimer * timer_head,int64_t current_time)508 int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
509 {
510     if (!timer_head)
511         return 0;
512     return (timer_head->expire_time <= current_time);
513 }
514 
qemu_run_timers(QEMUClock * clock)515 static void qemu_run_timers(QEMUClock *clock)
516 {
517     QEMUTimer **ptimer_head, *ts;
518     int64_t current_time;
519 
520     if (!clock->enabled)
521         return;
522 
523     current_time = qemu_get_clock (clock);
524     ptimer_head = &active_timers[clock->type];
525     for(;;) {
526         ts = *ptimer_head;
527         if (!ts || ts->expire_time > current_time)
528             break;
529 
530         trace_qemu_run_timer(ts, ts->expire_time, current_time);
531 
532         /* remove timer from the list before calling the callback */
533         *ptimer_head = ts->next;
534         ts->next = NULL;
535 
536         /* run the callback (the timer list can be modified) */
537         ts->cb(ts->opaque);
538     }
539 }
540 
qemu_get_clock(QEMUClock * clock)541 int64_t qemu_get_clock(QEMUClock *clock)
542 {
543     switch(clock->type) {
544     case QEMU_CLOCK_REALTIME:
545         return get_clock() / 1000000;
546     default:
547     case QEMU_CLOCK_VIRTUAL:
548         if (use_icount) {
549             return cpu_get_icount();
550         } else {
551             return cpu_get_clock();
552         }
553     case QEMU_CLOCK_HOST:
554         return get_clock_realtime();
555     }
556 }
557 
qemu_get_clock_ns(QEMUClock * clock)558 int64_t qemu_get_clock_ns(QEMUClock *clock)
559 {
560     switch(clock->type) {
561     case QEMU_CLOCK_REALTIME:
562         return get_clock();
563     default:
564     case QEMU_CLOCK_VIRTUAL:
565         if (use_icount) {
566             return cpu_get_icount();
567         } else {
568             return cpu_get_clock();
569         }
570     case QEMU_CLOCK_HOST:
571         return get_clock_realtime();
572     }
573 }
574 
init_clocks(void)575 void init_clocks(void)
576 {
577     rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
578     vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
579     host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
580 
581     rtc_clock = host_clock;
582 }
583 
584 /* save a timer */
qemu_put_timer(QEMUFile * f,QEMUTimer * ts)585 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
586 {
587     uint64_t expire_time;
588 
589     if (qemu_timer_pending(ts)) {
590         expire_time = ts->expire_time;
591     } else {
592         expire_time = -1;
593     }
594     qemu_put_be64(f, expire_time);
595 }
596 
qemu_get_timer(QEMUFile * f,QEMUTimer * ts)597 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
598 {
599     uint64_t expire_time;
600 
601     expire_time = qemu_get_be64(f);
602     if (expire_time != -1) {
603         qemu_mod_timer(ts, expire_time);
604     } else {
605         qemu_del_timer(ts);
606     }
607 }
608 
609 static const VMStateDescription vmstate_timers = {
610     .name = "timer",
611     .version_id = 2,
612     .minimum_version_id = 1,
613     .minimum_version_id_old = 1,
614     .fields      = (VMStateField []) {
615         VMSTATE_INT64(cpu_ticks_offset, TimersState),
616         VMSTATE_INT64(dummy, TimersState),
617         VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
618         VMSTATE_END_OF_LIST()
619     }
620 };
621 
configure_icount(const char * option)622 void configure_icount(const char *option)
623 {
624     vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
625     if (!option)
626         return;
627 
628     if (strcmp(option, "auto") != 0) {
629         icount_time_shift = strtol(option, NULL, 0);
630         use_icount = 1;
631         return;
632     }
633 
634     use_icount = 2;
635 
636     /* 125MIPS seems a reasonable initial guess at the guest speed.
637        It will be corrected fairly quickly anyway.  */
638     icount_time_shift = 3;
639 
640     /* Have both realtime and virtual time triggers for speed adjustment.
641        The realtime trigger catches emulated time passing too slowly,
642        the virtual time trigger catches emulated time passing too fast.
643        Realtime triggers occur even when idle, so use them less frequently
644        than VM triggers.  */
645     icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
646     qemu_mod_timer(icount_rt_timer,
647                    qemu_get_clock(rt_clock) + 1000);
648     icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
649     qemu_mod_timer(icount_vm_timer,
650                    qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
651 }
652 
qemu_run_all_timers(void)653 void qemu_run_all_timers(void)
654 {
655     alarm_timer->pending = 0;
656 
657     /* rearm timer, if not periodic */
658     if (alarm_timer->expired) {
659         alarm_timer->expired = 0;
660         qemu_rearm_alarm_timer(alarm_timer);
661     }
662 
663     /* vm time timers */
664     if (vm_running) {
665         qemu_run_timers(vm_clock);
666     }
667 
668     qemu_run_timers(rt_clock);
669     qemu_run_timers(host_clock);
670 }
671 
672 static int64_t qemu_next_alarm_deadline(struct QEMUTimer **);
673 
674 #ifdef _WIN32
host_alarm_handler(UINT uTimerID,UINT uMsg,DWORD_PTR dwUser,DWORD_PTR dw1,DWORD_PTR dw2)675 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
676                                         DWORD_PTR dwUser, DWORD_PTR dw1,
677                                         DWORD_PTR dw2)
678 #else
679 static void host_alarm_handler(int host_signum)
680 #endif
681 {
682     struct qemu_alarm_timer *t = alarm_timer;
683     if (!t)
684 	return;
685 
686 #if 0
687 #define DISP_FREQ 1000
688     {
689         static int64_t delta_min = INT64_MAX;
690         static int64_t delta_max, delta_cum, last_clock, delta, ti;
691         static int count;
692         ti = qemu_get_clock(vm_clock);
693         if (last_clock != 0) {
694             delta = ti - last_clock;
695             if (delta < delta_min)
696                 delta_min = delta;
697             if (delta > delta_max)
698                 delta_max = delta;
699             delta_cum += delta;
700             if (++count == DISP_FREQ) {
701                 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
702                        muldiv64(delta_min, 1000000, get_ticks_per_sec()),
703                        muldiv64(delta_max, 1000000, get_ticks_per_sec()),
704                        muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
705                        (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
706                 count = 0;
707                 delta_min = INT64_MAX;
708                 delta_max = 0;
709                 delta_cum = 0;
710             }
711         }
712         last_clock = ti;
713     }
714 #endif
715     if (alarm_has_dynticks(t) ||
716         qemu_next_alarm_deadline (NULL) <= 0) {
717         t->expired = alarm_has_dynticks(t);
718         t->pending = 1;
719         qemu_notify_event();
720     }
721 }
722 
qemu_next_deadline(void)723 int64_t qemu_next_deadline(void)
724 {
725     /* To avoid problems with overflow limit this to 2^32.  */
726     int64_t delta = INT32_MAX;
727 
728     if (active_timers[QEMU_CLOCK_VIRTUAL]) {
729         delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
730                      qemu_get_clock_ns(vm_clock);
731     }
732     if (active_timers[QEMU_CLOCK_HOST]) {
733         int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
734                  qemu_get_clock_ns(host_clock);
735         if (hdelta < delta)
736             delta = hdelta;
737     }
738 
739     if (delta < 0)
740         delta = 0;
741 
742     return delta;
743 }
744 
qemu_next_alarm_deadline(struct QEMUTimer ** tp)745 static int64_t qemu_next_alarm_deadline(struct QEMUTimer **tp)
746 {
747     int64_t delta;
748     int64_t rtdelta;
749     struct QEMUTimer *t;
750 
751     if (tp == NULL)
752         tp = &t;
753 
754     if (!use_icount && active_timers[QEMU_CLOCK_VIRTUAL]) {
755         delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
756                      qemu_get_clock(vm_clock);
757         *tp = active_timers[QEMU_CLOCK_VIRTUAL];
758     } else {
759         delta = INT32_MAX;
760         *tp = NULL;
761     }
762     if (active_timers[QEMU_CLOCK_HOST]) {
763         int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
764                  qemu_get_clock_ns(host_clock);
765         if (hdelta < delta) {
766             delta = hdelta;
767             *tp = active_timers[QEMU_CLOCK_HOST];
768         }
769     }
770 
771     if (active_timers[QEMU_CLOCK_REALTIME]) {
772         rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time * 1000000 -
773                  qemu_get_clock_ns(rt_clock));
774         if (rtdelta < delta) {
775             delta = rtdelta;
776             *tp = active_timers[QEMU_CLOCK_REALTIME];
777         }
778     }
779 
780     return delta;
781 }
782 
783 #if defined(__linux__)
784 
785 #define RTC_FREQ 1024
786 
enable_sigio_timer(int fd)787 static void enable_sigio_timer(int fd)
788 {
789     struct sigaction act;
790 
791     /* timer signal */
792     sigfillset(&act.sa_mask);
793     act.sa_flags = 0;
794     act.sa_handler = host_alarm_handler;
795 
796     sigaction(SIGIO, &act, NULL);
797     fcntl_setfl(fd, O_ASYNC);
798     fcntl(fd, F_SETOWN, getpid());
799 }
800 
hpet_start_timer(struct qemu_alarm_timer * t)801 static int hpet_start_timer(struct qemu_alarm_timer *t)
802 {
803     struct hpet_info info;
804     int r, fd;
805 
806     fd = qemu_open("/dev/hpet", O_RDONLY);
807     if (fd < 0)
808         return -1;
809 
810     /* Set frequency */
811     r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
812     if (r < 0) {
813         fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
814                 "error, but for better emulation accuracy type:\n"
815                 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
816         goto fail;
817     }
818 
819     /* Check capabilities */
820     r = ioctl(fd, HPET_INFO, &info);
821     if (r < 0)
822         goto fail;
823 
824     /* Enable periodic mode */
825     r = ioctl(fd, HPET_EPI, 0);
826     if (info.hi_flags && (r < 0))
827         goto fail;
828 
829     /* Enable interrupt */
830     r = ioctl(fd, HPET_IE_ON, 0);
831     if (r < 0)
832         goto fail;
833 
834     enable_sigio_timer(fd);
835     t->priv = (void *)(long)fd;
836 
837     return 0;
838 fail:
839     close(fd);
840     return -1;
841 }
842 
hpet_stop_timer(struct qemu_alarm_timer * t)843 static void hpet_stop_timer(struct qemu_alarm_timer *t)
844 {
845     int fd = (long)t->priv;
846 
847     close(fd);
848 }
849 
rtc_start_timer(struct qemu_alarm_timer * t)850 static int rtc_start_timer(struct qemu_alarm_timer *t)
851 {
852     int rtc_fd;
853     unsigned long current_rtc_freq = 0;
854 
855     TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
856     if (rtc_fd < 0)
857         return -1;
858     ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
859     if (current_rtc_freq != RTC_FREQ &&
860         ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
861         fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
862                 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
863                 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
864         goto fail;
865     }
866     if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
867     fail:
868         close(rtc_fd);
869         return -1;
870     }
871 
872     enable_sigio_timer(rtc_fd);
873 
874     t->priv = (void *)(long)rtc_fd;
875 
876     return 0;
877 }
878 
rtc_stop_timer(struct qemu_alarm_timer * t)879 static void rtc_stop_timer(struct qemu_alarm_timer *t)
880 {
881     int rtc_fd = (long)t->priv;
882 
883     close(rtc_fd);
884 }
885 
886 #endif /* defined(__linux__) */
887 
888 #if defined(__sun__)
889 
890 #define QEMU_MULTITICKS_NSOURCES 8
891 
892 int multiticks_enabled = 1;
893 int multiticks_tolerance_jitter = 20000;
894 int64_t multiticks_tolerance_interval = 200000;
895 int64_t multiticks_reap_threshold = NANOSEC;
896 int multiticks_reap_multiplier = 4;
897 
898 struct multitick_source {
899     timer_t source;
900     QEMUTimer *timer;
901     int64_t armed;
902     int64_t interval;
903     int64_t initial;
904 };
905 
906 struct qemu_alarm_multiticks {
907     int64_t reaped;
908     struct multitick_source sources[QEMU_MULTITICKS_NSOURCES];
909 };
910 
911 /*
912  * Many QEMU timer consumers seek to create interval timers, but QEMU only has
913  * a one-shot timer facility.  This forces the consumer to effect their own
914  * intervals, an annoying (but not necessarily difficult) task. However, the
915  * problem with using one-shots to implement interval timers is the overhead
916  * of programming the underlying timer (e.g., timer_settime()):  even at
917  * moderate frequencies (e.g., 1 KHz) this overhead can become significant at
918  * modest levels of tenancy.  Given that the underlying POSIX timer facility
919  * is in fact capable of providing interval timers (and given that using the
920  * interval timers is more accurate than effecting the same with a one-shot),
921  * and given that one can have multiple timers in a process, there is an
922  * opportunity to significantly reduce timer programming overhead while
923  * increasing timer accuracy by making better use of POSIX timers.  The
924  * multiticks alarm timer does exactly this via a cache of interval timers,
925  * associating a timer in a one-to-one manner with an underlying source.
926  */
multiticks_start_timer(struct qemu_alarm_timer * t)927 static int multiticks_start_timer(struct qemu_alarm_timer *t)
928 {
929     struct sigevent ev;
930     struct sigaction act;
931     struct qemu_alarm_multiticks *multiticks;
932     struct multitick_source *sources;
933     struct itimerspec timeout;
934     struct timespec res;
935     int64_t resolution, found;
936     int i;
937 
938     if (!multiticks_enabled) {
939         fprintf(stderr, "multiticks: programmatically disabled\n");
940         return -1;
941     }
942 
943     sigfillset(&act.sa_mask);
944     act.sa_flags = 0;
945     act.sa_handler = host_alarm_handler;
946 
947     sigaction(SIGALRM, &act, NULL);
948 
949     multiticks = qemu_mallocz(sizeof (struct qemu_alarm_multiticks));
950     sources = multiticks->sources;
951     t->priv = multiticks;
952 
953     memset(&ev, 0, sizeof(ev));
954     ev.sigev_value.sival_int = 0;
955     ev.sigev_notify = SIGEV_SIGNAL;
956     ev.sigev_signo = SIGALRM;
957 
958     for (i = 0; i < QEMU_MULTITICKS_NSOURCES; i++)
959         sources[i].source = -1;
960 
961     for (i = 0; i < QEMU_MULTITICKS_NSOURCES; i++) {
962         if (timer_create(CLOCK_MONOTONIC, &ev, &sources[i].source) != 0) {
963             perror("multiticks: timer_create");
964             fprintf(stderr, "multiticks: could not create timer; disabling\n");
965             multiticks_stop_timer(t);
966             return -1;
967         }
968     }
969 
970     /*
971      * Check that the implementation properly honors an arbitrary interval --
972      * and in particular, an interval that is explicitly not evenly divided
973      * by the resolution.  (Multiticks very much relies on interval timers
974      * being properly implemented; even small errors in the interval can
975      * add up quickly when frequencies are high.)
976      */
977     if (clock_getres(CLOCK_MONOTONIC, &res) != 0) {
978         perror("multiticks: clock_getres");
979         fprintf(stderr, "multiticks: could not get resolution; disabling\n");
980         multiticks_stop_timer(t);
981         return -1;
982     }
983 
984     resolution = (res.tv_sec * NANOSEC + res.tv_nsec) * 60 * NANOSEC + 1;
985 
986     timeout.it_value.tv_sec = resolution / NANOSEC;
987     timeout.it_value.tv_nsec = resolution % NANOSEC;
988     timeout.it_interval.tv_sec = resolution / NANOSEC;
989     timeout.it_interval.tv_nsec = resolution % NANOSEC;
990 
991     if (timer_settime(sources[0].source, TIMER_RELTIME, &timeout, NULL) != 0) {
992         perror("multiticks: timer_settime");
993         fprintf(stderr, "multiticks: could not set test timer; disabling\n");
994         multiticks_stop_timer(t);
995         return -1;
996     }
997 
998     if (timer_gettime(sources[0].source, &timeout) != 0) {
999         perror("multiticks: timer_gettime");
1000         fprintf(stderr, "multiticks: could not get test timer; disabling\n");
1001         multiticks_stop_timer(t);
1002         return -1;
1003     }
1004 
1005     found = timeout.it_interval.tv_sec * NANOSEC + timeout.it_interval.tv_nsec;
1006 
1007     if (resolution != found) {
1008         fprintf(stderr, "multiticks: interval not properly honored "
1009             "(set to %lld; found %lld); disabling\n",
1010             (long long)resolution, (long long)found);
1011         multiticks_stop_timer(t);
1012         return -1;
1013     }
1014 
1015     memset(&timeout, 0, sizeof (timeout));
1016     (void) timer_settime(sources[0].source, TIMER_RELTIME, &timeout, NULL);
1017 
1018     return 0;
1019 }
1020 
multiticks_stop_timer(struct qemu_alarm_timer * t)1021 static void multiticks_stop_timer(struct qemu_alarm_timer *t)
1022 {
1023     struct qemu_alarm_multiticks *multiticks = t->priv;
1024     struct multitick_source *sources = multiticks->sources;
1025     int i;
1026 
1027     for (i = 0; i < QEMU_MULTITICKS_NSOURCES; i++) {
1028         if (sources[i].source != -1)
1029             timer_delete(sources[i].source);
1030     }
1031 
1032     qemu_vfree(multiticks);
1033     t->priv = NULL;
1034 }
1035 
multiticks_source(struct qemu_alarm_timer * t,QEMUTimer * timer)1036 static struct multitick_source *multiticks_source(struct qemu_alarm_timer *t,
1037                                                   QEMUTimer *timer)
1038 {
1039     struct qemu_alarm_multiticks *multiticks = t->priv;
1040     struct multitick_source *sources = multiticks->sources, *source;
1041     int64_t oldest = INT64_MAX;
1042     int i;
1043 
1044     /*
1045      * We have a dynamic check here against multiticks_enabled to allow it
1046      * to be dynamically disabled after the multiticks alarm timer has been
1047      * configured.  When disabled, multiticks should degenerate to an
1048      * implementation approximating that of dynticks, allowing for behavior
1049      * comparisons to be made without restarting guests.
1050      */
1051     if (!multiticks_enabled) {
1052         source = &sources[0];
1053         source->interval = 0;
1054     } else {
1055         if ((source = timer->source) != NULL && source->timer == timer) {
1056             /*
1057              * This timer still owns its source -- it wasn't stolen since last
1058              * being armed.
1059              */
1060             return (source);
1061         }
1062 
1063         /*
1064          * The source has either been stolen from the timer, or it was never
1065          * assigned; find a source and assign it.
1066          */
1067         for (i = 0; i < QEMU_MULTITICKS_NSOURCES; i++) {
1068             if (sources[i].armed < oldest) {
1069                 oldest = sources[i].armed;
1070                 source = &sources[i];
1071             }
1072         }
1073     }
1074 
1075     trace_multiticks_assign(source->timer, source->source);
1076 
1077     assert(source != NULL);
1078     source->timer = timer;
1079     timer->source = source;
1080 
1081     return (source);
1082 }
1083 
multiticks_reap(struct qemu_alarm_timer * t,int64_t now)1084 static void multiticks_reap(struct qemu_alarm_timer *t, int64_t now)
1085 {
1086     struct qemu_alarm_multiticks *multiticks = t->priv;
1087     struct multitick_source *sources = multiticks->sources, *source;
1088     int multiplier = multiticks_reap_multiplier;
1089     struct itimerspec timeout;
1090     int64_t interval;
1091     int i;
1092 
1093     if (now - multiticks->reaped < multiticks_reap_threshold)
1094         return;
1095 
1096     memset(&timeout, 0, sizeof (timeout));
1097 
1098     for (i = 0; i < QEMU_MULTITICKS_NSOURCES; i++) {
1099         if (!(interval = sources[i].interval))
1100             continue;
1101 
1102         if (sources[i].armed + (multiplier * interval) > now)
1103             continue;
1104 
1105         source = &sources[i];
1106         trace_multiticks_reap(source->source, source->armed, interval);
1107 
1108         source->interval = 0;
1109 
1110         if (timer_settime(source->source, TIMER_RELTIME, &timeout, NULL) != 0) {
1111             perror("timer_settime");
1112             fprintf(stderr, "multiticks: internal reaping error; aborting\n");
1113             exit(1);
1114         }
1115     }
1116 
1117     multiticks->reaped = now;
1118 }
1119 
multiticks_rearm_timer(struct qemu_alarm_timer * t)1120 static void multiticks_rearm_timer(struct qemu_alarm_timer *t)
1121 {
1122     struct multitick_source *source;
1123     struct itimerspec timeout;
1124     QEMUTimer *timer;
1125     int64_t delta, when, interval;
1126     int64_t low, high, now;
1127 
1128     assert(alarm_has_dynticks(t));
1129 
1130     /*
1131      * First we need to find the next timer to fire.
1132      */
1133     low = get_clock();
1134     delta = qemu_next_alarm_deadline(&timer);
1135     now = high = get_clock();
1136 
1137     multiticks_reap(t, now);
1138 
1139     if (timer == NULL)
1140         return;
1141 
1142     low += delta;
1143     high += delta;
1144 
1145     if (timer->clock->type == QEMU_CLOCK_REALTIME) {
1146         interval = timer->interval * 1000000;
1147     } else {
1148         interval = timer->interval;
1149     }
1150 
1151     if (interval < multiticks_tolerance_interval)
1152         interval = 0;
1153 
1154     source = multiticks_source(t, timer);
1155 
1156     if (interval && source->interval) {
1157         int64_t offset, fire;
1158 
1159         if (low < source->initial && source->initial < high) {
1160             /*
1161              * Our timer has not yet had its initial firing, which is already
1162              * scheduled to be within band; we have nothing else to do.
1163              */
1164             trace_multiticks_inband(source->timer, low, high, source->initial);
1165             source->armed = now;
1166             return;
1167         }
1168 
1169         offset = (low - source->initial) % source->interval;
1170         fire = low + (source->interval - offset);
1171 
1172         if (fire < high) {
1173             /*
1174              * Our timer is going to fire within our band of expectation; we
1175              * have nothing else to do.
1176              */
1177             trace_multiticks_inband(source->timer, low, high, fire);
1178             source->armed = now;
1179             return;
1180         }
1181 
1182         if (fire - high < multiticks_tolerance_jitter) {
1183             /*
1184              * Our timer is going to fire out of our band of expection, but
1185              * within our jitter tolerance; we'll let it ride.
1186              */
1187             trace_multiticks_inband(source->timer, low, high, fire);
1188             source->armed = now;
1189             return;
1190         }
1191 
1192         trace_multiticks_outofband(source->timer, low, high, fire);
1193     }
1194 
1195     /*
1196      * We don't actually know the precise (absolute) time to fire, so we'll
1197      * take the middle of the band.
1198      */
1199     when = low + (high - low) / 2;
1200 
1201     trace_multiticks_program(source->timer, when, interval);
1202 
1203     source->interval = interval;
1204     source->armed = interval ? now : 0;
1205     source->initial = when;
1206     timeout.it_value.tv_sec = when / NANOSEC;
1207     timeout.it_value.tv_nsec = when % NANOSEC;
1208     timeout.it_interval.tv_sec = interval / NANOSEC;
1209     timeout.it_interval.tv_nsec = interval % NANOSEC;
1210 
1211     if (timer_settime(source->source, TIMER_ABSTIME, &timeout, NULL) != 0) {
1212         perror("timer_settime");
1213         fprintf(stderr, "multiticks: internal timer error; aborting\n");
1214         exit(1);
1215     }
1216 }
1217 #endif
1218 
1219 #if defined(__linux__) || defined(__sun__)
1220 
dynticks_start_timer(struct qemu_alarm_timer * t)1221 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1222 {
1223     struct sigevent ev;
1224     timer_t host_timer;
1225     struct sigaction act;
1226 
1227     sigfillset(&act.sa_mask);
1228     act.sa_flags = 0;
1229     act.sa_handler = host_alarm_handler;
1230 
1231     sigaction(SIGALRM, &act, NULL);
1232 
1233     /*
1234      * Initialize ev struct to 0 to avoid valgrind complaining
1235      * about uninitialized data in timer_create call
1236      */
1237     memset(&ev, 0, sizeof(ev));
1238     ev.sigev_value.sival_int = 0;
1239     ev.sigev_notify = SIGEV_SIGNAL;
1240     ev.sigev_signo = SIGALRM;
1241 
1242 #if defined(__sun__)
1243     if (timer_create(CLOCK_HIGHRES, &ev, &host_timer)) {
1244 #else
1245     if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1246 #endif
1247         perror("timer_create");
1248 
1249         /* disable dynticks */
1250         fprintf(stderr, "Dynamic Ticks disabled\n");
1251 
1252         return -1;
1253     }
1254 
1255     t->priv = (void *)(long)host_timer;
1256 
1257     return 0;
1258 }
1259 
1260 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1261 {
1262     timer_t host_timer = (timer_t)(long)t->priv;
1263 
1264     timer_delete(host_timer);
1265 }
1266 
1267 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1268 {
1269     timer_t host_timer = (timer_t)(long)t->priv;
1270     struct itimerspec timeout;
1271     int64_t nearest_delta_ns = INT64_MAX;
1272     int64_t current_ns;
1273 
1274     assert(alarm_has_dynticks(t));
1275     if (!active_timers[QEMU_CLOCK_REALTIME] &&
1276         !active_timers[QEMU_CLOCK_VIRTUAL] &&
1277         !active_timers[QEMU_CLOCK_HOST])
1278         return;
1279 
1280     nearest_delta_ns = qemu_next_alarm_deadline(NULL);
1281     if (nearest_delta_ns < MIN_TIMER_REARM_NS)
1282         nearest_delta_ns = MIN_TIMER_REARM_NS;
1283 
1284     /* check whether a timer is already running */
1285     if (timer_gettime(host_timer, &timeout)) {
1286         perror("gettime");
1287         fprintf(stderr, "Internal timer error: aborting\n");
1288         exit(1);
1289     }
1290     current_ns = timeout.it_value.tv_sec * 1000000000LL + timeout.it_value.tv_nsec;
1291     if (current_ns && current_ns <= nearest_delta_ns)
1292         return;
1293 
1294     timeout.it_interval.tv_sec = 0;
1295     timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1296     timeout.it_value.tv_sec =  nearest_delta_ns / 1000000000;
1297     timeout.it_value.tv_nsec = nearest_delta_ns % 1000000000;
1298     if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1299         perror("settime");
1300         fprintf(stderr, "Internal timer error: aborting\n");
1301         exit(1);
1302     }
1303 }
1304 
1305 #endif /* defined(__linux__) || defined(__sun__) */
1306 
1307 #if !defined(_WIN32)
1308 
1309 static int unix_start_timer(struct qemu_alarm_timer *t)
1310 {
1311     struct sigaction act;
1312     struct itimerval itv;
1313     int err;
1314 
1315     /* timer signal */
1316     sigfillset(&act.sa_mask);
1317     act.sa_flags = 0;
1318     act.sa_handler = host_alarm_handler;
1319 
1320     sigaction(SIGALRM, &act, NULL);
1321 
1322     itv.it_interval.tv_sec = 0;
1323     /* for i386 kernel 2.6 to get 1 ms */
1324     itv.it_interval.tv_usec = 999;
1325     itv.it_value.tv_sec = 0;
1326     itv.it_value.tv_usec = 10 * 1000;
1327 
1328     err = setitimer(ITIMER_REAL, &itv, NULL);
1329     if (err)
1330         return -1;
1331 
1332     return 0;
1333 }
1334 
1335 static void unix_stop_timer(struct qemu_alarm_timer *t)
1336 {
1337     struct itimerval itv;
1338 
1339     memset(&itv, 0, sizeof(itv));
1340     setitimer(ITIMER_REAL, &itv, NULL);
1341 }
1342 
1343 #endif /* !defined(_WIN32) */
1344 
1345 
1346 #ifdef _WIN32
1347 
1348 static int win32_start_timer(struct qemu_alarm_timer *t)
1349 {
1350     TIMECAPS tc;
1351     struct qemu_alarm_win32 *data = t->priv;
1352     UINT flags;
1353 
1354     memset(&tc, 0, sizeof(tc));
1355     timeGetDevCaps(&tc, sizeof(tc));
1356 
1357     data->period = tc.wPeriodMin;
1358     timeBeginPeriod(data->period);
1359 
1360     flags = TIME_CALLBACK_FUNCTION;
1361     if (alarm_has_dynticks(t))
1362         flags |= TIME_ONESHOT;
1363     else
1364         flags |= TIME_PERIODIC;
1365 
1366     data->timerId = timeSetEvent(1,         // interval (ms)
1367                         data->period,       // resolution
1368                         host_alarm_handler, // function
1369                         (DWORD)t,           // parameter
1370                         flags);
1371 
1372     if (!data->timerId) {
1373         fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1374                 GetLastError());
1375         timeEndPeriod(data->period);
1376         return -1;
1377     }
1378 
1379     return 0;
1380 }
1381 
1382 static void win32_stop_timer(struct qemu_alarm_timer *t)
1383 {
1384     struct qemu_alarm_win32 *data = t->priv;
1385 
1386     timeKillEvent(data->timerId);
1387     timeEndPeriod(data->period);
1388 }
1389 
1390 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1391 {
1392     struct qemu_alarm_win32 *data = t->priv;
1393 
1394     assert(alarm_has_dynticks(t));
1395     if (!active_timers[QEMU_CLOCK_REALTIME] &&
1396         !active_timers[QEMU_CLOCK_VIRTUAL] &&
1397         !active_timers[QEMU_CLOCK_HOST])
1398         return;
1399 
1400     timeKillEvent(data->timerId);
1401 
1402     data->timerId = timeSetEvent(1,
1403                         data->period,
1404                         host_alarm_handler,
1405                         (DWORD)t,
1406                         TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1407 
1408     if (!data->timerId) {
1409         fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1410                 GetLastError());
1411 
1412         timeEndPeriod(data->period);
1413         exit(1);
1414     }
1415 }
1416 
1417 #endif /* _WIN32 */
1418 
1419 static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1420 {
1421     if (running)
1422         qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1423 }
1424 
1425 int init_timer_alarm(void)
1426 {
1427     struct qemu_alarm_timer *t = NULL;
1428     int i, err = -1;
1429 
1430     for (i = 0; alarm_timers[i].name; i++) {
1431         t = &alarm_timers[i];
1432 
1433         err = t->start(t);
1434         if (!err)
1435             break;
1436     }
1437 
1438     if (err) {
1439         err = -ENOENT;
1440         goto fail;
1441     }
1442 
1443     /* first event is at time 0 */
1444     t->pending = 1;
1445     alarm_timer = t;
1446     qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1447 
1448     return 0;
1449 
1450 fail:
1451     return err;
1452 }
1453 
1454 void quit_timers(void)
1455 {
1456     struct qemu_alarm_timer *t = alarm_timer;
1457     alarm_timer = NULL;
1458     t->stop(t);
1459 }
1460 
1461 int qemu_calculate_timeout(void)
1462 {
1463     int timeout;
1464 
1465 #define QEMUKVM 1
1466 #if defined (CONFIG_IOTHREAD) || defined (QEMUKVM)
1467     /* When using icount, making forward progress with qemu_icount when the
1468        guest CPU is idle is critical. We only use the static io-thread timeout
1469        for non icount runs.  */
1470     if (!use_icount) {
1471         return 1000;
1472     }
1473 #endif
1474 
1475     if (!vm_running)
1476         timeout = 5000;
1477     else {
1478      /* XXX: use timeout computed from timers */
1479         int64_t add;
1480         int64_t delta;
1481         /* Advance virtual time to the next event.  */
1482 	delta = qemu_icount_delta();
1483         if (delta > 0) {
1484             /* If virtual time is ahead of real time then just
1485                wait for IO.  */
1486             timeout = (delta + 999999) / 1000000;
1487         } else {
1488             /* Wait for either IO to occur or the next
1489                timer event.  */
1490             add = qemu_next_deadline();
1491             /* We advance the timer before checking for IO.
1492                Limit the amount we advance so that early IO
1493                activity won't get the guest too far ahead.  */
1494             if (add > 10000000)
1495                 add = 10000000;
1496             delta += add;
1497             qemu_icount += qemu_icount_round (add);
1498             timeout = delta / 1000000;
1499             if (timeout < 0)
1500                 timeout = 0;
1501         }
1502     }
1503 
1504     return timeout;
1505 }
1506 
1507