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