4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 #include <sys/param.h>
47 #include "qemu-timer.h"
49 /***********************************************************/
52 #define QEMU_CLOCK_REALTIME 0
53 #define QEMU_CLOCK_VIRTUAL 1
54 #define QEMU_CLOCK_HOST 2
60 QEMUTimer
*active_timers
;
62 NotifierList reset_notifiers
;
68 int64_t expire_time
; /* in nanoseconds */
72 struct QEMUTimer
*next
;
75 struct qemu_alarm_timer
{
77 int (*start
)(struct qemu_alarm_timer
*t
);
78 void (*stop
)(struct qemu_alarm_timer
*t
);
79 void (*rearm
)(struct qemu_alarm_timer
*t
, int64_t nearest_delta_ns
);
80 #if defined(__linux__)
90 static struct qemu_alarm_timer
*alarm_timer
;
92 static bool qemu_timer_expired_ns(QEMUTimer
*timer_head
, int64_t current_time
)
94 return timer_head
&& (timer_head
->expire_time
<= current_time
);
97 int qemu_alarm_pending(void)
99 return alarm_timer
->pending
;
102 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
107 static int64_t qemu_next_alarm_deadline(void)
112 if (!use_icount
&& vm_clock
->active_timers
) {
113 delta
= vm_clock
->active_timers
->expire_time
-
114 qemu_get_clock_ns(vm_clock
);
118 if (host_clock
->active_timers
) {
119 int64_t hdelta
= host_clock
->active_timers
->expire_time
-
120 qemu_get_clock_ns(host_clock
);
121 if (hdelta
< delta
) {
125 if (rt_clock
->active_timers
) {
126 rtdelta
= (rt_clock
->active_timers
->expire_time
-
127 qemu_get_clock_ns(rt_clock
));
128 if (rtdelta
< delta
) {
136 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
138 int64_t nearest_delta_ns
;
139 assert(alarm_has_dynticks(t
));
140 if (!rt_clock
->active_timers
&&
141 !vm_clock
->active_timers
&&
142 !host_clock
->active_timers
) {
145 nearest_delta_ns
= qemu_next_alarm_deadline();
146 t
->rearm(t
, nearest_delta_ns
);
149 /* TODO: MIN_TIMER_REARM_NS should be optimized */
150 #define MIN_TIMER_REARM_NS 250000
154 static int mm_start_timer(struct qemu_alarm_timer
*t
);
155 static void mm_stop_timer(struct qemu_alarm_timer
*t
);
156 static void mm_rearm_timer(struct qemu_alarm_timer
*t
, int64_t delta
);
158 static int win32_start_timer(struct qemu_alarm_timer
*t
);
159 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
160 static void win32_rearm_timer(struct qemu_alarm_timer
*t
, int64_t delta
);
164 static int unix_start_timer(struct qemu_alarm_timer
*t
);
165 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
166 static void unix_rearm_timer(struct qemu_alarm_timer
*t
, int64_t delta
);
170 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
171 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
172 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
, int64_t delta
);
174 #endif /* __linux__ */
178 static struct qemu_alarm_timer alarm_timers
[] = {
181 {"dynticks", dynticks_start_timer
,
182 dynticks_stop_timer
, dynticks_rearm_timer
},
184 {"unix", unix_start_timer
, unix_stop_timer
, unix_rearm_timer
},
186 {"mmtimer", mm_start_timer
, mm_stop_timer
, NULL
},
187 {"mmtimer2", mm_start_timer
, mm_stop_timer
, mm_rearm_timer
},
188 {"dynticks", win32_start_timer
, win32_stop_timer
, win32_rearm_timer
},
189 {"win32", win32_start_timer
, win32_stop_timer
, NULL
},
194 static void show_available_alarms(void)
198 printf("Available alarm timers, in order of precedence:\n");
199 for (i
= 0; alarm_timers
[i
].name
; i
++)
200 printf("%s\n", alarm_timers
[i
].name
);
203 void configure_alarms(char const *opt
)
207 int count
= ARRAY_SIZE(alarm_timers
) - 1;
210 struct qemu_alarm_timer tmp
;
212 if (!strcmp(opt
, "?")) {
213 show_available_alarms();
219 /* Reorder the array */
220 name
= strtok(arg
, ",");
222 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
223 if (!strcmp(alarm_timers
[i
].name
, name
))
228 fprintf(stderr
, "Unknown clock %s\n", name
);
237 tmp
= alarm_timers
[i
];
238 alarm_timers
[i
] = alarm_timers
[cur
];
239 alarm_timers
[cur
] = tmp
;
243 name
= strtok(NULL
, ",");
249 /* Disable remaining timers */
250 for (i
= cur
; i
< count
; i
++)
251 alarm_timers
[i
].name
= NULL
;
253 show_available_alarms();
260 QEMUClock
*host_clock
;
262 static QEMUClock
*qemu_new_clock(int type
)
266 clock
= g_malloc0(sizeof(QEMUClock
));
269 clock
->last
= INT64_MIN
;
270 notifier_list_init(&clock
->reset_notifiers
);
274 void qemu_clock_enable(QEMUClock
*clock
, int enabled
)
276 bool old
= clock
->enabled
;
277 clock
->enabled
= enabled
;
278 if (enabled
&& !old
) {
279 qemu_rearm_alarm_timer(alarm_timer
);
283 int64_t qemu_clock_has_timers(QEMUClock
*clock
)
285 return !!clock
->active_timers
;
288 int64_t qemu_clock_expired(QEMUClock
*clock
)
290 return (clock
->active_timers
&&
291 clock
->active_timers
->expire_time
< qemu_get_clock_ns(clock
));
294 int64_t qemu_clock_deadline(QEMUClock
*clock
)
296 /* To avoid problems with overflow limit this to 2^32. */
297 int64_t delta
= INT32_MAX
;
299 if (clock
->active_timers
) {
300 delta
= clock
->active_timers
->expire_time
- qemu_get_clock_ns(clock
);
308 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, int scale
,
309 QEMUTimerCB
*cb
, void *opaque
)
313 ts
= g_malloc0(sizeof(QEMUTimer
));
321 void qemu_free_timer(QEMUTimer
*ts
)
326 /* stop a timer, but do not dealloc it */
327 void qemu_del_timer(QEMUTimer
*ts
)
331 /* NOTE: this code must be signal safe because
332 qemu_timer_expired() can be called from a signal. */
333 pt
= &ts
->clock
->active_timers
;
346 /* modify the current timer so that it will be fired when current_time
347 >= expire_time. The corresponding callback will be called. */
348 void qemu_mod_timer_ns(QEMUTimer
*ts
, int64_t expire_time
)
354 /* add the timer in the sorted list */
355 /* NOTE: this code must be signal safe because
356 qemu_timer_expired() can be called from a signal. */
357 pt
= &ts
->clock
->active_timers
;
360 if (!qemu_timer_expired_ns(t
, expire_time
)) {
365 ts
->expire_time
= expire_time
;
369 /* Rearm if necessary */
370 if (pt
== &ts
->clock
->active_timers
) {
371 if (!alarm_timer
->pending
) {
372 qemu_rearm_alarm_timer(alarm_timer
);
374 /* Interrupt execution to force deadline recalculation. */
375 qemu_clock_warp(ts
->clock
);
382 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
384 qemu_mod_timer_ns(ts
, expire_time
* ts
->scale
);
387 int qemu_timer_pending(QEMUTimer
*ts
)
390 for (t
= ts
->clock
->active_timers
; t
!= NULL
; t
= t
->next
) {
397 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
399 return qemu_timer_expired_ns(timer_head
, current_time
* timer_head
->scale
);
402 static void qemu_run_timers(QEMUClock
*clock
)
404 QEMUTimer
**ptimer_head
, *ts
;
405 int64_t current_time
;
410 current_time
= qemu_get_clock_ns(clock
);
411 ptimer_head
= &clock
->active_timers
;
414 if (!qemu_timer_expired_ns(ts
, current_time
)) {
417 /* remove timer from the list before calling the callback */
418 *ptimer_head
= ts
->next
;
421 /* run the callback (the timer list can be modified) */
426 int64_t qemu_get_clock_ns(QEMUClock
*clock
)
430 switch(clock
->type
) {
431 case QEMU_CLOCK_REALTIME
:
434 case QEMU_CLOCK_VIRTUAL
:
436 return cpu_get_icount();
438 return cpu_get_clock();
440 case QEMU_CLOCK_HOST
:
441 now
= get_clock_realtime();
445 notifier_list_notify(&clock
->reset_notifiers
, &now
);
451 void qemu_register_clock_reset_notifier(QEMUClock
*clock
, Notifier
*notifier
)
453 notifier_list_add(&clock
->reset_notifiers
, notifier
);
456 void qemu_unregister_clock_reset_notifier(QEMUClock
*clock
, Notifier
*notifier
)
458 notifier_list_remove(&clock
->reset_notifiers
, notifier
);
461 void init_clocks(void)
463 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
464 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
465 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
468 uint64_t qemu_timer_expire_time_ns(QEMUTimer
*ts
)
470 return qemu_timer_pending(ts
) ? ts
->expire_time
: -1;
473 void qemu_run_all_timers(void)
475 alarm_timer
->pending
= 0;
477 /* rearm timer, if not periodic */
478 if (alarm_timer
->expired
) {
479 alarm_timer
->expired
= 0;
480 qemu_rearm_alarm_timer(alarm_timer
);
484 qemu_run_timers(vm_clock
);
485 qemu_run_timers(rt_clock
);
486 qemu_run_timers(host_clock
);
490 static void CALLBACK
host_alarm_handler(PVOID lpParam
, BOOLEAN unused
)
492 static void host_alarm_handler(int host_signum
)
495 struct qemu_alarm_timer
*t
= alarm_timer
;
500 #define DISP_FREQ 1000
502 static int64_t delta_min
= INT64_MAX
;
503 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
505 ti
= qemu_get_clock_ns(vm_clock
);
506 if (last_clock
!= 0) {
507 delta
= ti
- last_clock
;
508 if (delta
< delta_min
)
510 if (delta
> delta_max
)
513 if (++count
== DISP_FREQ
) {
514 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
515 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
516 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
517 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
518 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
520 delta_min
= INT64_MAX
;
528 if (alarm_has_dynticks(t
) ||
529 qemu_next_alarm_deadline () <= 0) {
530 t
->expired
= alarm_has_dynticks(t
);
536 #if defined(__linux__)
538 #include "compatfd.h"
540 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
544 struct sigaction act
;
546 sigfillset(&act
.sa_mask
);
548 act
.sa_handler
= host_alarm_handler
;
550 sigaction(SIGALRM
, &act
, NULL
);
553 * Initialize ev struct to 0 to avoid valgrind complaining
554 * about uninitialized data in timer_create call
556 memset(&ev
, 0, sizeof(ev
));
557 ev
.sigev_value
.sival_int
= 0;
558 ev
.sigev_notify
= SIGEV_SIGNAL
;
559 #ifdef SIGEV_THREAD_ID
560 if (qemu_signalfd_available()) {
561 ev
.sigev_notify
= SIGEV_THREAD_ID
;
562 ev
._sigev_un
._tid
= qemu_get_thread_id();
564 #endif /* SIGEV_THREAD_ID */
565 ev
.sigev_signo
= SIGALRM
;
567 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
568 perror("timer_create");
570 /* disable dynticks */
571 fprintf(stderr
, "Dynamic Ticks disabled\n");
576 t
->timer
= host_timer
;
581 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
583 timer_t host_timer
= t
->timer
;
585 timer_delete(host_timer
);
588 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
,
589 int64_t nearest_delta_ns
)
591 timer_t host_timer
= t
->timer
;
592 struct itimerspec timeout
;
595 if (nearest_delta_ns
< MIN_TIMER_REARM_NS
)
596 nearest_delta_ns
= MIN_TIMER_REARM_NS
;
598 /* check whether a timer is already running */
599 if (timer_gettime(host_timer
, &timeout
)) {
601 fprintf(stderr
, "Internal timer error: aborting\n");
604 current_ns
= timeout
.it_value
.tv_sec
* 1000000000LL + timeout
.it_value
.tv_nsec
;
605 if (current_ns
&& current_ns
<= nearest_delta_ns
)
608 timeout
.it_interval
.tv_sec
= 0;
609 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
610 timeout
.it_value
.tv_sec
= nearest_delta_ns
/ 1000000000;
611 timeout
.it_value
.tv_nsec
= nearest_delta_ns
% 1000000000;
612 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
614 fprintf(stderr
, "Internal timer error: aborting\n");
619 #endif /* defined(__linux__) */
623 static int unix_start_timer(struct qemu_alarm_timer
*t
)
625 struct sigaction act
;
628 sigfillset(&act
.sa_mask
);
630 act
.sa_handler
= host_alarm_handler
;
632 sigaction(SIGALRM
, &act
, NULL
);
636 static void unix_rearm_timer(struct qemu_alarm_timer
*t
,
637 int64_t nearest_delta_ns
)
639 struct itimerval itv
;
642 if (nearest_delta_ns
< MIN_TIMER_REARM_NS
)
643 nearest_delta_ns
= MIN_TIMER_REARM_NS
;
645 itv
.it_interval
.tv_sec
= 0;
646 itv
.it_interval
.tv_usec
= 0; /* 0 for one-shot timer */
647 itv
.it_value
.tv_sec
= nearest_delta_ns
/ 1000000000;
648 itv
.it_value
.tv_usec
= (nearest_delta_ns
% 1000000000) / 1000;
649 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
652 fprintf(stderr
, "Internal timer error: aborting\n");
657 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
659 struct itimerval itv
;
661 memset(&itv
, 0, sizeof(itv
));
662 setitimer(ITIMER_REAL
, &itv
, NULL
);
665 #endif /* !defined(_WIN32) */
670 static MMRESULT mm_timer
;
671 static unsigned mm_period
;
673 static void CALLBACK
mm_alarm_handler(UINT uTimerID
, UINT uMsg
,
674 DWORD_PTR dwUser
, DWORD_PTR dw1
,
677 struct qemu_alarm_timer
*t
= alarm_timer
;
681 if (alarm_has_dynticks(t
) || qemu_next_alarm_deadline() <= 0) {
682 t
->expired
= alarm_has_dynticks(t
);
688 static int mm_start_timer(struct qemu_alarm_timer
*t
)
693 memset(&tc
, 0, sizeof(tc
));
694 timeGetDevCaps(&tc
, sizeof(tc
));
696 mm_period
= tc
.wPeriodMin
;
697 timeBeginPeriod(mm_period
);
699 flags
= TIME_CALLBACK_FUNCTION
;
700 if (alarm_has_dynticks(t
)) {
701 flags
|= TIME_ONESHOT
;
703 flags
|= TIME_PERIODIC
;
706 mm_timer
= timeSetEvent(1, /* interval (ms) */
707 mm_period
, /* resolution */
708 mm_alarm_handler
, /* function */
709 (DWORD_PTR
)t
, /* parameter */
713 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
715 timeEndPeriod(mm_period
);
722 static void mm_stop_timer(struct qemu_alarm_timer
*t
)
724 timeKillEvent(mm_timer
);
725 timeEndPeriod(mm_period
);
728 static void mm_rearm_timer(struct qemu_alarm_timer
*t
, int64_t delta
)
730 int nearest_delta_ms
= (delta
+ 999999) / 1000000;
731 if (nearest_delta_ms
< 1) {
732 nearest_delta_ms
= 1;
735 timeKillEvent(mm_timer
);
736 mm_timer
= timeSetEvent(nearest_delta_ms
,
740 TIME_ONESHOT
| TIME_CALLBACK_FUNCTION
);
743 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
746 timeEndPeriod(mm_period
);
751 static int win32_start_timer(struct qemu_alarm_timer
*t
)
756 /* If you call ChangeTimerQueueTimer on a one-shot timer (its period
757 is zero) that has already expired, the timer is not updated. Since
758 creating a new timer is relatively expensive, set a bogus one-hour
759 interval in the dynticks case. */
760 success
= CreateTimerQueueTimer(&hTimer
,
765 alarm_has_dynticks(t
) ? 3600000 : 1,
766 WT_EXECUTEINTIMERTHREAD
);
769 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
778 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
780 HANDLE hTimer
= t
->timer
;
783 DeleteTimerQueueTimer(NULL
, hTimer
, NULL
);
787 static void win32_rearm_timer(struct qemu_alarm_timer
*t
,
788 int64_t nearest_delta_ns
)
790 HANDLE hTimer
= t
->timer
;
791 int nearest_delta_ms
;
794 nearest_delta_ms
= (nearest_delta_ns
+ 999999) / 1000000;
795 if (nearest_delta_ms
< 1) {
796 nearest_delta_ms
= 1;
798 success
= ChangeTimerQueueTimer(NULL
,
804 fprintf(stderr
, "Failed to rearm win32 alarm timer: %ld\n",
813 static void quit_timers(void)
815 struct qemu_alarm_timer
*t
= alarm_timer
;
820 int init_timer_alarm(void)
822 struct qemu_alarm_timer
*t
= NULL
;
825 for (i
= 0; alarm_timers
[i
].name
; i
++) {
826 t
= &alarm_timers
[i
];
838 /* first event is at time 0 */
849 int qemu_calculate_timeout(void)