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