]> Git Repo - qemu.git/blob - softmmu/vl.c
6a2972938d0b01040fc2b7c22eb66a9b9c2a4002
[qemu.git] / softmmu / vl.c
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-common.h"
27 #include "qemu/units.h"
28 #include "hw/boards.h"
29 #include "hw/qdev-properties.h"
30 #include "qapi/error.h"
31 #include "qemu-version.h"
32 #include "qemu/cutils.h"
33 #include "qemu/help_option.h"
34 #include "qemu/uuid.h"
35 #include "sysemu/reset.h"
36 #include "sysemu/runstate.h"
37 #include "sysemu/seccomp.h"
38 #include "sysemu/tcg.h"
39 #include "sysemu/xen.h"
40
41 #include "qemu/error-report.h"
42 #include "qemu/sockets.h"
43 #include "sysemu/accel.h"
44 #include "hw/usb.h"
45 #include "hw/isa/isa.h"
46 #include "hw/scsi/scsi.h"
47 #include "hw/display/vga.h"
48 #include "sysemu/watchdog.h"
49 #include "hw/firmware/smbios.h"
50 #include "hw/acpi/acpi.h"
51 #include "hw/xen/xen.h"
52 #include "hw/loader.h"
53 #include "monitor/qdev.h"
54 #include "net/net.h"
55 #include "net/slirp.h"
56 #include "monitor/monitor.h"
57 #include "ui/console.h"
58 #include "ui/input.h"
59 #include "sysemu/sysemu.h"
60 #include "sysemu/numa.h"
61 #include "sysemu/hostmem.h"
62 #include "exec/gdbstub.h"
63 #include "qemu/timer.h"
64 #include "chardev/char.h"
65 #include "qemu/bitmap.h"
66 #include "qemu/log.h"
67 #include "sysemu/blockdev.h"
68 #include "hw/block/block.h"
69 #include "migration/misc.h"
70 #include "migration/snapshot.h"
71 #include "migration/global_state.h"
72 #include "sysemu/tpm.h"
73 #include "sysemu/dma.h"
74 #include "hw/audio/soundhw.h"
75 #include "audio/audio.h"
76 #include "sysemu/cpus.h"
77 #include "sysemu/cpu-timers.h"
78 #include "migration/colo.h"
79 #include "migration/postcopy-ram.h"
80 #include "sysemu/kvm.h"
81 #include "sysemu/hax.h"
82 #include "qapi/qobject-input-visitor.h"
83 #include "qemu/option.h"
84 #include "qemu/config-file.h"
85 #include "qemu-options.h"
86 #include "qemu/main-loop.h"
87 #ifdef CONFIG_VIRTFS
88 #include "fsdev/qemu-fsdev.h"
89 #endif
90 #include "sysemu/qtest.h"
91
92 #include "disas/disas.h"
93
94 #include "trace.h"
95 #include "trace/control.h"
96 #include "qemu/plugin.h"
97 #include "qemu/queue.h"
98 #include "sysemu/arch_init.h"
99
100 #include "ui/qemu-spice.h"
101 #include "qapi/string-input-visitor.h"
102 #include "qapi/opts-visitor.h"
103 #include "qapi/clone-visitor.h"
104 #include "qom/object_interfaces.h"
105 #include "hw/semihosting/semihost.h"
106 #include "crypto/init.h"
107 #include "sysemu/replay.h"
108 #include "qapi/qapi-events-run-state.h"
109 #include "qapi/qapi-visit-block-core.h"
110 #include "qapi/qapi-visit-ui.h"
111 #include "qapi/qapi-commands-block-core.h"
112 #include "qapi/qapi-commands-run-state.h"
113 #include "qapi/qapi-commands-ui.h"
114 #include "qapi/qmp/qerror.h"
115 #include "sysemu/iothread.h"
116 #include "qemu/guest-random.h"
117
118 #define MAX_VIRTIO_CONSOLES 1
119
120 typedef struct BlockdevOptionsQueueEntry {
121     BlockdevOptions *bdo;
122     Location loc;
123     QSIMPLEQ_ENTRY(BlockdevOptionsQueueEntry) entry;
124 } BlockdevOptionsQueueEntry;
125
126 typedef QSIMPLEQ_HEAD(, BlockdevOptionsQueueEntry) BlockdevOptionsQueue;
127
128 static const char *cpu_option;
129 static const char *data_dir[16];
130 static int data_dir_idx;
131 static const char *mem_path;
132 static const char *boot_order;
133 static const char *boot_once;
134 static const char *incoming;
135 static const char *loadvm;
136 static ram_addr_t maxram_size;
137 static uint64_t ram_slots;
138 static int display_remote;
139 static int snapshot;
140 static bool preconfig_requested;
141 static QemuPluginList plugin_list = QTAILQ_HEAD_INITIALIZER(plugin_list);
142 static BlockdevOptionsQueue bdo_queue = QSIMPLEQ_HEAD_INITIALIZER(bdo_queue);
143 static bool nographic = false;
144 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
145 static int mem_prealloc; /* force preallocation of physical target memory */
146 int display_opengl;
147 const char* keyboard_layout = NULL;
148 static ram_addr_t ram_size;
149 bool enable_mlock = false;
150 bool enable_cpu_pm = false;
151 int nb_nics;
152 NICInfo nd_table[MAX_NICS];
153 int autostart = 1;
154 static enum {
155     RTC_BASE_UTC,
156     RTC_BASE_LOCALTIME,
157     RTC_BASE_DATETIME,
158 } rtc_base_type = RTC_BASE_UTC;
159 static time_t rtc_ref_start_datetime;
160 static int rtc_realtime_clock_offset; /* used only with QEMU_CLOCK_REALTIME */
161 static int rtc_host_datetime_offset = -1; /* valid & used only with
162                                              RTC_BASE_DATETIME */
163 QEMUClockType rtc_clock;
164 int vga_interface_type = VGA_NONE;
165 static const char *vga_model = NULL;
166 static DisplayOptions dpy;
167 static int num_serial_hds;
168 static Chardev **serial_hds;
169 static const char *log_mask;
170 static const char *log_file;
171 static bool list_data_dirs;
172 Chardev *parallel_hds[MAX_PARALLEL_PORTS];
173 int win2k_install_hack = 0;
174 int singlestep = 0;
175 int fd_bootchk = 1;
176 static int no_reboot;
177 int no_shutdown = 0;
178 int graphic_rotate = 0;
179 static const char *watchdog;
180 QEMUOptionRom option_rom[MAX_OPTION_ROMS];
181 int nb_option_roms;
182 int old_param = 0;
183 const char *qemu_name;
184 int alt_grab = 0;
185 int ctrl_grab = 0;
186 unsigned int nb_prom_envs = 0;
187 const char *prom_envs[MAX_PROM_ENVS];
188 int boot_menu;
189 bool boot_strict;
190 uint8_t *boot_splash_filedata;
191 int only_migratable; /* turn it off unless user states otherwise */
192 bool wakeup_suspend_enabled;
193 int icount_align_option;
194 static const char *qtest_chrdev;
195 static const char *qtest_log;
196
197 /* The bytes in qemu_uuid are in the order specified by RFC4122, _not_ in the
198  * little-endian "wire format" described in the SMBIOS 2.6 specification.
199  */
200 QemuUUID qemu_uuid;
201 bool qemu_uuid_set;
202
203 static NotifierList exit_notifiers =
204     NOTIFIER_LIST_INITIALIZER(exit_notifiers);
205
206 static NotifierList machine_init_done_notifiers =
207     NOTIFIER_LIST_INITIALIZER(machine_init_done_notifiers);
208
209 uint32_t xen_domid;
210 enum xen_mode xen_mode = XEN_EMULATE;
211 bool xen_domid_restrict;
212
213 static int has_defaults = 1;
214 static int default_serial = 1;
215 static int default_parallel = 1;
216 static int default_monitor = 1;
217 static int default_floppy = 1;
218 static int default_cdrom = 1;
219 static int default_sdcard = 1;
220 static int default_vga = 1;
221 static int default_net = 1;
222
223 static struct {
224     const char *driver;
225     int *flag;
226 } default_list[] = {
227     { .driver = "isa-serial",           .flag = &default_serial    },
228     { .driver = "isa-parallel",         .flag = &default_parallel  },
229     { .driver = "isa-fdc",              .flag = &default_floppy    },
230     { .driver = "floppy",               .flag = &default_floppy    },
231     { .driver = "ide-cd",               .flag = &default_cdrom     },
232     { .driver = "ide-hd",               .flag = &default_cdrom     },
233     { .driver = "ide-drive",            .flag = &default_cdrom     },
234     { .driver = "scsi-cd",              .flag = &default_cdrom     },
235     { .driver = "scsi-hd",              .flag = &default_cdrom     },
236     { .driver = "VGA",                  .flag = &default_vga       },
237     { .driver = "isa-vga",              .flag = &default_vga       },
238     { .driver = "cirrus-vga",           .flag = &default_vga       },
239     { .driver = "isa-cirrus-vga",       .flag = &default_vga       },
240     { .driver = "vmware-svga",          .flag = &default_vga       },
241     { .driver = "qxl-vga",              .flag = &default_vga       },
242     { .driver = "virtio-vga",           .flag = &default_vga       },
243     { .driver = "ati-vga",              .flag = &default_vga       },
244     { .driver = "vhost-user-vga",       .flag = &default_vga       },
245 };
246
247 static QemuOptsList qemu_rtc_opts = {
248     .name = "rtc",
249     .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
250     .merge_lists = true,
251     .desc = {
252         {
253             .name = "base",
254             .type = QEMU_OPT_STRING,
255         },{
256             .name = "clock",
257             .type = QEMU_OPT_STRING,
258         },{
259             .name = "driftfix",
260             .type = QEMU_OPT_STRING,
261         },
262         { /* end of list */ }
263     },
264 };
265
266 static QemuOptsList qemu_option_rom_opts = {
267     .name = "option-rom",
268     .implied_opt_name = "romfile",
269     .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
270     .desc = {
271         {
272             .name = "bootindex",
273             .type = QEMU_OPT_NUMBER,
274         }, {
275             .name = "romfile",
276             .type = QEMU_OPT_STRING,
277         },
278         { /* end of list */ }
279     },
280 };
281
282 static QemuOptsList qemu_machine_opts = {
283     .name = "machine",
284     .implied_opt_name = "type",
285     .merge_lists = true,
286     .head = QTAILQ_HEAD_INITIALIZER(qemu_machine_opts.head),
287     .desc = {
288         /*
289          * no elements => accept any
290          * sanity checking will happen later
291          * when setting machine properties
292          */
293         { }
294     },
295 };
296
297 static QemuOptsList qemu_accel_opts = {
298     .name = "accel",
299     .implied_opt_name = "accel",
300     .head = QTAILQ_HEAD_INITIALIZER(qemu_accel_opts.head),
301     .desc = {
302         /*
303          * no elements => accept any
304          * sanity checking will happen later
305          * when setting accelerator properties
306          */
307         { }
308     },
309 };
310
311 static QemuOptsList qemu_boot_opts = {
312     .name = "boot-opts",
313     .implied_opt_name = "order",
314     .merge_lists = true,
315     .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
316     .desc = {
317         {
318             .name = "order",
319             .type = QEMU_OPT_STRING,
320         }, {
321             .name = "once",
322             .type = QEMU_OPT_STRING,
323         }, {
324             .name = "menu",
325             .type = QEMU_OPT_BOOL,
326         }, {
327             .name = "splash",
328             .type = QEMU_OPT_STRING,
329         }, {
330             .name = "splash-time",
331             .type = QEMU_OPT_NUMBER,
332         }, {
333             .name = "reboot-timeout",
334             .type = QEMU_OPT_NUMBER,
335         }, {
336             .name = "strict",
337             .type = QEMU_OPT_BOOL,
338         },
339         { /*End of list */ }
340     },
341 };
342
343 static QemuOptsList qemu_add_fd_opts = {
344     .name = "add-fd",
345     .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
346     .desc = {
347         {
348             .name = "fd",
349             .type = QEMU_OPT_NUMBER,
350             .help = "file descriptor of which a duplicate is added to fd set",
351         },{
352             .name = "set",
353             .type = QEMU_OPT_NUMBER,
354             .help = "ID of the fd set to add fd to",
355         },{
356             .name = "opaque",
357             .type = QEMU_OPT_STRING,
358             .help = "free-form string used to describe fd",
359         },
360         { /* end of list */ }
361     },
362 };
363
364 static QemuOptsList qemu_object_opts = {
365     .name = "object",
366     .implied_opt_name = "qom-type",
367     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
368     .desc = {
369         { }
370     },
371 };
372
373 static QemuOptsList qemu_tpmdev_opts = {
374     .name = "tpmdev",
375     .implied_opt_name = "type",
376     .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
377     .desc = {
378         /* options are defined in the TPM backends */
379         { /* end of list */ }
380     },
381 };
382
383 static QemuOptsList qemu_realtime_opts = {
384     .name = "realtime",
385     .head = QTAILQ_HEAD_INITIALIZER(qemu_realtime_opts.head),
386     .desc = {
387         {
388             .name = "mlock",
389             .type = QEMU_OPT_BOOL,
390         },
391         { /* end of list */ }
392     },
393 };
394
395 static QemuOptsList qemu_overcommit_opts = {
396     .name = "overcommit",
397     .head = QTAILQ_HEAD_INITIALIZER(qemu_overcommit_opts.head),
398     .desc = {
399         {
400             .name = "mem-lock",
401             .type = QEMU_OPT_BOOL,
402         },
403         {
404             .name = "cpu-pm",
405             .type = QEMU_OPT_BOOL,
406         },
407         { /* end of list */ }
408     },
409 };
410
411 static QemuOptsList qemu_msg_opts = {
412     .name = "msg",
413     .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
414     .desc = {
415         {
416             .name = "timestamp",
417             .type = QEMU_OPT_BOOL,
418         },
419         {
420             .name = "guest-name",
421             .type = QEMU_OPT_BOOL,
422             .help = "Prepends guest name for error messages but only if "
423                     "-name guest is set otherwise option is ignored\n",
424         },
425         { /* end of list */ }
426     },
427 };
428
429 static QemuOptsList qemu_name_opts = {
430     .name = "name",
431     .implied_opt_name = "guest",
432     .merge_lists = true,
433     .head = QTAILQ_HEAD_INITIALIZER(qemu_name_opts.head),
434     .desc = {
435         {
436             .name = "guest",
437             .type = QEMU_OPT_STRING,
438             .help = "Sets the name of the guest.\n"
439                     "This name will be displayed in the SDL window caption.\n"
440                     "The name will also be used for the VNC server",
441         }, {
442             .name = "process",
443             .type = QEMU_OPT_STRING,
444             .help = "Sets the name of the QEMU process, as shown in top etc",
445         }, {
446             .name = "debug-threads",
447             .type = QEMU_OPT_BOOL,
448             .help = "When enabled, name the individual threads; defaults off.\n"
449                     "NOTE: The thread names are for debugging and not a\n"
450                     "stable API.",
451         },
452         { /* End of list */ }
453     },
454 };
455
456 static QemuOptsList qemu_mem_opts = {
457     .name = "memory",
458     .implied_opt_name = "size",
459     .head = QTAILQ_HEAD_INITIALIZER(qemu_mem_opts.head),
460     .merge_lists = true,
461     .desc = {
462         {
463             .name = "size",
464             .type = QEMU_OPT_SIZE,
465         },
466         {
467             .name = "slots",
468             .type = QEMU_OPT_NUMBER,
469         },
470         {
471             .name = "maxmem",
472             .type = QEMU_OPT_SIZE,
473         },
474         { /* end of list */ }
475     },
476 };
477
478 static QemuOptsList qemu_icount_opts = {
479     .name = "icount",
480     .implied_opt_name = "shift",
481     .merge_lists = true,
482     .head = QTAILQ_HEAD_INITIALIZER(qemu_icount_opts.head),
483     .desc = {
484         {
485             .name = "shift",
486             .type = QEMU_OPT_STRING,
487         }, {
488             .name = "align",
489             .type = QEMU_OPT_BOOL,
490         }, {
491             .name = "sleep",
492             .type = QEMU_OPT_BOOL,
493         }, {
494             .name = "rr",
495             .type = QEMU_OPT_STRING,
496         }, {
497             .name = "rrfile",
498             .type = QEMU_OPT_STRING,
499         }, {
500             .name = "rrsnapshot",
501             .type = QEMU_OPT_STRING,
502         },
503         { /* end of list */ }
504     },
505 };
506
507 static QemuOptsList qemu_fw_cfg_opts = {
508     .name = "fw_cfg",
509     .implied_opt_name = "name",
510     .head = QTAILQ_HEAD_INITIALIZER(qemu_fw_cfg_opts.head),
511     .desc = {
512         {
513             .name = "name",
514             .type = QEMU_OPT_STRING,
515             .help = "Sets the fw_cfg name of the blob to be inserted",
516         }, {
517             .name = "file",
518             .type = QEMU_OPT_STRING,
519             .help = "Sets the name of the file from which "
520                     "the fw_cfg blob will be loaded",
521         }, {
522             .name = "string",
523             .type = QEMU_OPT_STRING,
524             .help = "Sets content of the blob to be inserted from a string",
525         }, {
526             .name = "gen_id",
527             .type = QEMU_OPT_STRING,
528             .help = "Sets id of the object generating the fw_cfg blob "
529                     "to be inserted",
530         },
531         { /* end of list */ }
532     },
533 };
534
535 /**
536  * Get machine options
537  *
538  * Returns: machine options (never null).
539  */
540 QemuOpts *qemu_get_machine_opts(void)
541 {
542     return qemu_find_opts_singleton("machine");
543 }
544
545 const char *qemu_get_vm_name(void)
546 {
547     return qemu_name;
548 }
549
550 static void res_free(void)
551 {
552     g_free(boot_splash_filedata);
553     boot_splash_filedata = NULL;
554 }
555
556 static int default_driver_check(void *opaque, QemuOpts *opts, Error **errp)
557 {
558     const char *driver = qemu_opt_get(opts, "driver");
559     int i;
560
561     if (!driver)
562         return 0;
563     for (i = 0; i < ARRAY_SIZE(default_list); i++) {
564         if (strcmp(default_list[i].driver, driver) != 0)
565             continue;
566         *(default_list[i].flag) = 0;
567     }
568     return 0;
569 }
570
571 /***********************************************************/
572 /* QEMU state */
573
574 static RunState current_run_state = RUN_STATE_PRECONFIG;
575
576 /* We use RUN_STATE__MAX but any invalid value will do */
577 static RunState vmstop_requested = RUN_STATE__MAX;
578 static QemuMutex vmstop_lock;
579
580 typedef struct {
581     RunState from;
582     RunState to;
583 } RunStateTransition;
584
585 static const RunStateTransition runstate_transitions_def[] = {
586     /*     from      ->     to      */
587     { RUN_STATE_PRECONFIG, RUN_STATE_PRELAUNCH },
588       /* Early switch to inmigrate state to allow  -incoming CLI option work
589        * as it used to. TODO: delay actual switching to inmigrate state to
590        * the point after machine is built and remove this hack.
591        */
592     { RUN_STATE_PRECONFIG, RUN_STATE_INMIGRATE },
593
594     { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
595     { RUN_STATE_DEBUG, RUN_STATE_FINISH_MIGRATE },
596     { RUN_STATE_DEBUG, RUN_STATE_PRELAUNCH },
597
598     { RUN_STATE_INMIGRATE, RUN_STATE_INTERNAL_ERROR },
599     { RUN_STATE_INMIGRATE, RUN_STATE_IO_ERROR },
600     { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
601     { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
602     { RUN_STATE_INMIGRATE, RUN_STATE_SHUTDOWN },
603     { RUN_STATE_INMIGRATE, RUN_STATE_SUSPENDED },
604     { RUN_STATE_INMIGRATE, RUN_STATE_WATCHDOG },
605     { RUN_STATE_INMIGRATE, RUN_STATE_GUEST_PANICKED },
606     { RUN_STATE_INMIGRATE, RUN_STATE_FINISH_MIGRATE },
607     { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
608     { RUN_STATE_INMIGRATE, RUN_STATE_POSTMIGRATE },
609     { RUN_STATE_INMIGRATE, RUN_STATE_COLO },
610
611     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
612     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
613     { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PRELAUNCH },
614
615     { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
616     { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
617     { RUN_STATE_IO_ERROR, RUN_STATE_PRELAUNCH },
618
619     { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
620     { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
621     { RUN_STATE_PAUSED, RUN_STATE_POSTMIGRATE },
622     { RUN_STATE_PAUSED, RUN_STATE_PRELAUNCH },
623     { RUN_STATE_PAUSED, RUN_STATE_COLO},
624
625     { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
626     { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
627     { RUN_STATE_POSTMIGRATE, RUN_STATE_PRELAUNCH },
628
629     { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
630     { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
631     { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
632
633     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
634     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PAUSED },
635     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
636     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_PRELAUNCH },
637     { RUN_STATE_FINISH_MIGRATE, RUN_STATE_COLO},
638
639     { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
640     { RUN_STATE_RESTORE_VM, RUN_STATE_PRELAUNCH },
641
642     { RUN_STATE_COLO, RUN_STATE_RUNNING },
643
644     { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
645     { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
646     { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
647     { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
648     { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
649     { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
650     { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
651     { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
652     { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
653     { RUN_STATE_RUNNING, RUN_STATE_GUEST_PANICKED },
654     { RUN_STATE_RUNNING, RUN_STATE_COLO},
655
656     { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
657
658     { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
659     { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
660     { RUN_STATE_SHUTDOWN, RUN_STATE_PRELAUNCH },
661     { RUN_STATE_SHUTDOWN, RUN_STATE_COLO },
662
663     { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
664     { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
665     { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
666     { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
667     { RUN_STATE_SUSPENDED, RUN_STATE_PRELAUNCH },
668     { RUN_STATE_SUSPENDED, RUN_STATE_COLO},
669
670     { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
671     { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
672     { RUN_STATE_WATCHDOG, RUN_STATE_PRELAUNCH },
673     { RUN_STATE_WATCHDOG, RUN_STATE_COLO},
674
675     { RUN_STATE_GUEST_PANICKED, RUN_STATE_RUNNING },
676     { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
677     { RUN_STATE_GUEST_PANICKED, RUN_STATE_PRELAUNCH },
678
679     { RUN_STATE__MAX, RUN_STATE__MAX },
680 };
681
682 static bool runstate_valid_transitions[RUN_STATE__MAX][RUN_STATE__MAX];
683
684 bool runstate_check(RunState state)
685 {
686     return current_run_state == state;
687 }
688
689 bool runstate_store(char *str, size_t size)
690 {
691     const char *state = RunState_str(current_run_state);
692     size_t len = strlen(state) + 1;
693
694     if (len > size) {
695         return false;
696     }
697     memcpy(str, state, len);
698     return true;
699 }
700
701 static void runstate_init(void)
702 {
703     const RunStateTransition *p;
704
705     memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
706     for (p = &runstate_transitions_def[0]; p->from != RUN_STATE__MAX; p++) {
707         runstate_valid_transitions[p->from][p->to] = true;
708     }
709
710     qemu_mutex_init(&vmstop_lock);
711 }
712
713 /* This function will abort() on invalid state transitions */
714 void runstate_set(RunState new_state)
715 {
716     assert(new_state < RUN_STATE__MAX);
717
718     trace_runstate_set(current_run_state, RunState_str(current_run_state),
719                        new_state, RunState_str(new_state));
720
721     if (current_run_state == new_state) {
722         return;
723     }
724
725     if (!runstate_valid_transitions[current_run_state][new_state]) {
726         error_report("invalid runstate transition: '%s' -> '%s'",
727                      RunState_str(current_run_state),
728                      RunState_str(new_state));
729         abort();
730     }
731
732     current_run_state = new_state;
733 }
734
735 int runstate_is_running(void)
736 {
737     return runstate_check(RUN_STATE_RUNNING);
738 }
739
740 bool runstate_needs_reset(void)
741 {
742     return runstate_check(RUN_STATE_INTERNAL_ERROR) ||
743         runstate_check(RUN_STATE_SHUTDOWN);
744 }
745
746 StatusInfo *qmp_query_status(Error **errp)
747 {
748     StatusInfo *info = g_malloc0(sizeof(*info));
749
750     info->running = runstate_is_running();
751     info->singlestep = singlestep;
752     info->status = current_run_state;
753
754     return info;
755 }
756
757 bool qemu_vmstop_requested(RunState *r)
758 {
759     qemu_mutex_lock(&vmstop_lock);
760     *r = vmstop_requested;
761     vmstop_requested = RUN_STATE__MAX;
762     qemu_mutex_unlock(&vmstop_lock);
763     return *r < RUN_STATE__MAX;
764 }
765
766 void qemu_system_vmstop_request_prepare(void)
767 {
768     qemu_mutex_lock(&vmstop_lock);
769 }
770
771 void qemu_system_vmstop_request(RunState state)
772 {
773     vmstop_requested = state;
774     qemu_mutex_unlock(&vmstop_lock);
775     qemu_notify_event();
776 }
777
778 /***********************************************************/
779 /* RTC reference time/date access */
780 static time_t qemu_ref_timedate(QEMUClockType clock)
781 {
782     time_t value = qemu_clock_get_ms(clock) / 1000;
783     switch (clock) {
784     case QEMU_CLOCK_REALTIME:
785         value -= rtc_realtime_clock_offset;
786         /* fall through */
787     case QEMU_CLOCK_VIRTUAL:
788         value += rtc_ref_start_datetime;
789         break;
790     case QEMU_CLOCK_HOST:
791         if (rtc_base_type == RTC_BASE_DATETIME) {
792             value -= rtc_host_datetime_offset;
793         }
794         break;
795     default:
796         assert(0);
797     }
798     return value;
799 }
800
801 void qemu_get_timedate(struct tm *tm, int offset)
802 {
803     time_t ti = qemu_ref_timedate(rtc_clock);
804
805     ti += offset;
806
807     switch (rtc_base_type) {
808     case RTC_BASE_DATETIME:
809     case RTC_BASE_UTC:
810         gmtime_r(&ti, tm);
811         break;
812     case RTC_BASE_LOCALTIME:
813         localtime_r(&ti, tm);
814         break;
815     }
816 }
817
818 int qemu_timedate_diff(struct tm *tm)
819 {
820     time_t seconds;
821
822     switch (rtc_base_type) {
823     case RTC_BASE_DATETIME:
824     case RTC_BASE_UTC:
825         seconds = mktimegm(tm);
826         break;
827     case RTC_BASE_LOCALTIME:
828     {
829         struct tm tmp = *tm;
830         tmp.tm_isdst = -1; /* use timezone to figure it out */
831         seconds = mktime(&tmp);
832         break;
833     }
834     default:
835         abort();
836     }
837
838     return seconds - qemu_ref_timedate(QEMU_CLOCK_HOST);
839 }
840
841 static void configure_rtc_base_datetime(const char *startdate)
842 {
843     time_t rtc_start_datetime;
844     struct tm tm;
845
846     if (sscanf(startdate, "%d-%d-%dT%d:%d:%d", &tm.tm_year, &tm.tm_mon,
847                &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6) {
848         /* OK */
849     } else if (sscanf(startdate, "%d-%d-%d",
850                       &tm.tm_year, &tm.tm_mon, &tm.tm_mday) == 3) {
851         tm.tm_hour = 0;
852         tm.tm_min = 0;
853         tm.tm_sec = 0;
854     } else {
855         goto date_fail;
856     }
857     tm.tm_year -= 1900;
858     tm.tm_mon--;
859     rtc_start_datetime = mktimegm(&tm);
860     if (rtc_start_datetime == -1) {
861     date_fail:
862         error_report("invalid datetime format");
863         error_printf("valid formats: "
864                      "'2006-06-17T16:01:21' or '2006-06-17'\n");
865         exit(1);
866     }
867     rtc_host_datetime_offset = rtc_ref_start_datetime - rtc_start_datetime;
868     rtc_ref_start_datetime = rtc_start_datetime;
869 }
870
871 static void configure_rtc(QemuOpts *opts)
872 {
873     const char *value;
874
875     /* Set defaults */
876     rtc_clock = QEMU_CLOCK_HOST;
877     rtc_ref_start_datetime = qemu_clock_get_ms(QEMU_CLOCK_HOST) / 1000;
878     rtc_realtime_clock_offset = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) / 1000;
879
880     value = qemu_opt_get(opts, "base");
881     if (value) {
882         if (!strcmp(value, "utc")) {
883             rtc_base_type = RTC_BASE_UTC;
884         } else if (!strcmp(value, "localtime")) {
885             Error *blocker = NULL;
886             rtc_base_type = RTC_BASE_LOCALTIME;
887             error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
888                       "-rtc base=localtime");
889             replay_add_blocker(blocker);
890         } else {
891             rtc_base_type = RTC_BASE_DATETIME;
892             configure_rtc_base_datetime(value);
893         }
894     }
895     value = qemu_opt_get(opts, "clock");
896     if (value) {
897         if (!strcmp(value, "host")) {
898             rtc_clock = QEMU_CLOCK_HOST;
899         } else if (!strcmp(value, "rt")) {
900             rtc_clock = QEMU_CLOCK_REALTIME;
901         } else if (!strcmp(value, "vm")) {
902             rtc_clock = QEMU_CLOCK_VIRTUAL;
903         } else {
904             error_report("invalid option value '%s'", value);
905             exit(1);
906         }
907     }
908     value = qemu_opt_get(opts, "driftfix");
909     if (value) {
910         if (!strcmp(value, "slew")) {
911             object_register_sugar_prop("mc146818rtc",
912                                        "lost_tick_policy",
913                                        "slew");
914         } else if (!strcmp(value, "none")) {
915             /* discard is default */
916         } else {
917             error_report("invalid option value '%s'", value);
918             exit(1);
919         }
920     }
921 }
922
923 static int parse_name(void *opaque, QemuOpts *opts, Error **errp)
924 {
925     const char *proc_name;
926
927     if (qemu_opt_get(opts, "debug-threads")) {
928         qemu_thread_naming(qemu_opt_get_bool(opts, "debug-threads", false));
929     }
930     qemu_name = qemu_opt_get(opts, "guest");
931
932     proc_name = qemu_opt_get(opts, "process");
933     if (proc_name) {
934         os_set_proc_name(proc_name);
935     }
936
937     return 0;
938 }
939
940 bool defaults_enabled(void)
941 {
942     return has_defaults;
943 }
944
945 #ifndef _WIN32
946 static int parse_add_fd(void *opaque, QemuOpts *opts, Error **errp)
947 {
948     int fd, dupfd, flags;
949     int64_t fdset_id;
950     const char *fd_opaque = NULL;
951     AddfdInfo *fdinfo;
952
953     fd = qemu_opt_get_number(opts, "fd", -1);
954     fdset_id = qemu_opt_get_number(opts, "set", -1);
955     fd_opaque = qemu_opt_get(opts, "opaque");
956
957     if (fd < 0) {
958         error_setg(errp, "fd option is required and must be non-negative");
959         return -1;
960     }
961
962     if (fd <= STDERR_FILENO) {
963         error_setg(errp, "fd cannot be a standard I/O stream");
964         return -1;
965     }
966
967     /*
968      * All fds inherited across exec() necessarily have FD_CLOEXEC
969      * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
970      */
971     flags = fcntl(fd, F_GETFD);
972     if (flags == -1 || (flags & FD_CLOEXEC)) {
973         error_setg(errp, "fd is not valid or already in use");
974         return -1;
975     }
976
977     if (fdset_id < 0) {
978         error_setg(errp, "set option is required and must be non-negative");
979         return -1;
980     }
981
982 #ifdef F_DUPFD_CLOEXEC
983     dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
984 #else
985     dupfd = dup(fd);
986     if (dupfd != -1) {
987         qemu_set_cloexec(dupfd);
988     }
989 #endif
990     if (dupfd == -1) {
991         error_setg(errp, "error duplicating fd: %s", strerror(errno));
992         return -1;
993     }
994
995     /* add the duplicate fd, and optionally the opaque string, to the fd set */
996     fdinfo = monitor_fdset_add_fd(dupfd, true, fdset_id, !!fd_opaque, fd_opaque,
997                                   &error_abort);
998     g_free(fdinfo);
999
1000     return 0;
1001 }
1002
1003 static int cleanup_add_fd(void *opaque, QemuOpts *opts, Error **errp)
1004 {
1005     int fd;
1006
1007     fd = qemu_opt_get_number(opts, "fd", -1);
1008     close(fd);
1009
1010     return 0;
1011 }
1012 #endif
1013
1014 /***********************************************************/
1015 /* QEMU Block devices */
1016
1017 #define HD_OPTS "media=disk"
1018 #define CDROM_OPTS "media=cdrom"
1019 #define FD_OPTS ""
1020 #define PFLASH_OPTS ""
1021 #define MTD_OPTS ""
1022 #define SD_OPTS ""
1023
1024 static int drive_init_func(void *opaque, QemuOpts *opts, Error **errp)
1025 {
1026     BlockInterfaceType *block_default_type = opaque;
1027
1028     return drive_new(opts, *block_default_type, errp) == NULL;
1029 }
1030
1031 static int drive_enable_snapshot(void *opaque, QemuOpts *opts, Error **errp)
1032 {
1033     if (qemu_opt_get(opts, "snapshot") == NULL) {
1034         qemu_opt_set(opts, "snapshot", "on", &error_abort);
1035     }
1036     return 0;
1037 }
1038
1039 static void default_drive(int enable, int snapshot, BlockInterfaceType type,
1040                           int index, const char *optstr)
1041 {
1042     QemuOpts *opts;
1043     DriveInfo *dinfo;
1044
1045     if (!enable || drive_get_by_index(type, index)) {
1046         return;
1047     }
1048
1049     opts = drive_add(type, index, NULL, optstr);
1050     if (snapshot) {
1051         drive_enable_snapshot(NULL, opts, NULL);
1052     }
1053
1054     dinfo = drive_new(opts, type, &error_abort);
1055     dinfo->is_default = true;
1056
1057 }
1058
1059 static void configure_blockdev(BlockdevOptionsQueue *bdo_queue,
1060                                MachineClass *machine_class, int snapshot)
1061 {
1062     /*
1063      * If the currently selected machine wishes to override the
1064      * units-per-bus property of its default HBA interface type, do so
1065      * now.
1066      */
1067     if (machine_class->units_per_default_bus) {
1068         override_max_devs(machine_class->block_default_type,
1069                           machine_class->units_per_default_bus);
1070     }
1071
1072     /* open the virtual block devices */
1073     while (!QSIMPLEQ_EMPTY(bdo_queue)) {
1074         BlockdevOptionsQueueEntry *bdo = QSIMPLEQ_FIRST(bdo_queue);
1075
1076         QSIMPLEQ_REMOVE_HEAD(bdo_queue, entry);
1077         loc_push_restore(&bdo->loc);
1078         qmp_blockdev_add(bdo->bdo, &error_fatal);
1079         loc_pop(&bdo->loc);
1080         qapi_free_BlockdevOptions(bdo->bdo);
1081         g_free(bdo);
1082     }
1083     if (snapshot) {
1084         qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot,
1085                           NULL, NULL);
1086     }
1087     if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
1088                           &machine_class->block_default_type, &error_fatal)) {
1089         /* We printed help */
1090         exit(0);
1091     }
1092
1093     default_drive(default_cdrom, snapshot, machine_class->block_default_type, 2,
1094                   CDROM_OPTS);
1095     default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
1096     default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
1097
1098 }
1099
1100 static QemuOptsList qemu_smp_opts = {
1101     .name = "smp-opts",
1102     .implied_opt_name = "cpus",
1103     .merge_lists = true,
1104     .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
1105     .desc = {
1106         {
1107             .name = "cpus",
1108             .type = QEMU_OPT_NUMBER,
1109         }, {
1110             .name = "sockets",
1111             .type = QEMU_OPT_NUMBER,
1112         }, {
1113             .name = "dies",
1114             .type = QEMU_OPT_NUMBER,
1115         }, {
1116             .name = "cores",
1117             .type = QEMU_OPT_NUMBER,
1118         }, {
1119             .name = "threads",
1120             .type = QEMU_OPT_NUMBER,
1121         }, {
1122             .name = "maxcpus",
1123             .type = QEMU_OPT_NUMBER,
1124         },
1125         { /*End of list */ }
1126     },
1127 };
1128
1129 static void realtime_init(void)
1130 {
1131     if (enable_mlock) {
1132         if (os_mlock() < 0) {
1133             error_report("locking memory failed");
1134             exit(1);
1135         }
1136     }
1137 }
1138
1139
1140 static void configure_msg(QemuOpts *opts)
1141 {
1142     error_with_timestamp = qemu_opt_get_bool(opts, "timestamp", false);
1143     error_with_guestname = qemu_opt_get_bool(opts, "guest-name", false);
1144 }
1145
1146
1147 /***********************************************************/
1148 /* USB devices */
1149
1150 static int usb_device_add(const char *devname)
1151 {
1152     USBDevice *dev = NULL;
1153
1154     if (!machine_usb(current_machine)) {
1155         return -1;
1156     }
1157
1158     dev = usbdevice_create(devname);
1159     if (!dev)
1160         return -1;
1161
1162     return 0;
1163 }
1164
1165 static int usb_parse(const char *cmdline)
1166 {
1167     int r;
1168     r = usb_device_add(cmdline);
1169     if (r < 0) {
1170         error_report("could not add USB device '%s'", cmdline);
1171     }
1172     return r;
1173 }
1174
1175 /***********************************************************/
1176 /* machine registration */
1177
1178 MachineState *current_machine;
1179
1180 static MachineClass *find_machine(const char *name, GSList *machines)
1181 {
1182     GSList *el;
1183
1184     for (el = machines; el; el = el->next) {
1185         MachineClass *mc = el->data;
1186
1187         if (!strcmp(mc->name, name) || !g_strcmp0(mc->alias, name)) {
1188             return mc;
1189         }
1190     }
1191
1192     return NULL;
1193 }
1194
1195 static MachineClass *find_default_machine(GSList *machines)
1196 {
1197     GSList *el;
1198     MachineClass *default_machineclass = NULL;
1199
1200     for (el = machines; el; el = el->next) {
1201         MachineClass *mc = el->data;
1202
1203         if (mc->is_default) {
1204             assert(default_machineclass == NULL && "Multiple default machines");
1205             default_machineclass = mc;
1206         }
1207     }
1208
1209     return default_machineclass;
1210 }
1211
1212 static int machine_help_func(QemuOpts *opts, MachineState *machine)
1213 {
1214     ObjectProperty *prop;
1215     ObjectPropertyIterator iter;
1216
1217     if (!qemu_opt_has_help_opt(opts)) {
1218         return 0;
1219     }
1220
1221     object_property_iter_init(&iter, OBJECT(machine));
1222     while ((prop = object_property_iter_next(&iter))) {
1223         if (!prop->set) {
1224             continue;
1225         }
1226
1227         printf("%s.%s=%s", MACHINE_GET_CLASS(machine)->name,
1228                prop->name, prop->type);
1229         if (prop->description) {
1230             printf(" (%s)\n", prop->description);
1231         } else {
1232             printf("\n");
1233         }
1234     }
1235
1236     return 1;
1237 }
1238
1239 struct VMChangeStateEntry {
1240     VMChangeStateHandler *cb;
1241     void *opaque;
1242     QTAILQ_ENTRY(VMChangeStateEntry) entries;
1243     int priority;
1244 };
1245
1246 static QTAILQ_HEAD(, VMChangeStateEntry) vm_change_state_head =
1247     QTAILQ_HEAD_INITIALIZER(vm_change_state_head);
1248
1249 /**
1250  * qemu_add_vm_change_state_handler_prio:
1251  * @cb: the callback to invoke
1252  * @opaque: user data passed to the callback
1253  * @priority: low priorities execute first when the vm runs and the reverse is
1254  *            true when the vm stops
1255  *
1256  * Register a callback function that is invoked when the vm starts or stops
1257  * running.
1258  *
1259  * Returns: an entry to be freed using qemu_del_vm_change_state_handler()
1260  */
1261 VMChangeStateEntry *qemu_add_vm_change_state_handler_prio(
1262         VMChangeStateHandler *cb, void *opaque, int priority)
1263 {
1264     VMChangeStateEntry *e;
1265     VMChangeStateEntry *other;
1266
1267     e = g_malloc0(sizeof(*e));
1268     e->cb = cb;
1269     e->opaque = opaque;
1270     e->priority = priority;
1271
1272     /* Keep list sorted in ascending priority order */
1273     QTAILQ_FOREACH(other, &vm_change_state_head, entries) {
1274         if (priority < other->priority) {
1275             QTAILQ_INSERT_BEFORE(other, e, entries);
1276             return e;
1277         }
1278     }
1279
1280     QTAILQ_INSERT_TAIL(&vm_change_state_head, e, entries);
1281     return e;
1282 }
1283
1284 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1285                                                      void *opaque)
1286 {
1287     return qemu_add_vm_change_state_handler_prio(cb, opaque, 0);
1288 }
1289
1290 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1291 {
1292     QTAILQ_REMOVE(&vm_change_state_head, e, entries);
1293     g_free(e);
1294 }
1295
1296 void vm_state_notify(int running, RunState state)
1297 {
1298     VMChangeStateEntry *e, *next;
1299
1300     trace_vm_state_notify(running, state, RunState_str(state));
1301
1302     if (running) {
1303         QTAILQ_FOREACH_SAFE(e, &vm_change_state_head, entries, next) {
1304             e->cb(e->opaque, running, state);
1305         }
1306     } else {
1307         QTAILQ_FOREACH_REVERSE_SAFE(e, &vm_change_state_head, entries, next) {
1308             e->cb(e->opaque, running, state);
1309         }
1310     }
1311 }
1312
1313 static ShutdownCause reset_requested;
1314 static ShutdownCause shutdown_requested;
1315 static int shutdown_signal;
1316 static pid_t shutdown_pid;
1317 static int powerdown_requested;
1318 static int debug_requested;
1319 static int suspend_requested;
1320 static bool preconfig_exit_requested = true;
1321 static WakeupReason wakeup_reason;
1322 static NotifierList powerdown_notifiers =
1323     NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
1324 static NotifierList suspend_notifiers =
1325     NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1326 static NotifierList wakeup_notifiers =
1327     NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1328 static NotifierList shutdown_notifiers =
1329     NOTIFIER_LIST_INITIALIZER(shutdown_notifiers);
1330 static uint32_t wakeup_reason_mask = ~(1 << QEMU_WAKEUP_REASON_NONE);
1331
1332 ShutdownCause qemu_shutdown_requested_get(void)
1333 {
1334     return shutdown_requested;
1335 }
1336
1337 ShutdownCause qemu_reset_requested_get(void)
1338 {
1339     return reset_requested;
1340 }
1341
1342 static int qemu_shutdown_requested(void)
1343 {
1344     return qatomic_xchg(&shutdown_requested, SHUTDOWN_CAUSE_NONE);
1345 }
1346
1347 static void qemu_kill_report(void)
1348 {
1349     if (!qtest_driver() && shutdown_signal) {
1350         if (shutdown_pid == 0) {
1351             /* This happens for eg ^C at the terminal, so it's worth
1352              * avoiding printing an odd message in that case.
1353              */
1354             error_report("terminating on signal %d", shutdown_signal);
1355         } else {
1356             char *shutdown_cmd = qemu_get_pid_name(shutdown_pid);
1357
1358             error_report("terminating on signal %d from pid " FMT_pid " (%s)",
1359                          shutdown_signal, shutdown_pid,
1360                          shutdown_cmd ? shutdown_cmd : "<unknown process>");
1361             g_free(shutdown_cmd);
1362         }
1363         shutdown_signal = 0;
1364     }
1365 }
1366
1367 static ShutdownCause qemu_reset_requested(void)
1368 {
1369     ShutdownCause r = reset_requested;
1370
1371     if (r && replay_checkpoint(CHECKPOINT_RESET_REQUESTED)) {
1372         reset_requested = SHUTDOWN_CAUSE_NONE;
1373         return r;
1374     }
1375     return SHUTDOWN_CAUSE_NONE;
1376 }
1377
1378 static int qemu_suspend_requested(void)
1379 {
1380     int r = suspend_requested;
1381     if (r && replay_checkpoint(CHECKPOINT_SUSPEND_REQUESTED)) {
1382         suspend_requested = 0;
1383         return r;
1384     }
1385     return false;
1386 }
1387
1388 static WakeupReason qemu_wakeup_requested(void)
1389 {
1390     return wakeup_reason;
1391 }
1392
1393 static int qemu_powerdown_requested(void)
1394 {
1395     int r = powerdown_requested;
1396     powerdown_requested = 0;
1397     return r;
1398 }
1399
1400 static int qemu_debug_requested(void)
1401 {
1402     int r = debug_requested;
1403     debug_requested = 0;
1404     return r;
1405 }
1406
1407 void qemu_exit_preconfig_request(void)
1408 {
1409     preconfig_exit_requested = true;
1410 }
1411
1412 /*
1413  * Reset the VM. Issue an event unless @reason is SHUTDOWN_CAUSE_NONE.
1414  */
1415 void qemu_system_reset(ShutdownCause reason)
1416 {
1417     MachineClass *mc;
1418
1419     mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1420
1421     cpu_synchronize_all_states();
1422
1423     if (mc && mc->reset) {
1424         mc->reset(current_machine);
1425     } else {
1426         qemu_devices_reset();
1427     }
1428     if (reason && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1429         qapi_event_send_reset(shutdown_caused_by_guest(reason), reason);
1430     }
1431     cpu_synchronize_all_post_reset();
1432 }
1433
1434 /*
1435  * Wake the VM after suspend.
1436  */
1437 static void qemu_system_wakeup(void)
1438 {
1439     MachineClass *mc;
1440
1441     mc = current_machine ? MACHINE_GET_CLASS(current_machine) : NULL;
1442
1443     if (mc && mc->wakeup) {
1444         mc->wakeup(current_machine);
1445     }
1446 }
1447
1448 void qemu_system_guest_panicked(GuestPanicInformation *info)
1449 {
1450     qemu_log_mask(LOG_GUEST_ERROR, "Guest crashed");
1451
1452     if (current_cpu) {
1453         current_cpu->crash_occurred = true;
1454     }
1455     qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE,
1456                                    !!info, info);
1457     vm_stop(RUN_STATE_GUEST_PANICKED);
1458     if (!no_shutdown) {
1459         qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_POWEROFF,
1460                                        !!info, info);
1461         qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_PANIC);
1462     }
1463
1464     if (info) {
1465         if (info->type == GUEST_PANIC_INFORMATION_TYPE_HYPER_V) {
1466             qemu_log_mask(LOG_GUEST_ERROR, "\nHV crash parameters: (%#"PRIx64
1467                           " %#"PRIx64" %#"PRIx64" %#"PRIx64" %#"PRIx64")\n",
1468                           info->u.hyper_v.arg1,
1469                           info->u.hyper_v.arg2,
1470                           info->u.hyper_v.arg3,
1471                           info->u.hyper_v.arg4,
1472                           info->u.hyper_v.arg5);
1473         } else if (info->type == GUEST_PANIC_INFORMATION_TYPE_S390) {
1474             qemu_log_mask(LOG_GUEST_ERROR, " on cpu %d: %s\n"
1475                           "PSW: 0x%016" PRIx64 " 0x%016" PRIx64"\n",
1476                           info->u.s390.core,
1477                           S390CrashReason_str(info->u.s390.reason),
1478                           info->u.s390.psw_mask,
1479                           info->u.s390.psw_addr);
1480         }
1481         qapi_free_GuestPanicInformation(info);
1482     }
1483 }
1484
1485 void qemu_system_guest_crashloaded(GuestPanicInformation *info)
1486 {
1487     qemu_log_mask(LOG_GUEST_ERROR, "Guest crash loaded");
1488
1489     qapi_event_send_guest_crashloaded(GUEST_PANIC_ACTION_RUN,
1490                                    !!info, info);
1491
1492     if (info) {
1493         qapi_free_GuestPanicInformation(info);
1494     }
1495 }
1496
1497 void qemu_system_reset_request(ShutdownCause reason)
1498 {
1499     if (no_reboot && reason != SHUTDOWN_CAUSE_SUBSYSTEM_RESET) {
1500         shutdown_requested = reason;
1501     } else {
1502         reset_requested = reason;
1503     }
1504     cpu_stop_current();
1505     qemu_notify_event();
1506 }
1507
1508 static void qemu_system_suspend(void)
1509 {
1510     pause_all_vcpus();
1511     notifier_list_notify(&suspend_notifiers, NULL);
1512     runstate_set(RUN_STATE_SUSPENDED);
1513     qapi_event_send_suspend();
1514 }
1515
1516 void qemu_system_suspend_request(void)
1517 {
1518     if (runstate_check(RUN_STATE_SUSPENDED)) {
1519         return;
1520     }
1521     suspend_requested = 1;
1522     cpu_stop_current();
1523     qemu_notify_event();
1524 }
1525
1526 void qemu_register_suspend_notifier(Notifier *notifier)
1527 {
1528     notifier_list_add(&suspend_notifiers, notifier);
1529 }
1530
1531 void qemu_system_wakeup_request(WakeupReason reason, Error **errp)
1532 {
1533     trace_system_wakeup_request(reason);
1534
1535     if (!runstate_check(RUN_STATE_SUSPENDED)) {
1536         error_setg(errp,
1537                    "Unable to wake up: guest is not in suspended state");
1538         return;
1539     }
1540     if (!(wakeup_reason_mask & (1 << reason))) {
1541         return;
1542     }
1543     runstate_set(RUN_STATE_RUNNING);
1544     wakeup_reason = reason;
1545     qemu_notify_event();
1546 }
1547
1548 void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1549 {
1550     if (enabled) {
1551         wakeup_reason_mask |= (1 << reason);
1552     } else {
1553         wakeup_reason_mask &= ~(1 << reason);
1554     }
1555 }
1556
1557 void qemu_register_wakeup_notifier(Notifier *notifier)
1558 {
1559     notifier_list_add(&wakeup_notifiers, notifier);
1560 }
1561
1562 void qemu_register_wakeup_support(void)
1563 {
1564     wakeup_suspend_enabled = true;
1565 }
1566
1567 bool qemu_wakeup_suspend_enabled(void)
1568 {
1569     return wakeup_suspend_enabled;
1570 }
1571
1572 void qemu_system_killed(int signal, pid_t pid)
1573 {
1574     shutdown_signal = signal;
1575     shutdown_pid = pid;
1576     no_shutdown = 0;
1577
1578     /* Cannot call qemu_system_shutdown_request directly because
1579      * we are in a signal handler.
1580      */
1581     shutdown_requested = SHUTDOWN_CAUSE_HOST_SIGNAL;
1582     qemu_notify_event();
1583 }
1584
1585 void qemu_system_shutdown_request(ShutdownCause reason)
1586 {
1587     trace_qemu_system_shutdown_request(reason);
1588     replay_shutdown_request(reason);
1589     shutdown_requested = reason;
1590     qemu_notify_event();
1591 }
1592
1593 static void qemu_system_powerdown(void)
1594 {
1595     qapi_event_send_powerdown();
1596     notifier_list_notify(&powerdown_notifiers, NULL);
1597 }
1598
1599 static void qemu_system_shutdown(ShutdownCause cause)
1600 {
1601     qapi_event_send_shutdown(shutdown_caused_by_guest(cause), cause);
1602     notifier_list_notify(&shutdown_notifiers, &cause);
1603 }
1604
1605 void qemu_system_powerdown_request(void)
1606 {
1607     trace_qemu_system_powerdown_request();
1608     powerdown_requested = 1;
1609     qemu_notify_event();
1610 }
1611
1612 void qemu_register_powerdown_notifier(Notifier *notifier)
1613 {
1614     notifier_list_add(&powerdown_notifiers, notifier);
1615 }
1616
1617 void qemu_register_shutdown_notifier(Notifier *notifier)
1618 {
1619     notifier_list_add(&shutdown_notifiers, notifier);
1620 }
1621
1622 void qemu_system_debug_request(void)
1623 {
1624     debug_requested = 1;
1625     qemu_notify_event();
1626 }
1627
1628 static bool main_loop_should_exit(void)
1629 {
1630     RunState r;
1631     ShutdownCause request;
1632
1633     if (preconfig_exit_requested) {
1634         if (runstate_check(RUN_STATE_PRECONFIG)) {
1635             runstate_set(RUN_STATE_PRELAUNCH);
1636         }
1637         preconfig_exit_requested = false;
1638         return true;
1639     }
1640     if (qemu_debug_requested()) {
1641         vm_stop(RUN_STATE_DEBUG);
1642     }
1643     if (qemu_suspend_requested()) {
1644         qemu_system_suspend();
1645     }
1646     request = qemu_shutdown_requested();
1647     if (request) {
1648         qemu_kill_report();
1649         qemu_system_shutdown(request);
1650         if (no_shutdown) {
1651             vm_stop(RUN_STATE_SHUTDOWN);
1652         } else {
1653             return true;
1654         }
1655     }
1656     request = qemu_reset_requested();
1657     if (request) {
1658         pause_all_vcpus();
1659         qemu_system_reset(request);
1660         resume_all_vcpus();
1661         /*
1662          * runstate can change in pause_all_vcpus()
1663          * as iothread mutex is unlocked
1664          */
1665         if (!runstate_check(RUN_STATE_RUNNING) &&
1666                 !runstate_check(RUN_STATE_INMIGRATE) &&
1667                 !runstate_check(RUN_STATE_FINISH_MIGRATE)) {
1668             runstate_set(RUN_STATE_PRELAUNCH);
1669         }
1670     }
1671     if (qemu_wakeup_requested()) {
1672         pause_all_vcpus();
1673         qemu_system_wakeup();
1674         notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
1675         wakeup_reason = QEMU_WAKEUP_REASON_NONE;
1676         resume_all_vcpus();
1677         qapi_event_send_wakeup();
1678     }
1679     if (qemu_powerdown_requested()) {
1680         qemu_system_powerdown();
1681     }
1682     if (qemu_vmstop_requested(&r)) {
1683         vm_stop(r);
1684     }
1685     return false;
1686 }
1687
1688 void qemu_main_loop(void)
1689 {
1690 #ifdef CONFIG_PROFILER
1691     int64_t ti;
1692 #endif
1693     while (!main_loop_should_exit()) {
1694 #ifdef CONFIG_PROFILER
1695         ti = profile_getclock();
1696 #endif
1697         main_loop_wait(false);
1698 #ifdef CONFIG_PROFILER
1699         dev_time += profile_getclock() - ti;
1700 #endif
1701     }
1702 }
1703
1704 static void version(void)
1705 {
1706     printf("QEMU emulator version " QEMU_FULL_VERSION "\n"
1707            QEMU_COPYRIGHT "\n");
1708 }
1709
1710 static void help(int exitcode)
1711 {
1712     version();
1713     printf("usage: %s [options] [disk_image]\n\n"
1714            "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
1715             error_get_progname());
1716
1717 #define QEMU_OPTIONS_GENERATE_HELP
1718 #include "qemu-options-wrapper.h"
1719
1720     printf("\nDuring emulation, the following keys are useful:\n"
1721            "ctrl-alt-f      toggle full screen\n"
1722            "ctrl-alt-n      switch to virtual console 'n'\n"
1723            "ctrl-alt        toggle mouse and keyboard grab\n"
1724            "\n"
1725            "When using -nographic, press 'ctrl-a h' to get some help.\n"
1726            "\n"
1727            QEMU_HELP_BOTTOM "\n");
1728
1729     exit(exitcode);
1730 }
1731
1732 #define HAS_ARG 0x0001
1733
1734 typedef struct QEMUOption {
1735     const char *name;
1736     int flags;
1737     int index;
1738     uint32_t arch_mask;
1739 } QEMUOption;
1740
1741 static const QEMUOption qemu_options[] = {
1742     { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1743 #define QEMU_OPTIONS_GENERATE_OPTIONS
1744 #include "qemu-options-wrapper.h"
1745     { NULL },
1746 };
1747
1748 typedef struct VGAInterfaceInfo {
1749     const char *opt_name;    /* option name */
1750     const char *name;        /* human-readable name */
1751     /* Class names indicating that support is available.
1752      * If no class is specified, the interface is always available */
1753     const char *class_names[2];
1754 } VGAInterfaceInfo;
1755
1756 static const VGAInterfaceInfo vga_interfaces[VGA_TYPE_MAX] = {
1757     [VGA_NONE] = {
1758         .opt_name = "none",
1759         .name = "no graphic card",
1760     },
1761     [VGA_STD] = {
1762         .opt_name = "std",
1763         .name = "standard VGA",
1764         .class_names = { "VGA", "isa-vga" },
1765     },
1766     [VGA_CIRRUS] = {
1767         .opt_name = "cirrus",
1768         .name = "Cirrus VGA",
1769         .class_names = { "cirrus-vga", "isa-cirrus-vga" },
1770     },
1771     [VGA_VMWARE] = {
1772         .opt_name = "vmware",
1773         .name = "VMWare SVGA",
1774         .class_names = { "vmware-svga" },
1775     },
1776     [VGA_VIRTIO] = {
1777         .opt_name = "virtio",
1778         .name = "Virtio VGA",
1779         .class_names = { "virtio-vga" },
1780     },
1781     [VGA_QXL] = {
1782         .opt_name = "qxl",
1783         .name = "QXL VGA",
1784         .class_names = { "qxl-vga" },
1785     },
1786     [VGA_TCX] = {
1787         .opt_name = "tcx",
1788         .name = "TCX framebuffer",
1789         .class_names = { "SUNW,tcx" },
1790     },
1791     [VGA_CG3] = {
1792         .opt_name = "cg3",
1793         .name = "CG3 framebuffer",
1794         .class_names = { "cgthree" },
1795     },
1796     [VGA_XENFB] = {
1797         .opt_name = "xenfb",
1798         .name = "Xen paravirtualized framebuffer",
1799     },
1800 };
1801
1802 static bool vga_interface_available(VGAInterfaceType t)
1803 {
1804     const VGAInterfaceInfo *ti = &vga_interfaces[t];
1805
1806     assert(t < VGA_TYPE_MAX);
1807     return !ti->class_names[0] ||
1808            module_object_class_by_name(ti->class_names[0]) ||
1809            module_object_class_by_name(ti->class_names[1]);
1810 }
1811
1812 static const char *
1813 get_default_vga_model(const MachineClass *machine_class)
1814 {
1815     if (machine_class->default_display) {
1816         return machine_class->default_display;
1817     } else if (vga_interface_available(VGA_CIRRUS)) {
1818         return "cirrus";
1819     } else if (vga_interface_available(VGA_STD)) {
1820         return "std";
1821     }
1822
1823     return NULL;
1824 }
1825
1826 static void select_vgahw(const MachineClass *machine_class, const char *p)
1827 {
1828     const char *opts;
1829     int t;
1830
1831     if (g_str_equal(p, "help")) {
1832         const char *def = get_default_vga_model(machine_class);
1833
1834         for (t = 0; t < VGA_TYPE_MAX; t++) {
1835             const VGAInterfaceInfo *ti = &vga_interfaces[t];
1836
1837             if (vga_interface_available(t) && ti->opt_name) {
1838                 printf("%-20s %s%s\n", ti->opt_name, ti->name ?: "",
1839                        g_str_equal(ti->opt_name, def) ? " (default)" : "");
1840             }
1841         }
1842         exit(0);
1843     }
1844
1845     assert(vga_interface_type == VGA_NONE);
1846     for (t = 0; t < VGA_TYPE_MAX; t++) {
1847         const VGAInterfaceInfo *ti = &vga_interfaces[t];
1848         if (ti->opt_name && strstart(p, ti->opt_name, &opts)) {
1849             if (!vga_interface_available(t)) {
1850                 error_report("%s not available", ti->name);
1851                 exit(1);
1852             }
1853             vga_interface_type = t;
1854             break;
1855         }
1856     }
1857     if (t == VGA_TYPE_MAX) {
1858     invalid_vga:
1859         error_report("unknown vga type: %s", p);
1860         exit(1);
1861     }
1862     while (*opts) {
1863         const char *nextopt;
1864
1865         if (strstart(opts, ",retrace=", &nextopt)) {
1866             opts = nextopt;
1867             if (strstart(opts, "dumb", &nextopt))
1868                 vga_retrace_method = VGA_RETRACE_DUMB;
1869             else if (strstart(opts, "precise", &nextopt))
1870                 vga_retrace_method = VGA_RETRACE_PRECISE;
1871             else goto invalid_vga;
1872         } else goto invalid_vga;
1873         opts = nextopt;
1874     }
1875 }
1876
1877 static void parse_display_qapi(const char *optarg)
1878 {
1879     DisplayOptions *opts;
1880     Visitor *v;
1881
1882     v = qobject_input_visitor_new_str(optarg, "type", &error_fatal);
1883
1884     visit_type_DisplayOptions(v, NULL, &opts, &error_fatal);
1885     QAPI_CLONE_MEMBERS(DisplayOptions, &dpy, opts);
1886
1887     qapi_free_DisplayOptions(opts);
1888     visit_free(v);
1889 }
1890
1891 DisplayOptions *qmp_query_display_options(Error **errp)
1892 {
1893     return QAPI_CLONE(DisplayOptions, &dpy);
1894 }
1895
1896 static void parse_display(const char *p)
1897 {
1898     const char *opts;
1899
1900     if (is_help_option(p)) {
1901         qemu_display_help();
1902         exit(0);
1903     }
1904
1905     if (strstart(p, "sdl", &opts)) {
1906         /*
1907          * sdl DisplayType needs hand-crafted parser instead of
1908          * parse_display_qapi() due to some options not in
1909          * DisplayOptions, specifically:
1910          *   - frame
1911          *     Already deprecated.
1912          *   - ctrl_grab + alt_grab
1913          *     Not clear yet what happens to them long-term.  Should
1914          *     replaced by something better or deprecated and dropped.
1915          */
1916         dpy.type = DISPLAY_TYPE_SDL;
1917         while (*opts) {
1918             const char *nextopt;
1919
1920             if (strstart(opts, ",alt_grab=", &nextopt)) {
1921                 opts = nextopt;
1922                 if (strstart(opts, "on", &nextopt)) {
1923                     alt_grab = 1;
1924                 } else if (strstart(opts, "off", &nextopt)) {
1925                     alt_grab = 0;
1926                 } else {
1927                     goto invalid_sdl_args;
1928                 }
1929             } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
1930                 opts = nextopt;
1931                 if (strstart(opts, "on", &nextopt)) {
1932                     ctrl_grab = 1;
1933                 } else if (strstart(opts, "off", &nextopt)) {
1934                     ctrl_grab = 0;
1935                 } else {
1936                     goto invalid_sdl_args;
1937                 }
1938             } else if (strstart(opts, ",window_close=", &nextopt)) {
1939                 opts = nextopt;
1940                 dpy.has_window_close = true;
1941                 if (strstart(opts, "on", &nextopt)) {
1942                     dpy.window_close = true;
1943                 } else if (strstart(opts, "off", &nextopt)) {
1944                     dpy.window_close = false;
1945                 } else {
1946                     goto invalid_sdl_args;
1947                 }
1948             } else if (strstart(opts, ",show-cursor=", &nextopt)) {
1949                 opts = nextopt;
1950                 dpy.has_show_cursor = true;
1951                 if (strstart(opts, "on", &nextopt)) {
1952                     dpy.show_cursor = true;
1953                 } else if (strstart(opts, "off", &nextopt)) {
1954                     dpy.show_cursor = false;
1955                 } else {
1956                     goto invalid_sdl_args;
1957                 }
1958             } else if (strstart(opts, ",gl=", &nextopt)) {
1959                 opts = nextopt;
1960                 dpy.has_gl = true;
1961                 if (strstart(opts, "on", &nextopt)) {
1962                     dpy.gl = DISPLAYGL_MODE_ON;
1963                 } else if (strstart(opts, "core", &nextopt)) {
1964                     dpy.gl = DISPLAYGL_MODE_CORE;
1965                 } else if (strstart(opts, "es", &nextopt)) {
1966                     dpy.gl = DISPLAYGL_MODE_ES;
1967                 } else if (strstart(opts, "off", &nextopt)) {
1968                     dpy.gl = DISPLAYGL_MODE_OFF;
1969                 } else {
1970                     goto invalid_sdl_args;
1971                 }
1972             } else {
1973             invalid_sdl_args:
1974                 error_report("invalid SDL option string");
1975                 exit(1);
1976             }
1977             opts = nextopt;
1978         }
1979     } else if (strstart(p, "vnc", &opts)) {
1980         /*
1981          * vnc isn't a (local) DisplayType but a protocol for remote
1982          * display access.
1983          */
1984         if (*opts == '=') {
1985             vnc_parse(opts + 1, &error_fatal);
1986         } else {
1987             error_report("VNC requires a display argument vnc=<display>");
1988             exit(1);
1989         }
1990     } else {
1991         parse_display_qapi(p);
1992     }
1993 }
1994
1995 char *qemu_find_file(int type, const char *name)
1996 {
1997     int i;
1998     const char *subdir;
1999     char *buf;
2000
2001     /* Try the name as a straight path first */
2002     if (access(name, R_OK) == 0) {
2003         trace_load_file(name, name);
2004         return g_strdup(name);
2005     }
2006
2007     switch (type) {
2008     case QEMU_FILE_TYPE_BIOS:
2009         subdir = "";
2010         break;
2011     case QEMU_FILE_TYPE_KEYMAP:
2012         subdir = "keymaps/";
2013         break;
2014     default:
2015         abort();
2016     }
2017
2018     for (i = 0; i < data_dir_idx; i++) {
2019         buf = g_strdup_printf("%s/%s%s", data_dir[i], subdir, name);
2020         if (access(buf, R_OK) == 0) {
2021             trace_load_file(name, buf);
2022             return buf;
2023         }
2024         g_free(buf);
2025     }
2026     return NULL;
2027 }
2028
2029 void qemu_add_data_dir(char *path)
2030 {
2031     int i;
2032
2033     if (path == NULL) {
2034         return;
2035     }
2036     if (data_dir_idx == ARRAY_SIZE(data_dir)) {
2037         return;
2038     }
2039     for (i = 0; i < data_dir_idx; i++) {
2040         if (strcmp(data_dir[i], path) == 0) {
2041             g_free(path); /* duplicate */
2042             return;
2043         }
2044     }
2045     data_dir[data_dir_idx++] = path;
2046 }
2047
2048 static inline bool nonempty_str(const char *str)
2049 {
2050     return str && *str;
2051 }
2052
2053 static int parse_fw_cfg(void *opaque, QemuOpts *opts, Error **errp)
2054 {
2055     gchar *buf;
2056     size_t size;
2057     const char *name, *file, *str, *gen_id;
2058     FWCfgState *fw_cfg = (FWCfgState *) opaque;
2059
2060     if (fw_cfg == NULL) {
2061         error_setg(errp, "fw_cfg device not available");
2062         return -1;
2063     }
2064     name = qemu_opt_get(opts, "name");
2065     file = qemu_opt_get(opts, "file");
2066     str = qemu_opt_get(opts, "string");
2067     gen_id = qemu_opt_get(opts, "gen_id");
2068
2069     /* we need the name, and exactly one of: file, content string, gen_id */
2070     if (!nonempty_str(name) ||
2071         nonempty_str(file) + nonempty_str(str) + nonempty_str(gen_id) != 1) {
2072         error_setg(errp, "name, plus exactly one of file,"
2073                          " string and gen_id, are needed");
2074         return -1;
2075     }
2076     if (strlen(name) > FW_CFG_MAX_FILE_PATH - 1) {
2077         error_setg(errp, "name too long (max. %d char)",
2078                    FW_CFG_MAX_FILE_PATH - 1);
2079         return -1;
2080     }
2081     if (nonempty_str(gen_id)) {
2082         /*
2083          * In this particular case where the content is populated
2084          * internally, the "etc/" namespace protection is relaxed,
2085          * so do not emit a warning.
2086          */
2087     } else if (strncmp(name, "opt/", 4) != 0) {
2088         warn_report("externally provided fw_cfg item names "
2089                     "should be prefixed with \"opt/\"");
2090     }
2091     if (nonempty_str(str)) {
2092         size = strlen(str); /* NUL terminator NOT included in fw_cfg blob */
2093         buf = g_memdup(str, size);
2094     } else if (nonempty_str(gen_id)) {
2095         if (!fw_cfg_add_from_generator(fw_cfg, name, gen_id, errp)) {
2096             return -1;
2097         }
2098         return 0;
2099     } else {
2100         GError *err = NULL;
2101         if (!g_file_get_contents(file, &buf, &size, &err)) {
2102             error_setg(errp, "can't load %s: %s", file, err->message);
2103             g_error_free(err);
2104             return -1;
2105         }
2106     }
2107     /* For legacy, keep user files in a specific global order. */
2108     fw_cfg_set_order_override(fw_cfg, FW_CFG_ORDER_OVERRIDE_USER);
2109     fw_cfg_add_file(fw_cfg, name, buf, size);
2110     fw_cfg_reset_order_override(fw_cfg);
2111     return 0;
2112 }
2113
2114 static int device_help_func(void *opaque, QemuOpts *opts, Error **errp)
2115 {
2116     return qdev_device_help(opts);
2117 }
2118
2119 static int device_init_func(void *opaque, QemuOpts *opts, Error **errp)
2120 {
2121     DeviceState *dev;
2122
2123     dev = qdev_device_add(opts, errp);
2124     if (!dev && *errp) {
2125         error_report_err(*errp);
2126         return -1;
2127     } else if (dev) {
2128         object_unref(OBJECT(dev));
2129     }
2130     return 0;
2131 }
2132
2133 static int chardev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2134 {
2135     Error *local_err = NULL;
2136
2137     if (!qemu_chr_new_from_opts(opts, NULL, &local_err)) {
2138         if (local_err) {
2139             error_propagate(errp, local_err);
2140             return -1;
2141         }
2142         exit(0);
2143     }
2144     return 0;
2145 }
2146
2147 #ifdef CONFIG_VIRTFS
2148 static int fsdev_init_func(void *opaque, QemuOpts *opts, Error **errp)
2149 {
2150     return qemu_fsdev_add(opts, errp);
2151 }
2152 #endif
2153
2154 static int mon_init_func(void *opaque, QemuOpts *opts, Error **errp)
2155 {
2156     return monitor_init_opts(opts, errp);
2157 }
2158
2159 static void monitor_parse(const char *optarg, const char *mode, bool pretty)
2160 {
2161     static int monitor_device_index = 0;
2162     QemuOpts *opts;
2163     const char *p;
2164     char label[32];
2165
2166     if (strstart(optarg, "chardev:", &p)) {
2167         snprintf(label, sizeof(label), "%s", p);
2168     } else {
2169         snprintf(label, sizeof(label), "compat_monitor%d",
2170                  monitor_device_index);
2171         opts = qemu_chr_parse_compat(label, optarg, true);
2172         if (!opts) {
2173             error_report("parse error: %s", optarg);
2174             exit(1);
2175         }
2176     }
2177
2178     opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, &error_fatal);
2179     qemu_opt_set(opts, "mode", mode, &error_abort);
2180     qemu_opt_set(opts, "chardev", label, &error_abort);
2181     if (!strcmp(mode, "control")) {
2182         qemu_opt_set_bool(opts, "pretty", pretty, &error_abort);
2183     } else {
2184         assert(pretty == false);
2185     }
2186     monitor_device_index++;
2187 }
2188
2189 struct device_config {
2190     enum {
2191         DEV_USB,       /* -usbdevice     */
2192         DEV_SERIAL,    /* -serial        */
2193         DEV_PARALLEL,  /* -parallel      */
2194         DEV_DEBUGCON,  /* -debugcon */
2195         DEV_GDB,       /* -gdb, -s */
2196         DEV_SCLP,      /* s390 sclp */
2197     } type;
2198     const char *cmdline;
2199     Location loc;
2200     QTAILQ_ENTRY(device_config) next;
2201 };
2202
2203 static QTAILQ_HEAD(, device_config) device_configs =
2204     QTAILQ_HEAD_INITIALIZER(device_configs);
2205
2206 static void add_device_config(int type, const char *cmdline)
2207 {
2208     struct device_config *conf;
2209
2210     conf = g_malloc0(sizeof(*conf));
2211     conf->type = type;
2212     conf->cmdline = cmdline;
2213     loc_save(&conf->loc);
2214     QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2215 }
2216
2217 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2218 {
2219     struct device_config *conf;
2220     int rc;
2221
2222     QTAILQ_FOREACH(conf, &device_configs, next) {
2223         if (conf->type != type)
2224             continue;
2225         loc_push_restore(&conf->loc);
2226         rc = func(conf->cmdline);
2227         loc_pop(&conf->loc);
2228         if (rc) {
2229             return rc;
2230         }
2231     }
2232     return 0;
2233 }
2234
2235 static void qemu_disable_default_devices(void)
2236 {
2237     MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2238
2239     qemu_opts_foreach(qemu_find_opts("device"),
2240                       default_driver_check, NULL, NULL);
2241     qemu_opts_foreach(qemu_find_opts("global"),
2242                       default_driver_check, NULL, NULL);
2243
2244     if (!vga_model && !default_vga) {
2245         vga_interface_type = VGA_DEVICE;
2246     }
2247     if (!has_defaults || machine_class->no_serial) {
2248         default_serial = 0;
2249     }
2250     if (!has_defaults || machine_class->no_parallel) {
2251         default_parallel = 0;
2252     }
2253     if (!has_defaults || machine_class->no_floppy) {
2254         default_floppy = 0;
2255     }
2256     if (!has_defaults || machine_class->no_cdrom) {
2257         default_cdrom = 0;
2258     }
2259     if (!has_defaults || machine_class->no_sdcard) {
2260         default_sdcard = 0;
2261     }
2262     if (!has_defaults) {
2263         default_monitor = 0;
2264         default_net = 0;
2265         default_vga = 0;
2266     }
2267 }
2268
2269 static void qemu_create_default_devices(void)
2270 {
2271     MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2272
2273     if (is_daemonized()) {
2274         /* According to documentation and historically, -nographic redirects
2275          * serial port, parallel port and monitor to stdio, which does not work
2276          * with -daemonize.  We can redirect these to null instead, but since
2277          * -nographic is legacy, let's just error out.
2278          * We disallow -nographic only if all other ports are not redirected
2279          * explicitly, to not break existing legacy setups which uses
2280          * -nographic _and_ redirects all ports explicitly - this is valid
2281          * usage, -nographic is just a no-op in this case.
2282          */
2283         if (nographic
2284             && (default_parallel || default_serial || default_monitor)) {
2285             error_report("-nographic cannot be used with -daemonize");
2286             exit(1);
2287         }
2288     }
2289
2290     if (nographic) {
2291         if (default_parallel)
2292             add_device_config(DEV_PARALLEL, "null");
2293         if (default_serial && default_monitor) {
2294             add_device_config(DEV_SERIAL, "mon:stdio");
2295         } else {
2296             if (default_serial)
2297                 add_device_config(DEV_SERIAL, "stdio");
2298             if (default_monitor)
2299                 monitor_parse("stdio", "readline", false);
2300         }
2301     } else {
2302         if (default_serial)
2303             add_device_config(DEV_SERIAL, "vc:80Cx24C");
2304         if (default_parallel)
2305             add_device_config(DEV_PARALLEL, "vc:80Cx24C");
2306         if (default_monitor)
2307             monitor_parse("vc:80Cx24C", "readline", false);
2308     }
2309
2310     if (default_net) {
2311         QemuOptsList *net = qemu_find_opts("net");
2312         qemu_opts_parse(net, "nic", true, &error_abort);
2313 #ifdef CONFIG_SLIRP
2314         qemu_opts_parse(net, "user", true, &error_abort);
2315 #endif
2316     }
2317
2318 #if defined(CONFIG_VNC)
2319     if (!QTAILQ_EMPTY(&(qemu_find_opts("vnc")->head))) {
2320         display_remote++;
2321     }
2322 #endif
2323     if (dpy.type == DISPLAY_TYPE_DEFAULT && !display_remote) {
2324         if (!qemu_display_find_default(&dpy)) {
2325             dpy.type = DISPLAY_TYPE_NONE;
2326 #if defined(CONFIG_VNC)
2327             vnc_parse("localhost:0,to=99,id=default", &error_abort);
2328 #endif
2329         }
2330     }
2331     if (dpy.type == DISPLAY_TYPE_DEFAULT) {
2332         dpy.type = DISPLAY_TYPE_NONE;
2333     }
2334
2335     /* If no default VGA is requested, the default is "none".  */
2336     if (default_vga) {
2337         vga_model = get_default_vga_model(machine_class);
2338     }
2339     if (vga_model) {
2340         select_vgahw(machine_class, vga_model);
2341     }
2342 }
2343
2344 static int serial_parse(const char *devname)
2345 {
2346     int index = num_serial_hds;
2347     char label[32];
2348
2349     if (strcmp(devname, "none") == 0)
2350         return 0;
2351     snprintf(label, sizeof(label), "serial%d", index);
2352     serial_hds = g_renew(Chardev *, serial_hds, index + 1);
2353
2354     serial_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2355     if (!serial_hds[index]) {
2356         error_report("could not connect serial device"
2357                      " to character backend '%s'", devname);
2358         return -1;
2359     }
2360     num_serial_hds++;
2361     return 0;
2362 }
2363
2364 Chardev *serial_hd(int i)
2365 {
2366     assert(i >= 0);
2367     if (i < num_serial_hds) {
2368         return serial_hds[i];
2369     }
2370     return NULL;
2371 }
2372
2373 int serial_max_hds(void)
2374 {
2375     return num_serial_hds;
2376 }
2377
2378 static int parallel_parse(const char *devname)
2379 {
2380     static int index = 0;
2381     char label[32];
2382
2383     if (strcmp(devname, "none") == 0)
2384         return 0;
2385     if (index == MAX_PARALLEL_PORTS) {
2386         error_report("too many parallel ports");
2387         exit(1);
2388     }
2389     snprintf(label, sizeof(label), "parallel%d", index);
2390     parallel_hds[index] = qemu_chr_new_mux_mon(label, devname, NULL);
2391     if (!parallel_hds[index]) {
2392         error_report("could not connect parallel device"
2393                      " to character backend '%s'", devname);
2394         return -1;
2395     }
2396     index++;
2397     return 0;
2398 }
2399
2400 static int debugcon_parse(const char *devname)
2401 {
2402     QemuOpts *opts;
2403
2404     if (!qemu_chr_new_mux_mon("debugcon", devname, NULL)) {
2405         error_report("invalid character backend '%s'", devname);
2406         exit(1);
2407     }
2408     opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2409     if (!opts) {
2410         error_report("already have a debugcon device");
2411         exit(1);
2412     }
2413     qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);
2414     qemu_opt_set(opts, "chardev", "debugcon", &error_abort);
2415     return 0;
2416 }
2417
2418 static gint machine_class_cmp(gconstpointer a, gconstpointer b)
2419 {
2420     const MachineClass *mc1 = a, *mc2 = b;
2421     int res;
2422
2423     if (mc1->family == NULL) {
2424         if (mc2->family == NULL) {
2425             /* Compare standalone machine types against each other; they sort
2426              * in increasing order.
2427              */
2428             return strcmp(object_class_get_name(OBJECT_CLASS(mc1)),
2429                           object_class_get_name(OBJECT_CLASS(mc2)));
2430         }
2431
2432         /* Standalone machine types sort after families. */
2433         return 1;
2434     }
2435
2436     if (mc2->family == NULL) {
2437         /* Families sort before standalone machine types. */
2438         return -1;
2439     }
2440
2441     /* Families sort between each other alphabetically increasingly. */
2442     res = strcmp(mc1->family, mc2->family);
2443     if (res != 0) {
2444         return res;
2445     }
2446
2447     /* Within the same family, machine types sort in decreasing order. */
2448     return strcmp(object_class_get_name(OBJECT_CLASS(mc2)),
2449                   object_class_get_name(OBJECT_CLASS(mc1)));
2450 }
2451
2452 static MachineClass *machine_parse(const char *name, GSList *machines)
2453 {
2454     MachineClass *mc;
2455     GSList *el;
2456
2457     if (is_help_option(name)) {
2458         printf("Supported machines are:\n");
2459         machines = g_slist_sort(machines, machine_class_cmp);
2460         for (el = machines; el; el = el->next) {
2461             MachineClass *mc = el->data;
2462             if (mc->alias) {
2463                 printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);
2464             }
2465             printf("%-20s %s%s%s\n", mc->name, mc->desc,
2466                    mc->is_default ? " (default)" : "",
2467                    mc->deprecation_reason ? " (deprecated)" : "");
2468         }
2469         exit(0);
2470     }
2471
2472     mc = find_machine(name, machines);
2473     if (!mc) {
2474         error_report("unsupported machine type");
2475         error_printf("Use -machine help to list supported machines\n");
2476         exit(1);
2477     }
2478     return mc;
2479 }
2480
2481 void qemu_add_exit_notifier(Notifier *notify)
2482 {
2483     notifier_list_add(&exit_notifiers, notify);
2484 }
2485
2486 void qemu_remove_exit_notifier(Notifier *notify)
2487 {
2488     notifier_remove(notify);
2489 }
2490
2491 static void qemu_run_exit_notifiers(void)
2492 {
2493     notifier_list_notify(&exit_notifiers, NULL);
2494 }
2495
2496 static const char *pid_file;
2497 static Notifier qemu_unlink_pidfile_notifier;
2498
2499 static void qemu_unlink_pidfile(Notifier *n, void *data)
2500 {
2501     if (pid_file) {
2502         unlink(pid_file);
2503     }
2504 }
2505
2506 bool machine_init_done;
2507
2508 void qemu_add_machine_init_done_notifier(Notifier *notify)
2509 {
2510     notifier_list_add(&machine_init_done_notifiers, notify);
2511     if (machine_init_done) {
2512         notify->notify(notify, NULL);
2513     }
2514 }
2515
2516 void qemu_remove_machine_init_done_notifier(Notifier *notify)
2517 {
2518     notifier_remove(notify);
2519 }
2520
2521 static void qemu_run_machine_init_done_notifiers(void)
2522 {
2523     machine_init_done = true;
2524     notifier_list_notify(&machine_init_done_notifiers, NULL);
2525 }
2526
2527 static const QEMUOption *lookup_opt(int argc, char **argv,
2528                                     const char **poptarg, int *poptind)
2529 {
2530     const QEMUOption *popt;
2531     int optind = *poptind;
2532     char *r = argv[optind];
2533     const char *optarg;
2534
2535     loc_set_cmdline(argv, optind, 1);
2536     optind++;
2537     /* Treat --foo the same as -foo.  */
2538     if (r[1] == '-')
2539         r++;
2540     popt = qemu_options;
2541     for(;;) {
2542         if (!popt->name) {
2543             error_report("invalid option");
2544             exit(1);
2545         }
2546         if (!strcmp(popt->name, r + 1))
2547             break;
2548         popt++;
2549     }
2550     if (popt->flags & HAS_ARG) {
2551         if (optind >= argc) {
2552             error_report("requires an argument");
2553             exit(1);
2554         }
2555         optarg = argv[optind++];
2556         loc_set_cmdline(argv, optind - 2, 2);
2557     } else {
2558         optarg = NULL;
2559     }
2560
2561     *poptarg = optarg;
2562     *poptind = optind;
2563
2564     return popt;
2565 }
2566
2567 static MachineClass *select_machine(void)
2568 {
2569     GSList *machines = object_class_get_list(TYPE_MACHINE, false);
2570     MachineClass *machine_class = find_default_machine(machines);
2571     const char *optarg;
2572     QemuOpts *opts;
2573     Location loc;
2574
2575     loc_push_none(&loc);
2576
2577     opts = qemu_get_machine_opts();
2578     qemu_opts_loc_restore(opts);
2579
2580     optarg = qemu_opt_get(opts, "type");
2581     if (optarg) {
2582         machine_class = machine_parse(optarg, machines);
2583     }
2584
2585     if (!machine_class) {
2586         error_report("No machine specified, and there is no default");
2587         error_printf("Use -machine help to list supported machines\n");
2588         exit(1);
2589     }
2590
2591     loc_pop(&loc);
2592     g_slist_free(machines);
2593     return machine_class;
2594 }
2595
2596 static int object_parse_property_opt(Object *obj,
2597                                      const char *name, const char *value,
2598                                      const char *skip, Error **errp)
2599 {
2600     if (g_str_equal(name, skip)) {
2601         return 0;
2602     }
2603
2604     if (!object_property_parse(obj, name, value, errp)) {
2605         return -1;
2606     }
2607
2608     return 0;
2609 }
2610
2611 static int machine_set_property(void *opaque,
2612                                 const char *name, const char *value,
2613                                 Error **errp)
2614 {
2615     g_autofree char *qom_name = g_strdup(name);
2616     char *p;
2617
2618     for (p = qom_name; *p; p++) {
2619         if (*p == '_') {
2620             *p = '-';
2621         }
2622     }
2623
2624     /* Legacy options do not correspond to MachineState properties.  */
2625     if (g_str_equal(qom_name, "accel")) {
2626         return 0;
2627     }
2628     if (g_str_equal(qom_name, "igd-passthru")) {
2629         object_register_sugar_prop(ACCEL_CLASS_NAME("xen"), qom_name, value);
2630         return 0;
2631     }
2632     if (g_str_equal(qom_name, "kvm-shadow-mem")) {
2633         object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), qom_name, value);
2634         return 0;
2635     }
2636     if (g_str_equal(qom_name, "kernel-irqchip")) {
2637         object_register_sugar_prop(ACCEL_CLASS_NAME("kvm"), qom_name, value);
2638         object_register_sugar_prop(ACCEL_CLASS_NAME("whpx"), qom_name, value);
2639         return 0;
2640     }
2641
2642     return object_parse_property_opt(opaque, name, value, "type", errp);
2643 }
2644
2645 /*
2646  * Initial object creation happens before all other
2647  * QEMU data types are created. The majority of objects
2648  * can be created at this point. The rng-egd object
2649  * cannot be created here, as it depends on the chardev
2650  * already existing.
2651  */
2652 static bool object_create_early(const char *type, QemuOpts *opts)
2653 {
2654     if (user_creatable_print_help(type, opts)) {
2655         exit(0);
2656     }
2657
2658     /*
2659      * Objects should not be made "delayed" without a reason.  If you
2660      * add one, state the reason in a comment!
2661      */
2662
2663     /* Reason: rng-egd property "chardev" */
2664     if (g_str_equal(type, "rng-egd")) {
2665         return false;
2666     }
2667
2668 #if defined(CONFIG_VHOST_USER) && defined(CONFIG_LINUX)
2669     /* Reason: cryptodev-vhost-user property "chardev" */
2670     if (g_str_equal(type, "cryptodev-vhost-user")) {
2671         return false;
2672     }
2673 #endif
2674
2675     /* Reason: vhost-user-blk-server property "node-name" */
2676     if (g_str_equal(type, "vhost-user-blk-server")) {
2677         return false;
2678     }
2679     /*
2680      * Reason: filter-* property "netdev" etc.
2681      */
2682     if (g_str_equal(type, "filter-buffer") ||
2683         g_str_equal(type, "filter-dump") ||
2684         g_str_equal(type, "filter-mirror") ||
2685         g_str_equal(type, "filter-redirector") ||
2686         g_str_equal(type, "colo-compare") ||
2687         g_str_equal(type, "filter-rewriter") ||
2688         g_str_equal(type, "filter-replay")) {
2689         return false;
2690     }
2691
2692     /* Memory allocation by backends needs to be done
2693      * after configure_accelerator() (due to the tcg_enabled()
2694      * checks at memory_region_init_*()).
2695      *
2696      * Also, allocation of large amounts of memory may delay
2697      * chardev initialization for too long, and trigger timeouts
2698      * on software that waits for a monitor socket to be created
2699      * (e.g. libvirt).
2700      */
2701     if (g_str_has_prefix(type, "memory-backend-")) {
2702         return false;
2703     }
2704
2705     return true;
2706 }
2707
2708 static void qemu_apply_machine_options(void)
2709 {
2710     MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2711     QemuOpts *machine_opts = qemu_get_machine_opts();
2712     QemuOpts *opts;
2713
2714     qemu_opt_foreach(machine_opts, machine_set_property, current_machine,
2715                      &error_fatal);
2716     current_machine->ram_size = ram_size;
2717     current_machine->maxram_size = maxram_size;
2718     current_machine->ram_slots = ram_slots;
2719
2720     opts = qemu_opts_find(qemu_find_opts("boot-opts"), NULL);
2721     if (opts) {
2722         boot_order = qemu_opt_get(opts, "order");
2723         if (boot_order) {
2724             validate_bootdevices(boot_order, &error_fatal);
2725         }
2726
2727         boot_once = qemu_opt_get(opts, "once");
2728         if (boot_once) {
2729             validate_bootdevices(boot_once, &error_fatal);
2730         }
2731
2732         boot_menu = qemu_opt_get_bool(opts, "menu", boot_menu);
2733         boot_strict = qemu_opt_get_bool(opts, "strict", false);
2734     }
2735
2736     if (!boot_order) {
2737         boot_order = machine_class->default_boot_order;
2738     }
2739
2740     current_machine->boot_order = boot_order;
2741
2742     if (semihosting_enabled() && !semihosting_get_argc()) {
2743         const char *kernel_filename = qemu_opt_get(machine_opts, "kernel");
2744         const char *kernel_cmdline = qemu_opt_get(machine_opts, "append") ?: "";
2745         /* fall back to the -kernel/-append */
2746         semihosting_arg_fallback(kernel_filename, kernel_cmdline);
2747     }
2748
2749 }
2750
2751 static void qemu_create_early_backends(void)
2752 {
2753     MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
2754
2755     if ((alt_grab || ctrl_grab) && dpy.type != DISPLAY_TYPE_SDL) {
2756         error_report("-alt-grab and -ctrl-grab are only valid "
2757                      "for SDL, ignoring option");
2758     }
2759     if (dpy.has_window_close &&
2760         (dpy.type != DISPLAY_TYPE_GTK && dpy.type != DISPLAY_TYPE_SDL)) {
2761         error_report("-no-quit is only valid for GTK and SDL, "
2762                      "ignoring option");
2763     }
2764
2765     qemu_display_early_init(&dpy);
2766     qemu_console_early_init();
2767
2768     if (dpy.has_gl && dpy.gl != DISPLAYGL_MODE_OFF && display_opengl == 0) {
2769 #if defined(CONFIG_OPENGL)
2770         error_report("OpenGL is not supported by the display");
2771 #else
2772         error_report("OpenGL support is disabled");
2773 #endif
2774         exit(1);
2775     }
2776
2777     qemu_opts_foreach(qemu_find_opts("object"),
2778                       user_creatable_add_opts_foreach,
2779                       object_create_early, &error_fatal);
2780
2781     /* spice needs the timers to be initialized by this point */
2782     /* spice must initialize before audio as it changes the default auiodev */
2783     /* spice must initialize before chardevs (for spicevmc and spiceport) */
2784     qemu_spice.init();
2785
2786     qemu_opts_foreach(qemu_find_opts("chardev"),
2787                       chardev_init_func, NULL, &error_fatal);
2788
2789 #ifdef CONFIG_VIRTFS
2790     qemu_opts_foreach(qemu_find_opts("fsdev"),
2791                       fsdev_init_func, NULL, &error_fatal);
2792 #endif
2793
2794     /*
2795      * Note: we need to create audio and block backends before
2796      * machine_set_property(), so machine properties can refer to
2797      * them.
2798      */
2799     configure_blockdev(&bdo_queue, machine_class, snapshot);
2800     audio_init_audiodevs();
2801 }
2802
2803
2804 /*
2805  * The remainder of object creation happens after the
2806  * creation of chardev, fsdev, net clients and device data types.
2807  */
2808 static bool object_create_late(const char *type, QemuOpts *opts)
2809 {
2810     return !object_create_early(type, opts);
2811 }
2812
2813 static void qemu_create_late_backends(void)
2814 {
2815     if (qtest_chrdev) {
2816         qtest_server_init(qtest_chrdev, qtest_log, &error_fatal);
2817     }
2818
2819     net_init_clients(&error_fatal);
2820
2821     qemu_opts_foreach(qemu_find_opts("object"),
2822                       user_creatable_add_opts_foreach,
2823                       object_create_late, &error_fatal);
2824
2825     if (tpm_init() < 0) {
2826         exit(1);
2827     }
2828
2829     qemu_opts_foreach(qemu_find_opts("mon"),
2830                       mon_init_func, NULL, &error_fatal);
2831
2832     if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
2833         exit(1);
2834     if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
2835         exit(1);
2836     if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
2837         exit(1);
2838
2839     /* now chardevs have been created we may have semihosting to connect */
2840     qemu_semihosting_connect_chardevs();
2841     qemu_semihosting_console_init();
2842 }
2843
2844 static bool have_custom_ram_size(void)
2845 {
2846     QemuOpts *opts = qemu_find_opts_singleton("memory");
2847     return !!qemu_opt_get_size(opts, "size", 0);
2848 }
2849
2850 static void qemu_resolve_machine_memdev(void)
2851 {
2852     if (current_machine->ram_memdev_id) {
2853         Object *backend;
2854         ram_addr_t backend_size;
2855
2856         backend = object_resolve_path_type(current_machine->ram_memdev_id,
2857                                            TYPE_MEMORY_BACKEND, NULL);
2858         if (!backend) {
2859             error_report("Memory backend '%s' not found",
2860                          current_machine->ram_memdev_id);
2861             exit(EXIT_FAILURE);
2862         }
2863         backend_size = object_property_get_uint(backend, "size",  &error_abort);
2864         if (have_custom_ram_size() && backend_size != ram_size) {
2865                 error_report("Size specified by -m option must match size of "
2866                              "explicitly specified 'memory-backend' property");
2867                 exit(EXIT_FAILURE);
2868         }
2869         if (mem_path) {
2870             error_report("'-mem-path' can't be used together with"
2871                          "'-machine memory-backend'");
2872             exit(EXIT_FAILURE);
2873         }
2874         ram_size = backend_size;
2875     }
2876
2877     if (!xen_enabled()) {
2878         /* On 32-bit hosts, QEMU is limited by virtual address space */
2879         if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
2880             error_report("at most 2047 MB RAM can be simulated");
2881             exit(1);
2882         }
2883     }
2884 }
2885
2886 static void set_memory_options(MachineClass *mc)
2887 {
2888     uint64_t sz;
2889     const char *mem_str;
2890     const ram_addr_t default_ram_size = mc->default_ram_size;
2891     QemuOpts *opts = qemu_find_opts_singleton("memory");
2892     Location loc;
2893
2894     loc_push_none(&loc);
2895     qemu_opts_loc_restore(opts);
2896
2897     sz = 0;
2898     mem_str = qemu_opt_get(opts, "size");
2899     if (mem_str) {
2900         if (!*mem_str) {
2901             error_report("missing 'size' option value");
2902             exit(EXIT_FAILURE);
2903         }
2904
2905         sz = qemu_opt_get_size(opts, "size", ram_size);
2906
2907         /* Fix up legacy suffix-less format */
2908         if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {
2909             uint64_t overflow_check = sz;
2910
2911             sz *= MiB;
2912             if (sz / MiB != overflow_check) {
2913                 error_report("too large 'size' option value");
2914                 exit(EXIT_FAILURE);
2915             }
2916         }
2917     }
2918
2919     /* backward compatibility behaviour for case "-m 0" */
2920     if (sz == 0) {
2921         sz = default_ram_size;
2922     }
2923
2924     sz = QEMU_ALIGN_UP(sz, 8192);
2925     if (mc->fixup_ram_size) {
2926         sz = mc->fixup_ram_size(sz);
2927     }
2928     ram_size = sz;
2929     if (ram_size != sz) {
2930         error_report("ram size too large");
2931         exit(EXIT_FAILURE);
2932     }
2933
2934     /* store value for the future use */
2935     qemu_opt_set_number(opts, "size", ram_size, &error_abort);
2936     maxram_size = ram_size;
2937
2938     if (qemu_opt_get(opts, "maxmem")) {
2939         uint64_t slots;
2940
2941         sz = qemu_opt_get_size(opts, "maxmem", 0);
2942         slots = qemu_opt_get_number(opts, "slots", 0);
2943         if (sz < ram_size) {
2944             error_report("invalid value of -m option maxmem: "
2945                          "maximum memory size (0x%" PRIx64 ") must be at least "
2946                          "the initial memory size (0x" RAM_ADDR_FMT ")",
2947                          sz, ram_size);
2948             exit(EXIT_FAILURE);
2949         } else if (slots && sz == ram_size) {
2950             error_report("invalid value of -m option maxmem: "
2951                          "memory slots were specified but maximum memory size "
2952                          "(0x%" PRIx64 ") is equal to the initial memory size "
2953                          "(0x" RAM_ADDR_FMT ")", sz, ram_size);
2954             exit(EXIT_FAILURE);
2955         }
2956
2957         maxram_size = sz;
2958         ram_slots = slots;
2959     } else if (qemu_opt_get(opts, "slots")) {
2960         error_report("invalid -m option value: missing 'maxmem' option");
2961         exit(EXIT_FAILURE);
2962     }
2963
2964     loc_pop(&loc);
2965 }
2966
2967 static void qemu_create_machine(MachineClass *machine_class)
2968 {
2969     object_set_machine_compat_props(machine_class->compat_props);
2970
2971     set_memory_options(machine_class);
2972
2973     current_machine = MACHINE(object_new_with_class(OBJECT_CLASS(machine_class)));
2974     if (machine_help_func(qemu_get_machine_opts(), current_machine)) {
2975         exit(0);
2976     }
2977     object_property_add_child(object_get_root(), "machine",
2978                               OBJECT(current_machine));
2979     object_property_add_child(container_get(OBJECT(current_machine),
2980                                             "/unattached"),
2981                               "sysbus", OBJECT(sysbus_get_default()));
2982
2983     if (machine_class->minimum_page_bits) {
2984         if (!set_preferred_target_page_bits(machine_class->minimum_page_bits)) {
2985             /* This would be a board error: specifying a minimum smaller than
2986              * a target's compile-time fixed setting.
2987              */
2988             g_assert_not_reached();
2989         }
2990     }
2991
2992     cpu_exec_init_all();
2993     page_size_init();
2994
2995     if (machine_class->hw_version) {
2996         qemu_set_hw_version(machine_class->hw_version);
2997     }
2998
2999     machine_smp_parse(current_machine,
3000         qemu_opts_find(qemu_find_opts("smp-opts"), NULL), &error_fatal);
3001
3002     /*
3003      * Get the default machine options from the machine if it is not already
3004      * specified either by the configuration file or by the command line.
3005      */
3006     if (machine_class->default_machine_opts) {
3007         qemu_opts_set_defaults(qemu_find_opts("machine"),
3008                                machine_class->default_machine_opts, 0);
3009     }
3010 }
3011
3012 static int global_init_func(void *opaque, QemuOpts *opts, Error **errp)
3013 {
3014     GlobalProperty *g;
3015
3016     g = g_malloc0(sizeof(*g));
3017     g->driver   = qemu_opt_get(opts, "driver");
3018     g->property = qemu_opt_get(opts, "property");
3019     g->value    = qemu_opt_get(opts, "value");
3020     qdev_prop_register_global(g);
3021     return 0;
3022 }
3023
3024 static int qemu_read_default_config_file(void)
3025 {
3026     int ret;
3027     g_autofree char *file = get_relocated_path(CONFIG_QEMU_CONFDIR "/qemu.conf");
3028
3029     ret = qemu_read_config_file(file);
3030     if (ret < 0 && ret != -ENOENT) {
3031         return ret;
3032     }
3033
3034     return 0;
3035 }
3036
3037 static void user_register_global_props(void)
3038 {
3039     qemu_opts_foreach(qemu_find_opts("global"),
3040                       global_init_func, NULL, NULL);
3041 }
3042
3043 static int do_configure_icount(void *opaque, QemuOpts *opts, Error **errp)
3044 {
3045     icount_configure(opts, errp);
3046     return 0;
3047 }
3048
3049 static int accelerator_set_property(void *opaque,
3050                                 const char *name, const char *value,
3051                                 Error **errp)
3052 {
3053     return object_parse_property_opt(opaque, name, value, "accel", errp);
3054 }
3055
3056 static int do_configure_accelerator(void *opaque, QemuOpts *opts, Error **errp)
3057 {
3058     bool *p_init_failed = opaque;
3059     const char *acc = qemu_opt_get(opts, "accel");
3060     AccelClass *ac = accel_find(acc);
3061     AccelState *accel;
3062     int ret;
3063     bool qtest_with_kvm;
3064
3065     qtest_with_kvm = g_str_equal(acc, "kvm") && qtest_chrdev != NULL;
3066
3067     if (!ac) {
3068         *p_init_failed = true;
3069         if (!qtest_with_kvm) {
3070             error_report("invalid accelerator %s", acc);
3071         }
3072         return 0;
3073     }
3074     accel = ACCEL(object_new_with_class(OBJECT_CLASS(ac)));
3075     object_apply_compat_props(OBJECT(accel));
3076     qemu_opt_foreach(opts, accelerator_set_property,
3077                      accel,
3078                      &error_fatal);
3079
3080     ret = accel_init_machine(accel, current_machine);
3081     if (ret < 0) {
3082         *p_init_failed = true;
3083         if (!qtest_with_kvm || ret != -ENOENT) {
3084             error_report("failed to initialize %s: %s", acc, strerror(-ret));
3085         }
3086         return 0;
3087     }
3088
3089     return 1;
3090 }
3091
3092 static void configure_accelerators(const char *progname)
3093 {
3094     const char *accel;
3095     bool init_failed = false;
3096
3097     qemu_opts_foreach(qemu_find_opts("icount"),
3098                       do_configure_icount, NULL, &error_fatal);
3099
3100     accel = qemu_opt_get(qemu_get_machine_opts(), "accel");
3101     if (QTAILQ_EMPTY(&qemu_accel_opts.head)) {
3102         char **accel_list, **tmp;
3103
3104         if (accel == NULL) {
3105             /* Select the default accelerator */
3106             bool have_tcg = accel_find("tcg");
3107             bool have_kvm = accel_find("kvm");
3108
3109             if (have_tcg && have_kvm) {
3110                 if (g_str_has_suffix(progname, "kvm")) {
3111                     /* If the program name ends with "kvm", we prefer KVM */
3112                     accel = "kvm:tcg";
3113                 } else {
3114                     accel = "tcg:kvm";
3115                 }
3116             } else if (have_kvm) {
3117                 accel = "kvm";
3118             } else if (have_tcg) {
3119                 accel = "tcg";
3120             } else {
3121                 error_report("No accelerator selected and"
3122                              " no default accelerator available");
3123                 exit(1);
3124             }
3125         }
3126         accel_list = g_strsplit(accel, ":", 0);
3127
3128         for (tmp = accel_list; *tmp; tmp++) {
3129             /*
3130              * Filter invalid accelerators here, to prevent obscenities
3131              * such as "-machine accel=tcg,,thread=single".
3132              */
3133             if (accel_find(*tmp)) {
3134                 qemu_opts_parse_noisily(qemu_find_opts("accel"), *tmp, true);
3135             } else {
3136                 init_failed = true;
3137                 error_report("invalid accelerator %s", *tmp);
3138             }
3139         }
3140         g_strfreev(accel_list);
3141     } else {
3142         if (accel != NULL) {
3143             error_report("The -accel and \"-machine accel=\" options are incompatible");
3144             exit(1);
3145         }
3146     }
3147
3148     if (!qemu_opts_foreach(qemu_find_opts("accel"),
3149                            do_configure_accelerator, &init_failed, &error_fatal)) {
3150         if (!init_failed) {
3151             error_report("no accelerator found");
3152         }
3153         exit(1);
3154     }
3155
3156     if (init_failed && !qtest_chrdev) {
3157         AccelClass *ac = ACCEL_GET_CLASS(current_accel());
3158         error_report("falling back to %s", ac->name);
3159     }
3160
3161     if (icount_enabled() && !tcg_enabled()) {
3162         error_report("-icount is not allowed with hardware virtualization");
3163         exit(1);
3164     }
3165 }
3166
3167 static void create_default_memdev(MachineState *ms, const char *path)
3168 {
3169     Object *obj;
3170     MachineClass *mc = MACHINE_GET_CLASS(ms);
3171
3172     obj = object_new(path ? TYPE_MEMORY_BACKEND_FILE : TYPE_MEMORY_BACKEND_RAM);
3173     if (path) {
3174         object_property_set_str(obj, "mem-path", path, &error_fatal);
3175     }
3176     object_property_set_int(obj, "size", ms->ram_size, &error_fatal);
3177     object_property_add_child(object_get_objects_root(), mc->default_ram_id,
3178                               obj);
3179     /* Ensure backend's memory region name is equal to mc->default_ram_id */
3180     object_property_set_bool(obj, "x-use-canonical-path-for-ramblock-id",
3181                              false, &error_fatal);
3182     user_creatable_complete(USER_CREATABLE(obj), &error_fatal);
3183     object_unref(obj);
3184     object_property_set_str(OBJECT(ms), "memory-backend", mc->default_ram_id,
3185                             &error_fatal);
3186 }
3187
3188 /*
3189  * Find a likely location for support files using the location of the binary.
3190  * When running from the build tree this will be "$bindir/pc-bios".
3191  * Otherwise, this is CONFIG_QEMU_DATADIR (possibly relocated).
3192  *
3193  * The caller must use g_free() to free the returned data when it is
3194  * no longer required.
3195  */
3196 static char *find_datadir(void)
3197 {
3198     g_autofree char *dir = NULL;
3199
3200     dir = g_build_filename(qemu_get_exec_dir(), "pc-bios", NULL);
3201     if (g_file_test(dir, G_FILE_TEST_IS_DIR)) {
3202         return g_steal_pointer(&dir);
3203     }
3204
3205     return get_relocated_path(CONFIG_QEMU_DATADIR);
3206 }
3207
3208 static void qemu_validate_options(void)
3209 {
3210     QemuOpts *machine_opts = qemu_get_machine_opts();
3211     const char *kernel_filename = qemu_opt_get(machine_opts, "kernel");
3212     const char *initrd_filename = qemu_opt_get(machine_opts, "initrd");
3213     const char *kernel_cmdline = qemu_opt_get(machine_opts, "append");
3214
3215     if (kernel_filename == NULL) {
3216          if (kernel_cmdline != NULL) {
3217               error_report("-append only allowed with -kernel option");
3218               exit(1);
3219           }
3220
3221           if (initrd_filename != NULL) {
3222               error_report("-initrd only allowed with -kernel option");
3223               exit(1);
3224           }
3225     }
3226
3227     if (loadvm && preconfig_requested) {
3228         error_report("'preconfig' and 'loadvm' options are "
3229                      "mutually exclusive");
3230         exit(EXIT_FAILURE);
3231     }
3232     if (incoming && preconfig_requested) {
3233         error_report("'preconfig' and 'incoming' options are "
3234                      "mutually exclusive");
3235         exit(EXIT_FAILURE);
3236     }
3237
3238 #ifdef CONFIG_CURSES
3239     if (is_daemonized() && dpy.type == DISPLAY_TYPE_CURSES) {
3240         error_report("curses display cannot be used with -daemonize");
3241         exit(1);
3242     }
3243 #endif
3244 }
3245
3246 static void qemu_process_sugar_options(void)
3247 {
3248     if (mem_prealloc) {
3249         char *val;
3250
3251         val = g_strdup_printf("%d",
3252                  (uint32_t) qemu_opt_get_number(qemu_find_opts_singleton("smp-opts"), "cpus", 1));
3253         object_register_sugar_prop("memory-backend", "prealloc-threads", val);
3254         g_free(val);
3255         object_register_sugar_prop("memory-backend", "prealloc", "on");
3256     }
3257
3258     if (watchdog) {
3259         int i = select_watchdog(watchdog);
3260         if (i > 0)
3261             exit (i == 1 ? 1 : 0);
3262     }
3263 }
3264
3265 static void qemu_process_early_options(void)
3266 {
3267     char **dirs;
3268     int i;
3269
3270 #ifdef CONFIG_SECCOMP
3271     QemuOptsList *olist = qemu_find_opts_err("sandbox", NULL);
3272     if (olist) {
3273         qemu_opts_foreach(olist, parse_sandbox, NULL, &error_fatal);
3274     }
3275 #endif
3276
3277     qemu_opts_foreach(qemu_find_opts("name"),
3278                       parse_name, NULL, &error_fatal);
3279
3280 #ifndef _WIN32
3281     qemu_opts_foreach(qemu_find_opts("add-fd"),
3282                       parse_add_fd, NULL, &error_fatal);
3283
3284     qemu_opts_foreach(qemu_find_opts("add-fd"),
3285                       cleanup_add_fd, NULL, &error_fatal);
3286 #endif
3287
3288     if (!trace_init_backends()) {
3289         exit(1);
3290     }
3291     trace_init_file();
3292
3293     /* Open the logfile at this point and set the log mask if necessary.  */
3294     qemu_set_log_filename(log_file, &error_fatal);
3295     if (log_mask) {
3296         int mask;
3297         mask = qemu_str_to_log_mask(log_mask);
3298         if (!mask) {
3299             qemu_print_log_usage(stdout);
3300             exit(1);
3301         }
3302         qemu_set_log(mask);
3303     } else {
3304         qemu_set_log(0);
3305     }
3306
3307     /* add configured firmware directories */
3308     dirs = g_strsplit(CONFIG_QEMU_FIRMWAREPATH, G_SEARCHPATH_SEPARATOR_S, 0);
3309     for (i = 0; dirs[i] != NULL; i++) {
3310         qemu_add_data_dir(get_relocated_path(dirs[i]));
3311     }
3312     g_strfreev(dirs);
3313
3314     /* try to find datadir relative to the executable path */
3315     qemu_add_data_dir(find_datadir());
3316 }
3317
3318 static void qemu_process_help_options(void)
3319 {
3320     int i;
3321
3322     /*
3323      * Check for -cpu help and -device help before we call select_machine(),
3324      * which will return an error if the architecture has no default machine
3325      * type and the user did not specify one, so that the user doesn't need
3326      * to say '-cpu help -machine something'.
3327      */
3328     if (cpu_option && is_help_option(cpu_option)) {
3329         list_cpus(cpu_option);
3330         exit(0);
3331     }
3332
3333     if (qemu_opts_foreach(qemu_find_opts("device"),
3334                           device_help_func, NULL, NULL)) {
3335         exit(0);
3336     }
3337
3338     /* -L help lists the data directories and exits. */
3339     if (list_data_dirs) {
3340         for (i = 0; i < data_dir_idx; i++) {
3341             printf("%s\n", data_dir[i]);
3342         }
3343         exit(0);
3344     }
3345 }
3346
3347 static void qemu_maybe_daemonize(const char *pid_file)
3348 {
3349     Error *err;
3350
3351     os_daemonize();
3352     rcu_disable_atfork();
3353
3354     if (pid_file && !qemu_write_pidfile(pid_file, &err)) {
3355         error_reportf_err(err, "cannot create PID file: ");
3356         exit(1);
3357     }
3358
3359     qemu_unlink_pidfile_notifier.notify = qemu_unlink_pidfile;
3360     qemu_add_exit_notifier(&qemu_unlink_pidfile_notifier);
3361 }
3362
3363 static void qemu_init_subsystems(void)
3364 {
3365     Error *err;
3366
3367     os_set_line_buffering();
3368
3369     module_call_init(MODULE_INIT_TRACE);
3370
3371     qemu_init_cpu_list();
3372     qemu_init_cpu_loop();
3373     qemu_mutex_lock_iothread();
3374
3375     atexit(qemu_run_exit_notifiers);
3376
3377     module_call_init(MODULE_INIT_QOM);
3378     module_call_init(MODULE_INIT_MIGRATION);
3379
3380     runstate_init();
3381     precopy_infrastructure_init();
3382     postcopy_infrastructure_init();
3383     monitor_init_globals();
3384
3385     if (qcrypto_init(&err) < 0) {
3386         error_reportf_err(err, "cannot initialize crypto: ");
3387         exit(1);
3388     }
3389
3390     os_setup_early_signal_handling();
3391
3392     bdrv_init_with_whitelist();
3393     socket_init();
3394 }
3395
3396 static void qemu_init_displays(void)
3397 {
3398     DisplayState *ds;
3399
3400     /* init local displays */
3401     ds = init_displaystate();
3402     qemu_display_init(ds, &dpy);
3403
3404     /* must be after terminal init, SDL library changes signal handlers */
3405     os_setup_signal_handling();
3406
3407     /* init remote displays */
3408 #ifdef CONFIG_VNC
3409     qemu_opts_foreach(qemu_find_opts("vnc"),
3410                       vnc_init_func, NULL, &error_fatal);
3411 #endif
3412
3413     if (using_spice) {
3414         qemu_spice.display_init();
3415     }
3416 }
3417
3418 /*
3419  * Called after leaving preconfig state.  From here on runstate is
3420  * RUN_STATE_PRELAUNCH or RUN_STATE_INMIGRATE.
3421  */
3422 static void qemu_init_board(void)
3423 {
3424     MachineClass *machine_class = MACHINE_GET_CLASS(current_machine);
3425
3426     if (machine_class->default_ram_id && current_machine->ram_size &&
3427         numa_uses_legacy_mem() && !current_machine->ram_memdev_id) {
3428         create_default_memdev(current_machine, mem_path);
3429     }
3430
3431     /* process plugin before CPUs are created, but once -smp has been parsed */
3432     if (qemu_plugin_load_list(&plugin_list)) {
3433         exit(1);
3434     }
3435
3436     machine_run_board_init(current_machine);
3437
3438     /*
3439      * TODO To drop support for deprecated bogus if=..., move
3440      * drive_check_orphaned() here, replacing this call.  Also drop
3441      * its deprecation warning, along with DriveInfo member
3442      * @claimed_by_board.
3443      */
3444     drive_mark_claimed_by_board();
3445
3446     realtime_init();
3447
3448     if (hax_enabled()) {
3449         /* FIXME: why isn't cpu_synchronize_all_post_init enough? */
3450         hax_sync_vcpus();
3451     }
3452 }
3453
3454 static void qemu_create_cli_devices(void)
3455 {
3456     soundhw_init();
3457
3458     qemu_opts_foreach(qemu_find_opts("fw_cfg"),
3459                       parse_fw_cfg, fw_cfg_find(), &error_fatal);
3460
3461     /* init USB devices */
3462     if (machine_usb(current_machine)) {
3463         if (foreach_device_config(DEV_USB, usb_parse) < 0)
3464             exit(1);
3465     }
3466
3467     /* init generic devices */
3468     rom_set_order_override(FW_CFG_ORDER_OVERRIDE_DEVICE);
3469     qemu_opts_foreach(qemu_find_opts("device"),
3470                       device_init_func, NULL, &error_fatal);
3471     rom_reset_order_override();
3472 }
3473
3474 static void qemu_machine_creation_done(void)
3475 {
3476     cpu_synchronize_all_post_init();
3477
3478     /* Did we create any drives that we failed to create a device for? */
3479     drive_check_orphaned();
3480
3481     /* Don't warn about the default network setup that you get if
3482      * no command line -net or -netdev options are specified. There
3483      * are two cases that we would otherwise complain about:
3484      * (1) board doesn't support a NIC but the implicit "-net nic"
3485      * requested one
3486      * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
3487      * sets up a nic that isn't connected to anything.
3488      */
3489     if (!default_net && (!qtest_enabled() || has_defaults)) {
3490         net_check_clients();
3491     }
3492
3493     if (boot_once) {
3494         qemu_boot_set(boot_once, &error_fatal);
3495         qemu_register_reset(restore_boot_order, g_strdup(boot_order));
3496     }
3497
3498     if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
3499         exit(1);
3500     }
3501
3502     qdev_machine_creation_done();
3503
3504     /* TODO: once all bus devices are qdevified, this should be done
3505      * when bus is created by qdev.c */
3506     /*
3507      * TODO: If we had a main 'reset container' that the whole system
3508      * lived in, we could reset that using the multi-phase reset
3509      * APIs. For the moment, we just reset the sysbus, which will cause
3510      * all devices hanging off it (and all their child buses, recursively)
3511      * to be reset. Note that this will *not* reset any Device objects
3512      * which are not attached to some part of the qbus tree!
3513      */
3514     qemu_register_reset(resettable_cold_reset_fn, sysbus_get_default());
3515     qemu_run_machine_init_done_notifiers();
3516
3517     if (rom_check_and_register_reset() != 0) {
3518         error_report("rom check and register reset failed");
3519         exit(1);
3520     }
3521
3522     replay_start();
3523
3524     /* This checkpoint is required by replay to separate prior clock
3525        reading from the other reads, because timer polling functions query
3526        clock values from the log. */
3527     replay_checkpoint(CHECKPOINT_RESET);
3528     qemu_system_reset(SHUTDOWN_CAUSE_NONE);
3529     register_global_state();
3530 }
3531
3532 void qemu_init(int argc, char **argv, char **envp)
3533 {
3534     QemuOpts *opts;
3535     QemuOpts *icount_opts = NULL, *accel_opts = NULL;
3536     QemuOptsList *olist;
3537     int optind;
3538     const char *optarg;
3539     MachineClass *machine_class;
3540     bool userconfig = true;
3541     FILE *vmstate_dump_file = NULL;
3542
3543     qemu_add_opts(&qemu_drive_opts);
3544     qemu_add_drive_opts(&qemu_legacy_drive_opts);
3545     qemu_add_drive_opts(&qemu_common_drive_opts);
3546     qemu_add_drive_opts(&qemu_drive_opts);
3547     qemu_add_drive_opts(&bdrv_runtime_opts);
3548     qemu_add_opts(&qemu_chardev_opts);
3549     qemu_add_opts(&qemu_device_opts);
3550     qemu_add_opts(&qemu_netdev_opts);
3551     qemu_add_opts(&qemu_nic_opts);
3552     qemu_add_opts(&qemu_net_opts);
3553     qemu_add_opts(&qemu_rtc_opts);
3554     qemu_add_opts(&qemu_global_opts);
3555     qemu_add_opts(&qemu_mon_opts);
3556     qemu_add_opts(&qemu_trace_opts);
3557     qemu_plugin_add_opts();
3558     qemu_add_opts(&qemu_option_rom_opts);
3559     qemu_add_opts(&qemu_machine_opts);
3560     qemu_add_opts(&qemu_accel_opts);
3561     qemu_add_opts(&qemu_mem_opts);
3562     qemu_add_opts(&qemu_smp_opts);
3563     qemu_add_opts(&qemu_boot_opts);
3564     qemu_add_opts(&qemu_add_fd_opts);
3565     qemu_add_opts(&qemu_object_opts);
3566     qemu_add_opts(&qemu_tpmdev_opts);
3567     qemu_add_opts(&qemu_realtime_opts);
3568     qemu_add_opts(&qemu_overcommit_opts);
3569     qemu_add_opts(&qemu_msg_opts);
3570     qemu_add_opts(&qemu_name_opts);
3571     qemu_add_opts(&qemu_numa_opts);
3572     qemu_add_opts(&qemu_icount_opts);
3573     qemu_add_opts(&qemu_semihosting_config_opts);
3574     qemu_add_opts(&qemu_fw_cfg_opts);
3575     module_call_init(MODULE_INIT_OPTS);
3576
3577     error_init(argv[0]);
3578     qemu_init_exec_dir(argv[0]);
3579
3580     qemu_init_subsystems();
3581
3582     /* first pass of option parsing */
3583     optind = 1;
3584     while (optind < argc) {
3585         if (argv[optind][0] != '-') {
3586             /* disk image */
3587             optind++;
3588         } else {
3589             const QEMUOption *popt;
3590
3591             popt = lookup_opt(argc, argv, &optarg, &optind);
3592             switch (popt->index) {
3593             case QEMU_OPTION_nouserconfig:
3594                 userconfig = false;
3595                 break;
3596             }
3597         }
3598     }
3599
3600     if (userconfig) {
3601         if (qemu_read_default_config_file() < 0) {
3602             exit(1);
3603         }
3604     }
3605
3606     /* second pass of option parsing */
3607     optind = 1;
3608     for(;;) {
3609         if (optind >= argc)
3610             break;
3611         if (argv[optind][0] != '-') {
3612             loc_set_cmdline(argv, optind, 1);
3613             drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
3614         } else {
3615             const QEMUOption *popt;
3616
3617             popt = lookup_opt(argc, argv, &optarg, &optind);
3618             if (!(popt->arch_mask & arch_type)) {
3619                 error_report("Option not supported for this target");
3620                 exit(1);
3621             }
3622             switch(popt->index) {
3623             case QEMU_OPTION_cpu:
3624                 /* hw initialization will check this */
3625                 cpu_option = optarg;
3626                 break;
3627             case QEMU_OPTION_hda:
3628             case QEMU_OPTION_hdb:
3629             case QEMU_OPTION_hdc:
3630             case QEMU_OPTION_hdd:
3631                 drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
3632                           HD_OPTS);
3633                 break;
3634             case QEMU_OPTION_blockdev:
3635                 {
3636                     Visitor *v;
3637                     BlockdevOptionsQueueEntry *bdo;
3638
3639                     v = qobject_input_visitor_new_str(optarg, "driver",
3640                                                       &error_fatal);
3641
3642                     bdo = g_new(BlockdevOptionsQueueEntry, 1);
3643                     visit_type_BlockdevOptions(v, NULL, &bdo->bdo,
3644                                                &error_fatal);
3645                     visit_free(v);
3646                     loc_save(&bdo->loc);
3647                     QSIMPLEQ_INSERT_TAIL(&bdo_queue, bdo, entry);
3648                     break;
3649                 }
3650             case QEMU_OPTION_drive:
3651                 if (drive_def(optarg) == NULL) {
3652                     exit(1);
3653                 }
3654                 break;
3655             case QEMU_OPTION_set:
3656                 if (qemu_set_option(optarg) != 0)
3657                     exit(1);
3658                 break;
3659             case QEMU_OPTION_global:
3660                 if (qemu_global_option(optarg) != 0)
3661                     exit(1);
3662                 break;
3663             case QEMU_OPTION_mtdblock:
3664                 drive_add(IF_MTD, -1, optarg, MTD_OPTS);
3665                 break;
3666             case QEMU_OPTION_sd:
3667                 drive_add(IF_SD, -1, optarg, SD_OPTS);
3668                 break;
3669             case QEMU_OPTION_pflash:
3670                 drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
3671                 break;
3672             case QEMU_OPTION_snapshot:
3673                 {
3674                     Error *blocker = NULL;
3675                     snapshot = 1;
3676                     error_setg(&blocker, QERR_REPLAY_NOT_SUPPORTED,
3677                                "-snapshot");
3678                     replay_add_blocker(blocker);
3679                 }
3680                 break;
3681             case QEMU_OPTION_numa:
3682                 opts = qemu_opts_parse_noisily(qemu_find_opts("numa"),
3683                                                optarg, true);
3684                 if (!opts) {
3685                     exit(1);
3686                 }
3687                 break;
3688             case QEMU_OPTION_display:
3689                 parse_display(optarg);
3690                 break;
3691             case QEMU_OPTION_nographic:
3692                 olist = qemu_find_opts("machine");
3693                 qemu_opts_parse_noisily(olist, "graphics=off", false);
3694                 nographic = true;
3695                 dpy.type = DISPLAY_TYPE_NONE;
3696                 break;
3697             case QEMU_OPTION_curses:
3698 #ifdef CONFIG_CURSES
3699                 dpy.type = DISPLAY_TYPE_CURSES;
3700 #else
3701                 error_report("curses or iconv support is disabled");
3702                 exit(1);
3703 #endif
3704                 break;
3705             case QEMU_OPTION_portrait:
3706                 graphic_rotate = 90;
3707                 break;
3708             case QEMU_OPTION_rotate:
3709                 graphic_rotate = strtol(optarg, (char **) &optarg, 10);
3710                 if (graphic_rotate != 0 && graphic_rotate != 90 &&
3711                     graphic_rotate != 180 && graphic_rotate != 270) {
3712                     error_report("only 90, 180, 270 deg rotation is available");
3713                     exit(1);
3714                 }
3715                 break;
3716             case QEMU_OPTION_kernel:
3717                 qemu_opts_set(qemu_find_opts("machine"), "kernel", optarg, &error_abort);
3718                 break;
3719             case QEMU_OPTION_initrd:
3720                 qemu_opts_set(qemu_find_opts("machine"), "initrd", optarg, &error_abort);
3721                 break;
3722             case QEMU_OPTION_append:
3723                 qemu_opts_set(qemu_find_opts("machine"), "append", optarg, &error_abort);
3724                 break;
3725             case QEMU_OPTION_dtb:
3726                 qemu_opts_set(qemu_find_opts("machine"), "dtb", optarg, &error_abort);
3727                 break;
3728             case QEMU_OPTION_cdrom:
3729                 drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
3730                 break;
3731             case QEMU_OPTION_boot:
3732                 opts = qemu_opts_parse_noisily(qemu_find_opts("boot-opts"),
3733                                                optarg, true);
3734                 if (!opts) {
3735                     exit(1);
3736                 }
3737                 break;
3738             case QEMU_OPTION_fda:
3739             case QEMU_OPTION_fdb:
3740                 drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
3741                           optarg, FD_OPTS);
3742                 break;
3743             case QEMU_OPTION_no_fd_bootchk:
3744                 fd_bootchk = 0;
3745                 break;
3746             case QEMU_OPTION_netdev:
3747                 default_net = 0;
3748                 if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
3749                     exit(1);
3750                 }
3751                 break;
3752             case QEMU_OPTION_nic:
3753                 default_net = 0;
3754                 if (net_client_parse(qemu_find_opts("nic"), optarg) == -1) {
3755                     exit(1);
3756                 }
3757                 break;
3758             case QEMU_OPTION_net:
3759                 default_net = 0;
3760                 if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
3761                     exit(1);
3762                 }
3763                 break;
3764 #ifdef CONFIG_LIBISCSI
3765             case QEMU_OPTION_iscsi:
3766                 opts = qemu_opts_parse_noisily(qemu_find_opts("iscsi"),
3767                                                optarg, false);
3768                 if (!opts) {
3769                     exit(1);
3770                 }
3771                 break;
3772 #endif
3773             case QEMU_OPTION_audio_help:
3774                 audio_legacy_help();
3775                 exit (0);
3776                 break;
3777             case QEMU_OPTION_audiodev:
3778                 audio_parse_option(optarg);
3779                 break;
3780             case QEMU_OPTION_soundhw:
3781                 select_soundhw (optarg);
3782                 break;
3783             case QEMU_OPTION_h:
3784                 help(0);
3785                 break;
3786             case QEMU_OPTION_version:
3787                 version();
3788                 exit(0);
3789                 break;
3790             case QEMU_OPTION_m:
3791                 opts = qemu_opts_parse_noisily(qemu_find_opts("memory"),
3792                                                optarg, true);
3793                 if (!opts) {
3794                     exit(EXIT_FAILURE);
3795                 }
3796                 break;
3797 #ifdef CONFIG_TPM
3798             case QEMU_OPTION_tpmdev:
3799                 if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3800                     exit(1);
3801                 }
3802                 break;
3803 #endif
3804             case QEMU_OPTION_mempath:
3805                 mem_path = optarg;
3806                 break;
3807             case QEMU_OPTION_mem_prealloc:
3808                 mem_prealloc = 1;
3809                 break;
3810             case QEMU_OPTION_d:
3811                 log_mask = optarg;
3812                 break;
3813             case QEMU_OPTION_D:
3814                 log_file = optarg;
3815                 break;
3816             case QEMU_OPTION_DFILTER:
3817                 qemu_set_dfilter_ranges(optarg, &error_fatal);
3818                 break;
3819             case QEMU_OPTION_seed:
3820                 qemu_guest_random_seed_main(optarg, &error_fatal);
3821                 break;
3822             case QEMU_OPTION_s:
3823                 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3824                 break;
3825             case QEMU_OPTION_gdb:
3826                 add_device_config(DEV_GDB, optarg);
3827                 break;
3828             case QEMU_OPTION_L:
3829                 if (is_help_option(optarg)) {
3830                     list_data_dirs = true;
3831                 } else {
3832                     qemu_add_data_dir(g_strdup(optarg));
3833                 }
3834                 break;
3835             case QEMU_OPTION_bios:
3836                 qemu_opts_set(qemu_find_opts("machine"), "firmware", optarg, &error_abort);
3837                 break;
3838             case QEMU_OPTION_singlestep:
3839                 singlestep = 1;
3840                 break;
3841             case QEMU_OPTION_S:
3842                 autostart = 0;
3843                 break;
3844             case QEMU_OPTION_k:
3845                 keyboard_layout = optarg;
3846                 break;
3847             case QEMU_OPTION_vga:
3848                 vga_model = optarg;
3849                 default_vga = 0;
3850                 break;
3851             case QEMU_OPTION_g:
3852                 {
3853                     const char *p;
3854                     int w, h, depth;
3855                     p = optarg;
3856                     w = strtol(p, (char **)&p, 10);
3857                     if (w <= 0) {
3858                     graphic_error:
3859                         error_report("invalid resolution or depth");
3860                         exit(1);
3861                     }
3862                     if (*p != 'x')
3863                         goto graphic_error;
3864                     p++;
3865                     h = strtol(p, (char **)&p, 10);
3866                     if (h <= 0)
3867                         goto graphic_error;
3868                     if (*p == 'x') {
3869                         p++;
3870                         depth = strtol(p, (char **)&p, 10);
3871                         if (depth != 1 && depth != 2 && depth != 4 &&
3872                             depth != 8 && depth != 15 && depth != 16 &&
3873                             depth != 24 && depth != 32)
3874                             goto graphic_error;
3875                     } else if (*p == '\0') {
3876                         depth = graphic_depth;
3877                     } else {
3878                         goto graphic_error;
3879                     }
3880
3881                     graphic_width = w;
3882                     graphic_height = h;
3883                     graphic_depth = depth;
3884                 }
3885                 break;
3886             case QEMU_OPTION_echr:
3887                 {
3888                     char *r;
3889                     term_escape_char = strtol(optarg, &r, 0);
3890                     if (r == optarg)
3891                         printf("Bad argument to echr\n");
3892                     break;
3893                 }
3894             case QEMU_OPTION_monitor:
3895                 default_monitor = 0;
3896                 if (strncmp(optarg, "none", 4)) {
3897                     monitor_parse(optarg, "readline", false);
3898                 }
3899                 break;
3900             case QEMU_OPTION_qmp:
3901                 monitor_parse(optarg, "control", false);
3902                 default_monitor = 0;
3903                 break;
3904             case QEMU_OPTION_qmp_pretty:
3905                 monitor_parse(optarg, "control", true);
3906                 default_monitor = 0;
3907                 break;
3908             case QEMU_OPTION_mon:
3909                 opts = qemu_opts_parse_noisily(qemu_find_opts("mon"), optarg,
3910                                                true);
3911                 if (!opts) {
3912                     exit(1);
3913                 }
3914                 default_monitor = 0;
3915                 break;
3916             case QEMU_OPTION_chardev:
3917                 opts = qemu_opts_parse_noisily(qemu_find_opts("chardev"),
3918                                                optarg, true);
3919                 if (!opts) {
3920                     exit(1);
3921                 }
3922                 break;
3923             case QEMU_OPTION_fsdev:
3924                 olist = qemu_find_opts("fsdev");
3925                 if (!olist) {
3926                     error_report("fsdev support is disabled");
3927                     exit(1);
3928                 }
3929                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3930                 if (!opts) {
3931                     exit(1);
3932                 }
3933                 break;
3934             case QEMU_OPTION_virtfs: {
3935                 QemuOpts *fsdev;
3936                 QemuOpts *device;
3937                 const char *writeout, *sock_fd, *socket, *path, *security_model,
3938                            *multidevs;
3939
3940                 olist = qemu_find_opts("virtfs");
3941                 if (!olist) {
3942                     error_report("virtfs support is disabled");
3943                     exit(1);
3944                 }
3945                 opts = qemu_opts_parse_noisily(olist, optarg, true);
3946                 if (!opts) {
3947                     exit(1);
3948                 }
3949
3950                 if (qemu_opt_get(opts, "fsdriver") == NULL ||
3951                     qemu_opt_get(opts, "mount_tag") == NULL) {
3952                     error_report("Usage: -virtfs fsdriver,mount_tag=tag");
3953                     exit(1);
3954                 }
3955                 fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3956                                          qemu_opts_id(opts) ?:
3957                                          qemu_opt_get(opts, "mount_tag"),
3958                                          1, NULL);
3959                 if (!fsdev) {
3960                     error_report("duplicate or invalid fsdev id: %s",
3961                                  qemu_opt_get(opts, "mount_tag"));
3962                     exit(1);
3963                 }
3964
3965                 writeout = qemu_opt_get(opts, "writeout");
3966                 if (writeout) {
3967 #ifdef CONFIG_SYNC_FILE_RANGE
3968                     qemu_opt_set(fsdev, "writeout", writeout, &error_abort);
3969 #else
3970                     error_report("writeout=immediate not supported "
3971                                  "on this platform");
3972                     exit(1);
3973 #endif
3974                 }
3975                 qemu_opt_set(fsdev, "fsdriver",
3976                              qemu_opt_get(opts, "fsdriver"), &error_abort);
3977                 path = qemu_opt_get(opts, "path");
3978                 if (path) {
3979                     qemu_opt_set(fsdev, "path", path, &error_abort);
3980                 }
3981                 security_model = qemu_opt_get(opts, "security_model");
3982                 if (security_model) {
3983                     qemu_opt_set(fsdev, "security_model", security_model,
3984                                  &error_abort);
3985                 }
3986                 socket = qemu_opt_get(opts, "socket");
3987                 if (socket) {
3988                     qemu_opt_set(fsdev, "socket", socket, &error_abort);
3989                 }
3990                 sock_fd = qemu_opt_get(opts, "sock_fd");
3991                 if (sock_fd) {
3992                     qemu_opt_set(fsdev, "sock_fd", sock_fd, &error_abort);
3993                 }
3994
3995                 qemu_opt_set_bool(fsdev, "readonly",
3996                                   qemu_opt_get_bool(opts, "readonly", 0),
3997                                   &error_abort);
3998                 multidevs = qemu_opt_get(opts, "multidevs");
3999                 if (multidevs) {
4000                     qemu_opt_set(fsdev, "multidevs", multidevs, &error_abort);
4001                 }
4002                 device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
4003                                           &error_abort);
4004                 qemu_opt_set(device, "driver", "virtio-9p-pci", &error_abort);
4005                 qemu_opt_set(device, "fsdev",
4006                              qemu_opts_id(fsdev), &error_abort);
4007                 qemu_opt_set(device, "mount_tag",
4008                              qemu_opt_get(opts, "mount_tag"), &error_abort);
4009                 break;
4010             }
4011             case QEMU_OPTION_serial:
4012                 add_device_config(DEV_SERIAL, optarg);
4013                 default_serial = 0;
4014                 if (strncmp(optarg, "mon:", 4) == 0) {
4015                     default_monitor = 0;
4016                 }
4017                 break;
4018             case QEMU_OPTION_watchdog:
4019                 if (watchdog) {
4020                     error_report("only one watchdog option may be given");
4021                     exit(1);
4022                 }
4023                 watchdog = optarg;
4024                 break;
4025             case QEMU_OPTION_watchdog_action:
4026                 if (select_watchdog_action(optarg) == -1) {
4027                     error_report("unknown -watchdog-action parameter");
4028                     exit(1);
4029                 }
4030                 break;
4031             case QEMU_OPTION_parallel:
4032                 add_device_config(DEV_PARALLEL, optarg);
4033                 default_parallel = 0;
4034                 if (strncmp(optarg, "mon:", 4) == 0) {
4035                     default_monitor = 0;
4036                 }
4037                 break;
4038             case QEMU_OPTION_debugcon:
4039                 add_device_config(DEV_DEBUGCON, optarg);
4040                 break;
4041             case QEMU_OPTION_loadvm:
4042                 loadvm = optarg;
4043                 break;
4044             case QEMU_OPTION_full_screen:
4045                 dpy.has_full_screen = true;
4046                 dpy.full_screen = true;
4047                 break;
4048             case QEMU_OPTION_alt_grab:
4049                 alt_grab = 1;
4050                 break;
4051             case QEMU_OPTION_ctrl_grab:
4052                 ctrl_grab = 1;
4053                 break;
4054             case QEMU_OPTION_no_quit:
4055                 dpy.has_window_close = true;
4056                 dpy.window_close = false;
4057                 break;
4058             case QEMU_OPTION_sdl:
4059 #ifdef CONFIG_SDL
4060                 dpy.type = DISPLAY_TYPE_SDL;
4061                 break;
4062 #else
4063                 error_report("SDL support is disabled");
4064                 exit(1);
4065 #endif
4066             case QEMU_OPTION_pidfile:
4067                 pid_file = optarg;
4068                 break;
4069             case QEMU_OPTION_win2k_hack:
4070                 win2k_install_hack = 1;
4071                 break;
4072             case QEMU_OPTION_acpitable:
4073                 opts = qemu_opts_parse_noisily(qemu_find_opts("acpi"),
4074                                                optarg, true);
4075                 if (!opts) {
4076                     exit(1);
4077                 }
4078                 acpi_table_add(opts, &error_fatal);
4079                 break;
4080             case QEMU_OPTION_smbios:
4081                 opts = qemu_opts_parse_noisily(qemu_find_opts("smbios"),
4082                                                optarg, false);
4083                 if (!opts) {
4084                     exit(1);
4085                 }
4086                 smbios_entry_add(opts, &error_fatal);
4087                 break;
4088             case QEMU_OPTION_fwcfg:
4089                 opts = qemu_opts_parse_noisily(qemu_find_opts("fw_cfg"),
4090                                                optarg, true);
4091                 if (opts == NULL) {
4092                     exit(1);
4093                 }
4094                 break;
4095             case QEMU_OPTION_preconfig:
4096                 preconfig_exit_requested = false;
4097                 preconfig_requested = true;
4098                 break;
4099             case QEMU_OPTION_enable_kvm:
4100                 olist = qemu_find_opts("machine");
4101                 qemu_opts_parse_noisily(olist, "accel=kvm", false);
4102                 break;
4103             case QEMU_OPTION_M:
4104             case QEMU_OPTION_machine:
4105                 olist = qemu_find_opts("machine");
4106                 opts = qemu_opts_parse_noisily(olist, optarg, true);
4107                 if (!opts) {
4108                     exit(1);
4109                 }
4110                 break;
4111             case QEMU_OPTION_accel:
4112                 accel_opts = qemu_opts_parse_noisily(qemu_find_opts("accel"),
4113                                                      optarg, true);
4114                 optarg = qemu_opt_get(accel_opts, "accel");
4115                 if (!optarg || is_help_option(optarg)) {
4116                     printf("Accelerators supported in QEMU binary:\n");
4117                     GSList *el, *accel_list = object_class_get_list(TYPE_ACCEL,
4118                                                                     false);
4119                     for (el = accel_list; el; el = el->next) {
4120                         gchar *typename = g_strdup(object_class_get_name(
4121                                                    OBJECT_CLASS(el->data)));
4122                         /* omit qtest which is used for tests only */
4123                         if (g_strcmp0(typename, ACCEL_CLASS_NAME("qtest")) &&
4124                             g_str_has_suffix(typename, ACCEL_CLASS_SUFFIX)) {
4125                             gchar **optname = g_strsplit(typename,
4126                                                          ACCEL_CLASS_SUFFIX, 0);
4127                             printf("%s\n", optname[0]);
4128                             g_strfreev(optname);
4129                         }
4130                         g_free(typename);
4131                     }
4132                     g_slist_free(accel_list);
4133                     exit(0);
4134                 }
4135                 break;
4136             case QEMU_OPTION_usb:
4137                 olist = qemu_find_opts("machine");
4138                 qemu_opts_parse_noisily(olist, "usb=on", false);
4139                 break;
4140             case QEMU_OPTION_usbdevice:
4141                 error_report("'-usbdevice' is deprecated, please use "
4142                              "'-device usb-...' instead");
4143                 olist = qemu_find_opts("machine");
4144                 qemu_opts_parse_noisily(olist, "usb=on", false);
4145                 add_device_config(DEV_USB, optarg);
4146                 break;
4147             case QEMU_OPTION_device:
4148                 if (!qemu_opts_parse_noisily(qemu_find_opts("device"),
4149                                              optarg, true)) {
4150                     exit(1);
4151                 }
4152                 break;
4153             case QEMU_OPTION_smp:
4154                 if (!qemu_opts_parse_noisily(qemu_find_opts("smp-opts"),
4155                                              optarg, true)) {
4156                     exit(1);
4157                 }
4158                 break;
4159             case QEMU_OPTION_vnc:
4160                 vnc_parse(optarg, &error_fatal);
4161                 break;
4162             case QEMU_OPTION_no_acpi:
4163                 olist = qemu_find_opts("machine");
4164                 qemu_opts_parse_noisily(olist, "acpi=off", false);
4165                 break;
4166             case QEMU_OPTION_no_hpet:
4167                 olist = qemu_find_opts("machine");
4168                 qemu_opts_parse_noisily(olist, "hpet=off", false);
4169                 break;
4170             case QEMU_OPTION_no_reboot:
4171                 no_reboot = 1;
4172                 break;
4173             case QEMU_OPTION_no_shutdown:
4174                 no_shutdown = 1;
4175                 break;
4176             case QEMU_OPTION_show_cursor:
4177                 warn_report("The -show-cursor option is deprecated. Please "
4178                             "add show-cursor=on to your -display options.");
4179                 warn_report("When using the default display you can use "
4180                             "-display default,show-cursor=on");
4181                 dpy.has_show_cursor = true;
4182                 dpy.show_cursor = true;
4183                 break;
4184             case QEMU_OPTION_uuid:
4185                 if (qemu_uuid_parse(optarg, &qemu_uuid) < 0) {
4186                     error_report("failed to parse UUID string: wrong format");
4187                     exit(1);
4188                 }
4189                 qemu_uuid_set = true;
4190                 break;
4191             case QEMU_OPTION_option_rom:
4192                 if (nb_option_roms >= MAX_OPTION_ROMS) {
4193                     error_report("too many option ROMs");
4194                     exit(1);
4195                 }
4196                 opts = qemu_opts_parse_noisily(qemu_find_opts("option-rom"),
4197                                                optarg, true);
4198                 if (!opts) {
4199                     exit(1);
4200                 }
4201                 option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
4202                 option_rom[nb_option_roms].bootindex =
4203                     qemu_opt_get_number(opts, "bootindex", -1);
4204                 if (!option_rom[nb_option_roms].name) {
4205                     error_report("Option ROM file is not specified");
4206                     exit(1);
4207                 }
4208                 nb_option_roms++;
4209                 break;
4210             case QEMU_OPTION_semihosting:
4211                 qemu_semihosting_enable();
4212                 break;
4213             case QEMU_OPTION_semihosting_config:
4214                 if (qemu_semihosting_config_options(optarg) != 0) {
4215                     exit(1);
4216                 }
4217                 break;
4218             case QEMU_OPTION_name:
4219                 opts = qemu_opts_parse_noisily(qemu_find_opts("name"),
4220                                                optarg, true);
4221                 if (!opts) {
4222                     exit(1);
4223                 }
4224                 /* Capture guest name if -msg guest-name is used later */
4225                 error_guest_name = qemu_opt_get(opts, "guest");
4226                 break;
4227             case QEMU_OPTION_prom_env:
4228                 if (nb_prom_envs >= MAX_PROM_ENVS) {
4229                     error_report("too many prom variables");
4230                     exit(1);
4231                 }
4232                 prom_envs[nb_prom_envs] = optarg;
4233                 nb_prom_envs++;
4234                 break;
4235             case QEMU_OPTION_old_param:
4236                 old_param = 1;
4237                 break;
4238             case QEMU_OPTION_rtc:
4239                 opts = qemu_opts_parse_noisily(qemu_find_opts("rtc"), optarg,
4240                                                false);
4241                 if (!opts) {
4242                     exit(1);
4243                 }
4244                 break;
4245             case QEMU_OPTION_tb_size:
4246 #ifndef CONFIG_TCG
4247                 error_report("TCG is disabled");
4248                 exit(1);
4249 #endif
4250                 warn_report("The -tb-size option is deprecated, use -accel tcg,tb-size instead");
4251                 object_register_sugar_prop(ACCEL_CLASS_NAME("tcg"), "tb-size", optarg);
4252                 break;
4253             case QEMU_OPTION_icount:
4254                 icount_opts = qemu_opts_parse_noisily(qemu_find_opts("icount"),
4255                                                       optarg, true);
4256                 if (!icount_opts) {
4257                     exit(1);
4258                 }
4259                 break;
4260             case QEMU_OPTION_incoming:
4261                 if (!incoming) {
4262                     runstate_set(RUN_STATE_INMIGRATE);
4263                 }
4264                 incoming = optarg;
4265                 break;
4266             case QEMU_OPTION_only_migratable:
4267                 only_migratable = 1;
4268                 break;
4269             case QEMU_OPTION_nodefaults:
4270                 has_defaults = 0;
4271                 break;
4272             case QEMU_OPTION_xen_domid:
4273                 if (!(xen_available())) {
4274                     error_report("Option not supported for this target");
4275                     exit(1);
4276                 }
4277                 xen_domid = atoi(optarg);
4278                 break;
4279             case QEMU_OPTION_xen_attach:
4280                 if (!(xen_available())) {
4281                     error_report("Option not supported for this target");
4282                     exit(1);
4283                 }
4284                 xen_mode = XEN_ATTACH;
4285                 break;
4286             case QEMU_OPTION_xen_domid_restrict:
4287                 if (!(xen_available())) {
4288                     error_report("Option not supported for this target");
4289                     exit(1);
4290                 }
4291                 xen_domid_restrict = true;
4292                 break;
4293             case QEMU_OPTION_trace:
4294                 trace_opt_parse(optarg);
4295                 break;
4296             case QEMU_OPTION_plugin:
4297                 qemu_plugin_opt_parse(optarg, &plugin_list);
4298                 break;
4299             case QEMU_OPTION_readconfig:
4300                 {
4301                     int ret = qemu_read_config_file(optarg);
4302                     if (ret < 0) {
4303                         error_report("read config %s: %s", optarg,
4304                                      strerror(-ret));
4305                         exit(1);
4306                     }
4307                     break;
4308                 }
4309             case QEMU_OPTION_spice:
4310                 olist = qemu_find_opts_err("spice", NULL);
4311                 if (!olist) {
4312                     ui_module_load_one("spice-core");
4313                     olist = qemu_find_opts("spice");
4314                 }
4315                 if (!olist) {
4316                     error_report("spice support is disabled");
4317                     exit(1);
4318                 }
4319                 opts = qemu_opts_parse_noisily(olist, optarg, false);
4320                 if (!opts) {
4321                     exit(1);
4322                 }
4323                 display_remote++;
4324                 break;
4325             case QEMU_OPTION_writeconfig:
4326                 {
4327                     FILE *fp;
4328                     if (strcmp(optarg, "-") == 0) {
4329                         fp = stdout;
4330                     } else {
4331                         fp = fopen(optarg, "w");
4332                         if (fp == NULL) {
4333                             error_report("open %s: %s", optarg,
4334                                          strerror(errno));
4335                             exit(1);
4336                         }
4337                     }
4338                     qemu_config_write(fp);
4339                     if (fp != stdout) {
4340                         fclose(fp);
4341                     }
4342                     break;
4343                 }
4344             case QEMU_OPTION_qtest:
4345                 qtest_chrdev = optarg;
4346                 break;
4347             case QEMU_OPTION_qtest_log:
4348                 qtest_log = optarg;
4349                 break;
4350             case QEMU_OPTION_sandbox:
4351                 olist = qemu_find_opts("sandbox");
4352                 if (!olist) {
4353 #ifndef CONFIG_SECCOMP
4354                     error_report("-sandbox support is not enabled "
4355                                  "in this QEMU binary");
4356 #endif
4357                     exit(1);
4358                 }
4359
4360                 opts = qemu_opts_parse_noisily(olist, optarg, true);
4361                 if (!opts) {
4362                     exit(1);
4363                 }
4364                 break;
4365             case QEMU_OPTION_add_fd:
4366 #ifndef _WIN32
4367                 opts = qemu_opts_parse_noisily(qemu_find_opts("add-fd"),
4368                                                optarg, false);
4369                 if (!opts) {
4370                     exit(1);
4371                 }
4372 #else
4373                 error_report("File descriptor passing is disabled on this "
4374                              "platform");
4375                 exit(1);
4376 #endif
4377                 break;
4378             case QEMU_OPTION_object:
4379                 opts = qemu_opts_parse_noisily(qemu_find_opts("object"),
4380                                                optarg, true);
4381                 if (!opts) {
4382                     exit(1);
4383                 }
4384                 break;
4385             case QEMU_OPTION_realtime:
4386                 warn_report("'-realtime mlock=...' is deprecated, please use "
4387                              "'-overcommit mem-lock=...' instead");
4388                 opts = qemu_opts_parse_noisily(qemu_find_opts("realtime"),
4389                                                optarg, false);
4390                 if (!opts) {
4391                     exit(1);
4392                 }
4393                 /* Don't override the -overcommit option if set */
4394                 enable_mlock = enable_mlock ||
4395                     qemu_opt_get_bool(opts, "mlock", true);
4396                 break;
4397             case QEMU_OPTION_overcommit:
4398                 opts = qemu_opts_parse_noisily(qemu_find_opts("overcommit"),
4399                                                optarg, false);
4400                 if (!opts) {
4401                     exit(1);
4402                 }
4403                 /* Don't override the -realtime option if set */
4404                 enable_mlock = enable_mlock ||
4405                     qemu_opt_get_bool(opts, "mem-lock", false);
4406                 enable_cpu_pm = qemu_opt_get_bool(opts, "cpu-pm", false);
4407                 break;
4408             case QEMU_OPTION_msg:
4409                 opts = qemu_opts_parse_noisily(qemu_find_opts("msg"), optarg,
4410                                                false);
4411                 if (!opts) {
4412                     exit(1);
4413                 }
4414                 configure_msg(opts);
4415                 break;
4416             case QEMU_OPTION_dump_vmstate:
4417                 if (vmstate_dump_file) {
4418                     error_report("only one '-dump-vmstate' "
4419                                  "option may be given");
4420                     exit(1);
4421                 }
4422                 vmstate_dump_file = fopen(optarg, "w");
4423                 if (vmstate_dump_file == NULL) {
4424                     error_report("open %s: %s", optarg, strerror(errno));
4425                     exit(1);
4426                 }
4427                 break;
4428             case QEMU_OPTION_enable_sync_profile:
4429                 qsp_enable();
4430                 break;
4431             case QEMU_OPTION_nouserconfig:
4432                 /* Nothing to be parsed here. Especially, do not error out below. */
4433                 break;
4434             default:
4435                 if (os_parse_cmd_args(popt->index, optarg)) {
4436                     error_report("Option not supported in this build");
4437                     exit(1);
4438                 }
4439             }
4440         }
4441     }
4442     /*
4443      * Clear error location left behind by the loop.
4444      * Best done right after the loop.  Do not insert code here!
4445      */
4446     loc_set_none();
4447
4448     qemu_validate_options();
4449     qemu_process_sugar_options();
4450
4451     /*
4452      * These options affect everything else and should be processed
4453      * before daemonizing.
4454      */
4455     qemu_process_early_options();
4456
4457     qemu_process_help_options();
4458     qemu_maybe_daemonize(pid_file);
4459
4460     qemu_init_main_loop(&error_fatal);
4461     cpu_timers_init();
4462
4463     user_register_global_props();
4464     replay_configure(icount_opts);
4465
4466     configure_rtc(qemu_find_opts_singleton("rtc"));
4467
4468     qemu_create_machine(select_machine());
4469
4470     qemu_disable_default_devices();
4471     qemu_create_default_devices();
4472     qemu_create_early_backends();
4473
4474     qemu_apply_machine_options();
4475
4476     /*
4477      * Note: uses machine properties such as kernel-irqchip, must run
4478      * after machine_set_property().
4479      */
4480     configure_accelerators(argv[0]);
4481
4482     /*
4483      * Beware, QOM objects created before this point miss global and
4484      * compat properties.
4485      *
4486      * Global properties get set up by qdev_prop_register_global(),
4487      * called from user_register_global_props(), and certain option
4488      * desugaring.  Also in CPU feature desugaring (buried in
4489      * parse_cpu_option()), which happens below this point, but may
4490      * only target the CPU type, which can only be created after
4491      * parse_cpu_option() returned the type.
4492      *
4493      * Machine compat properties: object_set_machine_compat_props().
4494      * Accelerator compat props: object_set_accelerator_compat_props(),
4495      * called from configure_accelerator().
4496      */
4497
4498     machine_class = MACHINE_GET_CLASS(current_machine);
4499     if (!qtest_enabled() && machine_class->deprecation_reason) {
4500         error_report("Machine type '%s' is deprecated: %s",
4501                      machine_class->name, machine_class->deprecation_reason);
4502     }
4503
4504     /*
4505      * Note: creates a QOM object, must run only after global and
4506      * compat properties have been set up.
4507      */
4508     migration_object_init();
4509
4510     qemu_create_late_backends();
4511
4512     /* parse features once if machine provides default cpu_type */
4513     current_machine->cpu_type = machine_class->default_cpu_type;
4514     if (cpu_option) {
4515         current_machine->cpu_type = parse_cpu_option(cpu_option);
4516     }
4517
4518     qemu_resolve_machine_memdev();
4519     parse_numa_opts(current_machine);
4520
4521     if (preconfig_requested) {
4522         qemu_init_displays();
4523     }
4524
4525     /* do monitor/qmp handling at preconfig state if requested */
4526     qemu_main_loop();
4527
4528     qemu_init_board();
4529
4530     qemu_create_cli_devices();
4531
4532     /* initialize displays after all errors have been reported */
4533     if (!preconfig_requested) {
4534         qemu_init_displays();
4535     }
4536     qemu_machine_creation_done();
4537
4538     if (loadvm) {
4539         Error *local_err = NULL;
4540         if (load_snapshot(loadvm, &local_err) < 0) {
4541             error_report_err(local_err);
4542             autostart = 0;
4543             exit(1);
4544         }
4545     }
4546     if (replay_mode != REPLAY_MODE_NONE) {
4547         replay_vmstate_init();
4548     }
4549
4550     qdev_prop_check_globals();
4551     if (vmstate_dump_file) {
4552         /* dump and exit */
4553         dump_vmstate_json_to_file(vmstate_dump_file);
4554         exit(0);
4555     }
4556     if (incoming) {
4557         Error *local_err = NULL;
4558         qemu_start_incoming_migration(incoming, &local_err);
4559         if (local_err) {
4560             error_reportf_err(local_err, "-incoming %s: ", incoming);
4561             exit(1);
4562         }
4563     } else if (autostart) {
4564         vm_start();
4565     }
4566
4567     accel_setup_post(current_machine);
4568     os_setup_post();
4569
4570     return;
4571 }
4572
4573 void qemu_cleanup(void)
4574 {
4575     gdbserver_cleanup();
4576
4577     /*
4578      * cleaning up the migration object cancels any existing migration
4579      * try to do this early so that it also stops using devices.
4580      */
4581     migration_shutdown();
4582
4583     /*
4584      * We must cancel all block jobs while the block layer is drained,
4585      * or cancelling will be affected by throttling and thus may block
4586      * for an extended period of time.
4587      * vm_shutdown() will bdrv_drain_all(), so we may as well include
4588      * it in the drained section.
4589      * We do not need to end this section, because we do not want any
4590      * requests happening from here on anyway.
4591      */
4592     bdrv_drain_all_begin();
4593
4594     /* No more vcpu or device emulation activity beyond this point */
4595     vm_shutdown();
4596     replay_finish();
4597
4598     job_cancel_sync_all();
4599     bdrv_close_all();
4600
4601     res_free();
4602
4603     /* vhost-user must be cleaned up before chardevs.  */
4604     tpm_cleanup();
4605     net_cleanup();
4606     audio_cleanup();
4607     monitor_cleanup();
4608     qemu_chr_cleanup();
4609     user_creatable_cleanup();
4610     /* TODO: unref root container, check all devices are ok */
4611 }
This page took 0.270027 seconds and 2 git commands to generate.