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