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