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