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