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