Merge commit 'ac4040955b1669f0aac5937f623d6587d5210679' into upstream-merge
[qemu-kvm/amd-iommu.git] / vl.c
blobe4e6d9e4aca34795a05dafddca298bca82e9d4c1
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
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>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #include <arpa/inet.h>
48 #include <dirent.h>
49 #include <netdb.h>
50 #include <sys/select.h>
51 #ifdef CONFIG_BSD
52 #include <sys/stat.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54 #include <libutil.h>
55 #include <sys/sysctl.h>
56 #else
57 #include <util.h>
58 #endif
59 #else
60 #ifdef __linux__
61 #include <pty.h>
62 #include <malloc.h>
63 #include <sys/prctl.h>
65 #include <linux/ppdev.h>
66 #include <linux/parport.h>
67 #endif
68 #ifdef __sun__
69 #include <sys/stat.h>
70 #include <sys/ethernet.h>
71 #include <sys/sockio.h>
72 #include <netinet/arp.h>
73 #include <netinet/in.h>
74 #include <netinet/in_systm.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_icmp.h> // must come after ip.h
77 #include <netinet/udp.h>
78 #include <netinet/tcp.h>
79 #include <net/if.h>
80 #include <syslog.h>
81 #include <stropts.h>
82 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
83 discussion about Solaris header problems */
84 extern int madvise(caddr_t, size_t, int);
85 #endif
86 #endif
87 #endif
89 #if defined(__OpenBSD__)
90 #include <util.h>
91 #endif
93 #if defined(CONFIG_VDE)
94 #include <libvdeplug.h>
95 #endif
97 #ifdef _WIN32
98 #include <windows.h>
99 #endif
101 #ifdef CONFIG_SDL
102 #if defined(__APPLE__) || defined(main)
103 #include <SDL.h>
104 int qemu_main(int argc, char **argv, char **envp);
105 int main(int argc, char **argv)
107 return qemu_main(argc, argv, NULL);
109 #undef main
110 #define main qemu_main
111 #endif
112 #endif /* CONFIG_SDL */
114 #ifdef CONFIG_COCOA
115 #undef main
116 #define main qemu_main
117 #endif /* CONFIG_COCOA */
119 #include "hw/hw.h"
120 #include "hw/boards.h"
121 #include "hw/usb.h"
122 #include "hw/pcmcia.h"
123 #include "hw/pc.h"
124 #include "hw/isa.h"
125 #include "hw/baum.h"
126 #include "hw/bt.h"
127 #include "hw/watchdog.h"
128 #include "hw/smbios.h"
129 #include "hw/xen.h"
130 #include "hw/qdev.h"
131 #include "hw/loader.h"
132 #include "bt-host.h"
133 #include "net.h"
134 #include "net/slirp.h"
135 #include "monitor.h"
136 #include "console.h"
137 #include "sysemu.h"
138 #include "gdbstub.h"
139 #include "qemu-timer.h"
140 #include "qemu-char.h"
141 #include "cache-utils.h"
142 #include "block.h"
143 #include "block_int.h"
144 #include "block-migration.h"
145 #include "dma.h"
146 #include "audio/audio.h"
147 #include "migration.h"
148 #include "kvm.h"
149 #include "qemu-option.h"
150 #include "qemu-config.h"
151 #include "qemu-objects.h"
152 #include "hw/device-assignment.h"
153 #ifdef CONFIG_LINUX
154 #include "fsdev/qemu-fsdev.h"
155 #endif
157 #include "disas.h"
159 #include "qemu_socket.h"
161 #include "slirp/libslirp.h"
163 #include "qemu-queue.h"
164 #include "cpus.h"
165 #include "arch_init.h"
167 //#define DEBUG_NET
168 //#define DEBUG_SLIRP
170 #define DEFAULT_RAM_SIZE 128
172 #define MAX_VIRTIO_CONSOLES 1
174 static const char *data_dir;
175 const char *bios_name = NULL;
176 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
177 to store the VM snapshots */
178 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
179 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
180 DriveInfo *extboot_drive = NULL;
181 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
182 DisplayType display_type = DT_DEFAULT;
183 const char* keyboard_layout = NULL;
184 ram_addr_t ram_size;
185 const char *mem_path = NULL;
186 #ifdef MAP_POPULATE
187 int mem_prealloc = 0; /* force preallocation of physical target memory */
188 #endif
189 int nb_nics;
190 NICInfo nd_table[MAX_NICS];
191 int vm_running;
192 int autostart;
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 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
210 int assigned_devices_index;
211 int smp_cpus = 1;
212 int max_cpus = 0;
213 int smp_cores = 1;
214 int smp_threads = 1;
215 const char *vnc_display;
216 int acpi_enabled = 1;
217 #ifdef TARGET_I386
218 int no_hpet = 0;
219 #endif
220 int fd_bootchk = 1;
221 int no_reboot = 0;
222 int no_shutdown = 0;
223 int cursor_hide = 1;
224 int graphic_rotate = 0;
225 uint8_t irq0override = 1;
226 #ifndef _WIN32
227 int daemonize = 0;
228 #endif
229 const char *watchdog;
230 const char *option_rom[MAX_OPTION_ROMS];
231 int nb_option_roms;
232 int semihosting_enabled = 0;
233 int time_drift_fix = 0;
234 unsigned int kvm_shadow_memory = 0;
235 int old_param = 0;
236 const char *qemu_name;
237 int alt_grab = 0;
238 int ctrl_grab = 0;
239 unsigned int nb_prom_envs = 0;
240 const char *prom_envs[MAX_PROM_ENVS];
241 const char *nvram = NULL;
242 int boot_menu;
244 int nb_numa_nodes;
245 uint64_t node_mem[MAX_NODES];
246 uint64_t node_cpumask[MAX_NODES];
248 static QEMUTimer *nographic_timer;
250 uint8_t qemu_uuid[16];
252 static QEMUBootSetHandler *boot_set_handler;
253 static void *boot_set_opaque;
255 int kvm_allowed = 1;
256 uint32_t xen_domid;
257 enum xen_mode xen_mode = XEN_EMULATE;
259 static int default_serial = 1;
260 static int default_parallel = 1;
261 static int default_virtcon = 1;
262 static int default_monitor = 1;
263 static int default_vga = 1;
264 static int default_floppy = 1;
265 static int default_cdrom = 1;
266 static int default_sdcard = 1;
268 static struct {
269 const char *driver;
270 int *flag;
271 } default_list[] = {
272 { .driver = "isa-serial", .flag = &default_serial },
273 { .driver = "isa-parallel", .flag = &default_parallel },
274 { .driver = "isa-fdc", .flag = &default_floppy },
275 { .driver = "ide-drive", .flag = &default_cdrom },
276 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
277 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
278 { .driver = "virtio-serial", .flag = &default_virtcon },
279 { .driver = "VGA", .flag = &default_vga },
280 { .driver = "cirrus-vga", .flag = &default_vga },
281 { .driver = "vmware-svga", .flag = &default_vga },
284 static int default_driver_check(QemuOpts *opts, void *opaque)
286 const char *driver = qemu_opt_get(opts, "driver");
287 int i;
289 if (!driver)
290 return 0;
291 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
292 if (strcmp(default_list[i].driver, driver) != 0)
293 continue;
294 *(default_list[i].flag) = 0;
296 return 0;
299 /***********************************************************/
301 static void set_proc_name(const char *s)
303 #if defined(__linux__) && defined(PR_SET_NAME)
304 char name[16];
305 if (!s)
306 return;
307 name[sizeof(name) - 1] = 0;
308 strncpy(name, s, sizeof(name));
309 /* Could rewrite argv[0] too, but that's a bit more complicated.
310 This simple way is enough for `top'. */
311 prctl(PR_SET_NAME, name);
312 #endif
315 /***********************************************************/
316 /* real time host monotonic timer */
318 /* compute with 96 bit intermediate result: (a*b)/c */
319 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
321 union {
322 uint64_t ll;
323 struct {
324 #ifdef HOST_WORDS_BIGENDIAN
325 uint32_t high, low;
326 #else
327 uint32_t low, high;
328 #endif
329 } l;
330 } u, res;
331 uint64_t rl, rh;
333 u.ll = a;
334 rl = (uint64_t)u.l.low * (uint64_t)b;
335 rh = (uint64_t)u.l.high * (uint64_t)b;
336 rh += (rl >> 32);
337 res.l.high = rh / c;
338 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
339 return res.ll;
342 /***********************************************************/
343 /* host time/date access */
344 void qemu_get_timedate(struct tm *tm, int offset)
346 time_t ti;
347 struct tm *ret;
349 time(&ti);
350 ti += offset;
351 if (rtc_date_offset == -1) {
352 if (rtc_utc)
353 ret = gmtime(&ti);
354 else
355 ret = localtime(&ti);
356 } else {
357 ti -= rtc_date_offset;
358 ret = gmtime(&ti);
361 memcpy(tm, ret, sizeof(struct tm));
364 int qemu_timedate_diff(struct tm *tm)
366 time_t seconds;
368 if (rtc_date_offset == -1)
369 if (rtc_utc)
370 seconds = mktimegm(tm);
371 else
372 seconds = mktime(tm);
373 else
374 seconds = mktimegm(tm) + rtc_date_offset;
376 return seconds - time(NULL);
379 void rtc_change_mon_event(struct tm *tm)
381 QObject *data;
383 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
384 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
385 qobject_decref(data);
388 static void configure_rtc_date_offset(const char *startdate, int legacy)
390 time_t rtc_start_date;
391 struct tm tm;
393 if (!strcmp(startdate, "now") && legacy) {
394 rtc_date_offset = -1;
395 } else {
396 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
397 &tm.tm_year,
398 &tm.tm_mon,
399 &tm.tm_mday,
400 &tm.tm_hour,
401 &tm.tm_min,
402 &tm.tm_sec) == 6) {
403 /* OK */
404 } else if (sscanf(startdate, "%d-%d-%d",
405 &tm.tm_year,
406 &tm.tm_mon,
407 &tm.tm_mday) == 3) {
408 tm.tm_hour = 0;
409 tm.tm_min = 0;
410 tm.tm_sec = 0;
411 } else {
412 goto date_fail;
414 tm.tm_year -= 1900;
415 tm.tm_mon--;
416 rtc_start_date = mktimegm(&tm);
417 if (rtc_start_date == -1) {
418 date_fail:
419 fprintf(stderr, "Invalid date format. Valid formats are:\n"
420 "'2006-06-17T16:01:21' or '2006-06-17'\n");
421 exit(1);
423 rtc_date_offset = time(NULL) - rtc_start_date;
427 static void configure_rtc(QemuOpts *opts)
429 const char *value;
431 value = qemu_opt_get(opts, "base");
432 if (value) {
433 if (!strcmp(value, "utc")) {
434 rtc_utc = 1;
435 } else if (!strcmp(value, "localtime")) {
436 rtc_utc = 0;
437 } else {
438 configure_rtc_date_offset(value, 0);
441 value = qemu_opt_get(opts, "clock");
442 if (value) {
443 if (!strcmp(value, "host")) {
444 rtc_clock = host_clock;
445 } else if (!strcmp(value, "vm")) {
446 rtc_clock = vm_clock;
447 } else {
448 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
449 exit(1);
452 value = qemu_opt_get(opts, "driftfix");
453 if (value) {
454 if (!strcmp(value, "slew")) {
455 rtc_td_hack = 1;
456 } else if (!strcmp(value, "none")) {
457 rtc_td_hack = 0;
458 } else {
459 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
460 exit(1);
465 /***********************************************************/
466 /* Bluetooth support */
467 static int nb_hcis;
468 static int cur_hci;
469 static struct HCIInfo *hci_table[MAX_NICS];
471 static struct bt_vlan_s {
472 struct bt_scatternet_s net;
473 int id;
474 struct bt_vlan_s *next;
475 } *first_bt_vlan;
477 /* find or alloc a new bluetooth "VLAN" */
478 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
480 struct bt_vlan_s **pvlan, *vlan;
481 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
482 if (vlan->id == id)
483 return &vlan->net;
485 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
486 vlan->id = id;
487 pvlan = &first_bt_vlan;
488 while (*pvlan != NULL)
489 pvlan = &(*pvlan)->next;
490 *pvlan = vlan;
491 return &vlan->net;
494 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
498 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
500 return -ENOTSUP;
503 static struct HCIInfo null_hci = {
504 .cmd_send = null_hci_send,
505 .sco_send = null_hci_send,
506 .acl_send = null_hci_send,
507 .bdaddr_set = null_hci_addr_set,
510 struct HCIInfo *qemu_next_hci(void)
512 if (cur_hci == nb_hcis)
513 return &null_hci;
515 return hci_table[cur_hci++];
518 static struct HCIInfo *hci_init(const char *str)
520 char *endp;
521 struct bt_scatternet_s *vlan = 0;
523 if (!strcmp(str, "null"))
524 /* null */
525 return &null_hci;
526 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
527 /* host[:hciN] */
528 return bt_host_hci(str[4] ? str + 5 : "hci0");
529 else if (!strncmp(str, "hci", 3)) {
530 /* hci[,vlan=n] */
531 if (str[3]) {
532 if (!strncmp(str + 3, ",vlan=", 6)) {
533 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
534 if (*endp)
535 vlan = 0;
537 } else
538 vlan = qemu_find_bt_vlan(0);
539 if (vlan)
540 return bt_new_hci(vlan);
543 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
545 return 0;
548 static int bt_hci_parse(const char *str)
550 struct HCIInfo *hci;
551 bdaddr_t bdaddr;
553 if (nb_hcis >= MAX_NICS) {
554 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
555 return -1;
558 hci = hci_init(str);
559 if (!hci)
560 return -1;
562 bdaddr.b[0] = 0x52;
563 bdaddr.b[1] = 0x54;
564 bdaddr.b[2] = 0x00;
565 bdaddr.b[3] = 0x12;
566 bdaddr.b[4] = 0x34;
567 bdaddr.b[5] = 0x56 + nb_hcis;
568 hci->bdaddr_set(hci, bdaddr.b);
570 hci_table[nb_hcis++] = hci;
572 return 0;
575 static void bt_vhci_add(int vlan_id)
577 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
579 if (!vlan->slave)
580 fprintf(stderr, "qemu: warning: adding a VHCI to "
581 "an empty scatternet %i\n", vlan_id);
583 bt_vhci_init(bt_new_hci(vlan));
586 static struct bt_device_s *bt_device_add(const char *opt)
588 struct bt_scatternet_s *vlan;
589 int vlan_id = 0;
590 char *endp = strstr(opt, ",vlan=");
591 int len = (endp ? endp - opt : strlen(opt)) + 1;
592 char devname[10];
594 pstrcpy(devname, MIN(sizeof(devname), len), opt);
596 if (endp) {
597 vlan_id = strtol(endp + 6, &endp, 0);
598 if (*endp) {
599 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
600 return 0;
604 vlan = qemu_find_bt_vlan(vlan_id);
606 if (!vlan->slave)
607 fprintf(stderr, "qemu: warning: adding a slave device to "
608 "an empty scatternet %i\n", vlan_id);
610 if (!strcmp(devname, "keyboard"))
611 return bt_keyboard_init(vlan);
613 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
614 return 0;
617 static int bt_parse(const char *opt)
619 const char *endp, *p;
620 int vlan;
622 if (strstart(opt, "hci", &endp)) {
623 if (!*endp || *endp == ',') {
624 if (*endp)
625 if (!strstart(endp, ",vlan=", 0))
626 opt = endp + 1;
628 return bt_hci_parse(opt);
630 } else if (strstart(opt, "vhci", &endp)) {
631 if (!*endp || *endp == ',') {
632 if (*endp) {
633 if (strstart(endp, ",vlan=", &p)) {
634 vlan = strtol(p, (char **) &endp, 0);
635 if (*endp) {
636 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
637 return 1;
639 } else {
640 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
641 return 1;
643 } else
644 vlan = 0;
646 bt_vhci_add(vlan);
647 return 0;
649 } else if (strstart(opt, "device:", &endp))
650 return !bt_device_add(endp);
652 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
653 return 1;
656 /***********************************************************/
657 /* QEMU Block devices */
659 #define HD_ALIAS "index=%d,media=disk"
660 #define CDROM_ALIAS "index=2,media=cdrom"
661 #define FD_ALIAS "index=%d,if=floppy"
662 #define PFLASH_ALIAS "if=pflash"
663 #define MTD_ALIAS "if=mtd"
664 #define SD_ALIAS "index=0,if=sd"
666 QemuOpts *drive_add(const char *file, const char *fmt, ...)
668 va_list ap;
669 char optstr[1024];
670 QemuOpts *opts;
672 va_start(ap, fmt);
673 vsnprintf(optstr, sizeof(optstr), fmt, ap);
674 va_end(ap);
676 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
677 if (!opts) {
678 return NULL;
680 if (file)
681 qemu_opt_set(opts, "file", file);
682 return opts;
685 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
687 DriveInfo *dinfo;
689 /* seek interface, bus and unit */
691 QTAILQ_FOREACH(dinfo, &drives, next) {
692 if (dinfo->type == type &&
693 dinfo->bus == bus &&
694 dinfo->unit == unit)
695 return dinfo;
698 return NULL;
701 DriveInfo *drive_get_by_id(const char *id)
703 DriveInfo *dinfo;
705 QTAILQ_FOREACH(dinfo, &drives, next) {
706 if (strcmp(id, dinfo->id))
707 continue;
708 return dinfo;
710 return NULL;
713 int drive_get_max_bus(BlockInterfaceType type)
715 int max_bus;
716 DriveInfo *dinfo;
718 max_bus = -1;
719 QTAILQ_FOREACH(dinfo, &drives, next) {
720 if(dinfo->type == type &&
721 dinfo->bus > max_bus)
722 max_bus = dinfo->bus;
724 return max_bus;
727 const char *drive_get_serial(BlockDriverState *bdrv)
729 DriveInfo *dinfo;
731 QTAILQ_FOREACH(dinfo, &drives, next) {
732 if (dinfo->bdrv == bdrv)
733 return dinfo->serial;
736 return "\0";
739 BlockInterfaceErrorAction drive_get_on_error(
740 BlockDriverState *bdrv, int is_read)
742 DriveInfo *dinfo;
744 QTAILQ_FOREACH(dinfo, &drives, next) {
745 if (dinfo->bdrv == bdrv)
746 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
749 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
752 static void bdrv_format_print(void *opaque, const char *name)
754 fprintf(stderr, " %s", name);
757 void drive_uninit(DriveInfo *dinfo)
759 qemu_opts_del(dinfo->opts);
760 bdrv_delete(dinfo->bdrv);
761 QTAILQ_REMOVE(&drives, dinfo, next);
762 qemu_free(dinfo);
765 static int parse_block_error_action(const char *buf, int is_read)
767 if (!strcmp(buf, "ignore")) {
768 return BLOCK_ERR_IGNORE;
769 } else if (!is_read && !strcmp(buf, "enospc")) {
770 return BLOCK_ERR_STOP_ENOSPC;
771 } else if (!strcmp(buf, "stop")) {
772 return BLOCK_ERR_STOP_ANY;
773 } else if (!strcmp(buf, "report")) {
774 return BLOCK_ERR_REPORT;
775 } else {
776 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
777 buf, is_read ? "read" : "write");
778 return -1;
782 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
783 int *fatal_error)
785 const char *buf;
786 const char *file = NULL;
787 char devname[128];
788 const char *serial;
789 const char *mediastr = "";
790 BlockInterfaceType type;
791 enum { MEDIA_DISK, MEDIA_CDROM } media;
792 int bus_id, unit_id;
793 int cyls, heads, secs, translation;
794 BlockDriver *drv = NULL;
795 QEMUMachine *machine = opaque;
796 int max_devs;
797 int index;
798 int ro = 0;
799 int bdrv_flags = 0;
800 int on_read_error, on_write_error;
801 const char *devaddr;
802 DriveInfo *dinfo;
803 int is_extboot = 0;
804 int snapshot = 0;
806 *fatal_error = 1;
808 translation = BIOS_ATA_TRANSLATION_AUTO;
810 if (machine && machine->use_scsi) {
811 type = IF_SCSI;
812 max_devs = MAX_SCSI_DEVS;
813 pstrcpy(devname, sizeof(devname), "scsi");
814 } else {
815 type = IF_IDE;
816 max_devs = MAX_IDE_DEVS;
817 pstrcpy(devname, sizeof(devname), "ide");
819 media = MEDIA_DISK;
821 /* extract parameters */
822 bus_id = qemu_opt_get_number(opts, "bus", 0);
823 unit_id = qemu_opt_get_number(opts, "unit", -1);
824 index = qemu_opt_get_number(opts, "index", -1);
826 cyls = qemu_opt_get_number(opts, "cyls", 0);
827 heads = qemu_opt_get_number(opts, "heads", 0);
828 secs = qemu_opt_get_number(opts, "secs", 0);
830 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
831 ro = qemu_opt_get_bool(opts, "readonly", 0);
833 file = qemu_opt_get(opts, "file");
834 serial = qemu_opt_get(opts, "serial");
836 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
837 pstrcpy(devname, sizeof(devname), buf);
838 if (!strcmp(buf, "ide")) {
839 type = IF_IDE;
840 max_devs = MAX_IDE_DEVS;
841 } else if (!strcmp(buf, "scsi")) {
842 type = IF_SCSI;
843 max_devs = MAX_SCSI_DEVS;
844 } else if (!strcmp(buf, "floppy")) {
845 type = IF_FLOPPY;
846 max_devs = 0;
847 } else if (!strcmp(buf, "pflash")) {
848 type = IF_PFLASH;
849 max_devs = 0;
850 } else if (!strcmp(buf, "mtd")) {
851 type = IF_MTD;
852 max_devs = 0;
853 } else if (!strcmp(buf, "sd")) {
854 type = IF_SD;
855 max_devs = 0;
856 } else if (!strcmp(buf, "virtio")) {
857 type = IF_VIRTIO;
858 max_devs = 0;
859 } else if (!strcmp(buf, "xen")) {
860 type = IF_XEN;
861 max_devs = 0;
862 } else if (!strcmp(buf, "none")) {
863 type = IF_NONE;
864 max_devs = 0;
865 } else {
866 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
867 return NULL;
871 if (cyls || heads || secs) {
872 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
873 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
874 return NULL;
876 if (heads < 1 || (type == IF_IDE && heads > 16)) {
877 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
878 return NULL;
880 if (secs < 1 || (type == IF_IDE && secs > 63)) {
881 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
882 return NULL;
886 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
887 if (!cyls) {
888 fprintf(stderr,
889 "qemu: '%s' trans must be used with cyls,heads and secs\n",
890 buf);
891 return NULL;
893 if (!strcmp(buf, "none"))
894 translation = BIOS_ATA_TRANSLATION_NONE;
895 else if (!strcmp(buf, "lba"))
896 translation = BIOS_ATA_TRANSLATION_LBA;
897 else if (!strcmp(buf, "auto"))
898 translation = BIOS_ATA_TRANSLATION_AUTO;
899 else {
900 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
901 return NULL;
905 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
906 if (!strcmp(buf, "disk")) {
907 media = MEDIA_DISK;
908 } else if (!strcmp(buf, "cdrom")) {
909 if (cyls || secs || heads) {
910 fprintf(stderr,
911 "qemu: '%s' invalid physical CHS format\n", buf);
912 return NULL;
914 media = MEDIA_CDROM;
915 } else {
916 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
917 return NULL;
921 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
922 if (!strcmp(buf, "off") || !strcmp(buf, "none")) {
923 bdrv_flags |= BDRV_O_NOCACHE;
924 } else if (!strcmp(buf, "writeback")) {
925 bdrv_flags |= BDRV_O_CACHE_WB;
926 } else if (!strcmp(buf, "writethrough")) {
927 /* this is the default */
928 } else {
929 fprintf(stderr, "qemu: invalid cache option\n");
930 return NULL;
934 #ifdef CONFIG_LINUX_AIO
935 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
936 if (!strcmp(buf, "native")) {
937 bdrv_flags |= BDRV_O_NATIVE_AIO;
938 } else if (!strcmp(buf, "threads")) {
939 /* this is the default */
940 } else {
941 fprintf(stderr, "qemu: invalid aio option\n");
942 return NULL;
945 #endif
947 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
948 if (strcmp(buf, "?") == 0) {
949 fprintf(stderr, "qemu: Supported formats:");
950 bdrv_iterate_format(bdrv_format_print, NULL);
951 fprintf(stderr, "\n");
952 return NULL;
954 drv = bdrv_find_whitelisted_format(buf);
955 if (!drv) {
956 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
957 return NULL;
961 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
962 if (is_extboot && extboot_drive) {
963 fprintf(stderr, "qemu: two bootable drives specified\n");
964 return NULL;
967 on_write_error = BLOCK_ERR_STOP_ENOSPC;
968 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
969 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
970 fprintf(stderr, "werror is no supported by this format\n");
971 return NULL;
974 on_write_error = parse_block_error_action(buf, 0);
975 if (on_write_error < 0) {
976 return NULL;
980 on_read_error = BLOCK_ERR_REPORT;
981 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
982 if (type != IF_IDE && type != IF_VIRTIO) {
983 fprintf(stderr, "rerror is no supported by this format\n");
984 return NULL;
987 on_read_error = parse_block_error_action(buf, 1);
988 if (on_read_error < 0) {
989 return NULL;
993 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
994 if (type != IF_VIRTIO) {
995 fprintf(stderr, "addr is not supported\n");
996 return NULL;
1000 /* compute bus and unit according index */
1002 if (index != -1) {
1003 if (bus_id != 0 || unit_id != -1) {
1004 fprintf(stderr,
1005 "qemu: index cannot be used with bus and unit\n");
1006 return NULL;
1008 if (max_devs == 0)
1010 unit_id = index;
1011 bus_id = 0;
1012 } else {
1013 unit_id = index % max_devs;
1014 bus_id = index / max_devs;
1018 /* if user doesn't specify a unit_id,
1019 * try to find the first free
1022 if (unit_id == -1) {
1023 unit_id = 0;
1024 while (drive_get(type, bus_id, unit_id) != NULL) {
1025 unit_id++;
1026 if (max_devs && unit_id >= max_devs) {
1027 unit_id -= max_devs;
1028 bus_id++;
1033 /* check unit id */
1035 if (max_devs && unit_id >= max_devs) {
1036 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1037 unit_id, max_devs - 1);
1038 return NULL;
1042 * ignore multiple definitions
1045 if (drive_get(type, bus_id, unit_id) != NULL) {
1046 *fatal_error = 0;
1047 return NULL;
1050 /* init */
1052 dinfo = qemu_mallocz(sizeof(*dinfo));
1053 if ((buf = qemu_opts_id(opts)) != NULL) {
1054 dinfo->id = qemu_strdup(buf);
1055 } else {
1056 /* no id supplied -> create one */
1057 dinfo->id = qemu_mallocz(32);
1058 if (type == IF_IDE || type == IF_SCSI)
1059 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1060 if (max_devs)
1061 snprintf(dinfo->id, 32, "%s%i%s%i",
1062 devname, bus_id, mediastr, unit_id);
1063 else
1064 snprintf(dinfo->id, 32, "%s%s%i",
1065 devname, mediastr, unit_id);
1067 dinfo->bdrv = bdrv_new(dinfo->id);
1068 dinfo->devaddr = devaddr;
1069 dinfo->type = type;
1070 dinfo->bus = bus_id;
1071 dinfo->unit = unit_id;
1072 dinfo->on_read_error = on_read_error;
1073 dinfo->on_write_error = on_write_error;
1074 dinfo->opts = opts;
1075 if (serial)
1076 strncpy(dinfo->serial, serial, sizeof(serial));
1077 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1078 if (is_extboot) {
1079 extboot_drive = dinfo;
1082 switch(type) {
1083 case IF_IDE:
1084 case IF_SCSI:
1085 case IF_XEN:
1086 case IF_NONE:
1087 switch(media) {
1088 case MEDIA_DISK:
1089 if (cyls != 0) {
1090 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1091 bdrv_set_translation_hint(dinfo->bdrv, translation);
1093 break;
1094 case MEDIA_CDROM:
1095 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1096 break;
1098 break;
1099 case IF_SD:
1100 /* FIXME: This isn't really a floppy, but it's a reasonable
1101 approximation. */
1102 case IF_FLOPPY:
1103 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1104 break;
1105 case IF_PFLASH:
1106 case IF_MTD:
1107 break;
1108 case IF_VIRTIO:
1109 /* add virtio block device */
1110 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1111 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1112 qemu_opt_set(opts, "drive", dinfo->id);
1113 if (devaddr)
1114 qemu_opt_set(opts, "addr", devaddr);
1115 break;
1116 case IF_COUNT:
1117 abort();
1119 if (!file) {
1120 *fatal_error = 0;
1121 return NULL;
1123 if (snapshot) {
1124 /* always use write-back with snapshot */
1125 bdrv_flags &= ~BDRV_O_CACHE_MASK;
1126 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB);
1129 if (media == MEDIA_CDROM) {
1130 /* CDROM is fine for any interface, don't check. */
1131 ro = 1;
1132 } else if (ro == 1) {
1133 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1134 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1135 return NULL;
1139 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1141 if (bdrv_open(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1142 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1143 file, strerror(errno));
1144 return NULL;
1147 if (bdrv_key_required(dinfo->bdrv))
1148 autostart = 0;
1149 *fatal_error = 0;
1150 return dinfo;
1153 static int drive_init_func(QemuOpts *opts, void *opaque)
1155 QEMUMachine *machine = opaque;
1156 int fatal_error = 0;
1158 if (drive_init(opts, machine, &fatal_error) == NULL) {
1159 if (fatal_error)
1160 return 1;
1162 return 0;
1165 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1167 if (NULL == qemu_opt_get(opts, "snapshot")) {
1168 qemu_opt_set(opts, "snapshot", "on");
1170 return 0;
1173 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1175 boot_set_handler = func;
1176 boot_set_opaque = opaque;
1179 int qemu_boot_set(const char *boot_devices)
1181 if (!boot_set_handler) {
1182 return -EINVAL;
1184 return boot_set_handler(boot_set_opaque, boot_devices);
1187 static void validate_bootdevices(char *devices)
1189 /* We just do some generic consistency checks */
1190 const char *p;
1191 int bitmap = 0;
1193 for (p = devices; *p != '\0'; p++) {
1194 /* Allowed boot devices are:
1195 * a-b: floppy disk drives
1196 * c-f: IDE disk drives
1197 * g-m: machine implementation dependant drives
1198 * n-p: network devices
1199 * It's up to each machine implementation to check if the given boot
1200 * devices match the actual hardware implementation and firmware
1201 * features.
1203 if (*p < 'a' || *p > 'p') {
1204 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1205 exit(1);
1207 if (bitmap & (1 << (*p - 'a'))) {
1208 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1209 exit(1);
1211 bitmap |= 1 << (*p - 'a');
1215 static void restore_boot_devices(void *opaque)
1217 char *standard_boot_devices = opaque;
1218 static int first = 1;
1220 /* Restore boot order and remove ourselves after the first boot */
1221 if (first) {
1222 first = 0;
1223 return;
1226 qemu_boot_set(standard_boot_devices);
1228 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1229 qemu_free(standard_boot_devices);
1232 static void numa_add(const char *optarg)
1234 char option[128];
1235 char *endptr;
1236 unsigned long long value, endvalue;
1237 int nodenr;
1239 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1240 if (!strcmp(option, "node")) {
1241 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1242 nodenr = nb_numa_nodes;
1243 } else {
1244 nodenr = strtoull(option, NULL, 10);
1247 if (get_param_value(option, 128, "mem", optarg) == 0) {
1248 node_mem[nodenr] = 0;
1249 } else {
1250 value = strtoull(option, &endptr, 0);
1251 switch (*endptr) {
1252 case 0: case 'M': case 'm':
1253 value <<= 20;
1254 break;
1255 case 'G': case 'g':
1256 value <<= 30;
1257 break;
1259 node_mem[nodenr] = value;
1261 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1262 node_cpumask[nodenr] = 0;
1263 } else {
1264 value = strtoull(option, &endptr, 10);
1265 if (value >= 64) {
1266 value = 63;
1267 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1268 } else {
1269 if (*endptr == '-') {
1270 endvalue = strtoull(endptr+1, &endptr, 10);
1271 if (endvalue >= 63) {
1272 endvalue = 62;
1273 fprintf(stderr,
1274 "only 63 CPUs in NUMA mode supported.\n");
1276 value = (2ULL << endvalue) - (1ULL << value);
1277 } else {
1278 value = 1ULL << value;
1281 node_cpumask[nodenr] = value;
1283 nb_numa_nodes++;
1285 return;
1288 static void smp_parse(const char *optarg)
1290 int smp, sockets = 0, threads = 0, cores = 0;
1291 char *endptr;
1292 char option[128];
1294 smp = strtoul(optarg, &endptr, 10);
1295 if (endptr != optarg) {
1296 if (*endptr == ',') {
1297 endptr++;
1300 if (get_param_value(option, 128, "sockets", endptr) != 0)
1301 sockets = strtoull(option, NULL, 10);
1302 if (get_param_value(option, 128, "cores", endptr) != 0)
1303 cores = strtoull(option, NULL, 10);
1304 if (get_param_value(option, 128, "threads", endptr) != 0)
1305 threads = strtoull(option, NULL, 10);
1306 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1307 max_cpus = strtoull(option, NULL, 10);
1309 /* compute missing values, prefer sockets over cores over threads */
1310 if (smp == 0 || sockets == 0) {
1311 sockets = sockets > 0 ? sockets : 1;
1312 cores = cores > 0 ? cores : 1;
1313 threads = threads > 0 ? threads : 1;
1314 if (smp == 0) {
1315 smp = cores * threads * sockets;
1317 } else {
1318 if (cores == 0) {
1319 threads = threads > 0 ? threads : 1;
1320 cores = smp / (sockets * threads);
1321 } else {
1322 if (sockets) {
1323 threads = smp / (cores * sockets);
1327 smp_cpus = smp;
1328 smp_cores = cores > 0 ? cores : 1;
1329 smp_threads = threads > 0 ? threads : 1;
1330 if (max_cpus == 0)
1331 max_cpus = smp_cpus;
1334 /***********************************************************/
1335 /* USB devices */
1337 static int usb_device_add(const char *devname, int is_hotplug)
1339 const char *p;
1340 USBDevice *dev = NULL;
1342 if (!usb_enabled)
1343 return -1;
1345 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1346 dev = usbdevice_create(devname);
1347 if (dev)
1348 goto done;
1350 /* the other ones */
1351 if (strstart(devname, "host:", &p)) {
1352 dev = usb_host_device_open(p);
1353 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1354 dev = usb_bt_init(devname[2] ? hci_init(p) :
1355 bt_new_hci(qemu_find_bt_vlan(0)));
1356 } else {
1357 return -1;
1359 if (!dev)
1360 return -1;
1362 done:
1363 return 0;
1366 static int usb_device_del(const char *devname)
1368 int bus_num, addr;
1369 const char *p;
1371 if (strstart(devname, "host:", &p))
1372 return usb_host_device_close(p);
1374 if (!usb_enabled)
1375 return -1;
1377 p = strchr(devname, '.');
1378 if (!p)
1379 return -1;
1380 bus_num = strtoul(devname, NULL, 0);
1381 addr = strtoul(p + 1, NULL, 0);
1383 return usb_device_delete_addr(bus_num, addr);
1386 static int usb_parse(const char *cmdline)
1388 int r;
1389 r = usb_device_add(cmdline, 0);
1390 if (r < 0) {
1391 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1393 return r;
1396 void do_usb_add(Monitor *mon, const QDict *qdict)
1398 const char *devname = qdict_get_str(qdict, "devname");
1399 if (usb_device_add(devname, 1) < 0) {
1400 error_report("could not add USB device '%s'", devname);
1404 void do_usb_del(Monitor *mon, const QDict *qdict)
1406 const char *devname = qdict_get_str(qdict, "devname");
1407 if (usb_device_del(devname) < 0) {
1408 error_report("could not delete USB device '%s'", devname);
1412 /***********************************************************/
1413 /* PCMCIA/Cardbus */
1415 static struct pcmcia_socket_entry_s {
1416 PCMCIASocket *socket;
1417 struct pcmcia_socket_entry_s *next;
1418 } *pcmcia_sockets = 0;
1420 void pcmcia_socket_register(PCMCIASocket *socket)
1422 struct pcmcia_socket_entry_s *entry;
1424 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1425 entry->socket = socket;
1426 entry->next = pcmcia_sockets;
1427 pcmcia_sockets = entry;
1430 void pcmcia_socket_unregister(PCMCIASocket *socket)
1432 struct pcmcia_socket_entry_s *entry, **ptr;
1434 ptr = &pcmcia_sockets;
1435 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1436 if (entry->socket == socket) {
1437 *ptr = entry->next;
1438 qemu_free(entry);
1442 void pcmcia_info(Monitor *mon)
1444 struct pcmcia_socket_entry_s *iter;
1446 if (!pcmcia_sockets)
1447 monitor_printf(mon, "No PCMCIA sockets\n");
1449 for (iter = pcmcia_sockets; iter; iter = iter->next)
1450 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1451 iter->socket->attached ? iter->socket->card_string :
1452 "Empty");
1455 /***********************************************************/
1456 /* I/O handling */
1458 typedef struct IOHandlerRecord {
1459 int fd;
1460 IOCanReadHandler *fd_read_poll;
1461 IOHandler *fd_read;
1462 IOHandler *fd_write;
1463 int deleted;
1464 void *opaque;
1465 /* temporary data */
1466 struct pollfd *ufd;
1467 QLIST_ENTRY(IOHandlerRecord) next;
1468 } IOHandlerRecord;
1470 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1471 QLIST_HEAD_INITIALIZER(io_handlers);
1474 /* XXX: fd_read_poll should be suppressed, but an API change is
1475 necessary in the character devices to suppress fd_can_read(). */
1476 int qemu_set_fd_handler2(int fd,
1477 IOCanReadHandler *fd_read_poll,
1478 IOHandler *fd_read,
1479 IOHandler *fd_write,
1480 void *opaque)
1482 IOHandlerRecord *ioh;
1484 if (!fd_read && !fd_write) {
1485 QLIST_FOREACH(ioh, &io_handlers, next) {
1486 if (ioh->fd == fd) {
1487 ioh->deleted = 1;
1488 break;
1491 } else {
1492 QLIST_FOREACH(ioh, &io_handlers, next) {
1493 if (ioh->fd == fd)
1494 goto found;
1496 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1497 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1498 found:
1499 ioh->fd = fd;
1500 ioh->fd_read_poll = fd_read_poll;
1501 ioh->fd_read = fd_read;
1502 ioh->fd_write = fd_write;
1503 ioh->opaque = opaque;
1504 ioh->deleted = 0;
1506 qemu_notify_event();
1507 return 0;
1510 int qemu_set_fd_handler(int fd,
1511 IOHandler *fd_read,
1512 IOHandler *fd_write,
1513 void *opaque)
1515 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1518 #ifdef _WIN32
1519 /***********************************************************/
1520 /* Polling handling */
1522 typedef struct PollingEntry {
1523 PollingFunc *func;
1524 void *opaque;
1525 struct PollingEntry *next;
1526 } PollingEntry;
1528 static PollingEntry *first_polling_entry;
1530 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1532 PollingEntry **ppe, *pe;
1533 pe = qemu_mallocz(sizeof(PollingEntry));
1534 pe->func = func;
1535 pe->opaque = opaque;
1536 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1537 *ppe = pe;
1538 return 0;
1541 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1543 PollingEntry **ppe, *pe;
1544 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1545 pe = *ppe;
1546 if (pe->func == func && pe->opaque == opaque) {
1547 *ppe = pe->next;
1548 qemu_free(pe);
1549 break;
1554 /***********************************************************/
1555 /* Wait objects support */
1556 typedef struct WaitObjects {
1557 int num;
1558 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1559 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1560 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1561 } WaitObjects;
1563 static WaitObjects wait_objects = {0};
1565 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1567 WaitObjects *w = &wait_objects;
1569 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1570 return -1;
1571 w->events[w->num] = handle;
1572 w->func[w->num] = func;
1573 w->opaque[w->num] = opaque;
1574 w->num++;
1575 return 0;
1578 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1580 int i, found;
1581 WaitObjects *w = &wait_objects;
1583 found = 0;
1584 for (i = 0; i < w->num; i++) {
1585 if (w->events[i] == handle)
1586 found = 1;
1587 if (found) {
1588 w->events[i] = w->events[i + 1];
1589 w->func[i] = w->func[i + 1];
1590 w->opaque[i] = w->opaque[i + 1];
1593 if (found)
1594 w->num--;
1596 #endif
1598 /***********************************************************/
1599 /* machine registration */
1601 static QEMUMachine *first_machine = NULL;
1602 QEMUMachine *current_machine = NULL;
1604 int qemu_register_machine(QEMUMachine *m)
1606 QEMUMachine **pm;
1607 pm = &first_machine;
1608 while (*pm != NULL)
1609 pm = &(*pm)->next;
1610 m->next = NULL;
1611 *pm = m;
1612 return 0;
1615 static QEMUMachine *find_machine(const char *name)
1617 QEMUMachine *m;
1619 for(m = first_machine; m != NULL; m = m->next) {
1620 if (!strcmp(m->name, name))
1621 return m;
1622 if (m->alias && !strcmp(m->alias, name))
1623 return m;
1625 return NULL;
1628 static QEMUMachine *find_default_machine(void)
1630 QEMUMachine *m;
1632 for(m = first_machine; m != NULL; m = m->next) {
1633 if (m->is_default) {
1634 return m;
1637 return NULL;
1640 /***********************************************************/
1641 /* main execution loop */
1643 static void gui_update(void *opaque)
1645 uint64_t interval = GUI_REFRESH_INTERVAL;
1646 DisplayState *ds = opaque;
1647 DisplayChangeListener *dcl = ds->listeners;
1649 qemu_flush_coalesced_mmio_buffer();
1650 dpy_refresh(ds);
1652 while (dcl != NULL) {
1653 if (dcl->gui_timer_interval &&
1654 dcl->gui_timer_interval < interval)
1655 interval = dcl->gui_timer_interval;
1656 dcl = dcl->next;
1658 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1661 static void nographic_update(void *opaque)
1663 uint64_t interval = GUI_REFRESH_INTERVAL;
1665 qemu_flush_coalesced_mmio_buffer();
1666 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1669 struct vm_change_state_entry {
1670 VMChangeStateHandler *cb;
1671 void *opaque;
1672 QLIST_ENTRY (vm_change_state_entry) entries;
1675 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1677 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1678 void *opaque)
1680 VMChangeStateEntry *e;
1682 e = qemu_mallocz(sizeof (*e));
1684 e->cb = cb;
1685 e->opaque = opaque;
1686 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1687 return e;
1690 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1692 QLIST_REMOVE (e, entries);
1693 qemu_free (e);
1696 void vm_state_notify(int running, int reason)
1698 VMChangeStateEntry *e;
1700 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1701 e->cb(e->opaque, running, reason);
1705 void vm_start(void)
1707 if (!vm_running) {
1708 cpu_enable_ticks();
1709 vm_running = 1;
1710 vm_state_notify(1, 0);
1711 resume_all_vcpus();
1712 monitor_protocol_event(QEVENT_RESUME, NULL);
1716 /* reset/shutdown handler */
1718 typedef struct QEMUResetEntry {
1719 QTAILQ_ENTRY(QEMUResetEntry) entry;
1720 QEMUResetHandler *func;
1721 void *opaque;
1722 } QEMUResetEntry;
1724 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1725 QTAILQ_HEAD_INITIALIZER(reset_handlers);
1726 static int reset_requested;
1727 static int shutdown_requested;
1728 static int powerdown_requested;
1729 int debug_requested;
1730 int vmstop_requested;
1731 static int exit_requested;
1733 int qemu_no_shutdown(void)
1735 int r = no_shutdown;
1736 no_shutdown = 0;
1737 return r;
1740 int qemu_shutdown_requested(void)
1742 int r = shutdown_requested;
1743 shutdown_requested = 0;
1744 return r;
1747 int qemu_reset_requested(void)
1749 int r = reset_requested;
1750 reset_requested = 0;
1751 return r;
1754 int qemu_powerdown_requested(void)
1756 int r = powerdown_requested;
1757 powerdown_requested = 0;
1758 return r;
1761 int qemu_exit_requested(void)
1763 /* just return it, we'll exit() anyway */
1764 return exit_requested;
1767 static int qemu_debug_requested(void)
1769 int r = debug_requested;
1770 debug_requested = 0;
1771 return r;
1774 static int qemu_vmstop_requested(void)
1776 int r = vmstop_requested;
1777 vmstop_requested = 0;
1778 return r;
1781 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1783 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
1785 re->func = func;
1786 re->opaque = opaque;
1787 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1790 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1792 QEMUResetEntry *re;
1794 QTAILQ_FOREACH(re, &reset_handlers, entry) {
1795 if (re->func == func && re->opaque == opaque) {
1796 QTAILQ_REMOVE(&reset_handlers, re, entry);
1797 qemu_free(re);
1798 return;
1803 void qemu_system_reset(void)
1805 QEMUResetEntry *re, *nre;
1807 /* reset all devices */
1808 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1809 re->func(re->opaque);
1811 monitor_protocol_event(QEVENT_RESET, NULL);
1812 cpu_synchronize_all_post_reset();
1815 void qemu_system_reset_request(void)
1817 if (no_reboot) {
1818 shutdown_requested = 1;
1819 } else {
1820 reset_requested = 1;
1822 if (cpu_single_env) {
1823 cpu_single_env->stopped = 1;
1825 qemu_notify_event();
1828 void qemu_system_shutdown_request(void)
1830 shutdown_requested = 1;
1831 qemu_notify_event();
1834 void qemu_system_powerdown_request(void)
1836 powerdown_requested = 1;
1837 qemu_notify_event();
1840 void qemu_system_exit_request(void)
1842 exit_requested = 1;
1843 qemu_notify_event();
1846 #ifdef _WIN32
1847 static void host_main_loop_wait(int *timeout)
1849 int ret, ret2, i;
1850 PollingEntry *pe;
1853 /* XXX: need to suppress polling by better using win32 events */
1854 ret = 0;
1855 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
1856 ret |= pe->func(pe->opaque);
1858 if (ret == 0) {
1859 int err;
1860 WaitObjects *w = &wait_objects;
1862 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
1863 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
1864 if (w->func[ret - WAIT_OBJECT_0])
1865 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
1867 /* Check for additional signaled events */
1868 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
1870 /* Check if event is signaled */
1871 ret2 = WaitForSingleObject(w->events[i], 0);
1872 if(ret2 == WAIT_OBJECT_0) {
1873 if (w->func[i])
1874 w->func[i](w->opaque[i]);
1875 } else if (ret2 == WAIT_TIMEOUT) {
1876 } else {
1877 err = GetLastError();
1878 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
1881 } else if (ret == WAIT_TIMEOUT) {
1882 } else {
1883 err = GetLastError();
1884 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
1888 *timeout = 0;
1890 #else
1891 static void host_main_loop_wait(int *timeout)
1894 #endif
1896 void main_loop_wait(int nonblocking)
1898 IOHandlerRecord *ioh;
1899 fd_set rfds, wfds, xfds;
1900 int ret, nfds;
1901 struct timeval tv;
1902 int timeout;
1904 if (nonblocking)
1905 timeout = 0;
1906 else {
1907 timeout = qemu_calculate_timeout();
1908 qemu_bh_update_timeout(&timeout);
1911 host_main_loop_wait(&timeout);
1913 /* poll any events */
1914 /* XXX: separate device handlers from system ones */
1915 nfds = -1;
1916 FD_ZERO(&rfds);
1917 FD_ZERO(&wfds);
1918 FD_ZERO(&xfds);
1919 QLIST_FOREACH(ioh, &io_handlers, next) {
1920 if (ioh->deleted)
1921 continue;
1922 if (ioh->fd_read &&
1923 (!ioh->fd_read_poll ||
1924 ioh->fd_read_poll(ioh->opaque) != 0)) {
1925 FD_SET(ioh->fd, &rfds);
1926 if (ioh->fd > nfds)
1927 nfds = ioh->fd;
1929 if (ioh->fd_write) {
1930 FD_SET(ioh->fd, &wfds);
1931 if (ioh->fd > nfds)
1932 nfds = ioh->fd;
1936 tv.tv_sec = timeout / 1000;
1937 tv.tv_usec = (timeout % 1000) * 1000;
1939 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1941 qemu_mutex_unlock_iothread();
1942 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1943 qemu_mutex_lock_iothread();
1944 if (ret > 0) {
1945 IOHandlerRecord *pioh;
1947 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
1948 if (ioh->deleted) {
1949 QLIST_REMOVE(ioh, next);
1950 qemu_free(ioh);
1951 continue;
1953 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
1954 ioh->fd_read(ioh->opaque);
1955 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
1956 FD_CLR(ioh->fd, &rfds);
1958 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
1959 ioh->fd_write(ioh->opaque);
1964 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1966 qemu_run_all_timers();
1968 /* Check bottom-halves last in case any of the earlier events triggered
1969 them. */
1970 qemu_bh_poll();
1974 static int vm_can_run(void)
1976 if (powerdown_requested)
1977 return 0;
1978 if (reset_requested)
1979 return 0;
1980 if (shutdown_requested)
1981 return 0;
1982 if (debug_requested)
1983 return 0;
1984 if (exit_requested)
1985 return 0;
1986 return 1;
1989 qemu_irq qemu_system_powerdown;
1991 static void main_loop(void)
1993 int r;
1995 if (kvm_enabled()) {
1996 kvm_main_loop();
1997 cpu_disable_ticks();
1998 return;
2001 qemu_main_loop_start();
2003 for (;;) {
2004 do {
2005 bool nonblocking = false;
2006 #ifdef CONFIG_PROFILER
2007 int64_t ti;
2008 #endif
2009 #ifndef CONFIG_IOTHREAD
2010 nonblocking = tcg_cpu_exec();
2011 #endif
2012 #ifdef CONFIG_PROFILER
2013 ti = profile_getclock();
2014 #endif
2015 main_loop_wait(nonblocking);
2016 #ifdef CONFIG_PROFILER
2017 dev_time += profile_getclock() - ti;
2018 #endif
2019 } while (vm_can_run());
2021 if ((r = qemu_debug_requested())) {
2022 vm_stop(r);
2024 if (qemu_shutdown_requested()) {
2025 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2026 if (no_shutdown) {
2027 vm_stop(0);
2028 no_shutdown = 0;
2029 } else
2030 break;
2032 if (qemu_reset_requested()) {
2033 pause_all_vcpus();
2034 qemu_system_reset();
2035 resume_all_vcpus();
2037 if (qemu_powerdown_requested()) {
2038 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
2039 qemu_irq_raise(qemu_system_powerdown);
2041 if ((r = qemu_vmstop_requested())) {
2042 vm_stop(r);
2044 if (qemu_exit_requested()) {
2045 exit(0);
2048 pause_all_vcpus();
2051 static void version(void)
2053 printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
2056 static void help(int exitcode)
2058 const char *options_help =
2059 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2060 opt_help
2061 #define DEFHEADING(text) stringify(text) "\n"
2062 #include "qemu-options.h"
2063 #undef DEF
2064 #undef DEFHEADING
2065 #undef GEN_DOCS
2067 version();
2068 printf("usage: %s [options] [disk_image]\n"
2069 "\n"
2070 "'disk_image' is a raw hard disk image for IDE hard disk 0\n"
2071 "\n"
2072 "%s\n"
2073 "During emulation, the following keys are useful:\n"
2074 "ctrl-alt-f toggle full screen\n"
2075 "ctrl-alt-n switch to virtual console 'n'\n"
2076 "ctrl-alt toggle mouse and keyboard grab\n"
2077 "\n"
2078 "When using -nographic, press 'ctrl-a h' to get some help.\n",
2079 "qemu",
2080 options_help);
2081 exit(exitcode);
2084 #define HAS_ARG 0x0001
2086 enum {
2087 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2088 opt_enum,
2089 #define DEFHEADING(text)
2090 #include "qemu-options.h"
2091 #undef DEF
2092 #undef DEFHEADING
2093 #undef GEN_DOCS
2096 typedef struct QEMUOption {
2097 const char *name;
2098 int flags;
2099 int index;
2100 uint32_t arch_mask;
2101 } QEMUOption;
2103 static const QEMUOption qemu_options[] = {
2104 { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
2105 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2106 { option, opt_arg, opt_enum, arch_mask },
2107 #define DEFHEADING(text)
2108 #include "qemu-options.h"
2109 #undef DEF
2110 #undef DEFHEADING
2111 #undef GEN_DOCS
2112 { NULL },
2114 static void select_vgahw (const char *p)
2116 const char *opts;
2118 default_vga = 0;
2119 vga_interface_type = VGA_NONE;
2120 if (strstart(p, "std", &opts)) {
2121 vga_interface_type = VGA_STD;
2122 } else if (strstart(p, "cirrus", &opts)) {
2123 vga_interface_type = VGA_CIRRUS;
2124 } else if (strstart(p, "vmware", &opts)) {
2125 vga_interface_type = VGA_VMWARE;
2126 } else if (strstart(p, "xenfb", &opts)) {
2127 vga_interface_type = VGA_XENFB;
2128 } else if (!strstart(p, "none", &opts)) {
2129 invalid_vga:
2130 fprintf(stderr, "Unknown vga type: %s\n", p);
2131 exit(1);
2133 while (*opts) {
2134 const char *nextopt;
2136 if (strstart(opts, ",retrace=", &nextopt)) {
2137 opts = nextopt;
2138 if (strstart(opts, "dumb", &nextopt))
2139 vga_retrace_method = VGA_RETRACE_DUMB;
2140 else if (strstart(opts, "precise", &nextopt))
2141 vga_retrace_method = VGA_RETRACE_PRECISE;
2142 else goto invalid_vga;
2143 } else goto invalid_vga;
2144 opts = nextopt;
2148 static int balloon_parse(const char *arg)
2150 QemuOpts *opts;
2152 if (strcmp(arg, "none") == 0) {
2153 return 0;
2156 if (!strncmp(arg, "virtio", 6)) {
2157 if (arg[6] == ',') {
2158 /* have params -> parse them */
2159 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
2160 if (!opts)
2161 return -1;
2162 } else {
2163 /* create empty opts */
2164 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2166 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
2167 return 0;
2170 return -1;
2173 #ifdef _WIN32
2174 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
2176 exit(STATUS_CONTROL_C_EXIT);
2177 return TRUE;
2179 #endif
2181 #ifndef _WIN32
2183 static void termsig_handler(int signal)
2185 qemu_system_shutdown_request();
2188 static void sigchld_handler(int signal)
2190 waitpid(-1, NULL, WNOHANG);
2193 static void sighandler_setup(void)
2195 struct sigaction act;
2197 memset(&act, 0, sizeof(act));
2198 act.sa_handler = termsig_handler;
2199 sigaction(SIGINT, &act, NULL);
2200 sigaction(SIGHUP, &act, NULL);
2201 sigaction(SIGTERM, &act, NULL);
2203 act.sa_handler = sigchld_handler;
2204 act.sa_flags = SA_NOCLDSTOP;
2205 sigaction(SIGCHLD, &act, NULL);
2208 #endif
2210 #ifdef _WIN32
2211 /* Look for support files in the same directory as the executable. */
2212 static char *find_datadir(const char *argv0)
2214 char *p;
2215 char buf[MAX_PATH];
2216 DWORD len;
2218 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
2219 if (len == 0) {
2220 return NULL;
2223 buf[len] = 0;
2224 p = buf + len - 1;
2225 while (p != buf && *p != '\\')
2226 p--;
2227 *p = 0;
2228 if (access(buf, R_OK) == 0) {
2229 return qemu_strdup(buf);
2231 return NULL;
2233 #else /* !_WIN32 */
2235 /* Find a likely location for support files using the location of the binary.
2236 For installed binaries this will be "$bindir/../share/qemu". When
2237 running from the build tree this will be "$bindir/../pc-bios". */
2238 #define SHARE_SUFFIX "/share/qemu"
2239 #define BUILD_SUFFIX "/pc-bios"
2240 static char *find_datadir(const char *argv0)
2242 char *dir;
2243 char *p = NULL;
2244 char *res;
2245 char buf[PATH_MAX];
2246 size_t max_len;
2248 #if defined(__linux__)
2250 int len;
2251 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
2252 if (len > 0) {
2253 buf[len] = 0;
2254 p = buf;
2257 #elif defined(__FreeBSD__)
2259 static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
2260 size_t len = sizeof(buf) - 1;
2262 *buf = '\0';
2263 if (!sysctl(mib, sizeof(mib)/sizeof(*mib), buf, &len, NULL, 0) &&
2264 *buf) {
2265 buf[sizeof(buf) - 1] = '\0';
2266 p = buf;
2269 #endif
2270 /* If we don't have any way of figuring out the actual executable
2271 location then try argv[0]. */
2272 if (!p) {
2273 p = realpath(argv0, buf);
2274 if (!p) {
2275 return NULL;
2278 dir = dirname(p);
2279 dir = dirname(dir);
2281 max_len = strlen(dir) +
2282 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
2283 res = qemu_mallocz(max_len);
2284 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
2285 if (access(res, R_OK)) {
2286 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
2287 if (access(res, R_OK)) {
2288 qemu_free(res);
2289 res = NULL;
2293 return res;
2295 #undef SHARE_SUFFIX
2296 #undef BUILD_SUFFIX
2297 #endif
2299 char *qemu_find_file(int type, const char *name)
2301 int len;
2302 const char *subdir;
2303 char *buf;
2305 /* If name contains path separators then try it as a straight path. */
2306 if ((strchr(name, '/') || strchr(name, '\\'))
2307 && access(name, R_OK) == 0) {
2308 return qemu_strdup(name);
2310 switch (type) {
2311 case QEMU_FILE_TYPE_BIOS:
2312 subdir = "";
2313 break;
2314 case QEMU_FILE_TYPE_KEYMAP:
2315 subdir = "keymaps/";
2316 break;
2317 default:
2318 abort();
2320 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
2321 buf = qemu_mallocz(len);
2322 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
2323 if (access(buf, R_OK)) {
2324 qemu_free(buf);
2325 return NULL;
2327 return buf;
2330 static int device_help_func(QemuOpts *opts, void *opaque)
2332 return qdev_device_help(opts);
2335 static int device_init_func(QemuOpts *opts, void *opaque)
2337 DeviceState *dev;
2339 dev = qdev_device_add(opts);
2340 if (!dev)
2341 return -1;
2342 return 0;
2345 static int chardev_init_func(QemuOpts *opts, void *opaque)
2347 CharDriverState *chr;
2349 chr = qemu_chr_open_opts(opts, NULL);
2350 if (!chr)
2351 return -1;
2352 return 0;
2355 #ifdef CONFIG_LINUX
2356 static int fsdev_init_func(QemuOpts *opts, void *opaque)
2358 int ret;
2359 ret = qemu_fsdev_add(opts);
2361 return ret;
2363 #endif
2365 static int mon_init_func(QemuOpts *opts, void *opaque)
2367 CharDriverState *chr;
2368 const char *chardev;
2369 const char *mode;
2370 int flags;
2372 mode = qemu_opt_get(opts, "mode");
2373 if (mode == NULL) {
2374 mode = "readline";
2376 if (strcmp(mode, "readline") == 0) {
2377 flags = MONITOR_USE_READLINE;
2378 } else if (strcmp(mode, "control") == 0) {
2379 flags = MONITOR_USE_CONTROL;
2380 } else {
2381 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2382 exit(1);
2385 if (qemu_opt_get_bool(opts, "default", 0))
2386 flags |= MONITOR_IS_DEFAULT;
2388 chardev = qemu_opt_get(opts, "chardev");
2389 chr = qemu_chr_find(chardev);
2390 if (chr == NULL) {
2391 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2392 exit(1);
2395 monitor_init(chr, flags);
2396 return 0;
2399 static void monitor_parse(const char *optarg, const char *mode)
2401 static int monitor_device_index = 0;
2402 QemuOpts *opts;
2403 const char *p;
2404 char label[32];
2405 int def = 0;
2407 if (strstart(optarg, "chardev:", &p)) {
2408 snprintf(label, sizeof(label), "%s", p);
2409 } else {
2410 snprintf(label, sizeof(label), "compat_monitor%d",
2411 monitor_device_index);
2412 if (monitor_device_index == 0) {
2413 def = 1;
2415 opts = qemu_chr_parse_compat(label, optarg);
2416 if (!opts) {
2417 fprintf(stderr, "parse error: %s\n", optarg);
2418 exit(1);
2422 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
2423 if (!opts) {
2424 fprintf(stderr, "duplicate chardev: %s\n", label);
2425 exit(1);
2427 qemu_opt_set(opts, "mode", mode);
2428 qemu_opt_set(opts, "chardev", label);
2429 if (def)
2430 qemu_opt_set(opts, "default", "on");
2431 monitor_device_index++;
2434 struct device_config {
2435 enum {
2436 DEV_USB, /* -usbdevice */
2437 DEV_BT, /* -bt */
2438 DEV_SERIAL, /* -serial */
2439 DEV_PARALLEL, /* -parallel */
2440 DEV_VIRTCON, /* -virtioconsole */
2441 DEV_DEBUGCON, /* -debugcon */
2442 } type;
2443 const char *cmdline;
2444 QTAILQ_ENTRY(device_config) next;
2446 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
2448 static void add_device_config(int type, const char *cmdline)
2450 struct device_config *conf;
2452 conf = qemu_mallocz(sizeof(*conf));
2453 conf->type = type;
2454 conf->cmdline = cmdline;
2455 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2458 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2460 struct device_config *conf;
2461 int rc;
2463 QTAILQ_FOREACH(conf, &device_configs, next) {
2464 if (conf->type != type)
2465 continue;
2466 rc = func(conf->cmdline);
2467 if (0 != rc)
2468 return rc;
2470 return 0;
2473 static int serial_parse(const char *devname)
2475 static int index = 0;
2476 char label[32];
2478 if (strcmp(devname, "none") == 0)
2479 return 0;
2480 if (index == MAX_SERIAL_PORTS) {
2481 fprintf(stderr, "qemu: too many serial ports\n");
2482 exit(1);
2484 snprintf(label, sizeof(label), "serial%d", index);
2485 serial_hds[index] = qemu_chr_open(label, devname, NULL);
2486 if (!serial_hds[index]) {
2487 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
2488 devname, strerror(errno));
2489 return -1;
2491 index++;
2492 return 0;
2495 static int parallel_parse(const char *devname)
2497 static int index = 0;
2498 char label[32];
2500 if (strcmp(devname, "none") == 0)
2501 return 0;
2502 if (index == MAX_PARALLEL_PORTS) {
2503 fprintf(stderr, "qemu: too many parallel ports\n");
2504 exit(1);
2506 snprintf(label, sizeof(label), "parallel%d", index);
2507 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
2508 if (!parallel_hds[index]) {
2509 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2510 devname, strerror(errno));
2511 return -1;
2513 index++;
2514 return 0;
2517 static int virtcon_parse(const char *devname)
2519 static int index = 0;
2520 char label[32];
2521 QemuOpts *bus_opts, *dev_opts;
2523 if (strcmp(devname, "none") == 0)
2524 return 0;
2525 if (index == MAX_VIRTIO_CONSOLES) {
2526 fprintf(stderr, "qemu: too many virtio consoles\n");
2527 exit(1);
2530 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2531 qemu_opt_set(bus_opts, "driver", "virtio-serial");
2533 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2534 qemu_opt_set(dev_opts, "driver", "virtconsole");
2536 snprintf(label, sizeof(label), "virtcon%d", index);
2537 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
2538 if (!virtcon_hds[index]) {
2539 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2540 devname, strerror(errno));
2541 return -1;
2543 qemu_opt_set(dev_opts, "chardev", label);
2545 index++;
2546 return 0;
2549 static int debugcon_parse(const char *devname)
2551 QemuOpts *opts;
2553 if (!qemu_chr_open("debugcon", devname, NULL)) {
2554 exit(1);
2556 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
2557 if (!opts) {
2558 fprintf(stderr, "qemu: already have a debugcon device\n");
2559 exit(1);
2561 qemu_opt_set(opts, "driver", "isa-debugcon");
2562 qemu_opt_set(opts, "chardev", "debugcon");
2563 return 0;
2566 static const QEMUOption *lookup_opt(int argc, char **argv,
2567 const char **poptarg, int *poptind)
2569 const QEMUOption *popt;
2570 int optind = *poptind;
2571 char *r = argv[optind];
2572 const char *optarg;
2574 loc_set_cmdline(argv, optind, 1);
2575 optind++;
2576 /* Treat --foo the same as -foo. */
2577 if (r[1] == '-')
2578 r++;
2579 popt = qemu_options;
2580 for(;;) {
2581 if (!popt->name) {
2582 error_report("invalid option");
2583 exit(1);
2585 if (!strcmp(popt->name, r + 1))
2586 break;
2587 popt++;
2589 if (popt->flags & HAS_ARG) {
2590 if (optind >= argc) {
2591 error_report("requires an argument");
2592 exit(1);
2594 optarg = argv[optind++];
2595 loc_set_cmdline(argv, optind - 2, 2);
2596 } else {
2597 optarg = NULL;
2600 *poptarg = optarg;
2601 *poptind = optind;
2603 return popt;
2606 int main(int argc, char **argv, char **envp)
2608 const char *gdbstub_dev = NULL;
2609 int i;
2610 int snapshot, linux_boot;
2611 const char *icount_option = NULL;
2612 const char *initrd_filename;
2613 const char *kernel_filename, *kernel_cmdline;
2614 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2615 DisplayState *ds;
2616 DisplayChangeListener *dcl;
2617 int cyls, heads, secs, translation;
2618 QemuOpts *hda_opts = NULL, *opts;
2619 int optind;
2620 const char *optarg;
2621 const char *loadvm = NULL;
2622 QEMUMachine *machine;
2623 const char *cpu_model;
2624 #ifndef _WIN32
2625 int fds[2];
2626 #endif
2627 int tb_size;
2628 const char *pid_file = NULL;
2629 const char *incoming = NULL;
2630 #ifndef _WIN32
2631 int fd = 0;
2632 struct passwd *pwd = NULL;
2633 const char *chroot_dir = NULL;
2634 const char *run_as = NULL;
2635 #endif
2636 int show_vnc_port = 0;
2637 int defconfig = 1;
2639 error_set_progname(argv[0]);
2641 init_clocks();
2643 qemu_cache_utils_init(envp);
2645 QLIST_INIT (&vm_change_state_head);
2646 #ifndef _WIN32
2648 struct sigaction act;
2649 sigfillset(&act.sa_mask);
2650 act.sa_flags = 0;
2651 act.sa_handler = SIG_IGN;
2652 sigaction(SIGPIPE, &act, NULL);
2654 #else
2655 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
2656 /* Note: cpu_interrupt() is currently not SMP safe, so we force
2657 QEMU to run on a single CPU */
2659 HANDLE h;
2660 DWORD mask, smask;
2661 int i;
2662 h = GetCurrentProcess();
2663 if (GetProcessAffinityMask(h, &mask, &smask)) {
2664 for(i = 0; i < 32; i++) {
2665 if (mask & (1 << i))
2666 break;
2668 if (i != 32) {
2669 mask = 1 << i;
2670 SetProcessAffinityMask(h, mask);
2674 #endif
2676 module_call_init(MODULE_INIT_MACHINE);
2677 machine = find_default_machine();
2678 cpu_model = NULL;
2679 initrd_filename = NULL;
2680 ram_size = 0;
2681 snapshot = 0;
2682 kernel_filename = NULL;
2683 kernel_cmdline = "";
2684 cyls = heads = secs = 0;
2685 translation = BIOS_ATA_TRANSLATION_AUTO;
2687 for (i = 0; i < MAX_NODES; i++) {
2688 node_mem[i] = 0;
2689 node_cpumask[i] = 0;
2692 assigned_devices_index = 0;
2694 nb_numa_nodes = 0;
2695 nb_nics = 0;
2697 tb_size = 0;
2698 autostart= 1;
2700 /* first pass of option parsing */
2701 optind = 1;
2702 while (optind < argc) {
2703 if (argv[optind][0] != '-') {
2704 /* disk image */
2705 optind++;
2706 continue;
2707 } else {
2708 const QEMUOption *popt;
2710 popt = lookup_opt(argc, argv, &optarg, &optind);
2711 switch (popt->index) {
2712 case QEMU_OPTION_nodefconfig:
2713 defconfig=0;
2714 break;
2719 if (defconfig) {
2720 int ret;
2722 ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");
2723 if (ret == -EINVAL) {
2724 exit(1);
2727 ret = qemu_read_config_file(arch_config_name);
2728 if (ret == -EINVAL) {
2729 exit(1);
2732 cpudef_init();
2734 /* second pass of option parsing */
2735 optind = 1;
2736 for(;;) {
2737 if (optind >= argc)
2738 break;
2739 if (argv[optind][0] != '-') {
2740 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
2741 } else {
2742 const QEMUOption *popt;
2744 popt = lookup_opt(argc, argv, &optarg, &optind);
2745 if (!(popt->arch_mask & arch_type)) {
2746 printf("Option %s not supported for this target\n", popt->name);
2747 exit(1);
2749 switch(popt->index) {
2750 case QEMU_OPTION_M:
2751 machine = find_machine(optarg);
2752 if (!machine) {
2753 QEMUMachine *m;
2754 printf("Supported machines are:\n");
2755 for(m = first_machine; m != NULL; m = m->next) {
2756 if (m->alias)
2757 printf("%-10s %s (alias of %s)\n",
2758 m->alias, m->desc, m->name);
2759 printf("%-10s %s%s\n",
2760 m->name, m->desc,
2761 m->is_default ? " (default)" : "");
2763 exit(*optarg != '?');
2765 break;
2766 case QEMU_OPTION_cpu:
2767 /* hw initialization will check this */
2768 if (*optarg == '?') {
2769 list_cpus(stdout, &fprintf, optarg);
2770 exit(0);
2771 } else {
2772 cpu_model = optarg;
2774 break;
2775 case QEMU_OPTION_initrd:
2776 initrd_filename = optarg;
2777 break;
2778 case QEMU_OPTION_hda:
2779 if (cyls == 0)
2780 hda_opts = drive_add(optarg, HD_ALIAS, 0);
2781 else
2782 hda_opts = drive_add(optarg, HD_ALIAS
2783 ",cyls=%d,heads=%d,secs=%d%s",
2784 0, cyls, heads, secs,
2785 translation == BIOS_ATA_TRANSLATION_LBA ?
2786 ",trans=lba" :
2787 translation == BIOS_ATA_TRANSLATION_NONE ?
2788 ",trans=none" : "");
2789 break;
2790 case QEMU_OPTION_hdb:
2791 case QEMU_OPTION_hdc:
2792 case QEMU_OPTION_hdd:
2793 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
2794 break;
2795 case QEMU_OPTION_drive:
2796 drive_add(NULL, "%s", optarg);
2797 break;
2798 case QEMU_OPTION_set:
2799 if (qemu_set_option(optarg) != 0)
2800 exit(1);
2801 break;
2802 case QEMU_OPTION_global:
2803 if (qemu_global_option(optarg) != 0)
2804 exit(1);
2805 break;
2806 case QEMU_OPTION_mtdblock:
2807 drive_add(optarg, MTD_ALIAS);
2808 break;
2809 case QEMU_OPTION_sd:
2810 drive_add(optarg, SD_ALIAS);
2811 break;
2812 case QEMU_OPTION_pflash:
2813 drive_add(optarg, PFLASH_ALIAS);
2814 break;
2815 case QEMU_OPTION_snapshot:
2816 snapshot = 1;
2817 break;
2818 case QEMU_OPTION_hdachs:
2820 const char *p;
2821 p = optarg;
2822 cyls = strtol(p, (char **)&p, 0);
2823 if (cyls < 1 || cyls > 16383)
2824 goto chs_fail;
2825 if (*p != ',')
2826 goto chs_fail;
2827 p++;
2828 heads = strtol(p, (char **)&p, 0);
2829 if (heads < 1 || heads > 16)
2830 goto chs_fail;
2831 if (*p != ',')
2832 goto chs_fail;
2833 p++;
2834 secs = strtol(p, (char **)&p, 0);
2835 if (secs < 1 || secs > 63)
2836 goto chs_fail;
2837 if (*p == ',') {
2838 p++;
2839 if (!strcmp(p, "none"))
2840 translation = BIOS_ATA_TRANSLATION_NONE;
2841 else if (!strcmp(p, "lba"))
2842 translation = BIOS_ATA_TRANSLATION_LBA;
2843 else if (!strcmp(p, "auto"))
2844 translation = BIOS_ATA_TRANSLATION_AUTO;
2845 else
2846 goto chs_fail;
2847 } else if (*p != '\0') {
2848 chs_fail:
2849 fprintf(stderr, "qemu: invalid physical CHS format\n");
2850 exit(1);
2852 if (hda_opts != NULL) {
2853 char num[16];
2854 snprintf(num, sizeof(num), "%d", cyls);
2855 qemu_opt_set(hda_opts, "cyls", num);
2856 snprintf(num, sizeof(num), "%d", heads);
2857 qemu_opt_set(hda_opts, "heads", num);
2858 snprintf(num, sizeof(num), "%d", secs);
2859 qemu_opt_set(hda_opts, "secs", num);
2860 if (translation == BIOS_ATA_TRANSLATION_LBA)
2861 qemu_opt_set(hda_opts, "trans", "lba");
2862 if (translation == BIOS_ATA_TRANSLATION_NONE)
2863 qemu_opt_set(hda_opts, "trans", "none");
2866 break;
2867 case QEMU_OPTION_numa:
2868 if (nb_numa_nodes >= MAX_NODES) {
2869 fprintf(stderr, "qemu: too many NUMA nodes\n");
2870 exit(1);
2872 numa_add(optarg);
2873 break;
2874 case QEMU_OPTION_nographic:
2875 display_type = DT_NOGRAPHIC;
2876 break;
2877 #ifdef CONFIG_CURSES
2878 case QEMU_OPTION_curses:
2879 display_type = DT_CURSES;
2880 break;
2881 #endif
2882 case QEMU_OPTION_portrait:
2883 graphic_rotate = 1;
2884 break;
2885 case QEMU_OPTION_kernel:
2886 kernel_filename = optarg;
2887 break;
2888 case QEMU_OPTION_append:
2889 kernel_cmdline = optarg;
2890 break;
2891 case QEMU_OPTION_cdrom:
2892 drive_add(optarg, CDROM_ALIAS);
2893 break;
2894 case QEMU_OPTION_boot:
2896 static const char * const params[] = {
2897 "order", "once", "menu", NULL
2899 char buf[sizeof(boot_devices)];
2900 char *standard_boot_devices;
2901 int legacy = 0;
2903 if (!strchr(optarg, '=')) {
2904 legacy = 1;
2905 pstrcpy(buf, sizeof(buf), optarg);
2906 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2907 fprintf(stderr,
2908 "qemu: unknown boot parameter '%s' in '%s'\n",
2909 buf, optarg);
2910 exit(1);
2913 if (legacy ||
2914 get_param_value(buf, sizeof(buf), "order", optarg)) {
2915 validate_bootdevices(buf);
2916 pstrcpy(boot_devices, sizeof(boot_devices), buf);
2918 if (!legacy) {
2919 if (get_param_value(buf, sizeof(buf),
2920 "once", optarg)) {
2921 validate_bootdevices(buf);
2922 standard_boot_devices = qemu_strdup(boot_devices);
2923 pstrcpy(boot_devices, sizeof(boot_devices), buf);
2924 qemu_register_reset(restore_boot_devices,
2925 standard_boot_devices);
2927 if (get_param_value(buf, sizeof(buf),
2928 "menu", optarg)) {
2929 if (!strcmp(buf, "on")) {
2930 boot_menu = 1;
2931 } else if (!strcmp(buf, "off")) {
2932 boot_menu = 0;
2933 } else {
2934 fprintf(stderr,
2935 "qemu: invalid option value '%s'\n",
2936 buf);
2937 exit(1);
2942 break;
2943 case QEMU_OPTION_fda:
2944 case QEMU_OPTION_fdb:
2945 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
2946 break;
2947 case QEMU_OPTION_no_fd_bootchk:
2948 fd_bootchk = 0;
2949 break;
2950 case QEMU_OPTION_netdev:
2951 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
2952 exit(1);
2954 break;
2955 case QEMU_OPTION_net:
2956 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
2957 exit(1);
2959 break;
2960 #ifdef CONFIG_SLIRP
2961 case QEMU_OPTION_tftp:
2962 legacy_tftp_prefix = optarg;
2963 break;
2964 case QEMU_OPTION_bootp:
2965 legacy_bootp_filename = optarg;
2966 break;
2967 #ifndef _WIN32
2968 case QEMU_OPTION_smb:
2969 if (net_slirp_smb(optarg) < 0)
2970 exit(1);
2971 break;
2972 #endif
2973 case QEMU_OPTION_redir:
2974 if (net_slirp_redir(optarg) < 0)
2975 exit(1);
2976 break;
2977 #endif
2978 case QEMU_OPTION_bt:
2979 add_device_config(DEV_BT, optarg);
2980 break;
2981 case QEMU_OPTION_audio_help:
2982 if (!(audio_available())) {
2983 printf("Option %s not supported for this target\n", popt->name);
2984 exit(1);
2986 AUD_help ();
2987 exit (0);
2988 break;
2989 case QEMU_OPTION_soundhw:
2990 if (!(audio_available())) {
2991 printf("Option %s not supported for this target\n", popt->name);
2992 exit(1);
2994 select_soundhw (optarg);
2995 break;
2996 case QEMU_OPTION_h:
2997 help(0);
2998 break;
2999 case QEMU_OPTION_version:
3000 version();
3001 exit(0);
3002 break;
3003 case QEMU_OPTION_m: {
3004 uint64_t value;
3005 char *ptr;
3007 value = strtoul(optarg, &ptr, 10);
3008 switch (*ptr) {
3009 case 0: case 'M': case 'm':
3010 value <<= 20;
3011 break;
3012 case 'G': case 'g':
3013 value <<= 30;
3014 break;
3015 default:
3016 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
3017 exit(1);
3020 /* On 32-bit hosts, QEMU is limited by virtual address space */
3021 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
3022 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3023 exit(1);
3025 if (value != (uint64_t)(ram_addr_t)value) {
3026 fprintf(stderr, "qemu: ram size too large\n");
3027 exit(1);
3029 ram_size = value;
3030 break;
3032 case QEMU_OPTION_mempath:
3033 mem_path = optarg;
3034 break;
3035 #ifdef MAP_POPULATE
3036 case QEMU_OPTION_mem_prealloc:
3037 mem_prealloc = 1;
3038 break;
3039 #endif
3040 case QEMU_OPTION_d:
3041 set_cpu_log(optarg);
3042 break;
3043 case QEMU_OPTION_s:
3044 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
3045 break;
3046 case QEMU_OPTION_gdb:
3047 gdbstub_dev = optarg;
3048 break;
3049 case QEMU_OPTION_L:
3050 data_dir = optarg;
3051 break;
3052 case QEMU_OPTION_bios:
3053 bios_name = optarg;
3054 break;
3055 case QEMU_OPTION_singlestep:
3056 singlestep = 1;
3057 break;
3058 case QEMU_OPTION_S:
3059 autostart = 0;
3060 break;
3061 case QEMU_OPTION_k:
3062 keyboard_layout = optarg;
3063 break;
3064 case QEMU_OPTION_localtime:
3065 rtc_utc = 0;
3066 break;
3067 case QEMU_OPTION_vga:
3068 select_vgahw (optarg);
3069 break;
3070 case QEMU_OPTION_g:
3072 const char *p;
3073 int w, h, depth;
3074 p = optarg;
3075 w = strtol(p, (char **)&p, 10);
3076 if (w <= 0) {
3077 graphic_error:
3078 fprintf(stderr, "qemu: invalid resolution or depth\n");
3079 exit(1);
3081 if (*p != 'x')
3082 goto graphic_error;
3083 p++;
3084 h = strtol(p, (char **)&p, 10);
3085 if (h <= 0)
3086 goto graphic_error;
3087 if (*p == 'x') {
3088 p++;
3089 depth = strtol(p, (char **)&p, 10);
3090 if (depth != 8 && depth != 15 && depth != 16 &&
3091 depth != 24 && depth != 32)
3092 goto graphic_error;
3093 } else if (*p == '\0') {
3094 depth = graphic_depth;
3095 } else {
3096 goto graphic_error;
3099 graphic_width = w;
3100 graphic_height = h;
3101 graphic_depth = depth;
3103 break;
3104 case QEMU_OPTION_echr:
3106 char *r;
3107 term_escape_char = strtol(optarg, &r, 0);
3108 if (r == optarg)
3109 printf("Bad argument to echr\n");
3110 break;
3112 case QEMU_OPTION_monitor:
3113 monitor_parse(optarg, "readline");
3114 default_monitor = 0;
3115 break;
3116 case QEMU_OPTION_qmp:
3117 monitor_parse(optarg, "control");
3118 default_monitor = 0;
3119 break;
3120 case QEMU_OPTION_mon:
3121 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
3122 if (!opts) {
3123 exit(1);
3125 default_monitor = 0;
3126 break;
3127 case QEMU_OPTION_chardev:
3128 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
3129 if (!opts) {
3130 exit(1);
3132 break;
3133 #ifdef CONFIG_LINUX
3134 case QEMU_OPTION_fsdev:
3135 opts = qemu_opts_parse(&qemu_fsdev_opts, optarg, 1);
3136 if (!opts) {
3137 fprintf(stderr, "parse error: %s\n", optarg);
3138 exit(1);
3140 break;
3141 case QEMU_OPTION_virtfs: {
3142 char *arg_fsdev = NULL;
3143 char *arg_9p = NULL;
3144 int len = 0;
3146 opts = qemu_opts_parse(&qemu_virtfs_opts, optarg, 1);
3147 if (!opts) {
3148 fprintf(stderr, "parse error: %s\n", optarg);
3149 exit(1);
3152 len = strlen(",id=,path=");
3153 len += strlen(qemu_opt_get(opts, "fstype"));
3154 len += strlen(qemu_opt_get(opts, "mount_tag"));
3155 len += strlen(qemu_opt_get(opts, "path"));
3156 arg_fsdev = qemu_malloc((len + 1) * sizeof(*arg_fsdev));
3158 if (!arg_fsdev) {
3159 fprintf(stderr, "No memory to parse -fsdev for %s\n",
3160 optarg);
3161 exit(1);
3164 sprintf(arg_fsdev, "%s,id=%s,path=%s",
3165 qemu_opt_get(opts, "fstype"),
3166 qemu_opt_get(opts, "mount_tag"),
3167 qemu_opt_get(opts, "path"));
3169 len = strlen("virtio-9p-pci,fsdev=,mount_tag=");
3170 len += 2*strlen(qemu_opt_get(opts, "mount_tag"));
3171 arg_9p = qemu_malloc((len + 1) * sizeof(*arg_9p));
3173 if (!arg_9p) {
3174 fprintf(stderr, "No memory to parse -device for %s\n",
3175 optarg);
3176 exit(1);
3179 sprintf(arg_9p, "virtio-9p-pci,fsdev=%s,mount_tag=%s",
3180 qemu_opt_get(opts, "mount_tag"),
3181 qemu_opt_get(opts, "mount_tag"));
3183 if (!qemu_opts_parse(&qemu_fsdev_opts, arg_fsdev, 1)) {
3184 fprintf(stderr, "parse error [fsdev]: %s\n", optarg);
3185 exit(1);
3188 if (!qemu_opts_parse(&qemu_device_opts, arg_9p, 1)) {
3189 fprintf(stderr, "parse error [device]: %s\n", optarg);
3190 exit(1);
3193 qemu_free(arg_fsdev);
3194 qemu_free(arg_9p);
3195 break;
3197 #endif
3198 case QEMU_OPTION_serial:
3199 add_device_config(DEV_SERIAL, optarg);
3200 default_serial = 0;
3201 if (strncmp(optarg, "mon:", 4) == 0) {
3202 default_monitor = 0;
3204 break;
3205 case QEMU_OPTION_watchdog:
3206 if (watchdog) {
3207 fprintf(stderr,
3208 "qemu: only one watchdog option may be given\n");
3209 return 1;
3211 watchdog = optarg;
3212 break;
3213 case QEMU_OPTION_watchdog_action:
3214 if (select_watchdog_action(optarg) == -1) {
3215 fprintf(stderr, "Unknown -watchdog-action parameter\n");
3216 exit(1);
3218 break;
3219 case QEMU_OPTION_virtiocon:
3220 add_device_config(DEV_VIRTCON, optarg);
3221 default_virtcon = 0;
3222 if (strncmp(optarg, "mon:", 4) == 0) {
3223 default_monitor = 0;
3225 break;
3226 case QEMU_OPTION_parallel:
3227 add_device_config(DEV_PARALLEL, optarg);
3228 default_parallel = 0;
3229 if (strncmp(optarg, "mon:", 4) == 0) {
3230 default_monitor = 0;
3232 break;
3233 case QEMU_OPTION_debugcon:
3234 add_device_config(DEV_DEBUGCON, optarg);
3235 break;
3236 case QEMU_OPTION_loadvm:
3237 loadvm = optarg;
3238 break;
3239 case QEMU_OPTION_full_screen:
3240 full_screen = 1;
3241 break;
3242 #ifdef CONFIG_SDL
3243 case QEMU_OPTION_no_frame:
3244 no_frame = 1;
3245 break;
3246 case QEMU_OPTION_alt_grab:
3247 alt_grab = 1;
3248 break;
3249 case QEMU_OPTION_ctrl_grab:
3250 ctrl_grab = 1;
3251 break;
3252 case QEMU_OPTION_no_quit:
3253 no_quit = 1;
3254 break;
3255 case QEMU_OPTION_sdl:
3256 display_type = DT_SDL;
3257 break;
3258 #endif
3259 case QEMU_OPTION_pidfile:
3260 pid_file = optarg;
3261 break;
3262 case QEMU_OPTION_win2k_hack:
3263 win2k_install_hack = 1;
3264 break;
3265 case QEMU_OPTION_rtc_td_hack:
3266 rtc_td_hack = 1;
3267 break;
3268 case QEMU_OPTION_acpitable:
3269 do_acpitable_option(optarg);
3270 break;
3271 case QEMU_OPTION_smbios:
3272 do_smbios_option(optarg);
3273 break;
3274 #ifdef KVM_UPSTREAM
3275 case QEMU_OPTION_enable_kvm:
3276 kvm_allowed = 1;
3277 #endif
3278 break;
3279 case QEMU_OPTION_no_kvm:
3280 kvm_allowed = 0;
3281 break;
3282 case QEMU_OPTION_no_kvm_irqchip: {
3283 kvm_irqchip = 0;
3284 kvm_pit = 0;
3285 break;
3287 case QEMU_OPTION_no_kvm_pit: {
3288 kvm_pit = 0;
3289 break;
3291 case QEMU_OPTION_no_kvm_pit_reinjection: {
3292 kvm_pit_reinject = 0;
3293 break;
3295 case QEMU_OPTION_enable_nesting: {
3296 kvm_nested = 1;
3297 break;
3299 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
3300 case QEMU_OPTION_pcidevice:
3301 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
3302 fprintf(stderr, "Too many assigned devices\n");
3303 exit(1);
3305 assigned_devices[assigned_devices_index] = optarg;
3306 assigned_devices_index++;
3307 break;
3308 #endif
3309 case QEMU_OPTION_usb:
3310 usb_enabled = 1;
3311 break;
3312 case QEMU_OPTION_usbdevice:
3313 usb_enabled = 1;
3314 add_device_config(DEV_USB, optarg);
3315 break;
3316 case QEMU_OPTION_device:
3317 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
3318 exit(1);
3320 break;
3321 case QEMU_OPTION_smp:
3322 smp_parse(optarg);
3323 if (smp_cpus < 1) {
3324 fprintf(stderr, "Invalid number of CPUs\n");
3325 exit(1);
3327 if (max_cpus < smp_cpus) {
3328 fprintf(stderr, "maxcpus must be equal to or greater than "
3329 "smp\n");
3330 exit(1);
3332 if (max_cpus > 255) {
3333 fprintf(stderr, "Unsupported number of maxcpus\n");
3334 exit(1);
3336 break;
3337 case QEMU_OPTION_vnc:
3338 display_type = DT_VNC;
3339 vnc_display = optarg;
3340 break;
3341 case QEMU_OPTION_no_acpi:
3342 acpi_enabled = 0;
3343 break;
3344 case QEMU_OPTION_no_hpet:
3345 no_hpet = 1;
3346 break;
3347 case QEMU_OPTION_balloon:
3348 if (balloon_parse(optarg) < 0) {
3349 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3350 exit(1);
3352 break;
3353 case QEMU_OPTION_no_reboot:
3354 no_reboot = 1;
3355 break;
3356 case QEMU_OPTION_no_shutdown:
3357 no_shutdown = 1;
3358 break;
3359 case QEMU_OPTION_show_cursor:
3360 cursor_hide = 0;
3361 break;
3362 case QEMU_OPTION_uuid:
3363 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3364 fprintf(stderr, "Fail to parse UUID string."
3365 " Wrong format.\n");
3366 exit(1);
3368 break;
3369 #ifndef _WIN32
3370 case QEMU_OPTION_daemonize:
3371 daemonize = 1;
3372 break;
3373 #endif
3374 case QEMU_OPTION_option_rom:
3375 if (nb_option_roms >= MAX_OPTION_ROMS) {
3376 fprintf(stderr, "Too many option ROMs\n");
3377 exit(1);
3379 option_rom[nb_option_roms] = optarg;
3380 nb_option_roms++;
3381 break;
3382 case QEMU_OPTION_semihosting:
3383 semihosting_enabled = 1;
3384 break;
3385 case QEMU_OPTION_tdf:
3386 time_drift_fix = 1;
3387 break;
3388 case QEMU_OPTION_kvm_shadow_memory:
3389 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
3390 break;
3391 case QEMU_OPTION_name:
3392 qemu_name = qemu_strdup(optarg);
3394 char *p = strchr(qemu_name, ',');
3395 if (p != NULL) {
3396 *p++ = 0;
3397 if (strncmp(p, "process=", 8)) {
3398 fprintf(stderr, "Unknown subargument %s to -name", p);
3399 exit(1);
3401 p += 8;
3402 set_proc_name(p);
3405 break;
3406 case QEMU_OPTION_prom_env:
3407 if (nb_prom_envs >= MAX_PROM_ENVS) {
3408 fprintf(stderr, "Too many prom variables\n");
3409 exit(1);
3411 prom_envs[nb_prom_envs] = optarg;
3412 nb_prom_envs++;
3413 break;
3414 case QEMU_OPTION_old_param:
3415 old_param = 1;
3416 break;
3417 case QEMU_OPTION_clock:
3418 configure_alarms(optarg);
3419 break;
3420 case QEMU_OPTION_startdate:
3421 configure_rtc_date_offset(optarg, 1);
3422 break;
3423 case QEMU_OPTION_rtc:
3424 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
3425 if (!opts) {
3426 exit(1);
3428 configure_rtc(opts);
3429 break;
3430 case QEMU_OPTION_tb_size:
3431 tb_size = strtol(optarg, NULL, 0);
3432 if (tb_size < 0)
3433 tb_size = 0;
3434 break;
3435 case QEMU_OPTION_icount:
3436 icount_option = optarg;
3437 break;
3438 case QEMU_OPTION_incoming:
3439 incoming = optarg;
3440 break;
3441 case QEMU_OPTION_nodefaults:
3442 default_serial = 0;
3443 default_parallel = 0;
3444 default_virtcon = 0;
3445 default_monitor = 0;
3446 default_vga = 0;
3447 default_net = 0;
3448 default_floppy = 0;
3449 default_cdrom = 0;
3450 default_sdcard = 0;
3451 break;
3452 #ifndef _WIN32
3453 case QEMU_OPTION_chroot:
3454 chroot_dir = optarg;
3455 break;
3456 case QEMU_OPTION_runas:
3457 run_as = optarg;
3458 break;
3459 case QEMU_OPTION_nvram:
3460 nvram = optarg;
3461 break;
3462 #endif
3463 case QEMU_OPTION_xen_domid:
3464 if (!(xen_available())) {
3465 printf("Option %s not supported for this target\n", popt->name);
3466 exit(1);
3468 xen_domid = atoi(optarg);
3469 break;
3470 case QEMU_OPTION_xen_create:
3471 if (!(xen_available())) {
3472 printf("Option %s not supported for this target\n", popt->name);
3473 exit(1);
3475 xen_mode = XEN_CREATE;
3476 break;
3477 case QEMU_OPTION_xen_attach:
3478 if (!(xen_available())) {
3479 printf("Option %s not supported for this target\n", popt->name);
3480 exit(1);
3482 xen_mode = XEN_ATTACH;
3483 break;
3484 case QEMU_OPTION_readconfig:
3486 int ret = qemu_read_config_file(optarg);
3487 if (ret < 0) {
3488 fprintf(stderr, "read config %s: %s\n", optarg,
3489 strerror(-ret));
3490 exit(1);
3492 break;
3494 case QEMU_OPTION_writeconfig:
3496 FILE *fp;
3497 if (strcmp(optarg, "-") == 0) {
3498 fp = stdout;
3499 } else {
3500 fp = fopen(optarg, "w");
3501 if (fp == NULL) {
3502 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3503 exit(1);
3506 qemu_config_write(fp);
3507 fclose(fp);
3508 break;
3513 loc_set_none();
3515 /* If no data_dir is specified then try to find it relative to the
3516 executable path. */
3517 if (!data_dir) {
3518 data_dir = find_datadir(argv[0]);
3520 /* If all else fails use the install patch specified when building. */
3521 if (!data_dir) {
3522 data_dir = CONFIG_QEMU_SHAREDIR;
3526 * Default to max_cpus = smp_cpus, in case the user doesn't
3527 * specify a max_cpus value.
3529 if (!max_cpus)
3530 max_cpus = smp_cpus;
3532 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3533 if (smp_cpus > machine->max_cpus) {
3534 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3535 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
3536 machine->max_cpus);
3537 exit(1);
3540 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
3541 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
3543 if (machine->no_serial) {
3544 default_serial = 0;
3546 if (machine->no_parallel) {
3547 default_parallel = 0;
3549 if (!machine->use_virtcon) {
3550 default_virtcon = 0;
3552 if (machine->no_vga) {
3553 default_vga = 0;
3555 if (machine->no_floppy) {
3556 default_floppy = 0;
3558 if (machine->no_cdrom) {
3559 default_cdrom = 0;
3561 if (machine->no_sdcard) {
3562 default_sdcard = 0;
3565 if (display_type == DT_NOGRAPHIC) {
3566 if (default_parallel)
3567 add_device_config(DEV_PARALLEL, "null");
3568 if (default_serial && default_monitor) {
3569 add_device_config(DEV_SERIAL, "mon:stdio");
3570 } else if (default_virtcon && default_monitor) {
3571 add_device_config(DEV_VIRTCON, "mon:stdio");
3572 } else {
3573 if (default_serial)
3574 add_device_config(DEV_SERIAL, "stdio");
3575 if (default_virtcon)
3576 add_device_config(DEV_VIRTCON, "stdio");
3577 if (default_monitor)
3578 monitor_parse("stdio", "readline");
3580 } else {
3581 if (default_serial)
3582 add_device_config(DEV_SERIAL, "vc:80Cx24C");
3583 if (default_parallel)
3584 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3585 if (default_monitor)
3586 monitor_parse("vc:80Cx24C", "readline");
3587 if (default_virtcon)
3588 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3590 if (default_vga)
3591 vga_interface_type = VGA_CIRRUS;
3593 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
3594 exit(1);
3595 #ifdef CONFIG_LINUX
3596 if (qemu_opts_foreach(&qemu_fsdev_opts, fsdev_init_func, NULL, 1) != 0) {
3597 exit(1);
3599 #endif
3601 #ifndef _WIN32
3602 if (daemonize) {
3603 pid_t pid;
3605 if (pipe(fds) == -1)
3606 exit(1);
3608 pid = fork();
3609 if (pid > 0) {
3610 uint8_t status;
3611 ssize_t len;
3613 close(fds[1]);
3615 again:
3616 len = read(fds[0], &status, 1);
3617 if (len == -1 && (errno == EINTR))
3618 goto again;
3620 if (len != 1)
3621 exit(1);
3622 else if (status == 1) {
3623 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
3624 exit(1);
3625 } else
3626 exit(0);
3627 } else if (pid < 0)
3628 exit(1);
3630 close(fds[0]);
3631 qemu_set_cloexec(fds[1]);
3633 setsid();
3635 pid = fork();
3636 if (pid > 0)
3637 exit(0);
3638 else if (pid < 0)
3639 exit(1);
3641 umask(027);
3643 signal(SIGTSTP, SIG_IGN);
3644 signal(SIGTTOU, SIG_IGN);
3645 signal(SIGTTIN, SIG_IGN);
3647 #endif
3649 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3650 #ifndef _WIN32
3651 if (daemonize) {
3652 uint8_t status = 1;
3653 if (write(fds[1], &status, 1) != 1) {
3654 perror("daemonize. Writing to pipe\n");
3656 } else
3657 #endif
3658 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
3659 exit(1);
3662 if (kvm_allowed) {
3663 int ret = kvm_init(smp_cpus);
3664 if (ret < 0) {
3665 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
3666 if (!kvm_available()) {
3667 printf("KVM not supported for this target\n");
3668 } else {
3669 fprintf(stderr, "failed to initialize KVM: %s\n", strerror(-ret));
3671 exit(1);
3672 #endif
3673 #ifdef CONFIG_KVM
3674 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
3675 kvm_allowed = 0;
3676 #endif
3680 if (qemu_init_main_loop()) {
3681 fprintf(stderr, "qemu_init_main_loop failed\n");
3682 exit(1);
3684 linux_boot = (kernel_filename != NULL);
3686 if (!linux_boot && *kernel_cmdline != '\0') {
3687 fprintf(stderr, "-append only allowed with -kernel option\n");
3688 exit(1);
3691 if (!linux_boot && initrd_filename != NULL) {
3692 fprintf(stderr, "-initrd only allowed with -kernel option\n");
3693 exit(1);
3696 #ifndef _WIN32
3697 /* Win32 doesn't support line-buffering and requires size >= 2 */
3698 setvbuf(stdout, NULL, _IOLBF, 0);
3699 #endif
3701 if (init_timer_alarm() < 0) {
3702 fprintf(stderr, "could not initialize alarm timer\n");
3703 exit(1);
3705 configure_icount(icount_option);
3707 socket_init();
3709 if (net_init_clients() < 0) {
3710 exit(1);
3713 /* init the bluetooth world */
3714 if (foreach_device_config(DEV_BT, bt_parse))
3715 exit(1);
3717 /* init the memory */
3718 if (ram_size == 0)
3719 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3721 /* init the dynamic translator */
3722 cpu_exec_init_all(tb_size * 1024 * 1024);
3724 bdrv_init_with_whitelist();
3726 blk_mig_init();
3728 if (default_cdrom) {
3729 /* we always create the cdrom drive, even if no disk is there */
3730 drive_add(NULL, CDROM_ALIAS);
3733 if (default_floppy) {
3734 /* we always create at least one floppy */
3735 drive_add(NULL, FD_ALIAS, 0);
3738 if (default_sdcard) {
3739 /* we always create one sd slot, even if no card is in it */
3740 drive_add(NULL, SD_ALIAS);
3743 /* open the virtual block devices */
3744 if (snapshot)
3745 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
3746 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
3747 exit(1);
3749 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
3750 ram_load, NULL);
3752 if (nb_numa_nodes > 0) {
3753 int i;
3755 if (nb_numa_nodes > smp_cpus) {
3756 nb_numa_nodes = smp_cpus;
3759 /* If no memory size if given for any node, assume the default case
3760 * and distribute the available memory equally across all nodes
3762 for (i = 0; i < nb_numa_nodes; i++) {
3763 if (node_mem[i] != 0)
3764 break;
3766 if (i == nb_numa_nodes) {
3767 uint64_t usedmem = 0;
3769 /* On Linux, the each node's border has to be 8MB aligned,
3770 * the final node gets the rest.
3772 for (i = 0; i < nb_numa_nodes - 1; i++) {
3773 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3774 usedmem += node_mem[i];
3776 node_mem[i] = ram_size - usedmem;
3779 for (i = 0; i < nb_numa_nodes; i++) {
3780 if (node_cpumask[i] != 0)
3781 break;
3783 /* assigning the VCPUs round-robin is easier to implement, guest OSes
3784 * must cope with this anyway, because there are BIOSes out there in
3785 * real machines which also use this scheme.
3787 if (i == nb_numa_nodes) {
3788 for (i = 0; i < smp_cpus; i++) {
3789 node_cpumask[i % nb_numa_nodes] |= 1 << i;
3794 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0) {
3795 exit(1);
3798 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3799 exit(1);
3800 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3801 exit(1);
3802 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3803 exit(1);
3804 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3805 exit(1);
3807 module_call_init(MODULE_INIT_DEVICE);
3809 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
3810 exit(0);
3812 if (watchdog) {
3813 i = select_watchdog(watchdog);
3814 if (i > 0)
3815 exit (i == 1 ? 1 : 0);
3818 if (machine->compat_props) {
3819 qdev_prop_register_global_list(machine->compat_props);
3821 qemu_add_globals();
3823 machine->init(ram_size, boot_devices,
3824 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3826 cpu_synchronize_all_post_init();
3828 #ifndef _WIN32
3829 /* must be after terminal init, SDL library changes signal handlers */
3830 sighandler_setup();
3831 #endif
3833 set_numa_modes();
3835 current_machine = machine;
3837 /* init USB devices */
3838 if (usb_enabled) {
3839 if (foreach_device_config(DEV_USB, usb_parse) < 0)
3840 exit(1);
3843 /* init generic devices */
3844 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
3845 exit(1);
3847 net_check_clients();
3849 /* just use the first displaystate for the moment */
3850 ds = get_displaystate();
3852 if (display_type == DT_DEFAULT) {
3853 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3854 display_type = DT_SDL;
3855 #else
3856 display_type = DT_VNC;
3857 vnc_display = "localhost:0,to=99";
3858 show_vnc_port = 1;
3859 #endif
3863 switch (display_type) {
3864 case DT_NOGRAPHIC:
3865 break;
3866 #if defined(CONFIG_CURSES)
3867 case DT_CURSES:
3868 curses_display_init(ds, full_screen);
3869 break;
3870 #endif
3871 #if defined(CONFIG_SDL)
3872 case DT_SDL:
3873 sdl_display_init(ds, full_screen, no_frame);
3874 break;
3875 #elif defined(CONFIG_COCOA)
3876 case DT_SDL:
3877 cocoa_display_init(ds, full_screen);
3878 break;
3879 #endif
3880 case DT_VNC:
3881 vnc_display_init(ds);
3882 if (vnc_display_open(ds, vnc_display) < 0)
3883 exit(1);
3885 if (show_vnc_port) {
3886 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3888 break;
3889 default:
3890 break;
3892 dpy_resize(ds);
3894 dcl = ds->listeners;
3895 while (dcl != NULL) {
3896 if (dcl->dpy_refresh != NULL) {
3897 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
3898 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
3900 dcl = dcl->next;
3903 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
3904 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
3905 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
3908 text_consoles_set_display(ds);
3910 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3911 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3912 gdbstub_dev);
3913 exit(1);
3916 qdev_machine_creation_done();
3918 if (rom_load_all() != 0) {
3919 fprintf(stderr, "rom loading failed\n");
3920 exit(1);
3923 qemu_system_reset();
3924 if (loadvm) {
3925 if (load_vmstate(loadvm) < 0) {
3926 autostart = 0;
3930 if (incoming) {
3931 qemu_start_incoming_migration(incoming);
3932 } else if (autostart) {
3933 vm_start();
3936 #ifndef _WIN32
3937 if (daemonize) {
3938 uint8_t status = 0;
3939 ssize_t len;
3941 again1:
3942 len = write(fds[1], &status, 1);
3943 if (len == -1 && (errno == EINTR))
3944 goto again1;
3946 if (len != 1)
3947 exit(1);
3949 if (chdir("/")) {
3950 perror("not able to chdir to /");
3951 exit(1);
3953 TFR(fd = qemu_open("/dev/null", O_RDWR));
3954 if (fd == -1)
3955 exit(1);
3958 if (run_as) {
3959 pwd = getpwnam(run_as);
3960 if (!pwd) {
3961 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
3962 exit(1);
3966 if (chroot_dir) {
3967 if (chroot(chroot_dir) < 0) {
3968 fprintf(stderr, "chroot failed\n");
3969 exit(1);
3971 if (chdir("/")) {
3972 perror("not able to chdir to /");
3973 exit(1);
3977 if (run_as) {
3978 if (setgid(pwd->pw_gid) < 0) {
3979 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
3980 exit(1);
3982 if (setuid(pwd->pw_uid) < 0) {
3983 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
3984 exit(1);
3986 if (setuid(0) != -1) {
3987 fprintf(stderr, "Dropping privileges failed\n");
3988 exit(1);
3992 if (daemonize) {
3993 dup2(fd, 0);
3994 dup2(fd, 1);
3995 dup2(fd, 2);
3997 close(fd);
3999 #endif
4001 main_loop();
4002 quit_timers();
4003 net_cleanup();
4005 return 0;