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
25 #include "qemu/osdep.h"
26 #include "qemu-common.h"
27 #include "qemu/config-file.h"
28 #include "qemu/cutils.h"
29 #include "migration/vmstate.h"
30 #include "monitor/monitor.h"
31 #include "qapi/error.h"
32 #include "qapi/qapi-commands-misc.h"
33 #include "qapi/qapi-events-run-state.h"
34 #include "qapi/qmp/qerror.h"
35 #include "qemu/error-report.h"
36 #include "qemu/qemu-print.h"
37 #include "sysemu/tcg.h"
38 #include "sysemu/block-backend.h"
39 #include "exec/gdbstub.h"
40 #include "sysemu/dma.h"
41 #include "sysemu/hw_accel.h"
42 #include "sysemu/kvm.h"
43 #include "sysemu/hax.h"
44 #include "sysemu/hvf.h"
45 #include "sysemu/whpx.h"
46 #include "exec/exec-all.h"
48 #include "qemu/thread.h"
49 #include "qemu/plugin.h"
50 #include "sysemu/cpus.h"
51 #include "sysemu/qtest.h"
52 #include "qemu/main-loop.h"
53 #include "qemu/option.h"
54 #include "qemu/bitmap.h"
55 #include "qemu/seqlock.h"
56 #include "qemu/guest-random.h"
59 #include "sysemu/replay.h"
60 #include "sysemu/runstate.h"
61 #include "hw/boards.h"
64 #include "sysemu/cpu-throttle.h"
68 #include <sys/prctl.h>
71 #define PR_MCE_KILL 33
74 #ifndef PR_MCE_KILL_SET
75 #define PR_MCE_KILL_SET 1
78 #ifndef PR_MCE_KILL_EARLY
79 #define PR_MCE_KILL_EARLY 1
82 #endif /* CONFIG_LINUX */
84 static QemuMutex qemu_global_mutex
;
89 bool cpu_is_stopped(CPUState
*cpu
)
91 return cpu
->stopped
|| !runstate_is_running();
94 static inline bool cpu_work_list_empty(CPUState
*cpu
)
98 qemu_mutex_lock(&cpu
->work_mutex
);
99 ret
= QSIMPLEQ_EMPTY(&cpu
->work_list
);
100 qemu_mutex_unlock(&cpu
->work_mutex
);
104 static bool cpu_thread_is_idle(CPUState
*cpu
)
106 if (cpu
->stop
|| !cpu_work_list_empty(cpu
)) {
109 if (cpu_is_stopped(cpu
)) {
112 if (!cpu
->halted
|| cpu_has_work(cpu
) ||
113 kvm_halt_in_kernel()) {
119 static bool all_cpu_threads_idle(void)
124 if (!cpu_thread_is_idle(cpu
)) {
131 /***********************************************************/
132 /* guest cycle counter */
134 /* Protected by TimersState seqlock */
136 static bool icount_sleep
= true;
137 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
138 #define MAX_ICOUNT_SHIFT 10
140 typedef struct TimersState
{
141 /* Protected by BQL. */
142 int64_t cpu_ticks_prev
;
143 int64_t cpu_ticks_offset
;
145 /* Protect fields that can be respectively read outside the
146 * BQL, and written from multiple threads.
148 QemuSeqLock vm_clock_seqlock
;
149 QemuSpin vm_clock_lock
;
151 int16_t cpu_ticks_enabled
;
153 /* Conversion factor from emulated instructions to virtual clock ticks. */
154 int16_t icount_time_shift
;
156 /* Compensate for varying guest execution speed. */
157 int64_t qemu_icount_bias
;
159 int64_t vm_clock_warp_start
;
160 int64_t cpu_clock_offset
;
162 /* Only written by TCG thread */
165 /* for adjusting icount */
166 QEMUTimer
*icount_rt_timer
;
167 QEMUTimer
*icount_vm_timer
;
168 QEMUTimer
*icount_warp_timer
;
171 static TimersState timers_state
;
175 /* The current number of executed instructions is based on what we
176 * originally budgeted minus the current state of the decrementing
177 * icount counters in extra/u16.low.
179 static int64_t cpu_get_icount_executed(CPUState
*cpu
)
181 return (cpu
->icount_budget
-
182 (cpu_neg(cpu
)->icount_decr
.u16
.low
+ cpu
->icount_extra
));
186 * Update the global shared timer_state.qemu_icount to take into
187 * account executed instructions. This is done by the TCG vCPU
188 * thread so the main-loop can see time has moved forward.
190 static void cpu_update_icount_locked(CPUState
*cpu
)
192 int64_t executed
= cpu_get_icount_executed(cpu
);
193 cpu
->icount_budget
-= executed
;
195 atomic_set_i64(&timers_state
.qemu_icount
,
196 timers_state
.qemu_icount
+ executed
);
200 * Update the global shared timer_state.qemu_icount to take into
201 * account executed instructions. This is done by the TCG vCPU
202 * thread so the main-loop can see time has moved forward.
204 void cpu_update_icount(CPUState
*cpu
)
206 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
207 &timers_state
.vm_clock_lock
);
208 cpu_update_icount_locked(cpu
);
209 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
210 &timers_state
.vm_clock_lock
);
213 static int64_t cpu_get_icount_raw_locked(void)
215 CPUState
*cpu
= current_cpu
;
217 if (cpu
&& cpu
->running
) {
218 if (!cpu
->can_do_io
) {
219 error_report("Bad icount read");
222 /* Take into account what has run */
223 cpu_update_icount_locked(cpu
);
225 /* The read is protected by the seqlock, but needs atomic64 to avoid UB */
226 return atomic_read_i64(&timers_state
.qemu_icount
);
229 static int64_t cpu_get_icount_locked(void)
231 int64_t icount
= cpu_get_icount_raw_locked();
232 return atomic_read_i64(&timers_state
.qemu_icount_bias
) +
233 cpu_icount_to_ns(icount
);
236 int64_t cpu_get_icount_raw(void)
242 start
= seqlock_read_begin(&timers_state
.vm_clock_seqlock
);
243 icount
= cpu_get_icount_raw_locked();
244 } while (seqlock_read_retry(&timers_state
.vm_clock_seqlock
, start
));
249 /* Return the virtual CPU time, based on the instruction counter. */
250 int64_t cpu_get_icount(void)
256 start
= seqlock_read_begin(&timers_state
.vm_clock_seqlock
);
257 icount
= cpu_get_icount_locked();
258 } while (seqlock_read_retry(&timers_state
.vm_clock_seqlock
, start
));
263 int64_t cpu_icount_to_ns(int64_t icount
)
265 return icount
<< atomic_read(&timers_state
.icount_time_shift
);
268 static int64_t cpu_get_ticks_locked(void)
270 int64_t ticks
= timers_state
.cpu_ticks_offset
;
271 if (timers_state
.cpu_ticks_enabled
) {
272 ticks
+= cpu_get_host_ticks();
275 if (timers_state
.cpu_ticks_prev
> ticks
) {
276 /* Non increasing ticks may happen if the host uses software suspend. */
277 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
278 ticks
= timers_state
.cpu_ticks_prev
;
281 timers_state
.cpu_ticks_prev
= ticks
;
285 /* return the time elapsed in VM between vm_start and vm_stop. Unless
286 * icount is active, cpu_get_ticks() uses units of the host CPU cycle
289 int64_t cpu_get_ticks(void)
294 return cpu_get_icount();
297 qemu_spin_lock(&timers_state
.vm_clock_lock
);
298 ticks
= cpu_get_ticks_locked();
299 qemu_spin_unlock(&timers_state
.vm_clock_lock
);
303 static int64_t cpu_get_clock_locked(void)
307 time
= timers_state
.cpu_clock_offset
;
308 if (timers_state
.cpu_ticks_enabled
) {
315 /* Return the monotonic time elapsed in VM, i.e.,
316 * the time between vm_start and vm_stop
318 int64_t cpu_get_clock(void)
324 start
= seqlock_read_begin(&timers_state
.vm_clock_seqlock
);
325 ti
= cpu_get_clock_locked();
326 } while (seqlock_read_retry(&timers_state
.vm_clock_seqlock
, start
));
331 /* enable cpu_get_ticks()
332 * Caller must hold BQL which serves as mutex for vm_clock_seqlock.
334 void cpu_enable_ticks(void)
336 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
337 &timers_state
.vm_clock_lock
);
338 if (!timers_state
.cpu_ticks_enabled
) {
339 timers_state
.cpu_ticks_offset
-= cpu_get_host_ticks();
340 timers_state
.cpu_clock_offset
-= get_clock();
341 timers_state
.cpu_ticks_enabled
= 1;
343 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
344 &timers_state
.vm_clock_lock
);
347 /* disable cpu_get_ticks() : the clock is stopped. You must not call
348 * cpu_get_ticks() after that.
349 * Caller must hold BQL which serves as mutex for vm_clock_seqlock.
351 void cpu_disable_ticks(void)
353 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
354 &timers_state
.vm_clock_lock
);
355 if (timers_state
.cpu_ticks_enabled
) {
356 timers_state
.cpu_ticks_offset
+= cpu_get_host_ticks();
357 timers_state
.cpu_clock_offset
= cpu_get_clock_locked();
358 timers_state
.cpu_ticks_enabled
= 0;
360 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
361 &timers_state
.vm_clock_lock
);
364 /* Correlation between real and virtual time is always going to be
365 fairly approximate, so ignore small variation.
366 When the guest is idle real and virtual time will be aligned in
368 #define ICOUNT_WOBBLE (NANOSECONDS_PER_SECOND / 10)
370 static void icount_adjust(void)
376 /* Protected by TimersState mutex. */
377 static int64_t last_delta
;
379 /* If the VM is not running, then do nothing. */
380 if (!runstate_is_running()) {
384 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
385 &timers_state
.vm_clock_lock
);
386 cur_time
= REPLAY_CLOCK_LOCKED(REPLAY_CLOCK_VIRTUAL_RT
,
387 cpu_get_clock_locked());
388 cur_icount
= cpu_get_icount_locked();
390 delta
= cur_icount
- cur_time
;
391 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
393 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
394 && timers_state
.icount_time_shift
> 0) {
395 /* The guest is getting too far ahead. Slow time down. */
396 atomic_set(&timers_state
.icount_time_shift
,
397 timers_state
.icount_time_shift
- 1);
400 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
401 && timers_state
.icount_time_shift
< MAX_ICOUNT_SHIFT
) {
402 /* The guest is getting too far behind. Speed time up. */
403 atomic_set(&timers_state
.icount_time_shift
,
404 timers_state
.icount_time_shift
+ 1);
407 atomic_set_i64(&timers_state
.qemu_icount_bias
,
408 cur_icount
- (timers_state
.qemu_icount
409 << timers_state
.icount_time_shift
));
410 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
411 &timers_state
.vm_clock_lock
);
414 static void icount_adjust_rt(void *opaque
)
416 timer_mod(timers_state
.icount_rt_timer
,
417 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT
) + 1000);
421 static void icount_adjust_vm(void *opaque
)
423 timer_mod(timers_state
.icount_vm_timer
,
424 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
) +
425 NANOSECONDS_PER_SECOND
/ 10);
429 static int64_t qemu_icount_round(int64_t count
)
431 int shift
= atomic_read(&timers_state
.icount_time_shift
);
432 return (count
+ (1 << shift
) - 1) >> shift
;
435 static void icount_warp_rt(void)
440 /* The icount_warp_timer is rescheduled soon after vm_clock_warp_start
441 * changes from -1 to another value, so the race here is okay.
444 seq
= seqlock_read_begin(&timers_state
.vm_clock_seqlock
);
445 warp_start
= timers_state
.vm_clock_warp_start
;
446 } while (seqlock_read_retry(&timers_state
.vm_clock_seqlock
, seq
));
448 if (warp_start
== -1) {
452 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
453 &timers_state
.vm_clock_lock
);
454 if (runstate_is_running()) {
455 int64_t clock
= REPLAY_CLOCK_LOCKED(REPLAY_CLOCK_VIRTUAL_RT
,
456 cpu_get_clock_locked());
459 warp_delta
= clock
- timers_state
.vm_clock_warp_start
;
460 if (use_icount
== 2) {
462 * In adaptive mode, do not let QEMU_CLOCK_VIRTUAL run too
463 * far ahead of real time.
465 int64_t cur_icount
= cpu_get_icount_locked();
466 int64_t delta
= clock
- cur_icount
;
467 warp_delta
= MIN(warp_delta
, delta
);
469 atomic_set_i64(&timers_state
.qemu_icount_bias
,
470 timers_state
.qemu_icount_bias
+ warp_delta
);
472 timers_state
.vm_clock_warp_start
= -1;
473 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
474 &timers_state
.vm_clock_lock
);
476 if (qemu_clock_expired(QEMU_CLOCK_VIRTUAL
)) {
477 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
481 static void icount_timer_cb(void *opaque
)
483 /* No need for a checkpoint because the timer already synchronizes
484 * with CHECKPOINT_CLOCK_VIRTUAL_RT.
489 void qtest_clock_warp(int64_t dest
)
491 int64_t clock
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
);
492 AioContext
*aio_context
;
493 assert(qtest_enabled());
494 aio_context
= qemu_get_aio_context();
495 while (clock
< dest
) {
496 int64_t deadline
= qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL
,
497 QEMU_TIMER_ATTR_ALL
);
498 int64_t warp
= qemu_soonest_timeout(dest
- clock
, deadline
);
500 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
501 &timers_state
.vm_clock_lock
);
502 atomic_set_i64(&timers_state
.qemu_icount_bias
,
503 timers_state
.qemu_icount_bias
+ warp
);
504 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
505 &timers_state
.vm_clock_lock
);
507 qemu_clock_run_timers(QEMU_CLOCK_VIRTUAL
);
508 timerlist_run_timers(aio_context
->tlg
.tl
[QEMU_CLOCK_VIRTUAL
]);
509 clock
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
);
511 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
514 void qemu_start_warp_timer(void)
523 /* Nothing to do if the VM is stopped: QEMU_CLOCK_VIRTUAL timers
524 * do not fire, so computing the deadline does not make sense.
526 if (!runstate_is_running()) {
530 if (replay_mode
!= REPLAY_MODE_PLAY
) {
531 if (!all_cpu_threads_idle()) {
535 if (qtest_enabled()) {
536 /* When testing, qtest commands advance icount. */
540 replay_checkpoint(CHECKPOINT_CLOCK_WARP_START
);
542 /* warp clock deterministically in record/replay mode */
543 if (!replay_checkpoint(CHECKPOINT_CLOCK_WARP_START
)) {
544 /* vCPU is sleeping and warp can't be started.
545 It is probably a race condition: notification sent
546 to vCPU was processed in advance and vCPU went to sleep.
547 Therefore we have to wake it up for doing someting. */
548 if (replay_has_checkpoint()) {
549 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
555 /* We want to use the earliest deadline from ALL vm_clocks */
556 clock
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT
);
557 deadline
= qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL
,
558 ~QEMU_TIMER_ATTR_EXTERNAL
);
560 static bool notified
;
561 if (!icount_sleep
&& !notified
) {
562 warn_report("icount sleep disabled and no active timers");
570 * Ensure QEMU_CLOCK_VIRTUAL proceeds even when the virtual CPU goes to
571 * sleep. Otherwise, the CPU might be waiting for a future timer
572 * interrupt to wake it up, but the interrupt never comes because
573 * the vCPU isn't running any insns and thus doesn't advance the
574 * QEMU_CLOCK_VIRTUAL.
578 * We never let VCPUs sleep in no sleep icount mode.
579 * If there is a pending QEMU_CLOCK_VIRTUAL timer we just advance
580 * to the next QEMU_CLOCK_VIRTUAL event and notify it.
581 * It is useful when we want a deterministic execution time,
582 * isolated from host latencies.
584 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
585 &timers_state
.vm_clock_lock
);
586 atomic_set_i64(&timers_state
.qemu_icount_bias
,
587 timers_state
.qemu_icount_bias
+ deadline
);
588 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
589 &timers_state
.vm_clock_lock
);
590 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
593 * We do stop VCPUs and only advance QEMU_CLOCK_VIRTUAL after some
594 * "real" time, (related to the time left until the next event) has
595 * passed. The QEMU_CLOCK_VIRTUAL_RT clock will do this.
596 * This avoids that the warps are visible externally; for example,
597 * you will not be sending network packets continuously instead of
600 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
601 &timers_state
.vm_clock_lock
);
602 if (timers_state
.vm_clock_warp_start
== -1
603 || timers_state
.vm_clock_warp_start
> clock
) {
604 timers_state
.vm_clock_warp_start
= clock
;
606 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
607 &timers_state
.vm_clock_lock
);
608 timer_mod_anticipate(timers_state
.icount_warp_timer
,
611 } else if (deadline
== 0) {
612 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
616 static void qemu_account_warp_timer(void)
618 if (!use_icount
|| !icount_sleep
) {
622 /* Nothing to do if the VM is stopped: QEMU_CLOCK_VIRTUAL timers
623 * do not fire, so computing the deadline does not make sense.
625 if (!runstate_is_running()) {
629 /* warp clock deterministically in record/replay mode */
630 if (!replay_checkpoint(CHECKPOINT_CLOCK_WARP_ACCOUNT
)) {
634 timer_del(timers_state
.icount_warp_timer
);
638 static bool icount_state_needed(void *opaque
)
643 static bool warp_timer_state_needed(void *opaque
)
645 TimersState
*s
= opaque
;
646 return s
->icount_warp_timer
!= NULL
;
649 static bool adjust_timers_state_needed(void *opaque
)
651 TimersState
*s
= opaque
;
652 return s
->icount_rt_timer
!= NULL
;
655 static bool shift_state_needed(void *opaque
)
657 return use_icount
== 2;
661 * Subsection for warp timer migration is optional, because may not be created
663 static const VMStateDescription icount_vmstate_warp_timer
= {
664 .name
= "timer/icount/warp_timer",
666 .minimum_version_id
= 1,
667 .needed
= warp_timer_state_needed
,
668 .fields
= (VMStateField
[]) {
669 VMSTATE_INT64(vm_clock_warp_start
, TimersState
),
670 VMSTATE_TIMER_PTR(icount_warp_timer
, TimersState
),
671 VMSTATE_END_OF_LIST()
675 static const VMStateDescription icount_vmstate_adjust_timers
= {
676 .name
= "timer/icount/timers",
678 .minimum_version_id
= 1,
679 .needed
= adjust_timers_state_needed
,
680 .fields
= (VMStateField
[]) {
681 VMSTATE_TIMER_PTR(icount_rt_timer
, TimersState
),
682 VMSTATE_TIMER_PTR(icount_vm_timer
, TimersState
),
683 VMSTATE_END_OF_LIST()
687 static const VMStateDescription icount_vmstate_shift
= {
688 .name
= "timer/icount/shift",
690 .minimum_version_id
= 1,
691 .needed
= shift_state_needed
,
692 .fields
= (VMStateField
[]) {
693 VMSTATE_INT16(icount_time_shift
, TimersState
),
694 VMSTATE_END_OF_LIST()
699 * This is a subsection for icount migration.
701 static const VMStateDescription icount_vmstate_timers
= {
702 .name
= "timer/icount",
704 .minimum_version_id
= 1,
705 .needed
= icount_state_needed
,
706 .fields
= (VMStateField
[]) {
707 VMSTATE_INT64(qemu_icount_bias
, TimersState
),
708 VMSTATE_INT64(qemu_icount
, TimersState
),
709 VMSTATE_END_OF_LIST()
711 .subsections
= (const VMStateDescription
*[]) {
712 &icount_vmstate_warp_timer
,
713 &icount_vmstate_adjust_timers
,
714 &icount_vmstate_shift
,
719 static const VMStateDescription vmstate_timers
= {
722 .minimum_version_id
= 1,
723 .fields
= (VMStateField
[]) {
724 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
726 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
727 VMSTATE_END_OF_LIST()
729 .subsections
= (const VMStateDescription
*[]) {
730 &icount_vmstate_timers
,
735 void cpu_ticks_init(void)
737 seqlock_init(&timers_state
.vm_clock_seqlock
);
738 qemu_spin_init(&timers_state
.vm_clock_lock
);
739 vmstate_register(NULL
, 0, &vmstate_timers
, &timers_state
);
743 void configure_icount(QemuOpts
*opts
, Error
**errp
)
745 const char *option
= qemu_opt_get(opts
, "shift");
746 bool sleep
= qemu_opt_get_bool(opts
, "sleep", true);
747 bool align
= qemu_opt_get_bool(opts
, "align", false);
748 long time_shift
= -1;
751 if (qemu_opt_get(opts
, "align") != NULL
) {
752 error_setg(errp
, "Please specify shift option when using align");
757 if (align
&& !sleep
) {
758 error_setg(errp
, "align=on and sleep=off are incompatible");
762 if (strcmp(option
, "auto") != 0) {
763 if (qemu_strtol(option
, NULL
, 0, &time_shift
) < 0
764 || time_shift
< 0 || time_shift
> MAX_ICOUNT_SHIFT
) {
765 error_setg(errp
, "icount: Invalid shift value");
768 } else if (icount_align_option
) {
769 error_setg(errp
, "shift=auto and align=on are incompatible");
771 } else if (!icount_sleep
) {
772 error_setg(errp
, "shift=auto and sleep=off are incompatible");
776 icount_sleep
= sleep
;
778 timers_state
.icount_warp_timer
= timer_new_ns(QEMU_CLOCK_VIRTUAL_RT
,
779 icount_timer_cb
, NULL
);
782 icount_align_option
= align
;
784 if (time_shift
>= 0) {
785 timers_state
.icount_time_shift
= time_shift
;
792 /* 125MIPS seems a reasonable initial guess at the guest speed.
793 It will be corrected fairly quickly anyway. */
794 timers_state
.icount_time_shift
= 3;
796 /* Have both realtime and virtual time triggers for speed adjustment.
797 The realtime trigger catches emulated time passing too slowly,
798 the virtual time trigger catches emulated time passing too fast.
799 Realtime triggers occur even when idle, so use them less frequently
801 timers_state
.vm_clock_warp_start
= -1;
802 timers_state
.icount_rt_timer
= timer_new_ms(QEMU_CLOCK_VIRTUAL_RT
,
803 icount_adjust_rt
, NULL
);
804 timer_mod(timers_state
.icount_rt_timer
,
805 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT
) + 1000);
806 timers_state
.icount_vm_timer
= timer_new_ns(QEMU_CLOCK_VIRTUAL
,
807 icount_adjust_vm
, NULL
);
808 timer_mod(timers_state
.icount_vm_timer
,
809 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
) +
810 NANOSECONDS_PER_SECOND
/ 10);
813 /***********************************************************/
814 /* TCG vCPU kick timer
816 * The kick timer is responsible for moving single threaded vCPU
817 * emulation on to the next vCPU. If more than one vCPU is running a
818 * timer event with force a cpu->exit so the next vCPU can get
821 * The timer is removed if all vCPUs are idle and restarted again once
822 * idleness is complete.
825 static QEMUTimer
*tcg_kick_vcpu_timer
;
826 static CPUState
*tcg_current_rr_cpu
;
828 #define TCG_KICK_PERIOD (NANOSECONDS_PER_SECOND / 10)
830 static inline int64_t qemu_tcg_next_kick(void)
832 return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
) + TCG_KICK_PERIOD
;
835 /* Kick the currently round-robin scheduled vCPU to next */
836 static void qemu_cpu_kick_rr_next_cpu(void)
840 cpu
= atomic_mb_read(&tcg_current_rr_cpu
);
844 } while (cpu
!= atomic_mb_read(&tcg_current_rr_cpu
));
847 /* Kick all RR vCPUs */
848 static void qemu_cpu_kick_rr_cpus(void)
857 static void do_nothing(CPUState
*cpu
, run_on_cpu_data unused
)
861 void qemu_timer_notify_cb(void *opaque
, QEMUClockType type
)
863 if (!use_icount
|| type
!= QEMU_CLOCK_VIRTUAL
) {
868 if (qemu_in_vcpu_thread()) {
869 /* A CPU is currently running; kick it back out to the
870 * tcg_cpu_exec() loop so it will recalculate its
871 * icount deadline immediately.
873 qemu_cpu_kick(current_cpu
);
874 } else if (first_cpu
) {
875 /* qemu_cpu_kick is not enough to kick a halted CPU out of
876 * qemu_tcg_wait_io_event. async_run_on_cpu, instead,
877 * causes cpu_thread_is_idle to return false. This way,
878 * handle_icount_deadline can run.
879 * If we have no CPUs at all for some reason, we don't
880 * need to do anything.
882 async_run_on_cpu(first_cpu
, do_nothing
, RUN_ON_CPU_NULL
);
886 static void kick_tcg_thread(void *opaque
)
888 timer_mod(tcg_kick_vcpu_timer
, qemu_tcg_next_kick());
889 qemu_cpu_kick_rr_next_cpu();
892 static void start_tcg_kick_timer(void)
894 assert(!mttcg_enabled
);
895 if (!tcg_kick_vcpu_timer
&& CPU_NEXT(first_cpu
)) {
896 tcg_kick_vcpu_timer
= timer_new_ns(QEMU_CLOCK_VIRTUAL
,
897 kick_tcg_thread
, NULL
);
899 if (tcg_kick_vcpu_timer
&& !timer_pending(tcg_kick_vcpu_timer
)) {
900 timer_mod(tcg_kick_vcpu_timer
, qemu_tcg_next_kick());
904 static void stop_tcg_kick_timer(void)
906 assert(!mttcg_enabled
);
907 if (tcg_kick_vcpu_timer
&& timer_pending(tcg_kick_vcpu_timer
)) {
908 timer_del(tcg_kick_vcpu_timer
);
912 /***********************************************************/
913 void hw_error(const char *fmt
, ...)
919 fprintf(stderr
, "qemu: hardware error: ");
920 vfprintf(stderr
, fmt
, ap
);
921 fprintf(stderr
, "\n");
923 fprintf(stderr
, "CPU #%d:\n", cpu
->cpu_index
);
924 cpu_dump_state(cpu
, stderr
, CPU_DUMP_FPU
);
930 void cpu_synchronize_all_states(void)
935 cpu_synchronize_state(cpu
);
939 void cpu_synchronize_all_post_reset(void)
944 cpu_synchronize_post_reset(cpu
);
948 void cpu_synchronize_all_post_init(void)
953 cpu_synchronize_post_init(cpu
);
957 void cpu_synchronize_all_pre_loadvm(void)
962 cpu_synchronize_pre_loadvm(cpu
);
966 static int do_vm_stop(RunState state
, bool send_stop
)
970 if (runstate_is_running()) {
974 vm_state_notify(0, state
);
976 qapi_event_send_stop();
981 ret
= bdrv_flush_all();
986 /* Special vm_stop() variant for terminating the process. Historically clients
987 * did not expect a QMP STOP event and so we need to retain compatibility.
989 int vm_shutdown(void)
991 return do_vm_stop(RUN_STATE_SHUTDOWN
, false);
994 static bool cpu_can_run(CPUState
*cpu
)
999 if (cpu_is_stopped(cpu
)) {
1005 static void cpu_handle_guest_debug(CPUState
*cpu
)
1007 gdb_set_stop_cpu(cpu
);
1008 qemu_system_debug_request();
1009 cpu
->stopped
= true;
1013 static void sigbus_reraise(void)
1016 struct sigaction action
;
1018 memset(&action
, 0, sizeof(action
));
1019 action
.sa_handler
= SIG_DFL
;
1020 if (!sigaction(SIGBUS
, &action
, NULL
)) {
1023 sigaddset(&set
, SIGBUS
);
1024 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
1026 perror("Failed to re-raise SIGBUS!\n");
1030 static void sigbus_handler(int n
, siginfo_t
*siginfo
, void *ctx
)
1032 if (siginfo
->si_code
!= BUS_MCEERR_AO
&& siginfo
->si_code
!= BUS_MCEERR_AR
) {
1037 /* Called asynchronously in VCPU thread. */
1038 if (kvm_on_sigbus_vcpu(current_cpu
, siginfo
->si_code
, siginfo
->si_addr
)) {
1042 /* Called synchronously (via signalfd) in main thread. */
1043 if (kvm_on_sigbus(siginfo
->si_code
, siginfo
->si_addr
)) {
1049 static void qemu_init_sigbus(void)
1051 struct sigaction action
;
1053 memset(&action
, 0, sizeof(action
));
1054 action
.sa_flags
= SA_SIGINFO
;
1055 action
.sa_sigaction
= sigbus_handler
;
1056 sigaction(SIGBUS
, &action
, NULL
);
1058 prctl(PR_MCE_KILL
, PR_MCE_KILL_SET
, PR_MCE_KILL_EARLY
, 0, 0);
1060 #else /* !CONFIG_LINUX */
1061 static void qemu_init_sigbus(void)
1064 #endif /* !CONFIG_LINUX */
1066 static QemuThread io_thread
;
1069 static QemuCond qemu_cpu_cond
;
1071 static QemuCond qemu_pause_cond
;
1073 void qemu_init_cpu_loop(void)
1076 qemu_cond_init(&qemu_cpu_cond
);
1077 qemu_cond_init(&qemu_pause_cond
);
1078 qemu_mutex_init(&qemu_global_mutex
);
1080 qemu_thread_get_self(&io_thread
);
1083 void run_on_cpu(CPUState
*cpu
, run_on_cpu_func func
, run_on_cpu_data data
)
1085 do_run_on_cpu(cpu
, func
, data
, &qemu_global_mutex
);
1088 static void qemu_kvm_destroy_vcpu(CPUState
*cpu
)
1090 if (kvm_destroy_vcpu(cpu
) < 0) {
1091 error_report("kvm_destroy_vcpu failed");
1096 static void qemu_tcg_destroy_vcpu(CPUState
*cpu
)
1100 static void qemu_cpu_stop(CPUState
*cpu
, bool exit
)
1102 g_assert(qemu_cpu_is_self(cpu
));
1104 cpu
->stopped
= true;
1108 qemu_cond_broadcast(&qemu_pause_cond
);
1111 static void qemu_wait_io_event_common(CPUState
*cpu
)
1113 atomic_mb_set(&cpu
->thread_kicked
, false);
1115 qemu_cpu_stop(cpu
, false);
1117 process_queued_cpu_work(cpu
);
1120 static void qemu_tcg_rr_wait_io_event(void)
1124 while (all_cpu_threads_idle()) {
1125 stop_tcg_kick_timer();
1126 qemu_cond_wait(first_cpu
->halt_cond
, &qemu_global_mutex
);
1129 start_tcg_kick_timer();
1132 qemu_wait_io_event_common(cpu
);
1136 static void qemu_wait_io_event(CPUState
*cpu
)
1140 while (cpu_thread_is_idle(cpu
)) {
1143 qemu_plugin_vcpu_idle_cb(cpu
);
1145 qemu_cond_wait(cpu
->halt_cond
, &qemu_global_mutex
);
1148 qemu_plugin_vcpu_resume_cb(cpu
);
1152 /* Eat dummy APC queued by qemu_cpu_kick_thread. */
1153 if (!tcg_enabled()) {
1157 qemu_wait_io_event_common(cpu
);
1160 static void *qemu_kvm_cpu_thread_fn(void *arg
)
1162 CPUState
*cpu
= arg
;
1165 rcu_register_thread();
1167 qemu_mutex_lock_iothread();
1168 qemu_thread_get_self(cpu
->thread
);
1169 cpu
->thread_id
= qemu_get_thread_id();
1173 r
= kvm_init_vcpu(cpu
);
1175 error_report("kvm_init_vcpu failed: %s", strerror(-r
));
1179 kvm_init_cpu_signals(cpu
);
1181 /* signal CPU creation */
1182 cpu
->created
= true;
1183 qemu_cond_signal(&qemu_cpu_cond
);
1184 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1187 if (cpu_can_run(cpu
)) {
1188 r
= kvm_cpu_exec(cpu
);
1189 if (r
== EXCP_DEBUG
) {
1190 cpu_handle_guest_debug(cpu
);
1193 qemu_wait_io_event(cpu
);
1194 } while (!cpu
->unplug
|| cpu_can_run(cpu
));
1196 qemu_kvm_destroy_vcpu(cpu
);
1197 cpu
->created
= false;
1198 qemu_cond_signal(&qemu_cpu_cond
);
1199 qemu_mutex_unlock_iothread();
1200 rcu_unregister_thread();
1204 static void *qemu_dummy_cpu_thread_fn(void *arg
)
1207 error_report("qtest is not supported under Windows");
1210 CPUState
*cpu
= arg
;
1214 rcu_register_thread();
1216 qemu_mutex_lock_iothread();
1217 qemu_thread_get_self(cpu
->thread
);
1218 cpu
->thread_id
= qemu_get_thread_id();
1222 sigemptyset(&waitset
);
1223 sigaddset(&waitset
, SIG_IPI
);
1225 /* signal CPU creation */
1226 cpu
->created
= true;
1227 qemu_cond_signal(&qemu_cpu_cond
);
1228 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1231 qemu_mutex_unlock_iothread();
1234 r
= sigwait(&waitset
, &sig
);
1235 } while (r
== -1 && (errno
== EAGAIN
|| errno
== EINTR
));
1240 qemu_mutex_lock_iothread();
1241 qemu_wait_io_event(cpu
);
1242 } while (!cpu
->unplug
);
1244 qemu_mutex_unlock_iothread();
1245 rcu_unregister_thread();
1250 static int64_t tcg_get_icount_limit(void)
1254 if (replay_mode
!= REPLAY_MODE_PLAY
) {
1256 * Include all the timers, because they may need an attention.
1257 * Too long CPU execution may create unnecessary delay in UI.
1259 deadline
= qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL
,
1260 QEMU_TIMER_ATTR_ALL
);
1261 /* Check realtime timers, because they help with input processing */
1262 deadline
= qemu_soonest_timeout(deadline
,
1263 qemu_clock_deadline_ns_all(QEMU_CLOCK_REALTIME
,
1264 QEMU_TIMER_ATTR_ALL
));
1266 /* Maintain prior (possibly buggy) behaviour where if no deadline
1267 * was set (as there is no QEMU_CLOCK_VIRTUAL timer) or it is more than
1268 * INT32_MAX nanoseconds ahead, we still use INT32_MAX
1271 if ((deadline
< 0) || (deadline
> INT32_MAX
)) {
1272 deadline
= INT32_MAX
;
1275 return qemu_icount_round(deadline
);
1277 return replay_get_instructions();
1281 static void notify_aio_contexts(void)
1283 /* Wake up other AioContexts. */
1284 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
1285 qemu_clock_run_timers(QEMU_CLOCK_VIRTUAL
);
1288 static void handle_icount_deadline(void)
1290 assert(qemu_in_vcpu_thread());
1292 int64_t deadline
= qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL
,
1293 QEMU_TIMER_ATTR_ALL
);
1295 if (deadline
== 0) {
1296 notify_aio_contexts();
1301 static void prepare_icount_for_run(CPUState
*cpu
)
1306 /* These should always be cleared by process_icount_data after
1307 * each vCPU execution. However u16.high can be raised
1308 * asynchronously by cpu_exit/cpu_interrupt/tcg_handle_interrupt
1310 g_assert(cpu_neg(cpu
)->icount_decr
.u16
.low
== 0);
1311 g_assert(cpu
->icount_extra
== 0);
1313 cpu
->icount_budget
= tcg_get_icount_limit();
1314 insns_left
= MIN(0xffff, cpu
->icount_budget
);
1315 cpu_neg(cpu
)->icount_decr
.u16
.low
= insns_left
;
1316 cpu
->icount_extra
= cpu
->icount_budget
- insns_left
;
1318 replay_mutex_lock();
1320 if (cpu
->icount_budget
== 0 && replay_has_checkpoint()) {
1321 notify_aio_contexts();
1326 static void process_icount_data(CPUState
*cpu
)
1329 /* Account for executed instructions */
1330 cpu_update_icount(cpu
);
1332 /* Reset the counters */
1333 cpu_neg(cpu
)->icount_decr
.u16
.low
= 0;
1334 cpu
->icount_extra
= 0;
1335 cpu
->icount_budget
= 0;
1337 replay_account_executed_instructions();
1339 replay_mutex_unlock();
1344 static int tcg_cpu_exec(CPUState
*cpu
)
1347 #ifdef CONFIG_PROFILER
1351 assert(tcg_enabled());
1352 #ifdef CONFIG_PROFILER
1353 ti
= profile_getclock();
1355 cpu_exec_start(cpu
);
1356 ret
= cpu_exec(cpu
);
1358 #ifdef CONFIG_PROFILER
1359 atomic_set(&tcg_ctx
->prof
.cpu_exec_time
,
1360 tcg_ctx
->prof
.cpu_exec_time
+ profile_getclock() - ti
);
1365 /* Destroy any remaining vCPUs which have been unplugged and have
1368 static void deal_with_unplugged_cpus(void)
1373 if (cpu
->unplug
&& !cpu_can_run(cpu
)) {
1374 qemu_tcg_destroy_vcpu(cpu
);
1375 cpu
->created
= false;
1376 qemu_cond_signal(&qemu_cpu_cond
);
1382 /* Single-threaded TCG
1384 * In the single-threaded case each vCPU is simulated in turn. If
1385 * there is more than a single vCPU we create a simple timer to kick
1386 * the vCPU and ensure we don't get stuck in a tight loop in one vCPU.
1387 * This is done explicitly rather than relying on side-effects
1391 static void *qemu_tcg_rr_cpu_thread_fn(void *arg
)
1393 CPUState
*cpu
= arg
;
1395 assert(tcg_enabled());
1396 rcu_register_thread();
1397 tcg_register_thread();
1399 qemu_mutex_lock_iothread();
1400 qemu_thread_get_self(cpu
->thread
);
1402 cpu
->thread_id
= qemu_get_thread_id();
1403 cpu
->created
= true;
1405 qemu_cond_signal(&qemu_cpu_cond
);
1406 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1408 /* wait for initial kick-off after machine start */
1409 while (first_cpu
->stopped
) {
1410 qemu_cond_wait(first_cpu
->halt_cond
, &qemu_global_mutex
);
1412 /* process any pending work */
1415 qemu_wait_io_event_common(cpu
);
1419 start_tcg_kick_timer();
1423 /* process any pending work */
1424 cpu
->exit_request
= 1;
1427 qemu_mutex_unlock_iothread();
1428 replay_mutex_lock();
1429 qemu_mutex_lock_iothread();
1430 /* Account partial waits to QEMU_CLOCK_VIRTUAL. */
1431 qemu_account_warp_timer();
1433 /* Run the timers here. This is much more efficient than
1434 * waking up the I/O thread and waiting for completion.
1436 handle_icount_deadline();
1438 replay_mutex_unlock();
1444 while (cpu
&& cpu_work_list_empty(cpu
) && !cpu
->exit_request
) {
1446 atomic_mb_set(&tcg_current_rr_cpu
, cpu
);
1449 qemu_clock_enable(QEMU_CLOCK_VIRTUAL
,
1450 (cpu
->singlestep_enabled
& SSTEP_NOTIMER
) == 0);
1452 if (cpu_can_run(cpu
)) {
1455 qemu_mutex_unlock_iothread();
1456 prepare_icount_for_run(cpu
);
1458 r
= tcg_cpu_exec(cpu
);
1460 process_icount_data(cpu
);
1461 qemu_mutex_lock_iothread();
1463 if (r
== EXCP_DEBUG
) {
1464 cpu_handle_guest_debug(cpu
);
1466 } else if (r
== EXCP_ATOMIC
) {
1467 qemu_mutex_unlock_iothread();
1468 cpu_exec_step_atomic(cpu
);
1469 qemu_mutex_lock_iothread();
1472 } else if (cpu
->stop
) {
1474 cpu
= CPU_NEXT(cpu
);
1479 cpu
= CPU_NEXT(cpu
);
1480 } /* while (cpu && !cpu->exit_request).. */
1482 /* Does not need atomic_mb_set because a spurious wakeup is okay. */
1483 atomic_set(&tcg_current_rr_cpu
, NULL
);
1485 if (cpu
&& cpu
->exit_request
) {
1486 atomic_mb_set(&cpu
->exit_request
, 0);
1489 if (use_icount
&& all_cpu_threads_idle()) {
1491 * When all cpus are sleeping (e.g in WFI), to avoid a deadlock
1492 * in the main_loop, wake it up in order to start the warp timer.
1494 qemu_notify_event();
1497 qemu_tcg_rr_wait_io_event();
1498 deal_with_unplugged_cpus();
1501 rcu_unregister_thread();
1505 static void *qemu_hax_cpu_thread_fn(void *arg
)
1507 CPUState
*cpu
= arg
;
1510 rcu_register_thread();
1511 qemu_mutex_lock_iothread();
1512 qemu_thread_get_self(cpu
->thread
);
1514 cpu
->thread_id
= qemu_get_thread_id();
1515 cpu
->created
= true;
1519 qemu_cond_signal(&qemu_cpu_cond
);
1520 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1523 if (cpu_can_run(cpu
)) {
1524 r
= hax_smp_cpu_exec(cpu
);
1525 if (r
== EXCP_DEBUG
) {
1526 cpu_handle_guest_debug(cpu
);
1530 qemu_wait_io_event(cpu
);
1531 } while (!cpu
->unplug
|| cpu_can_run(cpu
));
1532 rcu_unregister_thread();
1536 /* The HVF-specific vCPU thread function. This one should only run when the host
1537 * CPU supports the VMX "unrestricted guest" feature. */
1538 static void *qemu_hvf_cpu_thread_fn(void *arg
)
1540 CPUState
*cpu
= arg
;
1544 assert(hvf_enabled());
1546 rcu_register_thread();
1548 qemu_mutex_lock_iothread();
1549 qemu_thread_get_self(cpu
->thread
);
1551 cpu
->thread_id
= qemu_get_thread_id();
1557 /* signal CPU creation */
1558 cpu
->created
= true;
1559 qemu_cond_signal(&qemu_cpu_cond
);
1560 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1563 if (cpu_can_run(cpu
)) {
1564 r
= hvf_vcpu_exec(cpu
);
1565 if (r
== EXCP_DEBUG
) {
1566 cpu_handle_guest_debug(cpu
);
1569 qemu_wait_io_event(cpu
);
1570 } while (!cpu
->unplug
|| cpu_can_run(cpu
));
1572 hvf_vcpu_destroy(cpu
);
1573 cpu
->created
= false;
1574 qemu_cond_signal(&qemu_cpu_cond
);
1575 qemu_mutex_unlock_iothread();
1576 rcu_unregister_thread();
1580 static void *qemu_whpx_cpu_thread_fn(void *arg
)
1582 CPUState
*cpu
= arg
;
1585 rcu_register_thread();
1587 qemu_mutex_lock_iothread();
1588 qemu_thread_get_self(cpu
->thread
);
1589 cpu
->thread_id
= qemu_get_thread_id();
1592 r
= whpx_init_vcpu(cpu
);
1594 fprintf(stderr
, "whpx_init_vcpu failed: %s\n", strerror(-r
));
1598 /* signal CPU creation */
1599 cpu
->created
= true;
1600 qemu_cond_signal(&qemu_cpu_cond
);
1601 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1604 if (cpu_can_run(cpu
)) {
1605 r
= whpx_vcpu_exec(cpu
);
1606 if (r
== EXCP_DEBUG
) {
1607 cpu_handle_guest_debug(cpu
);
1610 while (cpu_thread_is_idle(cpu
)) {
1611 qemu_cond_wait(cpu
->halt_cond
, &qemu_global_mutex
);
1613 qemu_wait_io_event_common(cpu
);
1614 } while (!cpu
->unplug
|| cpu_can_run(cpu
));
1616 whpx_destroy_vcpu(cpu
);
1617 cpu
->created
= false;
1618 qemu_cond_signal(&qemu_cpu_cond
);
1619 qemu_mutex_unlock_iothread();
1620 rcu_unregister_thread();
1625 static void CALLBACK
dummy_apc_func(ULONG_PTR unused
)
1630 /* Multi-threaded TCG
1632 * In the multi-threaded case each vCPU has its own thread. The TLS
1633 * variable current_cpu can be used deep in the code to find the
1634 * current CPUState for a given thread.
1637 static void *qemu_tcg_cpu_thread_fn(void *arg
)
1639 CPUState
*cpu
= arg
;
1641 assert(tcg_enabled());
1642 g_assert(!use_icount
);
1644 rcu_register_thread();
1645 tcg_register_thread();
1647 qemu_mutex_lock_iothread();
1648 qemu_thread_get_self(cpu
->thread
);
1650 cpu
->thread_id
= qemu_get_thread_id();
1651 cpu
->created
= true;
1654 qemu_cond_signal(&qemu_cpu_cond
);
1655 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1657 /* process any pending work */
1658 cpu
->exit_request
= 1;
1661 if (cpu_can_run(cpu
)) {
1663 qemu_mutex_unlock_iothread();
1664 r
= tcg_cpu_exec(cpu
);
1665 qemu_mutex_lock_iothread();
1668 cpu_handle_guest_debug(cpu
);
1671 /* during start-up the vCPU is reset and the thread is
1672 * kicked several times. If we don't ensure we go back
1673 * to sleep in the halted state we won't cleanly
1674 * start-up when the vCPU is enabled.
1676 * cpu->halted should ensure we sleep in wait_io_event
1678 g_assert(cpu
->halted
);
1681 qemu_mutex_unlock_iothread();
1682 cpu_exec_step_atomic(cpu
);
1683 qemu_mutex_lock_iothread();
1685 /* Ignore everything else? */
1690 atomic_mb_set(&cpu
->exit_request
, 0);
1691 qemu_wait_io_event(cpu
);
1692 } while (!cpu
->unplug
|| cpu_can_run(cpu
));
1694 qemu_tcg_destroy_vcpu(cpu
);
1695 cpu
->created
= false;
1696 qemu_cond_signal(&qemu_cpu_cond
);
1697 qemu_mutex_unlock_iothread();
1698 rcu_unregister_thread();
1702 static void qemu_cpu_kick_thread(CPUState
*cpu
)
1707 if (cpu
->thread_kicked
) {
1710 cpu
->thread_kicked
= true;
1711 err
= pthread_kill(cpu
->thread
->thread
, SIG_IPI
);
1712 if (err
&& err
!= ESRCH
) {
1713 fprintf(stderr
, "qemu:%s: %s", __func__
, strerror(err
));
1717 if (!qemu_cpu_is_self(cpu
)) {
1718 if (whpx_enabled()) {
1719 whpx_vcpu_kick(cpu
);
1720 } else if (!QueueUserAPC(dummy_apc_func
, cpu
->hThread
, 0)) {
1721 fprintf(stderr
, "%s: QueueUserAPC failed with error %lu\n",
1722 __func__
, GetLastError());
1729 void qemu_cpu_kick(CPUState
*cpu
)
1731 qemu_cond_broadcast(cpu
->halt_cond
);
1732 if (tcg_enabled()) {
1733 if (qemu_tcg_mttcg_enabled()) {
1736 qemu_cpu_kick_rr_cpus();
1739 if (hax_enabled()) {
1741 * FIXME: race condition with the exit_request check in
1744 cpu
->exit_request
= 1;
1746 qemu_cpu_kick_thread(cpu
);
1750 void qemu_cpu_kick_self(void)
1752 assert(current_cpu
);
1753 qemu_cpu_kick_thread(current_cpu
);
1756 bool qemu_cpu_is_self(CPUState
*cpu
)
1758 return qemu_thread_is_self(cpu
->thread
);
1761 bool qemu_in_vcpu_thread(void)
1763 return current_cpu
&& qemu_cpu_is_self(current_cpu
);
1766 static __thread
bool iothread_locked
= false;
1768 bool qemu_mutex_iothread_locked(void)
1770 return iothread_locked
;
1774 * The BQL is taken from so many places that it is worth profiling the
1775 * callers directly, instead of funneling them all through a single function.
1777 void qemu_mutex_lock_iothread_impl(const char *file
, int line
)
1779 QemuMutexLockFunc bql_lock
= atomic_read(&qemu_bql_mutex_lock_func
);
1781 g_assert(!qemu_mutex_iothread_locked());
1782 bql_lock(&qemu_global_mutex
, file
, line
);
1783 iothread_locked
= true;
1786 void qemu_mutex_unlock_iothread(void)
1788 g_assert(qemu_mutex_iothread_locked());
1789 iothread_locked
= false;
1790 qemu_mutex_unlock(&qemu_global_mutex
);
1793 void qemu_cond_wait_iothread(QemuCond
*cond
)
1795 qemu_cond_wait(cond
, &qemu_global_mutex
);
1798 void qemu_cond_timedwait_iothread(QemuCond
*cond
, int ms
)
1800 qemu_cond_timedwait(cond
, &qemu_global_mutex
, ms
);
1803 static bool all_vcpus_paused(void)
1808 if (!cpu
->stopped
) {
1816 void pause_all_vcpus(void)
1820 qemu_clock_enable(QEMU_CLOCK_VIRTUAL
, false);
1822 if (qemu_cpu_is_self(cpu
)) {
1823 qemu_cpu_stop(cpu
, true);
1830 /* We need to drop the replay_lock so any vCPU threads woken up
1831 * can finish their replay tasks
1833 replay_mutex_unlock();
1835 while (!all_vcpus_paused()) {
1836 qemu_cond_wait(&qemu_pause_cond
, &qemu_global_mutex
);
1842 qemu_mutex_unlock_iothread();
1843 replay_mutex_lock();
1844 qemu_mutex_lock_iothread();
1847 void cpu_resume(CPUState
*cpu
)
1850 cpu
->stopped
= false;
1854 void resume_all_vcpus(void)
1858 if (!runstate_is_running()) {
1862 qemu_clock_enable(QEMU_CLOCK_VIRTUAL
, true);
1868 void cpu_remove_sync(CPUState
*cpu
)
1873 qemu_mutex_unlock_iothread();
1874 qemu_thread_join(cpu
->thread
);
1875 qemu_mutex_lock_iothread();
1878 /* For temporary buffers for forming a name */
1879 #define VCPU_THREAD_NAME_SIZE 16
1881 static void qemu_tcg_init_vcpu(CPUState
*cpu
)
1883 char thread_name
[VCPU_THREAD_NAME_SIZE
];
1884 static QemuCond
*single_tcg_halt_cond
;
1885 static QemuThread
*single_tcg_cpu_thread
;
1886 static int tcg_region_inited
;
1888 assert(tcg_enabled());
1890 * Initialize TCG regions--once. Now is a good time, because:
1891 * (1) TCG's init context, prologue and target globals have been set up.
1892 * (2) qemu_tcg_mttcg_enabled() works now (TCG init code runs before the
1893 * -accel flag is processed, so the check doesn't work then).
1895 if (!tcg_region_inited
) {
1896 tcg_region_inited
= 1;
1900 if (qemu_tcg_mttcg_enabled() || !single_tcg_cpu_thread
) {
1901 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
1902 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
1903 qemu_cond_init(cpu
->halt_cond
);
1905 if (qemu_tcg_mttcg_enabled()) {
1906 /* create a thread per vCPU with TCG (MTTCG) */
1907 parallel_cpus
= true;
1908 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/TCG",
1911 qemu_thread_create(cpu
->thread
, thread_name
, qemu_tcg_cpu_thread_fn
,
1912 cpu
, QEMU_THREAD_JOINABLE
);
1915 /* share a single thread for all cpus with TCG */
1916 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "ALL CPUs/TCG");
1917 qemu_thread_create(cpu
->thread
, thread_name
,
1918 qemu_tcg_rr_cpu_thread_fn
,
1919 cpu
, QEMU_THREAD_JOINABLE
);
1921 single_tcg_halt_cond
= cpu
->halt_cond
;
1922 single_tcg_cpu_thread
= cpu
->thread
;
1925 cpu
->hThread
= qemu_thread_get_handle(cpu
->thread
);
1928 /* For non-MTTCG cases we share the thread */
1929 cpu
->thread
= single_tcg_cpu_thread
;
1930 cpu
->halt_cond
= single_tcg_halt_cond
;
1931 cpu
->thread_id
= first_cpu
->thread_id
;
1933 cpu
->created
= true;
1937 static void qemu_hax_start_vcpu(CPUState
*cpu
)
1939 char thread_name
[VCPU_THREAD_NAME_SIZE
];
1941 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
1942 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
1943 qemu_cond_init(cpu
->halt_cond
);
1945 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/HAX",
1947 qemu_thread_create(cpu
->thread
, thread_name
, qemu_hax_cpu_thread_fn
,
1948 cpu
, QEMU_THREAD_JOINABLE
);
1950 cpu
->hThread
= qemu_thread_get_handle(cpu
->thread
);
1954 static void qemu_kvm_start_vcpu(CPUState
*cpu
)
1956 char thread_name
[VCPU_THREAD_NAME_SIZE
];
1958 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
1959 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
1960 qemu_cond_init(cpu
->halt_cond
);
1961 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/KVM",
1963 qemu_thread_create(cpu
->thread
, thread_name
, qemu_kvm_cpu_thread_fn
,
1964 cpu
, QEMU_THREAD_JOINABLE
);
1967 static void qemu_hvf_start_vcpu(CPUState
*cpu
)
1969 char thread_name
[VCPU_THREAD_NAME_SIZE
];
1971 /* HVF currently does not support TCG, and only runs in
1972 * unrestricted-guest mode. */
1973 assert(hvf_enabled());
1975 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
1976 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
1977 qemu_cond_init(cpu
->halt_cond
);
1979 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/HVF",
1981 qemu_thread_create(cpu
->thread
, thread_name
, qemu_hvf_cpu_thread_fn
,
1982 cpu
, QEMU_THREAD_JOINABLE
);
1985 static void qemu_whpx_start_vcpu(CPUState
*cpu
)
1987 char thread_name
[VCPU_THREAD_NAME_SIZE
];
1989 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
1990 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
1991 qemu_cond_init(cpu
->halt_cond
);
1992 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/WHPX",
1994 qemu_thread_create(cpu
->thread
, thread_name
, qemu_whpx_cpu_thread_fn
,
1995 cpu
, QEMU_THREAD_JOINABLE
);
1997 cpu
->hThread
= qemu_thread_get_handle(cpu
->thread
);
2001 static void qemu_dummy_start_vcpu(CPUState
*cpu
)
2003 char thread_name
[VCPU_THREAD_NAME_SIZE
];
2005 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
2006 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
2007 qemu_cond_init(cpu
->halt_cond
);
2008 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/DUMMY",
2010 qemu_thread_create(cpu
->thread
, thread_name
, qemu_dummy_cpu_thread_fn
, cpu
,
2011 QEMU_THREAD_JOINABLE
);
2014 void qemu_init_vcpu(CPUState
*cpu
)
2016 MachineState
*ms
= MACHINE(qdev_get_machine());
2018 cpu
->nr_cores
= ms
->smp
.cores
;
2019 cpu
->nr_threads
= ms
->smp
.threads
;
2020 cpu
->stopped
= true;
2021 cpu
->random_seed
= qemu_guest_random_seed_thread_part1();
2024 /* If the target cpu hasn't set up any address spaces itself,
2025 * give it the default one.
2028 cpu_address_space_init(cpu
, 0, "cpu-memory", cpu
->memory
);
2031 if (kvm_enabled()) {
2032 qemu_kvm_start_vcpu(cpu
);
2033 } else if (hax_enabled()) {
2034 qemu_hax_start_vcpu(cpu
);
2035 } else if (hvf_enabled()) {
2036 qemu_hvf_start_vcpu(cpu
);
2037 } else if (tcg_enabled()) {
2038 qemu_tcg_init_vcpu(cpu
);
2039 } else if (whpx_enabled()) {
2040 qemu_whpx_start_vcpu(cpu
);
2042 qemu_dummy_start_vcpu(cpu
);
2045 while (!cpu
->created
) {
2046 qemu_cond_wait(&qemu_cpu_cond
, &qemu_global_mutex
);
2050 void cpu_stop_current(void)
2053 current_cpu
->stop
= true;
2054 cpu_exit(current_cpu
);
2058 int vm_stop(RunState state
)
2060 if (qemu_in_vcpu_thread()) {
2061 qemu_system_vmstop_request_prepare();
2062 qemu_system_vmstop_request(state
);
2064 * FIXME: should not return to device code in case
2065 * vm_stop() has been requested.
2071 return do_vm_stop(state
, true);
2075 * Prepare for (re)starting the VM.
2076 * Returns -1 if the vCPUs are not to be restarted (e.g. if they are already
2077 * running or in case of an error condition), 0 otherwise.
2079 int vm_prepare_start(void)
2083 qemu_vmstop_requested(&requested
);
2084 if (runstate_is_running() && requested
== RUN_STATE__MAX
) {
2088 /* Ensure that a STOP/RESUME pair of events is emitted if a
2089 * vmstop request was pending. The BLOCK_IO_ERROR event, for
2090 * example, according to documentation is always followed by
2093 if (runstate_is_running()) {
2094 qapi_event_send_stop();
2095 qapi_event_send_resume();
2099 /* We are sending this now, but the CPUs will be resumed shortly later */
2100 qapi_event_send_resume();
2103 runstate_set(RUN_STATE_RUNNING
);
2104 vm_state_notify(1, RUN_STATE_RUNNING
);
2110 if (!vm_prepare_start()) {
2115 /* does a state transition even if the VM is already stopped,
2116 current state is forgotten forever */
2117 int vm_stop_force_state(RunState state
)
2119 if (runstate_is_running()) {
2120 return vm_stop(state
);
2122 runstate_set(state
);
2125 /* Make sure to return an error if the flush in a previous vm_stop()
2127 return bdrv_flush_all();
2131 void list_cpus(const char *optarg
)
2133 /* XXX: implement xxx_cpu_list for targets that still miss it */
2134 #if defined(cpu_list)
2139 void qmp_memsave(int64_t addr
, int64_t size
, const char *filename
,
2140 bool has_cpu
, int64_t cpu_index
, Error
**errp
)
2146 int64_t orig_addr
= addr
, orig_size
= size
;
2152 cpu
= qemu_get_cpu(cpu_index
);
2154 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cpu-index",
2159 f
= fopen(filename
, "wb");
2161 error_setg_file_open(errp
, errno
, filename
);
2169 if (cpu_memory_rw_debug(cpu
, addr
, buf
, l
, 0) != 0) {
2170 error_setg(errp
, "Invalid addr 0x%016" PRIx64
"/size %" PRId64
2171 " specified", orig_addr
, orig_size
);
2174 if (fwrite(buf
, 1, l
, f
) != l
) {
2175 error_setg(errp
, QERR_IO_ERROR
);
2186 void qmp_pmemsave(int64_t addr
, int64_t size
, const char *filename
,
2193 f
= fopen(filename
, "wb");
2195 error_setg_file_open(errp
, errno
, filename
);
2203 cpu_physical_memory_read(addr
, buf
, l
);
2204 if (fwrite(buf
, 1, l
, f
) != l
) {
2205 error_setg(errp
, QERR_IO_ERROR
);
2216 void qmp_inject_nmi(Error
**errp
)
2218 nmi_monitor_handle(monitor_get_cpu_index(), errp
);
2221 void dump_drift_info(void)
2227 qemu_printf("Host - Guest clock %"PRIi64
" ms\n",
2228 (cpu_get_clock() - cpu_get_icount())/SCALE_MS
);
2229 if (icount_align_option
) {
2230 qemu_printf("Max guest delay %"PRIi64
" ms\n",
2231 -max_delay
/ SCALE_MS
);
2232 qemu_printf("Max guest advance %"PRIi64
" ms\n",
2233 max_advance
/ SCALE_MS
);
2235 qemu_printf("Max guest delay NA\n");
2236 qemu_printf("Max guest advance NA\n");