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