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