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