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