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