xref: /openbmc/qemu/system/vl.c (revision 8a2f1f921cc84cae3aa54c29e24e8c1defc9ef34)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qemu/help-texts.h"
27 #include "qemu/datadir.h"
28 #include "qemu/units.h"
29 #include "exec/cpu-common.h"
30 #include "exec/page-vary.h"
31 #include "hw/qdev-properties.h"
32 #include "qapi/compat-policy.h"
33 #include "qapi/error.h"
34 #include "qobject/qdict.h"
35 #include "qobject/qstring.h"
36 #include "qobject/qjson.h"
37 #include "qemu-version.h"
38 #include "qemu/cutils.h"
39 #include "qemu/help_option.h"
40 #include "qemu/hw-version.h"
41 #include "qemu/uuid.h"
42 #include "system/reset.h"
43 #include "system/runstate.h"
44 #include "system/runstate-action.h"
45 #include "system/seccomp.h"
46 #include "system/tcg.h"
47 #include "system/xen.h"
48 
49 #include "qemu/error-report.h"
50 #include "qemu/sockets.h"
51 #include "qemu/accel.h"
52 #include "qemu/async-teardown.h"
53 #include "hw/usb.h"
54 #include "hw/isa/isa.h"
55 #include "hw/scsi/scsi.h"
56 #include "hw/display/vga.h"
57 #include "hw/firmware/smbios.h"
58 #include "hw/acpi/acpi.h"
59 #include "hw/xen/xen.h"
60 #include "hw/loader.h"
61 #include "monitor/qdev.h"
62 #include "net/net.h"
63 #include "net/slirp.h"
64 #include "monitor/monitor.h"
65 #include "ui/console.h"
66 #include "ui/input.h"
67 #include "system/system.h"
68 #include "system/numa.h"
69 #include "system/hostmem.h"
70 #include "exec/gdbstub.h"
71 #include "gdbstub/enums.h"
72 #include "qemu/timer.h"
73 #include "chardev/char.h"
74 #include "qemu/bitmap.h"
75 #include "qemu/log.h"
76 #include "system/blockdev.h"
77 #include "hw/block/block.h"
78 #include "hw/i386/x86.h"
79 #include "hw/i386/pc.h"
80 #include "migration/cpr.h"
81 #include "migration/misc.h"
82 #include "migration/snapshot.h"
83 #include "system/tpm.h"
84 #include "system/dma.h"
85 #include "hw/audio/soundhw.h"
86 #include "audio/audio.h"
87 #include "system/cpus.h"
88 #include "system/cpu-timers.h"
89 #include "migration/colo.h"
90 #include "migration/postcopy-ram.h"
91 #include "system/kvm.h"
92 #include "qapi/qobject-input-visitor.h"
93 #include "qemu/option.h"
94 #include "qemu/config-file.h"
95 #include "qemu/main-loop.h"
96 #ifdef CONFIG_VIRTFS
97 #include "fsdev/qemu-fsdev.h"
98 #endif
99 #include "system/qtest.h"
100 #ifdef CONFIG_TCG
101 #include "tcg/perf.h"
102 #endif
103 
104 #include "disas/disas.h"
105 
106 #include "trace.h"
107 #include "trace/control.h"
108 #include "qemu/plugin.h"
109 #include "qemu/queue.h"
110 #include "system/arch_init.h"
111 #include "system/confidential-guest-support.h"
112 
113 #include "ui/qemu-spice.h"
114 #include "qapi/string-input-visitor.h"
115 #include "qapi/opts-visitor.h"
116 #include "qapi/clone-visitor.h"
117 #include "qom/object_interfaces.h"
118 #include "semihosting/semihost.h"
119 #include "crypto/init.h"
120 #include "system/replay.h"
121 #include "qapi/qapi-events-run-state.h"
122 #include "qapi/qapi-types-audio.h"
123 #include "qapi/qapi-visit-audio.h"
124 #include "qapi/qapi-visit-block-core.h"
125 #include "qapi/qapi-visit-compat.h"
126 #include "qapi/qapi-visit-machine.h"
127 #include "qapi/qapi-visit-migration.h"
128 #include "qapi/qapi-visit-ui.h"
129 #include "qapi/qapi-commands-block-core.h"
130 #include "qapi/qapi-commands-migration.h"
131 #include "qapi/qapi-commands-misc.h"
132 #include "qapi/qapi-visit-qom.h"
133 #include "qapi/qapi-commands-ui.h"
134 #include "block/qdict.h"
135 #include "qapi/qmp/qerror.h"
136 #include "system/iothread.h"
137 #include "qemu/guest-random.h"
138 #include "qemu/keyval.h"
139 
140 #define MAX_VIRTIO_CONSOLES 1
141 
142 typedef struct BlockdevOptionsQueueEntry {
143     BlockdevOptions *bdo;
144     Location loc;
145     QSIMPLEQ_ENTRY(BlockdevOptionsQueueEntry) entry;
146 } BlockdevOptionsQueueEntry;
147 
148 typedef QSIMPLEQ_HEAD(, BlockdevOptionsQueueEntry) BlockdevOptionsQueue;
149 
150 typedef struct ObjectOption {
151     ObjectOptions *opts;
152     QTAILQ_ENTRY(ObjectOption) next;
153 } ObjectOption;
154 
155 typedef struct DeviceOption {
156     QDict *opts;
157     Location loc;
158     QTAILQ_ENTRY(DeviceOption) next;
159 } DeviceOption;
160 
161 static const char *cpu_option;
162 static const char *mem_path;
163 static const char *incoming;
164 static const char *incoming_str[MIGRATION_CHANNEL_TYPE__MAX];
165 static MigrationChannel *incoming_channels[MIGRATION_CHANNEL_TYPE__MAX];
166 static const char *loadvm;
167 static const char *accelerators;
168 static bool have_custom_ram_size;
169 static const char *ram_memdev_id;
170 static QDict *machine_opts_dict;
171 static QTAILQ_HEAD(, ObjectOption) object_opts = QTAILQ_HEAD_INITIALIZER(object_opts);
172 static QTAILQ_HEAD(, DeviceOption) device_opts = QTAILQ_HEAD_INITIALIZER(device_opts);
173 static int display_remote;
174 static int snapshot;
175 static bool preconfig_requested;
176 static QemuPluginList plugin_list = QTAILQ_HEAD_INITIALIZER(plugin_list);
177 static BlockdevOptionsQueue bdo_queue = QSIMPLEQ_HEAD_INITIALIZER(bdo_queue);
178 static bool nographic = false;
179 static int mem_prealloc; /* force preallocation of physical target memory */
180 static const char *vga_model = NULL;
181 static DisplayOptions dpy;
182 static int num_serial_hds;
183 static Chardev **serial_hds;
184 static const char *log_mask;
185 static const char *log_file;
186 static bool list_data_dirs;
187 static const char *qtest_chrdev;
188 static const char *qtest_log;
189 
190 static int has_defaults = 1;
191 static int default_audio = 1;
192 static int default_serial = 1;
193 static int default_parallel = 1;
194 static int default_monitor = 1;
195 static int default_floppy = 1;
196 static int default_cdrom = 1;
197 static int default_sdcard = 1;
198 static int default_vga = 1;
199 static int default_net = 1;
200 
201 static const struct {
202     const char *driver;
203     int *flag;
204 } default_list[] = {
205     { .driver = "xen-console",          .flag = &default_serial    },
206     { .driver = "isa-serial",           .flag = &default_serial    },
207     { .driver = "isa-parallel",         .flag = &default_parallel  },
208     { .driver = "isa-fdc",              .flag = &default_floppy    },
209     { .driver = "floppy",               .flag = &default_floppy    },
210     { .driver = "ide-cd",               .flag = &default_cdrom     },
211     { .driver = "ide-hd",               .flag = &default_cdrom     },
212     { .driver = "scsi-cd",              .flag = &default_cdrom     },
213     { .driver = "scsi-hd",              .flag = &default_cdrom     },
214     { .driver = "VGA",                  .flag = &default_vga       },
215     { .driver = "isa-vga",              .flag = &default_vga       },
216     { .driver = "cirrus-vga",           .flag = &default_vga       },
217     { .driver = "isa-cirrus-vga",       .flag = &default_vga       },
218     { .driver = "vmware-svga",          .flag = &default_vga       },
219     { .driver = "qxl-vga",              .flag = &default_vga       },
220     { .driver = "virtio-vga",           .flag = &default_vga       },
221     { .driver = "ati-vga",              .flag = &default_vga       },
222     { .driver = "vhost-user-vga",       .flag = &default_vga       },
223     { .driver = "virtio-vga-gl",        .flag = &default_vga       },
224     { .driver = "virtio-vga-rutabaga",  .flag = &default_vga       },
225 };
226 
227 static QemuOptsList qemu_rtc_opts = {
228     .name = "rtc",
229     .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
230     .merge_lists = true,
231     .desc = {
232         {
233             .name = "base",
234             .type = QEMU_OPT_STRING,
235         },{
236             .name = "clock",
237             .type = QEMU_OPT_STRING,
238         },{
239             .name = "driftfix",
240             .type = QEMU_OPT_STRING,
241         },
242         { /* end of list */ }
243     },
244 };
245 
246 static QemuOptsList qemu_option_rom_opts = {
247     .name = "option-rom",
248     .implied_opt_name = "romfile",
249     .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
250     .desc = {
251         {
252             .name = "bootindex",
253             .type = QEMU_OPT_NUMBER,
254         }, {
255             .name = "romfile",
256             .type = QEMU_OPT_STRING,
257         },
258         { /* end of list */ }
259     },
260 };
261 
262 static QemuOptsList qemu_accel_opts = {
263     .name = "accel",
264     .implied_opt_name = "accel",
265     .head = QTAILQ_HEAD_INITIALIZER(qemu_accel_opts.head),
266     .desc = {
267         /*
268          * no elements => accept any
269          * sanity checking will happen later
270          * when setting accelerator properties
271          */
272         { }
273     },
274 };
275 
276 static QemuOptsList qemu_boot_opts = {
277     .name = "boot-opts",
278     .implied_opt_name = "order",
279     .merge_lists = true,
280     .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
281     .desc = {
282         {
283             .name = "order",
284             .type = QEMU_OPT_STRING,
285         }, {
286             .name = "once",
287             .type = QEMU_OPT_STRING,
288         }, {
289             .name = "menu",
290             .type = QEMU_OPT_BOOL,
291         }, {
292             .name = "splash",
293             .type = QEMU_OPT_STRING,
294         }, {
295             .name = "splash-time",
296             .type = QEMU_OPT_NUMBER,
297         }, {
298             .name = "reboot-timeout",
299             .type = QEMU_OPT_NUMBER,
300         }, {
301             .name = "strict",
302             .type = QEMU_OPT_BOOL,
303         },
304         { /*End of list */ }
305     },
306 };
307 
308 static QemuOptsList qemu_add_fd_opts = {
309     .name = "add-fd",
310     .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
311     .desc = {
312         {
313             .name = "fd",
314             .type = QEMU_OPT_NUMBER,
315             .help = "file descriptor of which a duplicate is added to fd set",
316         },{
317             .name = "set",
318             .type = QEMU_OPT_NUMBER,
319             .help = "ID of the fd set to add fd to",
320         },{
321             .name = "opaque",
322             .type = QEMU_OPT_STRING,
323             .help = "free-form string used to describe fd",
324         },
325         { /* end of list */ }
326     },
327 };
328 
329 static QemuOptsList qemu_object_opts = {
330     .name = "object",
331     .implied_opt_name = "qom-type",
332     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
333     .desc = {
334         { }
335     },
336 };
337 
338 static QemuOptsList qemu_tpmdev_opts = {
339     .name = "tpmdev",
340     .implied_opt_name = "type",
341     .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
342     .desc = {
343         /* options are defined in the TPM backends */
344         { /* end of list */ }
345     },
346 };
347 
348 static QemuOptsList qemu_overcommit_opts = {
349     .name = "overcommit",
350     .head = QTAILQ_HEAD_INITIALIZER(qemu_overcommit_opts.head),
351     .desc = {
352         {
353             .name = "mem-lock",
354             .type = QEMU_OPT_BOOL,
355         },
356         {
357             .name = "cpu-pm",
358             .type = QEMU_OPT_BOOL,
359         },
360         { /* end of list */ }
361     },
362 };
363 
364 static QemuOptsList qemu_msg_opts = {
365     .name = "msg",
366     .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
367     .desc = {
368         {
369             .name = "timestamp",
370             .type = QEMU_OPT_BOOL,
371         },
372         {
373             .name = "guest-name",
374             .type = QEMU_OPT_BOOL,
375             .help = "Prepends guest name for error messages but only if "
376                     "-name guest is set otherwise option is ignored\n",
377         },
378         { /* end of list */ }
379     },
380 };
381 
382 static QemuOptsList qemu_name_opts = {
383     .name = "name",
384     .implied_opt_name = "guest",
385     .merge_lists = true,
386     .head = QTAILQ_HEAD_INITIALIZER(qemu_name_opts.head),
387     .desc = {
388         {
389             .name = "guest",
390             .type = QEMU_OPT_STRING,
391             .help = "Sets the name of the guest.\n"
392                     "This name will be displayed in the SDL window caption.\n"
393                     "The name will also be used for the VNC server",
394         }, {
395             .name = "process",
396             .type = QEMU_OPT_STRING,
397             .help = "Sets the name of the QEMU process, as shown in top etc",
398         }, {
399             .name = "debug-threads",
400             .type = QEMU_OPT_BOOL,
401             .help = "When enabled, name the individual threads; defaults off.\n"
402                     "NOTE: The thread names are for debugging and not a\n"
403                     "stable API.",
404         },
405         { /* End of list */ }
406     },
407 };
408 
409 static QemuOptsList qemu_mem_opts = {
410     .name = "memory",
411     .implied_opt_name = "size",
412     .head = QTAILQ_HEAD_INITIALIZER(qemu_mem_opts.head),
413     .merge_lists = true,
414     .desc = {
415         {
416             .name = "size",
417             .type = QEMU_OPT_SIZE,
418         },
419         {
420             .name = "slots",
421             .type = QEMU_OPT_NUMBER,
422         },
423         {
424             .name = "maxmem",
425             .type = QEMU_OPT_SIZE,
426         },
427         { /* end of list */ }
428     },
429 };
430 
431 static QemuOptsList qemu_icount_opts = {
432     .name = "icount",
433     .implied_opt_name = "shift",
434     .merge_lists = true,
435     .head = QTAILQ_HEAD_INITIALIZER(qemu_icount_opts.head),
436     .desc = {
437         {
438             .name = "shift",
439             .type = QEMU_OPT_STRING,
440         }, {
441             .name = "align",
442             .type = QEMU_OPT_BOOL,
443         }, {
444             .name = "sleep",
445             .type = QEMU_OPT_BOOL,
446         }, {
447             .name = "rr",
448             .type = QEMU_OPT_STRING,
449         }, {
450             .name = "rrfile",
451             .type = QEMU_OPT_STRING,
452         }, {
453             .name = "rrsnapshot",
454             .type = QEMU_OPT_STRING,
455         },
456         { /* end of list */ }
457     },
458 };
459 
460 static QemuOptsList qemu_fw_cfg_opts = {
461     .name = "fw_cfg",
462     .implied_opt_name = "name",
463     .head = QTAILQ_HEAD_INITIALIZER(qemu_fw_cfg_opts.head),
464     .desc = {
465         {
466             .name = "name",
467             .type = QEMU_OPT_STRING,
468             .help = "Sets the fw_cfg name of the blob to be inserted",
469         }, {
470             .name = "file",
471             .type = QEMU_OPT_STRING,
472             .help = "Sets the name of the file from which "
473                     "the fw_cfg blob will be loaded",
474         }, {
475             .name = "string",
476             .type = QEMU_OPT_STRING,
477             .help = "Sets content of the blob to be inserted from a string",
478         }, {
479             .name = "gen_id",
480             .type = QEMU_OPT_STRING,
481             .help = "Sets id of the object generating the fw_cfg blob "
482                     "to be inserted",
483         },
484         { /* end of list */ }
485     },
486 };
487 
488 static QemuOptsList qemu_action_opts = {
489     .name = "action",
490     .merge_lists = true,
491     .head = QTAILQ_HEAD_INITIALIZER(qemu_action_opts.head),
492     .desc = {
493         {
494             .name = "shutdown",
495             .type = QEMU_OPT_STRING,
496         },{
497             .name = "reboot",
498             .type = QEMU_OPT_STRING,
499         },{
500             .name = "panic",
501             .type = QEMU_OPT_STRING,
502         },{
503             .name = "watchdog",
504             .type = QEMU_OPT_STRING,
505         },
506         { /* end of list */ }
507     },
508 };
509 
510 const char *qemu_get_vm_name(void)
511 {
512     return qemu_name;
513 }
514 
515 static void default_driver_disable(const char *driver)
516 {
517     int i;
518 
519     if (!driver) {
520         return;
521     }
522 
523     for (i = 0; i < ARRAY_SIZE(default_list); i++) {
524         if (strcmp(default_list[i].driver, driver) != 0)
525             continue;
526         *(default_list[i].flag) = 0;
527     }
528 }
529 
530 static int default_driver_check(void *opaque, QemuOpts *opts, Error **errp)
531 {
532     const char *driver = qemu_opt_get(opts, "driver");
533 
534     default_driver_disable(driver);
535     return 0;
536 }
537 
538 static void default_driver_check_json(void)
539 {
540     DeviceOption *opt;
541 
542     QTAILQ_FOREACH(opt, &device_opts, next) {
543         const char *driver = qdict_get_try_str(opt->opts, "driver");
544         default_driver_disable(driver);
545     }
546 }
547 
548 static int parse_name(void *opaque, QemuOpts *opts, Error **errp)
549 {
550     const char *proc_name;
551 
552     if (qemu_opt_get(opts, "debug-threads")) {
553         qemu_thread_naming(qemu_opt_get_bool(opts, "debug-threads", false));
554     }
555     qemu_name = qemu_opt_get(opts, "guest");
556 
557     proc_name = qemu_opt_get(opts, "process");
558     if (proc_name) {
559         os_set_proc_name(proc_name);
560     }
561 
562     return 0;
563 }
564 
565 bool defaults_enabled(void)
566 {
567     return has_defaults;
568 }
569 
570 #ifndef _WIN32
571 static int parse_add_fd(void *opaque, QemuOpts *opts, Error **errp)
572 {
573     int fd, dupfd, flags;
574     int64_t fdset_id;
575     const char *fd_opaque = NULL;
576     AddfdInfo *fdinfo;
577 
578     fd = qemu_opt_get_number(opts, "fd", -1);
579     fdset_id = qemu_opt_get_number(opts, "set", -1);
580     fd_opaque = qemu_opt_get(opts, "opaque");
581 
582     if (fd < 0) {
583         error_setg(errp, "fd option is required and must be non-negative");
584         return -1;
585     }
586 
587     if (fd <= STDERR_FILENO) {
588         error_setg(errp, "fd cannot be a standard I/O stream");
589         return -1;
590     }
591 
592     /*
593      * All fds inherited across exec() necessarily have FD_CLOEXEC
594      * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
595      */
596     flags = fcntl(fd, F_GETFD);
597     if (flags == -1 || (flags & FD_CLOEXEC)) {
598         error_setg(errp, "fd is not valid or already in use");
599         return -1;
600     }
601 
602     if (fdset_id < 0) {
603         error_setg(errp, "set option is required and must be non-negative");
604         return -1;
605     }
606 
607 #ifdef F_DUPFD_CLOEXEC
608     dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
609 #else
610     dupfd = dup(fd);
611     if (dupfd != -1) {
612         qemu_set_cloexec(dupfd);
613     }
614 #endif
615     if (dupfd == -1) {
616         error_setg(errp, "error duplicating fd: %s", strerror(errno));
617         return -1;
618     }
619 
620     /* add the duplicate fd, and optionally the opaque string, to the fd set */
621     fdinfo = monitor_fdset_add_fd(dupfd, true, fdset_id, fd_opaque,
622                                   &error_abort);
623     g_free(fdinfo);
624 
625     return 0;
626 }
627 
628 static int cleanup_add_fd(void *opaque, QemuOpts *opts, Error **errp)
629 {
630     int fd;
631 
632     fd = qemu_opt_get_number(opts, "fd", -1);
633     close(fd);
634 
635     return 0;
636 }
637 #endif
638 
639 /***********************************************************/
640 /* QEMU Block devices */
641 
642 #define HD_OPTS "media=disk"
643 #define CDROM_OPTS "media=cdrom"
644 #define FD_OPTS ""
645 #define PFLASH_OPTS ""
646 #define MTD_OPTS ""
647 #define SD_OPTS ""
648 
649 static int drive_init_func(void *opaque, QemuOpts *opts, Error **errp)
650 {
651     BlockInterfaceType *block_default_type = opaque;
652 
653     return drive_new(opts, *block_default_type, errp) == NULL;
654 }
655 
656 static int drive_enable_snapshot(void *opaque, QemuOpts *opts, Error **errp)
657 {
658     if (qemu_opt_get(opts, "snapshot") == NULL) {
659         qemu_opt_set(opts, "snapshot", "on", &error_abort);
660     }
661     return 0;
662 }
663 
664 static void default_drive(int enable, int snapshot, BlockInterfaceType type,
665                           int index, const char *optstr)
666 {
667     QemuOpts *opts;
668     DriveInfo *dinfo;
669 
670     if (!enable || drive_get_by_index(type, index)) {
671         return;
672     }
673 
674     opts = drive_add(type, index, NULL, optstr);
675     if (snapshot) {
676         drive_enable_snapshot(NULL, opts, NULL);
677     }
678 
679     dinfo = drive_new(opts, type, &error_abort);
680     dinfo->is_default = true;
681 
682 }
683 
684 static void configure_blockdev(BlockdevOptionsQueue *bdo_queue,
685                                MachineClass *machine_class, int snapshot)
686 {
687     /*
688      * If the currently selected machine wishes to override the
689      * units-per-bus property of its default HBA interface type, do so
690      * now.
691      */
692     if (machine_class->units_per_default_bus) {
693         override_max_devs(machine_class->block_default_type,
694                           machine_class->units_per_default_bus);
695     }
696 
697     /* open the virtual block devices */
698     while (!QSIMPLEQ_EMPTY(bdo_queue)) {
699         BlockdevOptionsQueueEntry *bdo = QSIMPLEQ_FIRST(bdo_queue);
700 
701         QSIMPLEQ_REMOVE_HEAD(bdo_queue, entry);
702         loc_push_restore(&bdo->loc);
703         qmp_blockdev_add(bdo->bdo, &error_fatal);
704         loc_pop(&bdo->loc);
705         qapi_free_BlockdevOptions(bdo->bdo);
706         g_free(bdo);
707     }
708     if (snapshot) {
709         qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot,
710                           NULL, NULL);
711     }
712     if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
713                           &machine_class->block_default_type, &error_fatal)) {
714         /* We printed help */
715         exit(0);
716     }
717 
718     default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
719                   CDROM_OPTS);
720     default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
721     default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
722 
723 }
724 
725 static QemuOptsList qemu_smp_opts = {
726     .name = "smp-opts",
727     .implied_opt_name = "cpus",
728     .merge_lists = true,
729     .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
730     .desc = {
731         {
732             .name = "cpus",
733             .type = QEMU_OPT_NUMBER,
734         }, {
735             .name = "drawers",
736             .type = QEMU_OPT_NUMBER,
737         }, {
738             .name = "books",
739             .type = QEMU_OPT_NUMBER,
740         }, {
741             .name = "sockets",
742             .type = QEMU_OPT_NUMBER,
743         }, {
744             .name = "dies",
745             .type = QEMU_OPT_NUMBER,
746         }, {
747             .name = "clusters",
748             .type = QEMU_OPT_NUMBER,
749         }, {
750             .name = "modules",
751             .type = QEMU_OPT_NUMBER,
752         }, {
753             .name = "cores",
754             .type = QEMU_OPT_NUMBER,
755         }, {
756             .name = "threads",
757             .type = QEMU_OPT_NUMBER,
758         }, {
759             .name = "maxcpus",
760             .type = QEMU_OPT_NUMBER,
761         },
762         { /*End of list */ }
763     },
764 };
765 
766 #if defined(CONFIG_POSIX)
767 static QemuOptsList qemu_run_with_opts = {
768     .name = "run-with",
769     .head = QTAILQ_HEAD_INITIALIZER(qemu_run_with_opts.head),
770     .desc = {
771 #if defined(CONFIG_LINUX)
772         {
773             .name = "async-teardown",
774             .type = QEMU_OPT_BOOL,
775         },
776 #endif
777         {
778             .name = "chroot",
779             .type = QEMU_OPT_STRING,
780         },
781         {
782             .name = "user",
783             .type = QEMU_OPT_STRING,
784         },
785         { /* end of list */ }
786     },
787 };
788 
789 #define qemu_add_run_with_opts() qemu_add_opts(&qemu_run_with_opts)
790 
791 #else
792 
793 #define qemu_add_run_with_opts()
794 
795 #endif /* CONFIG_POSIX */
796 
797 static void realtime_init(void)
798 {
799     if (enable_mlock) {
800         if (os_mlock() < 0) {
801             error_report("locking memory failed");
802             exit(1);
803         }
804     }
805 }
806 
807 
808 static void configure_msg(QemuOpts *opts)
809 {
810     message_with_timestamp = qemu_opt_get_bool(opts, "timestamp", false);
811     error_with_guestname = qemu_opt_get_bool(opts, "guest-name", false);
812 }
813 
814 
815 /***********************************************************/
816 /* USB devices */
817 
818 static bool usb_parse(const char *cmdline, Error **errp)
819 {
820     g_assert(machine_usb(current_machine));
821 
822     if (!usbdevice_create(cmdline)) {
823         error_setg(errp, "could not add USB device '%s'", cmdline);
824         return false;
825     }
826     return true;
827 }
828 
829 /***********************************************************/
830 /* machine registration */
831 
832 static MachineClass *find_machine(const char *name, GSList *machines)
833 {
834     GSList *el;
835 
836     for (el = machines; el; el = el->next) {
837         MachineClass *mc = el->data;
838 
839         if (!strcmp(mc->name, name) || !g_strcmp0(mc->alias, name)) {
840             return mc;
841         }
842     }
843 
844     return NULL;
845 }
846 
847 static MachineClass *find_default_machine(GSList *machines)
848 {
849     GSList *el;
850     MachineClass *default_machineclass = NULL;
851 
852     for (el = machines; el; el = el->next) {
853         MachineClass *mc = el->data;
854 
855         if (mc->is_default) {
856             assert(default_machineclass == NULL && "Multiple default machines");
857             default_machineclass = mc;
858         }
859     }
860 
861     return default_machineclass;
862 }
863 
864 static void version(void)
865 {
866     printf("QEMU emulator version " QEMU_FULL_VERSION "\n"
867            QEMU_COPYRIGHT "\n");
868 }
869 
870 static void help(int exitcode)
871 {
872     version();
873     printf("usage: %s [options] [disk_image]\n\n"
874            "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
875             g_get_prgname());
876 
877 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)    \
878     if ((arch_mask) & arch_type)                               \
879         fputs(opt_help, stdout);
880 
881 #define ARCHHEADING(text, arch_mask) \
882     if ((arch_mask) & arch_type)    \
883         puts(stringify(text));
884 
885 #define DEFHEADING(text) ARCHHEADING(text, QEMU_ARCH_ALL)
886 
887 #include "qemu-options.def"
888 
889     printf("\nDuring emulation, the following keys are useful:\n"
890            "ctrl-alt-f      toggle full screen\n"
891            "ctrl-alt-n      switch to virtual console 'n'\n"
892            "ctrl-alt-g      toggle mouse and keyboard grab\n"
893            "\n"
894            "When using -nographic, press 'ctrl-a h' to get some help.\n"
895            "\n"
896            QEMU_HELP_BOTTOM "\n");
897 
898     exit(exitcode);
899 }
900 
901 enum {
902 
903 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
904     opt_enum,
905 #define DEFHEADING(text)
906 #define ARCHHEADING(text, arch_mask)
907 
908 #include "qemu-options.def"
909 };
910 
911 #define HAS_ARG 0x0001
912 
913 typedef struct QEMUOption {
914     const char *name;
915     int flags;
916     int index;
917     uint32_t arch_mask;
918 } QEMUOption;
919 
920 static const QEMUOption qemu_options[] = {
921     { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
922 
923 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
924     { option, opt_arg, opt_enum, arch_mask },
925 #define DEFHEADING(text)
926 #define ARCHHEADING(text, arch_mask)
927 
928 #include "qemu-options.def"
929     { /* end of list */ }
930 };
931 
932 typedef struct VGAInterfaceInfo {
933     const char *opt_name;    /* option name */
934     const char *name;        /* human-readable name */
935     /* Class names indicating that support is available.
936      * If no class is specified, the interface is always available */
937     const char *class_names[2];
938 } VGAInterfaceInfo;
939 
940 static const VGAInterfaceInfo vga_interfaces[VGA_TYPE_MAX] = {
941     [VGA_NONE] = {
942         .opt_name = "none",
943         .name = "no graphic card",
944     },
945     [VGA_STD] = {
946         .opt_name = "std",
947         .name = "standard VGA",
948         .class_names = { "VGA", "isa-vga" },
949     },
950     [VGA_CIRRUS] = {
951         .opt_name = "cirrus",
952         .name = "Cirrus VGA",
953         .class_names = { "cirrus-vga", "isa-cirrus-vga" },
954     },
955     [VGA_VMWARE] = {
956         .opt_name = "vmware",
957         .name = "VMWare SVGA",
958         .class_names = { "vmware-svga" },
959     },
960     [VGA_VIRTIO] = {
961         .opt_name = "virtio",
962         .name = "Virtio VGA",
963         .class_names = { "virtio-vga" },
964     },
965     [VGA_QXL] = {
966         .opt_name = "qxl",
967         .name = "QXL VGA",
968         .class_names = { "qxl-vga" },
969     },
970     [VGA_TCX] = {
971         .opt_name = "tcx",
972         .name = "TCX framebuffer",
973         .class_names = { "sun-tcx" },
974     },
975     [VGA_CG3] = {
976         .opt_name = "cg3",
977         .name = "CG3 framebuffer",
978         .class_names = { "cgthree" },
979     },
980 #ifdef CONFIG_XEN_BACKEND
981     [VGA_XENFB] = {
982         .opt_name = "xenfb",
983         .name = "Xen paravirtualized framebuffer",
984     },
985 #endif
986 };
987 
988 static bool vga_interface_available(VGAInterfaceType t)
989 {
990     const VGAInterfaceInfo *ti = &vga_interfaces[t];
991 
992     assert(t < VGA_TYPE_MAX);
993 
994     if (!ti->class_names[0] || module_object_class_by_name(ti->class_names[0])) {
995         return true;
996     }
997 
998     if (ti->class_names[1] && module_object_class_by_name(ti->class_names[1])) {
999         return true;
1000     }
1001 
1002     return false;
1003 }
1004 
1005 static const char *
1006 get_default_vga_model(const MachineClass *machine_class)
1007 {
1008     if (machine_class->default_display) {
1009         for (int t = 0; t < VGA_TYPE_MAX; t++) {
1010             const VGAInterfaceInfo *ti = &vga_interfaces[t];
1011 
1012             if (ti->opt_name && vga_interface_available(t) &&
1013                 g_str_equal(ti->opt_name, machine_class->default_display)) {
1014                 return machine_class->default_display;
1015             }
1016         }
1017 
1018         warn_report_once("Default display '%s' is not available in this binary",
1019                          machine_class->default_display);
1020         return NULL;
1021     } else if (vga_interface_available(VGA_CIRRUS)) {
1022         return "cirrus";
1023     } else if (vga_interface_available(VGA_STD)) {
1024         return "std";
1025     }
1026 
1027     return NULL;
1028 }
1029 
1030 static void select_vgahw(const MachineClass *machine_class, const char *p)
1031 {
1032     const char *opts;
1033     int t;
1034 
1035     if (g_str_equal(p, "help")) {
1036         const char *def = get_default_vga_model(machine_class);
1037 
1038         for (t = 0; t < VGA_TYPE_MAX; t++) {
1039             const VGAInterfaceInfo *ti = &vga_interfaces[t];
1040 
1041             if (vga_interface_available(t) && ti->opt_name) {
1042                 printf("%-20s %s%s\n", ti->opt_name, ti->name ?: "",
1043                         (def && g_str_equal(ti->opt_name, def)) ?
1044                         " (default)" : "");
1045             }
1046         }
1047         exit(0);
1048     }
1049 
1050     assert(vga_interface_type == VGA_NONE);
1051     for (t = 0; t < VGA_TYPE_MAX; t++) {
1052         const VGAInterfaceInfo *ti = &vga_interfaces[t];
1053         if (ti->opt_name && strstart(p, ti->opt_name, &opts)) {
1054             if (!vga_interface_available(t)) {
1055                 error_report("%s not available", ti->name);
1056                 exit(1);
1057             }
1058             vga_interface_type = t;
1059             break;
1060         }
1061     }
1062     if (t == VGA_TYPE_MAX) {
1063     invalid_vga:
1064         error_report("unknown vga type: %s", p);
1065         exit(1);
1066     }
1067     while (*opts) {
1068         const char *nextopt;
1069 
1070         if (strstart(opts, ",retrace=", &nextopt)) {
1071             opts = nextopt;
1072             if (strstart(opts, "dumb", &nextopt))
1073                 vga_retrace_method = VGA_RETRACE_DUMB;
1074             else if (strstart(opts, "precise", &nextopt))
1075                 vga_retrace_method = VGA_RETRACE_PRECISE;
1076             else goto invalid_vga;
1077         } else goto invalid_vga;
1078         opts = nextopt;
1079     }
1080 }
1081 
1082 static void parse_display_qapi(const char *str)
1083 {
1084     DisplayOptions *opts;
1085     Visitor *v;
1086 
1087     v = qobject_input_visitor_new_str(str, "type", &error_fatal);
1088 
1089     visit_type_DisplayOptions(v, NULL, &opts, &error_fatal);
1090     QAPI_CLONE_MEMBERS(DisplayOptions, &dpy, opts);
1091 
1092     qapi_free_DisplayOptions(opts);
1093     visit_free(v);
1094 }
1095 
1096 DisplayOptions *qmp_query_display_options(Error **errp)
1097 {
1098     return QAPI_CLONE(DisplayOptions, &dpy);
1099 }
1100 
1101 static void parse_display(const char *p)
1102 {
1103     if (is_help_option(p)) {
1104         qemu_display_help();
1105         exit(0);
1106     }
1107 
1108 #ifdef CONFIG_VNC
1109     const char *opts;
1110 
1111     if (strstart(p, "vnc", &opts)) {
1112         /*
1113          * vnc isn't a (local) DisplayType but a protocol for remote
1114          * display access.
1115          */
1116         if (*opts == '=') {
1117             vnc_parse(opts + 1);
1118             display_remote++;
1119         } else {
1120             error_report("VNC requires a display argument vnc=<display>");
1121             exit(1);
1122         }
1123         return;
1124     }
1125 #endif
1126 
1127     parse_display_qapi(p);
1128 }
1129 
1130 static inline bool nonempty_str(const char *str)
1131 {
1132     return str && *str;
1133 }
1134 
1135 static int parse_fw_cfg(void *opaque, QemuOpts *opts, Error **errp)
1136 {
1137     gchar *buf;
1138     size_t size;
1139     const char *name, *file, *str, *gen_id;
1140     FWCfgState *fw_cfg = (FWCfgState *) opaque;
1141 
1142     if (fw_cfg == NULL) {
1143         error_setg(errp, "fw_cfg device not available");
1144         return -1;
1145     }
1146     name = qemu_opt_get(opts, "name");
1147     file = qemu_opt_get(opts, "file");
1148     str = qemu_opt_get(opts, "string");
1149     gen_id = qemu_opt_get(opts, "gen_id");
1150 
1151     /* we need the name, and exactly one of: file, content string, gen_id */
1152     if (!nonempty_str(name) ||
1153         nonempty_str(file) + nonempty_str(str) + nonempty_str(gen_id) != 1) {
1154         error_setg(errp, "name, plus exactly one of file,"
1155                          " string and gen_id, are needed");
1156         return -1;
1157     }
1158     if (strlen(name) > FW_CFG_MAX_FILE_PATH - 1) {
1159         error_setg(errp, "name too long (max. %d char)",
1160                    FW_CFG_MAX_FILE_PATH - 1);
1161         return -1;
1162     }
1163     if (nonempty_str(gen_id)) {
1164         /*
1165          * In this particular case where the content is populated
1166          * internally, the "etc/" namespace protection is relaxed,
1167          * so do not emit a warning.
1168          */
1169     } else if (strncmp(name, "opt/", 4) != 0) {
1170         warn_report("externally provided fw_cfg item names "
1171                     "should be prefixed with \"opt/\"");
1172     }
1173     if (nonempty_str(str)) {
1174         size = strlen(str); /* NUL terminator NOT included in fw_cfg blob */
1175         buf = g_memdup(str, size);
1176     } else if (nonempty_str(gen_id)) {
1177         if (!fw_cfg_add_file_from_generator(fw_cfg, object_get_objects_root(),
1178                                             gen_id, name, errp)) {
1179             return -1;
1180         }
1181         return 0;
1182     } else {
1183         GError *err = NULL;
1184         if (!g_file_get_contents(file, &buf, &size, &err)) {
1185             error_setg(errp, "can't load %s: %s", file, err->message);
1186             g_error_free(err);
1187             return -1;
1188         }
1189     }
1190     /* For legacy, keep user files in a specific global order. */
1191     fw_cfg_set_order_override(fw_cfg, FW_CFG_ORDER_OVERRIDE_USER);
1192     fw_cfg_add_file(fw_cfg, name, buf, size);
1193     fw_cfg_reset_order_override(fw_cfg);
1194     return 0;
1195 }
1196 
1197 static int device_help_func(void *opaque, QemuOpts *opts, Error **errp)
1198 {
1199     return qdev_device_help(opts);
1200 }
1201 
1202 static int device_init_func(void *opaque, QemuOpts *opts, Error **errp)
1203 {
1204     DeviceState *dev;
1205 
1206     dev = qdev_device_add(opts, errp);
1207     if (!dev && *errp) {
1208         error_report_err(*errp);
1209         return -1;
1210     } else if (dev) {
1211         object_unref(OBJECT(dev));
1212     }
1213     return 0;
1214 }
1215 
1216 static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)
1217 {
1218     Error *local_err = NULL;
1219 
1220     if (!qemu_chr_new_from_opts(opts, NULL, &local_err)) {
1221         if (local_err) {
1222             error_propagate(errp, local_err);
1223             return -1;
1224         }
1225         exit(0);
1226     }
1227     return 0;
1228 }
1229 
1230 #ifdef CONFIG_VIRTFS
1231 static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp)
1232 {
1233     return qemu_fsdev_add(opts, errp);
1234 }
1235 #endif
1236 
1237 static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp)
1238 {
1239     return monitor_init_opts(opts, errp);
1240 }
1241 
1242 static void monitor_parse(const char *str, const char *mode, bool pretty)
1243 {
1244     static int monitor_device_index = 0;
1245     QemuOpts *opts;
1246     const char *p;
1247     char label[32];
1248 
1249     if (strstart(str, "chardev:", &p)) {
1250         snprintf(label, sizeof(label), "%s", p);
1251     } else {
1252         snprintf(label, sizeof(label), "compat_monitor%d",
1253                  monitor_device_index);
1254         opts = qemu_chr_parse_compat(label, str, true);
1255         if (!opts) {
1256             error_report("parse error: %s", str);
1257             exit(1);
1258         }
1259     }
1260 
1261     opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &error_fatal);
1262     qemu_opt_set(opts, "mode", mode, &error_abort);
1263     qemu_opt_set(opts, "chardev", label, &error_abort);
1264     if (!strcmp(mode, "control")) {
1265         qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);
1266     } else {
1267         assert(pretty == false);
1268     }
1269     monitor_device_index++;
1270 }
1271 
1272 struct device_config {
1273     enum {
1274         DEV_USB,       /* -usbdevice     */
1275         DEV_SERIAL,    /* -serial        */
1276         DEV_PARALLEL,  /* -parallel      */
1277         DEV_DEBUGCON,  /* -debugcon */
1278         DEV_GDB,       /* -gdb, -s */
1279         DEV_SCLP,      /* s390 sclp */
1280     } type;
1281     const char *cmdline;
1282     Location loc;
1283     QTAILQ_ENTRY(device_config) next;
1284 };
1285 
1286 static QTAILQ_HEAD(, device_config) device_configs =
1287     QTAILQ_HEAD_INITIALIZER(device_configs);
1288 
1289 static void add_device_config(int type, const char *cmdline)
1290 {
1291     struct device_config *conf;
1292 
1293     conf = g_malloc0(sizeof(*conf));
1294     conf->type = type;
1295     conf->cmdline = cmdline;
1296     loc_save(&conf->loc);
1297     QTAILQ_INSERT_TAIL(&device_configs, conf, next);
1298 }
1299 
1300 /**
1301  * foreach_device_config_or_exit(): process per-device configs
1302  * @type: device_config type
1303  * @func: device specific config function, returning pass/fail
1304  *
1305  * @func is called with the &error_fatal handler so device specific
1306  * error messages can be reported on failure.
1307  */
1308 static void foreach_device_config_or_exit(int type,
1309                                           bool (*func)(const char *cmdline,
1310                                                        Error **errp))
1311 {
1312     struct device_config *conf;
1313 
1314     QTAILQ_FOREACH(conf, &device_configs, next) {
1315         if (conf->type != type)
1316             continue;
1317         loc_push_restore(&conf->loc);
1318         func(conf->cmdline, &error_fatal);
1319         loc_pop(&conf->loc);
1320     }
1321 }
1322 
1323 static void qemu_disable_default_devices(void)
1324 {
1325     MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
1326 
1327     default_driver_check_json();
1328     qemu_opts_foreach(qemu_find_opts("device"),
1329                       default_driver_check, NULL, NULL);
1330     qemu_opts_foreach(qemu_find_opts("global"),
1331                       default_driver_check, NULL, NULL);
1332 
1333     if (!vga_model && !default_vga) {
1334         vga_interface_type = VGA_DEVICE;
1335         vga_interface_created = true;
1336     }
1337     if (!has_defaults || machine_class->no_serial) {
1338         default_serial = 0;
1339     }
1340     if (!has_defaults || machine_class->no_parallel) {
1341         default_parallel = 0;
1342     }
1343     if (!has_defaults || machine_class->no_floppy) {
1344         default_floppy = 0;
1345     }
1346     if (!has_defaults || machine_class->no_cdrom) {
1347         default_cdrom = 0;
1348     }
1349     assert(machine_class->no_sdcard != ON_OFF_AUTO_AUTO);
1350     if (!has_defaults || machine_class->no_sdcard == ON_OFF_AUTO_ON) {
1351         default_sdcard = 0;
1352     }
1353     if (!has_defaults) {
1354         default_audio = 0;
1355         default_monitor = 0;
1356         default_net = 0;
1357         default_vga = 0;
1358     } else {
1359         if (default_net && machine_class->default_nic &&
1360             !module_object_class_by_name(machine_class->default_nic)) {
1361             warn_report("Default NIC '%s' is not available in this binary",
1362                         machine_class->default_nic);
1363             default_net = 0;
1364         }
1365     }
1366 }
1367 
1368 static void qemu_setup_display(void)
1369 {
1370     if (dpy.type == DISPLAY_TYPE_DEFAULT && !display_remote) {
1371         if (!qemu_display_find_default(&dpy)) {
1372             dpy.type = DISPLAY_TYPE_NONE;
1373 #if defined(CONFIG_VNC)
1374             vnc_parse("localhost:0,to=99,id=default");
1375             display_remote++;
1376 #endif
1377         }
1378     }
1379     if (dpy.type == DISPLAY_TYPE_DEFAULT) {
1380         dpy.type = DISPLAY_TYPE_NONE;
1381     }
1382 
1383     qemu_display_early_init(&dpy);
1384 }
1385 
1386 static void qemu_create_default_devices(void)
1387 {
1388     MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
1389     const char *vc = qemu_display_get_vc(&dpy);
1390 
1391     if (is_daemonized()) {
1392         /* According to documentation and historically, -nographic redirects
1393          * serial port, parallel port and monitor to stdio, which does not work
1394          * with -daemonize.  We can redirect these to null instead, but since
1395          * -nographic is legacy, let's just error out.
1396          * We disallow -nographic only if all other ports are not redirected
1397          * explicitly, to not break existing legacy setups which uses
1398          * -nographic _and_ redirects all ports explicitly - this is valid
1399          * usage, -nographic is just a no-op in this case.
1400          */
1401         if (nographic
1402             && (default_parallel || default_serial || default_monitor)) {
1403             error_report("-nographic cannot be used with -daemonize");
1404             exit(1);
1405         }
1406     }
1407 
1408     if (nographic) {
1409         if (default_parallel) {
1410             add_device_config(DEV_PARALLEL, "null");
1411         }
1412         if (default_serial && default_monitor) {
1413             add_device_config(DEV_SERIAL, "mon:stdio");
1414         } else {
1415             if (default_serial) {
1416                 add_device_config(DEV_SERIAL, "stdio");
1417             }
1418             if (default_monitor) {
1419                 monitor_parse("stdio", "readline", false);
1420             }
1421         }
1422     } else {
1423         if (default_serial) {
1424             add_device_config(DEV_SERIAL, vc ?: "null");
1425         }
1426         if (default_parallel) {
1427             add_device_config(DEV_PARALLEL, vc ?: "null");
1428         }
1429         if (default_monitor && vc) {
1430             monitor_parse(vc, "readline", false);
1431         }
1432     }
1433 
1434     if (default_net) {
1435         QemuOptsList *net = qemu_find_opts("net");
1436         qemu_opts_parse(net, "nic", true, &error_abort);
1437 #ifdef CONFIG_SLIRP
1438         qemu_opts_parse(net, "user", true, &error_abort);
1439 #endif
1440     }
1441 
1442     /* If no default VGA is requested, the default is "none".  */
1443     if (default_vga) {
1444         vga_model = get_default_vga_model(machine_class);
1445     }
1446     if (vga_model) {
1447         select_vgahw(machine_class, vga_model);
1448     }
1449 }
1450 
1451 static bool serial_parse(const char *devname, Error **errp)
1452 {
1453     int index = num_serial_hds;
1454 
1455     serial_hds = g_renew(Chardev *, serial_hds, index + 1);
1456 
1457     if (strcmp(devname, "none") == 0) {
1458         /* Don't allocate a serial device for this index */
1459         serial_hds[index] = NULL;
1460     } else {
1461         char label[32];
1462         snprintf(label, sizeof(label), "serial%d", index);
1463 
1464         serial_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
1465         if (!serial_hds[index]) {
1466             error_setg(errp, "could not connect serial device"
1467                        " to character backend '%s'", devname);
1468             return false;
1469         }
1470     }
1471     num_serial_hds++;
1472     return true;
1473 }
1474 
1475 Chardev *serial_hd(int i)
1476 {
1477     assert(i >= 0);
1478     if (i < num_serial_hds) {
1479         return serial_hds[i];
1480     }
1481     return NULL;
1482 }
1483 
1484 static bool parallel_parse(const char *devname, Error **errp)
1485 {
1486     static int index = 0;
1487     char label[32];
1488 
1489     if (strcmp(devname, "none") == 0)
1490         return true;
1491     if (index == MAX_PARALLEL_PORTS) {
1492         error_setg(errp, "too many parallel ports");
1493         return false;
1494     }
1495     snprintf(label, sizeof(label), "parallel%d", index);
1496     parallel_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
1497     if (!parallel_hds[index]) {
1498         error_setg(errp, "could not connect parallel device"
1499                    " to character backend '%s'", devname);
1500         return false;
1501     }
1502     index++;
1503     return true;
1504 }
1505 
1506 static bool debugcon_parse(const char *devname, Error **errp)
1507 {
1508     QemuOpts *opts;
1509 
1510     if (!qemu_chr_new_mux_mon("debugcon", devname, NULL)) {
1511         error_setg(errp, "invalid character backend '%s'", devname);
1512         return false;
1513     }
1514     opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
1515     if (!opts) {
1516         error_setg(errp, "already have a debugcon device");
1517         return false;
1518     }
1519     qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);
1520     qemu_opt_set(opts, "chardev", "debugcon", &error_abort);
1521     return true;
1522 }
1523 
1524 static gint machine_class_cmp(gconstpointer a, gconstpointer b)
1525 {
1526     const MachineClass *mc1 = a, *mc2 = b;
1527     int res;
1528 
1529     if (mc1->family == NULL) {
1530         if (mc2->family == NULL) {
1531             /* Compare standalone machine types against each other; they sort
1532              * in increasing order.
1533              */
1534             return strcmp(object_class_get_name(OBJECT_CLASS(mc1)),
1535                           object_class_get_name(OBJECT_CLASS(mc2)));
1536         }
1537 
1538         /* Standalone machine types sort after families. */
1539         return 1;
1540     }
1541 
1542     if (mc2->family == NULL) {
1543         /* Families sort before standalone machine types. */
1544         return -1;
1545     }
1546 
1547     /* Families sort between each other alphabetically increasingly. */
1548     res = strcmp(mc1->family, mc2->family);
1549     if (res != 0) {
1550         return res;
1551     }
1552 
1553     /* Within the same family, machine types sort in decreasing order. */
1554     return strcmp(object_class_get_name(OBJECT_CLASS(mc2)),
1555                   object_class_get_name(OBJECT_CLASS(mc1)));
1556 }
1557 
1558 static void machine_help_func(const QDict *qdict)
1559 {
1560     g_autoptr(GSList) machines = NULL;
1561     GSList *el;
1562     const char *type = qdict_get_try_str(qdict, "type");
1563 
1564     machines = object_class_get_list(TYPE_MACHINE, false);
1565     if (type) {
1566         ObjectClass *machine_class = OBJECT_CLASS(find_machine(type, machines));
1567         if (machine_class) {
1568             type_print_class_properties(object_class_get_name(machine_class));
1569             return;
1570         }
1571     }
1572 
1573     printf("Supported machines are:\n");
1574     machines = g_slist_sort(machines, machine_class_cmp);
1575     for (el = machines; el; el = el->next) {
1576         MachineClass *mc = el->data;
1577         if (mc->alias) {
1578             printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
1579         }
1580         printf("%-20s %s%s%s\n", mc->name, mc->desc,
1581                mc->is_default ? " (default)" : "",
1582                mc->deprecation_reason ? " (deprecated)" : "");
1583     }
1584 }
1585 
1586 static void
1587 machine_merge_property(const char *propname, QDict *prop, Error **errp)
1588 {
1589     QDict *opts;
1590 
1591     opts = qdict_new();
1592     /* Preserve the caller's reference to prop.  */
1593     qobject_ref(prop);
1594     qdict_put(opts, propname, prop);
1595     keyval_merge(machine_opts_dict, opts, errp);
1596     qobject_unref(opts);
1597 }
1598 
1599 static void
1600 machine_parse_property_opt(QemuOptsList *opts_list, const char *propname,
1601                            const char *arg)
1602 {
1603     QDict *prop = NULL;
1604     bool help = false;
1605 
1606     prop = keyval_parse(arg, opts_list->implied_opt_name, &help, &error_fatal);
1607     if (help) {
1608         qemu_opts_print_help(opts_list, true);
1609         exit(0);
1610     }
1611     machine_merge_property(propname, prop, &error_fatal);
1612     qobject_unref(prop);
1613 }
1614 
1615 static const char *pid_file;
1616 struct UnlinkPidfileNotifier {
1617     Notifier notifier;
1618     char *pid_file_realpath;
1619 };
1620 static struct UnlinkPidfileNotifier qemu_unlink_pidfile_notifier;
1621 
1622 static void qemu_unlink_pidfile(Notifier *n, void *data)
1623 {
1624     struct UnlinkPidfileNotifier *upn;
1625 
1626     upn = DO_UPCAST(struct UnlinkPidfileNotifier, notifier, n);
1627     unlink(upn->pid_file_realpath);
1628 }
1629 
1630 static const QEMUOption *lookup_opt(int argc, char **argv,
1631                                     const char **poptarg, int *poptind)
1632 {
1633     const QEMUOption *popt;
1634     int optind = *poptind;
1635     char *r = argv[optind];
1636     const char *optarg;
1637 
1638     loc_set_cmdline(argv, optind, 1);
1639     optind++;
1640     /* Treat --foo the same as -foo.  */
1641     if (r[1] == '-')
1642         r++;
1643     popt = qemu_options;
1644     for(;;) {
1645         if (!popt->name) {
1646             error_report("invalid option");
1647             exit(1);
1648         }
1649         if (!strcmp(popt->name, r + 1))
1650             break;
1651         popt++;
1652     }
1653     if (popt->flags & HAS_ARG) {
1654         if (optind >= argc) {
1655             error_report("requires an argument");
1656             exit(1);
1657         }
1658         optarg = argv[optind++];
1659         loc_set_cmdline(argv, optind - 2, 2);
1660     } else {
1661         optarg = NULL;
1662     }
1663 
1664     *poptarg = optarg;
1665     *poptind = optind;
1666 
1667     return popt;
1668 }
1669 
1670 static MachineClass *select_machine(QDict *qdict, Error **errp)
1671 {
1672     ERRP_GUARD();
1673     const char *machine_type = qdict_get_try_str(qdict, "type");
1674     g_autoptr(GSList) machines = object_class_get_list(TYPE_MACHINE, false);
1675     MachineClass *machine_class = NULL;
1676 
1677     if (machine_type) {
1678         machine_class = find_machine(machine_type, machines);
1679         if (!machine_class) {
1680             error_setg(errp, "unsupported machine type: \"%s\"", machine_type);
1681         }
1682         qdict_del(qdict, "type");
1683     } else {
1684         machine_class = find_default_machine(machines);
1685         if (!machine_class) {
1686             error_setg(errp, "No machine specified, and there is no default");
1687         }
1688     }
1689 
1690     if (!machine_class) {
1691         error_append_hint(errp,
1692                           "Use -machine help to list supported machines\n");
1693     }
1694     return machine_class;
1695 }
1696 
1697 static int object_parse_property_opt(Object *obj,
1698                                      const char *name, const char *value,
1699                                      const char *skip, Error **errp)
1700 {
1701     if (g_str_equal(name, skip)) {
1702         return 0;
1703     }
1704 
1705     if (!object_property_parse(obj, name, value, errp)) {
1706         return -1;
1707     }
1708 
1709     return 0;
1710 }
1711 
1712 /* *Non*recursively replace underscores with dashes in QDict keys.  */
1713 static void keyval_dashify(QDict *qdict, Error **errp)
1714 {
1715     const QDictEntry *ent, *next;
1716     char *p;
1717 
1718     for (ent = qdict_first(qdict); ent; ent = next) {
1719         g_autofree char *new_key = NULL;
1720 
1721         next = qdict_next(qdict, ent);
1722         if (!strchr(ent->key, '_')) {
1723             continue;
1724         }
1725         new_key = g_strdup(ent->key);
1726         for (p = new_key; *p; p++) {
1727             if (*p == '_') {
1728                 *p = '-';
1729             }
1730         }
1731         if (qdict_haskey(qdict, new_key)) {
1732             error_setg(errp, "Conflict between '%s' and '%s'", ent->key, new_key);
1733             return;
1734         }
1735         qobject_ref(ent->value);
1736         qdict_put_obj(qdict, new_key, ent->value);
1737         qdict_del(qdict, ent->key);
1738     }
1739 }
1740 
1741 static void qemu_apply_legacy_machine_options(QDict *qdict)
1742 {
1743     const char *value;
1744     QObject *prop;
1745 
1746     keyval_dashify(qdict, &error_fatal);
1747 
1748     /* Legacy options do not correspond to MachineState properties.  */
1749     value = qdict_get_try_str(qdict, "accel");
1750     if (value) {
1751         accelerators = g_strdup(value);
1752         qdict_del(qdict, "accel");
1753     }
1754 
1755     value = qdict_get_try_str(qdict, "igd-passthru");
1756     if (value) {
1757         object_register_sugar_prop(ACCEL_CLASS_NAME("xen"), "igd-passthru", value,
1758                                    false);
1759         qdict_del(qdict, "igd-passthru");
1760     }
1761 
1762     value = qdict_get_try_str(qdict, "kvm-shadow-mem");
1763     if (value) {
1764         object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), "kvm-shadow-mem", value,
1765                                    false);
1766         qdict_del(qdict, "kvm-shadow-mem");
1767     }
1768 
1769     value = qdict_get_try_str(qdict, "kernel-irqchip");
1770     if (value) {
1771         object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), "kernel-irqchip", value,
1772                                    false);
1773         object_register_sugar_prop(ACCEL_CLASS_NAME("whpx"), "kernel-irqchip", value,
1774                                    false);
1775         qdict_del(qdict, "kernel-irqchip");
1776     }
1777 
1778     value = qdict_get_try_str(qdict, "memory-backend");
1779     if (value) {
1780         if (mem_path) {
1781             error_report("'-mem-path' can't be used together with"
1782                          "'-machine memory-backend'");
1783             exit(EXIT_FAILURE);
1784         }
1785 
1786         /* Resolved later.  */
1787         ram_memdev_id = g_strdup(value);
1788         qdict_del(qdict, "memory-backend");
1789     }
1790 
1791     prop = qdict_get(qdict, "memory");
1792     if (prop) {
1793         have_custom_ram_size =
1794             qobject_type(prop) == QTYPE_QDICT &&
1795             qdict_haskey(qobject_to(QDict, prop), "size");
1796     }
1797 }
1798 
1799 static void object_option_foreach_add(bool (*type_opt_predicate)(const char *))
1800 {
1801     ObjectOption *opt, *next;
1802 
1803     QTAILQ_FOREACH_SAFE(opt, &object_opts, next, next) {
1804         const char *type = ObjectType_str(opt->opts->qom_type);
1805         if (type_opt_predicate(type)) {
1806             user_creatable_add_qapi(opt->opts, &error_fatal);
1807             qapi_free_ObjectOptions(opt->opts);
1808             QTAILQ_REMOVE(&object_opts, opt, next);
1809             g_free(opt);
1810         }
1811     }
1812 }
1813 
1814 static void object_option_add_visitor(Visitor *v)
1815 {
1816     ObjectOption *opt = g_new0(ObjectOption, 1);
1817     visit_type_ObjectOptions(v, NULL, &opt->opts, &error_fatal);
1818     QTAILQ_INSERT_TAIL(&object_opts, opt, next);
1819 }
1820 
1821 static void incoming_option_parse(const char *str)
1822 {
1823     MigrationChannelType type = MIGRATION_CHANNEL_TYPE_MAIN;
1824     MigrationChannel *channel;
1825     Visitor *v;
1826 
1827     if (!strcmp(str, "defer")) {
1828         channel = NULL;
1829     } else if (migrate_is_uri(str)) {
1830         migrate_uri_parse(str, &channel, &error_fatal);
1831     } else {
1832         v = qobject_input_visitor_new_str(str, "channel-type", &error_fatal);
1833         visit_type_MigrationChannel(v, NULL, &channel, &error_fatal);
1834         visit_free(v);
1835         type = channel->channel_type;
1836     }
1837 
1838     /* New incoming spec replaces the previous */
1839     qapi_free_MigrationChannel(incoming_channels[type]);
1840     incoming_channels[type] = channel;
1841     incoming_str[type] = str;
1842     incoming = incoming_str[MIGRATION_CHANNEL_TYPE_MAIN];
1843 }
1844 
1845 static void object_option_parse(const char *str)
1846 {
1847     QemuOpts *opts;
1848     const char *type;
1849     Visitor *v;
1850 
1851     if (str[0] == '{') {
1852         QObject *obj = qobject_from_json(str, &error_fatal);
1853 
1854         v = qobject_input_visitor_new(obj);
1855         qobject_unref(obj);
1856     } else {
1857         opts = qemu_opts_parse_noisily(qemu_find_opts("object"),
1858                                        str, true);
1859         if (!opts) {
1860             exit(1);
1861         }
1862 
1863         type = qemu_opt_get(opts, "qom-type");
1864         if (!type) {
1865             error_report(QERR_MISSING_PARAMETER, "qom-type");
1866             exit(1);
1867         }
1868         if (user_creatable_print_help(type, opts)) {
1869             exit(0);
1870         }
1871 
1872         v = opts_visitor_new(opts);
1873     }
1874 
1875     object_option_add_visitor(v);
1876     visit_free(v);
1877 }
1878 
1879 /*
1880  * Very early object creation, before the sandbox options have been activated.
1881  */
1882 static bool object_create_pre_sandbox(const char *type)
1883 {
1884     /*
1885      * Objects should in general not get initialized "too early" without
1886      * a reason. If you add one, state the reason in a comment!
1887      */
1888 
1889     /*
1890      * Reason: -sandbox on,resourcecontrol=deny disallows setting CPU
1891      * affinity of threads.
1892      */
1893     if (g_str_equal(type, "thread-context")) {
1894         return true;
1895     }
1896 
1897     return false;
1898 }
1899 
1900 /*
1901  * Initial object creation happens before all other
1902  * QEMU data types are created. The majority of objects
1903  * can be created at this point. The rng-egd object
1904  * cannot be created here, as it depends on the chardev
1905  * already existing.
1906  */
1907 static bool object_create_early(const char *type)
1908 {
1909     /*
1910      * Objects should not be made "delayed" without a reason.  If you
1911      * add one, state the reason in a comment!
1912      */
1913 
1914     /* Reason: already created. */
1915     if (object_create_pre_sandbox(type)) {
1916         return false;
1917     }
1918 
1919     /* Reason: property "chardev" */
1920     if (g_str_equal(type, "rng-egd") ||
1921         g_str_equal(type, "qtest")) {
1922         return false;
1923     }
1924 
1925 #if defined(CONFIG_VHOST_USER) && defined(CONFIG_LINUX)
1926     /* Reason: cryptodev-vhost-user property "chardev" */
1927     if (g_str_equal(type, "cryptodev-vhost-user")) {
1928         return false;
1929     }
1930 #endif
1931 
1932     /* Reason: vhost-user-blk-server property "node-name" */
1933     if (g_str_equal(type, "vhost-user-blk-server")) {
1934         return false;
1935     }
1936     /*
1937      * Reason: filter-* property "netdev" etc.
1938      */
1939     if (g_str_equal(type, "filter-buffer") ||
1940         g_str_equal(type, "filter-dump") ||
1941         g_str_equal(type, "filter-mirror") ||
1942         g_str_equal(type, "filter-redirector") ||
1943         g_str_equal(type, "colo-compare") ||
1944         g_str_equal(type, "filter-rewriter") ||
1945         g_str_equal(type, "filter-replay")) {
1946         return false;
1947     }
1948 
1949     /*
1950      * Allocation of large amounts of memory may delay
1951      * chardev initialization for too long, and trigger timeouts
1952      * on software that waits for a monitor socket to be created
1953      */
1954     if (g_str_has_prefix(type, "memory-backend-")) {
1955         return false;
1956     }
1957 
1958     return true;
1959 }
1960 
1961 static void qemu_apply_machine_options(QDict *qdict)
1962 {
1963     object_set_properties_from_keyval(OBJECT(current_machine), qdict, false, &error_fatal);
1964 
1965     if (semihosting_enabled(false) && !semihosting_get_argc()) {
1966         /* fall back to the -kernel/-append */
1967         semihosting_arg_fallback(current_machine->kernel_filename, current_machine->kernel_cmdline);
1968     }
1969 
1970     if (current_machine->smp.cpus > 1) {
1971         replay_add_blocker("multiple CPUs");
1972     }
1973 }
1974 
1975 static void qemu_create_early_backends(void)
1976 {
1977     MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
1978 #if defined(CONFIG_SDL)
1979     const bool use_sdl = (dpy.type == DISPLAY_TYPE_SDL);
1980 #else
1981     const bool use_sdl = false;
1982 #endif
1983 #if defined(CONFIG_GTK)
1984     const bool use_gtk = (dpy.type == DISPLAY_TYPE_GTK);
1985 #else
1986     const bool use_gtk = false;
1987 #endif
1988 
1989     if (dpy.has_window_close && !use_gtk && !use_sdl) {
1990         error_report("window-close is only valid for GTK and SDL, "
1991                      "ignoring option");
1992     }
1993 
1994     qemu_console_early_init();
1995 
1996     if (dpy.has_gl && dpy.gl != DISPLAY_GL_MODE_OFF && display_opengl == 0) {
1997 #if defined(CONFIG_OPENGL)
1998         error_report("OpenGL is not supported by display backend '%s'",
1999                      DisplayType_str(dpy.type));
2000 #else
2001         error_report("OpenGL support was not enabled in this build of QEMU");
2002 #endif
2003         exit(1);
2004     }
2005 
2006     object_option_foreach_add(object_create_early);
2007 
2008     /* spice needs the timers to be initialized by this point */
2009     /* spice must initialize before audio as it changes the default audiodev */
2010     /* spice must initialize before chardevs (for spicevmc and spiceport) */
2011     qemu_spice.init();
2012 
2013     qemu_opts_foreach(qemu_find_opts("chardev"),
2014                       chardev_init_func, NULL, &error_fatal);
2015 
2016 #ifdef CONFIG_VIRTFS
2017     qemu_opts_foreach(qemu_find_opts("fsdev"),
2018                       fsdev_init_func, NULL, &error_fatal);
2019 #endif
2020 
2021     /*
2022      * Note: we need to create audio and block backends before
2023      * setting machine properties, so they can be referred to.
2024      */
2025     configure_blockdev(&bdo_queue, machine_class, snapshot);
2026     audio_init_audiodevs();
2027     if (default_audio) {
2028         audio_create_default_audiodevs();
2029     }
2030 }
2031 
2032 
2033 /*
2034  * The remainder of object creation happens after the
2035  * creation of chardev, fsdev, net clients and device data types.
2036  */
2037 static bool object_create_late(const char *type)
2038 {
2039     return !object_create_early(type) && !object_create_pre_sandbox(type);
2040 }
2041 
2042 static void qemu_create_late_backends(void)
2043 {
2044     if (qtest_chrdev) {
2045         qtest_server_init(qtest_chrdev, qtest_log, &error_fatal);
2046     }
2047 
2048     net_init_clients();
2049 
2050     object_option_foreach_add(object_create_late);
2051 
2052     /*
2053      * Wait for any outstanding memory prealloc from created memory
2054      * backends to complete.
2055      */
2056     if (!qemu_finish_async_prealloc_mem(&error_fatal)) {
2057         exit(1);
2058     }
2059 
2060     if (tpm_init() < 0) {
2061         exit(1);
2062     }
2063 
2064     qemu_opts_foreach(qemu_find_opts("mon"),
2065                       mon_init_func, NULL, &error_fatal);
2066 
2067     foreach_device_config_or_exit(DEV_SERIAL, serial_parse);
2068     foreach_device_config_or_exit(DEV_PARALLEL, parallel_parse);
2069     foreach_device_config_or_exit(DEV_DEBUGCON, debugcon_parse);
2070 
2071     /* now chardevs have been created we may have semihosting to connect */
2072     qemu_semihosting_chardev_init();
2073 }
2074 
2075 static void qemu_resolve_machine_memdev(void)
2076 {
2077     if (ram_memdev_id) {
2078         Object *backend;
2079         ram_addr_t backend_size;
2080 
2081         backend = object_resolve_path_type(ram_memdev_id,
2082                                            TYPE_MEMORY_BACKEND, NULL);
2083         if (!backend) {
2084             error_report("Memory backend '%s' not found", ram_memdev_id);
2085             exit(EXIT_FAILURE);
2086         }
2087         if (!have_custom_ram_size) {
2088             backend_size = object_property_get_uint(backend, "size",  &error_abort);
2089             current_machine->ram_size = backend_size;
2090         }
2091         object_property_set_link(OBJECT(current_machine),
2092                                  "memory-backend", backend, &error_fatal);
2093     }
2094 }
2095 
2096 static void parse_memory_options(void)
2097 {
2098     QemuOpts *opts = qemu_find_opts_singleton("memory");
2099     QDict *dict, *prop;
2100     const char *mem_str;
2101     Location loc;
2102 
2103     loc_push_none(&loc);
2104     qemu_opts_loc_restore(opts);
2105 
2106     prop = qdict_new();
2107 
2108     if (qemu_opt_get_size(opts, "size", 0) != 0) {
2109         /* Fix up legacy suffix-less format */
2110         mem_str = qemu_opt_get(opts, "size");
2111         if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
2112             g_autofree char *mib_str = g_strdup_printf("%sM", mem_str);
2113             qdict_put_str(prop, "size", mib_str);
2114         } else {
2115             qdict_put_str(prop, "size", mem_str);
2116         }
2117     }
2118 
2119     if (qemu_opt_get(opts, "maxmem")) {
2120         qdict_put_str(prop, "max-size", qemu_opt_get(opts, "maxmem"));
2121     }
2122     if (qemu_opt_get(opts, "slots")) {
2123         qdict_put_str(prop, "slots", qemu_opt_get(opts, "slots"));
2124     }
2125 
2126     dict = qdict_new();
2127     qdict_put(dict, "memory", prop);
2128     keyval_merge(machine_opts_dict, dict, &error_fatal);
2129     qobject_unref(dict);
2130     loc_pop(&loc);
2131 }
2132 
2133 static void qemu_create_machine_containers(Object *machine)
2134 {
2135     static const char *const containers[] = {
2136         "unattached",
2137         "peripheral",
2138         "peripheral-anon",
2139     };
2140 
2141     for (unsigned i = 0; i < ARRAY_SIZE(containers); i++) {
2142         object_property_add_new_container(machine, containers[i]);
2143     }
2144 }
2145 
2146 static void qemu_create_machine(QDict *qdict)
2147 {
2148     MachineClass *machine_class = select_machine(qdict, &error_fatal);
2149     object_set_machine_compat_props(machine_class->compat_props);
2150 
2151     current_machine = MACHINE(object_new_with_class(OBJECT_CLASS(machine_class)));
2152     object_property_add_child(object_get_root(), "machine",
2153                               OBJECT(current_machine));
2154     qemu_create_machine_containers(OBJECT(current_machine));
2155     object_property_add_child(machine_get_container("unattached"),
2156                               "sysbus", OBJECT(sysbus_get_default()));
2157 
2158     if (machine_class->minimum_page_bits) {
2159         if (!set_preferred_target_page_bits(machine_class->minimum_page_bits)) {
2160             /* This would be a board error: specifying a minimum smaller than
2161              * a target's compile-time fixed setting.
2162              */
2163             g_assert_not_reached();
2164         }
2165     }
2166 
2167     cpu_exec_init_all();
2168 
2169     if (machine_class->hw_version) {
2170         qemu_set_hw_version(machine_class->hw_version);
2171     }
2172 
2173     /*
2174      * Get the default machine options from the machine if it is not already
2175      * specified either by the configuration file or by the command line.
2176      */
2177     if (machine_class->default_machine_opts) {
2178         QDict *default_opts =
2179             keyval_parse(machine_class->default_machine_opts, NULL, NULL,
2180                          &error_abort);
2181         qemu_apply_legacy_machine_options(default_opts);
2182         object_set_properties_from_keyval(OBJECT(current_machine), default_opts,
2183                                           false, &error_abort);
2184         qobject_unref(default_opts);
2185     }
2186 }
2187 
2188 static int global_init_func(void *opaque, QemuOpts *opts, Error **errp)
2189 {
2190     GlobalProperty *g;
2191 
2192     g = g_malloc0(sizeof(*g));
2193     g->driver   = qemu_opt_get(opts, "driver");
2194     g->property = qemu_opt_get(opts, "property");
2195     g->value    = qemu_opt_get(opts, "value");
2196     qdev_prop_register_global(g);
2197     return 0;
2198 }
2199 
2200 /*
2201  * Return whether configuration group @group is stored in QemuOpts, or
2202  * recorded as one or more QDicts by qemu_record_config_group.
2203  */
2204 static bool is_qemuopts_group(const char *group)
2205 {
2206     if (g_str_equal(group, "object") ||
2207         g_str_equal(group, "audiodev") ||
2208         g_str_equal(group, "machine") ||
2209         g_str_equal(group, "smp-opts") ||
2210         g_str_equal(group, "boot-opts")) {
2211         return false;
2212     }
2213     return true;
2214 }
2215 
2216 static void qemu_record_config_group(const char *group, QDict *dict,
2217                                      bool from_json, Error **errp)
2218 {
2219     if (g_str_equal(group, "object")) {
2220         Visitor *v = qobject_input_visitor_new_keyval(QOBJECT(dict));
2221         object_option_add_visitor(v);
2222         visit_free(v);
2223 
2224     } else if (g_str_equal(group, "audiodev")) {
2225         Audiodev *dev = NULL;
2226         Visitor *v = qobject_input_visitor_new_keyval(QOBJECT(dict));
2227         if (visit_type_Audiodev(v, NULL, &dev, errp)) {
2228             audio_define(dev);
2229         }
2230         visit_free(v);
2231 
2232     } else if (g_str_equal(group, "machine")) {
2233         /*
2234          * Cannot merge string-valued and type-safe dictionaries, so JSON
2235          * is not accepted yet for -M.
2236          */
2237         assert(!from_json);
2238         keyval_merge(machine_opts_dict, dict, errp);
2239     } else if (g_str_equal(group, "smp-opts")) {
2240         machine_merge_property("smp", dict, &error_fatal);
2241     } else if (g_str_equal(group, "boot-opts")) {
2242         machine_merge_property("boot", dict, &error_fatal);
2243     } else {
2244         abort();
2245     }
2246 }
2247 
2248 /*
2249  * Parse non-QemuOpts config file groups, pass the rest to
2250  * qemu_config_do_parse.
2251  */
2252 static void qemu_parse_config_group(const char *group, QDict *qdict,
2253                                     void *opaque, Error **errp)
2254 {
2255     QObject *crumpled;
2256     if (is_qemuopts_group(group)) {
2257         qemu_config_do_parse(group, qdict, opaque, errp);
2258         return;
2259     }
2260 
2261     crumpled = qdict_crumple(qdict, errp);
2262     if (!crumpled) {
2263         return;
2264     }
2265     switch (qobject_type(crumpled)) {
2266     case QTYPE_QDICT:
2267         qemu_record_config_group(group, qobject_to(QDict, crumpled), false, errp);
2268         break;
2269     case QTYPE_QLIST:
2270         error_setg(errp, "Lists cannot be at top level of a configuration section");
2271         break;
2272     default:
2273         g_assert_not_reached();
2274     }
2275     qobject_unref(crumpled);
2276 }
2277 
2278 static void qemu_read_default_config_file(Error **errp)
2279 {
2280     ERRP_GUARD();
2281     int ret;
2282     g_autofree char *file = get_relocated_path(CONFIG_QEMU_CONFDIR "/qemu.conf");
2283 
2284     ret = qemu_read_config_file(file, qemu_parse_config_group, errp);
2285     if (ret < 0) {
2286         if (ret == -ENOENT) {
2287             error_free(*errp);
2288             *errp = NULL;
2289         }
2290     }
2291 }
2292 
2293 static void qemu_set_option(const char *str, Error **errp)
2294 {
2295     char group[64], id[64], arg[64];
2296     QemuOptsList *list;
2297     QemuOpts *opts;
2298     int rc, offset;
2299 
2300     rc = sscanf(str, "%63[^.].%63[^.].%63[^=]%n", group, id, arg, &offset);
2301     if (rc < 3 || str[offset] != '=') {
2302         error_setg(errp, "can't parse: \"%s\"", str);
2303         return;
2304     }
2305 
2306     if (!is_qemuopts_group(group)) {
2307         error_setg(errp, "-set is not supported with %s", group);
2308     } else {
2309         list = qemu_find_opts_err(group, errp);
2310         if (list) {
2311             opts = qemu_opts_find(list, id);
2312             if (!opts) {
2313                 error_setg(errp, "there is no %s \"%s\" defined", group, id);
2314                 return;
2315             }
2316             qemu_opt_set(opts, arg, str + offset + 1, errp);
2317         }
2318     }
2319 }
2320 
2321 static void user_register_global_props(void)
2322 {
2323     qemu_opts_foreach(qemu_find_opts("global"),
2324                       global_init_func, NULL, NULL);
2325 }
2326 
2327 static int do_configure_icount(void *opaque, QemuOpts *opts, Error **errp)
2328 {
2329     return !icount_configure(opts, errp);
2330 }
2331 
2332 static int accelerator_set_property(void *opaque,
2333                                 const char *name, const char *value,
2334                                 Error **errp)
2335 {
2336     return object_parse_property_opt(opaque, name, value, "accel", errp);
2337 }
2338 
2339 static int do_configure_accelerator(void *opaque, QemuOpts *opts, Error **errp)
2340 {
2341     bool *p_init_failed = opaque;
2342     const char *acc = qemu_opt_get(opts, "accel");
2343     AccelClass *ac = accel_find(acc);
2344     AccelState *accel;
2345     int ret;
2346     bool qtest_with_kvm;
2347 
2348     if (!acc) {
2349         error_setg(errp, QERR_MISSING_PARAMETER, "accel");
2350         goto bad;
2351     }
2352 
2353     qtest_with_kvm = g_str_equal(acc, "kvm") && qtest_chrdev != NULL;
2354 
2355     if (!ac) {
2356         if (!qtest_with_kvm) {
2357             error_report("invalid accelerator %s", acc);
2358         }
2359         goto bad;
2360     }
2361     accel = ACCEL(object_new_with_class(OBJECT_CLASS(ac)));
2362     object_apply_compat_props(OBJECT(accel));
2363     qemu_opt_foreach(opts, accelerator_set_property,
2364                      accel,
2365                      &error_fatal);
2366 
2367     ret = accel_init_machine(accel, current_machine);
2368     if (ret < 0) {
2369         if (!qtest_with_kvm || ret != -ENOENT) {
2370             error_report("failed to initialize %s: %s", acc, strerror(-ret));
2371         }
2372         goto bad;
2373     }
2374 
2375     return 1;
2376 
2377 bad:
2378     *p_init_failed = true;
2379     return 0;
2380 }
2381 
2382 static void configure_accelerators(const char *progname)
2383 {
2384     bool init_failed = false;
2385 
2386     qemu_opts_foreach(qemu_find_opts("icount"),
2387                       do_configure_icount, NULL, &error_fatal);
2388 
2389     if (QTAILQ_EMPTY(&qemu_accel_opts.head)) {
2390         char **accel_list, **tmp;
2391 
2392         if (accelerators == NULL) {
2393             /* Select the default accelerator */
2394             bool have_tcg = accel_find("tcg");
2395             bool have_kvm = accel_find("kvm");
2396             bool have_hvf = accel_find("hvf");
2397 
2398             if (have_tcg && have_kvm) {
2399                 if (g_str_has_suffix(progname, "kvm")) {
2400                     /* If the program name ends with "kvm", we prefer KVM */
2401                     accelerators = "kvm:tcg";
2402                 } else {
2403                     accelerators = "tcg:kvm";
2404                 }
2405             } else if (have_kvm) {
2406                 accelerators = "kvm";
2407             } else if (have_tcg) {
2408                 accelerators = "tcg";
2409             } else if (have_hvf) {
2410                 accelerators = "hvf";
2411             } else {
2412                 error_report("No accelerator selected and"
2413                              " no default accelerator available");
2414                 exit(1);
2415             }
2416         }
2417         accel_list = g_strsplit(accelerators, ":", 0);
2418 
2419         for (tmp = accel_list; *tmp; tmp++) {
2420             /*
2421              * Filter invalid accelerators here, to prevent obscenities
2422              * such as "-machine accel=tcg,,thread=single".
2423              */
2424             if (accel_find(*tmp)) {
2425                 qemu_opts_parse_noisily(qemu_find_opts("accel"), *tmp, true);
2426             } else {
2427                 init_failed = true;
2428                 error_report("invalid accelerator %s", *tmp);
2429             }
2430         }
2431         g_strfreev(accel_list);
2432     } else {
2433         if (accelerators != NULL) {
2434             error_report("The -accel and \"-machine accel=\" options are incompatible");
2435             exit(1);
2436         }
2437     }
2438 
2439     if (!qemu_opts_foreach(qemu_find_opts("accel"),
2440                            do_configure_accelerator, &init_failed, &error_fatal)) {
2441         if (!init_failed) {
2442             error_report("no accelerator found");
2443         }
2444         exit(1);
2445     }
2446 
2447     if (init_failed && !qtest_chrdev) {
2448         error_report("falling back to %s", current_accel_name());
2449     }
2450 
2451     if (icount_enabled() && !tcg_enabled()) {
2452         error_report("-icount is not allowed with hardware virtualization");
2453         exit(1);
2454     }
2455 }
2456 
2457 static void qemu_validate_options(const QDict *machine_opts)
2458 {
2459     const char *kernel_filename = qdict_get_try_str(machine_opts, "kernel");
2460     const char *shim_filename = qdict_get_try_str(machine_opts, "shim");
2461     const char *initrd_filename = qdict_get_try_str(machine_opts, "initrd");
2462     const char *kernel_cmdline = qdict_get_try_str(machine_opts, "append");
2463 
2464     if (kernel_filename == NULL) {
2465         if (kernel_cmdline != NULL) {
2466             error_report("-append only allowed with -kernel option");
2467             exit(1);
2468         }
2469 
2470         if (shim_filename != NULL) {
2471             error_report("-shim only allowed with -kernel option");
2472             exit(1);
2473         }
2474 
2475         if (initrd_filename != NULL) {
2476             error_report("-initrd only allowed with -kernel option");
2477             exit(1);
2478         }
2479     }
2480 
2481     if (loadvm && incoming) {
2482         error_report("'incoming' and 'loadvm' options are mutually exclusive");
2483         exit(EXIT_FAILURE);
2484     }
2485     if (loadvm && preconfig_requested) {
2486         error_report("'preconfig' and 'loadvm' options are "
2487                      "mutually exclusive");
2488         exit(EXIT_FAILURE);
2489     }
2490     if (incoming && preconfig_requested && strcmp(incoming, "defer") != 0) {
2491         error_report("'preconfig' supports '-incoming defer' only");
2492         exit(EXIT_FAILURE);
2493     }
2494 
2495 #ifdef CONFIG_CURSES
2496     if (is_daemonized() && dpy.type == DISPLAY_TYPE_CURSES) {
2497         error_report("curses display cannot be used with -daemonize");
2498         exit(1);
2499     }
2500 #endif
2501 }
2502 
2503 static void qemu_process_sugar_options(void)
2504 {
2505     if (mem_prealloc) {
2506         QObject *smp = qdict_get(machine_opts_dict, "smp");
2507         if (smp && qobject_type(smp) == QTYPE_QDICT) {
2508             QObject *cpus = qdict_get(qobject_to(QDict, smp), "cpus");
2509             if (cpus && qobject_type(cpus) == QTYPE_QSTRING) {
2510                 const char *val = qstring_get_str(qobject_to(QString, cpus));
2511                 object_register_sugar_prop("memory-backend", "prealloc-threads",
2512                                            val, false);
2513             }
2514         }
2515         object_register_sugar_prop("memory-backend", "prealloc", "on", false);
2516     }
2517 }
2518 
2519 /* -action processing */
2520 
2521 /*
2522  * Process all the -action parameters parsed from cmdline.
2523  */
2524 static int process_runstate_actions(void *opaque, QemuOpts *opts, Error **errp)
2525 {
2526     Error *local_err = NULL;
2527     QDict *qdict = qemu_opts_to_qdict(opts, NULL);
2528     QObject *ret = NULL;
2529     qmp_marshal_set_action(qdict, &ret, &local_err);
2530     qobject_unref(ret);
2531     qobject_unref(qdict);
2532     if (local_err) {
2533         error_propagate(errp, local_err);
2534         return 1;
2535     }
2536     return 0;
2537 }
2538 
2539 static void qemu_process_early_options(void)
2540 {
2541     qemu_opts_foreach(qemu_find_opts("name"),
2542                       parse_name, NULL, &error_fatal);
2543 
2544     object_option_foreach_add(object_create_pre_sandbox);
2545 
2546 #ifdef CONFIG_SECCOMP
2547     QemuOptsList *olist = qemu_find_opts_err("sandbox", NULL);
2548     if (olist) {
2549         qemu_opts_foreach(olist, parse_sandbox, NULL, &error_fatal);
2550     }
2551 #endif
2552 
2553     if (qemu_opts_foreach(qemu_find_opts("action"),
2554                           process_runstate_actions, NULL, &error_fatal)) {
2555         exit(1);
2556     }
2557 
2558 #ifndef _WIN32
2559     qemu_opts_foreach(qemu_find_opts("add-fd"),
2560                       parse_add_fd, NULL, &error_fatal);
2561 
2562     qemu_opts_foreach(qemu_find_opts("add-fd"),
2563                       cleanup_add_fd, NULL, &error_fatal);
2564 #endif
2565 
2566     /* Open the logfile at this point and set the log mask if necessary.  */
2567     {
2568         int mask = 0;
2569         if (log_mask) {
2570             mask = qemu_str_to_log_mask(log_mask);
2571             if (!mask) {
2572                 qemu_print_log_usage(stdout);
2573                 exit(1);
2574             }
2575         }
2576         qemu_set_log_filename_flags(log_file, mask, &error_fatal);
2577     }
2578 
2579     qemu_add_default_firmwarepath();
2580 }
2581 
2582 static void qemu_process_help_options(void)
2583 {
2584     /*
2585      * Check for -cpu help and -device help before we call select_machine(),
2586      * which will return an error if the architecture has no default machine
2587      * type and the user did not specify one, so that the user doesn't need
2588      * to say '-cpu help -machine something'.
2589      */
2590     if (cpu_option && is_help_option(cpu_option)) {
2591         list_cpus();
2592         exit(0);
2593     }
2594 
2595     if (qemu_opts_foreach(qemu_find_opts("device"),
2596                           device_help_func, NULL, NULL)) {
2597         exit(0);
2598     }
2599 
2600     /* -L help lists the data directories and exits. */
2601     if (list_data_dirs) {
2602         qemu_list_data_dirs();
2603         exit(0);
2604     }
2605 }
2606 
2607 static void qemu_maybe_daemonize(const char *pid_file)
2608 {
2609     Error *err = NULL;
2610 
2611     os_daemonize();
2612     rcu_disable_atfork();
2613 
2614     if (pid_file) {
2615         char *pid_file_realpath = NULL;
2616 
2617         if (!qemu_write_pidfile(pid_file, &err)) {
2618             error_reportf_err(err, "cannot create PID file: ");
2619             exit(1);
2620         }
2621 
2622         pid_file_realpath = g_malloc0(PATH_MAX);
2623         if (!realpath(pid_file, pid_file_realpath)) {
2624             if (errno != ENOENT) {
2625                 warn_report("not removing PID file on exit: cannot resolve PID "
2626                             "file path: %s: %s", pid_file, strerror(errno));
2627             }
2628             return;
2629         }
2630 
2631         qemu_unlink_pidfile_notifier = (struct UnlinkPidfileNotifier) {
2632             .notifier = {
2633                 .notify = qemu_unlink_pidfile,
2634             },
2635             .pid_file_realpath = pid_file_realpath,
2636         };
2637         qemu_add_exit_notifier(&qemu_unlink_pidfile_notifier.notifier);
2638     }
2639 }
2640 
2641 static void qemu_init_displays(void)
2642 {
2643     DisplayState *ds;
2644 
2645     /* init local displays */
2646     ds = init_displaystate();
2647     qemu_display_init(ds, &dpy);
2648 
2649     /* must be after terminal init, SDL library changes signal handlers */
2650     os_setup_signal_handling();
2651 
2652     /* init remote displays */
2653 #ifdef CONFIG_VNC
2654     qemu_opts_foreach(qemu_find_opts("vnc"),
2655                       vnc_init_func, NULL, &error_fatal);
2656 #endif
2657 
2658     if (using_spice) {
2659         qemu_spice.display_init();
2660     }
2661 }
2662 
2663 static void qemu_init_board(void)
2664 {
2665     /* process plugin before CPUs are created, but once -smp has been parsed */
2666     qemu_plugin_load_list(&plugin_list, &error_fatal);
2667 
2668     /* From here on we enter MACHINE_PHASE_INITIALIZED.  */
2669     machine_run_board_init(current_machine, mem_path, &error_fatal);
2670 
2671     drive_check_orphaned();
2672 
2673     realtime_init();
2674 }
2675 
2676 static void qemu_create_cli_devices(void)
2677 {
2678     DeviceOption *opt;
2679 
2680     soundhw_init();
2681 
2682     qemu_opts_foreach(qemu_find_opts("fw_cfg"),
2683                       parse_fw_cfg, fw_cfg_find(), &error_fatal);
2684 
2685     /* init USB devices */
2686     if (machine_usb(current_machine)) {
2687         foreach_device_config_or_exit(DEV_USB, usb_parse);
2688     }
2689 
2690     /* init generic devices */
2691     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
2692     qemu_opts_foreach(qemu_find_opts("device"),
2693                       device_init_func, NULL, &error_fatal);
2694     QTAILQ_FOREACH(opt, &device_opts, next) {
2695         QObject *ret_data = NULL;
2696 
2697         loc_push_restore(&opt->loc);
2698         qmp_device_add(opt->opts, &ret_data, &error_fatal);
2699         assert(ret_data == NULL); /* error_fatal aborts */
2700         loc_pop(&opt->loc);
2701     }
2702     rom_reset_order_override();
2703 }
2704 
2705 static bool qemu_machine_creation_done(Error **errp)
2706 {
2707     MachineState *machine = MACHINE(qdev_get_machine());
2708 
2709     /* Did we create any drives that we failed to create a device for? */
2710     drive_check_orphaned();
2711 
2712     /* Don't warn about the default network setup that you get if
2713      * no command line -net or -netdev options are specified. There
2714      * are two cases that we would otherwise complain about:
2715      * (1) board doesn't support a NIC but the implicit "-net nic"
2716      * requested one
2717      * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
2718      * sets up a nic that isn't connected to anything.
2719      */
2720     if (!default_net && (!qtest_enabled() || has_defaults)) {
2721         net_check_clients();
2722     }
2723 
2724     qdev_prop_check_globals();
2725 
2726     qdev_machine_creation_done();
2727 
2728     if (machine->cgs && !machine->cgs->ready) {
2729         error_setg(errp, "accelerator does not support confidential guest %s",
2730                    object_get_typename(OBJECT(machine->cgs)));
2731         exit(1);
2732     }
2733 
2734     foreach_device_config_or_exit(DEV_GDB, gdbserver_start);
2735 
2736     if (!vga_interface_created && !default_vga &&
2737         vga_interface_type != VGA_NONE) {
2738         warn_report("A -vga option was passed but this machine "
2739                     "type does not use that option; "
2740                     "No VGA device has been created");
2741     }
2742     return true;
2743 }
2744 
2745 void qmp_x_exit_preconfig(Error **errp)
2746 {
2747     if (phase_check(PHASE_MACHINE_INITIALIZED)) {
2748         error_setg(errp, "The command is permitted only before machine initialization");
2749         return;
2750     }
2751 
2752     qemu_init_board();
2753     qemu_create_cli_devices();
2754     if (!qemu_machine_creation_done(errp)) {
2755         return;
2756     }
2757 
2758     if (loadvm) {
2759         RunState state = autostart ? RUN_STATE_RUNNING : runstate_get();
2760         load_snapshot(loadvm, NULL, false, NULL, &error_fatal);
2761         load_snapshot_resume(state);
2762     }
2763     if (replay_mode != REPLAY_MODE_NONE) {
2764         replay_vmstate_init();
2765     }
2766 
2767     if (incoming) {
2768         Error *local_err = NULL;
2769         if (strcmp(incoming, "defer") != 0) {
2770             g_autofree MigrationChannelList *channels =
2771                 g_new0(MigrationChannelList, 1);
2772 
2773             channels->value = incoming_channels[MIGRATION_CHANNEL_TYPE_MAIN];
2774             qmp_migrate_incoming(NULL, true, channels, true, true, &local_err);
2775             if (local_err) {
2776                 error_reportf_err(local_err, "-incoming %s: ", incoming);
2777                 exit(1);
2778             }
2779         }
2780     } else if (autostart) {
2781         qmp_cont(NULL);
2782     }
2783 }
2784 
2785 void qemu_init(int argc, char **argv)
2786 {
2787     QemuOpts *opts;
2788     QemuOpts *icount_opts = NULL, *accel_opts = NULL;
2789     QemuOptsList *olist;
2790     int optind;
2791     const char *optarg;
2792     MachineClass *machine_class;
2793     bool userconfig = true;
2794     FILE *vmstate_dump_file = NULL;
2795 
2796     qemu_add_opts(&qemu_drive_opts);
2797     qemu_add_drive_opts(&qemu_legacy_drive_opts);
2798     qemu_add_drive_opts(&qemu_common_drive_opts);
2799     qemu_add_drive_opts(&qemu_drive_opts);
2800     qemu_add_drive_opts(&bdrv_runtime_opts);
2801     qemu_add_opts(&qemu_chardev_opts);
2802     qemu_add_opts(&qemu_device_opts);
2803     qemu_add_opts(&qemu_netdev_opts);
2804     qemu_add_opts(&qemu_nic_opts);
2805     qemu_add_opts(&qemu_net_opts);
2806     qemu_add_opts(&qemu_rtc_opts);
2807     qemu_add_opts(&qemu_global_opts);
2808     qemu_add_opts(&qemu_mon_opts);
2809     qemu_add_opts(&qemu_trace_opts);
2810     qemu_plugin_add_opts();
2811     qemu_add_opts(&qemu_option_rom_opts);
2812     qemu_add_opts(&qemu_accel_opts);
2813     qemu_add_opts(&qemu_mem_opts);
2814     qemu_add_opts(&qemu_smp_opts);
2815     qemu_add_opts(&qemu_boot_opts);
2816     qemu_add_opts(&qemu_add_fd_opts);
2817     qemu_add_opts(&qemu_object_opts);
2818     qemu_add_opts(&qemu_tpmdev_opts);
2819     qemu_add_opts(&qemu_overcommit_opts);
2820     qemu_add_opts(&qemu_msg_opts);
2821     qemu_add_opts(&qemu_name_opts);
2822     qemu_add_opts(&qemu_numa_opts);
2823     qemu_add_opts(&qemu_icount_opts);
2824     qemu_add_opts(&qemu_semihosting_config_opts);
2825     qemu_add_opts(&qemu_fw_cfg_opts);
2826     qemu_add_opts(&qemu_action_opts);
2827     qemu_add_run_with_opts();
2828     module_call_init(MODULE_INIT_OPTS);
2829 
2830     error_init(argv[0]);
2831     qemu_init_exec_dir(argv[0]);
2832 
2833     os_setup_limits();
2834 
2835     qemu_init_arch_modules();
2836 
2837     qemu_init_subsystems();
2838 
2839     /* first pass of option parsing */
2840     optind = 1;
2841     while (optind < argc) {
2842         if (argv[optind][0] != '-') {
2843             /* disk image */
2844             optind++;
2845         } else {
2846             const QEMUOption *popt;
2847 
2848             popt = lookup_opt(argc, argv, &optarg, &optind);
2849             switch (popt->index) {
2850             case QEMU_OPTION_nouserconfig:
2851                 userconfig = false;
2852                 break;
2853             }
2854         }
2855     }
2856 
2857     machine_opts_dict = qdict_new();
2858     if (userconfig) {
2859         qemu_read_default_config_file(&error_fatal);
2860     }
2861 
2862     /* second pass of option parsing */
2863     optind = 1;
2864     for(;;) {
2865         if (optind >= argc)
2866             break;
2867         if (argv[optind][0] != '-') {
2868             loc_set_cmdline(argv, optind, 1);
2869             drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
2870         } else {
2871             const QEMUOption *popt;
2872 
2873             popt = lookup_opt(argc, argv, &optarg, &optind);
2874             if (!(popt->arch_mask & arch_type)) {
2875                 error_report("Option not supported for this target");
2876                 exit(1);
2877             }
2878             switch(popt->index) {
2879             case QEMU_OPTION_cpu:
2880                 /* hw initialization will check this */
2881                 cpu_option = optarg;
2882                 break;
2883             case QEMU_OPTION_hda:
2884             case QEMU_OPTION_hdb:
2885             case QEMU_OPTION_hdc:
2886             case QEMU_OPTION_hdd:
2887                 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
2888                           HD_OPTS);
2889                 break;
2890             case QEMU_OPTION_blockdev:
2891                 {
2892                     Visitor *v;
2893                     BlockdevOptionsQueueEntry *bdo;
2894 
2895                     v = qobject_input_visitor_new_str(optarg, "driver",
2896                                                       &error_fatal);
2897 
2898                     bdo = g_new(BlockdevOptionsQueueEntry, 1);
2899                     visit_type_BlockdevOptions(v, NULL, &bdo->bdo,
2900                                                &error_fatal);
2901                     visit_free(v);
2902                     loc_save(&bdo->loc);
2903                     QSIMPLEQ_INSERT_TAIL(&bdo_queue, bdo, entry);
2904                     break;
2905                 }
2906             case QEMU_OPTION_drive:
2907                 opts = qemu_opts_parse_noisily(qemu_find_opts("drive"),
2908                                                optarg, false);
2909                 if (opts == NULL) {
2910                     exit(1);
2911                 }
2912                 break;
2913             case QEMU_OPTION_set:
2914                 qemu_set_option(optarg, &error_fatal);
2915                 break;
2916             case QEMU_OPTION_global:
2917                 if (qemu_global_option(optarg) != 0)
2918                     exit(1);
2919                 break;
2920             case QEMU_OPTION_mtdblock:
2921                 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
2922                 break;
2923             case QEMU_OPTION_sd:
2924                 drive_add(IF_SD, -1, optarg, SD_OPTS);
2925                 break;
2926             case QEMU_OPTION_pflash:
2927                 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
2928                 break;
2929             case QEMU_OPTION_snapshot:
2930                 snapshot = 1;
2931                 replay_add_blocker("-snapshot");
2932                 break;
2933             case QEMU_OPTION_numa:
2934                 opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
2935                                                optarg, true);
2936                 if (!opts) {
2937                     exit(1);
2938                 }
2939                 break;
2940             case QEMU_OPTION_display:
2941                 parse_display(optarg);
2942                 break;
2943             case QEMU_OPTION_nographic:
2944                 qdict_put_str(machine_opts_dict, "graphics", "off");
2945                 nographic = true;
2946                 dpy.type = DISPLAY_TYPE_NONE;
2947                 break;
2948             case QEMU_OPTION_kernel:
2949                 qdict_put_str(machine_opts_dict, "kernel", optarg);
2950                 break;
2951             case QEMU_OPTION_shim:
2952                 qdict_put_str(machine_opts_dict, "shim", optarg);
2953                 break;
2954             case QEMU_OPTION_initrd:
2955                 qdict_put_str(machine_opts_dict, "initrd", optarg);
2956                 break;
2957             case QEMU_OPTION_append:
2958                 qdict_put_str(machine_opts_dict, "append", optarg);
2959                 break;
2960             case QEMU_OPTION_dtb:
2961                 qdict_put_str(machine_opts_dict, "dtb", optarg);
2962                 break;
2963             case QEMU_OPTION_cdrom:
2964                 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
2965                 break;
2966             case QEMU_OPTION_boot:
2967                 machine_parse_property_opt(qemu_find_opts("boot-opts"), "boot", optarg);
2968                 break;
2969             case QEMU_OPTION_fda:
2970             case QEMU_OPTION_fdb:
2971                 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
2972                           optarg, FD_OPTS);
2973                 break;
2974             case QEMU_OPTION_no_fd_bootchk:
2975                 qdict_put_str(machine_opts_dict, "fd-bootchk", "off");
2976                 break;
2977             case QEMU_OPTION_netdev:
2978                 default_net = 0;
2979                 if (netdev_is_modern(optarg)) {
2980                     netdev_parse_modern(optarg);
2981                 } else {
2982                     net_client_parse(qemu_find_opts("netdev"), optarg);
2983                 }
2984                 break;
2985             case QEMU_OPTION_nic:
2986                 default_net = 0;
2987                 net_client_parse(qemu_find_opts("nic"), optarg);
2988                 break;
2989             case QEMU_OPTION_net:
2990                 default_net = 0;
2991                 net_client_parse(qemu_find_opts("net"), optarg);
2992                 break;
2993 #ifdef CONFIG_LIBISCSI
2994             case QEMU_OPTION_iscsi:
2995                 opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
2996                                                optarg, false);
2997                 if (!opts) {
2998                     exit(1);
2999                 }
3000                 break;
3001 #endif
3002             case QEMU_OPTION_audiodev:
3003                 default_audio = 0;
3004                 audio_parse_option(optarg);
3005                 break;
3006             case QEMU_OPTION_audio: {
3007                 bool help;
3008                 char *model = NULL;
3009                 Audiodev *dev = NULL;
3010                 Visitor *v;
3011                 QDict *dict = keyval_parse(optarg, "driver", &help, &error_fatal);
3012                 default_audio = 0;
3013                 if (help || (qdict_haskey(dict, "driver") &&
3014                              is_help_option(qdict_get_str(dict, "driver")))) {
3015                     audio_help();
3016                     exit(EXIT_SUCCESS);
3017                 }
3018                 if (!qdict_haskey(dict, "id")) {
3019                     qdict_put_str(dict, "id", "audiodev0");
3020                 }
3021                 if (qdict_haskey(dict, "model")) {
3022                     model = g_strdup(qdict_get_str(dict, "model"));
3023                     qdict_del(dict, "model");
3024                     if (is_help_option(model)) {
3025                         show_valid_soundhw();
3026                         exit(0);
3027                     }
3028                 }
3029                 v = qobject_input_visitor_new_keyval(QOBJECT(dict));
3030                 qobject_unref(dict);
3031                 visit_type_Audiodev(v, NULL, &dev, &error_fatal);
3032                 visit_free(v);
3033                 if (model) {
3034                     audio_define(dev);
3035                     select_soundhw(model, dev->id);
3036                     g_free(model);
3037                 } else {
3038                     audio_define_default(dev, &error_fatal);
3039                 }
3040                 break;
3041             }
3042             case QEMU_OPTION_h:
3043                 help(0);
3044                 break;
3045             case QEMU_OPTION_version:
3046                 version();
3047                 exit(0);
3048                 break;
3049             case QEMU_OPTION_m:
3050                 opts = qemu_opts_parse_noisily(qemu_find_opts("memory"), optarg, true);
3051                 if (opts == NULL) {
3052                     exit(1);
3053                 }
3054                 break;
3055 #ifdef CONFIG_TPM
3056             case QEMU_OPTION_tpmdev:
3057                 if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3058                     exit(1);
3059                 }
3060                 break;
3061 #endif
3062             case QEMU_OPTION_mempath:
3063                 mem_path = optarg;
3064                 break;
3065             case QEMU_OPTION_mem_prealloc:
3066                 mem_prealloc = 1;
3067                 break;
3068             case QEMU_OPTION_d:
3069                 log_mask = optarg;
3070                 break;
3071             case QEMU_OPTION_D:
3072                 log_file = optarg;
3073                 break;
3074             case QEMU_OPTION_DFILTER:
3075                 qemu_set_dfilter_ranges(optarg, &error_fatal);
3076                 break;
3077 #if defined(CONFIG_TCG) && defined(CONFIG_LINUX)
3078             case QEMU_OPTION_perfmap:
3079                 perf_enable_perfmap();
3080                 break;
3081             case QEMU_OPTION_jitdump:
3082                 perf_enable_jitdump();
3083                 break;
3084 #endif
3085             case QEMU_OPTION_seed:
3086                 qemu_guest_random_seed_main(optarg, &error_fatal);
3087                 break;
3088             case QEMU_OPTION_s:
3089                 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3090                 break;
3091             case QEMU_OPTION_gdb:
3092                 add_device_config(DEV_GDB, optarg);
3093                 break;
3094             case QEMU_OPTION_L:
3095                 if (is_help_option(optarg)) {
3096                     list_data_dirs = true;
3097                 } else {
3098                     qemu_add_data_dir(g_strdup(optarg));
3099                 }
3100                 break;
3101             case QEMU_OPTION_bios:
3102                 qdict_put_str(machine_opts_dict, "firmware", optarg);
3103                 break;
3104             case QEMU_OPTION_S:
3105                 autostart = 0;
3106                 break;
3107             case QEMU_OPTION_k:
3108                 keyboard_layout = optarg;
3109                 break;
3110             case QEMU_OPTION_vga:
3111                 vga_model = optarg;
3112                 default_vga = 0;
3113                 break;
3114             case QEMU_OPTION_g:
3115                 {
3116                     const char *p;
3117                     int w, h, depth;
3118                     p = optarg;
3119                     w = strtol(p, (char **)&p, 10);
3120                     if (w <= 0) {
3121                     graphic_error:
3122                         error_report("invalid resolution or depth");
3123                         exit(1);
3124                     }
3125                     if (*p != 'x')
3126                         goto graphic_error;
3127                     p++;
3128                     h = strtol(p, (char **)&p, 10);
3129                     if (h <= 0)
3130                         goto graphic_error;
3131                     if (*p == 'x') {
3132                         p++;
3133                         depth = strtol(p, (char **)&p, 10);
3134                         if (depth != 1 && depth != 2 && depth != 4 &&
3135                             depth != 8 && depth != 15 && depth != 16 &&
3136                             depth != 24 && depth != 32)
3137                             goto graphic_error;
3138                     } else if (*p == '\0') {
3139                         depth = graphic_depth;
3140                     } else {
3141                         goto graphic_error;
3142                     }
3143 
3144                     graphic_width = w;
3145                     graphic_height = h;
3146                     graphic_depth = depth;
3147                 }
3148                 break;
3149             case QEMU_OPTION_echr:
3150                 {
3151                     char *r;
3152                     term_escape_char = strtol(optarg, &r, 0);
3153                     if (r == optarg)
3154                         printf("Bad argument to echr\n");
3155                     break;
3156                 }
3157             case QEMU_OPTION_monitor:
3158                 default_monitor = 0;
3159                 if (strncmp(optarg, "none", 4)) {
3160                     monitor_parse(optarg, "readline", false);
3161                 }
3162                 break;
3163             case QEMU_OPTION_qmp:
3164                 monitor_parse(optarg, "control", false);
3165                 default_monitor = 0;
3166                 break;
3167             case QEMU_OPTION_qmp_pretty:
3168                 monitor_parse(optarg, "control", true);
3169                 default_monitor = 0;
3170                 break;
3171             case QEMU_OPTION_mon:
3172                 opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
3173                                                true);
3174                 if (!opts) {
3175                     exit(1);
3176                 }
3177                 default_monitor = 0;
3178                 break;
3179             case QEMU_OPTION_chardev:
3180                 opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
3181                                                optarg, true);
3182                 if (!opts) {
3183                     exit(1);
3184                 }
3185                 break;
3186             case QEMU_OPTION_fsdev:
3187                 olist = qemu_find_opts("fsdev");
3188                 if (!olist) {
3189                     error_report("fsdev support is disabled");
3190                     exit(1);
3191                 }
3192                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3193                 if (!opts) {
3194                     exit(1);
3195                 }
3196                 break;
3197             case QEMU_OPTION_virtfs: {
3198                 QemuOpts *fsdev;
3199                 QemuOpts *device;
3200                 const char *writeout, *sock_fd, *socket, *path, *security_model,
3201                            *multidevs;
3202 
3203                 olist = qemu_find_opts("virtfs");
3204                 if (!olist) {
3205                     error_report("virtfs support is disabled");
3206                     exit(1);
3207                 }
3208                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3209                 if (!opts) {
3210                     exit(1);
3211                 }
3212 
3213                 if (qemu_opt_get(opts, "fsdriver") == NULL ||
3214                     qemu_opt_get(opts, "mount_tag") == NULL) {
3215                     error_report("Usage: -virtfs fsdriver,mount_tag=tag");
3216                     exit(1);
3217                 }
3218                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3219                                          qemu_opts_id(opts) ?:
3220                                          qemu_opt_get(opts, "mount_tag"),
3221                                          1, NULL);
3222                 if (!fsdev) {
3223                     error_report("duplicate or invalid fsdev id: %s",
3224                                  qemu_opt_get(opts, "mount_tag"));
3225                     exit(1);
3226                 }
3227 
3228                 writeout = qemu_opt_get(opts, "writeout");
3229                 if (writeout) {
3230 #ifdef CONFIG_SYNC_FILE_RANGE
3231                     qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
3232 #else
3233                     error_report("writeout=immediate not supported "
3234                                  "on this platform");
3235                     exit(1);
3236 #endif
3237                 }
3238                 qemu_opt_set(fsdev, "fsdriver",
3239                              qemu_opt_get(opts, "fsdriver"), &error_abort);
3240                 path = qemu_opt_get(opts, "path");
3241                 if (path) {
3242                     qemu_opt_set(fsdev, "path", path, &error_abort);
3243                 }
3244                 security_model = qemu_opt_get(opts, "security_model");
3245                 if (security_model) {
3246                     qemu_opt_set(fsdev, "security_model", security_model,
3247                                  &error_abort);
3248                 }
3249                 socket = qemu_opt_get(opts, "socket");
3250                 if (socket) {
3251                     qemu_opt_set(fsdev, "socket", socket, &error_abort);
3252                 }
3253                 sock_fd = qemu_opt_get(opts, "sock_fd");
3254                 if (sock_fd) {
3255                     qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
3256                 }
3257 
3258                 qemu_opt_set_bool(fsdev, "readonly",
3259                                   qemu_opt_get_bool(opts, "readonly", 0),
3260                                   &error_abort);
3261                 multidevs = qemu_opt_get(opts, "multidevs");
3262                 if (multidevs) {
3263                     qemu_opt_set(fsdev, "multidevs", multidevs, &error_abort);
3264                 }
3265                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3266                                           &error_abort);
3267                 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
3268                 qemu_opt_set(device, "fsdev",
3269                              qemu_opts_id(fsdev), &error_abort);
3270                 qemu_opt_set(device, "mount_tag",
3271                              qemu_opt_get(opts, "mount_tag"), &error_abort);
3272                 break;
3273             }
3274             case QEMU_OPTION_serial:
3275                 add_device_config(DEV_SERIAL, optarg);
3276                 default_serial = 0;
3277                 if (strncmp(optarg, "mon:", 4) == 0) {
3278                     default_monitor = 0;
3279                 }
3280                 break;
3281             case QEMU_OPTION_action:
3282                 olist = qemu_find_opts("action");
3283                 if (!qemu_opts_parse_noisily(olist, optarg, false)) {
3284                      exit(1);
3285                 }
3286                 break;
3287             case QEMU_OPTION_watchdog_action: {
3288                 opts = qemu_opts_create(qemu_find_opts("action"), NULL, 0, &error_abort);
3289                 qemu_opt_set(opts, "watchdog", optarg, &error_abort);
3290                 break;
3291             }
3292             case QEMU_OPTION_parallel:
3293                 add_device_config(DEV_PARALLEL, optarg);
3294                 default_parallel = 0;
3295                 if (strncmp(optarg, "mon:", 4) == 0) {
3296                     default_monitor = 0;
3297                 }
3298                 break;
3299             case QEMU_OPTION_debugcon:
3300                 add_device_config(DEV_DEBUGCON, optarg);
3301                 break;
3302             case QEMU_OPTION_loadvm:
3303                 loadvm = optarg;
3304                 break;
3305             case QEMU_OPTION_full_screen:
3306                 dpy.has_full_screen = true;
3307                 dpy.full_screen = true;
3308                 break;
3309             case QEMU_OPTION_pidfile:
3310                 pid_file = optarg;
3311                 break;
3312             case QEMU_OPTION_win2k_hack:
3313                 object_register_sugar_prop("ide-device", "win2k-install-hack", "true", true);
3314                 break;
3315             case QEMU_OPTION_acpitable:
3316                 opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
3317                                                optarg, true);
3318                 if (!opts) {
3319                     exit(1);
3320                 }
3321                 acpi_table_add(opts, &error_fatal);
3322                 break;
3323             case QEMU_OPTION_smbios:
3324                 opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
3325                                                optarg, false);
3326                 if (!opts) {
3327                     exit(1);
3328                 }
3329                 smbios_entry_add(opts, &error_fatal);
3330                 break;
3331             case QEMU_OPTION_fwcfg:
3332                 opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
3333                                                optarg, true);
3334                 if (opts == NULL) {
3335                     exit(1);
3336                 }
3337                 break;
3338             case QEMU_OPTION_preconfig:
3339                 preconfig_requested = true;
3340                 break;
3341             case QEMU_OPTION_enable_kvm:
3342                 qdict_put_str(machine_opts_dict, "accel", "kvm");
3343                 break;
3344             case QEMU_OPTION_M:
3345             case QEMU_OPTION_machine:
3346                 {
3347                     bool help;
3348 
3349                     keyval_parse_into(machine_opts_dict, optarg, "type", &help, &error_fatal);
3350                     if (help) {
3351                         machine_help_func(machine_opts_dict);
3352                         exit(EXIT_SUCCESS);
3353                     }
3354                     break;
3355                 }
3356             case QEMU_OPTION_accel:
3357                 accel_opts = qemu_opts_parse_noisily(qemu_find_opts("accel"),
3358                                                      optarg, true);
3359                 optarg = qemu_opt_get(accel_opts, "accel");
3360                 if (!optarg || is_help_option(optarg)) {
3361                     printf("Accelerators supported in QEMU binary:\n");
3362                     GSList *el, *accel_list = object_class_get_list(TYPE_ACCEL,
3363                                                                     false);
3364                     for (el = accel_list; el; el = el->next) {
3365                         gchar *typename = g_strdup(object_class_get_name(
3366                                                    OBJECT_CLASS(el->data)));
3367                         /* omit qtest which is used for tests only */
3368                         if (g_strcmp0(typename, ACCEL_CLASS_NAME("qtest")) &&
3369                             g_str_has_suffix(typename, ACCEL_CLASS_SUFFIX)) {
3370                             gchar **optname = g_strsplit(typename,
3371                                                          ACCEL_CLASS_SUFFIX, 0);
3372                             printf("%s\n", optname[0]);
3373                             g_strfreev(optname);
3374                         }
3375                         g_free(typename);
3376                     }
3377                     g_slist_free(accel_list);
3378                     exit(0);
3379                 }
3380                 break;
3381             case QEMU_OPTION_usb:
3382                 qdict_put_str(machine_opts_dict, "usb", "on");
3383                 break;
3384             case QEMU_OPTION_usbdevice:
3385                 qdict_put_str(machine_opts_dict, "usb", "on");
3386                 add_device_config(DEV_USB, optarg);
3387                 break;
3388             case QEMU_OPTION_device:
3389                 if (optarg[0] == '{') {
3390                     QObject *obj = qobject_from_json(optarg, &error_fatal);
3391                     DeviceOption *opt = g_new0(DeviceOption, 1);
3392                     opt->opts = qobject_to(QDict, obj);
3393                     loc_save(&opt->loc);
3394                     assert(opt->opts != NULL);
3395                     QTAILQ_INSERT_TAIL(&device_opts, opt, next);
3396                 } else {
3397                     if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
3398                                                  optarg, true)) {
3399                         exit(1);
3400                     }
3401                 }
3402                 break;
3403             case QEMU_OPTION_smp:
3404                 machine_parse_property_opt(qemu_find_opts("smp-opts"),
3405                                            "smp", optarg);
3406                 break;
3407 #ifdef CONFIG_VNC
3408             case QEMU_OPTION_vnc:
3409                 vnc_parse(optarg);
3410                 display_remote++;
3411                 break;
3412 #endif
3413             case QEMU_OPTION_no_reboot:
3414                 olist = qemu_find_opts("action");
3415                 qemu_opts_parse_noisily(olist, "reboot=shutdown", false);
3416                 break;
3417             case QEMU_OPTION_no_shutdown:
3418                 olist = qemu_find_opts("action");
3419                 qemu_opts_parse_noisily(olist, "shutdown=pause", false);
3420                 break;
3421             case QEMU_OPTION_uuid:
3422                 if (qemu_uuid_parse(optarg, &qemu_uuid) < 0) {
3423                     error_report("failed to parse UUID string: wrong format");
3424                     exit(1);
3425                 }
3426                 qemu_uuid_set = true;
3427                 break;
3428             case QEMU_OPTION_option_rom:
3429                 if (nb_option_roms >= MAX_OPTION_ROMS) {
3430                     error_report("too many option ROMs");
3431                     exit(1);
3432                 }
3433                 opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
3434                                                optarg, true);
3435                 if (!opts) {
3436                     exit(1);
3437                 }
3438                 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3439                 option_rom[nb_option_roms].bootindex =
3440                     qemu_opt_get_number(opts, "bootindex", -1);
3441                 if (!option_rom[nb_option_roms].name) {
3442                     error_report("Option ROM file is not specified");
3443                     exit(1);
3444                 }
3445                 nb_option_roms++;
3446                 break;
3447             case QEMU_OPTION_semihosting:
3448                 qemu_semihosting_enable();
3449                 break;
3450             case QEMU_OPTION_semihosting_config:
3451                 if (qemu_semihosting_config_options(optarg) != 0) {
3452                     exit(1);
3453                 }
3454                 break;
3455             case QEMU_OPTION_name:
3456                 opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
3457                                                optarg, true);
3458                 if (!opts) {
3459                     exit(1);
3460                 }
3461                 /* Capture guest name if -msg guest-name is used later */
3462                 error_guest_name = qemu_opt_get(opts, "guest");
3463                 break;
3464             case QEMU_OPTION_prom_env:
3465                 if (nb_prom_envs >= MAX_PROM_ENVS) {
3466                     error_report("too many prom variables");
3467                     exit(1);
3468                 }
3469                 prom_envs[nb_prom_envs] = optarg;
3470                 nb_prom_envs++;
3471                 break;
3472             case QEMU_OPTION_old_param:
3473                 warn_report("-old-param is deprecated");
3474                 old_param = 1;
3475                 break;
3476             case QEMU_OPTION_rtc:
3477                 opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
3478                                                false);
3479                 if (!opts) {
3480                     exit(1);
3481                 }
3482                 break;
3483             case QEMU_OPTION_icount:
3484                 icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
3485                                                       optarg, true);
3486                 if (!icount_opts) {
3487                     exit(1);
3488                 }
3489                 break;
3490             case QEMU_OPTION_incoming:
3491                 if (!incoming) {
3492                     runstate_set(RUN_STATE_INMIGRATE);
3493                 }
3494                 incoming_option_parse(optarg);
3495                 break;
3496             case QEMU_OPTION_only_migratable:
3497                 only_migratable = 1;
3498                 break;
3499             case QEMU_OPTION_nodefaults:
3500                 has_defaults = 0;
3501                 break;
3502             case QEMU_OPTION_xen_domid:
3503                 if (!(accel_find("xen")) && !(accel_find("kvm"))) {
3504                     error_report("Option not supported for this target");
3505                     exit(1);
3506                 }
3507                 xen_domid = atoi(optarg);
3508                 break;
3509             case QEMU_OPTION_xen_attach:
3510                 if (!(accel_find("xen"))) {
3511                     error_report("Option not supported for this target");
3512                     exit(1);
3513                 }
3514                 xen_mode = XEN_ATTACH;
3515                 break;
3516             case QEMU_OPTION_xen_domid_restrict:
3517                 if (!(accel_find("xen"))) {
3518                     error_report("Option not supported for this target");
3519                     exit(1);
3520                 }
3521                 xen_domid_restrict = true;
3522                 break;
3523             case QEMU_OPTION_trace:
3524                 trace_opt_parse(optarg);
3525                 break;
3526             case QEMU_OPTION_plugin:
3527                 qemu_plugin_opt_parse(optarg, &plugin_list);
3528                 break;
3529             case QEMU_OPTION_readconfig:
3530                 qemu_read_config_file(optarg, qemu_parse_config_group, &error_fatal);
3531                 break;
3532 #ifdef CONFIG_SPICE
3533             case QEMU_OPTION_spice:
3534                 opts = qemu_opts_parse_noisily(qemu_find_opts("spice"), optarg, false);
3535                 if (!opts) {
3536                     exit(1);
3537                 }
3538                 display_remote++;
3539                 break;
3540 #endif
3541             case QEMU_OPTION_qtest:
3542                 qtest_chrdev = optarg;
3543                 break;
3544             case QEMU_OPTION_qtest_log:
3545                 qtest_log = optarg;
3546                 break;
3547             case QEMU_OPTION_sandbox:
3548                 olist = qemu_find_opts("sandbox");
3549                 if (!olist) {
3550 #ifndef CONFIG_SECCOMP
3551                     error_report("-sandbox support is not enabled "
3552                                  "in this QEMU binary");
3553 #endif
3554                     exit(1);
3555                 }
3556 
3557                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3558                 if (!opts) {
3559                     exit(1);
3560                 }
3561                 break;
3562             case QEMU_OPTION_add_fd:
3563 #ifndef _WIN32
3564                 opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
3565                                                optarg, false);
3566                 if (!opts) {
3567                     exit(1);
3568                 }
3569 #else
3570                 error_report("File descriptor passing is disabled on this "
3571                              "platform");
3572                 exit(1);
3573 #endif
3574                 break;
3575             case QEMU_OPTION_object:
3576                 object_option_parse(optarg);
3577                 break;
3578             case QEMU_OPTION_overcommit:
3579                 opts = qemu_opts_parse_noisily(qemu_find_opts("overcommit"),
3580                                                optarg, false);
3581                 if (!opts) {
3582                     exit(1);
3583                 }
3584                 enable_mlock = qemu_opt_get_bool(opts, "mem-lock", enable_mlock);
3585                 enable_cpu_pm = qemu_opt_get_bool(opts, "cpu-pm", enable_cpu_pm);
3586                 break;
3587             case QEMU_OPTION_compat:
3588                 {
3589                     CompatPolicy *opts_policy;
3590                     Visitor *v;
3591 
3592                     v = qobject_input_visitor_new_str(optarg, NULL,
3593                                                       &error_fatal);
3594 
3595                     visit_type_CompatPolicy(v, NULL, &opts_policy, &error_fatal);
3596                     QAPI_CLONE_MEMBERS(CompatPolicy, &compat_policy, opts_policy);
3597 
3598                     qapi_free_CompatPolicy(opts_policy);
3599                     visit_free(v);
3600                     break;
3601                 }
3602             case QEMU_OPTION_msg:
3603                 opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
3604                                                false);
3605                 if (!opts) {
3606                     exit(1);
3607                 }
3608                 configure_msg(opts);
3609                 break;
3610             case QEMU_OPTION_dump_vmstate:
3611                 if (vmstate_dump_file) {
3612                     error_report("only one '-dump-vmstate' "
3613                                  "option may be given");
3614                     exit(1);
3615                 }
3616                 vmstate_dump_file = fopen(optarg, "w");
3617                 if (vmstate_dump_file == NULL) {
3618                     error_report("open %s: %s", optarg, strerror(errno));
3619                     exit(1);
3620                 }
3621                 break;
3622             case QEMU_OPTION_enable_sync_profile:
3623                 qsp_enable();
3624                 break;
3625             case QEMU_OPTION_nouserconfig:
3626                 /* Nothing to be parsed here. Especially, do not error out below. */
3627                 break;
3628 #if defined(CONFIG_POSIX)
3629             case QEMU_OPTION_daemonize:
3630                 os_set_daemonize(true);
3631                 break;
3632             case QEMU_OPTION_run_with: {
3633                 const char *str;
3634                 opts = qemu_opts_parse_noisily(qemu_find_opts("run-with"),
3635                                                          optarg, false);
3636                 if (!opts) {
3637                     exit(1);
3638                 }
3639 #if defined(CONFIG_LINUX)
3640                 if (qemu_opt_get_bool(opts, "async-teardown", false)) {
3641                     init_async_teardown();
3642                 }
3643 #endif
3644                 str = qemu_opt_get(opts, "chroot");
3645                 if (str) {
3646                     os_set_chroot(str);
3647                 }
3648                 str = qemu_opt_get(opts, "user");
3649                 if (str) {
3650                     if (!os_set_runas(str)) {
3651                         error_report("User \"%s\" doesn't exist"
3652                                      " (and is not <uid>:<gid>)",
3653                                      optarg);
3654                         exit(1);
3655                     }
3656                 }
3657 
3658                 break;
3659             }
3660 #endif /* CONFIG_POSIX */
3661 
3662             default:
3663                 error_report("Option not supported in this build");
3664                 exit(1);
3665             }
3666         }
3667     }
3668     /*
3669      * Clear error location left behind by the loop.
3670      * Best done right after the loop.  Do not insert code here!
3671      */
3672     loc_set_none();
3673 
3674     qemu_validate_options(machine_opts_dict);
3675     qemu_process_sugar_options();
3676 
3677     /*
3678      * These options affect everything else and should be processed
3679      * before daemonizing.
3680      */
3681     qemu_process_early_options();
3682 
3683     qemu_process_help_options();
3684     qemu_maybe_daemonize(pid_file);
3685 
3686     /*
3687      * The trace backend must be initialized after daemonizing.
3688      * trace_init_backends() will call st_init(), which will create the
3689      * trace thread in the parent, and also register st_flush_trace_buffer()
3690      * in atexit(). This function will force the parent to wait for the
3691      * writeout thread to finish, which will not occur, and the parent
3692      * process will be left in the host.
3693      */
3694     if (!trace_init_backends()) {
3695         exit(1);
3696     }
3697     trace_init_file();
3698 
3699     qemu_init_main_loop(&error_fatal);
3700     cpu_timers_init();
3701 
3702     user_register_global_props();
3703     replay_configure(icount_opts);
3704 
3705     configure_rtc(qemu_find_opts_singleton("rtc"));
3706 
3707     /* Transfer QemuOpts options into machine options */
3708     parse_memory_options();
3709 
3710     qemu_create_machine(machine_opts_dict);
3711 
3712     /*
3713      * Load incoming CPR state before any devices are created, because it
3714      * contains file descriptors that are needed in device initialization code.
3715      */
3716     cpr_state_load(incoming_channels[MIGRATION_CHANNEL_TYPE_CPR], &error_fatal);
3717 
3718     suspend_mux_open();
3719 
3720     qemu_disable_default_devices();
3721     qemu_setup_display();
3722     qemu_create_default_devices();
3723     qemu_create_early_backends();
3724 
3725     qemu_apply_legacy_machine_options(machine_opts_dict);
3726     qemu_apply_machine_options(machine_opts_dict);
3727     qobject_unref(machine_opts_dict);
3728     phase_advance(PHASE_MACHINE_CREATED);
3729 
3730     /*
3731      * Note: uses machine properties such as kernel-irqchip, must run
3732      * after qemu_apply_machine_options.
3733      */
3734     configure_accelerators(argv[0]);
3735     phase_advance(PHASE_ACCEL_CREATED);
3736 
3737     /*
3738      * Beware, QOM objects created before this point miss global and
3739      * compat properties.
3740      *
3741      * Global properties get set up by qdev_prop_register_global(),
3742      * called from user_register_global_props(), and certain option
3743      * desugaring.  Also in CPU feature desugaring (buried in
3744      * parse_cpu_option()), which happens below this point, but may
3745      * only target the CPU type, which can only be created after
3746      * parse_cpu_option() returned the type.
3747      *
3748      * Machine compat properties: object_set_machine_compat_props().
3749      * Accelerator compat props: object_set_accelerator_compat_props(),
3750      * called from do_configure_accelerator().
3751      */
3752 
3753     machine_class = MACHINE_GET_CLASS(current_machine);
3754     if (!qtest_enabled() && machine_class->deprecation_reason) {
3755         warn_report("Machine type '%s' is deprecated: %s",
3756                      machine_class->name, machine_class->deprecation_reason);
3757     }
3758 
3759     /*
3760      * Create backends before creating migration objects, so that it can
3761      * check against compatibilities on the backend memories (e.g. postcopy
3762      * over memory-backend-file objects).
3763      */
3764     qemu_create_late_backends();
3765     phase_advance(PHASE_LATE_BACKENDS_CREATED);
3766 
3767     /*
3768      * Note: creates a QOM object, must run only after global and
3769      * compat properties have been set up.
3770      */
3771     migration_object_init();
3772 
3773     /* parse features once if machine provides default cpu_type */
3774     current_machine->cpu_type = machine_class_default_cpu_type(machine_class);
3775     if (cpu_option) {
3776         current_machine->cpu_type = parse_cpu_option(cpu_option);
3777     }
3778     /* NB: for machine none cpu_type could STILL be NULL here! */
3779 
3780     qemu_resolve_machine_memdev();
3781     parse_numa_opts(current_machine);
3782 
3783     if (vmstate_dump_file) {
3784         /* dump and exit */
3785         module_load_qom_all();
3786         dump_vmstate_json_to_file(vmstate_dump_file);
3787         exit(0);
3788     }
3789 
3790     if (!preconfig_requested) {
3791         qmp_x_exit_preconfig(&error_fatal);
3792     }
3793     qemu_init_displays();
3794     accel_setup_post(current_machine);
3795     os_setup_post();
3796     resume_mux_open();
3797 }
3798