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