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