xref: /openbmc/qemu/system/runstate.c (revision a4ad4a9d)
1 /*
2  * QEMU main system emulation loop
3  *
4  * Copyright (c) 2003-2020 QEMU contributors
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 "audio/audio.h"
27 #include "block/block.h"
28 #include "block/export.h"
29 #include "chardev/char.h"
30 #include "crypto/cipher.h"
31 #include "crypto/init.h"
32 #include "exec/cpu-common.h"
33 #include "gdbstub/syscalls.h"
34 #include "hw/boards.h"
35 #include "migration/misc.h"
36 #include "migration/postcopy-ram.h"
37 #include "monitor/monitor.h"
38 #include "net/net.h"
39 #include "net/vhost_net.h"
40 #include "qapi/error.h"
41 #include "qapi/qapi-commands-run-state.h"
42 #include "qapi/qapi-events-run-state.h"
43 #include "qemu/accel.h"
44 #include "qemu/error-report.h"
45 #include "qemu/job.h"
46 #include "qemu/log.h"
47 #include "qemu/module.h"
48 #include "qemu/sockets.h"
49 #include "qemu/timer.h"
50 #include "qemu/thread.h"
51 #include "qom/object.h"
52 #include "qom/object_interfaces.h"
53 #include "sysemu/cpus.h"
54 #include "sysemu/qtest.h"
55 #include "sysemu/replay.h"
56 #include "sysemu/reset.h"
57 #include "sysemu/runstate.h"
58 #include "sysemu/runstate-action.h"
59 #include "sysemu/sysemu.h"
60 #include "sysemu/tpm.h"
61 #include "trace.h"
62 
63 static NotifierList exit_notifiers =
64     NOTIFIER_LIST_INITIALIZER(exit_notifiers);
65 
66 static RunState current_run_state = RUN_STATE_PRELAUNCH;
67 
68 /* We use RUN_STATE__MAX but any invalid value will do */
69 static RunState vmstop_requested = RUN_STATE__MAX;
70 static QemuMutex vmstop_lock;
71 
72 typedef struct {
73     RunState from;
74     RunState to;
75 } RunStateTransition;
76 
77 static const RunStateTransition runstate_transitions_def[] = {
78     { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
79     { RUN_STATE_PRELAUNCH, RUN_STATE_SUSPENDED },
80 
81     { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
82     { RUN_STATE_DEBUG, RUN_STATE_FINISH_MIGRATE },
83     { RUN_STATE_DEBUG, RUN_STATE_PRELAUNCH },
84 
85     { RUN_STATE_INMIGRATE, RUN_STATE_INTERNAL_ERROR },
86     { RUN_STATE_INMIGRATE, RUN_STATE_IO_ERROR },
87     { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
88     { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
89     { RUN_STATE_INMIGRATE, RUN_STATE_SHUTDOWN },
90     { RUN_STATE_INMIGRATE, RUN_STATE_SUSPENDED },
91     { RUN_STATE_INMIGRATE, RUN_STATE_WATCHDOG },
92     { RUN_STATE_INMIGRATE, RUN_STATE_GUEST_PANICKED },
93     { RUN_STATE_INMIGRATE, RUN_STATE_FINISH_MIGRATE },
94     { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
95     { RUN_STATE_INMIGRATE, RUN_STATE_POSTMIGRATE },
96     { RUN_STATE_INMIGRATE, RUN_STATE_COLO },
97 
98     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
99     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
100     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PRELAUNCH },
101 
102     { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
103     { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
104     { RUN_STATE_IO_ERROR, RUN_STATE_PRELAUNCH },
105 
106     { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
107     { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
108     { RUN_STATE_PAUSED, RUN_STATE_POSTMIGRATE },
109     { RUN_STATE_PAUSED, RUN_STATE_PRELAUNCH },
110     { RUN_STATE_PAUSED, RUN_STATE_COLO},
111     { RUN_STATE_PAUSED, RUN_STATE_SUSPENDED},
112 
113     { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
114     { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
115     { RUN_STATE_POSTMIGRATE, RUN_STATE_PRELAUNCH },
116 
117     { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
118     { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
119     { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
120 
121     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
122     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PAUSED },
123     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
124     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PRELAUNCH },
125     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_COLO },
126     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_INTERNAL_ERROR },
127     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_IO_ERROR },
128     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_SHUTDOWN },
129     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_SUSPENDED },
130     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_WATCHDOG },
131     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_GUEST_PANICKED },
132 
133     { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
134     { RUN_STATE_RESTORE_VM, RUN_STATE_PRELAUNCH },
135     { RUN_STATE_RESTORE_VM, RUN_STATE_SUSPENDED },
136 
137     { RUN_STATE_COLO, RUN_STATE_RUNNING },
138     { RUN_STATE_COLO, RUN_STATE_PRELAUNCH },
139     { RUN_STATE_COLO, RUN_STATE_SHUTDOWN},
140 
141     { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
142     { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
143     { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
144     { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
145     { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
146     { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
147     { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
148     { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
149     { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
150     { RUN_STATE_RUNNING, RUN_STATE_GUEST_PANICKED },
151     { RUN_STATE_RUNNING, RUN_STATE_COLO},
152 
153     { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
154     { RUN_STATE_SAVE_VM, RUN_STATE_SUSPENDED },
155 
156     { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
157     { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
158     { RUN_STATE_SHUTDOWN, RUN_STATE_PRELAUNCH },
159     { RUN_STATE_SHUTDOWN, RUN_STATE_COLO },
160 
161     { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
162     { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
163     { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
164     { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
165     { RUN_STATE_SUSPENDED, RUN_STATE_PRELAUNCH },
166     { RUN_STATE_SUSPENDED, RUN_STATE_COLO},
167     { RUN_STATE_SUSPENDED, RUN_STATE_PAUSED},
168     { RUN_STATE_SUSPENDED, RUN_STATE_SAVE_VM },
169     { RUN_STATE_SUSPENDED, RUN_STATE_RESTORE_VM },
170     { RUN_STATE_SUSPENDED, RUN_STATE_SHUTDOWN },
171 
172     { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
173     { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
174     { RUN_STATE_WATCHDOG, RUN_STATE_PRELAUNCH },
175     { RUN_STATE_WATCHDOG, RUN_STATE_COLO},
176 
177     { RUN_STATE_GUEST_PANICKED, RUN_STATE_RUNNING },
178     { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
179     { RUN_STATE_GUEST_PANICKED, RUN_STATE_PRELAUNCH },
180 
181     { RUN_STATE__MAX, RUN_STATE__MAX },
182 };
183 
184 static const RunStateTransition replay_play_runstate_transitions_def[] = {
185     { RUN_STATE_SHUTDOWN, RUN_STATE_RUNNING},
186 
187     { RUN_STATE__MAX, RUN_STATE__MAX },
188 };
189 
190 static bool runstate_valid_transitions[RUN_STATE__MAX][RUN_STATE__MAX];
191 
192 bool runstate_check(RunState state)
193 {
194     return current_run_state == state;
195 }
196 
197 static void transitions_set_valid(const RunStateTransition *rst)
198 {
199     const RunStateTransition *p;
200 
201     for (p = rst; p->from != RUN_STATE__MAX; p++) {
202         runstate_valid_transitions[p->from][p->to] = true;
203     }
204 }
205 
206 void runstate_replay_enable(void)
207 {
208     assert(replay_mode != REPLAY_MODE_NONE);
209 
210     if (replay_mode == REPLAY_MODE_PLAY) {
211         /*
212          * When reverse-debugging, it is possible to move state from
213          * shutdown to running.
214          */
215         transitions_set_valid(&replay_play_runstate_transitions_def[0]);
216     }
217 }
218 
219 static void runstate_init(void)
220 {
221     memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
222 
223     transitions_set_valid(&runstate_transitions_def[0]);
224 
225     qemu_mutex_init(&vmstop_lock);
226 }
227 
228 /* This function will abort() on invalid state transitions */
229 void runstate_set(RunState new_state)
230 {
231     assert(new_state < RUN_STATE__MAX);
232 
233     trace_runstate_set(current_run_state, RunState_str(current_run_state),
234                        new_state, RunState_str(new_state));
235 
236     if (current_run_state == new_state) {
237         return;
238     }
239 
240     if (!runstate_valid_transitions[current_run_state][new_state]) {
241         error_report("invalid runstate transition: '%s' -> '%s'",
242                      RunState_str(current_run_state),
243                      RunState_str(new_state));
244         abort();
245     }
246 
247     current_run_state = new_state;
248 }
249 
250 RunState runstate_get(void)
251 {
252     return current_run_state;
253 }
254 
255 bool runstate_is_running(void)
256 {
257     return runstate_check(RUN_STATE_RUNNING);
258 }
259 
260 bool runstate_needs_reset(void)
261 {
262     return runstate_check(RUN_STATE_INTERNAL_ERROR) ||
263         runstate_check(RUN_STATE_SHUTDOWN);
264 }
265 
266 StatusInfo *qmp_query_status(Error **errp)
267 {
268     StatusInfo *info = g_malloc0(sizeof(*info));
269 
270     info->running = runstate_is_running();
271     info->status = current_run_state;
272 
273     return info;
274 }
275 
276 bool qemu_vmstop_requested(RunState *r)
277 {
278     qemu_mutex_lock(&vmstop_lock);
279     *r = vmstop_requested;
280     vmstop_requested = RUN_STATE__MAX;
281     qemu_mutex_unlock(&vmstop_lock);
282     return *r < RUN_STATE__MAX;
283 }
284 
285 void qemu_system_vmstop_request_prepare(void)
286 {
287     qemu_mutex_lock(&vmstop_lock);
288 }
289 
290 void qemu_system_vmstop_request(RunState state)
291 {
292     vmstop_requested = state;
293     qemu_mutex_unlock(&vmstop_lock);
294     qemu_notify_event();
295 }
296 struct VMChangeStateEntry {
297     VMChangeStateHandler *cb;
298     VMChangeStateHandler *prepare_cb;
299     void *opaque;
300     QTAILQ_ENTRY(VMChangeStateEntry) entries;
301     int priority;
302 };
303 
304 static QTAILQ_HEAD(, VMChangeStateEntry) vm_change_state_head =
305     QTAILQ_HEAD_INITIALIZER(vm_change_state_head);
306 
307 /**
308  * qemu_add_vm_change_state_handler_prio:
309  * @cb: the callback to invoke
310  * @opaque: user data passed to the callback
311  * @priority: low priorities execute first when the vm runs and the reverse is
312  *            true when the vm stops
313  *
314  * Register a callback function that is invoked when the vm starts or stops
315  * running.
316  *
317  * Returns: an entry to be freed using qemu_del_vm_change_state_handler()
318  */
319 VMChangeStateEntry *qemu_add_vm_change_state_handler_prio(
320         VMChangeStateHandler *cb, void *opaque, int priority)
321 {
322     return qemu_add_vm_change_state_handler_prio_full(cb, NULL, opaque,
323                                                       priority);
324 }
325 
326 /**
327  * qemu_add_vm_change_state_handler_prio_full:
328  * @cb: the main callback to invoke
329  * @prepare_cb: a callback to invoke before the main callback
330  * @opaque: user data passed to the callbacks
331  * @priority: low priorities execute first when the vm runs and the reverse is
332  *            true when the vm stops
333  *
334  * Register a main callback function and an optional prepare callback function
335  * that are invoked when the vm starts or stops running. The main callback and
336  * the prepare callback are called in two separate phases: First all prepare
337  * callbacks are called and only then all main callbacks are called. As its
338  * name suggests, the prepare callback can be used to do some preparatory work
339  * before invoking the main callback.
340  *
341  * Returns: an entry to be freed using qemu_del_vm_change_state_handler()
342  */
343 VMChangeStateEntry *
344 qemu_add_vm_change_state_handler_prio_full(VMChangeStateHandler *cb,
345                                            VMChangeStateHandler *prepare_cb,
346                                            void *opaque, int priority)
347 {
348     VMChangeStateEntry *e;
349     VMChangeStateEntry *other;
350 
351     e = g_malloc0(sizeof(*e));
352     e->cb = cb;
353     e->prepare_cb = prepare_cb;
354     e->opaque = opaque;
355     e->priority = priority;
356 
357     /* Keep list sorted in ascending priority order */
358     QTAILQ_FOREACH(other, &vm_change_state_head, entries) {
359         if (priority < other->priority) {
360             QTAILQ_INSERT_BEFORE(other, e, entries);
361             return e;
362         }
363     }
364 
365     QTAILQ_INSERT_TAIL(&vm_change_state_head, e, entries);
366     return e;
367 }
368 
369 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
370                                                      void *opaque)
371 {
372     return qemu_add_vm_change_state_handler_prio(cb, opaque, 0);
373 }
374 
375 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
376 {
377     QTAILQ_REMOVE(&vm_change_state_head, e, entries);
378     g_free(e);
379 }
380 
381 void vm_state_notify(bool running, RunState state)
382 {
383     VMChangeStateEntry *e, *next;
384 
385     trace_vm_state_notify(running, state, RunState_str(state));
386 
387     if (running) {
388         QTAILQ_FOREACH_SAFE(e, &vm_change_state_head, entries, next) {
389             if (e->prepare_cb) {
390                 e->prepare_cb(e->opaque, running, state);
391             }
392         }
393 
394         QTAILQ_FOREACH_SAFE(e, &vm_change_state_head, entries, next) {
395             e->cb(e->opaque, running, state);
396         }
397     } else {
398         QTAILQ_FOREACH_REVERSE_SAFE(e, &vm_change_state_head, entries, next) {
399             if (e->prepare_cb) {
400                 e->prepare_cb(e->opaque, running, state);
401             }
402         }
403 
404         QTAILQ_FOREACH_REVERSE_SAFE(e, &vm_change_state_head, entries, next) {
405             e->cb(e->opaque, running, state);
406         }
407     }
408 }
409 
410 static ShutdownCause reset_requested;
411 static ShutdownCause shutdown_requested;
412 static int shutdown_exit_code = EXIT_SUCCESS;
413 static int shutdown_signal;
414 static pid_t shutdown_pid;
415 static int powerdown_requested;
416 static int debug_requested;
417 static int suspend_requested;
418 static WakeupReason wakeup_reason;
419 static NotifierList powerdown_notifiers =
420     NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
421 static NotifierList suspend_notifiers =
422     NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
423 static NotifierList wakeup_notifiers =
424     NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
425 static NotifierList shutdown_notifiers =
426     NOTIFIER_LIST_INITIALIZER(shutdown_notifiers);
427 static uint32_t wakeup_reason_mask = ~(1 << QEMU_WAKEUP_REASON_NONE);
428 
429 ShutdownCause qemu_shutdown_requested_get(void)
430 {
431     return shutdown_requested;
432 }
433 
434 ShutdownCause qemu_reset_requested_get(void)
435 {
436     return reset_requested;
437 }
438 
439 static int qemu_shutdown_requested(void)
440 {
441     return qatomic_xchg(&shutdown_requested, SHUTDOWN_CAUSE_NONE);
442 }
443 
444 static void qemu_kill_report(void)
445 {
446     if (!qtest_driver() && shutdown_signal) {
447         if (shutdown_pid == 0) {
448             /* This happens for eg ^C at the terminal, so it's worth
449              * avoiding printing an odd message in that case.
450              */
451             error_report("terminating on signal %d", shutdown_signal);
452         } else {
453             char *shutdown_cmd = qemu_get_pid_name(shutdown_pid);
454 
455             error_report("terminating on signal %d from pid " FMT_pid " (%s)",
456                          shutdown_signal, shutdown_pid,
457                          shutdown_cmd ? shutdown_cmd : "<unknown process>");
458             g_free(shutdown_cmd);
459         }
460         shutdown_signal = 0;
461     }
462 }
463 
464 static ShutdownCause qemu_reset_requested(void)
465 {
466     ShutdownCause r = reset_requested;
467 
468     if (r && replay_checkpoint(CHECKPOINT_RESET_REQUESTED)) {
469         reset_requested = SHUTDOWN_CAUSE_NONE;
470         return r;
471     }
472     return SHUTDOWN_CAUSE_NONE;
473 }
474 
475 static int qemu_suspend_requested(void)
476 {
477     int r = suspend_requested;
478     if (r && replay_checkpoint(CHECKPOINT_SUSPEND_REQUESTED)) {
479         suspend_requested = 0;
480         return r;
481     }
482     return false;
483 }
484 
485 static WakeupReason qemu_wakeup_requested(void)
486 {
487     return wakeup_reason;
488 }
489 
490 static int qemu_powerdown_requested(void)
491 {
492     int r = powerdown_requested;
493     powerdown_requested = 0;
494     return r;
495 }
496 
497 static int qemu_debug_requested(void)
498 {
499     int r = debug_requested;
500     debug_requested = 0;
501     return r;
502 }
503 
504 /*
505  * Reset the VM. Issue an event unless @reason is SHUTDOWN_CAUSE_NONE.
506  */
507 void qemu_system_reset(ShutdownCause reason)
508 {
509     MachineClass *mc;
510 
511     mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
512 
513     cpu_synchronize_all_states();
514 
515     if (mc && mc->reset) {
516         mc->reset(current_machine, reason);
517     } else {
518         qemu_devices_reset(reason);
519     }
520     switch (reason) {
521     case SHUTDOWN_CAUSE_NONE:
522     case SHUTDOWN_CAUSE_SUBSYSTEM_RESET:
523     case SHUTDOWN_CAUSE_SNAPSHOT_LOAD:
524         break;
525     default:
526         qapi_event_send_reset(shutdown_caused_by_guest(reason), reason);
527     }
528 
529     /*
530      * Some boards use the machine reset callback to point CPUs to the firmware
531      * entry point.  Assume that this is not the case for boards that support
532      * non-resettable CPUs (currently used only for confidential guests), in
533      * which case cpu_synchronize_all_post_init() is enough because
534      * it does _more_  than cpu_synchronize_all_post_reset().
535      */
536     if (cpus_are_resettable()) {
537         cpu_synchronize_all_post_reset();
538     } else {
539         assert(runstate_check(RUN_STATE_PRELAUNCH));
540     }
541 
542     vm_set_suspended(false);
543 }
544 
545 /*
546  * Wake the VM after suspend.
547  */
548 static void qemu_system_wakeup(void)
549 {
550     MachineClass *mc;
551 
552     mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
553 
554     if (mc && mc->wakeup) {
555         mc->wakeup(current_machine);
556     }
557 }
558 
559 void qemu_system_guest_panicked(GuestPanicInformation *info)
560 {
561     qemu_log_mask(LOG_GUEST_ERROR, "Guest crashed");
562 
563     if (current_cpu) {
564         current_cpu->crash_occurred = true;
565     }
566     /*
567      * TODO:  Currently the available panic actions are: none, pause, and
568      * shutdown, but in principle debug and reset could be supported as well.
569      * Investigate any potential use cases for the unimplemented actions.
570      */
571     if (panic_action == PANIC_ACTION_PAUSE
572         || (panic_action == PANIC_ACTION_SHUTDOWN && shutdown_action == SHUTDOWN_ACTION_PAUSE)) {
573         qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE, info);
574         vm_stop(RUN_STATE_GUEST_PANICKED);
575     } else if (panic_action == PANIC_ACTION_SHUTDOWN ||
576                panic_action == PANIC_ACTION_EXIT_FAILURE) {
577         qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_POWEROFF, info);
578         vm_stop(RUN_STATE_GUEST_PANICKED);
579         qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_PANIC);
580     } else {
581         qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_RUN, info);
582     }
583 
584     if (info) {
585         if (info->type == GUEST_PANIC_INFORMATION_TYPE_HYPER_V) {
586             qemu_log_mask(LOG_GUEST_ERROR, "\nHV crash parameters: (%#"PRIx64
587                           " %#"PRIx64" %#"PRIx64" %#"PRIx64" %#"PRIx64")\n",
588                           info->u.hyper_v.arg1,
589                           info->u.hyper_v.arg2,
590                           info->u.hyper_v.arg3,
591                           info->u.hyper_v.arg4,
592                           info->u.hyper_v.arg5);
593         } else if (info->type == GUEST_PANIC_INFORMATION_TYPE_S390) {
594             qemu_log_mask(LOG_GUEST_ERROR, " on cpu %d: %s\n"
595                           "PSW: 0x%016" PRIx64 " 0x%016" PRIx64"\n",
596                           info->u.s390.core,
597                           S390CrashReason_str(info->u.s390.reason),
598                           info->u.s390.psw_mask,
599                           info->u.s390.psw_addr);
600         }
601         qapi_free_GuestPanicInformation(info);
602     }
603 }
604 
605 void qemu_system_guest_crashloaded(GuestPanicInformation *info)
606 {
607     qemu_log_mask(LOG_GUEST_ERROR, "Guest crash loaded");
608     qapi_event_send_guest_crashloaded(GUEST_PANIC_ACTION_RUN, info);
609     qapi_free_GuestPanicInformation(info);
610 }
611 
612 void qemu_system_guest_pvshutdown(void)
613 {
614     qapi_event_send_guest_pvshutdown();
615     qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
616 }
617 
618 void qemu_system_reset_request(ShutdownCause reason)
619 {
620     if (reboot_action == REBOOT_ACTION_SHUTDOWN &&
621         reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
622         shutdown_requested = reason;
623     } else if (!cpus_are_resettable()) {
624         error_report("cpus are not resettable, terminating");
625         shutdown_requested = reason;
626     } else {
627         reset_requested = reason;
628     }
629     cpu_stop_current();
630     qemu_notify_event();
631 }
632 
633 static void qemu_system_suspend(void)
634 {
635     pause_all_vcpus();
636     notifier_list_notify(&suspend_notifiers, NULL);
637     runstate_set(RUN_STATE_SUSPENDED);
638     qapi_event_send_suspend();
639 }
640 
641 void qemu_system_suspend_request(void)
642 {
643     if (runstate_check(RUN_STATE_SUSPENDED)) {
644         return;
645     }
646     suspend_requested = 1;
647     cpu_stop_current();
648     qemu_notify_event();
649 }
650 
651 void qemu_register_suspend_notifier(Notifier *notifier)
652 {
653     notifier_list_add(&suspend_notifiers, notifier);
654 }
655 
656 void qemu_system_wakeup_request(WakeupReason reason, Error **errp)
657 {
658     trace_system_wakeup_request(reason);
659 
660     if (!runstate_check(RUN_STATE_SUSPENDED)) {
661         error_setg(errp,
662                    "Unable to wake up: guest is not in suspended state");
663         return;
664     }
665     if (!(wakeup_reason_mask & (1 << reason))) {
666         return;
667     }
668     runstate_set(RUN_STATE_RUNNING);
669     wakeup_reason = reason;
670     qemu_notify_event();
671 }
672 
673 void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
674 {
675     if (enabled) {
676         wakeup_reason_mask |= (1 << reason);
677     } else {
678         wakeup_reason_mask &= ~(1 << reason);
679     }
680 }
681 
682 void qemu_register_wakeup_notifier(Notifier *notifier)
683 {
684     notifier_list_add(&wakeup_notifiers, notifier);
685 }
686 
687 static bool wakeup_suspend_enabled;
688 
689 void qemu_register_wakeup_support(void)
690 {
691     wakeup_suspend_enabled = true;
692 }
693 
694 bool qemu_wakeup_suspend_enabled(void)
695 {
696     return wakeup_suspend_enabled;
697 }
698 
699 void qemu_system_killed(int signal, pid_t pid)
700 {
701     shutdown_signal = signal;
702     shutdown_pid = pid;
703     shutdown_action = SHUTDOWN_ACTION_POWEROFF;
704 
705     /* Cannot call qemu_system_shutdown_request directly because
706      * we are in a signal handler.
707      */
708     shutdown_requested = SHUTDOWN_CAUSE_HOST_SIGNAL;
709     qemu_notify_event();
710 }
711 
712 void qemu_system_shutdown_request_with_code(ShutdownCause reason,
713                                             int exit_code)
714 {
715     shutdown_exit_code = exit_code;
716     qemu_system_shutdown_request(reason);
717 }
718 
719 void qemu_system_shutdown_request(ShutdownCause reason)
720 {
721     trace_qemu_system_shutdown_request(reason);
722     replay_shutdown_request(reason);
723     shutdown_requested = reason;
724     qemu_notify_event();
725 }
726 
727 static void qemu_system_powerdown(void)
728 {
729     qapi_event_send_powerdown();
730     notifier_list_notify(&powerdown_notifiers, NULL);
731 }
732 
733 static void qemu_system_shutdown(ShutdownCause cause)
734 {
735     qapi_event_send_shutdown(shutdown_caused_by_guest(cause), cause);
736     notifier_list_notify(&shutdown_notifiers, &cause);
737 }
738 
739 void qemu_system_powerdown_request(void)
740 {
741     trace_qemu_system_powerdown_request();
742     powerdown_requested = 1;
743     qemu_notify_event();
744 }
745 
746 void qemu_register_powerdown_notifier(Notifier *notifier)
747 {
748     notifier_list_add(&powerdown_notifiers, notifier);
749 }
750 
751 void qemu_register_shutdown_notifier(Notifier *notifier)
752 {
753     notifier_list_add(&shutdown_notifiers, notifier);
754 }
755 
756 void qemu_system_debug_request(void)
757 {
758     debug_requested = 1;
759     qemu_notify_event();
760 }
761 
762 static bool main_loop_should_exit(int *status)
763 {
764     RunState r;
765     ShutdownCause request;
766 
767     if (qemu_debug_requested()) {
768         vm_stop(RUN_STATE_DEBUG);
769     }
770     if (qemu_suspend_requested()) {
771         qemu_system_suspend();
772     }
773     request = qemu_shutdown_requested();
774     if (request) {
775         qemu_kill_report();
776         qemu_system_shutdown(request);
777         if (shutdown_action == SHUTDOWN_ACTION_PAUSE) {
778             vm_stop(RUN_STATE_SHUTDOWN);
779         } else {
780             if (shutdown_exit_code != EXIT_SUCCESS) {
781                 *status = shutdown_exit_code;
782             } else if (request == SHUTDOWN_CAUSE_GUEST_PANIC &&
783                 panic_action == PANIC_ACTION_EXIT_FAILURE) {
784                 *status = EXIT_FAILURE;
785             }
786             return true;
787         }
788     }
789     request = qemu_reset_requested();
790     if (request) {
791         pause_all_vcpus();
792         qemu_system_reset(request);
793         resume_all_vcpus();
794         /*
795          * runstate can change in pause_all_vcpus()
796          * as iothread mutex is unlocked
797          */
798         if (!runstate_check(RUN_STATE_RUNNING) &&
799                 !runstate_check(RUN_STATE_INMIGRATE) &&
800                 !runstate_check(RUN_STATE_FINISH_MIGRATE)) {
801             runstate_set(RUN_STATE_PRELAUNCH);
802         }
803     }
804     if (qemu_wakeup_requested()) {
805         pause_all_vcpus();
806         qemu_system_wakeup();
807         notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
808         wakeup_reason = QEMU_WAKEUP_REASON_NONE;
809         resume_all_vcpus();
810         qapi_event_send_wakeup();
811     }
812     if (qemu_powerdown_requested()) {
813         qemu_system_powerdown();
814     }
815     if (qemu_vmstop_requested(&r)) {
816         vm_stop(r);
817     }
818     return false;
819 }
820 
821 int qemu_main_loop(void)
822 {
823     int status = EXIT_SUCCESS;
824 
825     while (!main_loop_should_exit(&status)) {
826         main_loop_wait(false);
827     }
828 
829     return status;
830 }
831 
832 void qemu_add_exit_notifier(Notifier *notify)
833 {
834     notifier_list_add(&exit_notifiers, notify);
835 }
836 
837 void qemu_remove_exit_notifier(Notifier *notify)
838 {
839     notifier_remove(notify);
840 }
841 
842 static void qemu_run_exit_notifiers(void)
843 {
844     notifier_list_notify(&exit_notifiers, NULL);
845 }
846 
847 void qemu_init_subsystems(void)
848 {
849     Error *err = NULL;
850 
851     os_set_line_buffering();
852 
853     module_call_init(MODULE_INIT_TRACE);
854 
855     qemu_init_cpu_list();
856     qemu_init_cpu_loop();
857     bql_lock();
858 
859     atexit(qemu_run_exit_notifiers);
860 
861     module_call_init(MODULE_INIT_QOM);
862     module_call_init(MODULE_INIT_MIGRATION);
863 
864     runstate_init();
865     precopy_infrastructure_init();
866     postcopy_infrastructure_init();
867     monitor_init_globals();
868 
869     if (qcrypto_init(&err) < 0) {
870         error_reportf_err(err, "cannot initialize crypto: ");
871         exit(1);
872     }
873 
874     os_setup_early_signal_handling();
875 
876     bdrv_init_with_whitelist();
877     socket_init();
878 }
879 
880 
881 void qemu_cleanup(int status)
882 {
883     gdb_exit(status);
884 
885     /*
886      * cleaning up the migration object cancels any existing migration
887      * try to do this early so that it also stops using devices.
888      */
889     migration_shutdown();
890 
891     /*
892      * Close the exports before draining the block layer. The export
893      * drivers may have coroutines yielding on it, so we need to clean
894      * them up before the drain, as otherwise they may be get stuck in
895      * blk_wait_while_drained().
896      */
897     blk_exp_close_all();
898 
899 
900     /* No more vcpu or device emulation activity beyond this point */
901     vm_shutdown();
902     replay_finish();
903 
904     /*
905      * We must cancel all block jobs while the block layer is drained,
906      * or cancelling will be affected by throttling and thus may block
907      * for an extended period of time.
908      * Begin the drained section after vm_shutdown() to avoid requests being
909      * stuck in the BlockBackend's request queue.
910      * We do not need to end this section, because we do not want any
911      * requests happening from here on anyway.
912      */
913     bdrv_drain_all_begin();
914     job_cancel_sync_all();
915     bdrv_close_all();
916 
917     /* vhost-user must be cleaned up before chardevs.  */
918     tpm_cleanup();
919     net_cleanup();
920     audio_cleanup();
921     monitor_cleanup();
922     qemu_chr_cleanup();
923     user_creatable_cleanup();
924     /* TODO: unref root container, check all devices are ok */
925 }
926