xref: /qemu/system/cpus.c (revision 989dd906ed5556563a57b32ae7abf9db5e1f38ba)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "monitor/monitor.h"
27 #include "qemu/coroutine-tls.h"
28 #include "qapi/error.h"
29 #include "qapi/qapi-commands-machine.h"
30 #include "qapi/qapi-commands-misc.h"
31 #include "qapi/qapi-events-run-state.h"
32 #include "qapi/qmp/qerror.h"
33 #include "exec/gdbstub.h"
34 #include "system/accel-ops.h"
35 #include "system/hw_accel.h"
36 #include "exec/cpu-common.h"
37 #include "qemu/thread.h"
38 #include "qemu/main-loop.h"
39 #include "qemu/plugin.h"
40 #include "system/cpus.h"
41 #include "qemu/guest-random.h"
42 #include "hw/nmi.h"
43 #include "system/replay.h"
44 #include "system/runstate.h"
45 #include "system/cpu-timers.h"
46 #include "system/whpx.h"
47 #include "hw/boards.h"
48 #include "hw/hw.h"
49 #include "trace.h"
50 
51 #ifdef CONFIG_LINUX
52 
53 #include <sys/prctl.h>
54 
55 #ifndef PR_MCE_KILL
56 #define PR_MCE_KILL 33
57 #endif
58 
59 #ifndef PR_MCE_KILL_SET
60 #define PR_MCE_KILL_SET 1
61 #endif
62 
63 #ifndef PR_MCE_KILL_EARLY
64 #define PR_MCE_KILL_EARLY 1
65 #endif
66 
67 #endif /* CONFIG_LINUX */
68 
69 /* The Big QEMU Lock (BQL) */
70 static QemuMutex bql;
71 
72 /*
73  * The chosen accelerator is supposed to register this.
74  */
75 static const AccelOpsClass *cpus_accel;
76 
cpu_is_stopped(CPUState * cpu)77 bool cpu_is_stopped(CPUState *cpu)
78 {
79     return cpu->stopped || !runstate_is_running();
80 }
81 
cpu_work_list_empty(CPUState * cpu)82 bool cpu_work_list_empty(CPUState *cpu)
83 {
84     return QSIMPLEQ_EMPTY_ATOMIC(&cpu->work_list);
85 }
86 
cpu_thread_is_idle(CPUState * cpu)87 bool cpu_thread_is_idle(CPUState *cpu)
88 {
89     if (cpu->stop || !cpu_work_list_empty(cpu)) {
90         return false;
91     }
92     if (cpu_is_stopped(cpu)) {
93         return true;
94     }
95     if (!cpu->halted || cpu_has_work(cpu)) {
96         return false;
97     }
98     if (cpus_accel->cpu_thread_is_idle) {
99         return cpus_accel->cpu_thread_is_idle(cpu);
100     }
101     return true;
102 }
103 
all_cpu_threads_idle(void)104 bool all_cpu_threads_idle(void)
105 {
106     CPUState *cpu;
107 
108     CPU_FOREACH(cpu) {
109         if (!cpu_thread_is_idle(cpu)) {
110             return false;
111         }
112     }
113     return true;
114 }
115 
116 /***********************************************************/
hw_error(const char * fmt,...)117 void hw_error(const char *fmt, ...)
118 {
119     va_list ap;
120     CPUState *cpu;
121 
122     va_start(ap, fmt);
123     fprintf(stderr, "qemu: hardware error: ");
124     vfprintf(stderr, fmt, ap);
125     fprintf(stderr, "\n");
126     CPU_FOREACH(cpu) {
127         fprintf(stderr, "CPU #%d:\n", cpu->cpu_index);
128         cpu_dump_state(cpu, stderr, CPU_DUMP_FPU);
129     }
130     va_end(ap);
131     abort();
132 }
133 
cpu_synchronize_all_states(void)134 void cpu_synchronize_all_states(void)
135 {
136     CPUState *cpu;
137 
138     CPU_FOREACH(cpu) {
139         cpu_synchronize_state(cpu);
140     }
141 }
142 
cpu_synchronize_all_post_reset(void)143 void cpu_synchronize_all_post_reset(void)
144 {
145     CPUState *cpu;
146 
147     CPU_FOREACH(cpu) {
148         cpu_synchronize_post_reset(cpu);
149     }
150 }
151 
cpu_synchronize_all_post_init(void)152 void cpu_synchronize_all_post_init(void)
153 {
154     CPUState *cpu;
155 
156     CPU_FOREACH(cpu) {
157         cpu_synchronize_post_init(cpu);
158     }
159 }
160 
cpu_synchronize_all_pre_loadvm(void)161 void cpu_synchronize_all_pre_loadvm(void)
162 {
163     CPUState *cpu;
164 
165     CPU_FOREACH(cpu) {
166         cpu_synchronize_pre_loadvm(cpu);
167     }
168 }
169 
cpu_synchronize_state(CPUState * cpu)170 void cpu_synchronize_state(CPUState *cpu)
171 {
172     if (cpus_accel->synchronize_state) {
173         cpus_accel->synchronize_state(cpu);
174     }
175 }
176 
cpu_synchronize_post_reset(CPUState * cpu)177 void cpu_synchronize_post_reset(CPUState *cpu)
178 {
179     if (cpus_accel->synchronize_post_reset) {
180         cpus_accel->synchronize_post_reset(cpu);
181     }
182 }
183 
cpu_synchronize_post_init(CPUState * cpu)184 void cpu_synchronize_post_init(CPUState *cpu)
185 {
186     if (cpus_accel->synchronize_post_init) {
187         cpus_accel->synchronize_post_init(cpu);
188     }
189 }
190 
cpu_synchronize_pre_loadvm(CPUState * cpu)191 void cpu_synchronize_pre_loadvm(CPUState *cpu)
192 {
193     if (cpus_accel->synchronize_pre_loadvm) {
194         cpus_accel->synchronize_pre_loadvm(cpu);
195     }
196 }
197 
cpus_are_resettable(void)198 bool cpus_are_resettable(void)
199 {
200     if (cpus_accel->cpus_are_resettable) {
201         return cpus_accel->cpus_are_resettable();
202     }
203     return true;
204 }
205 
cpu_exec_reset_hold(CPUState * cpu)206 void cpu_exec_reset_hold(CPUState *cpu)
207 {
208     if (cpus_accel->cpu_reset_hold) {
209         cpus_accel->cpu_reset_hold(cpu);
210     }
211 }
212 
cpus_get_virtual_clock(void)213 int64_t cpus_get_virtual_clock(void)
214 {
215     /*
216      * XXX
217      *
218      * need to check that cpus_accel is not NULL, because qcow2 calls
219      * qemu_get_clock_ns(CLOCK_VIRTUAL) without any accel initialized and
220      * with ticks disabled in some io-tests:
221      * 030 040 041 060 099 120 127 140 156 161 172 181 191 192 195 203 229 249 256 267
222      *
223      * is this expected?
224      *
225      * XXX
226      */
227     if (cpus_accel && cpus_accel->get_virtual_clock) {
228         return cpus_accel->get_virtual_clock();
229     }
230     return cpu_get_clock();
231 }
232 
233 /*
234  * Signal the new virtual time to the accelerator. This is only needed
235  * by accelerators that need to track the changes as we warp time.
236  */
cpus_set_virtual_clock(int64_t new_time)237 void cpus_set_virtual_clock(int64_t new_time)
238 {
239     if (cpus_accel && cpus_accel->set_virtual_clock) {
240         cpus_accel->set_virtual_clock(new_time);
241     }
242 }
243 
244 /*
245  * return the time elapsed in VM between vm_start and vm_stop.  Unless
246  * icount is active, cpus_get_elapsed_ticks() uses units of the host CPU cycle
247  * counter.
248  */
cpus_get_elapsed_ticks(void)249 int64_t cpus_get_elapsed_ticks(void)
250 {
251     if (cpus_accel->get_elapsed_ticks) {
252         return cpus_accel->get_elapsed_ticks();
253     }
254     return cpu_get_ticks();
255 }
256 
generic_handle_interrupt(CPUState * cpu,int mask)257 void generic_handle_interrupt(CPUState *cpu, int mask)
258 {
259     cpu->interrupt_request |= mask;
260 
261     if (!qemu_cpu_is_self(cpu)) {
262         qemu_cpu_kick(cpu);
263     }
264 }
265 
cpu_interrupt(CPUState * cpu,int mask)266 void cpu_interrupt(CPUState *cpu, int mask)
267 {
268     g_assert(bql_locked());
269 
270     cpus_accel->handle_interrupt(cpu, mask);
271 }
272 
273 /*
274  * True if the vm was previously suspended, and has not been woken or reset.
275  */
276 static int vm_was_suspended;
277 
vm_set_suspended(bool suspended)278 void vm_set_suspended(bool suspended)
279 {
280     vm_was_suspended = suspended;
281 }
282 
vm_get_suspended(void)283 bool vm_get_suspended(void)
284 {
285     return vm_was_suspended;
286 }
287 
do_vm_stop(RunState state,bool send_stop)288 static int do_vm_stop(RunState state, bool send_stop)
289 {
290     int ret = 0;
291     RunState oldstate = runstate_get();
292 
293     if (runstate_is_live(oldstate)) {
294         vm_was_suspended = (oldstate == RUN_STATE_SUSPENDED);
295         runstate_set(state);
296         cpu_disable_ticks();
297         if (oldstate == RUN_STATE_RUNNING) {
298             pause_all_vcpus();
299         }
300         ret = vm_state_notify(0, state);
301         if (send_stop) {
302             qapi_event_send_stop();
303         }
304     }
305 
306     bdrv_drain_all();
307     /*
308      * Even if vm_state_notify() return failure,
309      * it would be better to flush as before.
310      */
311     ret |= bdrv_flush_all();
312     trace_vm_stop_flush_all(ret);
313 
314     return ret;
315 }
316 
317 /* Special vm_stop() variant for terminating the process.  Historically clients
318  * did not expect a QMP STOP event and so we need to retain compatibility.
319  */
vm_shutdown(void)320 int vm_shutdown(void)
321 {
322     return do_vm_stop(RUN_STATE_SHUTDOWN, false);
323 }
324 
cpu_can_run(CPUState * cpu)325 bool cpu_can_run(CPUState *cpu)
326 {
327     if (cpu->stop) {
328         return false;
329     }
330     if (cpu_is_stopped(cpu)) {
331         return false;
332     }
333     return true;
334 }
335 
cpu_handle_guest_debug(CPUState * cpu)336 void cpu_handle_guest_debug(CPUState *cpu)
337 {
338     if (replay_running_debug()) {
339         if (!cpu->singlestep_enabled) {
340             /*
341              * Report about the breakpoint and
342              * make a single step to skip it
343              */
344             replay_breakpoint();
345             cpu_single_step(cpu, SSTEP_ENABLE);
346         } else {
347             cpu_single_step(cpu, 0);
348         }
349     } else {
350         gdb_set_stop_cpu(cpu);
351         qemu_system_debug_request();
352         cpu->stopped = true;
353     }
354 }
355 
356 #ifdef CONFIG_LINUX
sigbus_reraise(void)357 static void sigbus_reraise(void)
358 {
359     sigset_t set;
360     struct sigaction action;
361 
362     memset(&action, 0, sizeof(action));
363     action.sa_handler = SIG_DFL;
364     if (!sigaction(SIGBUS, &action, NULL)) {
365         raise(SIGBUS);
366         sigemptyset(&set);
367         sigaddset(&set, SIGBUS);
368         pthread_sigmask(SIG_UNBLOCK, &set, NULL);
369     }
370     perror("Failed to re-raise SIGBUS!");
371     abort();
372 }
373 
sigbus_handler(int n,siginfo_t * siginfo,void * ctx)374 static void sigbus_handler(int n, siginfo_t *siginfo, void *ctx)
375 {
376     if (siginfo->si_code != BUS_MCEERR_AO && siginfo->si_code != BUS_MCEERR_AR) {
377         sigbus_reraise();
378     }
379 
380     if (current_cpu) {
381         /* Called asynchronously in VCPU thread.  */
382         if (kvm_on_sigbus_vcpu(current_cpu, siginfo->si_code, siginfo->si_addr)) {
383             sigbus_reraise();
384         }
385     } else {
386         /* Called synchronously (via signalfd) in main thread.  */
387         if (kvm_on_sigbus(siginfo->si_code, siginfo->si_addr)) {
388             sigbus_reraise();
389         }
390     }
391 }
392 
qemu_init_sigbus(void)393 static void qemu_init_sigbus(void)
394 {
395     struct sigaction action;
396 
397     /*
398      * ALERT: when modifying this, take care that SIGBUS forwarding in
399      * qemu_prealloc_mem() will continue working as expected.
400      */
401     memset(&action, 0, sizeof(action));
402     action.sa_flags = SA_SIGINFO;
403     action.sa_sigaction = sigbus_handler;
404     sigaction(SIGBUS, &action, NULL);
405 
406     prctl(PR_MCE_KILL, PR_MCE_KILL_SET, PR_MCE_KILL_EARLY, 0, 0);
407 }
408 #else /* !CONFIG_LINUX */
qemu_init_sigbus(void)409 static void qemu_init_sigbus(void)
410 {
411 }
412 #endif /* !CONFIG_LINUX */
413 
414 static QemuThread io_thread;
415 
416 /* cpu creation */
417 static QemuCond qemu_cpu_cond;
418 /* system init */
419 static QemuCond qemu_pause_cond;
420 
qemu_init_cpu_loop(void)421 void qemu_init_cpu_loop(void)
422 {
423     qemu_init_sigbus();
424     qemu_cond_init(&qemu_cpu_cond);
425     qemu_cond_init(&qemu_pause_cond);
426     qemu_mutex_init(&bql);
427 
428     qemu_thread_get_self(&io_thread);
429 }
430 
run_on_cpu(CPUState * cpu,run_on_cpu_func func,run_on_cpu_data data)431 void run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data)
432 {
433     do_run_on_cpu(cpu, func, data, &bql);
434 }
435 
qemu_cpu_stop(CPUState * cpu,bool exit)436 static void qemu_cpu_stop(CPUState *cpu, bool exit)
437 {
438     g_assert(qemu_cpu_is_self(cpu));
439     cpu->stop = false;
440     cpu->stopped = true;
441     if (exit) {
442         cpu_exit(cpu);
443     }
444     qemu_cond_broadcast(&qemu_pause_cond);
445 }
446 
qemu_wait_io_event_common(CPUState * cpu)447 void qemu_wait_io_event_common(CPUState *cpu)
448 {
449     qatomic_set_mb(&cpu->thread_kicked, false);
450     if (cpu->stop) {
451         qemu_cpu_stop(cpu, false);
452     }
453     process_queued_cpu_work(cpu);
454 }
455 
qemu_wait_io_event(CPUState * cpu)456 void qemu_wait_io_event(CPUState *cpu)
457 {
458     bool slept = false;
459 
460     while (cpu_thread_is_idle(cpu)) {
461         if (!slept) {
462             slept = true;
463             qemu_plugin_vcpu_idle_cb(cpu);
464         }
465         qemu_cond_wait(cpu->halt_cond, &bql);
466     }
467     if (slept) {
468         qemu_plugin_vcpu_resume_cb(cpu);
469     }
470 
471     qemu_wait_io_event_common(cpu);
472 }
473 
cpus_kick_thread(CPUState * cpu)474 void cpus_kick_thread(CPUState *cpu)
475 {
476     if (cpu->thread_kicked) {
477         return;
478     }
479     cpu->thread_kicked = true;
480 
481 #ifndef _WIN32
482     int err = pthread_kill(cpu->thread->thread, SIG_IPI);
483     if (err && err != ESRCH) {
484         fprintf(stderr, "qemu:%s: %s", __func__, strerror(err));
485         exit(1);
486     }
487 #else
488     qemu_sem_post(&cpu->sem);
489 #endif
490 }
491 
qemu_cpu_kick(CPUState * cpu)492 void qemu_cpu_kick(CPUState *cpu)
493 {
494     qemu_cond_broadcast(cpu->halt_cond);
495     if (cpus_accel->kick_vcpu_thread) {
496         cpus_accel->kick_vcpu_thread(cpu);
497     } else { /* default */
498         cpus_kick_thread(cpu);
499     }
500 }
501 
qemu_cpu_kick_self(void)502 void qemu_cpu_kick_self(void)
503 {
504     assert(current_cpu);
505     cpus_kick_thread(current_cpu);
506 }
507 
qemu_cpu_is_self(CPUState * cpu)508 bool qemu_cpu_is_self(CPUState *cpu)
509 {
510     return qemu_thread_is_self(cpu->thread);
511 }
512 
qemu_in_vcpu_thread(void)513 bool qemu_in_vcpu_thread(void)
514 {
515     return current_cpu && qemu_cpu_is_self(current_cpu);
516 }
517 
518 QEMU_DEFINE_STATIC_CO_TLS(bool, bql_locked)
519 
520 static uint32_t bql_unlock_blocked;
521 
bql_block_unlock(bool increase)522 void bql_block_unlock(bool increase)
523 {
524     uint32_t new_value;
525 
526     assert(bql_locked());
527 
528     /* check for overflow! */
529     new_value = bql_unlock_blocked + increase - !increase;
530     assert((new_value > bql_unlock_blocked) == increase);
531     bql_unlock_blocked = new_value;
532 }
533 
bql_locked(void)534 bool bql_locked(void)
535 {
536     return get_bql_locked();
537 }
538 
qemu_in_main_thread(void)539 bool qemu_in_main_thread(void)
540 {
541     return bql_locked();
542 }
543 
rust_bql_mock_lock(void)544 void rust_bql_mock_lock(void)
545 {
546     error_report("This function should be used only from tests");
547     abort();
548 }
549 
550 /*
551  * The BQL is taken from so many places that it is worth profiling the
552  * callers directly, instead of funneling them all through a single function.
553  */
bql_lock_impl(const char * file,int line)554 void bql_lock_impl(const char *file, int line)
555 {
556     QemuMutexLockFunc bql_lock_fn = qatomic_read(&bql_mutex_lock_func);
557 
558     g_assert(!bql_locked());
559     bql_lock_fn(&bql, file, line);
560     set_bql_locked(true);
561 }
562 
bql_unlock(void)563 void bql_unlock(void)
564 {
565     g_assert(bql_locked());
566     g_assert(!bql_unlock_blocked);
567     set_bql_locked(false);
568     qemu_mutex_unlock(&bql);
569 }
570 
qemu_cond_wait_bql(QemuCond * cond)571 void qemu_cond_wait_bql(QemuCond *cond)
572 {
573     qemu_cond_wait(cond, &bql);
574 }
575 
qemu_cond_timedwait_bql(QemuCond * cond,int ms)576 void qemu_cond_timedwait_bql(QemuCond *cond, int ms)
577 {
578     qemu_cond_timedwait(cond, &bql, ms);
579 }
580 
581 /* signal CPU creation */
cpu_thread_signal_created(CPUState * cpu)582 void cpu_thread_signal_created(CPUState *cpu)
583 {
584     cpu->created = true;
585     qemu_cond_signal(&qemu_cpu_cond);
586 }
587 
588 /* signal CPU destruction */
cpu_thread_signal_destroyed(CPUState * cpu)589 void cpu_thread_signal_destroyed(CPUState *cpu)
590 {
591     cpu->created = false;
592     qemu_cond_signal(&qemu_cpu_cond);
593 }
594 
cpu_pause(CPUState * cpu)595 void cpu_pause(CPUState *cpu)
596 {
597     if (qemu_cpu_is_self(cpu)) {
598         qemu_cpu_stop(cpu, true);
599     } else {
600         cpu->stop = true;
601         qemu_cpu_kick(cpu);
602     }
603 }
604 
cpu_resume(CPUState * cpu)605 void cpu_resume(CPUState *cpu)
606 {
607     cpu->stop = false;
608     cpu->stopped = false;
609     qemu_cpu_kick(cpu);
610 }
611 
all_vcpus_paused(void)612 static bool all_vcpus_paused(void)
613 {
614     CPUState *cpu;
615 
616     CPU_FOREACH(cpu) {
617         if (!cpu->stopped) {
618             return false;
619         }
620     }
621 
622     return true;
623 }
624 
pause_all_vcpus(void)625 void pause_all_vcpus(void)
626 {
627     CPUState *cpu;
628 
629     qemu_clock_enable(QEMU_CLOCK_VIRTUAL, false);
630     CPU_FOREACH(cpu) {
631         cpu_pause(cpu);
632     }
633 
634     /* We need to drop the replay_lock so any vCPU threads woken up
635      * can finish their replay tasks
636      */
637     replay_mutex_unlock();
638 
639     while (!all_vcpus_paused()) {
640         qemu_cond_wait(&qemu_pause_cond, &bql);
641         CPU_FOREACH(cpu) {
642             qemu_cpu_kick(cpu);
643         }
644     }
645 
646     bql_unlock();
647     replay_mutex_lock();
648     bql_lock();
649 }
650 
resume_all_vcpus(void)651 void resume_all_vcpus(void)
652 {
653     CPUState *cpu;
654 
655     if (!runstate_is_running()) {
656         return;
657     }
658 
659     qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
660     CPU_FOREACH(cpu) {
661         cpu_resume(cpu);
662     }
663 }
664 
cpu_remove_sync(CPUState * cpu)665 void cpu_remove_sync(CPUState *cpu)
666 {
667     cpu->stop = true;
668     cpu->unplug = true;
669     qemu_cpu_kick(cpu);
670     bql_unlock();
671     qemu_thread_join(cpu->thread);
672     bql_lock();
673 }
674 
cpus_register_accel(const AccelOpsClass * ops)675 void cpus_register_accel(const AccelOpsClass *ops)
676 {
677     assert(ops != NULL);
678     assert(ops->create_vcpu_thread != NULL); /* mandatory */
679     assert(ops->handle_interrupt);
680 
681     cpus_accel = ops;
682 }
683 
cpus_get_accel(void)684 const AccelOpsClass *cpus_get_accel(void)
685 {
686     /* broken if we call this early */
687     assert(cpus_accel);
688     return cpus_accel;
689 }
690 
qemu_init_vcpu(CPUState * cpu)691 void qemu_init_vcpu(CPUState *cpu)
692 {
693     MachineState *ms = MACHINE(qdev_get_machine());
694 
695     cpu->nr_threads =  ms->smp.threads;
696     cpu->stopped = true;
697     cpu->random_seed = qemu_guest_random_seed_thread_part1();
698 
699     if (!cpu->as) {
700         /* If the target cpu hasn't set up any address spaces itself,
701          * give it the default one.
702          */
703         cpu->num_ases = 1;
704         cpu_address_space_init(cpu, 0, "cpu-memory", cpu->memory);
705     }
706 
707     /* accelerators all implement the AccelOpsClass */
708     g_assert(cpus_accel != NULL && cpus_accel->create_vcpu_thread != NULL);
709     cpus_accel->create_vcpu_thread(cpu);
710 
711     while (!cpu->created) {
712         qemu_cond_wait(&qemu_cpu_cond, &bql);
713     }
714 }
715 
cpu_stop_current(void)716 void cpu_stop_current(void)
717 {
718     if (current_cpu) {
719         current_cpu->stop = true;
720         cpu_exit(current_cpu);
721     }
722 }
723 
vm_stop(RunState state)724 int vm_stop(RunState state)
725 {
726     if (qemu_in_vcpu_thread()) {
727         qemu_system_vmstop_request_prepare();
728         qemu_system_vmstop_request(state);
729         /*
730          * FIXME: should not return to device code in case
731          * vm_stop() has been requested.
732          */
733         cpu_stop_current();
734         return 0;
735     }
736 
737     return do_vm_stop(state, true);
738 }
739 
740 /**
741  * Prepare for (re)starting the VM.
742  * Returns 0 if the vCPUs should be restarted, -1 on an error condition,
743  * and 1 otherwise.
744  */
vm_prepare_start(bool step_pending)745 int vm_prepare_start(bool step_pending)
746 {
747     int ret = vm_was_suspended ? 1 : 0;
748     RunState state = vm_was_suspended ? RUN_STATE_SUSPENDED : RUN_STATE_RUNNING;
749     RunState requested;
750 
751     qemu_vmstop_requested(&requested);
752     if (runstate_is_running() && requested == RUN_STATE__MAX) {
753         return -1;
754     }
755 
756     /* Ensure that a STOP/RESUME pair of events is emitted if a
757      * vmstop request was pending.  The BLOCK_IO_ERROR event, for
758      * example, according to documentation is always followed by
759      * the STOP event.
760      */
761     if (runstate_is_running()) {
762         qapi_event_send_stop();
763         qapi_event_send_resume();
764         return -1;
765     }
766 
767     /*
768      * WHPX accelerator needs to know whether we are going to step
769      * any CPUs, before starting the first one.
770      */
771     if (cpus_accel->synchronize_pre_resume) {
772         cpus_accel->synchronize_pre_resume(step_pending);
773     }
774 
775     /* We are sending this now, but the CPUs will be resumed shortly later */
776     qapi_event_send_resume();
777 
778     cpu_enable_ticks();
779     runstate_set(state);
780     vm_state_notify(1, state);
781     vm_was_suspended = false;
782     return ret;
783 }
784 
vm_start(void)785 void vm_start(void)
786 {
787     if (!vm_prepare_start(false)) {
788         resume_all_vcpus();
789     }
790 }
791 
vm_resume(RunState state)792 void vm_resume(RunState state)
793 {
794     if (runstate_is_live(state)) {
795         vm_start();
796     } else {
797         runstate_set(state);
798     }
799 }
800 
801 /* does a state transition even if the VM is already stopped,
802    current state is forgotten forever */
vm_stop_force_state(RunState state)803 int vm_stop_force_state(RunState state)
804 {
805     if (runstate_is_live(runstate_get())) {
806         return vm_stop(state);
807     } else {
808         int ret;
809         runstate_set(state);
810 
811         bdrv_drain_all();
812         /* Make sure to return an error if the flush in a previous vm_stop()
813          * failed. */
814         ret = bdrv_flush_all();
815         trace_vm_stop_flush_all(ret);
816         return ret;
817     }
818 }
819 
qmp_memsave(uint64_t addr,uint64_t size,const char * filename,bool has_cpu,int64_t cpu_index,Error ** errp)820 void qmp_memsave(uint64_t addr, uint64_t size, const char *filename,
821                  bool has_cpu, int64_t cpu_index, Error **errp)
822 {
823     FILE *f;
824     uint64_t l;
825     CPUState *cpu;
826     uint8_t buf[1024];
827     uint64_t orig_addr = addr, orig_size = size;
828 
829     if (!has_cpu) {
830         cpu_index = 0;
831     }
832 
833     cpu = qemu_get_cpu(cpu_index);
834     if (cpu == NULL) {
835         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
836                    "a CPU number");
837         return;
838     }
839 
840     f = fopen(filename, "wb");
841     if (!f) {
842         error_setg_file_open(errp, errno, filename);
843         return;
844     }
845 
846     while (size != 0) {
847         l = sizeof(buf);
848         if (l > size)
849             l = size;
850         if (cpu_memory_rw_debug(cpu, addr, buf, l, 0) != 0) {
851             error_setg(errp, "Invalid addr 0x%016" PRIx64 "/size %" PRIu64
852                              " specified", orig_addr, orig_size);
853             goto exit;
854         }
855         if (fwrite(buf, 1, l, f) != l) {
856             error_setg(errp, "writing memory to '%s' failed",
857                        filename);
858             goto exit;
859         }
860         addr += l;
861         size -= l;
862     }
863 
864 exit:
865     fclose(f);
866 }
867 
qmp_pmemsave(uint64_t addr,uint64_t size,const char * filename,Error ** errp)868 void qmp_pmemsave(uint64_t addr, uint64_t size, const char *filename,
869                   Error **errp)
870 {
871     FILE *f;
872     uint64_t l;
873     uint8_t buf[1024];
874 
875     f = fopen(filename, "wb");
876     if (!f) {
877         error_setg_file_open(errp, errno, filename);
878         return;
879     }
880 
881     while (size != 0) {
882         l = sizeof(buf);
883         if (l > size)
884             l = size;
885         cpu_physical_memory_read(addr, buf, l);
886         if (fwrite(buf, 1, l, f) != l) {
887             error_setg(errp, "writing memory to '%s' failed",
888                        filename);
889             goto exit;
890         }
891         addr += l;
892         size -= l;
893     }
894 
895 exit:
896     fclose(f);
897 }
898 
qmp_inject_nmi(Error ** errp)899 void qmp_inject_nmi(Error **errp)
900 {
901     nmi_monitor_handle(monitor_get_cpu_index(monitor_cur()), errp);
902 }
903 
904