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"
66 #include <sys/prctl.h>
69 #define PR_MCE_KILL 33
72 #ifndef PR_MCE_KILL_SET
73 #define PR_MCE_KILL_SET 1
76 #ifndef PR_MCE_KILL_EARLY
77 #define PR_MCE_KILL_EARLY 1
80 #endif /* CONFIG_LINUX */
82 static QemuMutex qemu_global_mutex
;
87 /* vcpu throttling controls */
88 static QEMUTimer
*throttle_timer
;
89 static unsigned int throttle_percentage
;
91 #define CPU_THROTTLE_PCT_MIN 1
92 #define CPU_THROTTLE_PCT_MAX 99
93 #define CPU_THROTTLE_TIMESLICE_NS 10000000
95 bool cpu_is_stopped(CPUState
*cpu
)
97 return cpu
->stopped
|| !runstate_is_running();
100 static bool cpu_thread_is_idle(CPUState
*cpu
)
102 if (cpu
->stop
|| cpu
->queued_work_first
) {
105 if (cpu_is_stopped(cpu
)) {
108 if (!cpu
->halted
|| cpu_has_work(cpu
) ||
109 kvm_halt_in_kernel()) {
115 static bool all_cpu_threads_idle(void)
120 if (!cpu_thread_is_idle(cpu
)) {
127 /***********************************************************/
128 /* guest cycle counter */
130 /* Protected by TimersState seqlock */
132 static bool icount_sleep
= true;
133 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
134 #define MAX_ICOUNT_SHIFT 10
136 typedef struct TimersState
{
137 /* Protected by BQL. */
138 int64_t cpu_ticks_prev
;
139 int64_t cpu_ticks_offset
;
141 /* Protect fields that can be respectively read outside the
142 * BQL, and written from multiple threads.
144 QemuSeqLock vm_clock_seqlock
;
145 QemuSpin vm_clock_lock
;
147 int16_t cpu_ticks_enabled
;
149 /* Conversion factor from emulated instructions to virtual clock ticks. */
150 int16_t icount_time_shift
;
152 /* Compensate for varying guest execution speed. */
153 int64_t qemu_icount_bias
;
155 int64_t vm_clock_warp_start
;
156 int64_t cpu_clock_offset
;
158 /* Only written by TCG thread */
161 /* for adjusting icount */
162 QEMUTimer
*icount_rt_timer
;
163 QEMUTimer
*icount_vm_timer
;
164 QEMUTimer
*icount_warp_timer
;
167 static TimersState timers_state
;
171 /* The current number of executed instructions is based on what we
172 * originally budgeted minus the current state of the decrementing
173 * icount counters in extra/u16.low.
175 static int64_t cpu_get_icount_executed(CPUState
*cpu
)
177 return (cpu
->icount_budget
-
178 (cpu_neg(cpu
)->icount_decr
.u16
.low
+ cpu
->icount_extra
));
182 * Update the global shared timer_state.qemu_icount to take into
183 * account executed instructions. This is done by the TCG vCPU
184 * thread so the main-loop can see time has moved forward.
186 static void cpu_update_icount_locked(CPUState
*cpu
)
188 int64_t executed
= cpu_get_icount_executed(cpu
);
189 cpu
->icount_budget
-= executed
;
191 atomic_set_i64(&timers_state
.qemu_icount
,
192 timers_state
.qemu_icount
+ executed
);
196 * Update the global shared timer_state.qemu_icount to take into
197 * account executed instructions. This is done by the TCG vCPU
198 * thread so the main-loop can see time has moved forward.
200 void cpu_update_icount(CPUState
*cpu
)
202 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
203 &timers_state
.vm_clock_lock
);
204 cpu_update_icount_locked(cpu
);
205 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
206 &timers_state
.vm_clock_lock
);
209 static int64_t cpu_get_icount_raw_locked(void)
211 CPUState
*cpu
= current_cpu
;
213 if (cpu
&& cpu
->running
) {
214 if (!cpu
->can_do_io
) {
215 error_report("Bad icount read");
218 /* Take into account what has run */
219 cpu_update_icount_locked(cpu
);
221 /* The read is protected by the seqlock, but needs atomic64 to avoid UB */
222 return atomic_read_i64(&timers_state
.qemu_icount
);
225 static int64_t cpu_get_icount_locked(void)
227 int64_t icount
= cpu_get_icount_raw_locked();
228 return atomic_read_i64(&timers_state
.qemu_icount_bias
) +
229 cpu_icount_to_ns(icount
);
232 int64_t cpu_get_icount_raw(void)
238 start
= seqlock_read_begin(&timers_state
.vm_clock_seqlock
);
239 icount
= cpu_get_icount_raw_locked();
240 } while (seqlock_read_retry(&timers_state
.vm_clock_seqlock
, start
));
245 /* Return the virtual CPU time, based on the instruction counter. */
246 int64_t cpu_get_icount(void)
252 start
= seqlock_read_begin(&timers_state
.vm_clock_seqlock
);
253 icount
= cpu_get_icount_locked();
254 } while (seqlock_read_retry(&timers_state
.vm_clock_seqlock
, start
));
259 int64_t cpu_icount_to_ns(int64_t icount
)
261 return icount
<< atomic_read(&timers_state
.icount_time_shift
);
264 static int64_t cpu_get_ticks_locked(void)
266 int64_t ticks
= timers_state
.cpu_ticks_offset
;
267 if (timers_state
.cpu_ticks_enabled
) {
268 ticks
+= cpu_get_host_ticks();
271 if (timers_state
.cpu_ticks_prev
> ticks
) {
272 /* Non increasing ticks may happen if the host uses software suspend. */
273 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
274 ticks
= timers_state
.cpu_ticks_prev
;
277 timers_state
.cpu_ticks_prev
= ticks
;
281 /* return the time elapsed in VM between vm_start and vm_stop. Unless
282 * icount is active, cpu_get_ticks() uses units of the host CPU cycle
285 int64_t cpu_get_ticks(void)
290 return cpu_get_icount();
293 qemu_spin_lock(&timers_state
.vm_clock_lock
);
294 ticks
= cpu_get_ticks_locked();
295 qemu_spin_unlock(&timers_state
.vm_clock_lock
);
299 static int64_t cpu_get_clock_locked(void)
303 time
= timers_state
.cpu_clock_offset
;
304 if (timers_state
.cpu_ticks_enabled
) {
311 /* Return the monotonic time elapsed in VM, i.e.,
312 * the time between vm_start and vm_stop
314 int64_t cpu_get_clock(void)
320 start
= seqlock_read_begin(&timers_state
.vm_clock_seqlock
);
321 ti
= cpu_get_clock_locked();
322 } while (seqlock_read_retry(&timers_state
.vm_clock_seqlock
, start
));
327 /* enable cpu_get_ticks()
328 * Caller must hold BQL which serves as mutex for vm_clock_seqlock.
330 void cpu_enable_ticks(void)
332 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
333 &timers_state
.vm_clock_lock
);
334 if (!timers_state
.cpu_ticks_enabled
) {
335 timers_state
.cpu_ticks_offset
-= cpu_get_host_ticks();
336 timers_state
.cpu_clock_offset
-= get_clock();
337 timers_state
.cpu_ticks_enabled
= 1;
339 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
340 &timers_state
.vm_clock_lock
);
343 /* disable cpu_get_ticks() : the clock is stopped. You must not call
344 * cpu_get_ticks() after that.
345 * Caller must hold BQL which serves as mutex for vm_clock_seqlock.
347 void cpu_disable_ticks(void)
349 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
350 &timers_state
.vm_clock_lock
);
351 if (timers_state
.cpu_ticks_enabled
) {
352 timers_state
.cpu_ticks_offset
+= cpu_get_host_ticks();
353 timers_state
.cpu_clock_offset
= cpu_get_clock_locked();
354 timers_state
.cpu_ticks_enabled
= 0;
356 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
357 &timers_state
.vm_clock_lock
);
360 /* Correlation between real and virtual time is always going to be
361 fairly approximate, so ignore small variation.
362 When the guest is idle real and virtual time will be aligned in
364 #define ICOUNT_WOBBLE (NANOSECONDS_PER_SECOND / 10)
366 static void icount_adjust(void)
372 /* Protected by TimersState mutex. */
373 static int64_t last_delta
;
375 /* If the VM is not running, then do nothing. */
376 if (!runstate_is_running()) {
380 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
381 &timers_state
.vm_clock_lock
);
382 cur_time
= REPLAY_CLOCK_LOCKED(REPLAY_CLOCK_VIRTUAL_RT
,
383 cpu_get_clock_locked());
384 cur_icount
= cpu_get_icount_locked();
386 delta
= cur_icount
- cur_time
;
387 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
389 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
390 && timers_state
.icount_time_shift
> 0) {
391 /* The guest is getting too far ahead. Slow time down. */
392 atomic_set(&timers_state
.icount_time_shift
,
393 timers_state
.icount_time_shift
- 1);
396 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
397 && timers_state
.icount_time_shift
< MAX_ICOUNT_SHIFT
) {
398 /* The guest is getting too far behind. Speed time up. */
399 atomic_set(&timers_state
.icount_time_shift
,
400 timers_state
.icount_time_shift
+ 1);
403 atomic_set_i64(&timers_state
.qemu_icount_bias
,
404 cur_icount
- (timers_state
.qemu_icount
405 << timers_state
.icount_time_shift
));
406 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
407 &timers_state
.vm_clock_lock
);
410 static void icount_adjust_rt(void *opaque
)
412 timer_mod(timers_state
.icount_rt_timer
,
413 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT
) + 1000);
417 static void icount_adjust_vm(void *opaque
)
419 timer_mod(timers_state
.icount_vm_timer
,
420 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
) +
421 NANOSECONDS_PER_SECOND
/ 10);
425 static int64_t qemu_icount_round(int64_t count
)
427 int shift
= atomic_read(&timers_state
.icount_time_shift
);
428 return (count
+ (1 << shift
) - 1) >> shift
;
431 static void icount_warp_rt(void)
436 /* The icount_warp_timer is rescheduled soon after vm_clock_warp_start
437 * changes from -1 to another value, so the race here is okay.
440 seq
= seqlock_read_begin(&timers_state
.vm_clock_seqlock
);
441 warp_start
= timers_state
.vm_clock_warp_start
;
442 } while (seqlock_read_retry(&timers_state
.vm_clock_seqlock
, seq
));
444 if (warp_start
== -1) {
448 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
449 &timers_state
.vm_clock_lock
);
450 if (runstate_is_running()) {
451 int64_t clock
= REPLAY_CLOCK_LOCKED(REPLAY_CLOCK_VIRTUAL_RT
,
452 cpu_get_clock_locked());
455 warp_delta
= clock
- timers_state
.vm_clock_warp_start
;
456 if (use_icount
== 2) {
458 * In adaptive mode, do not let QEMU_CLOCK_VIRTUAL run too
459 * far ahead of real time.
461 int64_t cur_icount
= cpu_get_icount_locked();
462 int64_t delta
= clock
- cur_icount
;
463 warp_delta
= MIN(warp_delta
, delta
);
465 atomic_set_i64(&timers_state
.qemu_icount_bias
,
466 timers_state
.qemu_icount_bias
+ warp_delta
);
468 timers_state
.vm_clock_warp_start
= -1;
469 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
470 &timers_state
.vm_clock_lock
);
472 if (qemu_clock_expired(QEMU_CLOCK_VIRTUAL
)) {
473 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
477 static void icount_timer_cb(void *opaque
)
479 /* No need for a checkpoint because the timer already synchronizes
480 * with CHECKPOINT_CLOCK_VIRTUAL_RT.
485 void qtest_clock_warp(int64_t dest
)
487 int64_t clock
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
);
488 AioContext
*aio_context
;
489 assert(qtest_enabled());
490 aio_context
= qemu_get_aio_context();
491 while (clock
< dest
) {
492 int64_t deadline
= qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL
,
493 QEMU_TIMER_ATTR_ALL
);
494 int64_t warp
= qemu_soonest_timeout(dest
- clock
, deadline
);
496 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
497 &timers_state
.vm_clock_lock
);
498 atomic_set_i64(&timers_state
.qemu_icount_bias
,
499 timers_state
.qemu_icount_bias
+ warp
);
500 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
501 &timers_state
.vm_clock_lock
);
503 qemu_clock_run_timers(QEMU_CLOCK_VIRTUAL
);
504 timerlist_run_timers(aio_context
->tlg
.tl
[QEMU_CLOCK_VIRTUAL
]);
505 clock
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
);
507 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
510 void qemu_start_warp_timer(void)
519 /* Nothing to do if the VM is stopped: QEMU_CLOCK_VIRTUAL timers
520 * do not fire, so computing the deadline does not make sense.
522 if (!runstate_is_running()) {
526 if (replay_mode
!= REPLAY_MODE_PLAY
) {
527 if (!all_cpu_threads_idle()) {
531 if (qtest_enabled()) {
532 /* When testing, qtest commands advance icount. */
536 replay_checkpoint(CHECKPOINT_CLOCK_WARP_START
);
538 /* warp clock deterministically in record/replay mode */
539 if (!replay_checkpoint(CHECKPOINT_CLOCK_WARP_START
)) {
540 /* vCPU is sleeping and warp can't be started.
541 It is probably a race condition: notification sent
542 to vCPU was processed in advance and vCPU went to sleep.
543 Therefore we have to wake it up for doing someting. */
544 if (replay_has_checkpoint()) {
545 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
551 /* We want to use the earliest deadline from ALL vm_clocks */
552 clock
= qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT
);
553 deadline
= qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL
,
554 ~QEMU_TIMER_ATTR_EXTERNAL
);
556 static bool notified
;
557 if (!icount_sleep
&& !notified
) {
558 warn_report("icount sleep disabled and no active timers");
566 * Ensure QEMU_CLOCK_VIRTUAL proceeds even when the virtual CPU goes to
567 * sleep. Otherwise, the CPU might be waiting for a future timer
568 * interrupt to wake it up, but the interrupt never comes because
569 * the vCPU isn't running any insns and thus doesn't advance the
570 * QEMU_CLOCK_VIRTUAL.
574 * We never let VCPUs sleep in no sleep icount mode.
575 * If there is a pending QEMU_CLOCK_VIRTUAL timer we just advance
576 * to the next QEMU_CLOCK_VIRTUAL event and notify it.
577 * It is useful when we want a deterministic execution time,
578 * isolated from host latencies.
580 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
581 &timers_state
.vm_clock_lock
);
582 atomic_set_i64(&timers_state
.qemu_icount_bias
,
583 timers_state
.qemu_icount_bias
+ deadline
);
584 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
585 &timers_state
.vm_clock_lock
);
586 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
589 * We do stop VCPUs and only advance QEMU_CLOCK_VIRTUAL after some
590 * "real" time, (related to the time left until the next event) has
591 * passed. The QEMU_CLOCK_VIRTUAL_RT clock will do this.
592 * This avoids that the warps are visible externally; for example,
593 * you will not be sending network packets continuously instead of
596 seqlock_write_lock(&timers_state
.vm_clock_seqlock
,
597 &timers_state
.vm_clock_lock
);
598 if (timers_state
.vm_clock_warp_start
== -1
599 || timers_state
.vm_clock_warp_start
> clock
) {
600 timers_state
.vm_clock_warp_start
= clock
;
602 seqlock_write_unlock(&timers_state
.vm_clock_seqlock
,
603 &timers_state
.vm_clock_lock
);
604 timer_mod_anticipate(timers_state
.icount_warp_timer
,
607 } else if (deadline
== 0) {
608 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
612 static void qemu_account_warp_timer(void)
614 if (!use_icount
|| !icount_sleep
) {
618 /* Nothing to do if the VM is stopped: QEMU_CLOCK_VIRTUAL timers
619 * do not fire, so computing the deadline does not make sense.
621 if (!runstate_is_running()) {
625 /* warp clock deterministically in record/replay mode */
626 if (!replay_checkpoint(CHECKPOINT_CLOCK_WARP_ACCOUNT
)) {
630 timer_del(timers_state
.icount_warp_timer
);
634 static bool icount_state_needed(void *opaque
)
639 static bool warp_timer_state_needed(void *opaque
)
641 TimersState
*s
= opaque
;
642 return s
->icount_warp_timer
!= NULL
;
645 static bool adjust_timers_state_needed(void *opaque
)
647 TimersState
*s
= opaque
;
648 return s
->icount_rt_timer
!= NULL
;
651 static bool shift_state_needed(void *opaque
)
653 return use_icount
== 2;
657 * Subsection for warp timer migration is optional, because may not be created
659 static const VMStateDescription icount_vmstate_warp_timer
= {
660 .name
= "timer/icount/warp_timer",
662 .minimum_version_id
= 1,
663 .needed
= warp_timer_state_needed
,
664 .fields
= (VMStateField
[]) {
665 VMSTATE_INT64(vm_clock_warp_start
, TimersState
),
666 VMSTATE_TIMER_PTR(icount_warp_timer
, TimersState
),
667 VMSTATE_END_OF_LIST()
671 static const VMStateDescription icount_vmstate_adjust_timers
= {
672 .name
= "timer/icount/timers",
674 .minimum_version_id
= 1,
675 .needed
= adjust_timers_state_needed
,
676 .fields
= (VMStateField
[]) {
677 VMSTATE_TIMER_PTR(icount_rt_timer
, TimersState
),
678 VMSTATE_TIMER_PTR(icount_vm_timer
, TimersState
),
679 VMSTATE_END_OF_LIST()
683 static const VMStateDescription icount_vmstate_shift
= {
684 .name
= "timer/icount/shift",
686 .minimum_version_id
= 1,
687 .needed
= shift_state_needed
,
688 .fields
= (VMStateField
[]) {
689 VMSTATE_INT16(icount_time_shift
, TimersState
),
690 VMSTATE_END_OF_LIST()
695 * This is a subsection for icount migration.
697 static const VMStateDescription icount_vmstate_timers
= {
698 .name
= "timer/icount",
700 .minimum_version_id
= 1,
701 .needed
= icount_state_needed
,
702 .fields
= (VMStateField
[]) {
703 VMSTATE_INT64(qemu_icount_bias
, TimersState
),
704 VMSTATE_INT64(qemu_icount
, TimersState
),
705 VMSTATE_END_OF_LIST()
707 .subsections
= (const VMStateDescription
*[]) {
708 &icount_vmstate_warp_timer
,
709 &icount_vmstate_adjust_timers
,
710 &icount_vmstate_shift
,
715 static const VMStateDescription vmstate_timers
= {
718 .minimum_version_id
= 1,
719 .fields
= (VMStateField
[]) {
720 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
722 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
723 VMSTATE_END_OF_LIST()
725 .subsections
= (const VMStateDescription
*[]) {
726 &icount_vmstate_timers
,
731 static void cpu_throttle_thread(CPUState
*cpu
, run_on_cpu_data opaque
)
734 double throttle_ratio
;
735 int64_t sleeptime_ns
, endtime_ns
;
737 if (!cpu_throttle_get_percentage()) {
741 pct
= (double)cpu_throttle_get_percentage()/100;
742 throttle_ratio
= pct
/ (1 - pct
);
743 /* Add 1ns to fix double's rounding error (like 0.9999999...) */
744 sleeptime_ns
= (int64_t)(throttle_ratio
* CPU_THROTTLE_TIMESLICE_NS
+ 1);
745 endtime_ns
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) + sleeptime_ns
;
746 while (sleeptime_ns
> 0 && !cpu
->stop
) {
747 if (sleeptime_ns
> SCALE_MS
) {
748 qemu_cond_timedwait(cpu
->halt_cond
, &qemu_global_mutex
,
749 sleeptime_ns
/ SCALE_MS
);
751 qemu_mutex_unlock_iothread();
752 g_usleep(sleeptime_ns
/ SCALE_US
);
753 qemu_mutex_lock_iothread();
755 sleeptime_ns
= endtime_ns
- qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
757 atomic_set(&cpu
->throttle_thread_scheduled
, 0);
760 static void cpu_throttle_timer_tick(void *opaque
)
765 /* Stop the timer if needed */
766 if (!cpu_throttle_get_percentage()) {
770 if (!atomic_xchg(&cpu
->throttle_thread_scheduled
, 1)) {
771 async_run_on_cpu(cpu
, cpu_throttle_thread
,
776 pct
= (double)cpu_throttle_get_percentage()/100;
777 timer_mod(throttle_timer
, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT
) +
778 CPU_THROTTLE_TIMESLICE_NS
/ (1-pct
));
781 void cpu_throttle_set(int new_throttle_pct
)
783 /* Ensure throttle percentage is within valid range */
784 new_throttle_pct
= MIN(new_throttle_pct
, CPU_THROTTLE_PCT_MAX
);
785 new_throttle_pct
= MAX(new_throttle_pct
, CPU_THROTTLE_PCT_MIN
);
787 atomic_set(&throttle_percentage
, new_throttle_pct
);
789 timer_mod(throttle_timer
, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT
) +
790 CPU_THROTTLE_TIMESLICE_NS
);
793 void cpu_throttle_stop(void)
795 atomic_set(&throttle_percentage
, 0);
798 bool cpu_throttle_active(void)
800 return (cpu_throttle_get_percentage() != 0);
803 int cpu_throttle_get_percentage(void)
805 return atomic_read(&throttle_percentage
);
808 void cpu_ticks_init(void)
810 seqlock_init(&timers_state
.vm_clock_seqlock
);
811 qemu_spin_init(&timers_state
.vm_clock_lock
);
812 vmstate_register(NULL
, 0, &vmstate_timers
, &timers_state
);
813 throttle_timer
= timer_new_ns(QEMU_CLOCK_VIRTUAL_RT
,
814 cpu_throttle_timer_tick
, NULL
);
817 void configure_icount(QemuOpts
*opts
, Error
**errp
)
819 const char *option
= qemu_opt_get(opts
, "shift");
820 bool sleep
= qemu_opt_get_bool(opts
, "sleep", true);
821 bool align
= qemu_opt_get_bool(opts
, "align", false);
822 long time_shift
= -1;
825 if (qemu_opt_get(opts
, "align") != NULL
) {
826 error_setg(errp
, "Please specify shift option when using align");
831 if (align
&& !sleep
) {
832 error_setg(errp
, "align=on and sleep=off are incompatible");
836 if (strcmp(option
, "auto") != 0) {
837 if (qemu_strtol(option
, NULL
, 0, &time_shift
) < 0
838 || time_shift
< 0 || time_shift
> MAX_ICOUNT_SHIFT
) {
839 error_setg(errp
, "icount: Invalid shift value");
842 } else if (icount_align_option
) {
843 error_setg(errp
, "shift=auto and align=on are incompatible");
845 } else if (!icount_sleep
) {
846 error_setg(errp
, "shift=auto and sleep=off are incompatible");
850 icount_sleep
= sleep
;
852 timers_state
.icount_warp_timer
= timer_new_ns(QEMU_CLOCK_VIRTUAL_RT
,
853 icount_timer_cb
, NULL
);
856 icount_align_option
= align
;
858 if (time_shift
>= 0) {
859 timers_state
.icount_time_shift
= time_shift
;
866 /* 125MIPS seems a reasonable initial guess at the guest speed.
867 It will be corrected fairly quickly anyway. */
868 timers_state
.icount_time_shift
= 3;
870 /* Have both realtime and virtual time triggers for speed adjustment.
871 The realtime trigger catches emulated time passing too slowly,
872 the virtual time trigger catches emulated time passing too fast.
873 Realtime triggers occur even when idle, so use them less frequently
875 timers_state
.vm_clock_warp_start
= -1;
876 timers_state
.icount_rt_timer
= timer_new_ms(QEMU_CLOCK_VIRTUAL_RT
,
877 icount_adjust_rt
, NULL
);
878 timer_mod(timers_state
.icount_rt_timer
,
879 qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT
) + 1000);
880 timers_state
.icount_vm_timer
= timer_new_ns(QEMU_CLOCK_VIRTUAL
,
881 icount_adjust_vm
, NULL
);
882 timer_mod(timers_state
.icount_vm_timer
,
883 qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
) +
884 NANOSECONDS_PER_SECOND
/ 10);
887 /***********************************************************/
888 /* TCG vCPU kick timer
890 * The kick timer is responsible for moving single threaded vCPU
891 * emulation on to the next vCPU. If more than one vCPU is running a
892 * timer event with force a cpu->exit so the next vCPU can get
895 * The timer is removed if all vCPUs are idle and restarted again once
896 * idleness is complete.
899 static QEMUTimer
*tcg_kick_vcpu_timer
;
900 static CPUState
*tcg_current_rr_cpu
;
902 #define TCG_KICK_PERIOD (NANOSECONDS_PER_SECOND / 10)
904 static inline int64_t qemu_tcg_next_kick(void)
906 return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL
) + TCG_KICK_PERIOD
;
909 /* Kick the currently round-robin scheduled vCPU to next */
910 static void qemu_cpu_kick_rr_next_cpu(void)
914 cpu
= atomic_mb_read(&tcg_current_rr_cpu
);
918 } while (cpu
!= atomic_mb_read(&tcg_current_rr_cpu
));
921 /* Kick all RR vCPUs */
922 static void qemu_cpu_kick_rr_cpus(void)
931 static void do_nothing(CPUState
*cpu
, run_on_cpu_data unused
)
935 void qemu_timer_notify_cb(void *opaque
, QEMUClockType type
)
937 if (!use_icount
|| type
!= QEMU_CLOCK_VIRTUAL
) {
942 if (qemu_in_vcpu_thread()) {
943 /* A CPU is currently running; kick it back out to the
944 * tcg_cpu_exec() loop so it will recalculate its
945 * icount deadline immediately.
947 qemu_cpu_kick(current_cpu
);
948 } else if (first_cpu
) {
949 /* qemu_cpu_kick is not enough to kick a halted CPU out of
950 * qemu_tcg_wait_io_event. async_run_on_cpu, instead,
951 * causes cpu_thread_is_idle to return false. This way,
952 * handle_icount_deadline can run.
953 * If we have no CPUs at all for some reason, we don't
954 * need to do anything.
956 async_run_on_cpu(first_cpu
, do_nothing
, RUN_ON_CPU_NULL
);
960 static void kick_tcg_thread(void *opaque
)
962 timer_mod(tcg_kick_vcpu_timer
, qemu_tcg_next_kick());
963 qemu_cpu_kick_rr_next_cpu();
966 static void start_tcg_kick_timer(void)
968 assert(!mttcg_enabled
);
969 if (!tcg_kick_vcpu_timer
&& CPU_NEXT(first_cpu
)) {
970 tcg_kick_vcpu_timer
= timer_new_ns(QEMU_CLOCK_VIRTUAL
,
971 kick_tcg_thread
, NULL
);
973 if (tcg_kick_vcpu_timer
&& !timer_pending(tcg_kick_vcpu_timer
)) {
974 timer_mod(tcg_kick_vcpu_timer
, qemu_tcg_next_kick());
978 static void stop_tcg_kick_timer(void)
980 assert(!mttcg_enabled
);
981 if (tcg_kick_vcpu_timer
&& timer_pending(tcg_kick_vcpu_timer
)) {
982 timer_del(tcg_kick_vcpu_timer
);
986 /***********************************************************/
987 void hw_error(const char *fmt
, ...)
993 fprintf(stderr
, "qemu: hardware error: ");
994 vfprintf(stderr
, fmt
, ap
);
995 fprintf(stderr
, "\n");
997 fprintf(stderr
, "CPU #%d:\n", cpu
->cpu_index
);
998 cpu_dump_state(cpu
, stderr
, CPU_DUMP_FPU
);
1004 void cpu_synchronize_all_states(void)
1009 cpu_synchronize_state(cpu
);
1010 /* TODO: move to cpu_synchronize_state() */
1011 if (hvf_enabled()) {
1012 hvf_cpu_synchronize_state(cpu
);
1017 void cpu_synchronize_all_post_reset(void)
1022 cpu_synchronize_post_reset(cpu
);
1023 /* TODO: move to cpu_synchronize_post_reset() */
1024 if (hvf_enabled()) {
1025 hvf_cpu_synchronize_post_reset(cpu
);
1030 void cpu_synchronize_all_post_init(void)
1035 cpu_synchronize_post_init(cpu
);
1036 /* TODO: move to cpu_synchronize_post_init() */
1037 if (hvf_enabled()) {
1038 hvf_cpu_synchronize_post_init(cpu
);
1043 void cpu_synchronize_all_pre_loadvm(void)
1048 cpu_synchronize_pre_loadvm(cpu
);
1052 static int do_vm_stop(RunState state
, bool send_stop
)
1056 if (runstate_is_running()) {
1057 runstate_set(state
);
1058 cpu_disable_ticks();
1060 vm_state_notify(0, state
);
1062 qapi_event_send_stop();
1067 ret
= bdrv_flush_all();
1072 /* Special vm_stop() variant for terminating the process. Historically clients
1073 * did not expect a QMP STOP event and so we need to retain compatibility.
1075 int vm_shutdown(void)
1077 return do_vm_stop(RUN_STATE_SHUTDOWN
, false);
1080 static bool cpu_can_run(CPUState
*cpu
)
1085 if (cpu_is_stopped(cpu
)) {
1091 static void cpu_handle_guest_debug(CPUState
*cpu
)
1093 gdb_set_stop_cpu(cpu
);
1094 qemu_system_debug_request();
1095 cpu
->stopped
= true;
1099 static void sigbus_reraise(void)
1102 struct sigaction action
;
1104 memset(&action
, 0, sizeof(action
));
1105 action
.sa_handler
= SIG_DFL
;
1106 if (!sigaction(SIGBUS
, &action
, NULL
)) {
1109 sigaddset(&set
, SIGBUS
);
1110 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
1112 perror("Failed to re-raise SIGBUS!\n");
1116 static void sigbus_handler(int n
, siginfo_t
*siginfo
, void *ctx
)
1118 if (siginfo
->si_code
!= BUS_MCEERR_AO
&& siginfo
->si_code
!= BUS_MCEERR_AR
) {
1123 /* Called asynchronously in VCPU thread. */
1124 if (kvm_on_sigbus_vcpu(current_cpu
, siginfo
->si_code
, siginfo
->si_addr
)) {
1128 /* Called synchronously (via signalfd) in main thread. */
1129 if (kvm_on_sigbus(siginfo
->si_code
, siginfo
->si_addr
)) {
1135 static void qemu_init_sigbus(void)
1137 struct sigaction action
;
1139 memset(&action
, 0, sizeof(action
));
1140 action
.sa_flags
= SA_SIGINFO
;
1141 action
.sa_sigaction
= sigbus_handler
;
1142 sigaction(SIGBUS
, &action
, NULL
);
1144 prctl(PR_MCE_KILL
, PR_MCE_KILL_SET
, PR_MCE_KILL_EARLY
, 0, 0);
1146 #else /* !CONFIG_LINUX */
1147 static void qemu_init_sigbus(void)
1150 #endif /* !CONFIG_LINUX */
1152 static QemuThread io_thread
;
1155 static QemuCond qemu_cpu_cond
;
1157 static QemuCond qemu_pause_cond
;
1159 void qemu_init_cpu_loop(void)
1162 qemu_cond_init(&qemu_cpu_cond
);
1163 qemu_cond_init(&qemu_pause_cond
);
1164 qemu_mutex_init(&qemu_global_mutex
);
1166 qemu_thread_get_self(&io_thread
);
1169 void run_on_cpu(CPUState
*cpu
, run_on_cpu_func func
, run_on_cpu_data data
)
1171 do_run_on_cpu(cpu
, func
, data
, &qemu_global_mutex
);
1174 static void qemu_kvm_destroy_vcpu(CPUState
*cpu
)
1176 if (kvm_destroy_vcpu(cpu
) < 0) {
1177 error_report("kvm_destroy_vcpu failed");
1182 static void qemu_tcg_destroy_vcpu(CPUState
*cpu
)
1186 static void qemu_cpu_stop(CPUState
*cpu
, bool exit
)
1188 g_assert(qemu_cpu_is_self(cpu
));
1190 cpu
->stopped
= true;
1194 qemu_cond_broadcast(&qemu_pause_cond
);
1197 static void qemu_wait_io_event_common(CPUState
*cpu
)
1199 atomic_mb_set(&cpu
->thread_kicked
, false);
1201 qemu_cpu_stop(cpu
, false);
1203 process_queued_cpu_work(cpu
);
1206 static void qemu_tcg_rr_wait_io_event(void)
1210 while (all_cpu_threads_idle()) {
1211 stop_tcg_kick_timer();
1212 qemu_cond_wait(first_cpu
->halt_cond
, &qemu_global_mutex
);
1215 start_tcg_kick_timer();
1218 qemu_wait_io_event_common(cpu
);
1222 static void qemu_wait_io_event(CPUState
*cpu
)
1226 while (cpu_thread_is_idle(cpu
)) {
1229 qemu_plugin_vcpu_idle_cb(cpu
);
1231 qemu_cond_wait(cpu
->halt_cond
, &qemu_global_mutex
);
1234 qemu_plugin_vcpu_resume_cb(cpu
);
1238 /* Eat dummy APC queued by qemu_cpu_kick_thread. */
1239 if (!tcg_enabled()) {
1243 qemu_wait_io_event_common(cpu
);
1246 static void *qemu_kvm_cpu_thread_fn(void *arg
)
1248 CPUState
*cpu
= arg
;
1251 rcu_register_thread();
1253 qemu_mutex_lock_iothread();
1254 qemu_thread_get_self(cpu
->thread
);
1255 cpu
->thread_id
= qemu_get_thread_id();
1259 r
= kvm_init_vcpu(cpu
);
1261 error_report("kvm_init_vcpu failed: %s", strerror(-r
));
1265 kvm_init_cpu_signals(cpu
);
1267 /* signal CPU creation */
1268 cpu
->created
= true;
1269 qemu_cond_signal(&qemu_cpu_cond
);
1270 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1273 if (cpu_can_run(cpu
)) {
1274 r
= kvm_cpu_exec(cpu
);
1275 if (r
== EXCP_DEBUG
) {
1276 cpu_handle_guest_debug(cpu
);
1279 qemu_wait_io_event(cpu
);
1280 } while (!cpu
->unplug
|| cpu_can_run(cpu
));
1282 qemu_kvm_destroy_vcpu(cpu
);
1283 cpu
->created
= false;
1284 qemu_cond_signal(&qemu_cpu_cond
);
1285 qemu_mutex_unlock_iothread();
1286 rcu_unregister_thread();
1290 static void *qemu_dummy_cpu_thread_fn(void *arg
)
1293 error_report("qtest is not supported under Windows");
1296 CPUState
*cpu
= arg
;
1300 rcu_register_thread();
1302 qemu_mutex_lock_iothread();
1303 qemu_thread_get_self(cpu
->thread
);
1304 cpu
->thread_id
= qemu_get_thread_id();
1308 sigemptyset(&waitset
);
1309 sigaddset(&waitset
, SIG_IPI
);
1311 /* signal CPU creation */
1312 cpu
->created
= true;
1313 qemu_cond_signal(&qemu_cpu_cond
);
1314 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1317 qemu_mutex_unlock_iothread();
1320 r
= sigwait(&waitset
, &sig
);
1321 } while (r
== -1 && (errno
== EAGAIN
|| errno
== EINTR
));
1326 qemu_mutex_lock_iothread();
1327 qemu_wait_io_event(cpu
);
1328 } while (!cpu
->unplug
);
1330 qemu_mutex_unlock_iothread();
1331 rcu_unregister_thread();
1336 static int64_t tcg_get_icount_limit(void)
1340 if (replay_mode
!= REPLAY_MODE_PLAY
) {
1342 * Include all the timers, because they may need an attention.
1343 * Too long CPU execution may create unnecessary delay in UI.
1345 deadline
= qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL
,
1346 QEMU_TIMER_ATTR_ALL
);
1347 /* Check realtime timers, because they help with input processing */
1348 deadline
= qemu_soonest_timeout(deadline
,
1349 qemu_clock_deadline_ns_all(QEMU_CLOCK_REALTIME
,
1350 QEMU_TIMER_ATTR_ALL
));
1352 /* Maintain prior (possibly buggy) behaviour where if no deadline
1353 * was set (as there is no QEMU_CLOCK_VIRTUAL timer) or it is more than
1354 * INT32_MAX nanoseconds ahead, we still use INT32_MAX
1357 if ((deadline
< 0) || (deadline
> INT32_MAX
)) {
1358 deadline
= INT32_MAX
;
1361 return qemu_icount_round(deadline
);
1363 return replay_get_instructions();
1367 static void handle_icount_deadline(void)
1369 assert(qemu_in_vcpu_thread());
1371 int64_t deadline
= qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL
,
1372 QEMU_TIMER_ATTR_ALL
);
1374 if (deadline
== 0) {
1375 /* Wake up other AioContexts. */
1376 qemu_clock_notify(QEMU_CLOCK_VIRTUAL
);
1377 qemu_clock_run_timers(QEMU_CLOCK_VIRTUAL
);
1382 static void prepare_icount_for_run(CPUState
*cpu
)
1387 /* These should always be cleared by process_icount_data after
1388 * each vCPU execution. However u16.high can be raised
1389 * asynchronously by cpu_exit/cpu_interrupt/tcg_handle_interrupt
1391 g_assert(cpu_neg(cpu
)->icount_decr
.u16
.low
== 0);
1392 g_assert(cpu
->icount_extra
== 0);
1394 cpu
->icount_budget
= tcg_get_icount_limit();
1395 insns_left
= MIN(0xffff, cpu
->icount_budget
);
1396 cpu_neg(cpu
)->icount_decr
.u16
.low
= insns_left
;
1397 cpu
->icount_extra
= cpu
->icount_budget
- insns_left
;
1399 replay_mutex_lock();
1403 static void process_icount_data(CPUState
*cpu
)
1406 /* Account for executed instructions */
1407 cpu_update_icount(cpu
);
1409 /* Reset the counters */
1410 cpu_neg(cpu
)->icount_decr
.u16
.low
= 0;
1411 cpu
->icount_extra
= 0;
1412 cpu
->icount_budget
= 0;
1414 replay_account_executed_instructions();
1416 replay_mutex_unlock();
1421 static int tcg_cpu_exec(CPUState
*cpu
)
1424 #ifdef CONFIG_PROFILER
1428 assert(tcg_enabled());
1429 #ifdef CONFIG_PROFILER
1430 ti
= profile_getclock();
1432 cpu_exec_start(cpu
);
1433 ret
= cpu_exec(cpu
);
1435 #ifdef CONFIG_PROFILER
1436 atomic_set(&tcg_ctx
->prof
.cpu_exec_time
,
1437 tcg_ctx
->prof
.cpu_exec_time
+ profile_getclock() - ti
);
1442 /* Destroy any remaining vCPUs which have been unplugged and have
1445 static void deal_with_unplugged_cpus(void)
1450 if (cpu
->unplug
&& !cpu_can_run(cpu
)) {
1451 qemu_tcg_destroy_vcpu(cpu
);
1452 cpu
->created
= false;
1453 qemu_cond_signal(&qemu_cpu_cond
);
1459 /* Single-threaded TCG
1461 * In the single-threaded case each vCPU is simulated in turn. If
1462 * there is more than a single vCPU we create a simple timer to kick
1463 * the vCPU and ensure we don't get stuck in a tight loop in one vCPU.
1464 * This is done explicitly rather than relying on side-effects
1468 static void *qemu_tcg_rr_cpu_thread_fn(void *arg
)
1470 CPUState
*cpu
= arg
;
1472 assert(tcg_enabled());
1473 rcu_register_thread();
1474 tcg_register_thread();
1476 qemu_mutex_lock_iothread();
1477 qemu_thread_get_self(cpu
->thread
);
1479 cpu
->thread_id
= qemu_get_thread_id();
1480 cpu
->created
= true;
1482 qemu_cond_signal(&qemu_cpu_cond
);
1483 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1485 /* wait for initial kick-off after machine start */
1486 while (first_cpu
->stopped
) {
1487 qemu_cond_wait(first_cpu
->halt_cond
, &qemu_global_mutex
);
1489 /* process any pending work */
1492 qemu_wait_io_event_common(cpu
);
1496 start_tcg_kick_timer();
1500 /* process any pending work */
1501 cpu
->exit_request
= 1;
1504 qemu_mutex_unlock_iothread();
1505 replay_mutex_lock();
1506 qemu_mutex_lock_iothread();
1507 /* Account partial waits to QEMU_CLOCK_VIRTUAL. */
1508 qemu_account_warp_timer();
1510 /* Run the timers here. This is much more efficient than
1511 * waking up the I/O thread and waiting for completion.
1513 handle_icount_deadline();
1515 replay_mutex_unlock();
1521 while (cpu
&& !cpu
->queued_work_first
&& !cpu
->exit_request
) {
1523 atomic_mb_set(&tcg_current_rr_cpu
, cpu
);
1526 qemu_clock_enable(QEMU_CLOCK_VIRTUAL
,
1527 (cpu
->singlestep_enabled
& SSTEP_NOTIMER
) == 0);
1529 if (cpu_can_run(cpu
)) {
1532 qemu_mutex_unlock_iothread();
1533 prepare_icount_for_run(cpu
);
1535 r
= tcg_cpu_exec(cpu
);
1537 process_icount_data(cpu
);
1538 qemu_mutex_lock_iothread();
1540 if (r
== EXCP_DEBUG
) {
1541 cpu_handle_guest_debug(cpu
);
1543 } else if (r
== EXCP_ATOMIC
) {
1544 qemu_mutex_unlock_iothread();
1545 cpu_exec_step_atomic(cpu
);
1546 qemu_mutex_lock_iothread();
1549 } else if (cpu
->stop
) {
1551 cpu
= CPU_NEXT(cpu
);
1556 cpu
= CPU_NEXT(cpu
);
1557 } /* while (cpu && !cpu->exit_request).. */
1559 /* Does not need atomic_mb_set because a spurious wakeup is okay. */
1560 atomic_set(&tcg_current_rr_cpu
, NULL
);
1562 if (cpu
&& cpu
->exit_request
) {
1563 atomic_mb_set(&cpu
->exit_request
, 0);
1566 if (use_icount
&& all_cpu_threads_idle()) {
1568 * When all cpus are sleeping (e.g in WFI), to avoid a deadlock
1569 * in the main_loop, wake it up in order to start the warp timer.
1571 qemu_notify_event();
1574 qemu_tcg_rr_wait_io_event();
1575 deal_with_unplugged_cpus();
1578 rcu_unregister_thread();
1582 static void *qemu_hax_cpu_thread_fn(void *arg
)
1584 CPUState
*cpu
= arg
;
1587 rcu_register_thread();
1588 qemu_mutex_lock_iothread();
1589 qemu_thread_get_self(cpu
->thread
);
1591 cpu
->thread_id
= qemu_get_thread_id();
1592 cpu
->created
= true;
1596 qemu_cond_signal(&qemu_cpu_cond
);
1597 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1600 if (cpu_can_run(cpu
)) {
1601 r
= hax_smp_cpu_exec(cpu
);
1602 if (r
== EXCP_DEBUG
) {
1603 cpu_handle_guest_debug(cpu
);
1607 qemu_wait_io_event(cpu
);
1608 } while (!cpu
->unplug
|| cpu_can_run(cpu
));
1609 rcu_unregister_thread();
1613 /* The HVF-specific vCPU thread function. This one should only run when the host
1614 * CPU supports the VMX "unrestricted guest" feature. */
1615 static void *qemu_hvf_cpu_thread_fn(void *arg
)
1617 CPUState
*cpu
= arg
;
1621 assert(hvf_enabled());
1623 rcu_register_thread();
1625 qemu_mutex_lock_iothread();
1626 qemu_thread_get_self(cpu
->thread
);
1628 cpu
->thread_id
= qemu_get_thread_id();
1634 /* signal CPU creation */
1635 cpu
->created
= true;
1636 qemu_cond_signal(&qemu_cpu_cond
);
1637 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1640 if (cpu_can_run(cpu
)) {
1641 r
= hvf_vcpu_exec(cpu
);
1642 if (r
== EXCP_DEBUG
) {
1643 cpu_handle_guest_debug(cpu
);
1646 qemu_wait_io_event(cpu
);
1647 } while (!cpu
->unplug
|| cpu_can_run(cpu
));
1649 hvf_vcpu_destroy(cpu
);
1650 cpu
->created
= false;
1651 qemu_cond_signal(&qemu_cpu_cond
);
1652 qemu_mutex_unlock_iothread();
1653 rcu_unregister_thread();
1657 static void *qemu_whpx_cpu_thread_fn(void *arg
)
1659 CPUState
*cpu
= arg
;
1662 rcu_register_thread();
1664 qemu_mutex_lock_iothread();
1665 qemu_thread_get_self(cpu
->thread
);
1666 cpu
->thread_id
= qemu_get_thread_id();
1669 r
= whpx_init_vcpu(cpu
);
1671 fprintf(stderr
, "whpx_init_vcpu failed: %s\n", strerror(-r
));
1675 /* signal CPU creation */
1676 cpu
->created
= true;
1677 qemu_cond_signal(&qemu_cpu_cond
);
1678 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1681 if (cpu_can_run(cpu
)) {
1682 r
= whpx_vcpu_exec(cpu
);
1683 if (r
== EXCP_DEBUG
) {
1684 cpu_handle_guest_debug(cpu
);
1687 while (cpu_thread_is_idle(cpu
)) {
1688 qemu_cond_wait(cpu
->halt_cond
, &qemu_global_mutex
);
1690 qemu_wait_io_event_common(cpu
);
1691 } while (!cpu
->unplug
|| cpu_can_run(cpu
));
1693 whpx_destroy_vcpu(cpu
);
1694 cpu
->created
= false;
1695 qemu_cond_signal(&qemu_cpu_cond
);
1696 qemu_mutex_unlock_iothread();
1697 rcu_unregister_thread();
1702 static void CALLBACK
dummy_apc_func(ULONG_PTR unused
)
1707 /* Multi-threaded TCG
1709 * In the multi-threaded case each vCPU has its own thread. The TLS
1710 * variable current_cpu can be used deep in the code to find the
1711 * current CPUState for a given thread.
1714 static void *qemu_tcg_cpu_thread_fn(void *arg
)
1716 CPUState
*cpu
= arg
;
1718 assert(tcg_enabled());
1719 g_assert(!use_icount
);
1721 rcu_register_thread();
1722 tcg_register_thread();
1724 qemu_mutex_lock_iothread();
1725 qemu_thread_get_self(cpu
->thread
);
1727 cpu
->thread_id
= qemu_get_thread_id();
1728 cpu
->created
= true;
1731 qemu_cond_signal(&qemu_cpu_cond
);
1732 qemu_guest_random_seed_thread_part2(cpu
->random_seed
);
1734 /* process any pending work */
1735 cpu
->exit_request
= 1;
1738 if (cpu_can_run(cpu
)) {
1740 qemu_mutex_unlock_iothread();
1741 r
= tcg_cpu_exec(cpu
);
1742 qemu_mutex_lock_iothread();
1745 cpu_handle_guest_debug(cpu
);
1748 /* during start-up the vCPU is reset and the thread is
1749 * kicked several times. If we don't ensure we go back
1750 * to sleep in the halted state we won't cleanly
1751 * start-up when the vCPU is enabled.
1753 * cpu->halted should ensure we sleep in wait_io_event
1755 g_assert(cpu
->halted
);
1758 qemu_mutex_unlock_iothread();
1759 cpu_exec_step_atomic(cpu
);
1760 qemu_mutex_lock_iothread();
1762 /* Ignore everything else? */
1767 atomic_mb_set(&cpu
->exit_request
, 0);
1768 qemu_wait_io_event(cpu
);
1769 } while (!cpu
->unplug
|| cpu_can_run(cpu
));
1771 qemu_tcg_destroy_vcpu(cpu
);
1772 cpu
->created
= false;
1773 qemu_cond_signal(&qemu_cpu_cond
);
1774 qemu_mutex_unlock_iothread();
1775 rcu_unregister_thread();
1779 static void qemu_cpu_kick_thread(CPUState
*cpu
)
1784 if (cpu
->thread_kicked
) {
1787 cpu
->thread_kicked
= true;
1788 err
= pthread_kill(cpu
->thread
->thread
, SIG_IPI
);
1789 if (err
&& err
!= ESRCH
) {
1790 fprintf(stderr
, "qemu:%s: %s", __func__
, strerror(err
));
1794 if (!qemu_cpu_is_self(cpu
)) {
1795 if (whpx_enabled()) {
1796 whpx_vcpu_kick(cpu
);
1797 } else if (!QueueUserAPC(dummy_apc_func
, cpu
->hThread
, 0)) {
1798 fprintf(stderr
, "%s: QueueUserAPC failed with error %lu\n",
1799 __func__
, GetLastError());
1806 void qemu_cpu_kick(CPUState
*cpu
)
1808 qemu_cond_broadcast(cpu
->halt_cond
);
1809 if (tcg_enabled()) {
1810 if (qemu_tcg_mttcg_enabled()) {
1813 qemu_cpu_kick_rr_cpus();
1816 if (hax_enabled()) {
1818 * FIXME: race condition with the exit_request check in
1821 cpu
->exit_request
= 1;
1823 qemu_cpu_kick_thread(cpu
);
1827 void qemu_cpu_kick_self(void)
1829 assert(current_cpu
);
1830 qemu_cpu_kick_thread(current_cpu
);
1833 bool qemu_cpu_is_self(CPUState
*cpu
)
1835 return qemu_thread_is_self(cpu
->thread
);
1838 bool qemu_in_vcpu_thread(void)
1840 return current_cpu
&& qemu_cpu_is_self(current_cpu
);
1843 static __thread
bool iothread_locked
= false;
1845 bool qemu_mutex_iothread_locked(void)
1847 return iothread_locked
;
1851 * The BQL is taken from so many places that it is worth profiling the
1852 * callers directly, instead of funneling them all through a single function.
1854 void qemu_mutex_lock_iothread_impl(const char *file
, int line
)
1856 QemuMutexLockFunc bql_lock
= atomic_read(&qemu_bql_mutex_lock_func
);
1858 g_assert(!qemu_mutex_iothread_locked());
1859 bql_lock(&qemu_global_mutex
, file
, line
);
1860 iothread_locked
= true;
1863 void qemu_mutex_unlock_iothread(void)
1865 g_assert(qemu_mutex_iothread_locked());
1866 iothread_locked
= false;
1867 qemu_mutex_unlock(&qemu_global_mutex
);
1870 void qemu_cond_wait_iothread(QemuCond
*cond
)
1872 qemu_cond_wait(cond
, &qemu_global_mutex
);
1875 static bool all_vcpus_paused(void)
1880 if (!cpu
->stopped
) {
1888 void pause_all_vcpus(void)
1892 qemu_clock_enable(QEMU_CLOCK_VIRTUAL
, false);
1894 if (qemu_cpu_is_self(cpu
)) {
1895 qemu_cpu_stop(cpu
, true);
1902 /* We need to drop the replay_lock so any vCPU threads woken up
1903 * can finish their replay tasks
1905 replay_mutex_unlock();
1907 while (!all_vcpus_paused()) {
1908 qemu_cond_wait(&qemu_pause_cond
, &qemu_global_mutex
);
1914 qemu_mutex_unlock_iothread();
1915 replay_mutex_lock();
1916 qemu_mutex_lock_iothread();
1919 void cpu_resume(CPUState
*cpu
)
1922 cpu
->stopped
= false;
1926 void resume_all_vcpus(void)
1930 if (!runstate_is_running()) {
1934 qemu_clock_enable(QEMU_CLOCK_VIRTUAL
, true);
1940 void cpu_remove_sync(CPUState
*cpu
)
1945 qemu_mutex_unlock_iothread();
1946 qemu_thread_join(cpu
->thread
);
1947 qemu_mutex_lock_iothread();
1950 /* For temporary buffers for forming a name */
1951 #define VCPU_THREAD_NAME_SIZE 16
1953 static void qemu_tcg_init_vcpu(CPUState
*cpu
)
1955 char thread_name
[VCPU_THREAD_NAME_SIZE
];
1956 static QemuCond
*single_tcg_halt_cond
;
1957 static QemuThread
*single_tcg_cpu_thread
;
1958 static int tcg_region_inited
;
1960 assert(tcg_enabled());
1962 * Initialize TCG regions--once. Now is a good time, because:
1963 * (1) TCG's init context, prologue and target globals have been set up.
1964 * (2) qemu_tcg_mttcg_enabled() works now (TCG init code runs before the
1965 * -accel flag is processed, so the check doesn't work then).
1967 if (!tcg_region_inited
) {
1968 tcg_region_inited
= 1;
1972 if (qemu_tcg_mttcg_enabled() || !single_tcg_cpu_thread
) {
1973 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
1974 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
1975 qemu_cond_init(cpu
->halt_cond
);
1977 if (qemu_tcg_mttcg_enabled()) {
1978 /* create a thread per vCPU with TCG (MTTCG) */
1979 parallel_cpus
= true;
1980 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/TCG",
1983 qemu_thread_create(cpu
->thread
, thread_name
, qemu_tcg_cpu_thread_fn
,
1984 cpu
, QEMU_THREAD_JOINABLE
);
1987 /* share a single thread for all cpus with TCG */
1988 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "ALL CPUs/TCG");
1989 qemu_thread_create(cpu
->thread
, thread_name
,
1990 qemu_tcg_rr_cpu_thread_fn
,
1991 cpu
, QEMU_THREAD_JOINABLE
);
1993 single_tcg_halt_cond
= cpu
->halt_cond
;
1994 single_tcg_cpu_thread
= cpu
->thread
;
1997 cpu
->hThread
= qemu_thread_get_handle(cpu
->thread
);
2000 /* For non-MTTCG cases we share the thread */
2001 cpu
->thread
= single_tcg_cpu_thread
;
2002 cpu
->halt_cond
= single_tcg_halt_cond
;
2003 cpu
->thread_id
= first_cpu
->thread_id
;
2005 cpu
->created
= true;
2009 static void qemu_hax_start_vcpu(CPUState
*cpu
)
2011 char thread_name
[VCPU_THREAD_NAME_SIZE
];
2013 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
2014 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
2015 qemu_cond_init(cpu
->halt_cond
);
2017 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/HAX",
2019 qemu_thread_create(cpu
->thread
, thread_name
, qemu_hax_cpu_thread_fn
,
2020 cpu
, QEMU_THREAD_JOINABLE
);
2022 cpu
->hThread
= qemu_thread_get_handle(cpu
->thread
);
2026 static void qemu_kvm_start_vcpu(CPUState
*cpu
)
2028 char thread_name
[VCPU_THREAD_NAME_SIZE
];
2030 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
2031 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
2032 qemu_cond_init(cpu
->halt_cond
);
2033 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/KVM",
2035 qemu_thread_create(cpu
->thread
, thread_name
, qemu_kvm_cpu_thread_fn
,
2036 cpu
, QEMU_THREAD_JOINABLE
);
2039 static void qemu_hvf_start_vcpu(CPUState
*cpu
)
2041 char thread_name
[VCPU_THREAD_NAME_SIZE
];
2043 /* HVF currently does not support TCG, and only runs in
2044 * unrestricted-guest mode. */
2045 assert(hvf_enabled());
2047 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
2048 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
2049 qemu_cond_init(cpu
->halt_cond
);
2051 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/HVF",
2053 qemu_thread_create(cpu
->thread
, thread_name
, qemu_hvf_cpu_thread_fn
,
2054 cpu
, QEMU_THREAD_JOINABLE
);
2057 static void qemu_whpx_start_vcpu(CPUState
*cpu
)
2059 char thread_name
[VCPU_THREAD_NAME_SIZE
];
2061 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
2062 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
2063 qemu_cond_init(cpu
->halt_cond
);
2064 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/WHPX",
2066 qemu_thread_create(cpu
->thread
, thread_name
, qemu_whpx_cpu_thread_fn
,
2067 cpu
, QEMU_THREAD_JOINABLE
);
2069 cpu
->hThread
= qemu_thread_get_handle(cpu
->thread
);
2073 static void qemu_dummy_start_vcpu(CPUState
*cpu
)
2075 char thread_name
[VCPU_THREAD_NAME_SIZE
];
2077 cpu
->thread
= g_malloc0(sizeof(QemuThread
));
2078 cpu
->halt_cond
= g_malloc0(sizeof(QemuCond
));
2079 qemu_cond_init(cpu
->halt_cond
);
2080 snprintf(thread_name
, VCPU_THREAD_NAME_SIZE
, "CPU %d/DUMMY",
2082 qemu_thread_create(cpu
->thread
, thread_name
, qemu_dummy_cpu_thread_fn
, cpu
,
2083 QEMU_THREAD_JOINABLE
);
2086 void qemu_init_vcpu(CPUState
*cpu
)
2088 MachineState
*ms
= MACHINE(qdev_get_machine());
2090 cpu
->nr_cores
= ms
->smp
.cores
;
2091 cpu
->nr_threads
= ms
->smp
.threads
;
2092 cpu
->stopped
= true;
2093 cpu
->random_seed
= qemu_guest_random_seed_thread_part1();
2096 /* If the target cpu hasn't set up any address spaces itself,
2097 * give it the default one.
2100 cpu_address_space_init(cpu
, 0, "cpu-memory", cpu
->memory
);
2103 if (kvm_enabled()) {
2104 qemu_kvm_start_vcpu(cpu
);
2105 } else if (hax_enabled()) {
2106 qemu_hax_start_vcpu(cpu
);
2107 } else if (hvf_enabled()) {
2108 qemu_hvf_start_vcpu(cpu
);
2109 } else if (tcg_enabled()) {
2110 qemu_tcg_init_vcpu(cpu
);
2111 } else if (whpx_enabled()) {
2112 qemu_whpx_start_vcpu(cpu
);
2114 qemu_dummy_start_vcpu(cpu
);
2117 while (!cpu
->created
) {
2118 qemu_cond_wait(&qemu_cpu_cond
, &qemu_global_mutex
);
2122 void cpu_stop_current(void)
2125 current_cpu
->stop
= true;
2126 cpu_exit(current_cpu
);
2130 int vm_stop(RunState state
)
2132 if (qemu_in_vcpu_thread()) {
2133 qemu_system_vmstop_request_prepare();
2134 qemu_system_vmstop_request(state
);
2136 * FIXME: should not return to device code in case
2137 * vm_stop() has been requested.
2143 return do_vm_stop(state
, true);
2147 * Prepare for (re)starting the VM.
2148 * Returns -1 if the vCPUs are not to be restarted (e.g. if they are already
2149 * running or in case of an error condition), 0 otherwise.
2151 int vm_prepare_start(void)
2155 qemu_vmstop_requested(&requested
);
2156 if (runstate_is_running() && requested
== RUN_STATE__MAX
) {
2160 /* Ensure that a STOP/RESUME pair of events is emitted if a
2161 * vmstop request was pending. The BLOCK_IO_ERROR event, for
2162 * example, according to documentation is always followed by
2165 if (runstate_is_running()) {
2166 qapi_event_send_stop();
2167 qapi_event_send_resume();
2171 /* We are sending this now, but the CPUs will be resumed shortly later */
2172 qapi_event_send_resume();
2175 runstate_set(RUN_STATE_RUNNING
);
2176 vm_state_notify(1, RUN_STATE_RUNNING
);
2182 if (!vm_prepare_start()) {
2187 /* does a state transition even if the VM is already stopped,
2188 current state is forgotten forever */
2189 int vm_stop_force_state(RunState state
)
2191 if (runstate_is_running()) {
2192 return vm_stop(state
);
2194 runstate_set(state
);
2197 /* Make sure to return an error if the flush in a previous vm_stop()
2199 return bdrv_flush_all();
2203 void list_cpus(const char *optarg
)
2205 /* XXX: implement xxx_cpu_list for targets that still miss it */
2206 #if defined(cpu_list)
2211 void qmp_memsave(int64_t addr
, int64_t size
, const char *filename
,
2212 bool has_cpu
, int64_t cpu_index
, Error
**errp
)
2218 int64_t orig_addr
= addr
, orig_size
= size
;
2224 cpu
= qemu_get_cpu(cpu_index
);
2226 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cpu-index",
2231 f
= fopen(filename
, "wb");
2233 error_setg_file_open(errp
, errno
, filename
);
2241 if (cpu_memory_rw_debug(cpu
, addr
, buf
, l
, 0) != 0) {
2242 error_setg(errp
, "Invalid addr 0x%016" PRIx64
"/size %" PRId64
2243 " specified", orig_addr
, orig_size
);
2246 if (fwrite(buf
, 1, l
, f
) != l
) {
2247 error_setg(errp
, QERR_IO_ERROR
);
2258 void qmp_pmemsave(int64_t addr
, int64_t size
, const char *filename
,
2265 f
= fopen(filename
, "wb");
2267 error_setg_file_open(errp
, errno
, filename
);
2275 cpu_physical_memory_read(addr
, buf
, l
);
2276 if (fwrite(buf
, 1, l
, f
) != l
) {
2277 error_setg(errp
, QERR_IO_ERROR
);
2288 void qmp_inject_nmi(Error
**errp
)
2290 nmi_monitor_handle(monitor_get_cpu_index(), errp
);
2293 void dump_drift_info(void)
2299 qemu_printf("Host - Guest clock %"PRIi64
" ms\n",
2300 (cpu_get_clock() - cpu_get_icount())/SCALE_MS
);
2301 if (icount_align_option
) {
2302 qemu_printf("Max guest delay %"PRIi64
" ms\n",
2303 -max_delay
/ SCALE_MS
);
2304 qemu_printf("Max guest advance %"PRIi64
" ms\n",
2305 max_advance
/ SCALE_MS
);
2307 qemu_printf("Max guest delay NA\n");
2308 qemu_printf("Max guest advance NA\n");