configure / meson: Move check for sys/kcov.h to meson.build
[qemu/ar7.git] / softmmu / vl.c
blob7146fbe21986c0202efe636f83b2cca074c2f90b
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/datadir.h"
28 #include "qemu/units.h"
29 #include "hw/boards.h"
30 #include "hw/qdev-properties.h"
31 #include "qapi/error.h"
32 #include "qemu-version.h"
33 #include "qemu/cutils.h"
34 #include "qemu/help_option.h"
35 #include "qemu/uuid.h"
36 #include "sysemu/reset.h"
37 #include "sysemu/runstate.h"
38 #include "sysemu/seccomp.h"
39 #include "sysemu/tcg.h"
40 #include "sysemu/xen.h"
42 #include "qemu/error-report.h"
43 #include "qemu/sockets.h"
44 #include "sysemu/accel.h"
45 #include "hw/usb.h"
46 #include "hw/isa/isa.h"
47 #include "hw/scsi/scsi.h"
48 #include "hw/display/vga.h"
49 #include "sysemu/watchdog.h"
50 #include "hw/firmware/smbios.h"
51 #include "hw/acpi/acpi.h"
52 #include "hw/xen/xen.h"
53 #include "hw/loader.h"
54 #include "monitor/qdev.h"
55 #include "net/net.h"
56 #include "net/slirp.h"
57 #include "monitor/monitor.h"
58 #include "ui/console.h"
59 #include "ui/input.h"
60 #include "sysemu/sysemu.h"
61 #include "sysemu/numa.h"
62 #include "sysemu/hostmem.h"
63 #include "exec/gdbstub.h"
64 #include "qemu/timer.h"
65 #include "chardev/char.h"
66 #include "qemu/bitmap.h"
67 #include "qemu/log.h"
68 #include "sysemu/blockdev.h"
69 #include "hw/block/block.h"
70 #include "migration/misc.h"
71 #include "migration/snapshot.h"
72 #include "migration/global_state.h"
73 #include "sysemu/tpm.h"
74 #include "sysemu/dma.h"
75 #include "hw/audio/soundhw.h"
76 #include "audio/audio.h"
77 #include "sysemu/cpus.h"
78 #include "sysemu/cpu-timers.h"
79 #include "migration/colo.h"
80 #include "migration/postcopy-ram.h"
81 #include "sysemu/kvm.h"
82 #include "sysemu/hax.h"
83 #include "qapi/qobject-input-visitor.h"
84 #include "qemu/option.h"
85 #include "qemu/config-file.h"
86 #include "qemu-options.h"
87 #include "qemu/main-loop.h"
88 #ifdef CONFIG_VIRTFS
89 #include "fsdev/qemu-fsdev.h"
90 #endif
91 #include "sysemu/qtest.h"
93 #include "disas/disas.h"
95 #include "trace.h"
96 #include "trace/control.h"
97 #include "qemu/plugin.h"
98 #include "qemu/queue.h"
99 #include "sysemu/arch_init.h"
101 #include "ui/qemu-spice.h"
102 #include "qapi/string-input-visitor.h"
103 #include "qapi/opts-visitor.h"
104 #include "qapi/clone-visitor.h"
105 #include "qom/object_interfaces.h"
106 #include "hw/semihosting/semihost.h"
107 #include "crypto/init.h"
108 #include "sysemu/replay.h"
109 #include "qapi/qapi-events-run-state.h"
110 #include "qapi/qapi-visit-block-core.h"
111 #include "qapi/qapi-visit-ui.h"
112 #include "qapi/qapi-commands-block-core.h"
113 #include "qapi/qapi-commands-migration.h"
114 #include "qapi/qapi-commands-misc.h"
115 #include "qapi/qapi-commands-run-state.h"
116 #include "qapi/qapi-commands-ui.h"
117 #include "qapi/qmp/qerror.h"
118 #include "sysemu/iothread.h"
119 #include "qemu/guest-random.h"
121 #define MAX_VIRTIO_CONSOLES 1
123 typedef struct BlockdevOptionsQueueEntry {
124 BlockdevOptions *bdo;
125 Location loc;
126 QSIMPLEQ_ENTRY(BlockdevOptionsQueueEntry) entry;
127 } BlockdevOptionsQueueEntry;
129 typedef QSIMPLEQ_HEAD(, BlockdevOptionsQueueEntry) BlockdevOptionsQueue;
131 static const char *cpu_option;
132 static const char *mem_path;
133 static const char *incoming;
134 static const char *loadvm;
135 static ram_addr_t maxram_size;
136 static uint64_t ram_slots;
137 static int display_remote;
138 static int snapshot;
139 static bool preconfig_requested;
140 static QemuPluginList plugin_list = QTAILQ_HEAD_INITIALIZER(plugin_list);
141 static BlockdevOptionsQueue bdo_queue = QSIMPLEQ_HEAD_INITIALIZER(bdo_queue);
142 static bool nographic = false;
143 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
144 static int mem_prealloc; /* force preallocation of physical target memory */
145 int display_opengl;
146 const char* keyboard_layout = NULL;
147 static ram_addr_t ram_size;
148 bool enable_mlock = false;
149 bool enable_cpu_pm = false;
150 int nb_nics;
151 NICInfo nd_table[MAX_NICS];
152 int autostart = 1;
153 int vga_interface_type = VGA_NONE;
154 static const char *vga_model = NULL;
155 static DisplayOptions dpy;
156 static int num_serial_hds;
157 static Chardev **serial_hds;
158 static const char *log_mask;
159 static const char *log_file;
160 static bool list_data_dirs;
161 Chardev *parallel_hds[MAX_PARALLEL_PORTS];
162 int win2k_install_hack = 0;
163 int singlestep = 0;
164 int fd_bootchk = 1;
165 static int no_reboot;
166 int no_shutdown = 0;
167 int graphic_rotate = 0;
168 static const char *watchdog;
169 QEMUOptionRom option_rom[MAX_OPTION_ROMS];
170 int nb_option_roms;
171 int old_param = 0;
172 const char *qemu_name;
173 int alt_grab = 0;
174 int ctrl_grab = 0;
175 unsigned int nb_prom_envs = 0;
176 const char *prom_envs[MAX_PROM_ENVS];
177 int boot_menu;
178 bool boot_strict;
179 uint8_t *boot_splash_filedata;
180 int only_migratable; /* turn it off unless user states otherwise */
181 bool wakeup_suspend_enabled;
182 int icount_align_option;
183 static const char *qtest_chrdev;
184 static const char *qtest_log;
186 /* The bytes in qemu_uuid are in the order specified by RFC4122, _not_ in the
187 * little-endian "wire format" described in the SMBIOS 2.6 specification.
189 QemuUUID qemu_uuid;
190 bool qemu_uuid_set;
192 static NotifierList exit_notifiers =
193 NOTIFIER_LIST_INITIALIZER(exit_notifiers);
195 uint32_t xen_domid;
196 enum xen_mode xen_mode = XEN_EMULATE;
197 bool xen_domid_restrict;
199 static int has_defaults = 1;
200 static int default_serial = 1;
201 static int default_parallel = 1;
202 static int default_monitor = 1;
203 static int default_floppy = 1;
204 static int default_cdrom = 1;
205 static int default_sdcard = 1;
206 static int default_vga = 1;
207 static int default_net = 1;
209 static struct {
210 const char *driver;
211 int *flag;
212 } default_list[] = {
213 { .driver = "isa-serial", .flag = &default_serial },
214 { .driver = "isa-parallel", .flag = &default_parallel },
215 { .driver = "isa-fdc", .flag = &default_floppy },
216 { .driver = "floppy", .flag = &default_floppy },
217 { .driver = "ide-cd", .flag = &default_cdrom },
218 { .driver = "ide-hd", .flag = &default_cdrom },
219 { .driver = "ide-drive", .flag = &default_cdrom },
220 { .driver = "scsi-cd", .flag = &default_cdrom },
221 { .driver = "scsi-hd", .flag = &default_cdrom },
222 { .driver = "VGA", .flag = &default_vga },
223 { .driver = "isa-vga", .flag = &default_vga },
224 { .driver = "cirrus-vga", .flag = &default_vga },
225 { .driver = "isa-cirrus-vga", .flag = &default_vga },
226 { .driver = "vmware-svga", .flag = &default_vga },
227 { .driver = "qxl-vga", .flag = &default_vga },
228 { .driver = "virtio-vga", .flag = &default_vga },
229 { .driver = "ati-vga", .flag = &default_vga },
230 { .driver = "vhost-user-vga", .flag = &default_vga },
233 static QemuOptsList qemu_rtc_opts = {
234 .name = "rtc",
235 .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
236 .merge_lists = true,
237 .desc = {
239 .name = "base",
240 .type = QEMU_OPT_STRING,
242 .name = "clock",
243 .type = QEMU_OPT_STRING,
245 .name = "driftfix",
246 .type = QEMU_OPT_STRING,
248 { /* end of list */ }
252 static QemuOptsList qemu_option_rom_opts = {
253 .name = "option-rom",
254 .implied_opt_name = "romfile",
255 .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
256 .desc = {
258 .name = "bootindex",
259 .type = QEMU_OPT_NUMBER,
260 }, {
261 .name = "romfile",
262 .type = QEMU_OPT_STRING,
264 { /* end of list */ }
268 static QemuOptsList qemu_machine_opts = {
269 .name = "machine",
270 .implied_opt_name = "type",
271 .merge_lists = true,
272 .head = QTAILQ_HEAD_INITIALIZER(qemu_machine_opts.head),
273 .desc = {
275 * no elements => accept any
276 * sanity checking will happen later
277 * when setting machine properties
283 static QemuOptsList qemu_accel_opts = {
284 .name = "accel",
285 .implied_opt_name = "accel",
286 .head = QTAILQ_HEAD_INITIALIZER(qemu_accel_opts.head),
287 .desc = {
289 * no elements => accept any
290 * sanity checking will happen later
291 * when setting accelerator properties
297 static QemuOptsList qemu_boot_opts = {
298 .name = "boot-opts",
299 .implied_opt_name = "order",
300 .merge_lists = true,
301 .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
302 .desc = {
304 .name = "order",
305 .type = QEMU_OPT_STRING,
306 }, {
307 .name = "once",
308 .type = QEMU_OPT_STRING,
309 }, {
310 .name = "menu",
311 .type = QEMU_OPT_BOOL,
312 }, {
313 .name = "splash",
314 .type = QEMU_OPT_STRING,
315 }, {
316 .name = "splash-time",
317 .type = QEMU_OPT_NUMBER,
318 }, {
319 .name = "reboot-timeout",
320 .type = QEMU_OPT_NUMBER,
321 }, {
322 .name = "strict",
323 .type = QEMU_OPT_BOOL,
325 { /*End of list */ }
329 static QemuOptsList qemu_add_fd_opts = {
330 .name = "add-fd",
331 .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
332 .desc = {
334 .name = "fd",
335 .type = QEMU_OPT_NUMBER,
336 .help = "file descriptor of which a duplicate is added to fd set",
338 .name = "set",
339 .type = QEMU_OPT_NUMBER,
340 .help = "ID of the fd set to add fd to",
342 .name = "opaque",
343 .type = QEMU_OPT_STRING,
344 .help = "free-form string used to describe fd",
346 { /* end of list */ }
350 static QemuOptsList qemu_object_opts = {
351 .name = "object",
352 .implied_opt_name = "qom-type",
353 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
354 .desc = {
359 static QemuOptsList qemu_tpmdev_opts = {
360 .name = "tpmdev",
361 .implied_opt_name = "type",
362 .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
363 .desc = {
364 /* options are defined in the TPM backends */
365 { /* end of list */ }
369 static QemuOptsList qemu_realtime_opts = {
370 .name = "realtime",
371 .head = QTAILQ_HEAD_INITIALIZER(qemu_realtime_opts.head),
372 .desc = {
374 .name = "mlock",
375 .type = QEMU_OPT_BOOL,
377 { /* end of list */ }
381 static QemuOptsList qemu_overcommit_opts = {
382 .name = "overcommit",
383 .head = QTAILQ_HEAD_INITIALIZER(qemu_overcommit_opts.head),
384 .desc = {
386 .name = "mem-lock",
387 .type = QEMU_OPT_BOOL,
390 .name = "cpu-pm",
391 .type = QEMU_OPT_BOOL,
393 { /* end of list */ }
397 static QemuOptsList qemu_msg_opts = {
398 .name = "msg",
399 .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
400 .desc = {
402 .name = "timestamp",
403 .type = QEMU_OPT_BOOL,
406 .name = "guest-name",
407 .type = QEMU_OPT_BOOL,
408 .help = "Prepends guest name for error messages but only if "
409 "-name guest is set otherwise option is ignored\n",
411 { /* end of list */ }
415 static QemuOptsList qemu_name_opts = {
416 .name = "name",
417 .implied_opt_name = "guest",
418 .merge_lists = true,
419 .head = QTAILQ_HEAD_INITIALIZER(qemu_name_opts.head),
420 .desc = {
422 .name = "guest",
423 .type = QEMU_OPT_STRING,
424 .help = "Sets the name of the guest.\n"
425 "This name will be displayed in the SDL window caption.\n"
426 "The name will also be used for the VNC server",
427 }, {
428 .name = "process",
429 .type = QEMU_OPT_STRING,
430 .help = "Sets the name of the QEMU process, as shown in top etc",
431 }, {
432 .name = "debug-threads",
433 .type = QEMU_OPT_BOOL,
434 .help = "When enabled, name the individual threads; defaults off.\n"
435 "NOTE: The thread names are for debugging and not a\n"
436 "stable API.",
438 { /* End of list */ }
442 static QemuOptsList qemu_mem_opts = {
443 .name = "memory",
444 .implied_opt_name = "size",
445 .head = QTAILQ_HEAD_INITIALIZER(qemu_mem_opts.head),
446 .merge_lists = true,
447 .desc = {
449 .name = "size",
450 .type = QEMU_OPT_SIZE,
453 .name = "slots",
454 .type = QEMU_OPT_NUMBER,
457 .name = "maxmem",
458 .type = QEMU_OPT_SIZE,
460 { /* end of list */ }
464 static QemuOptsList qemu_icount_opts = {
465 .name = "icount",
466 .implied_opt_name = "shift",
467 .merge_lists = true,
468 .head = QTAILQ_HEAD_INITIALIZER(qemu_icount_opts.head),
469 .desc = {
471 .name = "shift",
472 .type = QEMU_OPT_STRING,
473 }, {
474 .name = "align",
475 .type = QEMU_OPT_BOOL,
476 }, {
477 .name = "sleep",
478 .type = QEMU_OPT_BOOL,
479 }, {
480 .name = "rr",
481 .type = QEMU_OPT_STRING,
482 }, {
483 .name = "rrfile",
484 .type = QEMU_OPT_STRING,
485 }, {
486 .name = "rrsnapshot",
487 .type = QEMU_OPT_STRING,
489 { /* end of list */ }
493 static QemuOptsList qemu_fw_cfg_opts = {
494 .name = "fw_cfg",
495 .implied_opt_name = "name",
496 .head = QTAILQ_HEAD_INITIALIZER(qemu_fw_cfg_opts.head),
497 .desc = {
499 .name = "name",
500 .type = QEMU_OPT_STRING,
501 .help = "Sets the fw_cfg name of the blob to be inserted",
502 }, {
503 .name = "file",
504 .type = QEMU_OPT_STRING,
505 .help = "Sets the name of the file from which "
506 "the fw_cfg blob will be loaded",
507 }, {
508 .name = "string",
509 .type = QEMU_OPT_STRING,
510 .help = "Sets content of the blob to be inserted from a string",
511 }, {
512 .name = "gen_id",
513 .type = QEMU_OPT_STRING,
514 .help = "Sets id of the object generating the fw_cfg blob "
515 "to be inserted",
517 { /* end of list */ }
522 * Get machine options
524 * Returns: machine options (never null).
526 QemuOpts *qemu_get_machine_opts(void)
528 return qemu_find_opts_singleton("machine");
531 const char *qemu_get_vm_name(void)
533 return qemu_name;
536 static void res_free(void)
538 g_free(boot_splash_filedata);
539 boot_splash_filedata = NULL;
542 static int default_driver_check(void *opaque, QemuOpts *opts, Error **errp)
544 const char *driver = qemu_opt_get(opts, "driver");
545 int i;
547 if (!driver)
548 return 0;
549 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
550 if (strcmp(default_list[i].driver, driver) != 0)
551 continue;
552 *(default_list[i].flag) = 0;
554 return 0;
557 /***********************************************************/
558 /* QEMU state */
560 static RunState current_run_state = RUN_STATE_PRECONFIG;
562 /* We use RUN_STATE__MAX but any invalid value will do */
563 static RunState vmstop_requested = RUN_STATE__MAX;
564 static QemuMutex vmstop_lock;
566 typedef struct {
567 RunState from;
568 RunState to;
569 } RunStateTransition;
571 static const RunStateTransition runstate_transitions_def[] = {
572 /* from -> to */
573 { RUN_STATE_PRECONFIG, RUN_STATE_PRELAUNCH },
574 /* Early switch to inmigrate state to allow -incoming CLI option work
575 * as it used to. TODO: delay actual switching to inmigrate state to
576 * the point after machine is built and remove this hack.
578 { RUN_STATE_PRECONFIG, RUN_STATE_INMIGRATE },
580 { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
581 { RUN_STATE_DEBUG, RUN_STATE_FINISH_MIGRATE },
582 { RUN_STATE_DEBUG, RUN_STATE_PRELAUNCH },
584 { RUN_STATE_INMIGRATE, RUN_STATE_INTERNAL_ERROR },
585 { RUN_STATE_INMIGRATE, RUN_STATE_IO_ERROR },
586 { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
587 { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
588 { RUN_STATE_INMIGRATE, RUN_STATE_SHUTDOWN },
589 { RUN_STATE_INMIGRATE, RUN_STATE_SUSPENDED },
590 { RUN_STATE_INMIGRATE, RUN_STATE_WATCHDOG },
591 { RUN_STATE_INMIGRATE, RUN_STATE_GUEST_PANICKED },
592 { RUN_STATE_INMIGRATE, RUN_STATE_FINISH_MIGRATE },
593 { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
594 { RUN_STATE_INMIGRATE, RUN_STATE_POSTMIGRATE },
595 { RUN_STATE_INMIGRATE, RUN_STATE_COLO },
597 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
598 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
599 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PRELAUNCH },
601 { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
602 { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
603 { RUN_STATE_IO_ERROR, RUN_STATE_PRELAUNCH },
605 { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
606 { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
607 { RUN_STATE_PAUSED, RUN_STATE_POSTMIGRATE },
608 { RUN_STATE_PAUSED, RUN_STATE_PRELAUNCH },
609 { RUN_STATE_PAUSED, RUN_STATE_COLO},
611 { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
612 { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
613 { RUN_STATE_POSTMIGRATE, RUN_STATE_PRELAUNCH },
615 { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
616 { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
617 { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
619 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
620 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PAUSED },
621 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
622 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PRELAUNCH },
623 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_COLO},
625 { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
626 { RUN_STATE_RESTORE_VM, RUN_STATE_PRELAUNCH },
628 { RUN_STATE_COLO, RUN_STATE_RUNNING },
630 { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
631 { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
632 { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
633 { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
634 { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
635 { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
636 { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
637 { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
638 { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
639 { RUN_STATE_RUNNING, RUN_STATE_GUEST_PANICKED },
640 { RUN_STATE_RUNNING, RUN_STATE_COLO},
642 { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
644 { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
645 { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
646 { RUN_STATE_SHUTDOWN, RUN_STATE_PRELAUNCH },
647 { RUN_STATE_SHUTDOWN, RUN_STATE_COLO },
649 { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
650 { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
651 { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
652 { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
653 { RUN_STATE_SUSPENDED, RUN_STATE_PRELAUNCH },
654 { RUN_STATE_SUSPENDED, RUN_STATE_COLO},
656 { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
657 { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
658 { RUN_STATE_WATCHDOG, RUN_STATE_PRELAUNCH },
659 { RUN_STATE_WATCHDOG, RUN_STATE_COLO},
661 { RUN_STATE_GUEST_PANICKED, RUN_STATE_RUNNING },
662 { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
663 { RUN_STATE_GUEST_PANICKED, RUN_STATE_PRELAUNCH },
665 { RUN_STATE__MAX, RUN_STATE__MAX },
668 static bool runstate_valid_transitions[RUN_STATE__MAX][RUN_STATE__MAX];
670 bool runstate_check(RunState state)
672 return current_run_state == state;
675 bool runstate_store(char *str, size_t size)
677 const char *state = RunState_str(current_run_state);
678 size_t len = strlen(state) + 1;
680 if (len > size) {
681 return false;
683 memcpy(str, state, len);
684 return true;
687 static void runstate_init(void)
689 const RunStateTransition *p;
691 memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
692 for (p = &runstate_transitions_def[0]; p->from != RUN_STATE__MAX; p++) {
693 runstate_valid_transitions[p->from][p->to] = true;
696 qemu_mutex_init(&vmstop_lock);
699 /* This function will abort() on invalid state transitions */
700 void runstate_set(RunState new_state)
702 assert(new_state < RUN_STATE__MAX);
704 trace_runstate_set(current_run_state, RunState_str(current_run_state),
705 new_state, RunState_str(new_state));
707 if (current_run_state == new_state) {
708 return;
711 if (!runstate_valid_transitions[current_run_state][new_state]) {
712 error_report("invalid runstate transition: '%s' -> '%s'",
713 RunState_str(current_run_state),
714 RunState_str(new_state));
715 abort();
718 current_run_state = new_state;
721 int runstate_is_running(void)
723 return runstate_check(RUN_STATE_RUNNING);
726 bool runstate_needs_reset(void)
728 return runstate_check(RUN_STATE_INTERNAL_ERROR) ||
729 runstate_check(RUN_STATE_SHUTDOWN);
732 StatusInfo *qmp_query_status(Error **errp)
734 StatusInfo *info = g_malloc0(sizeof(*info));
736 info->running = runstate_is_running();
737 info->singlestep = singlestep;
738 info->status = current_run_state;
740 return info;
743 bool qemu_vmstop_requested(RunState *r)
745 qemu_mutex_lock(&vmstop_lock);
746 *r = vmstop_requested;
747 vmstop_requested = RUN_STATE__MAX;
748 qemu_mutex_unlock(&vmstop_lock);
749 return *r < RUN_STATE__MAX;
752 void qemu_system_vmstop_request_prepare(void)
754 qemu_mutex_lock(&vmstop_lock);
757 void qemu_system_vmstop_request(RunState state)
759 vmstop_requested = state;
760 qemu_mutex_unlock(&vmstop_lock);
761 qemu_notify_event();
763 static int parse_name(void *opaque, QemuOpts *opts, Error **errp)
765 const char *proc_name;
767 if (qemu_opt_get(opts, "debug-threads")) {
768 qemu_thread_naming(qemu_opt_get_bool(opts, "debug-threads", false));
770 qemu_name = qemu_opt_get(opts, "guest");
772 proc_name = qemu_opt_get(opts, "process");
773 if (proc_name) {
774 os_set_proc_name(proc_name);
777 return 0;
780 bool defaults_enabled(void)
782 return has_defaults;
785 #ifndef _WIN32
786 static int parse_add_fd(void *opaque, QemuOpts *opts, Error **errp)
788 int fd, dupfd, flags;
789 int64_t fdset_id;
790 const char *fd_opaque = NULL;
791 AddfdInfo *fdinfo;
793 fd = qemu_opt_get_number(opts, "fd", -1);
794 fdset_id = qemu_opt_get_number(opts, "set", -1);
795 fd_opaque = qemu_opt_get(opts, "opaque");
797 if (fd < 0) {
798 error_setg(errp, "fd option is required and must be non-negative");
799 return -1;
802 if (fd <= STDERR_FILENO) {
803 error_setg(errp, "fd cannot be a standard I/O stream");
804 return -1;
808 * All fds inherited across exec() necessarily have FD_CLOEXEC
809 * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
811 flags = fcntl(fd, F_GETFD);
812 if (flags == -1 || (flags & FD_CLOEXEC)) {
813 error_setg(errp, "fd is not valid or already in use");
814 return -1;
817 if (fdset_id < 0) {
818 error_setg(errp, "set option is required and must be non-negative");
819 return -1;
822 #ifdef F_DUPFD_CLOEXEC
823 dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
824 #else
825 dupfd = dup(fd);
826 if (dupfd != -1) {
827 qemu_set_cloexec(dupfd);
829 #endif
830 if (dupfd == -1) {
831 error_setg(errp, "error duplicating fd: %s", strerror(errno));
832 return -1;
835 /* add the duplicate fd, and optionally the opaque string, to the fd set */
836 fdinfo = monitor_fdset_add_fd(dupfd, true, fdset_id, !!fd_opaque, fd_opaque,
837 &error_abort);
838 g_free(fdinfo);
840 return 0;
843 static int cleanup_add_fd(void *opaque, QemuOpts *opts, Error **errp)
845 int fd;
847 fd = qemu_opt_get_number(opts, "fd", -1);
848 close(fd);
850 return 0;
852 #endif
854 /***********************************************************/
855 /* QEMU Block devices */
857 #define HD_OPTS "media=disk"
858 #define CDROM_OPTS "media=cdrom"
859 #define FD_OPTS ""
860 #define PFLASH_OPTS ""
861 #define MTD_OPTS ""
862 #define SD_OPTS ""
864 static int drive_init_func(void *opaque, QemuOpts *opts, Error **errp)
866 BlockInterfaceType *block_default_type = opaque;
868 return drive_new(opts, *block_default_type, errp) == NULL;
871 static int drive_enable_snapshot(void *opaque, QemuOpts *opts, Error **errp)
873 if (qemu_opt_get(opts, "snapshot") == NULL) {
874 qemu_opt_set(opts, "snapshot", "on", &error_abort);
876 return 0;
879 static void default_drive(int enable, int snapshot, BlockInterfaceType type,
880 int index, const char *optstr)
882 QemuOpts *opts;
883 DriveInfo *dinfo;
885 if (!enable || drive_get_by_index(type, index)) {
886 return;
889 opts = drive_add(type, index, NULL, optstr);
890 if (snapshot) {
891 drive_enable_snapshot(NULL, opts, NULL);
894 dinfo = drive_new(opts, type, &error_abort);
895 dinfo->is_default = true;
899 static void configure_blockdev(BlockdevOptionsQueue *bdo_queue,
900 MachineClass *machine_class, int snapshot)
903 * If the currently selected machine wishes to override the
904 * units-per-bus property of its default HBA interface type, do so
905 * now.
907 if (machine_class->units_per_default_bus) {
908 override_max_devs(machine_class->block_default_type,
909 machine_class->units_per_default_bus);
912 /* open the virtual block devices */
913 while (!QSIMPLEQ_EMPTY(bdo_queue)) {
914 BlockdevOptionsQueueEntry *bdo = QSIMPLEQ_FIRST(bdo_queue);
916 QSIMPLEQ_REMOVE_HEAD(bdo_queue, entry);
917 loc_push_restore(&bdo->loc);
918 qmp_blockdev_add(bdo->bdo, &error_fatal);
919 loc_pop(&bdo->loc);
920 qapi_free_BlockdevOptions(bdo->bdo);
921 g_free(bdo);
923 if (snapshot) {
924 qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot,
925 NULL, NULL);
927 if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
928 &machine_class->block_default_type, &error_fatal)) {
929 /* We printed help */
930 exit(0);
933 default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
934 CDROM_OPTS);
935 default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
936 default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
940 static QemuOptsList qemu_smp_opts = {
941 .name = "smp-opts",
942 .implied_opt_name = "cpus",
943 .merge_lists = true,
944 .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
945 .desc = {
947 .name = "cpus",
948 .type = QEMU_OPT_NUMBER,
949 }, {
950 .name = "sockets",
951 .type = QEMU_OPT_NUMBER,
952 }, {
953 .name = "dies",
954 .type = QEMU_OPT_NUMBER,
955 }, {
956 .name = "cores",
957 .type = QEMU_OPT_NUMBER,
958 }, {
959 .name = "threads",
960 .type = QEMU_OPT_NUMBER,
961 }, {
962 .name = "maxcpus",
963 .type = QEMU_OPT_NUMBER,
965 { /*End of list */ }
969 static void realtime_init(void)
971 if (enable_mlock) {
972 if (os_mlock() < 0) {
973 error_report("locking memory failed");
974 exit(1);
980 static void configure_msg(QemuOpts *opts)
982 error_with_timestamp = qemu_opt_get_bool(opts, "timestamp", false);
983 error_with_guestname = qemu_opt_get_bool(opts, "guest-name", false);
987 /***********************************************************/
988 /* USB devices */
990 static int usb_device_add(const char *devname)
992 USBDevice *dev = NULL;
994 if (!machine_usb(current_machine)) {
995 return -1;
998 dev = usbdevice_create(devname);
999 if (!dev)
1000 return -1;
1002 return 0;
1005 static int usb_parse(const char *cmdline)
1007 int r;
1008 r = usb_device_add(cmdline);
1009 if (r < 0) {
1010 error_report("could not add USB device '%s'", cmdline);
1012 return r;
1015 /***********************************************************/
1016 /* machine registration */
1018 MachineState *current_machine;
1020 static MachineClass *find_machine(const char *name, GSList *machines)
1022 GSList *el;
1024 for (el = machines; el; el = el->next) {
1025 MachineClass *mc = el->data;
1027 if (!strcmp(mc->name, name) || !g_strcmp0(mc->alias, name)) {
1028 return mc;
1032 return NULL;
1035 static MachineClass *find_default_machine(GSList *machines)
1037 GSList *el;
1038 MachineClass *default_machineclass = NULL;
1040 for (el = machines; el; el = el->next) {
1041 MachineClass *mc = el->data;
1043 if (mc->is_default) {
1044 assert(default_machineclass == NULL && "Multiple default machines");
1045 default_machineclass = mc;
1049 return default_machineclass;
1052 static int machine_help_func(QemuOpts *opts, MachineState *machine)
1054 ObjectProperty *prop;
1055 ObjectPropertyIterator iter;
1057 if (!qemu_opt_has_help_opt(opts)) {
1058 return 0;
1061 object_property_iter_init(&iter, OBJECT(machine));
1062 while ((prop = object_property_iter_next(&iter))) {
1063 if (!prop->set) {
1064 continue;
1067 printf("%s.%s=%s", MACHINE_GET_CLASS(machine)->name,
1068 prop->name, prop->type);
1069 if (prop->description) {
1070 printf(" (%s)\n", prop->description);
1071 } else {
1072 printf("\n");
1076 return 1;
1079 struct VMChangeStateEntry {
1080 VMChangeStateHandler *cb;
1081 void *opaque;
1082 QTAILQ_ENTRY(VMChangeStateEntry) entries;
1083 int priority;
1086 static QTAILQ_HEAD(, VMChangeStateEntry) vm_change_state_head =
1087 QTAILQ_HEAD_INITIALIZER(vm_change_state_head);
1090 * qemu_add_vm_change_state_handler_prio:
1091 * @cb: the callback to invoke
1092 * @opaque: user data passed to the callback
1093 * @priority: low priorities execute first when the vm runs and the reverse is
1094 * true when the vm stops
1096 * Register a callback function that is invoked when the vm starts or stops
1097 * running.
1099 * Returns: an entry to be freed using qemu_del_vm_change_state_handler()
1101 VMChangeStateEntry *qemu_add_vm_change_state_handler_prio(
1102 VMChangeStateHandler *cb, void *opaque, int priority)
1104 VMChangeStateEntry *e;
1105 VMChangeStateEntry *other;
1107 e = g_malloc0(sizeof(*e));
1108 e->cb = cb;
1109 e->opaque = opaque;
1110 e->priority = priority;
1112 /* Keep list sorted in ascending priority order */
1113 QTAILQ_FOREACH(other, &vm_change_state_head, entries) {
1114 if (priority < other->priority) {
1115 QTAILQ_INSERT_BEFORE(other, e, entries);
1116 return e;
1120 QTAILQ_INSERT_TAIL(&vm_change_state_head, e, entries);
1121 return e;
1124 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1125 void *opaque)
1127 return qemu_add_vm_change_state_handler_prio(cb, opaque, 0);
1130 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1132 QTAILQ_REMOVE(&vm_change_state_head, e, entries);
1133 g_free(e);
1136 void vm_state_notify(int running, RunState state)
1138 VMChangeStateEntry *e, *next;
1140 trace_vm_state_notify(running, state, RunState_str(state));
1142 if (running) {
1143 QTAILQ_FOREACH_SAFE(e, &vm_change_state_head, entries, next) {
1144 e->cb(e->opaque, running, state);
1146 } else {
1147 QTAILQ_FOREACH_REVERSE_SAFE(e, &vm_change_state_head, entries, next) {
1148 e->cb(e->opaque, running, state);
1153 static ShutdownCause reset_requested;
1154 static ShutdownCause shutdown_requested;
1155 static int shutdown_signal;
1156 static pid_t shutdown_pid;
1157 static int powerdown_requested;
1158 static int debug_requested;
1159 static int suspend_requested;
1160 static bool preconfig_exit_requested = true;
1161 static WakeupReason wakeup_reason;
1162 static NotifierList powerdown_notifiers =
1163 NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
1164 static NotifierList suspend_notifiers =
1165 NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1166 static NotifierList wakeup_notifiers =
1167 NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1168 static NotifierList shutdown_notifiers =
1169 NOTIFIER_LIST_INITIALIZER(shutdown_notifiers);
1170 static uint32_t wakeup_reason_mask = ~(1 << QEMU_WAKEUP_REASON_NONE);
1172 ShutdownCause qemu_shutdown_requested_get(void)
1174 return shutdown_requested;
1177 ShutdownCause qemu_reset_requested_get(void)
1179 return reset_requested;
1182 static int qemu_shutdown_requested(void)
1184 return qatomic_xchg(&shutdown_requested, SHUTDOWN_CAUSE_NONE);
1187 static void qemu_kill_report(void)
1189 if (!qtest_driver() && shutdown_signal) {
1190 if (shutdown_pid == 0) {
1191 /* This happens for eg ^C at the terminal, so it's worth
1192 * avoiding printing an odd message in that case.
1194 error_report("terminating on signal %d", shutdown_signal);
1195 } else {
1196 char *shutdown_cmd = qemu_get_pid_name(shutdown_pid);
1198 error_report("terminating on signal %d from pid " FMT_pid " (%s)",
1199 shutdown_signal, shutdown_pid,
1200 shutdown_cmd ? shutdown_cmd : "<unknown process>");
1201 g_free(shutdown_cmd);
1203 shutdown_signal = 0;
1207 static ShutdownCause qemu_reset_requested(void)
1209 ShutdownCause r = reset_requested;
1211 if (r && replay_checkpoint(CHECKPOINT_RESET_REQUESTED)) {
1212 reset_requested = SHUTDOWN_CAUSE_NONE;
1213 return r;
1215 return SHUTDOWN_CAUSE_NONE;
1218 static int qemu_suspend_requested(void)
1220 int r = suspend_requested;
1221 if (r && replay_checkpoint(CHECKPOINT_SUSPEND_REQUESTED)) {
1222 suspend_requested = 0;
1223 return r;
1225 return false;
1228 static WakeupReason qemu_wakeup_requested(void)
1230 return wakeup_reason;
1233 static int qemu_powerdown_requested(void)
1235 int r = powerdown_requested;
1236 powerdown_requested = 0;
1237 return r;
1240 static int qemu_debug_requested(void)
1242 int r = debug_requested;
1243 debug_requested = 0;
1244 return r;
1247 void qemu_exit_preconfig_request(void)
1249 preconfig_exit_requested = true;
1253 * Reset the VM. Issue an event unless @reason is SHUTDOWN_CAUSE_NONE.
1255 void qemu_system_reset(ShutdownCause reason)
1257 MachineClass *mc;
1259 mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1261 cpu_synchronize_all_states();
1263 if (mc && mc->reset) {
1264 mc->reset(current_machine);
1265 } else {
1266 qemu_devices_reset();
1268 if (reason && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1269 qapi_event_send_reset(shutdown_caused_by_guest(reason), reason);
1271 cpu_synchronize_all_post_reset();
1275 * Wake the VM after suspend.
1277 static void qemu_system_wakeup(void)
1279 MachineClass *mc;
1281 mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1283 if (mc && mc->wakeup) {
1284 mc->wakeup(current_machine);
1288 void qemu_system_guest_panicked(GuestPanicInformation *info)
1290 qemu_log_mask(LOG_GUEST_ERROR, "Guest crashed");
1292 if (current_cpu) {
1293 current_cpu->crash_occurred = true;
1295 qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE,
1296 !!info, info);
1297 vm_stop(RUN_STATE_GUEST_PANICKED);
1298 if (!no_shutdown) {
1299 qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_POWEROFF,
1300 !!info, info);
1301 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_PANIC);
1304 if (info) {
1305 if (info->type == GUEST_PANIC_INFORMATION_TYPE_HYPER_V) {
1306 qemu_log_mask(LOG_GUEST_ERROR, "\nHV crash parameters: (%#"PRIx64
1307 " %#"PRIx64" %#"PRIx64" %#"PRIx64" %#"PRIx64")\n",
1308 info->u.hyper_v.arg1,
1309 info->u.hyper_v.arg2,
1310 info->u.hyper_v.arg3,
1311 info->u.hyper_v.arg4,
1312 info->u.hyper_v.arg5);
1313 } else if (info->type == GUEST_PANIC_INFORMATION_TYPE_S390) {
1314 qemu_log_mask(LOG_GUEST_ERROR, " on cpu %d: %s\n"
1315 "PSW: 0x%016" PRIx64 " 0x%016" PRIx64"\n",
1316 info->u.s390.core,
1317 S390CrashReason_str(info->u.s390.reason),
1318 info->u.s390.psw_mask,
1319 info->u.s390.psw_addr);
1321 qapi_free_GuestPanicInformation(info);
1325 void qemu_system_guest_crashloaded(GuestPanicInformation *info)
1327 qemu_log_mask(LOG_GUEST_ERROR, "Guest crash loaded");
1329 qapi_event_send_guest_crashloaded(GUEST_PANIC_ACTION_RUN,
1330 !!info, info);
1332 if (info) {
1333 qapi_free_GuestPanicInformation(info);
1337 void qemu_system_reset_request(ShutdownCause reason)
1339 if (no_reboot && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1340 shutdown_requested = reason;
1341 } else {
1342 reset_requested = reason;
1344 cpu_stop_current();
1345 qemu_notify_event();
1348 static void qemu_system_suspend(void)
1350 pause_all_vcpus();
1351 notifier_list_notify(&suspend_notifiers, NULL);
1352 runstate_set(RUN_STATE_SUSPENDED);
1353 qapi_event_send_suspend();
1356 void qemu_system_suspend_request(void)
1358 if (runstate_check(RUN_STATE_SUSPENDED)) {
1359 return;
1361 suspend_requested = 1;
1362 cpu_stop_current();
1363 qemu_notify_event();
1366 void qemu_register_suspend_notifier(Notifier *notifier)
1368 notifier_list_add(&suspend_notifiers, notifier);
1371 void qemu_system_wakeup_request(WakeupReason reason, Error **errp)
1373 trace_system_wakeup_request(reason);
1375 if (!runstate_check(RUN_STATE_SUSPENDED)) {
1376 error_setg(errp,
1377 "Unable to wake up: guest is not in suspended state");
1378 return;
1380 if (!(wakeup_reason_mask & (1 << reason))) {
1381 return;
1383 runstate_set(RUN_STATE_RUNNING);
1384 wakeup_reason = reason;
1385 qemu_notify_event();
1388 void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1390 if (enabled) {
1391 wakeup_reason_mask |= (1 << reason);
1392 } else {
1393 wakeup_reason_mask &= ~(1 << reason);
1397 void qemu_register_wakeup_notifier(Notifier *notifier)
1399 notifier_list_add(&wakeup_notifiers, notifier);
1402 void qemu_register_wakeup_support(void)
1404 wakeup_suspend_enabled = true;
1407 bool qemu_wakeup_suspend_enabled(void)
1409 return wakeup_suspend_enabled;
1412 void qemu_system_killed(int signal, pid_t pid)
1414 shutdown_signal = signal;
1415 shutdown_pid = pid;
1416 no_shutdown = 0;
1418 /* Cannot call qemu_system_shutdown_request directly because
1419 * we are in a signal handler.
1421 shutdown_requested = SHUTDOWN_CAUSE_HOST_SIGNAL;
1422 qemu_notify_event();
1425 void qemu_system_shutdown_request(ShutdownCause reason)
1427 trace_qemu_system_shutdown_request(reason);
1428 replay_shutdown_request(reason);
1429 shutdown_requested = reason;
1430 qemu_notify_event();
1433 static void qemu_system_powerdown(void)
1435 qapi_event_send_powerdown();
1436 notifier_list_notify(&powerdown_notifiers, NULL);
1439 static void qemu_system_shutdown(ShutdownCause cause)
1441 qapi_event_send_shutdown(shutdown_caused_by_guest(cause), cause);
1442 notifier_list_notify(&shutdown_notifiers, &cause);
1445 void qemu_system_powerdown_request(void)
1447 trace_qemu_system_powerdown_request();
1448 powerdown_requested = 1;
1449 qemu_notify_event();
1452 void qemu_register_powerdown_notifier(Notifier *notifier)
1454 notifier_list_add(&powerdown_notifiers, notifier);
1457 void qemu_register_shutdown_notifier(Notifier *notifier)
1459 notifier_list_add(&shutdown_notifiers, notifier);
1462 void qemu_system_debug_request(void)
1464 debug_requested = 1;
1465 qemu_notify_event();
1468 static bool main_loop_should_exit(void)
1470 RunState r;
1471 ShutdownCause request;
1473 if (preconfig_exit_requested) {
1474 if (runstate_check(RUN_STATE_PRECONFIG)) {
1475 runstate_set(RUN_STATE_PRELAUNCH);
1477 preconfig_exit_requested = false;
1478 return true;
1480 if (qemu_debug_requested()) {
1481 vm_stop(RUN_STATE_DEBUG);
1483 if (qemu_suspend_requested()) {
1484 qemu_system_suspend();
1486 request = qemu_shutdown_requested();
1487 if (request) {
1488 qemu_kill_report();
1489 qemu_system_shutdown(request);
1490 if (no_shutdown) {
1491 vm_stop(RUN_STATE_SHUTDOWN);
1492 } else {
1493 return true;
1496 request = qemu_reset_requested();
1497 if (request) {
1498 pause_all_vcpus();
1499 qemu_system_reset(request);
1500 resume_all_vcpus();
1502 * runstate can change in pause_all_vcpus()
1503 * as iothread mutex is unlocked
1505 if (!runstate_check(RUN_STATE_RUNNING) &&
1506 !runstate_check(RUN_STATE_INMIGRATE) &&
1507 !runstate_check(RUN_STATE_FINISH_MIGRATE)) {
1508 runstate_set(RUN_STATE_PRELAUNCH);
1511 if (qemu_wakeup_requested()) {
1512 pause_all_vcpus();
1513 qemu_system_wakeup();
1514 notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
1515 wakeup_reason = QEMU_WAKEUP_REASON_NONE;
1516 resume_all_vcpus();
1517 qapi_event_send_wakeup();
1519 if (qemu_powerdown_requested()) {
1520 qemu_system_powerdown();
1522 if (qemu_vmstop_requested(&r)) {
1523 vm_stop(r);
1525 return false;
1528 void qemu_main_loop(void)
1530 #ifdef CONFIG_PROFILER
1531 int64_t ti;
1532 #endif
1533 while (!main_loop_should_exit()) {
1534 #ifdef CONFIG_PROFILER
1535 ti = profile_getclock();
1536 #endif
1537 main_loop_wait(false);
1538 #ifdef CONFIG_PROFILER
1539 dev_time += profile_getclock() - ti;
1540 #endif
1544 static void version(void)
1546 printf("QEMU emulator version " QEMU_FULL_VERSION "\n"
1547 QEMU_COPYRIGHT "\n");
1550 static void help(int exitcode)
1552 version();
1553 printf("usage: %s [options] [disk_image]\n\n"
1554 "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
1555 error_get_progname());
1557 #define QEMU_OPTIONS_GENERATE_HELP
1558 #include "qemu-options-wrapper.h"
1560 printf("\nDuring emulation, the following keys are useful:\n"
1561 "ctrl-alt-f toggle full screen\n"
1562 "ctrl-alt-n switch to virtual console 'n'\n"
1563 "ctrl-alt toggle mouse and keyboard grab\n"
1564 "\n"
1565 "When using -nographic, press 'ctrl-a h' to get some help.\n"
1566 "\n"
1567 QEMU_HELP_BOTTOM "\n");
1569 exit(exitcode);
1572 #define HAS_ARG 0x0001
1574 typedef struct QEMUOption {
1575 const char *name;
1576 int flags;
1577 int index;
1578 uint32_t arch_mask;
1579 } QEMUOption;
1581 static const QEMUOption qemu_options[] = {
1582 { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1583 #define QEMU_OPTIONS_GENERATE_OPTIONS
1584 #include "qemu-options-wrapper.h"
1585 { NULL },
1588 typedef struct VGAInterfaceInfo {
1589 const char *opt_name; /* option name */
1590 const char *name; /* human-readable name */
1591 /* Class names indicating that support is available.
1592 * If no class is specified, the interface is always available */
1593 const char *class_names[2];
1594 } VGAInterfaceInfo;
1596 static const VGAInterfaceInfo vga_interfaces[VGA_TYPE_MAX] = {
1597 [VGA_NONE] = {
1598 .opt_name = "none",
1599 .name = "no graphic card",
1601 [VGA_STD] = {
1602 .opt_name = "std",
1603 .name = "standard VGA",
1604 .class_names = { "VGA", "isa-vga" },
1606 [VGA_CIRRUS] = {
1607 .opt_name = "cirrus",
1608 .name = "Cirrus VGA",
1609 .class_names = { "cirrus-vga", "isa-cirrus-vga" },
1611 [VGA_VMWARE] = {
1612 .opt_name = "vmware",
1613 .name = "VMWare SVGA",
1614 .class_names = { "vmware-svga" },
1616 [VGA_VIRTIO] = {
1617 .opt_name = "virtio",
1618 .name = "Virtio VGA",
1619 .class_names = { "virtio-vga" },
1621 [VGA_QXL] = {
1622 .opt_name = "qxl",
1623 .name = "QXL VGA",
1624 .class_names = { "qxl-vga" },
1626 [VGA_TCX] = {
1627 .opt_name = "tcx",
1628 .name = "TCX framebuffer",
1629 .class_names = { "SUNW,tcx" },
1631 [VGA_CG3] = {
1632 .opt_name = "cg3",
1633 .name = "CG3 framebuffer",
1634 .class_names = { "cgthree" },
1636 [VGA_XENFB] = {
1637 .opt_name = "xenfb",
1638 .name = "Xen paravirtualized framebuffer",
1642 static bool vga_interface_available(VGAInterfaceType t)
1644 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1646 assert(t < VGA_TYPE_MAX);
1647 return !ti->class_names[0] ||
1648 module_object_class_by_name(ti->class_names[0]) ||
1649 module_object_class_by_name(ti->class_names[1]);
1652 static const char *
1653 get_default_vga_model(const MachineClass *machine_class)
1655 if (machine_class->default_display) {
1656 return machine_class->default_display;
1657 } else if (vga_interface_available(VGA_CIRRUS)) {
1658 return "cirrus";
1659 } else if (vga_interface_available(VGA_STD)) {
1660 return "std";
1663 return NULL;
1666 static void select_vgahw(const MachineClass *machine_class, const char *p)
1668 const char *opts;
1669 int t;
1671 if (g_str_equal(p, "help")) {
1672 const char *def = get_default_vga_model(machine_class);
1674 for (t = 0; t < VGA_TYPE_MAX; t++) {
1675 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1677 if (vga_interface_available(t) && ti->opt_name) {
1678 printf("%-20s %s%s\n", ti->opt_name, ti->name ?: "",
1679 g_str_equal(ti->opt_name, def) ? " (default)" : "");
1682 exit(0);
1685 assert(vga_interface_type == VGA_NONE);
1686 for (t = 0; t < VGA_TYPE_MAX; t++) {
1687 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1688 if (ti->opt_name && strstart(p, ti->opt_name, &opts)) {
1689 if (!vga_interface_available(t)) {
1690 error_report("%s not available", ti->name);
1691 exit(1);
1693 vga_interface_type = t;
1694 break;
1697 if (t == VGA_TYPE_MAX) {
1698 invalid_vga:
1699 error_report("unknown vga type: %s", p);
1700 exit(1);
1702 while (*opts) {
1703 const char *nextopt;
1705 if (strstart(opts, ",retrace=", &nextopt)) {
1706 opts = nextopt;
1707 if (strstart(opts, "dumb", &nextopt))
1708 vga_retrace_method = VGA_RETRACE_DUMB;
1709 else if (strstart(opts, "precise", &nextopt))
1710 vga_retrace_method = VGA_RETRACE_PRECISE;
1711 else goto invalid_vga;
1712 } else goto invalid_vga;
1713 opts = nextopt;
1717 static void parse_display_qapi(const char *optarg)
1719 DisplayOptions *opts;
1720 Visitor *v;
1722 v = qobject_input_visitor_new_str(optarg, "type", &error_fatal);
1724 visit_type_DisplayOptions(v, NULL, &opts, &error_fatal);
1725 QAPI_CLONE_MEMBERS(DisplayOptions, &dpy, opts);
1727 qapi_free_DisplayOptions(opts);
1728 visit_free(v);
1731 DisplayOptions *qmp_query_display_options(Error **errp)
1733 return QAPI_CLONE(DisplayOptions, &dpy);
1736 static void parse_display(const char *p)
1738 const char *opts;
1740 if (is_help_option(p)) {
1741 qemu_display_help();
1742 exit(0);
1745 if (strstart(p, "sdl", &opts)) {
1747 * sdl DisplayType needs hand-crafted parser instead of
1748 * parse_display_qapi() due to some options not in
1749 * DisplayOptions, specifically:
1750 * - frame
1751 * Already deprecated.
1752 * - ctrl_grab + alt_grab
1753 * Not clear yet what happens to them long-term. Should
1754 * replaced by something better or deprecated and dropped.
1756 dpy.type = DISPLAY_TYPE_SDL;
1757 while (*opts) {
1758 const char *nextopt;
1760 if (strstart(opts, ",alt_grab=", &nextopt)) {
1761 opts = nextopt;
1762 if (strstart(opts, "on", &nextopt)) {
1763 alt_grab = 1;
1764 } else if (strstart(opts, "off", &nextopt)) {
1765 alt_grab = 0;
1766 } else {
1767 goto invalid_sdl_args;
1769 } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
1770 opts = nextopt;
1771 if (strstart(opts, "on", &nextopt)) {
1772 ctrl_grab = 1;
1773 } else if (strstart(opts, "off", &nextopt)) {
1774 ctrl_grab = 0;
1775 } else {
1776 goto invalid_sdl_args;
1778 } else if (strstart(opts, ",window_close=", &nextopt)) {
1779 opts = nextopt;
1780 dpy.has_window_close = true;
1781 if (strstart(opts, "on", &nextopt)) {
1782 dpy.window_close = true;
1783 } else if (strstart(opts, "off", &nextopt)) {
1784 dpy.window_close = false;
1785 } else {
1786 goto invalid_sdl_args;
1788 } else if (strstart(opts, ",show-cursor=", &nextopt)) {
1789 opts = nextopt;
1790 dpy.has_show_cursor = true;
1791 if (strstart(opts, "on", &nextopt)) {
1792 dpy.show_cursor = true;
1793 } else if (strstart(opts, "off", &nextopt)) {
1794 dpy.show_cursor = false;
1795 } else {
1796 goto invalid_sdl_args;
1798 } else if (strstart(opts, ",gl=", &nextopt)) {
1799 opts = nextopt;
1800 dpy.has_gl = true;
1801 if (strstart(opts, "on", &nextopt)) {
1802 dpy.gl = DISPLAYGL_MODE_ON;
1803 } else if (strstart(opts, "core", &nextopt)) {
1804 dpy.gl = DISPLAYGL_MODE_CORE;
1805 } else if (strstart(opts, "es", &nextopt)) {
1806 dpy.gl = DISPLAYGL_MODE_ES;
1807 } else if (strstart(opts, "off", &nextopt)) {
1808 dpy.gl = DISPLAYGL_MODE_OFF;
1809 } else {
1810 goto invalid_sdl_args;
1812 } else {
1813 invalid_sdl_args:
1814 error_report("invalid SDL option string");
1815 exit(1);
1817 opts = nextopt;
1819 } else if (strstart(p, "vnc", &opts)) {
1821 * vnc isn't a (local) DisplayType but a protocol for remote
1822 * display access.
1824 if (*opts == '=') {
1825 vnc_parse(opts + 1, &error_fatal);
1826 } else {
1827 error_report("VNC requires a display argument vnc=<display>");
1828 exit(1);
1830 } else {
1831 parse_display_qapi(p);
1835 static inline bool nonempty_str(const char *str)
1837 return str && *str;
1840 static int parse_fw_cfg(void *opaque, QemuOpts *opts, Error **errp)
1842 gchar *buf;
1843 size_t size;
1844 const char *name, *file, *str, *gen_id;
1845 FWCfgState *fw_cfg = (FWCfgState *) opaque;
1847 if (fw_cfg == NULL) {
1848 error_setg(errp, "fw_cfg device not available");
1849 return -1;
1851 name = qemu_opt_get(opts, "name");
1852 file = qemu_opt_get(opts, "file");
1853 str = qemu_opt_get(opts, "string");
1854 gen_id = qemu_opt_get(opts, "gen_id");
1856 /* we need the name, and exactly one of: file, content string, gen_id */
1857 if (!nonempty_str(name) ||
1858 nonempty_str(file) + nonempty_str(str) + nonempty_str(gen_id) != 1) {
1859 error_setg(errp, "name, plus exactly one of file,"
1860 " string and gen_id, are needed");
1861 return -1;
1863 if (strlen(name) > FW_CFG_MAX_FILE_PATH - 1) {
1864 error_setg(errp, "name too long (max. %d char)",
1865 FW_CFG_MAX_FILE_PATH - 1);
1866 return -1;
1868 if (nonempty_str(gen_id)) {
1870 * In this particular case where the content is populated
1871 * internally, the "etc/" namespace protection is relaxed,
1872 * so do not emit a warning.
1874 } else if (strncmp(name, "opt/", 4) != 0) {
1875 warn_report("externally provided fw_cfg item names "
1876 "should be prefixed with \"opt/\"");
1878 if (nonempty_str(str)) {
1879 size = strlen(str); /* NUL terminator NOT included in fw_cfg blob */
1880 buf = g_memdup(str, size);
1881 } else if (nonempty_str(gen_id)) {
1882 if (!fw_cfg_add_from_generator(fw_cfg, name, gen_id, errp)) {
1883 return -1;
1885 return 0;
1886 } else {
1887 GError *err = NULL;
1888 if (!g_file_get_contents(file, &buf, &size, &err)) {
1889 error_setg(errp, "can't load %s: %s", file, err->message);
1890 g_error_free(err);
1891 return -1;
1894 /* For legacy, keep user files in a specific global order. */
1895 fw_cfg_set_order_override(fw_cfg, FW_CFG_ORDER_OVERRIDE_USER);
1896 fw_cfg_add_file(fw_cfg, name, buf, size);
1897 fw_cfg_reset_order_override(fw_cfg);
1898 return 0;
1901 static int device_help_func(void *opaque, QemuOpts *opts, Error **errp)
1903 return qdev_device_help(opts);
1906 static int device_init_func(void *opaque, QemuOpts *opts, Error **errp)
1908 DeviceState *dev;
1910 dev = qdev_device_add(opts, errp);
1911 if (!dev && *errp) {
1912 error_report_err(*errp);
1913 return -1;
1914 } else if (dev) {
1915 object_unref(OBJECT(dev));
1917 return 0;
1920 static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)
1922 Error *local_err = NULL;
1924 if (!qemu_chr_new_from_opts(opts, NULL, &local_err)) {
1925 if (local_err) {
1926 error_propagate(errp, local_err);
1927 return -1;
1929 exit(0);
1931 return 0;
1934 #ifdef CONFIG_VIRTFS
1935 static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp)
1937 return qemu_fsdev_add(opts, errp);
1939 #endif
1941 static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp)
1943 return monitor_init_opts(opts, errp);
1946 static void monitor_parse(const char *optarg, const char *mode, bool pretty)
1948 static int monitor_device_index = 0;
1949 QemuOpts *opts;
1950 const char *p;
1951 char label[32];
1953 if (strstart(optarg, "chardev:", &p)) {
1954 snprintf(label, sizeof(label), "%s", p);
1955 } else {
1956 snprintf(label, sizeof(label), "compat_monitor%d",
1957 monitor_device_index);
1958 opts = qemu_chr_parse_compat(label, optarg, true);
1959 if (!opts) {
1960 error_report("parse error: %s", optarg);
1961 exit(1);
1965 opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &error_fatal);
1966 qemu_opt_set(opts, "mode", mode, &error_abort);
1967 qemu_opt_set(opts, "chardev", label, &error_abort);
1968 if (!strcmp(mode, "control")) {
1969 qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);
1970 } else {
1971 assert(pretty == false);
1973 monitor_device_index++;
1976 struct device_config {
1977 enum {
1978 DEV_USB, /* -usbdevice */
1979 DEV_SERIAL, /* -serial */
1980 DEV_PARALLEL, /* -parallel */
1981 DEV_DEBUGCON, /* -debugcon */
1982 DEV_GDB, /* -gdb, -s */
1983 DEV_SCLP, /* s390 sclp */
1984 } type;
1985 const char *cmdline;
1986 Location loc;
1987 QTAILQ_ENTRY(device_config) next;
1990 static QTAILQ_HEAD(, device_config) device_configs =
1991 QTAILQ_HEAD_INITIALIZER(device_configs);
1993 static void add_device_config(int type, const char *cmdline)
1995 struct device_config *conf;
1997 conf = g_malloc0(sizeof(*conf));
1998 conf->type = type;
1999 conf->cmdline = cmdline;
2000 loc_save(&conf->loc);
2001 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2004 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2006 struct device_config *conf;
2007 int rc;
2009 QTAILQ_FOREACH(conf, &device_configs, next) {
2010 if (conf->type != type)
2011 continue;
2012 loc_push_restore(&conf->loc);
2013 rc = func(conf->cmdline);
2014 loc_pop(&conf->loc);
2015 if (rc) {
2016 return rc;
2019 return 0;
2022 static void qemu_disable_default_devices(void)
2024 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2026 qemu_opts_foreach(qemu_find_opts("device"),
2027 default_driver_check, NULL, NULL);
2028 qemu_opts_foreach(qemu_find_opts("global"),
2029 default_driver_check, NULL, NULL);
2031 if (!vga_model && !default_vga) {
2032 vga_interface_type = VGA_DEVICE;
2034 if (!has_defaults || machine_class->no_serial) {
2035 default_serial = 0;
2037 if (!has_defaults || machine_class->no_parallel) {
2038 default_parallel = 0;
2040 if (!has_defaults || machine_class->no_floppy) {
2041 default_floppy = 0;
2043 if (!has_defaults || machine_class->no_cdrom) {
2044 default_cdrom = 0;
2046 if (!has_defaults || machine_class->no_sdcard) {
2047 default_sdcard = 0;
2049 if (!has_defaults) {
2050 default_monitor = 0;
2051 default_net = 0;
2052 default_vga = 0;
2056 static void qemu_create_default_devices(void)
2058 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2060 if (is_daemonized()) {
2061 /* According to documentation and historically, -nographic redirects
2062 * serial port, parallel port and monitor to stdio, which does not work
2063 * with -daemonize. We can redirect these to null instead, but since
2064 * -nographic is legacy, let's just error out.
2065 * We disallow -nographic only if all other ports are not redirected
2066 * explicitly, to not break existing legacy setups which uses
2067 * -nographic _and_ redirects all ports explicitly - this is valid
2068 * usage, -nographic is just a no-op in this case.
2070 if (nographic
2071 && (default_parallel || default_serial || default_monitor)) {
2072 error_report("-nographic cannot be used with -daemonize");
2073 exit(1);
2077 if (nographic) {
2078 if (default_parallel)
2079 add_device_config(DEV_PARALLEL, "null");
2080 if (default_serial && default_monitor) {
2081 add_device_config(DEV_SERIAL, "mon:stdio");
2082 } else {
2083 if (default_serial)
2084 add_device_config(DEV_SERIAL, "stdio");
2085 if (default_monitor)
2086 monitor_parse("stdio", "readline", false);
2088 } else {
2089 if (default_serial)
2090 add_device_config(DEV_SERIAL, "vc:80Cx24C");
2091 if (default_parallel)
2092 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
2093 if (default_monitor)
2094 monitor_parse("vc:80Cx24C", "readline", false);
2097 if (default_net) {
2098 QemuOptsList *net = qemu_find_opts("net");
2099 qemu_opts_parse(net, "nic", true, &error_abort);
2100 #ifdef CONFIG_SLIRP
2101 qemu_opts_parse(net, "user", true, &error_abort);
2102 #endif
2105 #if defined(CONFIG_VNC)
2106 if (!QTAILQ_EMPTY(&(qemu_find_opts("vnc")->head))) {
2107 display_remote++;
2109 #endif
2110 if (dpy.type == DISPLAY_TYPE_DEFAULT && !display_remote) {
2111 if (!qemu_display_find_default(&dpy)) {
2112 dpy.type = DISPLAY_TYPE_NONE;
2113 #if defined(CONFIG_VNC)
2114 vnc_parse("localhost:0,to=99,id=default", &error_abort);
2115 #endif
2118 if (dpy.type == DISPLAY_TYPE_DEFAULT) {
2119 dpy.type = DISPLAY_TYPE_NONE;
2122 /* If no default VGA is requested, the default is "none". */
2123 if (default_vga) {
2124 vga_model = get_default_vga_model(machine_class);
2126 if (vga_model) {
2127 select_vgahw(machine_class, vga_model);
2131 static int serial_parse(const char *devname)
2133 int index = num_serial_hds;
2134 char label[32];
2136 if (strcmp(devname, "none") == 0)
2137 return 0;
2138 snprintf(label, sizeof(label), "serial%d", index);
2139 serial_hds = g_renew(Chardev *, serial_hds, index + 1);
2141 serial_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2142 if (!serial_hds[index]) {
2143 error_report("could not connect serial device"
2144 " to character backend '%s'", devname);
2145 return -1;
2147 num_serial_hds++;
2148 return 0;
2151 Chardev *serial_hd(int i)
2153 assert(i >= 0);
2154 if (i < num_serial_hds) {
2155 return serial_hds[i];
2157 return NULL;
2160 static int parallel_parse(const char *devname)
2162 static int index = 0;
2163 char label[32];
2165 if (strcmp(devname, "none") == 0)
2166 return 0;
2167 if (index == MAX_PARALLEL_PORTS) {
2168 error_report("too many parallel ports");
2169 exit(1);
2171 snprintf(label, sizeof(label), "parallel%d", index);
2172 parallel_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2173 if (!parallel_hds[index]) {
2174 error_report("could not connect parallel device"
2175 " to character backend '%s'", devname);
2176 return -1;
2178 index++;
2179 return 0;
2182 static int debugcon_parse(const char *devname)
2184 QemuOpts *opts;
2186 if (!qemu_chr_new_mux_mon("debugcon", devname, NULL)) {
2187 error_report("invalid character backend '%s'", devname);
2188 exit(1);
2190 opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2191 if (!opts) {
2192 error_report("already have a debugcon device");
2193 exit(1);
2195 qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);
2196 qemu_opt_set(opts, "chardev", "debugcon", &error_abort);
2197 return 0;
2200 static gint machine_class_cmp(gconstpointer a, gconstpointer b)
2202 const MachineClass *mc1 = a, *mc2 = b;
2203 int res;
2205 if (mc1->family == NULL) {
2206 if (mc2->family == NULL) {
2207 /* Compare standalone machine types against each other; they sort
2208 * in increasing order.
2210 return strcmp(object_class_get_name(OBJECT_CLASS(mc1)),
2211 object_class_get_name(OBJECT_CLASS(mc2)));
2214 /* Standalone machine types sort after families. */
2215 return 1;
2218 if (mc2->family == NULL) {
2219 /* Families sort before standalone machine types. */
2220 return -1;
2223 /* Families sort between each other alphabetically increasingly. */
2224 res = strcmp(mc1->family, mc2->family);
2225 if (res != 0) {
2226 return res;
2229 /* Within the same family, machine types sort in decreasing order. */
2230 return strcmp(object_class_get_name(OBJECT_CLASS(mc2)),
2231 object_class_get_name(OBJECT_CLASS(mc1)));
2234 static MachineClass *machine_parse(const char *name, GSList *machines)
2236 MachineClass *mc;
2237 GSList *el;
2239 if (is_help_option(name)) {
2240 printf("Supported machines are:\n");
2241 machines = g_slist_sort(machines, machine_class_cmp);
2242 for (el = machines; el; el = el->next) {
2243 MachineClass *mc = el->data;
2244 if (mc->alias) {
2245 printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
2247 printf("%-20s %s%s%s\n", mc->name, mc->desc,
2248 mc->is_default ? " (default)" : "",
2249 mc->deprecation_reason ? " (deprecated)" : "");
2251 exit(0);
2254 mc = find_machine(name, machines);
2255 if (!mc) {
2256 error_report("unsupported machine type");
2257 error_printf("Use -machine help to list supported machines\n");
2258 exit(1);
2260 return mc;
2263 void qemu_add_exit_notifier(Notifier *notify)
2265 notifier_list_add(&exit_notifiers, notify);
2268 void qemu_remove_exit_notifier(Notifier *notify)
2270 notifier_remove(notify);
2273 static void qemu_run_exit_notifiers(void)
2275 notifier_list_notify(&exit_notifiers, NULL);
2278 static const char *pid_file;
2279 static Notifier qemu_unlink_pidfile_notifier;
2281 static void qemu_unlink_pidfile(Notifier *n, void *data)
2283 if (pid_file) {
2284 unlink(pid_file);
2288 static const QEMUOption *lookup_opt(int argc, char **argv,
2289 const char **poptarg, int *poptind)
2291 const QEMUOption *popt;
2292 int optind = *poptind;
2293 char *r = argv[optind];
2294 const char *optarg;
2296 loc_set_cmdline(argv, optind, 1);
2297 optind++;
2298 /* Treat --foo the same as -foo. */
2299 if (r[1] == '-')
2300 r++;
2301 popt = qemu_options;
2302 for(;;) {
2303 if (!popt->name) {
2304 error_report("invalid option");
2305 exit(1);
2307 if (!strcmp(popt->name, r + 1))
2308 break;
2309 popt++;
2311 if (popt->flags & HAS_ARG) {
2312 if (optind >= argc) {
2313 error_report("requires an argument");
2314 exit(1);
2316 optarg = argv[optind++];
2317 loc_set_cmdline(argv, optind - 2, 2);
2318 } else {
2319 optarg = NULL;
2322 *poptarg = optarg;
2323 *poptind = optind;
2325 return popt;
2328 static MachineClass *select_machine(void)
2330 GSList *machines = object_class_get_list(TYPE_MACHINE, false);
2331 MachineClass *machine_class = find_default_machine(machines);
2332 const char *optarg;
2333 QemuOpts *opts;
2334 Location loc;
2336 loc_push_none(&loc);
2338 opts = qemu_get_machine_opts();
2339 qemu_opts_loc_restore(opts);
2341 optarg = qemu_opt_get(opts, "type");
2342 if (optarg) {
2343 machine_class = machine_parse(optarg, machines);
2346 if (!machine_class) {
2347 error_report("No machine specified, and there is no default");
2348 error_printf("Use -machine help to list supported machines\n");
2349 exit(1);
2352 loc_pop(&loc);
2353 g_slist_free(machines);
2354 return machine_class;
2357 static int object_parse_property_opt(Object *obj,
2358 const char *name, const char *value,
2359 const char *skip, Error **errp)
2361 if (g_str_equal(name, skip)) {
2362 return 0;
2365 if (!object_property_parse(obj, name, value, errp)) {
2366 return -1;
2369 return 0;
2372 static int machine_set_property(void *opaque,
2373 const char *name, const char *value,
2374 Error **errp)
2376 g_autofree char *qom_name = g_strdup(name);
2377 char *p;
2379 for (p = qom_name; *p; p++) {
2380 if (*p == '_') {
2381 *p = '-';
2385 /* Legacy options do not correspond to MachineState properties. */
2386 if (g_str_equal(qom_name, "accel")) {
2387 return 0;
2389 if (g_str_equal(qom_name, "igd-passthru")) {
2390 object_register_sugar_prop(ACCEL_CLASS_NAME("xen"), qom_name, value);
2391 return 0;
2393 if (g_str_equal(qom_name, "kvm-shadow-mem")) {
2394 object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), qom_name, value);
2395 return 0;
2397 if (g_str_equal(qom_name, "kernel-irqchip")) {
2398 object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), qom_name, value);
2399 object_register_sugar_prop(ACCEL_CLASS_NAME("whpx"), qom_name, value);
2400 return 0;
2403 return object_parse_property_opt(opaque, name, value, "type", errp);
2407 * Initial object creation happens before all other
2408 * QEMU data types are created. The majority of objects
2409 * can be created at this point. The rng-egd object
2410 * cannot be created here, as it depends on the chardev
2411 * already existing.
2413 static bool object_create_early(const char *type, QemuOpts *opts)
2415 if (user_creatable_print_help(type, opts)) {
2416 exit(0);
2420 * Objects should not be made "delayed" without a reason. If you
2421 * add one, state the reason in a comment!
2424 /* Reason: rng-egd property "chardev" */
2425 if (g_str_equal(type, "rng-egd")) {
2426 return false;
2429 #if defined(CONFIG_VHOST_USER) && defined(CONFIG_LINUX)
2430 /* Reason: cryptodev-vhost-user property "chardev" */
2431 if (g_str_equal(type, "cryptodev-vhost-user")) {
2432 return false;
2434 #endif
2436 /* Reason: vhost-user-blk-server property "node-name" */
2437 if (g_str_equal(type, "vhost-user-blk-server")) {
2438 return false;
2441 * Reason: filter-* property "netdev" etc.
2443 if (g_str_equal(type, "filter-buffer") ||
2444 g_str_equal(type, "filter-dump") ||
2445 g_str_equal(type, "filter-mirror") ||
2446 g_str_equal(type, "filter-redirector") ||
2447 g_str_equal(type, "colo-compare") ||
2448 g_str_equal(type, "filter-rewriter") ||
2449 g_str_equal(type, "filter-replay")) {
2450 return false;
2453 /* Memory allocation by backends needs to be done
2454 * after configure_accelerator() (due to the tcg_enabled()
2455 * checks at memory_region_init_*()).
2457 * Also, allocation of large amounts of memory may delay
2458 * chardev initialization for too long, and trigger timeouts
2459 * on software that waits for a monitor socket to be created
2460 * (e.g. libvirt).
2462 if (g_str_has_prefix(type, "memory-backend-")) {
2463 return false;
2466 return true;
2469 static void qemu_apply_machine_options(void)
2471 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2472 QemuOpts *machine_opts = qemu_get_machine_opts();
2473 const char *boot_order = NULL;
2474 const char *boot_once = NULL;
2475 QemuOpts *opts;
2477 qemu_opt_foreach(machine_opts, machine_set_property, current_machine,
2478 &error_fatal);
2479 current_machine->ram_size = ram_size;
2480 current_machine->maxram_size = maxram_size;
2481 current_machine->ram_slots = ram_slots;
2483 opts = qemu_opts_find(qemu_find_opts("boot-opts"), NULL);
2484 if (opts) {
2485 boot_order = qemu_opt_get(opts, "order");
2486 if (boot_order) {
2487 validate_bootdevices(boot_order, &error_fatal);
2490 boot_once = qemu_opt_get(opts, "once");
2491 if (boot_once) {
2492 validate_bootdevices(boot_once, &error_fatal);
2495 boot_menu = qemu_opt_get_bool(opts, "menu", boot_menu);
2496 boot_strict = qemu_opt_get_bool(opts, "strict", false);
2499 if (!boot_order) {
2500 boot_order = machine_class->default_boot_order;
2503 current_machine->boot_order = boot_order;
2504 current_machine->boot_once = boot_once;
2506 if (semihosting_enabled() && !semihosting_get_argc()) {
2507 const char *kernel_filename = qemu_opt_get(machine_opts, "kernel");
2508 const char *kernel_cmdline = qemu_opt_get(machine_opts, "append") ?: "";
2509 /* fall back to the -kernel/-append */
2510 semihosting_arg_fallback(kernel_filename, kernel_cmdline);
2514 static void qemu_create_early_backends(void)
2516 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2518 if ((alt_grab || ctrl_grab) && dpy.type != DISPLAY_TYPE_SDL) {
2519 error_report("-alt-grab and -ctrl-grab are only valid "
2520 "for SDL, ignoring option");
2522 if (dpy.has_window_close &&
2523 (dpy.type != DISPLAY_TYPE_GTK && dpy.type != DISPLAY_TYPE_SDL)) {
2524 error_report("-no-quit is only valid for GTK and SDL, "
2525 "ignoring option");
2528 qemu_display_early_init(&dpy);
2529 qemu_console_early_init();
2531 if (dpy.has_gl && dpy.gl != DISPLAYGL_MODE_OFF && display_opengl == 0) {
2532 #if defined(CONFIG_OPENGL)
2533 error_report("OpenGL is not supported by the display");
2534 #else
2535 error_report("OpenGL support is disabled");
2536 #endif
2537 exit(1);
2540 qemu_opts_foreach(qemu_find_opts("object"),
2541 user_creatable_add_opts_foreach,
2542 object_create_early, &error_fatal);
2544 /* spice needs the timers to be initialized by this point */
2545 /* spice must initialize before audio as it changes the default auiodev */
2546 /* spice must initialize before chardevs (for spicevmc and spiceport) */
2547 qemu_spice.init();
2549 qemu_opts_foreach(qemu_find_opts("chardev"),
2550 chardev_init_func, NULL, &error_fatal);
2552 #ifdef CONFIG_VIRTFS
2553 qemu_opts_foreach(qemu_find_opts("fsdev"),
2554 fsdev_init_func, NULL, &error_fatal);
2555 #endif
2558 * Note: we need to create audio and block backends before
2559 * machine_set_property(), so machine properties can refer to
2560 * them.
2562 configure_blockdev(&bdo_queue, machine_class, snapshot);
2563 audio_init_audiodevs();
2568 * The remainder of object creation happens after the
2569 * creation of chardev, fsdev, net clients and device data types.
2571 static bool object_create_late(const char *type, QemuOpts *opts)
2573 return !object_create_early(type, opts);
2576 static void qemu_create_late_backends(void)
2578 if (qtest_chrdev) {
2579 qtest_server_init(qtest_chrdev, qtest_log, &error_fatal);
2582 net_init_clients(&error_fatal);
2584 qemu_opts_foreach(qemu_find_opts("object"),
2585 user_creatable_add_opts_foreach,
2586 object_create_late, &error_fatal);
2588 if (tpm_init() < 0) {
2589 exit(1);
2592 qemu_opts_foreach(qemu_find_opts("mon"),
2593 mon_init_func, NULL, &error_fatal);
2595 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
2596 exit(1);
2597 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
2598 exit(1);
2599 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
2600 exit(1);
2602 /* now chardevs have been created we may have semihosting to connect */
2603 qemu_semihosting_connect_chardevs();
2604 qemu_semihosting_console_init();
2607 static bool have_custom_ram_size(void)
2609 QemuOpts *opts = qemu_find_opts_singleton("memory");
2610 return !!qemu_opt_get_size(opts, "size", 0);
2613 static void qemu_resolve_machine_memdev(void)
2615 if (current_machine->ram_memdev_id) {
2616 Object *backend;
2617 ram_addr_t backend_size;
2619 backend = object_resolve_path_type(current_machine->ram_memdev_id,
2620 TYPE_MEMORY_BACKEND, NULL);
2621 if (!backend) {
2622 error_report("Memory backend '%s' not found",
2623 current_machine->ram_memdev_id);
2624 exit(EXIT_FAILURE);
2626 backend_size = object_property_get_uint(backend, "size", &error_abort);
2627 if (have_custom_ram_size() && backend_size != ram_size) {
2628 error_report("Size specified by -m option must match size of "
2629 "explicitly specified 'memory-backend' property");
2630 exit(EXIT_FAILURE);
2632 if (mem_path) {
2633 error_report("'-mem-path' can't be used together with"
2634 "'-machine memory-backend'");
2635 exit(EXIT_FAILURE);
2637 ram_size = backend_size;
2640 if (!xen_enabled()) {
2641 /* On 32-bit hosts, QEMU is limited by virtual address space */
2642 if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
2643 error_report("at most 2047 MB RAM can be simulated");
2644 exit(1);
2649 static void set_memory_options(MachineClass *mc)
2651 uint64_t sz;
2652 const char *mem_str;
2653 const ram_addr_t default_ram_size = mc->default_ram_size;
2654 QemuOpts *opts = qemu_find_opts_singleton("memory");
2655 Location loc;
2657 loc_push_none(&loc);
2658 qemu_opts_loc_restore(opts);
2660 sz = 0;
2661 mem_str = qemu_opt_get(opts, "size");
2662 if (mem_str) {
2663 if (!*mem_str) {
2664 error_report("missing 'size' option value");
2665 exit(EXIT_FAILURE);
2668 sz = qemu_opt_get_size(opts, "size", ram_size);
2670 /* Fix up legacy suffix-less format */
2671 if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
2672 uint64_t overflow_check = sz;
2674 sz *= MiB;
2675 if (sz / MiB != overflow_check) {
2676 error_report("too large 'size' option value");
2677 exit(EXIT_FAILURE);
2682 /* backward compatibility behaviour for case "-m 0" */
2683 if (sz == 0) {
2684 sz = default_ram_size;
2687 sz = QEMU_ALIGN_UP(sz, 8192);
2688 if (mc->fixup_ram_size) {
2689 sz = mc->fixup_ram_size(sz);
2691 ram_size = sz;
2692 if (ram_size != sz) {
2693 error_report("ram size too large");
2694 exit(EXIT_FAILURE);
2697 /* store value for the future use */
2698 qemu_opt_set_number(opts, "size", ram_size, &error_abort);
2699 maxram_size = ram_size;
2701 if (qemu_opt_get(opts, "maxmem")) {
2702 uint64_t slots;
2704 sz = qemu_opt_get_size(opts, "maxmem", 0);
2705 slots = qemu_opt_get_number(opts, "slots", 0);
2706 if (sz < ram_size) {
2707 error_report("invalid value of -m option maxmem: "
2708 "maximum memory size (0x%" PRIx64 ") must be at least "
2709 "the initial memory size (0x" RAM_ADDR_FMT ")",
2710 sz, ram_size);
2711 exit(EXIT_FAILURE);
2712 } else if (slots && sz == ram_size) {
2713 error_report("invalid value of -m option maxmem: "
2714 "memory slots were specified but maximum memory size "
2715 "(0x%" PRIx64 ") is equal to the initial memory size "
2716 "(0x" RAM_ADDR_FMT ")", sz, ram_size);
2717 exit(EXIT_FAILURE);
2720 maxram_size = sz;
2721 ram_slots = slots;
2722 } else if (qemu_opt_get(opts, "slots")) {
2723 error_report("invalid -m option value: missing 'maxmem' option");
2724 exit(EXIT_FAILURE);
2727 loc_pop(&loc);
2730 static void qemu_create_machine(MachineClass *machine_class)
2732 object_set_machine_compat_props(machine_class->compat_props);
2734 set_memory_options(machine_class);
2736 current_machine = MACHINE(object_new_with_class(OBJECT_CLASS(machine_class)));
2737 if (machine_help_func(qemu_get_machine_opts(), current_machine)) {
2738 exit(0);
2740 object_property_add_child(object_get_root(), "machine",
2741 OBJECT(current_machine));
2742 object_property_add_child(container_get(OBJECT(current_machine),
2743 "/unattached"),
2744 "sysbus", OBJECT(sysbus_get_default()));
2746 if (machine_class->minimum_page_bits) {
2747 if (!set_preferred_target_page_bits(machine_class->minimum_page_bits)) {
2748 /* This would be a board error: specifying a minimum smaller than
2749 * a target's compile-time fixed setting.
2751 g_assert_not_reached();
2755 cpu_exec_init_all();
2756 page_size_init();
2758 if (machine_class->hw_version) {
2759 qemu_set_hw_version(machine_class->hw_version);
2762 machine_smp_parse(current_machine,
2763 qemu_opts_find(qemu_find_opts("smp-opts"), NULL), &error_fatal);
2766 * Get the default machine options from the machine if it is not already
2767 * specified either by the configuration file or by the command line.
2769 if (machine_class->default_machine_opts) {
2770 qemu_opts_set_defaults(qemu_find_opts("machine"),
2771 machine_class->default_machine_opts, 0);
2775 static int global_init_func(void *opaque, QemuOpts *opts, Error **errp)
2777 GlobalProperty *g;
2779 g = g_malloc0(sizeof(*g));
2780 g->driver = qemu_opt_get(opts, "driver");
2781 g->property = qemu_opt_get(opts, "property");
2782 g->value = qemu_opt_get(opts, "value");
2783 qdev_prop_register_global(g);
2784 return 0;
2787 static int qemu_read_default_config_file(void)
2789 int ret;
2790 g_autofree char *file = get_relocated_path(CONFIG_QEMU_CONFDIR "/qemu.conf");
2792 ret = qemu_read_config_file(file);
2793 if (ret < 0 && ret != -ENOENT) {
2794 return ret;
2797 return 0;
2800 static int qemu_set_option(const char *str)
2802 Error *local_err = NULL;
2803 char group[64], id[64], arg[64];
2804 QemuOptsList *list;
2805 QemuOpts *opts;
2806 int rc, offset;
2808 rc = sscanf(str, "%63[^.].%63[^.].%63[^=]%n", group, id, arg, &offset);
2809 if (rc < 3 || str[offset] != '=') {
2810 error_report("can't parse: \"%s\"", str);
2811 return -1;
2814 list = qemu_find_opts(group);
2815 if (list == NULL) {
2816 return -1;
2819 opts = qemu_opts_find(list, id);
2820 if (!opts) {
2821 error_report("there is no %s \"%s\" defined",
2822 list->name, id);
2823 return -1;
2826 if (!qemu_opt_set(opts, arg, str + offset + 1, &local_err)) {
2827 error_report_err(local_err);
2828 return -1;
2830 return 0;
2833 static void user_register_global_props(void)
2835 qemu_opts_foreach(qemu_find_opts("global"),
2836 global_init_func, NULL, NULL);
2839 static int do_configure_icount(void *opaque, QemuOpts *opts, Error **errp)
2841 icount_configure(opts, errp);
2842 return 0;
2845 static int accelerator_set_property(void *opaque,
2846 const char *name, const char *value,
2847 Error **errp)
2849 return object_parse_property_opt(opaque, name, value, "accel", errp);
2852 static int do_configure_accelerator(void *opaque, QemuOpts *opts, Error **errp)
2854 bool *p_init_failed = opaque;
2855 const char *acc = qemu_opt_get(opts, "accel");
2856 AccelClass *ac = accel_find(acc);
2857 AccelState *accel;
2858 int ret;
2859 bool qtest_with_kvm;
2861 qtest_with_kvm = g_str_equal(acc, "kvm") && qtest_chrdev != NULL;
2863 if (!ac) {
2864 *p_init_failed = true;
2865 if (!qtest_with_kvm) {
2866 error_report("invalid accelerator %s", acc);
2868 return 0;
2870 accel = ACCEL(object_new_with_class(OBJECT_CLASS(ac)));
2871 object_apply_compat_props(OBJECT(accel));
2872 qemu_opt_foreach(opts, accelerator_set_property,
2873 accel,
2874 &error_fatal);
2876 ret = accel_init_machine(accel, current_machine);
2877 if (ret < 0) {
2878 *p_init_failed = true;
2879 if (!qtest_with_kvm || ret != -ENOENT) {
2880 error_report("failed to initialize %s: %s", acc, strerror(-ret));
2882 return 0;
2885 return 1;
2888 static void configure_accelerators(const char *progname)
2890 const char *accel;
2891 bool init_failed = false;
2893 qemu_opts_foreach(qemu_find_opts("icount"),
2894 do_configure_icount, NULL, &error_fatal);
2896 accel = qemu_opt_get(qemu_get_machine_opts(), "accel");
2897 if (QTAILQ_EMPTY(&qemu_accel_opts.head)) {
2898 char **accel_list, **tmp;
2900 if (accel == NULL) {
2901 /* Select the default accelerator */
2902 bool have_tcg = accel_find("tcg");
2903 bool have_kvm = accel_find("kvm");
2905 if (have_tcg && have_kvm) {
2906 if (g_str_has_suffix(progname, "kvm")) {
2907 /* If the program name ends with "kvm", we prefer KVM */
2908 accel = "kvm:tcg";
2909 } else {
2910 accel = "tcg:kvm";
2912 } else if (have_kvm) {
2913 accel = "kvm";
2914 } else if (have_tcg) {
2915 accel = "tcg";
2916 } else {
2917 error_report("No accelerator selected and"
2918 " no default accelerator available");
2919 exit(1);
2922 accel_list = g_strsplit(accel, ":", 0);
2924 for (tmp = accel_list; *tmp; tmp++) {
2926 * Filter invalid accelerators here, to prevent obscenities
2927 * such as "-machine accel=tcg,,thread=single".
2929 if (accel_find(*tmp)) {
2930 qemu_opts_parse_noisily(qemu_find_opts("accel"), *tmp, true);
2931 } else {
2932 init_failed = true;
2933 error_report("invalid accelerator %s", *tmp);
2936 g_strfreev(accel_list);
2937 } else {
2938 if (accel != NULL) {
2939 error_report("The -accel and \"-machine accel=\" options are incompatible");
2940 exit(1);
2944 if (!qemu_opts_foreach(qemu_find_opts("accel"),
2945 do_configure_accelerator, &init_failed, &error_fatal)) {
2946 if (!init_failed) {
2947 error_report("no accelerator found");
2949 exit(1);
2952 if (init_failed && !qtest_chrdev) {
2953 AccelClass *ac = ACCEL_GET_CLASS(current_accel());
2954 error_report("falling back to %s", ac->name);
2957 if (icount_enabled() && !tcg_enabled()) {
2958 error_report("-icount is not allowed with hardware virtualization");
2959 exit(1);
2963 static void create_default_memdev(MachineState *ms, const char *path)
2965 Object *obj;
2966 MachineClass *mc = MACHINE_GET_CLASS(ms);
2968 obj = object_new(path ? TYPE_MEMORY_BACKEND_FILE : TYPE_MEMORY_BACKEND_RAM);
2969 if (path) {
2970 object_property_set_str(obj, "mem-path", path, &error_fatal);
2972 object_property_set_int(obj, "size", ms->ram_size, &error_fatal);
2973 object_property_add_child(object_get_objects_root(), mc->default_ram_id,
2974 obj);
2975 /* Ensure backend's memory region name is equal to mc->default_ram_id */
2976 object_property_set_bool(obj, "x-use-canonical-path-for-ramblock-id",
2977 false, &error_fatal);
2978 user_creatable_complete(USER_CREATABLE(obj), &error_fatal);
2979 object_unref(obj);
2980 object_property_set_str(OBJECT(ms), "memory-backend", mc->default_ram_id,
2981 &error_fatal);
2984 static void qemu_validate_options(void)
2986 QemuOpts *machine_opts = qemu_get_machine_opts();
2987 const char *kernel_filename = qemu_opt_get(machine_opts, "kernel");
2988 const char *initrd_filename = qemu_opt_get(machine_opts, "initrd");
2989 const char *kernel_cmdline = qemu_opt_get(machine_opts, "append");
2991 if (kernel_filename == NULL) {
2992 if (kernel_cmdline != NULL) {
2993 error_report("-append only allowed with -kernel option");
2994 exit(1);
2997 if (initrd_filename != NULL) {
2998 error_report("-initrd only allowed with -kernel option");
2999 exit(1);
3003 if (loadvm && preconfig_requested) {
3004 error_report("'preconfig' and 'loadvm' options are "
3005 "mutually exclusive");
3006 exit(EXIT_FAILURE);
3008 if (incoming && preconfig_requested) {
3009 error_report("'preconfig' and 'incoming' options are "
3010 "mutually exclusive");
3011 exit(EXIT_FAILURE);
3014 #ifdef CONFIG_CURSES
3015 if (is_daemonized() && dpy.type == DISPLAY_TYPE_CURSES) {
3016 error_report("curses display cannot be used with -daemonize");
3017 exit(1);
3019 #endif
3022 static void qemu_process_sugar_options(void)
3024 if (mem_prealloc) {
3025 char *val;
3027 val = g_strdup_printf("%d",
3028 (uint32_t) qemu_opt_get_number(qemu_find_opts_singleton("smp-opts"), "cpus", 1));
3029 object_register_sugar_prop("memory-backend", "prealloc-threads", val);
3030 g_free(val);
3031 object_register_sugar_prop("memory-backend", "prealloc", "on");
3034 if (watchdog) {
3035 int i = select_watchdog(watchdog);
3036 if (i > 0)
3037 exit (i == 1 ? 1 : 0);
3041 static void qemu_process_early_options(void)
3043 #ifdef CONFIG_SECCOMP
3044 QemuOptsList *olist = qemu_find_opts_err("sandbox", NULL);
3045 if (olist) {
3046 qemu_opts_foreach(olist, parse_sandbox, NULL, &error_fatal);
3048 #endif
3050 qemu_opts_foreach(qemu_find_opts("name"),
3051 parse_name, NULL, &error_fatal);
3053 #ifndef _WIN32
3054 qemu_opts_foreach(qemu_find_opts("add-fd"),
3055 parse_add_fd, NULL, &error_fatal);
3057 qemu_opts_foreach(qemu_find_opts("add-fd"),
3058 cleanup_add_fd, NULL, &error_fatal);
3059 #endif
3061 if (!trace_init_backends()) {
3062 exit(1);
3064 trace_init_file();
3066 /* Open the logfile at this point and set the log mask if necessary. */
3067 qemu_set_log_filename(log_file, &error_fatal);
3068 if (log_mask) {
3069 int mask;
3070 mask = qemu_str_to_log_mask(log_mask);
3071 if (!mask) {
3072 qemu_print_log_usage(stdout);
3073 exit(1);
3075 qemu_set_log(mask);
3076 } else {
3077 qemu_set_log(0);
3080 qemu_add_default_firmwarepath();
3083 static void qemu_process_help_options(void)
3086 * Check for -cpu help and -device help before we call select_machine(),
3087 * which will return an error if the architecture has no default machine
3088 * type and the user did not specify one, so that the user doesn't need
3089 * to say '-cpu help -machine something'.
3091 if (cpu_option && is_help_option(cpu_option)) {
3092 list_cpus(cpu_option);
3093 exit(0);
3096 if (qemu_opts_foreach(qemu_find_opts("device"),
3097 device_help_func, NULL, NULL)) {
3098 exit(0);
3101 /* -L help lists the data directories and exits. */
3102 if (list_data_dirs) {
3103 qemu_list_data_dirs();
3104 exit(0);
3108 static void qemu_maybe_daemonize(const char *pid_file)
3110 Error *err;
3112 os_daemonize();
3113 rcu_disable_atfork();
3115 if (pid_file && !qemu_write_pidfile(pid_file, &err)) {
3116 error_reportf_err(err, "cannot create PID file: ");
3117 exit(1);
3120 qemu_unlink_pidfile_notifier.notify = qemu_unlink_pidfile;
3121 qemu_add_exit_notifier(&qemu_unlink_pidfile_notifier);
3124 static void qemu_init_subsystems(void)
3126 Error *err;
3128 os_set_line_buffering();
3130 module_call_init(MODULE_INIT_TRACE);
3132 qemu_init_cpu_list();
3133 qemu_init_cpu_loop();
3134 qemu_mutex_lock_iothread();
3136 atexit(qemu_run_exit_notifiers);
3138 module_call_init(MODULE_INIT_QOM);
3139 module_call_init(MODULE_INIT_MIGRATION);
3141 runstate_init();
3142 precopy_infrastructure_init();
3143 postcopy_infrastructure_init();
3144 monitor_init_globals();
3146 if (qcrypto_init(&err) < 0) {
3147 error_reportf_err(err, "cannot initialize crypto: ");
3148 exit(1);
3151 os_setup_early_signal_handling();
3153 bdrv_init_with_whitelist();
3154 socket_init();
3157 static void qemu_init_displays(void)
3159 DisplayState *ds;
3161 /* init local displays */
3162 ds = init_displaystate();
3163 qemu_display_init(ds, &dpy);
3165 /* must be after terminal init, SDL library changes signal handlers */
3166 os_setup_signal_handling();
3168 /* init remote displays */
3169 #ifdef CONFIG_VNC
3170 qemu_opts_foreach(qemu_find_opts("vnc"),
3171 vnc_init_func, NULL, &error_fatal);
3172 #endif
3174 if (using_spice) {
3175 qemu_spice.display_init();
3180 * Called after leaving preconfig state. From here on runstate is
3181 * RUN_STATE_PRELAUNCH or RUN_STATE_INMIGRATE.
3183 static void qemu_init_board(void)
3185 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
3187 if (machine_class->default_ram_id && current_machine->ram_size &&
3188 numa_uses_legacy_mem() && !current_machine->ram_memdev_id) {
3189 create_default_memdev(current_machine, mem_path);
3192 /* process plugin before CPUs are created, but once -smp has been parsed */
3193 if (qemu_plugin_load_list(&plugin_list)) {
3194 exit(1);
3197 machine_run_board_init(current_machine);
3200 * TODO To drop support for deprecated bogus if=..., move
3201 * drive_check_orphaned() here, replacing this call. Also drop
3202 * its deprecation warning, along with DriveInfo member
3203 * @claimed_by_board.
3205 drive_mark_claimed_by_board();
3207 realtime_init();
3209 if (hax_enabled()) {
3210 /* FIXME: why isn't cpu_synchronize_all_post_init enough? */
3211 hax_sync_vcpus();
3215 static void qemu_create_cli_devices(void)
3217 soundhw_init();
3219 qemu_opts_foreach(qemu_find_opts("fw_cfg"),
3220 parse_fw_cfg, fw_cfg_find(), &error_fatal);
3222 /* init USB devices */
3223 if (machine_usb(current_machine)) {
3224 if (foreach_device_config(DEV_USB, usb_parse) < 0)
3225 exit(1);
3228 /* init generic devices */
3229 rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
3230 qemu_opts_foreach(qemu_find_opts("device"),
3231 device_init_func, NULL, &error_fatal);
3232 rom_reset_order_override();
3235 static void qemu_machine_creation_done(void)
3237 cpu_synchronize_all_post_init();
3239 /* Did we create any drives that we failed to create a device for? */
3240 drive_check_orphaned();
3242 /* Don't warn about the default network setup that you get if
3243 * no command line -net or -netdev options are specified. There
3244 * are two cases that we would otherwise complain about:
3245 * (1) board doesn't support a NIC but the implicit "-net nic"
3246 * requested one
3247 * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
3248 * sets up a nic that isn't connected to anything.
3250 if (!default_net && (!qtest_enabled() || has_defaults)) {
3251 net_check_clients();
3254 qdev_prop_check_globals();
3256 if (current_machine->boot_once) {
3257 qemu_boot_set(current_machine->boot_once, &error_fatal);
3258 qemu_register_reset(restore_boot_order, g_strdup(current_machine->boot_order));
3261 if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
3262 exit(1);
3265 qdev_machine_creation_done();
3267 /* TODO: once all bus devices are qdevified, this should be done
3268 * when bus is created by qdev.c */
3270 * TODO: If we had a main 'reset container' that the whole system
3271 * lived in, we could reset that using the multi-phase reset
3272 * APIs. For the moment, we just reset the sysbus, which will cause
3273 * all devices hanging off it (and all their child buses, recursively)
3274 * to be reset. Note that this will *not* reset any Device objects
3275 * which are not attached to some part of the qbus tree!
3277 qemu_register_reset(resettable_cold_reset_fn, sysbus_get_default());
3278 qemu_run_machine_init_done_notifiers();
3280 if (rom_check_and_register_reset() != 0) {
3281 error_report("rom check and register reset failed");
3282 exit(1);
3285 replay_start();
3287 /* This checkpoint is required by replay to separate prior clock
3288 reading from the other reads, because timer polling functions query
3289 clock values from the log. */
3290 replay_checkpoint(CHECKPOINT_RESET);
3291 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
3292 register_global_state();
3295 void qemu_init(int argc, char **argv, char **envp)
3297 QemuOpts *opts;
3298 QemuOpts *icount_opts = NULL, *accel_opts = NULL;
3299 QemuOptsList *olist;
3300 int optind;
3301 const char *optarg;
3302 MachineClass *machine_class;
3303 bool userconfig = true;
3304 FILE *vmstate_dump_file = NULL;
3306 qemu_add_opts(&qemu_drive_opts);
3307 qemu_add_drive_opts(&qemu_legacy_drive_opts);
3308 qemu_add_drive_opts(&qemu_common_drive_opts);
3309 qemu_add_drive_opts(&qemu_drive_opts);
3310 qemu_add_drive_opts(&bdrv_runtime_opts);
3311 qemu_add_opts(&qemu_chardev_opts);
3312 qemu_add_opts(&qemu_device_opts);
3313 qemu_add_opts(&qemu_netdev_opts);
3314 qemu_add_opts(&qemu_nic_opts);
3315 qemu_add_opts(&qemu_net_opts);
3316 qemu_add_opts(&qemu_rtc_opts);
3317 qemu_add_opts(&qemu_global_opts);
3318 qemu_add_opts(&qemu_mon_opts);
3319 qemu_add_opts(&qemu_trace_opts);
3320 qemu_plugin_add_opts();
3321 qemu_add_opts(&qemu_option_rom_opts);
3322 qemu_add_opts(&qemu_machine_opts);
3323 qemu_add_opts(&qemu_accel_opts);
3324 qemu_add_opts(&qemu_mem_opts);
3325 qemu_add_opts(&qemu_smp_opts);
3326 qemu_add_opts(&qemu_boot_opts);
3327 qemu_add_opts(&qemu_add_fd_opts);
3328 qemu_add_opts(&qemu_object_opts);
3329 qemu_add_opts(&qemu_tpmdev_opts);
3330 qemu_add_opts(&qemu_realtime_opts);
3331 qemu_add_opts(&qemu_overcommit_opts);
3332 qemu_add_opts(&qemu_msg_opts);
3333 qemu_add_opts(&qemu_name_opts);
3334 qemu_add_opts(&qemu_numa_opts);
3335 qemu_add_opts(&qemu_icount_opts);
3336 qemu_add_opts(&qemu_semihosting_config_opts);
3337 qemu_add_opts(&qemu_fw_cfg_opts);
3338 module_call_init(MODULE_INIT_OPTS);
3340 error_init(argv[0]);
3341 qemu_init_exec_dir(argv[0]);
3343 qemu_init_subsystems();
3345 /* first pass of option parsing */
3346 optind = 1;
3347 while (optind < argc) {
3348 if (argv[optind][0] != '-') {
3349 /* disk image */
3350 optind++;
3351 } else {
3352 const QEMUOption *popt;
3354 popt = lookup_opt(argc, argv, &optarg, &optind);
3355 switch (popt->index) {
3356 case QEMU_OPTION_nouserconfig:
3357 userconfig = false;
3358 break;
3363 if (userconfig) {
3364 if (qemu_read_default_config_file() < 0) {
3365 exit(1);
3369 /* second pass of option parsing */
3370 optind = 1;
3371 for(;;) {
3372 if (optind >= argc)
3373 break;
3374 if (argv[optind][0] != '-') {
3375 loc_set_cmdline(argv, optind, 1);
3376 drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
3377 } else {
3378 const QEMUOption *popt;
3380 popt = lookup_opt(argc, argv, &optarg, &optind);
3381 if (!(popt->arch_mask & arch_type)) {
3382 error_report("Option not supported for this target");
3383 exit(1);
3385 switch(popt->index) {
3386 case QEMU_OPTION_cpu:
3387 /* hw initialization will check this */
3388 cpu_option = optarg;
3389 break;
3390 case QEMU_OPTION_hda:
3391 case QEMU_OPTION_hdb:
3392 case QEMU_OPTION_hdc:
3393 case QEMU_OPTION_hdd:
3394 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
3395 HD_OPTS);
3396 break;
3397 case QEMU_OPTION_blockdev:
3399 Visitor *v;
3400 BlockdevOptionsQueueEntry *bdo;
3402 v = qobject_input_visitor_new_str(optarg, "driver",
3403 &error_fatal);
3405 bdo = g_new(BlockdevOptionsQueueEntry, 1);
3406 visit_type_BlockdevOptions(v, NULL, &bdo->bdo,
3407 &error_fatal);
3408 visit_free(v);
3409 loc_save(&bdo->loc);
3410 QSIMPLEQ_INSERT_TAIL(&bdo_queue, bdo, entry);
3411 break;
3413 case QEMU_OPTION_drive:
3414 if (drive_def(optarg) == NULL) {
3415 exit(1);
3417 break;
3418 case QEMU_OPTION_set:
3419 if (qemu_set_option(optarg) != 0)
3420 exit(1);
3421 break;
3422 case QEMU_OPTION_global:
3423 if (qemu_global_option(optarg) != 0)
3424 exit(1);
3425 break;
3426 case QEMU_OPTION_mtdblock:
3427 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
3428 break;
3429 case QEMU_OPTION_sd:
3430 drive_add(IF_SD, -1, optarg, SD_OPTS);
3431 break;
3432 case QEMU_OPTION_pflash:
3433 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
3434 break;
3435 case QEMU_OPTION_snapshot:
3437 Error *blocker = NULL;
3438 snapshot = 1;
3439 error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
3440 "-snapshot");
3441 replay_add_blocker(blocker);
3443 break;
3444 case QEMU_OPTION_numa:
3445 opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
3446 optarg, true);
3447 if (!opts) {
3448 exit(1);
3450 break;
3451 case QEMU_OPTION_display:
3452 parse_display(optarg);
3453 break;
3454 case QEMU_OPTION_nographic:
3455 olist = qemu_find_opts("machine");
3456 qemu_opts_parse_noisily(olist, "graphics=off", false);
3457 nographic = true;
3458 dpy.type = DISPLAY_TYPE_NONE;
3459 break;
3460 case QEMU_OPTION_curses:
3461 #ifdef CONFIG_CURSES
3462 dpy.type = DISPLAY_TYPE_CURSES;
3463 #else
3464 error_report("curses or iconv support is disabled");
3465 exit(1);
3466 #endif
3467 break;
3468 case QEMU_OPTION_portrait:
3469 graphic_rotate = 90;
3470 break;
3471 case QEMU_OPTION_rotate:
3472 graphic_rotate = strtol(optarg, (char **) &optarg, 10);
3473 if (graphic_rotate != 0 && graphic_rotate != 90 &&
3474 graphic_rotate != 180 && graphic_rotate != 270) {
3475 error_report("only 90, 180, 270 deg rotation is available");
3476 exit(1);
3478 break;
3479 case QEMU_OPTION_kernel:
3480 qemu_opts_set(qemu_find_opts("machine"), "kernel", optarg, &error_abort);
3481 break;
3482 case QEMU_OPTION_initrd:
3483 qemu_opts_set(qemu_find_opts("machine"), "initrd", optarg, &error_abort);
3484 break;
3485 case QEMU_OPTION_append:
3486 qemu_opts_set(qemu_find_opts("machine"), "append", optarg, &error_abort);
3487 break;
3488 case QEMU_OPTION_dtb:
3489 qemu_opts_set(qemu_find_opts("machine"), "dtb", optarg, &error_abort);
3490 break;
3491 case QEMU_OPTION_cdrom:
3492 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
3493 break;
3494 case QEMU_OPTION_boot:
3495 opts = qemu_opts_parse_noisily(qemu_find_opts("boot-opts"),
3496 optarg, true);
3497 if (!opts) {
3498 exit(1);
3500 break;
3501 case QEMU_OPTION_fda:
3502 case QEMU_OPTION_fdb:
3503 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
3504 optarg, FD_OPTS);
3505 break;
3506 case QEMU_OPTION_no_fd_bootchk:
3507 fd_bootchk = 0;
3508 break;
3509 case QEMU_OPTION_netdev:
3510 default_net = 0;
3511 if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
3512 exit(1);
3514 break;
3515 case QEMU_OPTION_nic:
3516 default_net = 0;
3517 if (net_client_parse(qemu_find_opts("nic"), optarg) == -1) {
3518 exit(1);
3520 break;
3521 case QEMU_OPTION_net:
3522 default_net = 0;
3523 if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
3524 exit(1);
3526 break;
3527 #ifdef CONFIG_LIBISCSI
3528 case QEMU_OPTION_iscsi:
3529 opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
3530 optarg, false);
3531 if (!opts) {
3532 exit(1);
3534 break;
3535 #endif
3536 case QEMU_OPTION_audio_help:
3537 audio_legacy_help();
3538 exit (0);
3539 break;
3540 case QEMU_OPTION_audiodev:
3541 audio_parse_option(optarg);
3542 break;
3543 case QEMU_OPTION_soundhw:
3544 select_soundhw (optarg);
3545 break;
3546 case QEMU_OPTION_h:
3547 help(0);
3548 break;
3549 case QEMU_OPTION_version:
3550 version();
3551 exit(0);
3552 break;
3553 case QEMU_OPTION_m:
3554 opts = qemu_opts_parse_noisily(qemu_find_opts("memory"),
3555 optarg, true);
3556 if (!opts) {
3557 exit(EXIT_FAILURE);
3559 break;
3560 #ifdef CONFIG_TPM
3561 case QEMU_OPTION_tpmdev:
3562 if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3563 exit(1);
3565 break;
3566 #endif
3567 case QEMU_OPTION_mempath:
3568 mem_path = optarg;
3569 break;
3570 case QEMU_OPTION_mem_prealloc:
3571 mem_prealloc = 1;
3572 break;
3573 case QEMU_OPTION_d:
3574 log_mask = optarg;
3575 break;
3576 case QEMU_OPTION_D:
3577 log_file = optarg;
3578 break;
3579 case QEMU_OPTION_DFILTER:
3580 qemu_set_dfilter_ranges(optarg, &error_fatal);
3581 break;
3582 case QEMU_OPTION_seed:
3583 qemu_guest_random_seed_main(optarg, &error_fatal);
3584 break;
3585 case QEMU_OPTION_s:
3586 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3587 break;
3588 case QEMU_OPTION_gdb:
3589 add_device_config(DEV_GDB, optarg);
3590 break;
3591 case QEMU_OPTION_L:
3592 if (is_help_option(optarg)) {
3593 list_data_dirs = true;
3594 } else {
3595 qemu_add_data_dir(g_strdup(optarg));
3597 break;
3598 case QEMU_OPTION_bios:
3599 qemu_opts_set(qemu_find_opts("machine"), "firmware", optarg, &error_abort);
3600 break;
3601 case QEMU_OPTION_singlestep:
3602 singlestep = 1;
3603 break;
3604 case QEMU_OPTION_S:
3605 autostart = 0;
3606 break;
3607 case QEMU_OPTION_k:
3608 keyboard_layout = optarg;
3609 break;
3610 case QEMU_OPTION_vga:
3611 vga_model = optarg;
3612 default_vga = 0;
3613 break;
3614 case QEMU_OPTION_g:
3616 const char *p;
3617 int w, h, depth;
3618 p = optarg;
3619 w = strtol(p, (char **)&p, 10);
3620 if (w <= 0) {
3621 graphic_error:
3622 error_report("invalid resolution or depth");
3623 exit(1);
3625 if (*p != 'x')
3626 goto graphic_error;
3627 p++;
3628 h = strtol(p, (char **)&p, 10);
3629 if (h <= 0)
3630 goto graphic_error;
3631 if (*p == 'x') {
3632 p++;
3633 depth = strtol(p, (char **)&p, 10);
3634 if (depth != 1 && depth != 2 && depth != 4 &&
3635 depth != 8 && depth != 15 && depth != 16 &&
3636 depth != 24 && depth != 32)
3637 goto graphic_error;
3638 } else if (*p == '\0') {
3639 depth = graphic_depth;
3640 } else {
3641 goto graphic_error;
3644 graphic_width = w;
3645 graphic_height = h;
3646 graphic_depth = depth;
3648 break;
3649 case QEMU_OPTION_echr:
3651 char *r;
3652 term_escape_char = strtol(optarg, &r, 0);
3653 if (r == optarg)
3654 printf("Bad argument to echr\n");
3655 break;
3657 case QEMU_OPTION_monitor:
3658 default_monitor = 0;
3659 if (strncmp(optarg, "none", 4)) {
3660 monitor_parse(optarg, "readline", false);
3662 break;
3663 case QEMU_OPTION_qmp:
3664 monitor_parse(optarg, "control", false);
3665 default_monitor = 0;
3666 break;
3667 case QEMU_OPTION_qmp_pretty:
3668 monitor_parse(optarg, "control", true);
3669 default_monitor = 0;
3670 break;
3671 case QEMU_OPTION_mon:
3672 opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
3673 true);
3674 if (!opts) {
3675 exit(1);
3677 default_monitor = 0;
3678 break;
3679 case QEMU_OPTION_chardev:
3680 opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
3681 optarg, true);
3682 if (!opts) {
3683 exit(1);
3685 break;
3686 case QEMU_OPTION_fsdev:
3687 olist = qemu_find_opts("fsdev");
3688 if (!olist) {
3689 error_report("fsdev support is disabled");
3690 exit(1);
3692 opts = qemu_opts_parse_noisily(olist, optarg, true);
3693 if (!opts) {
3694 exit(1);
3696 break;
3697 case QEMU_OPTION_virtfs: {
3698 QemuOpts *fsdev;
3699 QemuOpts *device;
3700 const char *writeout, *sock_fd, *socket, *path, *security_model,
3701 *multidevs;
3703 olist = qemu_find_opts("virtfs");
3704 if (!olist) {
3705 error_report("virtfs support is disabled");
3706 exit(1);
3708 opts = qemu_opts_parse_noisily(olist, optarg, true);
3709 if (!opts) {
3710 exit(1);
3713 if (qemu_opt_get(opts, "fsdriver") == NULL ||
3714 qemu_opt_get(opts, "mount_tag") == NULL) {
3715 error_report("Usage: -virtfs fsdriver,mount_tag=tag");
3716 exit(1);
3718 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3719 qemu_opts_id(opts) ?:
3720 qemu_opt_get(opts, "mount_tag"),
3721 1, NULL);
3722 if (!fsdev) {
3723 error_report("duplicate or invalid fsdev id: %s",
3724 qemu_opt_get(opts, "mount_tag"));
3725 exit(1);
3728 writeout = qemu_opt_get(opts, "writeout");
3729 if (writeout) {
3730 #ifdef CONFIG_SYNC_FILE_RANGE
3731 qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
3732 #else
3733 error_report("writeout=immediate not supported "
3734 "on this platform");
3735 exit(1);
3736 #endif
3738 qemu_opt_set(fsdev, "fsdriver",
3739 qemu_opt_get(opts, "fsdriver"), &error_abort);
3740 path = qemu_opt_get(opts, "path");
3741 if (path) {
3742 qemu_opt_set(fsdev, "path", path, &error_abort);
3744 security_model = qemu_opt_get(opts, "security_model");
3745 if (security_model) {
3746 qemu_opt_set(fsdev, "security_model", security_model,
3747 &error_abort);
3749 socket = qemu_opt_get(opts, "socket");
3750 if (socket) {
3751 qemu_opt_set(fsdev, "socket", socket, &error_abort);
3753 sock_fd = qemu_opt_get(opts, "sock_fd");
3754 if (sock_fd) {
3755 qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
3758 qemu_opt_set_bool(fsdev, "readonly",
3759 qemu_opt_get_bool(opts, "readonly", 0),
3760 &error_abort);
3761 multidevs = qemu_opt_get(opts, "multidevs");
3762 if (multidevs) {
3763 qemu_opt_set(fsdev, "multidevs", multidevs, &error_abort);
3765 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3766 &error_abort);
3767 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3768 qemu_opt_set(device, "fsdev",
3769 qemu_opts_id(fsdev), &error_abort);
3770 qemu_opt_set(device, "mount_tag",
3771 qemu_opt_get(opts, "mount_tag"), &error_abort);
3772 break;
3774 case QEMU_OPTION_serial:
3775 add_device_config(DEV_SERIAL, optarg);
3776 default_serial = 0;
3777 if (strncmp(optarg, "mon:", 4) == 0) {
3778 default_monitor = 0;
3780 break;
3781 case QEMU_OPTION_watchdog:
3782 if (watchdog) {
3783 error_report("only one watchdog option may be given");
3784 exit(1);
3786 watchdog = optarg;
3787 break;
3788 case QEMU_OPTION_watchdog_action:
3789 if (select_watchdog_action(optarg) == -1) {
3790 error_report("unknown -watchdog-action parameter");
3791 exit(1);
3793 break;
3794 case QEMU_OPTION_parallel:
3795 add_device_config(DEV_PARALLEL, optarg);
3796 default_parallel = 0;
3797 if (strncmp(optarg, "mon:", 4) == 0) {
3798 default_monitor = 0;
3800 break;
3801 case QEMU_OPTION_debugcon:
3802 add_device_config(DEV_DEBUGCON, optarg);
3803 break;
3804 case QEMU_OPTION_loadvm:
3805 loadvm = optarg;
3806 break;
3807 case QEMU_OPTION_full_screen:
3808 dpy.has_full_screen = true;
3809 dpy.full_screen = true;
3810 break;
3811 case QEMU_OPTION_alt_grab:
3812 alt_grab = 1;
3813 break;
3814 case QEMU_OPTION_ctrl_grab:
3815 ctrl_grab = 1;
3816 break;
3817 case QEMU_OPTION_no_quit:
3818 dpy.has_window_close = true;
3819 dpy.window_close = false;
3820 break;
3821 case QEMU_OPTION_sdl:
3822 #ifdef CONFIG_SDL
3823 dpy.type = DISPLAY_TYPE_SDL;
3824 break;
3825 #else
3826 error_report("SDL support is disabled");
3827 exit(1);
3828 #endif
3829 case QEMU_OPTION_pidfile:
3830 pid_file = optarg;
3831 break;
3832 case QEMU_OPTION_win2k_hack:
3833 win2k_install_hack = 1;
3834 break;
3835 case QEMU_OPTION_acpitable:
3836 opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
3837 optarg, true);
3838 if (!opts) {
3839 exit(1);
3841 acpi_table_add(opts, &error_fatal);
3842 break;
3843 case QEMU_OPTION_smbios:
3844 opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
3845 optarg, false);
3846 if (!opts) {
3847 exit(1);
3849 smbios_entry_add(opts, &error_fatal);
3850 break;
3851 case QEMU_OPTION_fwcfg:
3852 opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
3853 optarg, true);
3854 if (opts == NULL) {
3855 exit(1);
3857 break;
3858 case QEMU_OPTION_preconfig:
3859 preconfig_exit_requested = false;
3860 preconfig_requested = true;
3861 break;
3862 case QEMU_OPTION_enable_kvm:
3863 olist = qemu_find_opts("machine");
3864 qemu_opts_parse_noisily(olist, "accel=kvm", false);
3865 break;
3866 case QEMU_OPTION_M:
3867 case QEMU_OPTION_machine:
3868 olist = qemu_find_opts("machine");
3869 opts = qemu_opts_parse_noisily(olist, optarg, true);
3870 if (!opts) {
3871 exit(1);
3873 break;
3874 case QEMU_OPTION_accel:
3875 accel_opts = qemu_opts_parse_noisily(qemu_find_opts("accel"),
3876 optarg, true);
3877 optarg = qemu_opt_get(accel_opts, "accel");
3878 if (!optarg || is_help_option(optarg)) {
3879 printf("Accelerators supported in QEMU binary:\n");
3880 GSList *el, *accel_list = object_class_get_list(TYPE_ACCEL,
3881 false);
3882 for (el = accel_list; el; el = el->next) {
3883 gchar *typename = g_strdup(object_class_get_name(
3884 OBJECT_CLASS(el->data)));
3885 /* omit qtest which is used for tests only */
3886 if (g_strcmp0(typename, ACCEL_CLASS_NAME("qtest")) &&
3887 g_str_has_suffix(typename, ACCEL_CLASS_SUFFIX)) {
3888 gchar **optname = g_strsplit(typename,
3889 ACCEL_CLASS_SUFFIX, 0);
3890 printf("%s\n", optname[0]);
3891 g_strfreev(optname);
3893 g_free(typename);
3895 g_slist_free(accel_list);
3896 exit(0);
3898 break;
3899 case QEMU_OPTION_usb:
3900 olist = qemu_find_opts("machine");
3901 qemu_opts_parse_noisily(olist, "usb=on", false);
3902 break;
3903 case QEMU_OPTION_usbdevice:
3904 error_report("'-usbdevice' is deprecated, please use "
3905 "'-device usb-...' instead");
3906 olist = qemu_find_opts("machine");
3907 qemu_opts_parse_noisily(olist, "usb=on", false);
3908 add_device_config(DEV_USB, optarg);
3909 break;
3910 case QEMU_OPTION_device:
3911 if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
3912 optarg, true)) {
3913 exit(1);
3915 break;
3916 case QEMU_OPTION_smp:
3917 if (!qemu_opts_parse_noisily(qemu_find_opts("smp-opts"),
3918 optarg, true)) {
3919 exit(1);
3921 break;
3922 case QEMU_OPTION_vnc:
3923 vnc_parse(optarg, &error_fatal);
3924 break;
3925 case QEMU_OPTION_no_acpi:
3926 olist = qemu_find_opts("machine");
3927 qemu_opts_parse_noisily(olist, "acpi=off", false);
3928 break;
3929 case QEMU_OPTION_no_hpet:
3930 olist = qemu_find_opts("machine");
3931 qemu_opts_parse_noisily(olist, "hpet=off", false);
3932 break;
3933 case QEMU_OPTION_no_reboot:
3934 no_reboot = 1;
3935 break;
3936 case QEMU_OPTION_no_shutdown:
3937 no_shutdown = 1;
3938 break;
3939 case QEMU_OPTION_show_cursor:
3940 warn_report("The -show-cursor option is deprecated. Please "
3941 "add show-cursor=on to your -display options.");
3942 warn_report("When using the default display you can use "
3943 "-display default,show-cursor=on");
3944 dpy.has_show_cursor = true;
3945 dpy.show_cursor = true;
3946 break;
3947 case QEMU_OPTION_uuid:
3948 if (qemu_uuid_parse(optarg, &qemu_uuid) < 0) {
3949 error_report("failed to parse UUID string: wrong format");
3950 exit(1);
3952 qemu_uuid_set = true;
3953 break;
3954 case QEMU_OPTION_option_rom:
3955 if (nb_option_roms >= MAX_OPTION_ROMS) {
3956 error_report("too many option ROMs");
3957 exit(1);
3959 opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
3960 optarg, true);
3961 if (!opts) {
3962 exit(1);
3964 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3965 option_rom[nb_option_roms].bootindex =
3966 qemu_opt_get_number(opts, "bootindex", -1);
3967 if (!option_rom[nb_option_roms].name) {
3968 error_report("Option ROM file is not specified");
3969 exit(1);
3971 nb_option_roms++;
3972 break;
3973 case QEMU_OPTION_semihosting:
3974 qemu_semihosting_enable();
3975 break;
3976 case QEMU_OPTION_semihosting_config:
3977 if (qemu_semihosting_config_options(optarg) != 0) {
3978 exit(1);
3980 break;
3981 case QEMU_OPTION_name:
3982 opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
3983 optarg, true);
3984 if (!opts) {
3985 exit(1);
3987 /* Capture guest name if -msg guest-name is used later */
3988 error_guest_name = qemu_opt_get(opts, "guest");
3989 break;
3990 case QEMU_OPTION_prom_env:
3991 if (nb_prom_envs >= MAX_PROM_ENVS) {
3992 error_report("too many prom variables");
3993 exit(1);
3995 prom_envs[nb_prom_envs] = optarg;
3996 nb_prom_envs++;
3997 break;
3998 case QEMU_OPTION_old_param:
3999 old_param = 1;
4000 break;
4001 case QEMU_OPTION_rtc:
4002 opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
4003 false);
4004 if (!opts) {
4005 exit(1);
4007 break;
4008 case QEMU_OPTION_tb_size:
4009 #ifndef CONFIG_TCG
4010 error_report("TCG is disabled");
4011 exit(1);
4012 #endif
4013 warn_report("The -tb-size option is deprecated, use -accel tcg,tb-size instead");
4014 object_register_sugar_prop(ACCEL_CLASS_NAME("tcg"), "tb-size", optarg);
4015 break;
4016 case QEMU_OPTION_icount:
4017 icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
4018 optarg, true);
4019 if (!icount_opts) {
4020 exit(1);
4022 break;
4023 case QEMU_OPTION_incoming:
4024 if (!incoming) {
4025 runstate_set(RUN_STATE_INMIGRATE);
4027 incoming = optarg;
4028 break;
4029 case QEMU_OPTION_only_migratable:
4030 only_migratable = 1;
4031 break;
4032 case QEMU_OPTION_nodefaults:
4033 has_defaults = 0;
4034 break;
4035 case QEMU_OPTION_xen_domid:
4036 if (!(xen_available())) {
4037 error_report("Option not supported for this target");
4038 exit(1);
4040 xen_domid = atoi(optarg);
4041 break;
4042 case QEMU_OPTION_xen_attach:
4043 if (!(xen_available())) {
4044 error_report("Option not supported for this target");
4045 exit(1);
4047 xen_mode = XEN_ATTACH;
4048 break;
4049 case QEMU_OPTION_xen_domid_restrict:
4050 if (!(xen_available())) {
4051 error_report("Option not supported for this target");
4052 exit(1);
4054 xen_domid_restrict = true;
4055 break;
4056 case QEMU_OPTION_trace:
4057 trace_opt_parse(optarg);
4058 break;
4059 case QEMU_OPTION_plugin:
4060 qemu_plugin_opt_parse(optarg, &plugin_list);
4061 break;
4062 case QEMU_OPTION_readconfig:
4064 int ret = qemu_read_config_file(optarg);
4065 if (ret < 0) {
4066 error_report("read config %s: %s", optarg,
4067 strerror(-ret));
4068 exit(1);
4070 break;
4072 case QEMU_OPTION_spice:
4073 olist = qemu_find_opts_err("spice", NULL);
4074 if (!olist) {
4075 ui_module_load_one("spice-core");
4076 olist = qemu_find_opts("spice");
4078 if (!olist) {
4079 error_report("spice support is disabled");
4080 exit(1);
4082 opts = qemu_opts_parse_noisily(olist, optarg, false);
4083 if (!opts) {
4084 exit(1);
4086 display_remote++;
4087 break;
4088 case QEMU_OPTION_writeconfig:
4090 FILE *fp;
4091 if (strcmp(optarg, "-") == 0) {
4092 fp = stdout;
4093 } else {
4094 fp = fopen(optarg, "w");
4095 if (fp == NULL) {
4096 error_report("open %s: %s", optarg,
4097 strerror(errno));
4098 exit(1);
4101 qemu_config_write(fp);
4102 if (fp != stdout) {
4103 fclose(fp);
4105 break;
4107 case QEMU_OPTION_qtest:
4108 qtest_chrdev = optarg;
4109 break;
4110 case QEMU_OPTION_qtest_log:
4111 qtest_log = optarg;
4112 break;
4113 case QEMU_OPTION_sandbox:
4114 olist = qemu_find_opts("sandbox");
4115 if (!olist) {
4116 #ifndef CONFIG_SECCOMP
4117 error_report("-sandbox support is not enabled "
4118 "in this QEMU binary");
4119 #endif
4120 exit(1);
4123 opts = qemu_opts_parse_noisily(olist, optarg, true);
4124 if (!opts) {
4125 exit(1);
4127 break;
4128 case QEMU_OPTION_add_fd:
4129 #ifndef _WIN32
4130 opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
4131 optarg, false);
4132 if (!opts) {
4133 exit(1);
4135 #else
4136 error_report("File descriptor passing is disabled on this "
4137 "platform");
4138 exit(1);
4139 #endif
4140 break;
4141 case QEMU_OPTION_object:
4142 opts = qemu_opts_parse_noisily(qemu_find_opts("object"),
4143 optarg, true);
4144 if (!opts) {
4145 exit(1);
4147 break;
4148 case QEMU_OPTION_realtime:
4149 warn_report("'-realtime mlock=...' is deprecated, please use "
4150 "'-overcommit mem-lock=...' instead");
4151 opts = qemu_opts_parse_noisily(qemu_find_opts("realtime"),
4152 optarg, false);
4153 if (!opts) {
4154 exit(1);
4156 /* Don't override the -overcommit option if set */
4157 enable_mlock = enable_mlock ||
4158 qemu_opt_get_bool(opts, "mlock", true);
4159 break;
4160 case QEMU_OPTION_overcommit:
4161 opts = qemu_opts_parse_noisily(qemu_find_opts("overcommit"),
4162 optarg, false);
4163 if (!opts) {
4164 exit(1);
4166 /* Don't override the -realtime option if set */
4167 enable_mlock = enable_mlock ||
4168 qemu_opt_get_bool(opts, "mem-lock", false);
4169 enable_cpu_pm = qemu_opt_get_bool(opts, "cpu-pm", false);
4170 break;
4171 case QEMU_OPTION_msg:
4172 opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
4173 false);
4174 if (!opts) {
4175 exit(1);
4177 configure_msg(opts);
4178 break;
4179 case QEMU_OPTION_dump_vmstate:
4180 if (vmstate_dump_file) {
4181 error_report("only one '-dump-vmstate' "
4182 "option may be given");
4183 exit(1);
4185 vmstate_dump_file = fopen(optarg, "w");
4186 if (vmstate_dump_file == NULL) {
4187 error_report("open %s: %s", optarg, strerror(errno));
4188 exit(1);
4190 break;
4191 case QEMU_OPTION_enable_sync_profile:
4192 qsp_enable();
4193 break;
4194 case QEMU_OPTION_nouserconfig:
4195 /* Nothing to be parsed here. Especially, do not error out below. */
4196 break;
4197 default:
4198 if (os_parse_cmd_args(popt->index, optarg)) {
4199 error_report("Option not supported in this build");
4200 exit(1);
4206 * Clear error location left behind by the loop.
4207 * Best done right after the loop. Do not insert code here!
4209 loc_set_none();
4211 qemu_validate_options();
4212 qemu_process_sugar_options();
4215 * These options affect everything else and should be processed
4216 * before daemonizing.
4218 qemu_process_early_options();
4220 qemu_process_help_options();
4221 qemu_maybe_daemonize(pid_file);
4223 qemu_init_main_loop(&error_fatal);
4224 cpu_timers_init();
4226 user_register_global_props();
4227 replay_configure(icount_opts);
4229 configure_rtc(qemu_find_opts_singleton("rtc"));
4231 qemu_create_machine(select_machine());
4233 qemu_disable_default_devices();
4234 qemu_create_default_devices();
4235 qemu_create_early_backends();
4237 qemu_apply_machine_options();
4240 * Note: uses machine properties such as kernel-irqchip, must run
4241 * after machine_set_property().
4243 configure_accelerators(argv[0]);
4246 * Beware, QOM objects created before this point miss global and
4247 * compat properties.
4249 * Global properties get set up by qdev_prop_register_global(),
4250 * called from user_register_global_props(), and certain option
4251 * desugaring. Also in CPU feature desugaring (buried in
4252 * parse_cpu_option()), which happens below this point, but may
4253 * only target the CPU type, which can only be created after
4254 * parse_cpu_option() returned the type.
4256 * Machine compat properties: object_set_machine_compat_props().
4257 * Accelerator compat props: object_set_accelerator_compat_props(),
4258 * called from configure_accelerator().
4261 machine_class = MACHINE_GET_CLASS(current_machine);
4262 if (!qtest_enabled() && machine_class->deprecation_reason) {
4263 error_report("Machine type '%s' is deprecated: %s",
4264 machine_class->name, machine_class->deprecation_reason);
4268 * Note: creates a QOM object, must run only after global and
4269 * compat properties have been set up.
4271 migration_object_init();
4273 qemu_create_late_backends();
4275 /* parse features once if machine provides default cpu_type */
4276 current_machine->cpu_type = machine_class->default_cpu_type;
4277 if (cpu_option) {
4278 current_machine->cpu_type = parse_cpu_option(cpu_option);
4281 qemu_resolve_machine_memdev();
4282 parse_numa_opts(current_machine);
4284 if (preconfig_requested) {
4285 qemu_init_displays();
4288 /* do monitor/qmp handling at preconfig state if requested */
4289 qemu_main_loop();
4291 qemu_init_board();
4293 qemu_create_cli_devices();
4295 /* initialize displays after all errors have been reported */
4296 if (!preconfig_requested) {
4297 qemu_init_displays();
4299 qemu_machine_creation_done();
4301 if (loadvm) {
4302 Error *local_err = NULL;
4303 if (load_snapshot(loadvm, &local_err) < 0) {
4304 error_report_err(local_err);
4305 autostart = 0;
4306 exit(1);
4309 if (replay_mode != REPLAY_MODE_NONE) {
4310 replay_vmstate_init();
4313 if (vmstate_dump_file) {
4314 /* dump and exit */
4315 dump_vmstate_json_to_file(vmstate_dump_file);
4316 exit(0);
4318 if (incoming) {
4319 Error *local_err = NULL;
4320 if (strcmp(incoming, "defer") != 0) {
4321 qmp_migrate_incoming(incoming, &local_err);
4322 if (local_err) {
4323 error_reportf_err(local_err, "-incoming %s: ", incoming);
4324 exit(1);
4327 } else if (autostart) {
4328 qmp_cont(NULL);
4331 accel_setup_post(current_machine);
4332 os_setup_post();
4334 return;
4337 void qemu_cleanup(void)
4339 gdbserver_cleanup();
4342 * cleaning up the migration object cancels any existing migration
4343 * try to do this early so that it also stops using devices.
4345 migration_shutdown();
4348 * We must cancel all block jobs while the block layer is drained,
4349 * or cancelling will be affected by throttling and thus may block
4350 * for an extended period of time.
4351 * vm_shutdown() will bdrv_drain_all(), so we may as well include
4352 * it in the drained section.
4353 * We do not need to end this section, because we do not want any
4354 * requests happening from here on anyway.
4356 bdrv_drain_all_begin();
4358 /* No more vcpu or device emulation activity beyond this point */
4359 vm_shutdown();
4360 replay_finish();
4362 job_cancel_sync_all();
4363 bdrv_close_all();
4365 res_free();
4367 /* vhost-user must be cleaned up before chardevs. */
4368 tpm_cleanup();
4369 net_cleanup();
4370 audio_cleanup();
4371 monitor_cleanup();
4372 qemu_chr_cleanup();
4373 user_creatable_cleanup();
4374 /* TODO: unref root container, check all devices are ok */