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