vl: remove serial_max_hds
[qemu/ar7.git] / softmmu / vl.c
blob43a0a45b68dd6f0e54162d2309f548edbf7c66dd
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 *boot_order;
134 static const char *boot_once;
135 static const char *incoming;
136 static const char *loadvm;
137 static ram_addr_t maxram_size;
138 static uint64_t ram_slots;
139 static int display_remote;
140 static int snapshot;
141 static bool preconfig_requested;
142 static QemuPluginList plugin_list = QTAILQ_HEAD_INITIALIZER(plugin_list);
143 static BlockdevOptionsQueue bdo_queue = QSIMPLEQ_HEAD_INITIALIZER(bdo_queue);
144 static bool nographic = false;
145 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
146 static int mem_prealloc; /* force preallocation of physical target memory */
147 int display_opengl;
148 const char* keyboard_layout = NULL;
149 static ram_addr_t ram_size;
150 bool enable_mlock = false;
151 bool enable_cpu_pm = false;
152 int nb_nics;
153 NICInfo nd_table[MAX_NICS];
154 int autostart = 1;
155 int vga_interface_type = VGA_NONE;
156 static const char *vga_model = NULL;
157 static DisplayOptions dpy;
158 static int num_serial_hds;
159 static Chardev **serial_hds;
160 static const char *log_mask;
161 static const char *log_file;
162 static bool list_data_dirs;
163 Chardev *parallel_hds[MAX_PARALLEL_PORTS];
164 int win2k_install_hack = 0;
165 int singlestep = 0;
166 int fd_bootchk = 1;
167 static int no_reboot;
168 int no_shutdown = 0;
169 int graphic_rotate = 0;
170 static const char *watchdog;
171 QEMUOptionRom option_rom[MAX_OPTION_ROMS];
172 int nb_option_roms;
173 int old_param = 0;
174 const char *qemu_name;
175 int alt_grab = 0;
176 int ctrl_grab = 0;
177 unsigned int nb_prom_envs = 0;
178 const char *prom_envs[MAX_PROM_ENVS];
179 int boot_menu;
180 bool boot_strict;
181 uint8_t *boot_splash_filedata;
182 int only_migratable; /* turn it off unless user states otherwise */
183 bool wakeup_suspend_enabled;
184 int icount_align_option;
185 static const char *qtest_chrdev;
186 static const char *qtest_log;
188 /* The bytes in qemu_uuid are in the order specified by RFC4122, _not_ in the
189 * little-endian "wire format" described in the SMBIOS 2.6 specification.
191 QemuUUID qemu_uuid;
192 bool qemu_uuid_set;
194 static NotifierList exit_notifiers =
195 NOTIFIER_LIST_INITIALIZER(exit_notifiers);
197 uint32_t xen_domid;
198 enum xen_mode xen_mode = XEN_EMULATE;
199 bool xen_domid_restrict;
201 static int has_defaults = 1;
202 static int default_serial = 1;
203 static int default_parallel = 1;
204 static int default_monitor = 1;
205 static int default_floppy = 1;
206 static int default_cdrom = 1;
207 static int default_sdcard = 1;
208 static int default_vga = 1;
209 static int default_net = 1;
211 static struct {
212 const char *driver;
213 int *flag;
214 } default_list[] = {
215 { .driver = "isa-serial", .flag = &default_serial },
216 { .driver = "isa-parallel", .flag = &default_parallel },
217 { .driver = "isa-fdc", .flag = &default_floppy },
218 { .driver = "floppy", .flag = &default_floppy },
219 { .driver = "ide-cd", .flag = &default_cdrom },
220 { .driver = "ide-hd", .flag = &default_cdrom },
221 { .driver = "ide-drive", .flag = &default_cdrom },
222 { .driver = "scsi-cd", .flag = &default_cdrom },
223 { .driver = "scsi-hd", .flag = &default_cdrom },
224 { .driver = "VGA", .flag = &default_vga },
225 { .driver = "isa-vga", .flag = &default_vga },
226 { .driver = "cirrus-vga", .flag = &default_vga },
227 { .driver = "isa-cirrus-vga", .flag = &default_vga },
228 { .driver = "vmware-svga", .flag = &default_vga },
229 { .driver = "qxl-vga", .flag = &default_vga },
230 { .driver = "virtio-vga", .flag = &default_vga },
231 { .driver = "ati-vga", .flag = &default_vga },
232 { .driver = "vhost-user-vga", .flag = &default_vga },
235 static QemuOptsList qemu_rtc_opts = {
236 .name = "rtc",
237 .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
238 .merge_lists = true,
239 .desc = {
241 .name = "base",
242 .type = QEMU_OPT_STRING,
244 .name = "clock",
245 .type = QEMU_OPT_STRING,
247 .name = "driftfix",
248 .type = QEMU_OPT_STRING,
250 { /* end of list */ }
254 static QemuOptsList qemu_option_rom_opts = {
255 .name = "option-rom",
256 .implied_opt_name = "romfile",
257 .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
258 .desc = {
260 .name = "bootindex",
261 .type = QEMU_OPT_NUMBER,
262 }, {
263 .name = "romfile",
264 .type = QEMU_OPT_STRING,
266 { /* end of list */ }
270 static QemuOptsList qemu_machine_opts = {
271 .name = "machine",
272 .implied_opt_name = "type",
273 .merge_lists = true,
274 .head = QTAILQ_HEAD_INITIALIZER(qemu_machine_opts.head),
275 .desc = {
277 * no elements => accept any
278 * sanity checking will happen later
279 * when setting machine properties
285 static QemuOptsList qemu_accel_opts = {
286 .name = "accel",
287 .implied_opt_name = "accel",
288 .head = QTAILQ_HEAD_INITIALIZER(qemu_accel_opts.head),
289 .desc = {
291 * no elements => accept any
292 * sanity checking will happen later
293 * when setting accelerator properties
299 static QemuOptsList qemu_boot_opts = {
300 .name = "boot-opts",
301 .implied_opt_name = "order",
302 .merge_lists = true,
303 .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
304 .desc = {
306 .name = "order",
307 .type = QEMU_OPT_STRING,
308 }, {
309 .name = "once",
310 .type = QEMU_OPT_STRING,
311 }, {
312 .name = "menu",
313 .type = QEMU_OPT_BOOL,
314 }, {
315 .name = "splash",
316 .type = QEMU_OPT_STRING,
317 }, {
318 .name = "splash-time",
319 .type = QEMU_OPT_NUMBER,
320 }, {
321 .name = "reboot-timeout",
322 .type = QEMU_OPT_NUMBER,
323 }, {
324 .name = "strict",
325 .type = QEMU_OPT_BOOL,
327 { /*End of list */ }
331 static QemuOptsList qemu_add_fd_opts = {
332 .name = "add-fd",
333 .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
334 .desc = {
336 .name = "fd",
337 .type = QEMU_OPT_NUMBER,
338 .help = "file descriptor of which a duplicate is added to fd set",
340 .name = "set",
341 .type = QEMU_OPT_NUMBER,
342 .help = "ID of the fd set to add fd to",
344 .name = "opaque",
345 .type = QEMU_OPT_STRING,
346 .help = "free-form string used to describe fd",
348 { /* end of list */ }
352 static QemuOptsList qemu_object_opts = {
353 .name = "object",
354 .implied_opt_name = "qom-type",
355 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
356 .desc = {
361 static QemuOptsList qemu_tpmdev_opts = {
362 .name = "tpmdev",
363 .implied_opt_name = "type",
364 .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
365 .desc = {
366 /* options are defined in the TPM backends */
367 { /* end of list */ }
371 static QemuOptsList qemu_realtime_opts = {
372 .name = "realtime",
373 .head = QTAILQ_HEAD_INITIALIZER(qemu_realtime_opts.head),
374 .desc = {
376 .name = "mlock",
377 .type = QEMU_OPT_BOOL,
379 { /* end of list */ }
383 static QemuOptsList qemu_overcommit_opts = {
384 .name = "overcommit",
385 .head = QTAILQ_HEAD_INITIALIZER(qemu_overcommit_opts.head),
386 .desc = {
388 .name = "mem-lock",
389 .type = QEMU_OPT_BOOL,
392 .name = "cpu-pm",
393 .type = QEMU_OPT_BOOL,
395 { /* end of list */ }
399 static QemuOptsList qemu_msg_opts = {
400 .name = "msg",
401 .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
402 .desc = {
404 .name = "timestamp",
405 .type = QEMU_OPT_BOOL,
408 .name = "guest-name",
409 .type = QEMU_OPT_BOOL,
410 .help = "Prepends guest name for error messages but only if "
411 "-name guest is set otherwise option is ignored\n",
413 { /* end of list */ }
417 static QemuOptsList qemu_name_opts = {
418 .name = "name",
419 .implied_opt_name = "guest",
420 .merge_lists = true,
421 .head = QTAILQ_HEAD_INITIALIZER(qemu_name_opts.head),
422 .desc = {
424 .name = "guest",
425 .type = QEMU_OPT_STRING,
426 .help = "Sets the name of the guest.\n"
427 "This name will be displayed in the SDL window caption.\n"
428 "The name will also be used for the VNC server",
429 }, {
430 .name = "process",
431 .type = QEMU_OPT_STRING,
432 .help = "Sets the name of the QEMU process, as shown in top etc",
433 }, {
434 .name = "debug-threads",
435 .type = QEMU_OPT_BOOL,
436 .help = "When enabled, name the individual threads; defaults off.\n"
437 "NOTE: The thread names are for debugging and not a\n"
438 "stable API.",
440 { /* End of list */ }
444 static QemuOptsList qemu_mem_opts = {
445 .name = "memory",
446 .implied_opt_name = "size",
447 .head = QTAILQ_HEAD_INITIALIZER(qemu_mem_opts.head),
448 .merge_lists = true,
449 .desc = {
451 .name = "size",
452 .type = QEMU_OPT_SIZE,
455 .name = "slots",
456 .type = QEMU_OPT_NUMBER,
459 .name = "maxmem",
460 .type = QEMU_OPT_SIZE,
462 { /* end of list */ }
466 static QemuOptsList qemu_icount_opts = {
467 .name = "icount",
468 .implied_opt_name = "shift",
469 .merge_lists = true,
470 .head = QTAILQ_HEAD_INITIALIZER(qemu_icount_opts.head),
471 .desc = {
473 .name = "shift",
474 .type = QEMU_OPT_STRING,
475 }, {
476 .name = "align",
477 .type = QEMU_OPT_BOOL,
478 }, {
479 .name = "sleep",
480 .type = QEMU_OPT_BOOL,
481 }, {
482 .name = "rr",
483 .type = QEMU_OPT_STRING,
484 }, {
485 .name = "rrfile",
486 .type = QEMU_OPT_STRING,
487 }, {
488 .name = "rrsnapshot",
489 .type = QEMU_OPT_STRING,
491 { /* end of list */ }
495 static QemuOptsList qemu_fw_cfg_opts = {
496 .name = "fw_cfg",
497 .implied_opt_name = "name",
498 .head = QTAILQ_HEAD_INITIALIZER(qemu_fw_cfg_opts.head),
499 .desc = {
501 .name = "name",
502 .type = QEMU_OPT_STRING,
503 .help = "Sets the fw_cfg name of the blob to be inserted",
504 }, {
505 .name = "file",
506 .type = QEMU_OPT_STRING,
507 .help = "Sets the name of the file from which "
508 "the fw_cfg blob will be loaded",
509 }, {
510 .name = "string",
511 .type = QEMU_OPT_STRING,
512 .help = "Sets content of the blob to be inserted from a string",
513 }, {
514 .name = "gen_id",
515 .type = QEMU_OPT_STRING,
516 .help = "Sets id of the object generating the fw_cfg blob "
517 "to be inserted",
519 { /* end of list */ }
524 * Get machine options
526 * Returns: machine options (never null).
528 QemuOpts *qemu_get_machine_opts(void)
530 return qemu_find_opts_singleton("machine");
533 const char *qemu_get_vm_name(void)
535 return qemu_name;
538 static void res_free(void)
540 g_free(boot_splash_filedata);
541 boot_splash_filedata = NULL;
544 static int default_driver_check(void *opaque, QemuOpts *opts, Error **errp)
546 const char *driver = qemu_opt_get(opts, "driver");
547 int i;
549 if (!driver)
550 return 0;
551 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
552 if (strcmp(default_list[i].driver, driver) != 0)
553 continue;
554 *(default_list[i].flag) = 0;
556 return 0;
559 /***********************************************************/
560 /* QEMU state */
562 static RunState current_run_state = RUN_STATE_PRECONFIG;
564 /* We use RUN_STATE__MAX but any invalid value will do */
565 static RunState vmstop_requested = RUN_STATE__MAX;
566 static QemuMutex vmstop_lock;
568 typedef struct {
569 RunState from;
570 RunState to;
571 } RunStateTransition;
573 static const RunStateTransition runstate_transitions_def[] = {
574 /* from -> to */
575 { RUN_STATE_PRECONFIG, RUN_STATE_PRELAUNCH },
576 /* Early switch to inmigrate state to allow -incoming CLI option work
577 * as it used to. TODO: delay actual switching to inmigrate state to
578 * the point after machine is built and remove this hack.
580 { RUN_STATE_PRECONFIG, RUN_STATE_INMIGRATE },
582 { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
583 { RUN_STATE_DEBUG, RUN_STATE_FINISH_MIGRATE },
584 { RUN_STATE_DEBUG, RUN_STATE_PRELAUNCH },
586 { RUN_STATE_INMIGRATE, RUN_STATE_INTERNAL_ERROR },
587 { RUN_STATE_INMIGRATE, RUN_STATE_IO_ERROR },
588 { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
589 { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
590 { RUN_STATE_INMIGRATE, RUN_STATE_SHUTDOWN },
591 { RUN_STATE_INMIGRATE, RUN_STATE_SUSPENDED },
592 { RUN_STATE_INMIGRATE, RUN_STATE_WATCHDOG },
593 { RUN_STATE_INMIGRATE, RUN_STATE_GUEST_PANICKED },
594 { RUN_STATE_INMIGRATE, RUN_STATE_FINISH_MIGRATE },
595 { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
596 { RUN_STATE_INMIGRATE, RUN_STATE_POSTMIGRATE },
597 { RUN_STATE_INMIGRATE, RUN_STATE_COLO },
599 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
600 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
601 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PRELAUNCH },
603 { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
604 { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
605 { RUN_STATE_IO_ERROR, RUN_STATE_PRELAUNCH },
607 { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
608 { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
609 { RUN_STATE_PAUSED, RUN_STATE_POSTMIGRATE },
610 { RUN_STATE_PAUSED, RUN_STATE_PRELAUNCH },
611 { RUN_STATE_PAUSED, RUN_STATE_COLO},
613 { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
614 { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
615 { RUN_STATE_POSTMIGRATE, RUN_STATE_PRELAUNCH },
617 { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
618 { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
619 { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
621 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
622 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PAUSED },
623 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
624 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PRELAUNCH },
625 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_COLO},
627 { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
628 { RUN_STATE_RESTORE_VM, RUN_STATE_PRELAUNCH },
630 { RUN_STATE_COLO, RUN_STATE_RUNNING },
632 { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
633 { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
634 { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
635 { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
636 { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
637 { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
638 { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
639 { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
640 { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
641 { RUN_STATE_RUNNING, RUN_STATE_GUEST_PANICKED },
642 { RUN_STATE_RUNNING, RUN_STATE_COLO},
644 { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
646 { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
647 { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
648 { RUN_STATE_SHUTDOWN, RUN_STATE_PRELAUNCH },
649 { RUN_STATE_SHUTDOWN, RUN_STATE_COLO },
651 { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
652 { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
653 { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
654 { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
655 { RUN_STATE_SUSPENDED, RUN_STATE_PRELAUNCH },
656 { RUN_STATE_SUSPENDED, RUN_STATE_COLO},
658 { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
659 { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
660 { RUN_STATE_WATCHDOG, RUN_STATE_PRELAUNCH },
661 { RUN_STATE_WATCHDOG, RUN_STATE_COLO},
663 { RUN_STATE_GUEST_PANICKED, RUN_STATE_RUNNING },
664 { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
665 { RUN_STATE_GUEST_PANICKED, RUN_STATE_PRELAUNCH },
667 { RUN_STATE__MAX, RUN_STATE__MAX },
670 static bool runstate_valid_transitions[RUN_STATE__MAX][RUN_STATE__MAX];
672 bool runstate_check(RunState state)
674 return current_run_state == state;
677 bool runstate_store(char *str, size_t size)
679 const char *state = RunState_str(current_run_state);
680 size_t len = strlen(state) + 1;
682 if (len > size) {
683 return false;
685 memcpy(str, state, len);
686 return true;
689 static void runstate_init(void)
691 const RunStateTransition *p;
693 memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
694 for (p = &runstate_transitions_def[0]; p->from != RUN_STATE__MAX; p++) {
695 runstate_valid_transitions[p->from][p->to] = true;
698 qemu_mutex_init(&vmstop_lock);
701 /* This function will abort() on invalid state transitions */
702 void runstate_set(RunState new_state)
704 assert(new_state < RUN_STATE__MAX);
706 trace_runstate_set(current_run_state, RunState_str(current_run_state),
707 new_state, RunState_str(new_state));
709 if (current_run_state == new_state) {
710 return;
713 if (!runstate_valid_transitions[current_run_state][new_state]) {
714 error_report("invalid runstate transition: '%s' -> '%s'",
715 RunState_str(current_run_state),
716 RunState_str(new_state));
717 abort();
720 current_run_state = new_state;
723 int runstate_is_running(void)
725 return runstate_check(RUN_STATE_RUNNING);
728 bool runstate_needs_reset(void)
730 return runstate_check(RUN_STATE_INTERNAL_ERROR) ||
731 runstate_check(RUN_STATE_SHUTDOWN);
734 StatusInfo *qmp_query_status(Error **errp)
736 StatusInfo *info = g_malloc0(sizeof(*info));
738 info->running = runstate_is_running();
739 info->singlestep = singlestep;
740 info->status = current_run_state;
742 return info;
745 bool qemu_vmstop_requested(RunState *r)
747 qemu_mutex_lock(&vmstop_lock);
748 *r = vmstop_requested;
749 vmstop_requested = RUN_STATE__MAX;
750 qemu_mutex_unlock(&vmstop_lock);
751 return *r < RUN_STATE__MAX;
754 void qemu_system_vmstop_request_prepare(void)
756 qemu_mutex_lock(&vmstop_lock);
759 void qemu_system_vmstop_request(RunState state)
761 vmstop_requested = state;
762 qemu_mutex_unlock(&vmstop_lock);
763 qemu_notify_event();
765 static int parse_name(void *opaque, QemuOpts *opts, Error **errp)
767 const char *proc_name;
769 if (qemu_opt_get(opts, "debug-threads")) {
770 qemu_thread_naming(qemu_opt_get_bool(opts, "debug-threads", false));
772 qemu_name = qemu_opt_get(opts, "guest");
774 proc_name = qemu_opt_get(opts, "process");
775 if (proc_name) {
776 os_set_proc_name(proc_name);
779 return 0;
782 bool defaults_enabled(void)
784 return has_defaults;
787 #ifndef _WIN32
788 static int parse_add_fd(void *opaque, QemuOpts *opts, Error **errp)
790 int fd, dupfd, flags;
791 int64_t fdset_id;
792 const char *fd_opaque = NULL;
793 AddfdInfo *fdinfo;
795 fd = qemu_opt_get_number(opts, "fd", -1);
796 fdset_id = qemu_opt_get_number(opts, "set", -1);
797 fd_opaque = qemu_opt_get(opts, "opaque");
799 if (fd < 0) {
800 error_setg(errp, "fd option is required and must be non-negative");
801 return -1;
804 if (fd <= STDERR_FILENO) {
805 error_setg(errp, "fd cannot be a standard I/O stream");
806 return -1;
810 * All fds inherited across exec() necessarily have FD_CLOEXEC
811 * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
813 flags = fcntl(fd, F_GETFD);
814 if (flags == -1 || (flags & FD_CLOEXEC)) {
815 error_setg(errp, "fd is not valid or already in use");
816 return -1;
819 if (fdset_id < 0) {
820 error_setg(errp, "set option is required and must be non-negative");
821 return -1;
824 #ifdef F_DUPFD_CLOEXEC
825 dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
826 #else
827 dupfd = dup(fd);
828 if (dupfd != -1) {
829 qemu_set_cloexec(dupfd);
831 #endif
832 if (dupfd == -1) {
833 error_setg(errp, "error duplicating fd: %s", strerror(errno));
834 return -1;
837 /* add the duplicate fd, and optionally the opaque string, to the fd set */
838 fdinfo = monitor_fdset_add_fd(dupfd, true, fdset_id, !!fd_opaque, fd_opaque,
839 &error_abort);
840 g_free(fdinfo);
842 return 0;
845 static int cleanup_add_fd(void *opaque, QemuOpts *opts, Error **errp)
847 int fd;
849 fd = qemu_opt_get_number(opts, "fd", -1);
850 close(fd);
852 return 0;
854 #endif
856 /***********************************************************/
857 /* QEMU Block devices */
859 #define HD_OPTS "media=disk"
860 #define CDROM_OPTS "media=cdrom"
861 #define FD_OPTS ""
862 #define PFLASH_OPTS ""
863 #define MTD_OPTS ""
864 #define SD_OPTS ""
866 static int drive_init_func(void *opaque, QemuOpts *opts, Error **errp)
868 BlockInterfaceType *block_default_type = opaque;
870 return drive_new(opts, *block_default_type, errp) == NULL;
873 static int drive_enable_snapshot(void *opaque, QemuOpts *opts, Error **errp)
875 if (qemu_opt_get(opts, "snapshot") == NULL) {
876 qemu_opt_set(opts, "snapshot", "on", &error_abort);
878 return 0;
881 static void default_drive(int enable, int snapshot, BlockInterfaceType type,
882 int index, const char *optstr)
884 QemuOpts *opts;
885 DriveInfo *dinfo;
887 if (!enable || drive_get_by_index(type, index)) {
888 return;
891 opts = drive_add(type, index, NULL, optstr);
892 if (snapshot) {
893 drive_enable_snapshot(NULL, opts, NULL);
896 dinfo = drive_new(opts, type, &error_abort);
897 dinfo->is_default = true;
901 static void configure_blockdev(BlockdevOptionsQueue *bdo_queue,
902 MachineClass *machine_class, int snapshot)
905 * If the currently selected machine wishes to override the
906 * units-per-bus property of its default HBA interface type, do so
907 * now.
909 if (machine_class->units_per_default_bus) {
910 override_max_devs(machine_class->block_default_type,
911 machine_class->units_per_default_bus);
914 /* open the virtual block devices */
915 while (!QSIMPLEQ_EMPTY(bdo_queue)) {
916 BlockdevOptionsQueueEntry *bdo = QSIMPLEQ_FIRST(bdo_queue);
918 QSIMPLEQ_REMOVE_HEAD(bdo_queue, entry);
919 loc_push_restore(&bdo->loc);
920 qmp_blockdev_add(bdo->bdo, &error_fatal);
921 loc_pop(&bdo->loc);
922 qapi_free_BlockdevOptions(bdo->bdo);
923 g_free(bdo);
925 if (snapshot) {
926 qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot,
927 NULL, NULL);
929 if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
930 &machine_class->block_default_type, &error_fatal)) {
931 /* We printed help */
932 exit(0);
935 default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
936 CDROM_OPTS);
937 default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
938 default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
942 static QemuOptsList qemu_smp_opts = {
943 .name = "smp-opts",
944 .implied_opt_name = "cpus",
945 .merge_lists = true,
946 .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
947 .desc = {
949 .name = "cpus",
950 .type = QEMU_OPT_NUMBER,
951 }, {
952 .name = "sockets",
953 .type = QEMU_OPT_NUMBER,
954 }, {
955 .name = "dies",
956 .type = QEMU_OPT_NUMBER,
957 }, {
958 .name = "cores",
959 .type = QEMU_OPT_NUMBER,
960 }, {
961 .name = "threads",
962 .type = QEMU_OPT_NUMBER,
963 }, {
964 .name = "maxcpus",
965 .type = QEMU_OPT_NUMBER,
967 { /*End of list */ }
971 static void realtime_init(void)
973 if (enable_mlock) {
974 if (os_mlock() < 0) {
975 error_report("locking memory failed");
976 exit(1);
982 static void configure_msg(QemuOpts *opts)
984 error_with_timestamp = qemu_opt_get_bool(opts, "timestamp", false);
985 error_with_guestname = qemu_opt_get_bool(opts, "guest-name", false);
989 /***********************************************************/
990 /* USB devices */
992 static int usb_device_add(const char *devname)
994 USBDevice *dev = NULL;
996 if (!machine_usb(current_machine)) {
997 return -1;
1000 dev = usbdevice_create(devname);
1001 if (!dev)
1002 return -1;
1004 return 0;
1007 static int usb_parse(const char *cmdline)
1009 int r;
1010 r = usb_device_add(cmdline);
1011 if (r < 0) {
1012 error_report("could not add USB device '%s'", cmdline);
1014 return r;
1017 /***********************************************************/
1018 /* machine registration */
1020 MachineState *current_machine;
1022 static MachineClass *find_machine(const char *name, GSList *machines)
1024 GSList *el;
1026 for (el = machines; el; el = el->next) {
1027 MachineClass *mc = el->data;
1029 if (!strcmp(mc->name, name) || !g_strcmp0(mc->alias, name)) {
1030 return mc;
1034 return NULL;
1037 static MachineClass *find_default_machine(GSList *machines)
1039 GSList *el;
1040 MachineClass *default_machineclass = NULL;
1042 for (el = machines; el; el = el->next) {
1043 MachineClass *mc = el->data;
1045 if (mc->is_default) {
1046 assert(default_machineclass == NULL && "Multiple default machines");
1047 default_machineclass = mc;
1051 return default_machineclass;
1054 static int machine_help_func(QemuOpts *opts, MachineState *machine)
1056 ObjectProperty *prop;
1057 ObjectPropertyIterator iter;
1059 if (!qemu_opt_has_help_opt(opts)) {
1060 return 0;
1063 object_property_iter_init(&iter, OBJECT(machine));
1064 while ((prop = object_property_iter_next(&iter))) {
1065 if (!prop->set) {
1066 continue;
1069 printf("%s.%s=%s", MACHINE_GET_CLASS(machine)->name,
1070 prop->name, prop->type);
1071 if (prop->description) {
1072 printf(" (%s)\n", prop->description);
1073 } else {
1074 printf("\n");
1078 return 1;
1081 struct VMChangeStateEntry {
1082 VMChangeStateHandler *cb;
1083 void *opaque;
1084 QTAILQ_ENTRY(VMChangeStateEntry) entries;
1085 int priority;
1088 static QTAILQ_HEAD(, VMChangeStateEntry) vm_change_state_head =
1089 QTAILQ_HEAD_INITIALIZER(vm_change_state_head);
1092 * qemu_add_vm_change_state_handler_prio:
1093 * @cb: the callback to invoke
1094 * @opaque: user data passed to the callback
1095 * @priority: low priorities execute first when the vm runs and the reverse is
1096 * true when the vm stops
1098 * Register a callback function that is invoked when the vm starts or stops
1099 * running.
1101 * Returns: an entry to be freed using qemu_del_vm_change_state_handler()
1103 VMChangeStateEntry *qemu_add_vm_change_state_handler_prio(
1104 VMChangeStateHandler *cb, void *opaque, int priority)
1106 VMChangeStateEntry *e;
1107 VMChangeStateEntry *other;
1109 e = g_malloc0(sizeof(*e));
1110 e->cb = cb;
1111 e->opaque = opaque;
1112 e->priority = priority;
1114 /* Keep list sorted in ascending priority order */
1115 QTAILQ_FOREACH(other, &vm_change_state_head, entries) {
1116 if (priority < other->priority) {
1117 QTAILQ_INSERT_BEFORE(other, e, entries);
1118 return e;
1122 QTAILQ_INSERT_TAIL(&vm_change_state_head, e, entries);
1123 return e;
1126 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1127 void *opaque)
1129 return qemu_add_vm_change_state_handler_prio(cb, opaque, 0);
1132 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1134 QTAILQ_REMOVE(&vm_change_state_head, e, entries);
1135 g_free(e);
1138 void vm_state_notify(int running, RunState state)
1140 VMChangeStateEntry *e, *next;
1142 trace_vm_state_notify(running, state, RunState_str(state));
1144 if (running) {
1145 QTAILQ_FOREACH_SAFE(e, &vm_change_state_head, entries, next) {
1146 e->cb(e->opaque, running, state);
1148 } else {
1149 QTAILQ_FOREACH_REVERSE_SAFE(e, &vm_change_state_head, entries, next) {
1150 e->cb(e->opaque, running, state);
1155 static ShutdownCause reset_requested;
1156 static ShutdownCause shutdown_requested;
1157 static int shutdown_signal;
1158 static pid_t shutdown_pid;
1159 static int powerdown_requested;
1160 static int debug_requested;
1161 static int suspend_requested;
1162 static bool preconfig_exit_requested = true;
1163 static WakeupReason wakeup_reason;
1164 static NotifierList powerdown_notifiers =
1165 NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
1166 static NotifierList suspend_notifiers =
1167 NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1168 static NotifierList wakeup_notifiers =
1169 NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1170 static NotifierList shutdown_notifiers =
1171 NOTIFIER_LIST_INITIALIZER(shutdown_notifiers);
1172 static uint32_t wakeup_reason_mask = ~(1 << QEMU_WAKEUP_REASON_NONE);
1174 ShutdownCause qemu_shutdown_requested_get(void)
1176 return shutdown_requested;
1179 ShutdownCause qemu_reset_requested_get(void)
1181 return reset_requested;
1184 static int qemu_shutdown_requested(void)
1186 return qatomic_xchg(&shutdown_requested, SHUTDOWN_CAUSE_NONE);
1189 static void qemu_kill_report(void)
1191 if (!qtest_driver() && shutdown_signal) {
1192 if (shutdown_pid == 0) {
1193 /* This happens for eg ^C at the terminal, so it's worth
1194 * avoiding printing an odd message in that case.
1196 error_report("terminating on signal %d", shutdown_signal);
1197 } else {
1198 char *shutdown_cmd = qemu_get_pid_name(shutdown_pid);
1200 error_report("terminating on signal %d from pid " FMT_pid " (%s)",
1201 shutdown_signal, shutdown_pid,
1202 shutdown_cmd ? shutdown_cmd : "<unknown process>");
1203 g_free(shutdown_cmd);
1205 shutdown_signal = 0;
1209 static ShutdownCause qemu_reset_requested(void)
1211 ShutdownCause r = reset_requested;
1213 if (r && replay_checkpoint(CHECKPOINT_RESET_REQUESTED)) {
1214 reset_requested = SHUTDOWN_CAUSE_NONE;
1215 return r;
1217 return SHUTDOWN_CAUSE_NONE;
1220 static int qemu_suspend_requested(void)
1222 int r = suspend_requested;
1223 if (r && replay_checkpoint(CHECKPOINT_SUSPEND_REQUESTED)) {
1224 suspend_requested = 0;
1225 return r;
1227 return false;
1230 static WakeupReason qemu_wakeup_requested(void)
1232 return wakeup_reason;
1235 static int qemu_powerdown_requested(void)
1237 int r = powerdown_requested;
1238 powerdown_requested = 0;
1239 return r;
1242 static int qemu_debug_requested(void)
1244 int r = debug_requested;
1245 debug_requested = 0;
1246 return r;
1249 void qemu_exit_preconfig_request(void)
1251 preconfig_exit_requested = true;
1255 * Reset the VM. Issue an event unless @reason is SHUTDOWN_CAUSE_NONE.
1257 void qemu_system_reset(ShutdownCause reason)
1259 MachineClass *mc;
1261 mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1263 cpu_synchronize_all_states();
1265 if (mc && mc->reset) {
1266 mc->reset(current_machine);
1267 } else {
1268 qemu_devices_reset();
1270 if (reason && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1271 qapi_event_send_reset(shutdown_caused_by_guest(reason), reason);
1273 cpu_synchronize_all_post_reset();
1277 * Wake the VM after suspend.
1279 static void qemu_system_wakeup(void)
1281 MachineClass *mc;
1283 mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1285 if (mc && mc->wakeup) {
1286 mc->wakeup(current_machine);
1290 void qemu_system_guest_panicked(GuestPanicInformation *info)
1292 qemu_log_mask(LOG_GUEST_ERROR, "Guest crashed");
1294 if (current_cpu) {
1295 current_cpu->crash_occurred = true;
1297 qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE,
1298 !!info, info);
1299 vm_stop(RUN_STATE_GUEST_PANICKED);
1300 if (!no_shutdown) {
1301 qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_POWEROFF,
1302 !!info, info);
1303 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_PANIC);
1306 if (info) {
1307 if (info->type == GUEST_PANIC_INFORMATION_TYPE_HYPER_V) {
1308 qemu_log_mask(LOG_GUEST_ERROR, "\nHV crash parameters: (%#"PRIx64
1309 " %#"PRIx64" %#"PRIx64" %#"PRIx64" %#"PRIx64")\n",
1310 info->u.hyper_v.arg1,
1311 info->u.hyper_v.arg2,
1312 info->u.hyper_v.arg3,
1313 info->u.hyper_v.arg4,
1314 info->u.hyper_v.arg5);
1315 } else if (info->type == GUEST_PANIC_INFORMATION_TYPE_S390) {
1316 qemu_log_mask(LOG_GUEST_ERROR, " on cpu %d: %s\n"
1317 "PSW: 0x%016" PRIx64 " 0x%016" PRIx64"\n",
1318 info->u.s390.core,
1319 S390CrashReason_str(info->u.s390.reason),
1320 info->u.s390.psw_mask,
1321 info->u.s390.psw_addr);
1323 qapi_free_GuestPanicInformation(info);
1327 void qemu_system_guest_crashloaded(GuestPanicInformation *info)
1329 qemu_log_mask(LOG_GUEST_ERROR, "Guest crash loaded");
1331 qapi_event_send_guest_crashloaded(GUEST_PANIC_ACTION_RUN,
1332 !!info, info);
1334 if (info) {
1335 qapi_free_GuestPanicInformation(info);
1339 void qemu_system_reset_request(ShutdownCause reason)
1341 if (no_reboot && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1342 shutdown_requested = reason;
1343 } else {
1344 reset_requested = reason;
1346 cpu_stop_current();
1347 qemu_notify_event();
1350 static void qemu_system_suspend(void)
1352 pause_all_vcpus();
1353 notifier_list_notify(&suspend_notifiers, NULL);
1354 runstate_set(RUN_STATE_SUSPENDED);
1355 qapi_event_send_suspend();
1358 void qemu_system_suspend_request(void)
1360 if (runstate_check(RUN_STATE_SUSPENDED)) {
1361 return;
1363 suspend_requested = 1;
1364 cpu_stop_current();
1365 qemu_notify_event();
1368 void qemu_register_suspend_notifier(Notifier *notifier)
1370 notifier_list_add(&suspend_notifiers, notifier);
1373 void qemu_system_wakeup_request(WakeupReason reason, Error **errp)
1375 trace_system_wakeup_request(reason);
1377 if (!runstate_check(RUN_STATE_SUSPENDED)) {
1378 error_setg(errp,
1379 "Unable to wake up: guest is not in suspended state");
1380 return;
1382 if (!(wakeup_reason_mask & (1 << reason))) {
1383 return;
1385 runstate_set(RUN_STATE_RUNNING);
1386 wakeup_reason = reason;
1387 qemu_notify_event();
1390 void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1392 if (enabled) {
1393 wakeup_reason_mask |= (1 << reason);
1394 } else {
1395 wakeup_reason_mask &= ~(1 << reason);
1399 void qemu_register_wakeup_notifier(Notifier *notifier)
1401 notifier_list_add(&wakeup_notifiers, notifier);
1404 void qemu_register_wakeup_support(void)
1406 wakeup_suspend_enabled = true;
1409 bool qemu_wakeup_suspend_enabled(void)
1411 return wakeup_suspend_enabled;
1414 void qemu_system_killed(int signal, pid_t pid)
1416 shutdown_signal = signal;
1417 shutdown_pid = pid;
1418 no_shutdown = 0;
1420 /* Cannot call qemu_system_shutdown_request directly because
1421 * we are in a signal handler.
1423 shutdown_requested = SHUTDOWN_CAUSE_HOST_SIGNAL;
1424 qemu_notify_event();
1427 void qemu_system_shutdown_request(ShutdownCause reason)
1429 trace_qemu_system_shutdown_request(reason);
1430 replay_shutdown_request(reason);
1431 shutdown_requested = reason;
1432 qemu_notify_event();
1435 static void qemu_system_powerdown(void)
1437 qapi_event_send_powerdown();
1438 notifier_list_notify(&powerdown_notifiers, NULL);
1441 static void qemu_system_shutdown(ShutdownCause cause)
1443 qapi_event_send_shutdown(shutdown_caused_by_guest(cause), cause);
1444 notifier_list_notify(&shutdown_notifiers, &cause);
1447 void qemu_system_powerdown_request(void)
1449 trace_qemu_system_powerdown_request();
1450 powerdown_requested = 1;
1451 qemu_notify_event();
1454 void qemu_register_powerdown_notifier(Notifier *notifier)
1456 notifier_list_add(&powerdown_notifiers, notifier);
1459 void qemu_register_shutdown_notifier(Notifier *notifier)
1461 notifier_list_add(&shutdown_notifiers, notifier);
1464 void qemu_system_debug_request(void)
1466 debug_requested = 1;
1467 qemu_notify_event();
1470 static bool main_loop_should_exit(void)
1472 RunState r;
1473 ShutdownCause request;
1475 if (preconfig_exit_requested) {
1476 if (runstate_check(RUN_STATE_PRECONFIG)) {
1477 runstate_set(RUN_STATE_PRELAUNCH);
1479 preconfig_exit_requested = false;
1480 return true;
1482 if (qemu_debug_requested()) {
1483 vm_stop(RUN_STATE_DEBUG);
1485 if (qemu_suspend_requested()) {
1486 qemu_system_suspend();
1488 request = qemu_shutdown_requested();
1489 if (request) {
1490 qemu_kill_report();
1491 qemu_system_shutdown(request);
1492 if (no_shutdown) {
1493 vm_stop(RUN_STATE_SHUTDOWN);
1494 } else {
1495 return true;
1498 request = qemu_reset_requested();
1499 if (request) {
1500 pause_all_vcpus();
1501 qemu_system_reset(request);
1502 resume_all_vcpus();
1504 * runstate can change in pause_all_vcpus()
1505 * as iothread mutex is unlocked
1507 if (!runstate_check(RUN_STATE_RUNNING) &&
1508 !runstate_check(RUN_STATE_INMIGRATE) &&
1509 !runstate_check(RUN_STATE_FINISH_MIGRATE)) {
1510 runstate_set(RUN_STATE_PRELAUNCH);
1513 if (qemu_wakeup_requested()) {
1514 pause_all_vcpus();
1515 qemu_system_wakeup();
1516 notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
1517 wakeup_reason = QEMU_WAKEUP_REASON_NONE;
1518 resume_all_vcpus();
1519 qapi_event_send_wakeup();
1521 if (qemu_powerdown_requested()) {
1522 qemu_system_powerdown();
1524 if (qemu_vmstop_requested(&r)) {
1525 vm_stop(r);
1527 return false;
1530 void qemu_main_loop(void)
1532 #ifdef CONFIG_PROFILER
1533 int64_t ti;
1534 #endif
1535 while (!main_loop_should_exit()) {
1536 #ifdef CONFIG_PROFILER
1537 ti = profile_getclock();
1538 #endif
1539 main_loop_wait(false);
1540 #ifdef CONFIG_PROFILER
1541 dev_time += profile_getclock() - ti;
1542 #endif
1546 static void version(void)
1548 printf("QEMU emulator version " QEMU_FULL_VERSION "\n"
1549 QEMU_COPYRIGHT "\n");
1552 static void help(int exitcode)
1554 version();
1555 printf("usage: %s [options] [disk_image]\n\n"
1556 "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
1557 error_get_progname());
1559 #define QEMU_OPTIONS_GENERATE_HELP
1560 #include "qemu-options-wrapper.h"
1562 printf("\nDuring emulation, the following keys are useful:\n"
1563 "ctrl-alt-f toggle full screen\n"
1564 "ctrl-alt-n switch to virtual console 'n'\n"
1565 "ctrl-alt toggle mouse and keyboard grab\n"
1566 "\n"
1567 "When using -nographic, press 'ctrl-a h' to get some help.\n"
1568 "\n"
1569 QEMU_HELP_BOTTOM "\n");
1571 exit(exitcode);
1574 #define HAS_ARG 0x0001
1576 typedef struct QEMUOption {
1577 const char *name;
1578 int flags;
1579 int index;
1580 uint32_t arch_mask;
1581 } QEMUOption;
1583 static const QEMUOption qemu_options[] = {
1584 { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1585 #define QEMU_OPTIONS_GENERATE_OPTIONS
1586 #include "qemu-options-wrapper.h"
1587 { NULL },
1590 typedef struct VGAInterfaceInfo {
1591 const char *opt_name; /* option name */
1592 const char *name; /* human-readable name */
1593 /* Class names indicating that support is available.
1594 * If no class is specified, the interface is always available */
1595 const char *class_names[2];
1596 } VGAInterfaceInfo;
1598 static const VGAInterfaceInfo vga_interfaces[VGA_TYPE_MAX] = {
1599 [VGA_NONE] = {
1600 .opt_name = "none",
1601 .name = "no graphic card",
1603 [VGA_STD] = {
1604 .opt_name = "std",
1605 .name = "standard VGA",
1606 .class_names = { "VGA", "isa-vga" },
1608 [VGA_CIRRUS] = {
1609 .opt_name = "cirrus",
1610 .name = "Cirrus VGA",
1611 .class_names = { "cirrus-vga", "isa-cirrus-vga" },
1613 [VGA_VMWARE] = {
1614 .opt_name = "vmware",
1615 .name = "VMWare SVGA",
1616 .class_names = { "vmware-svga" },
1618 [VGA_VIRTIO] = {
1619 .opt_name = "virtio",
1620 .name = "Virtio VGA",
1621 .class_names = { "virtio-vga" },
1623 [VGA_QXL] = {
1624 .opt_name = "qxl",
1625 .name = "QXL VGA",
1626 .class_names = { "qxl-vga" },
1628 [VGA_TCX] = {
1629 .opt_name = "tcx",
1630 .name = "TCX framebuffer",
1631 .class_names = { "SUNW,tcx" },
1633 [VGA_CG3] = {
1634 .opt_name = "cg3",
1635 .name = "CG3 framebuffer",
1636 .class_names = { "cgthree" },
1638 [VGA_XENFB] = {
1639 .opt_name = "xenfb",
1640 .name = "Xen paravirtualized framebuffer",
1644 static bool vga_interface_available(VGAInterfaceType t)
1646 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1648 assert(t < VGA_TYPE_MAX);
1649 return !ti->class_names[0] ||
1650 module_object_class_by_name(ti->class_names[0]) ||
1651 module_object_class_by_name(ti->class_names[1]);
1654 static const char *
1655 get_default_vga_model(const MachineClass *machine_class)
1657 if (machine_class->default_display) {
1658 return machine_class->default_display;
1659 } else if (vga_interface_available(VGA_CIRRUS)) {
1660 return "cirrus";
1661 } else if (vga_interface_available(VGA_STD)) {
1662 return "std";
1665 return NULL;
1668 static void select_vgahw(const MachineClass *machine_class, const char *p)
1670 const char *opts;
1671 int t;
1673 if (g_str_equal(p, "help")) {
1674 const char *def = get_default_vga_model(machine_class);
1676 for (t = 0; t < VGA_TYPE_MAX; t++) {
1677 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1679 if (vga_interface_available(t) && ti->opt_name) {
1680 printf("%-20s %s%s\n", ti->opt_name, ti->name ?: "",
1681 g_str_equal(ti->opt_name, def) ? " (default)" : "");
1684 exit(0);
1687 assert(vga_interface_type == VGA_NONE);
1688 for (t = 0; t < VGA_TYPE_MAX; t++) {
1689 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1690 if (ti->opt_name && strstart(p, ti->opt_name, &opts)) {
1691 if (!vga_interface_available(t)) {
1692 error_report("%s not available", ti->name);
1693 exit(1);
1695 vga_interface_type = t;
1696 break;
1699 if (t == VGA_TYPE_MAX) {
1700 invalid_vga:
1701 error_report("unknown vga type: %s", p);
1702 exit(1);
1704 while (*opts) {
1705 const char *nextopt;
1707 if (strstart(opts, ",retrace=", &nextopt)) {
1708 opts = nextopt;
1709 if (strstart(opts, "dumb", &nextopt))
1710 vga_retrace_method = VGA_RETRACE_DUMB;
1711 else if (strstart(opts, "precise", &nextopt))
1712 vga_retrace_method = VGA_RETRACE_PRECISE;
1713 else goto invalid_vga;
1714 } else goto invalid_vga;
1715 opts = nextopt;
1719 static void parse_display_qapi(const char *optarg)
1721 DisplayOptions *opts;
1722 Visitor *v;
1724 v = qobject_input_visitor_new_str(optarg, "type", &error_fatal);
1726 visit_type_DisplayOptions(v, NULL, &opts, &error_fatal);
1727 QAPI_CLONE_MEMBERS(DisplayOptions, &dpy, opts);
1729 qapi_free_DisplayOptions(opts);
1730 visit_free(v);
1733 DisplayOptions *qmp_query_display_options(Error **errp)
1735 return QAPI_CLONE(DisplayOptions, &dpy);
1738 static void parse_display(const char *p)
1740 const char *opts;
1742 if (is_help_option(p)) {
1743 qemu_display_help();
1744 exit(0);
1747 if (strstart(p, "sdl", &opts)) {
1749 * sdl DisplayType needs hand-crafted parser instead of
1750 * parse_display_qapi() due to some options not in
1751 * DisplayOptions, specifically:
1752 * - frame
1753 * Already deprecated.
1754 * - ctrl_grab + alt_grab
1755 * Not clear yet what happens to them long-term. Should
1756 * replaced by something better or deprecated and dropped.
1758 dpy.type = DISPLAY_TYPE_SDL;
1759 while (*opts) {
1760 const char *nextopt;
1762 if (strstart(opts, ",alt_grab=", &nextopt)) {
1763 opts = nextopt;
1764 if (strstart(opts, "on", &nextopt)) {
1765 alt_grab = 1;
1766 } else if (strstart(opts, "off", &nextopt)) {
1767 alt_grab = 0;
1768 } else {
1769 goto invalid_sdl_args;
1771 } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
1772 opts = nextopt;
1773 if (strstart(opts, "on", &nextopt)) {
1774 ctrl_grab = 1;
1775 } else if (strstart(opts, "off", &nextopt)) {
1776 ctrl_grab = 0;
1777 } else {
1778 goto invalid_sdl_args;
1780 } else if (strstart(opts, ",window_close=", &nextopt)) {
1781 opts = nextopt;
1782 dpy.has_window_close = true;
1783 if (strstart(opts, "on", &nextopt)) {
1784 dpy.window_close = true;
1785 } else if (strstart(opts, "off", &nextopt)) {
1786 dpy.window_close = false;
1787 } else {
1788 goto invalid_sdl_args;
1790 } else if (strstart(opts, ",show-cursor=", &nextopt)) {
1791 opts = nextopt;
1792 dpy.has_show_cursor = true;
1793 if (strstart(opts, "on", &nextopt)) {
1794 dpy.show_cursor = true;
1795 } else if (strstart(opts, "off", &nextopt)) {
1796 dpy.show_cursor = false;
1797 } else {
1798 goto invalid_sdl_args;
1800 } else if (strstart(opts, ",gl=", &nextopt)) {
1801 opts = nextopt;
1802 dpy.has_gl = true;
1803 if (strstart(opts, "on", &nextopt)) {
1804 dpy.gl = DISPLAYGL_MODE_ON;
1805 } else if (strstart(opts, "core", &nextopt)) {
1806 dpy.gl = DISPLAYGL_MODE_CORE;
1807 } else if (strstart(opts, "es", &nextopt)) {
1808 dpy.gl = DISPLAYGL_MODE_ES;
1809 } else if (strstart(opts, "off", &nextopt)) {
1810 dpy.gl = DISPLAYGL_MODE_OFF;
1811 } else {
1812 goto invalid_sdl_args;
1814 } else {
1815 invalid_sdl_args:
1816 error_report("invalid SDL option string");
1817 exit(1);
1819 opts = nextopt;
1821 } else if (strstart(p, "vnc", &opts)) {
1823 * vnc isn't a (local) DisplayType but a protocol for remote
1824 * display access.
1826 if (*opts == '=') {
1827 vnc_parse(opts + 1, &error_fatal);
1828 } else {
1829 error_report("VNC requires a display argument vnc=<display>");
1830 exit(1);
1832 } else {
1833 parse_display_qapi(p);
1837 static inline bool nonempty_str(const char *str)
1839 return str && *str;
1842 static int parse_fw_cfg(void *opaque, QemuOpts *opts, Error **errp)
1844 gchar *buf;
1845 size_t size;
1846 const char *name, *file, *str, *gen_id;
1847 FWCfgState *fw_cfg = (FWCfgState *) opaque;
1849 if (fw_cfg == NULL) {
1850 error_setg(errp, "fw_cfg device not available");
1851 return -1;
1853 name = qemu_opt_get(opts, "name");
1854 file = qemu_opt_get(opts, "file");
1855 str = qemu_opt_get(opts, "string");
1856 gen_id = qemu_opt_get(opts, "gen_id");
1858 /* we need the name, and exactly one of: file, content string, gen_id */
1859 if (!nonempty_str(name) ||
1860 nonempty_str(file) + nonempty_str(str) + nonempty_str(gen_id) != 1) {
1861 error_setg(errp, "name, plus exactly one of file,"
1862 " string and gen_id, are needed");
1863 return -1;
1865 if (strlen(name) > FW_CFG_MAX_FILE_PATH - 1) {
1866 error_setg(errp, "name too long (max. %d char)",
1867 FW_CFG_MAX_FILE_PATH - 1);
1868 return -1;
1870 if (nonempty_str(gen_id)) {
1872 * In this particular case where the content is populated
1873 * internally, the "etc/" namespace protection is relaxed,
1874 * so do not emit a warning.
1876 } else if (strncmp(name, "opt/", 4) != 0) {
1877 warn_report("externally provided fw_cfg item names "
1878 "should be prefixed with \"opt/\"");
1880 if (nonempty_str(str)) {
1881 size = strlen(str); /* NUL terminator NOT included in fw_cfg blob */
1882 buf = g_memdup(str, size);
1883 } else if (nonempty_str(gen_id)) {
1884 if (!fw_cfg_add_from_generator(fw_cfg, name, gen_id, errp)) {
1885 return -1;
1887 return 0;
1888 } else {
1889 GError *err = NULL;
1890 if (!g_file_get_contents(file, &buf, &size, &err)) {
1891 error_setg(errp, "can't load %s: %s", file, err->message);
1892 g_error_free(err);
1893 return -1;
1896 /* For legacy, keep user files in a specific global order. */
1897 fw_cfg_set_order_override(fw_cfg, FW_CFG_ORDER_OVERRIDE_USER);
1898 fw_cfg_add_file(fw_cfg, name, buf, size);
1899 fw_cfg_reset_order_override(fw_cfg);
1900 return 0;
1903 static int device_help_func(void *opaque, QemuOpts *opts, Error **errp)
1905 return qdev_device_help(opts);
1908 static int device_init_func(void *opaque, QemuOpts *opts, Error **errp)
1910 DeviceState *dev;
1912 dev = qdev_device_add(opts, errp);
1913 if (!dev && *errp) {
1914 error_report_err(*errp);
1915 return -1;
1916 } else if (dev) {
1917 object_unref(OBJECT(dev));
1919 return 0;
1922 static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)
1924 Error *local_err = NULL;
1926 if (!qemu_chr_new_from_opts(opts, NULL, &local_err)) {
1927 if (local_err) {
1928 error_propagate(errp, local_err);
1929 return -1;
1931 exit(0);
1933 return 0;
1936 #ifdef CONFIG_VIRTFS
1937 static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp)
1939 return qemu_fsdev_add(opts, errp);
1941 #endif
1943 static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp)
1945 return monitor_init_opts(opts, errp);
1948 static void monitor_parse(const char *optarg, const char *mode, bool pretty)
1950 static int monitor_device_index = 0;
1951 QemuOpts *opts;
1952 const char *p;
1953 char label[32];
1955 if (strstart(optarg, "chardev:", &p)) {
1956 snprintf(label, sizeof(label), "%s", p);
1957 } else {
1958 snprintf(label, sizeof(label), "compat_monitor%d",
1959 monitor_device_index);
1960 opts = qemu_chr_parse_compat(label, optarg, true);
1961 if (!opts) {
1962 error_report("parse error: %s", optarg);
1963 exit(1);
1967 opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &error_fatal);
1968 qemu_opt_set(opts, "mode", mode, &error_abort);
1969 qemu_opt_set(opts, "chardev", label, &error_abort);
1970 if (!strcmp(mode, "control")) {
1971 qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);
1972 } else {
1973 assert(pretty == false);
1975 monitor_device_index++;
1978 struct device_config {
1979 enum {
1980 DEV_USB, /* -usbdevice */
1981 DEV_SERIAL, /* -serial */
1982 DEV_PARALLEL, /* -parallel */
1983 DEV_DEBUGCON, /* -debugcon */
1984 DEV_GDB, /* -gdb, -s */
1985 DEV_SCLP, /* s390 sclp */
1986 } type;
1987 const char *cmdline;
1988 Location loc;
1989 QTAILQ_ENTRY(device_config) next;
1992 static QTAILQ_HEAD(, device_config) device_configs =
1993 QTAILQ_HEAD_INITIALIZER(device_configs);
1995 static void add_device_config(int type, const char *cmdline)
1997 struct device_config *conf;
1999 conf = g_malloc0(sizeof(*conf));
2000 conf->type = type;
2001 conf->cmdline = cmdline;
2002 loc_save(&conf->loc);
2003 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2006 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2008 struct device_config *conf;
2009 int rc;
2011 QTAILQ_FOREACH(conf, &device_configs, next) {
2012 if (conf->type != type)
2013 continue;
2014 loc_push_restore(&conf->loc);
2015 rc = func(conf->cmdline);
2016 loc_pop(&conf->loc);
2017 if (rc) {
2018 return rc;
2021 return 0;
2024 static void qemu_disable_default_devices(void)
2026 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2028 qemu_opts_foreach(qemu_find_opts("device"),
2029 default_driver_check, NULL, NULL);
2030 qemu_opts_foreach(qemu_find_opts("global"),
2031 default_driver_check, NULL, NULL);
2033 if (!vga_model && !default_vga) {
2034 vga_interface_type = VGA_DEVICE;
2036 if (!has_defaults || machine_class->no_serial) {
2037 default_serial = 0;
2039 if (!has_defaults || machine_class->no_parallel) {
2040 default_parallel = 0;
2042 if (!has_defaults || machine_class->no_floppy) {
2043 default_floppy = 0;
2045 if (!has_defaults || machine_class->no_cdrom) {
2046 default_cdrom = 0;
2048 if (!has_defaults || machine_class->no_sdcard) {
2049 default_sdcard = 0;
2051 if (!has_defaults) {
2052 default_monitor = 0;
2053 default_net = 0;
2054 default_vga = 0;
2058 static void qemu_create_default_devices(void)
2060 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2062 if (is_daemonized()) {
2063 /* According to documentation and historically, -nographic redirects
2064 * serial port, parallel port and monitor to stdio, which does not work
2065 * with -daemonize. We can redirect these to null instead, but since
2066 * -nographic is legacy, let's just error out.
2067 * We disallow -nographic only if all other ports are not redirected
2068 * explicitly, to not break existing legacy setups which uses
2069 * -nographic _and_ redirects all ports explicitly - this is valid
2070 * usage, -nographic is just a no-op in this case.
2072 if (nographic
2073 && (default_parallel || default_serial || default_monitor)) {
2074 error_report("-nographic cannot be used with -daemonize");
2075 exit(1);
2079 if (nographic) {
2080 if (default_parallel)
2081 add_device_config(DEV_PARALLEL, "null");
2082 if (default_serial && default_monitor) {
2083 add_device_config(DEV_SERIAL, "mon:stdio");
2084 } else {
2085 if (default_serial)
2086 add_device_config(DEV_SERIAL, "stdio");
2087 if (default_monitor)
2088 monitor_parse("stdio", "readline", false);
2090 } else {
2091 if (default_serial)
2092 add_device_config(DEV_SERIAL, "vc:80Cx24C");
2093 if (default_parallel)
2094 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
2095 if (default_monitor)
2096 monitor_parse("vc:80Cx24C", "readline", false);
2099 if (default_net) {
2100 QemuOptsList *net = qemu_find_opts("net");
2101 qemu_opts_parse(net, "nic", true, &error_abort);
2102 #ifdef CONFIG_SLIRP
2103 qemu_opts_parse(net, "user", true, &error_abort);
2104 #endif
2107 #if defined(CONFIG_VNC)
2108 if (!QTAILQ_EMPTY(&(qemu_find_opts("vnc")->head))) {
2109 display_remote++;
2111 #endif
2112 if (dpy.type == DISPLAY_TYPE_DEFAULT && !display_remote) {
2113 if (!qemu_display_find_default(&dpy)) {
2114 dpy.type = DISPLAY_TYPE_NONE;
2115 #if defined(CONFIG_VNC)
2116 vnc_parse("localhost:0,to=99,id=default", &error_abort);
2117 #endif
2120 if (dpy.type == DISPLAY_TYPE_DEFAULT) {
2121 dpy.type = DISPLAY_TYPE_NONE;
2124 /* If no default VGA is requested, the default is "none". */
2125 if (default_vga) {
2126 vga_model = get_default_vga_model(machine_class);
2128 if (vga_model) {
2129 select_vgahw(machine_class, vga_model);
2133 static int serial_parse(const char *devname)
2135 int index = num_serial_hds;
2136 char label[32];
2138 if (strcmp(devname, "none") == 0)
2139 return 0;
2140 snprintf(label, sizeof(label), "serial%d", index);
2141 serial_hds = g_renew(Chardev *, serial_hds, index + 1);
2143 serial_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2144 if (!serial_hds[index]) {
2145 error_report("could not connect serial device"
2146 " to character backend '%s'", devname);
2147 return -1;
2149 num_serial_hds++;
2150 return 0;
2153 Chardev *serial_hd(int i)
2155 assert(i >= 0);
2156 if (i < num_serial_hds) {
2157 return serial_hds[i];
2159 return NULL;
2162 static int parallel_parse(const char *devname)
2164 static int index = 0;
2165 char label[32];
2167 if (strcmp(devname, "none") == 0)
2168 return 0;
2169 if (index == MAX_PARALLEL_PORTS) {
2170 error_report("too many parallel ports");
2171 exit(1);
2173 snprintf(label, sizeof(label), "parallel%d", index);
2174 parallel_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2175 if (!parallel_hds[index]) {
2176 error_report("could not connect parallel device"
2177 " to character backend '%s'", devname);
2178 return -1;
2180 index++;
2181 return 0;
2184 static int debugcon_parse(const char *devname)
2186 QemuOpts *opts;
2188 if (!qemu_chr_new_mux_mon("debugcon", devname, NULL)) {
2189 error_report("invalid character backend '%s'", devname);
2190 exit(1);
2192 opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2193 if (!opts) {
2194 error_report("already have a debugcon device");
2195 exit(1);
2197 qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);
2198 qemu_opt_set(opts, "chardev", "debugcon", &error_abort);
2199 return 0;
2202 static gint machine_class_cmp(gconstpointer a, gconstpointer b)
2204 const MachineClass *mc1 = a, *mc2 = b;
2205 int res;
2207 if (mc1->family == NULL) {
2208 if (mc2->family == NULL) {
2209 /* Compare standalone machine types against each other; they sort
2210 * in increasing order.
2212 return strcmp(object_class_get_name(OBJECT_CLASS(mc1)),
2213 object_class_get_name(OBJECT_CLASS(mc2)));
2216 /* Standalone machine types sort after families. */
2217 return 1;
2220 if (mc2->family == NULL) {
2221 /* Families sort before standalone machine types. */
2222 return -1;
2225 /* Families sort between each other alphabetically increasingly. */
2226 res = strcmp(mc1->family, mc2->family);
2227 if (res != 0) {
2228 return res;
2231 /* Within the same family, machine types sort in decreasing order. */
2232 return strcmp(object_class_get_name(OBJECT_CLASS(mc2)),
2233 object_class_get_name(OBJECT_CLASS(mc1)));
2236 static MachineClass *machine_parse(const char *name, GSList *machines)
2238 MachineClass *mc;
2239 GSList *el;
2241 if (is_help_option(name)) {
2242 printf("Supported machines are:\n");
2243 machines = g_slist_sort(machines, machine_class_cmp);
2244 for (el = machines; el; el = el->next) {
2245 MachineClass *mc = el->data;
2246 if (mc->alias) {
2247 printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
2249 printf("%-20s %s%s%s\n", mc->name, mc->desc,
2250 mc->is_default ? " (default)" : "",
2251 mc->deprecation_reason ? " (deprecated)" : "");
2253 exit(0);
2256 mc = find_machine(name, machines);
2257 if (!mc) {
2258 error_report("unsupported machine type");
2259 error_printf("Use -machine help to list supported machines\n");
2260 exit(1);
2262 return mc;
2265 void qemu_add_exit_notifier(Notifier *notify)
2267 notifier_list_add(&exit_notifiers, notify);
2270 void qemu_remove_exit_notifier(Notifier *notify)
2272 notifier_remove(notify);
2275 static void qemu_run_exit_notifiers(void)
2277 notifier_list_notify(&exit_notifiers, NULL);
2280 static const char *pid_file;
2281 static Notifier qemu_unlink_pidfile_notifier;
2283 static void qemu_unlink_pidfile(Notifier *n, void *data)
2285 if (pid_file) {
2286 unlink(pid_file);
2290 static const QEMUOption *lookup_opt(int argc, char **argv,
2291 const char **poptarg, int *poptind)
2293 const QEMUOption *popt;
2294 int optind = *poptind;
2295 char *r = argv[optind];
2296 const char *optarg;
2298 loc_set_cmdline(argv, optind, 1);
2299 optind++;
2300 /* Treat --foo the same as -foo. */
2301 if (r[1] == '-')
2302 r++;
2303 popt = qemu_options;
2304 for(;;) {
2305 if (!popt->name) {
2306 error_report("invalid option");
2307 exit(1);
2309 if (!strcmp(popt->name, r + 1))
2310 break;
2311 popt++;
2313 if (popt->flags & HAS_ARG) {
2314 if (optind >= argc) {
2315 error_report("requires an argument");
2316 exit(1);
2318 optarg = argv[optind++];
2319 loc_set_cmdline(argv, optind - 2, 2);
2320 } else {
2321 optarg = NULL;
2324 *poptarg = optarg;
2325 *poptind = optind;
2327 return popt;
2330 static MachineClass *select_machine(void)
2332 GSList *machines = object_class_get_list(TYPE_MACHINE, false);
2333 MachineClass *machine_class = find_default_machine(machines);
2334 const char *optarg;
2335 QemuOpts *opts;
2336 Location loc;
2338 loc_push_none(&loc);
2340 opts = qemu_get_machine_opts();
2341 qemu_opts_loc_restore(opts);
2343 optarg = qemu_opt_get(opts, "type");
2344 if (optarg) {
2345 machine_class = machine_parse(optarg, machines);
2348 if (!machine_class) {
2349 error_report("No machine specified, and there is no default");
2350 error_printf("Use -machine help to list supported machines\n");
2351 exit(1);
2354 loc_pop(&loc);
2355 g_slist_free(machines);
2356 return machine_class;
2359 static int object_parse_property_opt(Object *obj,
2360 const char *name, const char *value,
2361 const char *skip, Error **errp)
2363 if (g_str_equal(name, skip)) {
2364 return 0;
2367 if (!object_property_parse(obj, name, value, errp)) {
2368 return -1;
2371 return 0;
2374 static int machine_set_property(void *opaque,
2375 const char *name, const char *value,
2376 Error **errp)
2378 g_autofree char *qom_name = g_strdup(name);
2379 char *p;
2381 for (p = qom_name; *p; p++) {
2382 if (*p == '_') {
2383 *p = '-';
2387 /* Legacy options do not correspond to MachineState properties. */
2388 if (g_str_equal(qom_name, "accel")) {
2389 return 0;
2391 if (g_str_equal(qom_name, "igd-passthru")) {
2392 object_register_sugar_prop(ACCEL_CLASS_NAME("xen"), qom_name, value);
2393 return 0;
2395 if (g_str_equal(qom_name, "kvm-shadow-mem")) {
2396 object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), qom_name, value);
2397 return 0;
2399 if (g_str_equal(qom_name, "kernel-irqchip")) {
2400 object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), qom_name, value);
2401 object_register_sugar_prop(ACCEL_CLASS_NAME("whpx"), qom_name, value);
2402 return 0;
2405 return object_parse_property_opt(opaque, name, value, "type", errp);
2409 * Initial object creation happens before all other
2410 * QEMU data types are created. The majority of objects
2411 * can be created at this point. The rng-egd object
2412 * cannot be created here, as it depends on the chardev
2413 * already existing.
2415 static bool object_create_early(const char *type, QemuOpts *opts)
2417 if (user_creatable_print_help(type, opts)) {
2418 exit(0);
2422 * Objects should not be made "delayed" without a reason. If you
2423 * add one, state the reason in a comment!
2426 /* Reason: rng-egd property "chardev" */
2427 if (g_str_equal(type, "rng-egd")) {
2428 return false;
2431 #if defined(CONFIG_VHOST_USER) && defined(CONFIG_LINUX)
2432 /* Reason: cryptodev-vhost-user property "chardev" */
2433 if (g_str_equal(type, "cryptodev-vhost-user")) {
2434 return false;
2436 #endif
2438 /* Reason: vhost-user-blk-server property "node-name" */
2439 if (g_str_equal(type, "vhost-user-blk-server")) {
2440 return false;
2443 * Reason: filter-* property "netdev" etc.
2445 if (g_str_equal(type, "filter-buffer") ||
2446 g_str_equal(type, "filter-dump") ||
2447 g_str_equal(type, "filter-mirror") ||
2448 g_str_equal(type, "filter-redirector") ||
2449 g_str_equal(type, "colo-compare") ||
2450 g_str_equal(type, "filter-rewriter") ||
2451 g_str_equal(type, "filter-replay")) {
2452 return false;
2455 /* Memory allocation by backends needs to be done
2456 * after configure_accelerator() (due to the tcg_enabled()
2457 * checks at memory_region_init_*()).
2459 * Also, allocation of large amounts of memory may delay
2460 * chardev initialization for too long, and trigger timeouts
2461 * on software that waits for a monitor socket to be created
2462 * (e.g. libvirt).
2464 if (g_str_has_prefix(type, "memory-backend-")) {
2465 return false;
2468 return true;
2471 static void qemu_apply_machine_options(void)
2473 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2474 QemuOpts *machine_opts = qemu_get_machine_opts();
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;
2505 if (semihosting_enabled() && !semihosting_get_argc()) {
2506 const char *kernel_filename = qemu_opt_get(machine_opts, "kernel");
2507 const char *kernel_cmdline = qemu_opt_get(machine_opts, "append") ?: "";
2508 /* fall back to the -kernel/-append */
2509 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 void user_register_global_props(void)
2802 qemu_opts_foreach(qemu_find_opts("global"),
2803 global_init_func, NULL, NULL);
2806 static int do_configure_icount(void *opaque, QemuOpts *opts, Error **errp)
2808 icount_configure(opts, errp);
2809 return 0;
2812 static int accelerator_set_property(void *opaque,
2813 const char *name, const char *value,
2814 Error **errp)
2816 return object_parse_property_opt(opaque, name, value, "accel", errp);
2819 static int do_configure_accelerator(void *opaque, QemuOpts *opts, Error **errp)
2821 bool *p_init_failed = opaque;
2822 const char *acc = qemu_opt_get(opts, "accel");
2823 AccelClass *ac = accel_find(acc);
2824 AccelState *accel;
2825 int ret;
2826 bool qtest_with_kvm;
2828 qtest_with_kvm = g_str_equal(acc, "kvm") && qtest_chrdev != NULL;
2830 if (!ac) {
2831 *p_init_failed = true;
2832 if (!qtest_with_kvm) {
2833 error_report("invalid accelerator %s", acc);
2835 return 0;
2837 accel = ACCEL(object_new_with_class(OBJECT_CLASS(ac)));
2838 object_apply_compat_props(OBJECT(accel));
2839 qemu_opt_foreach(opts, accelerator_set_property,
2840 accel,
2841 &error_fatal);
2843 ret = accel_init_machine(accel, current_machine);
2844 if (ret < 0) {
2845 *p_init_failed = true;
2846 if (!qtest_with_kvm || ret != -ENOENT) {
2847 error_report("failed to initialize %s: %s", acc, strerror(-ret));
2849 return 0;
2852 return 1;
2855 static void configure_accelerators(const char *progname)
2857 const char *accel;
2858 bool init_failed = false;
2860 qemu_opts_foreach(qemu_find_opts("icount"),
2861 do_configure_icount, NULL, &error_fatal);
2863 accel = qemu_opt_get(qemu_get_machine_opts(), "accel");
2864 if (QTAILQ_EMPTY(&qemu_accel_opts.head)) {
2865 char **accel_list, **tmp;
2867 if (accel == NULL) {
2868 /* Select the default accelerator */
2869 bool have_tcg = accel_find("tcg");
2870 bool have_kvm = accel_find("kvm");
2872 if (have_tcg && have_kvm) {
2873 if (g_str_has_suffix(progname, "kvm")) {
2874 /* If the program name ends with "kvm", we prefer KVM */
2875 accel = "kvm:tcg";
2876 } else {
2877 accel = "tcg:kvm";
2879 } else if (have_kvm) {
2880 accel = "kvm";
2881 } else if (have_tcg) {
2882 accel = "tcg";
2883 } else {
2884 error_report("No accelerator selected and"
2885 " no default accelerator available");
2886 exit(1);
2889 accel_list = g_strsplit(accel, ":", 0);
2891 for (tmp = accel_list; *tmp; tmp++) {
2893 * Filter invalid accelerators here, to prevent obscenities
2894 * such as "-machine accel=tcg,,thread=single".
2896 if (accel_find(*tmp)) {
2897 qemu_opts_parse_noisily(qemu_find_opts("accel"), *tmp, true);
2898 } else {
2899 init_failed = true;
2900 error_report("invalid accelerator %s", *tmp);
2903 g_strfreev(accel_list);
2904 } else {
2905 if (accel != NULL) {
2906 error_report("The -accel and \"-machine accel=\" options are incompatible");
2907 exit(1);
2911 if (!qemu_opts_foreach(qemu_find_opts("accel"),
2912 do_configure_accelerator, &init_failed, &error_fatal)) {
2913 if (!init_failed) {
2914 error_report("no accelerator found");
2916 exit(1);
2919 if (init_failed && !qtest_chrdev) {
2920 AccelClass *ac = ACCEL_GET_CLASS(current_accel());
2921 error_report("falling back to %s", ac->name);
2924 if (icount_enabled() && !tcg_enabled()) {
2925 error_report("-icount is not allowed with hardware virtualization");
2926 exit(1);
2930 static void create_default_memdev(MachineState *ms, const char *path)
2932 Object *obj;
2933 MachineClass *mc = MACHINE_GET_CLASS(ms);
2935 obj = object_new(path ? TYPE_MEMORY_BACKEND_FILE : TYPE_MEMORY_BACKEND_RAM);
2936 if (path) {
2937 object_property_set_str(obj, "mem-path", path, &error_fatal);
2939 object_property_set_int(obj, "size", ms->ram_size, &error_fatal);
2940 object_property_add_child(object_get_objects_root(), mc->default_ram_id,
2941 obj);
2942 /* Ensure backend's memory region name is equal to mc->default_ram_id */
2943 object_property_set_bool(obj, "x-use-canonical-path-for-ramblock-id",
2944 false, &error_fatal);
2945 user_creatable_complete(USER_CREATABLE(obj), &error_fatal);
2946 object_unref(obj);
2947 object_property_set_str(OBJECT(ms), "memory-backend", mc->default_ram_id,
2948 &error_fatal);
2951 static void qemu_validate_options(void)
2953 QemuOpts *machine_opts = qemu_get_machine_opts();
2954 const char *kernel_filename = qemu_opt_get(machine_opts, "kernel");
2955 const char *initrd_filename = qemu_opt_get(machine_opts, "initrd");
2956 const char *kernel_cmdline = qemu_opt_get(machine_opts, "append");
2958 if (kernel_filename == NULL) {
2959 if (kernel_cmdline != NULL) {
2960 error_report("-append only allowed with -kernel option");
2961 exit(1);
2964 if (initrd_filename != NULL) {
2965 error_report("-initrd only allowed with -kernel option");
2966 exit(1);
2970 if (loadvm && preconfig_requested) {
2971 error_report("'preconfig' and 'loadvm' options are "
2972 "mutually exclusive");
2973 exit(EXIT_FAILURE);
2975 if (incoming && preconfig_requested) {
2976 error_report("'preconfig' and 'incoming' options are "
2977 "mutually exclusive");
2978 exit(EXIT_FAILURE);
2981 #ifdef CONFIG_CURSES
2982 if (is_daemonized() && dpy.type == DISPLAY_TYPE_CURSES) {
2983 error_report("curses display cannot be used with -daemonize");
2984 exit(1);
2986 #endif
2989 static void qemu_process_sugar_options(void)
2991 if (mem_prealloc) {
2992 char *val;
2994 val = g_strdup_printf("%d",
2995 (uint32_t) qemu_opt_get_number(qemu_find_opts_singleton("smp-opts"), "cpus", 1));
2996 object_register_sugar_prop("memory-backend", "prealloc-threads", val);
2997 g_free(val);
2998 object_register_sugar_prop("memory-backend", "prealloc", "on");
3001 if (watchdog) {
3002 int i = select_watchdog(watchdog);
3003 if (i > 0)
3004 exit (i == 1 ? 1 : 0);
3008 static void qemu_process_early_options(void)
3010 #ifdef CONFIG_SECCOMP
3011 QemuOptsList *olist = qemu_find_opts_err("sandbox", NULL);
3012 if (olist) {
3013 qemu_opts_foreach(olist, parse_sandbox, NULL, &error_fatal);
3015 #endif
3017 qemu_opts_foreach(qemu_find_opts("name"),
3018 parse_name, NULL, &error_fatal);
3020 #ifndef _WIN32
3021 qemu_opts_foreach(qemu_find_opts("add-fd"),
3022 parse_add_fd, NULL, &error_fatal);
3024 qemu_opts_foreach(qemu_find_opts("add-fd"),
3025 cleanup_add_fd, NULL, &error_fatal);
3026 #endif
3028 if (!trace_init_backends()) {
3029 exit(1);
3031 trace_init_file();
3033 /* Open the logfile at this point and set the log mask if necessary. */
3034 qemu_set_log_filename(log_file, &error_fatal);
3035 if (log_mask) {
3036 int mask;
3037 mask = qemu_str_to_log_mask(log_mask);
3038 if (!mask) {
3039 qemu_print_log_usage(stdout);
3040 exit(1);
3042 qemu_set_log(mask);
3043 } else {
3044 qemu_set_log(0);
3047 qemu_add_default_firmwarepath();
3050 static void qemu_process_help_options(void)
3053 * Check for -cpu help and -device help before we call select_machine(),
3054 * which will return an error if the architecture has no default machine
3055 * type and the user did not specify one, so that the user doesn't need
3056 * to say '-cpu help -machine something'.
3058 if (cpu_option && is_help_option(cpu_option)) {
3059 list_cpus(cpu_option);
3060 exit(0);
3063 if (qemu_opts_foreach(qemu_find_opts("device"),
3064 device_help_func, NULL, NULL)) {
3065 exit(0);
3068 /* -L help lists the data directories and exits. */
3069 if (list_data_dirs) {
3070 qemu_list_data_dirs();
3071 exit(0);
3075 static void qemu_maybe_daemonize(const char *pid_file)
3077 Error *err;
3079 os_daemonize();
3080 rcu_disable_atfork();
3082 if (pid_file && !qemu_write_pidfile(pid_file, &err)) {
3083 error_reportf_err(err, "cannot create PID file: ");
3084 exit(1);
3087 qemu_unlink_pidfile_notifier.notify = qemu_unlink_pidfile;
3088 qemu_add_exit_notifier(&qemu_unlink_pidfile_notifier);
3091 static void qemu_init_subsystems(void)
3093 Error *err;
3095 os_set_line_buffering();
3097 module_call_init(MODULE_INIT_TRACE);
3099 qemu_init_cpu_list();
3100 qemu_init_cpu_loop();
3101 qemu_mutex_lock_iothread();
3103 atexit(qemu_run_exit_notifiers);
3105 module_call_init(MODULE_INIT_QOM);
3106 module_call_init(MODULE_INIT_MIGRATION);
3108 runstate_init();
3109 precopy_infrastructure_init();
3110 postcopy_infrastructure_init();
3111 monitor_init_globals();
3113 if (qcrypto_init(&err) < 0) {
3114 error_reportf_err(err, "cannot initialize crypto: ");
3115 exit(1);
3118 os_setup_early_signal_handling();
3120 bdrv_init_with_whitelist();
3121 socket_init();
3124 static void qemu_init_displays(void)
3126 DisplayState *ds;
3128 /* init local displays */
3129 ds = init_displaystate();
3130 qemu_display_init(ds, &dpy);
3132 /* must be after terminal init, SDL library changes signal handlers */
3133 os_setup_signal_handling();
3135 /* init remote displays */
3136 #ifdef CONFIG_VNC
3137 qemu_opts_foreach(qemu_find_opts("vnc"),
3138 vnc_init_func, NULL, &error_fatal);
3139 #endif
3141 if (using_spice) {
3142 qemu_spice.display_init();
3147 * Called after leaving preconfig state. From here on runstate is
3148 * RUN_STATE_PRELAUNCH or RUN_STATE_INMIGRATE.
3150 static void qemu_init_board(void)
3152 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
3154 if (machine_class->default_ram_id && current_machine->ram_size &&
3155 numa_uses_legacy_mem() && !current_machine->ram_memdev_id) {
3156 create_default_memdev(current_machine, mem_path);
3159 /* process plugin before CPUs are created, but once -smp has been parsed */
3160 if (qemu_plugin_load_list(&plugin_list)) {
3161 exit(1);
3164 machine_run_board_init(current_machine);
3167 * TODO To drop support for deprecated bogus if=..., move
3168 * drive_check_orphaned() here, replacing this call. Also drop
3169 * its deprecation warning, along with DriveInfo member
3170 * @claimed_by_board.
3172 drive_mark_claimed_by_board();
3174 realtime_init();
3176 if (hax_enabled()) {
3177 /* FIXME: why isn't cpu_synchronize_all_post_init enough? */
3178 hax_sync_vcpus();
3182 static void qemu_create_cli_devices(void)
3184 soundhw_init();
3186 qemu_opts_foreach(qemu_find_opts("fw_cfg"),
3187 parse_fw_cfg, fw_cfg_find(), &error_fatal);
3189 /* init USB devices */
3190 if (machine_usb(current_machine)) {
3191 if (foreach_device_config(DEV_USB, usb_parse) < 0)
3192 exit(1);
3195 /* init generic devices */
3196 rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
3197 qemu_opts_foreach(qemu_find_opts("device"),
3198 device_init_func, NULL, &error_fatal);
3199 rom_reset_order_override();
3202 static void qemu_machine_creation_done(void)
3204 cpu_synchronize_all_post_init();
3206 /* Did we create any drives that we failed to create a device for? */
3207 drive_check_orphaned();
3209 /* Don't warn about the default network setup that you get if
3210 * no command line -net or -netdev options are specified. There
3211 * are two cases that we would otherwise complain about:
3212 * (1) board doesn't support a NIC but the implicit "-net nic"
3213 * requested one
3214 * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
3215 * sets up a nic that isn't connected to anything.
3217 if (!default_net && (!qtest_enabled() || has_defaults)) {
3218 net_check_clients();
3221 qdev_prop_check_globals();
3223 if (boot_once) {
3224 qemu_boot_set(boot_once, &error_fatal);
3225 qemu_register_reset(restore_boot_order, g_strdup(boot_order));
3228 if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
3229 exit(1);
3232 qdev_machine_creation_done();
3234 /* TODO: once all bus devices are qdevified, this should be done
3235 * when bus is created by qdev.c */
3237 * TODO: If we had a main 'reset container' that the whole system
3238 * lived in, we could reset that using the multi-phase reset
3239 * APIs. For the moment, we just reset the sysbus, which will cause
3240 * all devices hanging off it (and all their child buses, recursively)
3241 * to be reset. Note that this will *not* reset any Device objects
3242 * which are not attached to some part of the qbus tree!
3244 qemu_register_reset(resettable_cold_reset_fn, sysbus_get_default());
3245 qemu_run_machine_init_done_notifiers();
3247 if (rom_check_and_register_reset() != 0) {
3248 error_report("rom check and register reset failed");
3249 exit(1);
3252 replay_start();
3254 /* This checkpoint is required by replay to separate prior clock
3255 reading from the other reads, because timer polling functions query
3256 clock values from the log. */
3257 replay_checkpoint(CHECKPOINT_RESET);
3258 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
3259 register_global_state();
3262 void qemu_init(int argc, char **argv, char **envp)
3264 QemuOpts *opts;
3265 QemuOpts *icount_opts = NULL, *accel_opts = NULL;
3266 QemuOptsList *olist;
3267 int optind;
3268 const char *optarg;
3269 MachineClass *machine_class;
3270 bool userconfig = true;
3271 FILE *vmstate_dump_file = NULL;
3273 qemu_add_opts(&qemu_drive_opts);
3274 qemu_add_drive_opts(&qemu_legacy_drive_opts);
3275 qemu_add_drive_opts(&qemu_common_drive_opts);
3276 qemu_add_drive_opts(&qemu_drive_opts);
3277 qemu_add_drive_opts(&bdrv_runtime_opts);
3278 qemu_add_opts(&qemu_chardev_opts);
3279 qemu_add_opts(&qemu_device_opts);
3280 qemu_add_opts(&qemu_netdev_opts);
3281 qemu_add_opts(&qemu_nic_opts);
3282 qemu_add_opts(&qemu_net_opts);
3283 qemu_add_opts(&qemu_rtc_opts);
3284 qemu_add_opts(&qemu_global_opts);
3285 qemu_add_opts(&qemu_mon_opts);
3286 qemu_add_opts(&qemu_trace_opts);
3287 qemu_plugin_add_opts();
3288 qemu_add_opts(&qemu_option_rom_opts);
3289 qemu_add_opts(&qemu_machine_opts);
3290 qemu_add_opts(&qemu_accel_opts);
3291 qemu_add_opts(&qemu_mem_opts);
3292 qemu_add_opts(&qemu_smp_opts);
3293 qemu_add_opts(&qemu_boot_opts);
3294 qemu_add_opts(&qemu_add_fd_opts);
3295 qemu_add_opts(&qemu_object_opts);
3296 qemu_add_opts(&qemu_tpmdev_opts);
3297 qemu_add_opts(&qemu_realtime_opts);
3298 qemu_add_opts(&qemu_overcommit_opts);
3299 qemu_add_opts(&qemu_msg_opts);
3300 qemu_add_opts(&qemu_name_opts);
3301 qemu_add_opts(&qemu_numa_opts);
3302 qemu_add_opts(&qemu_icount_opts);
3303 qemu_add_opts(&qemu_semihosting_config_opts);
3304 qemu_add_opts(&qemu_fw_cfg_opts);
3305 module_call_init(MODULE_INIT_OPTS);
3307 error_init(argv[0]);
3308 qemu_init_exec_dir(argv[0]);
3310 qemu_init_subsystems();
3312 /* first pass of option parsing */
3313 optind = 1;
3314 while (optind < argc) {
3315 if (argv[optind][0] != '-') {
3316 /* disk image */
3317 optind++;
3318 } else {
3319 const QEMUOption *popt;
3321 popt = lookup_opt(argc, argv, &optarg, &optind);
3322 switch (popt->index) {
3323 case QEMU_OPTION_nouserconfig:
3324 userconfig = false;
3325 break;
3330 if (userconfig) {
3331 if (qemu_read_default_config_file() < 0) {
3332 exit(1);
3336 /* second pass of option parsing */
3337 optind = 1;
3338 for(;;) {
3339 if (optind >= argc)
3340 break;
3341 if (argv[optind][0] != '-') {
3342 loc_set_cmdline(argv, optind, 1);
3343 drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
3344 } else {
3345 const QEMUOption *popt;
3347 popt = lookup_opt(argc, argv, &optarg, &optind);
3348 if (!(popt->arch_mask & arch_type)) {
3349 error_report("Option not supported for this target");
3350 exit(1);
3352 switch(popt->index) {
3353 case QEMU_OPTION_cpu:
3354 /* hw initialization will check this */
3355 cpu_option = optarg;
3356 break;
3357 case QEMU_OPTION_hda:
3358 case QEMU_OPTION_hdb:
3359 case QEMU_OPTION_hdc:
3360 case QEMU_OPTION_hdd:
3361 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
3362 HD_OPTS);
3363 break;
3364 case QEMU_OPTION_blockdev:
3366 Visitor *v;
3367 BlockdevOptionsQueueEntry *bdo;
3369 v = qobject_input_visitor_new_str(optarg, "driver",
3370 &error_fatal);
3372 bdo = g_new(BlockdevOptionsQueueEntry, 1);
3373 visit_type_BlockdevOptions(v, NULL, &bdo->bdo,
3374 &error_fatal);
3375 visit_free(v);
3376 loc_save(&bdo->loc);
3377 QSIMPLEQ_INSERT_TAIL(&bdo_queue, bdo, entry);
3378 break;
3380 case QEMU_OPTION_drive:
3381 if (drive_def(optarg) == NULL) {
3382 exit(1);
3384 break;
3385 case QEMU_OPTION_set:
3386 if (qemu_set_option(optarg) != 0)
3387 exit(1);
3388 break;
3389 case QEMU_OPTION_global:
3390 if (qemu_global_option(optarg) != 0)
3391 exit(1);
3392 break;
3393 case QEMU_OPTION_mtdblock:
3394 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
3395 break;
3396 case QEMU_OPTION_sd:
3397 drive_add(IF_SD, -1, optarg, SD_OPTS);
3398 break;
3399 case QEMU_OPTION_pflash:
3400 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
3401 break;
3402 case QEMU_OPTION_snapshot:
3404 Error *blocker = NULL;
3405 snapshot = 1;
3406 error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
3407 "-snapshot");
3408 replay_add_blocker(blocker);
3410 break;
3411 case QEMU_OPTION_numa:
3412 opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
3413 optarg, true);
3414 if (!opts) {
3415 exit(1);
3417 break;
3418 case QEMU_OPTION_display:
3419 parse_display(optarg);
3420 break;
3421 case QEMU_OPTION_nographic:
3422 olist = qemu_find_opts("machine");
3423 qemu_opts_parse_noisily(olist, "graphics=off", false);
3424 nographic = true;
3425 dpy.type = DISPLAY_TYPE_NONE;
3426 break;
3427 case QEMU_OPTION_curses:
3428 #ifdef CONFIG_CURSES
3429 dpy.type = DISPLAY_TYPE_CURSES;
3430 #else
3431 error_report("curses or iconv support is disabled");
3432 exit(1);
3433 #endif
3434 break;
3435 case QEMU_OPTION_portrait:
3436 graphic_rotate = 90;
3437 break;
3438 case QEMU_OPTION_rotate:
3439 graphic_rotate = strtol(optarg, (char **) &optarg, 10);
3440 if (graphic_rotate != 0 && graphic_rotate != 90 &&
3441 graphic_rotate != 180 && graphic_rotate != 270) {
3442 error_report("only 90, 180, 270 deg rotation is available");
3443 exit(1);
3445 break;
3446 case QEMU_OPTION_kernel:
3447 qemu_opts_set(qemu_find_opts("machine"), "kernel", optarg, &error_abort);
3448 break;
3449 case QEMU_OPTION_initrd:
3450 qemu_opts_set(qemu_find_opts("machine"), "initrd", optarg, &error_abort);
3451 break;
3452 case QEMU_OPTION_append:
3453 qemu_opts_set(qemu_find_opts("machine"), "append", optarg, &error_abort);
3454 break;
3455 case QEMU_OPTION_dtb:
3456 qemu_opts_set(qemu_find_opts("machine"), "dtb", optarg, &error_abort);
3457 break;
3458 case QEMU_OPTION_cdrom:
3459 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
3460 break;
3461 case QEMU_OPTION_boot:
3462 opts = qemu_opts_parse_noisily(qemu_find_opts("boot-opts"),
3463 optarg, true);
3464 if (!opts) {
3465 exit(1);
3467 break;
3468 case QEMU_OPTION_fda:
3469 case QEMU_OPTION_fdb:
3470 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
3471 optarg, FD_OPTS);
3472 break;
3473 case QEMU_OPTION_no_fd_bootchk:
3474 fd_bootchk = 0;
3475 break;
3476 case QEMU_OPTION_netdev:
3477 default_net = 0;
3478 if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
3479 exit(1);
3481 break;
3482 case QEMU_OPTION_nic:
3483 default_net = 0;
3484 if (net_client_parse(qemu_find_opts("nic"), optarg) == -1) {
3485 exit(1);
3487 break;
3488 case QEMU_OPTION_net:
3489 default_net = 0;
3490 if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
3491 exit(1);
3493 break;
3494 #ifdef CONFIG_LIBISCSI
3495 case QEMU_OPTION_iscsi:
3496 opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
3497 optarg, false);
3498 if (!opts) {
3499 exit(1);
3501 break;
3502 #endif
3503 case QEMU_OPTION_audio_help:
3504 audio_legacy_help();
3505 exit (0);
3506 break;
3507 case QEMU_OPTION_audiodev:
3508 audio_parse_option(optarg);
3509 break;
3510 case QEMU_OPTION_soundhw:
3511 select_soundhw (optarg);
3512 break;
3513 case QEMU_OPTION_h:
3514 help(0);
3515 break;
3516 case QEMU_OPTION_version:
3517 version();
3518 exit(0);
3519 break;
3520 case QEMU_OPTION_m:
3521 opts = qemu_opts_parse_noisily(qemu_find_opts("memory"),
3522 optarg, true);
3523 if (!opts) {
3524 exit(EXIT_FAILURE);
3526 break;
3527 #ifdef CONFIG_TPM
3528 case QEMU_OPTION_tpmdev:
3529 if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3530 exit(1);
3532 break;
3533 #endif
3534 case QEMU_OPTION_mempath:
3535 mem_path = optarg;
3536 break;
3537 case QEMU_OPTION_mem_prealloc:
3538 mem_prealloc = 1;
3539 break;
3540 case QEMU_OPTION_d:
3541 log_mask = optarg;
3542 break;
3543 case QEMU_OPTION_D:
3544 log_file = optarg;
3545 break;
3546 case QEMU_OPTION_DFILTER:
3547 qemu_set_dfilter_ranges(optarg, &error_fatal);
3548 break;
3549 case QEMU_OPTION_seed:
3550 qemu_guest_random_seed_main(optarg, &error_fatal);
3551 break;
3552 case QEMU_OPTION_s:
3553 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3554 break;
3555 case QEMU_OPTION_gdb:
3556 add_device_config(DEV_GDB, optarg);
3557 break;
3558 case QEMU_OPTION_L:
3559 if (is_help_option(optarg)) {
3560 list_data_dirs = true;
3561 } else {
3562 qemu_add_data_dir(g_strdup(optarg));
3564 break;
3565 case QEMU_OPTION_bios:
3566 qemu_opts_set(qemu_find_opts("machine"), "firmware", optarg, &error_abort);
3567 break;
3568 case QEMU_OPTION_singlestep:
3569 singlestep = 1;
3570 break;
3571 case QEMU_OPTION_S:
3572 autostart = 0;
3573 break;
3574 case QEMU_OPTION_k:
3575 keyboard_layout = optarg;
3576 break;
3577 case QEMU_OPTION_vga:
3578 vga_model = optarg;
3579 default_vga = 0;
3580 break;
3581 case QEMU_OPTION_g:
3583 const char *p;
3584 int w, h, depth;
3585 p = optarg;
3586 w = strtol(p, (char **)&p, 10);
3587 if (w <= 0) {
3588 graphic_error:
3589 error_report("invalid resolution or depth");
3590 exit(1);
3592 if (*p != 'x')
3593 goto graphic_error;
3594 p++;
3595 h = strtol(p, (char **)&p, 10);
3596 if (h <= 0)
3597 goto graphic_error;
3598 if (*p == 'x') {
3599 p++;
3600 depth = strtol(p, (char **)&p, 10);
3601 if (depth != 1 && depth != 2 && depth != 4 &&
3602 depth != 8 && depth != 15 && depth != 16 &&
3603 depth != 24 && depth != 32)
3604 goto graphic_error;
3605 } else if (*p == '\0') {
3606 depth = graphic_depth;
3607 } else {
3608 goto graphic_error;
3611 graphic_width = w;
3612 graphic_height = h;
3613 graphic_depth = depth;
3615 break;
3616 case QEMU_OPTION_echr:
3618 char *r;
3619 term_escape_char = strtol(optarg, &r, 0);
3620 if (r == optarg)
3621 printf("Bad argument to echr\n");
3622 break;
3624 case QEMU_OPTION_monitor:
3625 default_monitor = 0;
3626 if (strncmp(optarg, "none", 4)) {
3627 monitor_parse(optarg, "readline", false);
3629 break;
3630 case QEMU_OPTION_qmp:
3631 monitor_parse(optarg, "control", false);
3632 default_monitor = 0;
3633 break;
3634 case QEMU_OPTION_qmp_pretty:
3635 monitor_parse(optarg, "control", true);
3636 default_monitor = 0;
3637 break;
3638 case QEMU_OPTION_mon:
3639 opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
3640 true);
3641 if (!opts) {
3642 exit(1);
3644 default_monitor = 0;
3645 break;
3646 case QEMU_OPTION_chardev:
3647 opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
3648 optarg, true);
3649 if (!opts) {
3650 exit(1);
3652 break;
3653 case QEMU_OPTION_fsdev:
3654 olist = qemu_find_opts("fsdev");
3655 if (!olist) {
3656 error_report("fsdev support is disabled");
3657 exit(1);
3659 opts = qemu_opts_parse_noisily(olist, optarg, true);
3660 if (!opts) {
3661 exit(1);
3663 break;
3664 case QEMU_OPTION_virtfs: {
3665 QemuOpts *fsdev;
3666 QemuOpts *device;
3667 const char *writeout, *sock_fd, *socket, *path, *security_model,
3668 *multidevs;
3670 olist = qemu_find_opts("virtfs");
3671 if (!olist) {
3672 error_report("virtfs support is disabled");
3673 exit(1);
3675 opts = qemu_opts_parse_noisily(olist, optarg, true);
3676 if (!opts) {
3677 exit(1);
3680 if (qemu_opt_get(opts, "fsdriver") == NULL ||
3681 qemu_opt_get(opts, "mount_tag") == NULL) {
3682 error_report("Usage: -virtfs fsdriver,mount_tag=tag");
3683 exit(1);
3685 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3686 qemu_opts_id(opts) ?:
3687 qemu_opt_get(opts, "mount_tag"),
3688 1, NULL);
3689 if (!fsdev) {
3690 error_report("duplicate or invalid fsdev id: %s",
3691 qemu_opt_get(opts, "mount_tag"));
3692 exit(1);
3695 writeout = qemu_opt_get(opts, "writeout");
3696 if (writeout) {
3697 #ifdef CONFIG_SYNC_FILE_RANGE
3698 qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
3699 #else
3700 error_report("writeout=immediate not supported "
3701 "on this platform");
3702 exit(1);
3703 #endif
3705 qemu_opt_set(fsdev, "fsdriver",
3706 qemu_opt_get(opts, "fsdriver"), &error_abort);
3707 path = qemu_opt_get(opts, "path");
3708 if (path) {
3709 qemu_opt_set(fsdev, "path", path, &error_abort);
3711 security_model = qemu_opt_get(opts, "security_model");
3712 if (security_model) {
3713 qemu_opt_set(fsdev, "security_model", security_model,
3714 &error_abort);
3716 socket = qemu_opt_get(opts, "socket");
3717 if (socket) {
3718 qemu_opt_set(fsdev, "socket", socket, &error_abort);
3720 sock_fd = qemu_opt_get(opts, "sock_fd");
3721 if (sock_fd) {
3722 qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
3725 qemu_opt_set_bool(fsdev, "readonly",
3726 qemu_opt_get_bool(opts, "readonly", 0),
3727 &error_abort);
3728 multidevs = qemu_opt_get(opts, "multidevs");
3729 if (multidevs) {
3730 qemu_opt_set(fsdev, "multidevs", multidevs, &error_abort);
3732 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3733 &error_abort);
3734 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3735 qemu_opt_set(device, "fsdev",
3736 qemu_opts_id(fsdev), &error_abort);
3737 qemu_opt_set(device, "mount_tag",
3738 qemu_opt_get(opts, "mount_tag"), &error_abort);
3739 break;
3741 case QEMU_OPTION_serial:
3742 add_device_config(DEV_SERIAL, optarg);
3743 default_serial = 0;
3744 if (strncmp(optarg, "mon:", 4) == 0) {
3745 default_monitor = 0;
3747 break;
3748 case QEMU_OPTION_watchdog:
3749 if (watchdog) {
3750 error_report("only one watchdog option may be given");
3751 exit(1);
3753 watchdog = optarg;
3754 break;
3755 case QEMU_OPTION_watchdog_action:
3756 if (select_watchdog_action(optarg) == -1) {
3757 error_report("unknown -watchdog-action parameter");
3758 exit(1);
3760 break;
3761 case QEMU_OPTION_parallel:
3762 add_device_config(DEV_PARALLEL, optarg);
3763 default_parallel = 0;
3764 if (strncmp(optarg, "mon:", 4) == 0) {
3765 default_monitor = 0;
3767 break;
3768 case QEMU_OPTION_debugcon:
3769 add_device_config(DEV_DEBUGCON, optarg);
3770 break;
3771 case QEMU_OPTION_loadvm:
3772 loadvm = optarg;
3773 break;
3774 case QEMU_OPTION_full_screen:
3775 dpy.has_full_screen = true;
3776 dpy.full_screen = true;
3777 break;
3778 case QEMU_OPTION_alt_grab:
3779 alt_grab = 1;
3780 break;
3781 case QEMU_OPTION_ctrl_grab:
3782 ctrl_grab = 1;
3783 break;
3784 case QEMU_OPTION_no_quit:
3785 dpy.has_window_close = true;
3786 dpy.window_close = false;
3787 break;
3788 case QEMU_OPTION_sdl:
3789 #ifdef CONFIG_SDL
3790 dpy.type = DISPLAY_TYPE_SDL;
3791 break;
3792 #else
3793 error_report("SDL support is disabled");
3794 exit(1);
3795 #endif
3796 case QEMU_OPTION_pidfile:
3797 pid_file = optarg;
3798 break;
3799 case QEMU_OPTION_win2k_hack:
3800 win2k_install_hack = 1;
3801 break;
3802 case QEMU_OPTION_acpitable:
3803 opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
3804 optarg, true);
3805 if (!opts) {
3806 exit(1);
3808 acpi_table_add(opts, &error_fatal);
3809 break;
3810 case QEMU_OPTION_smbios:
3811 opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
3812 optarg, false);
3813 if (!opts) {
3814 exit(1);
3816 smbios_entry_add(opts, &error_fatal);
3817 break;
3818 case QEMU_OPTION_fwcfg:
3819 opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
3820 optarg, true);
3821 if (opts == NULL) {
3822 exit(1);
3824 break;
3825 case QEMU_OPTION_preconfig:
3826 preconfig_exit_requested = false;
3827 preconfig_requested = true;
3828 break;
3829 case QEMU_OPTION_enable_kvm:
3830 olist = qemu_find_opts("machine");
3831 qemu_opts_parse_noisily(olist, "accel=kvm", false);
3832 break;
3833 case QEMU_OPTION_M:
3834 case QEMU_OPTION_machine:
3835 olist = qemu_find_opts("machine");
3836 opts = qemu_opts_parse_noisily(olist, optarg, true);
3837 if (!opts) {
3838 exit(1);
3840 break;
3841 case QEMU_OPTION_accel:
3842 accel_opts = qemu_opts_parse_noisily(qemu_find_opts("accel"),
3843 optarg, true);
3844 optarg = qemu_opt_get(accel_opts, "accel");
3845 if (!optarg || is_help_option(optarg)) {
3846 printf("Accelerators supported in QEMU binary:\n");
3847 GSList *el, *accel_list = object_class_get_list(TYPE_ACCEL,
3848 false);
3849 for (el = accel_list; el; el = el->next) {
3850 gchar *typename = g_strdup(object_class_get_name(
3851 OBJECT_CLASS(el->data)));
3852 /* omit qtest which is used for tests only */
3853 if (g_strcmp0(typename, ACCEL_CLASS_NAME("qtest")) &&
3854 g_str_has_suffix(typename, ACCEL_CLASS_SUFFIX)) {
3855 gchar **optname = g_strsplit(typename,
3856 ACCEL_CLASS_SUFFIX, 0);
3857 printf("%s\n", optname[0]);
3858 g_strfreev(optname);
3860 g_free(typename);
3862 g_slist_free(accel_list);
3863 exit(0);
3865 break;
3866 case QEMU_OPTION_usb:
3867 olist = qemu_find_opts("machine");
3868 qemu_opts_parse_noisily(olist, "usb=on", false);
3869 break;
3870 case QEMU_OPTION_usbdevice:
3871 error_report("'-usbdevice' is deprecated, please use "
3872 "'-device usb-...' instead");
3873 olist = qemu_find_opts("machine");
3874 qemu_opts_parse_noisily(olist, "usb=on", false);
3875 add_device_config(DEV_USB, optarg);
3876 break;
3877 case QEMU_OPTION_device:
3878 if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
3879 optarg, true)) {
3880 exit(1);
3882 break;
3883 case QEMU_OPTION_smp:
3884 if (!qemu_opts_parse_noisily(qemu_find_opts("smp-opts"),
3885 optarg, true)) {
3886 exit(1);
3888 break;
3889 case QEMU_OPTION_vnc:
3890 vnc_parse(optarg, &error_fatal);
3891 break;
3892 case QEMU_OPTION_no_acpi:
3893 olist = qemu_find_opts("machine");
3894 qemu_opts_parse_noisily(olist, "acpi=off", false);
3895 break;
3896 case QEMU_OPTION_no_hpet:
3897 olist = qemu_find_opts("machine");
3898 qemu_opts_parse_noisily(olist, "hpet=off", false);
3899 break;
3900 case QEMU_OPTION_no_reboot:
3901 no_reboot = 1;
3902 break;
3903 case QEMU_OPTION_no_shutdown:
3904 no_shutdown = 1;
3905 break;
3906 case QEMU_OPTION_show_cursor:
3907 warn_report("The -show-cursor option is deprecated. Please "
3908 "add show-cursor=on to your -display options.");
3909 warn_report("When using the default display you can use "
3910 "-display default,show-cursor=on");
3911 dpy.has_show_cursor = true;
3912 dpy.show_cursor = true;
3913 break;
3914 case QEMU_OPTION_uuid:
3915 if (qemu_uuid_parse(optarg, &qemu_uuid) < 0) {
3916 error_report("failed to parse UUID string: wrong format");
3917 exit(1);
3919 qemu_uuid_set = true;
3920 break;
3921 case QEMU_OPTION_option_rom:
3922 if (nb_option_roms >= MAX_OPTION_ROMS) {
3923 error_report("too many option ROMs");
3924 exit(1);
3926 opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
3927 optarg, true);
3928 if (!opts) {
3929 exit(1);
3931 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3932 option_rom[nb_option_roms].bootindex =
3933 qemu_opt_get_number(opts, "bootindex", -1);
3934 if (!option_rom[nb_option_roms].name) {
3935 error_report("Option ROM file is not specified");
3936 exit(1);
3938 nb_option_roms++;
3939 break;
3940 case QEMU_OPTION_semihosting:
3941 qemu_semihosting_enable();
3942 break;
3943 case QEMU_OPTION_semihosting_config:
3944 if (qemu_semihosting_config_options(optarg) != 0) {
3945 exit(1);
3947 break;
3948 case QEMU_OPTION_name:
3949 opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
3950 optarg, true);
3951 if (!opts) {
3952 exit(1);
3954 /* Capture guest name if -msg guest-name is used later */
3955 error_guest_name = qemu_opt_get(opts, "guest");
3956 break;
3957 case QEMU_OPTION_prom_env:
3958 if (nb_prom_envs >= MAX_PROM_ENVS) {
3959 error_report("too many prom variables");
3960 exit(1);
3962 prom_envs[nb_prom_envs] = optarg;
3963 nb_prom_envs++;
3964 break;
3965 case QEMU_OPTION_old_param:
3966 old_param = 1;
3967 break;
3968 case QEMU_OPTION_rtc:
3969 opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
3970 false);
3971 if (!opts) {
3972 exit(1);
3974 break;
3975 case QEMU_OPTION_tb_size:
3976 #ifndef CONFIG_TCG
3977 error_report("TCG is disabled");
3978 exit(1);
3979 #endif
3980 warn_report("The -tb-size option is deprecated, use -accel tcg,tb-size instead");
3981 object_register_sugar_prop(ACCEL_CLASS_NAME("tcg"), "tb-size", optarg);
3982 break;
3983 case QEMU_OPTION_icount:
3984 icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
3985 optarg, true);
3986 if (!icount_opts) {
3987 exit(1);
3989 break;
3990 case QEMU_OPTION_incoming:
3991 if (!incoming) {
3992 runstate_set(RUN_STATE_INMIGRATE);
3994 incoming = optarg;
3995 break;
3996 case QEMU_OPTION_only_migratable:
3997 only_migratable = 1;
3998 break;
3999 case QEMU_OPTION_nodefaults:
4000 has_defaults = 0;
4001 break;
4002 case QEMU_OPTION_xen_domid:
4003 if (!(xen_available())) {
4004 error_report("Option not supported for this target");
4005 exit(1);
4007 xen_domid = atoi(optarg);
4008 break;
4009 case QEMU_OPTION_xen_attach:
4010 if (!(xen_available())) {
4011 error_report("Option not supported for this target");
4012 exit(1);
4014 xen_mode = XEN_ATTACH;
4015 break;
4016 case QEMU_OPTION_xen_domid_restrict:
4017 if (!(xen_available())) {
4018 error_report("Option not supported for this target");
4019 exit(1);
4021 xen_domid_restrict = true;
4022 break;
4023 case QEMU_OPTION_trace:
4024 trace_opt_parse(optarg);
4025 break;
4026 case QEMU_OPTION_plugin:
4027 qemu_plugin_opt_parse(optarg, &plugin_list);
4028 break;
4029 case QEMU_OPTION_readconfig:
4031 int ret = qemu_read_config_file(optarg);
4032 if (ret < 0) {
4033 error_report("read config %s: %s", optarg,
4034 strerror(-ret));
4035 exit(1);
4037 break;
4039 case QEMU_OPTION_spice:
4040 olist = qemu_find_opts_err("spice", NULL);
4041 if (!olist) {
4042 ui_module_load_one("spice-core");
4043 olist = qemu_find_opts("spice");
4045 if (!olist) {
4046 error_report("spice support is disabled");
4047 exit(1);
4049 opts = qemu_opts_parse_noisily(olist, optarg, false);
4050 if (!opts) {
4051 exit(1);
4053 display_remote++;
4054 break;
4055 case QEMU_OPTION_writeconfig:
4057 FILE *fp;
4058 if (strcmp(optarg, "-") == 0) {
4059 fp = stdout;
4060 } else {
4061 fp = fopen(optarg, "w");
4062 if (fp == NULL) {
4063 error_report("open %s: %s", optarg,
4064 strerror(errno));
4065 exit(1);
4068 qemu_config_write(fp);
4069 if (fp != stdout) {
4070 fclose(fp);
4072 break;
4074 case QEMU_OPTION_qtest:
4075 qtest_chrdev = optarg;
4076 break;
4077 case QEMU_OPTION_qtest_log:
4078 qtest_log = optarg;
4079 break;
4080 case QEMU_OPTION_sandbox:
4081 olist = qemu_find_opts("sandbox");
4082 if (!olist) {
4083 #ifndef CONFIG_SECCOMP
4084 error_report("-sandbox support is not enabled "
4085 "in this QEMU binary");
4086 #endif
4087 exit(1);
4090 opts = qemu_opts_parse_noisily(olist, optarg, true);
4091 if (!opts) {
4092 exit(1);
4094 break;
4095 case QEMU_OPTION_add_fd:
4096 #ifndef _WIN32
4097 opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
4098 optarg, false);
4099 if (!opts) {
4100 exit(1);
4102 #else
4103 error_report("File descriptor passing is disabled on this "
4104 "platform");
4105 exit(1);
4106 #endif
4107 break;
4108 case QEMU_OPTION_object:
4109 opts = qemu_opts_parse_noisily(qemu_find_opts("object"),
4110 optarg, true);
4111 if (!opts) {
4112 exit(1);
4114 break;
4115 case QEMU_OPTION_realtime:
4116 warn_report("'-realtime mlock=...' is deprecated, please use "
4117 "'-overcommit mem-lock=...' instead");
4118 opts = qemu_opts_parse_noisily(qemu_find_opts("realtime"),
4119 optarg, false);
4120 if (!opts) {
4121 exit(1);
4123 /* Don't override the -overcommit option if set */
4124 enable_mlock = enable_mlock ||
4125 qemu_opt_get_bool(opts, "mlock", true);
4126 break;
4127 case QEMU_OPTION_overcommit:
4128 opts = qemu_opts_parse_noisily(qemu_find_opts("overcommit"),
4129 optarg, false);
4130 if (!opts) {
4131 exit(1);
4133 /* Don't override the -realtime option if set */
4134 enable_mlock = enable_mlock ||
4135 qemu_opt_get_bool(opts, "mem-lock", false);
4136 enable_cpu_pm = qemu_opt_get_bool(opts, "cpu-pm", false);
4137 break;
4138 case QEMU_OPTION_msg:
4139 opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
4140 false);
4141 if (!opts) {
4142 exit(1);
4144 configure_msg(opts);
4145 break;
4146 case QEMU_OPTION_dump_vmstate:
4147 if (vmstate_dump_file) {
4148 error_report("only one '-dump-vmstate' "
4149 "option may be given");
4150 exit(1);
4152 vmstate_dump_file = fopen(optarg, "w");
4153 if (vmstate_dump_file == NULL) {
4154 error_report("open %s: %s", optarg, strerror(errno));
4155 exit(1);
4157 break;
4158 case QEMU_OPTION_enable_sync_profile:
4159 qsp_enable();
4160 break;
4161 case QEMU_OPTION_nouserconfig:
4162 /* Nothing to be parsed here. Especially, do not error out below. */
4163 break;
4164 default:
4165 if (os_parse_cmd_args(popt->index, optarg)) {
4166 error_report("Option not supported in this build");
4167 exit(1);
4173 * Clear error location left behind by the loop.
4174 * Best done right after the loop. Do not insert code here!
4176 loc_set_none();
4178 qemu_validate_options();
4179 qemu_process_sugar_options();
4182 * These options affect everything else and should be processed
4183 * before daemonizing.
4185 qemu_process_early_options();
4187 qemu_process_help_options();
4188 qemu_maybe_daemonize(pid_file);
4190 qemu_init_main_loop(&error_fatal);
4191 cpu_timers_init();
4193 user_register_global_props();
4194 replay_configure(icount_opts);
4196 configure_rtc(qemu_find_opts_singleton("rtc"));
4198 qemu_create_machine(select_machine());
4200 qemu_disable_default_devices();
4201 qemu_create_default_devices();
4202 qemu_create_early_backends();
4204 qemu_apply_machine_options();
4207 * Note: uses machine properties such as kernel-irqchip, must run
4208 * after machine_set_property().
4210 configure_accelerators(argv[0]);
4213 * Beware, QOM objects created before this point miss global and
4214 * compat properties.
4216 * Global properties get set up by qdev_prop_register_global(),
4217 * called from user_register_global_props(), and certain option
4218 * desugaring. Also in CPU feature desugaring (buried in
4219 * parse_cpu_option()), which happens below this point, but may
4220 * only target the CPU type, which can only be created after
4221 * parse_cpu_option() returned the type.
4223 * Machine compat properties: object_set_machine_compat_props().
4224 * Accelerator compat props: object_set_accelerator_compat_props(),
4225 * called from configure_accelerator().
4228 machine_class = MACHINE_GET_CLASS(current_machine);
4229 if (!qtest_enabled() && machine_class->deprecation_reason) {
4230 error_report("Machine type '%s' is deprecated: %s",
4231 machine_class->name, machine_class->deprecation_reason);
4235 * Note: creates a QOM object, must run only after global and
4236 * compat properties have been set up.
4238 migration_object_init();
4240 qemu_create_late_backends();
4242 /* parse features once if machine provides default cpu_type */
4243 current_machine->cpu_type = machine_class->default_cpu_type;
4244 if (cpu_option) {
4245 current_machine->cpu_type = parse_cpu_option(cpu_option);
4248 qemu_resolve_machine_memdev();
4249 parse_numa_opts(current_machine);
4251 if (preconfig_requested) {
4252 qemu_init_displays();
4255 /* do monitor/qmp handling at preconfig state if requested */
4256 qemu_main_loop();
4258 qemu_init_board();
4260 qemu_create_cli_devices();
4262 /* initialize displays after all errors have been reported */
4263 if (!preconfig_requested) {
4264 qemu_init_displays();
4266 qemu_machine_creation_done();
4268 if (loadvm) {
4269 Error *local_err = NULL;
4270 if (load_snapshot(loadvm, &local_err) < 0) {
4271 error_report_err(local_err);
4272 autostart = 0;
4273 exit(1);
4276 if (replay_mode != REPLAY_MODE_NONE) {
4277 replay_vmstate_init();
4280 if (vmstate_dump_file) {
4281 /* dump and exit */
4282 dump_vmstate_json_to_file(vmstate_dump_file);
4283 exit(0);
4285 if (incoming) {
4286 Error *local_err = NULL;
4287 if (strcmp(incoming, "defer") != 0) {
4288 qmp_migrate_incoming(incoming, &local_err);
4289 if (local_err) {
4290 error_reportf_err(local_err, "-incoming %s: ", incoming);
4291 exit(1);
4294 } else if (autostart) {
4295 qmp_cont(NULL);
4298 accel_setup_post(current_machine);
4299 os_setup_post();
4301 return;
4304 void qemu_cleanup(void)
4306 gdbserver_cleanup();
4309 * cleaning up the migration object cancels any existing migration
4310 * try to do this early so that it also stops using devices.
4312 migration_shutdown();
4315 * We must cancel all block jobs while the block layer is drained,
4316 * or cancelling will be affected by throttling and thus may block
4317 * for an extended period of time.
4318 * vm_shutdown() will bdrv_drain_all(), so we may as well include
4319 * it in the drained section.
4320 * We do not need to end this section, because we do not want any
4321 * requests happening from here on anyway.
4323 bdrv_drain_all_begin();
4325 /* No more vcpu or device emulation activity beyond this point */
4326 vm_shutdown();
4327 replay_finish();
4329 job_cancel_sync_all();
4330 bdrv_close_all();
4332 res_free();
4334 /* vhost-user must be cleaned up before chardevs. */
4335 tpm_cleanup();
4336 net_cleanup();
4337 audio_cleanup();
4338 monitor_cleanup();
4339 qemu_chr_cleanup();
4340 user_creatable_cleanup();
4341 /* TODO: unref root container, check all devices are ok */