hw/ppc/spapr_drc.c: use g_autofree in drc_unrealize()
[qemu.git] / softmmu / cpus.c
blob035395ae13e78f2664cc510deaeb14f75631aa2b
1 /*
2 * QEMU System Emulator
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
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "qemu-common.h"
27 #include "monitor/monitor.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 "sysemu/hw_accel.h"
35 #include "exec/exec-all.h"
36 #include "qemu/thread.h"
37 #include "qemu/plugin.h"
38 #include "sysemu/cpus.h"
39 #include "qemu/guest-random.h"
40 #include "hw/nmi.h"
41 #include "sysemu/replay.h"
42 #include "sysemu/runstate.h"
43 #include "sysemu/cpu-timers.h"
44 #include "sysemu/whpx.h"
45 #include "hw/boards.h"
46 #include "hw/hw.h"
47 #include "trace.h"
49 #ifdef CONFIG_LINUX
51 #include <sys/prctl.h>
53 #ifndef PR_MCE_KILL
54 #define PR_MCE_KILL 33
55 #endif
57 #ifndef PR_MCE_KILL_SET
58 #define PR_MCE_KILL_SET 1
59 #endif
61 #ifndef PR_MCE_KILL_EARLY
62 #define PR_MCE_KILL_EARLY 1
63 #endif
65 #endif /* CONFIG_LINUX */
67 static QemuMutex qemu_global_mutex;
69 bool cpu_is_stopped(CPUState *cpu)
71 return cpu->stopped || !runstate_is_running();
74 bool cpu_work_list_empty(CPUState *cpu)
76 return QSIMPLEQ_EMPTY_ATOMIC(&cpu->work_list);
79 bool cpu_thread_is_idle(CPUState *cpu)
81 if (cpu->stop || !cpu_work_list_empty(cpu)) {
82 return false;
84 if (cpu_is_stopped(cpu)) {
85 return true;
87 if (!cpu->halted || cpu_has_work(cpu) ||
88 kvm_halt_in_kernel() || whpx_apic_in_platform()) {
89 return false;
91 return true;
94 bool all_cpu_threads_idle(void)
96 CPUState *cpu;
98 CPU_FOREACH(cpu) {
99 if (!cpu_thread_is_idle(cpu)) {
100 return false;
103 return true;
106 /***********************************************************/
107 void hw_error(const char *fmt, ...)
109 va_list ap;
110 CPUState *cpu;
112 va_start(ap, fmt);
113 fprintf(stderr, "qemu: hardware error: ");
114 vfprintf(stderr, fmt, ap);
115 fprintf(stderr, "\n");
116 CPU_FOREACH(cpu) {
117 fprintf(stderr, "CPU #%d:\n", cpu->cpu_index);
118 cpu_dump_state(cpu, stderr, CPU_DUMP_FPU);
120 va_end(ap);
121 abort();
125 * The chosen accelerator is supposed to register this.
127 static const AccelOpsClass *cpus_accel;
129 void cpu_synchronize_all_states(void)
131 CPUState *cpu;
133 CPU_FOREACH(cpu) {
134 cpu_synchronize_state(cpu);
138 void cpu_synchronize_all_post_reset(void)
140 CPUState *cpu;
142 CPU_FOREACH(cpu) {
143 cpu_synchronize_post_reset(cpu);
147 void cpu_synchronize_all_post_init(void)
149 CPUState *cpu;
151 CPU_FOREACH(cpu) {
152 cpu_synchronize_post_init(cpu);
156 void cpu_synchronize_all_pre_loadvm(void)
158 CPUState *cpu;
160 CPU_FOREACH(cpu) {
161 cpu_synchronize_pre_loadvm(cpu);
165 void cpu_synchronize_state(CPUState *cpu)
167 if (cpus_accel->synchronize_state) {
168 cpus_accel->synchronize_state(cpu);
172 void cpu_synchronize_post_reset(CPUState *cpu)
174 if (cpus_accel->synchronize_post_reset) {
175 cpus_accel->synchronize_post_reset(cpu);
179 void cpu_synchronize_post_init(CPUState *cpu)
181 if (cpus_accel->synchronize_post_init) {
182 cpus_accel->synchronize_post_init(cpu);
186 void cpu_synchronize_pre_loadvm(CPUState *cpu)
188 if (cpus_accel->synchronize_pre_loadvm) {
189 cpus_accel->synchronize_pre_loadvm(cpu);
193 bool cpus_are_resettable(void)
195 return cpu_check_are_resettable();
198 int64_t cpus_get_virtual_clock(void)
201 * XXX
203 * need to check that cpus_accel is not NULL, because qcow2 calls
204 * qemu_get_clock_ns(CLOCK_VIRTUAL) without any accel initialized and
205 * with ticks disabled in some io-tests:
206 * 030 040 041 060 099 120 127 140 156 161 172 181 191 192 195 203 229 249 256 267
208 * is this expected?
210 * XXX
212 if (cpus_accel && cpus_accel->get_virtual_clock) {
213 return cpus_accel->get_virtual_clock();
215 return cpu_get_clock();
219 * return the time elapsed in VM between vm_start and vm_stop. Unless
220 * icount is active, cpus_get_elapsed_ticks() uses units of the host CPU cycle
221 * counter.
223 int64_t cpus_get_elapsed_ticks(void)
225 if (cpus_accel->get_elapsed_ticks) {
226 return cpus_accel->get_elapsed_ticks();
228 return cpu_get_ticks();
231 static void generic_handle_interrupt(CPUState *cpu, int mask)
233 cpu->interrupt_request |= mask;
235 if (!qemu_cpu_is_self(cpu)) {
236 qemu_cpu_kick(cpu);
240 void cpu_interrupt(CPUState *cpu, int mask)
242 if (cpus_accel->handle_interrupt) {
243 cpus_accel->handle_interrupt(cpu, mask);
244 } else {
245 generic_handle_interrupt(cpu, mask);
249 static int do_vm_stop(RunState state, bool send_stop)
251 int ret = 0;
253 if (runstate_is_running()) {
254 runstate_set(state);
255 cpu_disable_ticks();
256 pause_all_vcpus();
257 vm_state_notify(0, state);
258 if (send_stop) {
259 qapi_event_send_stop();
263 bdrv_drain_all();
264 ret = bdrv_flush_all();
265 trace_vm_stop_flush_all(ret);
267 return ret;
270 /* Special vm_stop() variant for terminating the process. Historically clients
271 * did not expect a QMP STOP event and so we need to retain compatibility.
273 int vm_shutdown(void)
275 return do_vm_stop(RUN_STATE_SHUTDOWN, false);
278 bool cpu_can_run(CPUState *cpu)
280 if (cpu->stop) {
281 return false;
283 if (cpu_is_stopped(cpu)) {
284 return false;
286 return true;
289 void cpu_handle_guest_debug(CPUState *cpu)
291 if (replay_running_debug()) {
292 if (!cpu->singlestep_enabled) {
294 * Report about the breakpoint and
295 * make a single step to skip it
297 replay_breakpoint();
298 cpu_single_step(cpu, SSTEP_ENABLE);
299 } else {
300 cpu_single_step(cpu, 0);
302 } else {
303 gdb_set_stop_cpu(cpu);
304 qemu_system_debug_request();
305 cpu->stopped = true;
309 #ifdef CONFIG_LINUX
310 static void sigbus_reraise(void)
312 sigset_t set;
313 struct sigaction action;
315 memset(&action, 0, sizeof(action));
316 action.sa_handler = SIG_DFL;
317 if (!sigaction(SIGBUS, &action, NULL)) {
318 raise(SIGBUS);
319 sigemptyset(&set);
320 sigaddset(&set, SIGBUS);
321 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
323 perror("Failed to re-raise SIGBUS!");
324 abort();
327 static void sigbus_handler(int n, siginfo_t *siginfo, void *ctx)
329 if (siginfo->si_code != BUS_MCEERR_AO && siginfo->si_code != BUS_MCEERR_AR) {
330 sigbus_reraise();
333 if (current_cpu) {
334 /* Called asynchronously in VCPU thread. */
335 if (kvm_on_sigbus_vcpu(current_cpu, siginfo->si_code, siginfo->si_addr)) {
336 sigbus_reraise();
338 } else {
339 /* Called synchronously (via signalfd) in main thread. */
340 if (kvm_on_sigbus(siginfo->si_code, siginfo->si_addr)) {
341 sigbus_reraise();
346 static void qemu_init_sigbus(void)
348 struct sigaction action;
351 * ALERT: when modifying this, take care that SIGBUS forwarding in
352 * os_mem_prealloc() will continue working as expected.
354 memset(&action, 0, sizeof(action));
355 action.sa_flags = SA_SIGINFO;
356 action.sa_sigaction = sigbus_handler;
357 sigaction(SIGBUS, &action, NULL);
359 prctl(PR_MCE_KILL, PR_MCE_KILL_SET, PR_MCE_KILL_EARLY, 0, 0);
361 #else /* !CONFIG_LINUX */
362 static void qemu_init_sigbus(void)
365 #endif /* !CONFIG_LINUX */
367 static QemuThread io_thread;
369 /* cpu creation */
370 static QemuCond qemu_cpu_cond;
371 /* system init */
372 static QemuCond qemu_pause_cond;
374 void qemu_init_cpu_loop(void)
376 qemu_init_sigbus();
377 qemu_cond_init(&qemu_cpu_cond);
378 qemu_cond_init(&qemu_pause_cond);
379 qemu_mutex_init(&qemu_global_mutex);
381 qemu_thread_get_self(&io_thread);
384 void run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data)
386 do_run_on_cpu(cpu, func, data, &qemu_global_mutex);
389 static void qemu_cpu_stop(CPUState *cpu, bool exit)
391 g_assert(qemu_cpu_is_self(cpu));
392 cpu->stop = false;
393 cpu->stopped = true;
394 if (exit) {
395 cpu_exit(cpu);
397 qemu_cond_broadcast(&qemu_pause_cond);
400 void qemu_wait_io_event_common(CPUState *cpu)
402 qatomic_mb_set(&cpu->thread_kicked, false);
403 if (cpu->stop) {
404 qemu_cpu_stop(cpu, false);
406 process_queued_cpu_work(cpu);
409 void qemu_wait_io_event(CPUState *cpu)
411 bool slept = false;
413 while (cpu_thread_is_idle(cpu)) {
414 if (!slept) {
415 slept = true;
416 qemu_plugin_vcpu_idle_cb(cpu);
418 qemu_cond_wait(cpu->halt_cond, &qemu_global_mutex);
420 if (slept) {
421 qemu_plugin_vcpu_resume_cb(cpu);
424 #ifdef _WIN32
425 /* Eat dummy APC queued by cpus_kick_thread. */
426 if (hax_enabled()) {
427 SleepEx(0, TRUE);
429 #endif
430 qemu_wait_io_event_common(cpu);
433 void cpus_kick_thread(CPUState *cpu)
435 #ifndef _WIN32
436 int err;
438 if (cpu->thread_kicked) {
439 return;
441 cpu->thread_kicked = true;
442 err = pthread_kill(cpu->thread->thread, SIG_IPI);
443 if (err && err != ESRCH) {
444 fprintf(stderr, "qemu:%s: %s", __func__, strerror(err));
445 exit(1);
447 #endif
450 void qemu_cpu_kick(CPUState *cpu)
452 qemu_cond_broadcast(cpu->halt_cond);
453 if (cpus_accel->kick_vcpu_thread) {
454 cpus_accel->kick_vcpu_thread(cpu);
455 } else { /* default */
456 cpus_kick_thread(cpu);
460 void qemu_cpu_kick_self(void)
462 assert(current_cpu);
463 cpus_kick_thread(current_cpu);
466 bool qemu_cpu_is_self(CPUState *cpu)
468 return qemu_thread_is_self(cpu->thread);
471 bool qemu_in_vcpu_thread(void)
473 return current_cpu && qemu_cpu_is_self(current_cpu);
476 static __thread bool iothread_locked = false;
478 bool qemu_mutex_iothread_locked(void)
480 return iothread_locked;
484 * The BQL is taken from so many places that it is worth profiling the
485 * callers directly, instead of funneling them all through a single function.
487 void qemu_mutex_lock_iothread_impl(const char *file, int line)
489 QemuMutexLockFunc bql_lock = qatomic_read(&qemu_bql_mutex_lock_func);
491 g_assert(!qemu_mutex_iothread_locked());
492 bql_lock(&qemu_global_mutex, file, line);
493 iothread_locked = true;
496 void qemu_mutex_unlock_iothread(void)
498 g_assert(qemu_mutex_iothread_locked());
499 iothread_locked = false;
500 qemu_mutex_unlock(&qemu_global_mutex);
503 void qemu_cond_wait_iothread(QemuCond *cond)
505 qemu_cond_wait(cond, &qemu_global_mutex);
508 void qemu_cond_timedwait_iothread(QemuCond *cond, int ms)
510 qemu_cond_timedwait(cond, &qemu_global_mutex, ms);
513 /* signal CPU creation */
514 void cpu_thread_signal_created(CPUState *cpu)
516 cpu->created = true;
517 qemu_cond_signal(&qemu_cpu_cond);
520 /* signal CPU destruction */
521 void cpu_thread_signal_destroyed(CPUState *cpu)
523 cpu->created = false;
524 qemu_cond_signal(&qemu_cpu_cond);
528 static bool all_vcpus_paused(void)
530 CPUState *cpu;
532 CPU_FOREACH(cpu) {
533 if (!cpu->stopped) {
534 return false;
538 return true;
541 void pause_all_vcpus(void)
543 CPUState *cpu;
545 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, false);
546 CPU_FOREACH(cpu) {
547 if (qemu_cpu_is_self(cpu)) {
548 qemu_cpu_stop(cpu, true);
549 } else {
550 cpu->stop = true;
551 qemu_cpu_kick(cpu);
555 /* We need to drop the replay_lock so any vCPU threads woken up
556 * can finish their replay tasks
558 replay_mutex_unlock();
560 while (!all_vcpus_paused()) {
561 qemu_cond_wait(&qemu_pause_cond, &qemu_global_mutex);
562 CPU_FOREACH(cpu) {
563 qemu_cpu_kick(cpu);
567 qemu_mutex_unlock_iothread();
568 replay_mutex_lock();
569 qemu_mutex_lock_iothread();
572 void cpu_resume(CPUState *cpu)
574 cpu->stop = false;
575 cpu->stopped = false;
576 qemu_cpu_kick(cpu);
579 void resume_all_vcpus(void)
581 CPUState *cpu;
583 if (!runstate_is_running()) {
584 return;
587 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
588 CPU_FOREACH(cpu) {
589 cpu_resume(cpu);
593 void cpu_remove_sync(CPUState *cpu)
595 cpu->stop = true;
596 cpu->unplug = true;
597 qemu_cpu_kick(cpu);
598 qemu_mutex_unlock_iothread();
599 qemu_thread_join(cpu->thread);
600 qemu_mutex_lock_iothread();
603 void cpus_register_accel(const AccelOpsClass *ops)
605 assert(ops != NULL);
606 assert(ops->create_vcpu_thread != NULL); /* mandatory */
607 cpus_accel = ops;
610 void qemu_init_vcpu(CPUState *cpu)
612 MachineState *ms = MACHINE(qdev_get_machine());
614 cpu->nr_cores = ms->smp.cores;
615 cpu->nr_threads = ms->smp.threads;
616 cpu->stopped = true;
617 cpu->random_seed = qemu_guest_random_seed_thread_part1();
619 if (!cpu->as) {
620 /* If the target cpu hasn't set up any address spaces itself,
621 * give it the default one.
623 cpu->num_ases = 1;
624 cpu_address_space_init(cpu, 0, "cpu-memory", cpu->memory);
627 /* accelerators all implement the AccelOpsClass */
628 g_assert(cpus_accel != NULL && cpus_accel->create_vcpu_thread != NULL);
629 cpus_accel->create_vcpu_thread(cpu);
631 while (!cpu->created) {
632 qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
636 void cpu_stop_current(void)
638 if (current_cpu) {
639 current_cpu->stop = true;
640 cpu_exit(current_cpu);
644 int vm_stop(RunState state)
646 if (qemu_in_vcpu_thread()) {
647 qemu_system_vmstop_request_prepare();
648 qemu_system_vmstop_request(state);
650 * FIXME: should not return to device code in case
651 * vm_stop() has been requested.
653 cpu_stop_current();
654 return 0;
657 return do_vm_stop(state, true);
661 * Prepare for (re)starting the VM.
662 * Returns -1 if the vCPUs are not to be restarted (e.g. if they are already
663 * running or in case of an error condition), 0 otherwise.
665 int vm_prepare_start(void)
667 RunState requested;
669 qemu_vmstop_requested(&requested);
670 if (runstate_is_running() && requested == RUN_STATE__MAX) {
671 return -1;
674 /* Ensure that a STOP/RESUME pair of events is emitted if a
675 * vmstop request was pending. The BLOCK_IO_ERROR event, for
676 * example, according to documentation is always followed by
677 * the STOP event.
679 if (runstate_is_running()) {
680 qapi_event_send_stop();
681 qapi_event_send_resume();
682 return -1;
685 /* We are sending this now, but the CPUs will be resumed shortly later */
686 qapi_event_send_resume();
688 cpu_enable_ticks();
689 runstate_set(RUN_STATE_RUNNING);
690 vm_state_notify(1, RUN_STATE_RUNNING);
691 return 0;
694 void vm_start(void)
696 if (!vm_prepare_start()) {
697 resume_all_vcpus();
701 /* does a state transition even if the VM is already stopped,
702 current state is forgotten forever */
703 int vm_stop_force_state(RunState state)
705 if (runstate_is_running()) {
706 return vm_stop(state);
707 } else {
708 int ret;
709 runstate_set(state);
711 bdrv_drain_all();
712 /* Make sure to return an error if the flush in a previous vm_stop()
713 * failed. */
714 ret = bdrv_flush_all();
715 trace_vm_stop_flush_all(ret);
716 return ret;
720 void list_cpus(const char *optarg)
722 /* XXX: implement xxx_cpu_list for targets that still miss it */
723 #if defined(cpu_list)
724 cpu_list();
725 #endif
728 void qmp_memsave(int64_t addr, int64_t size, const char *filename,
729 bool has_cpu, int64_t cpu_index, Error **errp)
731 FILE *f;
732 uint32_t l;
733 CPUState *cpu;
734 uint8_t buf[1024];
735 int64_t orig_addr = addr, orig_size = size;
737 if (!has_cpu) {
738 cpu_index = 0;
741 cpu = qemu_get_cpu(cpu_index);
742 if (cpu == NULL) {
743 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
744 "a CPU number");
745 return;
748 f = fopen(filename, "wb");
749 if (!f) {
750 error_setg_file_open(errp, errno, filename);
751 return;
754 while (size != 0) {
755 l = sizeof(buf);
756 if (l > size)
757 l = size;
758 if (cpu_memory_rw_debug(cpu, addr, buf, l, 0) != 0) {
759 error_setg(errp, "Invalid addr 0x%016" PRIx64 "/size %" PRId64
760 " specified", orig_addr, orig_size);
761 goto exit;
763 if (fwrite(buf, 1, l, f) != l) {
764 error_setg(errp, QERR_IO_ERROR);
765 goto exit;
767 addr += l;
768 size -= l;
771 exit:
772 fclose(f);
775 void qmp_pmemsave(int64_t addr, int64_t size, const char *filename,
776 Error **errp)
778 FILE *f;
779 uint32_t l;
780 uint8_t buf[1024];
782 f = fopen(filename, "wb");
783 if (!f) {
784 error_setg_file_open(errp, errno, filename);
785 return;
788 while (size != 0) {
789 l = sizeof(buf);
790 if (l > size)
791 l = size;
792 cpu_physical_memory_read(addr, buf, l);
793 if (fwrite(buf, 1, l, f) != l) {
794 error_setg(errp, QERR_IO_ERROR);
795 goto exit;
797 addr += l;
798 size -= l;
801 exit:
802 fclose(f);
805 void qmp_inject_nmi(Error **errp)
807 nmi_monitor_handle(monitor_get_cpu_index(monitor_cur()), errp);