OSDN Git Service

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