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