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