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