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