vl: extract machine done notifiers
[qemu/ar7.git] / softmmu / vl.c
blob852ecf08e1cde653c967eb1246ad59716504c5ce
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 static enum {
156 RTC_BASE_UTC,
157 RTC_BASE_LOCALTIME,
158 RTC_BASE_DATETIME,
159 } rtc_base_type = RTC_BASE_UTC;
160 static time_t rtc_ref_start_datetime;
161 static int rtc_realtime_clock_offset; /* used only with QEMU_CLOCK_REALTIME */
162 static int rtc_host_datetime_offset = -1; /* valid & used only with
163 RTC_BASE_DATETIME */
164 QEMUClockType rtc_clock;
165 int vga_interface_type = VGA_NONE;
166 static const char *vga_model = NULL;
167 static DisplayOptions dpy;
168 static int num_serial_hds;
169 static Chardev **serial_hds;
170 static const char *log_mask;
171 static const char *log_file;
172 static bool list_data_dirs;
173 Chardev *parallel_hds[MAX_PARALLEL_PORTS];
174 int win2k_install_hack = 0;
175 int singlestep = 0;
176 int fd_bootchk = 1;
177 static int no_reboot;
178 int no_shutdown = 0;
179 int graphic_rotate = 0;
180 static const char *watchdog;
181 QEMUOptionRom option_rom[MAX_OPTION_ROMS];
182 int nb_option_roms;
183 int old_param = 0;
184 const char *qemu_name;
185 int alt_grab = 0;
186 int ctrl_grab = 0;
187 unsigned int nb_prom_envs = 0;
188 const char *prom_envs[MAX_PROM_ENVS];
189 int boot_menu;
190 bool boot_strict;
191 uint8_t *boot_splash_filedata;
192 int only_migratable; /* turn it off unless user states otherwise */
193 bool wakeup_suspend_enabled;
194 int icount_align_option;
195 static const char *qtest_chrdev;
196 static const char *qtest_log;
198 /* The bytes in qemu_uuid are in the order specified by RFC4122, _not_ in the
199 * little-endian "wire format" described in the SMBIOS 2.6 specification.
201 QemuUUID qemu_uuid;
202 bool qemu_uuid_set;
204 static NotifierList exit_notifiers =
205 NOTIFIER_LIST_INITIALIZER(exit_notifiers);
207 uint32_t xen_domid;
208 enum xen_mode xen_mode = XEN_EMULATE;
209 bool xen_domid_restrict;
211 static int has_defaults = 1;
212 static int default_serial = 1;
213 static int default_parallel = 1;
214 static int default_monitor = 1;
215 static int default_floppy = 1;
216 static int default_cdrom = 1;
217 static int default_sdcard = 1;
218 static int default_vga = 1;
219 static int default_net = 1;
221 static struct {
222 const char *driver;
223 int *flag;
224 } default_list[] = {
225 { .driver = "isa-serial", .flag = &default_serial },
226 { .driver = "isa-parallel", .flag = &default_parallel },
227 { .driver = "isa-fdc", .flag = &default_floppy },
228 { .driver = "floppy", .flag = &default_floppy },
229 { .driver = "ide-cd", .flag = &default_cdrom },
230 { .driver = "ide-hd", .flag = &default_cdrom },
231 { .driver = "ide-drive", .flag = &default_cdrom },
232 { .driver = "scsi-cd", .flag = &default_cdrom },
233 { .driver = "scsi-hd", .flag = &default_cdrom },
234 { .driver = "VGA", .flag = &default_vga },
235 { .driver = "isa-vga", .flag = &default_vga },
236 { .driver = "cirrus-vga", .flag = &default_vga },
237 { .driver = "isa-cirrus-vga", .flag = &default_vga },
238 { .driver = "vmware-svga", .flag = &default_vga },
239 { .driver = "qxl-vga", .flag = &default_vga },
240 { .driver = "virtio-vga", .flag = &default_vga },
241 { .driver = "ati-vga", .flag = &default_vga },
242 { .driver = "vhost-user-vga", .flag = &default_vga },
245 static QemuOptsList qemu_rtc_opts = {
246 .name = "rtc",
247 .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
248 .merge_lists = true,
249 .desc = {
251 .name = "base",
252 .type = QEMU_OPT_STRING,
254 .name = "clock",
255 .type = QEMU_OPT_STRING,
257 .name = "driftfix",
258 .type = QEMU_OPT_STRING,
260 { /* end of list */ }
264 static QemuOptsList qemu_option_rom_opts = {
265 .name = "option-rom",
266 .implied_opt_name = "romfile",
267 .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
268 .desc = {
270 .name = "bootindex",
271 .type = QEMU_OPT_NUMBER,
272 }, {
273 .name = "romfile",
274 .type = QEMU_OPT_STRING,
276 { /* end of list */ }
280 static QemuOptsList qemu_machine_opts = {
281 .name = "machine",
282 .implied_opt_name = "type",
283 .merge_lists = true,
284 .head = QTAILQ_HEAD_INITIALIZER(qemu_machine_opts.head),
285 .desc = {
287 * no elements => accept any
288 * sanity checking will happen later
289 * when setting machine properties
295 static QemuOptsList qemu_accel_opts = {
296 .name = "accel",
297 .implied_opt_name = "accel",
298 .head = QTAILQ_HEAD_INITIALIZER(qemu_accel_opts.head),
299 .desc = {
301 * no elements => accept any
302 * sanity checking will happen later
303 * when setting accelerator properties
309 static QemuOptsList qemu_boot_opts = {
310 .name = "boot-opts",
311 .implied_opt_name = "order",
312 .merge_lists = true,
313 .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
314 .desc = {
316 .name = "order",
317 .type = QEMU_OPT_STRING,
318 }, {
319 .name = "once",
320 .type = QEMU_OPT_STRING,
321 }, {
322 .name = "menu",
323 .type = QEMU_OPT_BOOL,
324 }, {
325 .name = "splash",
326 .type = QEMU_OPT_STRING,
327 }, {
328 .name = "splash-time",
329 .type = QEMU_OPT_NUMBER,
330 }, {
331 .name = "reboot-timeout",
332 .type = QEMU_OPT_NUMBER,
333 }, {
334 .name = "strict",
335 .type = QEMU_OPT_BOOL,
337 { /*End of list */ }
341 static QemuOptsList qemu_add_fd_opts = {
342 .name = "add-fd",
343 .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
344 .desc = {
346 .name = "fd",
347 .type = QEMU_OPT_NUMBER,
348 .help = "file descriptor of which a duplicate is added to fd set",
350 .name = "set",
351 .type = QEMU_OPT_NUMBER,
352 .help = "ID of the fd set to add fd to",
354 .name = "opaque",
355 .type = QEMU_OPT_STRING,
356 .help = "free-form string used to describe fd",
358 { /* end of list */ }
362 static QemuOptsList qemu_object_opts = {
363 .name = "object",
364 .implied_opt_name = "qom-type",
365 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
366 .desc = {
371 static QemuOptsList qemu_tpmdev_opts = {
372 .name = "tpmdev",
373 .implied_opt_name = "type",
374 .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
375 .desc = {
376 /* options are defined in the TPM backends */
377 { /* end of list */ }
381 static QemuOptsList qemu_realtime_opts = {
382 .name = "realtime",
383 .head = QTAILQ_HEAD_INITIALIZER(qemu_realtime_opts.head),
384 .desc = {
386 .name = "mlock",
387 .type = QEMU_OPT_BOOL,
389 { /* end of list */ }
393 static QemuOptsList qemu_overcommit_opts = {
394 .name = "overcommit",
395 .head = QTAILQ_HEAD_INITIALIZER(qemu_overcommit_opts.head),
396 .desc = {
398 .name = "mem-lock",
399 .type = QEMU_OPT_BOOL,
402 .name = "cpu-pm",
403 .type = QEMU_OPT_BOOL,
405 { /* end of list */ }
409 static QemuOptsList qemu_msg_opts = {
410 .name = "msg",
411 .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
412 .desc = {
414 .name = "timestamp",
415 .type = QEMU_OPT_BOOL,
418 .name = "guest-name",
419 .type = QEMU_OPT_BOOL,
420 .help = "Prepends guest name for error messages but only if "
421 "-name guest is set otherwise option is ignored\n",
423 { /* end of list */ }
427 static QemuOptsList qemu_name_opts = {
428 .name = "name",
429 .implied_opt_name = "guest",
430 .merge_lists = true,
431 .head = QTAILQ_HEAD_INITIALIZER(qemu_name_opts.head),
432 .desc = {
434 .name = "guest",
435 .type = QEMU_OPT_STRING,
436 .help = "Sets the name of the guest.\n"
437 "This name will be displayed in the SDL window caption.\n"
438 "The name will also be used for the VNC server",
439 }, {
440 .name = "process",
441 .type = QEMU_OPT_STRING,
442 .help = "Sets the name of the QEMU process, as shown in top etc",
443 }, {
444 .name = "debug-threads",
445 .type = QEMU_OPT_BOOL,
446 .help = "When enabled, name the individual threads; defaults off.\n"
447 "NOTE: The thread names are for debugging and not a\n"
448 "stable API.",
450 { /* End of list */ }
454 static QemuOptsList qemu_mem_opts = {
455 .name = "memory",
456 .implied_opt_name = "size",
457 .head = QTAILQ_HEAD_INITIALIZER(qemu_mem_opts.head),
458 .merge_lists = true,
459 .desc = {
461 .name = "size",
462 .type = QEMU_OPT_SIZE,
465 .name = "slots",
466 .type = QEMU_OPT_NUMBER,
469 .name = "maxmem",
470 .type = QEMU_OPT_SIZE,
472 { /* end of list */ }
476 static QemuOptsList qemu_icount_opts = {
477 .name = "icount",
478 .implied_opt_name = "shift",
479 .merge_lists = true,
480 .head = QTAILQ_HEAD_INITIALIZER(qemu_icount_opts.head),
481 .desc = {
483 .name = "shift",
484 .type = QEMU_OPT_STRING,
485 }, {
486 .name = "align",
487 .type = QEMU_OPT_BOOL,
488 }, {
489 .name = "sleep",
490 .type = QEMU_OPT_BOOL,
491 }, {
492 .name = "rr",
493 .type = QEMU_OPT_STRING,
494 }, {
495 .name = "rrfile",
496 .type = QEMU_OPT_STRING,
497 }, {
498 .name = "rrsnapshot",
499 .type = QEMU_OPT_STRING,
501 { /* end of list */ }
505 static QemuOptsList qemu_fw_cfg_opts = {
506 .name = "fw_cfg",
507 .implied_opt_name = "name",
508 .head = QTAILQ_HEAD_INITIALIZER(qemu_fw_cfg_opts.head),
509 .desc = {
511 .name = "name",
512 .type = QEMU_OPT_STRING,
513 .help = "Sets the fw_cfg name of the blob to be inserted",
514 }, {
515 .name = "file",
516 .type = QEMU_OPT_STRING,
517 .help = "Sets the name of the file from which "
518 "the fw_cfg blob will be loaded",
519 }, {
520 .name = "string",
521 .type = QEMU_OPT_STRING,
522 .help = "Sets content of the blob to be inserted from a string",
523 }, {
524 .name = "gen_id",
525 .type = QEMU_OPT_STRING,
526 .help = "Sets id of the object generating the fw_cfg blob "
527 "to be inserted",
529 { /* end of list */ }
534 * Get machine options
536 * Returns: machine options (never null).
538 QemuOpts *qemu_get_machine_opts(void)
540 return qemu_find_opts_singleton("machine");
543 const char *qemu_get_vm_name(void)
545 return qemu_name;
548 static void res_free(void)
550 g_free(boot_splash_filedata);
551 boot_splash_filedata = NULL;
554 static int default_driver_check(void *opaque, QemuOpts *opts, Error **errp)
556 const char *driver = qemu_opt_get(opts, "driver");
557 int i;
559 if (!driver)
560 return 0;
561 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
562 if (strcmp(default_list[i].driver, driver) != 0)
563 continue;
564 *(default_list[i].flag) = 0;
566 return 0;
569 /***********************************************************/
570 /* QEMU state */
572 static RunState current_run_state = RUN_STATE_PRECONFIG;
574 /* We use RUN_STATE__MAX but any invalid value will do */
575 static RunState vmstop_requested = RUN_STATE__MAX;
576 static QemuMutex vmstop_lock;
578 typedef struct {
579 RunState from;
580 RunState to;
581 } RunStateTransition;
583 static const RunStateTransition runstate_transitions_def[] = {
584 /* from -> to */
585 { RUN_STATE_PRECONFIG, RUN_STATE_PRELAUNCH },
586 /* Early switch to inmigrate state to allow -incoming CLI option work
587 * as it used to. TODO: delay actual switching to inmigrate state to
588 * the point after machine is built and remove this hack.
590 { RUN_STATE_PRECONFIG, RUN_STATE_INMIGRATE },
592 { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
593 { RUN_STATE_DEBUG, RUN_STATE_FINISH_MIGRATE },
594 { RUN_STATE_DEBUG, RUN_STATE_PRELAUNCH },
596 { RUN_STATE_INMIGRATE, RUN_STATE_INTERNAL_ERROR },
597 { RUN_STATE_INMIGRATE, RUN_STATE_IO_ERROR },
598 { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
599 { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
600 { RUN_STATE_INMIGRATE, RUN_STATE_SHUTDOWN },
601 { RUN_STATE_INMIGRATE, RUN_STATE_SUSPENDED },
602 { RUN_STATE_INMIGRATE, RUN_STATE_WATCHDOG },
603 { RUN_STATE_INMIGRATE, RUN_STATE_GUEST_PANICKED },
604 { RUN_STATE_INMIGRATE, RUN_STATE_FINISH_MIGRATE },
605 { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
606 { RUN_STATE_INMIGRATE, RUN_STATE_POSTMIGRATE },
607 { RUN_STATE_INMIGRATE, RUN_STATE_COLO },
609 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
610 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
611 { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PRELAUNCH },
613 { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
614 { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
615 { RUN_STATE_IO_ERROR, RUN_STATE_PRELAUNCH },
617 { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
618 { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
619 { RUN_STATE_PAUSED, RUN_STATE_POSTMIGRATE },
620 { RUN_STATE_PAUSED, RUN_STATE_PRELAUNCH },
621 { RUN_STATE_PAUSED, RUN_STATE_COLO},
623 { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
624 { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
625 { RUN_STATE_POSTMIGRATE, RUN_STATE_PRELAUNCH },
627 { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
628 { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
629 { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
631 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
632 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PAUSED },
633 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
634 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PRELAUNCH },
635 { RUN_STATE_FINISH_MIGRATE, RUN_STATE_COLO},
637 { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
638 { RUN_STATE_RESTORE_VM, RUN_STATE_PRELAUNCH },
640 { RUN_STATE_COLO, RUN_STATE_RUNNING },
642 { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
643 { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
644 { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
645 { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
646 { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
647 { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
648 { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
649 { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
650 { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
651 { RUN_STATE_RUNNING, RUN_STATE_GUEST_PANICKED },
652 { RUN_STATE_RUNNING, RUN_STATE_COLO},
654 { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
656 { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
657 { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
658 { RUN_STATE_SHUTDOWN, RUN_STATE_PRELAUNCH },
659 { RUN_STATE_SHUTDOWN, RUN_STATE_COLO },
661 { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
662 { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
663 { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
664 { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
665 { RUN_STATE_SUSPENDED, RUN_STATE_PRELAUNCH },
666 { RUN_STATE_SUSPENDED, RUN_STATE_COLO},
668 { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
669 { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
670 { RUN_STATE_WATCHDOG, RUN_STATE_PRELAUNCH },
671 { RUN_STATE_WATCHDOG, RUN_STATE_COLO},
673 { RUN_STATE_GUEST_PANICKED, RUN_STATE_RUNNING },
674 { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
675 { RUN_STATE_GUEST_PANICKED, RUN_STATE_PRELAUNCH },
677 { RUN_STATE__MAX, RUN_STATE__MAX },
680 static bool runstate_valid_transitions[RUN_STATE__MAX][RUN_STATE__MAX];
682 bool runstate_check(RunState state)
684 return current_run_state == state;
687 bool runstate_store(char *str, size_t size)
689 const char *state = RunState_str(current_run_state);
690 size_t len = strlen(state) + 1;
692 if (len > size) {
693 return false;
695 memcpy(str, state, len);
696 return true;
699 static void runstate_init(void)
701 const RunStateTransition *p;
703 memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
704 for (p = &runstate_transitions_def[0]; p->from != RUN_STATE__MAX; p++) {
705 runstate_valid_transitions[p->from][p->to] = true;
708 qemu_mutex_init(&vmstop_lock);
711 /* This function will abort() on invalid state transitions */
712 void runstate_set(RunState new_state)
714 assert(new_state < RUN_STATE__MAX);
716 trace_runstate_set(current_run_state, RunState_str(current_run_state),
717 new_state, RunState_str(new_state));
719 if (current_run_state == new_state) {
720 return;
723 if (!runstate_valid_transitions[current_run_state][new_state]) {
724 error_report("invalid runstate transition: '%s' -> '%s'",
725 RunState_str(current_run_state),
726 RunState_str(new_state));
727 abort();
730 current_run_state = new_state;
733 int runstate_is_running(void)
735 return runstate_check(RUN_STATE_RUNNING);
738 bool runstate_needs_reset(void)
740 return runstate_check(RUN_STATE_INTERNAL_ERROR) ||
741 runstate_check(RUN_STATE_SHUTDOWN);
744 StatusInfo *qmp_query_status(Error **errp)
746 StatusInfo *info = g_malloc0(sizeof(*info));
748 info->running = runstate_is_running();
749 info->singlestep = singlestep;
750 info->status = current_run_state;
752 return info;
755 bool qemu_vmstop_requested(RunState *r)
757 qemu_mutex_lock(&vmstop_lock);
758 *r = vmstop_requested;
759 vmstop_requested = RUN_STATE__MAX;
760 qemu_mutex_unlock(&vmstop_lock);
761 return *r < RUN_STATE__MAX;
764 void qemu_system_vmstop_request_prepare(void)
766 qemu_mutex_lock(&vmstop_lock);
769 void qemu_system_vmstop_request(RunState state)
771 vmstop_requested = state;
772 qemu_mutex_unlock(&vmstop_lock);
773 qemu_notify_event();
776 /***********************************************************/
777 /* RTC reference time/date access */
778 static time_t qemu_ref_timedate(QEMUClockType clock)
780 time_t value = qemu_clock_get_ms(clock) / 1000;
781 switch (clock) {
782 case QEMU_CLOCK_REALTIME:
783 value -= rtc_realtime_clock_offset;
784 /* fall through */
785 case QEMU_CLOCK_VIRTUAL:
786 value += rtc_ref_start_datetime;
787 break;
788 case QEMU_CLOCK_HOST:
789 if (rtc_base_type == RTC_BASE_DATETIME) {
790 value -= rtc_host_datetime_offset;
792 break;
793 default:
794 assert(0);
796 return value;
799 void qemu_get_timedate(struct tm *tm, int offset)
801 time_t ti = qemu_ref_timedate(rtc_clock);
803 ti += offset;
805 switch (rtc_base_type) {
806 case RTC_BASE_DATETIME:
807 case RTC_BASE_UTC:
808 gmtime_r(&ti, tm);
809 break;
810 case RTC_BASE_LOCALTIME:
811 localtime_r(&ti, tm);
812 break;
816 int qemu_timedate_diff(struct tm *tm)
818 time_t seconds;
820 switch (rtc_base_type) {
821 case RTC_BASE_DATETIME:
822 case RTC_BASE_UTC:
823 seconds = mktimegm(tm);
824 break;
825 case RTC_BASE_LOCALTIME:
827 struct tm tmp = *tm;
828 tmp.tm_isdst = -1; /* use timezone to figure it out */
829 seconds = mktime(&tmp);
830 break;
832 default:
833 abort();
836 return seconds - qemu_ref_timedate(QEMU_CLOCK_HOST);
839 static void configure_rtc_base_datetime(const char *startdate)
841 time_t rtc_start_datetime;
842 struct tm tm;
844 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d", &tm.tm_year, &tm.tm_mon,
845 &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6) {
846 /* OK */
847 } else if (sscanf(startdate, "%d-%d-%d",
848 &tm.tm_year, &tm.tm_mon, &tm.tm_mday) == 3) {
849 tm.tm_hour = 0;
850 tm.tm_min = 0;
851 tm.tm_sec = 0;
852 } else {
853 goto date_fail;
855 tm.tm_year -= 1900;
856 tm.tm_mon--;
857 rtc_start_datetime = mktimegm(&tm);
858 if (rtc_start_datetime == -1) {
859 date_fail:
860 error_report("invalid datetime format");
861 error_printf("valid formats: "
862 "'2006-06-17T16:01:21' or '2006-06-17'\n");
863 exit(1);
865 rtc_host_datetime_offset = rtc_ref_start_datetime - rtc_start_datetime;
866 rtc_ref_start_datetime = rtc_start_datetime;
869 static void configure_rtc(QemuOpts *opts)
871 const char *value;
873 /* Set defaults */
874 rtc_clock = QEMU_CLOCK_HOST;
875 rtc_ref_start_datetime = qemu_clock_get_ms(QEMU_CLOCK_HOST) / 1000;
876 rtc_realtime_clock_offset = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) / 1000;
878 value = qemu_opt_get(opts, "base");
879 if (value) {
880 if (!strcmp(value, "utc")) {
881 rtc_base_type = RTC_BASE_UTC;
882 } else if (!strcmp(value, "localtime")) {
883 Error *blocker = NULL;
884 rtc_base_type = RTC_BASE_LOCALTIME;
885 error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
886 "-rtc base=localtime");
887 replay_add_blocker(blocker);
888 } else {
889 rtc_base_type = RTC_BASE_DATETIME;
890 configure_rtc_base_datetime(value);
893 value = qemu_opt_get(opts, "clock");
894 if (value) {
895 if (!strcmp(value, "host")) {
896 rtc_clock = QEMU_CLOCK_HOST;
897 } else if (!strcmp(value, "rt")) {
898 rtc_clock = QEMU_CLOCK_REALTIME;
899 } else if (!strcmp(value, "vm")) {
900 rtc_clock = QEMU_CLOCK_VIRTUAL;
901 } else {
902 error_report("invalid option value '%s'", value);
903 exit(1);
906 value = qemu_opt_get(opts, "driftfix");
907 if (value) {
908 if (!strcmp(value, "slew")) {
909 object_register_sugar_prop("mc146818rtc",
910 "lost_tick_policy",
911 "slew");
912 } else if (!strcmp(value, "none")) {
913 /* discard is default */
914 } else {
915 error_report("invalid option value '%s'", value);
916 exit(1);
921 static int parse_name(void *opaque, QemuOpts *opts, Error **errp)
923 const char *proc_name;
925 if (qemu_opt_get(opts, "debug-threads")) {
926 qemu_thread_naming(qemu_opt_get_bool(opts, "debug-threads", false));
928 qemu_name = qemu_opt_get(opts, "guest");
930 proc_name = qemu_opt_get(opts, "process");
931 if (proc_name) {
932 os_set_proc_name(proc_name);
935 return 0;
938 bool defaults_enabled(void)
940 return has_defaults;
943 #ifndef _WIN32
944 static int parse_add_fd(void *opaque, QemuOpts *opts, Error **errp)
946 int fd, dupfd, flags;
947 int64_t fdset_id;
948 const char *fd_opaque = NULL;
949 AddfdInfo *fdinfo;
951 fd = qemu_opt_get_number(opts, "fd", -1);
952 fdset_id = qemu_opt_get_number(opts, "set", -1);
953 fd_opaque = qemu_opt_get(opts, "opaque");
955 if (fd < 0) {
956 error_setg(errp, "fd option is required and must be non-negative");
957 return -1;
960 if (fd <= STDERR_FILENO) {
961 error_setg(errp, "fd cannot be a standard I/O stream");
962 return -1;
966 * All fds inherited across exec() necessarily have FD_CLOEXEC
967 * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
969 flags = fcntl(fd, F_GETFD);
970 if (flags == -1 || (flags & FD_CLOEXEC)) {
971 error_setg(errp, "fd is not valid or already in use");
972 return -1;
975 if (fdset_id < 0) {
976 error_setg(errp, "set option is required and must be non-negative");
977 return -1;
980 #ifdef F_DUPFD_CLOEXEC
981 dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
982 #else
983 dupfd = dup(fd);
984 if (dupfd != -1) {
985 qemu_set_cloexec(dupfd);
987 #endif
988 if (dupfd == -1) {
989 error_setg(errp, "error duplicating fd: %s", strerror(errno));
990 return -1;
993 /* add the duplicate fd, and optionally the opaque string, to the fd set */
994 fdinfo = monitor_fdset_add_fd(dupfd, true, fdset_id, !!fd_opaque, fd_opaque,
995 &error_abort);
996 g_free(fdinfo);
998 return 0;
1001 static int cleanup_add_fd(void *opaque, QemuOpts *opts, Error **errp)
1003 int fd;
1005 fd = qemu_opt_get_number(opts, "fd", -1);
1006 close(fd);
1008 return 0;
1010 #endif
1012 /***********************************************************/
1013 /* QEMU Block devices */
1015 #define HD_OPTS "media=disk"
1016 #define CDROM_OPTS "media=cdrom"
1017 #define FD_OPTS ""
1018 #define PFLASH_OPTS ""
1019 #define MTD_OPTS ""
1020 #define SD_OPTS ""
1022 static int drive_init_func(void *opaque, QemuOpts *opts, Error **errp)
1024 BlockInterfaceType *block_default_type = opaque;
1026 return drive_new(opts, *block_default_type, errp) == NULL;
1029 static int drive_enable_snapshot(void *opaque, QemuOpts *opts, Error **errp)
1031 if (qemu_opt_get(opts, "snapshot") == NULL) {
1032 qemu_opt_set(opts, "snapshot", "on", &error_abort);
1034 return 0;
1037 static void default_drive(int enable, int snapshot, BlockInterfaceType type,
1038 int index, const char *optstr)
1040 QemuOpts *opts;
1041 DriveInfo *dinfo;
1043 if (!enable || drive_get_by_index(type, index)) {
1044 return;
1047 opts = drive_add(type, index, NULL, optstr);
1048 if (snapshot) {
1049 drive_enable_snapshot(NULL, opts, NULL);
1052 dinfo = drive_new(opts, type, &error_abort);
1053 dinfo->is_default = true;
1057 static void configure_blockdev(BlockdevOptionsQueue *bdo_queue,
1058 MachineClass *machine_class, int snapshot)
1061 * If the currently selected machine wishes to override the
1062 * units-per-bus property of its default HBA interface type, do so
1063 * now.
1065 if (machine_class->units_per_default_bus) {
1066 override_max_devs(machine_class->block_default_type,
1067 machine_class->units_per_default_bus);
1070 /* open the virtual block devices */
1071 while (!QSIMPLEQ_EMPTY(bdo_queue)) {
1072 BlockdevOptionsQueueEntry *bdo = QSIMPLEQ_FIRST(bdo_queue);
1074 QSIMPLEQ_REMOVE_HEAD(bdo_queue, entry);
1075 loc_push_restore(&bdo->loc);
1076 qmp_blockdev_add(bdo->bdo, &error_fatal);
1077 loc_pop(&bdo->loc);
1078 qapi_free_BlockdevOptions(bdo->bdo);
1079 g_free(bdo);
1081 if (snapshot) {
1082 qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot,
1083 NULL, NULL);
1085 if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
1086 &machine_class->block_default_type, &error_fatal)) {
1087 /* We printed help */
1088 exit(0);
1091 default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
1092 CDROM_OPTS);
1093 default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
1094 default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
1098 static QemuOptsList qemu_smp_opts = {
1099 .name = "smp-opts",
1100 .implied_opt_name = "cpus",
1101 .merge_lists = true,
1102 .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
1103 .desc = {
1105 .name = "cpus",
1106 .type = QEMU_OPT_NUMBER,
1107 }, {
1108 .name = "sockets",
1109 .type = QEMU_OPT_NUMBER,
1110 }, {
1111 .name = "dies",
1112 .type = QEMU_OPT_NUMBER,
1113 }, {
1114 .name = "cores",
1115 .type = QEMU_OPT_NUMBER,
1116 }, {
1117 .name = "threads",
1118 .type = QEMU_OPT_NUMBER,
1119 }, {
1120 .name = "maxcpus",
1121 .type = QEMU_OPT_NUMBER,
1123 { /*End of list */ }
1127 static void realtime_init(void)
1129 if (enable_mlock) {
1130 if (os_mlock() < 0) {
1131 error_report("locking memory failed");
1132 exit(1);
1138 static void configure_msg(QemuOpts *opts)
1140 error_with_timestamp = qemu_opt_get_bool(opts, "timestamp", false);
1141 error_with_guestname = qemu_opt_get_bool(opts, "guest-name", false);
1145 /***********************************************************/
1146 /* USB devices */
1148 static int usb_device_add(const char *devname)
1150 USBDevice *dev = NULL;
1152 if (!machine_usb(current_machine)) {
1153 return -1;
1156 dev = usbdevice_create(devname);
1157 if (!dev)
1158 return -1;
1160 return 0;
1163 static int usb_parse(const char *cmdline)
1165 int r;
1166 r = usb_device_add(cmdline);
1167 if (r < 0) {
1168 error_report("could not add USB device '%s'", cmdline);
1170 return r;
1173 /***********************************************************/
1174 /* machine registration */
1176 MachineState *current_machine;
1178 static MachineClass *find_machine(const char *name, GSList *machines)
1180 GSList *el;
1182 for (el = machines; el; el = el->next) {
1183 MachineClass *mc = el->data;
1185 if (!strcmp(mc->name, name) || !g_strcmp0(mc->alias, name)) {
1186 return mc;
1190 return NULL;
1193 static MachineClass *find_default_machine(GSList *machines)
1195 GSList *el;
1196 MachineClass *default_machineclass = NULL;
1198 for (el = machines; el; el = el->next) {
1199 MachineClass *mc = el->data;
1201 if (mc->is_default) {
1202 assert(default_machineclass == NULL && "Multiple default machines");
1203 default_machineclass = mc;
1207 return default_machineclass;
1210 static int machine_help_func(QemuOpts *opts, MachineState *machine)
1212 ObjectProperty *prop;
1213 ObjectPropertyIterator iter;
1215 if (!qemu_opt_has_help_opt(opts)) {
1216 return 0;
1219 object_property_iter_init(&iter, OBJECT(machine));
1220 while ((prop = object_property_iter_next(&iter))) {
1221 if (!prop->set) {
1222 continue;
1225 printf("%s.%s=%s", MACHINE_GET_CLASS(machine)->name,
1226 prop->name, prop->type);
1227 if (prop->description) {
1228 printf(" (%s)\n", prop->description);
1229 } else {
1230 printf("\n");
1234 return 1;
1237 struct VMChangeStateEntry {
1238 VMChangeStateHandler *cb;
1239 void *opaque;
1240 QTAILQ_ENTRY(VMChangeStateEntry) entries;
1241 int priority;
1244 static QTAILQ_HEAD(, VMChangeStateEntry) vm_change_state_head =
1245 QTAILQ_HEAD_INITIALIZER(vm_change_state_head);
1248 * qemu_add_vm_change_state_handler_prio:
1249 * @cb: the callback to invoke
1250 * @opaque: user data passed to the callback
1251 * @priority: low priorities execute first when the vm runs and the reverse is
1252 * true when the vm stops
1254 * Register a callback function that is invoked when the vm starts or stops
1255 * running.
1257 * Returns: an entry to be freed using qemu_del_vm_change_state_handler()
1259 VMChangeStateEntry *qemu_add_vm_change_state_handler_prio(
1260 VMChangeStateHandler *cb, void *opaque, int priority)
1262 VMChangeStateEntry *e;
1263 VMChangeStateEntry *other;
1265 e = g_malloc0(sizeof(*e));
1266 e->cb = cb;
1267 e->opaque = opaque;
1268 e->priority = priority;
1270 /* Keep list sorted in ascending priority order */
1271 QTAILQ_FOREACH(other, &vm_change_state_head, entries) {
1272 if (priority < other->priority) {
1273 QTAILQ_INSERT_BEFORE(other, e, entries);
1274 return e;
1278 QTAILQ_INSERT_TAIL(&vm_change_state_head, e, entries);
1279 return e;
1282 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1283 void *opaque)
1285 return qemu_add_vm_change_state_handler_prio(cb, opaque, 0);
1288 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1290 QTAILQ_REMOVE(&vm_change_state_head, e, entries);
1291 g_free(e);
1294 void vm_state_notify(int running, RunState state)
1296 VMChangeStateEntry *e, *next;
1298 trace_vm_state_notify(running, state, RunState_str(state));
1300 if (running) {
1301 QTAILQ_FOREACH_SAFE(e, &vm_change_state_head, entries, next) {
1302 e->cb(e->opaque, running, state);
1304 } else {
1305 QTAILQ_FOREACH_REVERSE_SAFE(e, &vm_change_state_head, entries, next) {
1306 e->cb(e->opaque, running, state);
1311 static ShutdownCause reset_requested;
1312 static ShutdownCause shutdown_requested;
1313 static int shutdown_signal;
1314 static pid_t shutdown_pid;
1315 static int powerdown_requested;
1316 static int debug_requested;
1317 static int suspend_requested;
1318 static bool preconfig_exit_requested = true;
1319 static WakeupReason wakeup_reason;
1320 static NotifierList powerdown_notifiers =
1321 NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
1322 static NotifierList suspend_notifiers =
1323 NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1324 static NotifierList wakeup_notifiers =
1325 NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1326 static NotifierList shutdown_notifiers =
1327 NOTIFIER_LIST_INITIALIZER(shutdown_notifiers);
1328 static uint32_t wakeup_reason_mask = ~(1 << QEMU_WAKEUP_REASON_NONE);
1330 ShutdownCause qemu_shutdown_requested_get(void)
1332 return shutdown_requested;
1335 ShutdownCause qemu_reset_requested_get(void)
1337 return reset_requested;
1340 static int qemu_shutdown_requested(void)
1342 return qatomic_xchg(&shutdown_requested, SHUTDOWN_CAUSE_NONE);
1345 static void qemu_kill_report(void)
1347 if (!qtest_driver() && shutdown_signal) {
1348 if (shutdown_pid == 0) {
1349 /* This happens for eg ^C at the terminal, so it's worth
1350 * avoiding printing an odd message in that case.
1352 error_report("terminating on signal %d", shutdown_signal);
1353 } else {
1354 char *shutdown_cmd = qemu_get_pid_name(shutdown_pid);
1356 error_report("terminating on signal %d from pid " FMT_pid " (%s)",
1357 shutdown_signal, shutdown_pid,
1358 shutdown_cmd ? shutdown_cmd : "<unknown process>");
1359 g_free(shutdown_cmd);
1361 shutdown_signal = 0;
1365 static ShutdownCause qemu_reset_requested(void)
1367 ShutdownCause r = reset_requested;
1369 if (r && replay_checkpoint(CHECKPOINT_RESET_REQUESTED)) {
1370 reset_requested = SHUTDOWN_CAUSE_NONE;
1371 return r;
1373 return SHUTDOWN_CAUSE_NONE;
1376 static int qemu_suspend_requested(void)
1378 int r = suspend_requested;
1379 if (r && replay_checkpoint(CHECKPOINT_SUSPEND_REQUESTED)) {
1380 suspend_requested = 0;
1381 return r;
1383 return false;
1386 static WakeupReason qemu_wakeup_requested(void)
1388 return wakeup_reason;
1391 static int qemu_powerdown_requested(void)
1393 int r = powerdown_requested;
1394 powerdown_requested = 0;
1395 return r;
1398 static int qemu_debug_requested(void)
1400 int r = debug_requested;
1401 debug_requested = 0;
1402 return r;
1405 void qemu_exit_preconfig_request(void)
1407 preconfig_exit_requested = true;
1411 * Reset the VM. Issue an event unless @reason is SHUTDOWN_CAUSE_NONE.
1413 void qemu_system_reset(ShutdownCause reason)
1415 MachineClass *mc;
1417 mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1419 cpu_synchronize_all_states();
1421 if (mc && mc->reset) {
1422 mc->reset(current_machine);
1423 } else {
1424 qemu_devices_reset();
1426 if (reason && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1427 qapi_event_send_reset(shutdown_caused_by_guest(reason), reason);
1429 cpu_synchronize_all_post_reset();
1433 * Wake the VM after suspend.
1435 static void qemu_system_wakeup(void)
1437 MachineClass *mc;
1439 mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1441 if (mc && mc->wakeup) {
1442 mc->wakeup(current_machine);
1446 void qemu_system_guest_panicked(GuestPanicInformation *info)
1448 qemu_log_mask(LOG_GUEST_ERROR, "Guest crashed");
1450 if (current_cpu) {
1451 current_cpu->crash_occurred = true;
1453 qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE,
1454 !!info, info);
1455 vm_stop(RUN_STATE_GUEST_PANICKED);
1456 if (!no_shutdown) {
1457 qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_POWEROFF,
1458 !!info, info);
1459 qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_PANIC);
1462 if (info) {
1463 if (info->type == GUEST_PANIC_INFORMATION_TYPE_HYPER_V) {
1464 qemu_log_mask(LOG_GUEST_ERROR, "\nHV crash parameters: (%#"PRIx64
1465 " %#"PRIx64" %#"PRIx64" %#"PRIx64" %#"PRIx64")\n",
1466 info->u.hyper_v.arg1,
1467 info->u.hyper_v.arg2,
1468 info->u.hyper_v.arg3,
1469 info->u.hyper_v.arg4,
1470 info->u.hyper_v.arg5);
1471 } else if (info->type == GUEST_PANIC_INFORMATION_TYPE_S390) {
1472 qemu_log_mask(LOG_GUEST_ERROR, " on cpu %d: %s\n"
1473 "PSW: 0x%016" PRIx64 " 0x%016" PRIx64"\n",
1474 info->u.s390.core,
1475 S390CrashReason_str(info->u.s390.reason),
1476 info->u.s390.psw_mask,
1477 info->u.s390.psw_addr);
1479 qapi_free_GuestPanicInformation(info);
1483 void qemu_system_guest_crashloaded(GuestPanicInformation *info)
1485 qemu_log_mask(LOG_GUEST_ERROR, "Guest crash loaded");
1487 qapi_event_send_guest_crashloaded(GUEST_PANIC_ACTION_RUN,
1488 !!info, info);
1490 if (info) {
1491 qapi_free_GuestPanicInformation(info);
1495 void qemu_system_reset_request(ShutdownCause reason)
1497 if (no_reboot && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1498 shutdown_requested = reason;
1499 } else {
1500 reset_requested = reason;
1502 cpu_stop_current();
1503 qemu_notify_event();
1506 static void qemu_system_suspend(void)
1508 pause_all_vcpus();
1509 notifier_list_notify(&suspend_notifiers, NULL);
1510 runstate_set(RUN_STATE_SUSPENDED);
1511 qapi_event_send_suspend();
1514 void qemu_system_suspend_request(void)
1516 if (runstate_check(RUN_STATE_SUSPENDED)) {
1517 return;
1519 suspend_requested = 1;
1520 cpu_stop_current();
1521 qemu_notify_event();
1524 void qemu_register_suspend_notifier(Notifier *notifier)
1526 notifier_list_add(&suspend_notifiers, notifier);
1529 void qemu_system_wakeup_request(WakeupReason reason, Error **errp)
1531 trace_system_wakeup_request(reason);
1533 if (!runstate_check(RUN_STATE_SUSPENDED)) {
1534 error_setg(errp,
1535 "Unable to wake up: guest is not in suspended state");
1536 return;
1538 if (!(wakeup_reason_mask & (1 << reason))) {
1539 return;
1541 runstate_set(RUN_STATE_RUNNING);
1542 wakeup_reason = reason;
1543 qemu_notify_event();
1546 void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1548 if (enabled) {
1549 wakeup_reason_mask |= (1 << reason);
1550 } else {
1551 wakeup_reason_mask &= ~(1 << reason);
1555 void qemu_register_wakeup_notifier(Notifier *notifier)
1557 notifier_list_add(&wakeup_notifiers, notifier);
1560 void qemu_register_wakeup_support(void)
1562 wakeup_suspend_enabled = true;
1565 bool qemu_wakeup_suspend_enabled(void)
1567 return wakeup_suspend_enabled;
1570 void qemu_system_killed(int signal, pid_t pid)
1572 shutdown_signal = signal;
1573 shutdown_pid = pid;
1574 no_shutdown = 0;
1576 /* Cannot call qemu_system_shutdown_request directly because
1577 * we are in a signal handler.
1579 shutdown_requested = SHUTDOWN_CAUSE_HOST_SIGNAL;
1580 qemu_notify_event();
1583 void qemu_system_shutdown_request(ShutdownCause reason)
1585 trace_qemu_system_shutdown_request(reason);
1586 replay_shutdown_request(reason);
1587 shutdown_requested = reason;
1588 qemu_notify_event();
1591 static void qemu_system_powerdown(void)
1593 qapi_event_send_powerdown();
1594 notifier_list_notify(&powerdown_notifiers, NULL);
1597 static void qemu_system_shutdown(ShutdownCause cause)
1599 qapi_event_send_shutdown(shutdown_caused_by_guest(cause), cause);
1600 notifier_list_notify(&shutdown_notifiers, &cause);
1603 void qemu_system_powerdown_request(void)
1605 trace_qemu_system_powerdown_request();
1606 powerdown_requested = 1;
1607 qemu_notify_event();
1610 void qemu_register_powerdown_notifier(Notifier *notifier)
1612 notifier_list_add(&powerdown_notifiers, notifier);
1615 void qemu_register_shutdown_notifier(Notifier *notifier)
1617 notifier_list_add(&shutdown_notifiers, notifier);
1620 void qemu_system_debug_request(void)
1622 debug_requested = 1;
1623 qemu_notify_event();
1626 static bool main_loop_should_exit(void)
1628 RunState r;
1629 ShutdownCause request;
1631 if (preconfig_exit_requested) {
1632 if (runstate_check(RUN_STATE_PRECONFIG)) {
1633 runstate_set(RUN_STATE_PRELAUNCH);
1635 preconfig_exit_requested = false;
1636 return true;
1638 if (qemu_debug_requested()) {
1639 vm_stop(RUN_STATE_DEBUG);
1641 if (qemu_suspend_requested()) {
1642 qemu_system_suspend();
1644 request = qemu_shutdown_requested();
1645 if (request) {
1646 qemu_kill_report();
1647 qemu_system_shutdown(request);
1648 if (no_shutdown) {
1649 vm_stop(RUN_STATE_SHUTDOWN);
1650 } else {
1651 return true;
1654 request = qemu_reset_requested();
1655 if (request) {
1656 pause_all_vcpus();
1657 qemu_system_reset(request);
1658 resume_all_vcpus();
1660 * runstate can change in pause_all_vcpus()
1661 * as iothread mutex is unlocked
1663 if (!runstate_check(RUN_STATE_RUNNING) &&
1664 !runstate_check(RUN_STATE_INMIGRATE) &&
1665 !runstate_check(RUN_STATE_FINISH_MIGRATE)) {
1666 runstate_set(RUN_STATE_PRELAUNCH);
1669 if (qemu_wakeup_requested()) {
1670 pause_all_vcpus();
1671 qemu_system_wakeup();
1672 notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
1673 wakeup_reason = QEMU_WAKEUP_REASON_NONE;
1674 resume_all_vcpus();
1675 qapi_event_send_wakeup();
1677 if (qemu_powerdown_requested()) {
1678 qemu_system_powerdown();
1680 if (qemu_vmstop_requested(&r)) {
1681 vm_stop(r);
1683 return false;
1686 void qemu_main_loop(void)
1688 #ifdef CONFIG_PROFILER
1689 int64_t ti;
1690 #endif
1691 while (!main_loop_should_exit()) {
1692 #ifdef CONFIG_PROFILER
1693 ti = profile_getclock();
1694 #endif
1695 main_loop_wait(false);
1696 #ifdef CONFIG_PROFILER
1697 dev_time += profile_getclock() - ti;
1698 #endif
1702 static void version(void)
1704 printf("QEMU emulator version " QEMU_FULL_VERSION "\n"
1705 QEMU_COPYRIGHT "\n");
1708 static void help(int exitcode)
1710 version();
1711 printf("usage: %s [options] [disk_image]\n\n"
1712 "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
1713 error_get_progname());
1715 #define QEMU_OPTIONS_GENERATE_HELP
1716 #include "qemu-options-wrapper.h"
1718 printf("\nDuring emulation, the following keys are useful:\n"
1719 "ctrl-alt-f toggle full screen\n"
1720 "ctrl-alt-n switch to virtual console 'n'\n"
1721 "ctrl-alt toggle mouse and keyboard grab\n"
1722 "\n"
1723 "When using -nographic, press 'ctrl-a h' to get some help.\n"
1724 "\n"
1725 QEMU_HELP_BOTTOM "\n");
1727 exit(exitcode);
1730 #define HAS_ARG 0x0001
1732 typedef struct QEMUOption {
1733 const char *name;
1734 int flags;
1735 int index;
1736 uint32_t arch_mask;
1737 } QEMUOption;
1739 static const QEMUOption qemu_options[] = {
1740 { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1741 #define QEMU_OPTIONS_GENERATE_OPTIONS
1742 #include "qemu-options-wrapper.h"
1743 { NULL },
1746 typedef struct VGAInterfaceInfo {
1747 const char *opt_name; /* option name */
1748 const char *name; /* human-readable name */
1749 /* Class names indicating that support is available.
1750 * If no class is specified, the interface is always available */
1751 const char *class_names[2];
1752 } VGAInterfaceInfo;
1754 static const VGAInterfaceInfo vga_interfaces[VGA_TYPE_MAX] = {
1755 [VGA_NONE] = {
1756 .opt_name = "none",
1757 .name = "no graphic card",
1759 [VGA_STD] = {
1760 .opt_name = "std",
1761 .name = "standard VGA",
1762 .class_names = { "VGA", "isa-vga" },
1764 [VGA_CIRRUS] = {
1765 .opt_name = "cirrus",
1766 .name = "Cirrus VGA",
1767 .class_names = { "cirrus-vga", "isa-cirrus-vga" },
1769 [VGA_VMWARE] = {
1770 .opt_name = "vmware",
1771 .name = "VMWare SVGA",
1772 .class_names = { "vmware-svga" },
1774 [VGA_VIRTIO] = {
1775 .opt_name = "virtio",
1776 .name = "Virtio VGA",
1777 .class_names = { "virtio-vga" },
1779 [VGA_QXL] = {
1780 .opt_name = "qxl",
1781 .name = "QXL VGA",
1782 .class_names = { "qxl-vga" },
1784 [VGA_TCX] = {
1785 .opt_name = "tcx",
1786 .name = "TCX framebuffer",
1787 .class_names = { "SUNW,tcx" },
1789 [VGA_CG3] = {
1790 .opt_name = "cg3",
1791 .name = "CG3 framebuffer",
1792 .class_names = { "cgthree" },
1794 [VGA_XENFB] = {
1795 .opt_name = "xenfb",
1796 .name = "Xen paravirtualized framebuffer",
1800 static bool vga_interface_available(VGAInterfaceType t)
1802 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1804 assert(t < VGA_TYPE_MAX);
1805 return !ti->class_names[0] ||
1806 module_object_class_by_name(ti->class_names[0]) ||
1807 module_object_class_by_name(ti->class_names[1]);
1810 static const char *
1811 get_default_vga_model(const MachineClass *machine_class)
1813 if (machine_class->default_display) {
1814 return machine_class->default_display;
1815 } else if (vga_interface_available(VGA_CIRRUS)) {
1816 return "cirrus";
1817 } else if (vga_interface_available(VGA_STD)) {
1818 return "std";
1821 return NULL;
1824 static void select_vgahw(const MachineClass *machine_class, const char *p)
1826 const char *opts;
1827 int t;
1829 if (g_str_equal(p, "help")) {
1830 const char *def = get_default_vga_model(machine_class);
1832 for (t = 0; t < VGA_TYPE_MAX; t++) {
1833 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1835 if (vga_interface_available(t) && ti->opt_name) {
1836 printf("%-20s %s%s\n", ti->opt_name, ti->name ?: "",
1837 g_str_equal(ti->opt_name, def) ? " (default)" : "");
1840 exit(0);
1843 assert(vga_interface_type == VGA_NONE);
1844 for (t = 0; t < VGA_TYPE_MAX; t++) {
1845 const VGAInterfaceInfo *ti = &vga_interfaces[t];
1846 if (ti->opt_name && strstart(p, ti->opt_name, &opts)) {
1847 if (!vga_interface_available(t)) {
1848 error_report("%s not available", ti->name);
1849 exit(1);
1851 vga_interface_type = t;
1852 break;
1855 if (t == VGA_TYPE_MAX) {
1856 invalid_vga:
1857 error_report("unknown vga type: %s", p);
1858 exit(1);
1860 while (*opts) {
1861 const char *nextopt;
1863 if (strstart(opts, ",retrace=", &nextopt)) {
1864 opts = nextopt;
1865 if (strstart(opts, "dumb", &nextopt))
1866 vga_retrace_method = VGA_RETRACE_DUMB;
1867 else if (strstart(opts, "precise", &nextopt))
1868 vga_retrace_method = VGA_RETRACE_PRECISE;
1869 else goto invalid_vga;
1870 } else goto invalid_vga;
1871 opts = nextopt;
1875 static void parse_display_qapi(const char *optarg)
1877 DisplayOptions *opts;
1878 Visitor *v;
1880 v = qobject_input_visitor_new_str(optarg, "type", &error_fatal);
1882 visit_type_DisplayOptions(v, NULL, &opts, &error_fatal);
1883 QAPI_CLONE_MEMBERS(DisplayOptions, &dpy, opts);
1885 qapi_free_DisplayOptions(opts);
1886 visit_free(v);
1889 DisplayOptions *qmp_query_display_options(Error **errp)
1891 return QAPI_CLONE(DisplayOptions, &dpy);
1894 static void parse_display(const char *p)
1896 const char *opts;
1898 if (is_help_option(p)) {
1899 qemu_display_help();
1900 exit(0);
1903 if (strstart(p, "sdl", &opts)) {
1905 * sdl DisplayType needs hand-crafted parser instead of
1906 * parse_display_qapi() due to some options not in
1907 * DisplayOptions, specifically:
1908 * - frame
1909 * Already deprecated.
1910 * - ctrl_grab + alt_grab
1911 * Not clear yet what happens to them long-term. Should
1912 * replaced by something better or deprecated and dropped.
1914 dpy.type = DISPLAY_TYPE_SDL;
1915 while (*opts) {
1916 const char *nextopt;
1918 if (strstart(opts, ",alt_grab=", &nextopt)) {
1919 opts = nextopt;
1920 if (strstart(opts, "on", &nextopt)) {
1921 alt_grab = 1;
1922 } else if (strstart(opts, "off", &nextopt)) {
1923 alt_grab = 0;
1924 } else {
1925 goto invalid_sdl_args;
1927 } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
1928 opts = nextopt;
1929 if (strstart(opts, "on", &nextopt)) {
1930 ctrl_grab = 1;
1931 } else if (strstart(opts, "off", &nextopt)) {
1932 ctrl_grab = 0;
1933 } else {
1934 goto invalid_sdl_args;
1936 } else if (strstart(opts, ",window_close=", &nextopt)) {
1937 opts = nextopt;
1938 dpy.has_window_close = true;
1939 if (strstart(opts, "on", &nextopt)) {
1940 dpy.window_close = true;
1941 } else if (strstart(opts, "off", &nextopt)) {
1942 dpy.window_close = false;
1943 } else {
1944 goto invalid_sdl_args;
1946 } else if (strstart(opts, ",show-cursor=", &nextopt)) {
1947 opts = nextopt;
1948 dpy.has_show_cursor = true;
1949 if (strstart(opts, "on", &nextopt)) {
1950 dpy.show_cursor = true;
1951 } else if (strstart(opts, "off", &nextopt)) {
1952 dpy.show_cursor = false;
1953 } else {
1954 goto invalid_sdl_args;
1956 } else if (strstart(opts, ",gl=", &nextopt)) {
1957 opts = nextopt;
1958 dpy.has_gl = true;
1959 if (strstart(opts, "on", &nextopt)) {
1960 dpy.gl = DISPLAYGL_MODE_ON;
1961 } else if (strstart(opts, "core", &nextopt)) {
1962 dpy.gl = DISPLAYGL_MODE_CORE;
1963 } else if (strstart(opts, "es", &nextopt)) {
1964 dpy.gl = DISPLAYGL_MODE_ES;
1965 } else if (strstart(opts, "off", &nextopt)) {
1966 dpy.gl = DISPLAYGL_MODE_OFF;
1967 } else {
1968 goto invalid_sdl_args;
1970 } else {
1971 invalid_sdl_args:
1972 error_report("invalid SDL option string");
1973 exit(1);
1975 opts = nextopt;
1977 } else if (strstart(p, "vnc", &opts)) {
1979 * vnc isn't a (local) DisplayType but a protocol for remote
1980 * display access.
1982 if (*opts == '=') {
1983 vnc_parse(opts + 1, &error_fatal);
1984 } else {
1985 error_report("VNC requires a display argument vnc=<display>");
1986 exit(1);
1988 } else {
1989 parse_display_qapi(p);
1993 static inline bool nonempty_str(const char *str)
1995 return str && *str;
1998 static int parse_fw_cfg(void *opaque, QemuOpts *opts, Error **errp)
2000 gchar *buf;
2001 size_t size;
2002 const char *name, *file, *str, *gen_id;
2003 FWCfgState *fw_cfg = (FWCfgState *) opaque;
2005 if (fw_cfg == NULL) {
2006 error_setg(errp, "fw_cfg device not available");
2007 return -1;
2009 name = qemu_opt_get(opts, "name");
2010 file = qemu_opt_get(opts, "file");
2011 str = qemu_opt_get(opts, "string");
2012 gen_id = qemu_opt_get(opts, "gen_id");
2014 /* we need the name, and exactly one of: file, content string, gen_id */
2015 if (!nonempty_str(name) ||
2016 nonempty_str(file) + nonempty_str(str) + nonempty_str(gen_id) != 1) {
2017 error_setg(errp, "name, plus exactly one of file,"
2018 " string and gen_id, are needed");
2019 return -1;
2021 if (strlen(name) > FW_CFG_MAX_FILE_PATH - 1) {
2022 error_setg(errp, "name too long (max. %d char)",
2023 FW_CFG_MAX_FILE_PATH - 1);
2024 return -1;
2026 if (nonempty_str(gen_id)) {
2028 * In this particular case where the content is populated
2029 * internally, the "etc/" namespace protection is relaxed,
2030 * so do not emit a warning.
2032 } else if (strncmp(name, "opt/", 4) != 0) {
2033 warn_report("externally provided fw_cfg item names "
2034 "should be prefixed with \"opt/\"");
2036 if (nonempty_str(str)) {
2037 size = strlen(str); /* NUL terminator NOT included in fw_cfg blob */
2038 buf = g_memdup(str, size);
2039 } else if (nonempty_str(gen_id)) {
2040 if (!fw_cfg_add_from_generator(fw_cfg, name, gen_id, errp)) {
2041 return -1;
2043 return 0;
2044 } else {
2045 GError *err = NULL;
2046 if (!g_file_get_contents(file, &buf, &size, &err)) {
2047 error_setg(errp, "can't load %s: %s", file, err->message);
2048 g_error_free(err);
2049 return -1;
2052 /* For legacy, keep user files in a specific global order. */
2053 fw_cfg_set_order_override(fw_cfg, FW_CFG_ORDER_OVERRIDE_USER);
2054 fw_cfg_add_file(fw_cfg, name, buf, size);
2055 fw_cfg_reset_order_override(fw_cfg);
2056 return 0;
2059 static int device_help_func(void *opaque, QemuOpts *opts, Error **errp)
2061 return qdev_device_help(opts);
2064 static int device_init_func(void *opaque, QemuOpts *opts, Error **errp)
2066 DeviceState *dev;
2068 dev = qdev_device_add(opts, errp);
2069 if (!dev && *errp) {
2070 error_report_err(*errp);
2071 return -1;
2072 } else if (dev) {
2073 object_unref(OBJECT(dev));
2075 return 0;
2078 static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2080 Error *local_err = NULL;
2082 if (!qemu_chr_new_from_opts(opts, NULL, &local_err)) {
2083 if (local_err) {
2084 error_propagate(errp, local_err);
2085 return -1;
2087 exit(0);
2089 return 0;
2092 #ifdef CONFIG_VIRTFS
2093 static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2095 return qemu_fsdev_add(opts, errp);
2097 #endif
2099 static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp)
2101 return monitor_init_opts(opts, errp);
2104 static void monitor_parse(const char *optarg, const char *mode, bool pretty)
2106 static int monitor_device_index = 0;
2107 QemuOpts *opts;
2108 const char *p;
2109 char label[32];
2111 if (strstart(optarg, "chardev:", &p)) {
2112 snprintf(label, sizeof(label), "%s", p);
2113 } else {
2114 snprintf(label, sizeof(label), "compat_monitor%d",
2115 monitor_device_index);
2116 opts = qemu_chr_parse_compat(label, optarg, true);
2117 if (!opts) {
2118 error_report("parse error: %s", optarg);
2119 exit(1);
2123 opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &error_fatal);
2124 qemu_opt_set(opts, "mode", mode, &error_abort);
2125 qemu_opt_set(opts, "chardev", label, &error_abort);
2126 if (!strcmp(mode, "control")) {
2127 qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);
2128 } else {
2129 assert(pretty == false);
2131 monitor_device_index++;
2134 struct device_config {
2135 enum {
2136 DEV_USB, /* -usbdevice */
2137 DEV_SERIAL, /* -serial */
2138 DEV_PARALLEL, /* -parallel */
2139 DEV_DEBUGCON, /* -debugcon */
2140 DEV_GDB, /* -gdb, -s */
2141 DEV_SCLP, /* s390 sclp */
2142 } type;
2143 const char *cmdline;
2144 Location loc;
2145 QTAILQ_ENTRY(device_config) next;
2148 static QTAILQ_HEAD(, device_config) device_configs =
2149 QTAILQ_HEAD_INITIALIZER(device_configs);
2151 static void add_device_config(int type, const char *cmdline)
2153 struct device_config *conf;
2155 conf = g_malloc0(sizeof(*conf));
2156 conf->type = type;
2157 conf->cmdline = cmdline;
2158 loc_save(&conf->loc);
2159 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2162 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2164 struct device_config *conf;
2165 int rc;
2167 QTAILQ_FOREACH(conf, &device_configs, next) {
2168 if (conf->type != type)
2169 continue;
2170 loc_push_restore(&conf->loc);
2171 rc = func(conf->cmdline);
2172 loc_pop(&conf->loc);
2173 if (rc) {
2174 return rc;
2177 return 0;
2180 static void qemu_disable_default_devices(void)
2182 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2184 qemu_opts_foreach(qemu_find_opts("device"),
2185 default_driver_check, NULL, NULL);
2186 qemu_opts_foreach(qemu_find_opts("global"),
2187 default_driver_check, NULL, NULL);
2189 if (!vga_model && !default_vga) {
2190 vga_interface_type = VGA_DEVICE;
2192 if (!has_defaults || machine_class->no_serial) {
2193 default_serial = 0;
2195 if (!has_defaults || machine_class->no_parallel) {
2196 default_parallel = 0;
2198 if (!has_defaults || machine_class->no_floppy) {
2199 default_floppy = 0;
2201 if (!has_defaults || machine_class->no_cdrom) {
2202 default_cdrom = 0;
2204 if (!has_defaults || machine_class->no_sdcard) {
2205 default_sdcard = 0;
2207 if (!has_defaults) {
2208 default_monitor = 0;
2209 default_net = 0;
2210 default_vga = 0;
2214 static void qemu_create_default_devices(void)
2216 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2218 if (is_daemonized()) {
2219 /* According to documentation and historically, -nographic redirects
2220 * serial port, parallel port and monitor to stdio, which does not work
2221 * with -daemonize. We can redirect these to null instead, but since
2222 * -nographic is legacy, let's just error out.
2223 * We disallow -nographic only if all other ports are not redirected
2224 * explicitly, to not break existing legacy setups which uses
2225 * -nographic _and_ redirects all ports explicitly - this is valid
2226 * usage, -nographic is just a no-op in this case.
2228 if (nographic
2229 && (default_parallel || default_serial || default_monitor)) {
2230 error_report("-nographic cannot be used with -daemonize");
2231 exit(1);
2235 if (nographic) {
2236 if (default_parallel)
2237 add_device_config(DEV_PARALLEL, "null");
2238 if (default_serial && default_monitor) {
2239 add_device_config(DEV_SERIAL, "mon:stdio");
2240 } else {
2241 if (default_serial)
2242 add_device_config(DEV_SERIAL, "stdio");
2243 if (default_monitor)
2244 monitor_parse("stdio", "readline", false);
2246 } else {
2247 if (default_serial)
2248 add_device_config(DEV_SERIAL, "vc:80Cx24C");
2249 if (default_parallel)
2250 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
2251 if (default_monitor)
2252 monitor_parse("vc:80Cx24C", "readline", false);
2255 if (default_net) {
2256 QemuOptsList *net = qemu_find_opts("net");
2257 qemu_opts_parse(net, "nic", true, &error_abort);
2258 #ifdef CONFIG_SLIRP
2259 qemu_opts_parse(net, "user", true, &error_abort);
2260 #endif
2263 #if defined(CONFIG_VNC)
2264 if (!QTAILQ_EMPTY(&(qemu_find_opts("vnc")->head))) {
2265 display_remote++;
2267 #endif
2268 if (dpy.type == DISPLAY_TYPE_DEFAULT && !display_remote) {
2269 if (!qemu_display_find_default(&dpy)) {
2270 dpy.type = DISPLAY_TYPE_NONE;
2271 #if defined(CONFIG_VNC)
2272 vnc_parse("localhost:0,to=99,id=default", &error_abort);
2273 #endif
2276 if (dpy.type == DISPLAY_TYPE_DEFAULT) {
2277 dpy.type = DISPLAY_TYPE_NONE;
2280 /* If no default VGA is requested, the default is "none". */
2281 if (default_vga) {
2282 vga_model = get_default_vga_model(machine_class);
2284 if (vga_model) {
2285 select_vgahw(machine_class, vga_model);
2289 static int serial_parse(const char *devname)
2291 int index = num_serial_hds;
2292 char label[32];
2294 if (strcmp(devname, "none") == 0)
2295 return 0;
2296 snprintf(label, sizeof(label), "serial%d", index);
2297 serial_hds = g_renew(Chardev *, serial_hds, index + 1);
2299 serial_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2300 if (!serial_hds[index]) {
2301 error_report("could not connect serial device"
2302 " to character backend '%s'", devname);
2303 return -1;
2305 num_serial_hds++;
2306 return 0;
2309 Chardev *serial_hd(int i)
2311 assert(i >= 0);
2312 if (i < num_serial_hds) {
2313 return serial_hds[i];
2315 return NULL;
2318 int serial_max_hds(void)
2320 return num_serial_hds;
2323 static int parallel_parse(const char *devname)
2325 static int index = 0;
2326 char label[32];
2328 if (strcmp(devname, "none") == 0)
2329 return 0;
2330 if (index == MAX_PARALLEL_PORTS) {
2331 error_report("too many parallel ports");
2332 exit(1);
2334 snprintf(label, sizeof(label), "parallel%d", index);
2335 parallel_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2336 if (!parallel_hds[index]) {
2337 error_report("could not connect parallel device"
2338 " to character backend '%s'", devname);
2339 return -1;
2341 index++;
2342 return 0;
2345 static int debugcon_parse(const char *devname)
2347 QemuOpts *opts;
2349 if (!qemu_chr_new_mux_mon("debugcon", devname, NULL)) {
2350 error_report("invalid character backend '%s'", devname);
2351 exit(1);
2353 opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2354 if (!opts) {
2355 error_report("already have a debugcon device");
2356 exit(1);
2358 qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);
2359 qemu_opt_set(opts, "chardev", "debugcon", &error_abort);
2360 return 0;
2363 static gint machine_class_cmp(gconstpointer a, gconstpointer b)
2365 const MachineClass *mc1 = a, *mc2 = b;
2366 int res;
2368 if (mc1->family == NULL) {
2369 if (mc2->family == NULL) {
2370 /* Compare standalone machine types against each other; they sort
2371 * in increasing order.
2373 return strcmp(object_class_get_name(OBJECT_CLASS(mc1)),
2374 object_class_get_name(OBJECT_CLASS(mc2)));
2377 /* Standalone machine types sort after families. */
2378 return 1;
2381 if (mc2->family == NULL) {
2382 /* Families sort before standalone machine types. */
2383 return -1;
2386 /* Families sort between each other alphabetically increasingly. */
2387 res = strcmp(mc1->family, mc2->family);
2388 if (res != 0) {
2389 return res;
2392 /* Within the same family, machine types sort in decreasing order. */
2393 return strcmp(object_class_get_name(OBJECT_CLASS(mc2)),
2394 object_class_get_name(OBJECT_CLASS(mc1)));
2397 static MachineClass *machine_parse(const char *name, GSList *machines)
2399 MachineClass *mc;
2400 GSList *el;
2402 if (is_help_option(name)) {
2403 printf("Supported machines are:\n");
2404 machines = g_slist_sort(machines, machine_class_cmp);
2405 for (el = machines; el; el = el->next) {
2406 MachineClass *mc = el->data;
2407 if (mc->alias) {
2408 printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
2410 printf("%-20s %s%s%s\n", mc->name, mc->desc,
2411 mc->is_default ? " (default)" : "",
2412 mc->deprecation_reason ? " (deprecated)" : "");
2414 exit(0);
2417 mc = find_machine(name, machines);
2418 if (!mc) {
2419 error_report("unsupported machine type");
2420 error_printf("Use -machine help to list supported machines\n");
2421 exit(1);
2423 return mc;
2426 void qemu_add_exit_notifier(Notifier *notify)
2428 notifier_list_add(&exit_notifiers, notify);
2431 void qemu_remove_exit_notifier(Notifier *notify)
2433 notifier_remove(notify);
2436 static void qemu_run_exit_notifiers(void)
2438 notifier_list_notify(&exit_notifiers, NULL);
2441 static const char *pid_file;
2442 static Notifier qemu_unlink_pidfile_notifier;
2444 static void qemu_unlink_pidfile(Notifier *n, void *data)
2446 if (pid_file) {
2447 unlink(pid_file);
2451 static const QEMUOption *lookup_opt(int argc, char **argv,
2452 const char **poptarg, int *poptind)
2454 const QEMUOption *popt;
2455 int optind = *poptind;
2456 char *r = argv[optind];
2457 const char *optarg;
2459 loc_set_cmdline(argv, optind, 1);
2460 optind++;
2461 /* Treat --foo the same as -foo. */
2462 if (r[1] == '-')
2463 r++;
2464 popt = qemu_options;
2465 for(;;) {
2466 if (!popt->name) {
2467 error_report("invalid option");
2468 exit(1);
2470 if (!strcmp(popt->name, r + 1))
2471 break;
2472 popt++;
2474 if (popt->flags & HAS_ARG) {
2475 if (optind >= argc) {
2476 error_report("requires an argument");
2477 exit(1);
2479 optarg = argv[optind++];
2480 loc_set_cmdline(argv, optind - 2, 2);
2481 } else {
2482 optarg = NULL;
2485 *poptarg = optarg;
2486 *poptind = optind;
2488 return popt;
2491 static MachineClass *select_machine(void)
2493 GSList *machines = object_class_get_list(TYPE_MACHINE, false);
2494 MachineClass *machine_class = find_default_machine(machines);
2495 const char *optarg;
2496 QemuOpts *opts;
2497 Location loc;
2499 loc_push_none(&loc);
2501 opts = qemu_get_machine_opts();
2502 qemu_opts_loc_restore(opts);
2504 optarg = qemu_opt_get(opts, "type");
2505 if (optarg) {
2506 machine_class = machine_parse(optarg, machines);
2509 if (!machine_class) {
2510 error_report("No machine specified, and there is no default");
2511 error_printf("Use -machine help to list supported machines\n");
2512 exit(1);
2515 loc_pop(&loc);
2516 g_slist_free(machines);
2517 return machine_class;
2520 static int object_parse_property_opt(Object *obj,
2521 const char *name, const char *value,
2522 const char *skip, Error **errp)
2524 if (g_str_equal(name, skip)) {
2525 return 0;
2528 if (!object_property_parse(obj, name, value, errp)) {
2529 return -1;
2532 return 0;
2535 static int machine_set_property(void *opaque,
2536 const char *name, const char *value,
2537 Error **errp)
2539 g_autofree char *qom_name = g_strdup(name);
2540 char *p;
2542 for (p = qom_name; *p; p++) {
2543 if (*p == '_') {
2544 *p = '-';
2548 /* Legacy options do not correspond to MachineState properties. */
2549 if (g_str_equal(qom_name, "accel")) {
2550 return 0;
2552 if (g_str_equal(qom_name, "igd-passthru")) {
2553 object_register_sugar_prop(ACCEL_CLASS_NAME("xen"), qom_name, value);
2554 return 0;
2556 if (g_str_equal(qom_name, "kvm-shadow-mem")) {
2557 object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), qom_name, value);
2558 return 0;
2560 if (g_str_equal(qom_name, "kernel-irqchip")) {
2561 object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), qom_name, value);
2562 object_register_sugar_prop(ACCEL_CLASS_NAME("whpx"), qom_name, value);
2563 return 0;
2566 return object_parse_property_opt(opaque, name, value, "type", errp);
2570 * Initial object creation happens before all other
2571 * QEMU data types are created. The majority of objects
2572 * can be created at this point. The rng-egd object
2573 * cannot be created here, as it depends on the chardev
2574 * already existing.
2576 static bool object_create_early(const char *type, QemuOpts *opts)
2578 if (user_creatable_print_help(type, opts)) {
2579 exit(0);
2583 * Objects should not be made "delayed" without a reason. If you
2584 * add one, state the reason in a comment!
2587 /* Reason: rng-egd property "chardev" */
2588 if (g_str_equal(type, "rng-egd")) {
2589 return false;
2592 #if defined(CONFIG_VHOST_USER) && defined(CONFIG_LINUX)
2593 /* Reason: cryptodev-vhost-user property "chardev" */
2594 if (g_str_equal(type, "cryptodev-vhost-user")) {
2595 return false;
2597 #endif
2599 /* Reason: vhost-user-blk-server property "node-name" */
2600 if (g_str_equal(type, "vhost-user-blk-server")) {
2601 return false;
2604 * Reason: filter-* property "netdev" etc.
2606 if (g_str_equal(type, "filter-buffer") ||
2607 g_str_equal(type, "filter-dump") ||
2608 g_str_equal(type, "filter-mirror") ||
2609 g_str_equal(type, "filter-redirector") ||
2610 g_str_equal(type, "colo-compare") ||
2611 g_str_equal(type, "filter-rewriter") ||
2612 g_str_equal(type, "filter-replay")) {
2613 return false;
2616 /* Memory allocation by backends needs to be done
2617 * after configure_accelerator() (due to the tcg_enabled()
2618 * checks at memory_region_init_*()).
2620 * Also, allocation of large amounts of memory may delay
2621 * chardev initialization for too long, and trigger timeouts
2622 * on software that waits for a monitor socket to be created
2623 * (e.g. libvirt).
2625 if (g_str_has_prefix(type, "memory-backend-")) {
2626 return false;
2629 return true;
2632 static void qemu_apply_machine_options(void)
2634 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2635 QemuOpts *machine_opts = qemu_get_machine_opts();
2636 QemuOpts *opts;
2638 qemu_opt_foreach(machine_opts, machine_set_property, current_machine,
2639 &error_fatal);
2640 current_machine->ram_size = ram_size;
2641 current_machine->maxram_size = maxram_size;
2642 current_machine->ram_slots = ram_slots;
2644 opts = qemu_opts_find(qemu_find_opts("boot-opts"), NULL);
2645 if (opts) {
2646 boot_order = qemu_opt_get(opts, "order");
2647 if (boot_order) {
2648 validate_bootdevices(boot_order, &error_fatal);
2651 boot_once = qemu_opt_get(opts, "once");
2652 if (boot_once) {
2653 validate_bootdevices(boot_once, &error_fatal);
2656 boot_menu = qemu_opt_get_bool(opts, "menu", boot_menu);
2657 boot_strict = qemu_opt_get_bool(opts, "strict", false);
2660 if (!boot_order) {
2661 boot_order = machine_class->default_boot_order;
2664 current_machine->boot_order = boot_order;
2666 if (semihosting_enabled() && !semihosting_get_argc()) {
2667 const char *kernel_filename = qemu_opt_get(machine_opts, "kernel");
2668 const char *kernel_cmdline = qemu_opt_get(machine_opts, "append") ?: "";
2669 /* fall back to the -kernel/-append */
2670 semihosting_arg_fallback(kernel_filename, kernel_cmdline);
2675 static void qemu_create_early_backends(void)
2677 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2679 if ((alt_grab || ctrl_grab) && dpy.type != DISPLAY_TYPE_SDL) {
2680 error_report("-alt-grab and -ctrl-grab are only valid "
2681 "for SDL, ignoring option");
2683 if (dpy.has_window_close &&
2684 (dpy.type != DISPLAY_TYPE_GTK && dpy.type != DISPLAY_TYPE_SDL)) {
2685 error_report("-no-quit is only valid for GTK and SDL, "
2686 "ignoring option");
2689 qemu_display_early_init(&dpy);
2690 qemu_console_early_init();
2692 if (dpy.has_gl && dpy.gl != DISPLAYGL_MODE_OFF && display_opengl == 0) {
2693 #if defined(CONFIG_OPENGL)
2694 error_report("OpenGL is not supported by the display");
2695 #else
2696 error_report("OpenGL support is disabled");
2697 #endif
2698 exit(1);
2701 qemu_opts_foreach(qemu_find_opts("object"),
2702 user_creatable_add_opts_foreach,
2703 object_create_early, &error_fatal);
2705 /* spice needs the timers to be initialized by this point */
2706 /* spice must initialize before audio as it changes the default auiodev */
2707 /* spice must initialize before chardevs (for spicevmc and spiceport) */
2708 qemu_spice.init();
2710 qemu_opts_foreach(qemu_find_opts("chardev"),
2711 chardev_init_func, NULL, &error_fatal);
2713 #ifdef CONFIG_VIRTFS
2714 qemu_opts_foreach(qemu_find_opts("fsdev"),
2715 fsdev_init_func, NULL, &error_fatal);
2716 #endif
2719 * Note: we need to create audio and block backends before
2720 * machine_set_property(), so machine properties can refer to
2721 * them.
2723 configure_blockdev(&bdo_queue, machine_class, snapshot);
2724 audio_init_audiodevs();
2729 * The remainder of object creation happens after the
2730 * creation of chardev, fsdev, net clients and device data types.
2732 static bool object_create_late(const char *type, QemuOpts *opts)
2734 return !object_create_early(type, opts);
2737 static void qemu_create_late_backends(void)
2739 if (qtest_chrdev) {
2740 qtest_server_init(qtest_chrdev, qtest_log, &error_fatal);
2743 net_init_clients(&error_fatal);
2745 qemu_opts_foreach(qemu_find_opts("object"),
2746 user_creatable_add_opts_foreach,
2747 object_create_late, &error_fatal);
2749 if (tpm_init() < 0) {
2750 exit(1);
2753 qemu_opts_foreach(qemu_find_opts("mon"),
2754 mon_init_func, NULL, &error_fatal);
2756 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
2757 exit(1);
2758 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
2759 exit(1);
2760 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
2761 exit(1);
2763 /* now chardevs have been created we may have semihosting to connect */
2764 qemu_semihosting_connect_chardevs();
2765 qemu_semihosting_console_init();
2768 static bool have_custom_ram_size(void)
2770 QemuOpts *opts = qemu_find_opts_singleton("memory");
2771 return !!qemu_opt_get_size(opts, "size", 0);
2774 static void qemu_resolve_machine_memdev(void)
2776 if (current_machine->ram_memdev_id) {
2777 Object *backend;
2778 ram_addr_t backend_size;
2780 backend = object_resolve_path_type(current_machine->ram_memdev_id,
2781 TYPE_MEMORY_BACKEND, NULL);
2782 if (!backend) {
2783 error_report("Memory backend '%s' not found",
2784 current_machine->ram_memdev_id);
2785 exit(EXIT_FAILURE);
2787 backend_size = object_property_get_uint(backend, "size", &error_abort);
2788 if (have_custom_ram_size() && backend_size != ram_size) {
2789 error_report("Size specified by -m option must match size of "
2790 "explicitly specified 'memory-backend' property");
2791 exit(EXIT_FAILURE);
2793 if (mem_path) {
2794 error_report("'-mem-path' can't be used together with"
2795 "'-machine memory-backend'");
2796 exit(EXIT_FAILURE);
2798 ram_size = backend_size;
2801 if (!xen_enabled()) {
2802 /* On 32-bit hosts, QEMU is limited by virtual address space */
2803 if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
2804 error_report("at most 2047 MB RAM can be simulated");
2805 exit(1);
2810 static void set_memory_options(MachineClass *mc)
2812 uint64_t sz;
2813 const char *mem_str;
2814 const ram_addr_t default_ram_size = mc->default_ram_size;
2815 QemuOpts *opts = qemu_find_opts_singleton("memory");
2816 Location loc;
2818 loc_push_none(&loc);
2819 qemu_opts_loc_restore(opts);
2821 sz = 0;
2822 mem_str = qemu_opt_get(opts, "size");
2823 if (mem_str) {
2824 if (!*mem_str) {
2825 error_report("missing 'size' option value");
2826 exit(EXIT_FAILURE);
2829 sz = qemu_opt_get_size(opts, "size", ram_size);
2831 /* Fix up legacy suffix-less format */
2832 if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
2833 uint64_t overflow_check = sz;
2835 sz *= MiB;
2836 if (sz / MiB != overflow_check) {
2837 error_report("too large 'size' option value");
2838 exit(EXIT_FAILURE);
2843 /* backward compatibility behaviour for case "-m 0" */
2844 if (sz == 0) {
2845 sz = default_ram_size;
2848 sz = QEMU_ALIGN_UP(sz, 8192);
2849 if (mc->fixup_ram_size) {
2850 sz = mc->fixup_ram_size(sz);
2852 ram_size = sz;
2853 if (ram_size != sz) {
2854 error_report("ram size too large");
2855 exit(EXIT_FAILURE);
2858 /* store value for the future use */
2859 qemu_opt_set_number(opts, "size", ram_size, &error_abort);
2860 maxram_size = ram_size;
2862 if (qemu_opt_get(opts, "maxmem")) {
2863 uint64_t slots;
2865 sz = qemu_opt_get_size(opts, "maxmem", 0);
2866 slots = qemu_opt_get_number(opts, "slots", 0);
2867 if (sz < ram_size) {
2868 error_report("invalid value of -m option maxmem: "
2869 "maximum memory size (0x%" PRIx64 ") must be at least "
2870 "the initial memory size (0x" RAM_ADDR_FMT ")",
2871 sz, ram_size);
2872 exit(EXIT_FAILURE);
2873 } else if (slots && sz == ram_size) {
2874 error_report("invalid value of -m option maxmem: "
2875 "memory slots were specified but maximum memory size "
2876 "(0x%" PRIx64 ") is equal to the initial memory size "
2877 "(0x" RAM_ADDR_FMT ")", sz, ram_size);
2878 exit(EXIT_FAILURE);
2881 maxram_size = sz;
2882 ram_slots = slots;
2883 } else if (qemu_opt_get(opts, "slots")) {
2884 error_report("invalid -m option value: missing 'maxmem' option");
2885 exit(EXIT_FAILURE);
2888 loc_pop(&loc);
2891 static void qemu_create_machine(MachineClass *machine_class)
2893 object_set_machine_compat_props(machine_class->compat_props);
2895 set_memory_options(machine_class);
2897 current_machine = MACHINE(object_new_with_class(OBJECT_CLASS(machine_class)));
2898 if (machine_help_func(qemu_get_machine_opts(), current_machine)) {
2899 exit(0);
2901 object_property_add_child(object_get_root(), "machine",
2902 OBJECT(current_machine));
2903 object_property_add_child(container_get(OBJECT(current_machine),
2904 "/unattached"),
2905 "sysbus", OBJECT(sysbus_get_default()));
2907 if (machine_class->minimum_page_bits) {
2908 if (!set_preferred_target_page_bits(machine_class->minimum_page_bits)) {
2909 /* This would be a board error: specifying a minimum smaller than
2910 * a target's compile-time fixed setting.
2912 g_assert_not_reached();
2916 cpu_exec_init_all();
2917 page_size_init();
2919 if (machine_class->hw_version) {
2920 qemu_set_hw_version(machine_class->hw_version);
2923 machine_smp_parse(current_machine,
2924 qemu_opts_find(qemu_find_opts("smp-opts"), NULL), &error_fatal);
2927 * Get the default machine options from the machine if it is not already
2928 * specified either by the configuration file or by the command line.
2930 if (machine_class->default_machine_opts) {
2931 qemu_opts_set_defaults(qemu_find_opts("machine"),
2932 machine_class->default_machine_opts, 0);
2936 static int global_init_func(void *opaque, QemuOpts *opts, Error **errp)
2938 GlobalProperty *g;
2940 g = g_malloc0(sizeof(*g));
2941 g->driver = qemu_opt_get(opts, "driver");
2942 g->property = qemu_opt_get(opts, "property");
2943 g->value = qemu_opt_get(opts, "value");
2944 qdev_prop_register_global(g);
2945 return 0;
2948 static int qemu_read_default_config_file(void)
2950 int ret;
2951 g_autofree char *file = get_relocated_path(CONFIG_QEMU_CONFDIR "/qemu.conf");
2953 ret = qemu_read_config_file(file);
2954 if (ret < 0 && ret != -ENOENT) {
2955 return ret;
2958 return 0;
2961 static void user_register_global_props(void)
2963 qemu_opts_foreach(qemu_find_opts("global"),
2964 global_init_func, NULL, NULL);
2967 static int do_configure_icount(void *opaque, QemuOpts *opts, Error **errp)
2969 icount_configure(opts, errp);
2970 return 0;
2973 static int accelerator_set_property(void *opaque,
2974 const char *name, const char *value,
2975 Error **errp)
2977 return object_parse_property_opt(opaque, name, value, "accel", errp);
2980 static int do_configure_accelerator(void *opaque, QemuOpts *opts, Error **errp)
2982 bool *p_init_failed = opaque;
2983 const char *acc = qemu_opt_get(opts, "accel");
2984 AccelClass *ac = accel_find(acc);
2985 AccelState *accel;
2986 int ret;
2987 bool qtest_with_kvm;
2989 qtest_with_kvm = g_str_equal(acc, "kvm") && qtest_chrdev != NULL;
2991 if (!ac) {
2992 *p_init_failed = true;
2993 if (!qtest_with_kvm) {
2994 error_report("invalid accelerator %s", acc);
2996 return 0;
2998 accel = ACCEL(object_new_with_class(OBJECT_CLASS(ac)));
2999 object_apply_compat_props(OBJECT(accel));
3000 qemu_opt_foreach(opts, accelerator_set_property,
3001 accel,
3002 &error_fatal);
3004 ret = accel_init_machine(accel, current_machine);
3005 if (ret < 0) {
3006 *p_init_failed = true;
3007 if (!qtest_with_kvm || ret != -ENOENT) {
3008 error_report("failed to initialize %s: %s", acc, strerror(-ret));
3010 return 0;
3013 return 1;
3016 static void configure_accelerators(const char *progname)
3018 const char *accel;
3019 bool init_failed = false;
3021 qemu_opts_foreach(qemu_find_opts("icount"),
3022 do_configure_icount, NULL, &error_fatal);
3024 accel = qemu_opt_get(qemu_get_machine_opts(), "accel");
3025 if (QTAILQ_EMPTY(&qemu_accel_opts.head)) {
3026 char **accel_list, **tmp;
3028 if (accel == NULL) {
3029 /* Select the default accelerator */
3030 bool have_tcg = accel_find("tcg");
3031 bool have_kvm = accel_find("kvm");
3033 if (have_tcg && have_kvm) {
3034 if (g_str_has_suffix(progname, "kvm")) {
3035 /* If the program name ends with "kvm", we prefer KVM */
3036 accel = "kvm:tcg";
3037 } else {
3038 accel = "tcg:kvm";
3040 } else if (have_kvm) {
3041 accel = "kvm";
3042 } else if (have_tcg) {
3043 accel = "tcg";
3044 } else {
3045 error_report("No accelerator selected and"
3046 " no default accelerator available");
3047 exit(1);
3050 accel_list = g_strsplit(accel, ":", 0);
3052 for (tmp = accel_list; *tmp; tmp++) {
3054 * Filter invalid accelerators here, to prevent obscenities
3055 * such as "-machine accel=tcg,,thread=single".
3057 if (accel_find(*tmp)) {
3058 qemu_opts_parse_noisily(qemu_find_opts("accel"), *tmp, true);
3059 } else {
3060 init_failed = true;
3061 error_report("invalid accelerator %s", *tmp);
3064 g_strfreev(accel_list);
3065 } else {
3066 if (accel != NULL) {
3067 error_report("The -accel and \"-machine accel=\" options are incompatible");
3068 exit(1);
3072 if (!qemu_opts_foreach(qemu_find_opts("accel"),
3073 do_configure_accelerator, &init_failed, &error_fatal)) {
3074 if (!init_failed) {
3075 error_report("no accelerator found");
3077 exit(1);
3080 if (init_failed && !qtest_chrdev) {
3081 AccelClass *ac = ACCEL_GET_CLASS(current_accel());
3082 error_report("falling back to %s", ac->name);
3085 if (icount_enabled() && !tcg_enabled()) {
3086 error_report("-icount is not allowed with hardware virtualization");
3087 exit(1);
3091 static void create_default_memdev(MachineState *ms, const char *path)
3093 Object *obj;
3094 MachineClass *mc = MACHINE_GET_CLASS(ms);
3096 obj = object_new(path ? TYPE_MEMORY_BACKEND_FILE : TYPE_MEMORY_BACKEND_RAM);
3097 if (path) {
3098 object_property_set_str(obj, "mem-path", path, &error_fatal);
3100 object_property_set_int(obj, "size", ms->ram_size, &error_fatal);
3101 object_property_add_child(object_get_objects_root(), mc->default_ram_id,
3102 obj);
3103 /* Ensure backend's memory region name is equal to mc->default_ram_id */
3104 object_property_set_bool(obj, "x-use-canonical-path-for-ramblock-id",
3105 false, &error_fatal);
3106 user_creatable_complete(USER_CREATABLE(obj), &error_fatal);
3107 object_unref(obj);
3108 object_property_set_str(OBJECT(ms), "memory-backend", mc->default_ram_id,
3109 &error_fatal);
3112 static void qemu_validate_options(void)
3114 QemuOpts *machine_opts = qemu_get_machine_opts();
3115 const char *kernel_filename = qemu_opt_get(machine_opts, "kernel");
3116 const char *initrd_filename = qemu_opt_get(machine_opts, "initrd");
3117 const char *kernel_cmdline = qemu_opt_get(machine_opts, "append");
3119 if (kernel_filename == NULL) {
3120 if (kernel_cmdline != NULL) {
3121 error_report("-append only allowed with -kernel option");
3122 exit(1);
3125 if (initrd_filename != NULL) {
3126 error_report("-initrd only allowed with -kernel option");
3127 exit(1);
3131 if (loadvm && preconfig_requested) {
3132 error_report("'preconfig' and 'loadvm' options are "
3133 "mutually exclusive");
3134 exit(EXIT_FAILURE);
3136 if (incoming && preconfig_requested) {
3137 error_report("'preconfig' and 'incoming' options are "
3138 "mutually exclusive");
3139 exit(EXIT_FAILURE);
3142 #ifdef CONFIG_CURSES
3143 if (is_daemonized() && dpy.type == DISPLAY_TYPE_CURSES) {
3144 error_report("curses display cannot be used with -daemonize");
3145 exit(1);
3147 #endif
3150 static void qemu_process_sugar_options(void)
3152 if (mem_prealloc) {
3153 char *val;
3155 val = g_strdup_printf("%d",
3156 (uint32_t) qemu_opt_get_number(qemu_find_opts_singleton("smp-opts"), "cpus", 1));
3157 object_register_sugar_prop("memory-backend", "prealloc-threads", val);
3158 g_free(val);
3159 object_register_sugar_prop("memory-backend", "prealloc", "on");
3162 if (watchdog) {
3163 int i = select_watchdog(watchdog);
3164 if (i > 0)
3165 exit (i == 1 ? 1 : 0);
3169 static void qemu_process_early_options(void)
3171 #ifdef CONFIG_SECCOMP
3172 QemuOptsList *olist = qemu_find_opts_err("sandbox", NULL);
3173 if (olist) {
3174 qemu_opts_foreach(olist, parse_sandbox, NULL, &error_fatal);
3176 #endif
3178 qemu_opts_foreach(qemu_find_opts("name"),
3179 parse_name, NULL, &error_fatal);
3181 #ifndef _WIN32
3182 qemu_opts_foreach(qemu_find_opts("add-fd"),
3183 parse_add_fd, NULL, &error_fatal);
3185 qemu_opts_foreach(qemu_find_opts("add-fd"),
3186 cleanup_add_fd, NULL, &error_fatal);
3187 #endif
3189 if (!trace_init_backends()) {
3190 exit(1);
3192 trace_init_file();
3194 /* Open the logfile at this point and set the log mask if necessary. */
3195 qemu_set_log_filename(log_file, &error_fatal);
3196 if (log_mask) {
3197 int mask;
3198 mask = qemu_str_to_log_mask(log_mask);
3199 if (!mask) {
3200 qemu_print_log_usage(stdout);
3201 exit(1);
3203 qemu_set_log(mask);
3204 } else {
3205 qemu_set_log(0);
3208 qemu_add_default_firmwarepath();
3211 static void qemu_process_help_options(void)
3214 * Check for -cpu help and -device help before we call select_machine(),
3215 * which will return an error if the architecture has no default machine
3216 * type and the user did not specify one, so that the user doesn't need
3217 * to say '-cpu help -machine something'.
3219 if (cpu_option && is_help_option(cpu_option)) {
3220 list_cpus(cpu_option);
3221 exit(0);
3224 if (qemu_opts_foreach(qemu_find_opts("device"),
3225 device_help_func, NULL, NULL)) {
3226 exit(0);
3229 /* -L help lists the data directories and exits. */
3230 if (list_data_dirs) {
3231 qemu_list_data_dirs();
3232 exit(0);
3236 static void qemu_maybe_daemonize(const char *pid_file)
3238 Error *err;
3240 os_daemonize();
3241 rcu_disable_atfork();
3243 if (pid_file && !qemu_write_pidfile(pid_file, &err)) {
3244 error_reportf_err(err, "cannot create PID file: ");
3245 exit(1);
3248 qemu_unlink_pidfile_notifier.notify = qemu_unlink_pidfile;
3249 qemu_add_exit_notifier(&qemu_unlink_pidfile_notifier);
3252 static void qemu_init_subsystems(void)
3254 Error *err;
3256 os_set_line_buffering();
3258 module_call_init(MODULE_INIT_TRACE);
3260 qemu_init_cpu_list();
3261 qemu_init_cpu_loop();
3262 qemu_mutex_lock_iothread();
3264 atexit(qemu_run_exit_notifiers);
3266 module_call_init(MODULE_INIT_QOM);
3267 module_call_init(MODULE_INIT_MIGRATION);
3269 runstate_init();
3270 precopy_infrastructure_init();
3271 postcopy_infrastructure_init();
3272 monitor_init_globals();
3274 if (qcrypto_init(&err) < 0) {
3275 error_reportf_err(err, "cannot initialize crypto: ");
3276 exit(1);
3279 os_setup_early_signal_handling();
3281 bdrv_init_with_whitelist();
3282 socket_init();
3285 static void qemu_init_displays(void)
3287 DisplayState *ds;
3289 /* init local displays */
3290 ds = init_displaystate();
3291 qemu_display_init(ds, &dpy);
3293 /* must be after terminal init, SDL library changes signal handlers */
3294 os_setup_signal_handling();
3296 /* init remote displays */
3297 #ifdef CONFIG_VNC
3298 qemu_opts_foreach(qemu_find_opts("vnc"),
3299 vnc_init_func, NULL, &error_fatal);
3300 #endif
3302 if (using_spice) {
3303 qemu_spice.display_init();
3308 * Called after leaving preconfig state. From here on runstate is
3309 * RUN_STATE_PRELAUNCH or RUN_STATE_INMIGRATE.
3311 static void qemu_init_board(void)
3313 MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
3315 if (machine_class->default_ram_id && current_machine->ram_size &&
3316 numa_uses_legacy_mem() && !current_machine->ram_memdev_id) {
3317 create_default_memdev(current_machine, mem_path);
3320 /* process plugin before CPUs are created, but once -smp has been parsed */
3321 if (qemu_plugin_load_list(&plugin_list)) {
3322 exit(1);
3325 machine_run_board_init(current_machine);
3328 * TODO To drop support for deprecated bogus if=..., move
3329 * drive_check_orphaned() here, replacing this call. Also drop
3330 * its deprecation warning, along with DriveInfo member
3331 * @claimed_by_board.
3333 drive_mark_claimed_by_board();
3335 realtime_init();
3337 if (hax_enabled()) {
3338 /* FIXME: why isn't cpu_synchronize_all_post_init enough? */
3339 hax_sync_vcpus();
3343 static void qemu_create_cli_devices(void)
3345 soundhw_init();
3347 qemu_opts_foreach(qemu_find_opts("fw_cfg"),
3348 parse_fw_cfg, fw_cfg_find(), &error_fatal);
3350 /* init USB devices */
3351 if (machine_usb(current_machine)) {
3352 if (foreach_device_config(DEV_USB, usb_parse) < 0)
3353 exit(1);
3356 /* init generic devices */
3357 rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
3358 qemu_opts_foreach(qemu_find_opts("device"),
3359 device_init_func, NULL, &error_fatal);
3360 rom_reset_order_override();
3363 static void qemu_machine_creation_done(void)
3365 cpu_synchronize_all_post_init();
3367 /* Did we create any drives that we failed to create a device for? */
3368 drive_check_orphaned();
3370 /* Don't warn about the default network setup that you get if
3371 * no command line -net or -netdev options are specified. There
3372 * are two cases that we would otherwise complain about:
3373 * (1) board doesn't support a NIC but the implicit "-net nic"
3374 * requested one
3375 * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
3376 * sets up a nic that isn't connected to anything.
3378 if (!default_net && (!qtest_enabled() || has_defaults)) {
3379 net_check_clients();
3382 qdev_prop_check_globals();
3384 if (boot_once) {
3385 qemu_boot_set(boot_once, &error_fatal);
3386 qemu_register_reset(restore_boot_order, g_strdup(boot_order));
3389 if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
3390 exit(1);
3393 qdev_machine_creation_done();
3395 /* TODO: once all bus devices are qdevified, this should be done
3396 * when bus is created by qdev.c */
3398 * TODO: If we had a main 'reset container' that the whole system
3399 * lived in, we could reset that using the multi-phase reset
3400 * APIs. For the moment, we just reset the sysbus, which will cause
3401 * all devices hanging off it (and all their child buses, recursively)
3402 * to be reset. Note that this will *not* reset any Device objects
3403 * which are not attached to some part of the qbus tree!
3405 qemu_register_reset(resettable_cold_reset_fn, sysbus_get_default());
3406 qemu_run_machine_init_done_notifiers();
3408 if (rom_check_and_register_reset() != 0) {
3409 error_report("rom check and register reset failed");
3410 exit(1);
3413 replay_start();
3415 /* This checkpoint is required by replay to separate prior clock
3416 reading from the other reads, because timer polling functions query
3417 clock values from the log. */
3418 replay_checkpoint(CHECKPOINT_RESET);
3419 qemu_system_reset(SHUTDOWN_CAUSE_NONE);
3420 register_global_state();
3423 void qemu_init(int argc, char **argv, char **envp)
3425 QemuOpts *opts;
3426 QemuOpts *icount_opts = NULL, *accel_opts = NULL;
3427 QemuOptsList *olist;
3428 int optind;
3429 const char *optarg;
3430 MachineClass *machine_class;
3431 bool userconfig = true;
3432 FILE *vmstate_dump_file = NULL;
3434 qemu_add_opts(&qemu_drive_opts);
3435 qemu_add_drive_opts(&qemu_legacy_drive_opts);
3436 qemu_add_drive_opts(&qemu_common_drive_opts);
3437 qemu_add_drive_opts(&qemu_drive_opts);
3438 qemu_add_drive_opts(&bdrv_runtime_opts);
3439 qemu_add_opts(&qemu_chardev_opts);
3440 qemu_add_opts(&qemu_device_opts);
3441 qemu_add_opts(&qemu_netdev_opts);
3442 qemu_add_opts(&qemu_nic_opts);
3443 qemu_add_opts(&qemu_net_opts);
3444 qemu_add_opts(&qemu_rtc_opts);
3445 qemu_add_opts(&qemu_global_opts);
3446 qemu_add_opts(&qemu_mon_opts);
3447 qemu_add_opts(&qemu_trace_opts);
3448 qemu_plugin_add_opts();
3449 qemu_add_opts(&qemu_option_rom_opts);
3450 qemu_add_opts(&qemu_machine_opts);
3451 qemu_add_opts(&qemu_accel_opts);
3452 qemu_add_opts(&qemu_mem_opts);
3453 qemu_add_opts(&qemu_smp_opts);
3454 qemu_add_opts(&qemu_boot_opts);
3455 qemu_add_opts(&qemu_add_fd_opts);
3456 qemu_add_opts(&qemu_object_opts);
3457 qemu_add_opts(&qemu_tpmdev_opts);
3458 qemu_add_opts(&qemu_realtime_opts);
3459 qemu_add_opts(&qemu_overcommit_opts);
3460 qemu_add_opts(&qemu_msg_opts);
3461 qemu_add_opts(&qemu_name_opts);
3462 qemu_add_opts(&qemu_numa_opts);
3463 qemu_add_opts(&qemu_icount_opts);
3464 qemu_add_opts(&qemu_semihosting_config_opts);
3465 qemu_add_opts(&qemu_fw_cfg_opts);
3466 module_call_init(MODULE_INIT_OPTS);
3468 error_init(argv[0]);
3469 qemu_init_exec_dir(argv[0]);
3471 qemu_init_subsystems();
3473 /* first pass of option parsing */
3474 optind = 1;
3475 while (optind < argc) {
3476 if (argv[optind][0] != '-') {
3477 /* disk image */
3478 optind++;
3479 } else {
3480 const QEMUOption *popt;
3482 popt = lookup_opt(argc, argv, &optarg, &optind);
3483 switch (popt->index) {
3484 case QEMU_OPTION_nouserconfig:
3485 userconfig = false;
3486 break;
3491 if (userconfig) {
3492 if (qemu_read_default_config_file() < 0) {
3493 exit(1);
3497 /* second pass of option parsing */
3498 optind = 1;
3499 for(;;) {
3500 if (optind >= argc)
3501 break;
3502 if (argv[optind][0] != '-') {
3503 loc_set_cmdline(argv, optind, 1);
3504 drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
3505 } else {
3506 const QEMUOption *popt;
3508 popt = lookup_opt(argc, argv, &optarg, &optind);
3509 if (!(popt->arch_mask & arch_type)) {
3510 error_report("Option not supported for this target");
3511 exit(1);
3513 switch(popt->index) {
3514 case QEMU_OPTION_cpu:
3515 /* hw initialization will check this */
3516 cpu_option = optarg;
3517 break;
3518 case QEMU_OPTION_hda:
3519 case QEMU_OPTION_hdb:
3520 case QEMU_OPTION_hdc:
3521 case QEMU_OPTION_hdd:
3522 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
3523 HD_OPTS);
3524 break;
3525 case QEMU_OPTION_blockdev:
3527 Visitor *v;
3528 BlockdevOptionsQueueEntry *bdo;
3530 v = qobject_input_visitor_new_str(optarg, "driver",
3531 &error_fatal);
3533 bdo = g_new(BlockdevOptionsQueueEntry, 1);
3534 visit_type_BlockdevOptions(v, NULL, &bdo->bdo,
3535 &error_fatal);
3536 visit_free(v);
3537 loc_save(&bdo->loc);
3538 QSIMPLEQ_INSERT_TAIL(&bdo_queue, bdo, entry);
3539 break;
3541 case QEMU_OPTION_drive:
3542 if (drive_def(optarg) == NULL) {
3543 exit(1);
3545 break;
3546 case QEMU_OPTION_set:
3547 if (qemu_set_option(optarg) != 0)
3548 exit(1);
3549 break;
3550 case QEMU_OPTION_global:
3551 if (qemu_global_option(optarg) != 0)
3552 exit(1);
3553 break;
3554 case QEMU_OPTION_mtdblock:
3555 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
3556 break;
3557 case QEMU_OPTION_sd:
3558 drive_add(IF_SD, -1, optarg, SD_OPTS);
3559 break;
3560 case QEMU_OPTION_pflash:
3561 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
3562 break;
3563 case QEMU_OPTION_snapshot:
3565 Error *blocker = NULL;
3566 snapshot = 1;
3567 error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
3568 "-snapshot");
3569 replay_add_blocker(blocker);
3571 break;
3572 case QEMU_OPTION_numa:
3573 opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
3574 optarg, true);
3575 if (!opts) {
3576 exit(1);
3578 break;
3579 case QEMU_OPTION_display:
3580 parse_display(optarg);
3581 break;
3582 case QEMU_OPTION_nographic:
3583 olist = qemu_find_opts("machine");
3584 qemu_opts_parse_noisily(olist, "graphics=off", false);
3585 nographic = true;
3586 dpy.type = DISPLAY_TYPE_NONE;
3587 break;
3588 case QEMU_OPTION_curses:
3589 #ifdef CONFIG_CURSES
3590 dpy.type = DISPLAY_TYPE_CURSES;
3591 #else
3592 error_report("curses or iconv support is disabled");
3593 exit(1);
3594 #endif
3595 break;
3596 case QEMU_OPTION_portrait:
3597 graphic_rotate = 90;
3598 break;
3599 case QEMU_OPTION_rotate:
3600 graphic_rotate = strtol(optarg, (char **) &optarg, 10);
3601 if (graphic_rotate != 0 && graphic_rotate != 90 &&
3602 graphic_rotate != 180 && graphic_rotate != 270) {
3603 error_report("only 90, 180, 270 deg rotation is available");
3604 exit(1);
3606 break;
3607 case QEMU_OPTION_kernel:
3608 qemu_opts_set(qemu_find_opts("machine"), "kernel", optarg, &error_abort);
3609 break;
3610 case QEMU_OPTION_initrd:
3611 qemu_opts_set(qemu_find_opts("machine"), "initrd", optarg, &error_abort);
3612 break;
3613 case QEMU_OPTION_append:
3614 qemu_opts_set(qemu_find_opts("machine"), "append", optarg, &error_abort);
3615 break;
3616 case QEMU_OPTION_dtb:
3617 qemu_opts_set(qemu_find_opts("machine"), "dtb", optarg, &error_abort);
3618 break;
3619 case QEMU_OPTION_cdrom:
3620 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
3621 break;
3622 case QEMU_OPTION_boot:
3623 opts = qemu_opts_parse_noisily(qemu_find_opts("boot-opts"),
3624 optarg, true);
3625 if (!opts) {
3626 exit(1);
3628 break;
3629 case QEMU_OPTION_fda:
3630 case QEMU_OPTION_fdb:
3631 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
3632 optarg, FD_OPTS);
3633 break;
3634 case QEMU_OPTION_no_fd_bootchk:
3635 fd_bootchk = 0;
3636 break;
3637 case QEMU_OPTION_netdev:
3638 default_net = 0;
3639 if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
3640 exit(1);
3642 break;
3643 case QEMU_OPTION_nic:
3644 default_net = 0;
3645 if (net_client_parse(qemu_find_opts("nic"), optarg) == -1) {
3646 exit(1);
3648 break;
3649 case QEMU_OPTION_net:
3650 default_net = 0;
3651 if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
3652 exit(1);
3654 break;
3655 #ifdef CONFIG_LIBISCSI
3656 case QEMU_OPTION_iscsi:
3657 opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
3658 optarg, false);
3659 if (!opts) {
3660 exit(1);
3662 break;
3663 #endif
3664 case QEMU_OPTION_audio_help:
3665 audio_legacy_help();
3666 exit (0);
3667 break;
3668 case QEMU_OPTION_audiodev:
3669 audio_parse_option(optarg);
3670 break;
3671 case QEMU_OPTION_soundhw:
3672 select_soundhw (optarg);
3673 break;
3674 case QEMU_OPTION_h:
3675 help(0);
3676 break;
3677 case QEMU_OPTION_version:
3678 version();
3679 exit(0);
3680 break;
3681 case QEMU_OPTION_m:
3682 opts = qemu_opts_parse_noisily(qemu_find_opts("memory"),
3683 optarg, true);
3684 if (!opts) {
3685 exit(EXIT_FAILURE);
3687 break;
3688 #ifdef CONFIG_TPM
3689 case QEMU_OPTION_tpmdev:
3690 if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3691 exit(1);
3693 break;
3694 #endif
3695 case QEMU_OPTION_mempath:
3696 mem_path = optarg;
3697 break;
3698 case QEMU_OPTION_mem_prealloc:
3699 mem_prealloc = 1;
3700 break;
3701 case QEMU_OPTION_d:
3702 log_mask = optarg;
3703 break;
3704 case QEMU_OPTION_D:
3705 log_file = optarg;
3706 break;
3707 case QEMU_OPTION_DFILTER:
3708 qemu_set_dfilter_ranges(optarg, &error_fatal);
3709 break;
3710 case QEMU_OPTION_seed:
3711 qemu_guest_random_seed_main(optarg, &error_fatal);
3712 break;
3713 case QEMU_OPTION_s:
3714 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3715 break;
3716 case QEMU_OPTION_gdb:
3717 add_device_config(DEV_GDB, optarg);
3718 break;
3719 case QEMU_OPTION_L:
3720 if (is_help_option(optarg)) {
3721 list_data_dirs = true;
3722 } else {
3723 qemu_add_data_dir(g_strdup(optarg));
3725 break;
3726 case QEMU_OPTION_bios:
3727 qemu_opts_set(qemu_find_opts("machine"), "firmware", optarg, &error_abort);
3728 break;
3729 case QEMU_OPTION_singlestep:
3730 singlestep = 1;
3731 break;
3732 case QEMU_OPTION_S:
3733 autostart = 0;
3734 break;
3735 case QEMU_OPTION_k:
3736 keyboard_layout = optarg;
3737 break;
3738 case QEMU_OPTION_vga:
3739 vga_model = optarg;
3740 default_vga = 0;
3741 break;
3742 case QEMU_OPTION_g:
3744 const char *p;
3745 int w, h, depth;
3746 p = optarg;
3747 w = strtol(p, (char **)&p, 10);
3748 if (w <= 0) {
3749 graphic_error:
3750 error_report("invalid resolution or depth");
3751 exit(1);
3753 if (*p != 'x')
3754 goto graphic_error;
3755 p++;
3756 h = strtol(p, (char **)&p, 10);
3757 if (h <= 0)
3758 goto graphic_error;
3759 if (*p == 'x') {
3760 p++;
3761 depth = strtol(p, (char **)&p, 10);
3762 if (depth != 1 && depth != 2 && depth != 4 &&
3763 depth != 8 && depth != 15 && depth != 16 &&
3764 depth != 24 && depth != 32)
3765 goto graphic_error;
3766 } else if (*p == '\0') {
3767 depth = graphic_depth;
3768 } else {
3769 goto graphic_error;
3772 graphic_width = w;
3773 graphic_height = h;
3774 graphic_depth = depth;
3776 break;
3777 case QEMU_OPTION_echr:
3779 char *r;
3780 term_escape_char = strtol(optarg, &r, 0);
3781 if (r == optarg)
3782 printf("Bad argument to echr\n");
3783 break;
3785 case QEMU_OPTION_monitor:
3786 default_monitor = 0;
3787 if (strncmp(optarg, "none", 4)) {
3788 monitor_parse(optarg, "readline", false);
3790 break;
3791 case QEMU_OPTION_qmp:
3792 monitor_parse(optarg, "control", false);
3793 default_monitor = 0;
3794 break;
3795 case QEMU_OPTION_qmp_pretty:
3796 monitor_parse(optarg, "control", true);
3797 default_monitor = 0;
3798 break;
3799 case QEMU_OPTION_mon:
3800 opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
3801 true);
3802 if (!opts) {
3803 exit(1);
3805 default_monitor = 0;
3806 break;
3807 case QEMU_OPTION_chardev:
3808 opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
3809 optarg, true);
3810 if (!opts) {
3811 exit(1);
3813 break;
3814 case QEMU_OPTION_fsdev:
3815 olist = qemu_find_opts("fsdev");
3816 if (!olist) {
3817 error_report("fsdev support is disabled");
3818 exit(1);
3820 opts = qemu_opts_parse_noisily(olist, optarg, true);
3821 if (!opts) {
3822 exit(1);
3824 break;
3825 case QEMU_OPTION_virtfs: {
3826 QemuOpts *fsdev;
3827 QemuOpts *device;
3828 const char *writeout, *sock_fd, *socket, *path, *security_model,
3829 *multidevs;
3831 olist = qemu_find_opts("virtfs");
3832 if (!olist) {
3833 error_report("virtfs support is disabled");
3834 exit(1);
3836 opts = qemu_opts_parse_noisily(olist, optarg, true);
3837 if (!opts) {
3838 exit(1);
3841 if (qemu_opt_get(opts, "fsdriver") == NULL ||
3842 qemu_opt_get(opts, "mount_tag") == NULL) {
3843 error_report("Usage: -virtfs fsdriver,mount_tag=tag");
3844 exit(1);
3846 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3847 qemu_opts_id(opts) ?:
3848 qemu_opt_get(opts, "mount_tag"),
3849 1, NULL);
3850 if (!fsdev) {
3851 error_report("duplicate or invalid fsdev id: %s",
3852 qemu_opt_get(opts, "mount_tag"));
3853 exit(1);
3856 writeout = qemu_opt_get(opts, "writeout");
3857 if (writeout) {
3858 #ifdef CONFIG_SYNC_FILE_RANGE
3859 qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
3860 #else
3861 error_report("writeout=immediate not supported "
3862 "on this platform");
3863 exit(1);
3864 #endif
3866 qemu_opt_set(fsdev, "fsdriver",
3867 qemu_opt_get(opts, "fsdriver"), &error_abort);
3868 path = qemu_opt_get(opts, "path");
3869 if (path) {
3870 qemu_opt_set(fsdev, "path", path, &error_abort);
3872 security_model = qemu_opt_get(opts, "security_model");
3873 if (security_model) {
3874 qemu_opt_set(fsdev, "security_model", security_model,
3875 &error_abort);
3877 socket = qemu_opt_get(opts, "socket");
3878 if (socket) {
3879 qemu_opt_set(fsdev, "socket", socket, &error_abort);
3881 sock_fd = qemu_opt_get(opts, "sock_fd");
3882 if (sock_fd) {
3883 qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
3886 qemu_opt_set_bool(fsdev, "readonly",
3887 qemu_opt_get_bool(opts, "readonly", 0),
3888 &error_abort);
3889 multidevs = qemu_opt_get(opts, "multidevs");
3890 if (multidevs) {
3891 qemu_opt_set(fsdev, "multidevs", multidevs, &error_abort);
3893 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3894 &error_abort);
3895 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3896 qemu_opt_set(device, "fsdev",
3897 qemu_opts_id(fsdev), &error_abort);
3898 qemu_opt_set(device, "mount_tag",
3899 qemu_opt_get(opts, "mount_tag"), &error_abort);
3900 break;
3902 case QEMU_OPTION_serial:
3903 add_device_config(DEV_SERIAL, optarg);
3904 default_serial = 0;
3905 if (strncmp(optarg, "mon:", 4) == 0) {
3906 default_monitor = 0;
3908 break;
3909 case QEMU_OPTION_watchdog:
3910 if (watchdog) {
3911 error_report("only one watchdog option may be given");
3912 exit(1);
3914 watchdog = optarg;
3915 break;
3916 case QEMU_OPTION_watchdog_action:
3917 if (select_watchdog_action(optarg) == -1) {
3918 error_report("unknown -watchdog-action parameter");
3919 exit(1);
3921 break;
3922 case QEMU_OPTION_parallel:
3923 add_device_config(DEV_PARALLEL, optarg);
3924 default_parallel = 0;
3925 if (strncmp(optarg, "mon:", 4) == 0) {
3926 default_monitor = 0;
3928 break;
3929 case QEMU_OPTION_debugcon:
3930 add_device_config(DEV_DEBUGCON, optarg);
3931 break;
3932 case QEMU_OPTION_loadvm:
3933 loadvm = optarg;
3934 break;
3935 case QEMU_OPTION_full_screen:
3936 dpy.has_full_screen = true;
3937 dpy.full_screen = true;
3938 break;
3939 case QEMU_OPTION_alt_grab:
3940 alt_grab = 1;
3941 break;
3942 case QEMU_OPTION_ctrl_grab:
3943 ctrl_grab = 1;
3944 break;
3945 case QEMU_OPTION_no_quit:
3946 dpy.has_window_close = true;
3947 dpy.window_close = false;
3948 break;
3949 case QEMU_OPTION_sdl:
3950 #ifdef CONFIG_SDL
3951 dpy.type = DISPLAY_TYPE_SDL;
3952 break;
3953 #else
3954 error_report("SDL support is disabled");
3955 exit(1);
3956 #endif
3957 case QEMU_OPTION_pidfile:
3958 pid_file = optarg;
3959 break;
3960 case QEMU_OPTION_win2k_hack:
3961 win2k_install_hack = 1;
3962 break;
3963 case QEMU_OPTION_acpitable:
3964 opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
3965 optarg, true);
3966 if (!opts) {
3967 exit(1);
3969 acpi_table_add(opts, &error_fatal);
3970 break;
3971 case QEMU_OPTION_smbios:
3972 opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
3973 optarg, false);
3974 if (!opts) {
3975 exit(1);
3977 smbios_entry_add(opts, &error_fatal);
3978 break;
3979 case QEMU_OPTION_fwcfg:
3980 opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
3981 optarg, true);
3982 if (opts == NULL) {
3983 exit(1);
3985 break;
3986 case QEMU_OPTION_preconfig:
3987 preconfig_exit_requested = false;
3988 preconfig_requested = true;
3989 break;
3990 case QEMU_OPTION_enable_kvm:
3991 olist = qemu_find_opts("machine");
3992 qemu_opts_parse_noisily(olist, "accel=kvm", false);
3993 break;
3994 case QEMU_OPTION_M:
3995 case QEMU_OPTION_machine:
3996 olist = qemu_find_opts("machine");
3997 opts = qemu_opts_parse_noisily(olist, optarg, true);
3998 if (!opts) {
3999 exit(1);
4001 break;
4002 case QEMU_OPTION_accel:
4003 accel_opts = qemu_opts_parse_noisily(qemu_find_opts("accel"),
4004 optarg, true);
4005 optarg = qemu_opt_get(accel_opts, "accel");
4006 if (!optarg || is_help_option(optarg)) {
4007 printf("Accelerators supported in QEMU binary:\n");
4008 GSList *el, *accel_list = object_class_get_list(TYPE_ACCEL,
4009 false);
4010 for (el = accel_list; el; el = el->next) {
4011 gchar *typename = g_strdup(object_class_get_name(
4012 OBJECT_CLASS(el->data)));
4013 /* omit qtest which is used for tests only */
4014 if (g_strcmp0(typename, ACCEL_CLASS_NAME("qtest")) &&
4015 g_str_has_suffix(typename, ACCEL_CLASS_SUFFIX)) {
4016 gchar **optname = g_strsplit(typename,
4017 ACCEL_CLASS_SUFFIX, 0);
4018 printf("%s\n", optname[0]);
4019 g_strfreev(optname);
4021 g_free(typename);
4023 g_slist_free(accel_list);
4024 exit(0);
4026 break;
4027 case QEMU_OPTION_usb:
4028 olist = qemu_find_opts("machine");
4029 qemu_opts_parse_noisily(olist, "usb=on", false);
4030 break;
4031 case QEMU_OPTION_usbdevice:
4032 error_report("'-usbdevice' is deprecated, please use "
4033 "'-device usb-...' instead");
4034 olist = qemu_find_opts("machine");
4035 qemu_opts_parse_noisily(olist, "usb=on", false);
4036 add_device_config(DEV_USB, optarg);
4037 break;
4038 case QEMU_OPTION_device:
4039 if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
4040 optarg, true)) {
4041 exit(1);
4043 break;
4044 case QEMU_OPTION_smp:
4045 if (!qemu_opts_parse_noisily(qemu_find_opts("smp-opts"),
4046 optarg, true)) {
4047 exit(1);
4049 break;
4050 case QEMU_OPTION_vnc:
4051 vnc_parse(optarg, &error_fatal);
4052 break;
4053 case QEMU_OPTION_no_acpi:
4054 olist = qemu_find_opts("machine");
4055 qemu_opts_parse_noisily(olist, "acpi=off", false);
4056 break;
4057 case QEMU_OPTION_no_hpet:
4058 olist = qemu_find_opts("machine");
4059 qemu_opts_parse_noisily(olist, "hpet=off", false);
4060 break;
4061 case QEMU_OPTION_no_reboot:
4062 no_reboot = 1;
4063 break;
4064 case QEMU_OPTION_no_shutdown:
4065 no_shutdown = 1;
4066 break;
4067 case QEMU_OPTION_show_cursor:
4068 warn_report("The -show-cursor option is deprecated. Please "
4069 "add show-cursor=on to your -display options.");
4070 warn_report("When using the default display you can use "
4071 "-display default,show-cursor=on");
4072 dpy.has_show_cursor = true;
4073 dpy.show_cursor = true;
4074 break;
4075 case QEMU_OPTION_uuid:
4076 if (qemu_uuid_parse(optarg, &qemu_uuid) < 0) {
4077 error_report("failed to parse UUID string: wrong format");
4078 exit(1);
4080 qemu_uuid_set = true;
4081 break;
4082 case QEMU_OPTION_option_rom:
4083 if (nb_option_roms >= MAX_OPTION_ROMS) {
4084 error_report("too many option ROMs");
4085 exit(1);
4087 opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
4088 optarg, true);
4089 if (!opts) {
4090 exit(1);
4092 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
4093 option_rom[nb_option_roms].bootindex =
4094 qemu_opt_get_number(opts, "bootindex", -1);
4095 if (!option_rom[nb_option_roms].name) {
4096 error_report("Option ROM file is not specified");
4097 exit(1);
4099 nb_option_roms++;
4100 break;
4101 case QEMU_OPTION_semihosting:
4102 qemu_semihosting_enable();
4103 break;
4104 case QEMU_OPTION_semihosting_config:
4105 if (qemu_semihosting_config_options(optarg) != 0) {
4106 exit(1);
4108 break;
4109 case QEMU_OPTION_name:
4110 opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
4111 optarg, true);
4112 if (!opts) {
4113 exit(1);
4115 /* Capture guest name if -msg guest-name is used later */
4116 error_guest_name = qemu_opt_get(opts, "guest");
4117 break;
4118 case QEMU_OPTION_prom_env:
4119 if (nb_prom_envs >= MAX_PROM_ENVS) {
4120 error_report("too many prom variables");
4121 exit(1);
4123 prom_envs[nb_prom_envs] = optarg;
4124 nb_prom_envs++;
4125 break;
4126 case QEMU_OPTION_old_param:
4127 old_param = 1;
4128 break;
4129 case QEMU_OPTION_rtc:
4130 opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
4131 false);
4132 if (!opts) {
4133 exit(1);
4135 break;
4136 case QEMU_OPTION_tb_size:
4137 #ifndef CONFIG_TCG
4138 error_report("TCG is disabled");
4139 exit(1);
4140 #endif
4141 warn_report("The -tb-size option is deprecated, use -accel tcg,tb-size instead");
4142 object_register_sugar_prop(ACCEL_CLASS_NAME("tcg"), "tb-size", optarg);
4143 break;
4144 case QEMU_OPTION_icount:
4145 icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
4146 optarg, true);
4147 if (!icount_opts) {
4148 exit(1);
4150 break;
4151 case QEMU_OPTION_incoming:
4152 if (!incoming) {
4153 runstate_set(RUN_STATE_INMIGRATE);
4155 incoming = optarg;
4156 break;
4157 case QEMU_OPTION_only_migratable:
4158 only_migratable = 1;
4159 break;
4160 case QEMU_OPTION_nodefaults:
4161 has_defaults = 0;
4162 break;
4163 case QEMU_OPTION_xen_domid:
4164 if (!(xen_available())) {
4165 error_report("Option not supported for this target");
4166 exit(1);
4168 xen_domid = atoi(optarg);
4169 break;
4170 case QEMU_OPTION_xen_attach:
4171 if (!(xen_available())) {
4172 error_report("Option not supported for this target");
4173 exit(1);
4175 xen_mode = XEN_ATTACH;
4176 break;
4177 case QEMU_OPTION_xen_domid_restrict:
4178 if (!(xen_available())) {
4179 error_report("Option not supported for this target");
4180 exit(1);
4182 xen_domid_restrict = true;
4183 break;
4184 case QEMU_OPTION_trace:
4185 trace_opt_parse(optarg);
4186 break;
4187 case QEMU_OPTION_plugin:
4188 qemu_plugin_opt_parse(optarg, &plugin_list);
4189 break;
4190 case QEMU_OPTION_readconfig:
4192 int ret = qemu_read_config_file(optarg);
4193 if (ret < 0) {
4194 error_report("read config %s: %s", optarg,
4195 strerror(-ret));
4196 exit(1);
4198 break;
4200 case QEMU_OPTION_spice:
4201 olist = qemu_find_opts_err("spice", NULL);
4202 if (!olist) {
4203 ui_module_load_one("spice-core");
4204 olist = qemu_find_opts("spice");
4206 if (!olist) {
4207 error_report("spice support is disabled");
4208 exit(1);
4210 opts = qemu_opts_parse_noisily(olist, optarg, false);
4211 if (!opts) {
4212 exit(1);
4214 display_remote++;
4215 break;
4216 case QEMU_OPTION_writeconfig:
4218 FILE *fp;
4219 if (strcmp(optarg, "-") == 0) {
4220 fp = stdout;
4221 } else {
4222 fp = fopen(optarg, "w");
4223 if (fp == NULL) {
4224 error_report("open %s: %s", optarg,
4225 strerror(errno));
4226 exit(1);
4229 qemu_config_write(fp);
4230 if (fp != stdout) {
4231 fclose(fp);
4233 break;
4235 case QEMU_OPTION_qtest:
4236 qtest_chrdev = optarg;
4237 break;
4238 case QEMU_OPTION_qtest_log:
4239 qtest_log = optarg;
4240 break;
4241 case QEMU_OPTION_sandbox:
4242 olist = qemu_find_opts("sandbox");
4243 if (!olist) {
4244 #ifndef CONFIG_SECCOMP
4245 error_report("-sandbox support is not enabled "
4246 "in this QEMU binary");
4247 #endif
4248 exit(1);
4251 opts = qemu_opts_parse_noisily(olist, optarg, true);
4252 if (!opts) {
4253 exit(1);
4255 break;
4256 case QEMU_OPTION_add_fd:
4257 #ifndef _WIN32
4258 opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
4259 optarg, false);
4260 if (!opts) {
4261 exit(1);
4263 #else
4264 error_report("File descriptor passing is disabled on this "
4265 "platform");
4266 exit(1);
4267 #endif
4268 break;
4269 case QEMU_OPTION_object:
4270 opts = qemu_opts_parse_noisily(qemu_find_opts("object"),
4271 optarg, true);
4272 if (!opts) {
4273 exit(1);
4275 break;
4276 case QEMU_OPTION_realtime:
4277 warn_report("'-realtime mlock=...' is deprecated, please use "
4278 "'-overcommit mem-lock=...' instead");
4279 opts = qemu_opts_parse_noisily(qemu_find_opts("realtime"),
4280 optarg, false);
4281 if (!opts) {
4282 exit(1);
4284 /* Don't override the -overcommit option if set */
4285 enable_mlock = enable_mlock ||
4286 qemu_opt_get_bool(opts, "mlock", true);
4287 break;
4288 case QEMU_OPTION_overcommit:
4289 opts = qemu_opts_parse_noisily(qemu_find_opts("overcommit"),
4290 optarg, false);
4291 if (!opts) {
4292 exit(1);
4294 /* Don't override the -realtime option if set */
4295 enable_mlock = enable_mlock ||
4296 qemu_opt_get_bool(opts, "mem-lock", false);
4297 enable_cpu_pm = qemu_opt_get_bool(opts, "cpu-pm", false);
4298 break;
4299 case QEMU_OPTION_msg:
4300 opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
4301 false);
4302 if (!opts) {
4303 exit(1);
4305 configure_msg(opts);
4306 break;
4307 case QEMU_OPTION_dump_vmstate:
4308 if (vmstate_dump_file) {
4309 error_report("only one '-dump-vmstate' "
4310 "option may be given");
4311 exit(1);
4313 vmstate_dump_file = fopen(optarg, "w");
4314 if (vmstate_dump_file == NULL) {
4315 error_report("open %s: %s", optarg, strerror(errno));
4316 exit(1);
4318 break;
4319 case QEMU_OPTION_enable_sync_profile:
4320 qsp_enable();
4321 break;
4322 case QEMU_OPTION_nouserconfig:
4323 /* Nothing to be parsed here. Especially, do not error out below. */
4324 break;
4325 default:
4326 if (os_parse_cmd_args(popt->index, optarg)) {
4327 error_report("Option not supported in this build");
4328 exit(1);
4334 * Clear error location left behind by the loop.
4335 * Best done right after the loop. Do not insert code here!
4337 loc_set_none();
4339 qemu_validate_options();
4340 qemu_process_sugar_options();
4343 * These options affect everything else and should be processed
4344 * before daemonizing.
4346 qemu_process_early_options();
4348 qemu_process_help_options();
4349 qemu_maybe_daemonize(pid_file);
4351 qemu_init_main_loop(&error_fatal);
4352 cpu_timers_init();
4354 user_register_global_props();
4355 replay_configure(icount_opts);
4357 configure_rtc(qemu_find_opts_singleton("rtc"));
4359 qemu_create_machine(select_machine());
4361 qemu_disable_default_devices();
4362 qemu_create_default_devices();
4363 qemu_create_early_backends();
4365 qemu_apply_machine_options();
4368 * Note: uses machine properties such as kernel-irqchip, must run
4369 * after machine_set_property().
4371 configure_accelerators(argv[0]);
4374 * Beware, QOM objects created before this point miss global and
4375 * compat properties.
4377 * Global properties get set up by qdev_prop_register_global(),
4378 * called from user_register_global_props(), and certain option
4379 * desugaring. Also in CPU feature desugaring (buried in
4380 * parse_cpu_option()), which happens below this point, but may
4381 * only target the CPU type, which can only be created after
4382 * parse_cpu_option() returned the type.
4384 * Machine compat properties: object_set_machine_compat_props().
4385 * Accelerator compat props: object_set_accelerator_compat_props(),
4386 * called from configure_accelerator().
4389 machine_class = MACHINE_GET_CLASS(current_machine);
4390 if (!qtest_enabled() && machine_class->deprecation_reason) {
4391 error_report("Machine type '%s' is deprecated: %s",
4392 machine_class->name, machine_class->deprecation_reason);
4396 * Note: creates a QOM object, must run only after global and
4397 * compat properties have been set up.
4399 migration_object_init();
4401 qemu_create_late_backends();
4403 /* parse features once if machine provides default cpu_type */
4404 current_machine->cpu_type = machine_class->default_cpu_type;
4405 if (cpu_option) {
4406 current_machine->cpu_type = parse_cpu_option(cpu_option);
4409 qemu_resolve_machine_memdev();
4410 parse_numa_opts(current_machine);
4412 if (preconfig_requested) {
4413 qemu_init_displays();
4416 /* do monitor/qmp handling at preconfig state if requested */
4417 qemu_main_loop();
4419 qemu_init_board();
4421 qemu_create_cli_devices();
4423 /* initialize displays after all errors have been reported */
4424 if (!preconfig_requested) {
4425 qemu_init_displays();
4427 qemu_machine_creation_done();
4429 if (loadvm) {
4430 Error *local_err = NULL;
4431 if (load_snapshot(loadvm, &local_err) < 0) {
4432 error_report_err(local_err);
4433 autostart = 0;
4434 exit(1);
4437 if (replay_mode != REPLAY_MODE_NONE) {
4438 replay_vmstate_init();
4441 if (vmstate_dump_file) {
4442 /* dump and exit */
4443 dump_vmstate_json_to_file(vmstate_dump_file);
4444 exit(0);
4446 if (incoming) {
4447 Error *local_err = NULL;
4448 if (strcmp(incoming, "defer") != 0) {
4449 qmp_migrate_incoming(incoming, &local_err);
4450 if (local_err) {
4451 error_reportf_err(local_err, "-incoming %s: ", incoming);
4452 exit(1);
4455 } else if (autostart) {
4456 qmp_cont(NULL);
4459 accel_setup_post(current_machine);
4460 os_setup_post();
4462 return;
4465 void qemu_cleanup(void)
4467 gdbserver_cleanup();
4470 * cleaning up the migration object cancels any existing migration
4471 * try to do this early so that it also stops using devices.
4473 migration_shutdown();
4476 * We must cancel all block jobs while the block layer is drained,
4477 * or cancelling will be affected by throttling and thus may block
4478 * for an extended period of time.
4479 * vm_shutdown() will bdrv_drain_all(), so we may as well include
4480 * it in the drained section.
4481 * We do not need to end this section, because we do not want any
4482 * requests happening from here on anyway.
4484 bdrv_drain_all_begin();
4486 /* No more vcpu or device emulation activity beyond this point */
4487 vm_shutdown();
4488 replay_finish();
4490 job_cancel_sync_all();
4491 bdrv_close_all();
4493 res_free();
4495 /* vhost-user must be cleaned up before chardevs. */
4496 tpm_cleanup();
4497 net_cleanup();
4498 audio_cleanup();
4499 monitor_cleanup();
4500 qemu_chr_cleanup();
4501 user_creatable_cleanup();
4502 /* TODO: unref root container, check all devices are ok */