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