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