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