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