vl: move various initialization routines out of qemu_init
[qemu.git] / softmmu / vl.c
blob8640ddd3eceae66a1e4367947c81454aa4dd4e4d
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "qemu-common.h"
27 #include "qemu/units.h"
28 #include "hw/boards.h"
29 #include "hw/qdev-properties.h"
30 #include "qapi/error.h"
31 #include "qemu-version.h"
32 #include "qemu/cutils.h"
33 #include "qemu/help_option.h"
34 #include "qemu/uuid.h"
35 #include "sysemu/reset.h"
36 #include "sysemu/runstate.h"
37 #include "sysemu/seccomp.h"
38 #include "sysemu/tcg.h"
39 #include "sysemu/xen.h"
41 #include "qemu/error-report.h"
42 #include "qemu/sockets.h"
43 #include "sysemu/accel.h"
44 #include "hw/usb.h"
45 #include "hw/isa/isa.h"
46 #include "hw/scsi/scsi.h"
47 #include "hw/display/vga.h"
48 #include "sysemu/watchdog.h"
49 #include "hw/firmware/smbios.h"
50 #include "hw/acpi/acpi.h"
51 #include "hw/xen/xen.h"
52 #include "hw/loader.h"
53 #include "monitor/qdev.h"
54 #include "net/net.h"
55 #include "net/slirp.h"
56 #include "monitor/monitor.h"
57 #include "ui/console.h"
58 #include "ui/input.h"
59 #include "sysemu/sysemu.h"
60 #include "sysemu/numa.h"
61 #include "sysemu/hostmem.h"
62 #include "exec/gdbstub.h"
63 #include "qemu/timer.h"
64 #include "chardev/char.h"
65 #include "qemu/bitmap.h"
66 #include "qemu/log.h"
67 #include "sysemu/blockdev.h"
68 #include "hw/block/block.h"
69 #include "migration/misc.h"
70 #include "migration/snapshot.h"
71 #include "migration/global_state.h"
72 #include "sysemu/tpm.h"
73 #include "sysemu/dma.h"
74 #include "hw/audio/soundhw.h"
75 #include "audio/audio.h"
76 #include "sysemu/cpus.h"
77 #include "sysemu/cpu-timers.h"
78 #include "migration/colo.h"
79 #include "migration/postcopy-ram.h"
80 #include "sysemu/kvm.h"
81 #include "sysemu/hax.h"
82 #include "qapi/qobject-input-visitor.h"
83 #include "qemu/option.h"
84 #include "qemu/config-file.h"
85 #include "qemu-options.h"
86 #include "qemu/main-loop.h"
87 #ifdef CONFIG_VIRTFS
88 #include "fsdev/qemu-fsdev.h"
89 #endif
90 #include "sysemu/qtest.h"
92 #include "disas/disas.h"
94 #include "trace.h"
95 #include "trace/control.h"
96 #include "qemu/plugin.h"
97 #include "qemu/queue.h"
98 #include "sysemu/arch_init.h"
100 #include "ui/qemu-spice.h"
101 #include "qapi/string-input-visitor.h"
102 #include "qapi/opts-visitor.h"
103 #include "qapi/clone-visitor.h"
104 #include "qom/object_interfaces.h"
105 #include "hw/semihosting/semihost.h"
106 #include "crypto/init.h"
107 #include "sysemu/replay.h"
108 #include "qapi/qapi-events-run-state.h"
109 #include "qapi/qapi-visit-block-core.h"
110 #include "qapi/qapi-visit-ui.h"
111 #include "qapi/qapi-commands-block-core.h"
112 #include "qapi/qapi-commands-run-state.h"
113 #include "qapi/qapi-commands-ui.h"
114 #include "qapi/qmp/qerror.h"
115 #include "sysemu/iothread.h"
116 #include "qemu/guest-random.h"
118 #define MAX_VIRTIO_CONSOLES 1
120 static const char *cpu_option;
121 static const char *data_dir[16];
122 static int data_dir_idx;
123 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
124 int display_opengl;
125 const char* keyboard_layout = NULL;
126 static ram_addr_t ram_size;
127 bool enable_mlock = false;
128 bool enable_cpu_pm = false;
129 int nb_nics;
130 NICInfo nd_table[MAX_NICS];
131 int autostart;
132 static enum {
133 RTC_BASE_UTC,
134 RTC_BASE_LOCALTIME,
135 RTC_BASE_DATETIME,
136 } rtc_base_type = RTC_BASE_UTC;
137 static time_t rtc_ref_start_datetime;
138 static int rtc_realtime_clock_offset; /* used only with QEMU_CLOCK_REALTIME */
139 static int rtc_host_datetime_offset = -1; /* valid & used only with
140 RTC_BASE_DATETIME */
141 QEMUClockType rtc_clock;
142 int vga_interface_type = VGA_NONE;
143 static DisplayOptions dpy;
144 static int num_serial_hds;
145 static Chardev **serial_hds;
146 static const char *log_mask;
147 static const char *log_file;
148 static bool list_data_dirs;
149 Chardev *parallel_hds[MAX_PARALLEL_PORTS];
150 int win2k_install_hack = 0;
151 int singlestep = 0;
152 int fd_bootchk = 1;
153 static int no_reboot;
154 int no_shutdown = 0;
155 int graphic_rotate = 0;
156 const char *watchdog;
157 QEMUOptionRom option_rom[MAX_OPTION_ROMS];
158 int nb_option_roms;
159 int old_param = 0;
160 const char *qemu_name;
161 int alt_grab = 0;
162 int ctrl_grab = 0;
163 unsigned int nb_prom_envs = 0;
164 const char *prom_envs[MAX_PROM_ENVS];
165 int boot_menu;
166 bool boot_strict;
167 uint8_t *boot_splash_filedata;
168 int only_migratable; /* turn it off unless user states otherwise */
169 bool wakeup_suspend_enabled;
170 int icount_align_option;
171 static const char *qtest_chrdev;
172 static const char *qtest_log;
174 /* The bytes in qemu_uuid are in the order specified by RFC4122, _not_ in the
175 * little-endian "wire format" described in the SMBIOS 2.6 specification.
177 QemuUUID qemu_uuid;
178 bool qemu_uuid_set;
180 static NotifierList exit_notifiers =
181 NOTIFIER_LIST_INITIALIZER(exit_notifiers);
183 static NotifierList machine_init_done_notifiers =
184 NOTIFIER_LIST_INITIALIZER(machine_init_done_notifiers);
186 uint32_t xen_domid;
187 enum xen_mode xen_mode = XEN_EMULATE;
188 bool xen_domid_restrict;
190 static int has_defaults = 1;
191 static int default_serial = 1;
192 static int default_parallel = 1;
193 static int default_monitor = 1;
194 static int default_floppy = 1;
195 static int default_cdrom = 1;
196 static int default_sdcard = 1;
197 static int default_vga = 1;
198 static int default_net = 1;
200 static struct {
201 const char *driver;
202 int *flag;
203 } default_list[] = {
204 { .driver = "isa-serial", .flag = &default_serial },
205 { .driver = "isa-parallel", .flag = &default_parallel },
206 { .driver = "isa-fdc", .flag = &default_floppy },
207 { .driver = "floppy", .flag = &default_floppy },
208 { .driver = "ide-cd", .flag = &default_cdrom },
209 { .driver = "ide-hd", .flag = &default_cdrom },
210 { .driver = "ide-drive", .flag = &default_cdrom },
211 { .driver = "scsi-cd", .flag = &default_cdrom },
212 { .driver = "scsi-hd", .flag = &default_cdrom },
213 { .driver = "VGA", .flag = &default_vga },
214 { .driver = "isa-vga", .flag = &default_vga },
215 { .driver = "cirrus-vga", .flag = &default_vga },
216 { .driver = "isa-cirrus-vga", .flag = &default_vga },
217 { .driver = "vmware-svga", .flag = &default_vga },
218 { .driver = "qxl-vga", .flag = &default_vga },
219 { .driver = "virtio-vga", .flag = &default_vga },
220 { .driver = "ati-vga", .flag = &default_vga },
221 { .driver = "vhost-user-vga", .flag = &default_vga },
224 static QemuOptsList qemu_rtc_opts = {
225 .name = "rtc",
226 .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
227 .merge_lists = true,
228 .desc = {
230 .name = "base",
231 .type = QEMU_OPT_STRING,
233 .name = "clock",
234 .type = QEMU_OPT_STRING,
236 .name = "driftfix",
237 .type = QEMU_OPT_STRING,
239 { /* end of list */ }
243 static QemuOptsList qemu_option_rom_opts = {
244 .name = "option-rom",
245 .implied_opt_name = "romfile",
246 .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
247 .desc = {
249 .name = "bootindex",
250 .type = QEMU_OPT_NUMBER,
251 }, {
252 .name = "romfile",
253 .type = QEMU_OPT_STRING,
255 { /* end of list */ }
259 static QemuOptsList qemu_machine_opts = {
260 .name = "machine",
261 .implied_opt_name = "type",
262 .merge_lists = true,
263 .head = QTAILQ_HEAD_INITIALIZER(qemu_machine_opts.head),
264 .desc = {
266 * no elements => accept any
267 * sanity checking will happen later
268 * when setting machine properties
274 static QemuOptsList qemu_accel_opts = {
275 .name = "accel",
276 .implied_opt_name = "accel",
277 .head = QTAILQ_HEAD_INITIALIZER(qemu_accel_opts.head),
278 .desc = {
280 * no elements => accept any
281 * sanity checking will happen later
282 * when setting accelerator properties
288 static QemuOptsList qemu_boot_opts = {
289 .name = "boot-opts",
290 .implied_opt_name = "order",
291 .merge_lists = true,
292 .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
293 .desc = {
295 .name = "order",
296 .type = QEMU_OPT_STRING,
297 }, {
298 .name = "once",
299 .type = QEMU_OPT_STRING,
300 }, {
301 .name = "menu",
302 .type = QEMU_OPT_BOOL,
303 }, {
304 .name = "splash",
305 .type = QEMU_OPT_STRING,
306 }, {
307 .name = "splash-time",
308 .type = QEMU_OPT_NUMBER,
309 }, {
310 .name = "reboot-timeout",
311 .type = QEMU_OPT_NUMBER,
312 }, {
313 .name = "strict",
314 .type = QEMU_OPT_BOOL,
316 { /*End of list */ }
320 static QemuOptsList qemu_add_fd_opts = {
321 .name = "add-fd",
322 .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
323 .desc = {
325 .name = "fd",
326 .type = QEMU_OPT_NUMBER,
327 .help = "file descriptor of which a duplicate is added to fd set",
329 .name = "set",
330 .type = QEMU_OPT_NUMBER,
331 .help = "ID of the fd set to add fd to",
333 .name = "opaque",
334 .type = QEMU_OPT_STRING,
335 .help = "free-form string used to describe fd",
337 { /* end of list */ }
341 static QemuOptsList qemu_object_opts = {
342 .name = "object",
343 .implied_opt_name = "qom-type",
344 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
345 .desc = {
350 static QemuOptsList qemu_tpmdev_opts = {
351 .name = "tpmdev",
352 .implied_opt_name = "type",
353 .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
354 .desc = {
355 /* options are defined in the TPM backends */
356 { /* end of list */ }
360 static QemuOptsList qemu_realtime_opts = {
361 .name = "realtime",
362 .head = QTAILQ_HEAD_INITIALIZER(qemu_realtime_opts.head),
363 .desc = {
365 .name = "mlock",
366 .type = QEMU_OPT_BOOL,
368 { /* end of list */ }
372 static QemuOptsList qemu_overcommit_opts = {
373 .name = "overcommit",
374 .head = QTAILQ_HEAD_INITIALIZER(qemu_overcommit_opts.head),
375 .desc = {
377 .name = "mem-lock",
378 .type = QEMU_OPT_BOOL,
381 .name = "cpu-pm",
382 .type = QEMU_OPT_BOOL,
384 { /* end of list */ }
388 static QemuOptsList qemu_msg_opts = {
389 .name = "msg",
390 .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
391 .desc = {
393 .name = "timestamp",
394 .type = QEMU_OPT_BOOL,
397 .name = "guest-name",
398 .type = QEMU_OPT_BOOL,
399 .help = "Prepends guest name for error messages but only if "
400 "-name guest is set otherwise option is ignored\n",
402 { /* end of list */ }
406 static QemuOptsList qemu_name_opts = {
407 .name = "name",
408 .implied_opt_name = "guest",
409 .merge_lists = true,
410 .head = QTAILQ_HEAD_INITIALIZER(qemu_name_opts.head),
411 .desc = {
413 .name = "guest",
414 .type = QEMU_OPT_STRING,
415 .help = "Sets the name of the guest.\n"
416 "This name will be displayed in the SDL window caption.\n"
417 "The name will also be used for the VNC server",
418 }, {
419 .name = "process",
420 .type = QEMU_OPT_STRING,
421 .help = "Sets the name of the QEMU process, as shown in top etc",
422 }, {
423 .name = "debug-threads",
424 .type = QEMU_OPT_BOOL,
425 .help = "When enabled, name the individual threads; defaults off.\n"
426 "NOTE: The thread names are for debugging and not a\n"
427 "stable API.",
429 { /* End of list */ }
433 static QemuOptsList qemu_mem_opts = {
434 .name = "memory",
435 .implied_opt_name = "size",
436 .head = QTAILQ_HEAD_INITIALIZER(qemu_mem_opts.head),
437 .merge_lists = true,
438 .desc = {
440 .name = "size",
441 .type = QEMU_OPT_SIZE,
444 .name = "slots",
445 .type = QEMU_OPT_NUMBER,
448 .name = "maxmem",
449 .type = QEMU_OPT_SIZE,
451 { /* end of list */ }
455 static QemuOptsList qemu_icount_opts = {
456 .name = "icount",
457 .implied_opt_name = "shift",
458 .merge_lists = true,
459 .head = QTAILQ_HEAD_INITIALIZER(qemu_icount_opts.head),
460 .desc = {
462 .name = "shift",
463 .type = QEMU_OPT_STRING,
464 }, {
465 .name = "align",
466 .type = QEMU_OPT_BOOL,
467 }, {
468 .name = "sleep",
469 .type = QEMU_OPT_BOOL,
470 }, {
471 .name = "rr",
472 .type = QEMU_OPT_STRING,
473 }, {
474 .name = "rrfile",
475 .type = QEMU_OPT_STRING,
476 }, {
477 .name = "rrsnapshot",
478 .type = QEMU_OPT_STRING,
480 { /* end of list */ }
484 static QemuOptsList qemu_fw_cfg_opts = {
485 .name = "fw_cfg",
486 .implied_opt_name = "name",
487 .head = QTAILQ_HEAD_INITIALIZER(qemu_fw_cfg_opts.head),
488 .desc = {
490 .name = "name",
491 .type = QEMU_OPT_STRING,
492 .help = "Sets the fw_cfg name of the blob to be inserted",
493 }, {
494 .name = "file",
495 .type = QEMU_OPT_STRING,
496 .help = "Sets the name of the file from which "
497 "the fw_cfg blob will be loaded",
498 }, {
499 .name = "string",
500 .type = QEMU_OPT_STRING,
501 .help = "Sets content of the blob to be inserted from a string",
502 }, {
503 .name = "gen_id",
504 .type = QEMU_OPT_STRING,
505 .help = "Sets id of the object generating the fw_cfg blob "
506 "to be inserted",
508 { /* end of list */ }
513 * Get machine options
515 * Returns: machine options (never null).
517 QemuOpts *qemu_get_machine_opts(void)
519 return qemu_find_opts_singleton("machine");
522 const char *qemu_get_vm_name(void)
524 return qemu_name;
527 static void res_free(void)
529 g_free(boot_splash_filedata);
530 boot_splash_filedata = NULL;
533 static int default_driver_check(void *opaque, QemuOpts *opts, Error **errp)
535 const char *driver = qemu_opt_get(opts, "driver");
536 int i;
538 if (!driver)
539 return 0;
540 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
541 if (strcmp(default_list[i].driver, driver) != 0)
542 continue;
543 *(default_list[i].flag) = 0;
545 return 0;
548 /***********************************************************/
549 /* QEMU state */
551 static RunState current_run_state = RUN_STATE_PRECONFIG;
553 /* We use RUN_STATE__MAX but any invalid value will do */
554 static RunState vmstop_requested = RUN_STATE__MAX;
555 static QemuMutex vmstop_lock;
557 typedef struct {
558 RunState from;
559 RunState to;
560 } RunStateTransition;
562 static const RunStateTransition runstate_transitions_def[] = {
563 /* from -> to */
564 { RUN_STATE_PRECONFIG, RUN_STATE_PRELAUNCH },
565 /* Early switch to inmigrate state to allow -incoming CLI option work
566 * as it used to. TODO: delay actual switching to inmigrate state to
567 * the point after machine is built and remove this hack.
569 { RUN_STATE_PRECONFIG, RUN_STATE_INMIGRATE },
571 { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
572 { RUN_STATE_DEBUG, RUN_STATE_FINISH_MIGRATE },
573 { RUN_STATE_DEBUG, RUN_STATE_PRELAUNCH },
575 { RUN_STATE_INMIGRATE, RUN_STATE_INTERNAL_ERROR },
576 { RUN_STATE_INMIGRATE, RUN_STATE_IO_ERROR },
577 { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
578 { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
579 { RUN_STATE_INMIGRATE, RUN_STATE_SHUTDOWN },
580 { RUN_STATE_INMIGRATE, RUN_STATE_SUSPENDED },
581 { RUN_STATE_INMIGRATE, RUN_STATE_WATCHDOG },
582 { RUN_STATE_INMIGRATE, RUN_STATE_GUEST_PANICKED },
583 { RUN_STATE_INMIGRATE, RUN_STATE_FINISH_MIGRATE },
584 { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
585 { RUN_STATE_INMIGRATE, RUN_STATE_POSTMIGRATE },
586 { RUN_STATE_INMIGRATE, RUN_STATE_COLO },
588 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
589 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
590 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PRELAUNCH },
592 { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
593 { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
594 { RUN_STATE_IO_ERROR, RUN_STATE_PRELAUNCH },
596 { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
597 { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
598 { RUN_STATE_PAUSED, RUN_STATE_POSTMIGRATE },
599 { RUN_STATE_PAUSED, RUN_STATE_PRELAUNCH },
600 { RUN_STATE_PAUSED, RUN_STATE_COLO},
602 { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
603 { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
604 { RUN_STATE_POSTMIGRATE, RUN_STATE_PRELAUNCH },
606 { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
607 { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
608 { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
610 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
611 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PAUSED },
612 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
613 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PRELAUNCH },
614 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_COLO},
616 { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
617 { RUN_STATE_RESTORE_VM, RUN_STATE_PRELAUNCH },
619 { RUN_STATE_COLO, RUN_STATE_RUNNING },
621 { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
622 { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
623 { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
624 { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
625 { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
626 { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
627 { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
628 { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
629 { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
630 { RUN_STATE_RUNNING, RUN_STATE_GUEST_PANICKED },
631 { RUN_STATE_RUNNING, RUN_STATE_COLO},
633 { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
635 { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
636 { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
637 { RUN_STATE_SHUTDOWN, RUN_STATE_PRELAUNCH },
638 { RUN_STATE_SHUTDOWN, RUN_STATE_COLO },
640 { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
641 { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
642 { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
643 { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
644 { RUN_STATE_SUSPENDED, RUN_STATE_PRELAUNCH },
645 { RUN_STATE_SUSPENDED, RUN_STATE_COLO},
647 { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
648 { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
649 { RUN_STATE_WATCHDOG, RUN_STATE_PRELAUNCH },
650 { RUN_STATE_WATCHDOG, RUN_STATE_COLO},
652 { RUN_STATE_GUEST_PANICKED, RUN_STATE_RUNNING },
653 { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
654 { RUN_STATE_GUEST_PANICKED, RUN_STATE_PRELAUNCH },
656 { RUN_STATE__MAX, RUN_STATE__MAX },
659 static bool runstate_valid_transitions[RUN_STATE__MAX][RUN_STATE__MAX];
661 bool runstate_check(RunState state)
663 return current_run_state == state;
666 bool runstate_store(char *str, size_t size)
668 const char *state = RunState_str(current_run_state);
669 size_t len = strlen(state) + 1;
671 if (len > size) {
672 return false;
674 memcpy(str, state, len);
675 return true;
678 static void runstate_init(void)
680 const RunStateTransition *p;
682 memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
683 for (p = &runstate_transitions_def[0]; p->from != RUN_STATE__MAX; p++) {
684 runstate_valid_transitions[p->from][p->to] = true;
687 qemu_mutex_init(&vmstop_lock);
690 /* This function will abort() on invalid state transitions */
691 void runstate_set(RunState new_state)
693 assert(new_state < RUN_STATE__MAX);
695 trace_runstate_set(current_run_state, RunState_str(current_run_state),
696 new_state, RunState_str(new_state));
698 if (current_run_state == new_state) {
699 return;
702 if (!runstate_valid_transitions[current_run_state][new_state]) {
703 error_report("invalid runstate transition: '%s' -> '%s'",
704 RunState_str(current_run_state),
705 RunState_str(new_state));
706 abort();
709 current_run_state = new_state;
712 int runstate_is_running(void)
714 return runstate_check(RUN_STATE_RUNNING);
717 bool runstate_needs_reset(void)
719 return runstate_check(RUN_STATE_INTERNAL_ERROR) ||
720 runstate_check(RUN_STATE_SHUTDOWN);
723 StatusInfo *qmp_query_status(Error **errp)
725 StatusInfo *info = g_malloc0(sizeof(*info));
727 info->running = runstate_is_running();
728 info->singlestep = singlestep;
729 info->status = current_run_state;
731 return info;
734 bool qemu_vmstop_requested(RunState *r)
736 qemu_mutex_lock(&vmstop_lock);
737 *r = vmstop_requested;
738 vmstop_requested = RUN_STATE__MAX;
739 qemu_mutex_unlock(&vmstop_lock);
740 return *r < RUN_STATE__MAX;
743 void qemu_system_vmstop_request_prepare(void)
745 qemu_mutex_lock(&vmstop_lock);
748 void qemu_system_vmstop_request(RunState state)
750 vmstop_requested = state;
751 qemu_mutex_unlock(&vmstop_lock);
752 qemu_notify_event();
755 /***********************************************************/
756 /* RTC reference time/date access */
757 static time_t qemu_ref_timedate(QEMUClockType clock)
759 time_t value = qemu_clock_get_ms(clock) / 1000;
760 switch (clock) {
761 case QEMU_CLOCK_REALTIME:
762 value -= rtc_realtime_clock_offset;
763 /* fall through */
764 case QEMU_CLOCK_VIRTUAL:
765 value += rtc_ref_start_datetime;
766 break;
767 case QEMU_CLOCK_HOST:
768 if (rtc_base_type == RTC_BASE_DATETIME) {
769 value -= rtc_host_datetime_offset;
771 break;
772 default:
773 assert(0);
775 return value;
778 void qemu_get_timedate(struct tm *tm, int offset)
780 time_t ti = qemu_ref_timedate(rtc_clock);
782 ti += offset;
784 switch (rtc_base_type) {
785 case RTC_BASE_DATETIME:
786 case RTC_BASE_UTC:
787 gmtime_r(&ti, tm);
788 break;
789 case RTC_BASE_LOCALTIME:
790 localtime_r(&ti, tm);
791 break;
795 int qemu_timedate_diff(struct tm *tm)
797 time_t seconds;
799 switch (rtc_base_type) {
800 case RTC_BASE_DATETIME:
801 case RTC_BASE_UTC:
802 seconds = mktimegm(tm);
803 break;
804 case RTC_BASE_LOCALTIME:
806 struct tm tmp = *tm;
807 tmp.tm_isdst = -1; /* use timezone to figure it out */
808 seconds = mktime(&tmp);
809 break;
811 default:
812 abort();
815 return seconds - qemu_ref_timedate(QEMU_CLOCK_HOST);
818 static void configure_rtc_base_datetime(const char *startdate)
820 time_t rtc_start_datetime;
821 struct tm tm;
823 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d", &tm.tm_year, &tm.tm_mon,
824 &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6) {
825 /* OK */
826 } else if (sscanf(startdate, "%d-%d-%d",
827 &tm.tm_year, &tm.tm_mon, &tm.tm_mday) == 3) {
828 tm.tm_hour = 0;
829 tm.tm_min = 0;
830 tm.tm_sec = 0;
831 } else {
832 goto date_fail;
834 tm.tm_year -= 1900;
835 tm.tm_mon--;
836 rtc_start_datetime = mktimegm(&tm);
837 if (rtc_start_datetime == -1) {
838 date_fail:
839 error_report("invalid datetime format");
840 error_printf("valid formats: "
841 "'2006-06-17T16:01:21' or '2006-06-17'\n");
842 exit(1);
844 rtc_host_datetime_offset = rtc_ref_start_datetime - rtc_start_datetime;
845 rtc_ref_start_datetime = rtc_start_datetime;
848 static void configure_rtc(QemuOpts *opts)
850 const char *value;
852 /* Set defaults */
853 rtc_clock = QEMU_CLOCK_HOST;
854 rtc_ref_start_datetime = qemu_clock_get_ms(QEMU_CLOCK_HOST) / 1000;
855 rtc_realtime_clock_offset = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) / 1000;
857 value = qemu_opt_get(opts, "base");
858 if (value) {
859 if (!strcmp(value, "utc")) {
860 rtc_base_type = RTC_BASE_UTC;
861 } else if (!strcmp(value, "localtime")) {
862 Error *blocker = NULL;
863 rtc_base_type = RTC_BASE_LOCALTIME;
864 error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
865 "-rtc base=localtime");
866 replay_add_blocker(blocker);
867 } else {
868 rtc_base_type = RTC_BASE_DATETIME;
869 configure_rtc_base_datetime(value);
872 value = qemu_opt_get(opts, "clock");
873 if (value) {
874 if (!strcmp(value, "host")) {
875 rtc_clock = QEMU_CLOCK_HOST;
876 } else if (!strcmp(value, "rt")) {
877 rtc_clock = QEMU_CLOCK_REALTIME;
878 } else if (!strcmp(value, "vm")) {
879 rtc_clock = QEMU_CLOCK_VIRTUAL;
880 } else {
881 error_report("invalid option value '%s'", value);
882 exit(1);
885 value = qemu_opt_get(opts, "driftfix");
886 if (value) {
887 if (!strcmp(value, "slew")) {
888 object_register_sugar_prop("mc146818rtc",
889 "lost_tick_policy",
890 "slew");
891 } else if (!strcmp(value, "none")) {
892 /* discard is default */
893 } else {
894 error_report("invalid option value '%s'", value);
895 exit(1);
900 static int parse_name(void *opaque, QemuOpts *opts, Error **errp)
902 const char *proc_name;
904 if (qemu_opt_get(opts, "debug-threads")) {
905 qemu_thread_naming(qemu_opt_get_bool(opts, "debug-threads", false));
907 qemu_name = qemu_opt_get(opts, "guest");
909 proc_name = qemu_opt_get(opts, "process");
910 if (proc_name) {
911 os_set_proc_name(proc_name);
914 return 0;
917 bool defaults_enabled(void)
919 return has_defaults;
922 #ifndef _WIN32
923 static int parse_add_fd(void *opaque, QemuOpts *opts, Error **errp)
925 int fd, dupfd, flags;
926 int64_t fdset_id;
927 const char *fd_opaque = NULL;
928 AddfdInfo *fdinfo;
930 fd = qemu_opt_get_number(opts, "fd", -1);
931 fdset_id = qemu_opt_get_number(opts, "set", -1);
932 fd_opaque = qemu_opt_get(opts, "opaque");
934 if (fd < 0) {
935 error_setg(errp, "fd option is required and must be non-negative");
936 return -1;
939 if (fd <= STDERR_FILENO) {
940 error_setg(errp, "fd cannot be a standard I/O stream");
941 return -1;
945 * All fds inherited across exec() necessarily have FD_CLOEXEC
946 * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
948 flags = fcntl(fd, F_GETFD);
949 if (flags == -1 || (flags & FD_CLOEXEC)) {
950 error_setg(errp, "fd is not valid or already in use");
951 return -1;
954 if (fdset_id < 0) {
955 error_setg(errp, "set option is required and must be non-negative");
956 return -1;
959 #ifdef F_DUPFD_CLOEXEC
960 dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
961 #else
962 dupfd = dup(fd);
963 if (dupfd != -1) {
964 qemu_set_cloexec(dupfd);
966 #endif
967 if (dupfd == -1) {
968 error_setg(errp, "error duplicating fd: %s", strerror(errno));
969 return -1;
972 /* add the duplicate fd, and optionally the opaque string, to the fd set */
973 fdinfo = monitor_fdset_add_fd(dupfd, true, fdset_id, !!fd_opaque, fd_opaque,
974 &error_abort);
975 g_free(fdinfo);
977 return 0;
980 static int cleanup_add_fd(void *opaque, QemuOpts *opts, Error **errp)
982 int fd;
984 fd = qemu_opt_get_number(opts, "fd", -1);
985 close(fd);
987 return 0;
989 #endif
991 /***********************************************************/
992 /* QEMU Block devices */
994 #define HD_OPTS "media=disk"
995 #define CDROM_OPTS "media=cdrom"
996 #define FD_OPTS ""
997 #define PFLASH_OPTS ""
998 #define MTD_OPTS ""
999 #define SD_OPTS ""
1001 static int drive_init_func(void *opaque, QemuOpts *opts, Error **errp)
1003 BlockInterfaceType *block_default_type = opaque;
1005 return drive_new(opts, *block_default_type, errp) == NULL;
1008 static int drive_enable_snapshot(void *opaque, QemuOpts *opts, Error **errp)
1010 if (qemu_opt_get(opts, "snapshot") == NULL) {
1011 qemu_opt_set(opts, "snapshot", "on", &error_abort);
1013 return 0;
1016 static void default_drive(int enable, int snapshot, BlockInterfaceType type,
1017 int index, const char *optstr)
1019 QemuOpts *opts;
1020 DriveInfo *dinfo;
1022 if (!enable || drive_get_by_index(type, index)) {
1023 return;
1026 opts = drive_add(type, index, NULL, optstr);
1027 if (snapshot) {
1028 drive_enable_snapshot(NULL, opts, NULL);
1031 dinfo = drive_new(opts, type, &error_abort);
1032 dinfo->is_default = true;
1036 typedef struct BlockdevOptionsQueueEntry {
1037 BlockdevOptions *bdo;
1038 Location loc;
1039 QSIMPLEQ_ENTRY(BlockdevOptionsQueueEntry) entry;
1040 } BlockdevOptionsQueueEntry;
1042 typedef QSIMPLEQ_HEAD(, BlockdevOptionsQueueEntry) BlockdevOptionsQueue;
1044 static void configure_blockdev(BlockdevOptionsQueue *bdo_queue,
1045 MachineClass *machine_class, int snapshot)
1048 * If the currently selected machine wishes to override the
1049 * units-per-bus property of its default HBA interface type, do so
1050 * now.
1052 if (machine_class->units_per_default_bus) {
1053 override_max_devs(machine_class->block_default_type,
1054 machine_class->units_per_default_bus);
1057 /* open the virtual block devices */
1058 while (!QSIMPLEQ_EMPTY(bdo_queue)) {
1059 BlockdevOptionsQueueEntry *bdo = QSIMPLEQ_FIRST(bdo_queue);
1061 QSIMPLEQ_REMOVE_HEAD(bdo_queue, entry);
1062 loc_push_restore(&bdo->loc);
1063 qmp_blockdev_add(bdo->bdo, &error_fatal);
1064 loc_pop(&bdo->loc);
1065 qapi_free_BlockdevOptions(bdo->bdo);
1066 g_free(bdo);
1068 if (snapshot) {
1069 qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot,
1070 NULL, NULL);
1072 if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
1073 &machine_class->block_default_type, &error_fatal)) {
1074 /* We printed help */
1075 exit(0);
1078 default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
1079 CDROM_OPTS);
1080 default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
1081 default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
1085 static QemuOptsList qemu_smp_opts = {
1086 .name = "smp-opts",
1087 .implied_opt_name = "cpus",
1088 .merge_lists = true,
1089 .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
1090 .desc = {
1092 .name = "cpus",
1093 .type = QEMU_OPT_NUMBER,
1094 }, {
1095 .name = "sockets",
1096 .type = QEMU_OPT_NUMBER,
1097 }, {
1098 .name = "dies",
1099 .type = QEMU_OPT_NUMBER,
1100 }, {
1101 .name = "cores",
1102 .type = QEMU_OPT_NUMBER,
1103 }, {
1104 .name = "threads",
1105 .type = QEMU_OPT_NUMBER,
1106 }, {
1107 .name = "maxcpus",
1108 .type = QEMU_OPT_NUMBER,
1110 { /*End of list */ }
1114 static void realtime_init(void)
1116 if (enable_mlock) {
1117 if (os_mlock() < 0) {
1118 error_report("locking memory failed");
1119 exit(1);
1125 static void configure_msg(QemuOpts *opts)
1127 error_with_timestamp = qemu_opt_get_bool(opts, "timestamp", false);
1128 error_with_guestname = qemu_opt_get_bool(opts, "guest-name", false);
1132 /***********************************************************/
1133 /* USB devices */
1135 static int usb_device_add(const char *devname)
1137 USBDevice *dev = NULL;
1139 if (!machine_usb(current_machine)) {
1140 return -1;
1143 dev = usbdevice_create(devname);
1144 if (!dev)
1145 return -1;
1147 return 0;
1150 static int usb_parse(const char *cmdline)
1152 int r;
1153 r = usb_device_add(cmdline);
1154 if (r < 0) {
1155 error_report("could not add USB device '%s'", cmdline);
1157 return r;
1160 /***********************************************************/
1161 /* machine registration */
1163 MachineState *current_machine;
1165 static MachineClass *find_machine(const char *name, GSList *machines)
1167 GSList *el;
1169 for (el = machines; el; el = el->next) {
1170 MachineClass *mc = el->data;
1172 if (!strcmp(mc->name, name) || !g_strcmp0(mc->alias, name)) {
1173 return mc;
1177 return NULL;
1180 static MachineClass *find_default_machine(GSList *machines)
1182 GSList *el;
1183 MachineClass *default_machineclass = NULL;
1185 for (el = machines; el; el = el->next) {
1186 MachineClass *mc = el->data;
1188 if (mc->is_default) {
1189 assert(default_machineclass == NULL && "Multiple default machines");
1190 default_machineclass = mc;
1194 return default_machineclass;
1197 static int machine_help_func(QemuOpts *opts, MachineState *machine)
1199 ObjectProperty *prop;
1200 ObjectPropertyIterator iter;
1202 if (!qemu_opt_has_help_opt(opts)) {
1203 return 0;
1206 object_property_iter_init(&iter, OBJECT(machine));
1207 while ((prop = object_property_iter_next(&iter))) {
1208 if (!prop->set) {
1209 continue;
1212 printf("%s.%s=%s", MACHINE_GET_CLASS(machine)->name,
1213 prop->name, prop->type);
1214 if (prop->description) {
1215 printf(" (%s)\n", prop->description);
1216 } else {
1217 printf("\n");
1221 return 1;
1224 struct VMChangeStateEntry {
1225 VMChangeStateHandler *cb;
1226 void *opaque;
1227 QTAILQ_ENTRY(VMChangeStateEntry) entries;
1228 int priority;
1231 static QTAILQ_HEAD(, VMChangeStateEntry) vm_change_state_head;
1234 * qemu_add_vm_change_state_handler_prio:
1235 * @cb: the callback to invoke
1236 * @opaque: user data passed to the callback
1237 * @priority: low priorities execute first when the vm runs and the reverse is
1238 * true when the vm stops
1240 * Register a callback function that is invoked when the vm starts or stops
1241 * running.
1243 * Returns: an entry to be freed using qemu_del_vm_change_state_handler()
1245 VMChangeStateEntry *qemu_add_vm_change_state_handler_prio(
1246 VMChangeStateHandler *cb, void *opaque, int priority)
1248 VMChangeStateEntry *e;
1249 VMChangeStateEntry *other;
1251 e = g_malloc0(sizeof(*e));
1252 e->cb = cb;
1253 e->opaque = opaque;
1254 e->priority = priority;
1256 /* Keep list sorted in ascending priority order */
1257 QTAILQ_FOREACH(other, &vm_change_state_head, entries) {
1258 if (priority < other->priority) {
1259 QTAILQ_INSERT_BEFORE(other, e, entries);
1260 return e;
1264 QTAILQ_INSERT_TAIL(&vm_change_state_head, e, entries);
1265 return e;
1268 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1269 void *opaque)
1271 return qemu_add_vm_change_state_handler_prio(cb, opaque, 0);
1274 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1276 QTAILQ_REMOVE(&vm_change_state_head, e, entries);
1277 g_free(e);
1280 void vm_state_notify(int running, RunState state)
1282 VMChangeStateEntry *e, *next;
1284 trace_vm_state_notify(running, state, RunState_str(state));
1286 if (running) {
1287 QTAILQ_FOREACH_SAFE(e, &vm_change_state_head, entries, next) {
1288 e->cb(e->opaque, running, state);
1290 } else {
1291 QTAILQ_FOREACH_REVERSE_SAFE(e, &vm_change_state_head, entries, next) {
1292 e->cb(e->opaque, running, state);
1297 static ShutdownCause reset_requested;
1298 static ShutdownCause shutdown_requested;
1299 static int shutdown_signal;
1300 static pid_t shutdown_pid;
1301 static int powerdown_requested;
1302 static int debug_requested;
1303 static int suspend_requested;
1304 static bool preconfig_exit_requested = true;
1305 static WakeupReason wakeup_reason;
1306 static NotifierList powerdown_notifiers =
1307 NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
1308 static NotifierList suspend_notifiers =
1309 NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1310 static NotifierList wakeup_notifiers =
1311 NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1312 static NotifierList shutdown_notifiers =
1313 NOTIFIER_LIST_INITIALIZER(shutdown_notifiers);
1314 static uint32_t wakeup_reason_mask = ~(1 << QEMU_WAKEUP_REASON_NONE);
1316 ShutdownCause qemu_shutdown_requested_get(void)
1318 return shutdown_requested;
1321 ShutdownCause qemu_reset_requested_get(void)
1323 return reset_requested;
1326 static int qemu_shutdown_requested(void)
1328 return qatomic_xchg(&shutdown_requested, SHUTDOWN_CAUSE_NONE);
1331 static void qemu_kill_report(void)
1333 if (!qtest_driver() && shutdown_signal) {
1334 if (shutdown_pid == 0) {
1335 /* This happens for eg ^C at the terminal, so it's worth
1336 * avoiding printing an odd message in that case.
1338 error_report("terminating on signal %d", shutdown_signal);
1339 } else {
1340 char *shutdown_cmd = qemu_get_pid_name(shutdown_pid);
1342 error_report("terminating on signal %d from pid " FMT_pid " (%s)",
1343 shutdown_signal, shutdown_pid,
1344 shutdown_cmd ? shutdown_cmd : "<unknown process>");
1345 g_free(shutdown_cmd);
1347 shutdown_signal = 0;
1351 static ShutdownCause qemu_reset_requested(void)
1353 ShutdownCause r = reset_requested;
1355 if (r && replay_checkpoint(CHECKPOINT_RESET_REQUESTED)) {
1356 reset_requested = SHUTDOWN_CAUSE_NONE;
1357 return r;
1359 return SHUTDOWN_CAUSE_NONE;
1362 static int qemu_suspend_requested(void)
1364 int r = suspend_requested;
1365 if (r && replay_checkpoint(CHECKPOINT_SUSPEND_REQUESTED)) {
1366 suspend_requested = 0;
1367 return r;
1369 return false;
1372 static WakeupReason qemu_wakeup_requested(void)
1374 return wakeup_reason;
1377 static int qemu_powerdown_requested(void)
1379 int r = powerdown_requested;
1380 powerdown_requested = 0;
1381 return r;
1384 static int qemu_debug_requested(void)
1386 int r = debug_requested;
1387 debug_requested = 0;
1388 return r;
1391 void qemu_exit_preconfig_request(void)
1393 preconfig_exit_requested = true;
1397 * Reset the VM. Issue an event unless @reason is SHUTDOWN_CAUSE_NONE.
1399 void qemu_system_reset(ShutdownCause reason)
1401 MachineClass *mc;
1403 mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1405 cpu_synchronize_all_states();
1407 if (mc && mc->reset) {
1408 mc->reset(current_machine);
1409 } else {
1410 qemu_devices_reset();
1412 if (reason && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1413 qapi_event_send_reset(shutdown_caused_by_guest(reason), reason);
1415 cpu_synchronize_all_post_reset();
1419 * Wake the VM after suspend.
1421 static void qemu_system_wakeup(void)
1423 MachineClass *mc;
1425 mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1427 if (mc && mc->wakeup) {
1428 mc->wakeup(current_machine);
1432 void qemu_system_guest_panicked(GuestPanicInformation *info)
1434 qemu_log_mask(LOG_GUEST_ERROR, "Guest crashed");
1436 if (current_cpu) {
1437 current_cpu->crash_occurred = true;
1439 qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE,
1440 !!info, info);
1441 vm_stop(RUN_STATE_GUEST_PANICKED);
1442 if (!no_shutdown) {
1443 qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_POWEROFF,
1444 !!info, info);
1445 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_PANIC);
1448 if (info) {
1449 if (info->type == GUEST_PANIC_INFORMATION_TYPE_HYPER_V) {
1450 qemu_log_mask(LOG_GUEST_ERROR, "\nHV crash parameters: (%#"PRIx64
1451 " %#"PRIx64" %#"PRIx64" %#"PRIx64" %#"PRIx64")\n",
1452 info->u.hyper_v.arg1,
1453 info->u.hyper_v.arg2,
1454 info->u.hyper_v.arg3,
1455 info->u.hyper_v.arg4,
1456 info->u.hyper_v.arg5);
1457 } else if (info->type == GUEST_PANIC_INFORMATION_TYPE_S390) {
1458 qemu_log_mask(LOG_GUEST_ERROR, " on cpu %d: %s\n"
1459 "PSW: 0x%016" PRIx64 " 0x%016" PRIx64"\n",
1460 info->u.s390.core,
1461 S390CrashReason_str(info->u.s390.reason),
1462 info->u.s390.psw_mask,
1463 info->u.s390.psw_addr);
1465 qapi_free_GuestPanicInformation(info);
1469 void qemu_system_guest_crashloaded(GuestPanicInformation *info)
1471 qemu_log_mask(LOG_GUEST_ERROR, "Guest crash loaded");
1473 qapi_event_send_guest_crashloaded(GUEST_PANIC_ACTION_RUN,
1474 !!info, info);
1476 if (info) {
1477 qapi_free_GuestPanicInformation(info);
1481 void qemu_system_reset_request(ShutdownCause reason)
1483 if (no_reboot && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1484 shutdown_requested = reason;
1485 } else {
1486 reset_requested = reason;
1488 cpu_stop_current();
1489 qemu_notify_event();
1492 static void qemu_system_suspend(void)
1494 pause_all_vcpus();
1495 notifier_list_notify(&suspend_notifiers, NULL);
1496 runstate_set(RUN_STATE_SUSPENDED);
1497 qapi_event_send_suspend();
1500 void qemu_system_suspend_request(void)
1502 if (runstate_check(RUN_STATE_SUSPENDED)) {
1503 return;
1505 suspend_requested = 1;
1506 cpu_stop_current();
1507 qemu_notify_event();
1510 void qemu_register_suspend_notifier(Notifier *notifier)
1512 notifier_list_add(&suspend_notifiers, notifier);
1515 void qemu_system_wakeup_request(WakeupReason reason, Error **errp)
1517 trace_system_wakeup_request(reason);
1519 if (!runstate_check(RUN_STATE_SUSPENDED)) {
1520 error_setg(errp,
1521 "Unable to wake up: guest is not in suspended state");
1522 return;
1524 if (!(wakeup_reason_mask & (1 << reason))) {
1525 return;
1527 runstate_set(RUN_STATE_RUNNING);
1528 wakeup_reason = reason;
1529 qemu_notify_event();
1532 void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1534 if (enabled) {
1535 wakeup_reason_mask |= (1 << reason);
1536 } else {
1537 wakeup_reason_mask &= ~(1 << reason);
1541 void qemu_register_wakeup_notifier(Notifier *notifier)
1543 notifier_list_add(&wakeup_notifiers, notifier);
1546 void qemu_register_wakeup_support(void)
1548 wakeup_suspend_enabled = true;
1551 bool qemu_wakeup_suspend_enabled(void)
1553 return wakeup_suspend_enabled;
1556 void qemu_system_killed(int signal, pid_t pid)
1558 shutdown_signal = signal;
1559 shutdown_pid = pid;
1560 no_shutdown = 0;
1562 /* Cannot call qemu_system_shutdown_request directly because
1563 * we are in a signal handler.
1565 shutdown_requested = SHUTDOWN_CAUSE_HOST_SIGNAL;
1566 qemu_notify_event();
1569 void qemu_system_shutdown_request(ShutdownCause reason)
1571 trace_qemu_system_shutdown_request(reason);
1572 replay_shutdown_request(reason);
1573 shutdown_requested = reason;
1574 qemu_notify_event();
1577 static void qemu_system_powerdown(void)
1579 qapi_event_send_powerdown();
1580 notifier_list_notify(&powerdown_notifiers, NULL);
1583 static void qemu_system_shutdown(ShutdownCause cause)
1585 qapi_event_send_shutdown(shutdown_caused_by_guest(cause), cause);
1586 notifier_list_notify(&shutdown_notifiers, &cause);
1589 void qemu_system_powerdown_request(void)
1591 trace_qemu_system_powerdown_request();
1592 powerdown_requested = 1;
1593 qemu_notify_event();
1596 void qemu_register_powerdown_notifier(Notifier *notifier)
1598 notifier_list_add(&powerdown_notifiers, notifier);
1601 void qemu_register_shutdown_notifier(Notifier *notifier)
1603 notifier_list_add(&shutdown_notifiers, notifier);
1606 void qemu_system_debug_request(void)
1608 debug_requested = 1;
1609 qemu_notify_event();
1612 static bool main_loop_should_exit(void)
1614 RunState r;
1615 ShutdownCause request;
1617 if (preconfig_exit_requested) {
1618 if (runstate_check(RUN_STATE_PRECONFIG)) {
1619 runstate_set(RUN_STATE_PRELAUNCH);
1621 preconfig_exit_requested = false;
1622 return true;
1624 if (qemu_debug_requested()) {
1625 vm_stop(RUN_STATE_DEBUG);
1627 if (qemu_suspend_requested()) {
1628 qemu_system_suspend();
1630 request = qemu_shutdown_requested();
1631 if (request) {
1632 qemu_kill_report();
1633 qemu_system_shutdown(request);
1634 if (no_shutdown) {
1635 vm_stop(RUN_STATE_SHUTDOWN);
1636 } else {
1637 return true;
1640 request = qemu_reset_requested();
1641 if (request) {
1642 pause_all_vcpus();
1643 qemu_system_reset(request);
1644 resume_all_vcpus();
1646 * runstate can change in pause_all_vcpus()
1647 * as iothread mutex is unlocked
1649 if (!runstate_check(RUN_STATE_RUNNING) &&
1650 !runstate_check(RUN_STATE_INMIGRATE) &&
1651 !runstate_check(RUN_STATE_FINISH_MIGRATE)) {
1652 runstate_set(RUN_STATE_PRELAUNCH);
1655 if (qemu_wakeup_requested()) {
1656 pause_all_vcpus();
1657 qemu_system_wakeup();
1658 notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
1659 wakeup_reason = QEMU_WAKEUP_REASON_NONE;
1660 resume_all_vcpus();
1661 qapi_event_send_wakeup();
1663 if (qemu_powerdown_requested()) {
1664 qemu_system_powerdown();
1666 if (qemu_vmstop_requested(&r)) {
1667 vm_stop(r);
1669 return false;
1672 void qemu_main_loop(void)
1674 #ifdef CONFIG_PROFILER
1675 int64_t ti;
1676 #endif
1677 while (!main_loop_should_exit()) {
1678 #ifdef CONFIG_PROFILER
1679 ti = profile_getclock();
1680 #endif
1681 main_loop_wait(false);
1682 #ifdef CONFIG_PROFILER
1683 dev_time += profile_getclock() - ti;
1684 #endif
1688 static void version(void)
1690 printf("QEMU emulator version " QEMU_FULL_VERSION "\n"
1691 QEMU_COPYRIGHT "\n");
1694 static void help(int exitcode)
1696 version();
1697 printf("usage: %s [options] [disk_image]\n\n"
1698 "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
1699 error_get_progname());
1701 #define QEMU_OPTIONS_GENERATE_HELP
1702 #include "qemu-options-wrapper.h"
1704 printf("\nDuring emulation, the following keys are useful:\n"
1705 "ctrl-alt-f toggle full screen\n"
1706 "ctrl-alt-n switch to virtual console 'n'\n"
1707 "ctrl-alt toggle mouse and keyboard grab\n"
1708 "\n"
1709 "When using -nographic, press 'ctrl-a h' to get some help.\n"
1710 "\n"
1711 QEMU_HELP_BOTTOM "\n");
1713 exit(exitcode);
1716 #define HAS_ARG 0x0001
1718 typedef struct QEMUOption {
1719 const char *name;
1720 int flags;
1721 int index;
1722 uint32_t arch_mask;
1723 } QEMUOption;
1725 static const QEMUOption qemu_options[] = {
1726 { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1727 #define QEMU_OPTIONS_GENERATE_OPTIONS
1728 #include "qemu-options-wrapper.h"
1729 { NULL },
1732 typedef struct VGAInterfaceInfo {
1733 const char *opt_name; /* option name */
1734 const char *name; /* human-readable name */
1735 /* Class names indicating that support is available.
1736 * If no class is specified, the interface is always available */
1737 const char *class_names[2];
1738 } VGAInterfaceInfo;
1740 static const VGAInterfaceInfo vga_interfaces[VGA_TYPE_MAX] = {
1741 [VGA_NONE] = {
1742 .opt_name = "none",
1743 .name = "no graphic card",
1745 [VGA_STD] = {
1746 .opt_name = "std",
1747 .name = "standard VGA",
1748 .class_names = { "VGA", "isa-vga" },
1750 [VGA_CIRRUS] = {
1751 .opt_name = "cirrus",
1752 .name = "Cirrus VGA",
1753 .class_names = { "cirrus-vga", "isa-cirrus-vga" },
1755 [VGA_VMWARE] = {
1756 .opt_name = "vmware",
1757 .name = "VMWare SVGA",
1758 .class_names = { "vmware-svga" },
1760 [VGA_VIRTIO] = {
1761 .opt_name = "virtio",
1762 .name = "Virtio VGA",
1763 .class_names = { "virtio-vga" },
1765 [VGA_QXL] = {
1766 .opt_name = "qxl",
1767 .name = "QXL VGA",
1768 .class_names = { "qxl-vga" },
1770 [VGA_TCX] = {
1771 .opt_name = "tcx",
1772 .name = "TCX framebuffer",
1773 .class_names = { "SUNW,tcx" },
1775 [VGA_CG3] = {
1776 .opt_name = "cg3",
1777 .name = "CG3 framebuffer",
1778 .class_names = { "cgthree" },
1780 [VGA_XENFB] = {
1781 .opt_name = "xenfb",
1782 .name = "Xen paravirtualized framebuffer",
1786 static bool vga_interface_available(VGAInterfaceType t)
1788 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1790 assert(t < VGA_TYPE_MAX);
1791 return !ti->class_names[0] ||
1792 module_object_class_by_name(ti->class_names[0]) ||
1793 module_object_class_by_name(ti->class_names[1]);
1796 static const char *
1797 get_default_vga_model(const MachineClass *machine_class)
1799 if (machine_class->default_display) {
1800 return machine_class->default_display;
1801 } else if (vga_interface_available(VGA_CIRRUS)) {
1802 return "cirrus";
1803 } else if (vga_interface_available(VGA_STD)) {
1804 return "std";
1807 return NULL;
1810 static void select_vgahw(const MachineClass *machine_class, const char *p)
1812 const char *opts;
1813 int t;
1815 if (g_str_equal(p, "help")) {
1816 const char *def = get_default_vga_model(machine_class);
1818 for (t = 0; t < VGA_TYPE_MAX; t++) {
1819 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1821 if (vga_interface_available(t) && ti->opt_name) {
1822 printf("%-20s %s%s\n", ti->opt_name, ti->name ?: "",
1823 g_str_equal(ti->opt_name, def) ? " (default)" : "");
1826 exit(0);
1829 assert(vga_interface_type == VGA_NONE);
1830 for (t = 0; t < VGA_TYPE_MAX; t++) {
1831 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1832 if (ti->opt_name && strstart(p, ti->opt_name, &opts)) {
1833 if (!vga_interface_available(t)) {
1834 error_report("%s not available", ti->name);
1835 exit(1);
1837 vga_interface_type = t;
1838 break;
1841 if (t == VGA_TYPE_MAX) {
1842 invalid_vga:
1843 error_report("unknown vga type: %s", p);
1844 exit(1);
1846 while (*opts) {
1847 const char *nextopt;
1849 if (strstart(opts, ",retrace=", &nextopt)) {
1850 opts = nextopt;
1851 if (strstart(opts, "dumb", &nextopt))
1852 vga_retrace_method = VGA_RETRACE_DUMB;
1853 else if (strstart(opts, "precise", &nextopt))
1854 vga_retrace_method = VGA_RETRACE_PRECISE;
1855 else goto invalid_vga;
1856 } else goto invalid_vga;
1857 opts = nextopt;
1861 static void parse_display_qapi(const char *optarg)
1863 DisplayOptions *opts;
1864 Visitor *v;
1866 v = qobject_input_visitor_new_str(optarg, "type", &error_fatal);
1868 visit_type_DisplayOptions(v, NULL, &opts, &error_fatal);
1869 QAPI_CLONE_MEMBERS(DisplayOptions, &dpy, opts);
1871 qapi_free_DisplayOptions(opts);
1872 visit_free(v);
1875 DisplayOptions *qmp_query_display_options(Error **errp)
1877 return QAPI_CLONE(DisplayOptions, &dpy);
1880 static void parse_display(const char *p)
1882 const char *opts;
1884 if (is_help_option(p)) {
1885 qemu_display_help();
1886 exit(0);
1889 if (strstart(p, "sdl", &opts)) {
1891 * sdl DisplayType needs hand-crafted parser instead of
1892 * parse_display_qapi() due to some options not in
1893 * DisplayOptions, specifically:
1894 * - frame
1895 * Already deprecated.
1896 * - ctrl_grab + alt_grab
1897 * Not clear yet what happens to them long-term. Should
1898 * replaced by something better or deprecated and dropped.
1900 dpy.type = DISPLAY_TYPE_SDL;
1901 while (*opts) {
1902 const char *nextopt;
1904 if (strstart(opts, ",alt_grab=", &nextopt)) {
1905 opts = nextopt;
1906 if (strstart(opts, "on", &nextopt)) {
1907 alt_grab = 1;
1908 } else if (strstart(opts, "off", &nextopt)) {
1909 alt_grab = 0;
1910 } else {
1911 goto invalid_sdl_args;
1913 } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
1914 opts = nextopt;
1915 if (strstart(opts, "on", &nextopt)) {
1916 ctrl_grab = 1;
1917 } else if (strstart(opts, "off", &nextopt)) {
1918 ctrl_grab = 0;
1919 } else {
1920 goto invalid_sdl_args;
1922 } else if (strstart(opts, ",window_close=", &nextopt)) {
1923 opts = nextopt;
1924 dpy.has_window_close = true;
1925 if (strstart(opts, "on", &nextopt)) {
1926 dpy.window_close = true;
1927 } else if (strstart(opts, "off", &nextopt)) {
1928 dpy.window_close = false;
1929 } else {
1930 goto invalid_sdl_args;
1932 } else if (strstart(opts, ",show-cursor=", &nextopt)) {
1933 opts = nextopt;
1934 dpy.has_show_cursor = true;
1935 if (strstart(opts, "on", &nextopt)) {
1936 dpy.show_cursor = true;
1937 } else if (strstart(opts, "off", &nextopt)) {
1938 dpy.show_cursor = false;
1939 } else {
1940 goto invalid_sdl_args;
1942 } else if (strstart(opts, ",gl=", &nextopt)) {
1943 opts = nextopt;
1944 dpy.has_gl = true;
1945 if (strstart(opts, "on", &nextopt)) {
1946 dpy.gl = DISPLAYGL_MODE_ON;
1947 } else if (strstart(opts, "core", &nextopt)) {
1948 dpy.gl = DISPLAYGL_MODE_CORE;
1949 } else if (strstart(opts, "es", &nextopt)) {
1950 dpy.gl = DISPLAYGL_MODE_ES;
1951 } else if (strstart(opts, "off", &nextopt)) {
1952 dpy.gl = DISPLAYGL_MODE_OFF;
1953 } else {
1954 goto invalid_sdl_args;
1956 } else {
1957 invalid_sdl_args:
1958 error_report("invalid SDL option string");
1959 exit(1);
1961 opts = nextopt;
1963 } else if (strstart(p, "vnc", &opts)) {
1965 * vnc isn't a (local) DisplayType but a protocol for remote
1966 * display access.
1968 if (*opts == '=') {
1969 vnc_parse(opts + 1, &error_fatal);
1970 } else {
1971 error_report("VNC requires a display argument vnc=<display>");
1972 exit(1);
1974 } else {
1975 parse_display_qapi(p);
1979 char *qemu_find_file(int type, const char *name)
1981 int i;
1982 const char *subdir;
1983 char *buf;
1985 /* Try the name as a straight path first */
1986 if (access(name, R_OK) == 0) {
1987 trace_load_file(name, name);
1988 return g_strdup(name);
1991 switch (type) {
1992 case QEMU_FILE_TYPE_BIOS:
1993 subdir = "";
1994 break;
1995 case QEMU_FILE_TYPE_KEYMAP:
1996 subdir = "keymaps/";
1997 break;
1998 default:
1999 abort();
2002 for (i = 0; i < data_dir_idx; i++) {
2003 buf = g_strdup_printf("%s/%s%s", data_dir[i], subdir, name);
2004 if (access(buf, R_OK) == 0) {
2005 trace_load_file(name, buf);
2006 return buf;
2008 g_free(buf);
2010 return NULL;
2013 void qemu_add_data_dir(char *path)
2015 int i;
2017 if (path == NULL) {
2018 return;
2020 if (data_dir_idx == ARRAY_SIZE(data_dir)) {
2021 return;
2023 for (i = 0; i < data_dir_idx; i++) {
2024 if (strcmp(data_dir[i], path) == 0) {
2025 g_free(path); /* duplicate */
2026 return;
2029 data_dir[data_dir_idx++] = path;
2032 static inline bool nonempty_str(const char *str)
2034 return str && *str;
2037 static int parse_fw_cfg(void *opaque, QemuOpts *opts, Error **errp)
2039 gchar *buf;
2040 size_t size;
2041 const char *name, *file, *str, *gen_id;
2042 FWCfgState *fw_cfg = (FWCfgState *) opaque;
2044 if (fw_cfg == NULL) {
2045 error_setg(errp, "fw_cfg device not available");
2046 return -1;
2048 name = qemu_opt_get(opts, "name");
2049 file = qemu_opt_get(opts, "file");
2050 str = qemu_opt_get(opts, "string");
2051 gen_id = qemu_opt_get(opts, "gen_id");
2053 /* we need the name, and exactly one of: file, content string, gen_id */
2054 if (!nonempty_str(name) ||
2055 nonempty_str(file) + nonempty_str(str) + nonempty_str(gen_id) != 1) {
2056 error_setg(errp, "name, plus exactly one of file,"
2057 " string and gen_id, are needed");
2058 return -1;
2060 if (strlen(name) > FW_CFG_MAX_FILE_PATH - 1) {
2061 error_setg(errp, "name too long (max. %d char)",
2062 FW_CFG_MAX_FILE_PATH - 1);
2063 return -1;
2065 if (nonempty_str(gen_id)) {
2067 * In this particular case where the content is populated
2068 * internally, the "etc/" namespace protection is relaxed,
2069 * so do not emit a warning.
2071 } else if (strncmp(name, "opt/", 4) != 0) {
2072 warn_report("externally provided fw_cfg item names "
2073 "should be prefixed with \"opt/\"");
2075 if (nonempty_str(str)) {
2076 size = strlen(str); /* NUL terminator NOT included in fw_cfg blob */
2077 buf = g_memdup(str, size);
2078 } else if (nonempty_str(gen_id)) {
2079 if (!fw_cfg_add_from_generator(fw_cfg, name, gen_id, errp)) {
2080 return -1;
2082 return 0;
2083 } else {
2084 GError *err = NULL;
2085 if (!g_file_get_contents(file, &buf, &size, &err)) {
2086 error_setg(errp, "can't load %s: %s", file, err->message);
2087 g_error_free(err);
2088 return -1;
2091 /* For legacy, keep user files in a specific global order. */
2092 fw_cfg_set_order_override(fw_cfg, FW_CFG_ORDER_OVERRIDE_USER);
2093 fw_cfg_add_file(fw_cfg, name, buf, size);
2094 fw_cfg_reset_order_override(fw_cfg);
2095 return 0;
2098 static int device_help_func(void *opaque, QemuOpts *opts, Error **errp)
2100 return qdev_device_help(opts);
2103 static int device_init_func(void *opaque, QemuOpts *opts, Error **errp)
2105 DeviceState *dev;
2107 dev = qdev_device_add(opts, errp);
2108 if (!dev && *errp) {
2109 error_report_err(*errp);
2110 return -1;
2111 } else if (dev) {
2112 object_unref(OBJECT(dev));
2114 return 0;
2117 static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2119 Error *local_err = NULL;
2121 if (!qemu_chr_new_from_opts(opts, NULL, &local_err)) {
2122 if (local_err) {
2123 error_propagate(errp, local_err);
2124 return -1;
2126 exit(0);
2128 return 0;
2131 #ifdef CONFIG_VIRTFS
2132 static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2134 return qemu_fsdev_add(opts, errp);
2136 #endif
2138 static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp)
2140 return monitor_init_opts(opts, errp);
2143 static void monitor_parse(const char *optarg, const char *mode, bool pretty)
2145 static int monitor_device_index = 0;
2146 QemuOpts *opts;
2147 const char *p;
2148 char label[32];
2150 if (strstart(optarg, "chardev:", &p)) {
2151 snprintf(label, sizeof(label), "%s", p);
2152 } else {
2153 snprintf(label, sizeof(label), "compat_monitor%d",
2154 monitor_device_index);
2155 opts = qemu_chr_parse_compat(label, optarg, true);
2156 if (!opts) {
2157 error_report("parse error: %s", optarg);
2158 exit(1);
2162 opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &error_fatal);
2163 qemu_opt_set(opts, "mode", mode, &error_abort);
2164 qemu_opt_set(opts, "chardev", label, &error_abort);
2165 if (!strcmp(mode, "control")) {
2166 qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);
2167 } else {
2168 assert(pretty == false);
2170 monitor_device_index++;
2173 struct device_config {
2174 enum {
2175 DEV_USB, /* -usbdevice */
2176 DEV_SERIAL, /* -serial */
2177 DEV_PARALLEL, /* -parallel */
2178 DEV_DEBUGCON, /* -debugcon */
2179 DEV_GDB, /* -gdb, -s */
2180 DEV_SCLP, /* s390 sclp */
2181 } type;
2182 const char *cmdline;
2183 Location loc;
2184 QTAILQ_ENTRY(device_config) next;
2187 static QTAILQ_HEAD(, device_config) device_configs =
2188 QTAILQ_HEAD_INITIALIZER(device_configs);
2190 static void add_device_config(int type, const char *cmdline)
2192 struct device_config *conf;
2194 conf = g_malloc0(sizeof(*conf));
2195 conf->type = type;
2196 conf->cmdline = cmdline;
2197 loc_save(&conf->loc);
2198 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2201 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2203 struct device_config *conf;
2204 int rc;
2206 QTAILQ_FOREACH(conf, &device_configs, next) {
2207 if (conf->type != type)
2208 continue;
2209 loc_push_restore(&conf->loc);
2210 rc = func(conf->cmdline);
2211 loc_pop(&conf->loc);
2212 if (rc) {
2213 return rc;
2216 return 0;
2219 static int serial_parse(const char *devname)
2221 int index = num_serial_hds;
2222 char label[32];
2224 if (strcmp(devname, "none") == 0)
2225 return 0;
2226 snprintf(label, sizeof(label), "serial%d", index);
2227 serial_hds = g_renew(Chardev *, serial_hds, index + 1);
2229 serial_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2230 if (!serial_hds[index]) {
2231 error_report("could not connect serial device"
2232 " to character backend '%s'", devname);
2233 return -1;
2235 num_serial_hds++;
2236 return 0;
2239 Chardev *serial_hd(int i)
2241 assert(i >= 0);
2242 if (i < num_serial_hds) {
2243 return serial_hds[i];
2245 return NULL;
2248 int serial_max_hds(void)
2250 return num_serial_hds;
2253 static int parallel_parse(const char *devname)
2255 static int index = 0;
2256 char label[32];
2258 if (strcmp(devname, "none") == 0)
2259 return 0;
2260 if (index == MAX_PARALLEL_PORTS) {
2261 error_report("too many parallel ports");
2262 exit(1);
2264 snprintf(label, sizeof(label), "parallel%d", index);
2265 parallel_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2266 if (!parallel_hds[index]) {
2267 error_report("could not connect parallel device"
2268 " to character backend '%s'", devname);
2269 return -1;
2271 index++;
2272 return 0;
2275 static int debugcon_parse(const char *devname)
2277 QemuOpts *opts;
2279 if (!qemu_chr_new_mux_mon("debugcon", devname, NULL)) {
2280 error_report("invalid character backend '%s'", devname);
2281 exit(1);
2283 opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2284 if (!opts) {
2285 error_report("already have a debugcon device");
2286 exit(1);
2288 qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);
2289 qemu_opt_set(opts, "chardev", "debugcon", &error_abort);
2290 return 0;
2293 static gint machine_class_cmp(gconstpointer a, gconstpointer b)
2295 const MachineClass *mc1 = a, *mc2 = b;
2296 int res;
2298 if (mc1->family == NULL) {
2299 if (mc2->family == NULL) {
2300 /* Compare standalone machine types against each other; they sort
2301 * in increasing order.
2303 return strcmp(object_class_get_name(OBJECT_CLASS(mc1)),
2304 object_class_get_name(OBJECT_CLASS(mc2)));
2307 /* Standalone machine types sort after families. */
2308 return 1;
2311 if (mc2->family == NULL) {
2312 /* Families sort before standalone machine types. */
2313 return -1;
2316 /* Families sort between each other alphabetically increasingly. */
2317 res = strcmp(mc1->family, mc2->family);
2318 if (res != 0) {
2319 return res;
2322 /* Within the same family, machine types sort in decreasing order. */
2323 return strcmp(object_class_get_name(OBJECT_CLASS(mc2)),
2324 object_class_get_name(OBJECT_CLASS(mc1)));
2327 static MachineClass *machine_parse(const char *name, GSList *machines)
2329 MachineClass *mc;
2330 GSList *el;
2332 if (is_help_option(name)) {
2333 printf("Supported machines are:\n");
2334 machines = g_slist_sort(machines, machine_class_cmp);
2335 for (el = machines; el; el = el->next) {
2336 MachineClass *mc = el->data;
2337 if (mc->alias) {
2338 printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
2340 printf("%-20s %s%s%s\n", mc->name, mc->desc,
2341 mc->is_default ? " (default)" : "",
2342 mc->deprecation_reason ? " (deprecated)" : "");
2344 exit(0);
2347 mc = find_machine(name, machines);
2348 if (!mc) {
2349 error_report("unsupported machine type");
2350 error_printf("Use -machine help to list supported machines\n");
2351 exit(1);
2353 return mc;
2356 void qemu_add_exit_notifier(Notifier *notify)
2358 notifier_list_add(&exit_notifiers, notify);
2361 void qemu_remove_exit_notifier(Notifier *notify)
2363 notifier_remove(notify);
2366 static void qemu_run_exit_notifiers(void)
2368 notifier_list_notify(&exit_notifiers, NULL);
2371 static const char *pid_file;
2372 static Notifier qemu_unlink_pidfile_notifier;
2374 static void qemu_unlink_pidfile(Notifier *n, void *data)
2376 if (pid_file) {
2377 unlink(pid_file);
2381 bool machine_init_done;
2383 void qemu_add_machine_init_done_notifier(Notifier *notify)
2385 notifier_list_add(&machine_init_done_notifiers, notify);
2386 if (machine_init_done) {
2387 notify->notify(notify, NULL);
2391 void qemu_remove_machine_init_done_notifier(Notifier *notify)
2393 notifier_remove(notify);
2396 static void qemu_run_machine_init_done_notifiers(void)
2398 machine_init_done = true;
2399 notifier_list_notify(&machine_init_done_notifiers, NULL);
2402 static const QEMUOption *lookup_opt(int argc, char **argv,
2403 const char **poptarg, int *poptind)
2405 const QEMUOption *popt;
2406 int optind = *poptind;
2407 char *r = argv[optind];
2408 const char *optarg;
2410 loc_set_cmdline(argv, optind, 1);
2411 optind++;
2412 /* Treat --foo the same as -foo. */
2413 if (r[1] == '-')
2414 r++;
2415 popt = qemu_options;
2416 for(;;) {
2417 if (!popt->name) {
2418 error_report("invalid option");
2419 exit(1);
2421 if (!strcmp(popt->name, r + 1))
2422 break;
2423 popt++;
2425 if (popt->flags & HAS_ARG) {
2426 if (optind >= argc) {
2427 error_report("requires an argument");
2428 exit(1);
2430 optarg = argv[optind++];
2431 loc_set_cmdline(argv, optind - 2, 2);
2432 } else {
2433 optarg = NULL;
2436 *poptarg = optarg;
2437 *poptind = optind;
2439 return popt;
2442 static MachineClass *select_machine(void)
2444 GSList *machines = object_class_get_list(TYPE_MACHINE, false);
2445 MachineClass *machine_class = find_default_machine(machines);
2446 const char *optarg;
2447 QemuOpts *opts;
2448 Location loc;
2450 loc_push_none(&loc);
2452 opts = qemu_get_machine_opts();
2453 qemu_opts_loc_restore(opts);
2455 optarg = qemu_opt_get(opts, "type");
2456 if (optarg) {
2457 machine_class = machine_parse(optarg, machines);
2460 if (!machine_class) {
2461 error_report("No machine specified, and there is no default");
2462 error_printf("Use -machine help to list supported machines\n");
2463 exit(1);
2466 loc_pop(&loc);
2467 g_slist_free(machines);
2468 return machine_class;
2471 static int object_parse_property_opt(Object *obj,
2472 const char *name, const char *value,
2473 const char *skip, Error **errp)
2475 if (g_str_equal(name, skip)) {
2476 return 0;
2479 if (!object_property_parse(obj, name, value, errp)) {
2480 return -1;
2483 return 0;
2486 static int machine_set_property(void *opaque,
2487 const char *name, const char *value,
2488 Error **errp)
2490 g_autofree char *qom_name = g_strdup(name);
2491 char *p;
2493 for (p = qom_name; *p; p++) {
2494 if (*p == '_') {
2495 *p = '-';
2499 /* Legacy options do not correspond to MachineState properties. */
2500 if (g_str_equal(qom_name, "accel")) {
2501 return 0;
2503 if (g_str_equal(qom_name, "igd-passthru")) {
2504 object_register_sugar_prop(ACCEL_CLASS_NAME("xen"), qom_name, value);
2505 return 0;
2507 if (g_str_equal(qom_name, "kvm-shadow-mem")) {
2508 object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), qom_name, value);
2509 return 0;
2511 if (g_str_equal(qom_name, "kernel-irqchip")) {
2512 object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), qom_name, value);
2513 object_register_sugar_prop(ACCEL_CLASS_NAME("whpx"), qom_name, value);
2514 return 0;
2517 return object_parse_property_opt(opaque, name, value, "type", errp);
2521 * Initial object creation happens before all other
2522 * QEMU data types are created. The majority of objects
2523 * can be created at this point. The rng-egd object
2524 * cannot be created here, as it depends on the chardev
2525 * already existing.
2527 static bool object_create_initial(const char *type, QemuOpts *opts)
2529 if (user_creatable_print_help(type, opts)) {
2530 exit(0);
2534 * Objects should not be made "delayed" without a reason. If you
2535 * add one, state the reason in a comment!
2538 /* Reason: rng-egd property "chardev" */
2539 if (g_str_equal(type, "rng-egd")) {
2540 return false;
2543 #if defined(CONFIG_VHOST_USER) && defined(CONFIG_LINUX)
2544 /* Reason: cryptodev-vhost-user property "chardev" */
2545 if (g_str_equal(type, "cryptodev-vhost-user")) {
2546 return false;
2548 #endif
2550 /* Reason: vhost-user-blk-server property "node-name" */
2551 if (g_str_equal(type, "vhost-user-blk-server")) {
2552 return false;
2555 * Reason: filter-* property "netdev" etc.
2557 if (g_str_equal(type, "filter-buffer") ||
2558 g_str_equal(type, "filter-dump") ||
2559 g_str_equal(type, "filter-mirror") ||
2560 g_str_equal(type, "filter-redirector") ||
2561 g_str_equal(type, "colo-compare") ||
2562 g_str_equal(type, "filter-rewriter") ||
2563 g_str_equal(type, "filter-replay")) {
2564 return false;
2567 /* Memory allocation by backends needs to be done
2568 * after configure_accelerator() (due to the tcg_enabled()
2569 * checks at memory_region_init_*()).
2571 * Also, allocation of large amounts of memory may delay
2572 * chardev initialization for too long, and trigger timeouts
2573 * on software that waits for a monitor socket to be created
2574 * (e.g. libvirt).
2576 if (g_str_has_prefix(type, "memory-backend-")) {
2577 return false;
2580 return true;
2585 * The remainder of object creation happens after the
2586 * creation of chardev, fsdev, net clients and device data types.
2588 static bool object_create_delayed(const char *type, QemuOpts *opts)
2590 return !object_create_initial(type, opts);
2594 static bool set_memory_options(uint64_t *ram_slots, ram_addr_t *maxram_size,
2595 MachineClass *mc)
2597 uint64_t sz;
2598 const char *mem_str;
2599 const ram_addr_t default_ram_size = mc->default_ram_size;
2600 QemuOpts *opts = qemu_find_opts_singleton("memory");
2601 Location loc;
2603 loc_push_none(&loc);
2604 qemu_opts_loc_restore(opts);
2606 sz = 0;
2607 mem_str = qemu_opt_get(opts, "size");
2608 if (mem_str) {
2609 if (!*mem_str) {
2610 error_report("missing 'size' option value");
2611 exit(EXIT_FAILURE);
2614 sz = qemu_opt_get_size(opts, "size", ram_size);
2616 /* Fix up legacy suffix-less format */
2617 if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
2618 uint64_t overflow_check = sz;
2620 sz *= MiB;
2621 if (sz / MiB != overflow_check) {
2622 error_report("too large 'size' option value");
2623 exit(EXIT_FAILURE);
2628 /* backward compatibility behaviour for case "-m 0" */
2629 if (sz == 0) {
2630 sz = default_ram_size;
2633 sz = QEMU_ALIGN_UP(sz, 8192);
2634 if (mc->fixup_ram_size) {
2635 sz = mc->fixup_ram_size(sz);
2637 ram_size = sz;
2638 if (ram_size != sz) {
2639 error_report("ram size too large");
2640 exit(EXIT_FAILURE);
2643 /* store value for the future use */
2644 qemu_opt_set_number(opts, "size", ram_size, &error_abort);
2645 *maxram_size = ram_size;
2647 if (qemu_opt_get(opts, "maxmem")) {
2648 uint64_t slots;
2650 sz = qemu_opt_get_size(opts, "maxmem", 0);
2651 slots = qemu_opt_get_number(opts, "slots", 0);
2652 if (sz < ram_size) {
2653 error_report("invalid value of -m option maxmem: "
2654 "maximum memory size (0x%" PRIx64 ") must be at least "
2655 "the initial memory size (0x" RAM_ADDR_FMT ")",
2656 sz, ram_size);
2657 exit(EXIT_FAILURE);
2658 } else if (slots && sz == ram_size) {
2659 error_report("invalid value of -m option maxmem: "
2660 "memory slots were specified but maximum memory size "
2661 "(0x%" PRIx64 ") is equal to the initial memory size "
2662 "(0x" RAM_ADDR_FMT ")", sz, ram_size);
2663 exit(EXIT_FAILURE);
2666 *maxram_size = sz;
2667 *ram_slots = slots;
2668 } else if (qemu_opt_get(opts, "slots")) {
2669 error_report("invalid -m option value: missing 'maxmem' option");
2670 exit(EXIT_FAILURE);
2673 loc_pop(&loc);
2674 return !!mem_str;
2677 static int global_init_func(void *opaque, QemuOpts *opts, Error **errp)
2679 GlobalProperty *g;
2681 g = g_malloc0(sizeof(*g));
2682 g->driver = qemu_opt_get(opts, "driver");
2683 g->property = qemu_opt_get(opts, "property");
2684 g->value = qemu_opt_get(opts, "value");
2685 qdev_prop_register_global(g);
2686 return 0;
2689 static int qemu_read_default_config_file(void)
2691 int ret;
2692 g_autofree char *file = get_relocated_path(CONFIG_QEMU_CONFDIR "/qemu.conf");
2694 ret = qemu_read_config_file(file);
2695 if (ret < 0 && ret != -ENOENT) {
2696 return ret;
2699 return 0;
2702 static void user_register_global_props(void)
2704 qemu_opts_foreach(qemu_find_opts("global"),
2705 global_init_func, NULL, NULL);
2708 static int do_configure_icount(void *opaque, QemuOpts *opts, Error **errp)
2710 icount_configure(opts, errp);
2711 return 0;
2714 static int accelerator_set_property(void *opaque,
2715 const char *name, const char *value,
2716 Error **errp)
2718 return object_parse_property_opt(opaque, name, value, "accel", errp);
2721 static int do_configure_accelerator(void *opaque, QemuOpts *opts, Error **errp)
2723 bool *p_init_failed = opaque;
2724 const char *acc = qemu_opt_get(opts, "accel");
2725 AccelClass *ac = accel_find(acc);
2726 AccelState *accel;
2727 int ret;
2728 bool qtest_with_kvm;
2730 qtest_with_kvm = g_str_equal(acc, "kvm") && qtest_chrdev != NULL;
2732 if (!ac) {
2733 *p_init_failed = true;
2734 if (!qtest_with_kvm) {
2735 error_report("invalid accelerator %s", acc);
2737 return 0;
2739 accel = ACCEL(object_new_with_class(OBJECT_CLASS(ac)));
2740 object_apply_compat_props(OBJECT(accel));
2741 qemu_opt_foreach(opts, accelerator_set_property,
2742 accel,
2743 &error_fatal);
2745 ret = accel_init_machine(accel, current_machine);
2746 if (ret < 0) {
2747 *p_init_failed = true;
2748 if (!qtest_with_kvm || ret != -ENOENT) {
2749 error_report("failed to initialize %s: %s", acc, strerror(-ret));
2751 return 0;
2754 return 1;
2757 static void configure_accelerators(const char *progname)
2759 const char *accel;
2760 bool init_failed = false;
2762 qemu_opts_foreach(qemu_find_opts("icount"),
2763 do_configure_icount, NULL, &error_fatal);
2765 accel = qemu_opt_get(qemu_get_machine_opts(), "accel");
2766 if (QTAILQ_EMPTY(&qemu_accel_opts.head)) {
2767 char **accel_list, **tmp;
2769 if (accel == NULL) {
2770 /* Select the default accelerator */
2771 bool have_tcg = accel_find("tcg");
2772 bool have_kvm = accel_find("kvm");
2774 if (have_tcg && have_kvm) {
2775 if (g_str_has_suffix(progname, "kvm")) {
2776 /* If the program name ends with "kvm", we prefer KVM */
2777 accel = "kvm:tcg";
2778 } else {
2779 accel = "tcg:kvm";
2781 } else if (have_kvm) {
2782 accel = "kvm";
2783 } else if (have_tcg) {
2784 accel = "tcg";
2785 } else {
2786 error_report("No accelerator selected and"
2787 " no default accelerator available");
2788 exit(1);
2791 accel_list = g_strsplit(accel, ":", 0);
2793 for (tmp = accel_list; *tmp; tmp++) {
2795 * Filter invalid accelerators here, to prevent obscenities
2796 * such as "-machine accel=tcg,,thread=single".
2798 if (accel_find(*tmp)) {
2799 qemu_opts_parse_noisily(qemu_find_opts("accel"), *tmp, true);
2800 } else {
2801 init_failed = true;
2802 error_report("invalid accelerator %s", *tmp);
2805 g_strfreev(accel_list);
2806 } else {
2807 if (accel != NULL) {
2808 error_report("The -accel and \"-machine accel=\" options are incompatible");
2809 exit(1);
2813 if (!qemu_opts_foreach(qemu_find_opts("accel"),
2814 do_configure_accelerator, &init_failed, &error_fatal)) {
2815 if (!init_failed) {
2816 error_report("no accelerator found");
2818 exit(1);
2821 if (init_failed && !qtest_chrdev) {
2822 AccelClass *ac = ACCEL_GET_CLASS(current_accel());
2823 error_report("falling back to %s", ac->name);
2826 if (icount_enabled() && !tcg_enabled()) {
2827 error_report("-icount is not allowed with hardware virtualization");
2828 exit(1);
2832 static void create_default_memdev(MachineState *ms, const char *path)
2834 Object *obj;
2835 MachineClass *mc = MACHINE_GET_CLASS(ms);
2837 obj = object_new(path ? TYPE_MEMORY_BACKEND_FILE : TYPE_MEMORY_BACKEND_RAM);
2838 if (path) {
2839 object_property_set_str(obj, "mem-path", path, &error_fatal);
2841 object_property_set_int(obj, "size", ms->ram_size, &error_fatal);
2842 object_property_add_child(object_get_objects_root(), mc->default_ram_id,
2843 obj);
2844 /* Ensure backend's memory region name is equal to mc->default_ram_id */
2845 object_property_set_bool(obj, "x-use-canonical-path-for-ramblock-id",
2846 false, &error_fatal);
2847 user_creatable_complete(USER_CREATABLE(obj), &error_fatal);
2848 object_unref(obj);
2849 object_property_set_str(OBJECT(ms), "memory-backend", mc->default_ram_id,
2850 &error_fatal);
2854 * Find a likely location for support files using the location of the binary.
2855 * When running from the build tree this will be "$bindir/pc-bios".
2856 * Otherwise, this is CONFIG_QEMU_DATADIR (possibly relocated).
2858 * The caller must use g_free() to free the returned data when it is
2859 * no longer required.
2861 static char *find_datadir(void)
2863 g_autofree char *dir = NULL;
2865 dir = g_build_filename(qemu_get_exec_dir(), "pc-bios", NULL);
2866 if (g_file_test(dir, G_FILE_TEST_IS_DIR)) {
2867 return g_steal_pointer(&dir);
2870 return get_relocated_path(CONFIG_QEMU_DATADIR);
2873 static void qemu_process_early_options(void)
2875 char **dirs;
2876 int i;
2878 #ifdef CONFIG_SECCOMP
2879 QemuOptsList *olist = qemu_find_opts_err("sandbox", NULL);
2880 if (olist) {
2881 qemu_opts_foreach(olist, parse_sandbox, NULL, &error_fatal);
2883 #endif
2885 qemu_opts_foreach(qemu_find_opts("name"),
2886 parse_name, NULL, &error_fatal);
2888 #ifndef _WIN32
2889 qemu_opts_foreach(qemu_find_opts("add-fd"),
2890 parse_add_fd, NULL, &error_fatal);
2892 qemu_opts_foreach(qemu_find_opts("add-fd"),
2893 cleanup_add_fd, NULL, &error_fatal);
2894 #endif
2896 if (!trace_init_backends()) {
2897 exit(1);
2899 trace_init_file();
2901 /* Open the logfile at this point and set the log mask if necessary. */
2902 qemu_set_log_filename(log_file, &error_fatal);
2903 if (log_mask) {
2904 int mask;
2905 mask = qemu_str_to_log_mask(log_mask);
2906 if (!mask) {
2907 qemu_print_log_usage(stdout);
2908 exit(1);
2910 qemu_set_log(mask);
2911 } else {
2912 qemu_set_log(0);
2915 /* add configured firmware directories */
2916 dirs = g_strsplit(CONFIG_QEMU_FIRMWAREPATH, G_SEARCHPATH_SEPARATOR_S, 0);
2917 for (i = 0; dirs[i] != NULL; i++) {
2918 qemu_add_data_dir(get_relocated_path(dirs[i]));
2920 g_strfreev(dirs);
2922 /* try to find datadir relative to the executable path */
2923 qemu_add_data_dir(find_datadir());
2926 static void qemu_process_help_options(void)
2928 int i;
2931 * Check for -cpu help and -device help before we call select_machine(),
2932 * which will return an error if the architecture has no default machine
2933 * type and the user did not specify one, so that the user doesn't need
2934 * to say '-cpu help -machine something'.
2936 if (cpu_option && is_help_option(cpu_option)) {
2937 list_cpus(cpu_option);
2938 exit(0);
2941 if (qemu_opts_foreach(qemu_find_opts("device"),
2942 device_help_func, NULL, NULL)) {
2943 exit(0);
2946 /* -L help lists the data directories and exits. */
2947 if (list_data_dirs) {
2948 for (i = 0; i < data_dir_idx; i++) {
2949 printf("%s\n", data_dir[i]);
2951 exit(0);
2955 static void qemu_maybe_daemonize(const char *pid_file)
2957 Error *err;
2959 os_daemonize();
2960 rcu_disable_atfork();
2962 if (pid_file && !qemu_write_pidfile(pid_file, &err)) {
2963 error_reportf_err(err, "cannot create PID file: ");
2964 exit(1);
2967 qemu_unlink_pidfile_notifier.notify = qemu_unlink_pidfile;
2968 qemu_add_exit_notifier(&qemu_unlink_pidfile_notifier);
2972 void qemu_init(int argc, char **argv, char **envp)
2974 int i;
2975 int snapshot, linux_boot;
2976 const char *initrd_filename;
2977 const char *kernel_filename, *kernel_cmdline;
2978 const char *boot_order = NULL;
2979 const char *boot_once = NULL;
2980 DisplayState *ds;
2981 QemuOpts *opts, *machine_opts;
2982 QemuOpts *icount_opts = NULL, *accel_opts = NULL;
2983 QemuOptsList *olist;
2984 int optind;
2985 const char *optarg;
2986 const char *loadvm = NULL;
2987 MachineClass *machine_class;
2988 const char *vga_model = NULL;
2989 const char *incoming = NULL;
2990 bool userconfig = true;
2991 bool nographic = false;
2992 int display_remote = 0;
2993 ram_addr_t maxram_size;
2994 uint64_t ram_slots = 0;
2995 FILE *vmstate_dump_file = NULL;
2996 Error *main_loop_err = NULL;
2997 Error *err = NULL;
2998 const char *mem_path = NULL;
2999 bool have_custom_ram_size;
3000 BlockdevOptionsQueue bdo_queue = QSIMPLEQ_HEAD_INITIALIZER(bdo_queue);
3001 QemuPluginList plugin_list = QTAILQ_HEAD_INITIALIZER(plugin_list);
3002 int mem_prealloc = 0; /* force preallocation of physical target memory */
3004 os_set_line_buffering();
3006 error_init(argv[0]);
3007 module_call_init(MODULE_INIT_TRACE);
3009 qemu_init_cpu_list();
3010 qemu_init_cpu_loop();
3012 qemu_mutex_lock_iothread();
3014 atexit(qemu_run_exit_notifiers);
3015 qemu_init_exec_dir(argv[0]);
3017 module_call_init(MODULE_INIT_QOM);
3018 module_call_init(MODULE_INIT_MIGRATION);
3020 qemu_add_opts(&qemu_drive_opts);
3021 qemu_add_drive_opts(&qemu_legacy_drive_opts);
3022 qemu_add_drive_opts(&qemu_common_drive_opts);
3023 qemu_add_drive_opts(&qemu_drive_opts);
3024 qemu_add_drive_opts(&bdrv_runtime_opts);
3025 qemu_add_opts(&qemu_chardev_opts);
3026 qemu_add_opts(&qemu_device_opts);
3027 qemu_add_opts(&qemu_netdev_opts);
3028 qemu_add_opts(&qemu_nic_opts);
3029 qemu_add_opts(&qemu_net_opts);
3030 qemu_add_opts(&qemu_rtc_opts);
3031 qemu_add_opts(&qemu_global_opts);
3032 qemu_add_opts(&qemu_mon_opts);
3033 qemu_add_opts(&qemu_trace_opts);
3034 qemu_plugin_add_opts();
3035 qemu_add_opts(&qemu_option_rom_opts);
3036 qemu_add_opts(&qemu_machine_opts);
3037 qemu_add_opts(&qemu_accel_opts);
3038 qemu_add_opts(&qemu_mem_opts);
3039 qemu_add_opts(&qemu_smp_opts);
3040 qemu_add_opts(&qemu_boot_opts);
3041 qemu_add_opts(&qemu_add_fd_opts);
3042 qemu_add_opts(&qemu_object_opts);
3043 qemu_add_opts(&qemu_tpmdev_opts);
3044 qemu_add_opts(&qemu_realtime_opts);
3045 qemu_add_opts(&qemu_overcommit_opts);
3046 qemu_add_opts(&qemu_msg_opts);
3047 qemu_add_opts(&qemu_name_opts);
3048 qemu_add_opts(&qemu_numa_opts);
3049 qemu_add_opts(&qemu_icount_opts);
3050 qemu_add_opts(&qemu_semihosting_config_opts);
3051 qemu_add_opts(&qemu_fw_cfg_opts);
3052 module_call_init(MODULE_INIT_OPTS);
3054 runstate_init();
3055 precopy_infrastructure_init();
3056 postcopy_infrastructure_init();
3057 monitor_init_globals();
3059 if (qcrypto_init(&err) < 0) {
3060 error_reportf_err(err, "cannot initialize crypto: ");
3061 exit(1);
3064 QTAILQ_INIT(&vm_change_state_head);
3065 os_setup_early_signal_handling();
3067 cpu_option = NULL;
3068 snapshot = 0;
3070 nb_nics = 0;
3072 bdrv_init_with_whitelist();
3074 autostart = 1;
3076 /* first pass of option parsing */
3077 optind = 1;
3078 while (optind < argc) {
3079 if (argv[optind][0] != '-') {
3080 /* disk image */
3081 optind++;
3082 } else {
3083 const QEMUOption *popt;
3085 popt = lookup_opt(argc, argv, &optarg, &optind);
3086 switch (popt->index) {
3087 case QEMU_OPTION_nouserconfig:
3088 userconfig = false;
3089 break;
3094 if (userconfig) {
3095 if (qemu_read_default_config_file() < 0) {
3096 exit(1);
3100 /* second pass of option parsing */
3101 optind = 1;
3102 for(;;) {
3103 if (optind >= argc)
3104 break;
3105 if (argv[optind][0] != '-') {
3106 loc_set_cmdline(argv, optind, 1);
3107 drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
3108 } else {
3109 const QEMUOption *popt;
3111 popt = lookup_opt(argc, argv, &optarg, &optind);
3112 if (!(popt->arch_mask & arch_type)) {
3113 error_report("Option not supported for this target");
3114 exit(1);
3116 switch(popt->index) {
3117 case QEMU_OPTION_cpu:
3118 /* hw initialization will check this */
3119 cpu_option = optarg;
3120 break;
3121 case QEMU_OPTION_hda:
3122 case QEMU_OPTION_hdb:
3123 case QEMU_OPTION_hdc:
3124 case QEMU_OPTION_hdd:
3125 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
3126 HD_OPTS);
3127 break;
3128 case QEMU_OPTION_blockdev:
3130 Visitor *v;
3131 BlockdevOptionsQueueEntry *bdo;
3133 v = qobject_input_visitor_new_str(optarg, "driver",
3134 &error_fatal);
3136 bdo = g_new(BlockdevOptionsQueueEntry, 1);
3137 visit_type_BlockdevOptions(v, NULL, &bdo->bdo,
3138 &error_fatal);
3139 visit_free(v);
3140 loc_save(&bdo->loc);
3141 QSIMPLEQ_INSERT_TAIL(&bdo_queue, bdo, entry);
3142 break;
3144 case QEMU_OPTION_drive:
3145 if (drive_def(optarg) == NULL) {
3146 exit(1);
3148 break;
3149 case QEMU_OPTION_set:
3150 if (qemu_set_option(optarg) != 0)
3151 exit(1);
3152 break;
3153 case QEMU_OPTION_global:
3154 if (qemu_global_option(optarg) != 0)
3155 exit(1);
3156 break;
3157 case QEMU_OPTION_mtdblock:
3158 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
3159 break;
3160 case QEMU_OPTION_sd:
3161 drive_add(IF_SD, -1, optarg, SD_OPTS);
3162 break;
3163 case QEMU_OPTION_pflash:
3164 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
3165 break;
3166 case QEMU_OPTION_snapshot:
3168 Error *blocker = NULL;
3169 snapshot = 1;
3170 error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
3171 "-snapshot");
3172 replay_add_blocker(blocker);
3174 break;
3175 case QEMU_OPTION_numa:
3176 opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
3177 optarg, true);
3178 if (!opts) {
3179 exit(1);
3181 break;
3182 case QEMU_OPTION_display:
3183 parse_display(optarg);
3184 break;
3185 case QEMU_OPTION_nographic:
3186 olist = qemu_find_opts("machine");
3187 qemu_opts_parse_noisily(olist, "graphics=off", false);
3188 nographic = true;
3189 dpy.type = DISPLAY_TYPE_NONE;
3190 break;
3191 case QEMU_OPTION_curses:
3192 #ifdef CONFIG_CURSES
3193 dpy.type = DISPLAY_TYPE_CURSES;
3194 #else
3195 error_report("curses or iconv support is disabled");
3196 exit(1);
3197 #endif
3198 break;
3199 case QEMU_OPTION_portrait:
3200 graphic_rotate = 90;
3201 break;
3202 case QEMU_OPTION_rotate:
3203 graphic_rotate = strtol(optarg, (char **) &optarg, 10);
3204 if (graphic_rotate != 0 && graphic_rotate != 90 &&
3205 graphic_rotate != 180 && graphic_rotate != 270) {
3206 error_report("only 90, 180, 270 deg rotation is available");
3207 exit(1);
3209 break;
3210 case QEMU_OPTION_kernel:
3211 qemu_opts_set(qemu_find_opts("machine"), NULL, "kernel", optarg,
3212 &error_abort);
3213 break;
3214 case QEMU_OPTION_initrd:
3215 qemu_opts_set(qemu_find_opts("machine"), NULL, "initrd", optarg,
3216 &error_abort);
3217 break;
3218 case QEMU_OPTION_append:
3219 qemu_opts_set(qemu_find_opts("machine"), NULL, "append", optarg,
3220 &error_abort);
3221 break;
3222 case QEMU_OPTION_dtb:
3223 qemu_opts_set(qemu_find_opts("machine"), NULL, "dtb", optarg,
3224 &error_abort);
3225 break;
3226 case QEMU_OPTION_cdrom:
3227 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
3228 break;
3229 case QEMU_OPTION_boot:
3230 opts = qemu_opts_parse_noisily(qemu_find_opts("boot-opts"),
3231 optarg, true);
3232 if (!opts) {
3233 exit(1);
3235 break;
3236 case QEMU_OPTION_fda:
3237 case QEMU_OPTION_fdb:
3238 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
3239 optarg, FD_OPTS);
3240 break;
3241 case QEMU_OPTION_no_fd_bootchk:
3242 fd_bootchk = 0;
3243 break;
3244 case QEMU_OPTION_netdev:
3245 default_net = 0;
3246 if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
3247 exit(1);
3249 break;
3250 case QEMU_OPTION_nic:
3251 default_net = 0;
3252 if (net_client_parse(qemu_find_opts("nic"), optarg) == -1) {
3253 exit(1);
3255 break;
3256 case QEMU_OPTION_net:
3257 default_net = 0;
3258 if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
3259 exit(1);
3261 break;
3262 #ifdef CONFIG_LIBISCSI
3263 case QEMU_OPTION_iscsi:
3264 opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
3265 optarg, false);
3266 if (!opts) {
3267 exit(1);
3269 break;
3270 #endif
3271 case QEMU_OPTION_audio_help:
3272 audio_legacy_help();
3273 exit (0);
3274 break;
3275 case QEMU_OPTION_audiodev:
3276 audio_parse_option(optarg);
3277 break;
3278 case QEMU_OPTION_soundhw:
3279 select_soundhw (optarg);
3280 break;
3281 case QEMU_OPTION_h:
3282 help(0);
3283 break;
3284 case QEMU_OPTION_version:
3285 version();
3286 exit(0);
3287 break;
3288 case QEMU_OPTION_m:
3289 opts = qemu_opts_parse_noisily(qemu_find_opts("memory"),
3290 optarg, true);
3291 if (!opts) {
3292 exit(EXIT_FAILURE);
3294 break;
3295 #ifdef CONFIG_TPM
3296 case QEMU_OPTION_tpmdev:
3297 if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3298 exit(1);
3300 break;
3301 #endif
3302 case QEMU_OPTION_mempath:
3303 mem_path = optarg;
3304 break;
3305 case QEMU_OPTION_mem_prealloc:
3306 mem_prealloc = 1;
3307 break;
3308 case QEMU_OPTION_d:
3309 log_mask = optarg;
3310 break;
3311 case QEMU_OPTION_D:
3312 log_file = optarg;
3313 break;
3314 case QEMU_OPTION_DFILTER:
3315 qemu_set_dfilter_ranges(optarg, &error_fatal);
3316 break;
3317 case QEMU_OPTION_seed:
3318 qemu_guest_random_seed_main(optarg, &error_fatal);
3319 break;
3320 case QEMU_OPTION_s:
3321 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3322 break;
3323 case QEMU_OPTION_gdb:
3324 add_device_config(DEV_GDB, optarg);
3325 break;
3326 case QEMU_OPTION_L:
3327 if (is_help_option(optarg)) {
3328 list_data_dirs = true;
3329 } else {
3330 qemu_add_data_dir(g_strdup(optarg));
3332 break;
3333 case QEMU_OPTION_bios:
3334 qemu_opts_set(qemu_find_opts("machine"), NULL, "firmware", optarg,
3335 &error_abort);
3336 break;
3337 case QEMU_OPTION_singlestep:
3338 singlestep = 1;
3339 break;
3340 case QEMU_OPTION_S:
3341 autostart = 0;
3342 break;
3343 case QEMU_OPTION_k:
3344 keyboard_layout = optarg;
3345 break;
3346 case QEMU_OPTION_vga:
3347 vga_model = optarg;
3348 default_vga = 0;
3349 break;
3350 case QEMU_OPTION_g:
3352 const char *p;
3353 int w, h, depth;
3354 p = optarg;
3355 w = strtol(p, (char **)&p, 10);
3356 if (w <= 0) {
3357 graphic_error:
3358 error_report("invalid resolution or depth");
3359 exit(1);
3361 if (*p != 'x')
3362 goto graphic_error;
3363 p++;
3364 h = strtol(p, (char **)&p, 10);
3365 if (h <= 0)
3366 goto graphic_error;
3367 if (*p == 'x') {
3368 p++;
3369 depth = strtol(p, (char **)&p, 10);
3370 if (depth != 1 && depth != 2 && depth != 4 &&
3371 depth != 8 && depth != 15 && depth != 16 &&
3372 depth != 24 && depth != 32)
3373 goto graphic_error;
3374 } else if (*p == '\0') {
3375 depth = graphic_depth;
3376 } else {
3377 goto graphic_error;
3380 graphic_width = w;
3381 graphic_height = h;
3382 graphic_depth = depth;
3384 break;
3385 case QEMU_OPTION_echr:
3387 char *r;
3388 term_escape_char = strtol(optarg, &r, 0);
3389 if (r == optarg)
3390 printf("Bad argument to echr\n");
3391 break;
3393 case QEMU_OPTION_monitor:
3394 default_monitor = 0;
3395 if (strncmp(optarg, "none", 4)) {
3396 monitor_parse(optarg, "readline", false);
3398 break;
3399 case QEMU_OPTION_qmp:
3400 monitor_parse(optarg, "control", false);
3401 default_monitor = 0;
3402 break;
3403 case QEMU_OPTION_qmp_pretty:
3404 monitor_parse(optarg, "control", true);
3405 default_monitor = 0;
3406 break;
3407 case QEMU_OPTION_mon:
3408 opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
3409 true);
3410 if (!opts) {
3411 exit(1);
3413 default_monitor = 0;
3414 break;
3415 case QEMU_OPTION_chardev:
3416 opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
3417 optarg, true);
3418 if (!opts) {
3419 exit(1);
3421 break;
3422 case QEMU_OPTION_fsdev:
3423 olist = qemu_find_opts("fsdev");
3424 if (!olist) {
3425 error_report("fsdev support is disabled");
3426 exit(1);
3428 opts = qemu_opts_parse_noisily(olist, optarg, true);
3429 if (!opts) {
3430 exit(1);
3432 break;
3433 case QEMU_OPTION_virtfs: {
3434 QemuOpts *fsdev;
3435 QemuOpts *device;
3436 const char *writeout, *sock_fd, *socket, *path, *security_model,
3437 *multidevs;
3439 olist = qemu_find_opts("virtfs");
3440 if (!olist) {
3441 error_report("virtfs support is disabled");
3442 exit(1);
3444 opts = qemu_opts_parse_noisily(olist, optarg, true);
3445 if (!opts) {
3446 exit(1);
3449 if (qemu_opt_get(opts, "fsdriver") == NULL ||
3450 qemu_opt_get(opts, "mount_tag") == NULL) {
3451 error_report("Usage: -virtfs fsdriver,mount_tag=tag");
3452 exit(1);
3454 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3455 qemu_opts_id(opts) ?:
3456 qemu_opt_get(opts, "mount_tag"),
3457 1, NULL);
3458 if (!fsdev) {
3459 error_report("duplicate or invalid fsdev id: %s",
3460 qemu_opt_get(opts, "mount_tag"));
3461 exit(1);
3464 writeout = qemu_opt_get(opts, "writeout");
3465 if (writeout) {
3466 #ifdef CONFIG_SYNC_FILE_RANGE
3467 qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
3468 #else
3469 error_report("writeout=immediate not supported "
3470 "on this platform");
3471 exit(1);
3472 #endif
3474 qemu_opt_set(fsdev, "fsdriver",
3475 qemu_opt_get(opts, "fsdriver"), &error_abort);
3476 path = qemu_opt_get(opts, "path");
3477 if (path) {
3478 qemu_opt_set(fsdev, "path", path, &error_abort);
3480 security_model = qemu_opt_get(opts, "security_model");
3481 if (security_model) {
3482 qemu_opt_set(fsdev, "security_model", security_model,
3483 &error_abort);
3485 socket = qemu_opt_get(opts, "socket");
3486 if (socket) {
3487 qemu_opt_set(fsdev, "socket", socket, &error_abort);
3489 sock_fd = qemu_opt_get(opts, "sock_fd");
3490 if (sock_fd) {
3491 qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
3494 qemu_opt_set_bool(fsdev, "readonly",
3495 qemu_opt_get_bool(opts, "readonly", 0),
3496 &error_abort);
3497 multidevs = qemu_opt_get(opts, "multidevs");
3498 if (multidevs) {
3499 qemu_opt_set(fsdev, "multidevs", multidevs, &error_abort);
3501 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3502 &error_abort);
3503 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3504 qemu_opt_set(device, "fsdev",
3505 qemu_opts_id(fsdev), &error_abort);
3506 qemu_opt_set(device, "mount_tag",
3507 qemu_opt_get(opts, "mount_tag"), &error_abort);
3508 break;
3510 case QEMU_OPTION_serial:
3511 add_device_config(DEV_SERIAL, optarg);
3512 default_serial = 0;
3513 if (strncmp(optarg, "mon:", 4) == 0) {
3514 default_monitor = 0;
3516 break;
3517 case QEMU_OPTION_watchdog:
3518 if (watchdog) {
3519 error_report("only one watchdog option may be given");
3520 exit(1);
3522 watchdog = optarg;
3523 break;
3524 case QEMU_OPTION_watchdog_action:
3525 if (select_watchdog_action(optarg) == -1) {
3526 error_report("unknown -watchdog-action parameter");
3527 exit(1);
3529 break;
3530 case QEMU_OPTION_parallel:
3531 add_device_config(DEV_PARALLEL, optarg);
3532 default_parallel = 0;
3533 if (strncmp(optarg, "mon:", 4) == 0) {
3534 default_monitor = 0;
3536 break;
3537 case QEMU_OPTION_debugcon:
3538 add_device_config(DEV_DEBUGCON, optarg);
3539 break;
3540 case QEMU_OPTION_loadvm:
3541 loadvm = optarg;
3542 break;
3543 case QEMU_OPTION_full_screen:
3544 dpy.has_full_screen = true;
3545 dpy.full_screen = true;
3546 break;
3547 case QEMU_OPTION_alt_grab:
3548 alt_grab = 1;
3549 break;
3550 case QEMU_OPTION_ctrl_grab:
3551 ctrl_grab = 1;
3552 break;
3553 case QEMU_OPTION_no_quit:
3554 dpy.has_window_close = true;
3555 dpy.window_close = false;
3556 break;
3557 case QEMU_OPTION_sdl:
3558 #ifdef CONFIG_SDL
3559 dpy.type = DISPLAY_TYPE_SDL;
3560 break;
3561 #else
3562 error_report("SDL support is disabled");
3563 exit(1);
3564 #endif
3565 case QEMU_OPTION_pidfile:
3566 pid_file = optarg;
3567 break;
3568 case QEMU_OPTION_win2k_hack:
3569 win2k_install_hack = 1;
3570 break;
3571 case QEMU_OPTION_acpitable:
3572 opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
3573 optarg, true);
3574 if (!opts) {
3575 exit(1);
3577 acpi_table_add(opts, &error_fatal);
3578 break;
3579 case QEMU_OPTION_smbios:
3580 opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
3581 optarg, false);
3582 if (!opts) {
3583 exit(1);
3585 smbios_entry_add(opts, &error_fatal);
3586 break;
3587 case QEMU_OPTION_fwcfg:
3588 opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
3589 optarg, true);
3590 if (opts == NULL) {
3591 exit(1);
3593 break;
3594 case QEMU_OPTION_preconfig:
3595 preconfig_exit_requested = false;
3596 break;
3597 case QEMU_OPTION_enable_kvm:
3598 olist = qemu_find_opts("machine");
3599 qemu_opts_parse_noisily(olist, "accel=kvm", false);
3600 break;
3601 case QEMU_OPTION_M:
3602 case QEMU_OPTION_machine:
3603 olist = qemu_find_opts("machine");
3604 opts = qemu_opts_parse_noisily(olist, optarg, true);
3605 if (!opts) {
3606 exit(1);
3608 break;
3609 case QEMU_OPTION_accel:
3610 accel_opts = qemu_opts_parse_noisily(qemu_find_opts("accel"),
3611 optarg, true);
3612 optarg = qemu_opt_get(accel_opts, "accel");
3613 if (!optarg || is_help_option(optarg)) {
3614 printf("Accelerators supported in QEMU binary:\n");
3615 GSList *el, *accel_list = object_class_get_list(TYPE_ACCEL,
3616 false);
3617 for (el = accel_list; el; el = el->next) {
3618 gchar *typename = g_strdup(object_class_get_name(
3619 OBJECT_CLASS(el->data)));
3620 /* omit qtest which is used for tests only */
3621 if (g_strcmp0(typename, ACCEL_CLASS_NAME("qtest")) &&
3622 g_str_has_suffix(typename, ACCEL_CLASS_SUFFIX)) {
3623 gchar **optname = g_strsplit(typename,
3624 ACCEL_CLASS_SUFFIX, 0);
3625 printf("%s\n", optname[0]);
3626 g_strfreev(optname);
3628 g_free(typename);
3630 g_slist_free(accel_list);
3631 exit(0);
3633 break;
3634 case QEMU_OPTION_usb:
3635 olist = qemu_find_opts("machine");
3636 qemu_opts_parse_noisily(olist, "usb=on", false);
3637 break;
3638 case QEMU_OPTION_usbdevice:
3639 error_report("'-usbdevice' is deprecated, please use "
3640 "'-device usb-...' instead");
3641 olist = qemu_find_opts("machine");
3642 qemu_opts_parse_noisily(olist, "usb=on", false);
3643 add_device_config(DEV_USB, optarg);
3644 break;
3645 case QEMU_OPTION_device:
3646 if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
3647 optarg, true)) {
3648 exit(1);
3650 break;
3651 case QEMU_OPTION_smp:
3652 if (!qemu_opts_parse_noisily(qemu_find_opts("smp-opts"),
3653 optarg, true)) {
3654 exit(1);
3656 break;
3657 case QEMU_OPTION_vnc:
3658 vnc_parse(optarg, &error_fatal);
3659 break;
3660 case QEMU_OPTION_no_acpi:
3661 olist = qemu_find_opts("machine");
3662 qemu_opts_parse_noisily(olist, "acpi=off", false);
3663 break;
3664 case QEMU_OPTION_no_hpet:
3665 olist = qemu_find_opts("machine");
3666 qemu_opts_parse_noisily(olist, "hpet=off", false);
3667 break;
3668 case QEMU_OPTION_no_reboot:
3669 no_reboot = 1;
3670 break;
3671 case QEMU_OPTION_no_shutdown:
3672 no_shutdown = 1;
3673 break;
3674 case QEMU_OPTION_show_cursor:
3675 warn_report("The -show-cursor option is deprecated. Please "
3676 "add show-cursor=on to your -display options.");
3677 warn_report("When using the default display you can use "
3678 "-display default,show-cursor=on");
3679 dpy.has_show_cursor = true;
3680 dpy.show_cursor = true;
3681 break;
3682 case QEMU_OPTION_uuid:
3683 if (qemu_uuid_parse(optarg, &qemu_uuid) < 0) {
3684 error_report("failed to parse UUID string: wrong format");
3685 exit(1);
3687 qemu_uuid_set = true;
3688 break;
3689 case QEMU_OPTION_option_rom:
3690 if (nb_option_roms >= MAX_OPTION_ROMS) {
3691 error_report("too many option ROMs");
3692 exit(1);
3694 opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
3695 optarg, true);
3696 if (!opts) {
3697 exit(1);
3699 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3700 option_rom[nb_option_roms].bootindex =
3701 qemu_opt_get_number(opts, "bootindex", -1);
3702 if (!option_rom[nb_option_roms].name) {
3703 error_report("Option ROM file is not specified");
3704 exit(1);
3706 nb_option_roms++;
3707 break;
3708 case QEMU_OPTION_semihosting:
3709 qemu_semihosting_enable();
3710 break;
3711 case QEMU_OPTION_semihosting_config:
3712 if (qemu_semihosting_config_options(optarg) != 0) {
3713 exit(1);
3715 break;
3716 case QEMU_OPTION_name:
3717 opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
3718 optarg, true);
3719 if (!opts) {
3720 exit(1);
3722 /* Capture guest name if -msg guest-name is used later */
3723 error_guest_name = qemu_opt_get(opts, "guest");
3724 break;
3725 case QEMU_OPTION_prom_env:
3726 if (nb_prom_envs >= MAX_PROM_ENVS) {
3727 error_report("too many prom variables");
3728 exit(1);
3730 prom_envs[nb_prom_envs] = optarg;
3731 nb_prom_envs++;
3732 break;
3733 case QEMU_OPTION_old_param:
3734 old_param = 1;
3735 break;
3736 case QEMU_OPTION_rtc:
3737 opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
3738 false);
3739 if (!opts) {
3740 exit(1);
3742 break;
3743 case QEMU_OPTION_tb_size:
3744 #ifndef CONFIG_TCG
3745 error_report("TCG is disabled");
3746 exit(1);
3747 #endif
3748 warn_report("The -tb-size option is deprecated, use -accel tcg,tb-size instead");
3749 object_register_sugar_prop(ACCEL_CLASS_NAME("tcg"), "tb-size", optarg);
3750 break;
3751 case QEMU_OPTION_icount:
3752 icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
3753 optarg, true);
3754 if (!icount_opts) {
3755 exit(1);
3757 break;
3758 case QEMU_OPTION_incoming:
3759 if (!incoming) {
3760 runstate_set(RUN_STATE_INMIGRATE);
3762 incoming = optarg;
3763 break;
3764 case QEMU_OPTION_only_migratable:
3765 only_migratable = 1;
3766 break;
3767 case QEMU_OPTION_nodefaults:
3768 has_defaults = 0;
3769 break;
3770 case QEMU_OPTION_xen_domid:
3771 if (!(xen_available())) {
3772 error_report("Option not supported for this target");
3773 exit(1);
3775 xen_domid = atoi(optarg);
3776 break;
3777 case QEMU_OPTION_xen_attach:
3778 if (!(xen_available())) {
3779 error_report("Option not supported for this target");
3780 exit(1);
3782 xen_mode = XEN_ATTACH;
3783 break;
3784 case QEMU_OPTION_xen_domid_restrict:
3785 if (!(xen_available())) {
3786 error_report("Option not supported for this target");
3787 exit(1);
3789 xen_domid_restrict = true;
3790 break;
3791 case QEMU_OPTION_trace:
3792 trace_opt_parse(optarg);
3793 break;
3794 case QEMU_OPTION_plugin:
3795 qemu_plugin_opt_parse(optarg, &plugin_list);
3796 break;
3797 case QEMU_OPTION_readconfig:
3799 int ret = qemu_read_config_file(optarg);
3800 if (ret < 0) {
3801 error_report("read config %s: %s", optarg,
3802 strerror(-ret));
3803 exit(1);
3805 break;
3807 case QEMU_OPTION_spice:
3808 olist = qemu_find_opts_err("spice", NULL);
3809 if (!olist) {
3810 ui_module_load_one("spice-core");
3811 olist = qemu_find_opts("spice");
3813 if (!olist) {
3814 error_report("spice support is disabled");
3815 exit(1);
3817 opts = qemu_opts_parse_noisily(olist, optarg, false);
3818 if (!opts) {
3819 exit(1);
3821 display_remote++;
3822 break;
3823 case QEMU_OPTION_writeconfig:
3825 FILE *fp;
3826 if (strcmp(optarg, "-") == 0) {
3827 fp = stdout;
3828 } else {
3829 fp = fopen(optarg, "w");
3830 if (fp == NULL) {
3831 error_report("open %s: %s", optarg,
3832 strerror(errno));
3833 exit(1);
3836 qemu_config_write(fp);
3837 if (fp != stdout) {
3838 fclose(fp);
3840 break;
3842 case QEMU_OPTION_qtest:
3843 qtest_chrdev = optarg;
3844 break;
3845 case QEMU_OPTION_qtest_log:
3846 qtest_log = optarg;
3847 break;
3848 case QEMU_OPTION_sandbox:
3849 olist = qemu_find_opts("sandbox");
3850 if (!olist) {
3851 #ifndef CONFIG_SECCOMP
3852 error_report("-sandbox support is not enabled "
3853 "in this QEMU binary");
3854 #endif
3855 exit(1);
3858 opts = qemu_opts_parse_noisily(olist, optarg, true);
3859 if (!opts) {
3860 exit(1);
3862 break;
3863 case QEMU_OPTION_add_fd:
3864 #ifndef _WIN32
3865 opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
3866 optarg, false);
3867 if (!opts) {
3868 exit(1);
3870 #else
3871 error_report("File descriptor passing is disabled on this "
3872 "platform");
3873 exit(1);
3874 #endif
3875 break;
3876 case QEMU_OPTION_object:
3877 opts = qemu_opts_parse_noisily(qemu_find_opts("object"),
3878 optarg, true);
3879 if (!opts) {
3880 exit(1);
3882 break;
3883 case QEMU_OPTION_realtime:
3884 warn_report("'-realtime mlock=...' is deprecated, please use "
3885 "'-overcommit mem-lock=...' instead");
3886 opts = qemu_opts_parse_noisily(qemu_find_opts("realtime"),
3887 optarg, false);
3888 if (!opts) {
3889 exit(1);
3891 /* Don't override the -overcommit option if set */
3892 enable_mlock = enable_mlock ||
3893 qemu_opt_get_bool(opts, "mlock", true);
3894 break;
3895 case QEMU_OPTION_overcommit:
3896 opts = qemu_opts_parse_noisily(qemu_find_opts("overcommit"),
3897 optarg, false);
3898 if (!opts) {
3899 exit(1);
3901 /* Don't override the -realtime option if set */
3902 enable_mlock = enable_mlock ||
3903 qemu_opt_get_bool(opts, "mem-lock", false);
3904 enable_cpu_pm = qemu_opt_get_bool(opts, "cpu-pm", false);
3905 break;
3906 case QEMU_OPTION_msg:
3907 opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
3908 false);
3909 if (!opts) {
3910 exit(1);
3912 configure_msg(opts);
3913 break;
3914 case QEMU_OPTION_dump_vmstate:
3915 if (vmstate_dump_file) {
3916 error_report("only one '-dump-vmstate' "
3917 "option may be given");
3918 exit(1);
3920 vmstate_dump_file = fopen(optarg, "w");
3921 if (vmstate_dump_file == NULL) {
3922 error_report("open %s: %s", optarg, strerror(errno));
3923 exit(1);
3925 break;
3926 case QEMU_OPTION_enable_sync_profile:
3927 qsp_enable();
3928 break;
3929 case QEMU_OPTION_nouserconfig:
3930 /* Nothing to be parsed here. Especially, do not error out below. */
3931 break;
3932 default:
3933 if (os_parse_cmd_args(popt->index, optarg)) {
3934 error_report("Option not supported in this build");
3935 exit(1);
3941 * Clear error location left behind by the loop.
3942 * Best done right after the loop. Do not insert code here!
3944 loc_set_none();
3947 * These options affect everything else and should be processed
3948 * before daemonizing.
3950 qemu_process_early_options();
3952 qemu_process_help_options();
3953 qemu_maybe_daemonize(pid_file);
3955 if (qemu_init_main_loop(&main_loop_err)) {
3956 error_report_err(main_loop_err);
3957 exit(1);
3960 user_register_global_props();
3962 replay_configure(icount_opts);
3964 if (incoming && !preconfig_exit_requested) {
3965 error_report("'preconfig' and 'incoming' options are "
3966 "mutually exclusive");
3967 exit(EXIT_FAILURE);
3970 configure_rtc(qemu_find_opts_singleton("rtc"));
3972 machine_class = select_machine();
3973 object_set_machine_compat_props(machine_class->compat_props);
3975 have_custom_ram_size = set_memory_options(&ram_slots, &maxram_size,
3976 machine_class);
3978 current_machine = MACHINE(object_new_with_class(OBJECT_CLASS(machine_class)));
3979 if (machine_help_func(qemu_get_machine_opts(), current_machine)) {
3980 exit(0);
3982 object_property_add_child(object_get_root(), "machine",
3983 OBJECT(current_machine));
3984 object_property_add_child(container_get(OBJECT(current_machine),
3985 "/unattached"),
3986 "sysbus", OBJECT(sysbus_get_default()));
3988 if (machine_class->minimum_page_bits) {
3989 if (!set_preferred_target_page_bits(machine_class->minimum_page_bits)) {
3990 /* This would be a board error: specifying a minimum smaller than
3991 * a target's compile-time fixed setting.
3993 g_assert_not_reached();
3997 cpu_exec_init_all();
3999 if (machine_class->hw_version) {
4000 qemu_set_hw_version(machine_class->hw_version);
4003 machine_smp_parse(current_machine,
4004 qemu_opts_find(qemu_find_opts("smp-opts"), NULL), &error_fatal);
4006 if (mem_prealloc) {
4007 char *val;
4009 val = g_strdup_printf("%d", current_machine->smp.cpus);
4010 object_register_sugar_prop("memory-backend", "prealloc-threads", val);
4011 g_free(val);
4012 object_register_sugar_prop("memory-backend", "prealloc", "on");
4016 * Get the default machine options from the machine if it is not already
4017 * specified either by the configuration file or by the command line.
4019 if (machine_class->default_machine_opts) {
4020 qemu_opts_set_defaults(qemu_find_opts("machine"),
4021 machine_class->default_machine_opts, 0);
4024 /* process plugin before CPUs are created, but once -smp has been parsed */
4025 if (qemu_plugin_load_list(&plugin_list)) {
4026 exit(1);
4029 qemu_opts_foreach(qemu_find_opts("device"),
4030 default_driver_check, NULL, NULL);
4031 qemu_opts_foreach(qemu_find_opts("global"),
4032 default_driver_check, NULL, NULL);
4034 if (!vga_model && !default_vga) {
4035 vga_interface_type = VGA_DEVICE;
4037 if (!has_defaults || machine_class->no_serial) {
4038 default_serial = 0;
4040 if (!has_defaults || machine_class->no_parallel) {
4041 default_parallel = 0;
4043 if (!has_defaults || machine_class->no_floppy) {
4044 default_floppy = 0;
4046 if (!has_defaults || machine_class->no_cdrom) {
4047 default_cdrom = 0;
4049 if (!has_defaults || machine_class->no_sdcard) {
4050 default_sdcard = 0;
4052 if (!has_defaults) {
4053 default_monitor = 0;
4054 default_net = 0;
4055 default_vga = 0;
4058 if (is_daemonized()) {
4059 /* According to documentation and historically, -nographic redirects
4060 * serial port, parallel port and monitor to stdio, which does not work
4061 * with -daemonize. We can redirect these to null instead, but since
4062 * -nographic is legacy, let's just error out.
4063 * We disallow -nographic only if all other ports are not redirected
4064 * explicitly, to not break existing legacy setups which uses
4065 * -nographic _and_ redirects all ports explicitly - this is valid
4066 * usage, -nographic is just a no-op in this case.
4068 if (nographic
4069 && (default_parallel || default_serial || default_monitor)) {
4070 error_report("-nographic cannot be used with -daemonize");
4071 exit(1);
4073 #ifdef CONFIG_CURSES
4074 if (dpy.type == DISPLAY_TYPE_CURSES) {
4075 error_report("curses display cannot be used with -daemonize");
4076 exit(1);
4078 #endif
4081 if (nographic) {
4082 if (default_parallel)
4083 add_device_config(DEV_PARALLEL, "null");
4084 if (default_serial && default_monitor) {
4085 add_device_config(DEV_SERIAL, "mon:stdio");
4086 } else {
4087 if (default_serial)
4088 add_device_config(DEV_SERIAL, "stdio");
4089 if (default_monitor)
4090 monitor_parse("stdio", "readline", false);
4092 } else {
4093 if (default_serial)
4094 add_device_config(DEV_SERIAL, "vc:80Cx24C");
4095 if (default_parallel)
4096 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4097 if (default_monitor)
4098 monitor_parse("vc:80Cx24C", "readline", false);
4101 #if defined(CONFIG_VNC)
4102 if (!QTAILQ_EMPTY(&(qemu_find_opts("vnc")->head))) {
4103 display_remote++;
4105 #endif
4106 if (dpy.type == DISPLAY_TYPE_DEFAULT && !display_remote) {
4107 if (!qemu_display_find_default(&dpy)) {
4108 dpy.type = DISPLAY_TYPE_NONE;
4109 #if defined(CONFIG_VNC)
4110 vnc_parse("localhost:0,to=99,id=default", &error_abort);
4111 #endif
4114 if (dpy.type == DISPLAY_TYPE_DEFAULT) {
4115 dpy.type = DISPLAY_TYPE_NONE;
4118 if ((alt_grab || ctrl_grab) && dpy.type != DISPLAY_TYPE_SDL) {
4119 error_report("-alt-grab and -ctrl-grab are only valid "
4120 "for SDL, ignoring option");
4122 if (dpy.has_window_close &&
4123 (dpy.type != DISPLAY_TYPE_GTK && dpy.type != DISPLAY_TYPE_SDL)) {
4124 error_report("-no-quit is only valid for GTK and SDL, "
4125 "ignoring option");
4128 qemu_display_early_init(&dpy);
4129 qemu_console_early_init();
4131 if (dpy.has_gl && dpy.gl != DISPLAYGL_MODE_OFF && display_opengl == 0) {
4132 #if defined(CONFIG_OPENGL)
4133 error_report("OpenGL is not supported by the display");
4134 #else
4135 error_report("OpenGL support is disabled");
4136 #endif
4137 exit(1);
4140 page_size_init();
4141 socket_init();
4143 qemu_opts_foreach(qemu_find_opts("object"),
4144 user_creatable_add_opts_foreach,
4145 object_create_initial, &error_fatal);
4147 /* spice needs the timers to be initialized by this point */
4148 /* spice must initialize before audio as it changes the default auiodev */
4149 /* spice must initialize before chardevs (for spicevmc and spiceport) */
4150 qemu_spice.init();
4152 qemu_opts_foreach(qemu_find_opts("chardev"),
4153 chardev_init_func, NULL, &error_fatal);
4155 #ifdef CONFIG_VIRTFS
4156 qemu_opts_foreach(qemu_find_opts("fsdev"),
4157 fsdev_init_func, NULL, &error_fatal);
4158 #endif
4161 * Note: we need to create audio and block backends before
4162 * machine_set_property(), so machine properties can refer to
4163 * them.
4165 configure_blockdev(&bdo_queue, machine_class, snapshot);
4166 audio_init_audiodevs();
4168 machine_opts = qemu_get_machine_opts();
4169 qemu_opt_foreach(machine_opts, machine_set_property, current_machine,
4170 &error_fatal);
4171 current_machine->ram_size = ram_size;
4172 current_machine->maxram_size = maxram_size;
4173 current_machine->ram_slots = ram_slots;
4176 * Note: uses machine properties such as kernel-irqchip, must run
4177 * after machine_set_property().
4179 configure_accelerators(argv[0]);
4182 * Beware, QOM objects created before this point miss global and
4183 * compat properties.
4185 * Global properties get set up by qdev_prop_register_global(),
4186 * called from user_register_global_props(), and certain option
4187 * desugaring. Also in CPU feature desugaring (buried in
4188 * parse_cpu_option()), which happens below this point, but may
4189 * only target the CPU type, which can only be created after
4190 * parse_cpu_option() returned the type.
4192 * Machine compat properties: object_set_machine_compat_props().
4193 * Accelerator compat props: object_set_accelerator_compat_props(),
4194 * called from configure_accelerator().
4197 if (!qtest_enabled() && machine_class->deprecation_reason) {
4198 error_report("Machine type '%s' is deprecated: %s",
4199 machine_class->name, machine_class->deprecation_reason);
4203 * Note: creates a QOM object, must run only after global and
4204 * compat properties have been set up.
4206 migration_object_init();
4208 if (qtest_chrdev) {
4209 qtest_server_init(qtest_chrdev, qtest_log, &error_fatal);
4212 machine_opts = qemu_get_machine_opts();
4213 kernel_filename = qemu_opt_get(machine_opts, "kernel");
4214 initrd_filename = qemu_opt_get(machine_opts, "initrd");
4215 kernel_cmdline = qemu_opt_get(machine_opts, "append");
4217 opts = qemu_opts_find(qemu_find_opts("boot-opts"), NULL);
4218 if (opts) {
4219 boot_order = qemu_opt_get(opts, "order");
4220 if (boot_order) {
4221 validate_bootdevices(boot_order, &error_fatal);
4224 boot_once = qemu_opt_get(opts, "once");
4225 if (boot_once) {
4226 validate_bootdevices(boot_once, &error_fatal);
4229 boot_menu = qemu_opt_get_bool(opts, "menu", boot_menu);
4230 boot_strict = qemu_opt_get_bool(opts, "strict", false);
4233 if (!boot_order) {
4234 boot_order = machine_class->default_boot_order;
4237 if (!kernel_cmdline) {
4238 kernel_cmdline = "";
4239 current_machine->kernel_cmdline = (char *)kernel_cmdline;
4242 linux_boot = (kernel_filename != NULL);
4244 if (!linux_boot && *kernel_cmdline != '\0') {
4245 error_report("-append only allowed with -kernel option");
4246 exit(1);
4249 if (!linux_boot && initrd_filename != NULL) {
4250 error_report("-initrd only allowed with -kernel option");
4251 exit(1);
4254 if (semihosting_enabled() && !semihosting_get_argc() && kernel_filename) {
4255 /* fall back to the -kernel/-append */
4256 semihosting_arg_fallback(kernel_filename, kernel_cmdline);
4259 /* initialize cpu timers and VCPU throttle modules */
4260 cpu_timers_init();
4262 if (default_net) {
4263 QemuOptsList *net = qemu_find_opts("net");
4264 qemu_opts_set(net, NULL, "type", "nic", &error_abort);
4265 #ifdef CONFIG_SLIRP
4266 qemu_opts_set(net, NULL, "type", "user", &error_abort);
4267 #endif
4270 if (net_init_clients(&err) < 0) {
4271 error_report_err(err);
4272 exit(1);
4275 qemu_opts_foreach(qemu_find_opts("object"),
4276 user_creatable_add_opts_foreach,
4277 object_create_delayed, &error_fatal);
4279 if (tpm_init() < 0) {
4280 exit(1);
4283 qemu_opts_foreach(qemu_find_opts("mon"),
4284 mon_init_func, NULL, &error_fatal);
4286 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4287 exit(1);
4288 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4289 exit(1);
4290 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4291 exit(1);
4293 /* now chardevs have been created we may have semihosting to connect */
4294 qemu_semihosting_connect_chardevs();
4295 qemu_semihosting_console_init();
4297 /* If no default VGA is requested, the default is "none". */
4298 if (default_vga) {
4299 vga_model = get_default_vga_model(machine_class);
4301 if (vga_model) {
4302 select_vgahw(machine_class, vga_model);
4305 if (watchdog) {
4306 i = select_watchdog(watchdog);
4307 if (i > 0)
4308 exit (i == 1 ? 1 : 0);
4311 /* This checkpoint is required by replay to separate prior clock
4312 reading from the other reads, because timer polling functions query
4313 clock values from the log. */
4314 replay_checkpoint(CHECKPOINT_INIT);
4316 current_machine->boot_order = boot_order;
4318 /* parse features once if machine provides default cpu_type */
4319 current_machine->cpu_type = machine_class->default_cpu_type;
4320 if (cpu_option) {
4321 current_machine->cpu_type = parse_cpu_option(cpu_option);
4324 if (current_machine->ram_memdev_id) {
4325 Object *backend;
4326 ram_addr_t backend_size;
4328 backend = object_resolve_path_type(current_machine->ram_memdev_id,
4329 TYPE_MEMORY_BACKEND, NULL);
4330 if (!backend) {
4331 error_report("Memory backend '%s' not found",
4332 current_machine->ram_memdev_id);
4333 exit(EXIT_FAILURE);
4335 backend_size = object_property_get_uint(backend, "size", &error_abort);
4336 if (have_custom_ram_size && backend_size != ram_size) {
4337 error_report("Size specified by -m option must match size of "
4338 "explicitly specified 'memory-backend' property");
4339 exit(EXIT_FAILURE);
4341 if (mem_path) {
4342 error_report("'-mem-path' can't be used together with"
4343 "'-machine memory-backend'");
4344 exit(EXIT_FAILURE);
4346 ram_size = backend_size;
4349 if (!xen_enabled()) {
4350 /* On 32-bit hosts, QEMU is limited by virtual address space */
4351 if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
4352 error_report("at most 2047 MB RAM can be simulated");
4353 exit(1);
4357 parse_numa_opts(current_machine);
4359 /* do monitor/qmp handling at preconfig state if requested */
4360 qemu_main_loop();
4362 if (machine_class->default_ram_id && current_machine->ram_size &&
4363 numa_uses_legacy_mem() && !current_machine->ram_memdev_id) {
4364 create_default_memdev(current_machine, mem_path);
4367 /* from here on runstate is RUN_STATE_PRELAUNCH */
4368 machine_run_board_init(current_machine);
4371 * TODO To drop support for deprecated bogus if=..., move
4372 * drive_check_orphaned() here, replacing this call. Also drop
4373 * its deprecation warning, along with DriveInfo member
4374 * @claimed_by_board.
4376 drive_mark_claimed_by_board();
4378 realtime_init();
4380 soundhw_init();
4382 if (hax_enabled()) {
4383 hax_sync_vcpus();
4386 qemu_opts_foreach(qemu_find_opts("fw_cfg"),
4387 parse_fw_cfg, fw_cfg_find(), &error_fatal);
4389 /* init USB devices */
4390 if (machine_usb(current_machine)) {
4391 if (foreach_device_config(DEV_USB, usb_parse) < 0)
4392 exit(1);
4395 /* init generic devices */
4396 rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
4397 qemu_opts_foreach(qemu_find_opts("device"),
4398 device_init_func, NULL, &error_fatal);
4400 cpu_synchronize_all_post_init();
4402 rom_reset_order_override();
4404 /* Did we create any drives that we failed to create a device for? */
4405 drive_check_orphaned();
4407 /* Don't warn about the default network setup that you get if
4408 * no command line -net or -netdev options are specified. There
4409 * are two cases that we would otherwise complain about:
4410 * (1) board doesn't support a NIC but the implicit "-net nic"
4411 * requested one
4412 * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
4413 * sets up a nic that isn't connected to anything.
4415 if (!default_net && (!qtest_enabled() || has_defaults)) {
4416 net_check_clients();
4419 if (boot_once) {
4420 qemu_boot_set(boot_once, &error_fatal);
4421 qemu_register_reset(restore_boot_order, g_strdup(boot_order));
4424 /* init local displays */
4425 ds = init_displaystate();
4426 qemu_display_init(ds, &dpy);
4428 /* must be after terminal init, SDL library changes signal handlers */
4429 os_setup_signal_handling();
4431 /* init remote displays */
4432 #ifdef CONFIG_VNC
4433 qemu_opts_foreach(qemu_find_opts("vnc"),
4434 vnc_init_func, NULL, &error_fatal);
4435 #endif
4437 if (using_spice) {
4438 qemu_spice.display_init();
4441 if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
4442 exit(1);
4445 qdev_machine_creation_done();
4447 /* TODO: once all bus devices are qdevified, this should be done
4448 * when bus is created by qdev.c */
4450 * TODO: If we had a main 'reset container' that the whole system
4451 * lived in, we could reset that using the multi-phase reset
4452 * APIs. For the moment, we just reset the sysbus, which will cause
4453 * all devices hanging off it (and all their child buses, recursively)
4454 * to be reset. Note that this will *not* reset any Device objects
4455 * which are not attached to some part of the qbus tree!
4457 qemu_register_reset(resettable_cold_reset_fn, sysbus_get_default());
4458 qemu_run_machine_init_done_notifiers();
4460 if (rom_check_and_register_reset() != 0) {
4461 error_report("rom check and register reset failed");
4462 exit(1);
4465 replay_start();
4467 /* This checkpoint is required by replay to separate prior clock
4468 reading from the other reads, because timer polling functions query
4469 clock values from the log. */
4470 replay_checkpoint(CHECKPOINT_RESET);
4471 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
4472 register_global_state();
4473 if (loadvm) {
4474 Error *local_err = NULL;
4475 if (load_snapshot(loadvm, &local_err) < 0) {
4476 error_report_err(local_err);
4477 autostart = 0;
4478 exit(1);
4481 if (replay_mode != REPLAY_MODE_NONE) {
4482 replay_vmstate_init();
4485 qdev_prop_check_globals();
4486 if (vmstate_dump_file) {
4487 /* dump and exit */
4488 dump_vmstate_json_to_file(vmstate_dump_file);
4489 exit(0);
4492 if (incoming) {
4493 Error *local_err = NULL;
4494 qemu_start_incoming_migration(incoming, &local_err);
4495 if (local_err) {
4496 error_reportf_err(local_err, "-incoming %s: ", incoming);
4497 exit(1);
4499 } else if (autostart) {
4500 vm_start();
4503 accel_setup_post(current_machine);
4504 os_setup_post();
4506 return;
4509 void qemu_cleanup(void)
4511 gdbserver_cleanup();
4514 * cleaning up the migration object cancels any existing migration
4515 * try to do this early so that it also stops using devices.
4517 migration_shutdown();
4520 * We must cancel all block jobs while the block layer is drained,
4521 * or cancelling will be affected by throttling and thus may block
4522 * for an extended period of time.
4523 * vm_shutdown() will bdrv_drain_all(), so we may as well include
4524 * it in the drained section.
4525 * We do not need to end this section, because we do not want any
4526 * requests happening from here on anyway.
4528 bdrv_drain_all_begin();
4530 /* No more vcpu or device emulation activity beyond this point */
4531 vm_shutdown();
4532 replay_finish();
4534 job_cancel_sync_all();
4535 bdrv_close_all();
4537 res_free();
4539 /* vhost-user must be cleaned up before chardevs. */
4540 tpm_cleanup();
4541 net_cleanup();
4542 audio_cleanup();
4543 monitor_cleanup();
4544 qemu_chr_cleanup();
4545 user_creatable_cleanup();
4546 /* TODO: unref root container, check all devices are ok */