Merge commit 'ca35f780ac4654bfa086613c72b011448afff327' into upstream-merge
[qemu/qemu-dev-zwu.git] / vl.c
blob357c471117ee1d73438945de892029f66c301130
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, "unsafe")) {
927 bdrv_flags |= BDRV_O_CACHE_WB;
928 bdrv_flags |= BDRV_O_NO_FLUSH;
929 } else if (!strcmp(buf, "writethrough")) {
930 /* this is the default */
931 } else {
932 fprintf(stderr, "qemu: invalid cache option\n");
933 return NULL;
937 #ifdef CONFIG_LINUX_AIO
938 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
939 if (!strcmp(buf, "native")) {
940 bdrv_flags |= BDRV_O_NATIVE_AIO;
941 } else if (!strcmp(buf, "threads")) {
942 /* this is the default */
943 } else {
944 fprintf(stderr, "qemu: invalid aio option\n");
945 return NULL;
948 #endif
950 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
951 if (strcmp(buf, "?") == 0) {
952 fprintf(stderr, "qemu: Supported formats:");
953 bdrv_iterate_format(bdrv_format_print, NULL);
954 fprintf(stderr, "\n");
955 return NULL;
957 drv = bdrv_find_whitelisted_format(buf);
958 if (!drv) {
959 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
960 return NULL;
964 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
965 if (is_extboot && extboot_drive) {
966 fprintf(stderr, "qemu: two bootable drives specified\n");
967 return NULL;
970 on_write_error = BLOCK_ERR_STOP_ENOSPC;
971 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
972 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {
973 fprintf(stderr, "werror is no supported by this format\n");
974 return NULL;
977 on_write_error = parse_block_error_action(buf, 0);
978 if (on_write_error < 0) {
979 return NULL;
983 on_read_error = BLOCK_ERR_REPORT;
984 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
985 if (type != IF_IDE && type != IF_VIRTIO && type != IF_NONE) {
986 fprintf(stderr, "rerror is no supported by this format\n");
987 return NULL;
990 on_read_error = parse_block_error_action(buf, 1);
991 if (on_read_error < 0) {
992 return NULL;
996 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
997 if (type != IF_VIRTIO) {
998 fprintf(stderr, "addr is not supported\n");
999 return NULL;
1003 /* compute bus and unit according index */
1005 if (index != -1) {
1006 if (bus_id != 0 || unit_id != -1) {
1007 fprintf(stderr,
1008 "qemu: index cannot be used with bus and unit\n");
1009 return NULL;
1011 if (max_devs == 0)
1013 unit_id = index;
1014 bus_id = 0;
1015 } else {
1016 unit_id = index % max_devs;
1017 bus_id = index / max_devs;
1021 /* if user doesn't specify a unit_id,
1022 * try to find the first free
1025 if (unit_id == -1) {
1026 unit_id = 0;
1027 while (drive_get(type, bus_id, unit_id) != NULL) {
1028 unit_id++;
1029 if (max_devs && unit_id >= max_devs) {
1030 unit_id -= max_devs;
1031 bus_id++;
1036 /* check unit id */
1038 if (max_devs && unit_id >= max_devs) {
1039 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1040 unit_id, max_devs - 1);
1041 return NULL;
1045 * ignore multiple definitions
1048 if (drive_get(type, bus_id, unit_id) != NULL) {
1049 *fatal_error = 0;
1050 return NULL;
1053 /* init */
1055 dinfo = qemu_mallocz(sizeof(*dinfo));
1056 if ((buf = qemu_opts_id(opts)) != NULL) {
1057 dinfo->id = qemu_strdup(buf);
1058 } else {
1059 /* no id supplied -> create one */
1060 dinfo->id = qemu_mallocz(32);
1061 if (type == IF_IDE || type == IF_SCSI)
1062 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1063 if (max_devs)
1064 snprintf(dinfo->id, 32, "%s%i%s%i",
1065 devname, bus_id, mediastr, unit_id);
1066 else
1067 snprintf(dinfo->id, 32, "%s%s%i",
1068 devname, mediastr, unit_id);
1070 dinfo->bdrv = bdrv_new(dinfo->id);
1071 dinfo->devaddr = devaddr;
1072 dinfo->type = type;
1073 dinfo->bus = bus_id;
1074 dinfo->unit = unit_id;
1075 dinfo->on_read_error = on_read_error;
1076 dinfo->on_write_error = on_write_error;
1077 dinfo->opts = opts;
1078 if (serial)
1079 strncpy(dinfo->serial, serial, sizeof(serial));
1080 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1081 if (is_extboot) {
1082 extboot_drive = dinfo;
1085 switch(type) {
1086 case IF_IDE:
1087 case IF_SCSI:
1088 case IF_XEN:
1089 case IF_NONE:
1090 switch(media) {
1091 case MEDIA_DISK:
1092 if (cyls != 0) {
1093 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1094 bdrv_set_translation_hint(dinfo->bdrv, translation);
1096 break;
1097 case MEDIA_CDROM:
1098 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1099 break;
1101 break;
1102 case IF_SD:
1103 /* FIXME: This isn't really a floppy, but it's a reasonable
1104 approximation. */
1105 case IF_FLOPPY:
1106 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1107 break;
1108 case IF_PFLASH:
1109 case IF_MTD:
1110 break;
1111 case IF_VIRTIO:
1112 /* add virtio block device */
1113 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1114 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1115 qemu_opt_set(opts, "drive", dinfo->id);
1116 if (devaddr)
1117 qemu_opt_set(opts, "addr", devaddr);
1118 break;
1119 case IF_COUNT:
1120 abort();
1122 if (!file) {
1123 *fatal_error = 0;
1124 return NULL;
1126 if (snapshot) {
1127 /* always use cache=unsafe with snapshot */
1128 bdrv_flags &= ~BDRV_O_CACHE_MASK;
1129 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
1132 if (media == MEDIA_CDROM) {
1133 /* CDROM is fine for any interface, don't check. */
1134 ro = 1;
1135 } else if (ro == 1) {
1136 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY && type != IF_NONE) {
1137 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1138 return NULL;
1142 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1144 if (bdrv_open(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1145 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1146 file, strerror(errno));
1147 return NULL;
1150 if (bdrv_key_required(dinfo->bdrv))
1151 autostart = 0;
1152 *fatal_error = 0;
1153 return dinfo;
1156 static int drive_init_func(QemuOpts *opts, void *opaque)
1158 QEMUMachine *machine = opaque;
1159 int fatal_error = 0;
1161 if (drive_init(opts, machine, &fatal_error) == NULL) {
1162 if (fatal_error)
1163 return 1;
1165 return 0;
1168 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1170 if (NULL == qemu_opt_get(opts, "snapshot")) {
1171 qemu_opt_set(opts, "snapshot", "on");
1173 return 0;
1176 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1178 boot_set_handler = func;
1179 boot_set_opaque = opaque;
1182 int qemu_boot_set(const char *boot_devices)
1184 if (!boot_set_handler) {
1185 return -EINVAL;
1187 return boot_set_handler(boot_set_opaque, boot_devices);
1190 static void validate_bootdevices(char *devices)
1192 /* We just do some generic consistency checks */
1193 const char *p;
1194 int bitmap = 0;
1196 for (p = devices; *p != '\0'; p++) {
1197 /* Allowed boot devices are:
1198 * a-b: floppy disk drives
1199 * c-f: IDE disk drives
1200 * g-m: machine implementation dependant drives
1201 * n-p: network devices
1202 * It's up to each machine implementation to check if the given boot
1203 * devices match the actual hardware implementation and firmware
1204 * features.
1206 if (*p < 'a' || *p > 'p') {
1207 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1208 exit(1);
1210 if (bitmap & (1 << (*p - 'a'))) {
1211 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1212 exit(1);
1214 bitmap |= 1 << (*p - 'a');
1218 static void restore_boot_devices(void *opaque)
1220 char *standard_boot_devices = opaque;
1221 static int first = 1;
1223 /* Restore boot order and remove ourselves after the first boot */
1224 if (first) {
1225 first = 0;
1226 return;
1229 qemu_boot_set(standard_boot_devices);
1231 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1232 qemu_free(standard_boot_devices);
1235 static void numa_add(const char *optarg)
1237 char option[128];
1238 char *endptr;
1239 unsigned long long value, endvalue;
1240 int nodenr;
1242 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1243 if (!strcmp(option, "node")) {
1244 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1245 nodenr = nb_numa_nodes;
1246 } else {
1247 nodenr = strtoull(option, NULL, 10);
1250 if (get_param_value(option, 128, "mem", optarg) == 0) {
1251 node_mem[nodenr] = 0;
1252 } else {
1253 value = strtoull(option, &endptr, 0);
1254 switch (*endptr) {
1255 case 0: case 'M': case 'm':
1256 value <<= 20;
1257 break;
1258 case 'G': case 'g':
1259 value <<= 30;
1260 break;
1262 node_mem[nodenr] = value;
1264 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1265 node_cpumask[nodenr] = 0;
1266 } else {
1267 value = strtoull(option, &endptr, 10);
1268 if (value >= 64) {
1269 value = 63;
1270 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1271 } else {
1272 if (*endptr == '-') {
1273 endvalue = strtoull(endptr+1, &endptr, 10);
1274 if (endvalue >= 63) {
1275 endvalue = 62;
1276 fprintf(stderr,
1277 "only 63 CPUs in NUMA mode supported.\n");
1279 value = (2ULL << endvalue) - (1ULL << value);
1280 } else {
1281 value = 1ULL << value;
1284 node_cpumask[nodenr] = value;
1286 nb_numa_nodes++;
1288 return;
1291 static void smp_parse(const char *optarg)
1293 int smp, sockets = 0, threads = 0, cores = 0;
1294 char *endptr;
1295 char option[128];
1297 smp = strtoul(optarg, &endptr, 10);
1298 if (endptr != optarg) {
1299 if (*endptr == ',') {
1300 endptr++;
1303 if (get_param_value(option, 128, "sockets", endptr) != 0)
1304 sockets = strtoull(option, NULL, 10);
1305 if (get_param_value(option, 128, "cores", endptr) != 0)
1306 cores = strtoull(option, NULL, 10);
1307 if (get_param_value(option, 128, "threads", endptr) != 0)
1308 threads = strtoull(option, NULL, 10);
1309 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1310 max_cpus = strtoull(option, NULL, 10);
1312 /* compute missing values, prefer sockets over cores over threads */
1313 if (smp == 0 || sockets == 0) {
1314 sockets = sockets > 0 ? sockets : 1;
1315 cores = cores > 0 ? cores : 1;
1316 threads = threads > 0 ? threads : 1;
1317 if (smp == 0) {
1318 smp = cores * threads * sockets;
1320 } else {
1321 if (cores == 0) {
1322 threads = threads > 0 ? threads : 1;
1323 cores = smp / (sockets * threads);
1324 } else {
1325 if (sockets) {
1326 threads = smp / (cores * sockets);
1330 smp_cpus = smp;
1331 smp_cores = cores > 0 ? cores : 1;
1332 smp_threads = threads > 0 ? threads : 1;
1333 if (max_cpus == 0)
1334 max_cpus = smp_cpus;
1337 /***********************************************************/
1338 /* USB devices */
1340 static int usb_device_add(const char *devname, int is_hotplug)
1342 const char *p;
1343 USBDevice *dev = NULL;
1345 if (!usb_enabled)
1346 return -1;
1348 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1349 dev = usbdevice_create(devname);
1350 if (dev)
1351 goto done;
1353 /* the other ones */
1354 if (strstart(devname, "host:", &p)) {
1355 dev = usb_host_device_open(p);
1356 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1357 dev = usb_bt_init(devname[2] ? hci_init(p) :
1358 bt_new_hci(qemu_find_bt_vlan(0)));
1359 } else {
1360 return -1;
1362 if (!dev)
1363 return -1;
1365 done:
1366 return 0;
1369 static int usb_device_del(const char *devname)
1371 int bus_num, addr;
1372 const char *p;
1374 if (strstart(devname, "host:", &p))
1375 return usb_host_device_close(p);
1377 if (!usb_enabled)
1378 return -1;
1380 p = strchr(devname, '.');
1381 if (!p)
1382 return -1;
1383 bus_num = strtoul(devname, NULL, 0);
1384 addr = strtoul(p + 1, NULL, 0);
1386 return usb_device_delete_addr(bus_num, addr);
1389 static int usb_parse(const char *cmdline)
1391 int r;
1392 r = usb_device_add(cmdline, 0);
1393 if (r < 0) {
1394 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1396 return r;
1399 void do_usb_add(Monitor *mon, const QDict *qdict)
1401 const char *devname = qdict_get_str(qdict, "devname");
1402 if (usb_device_add(devname, 1) < 0) {
1403 error_report("could not add USB device '%s'", devname);
1407 void do_usb_del(Monitor *mon, const QDict *qdict)
1409 const char *devname = qdict_get_str(qdict, "devname");
1410 if (usb_device_del(devname) < 0) {
1411 error_report("could not delete USB device '%s'", devname);
1415 /***********************************************************/
1416 /* PCMCIA/Cardbus */
1418 static struct pcmcia_socket_entry_s {
1419 PCMCIASocket *socket;
1420 struct pcmcia_socket_entry_s *next;
1421 } *pcmcia_sockets = 0;
1423 void pcmcia_socket_register(PCMCIASocket *socket)
1425 struct pcmcia_socket_entry_s *entry;
1427 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1428 entry->socket = socket;
1429 entry->next = pcmcia_sockets;
1430 pcmcia_sockets = entry;
1433 void pcmcia_socket_unregister(PCMCIASocket *socket)
1435 struct pcmcia_socket_entry_s *entry, **ptr;
1437 ptr = &pcmcia_sockets;
1438 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1439 if (entry->socket == socket) {
1440 *ptr = entry->next;
1441 qemu_free(entry);
1445 void pcmcia_info(Monitor *mon)
1447 struct pcmcia_socket_entry_s *iter;
1449 if (!pcmcia_sockets)
1450 monitor_printf(mon, "No PCMCIA sockets\n");
1452 for (iter = pcmcia_sockets; iter; iter = iter->next)
1453 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1454 iter->socket->attached ? iter->socket->card_string :
1455 "Empty");
1458 /***********************************************************/
1459 /* I/O handling */
1461 typedef struct IOHandlerRecord {
1462 int fd;
1463 IOCanReadHandler *fd_read_poll;
1464 IOHandler *fd_read;
1465 IOHandler *fd_write;
1466 int deleted;
1467 void *opaque;
1468 /* temporary data */
1469 struct pollfd *ufd;
1470 QLIST_ENTRY(IOHandlerRecord) next;
1471 } IOHandlerRecord;
1473 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1474 QLIST_HEAD_INITIALIZER(io_handlers);
1477 /* XXX: fd_read_poll should be suppressed, but an API change is
1478 necessary in the character devices to suppress fd_can_read(). */
1479 int qemu_set_fd_handler2(int fd,
1480 IOCanReadHandler *fd_read_poll,
1481 IOHandler *fd_read,
1482 IOHandler *fd_write,
1483 void *opaque)
1485 IOHandlerRecord *ioh;
1487 if (!fd_read && !fd_write) {
1488 QLIST_FOREACH(ioh, &io_handlers, next) {
1489 if (ioh->fd == fd) {
1490 ioh->deleted = 1;
1491 break;
1494 } else {
1495 QLIST_FOREACH(ioh, &io_handlers, next) {
1496 if (ioh->fd == fd)
1497 goto found;
1499 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1500 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1501 found:
1502 ioh->fd = fd;
1503 ioh->fd_read_poll = fd_read_poll;
1504 ioh->fd_read = fd_read;
1505 ioh->fd_write = fd_write;
1506 ioh->opaque = opaque;
1507 ioh->deleted = 0;
1509 qemu_notify_event();
1510 return 0;
1513 int qemu_set_fd_handler(int fd,
1514 IOHandler *fd_read,
1515 IOHandler *fd_write,
1516 void *opaque)
1518 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1521 #ifdef _WIN32
1522 /***********************************************************/
1523 /* Polling handling */
1525 typedef struct PollingEntry {
1526 PollingFunc *func;
1527 void *opaque;
1528 struct PollingEntry *next;
1529 } PollingEntry;
1531 static PollingEntry *first_polling_entry;
1533 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1535 PollingEntry **ppe, *pe;
1536 pe = qemu_mallocz(sizeof(PollingEntry));
1537 pe->func = func;
1538 pe->opaque = opaque;
1539 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1540 *ppe = pe;
1541 return 0;
1544 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1546 PollingEntry **ppe, *pe;
1547 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1548 pe = *ppe;
1549 if (pe->func == func && pe->opaque == opaque) {
1550 *ppe = pe->next;
1551 qemu_free(pe);
1552 break;
1557 /***********************************************************/
1558 /* Wait objects support */
1559 typedef struct WaitObjects {
1560 int num;
1561 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1562 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1563 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1564 } WaitObjects;
1566 static WaitObjects wait_objects = {0};
1568 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1570 WaitObjects *w = &wait_objects;
1572 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1573 return -1;
1574 w->events[w->num] = handle;
1575 w->func[w->num] = func;
1576 w->opaque[w->num] = opaque;
1577 w->num++;
1578 return 0;
1581 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1583 int i, found;
1584 WaitObjects *w = &wait_objects;
1586 found = 0;
1587 for (i = 0; i < w->num; i++) {
1588 if (w->events[i] == handle)
1589 found = 1;
1590 if (found) {
1591 w->events[i] = w->events[i + 1];
1592 w->func[i] = w->func[i + 1];
1593 w->opaque[i] = w->opaque[i + 1];
1596 if (found)
1597 w->num--;
1599 #endif
1601 /***********************************************************/
1602 /* machine registration */
1604 static QEMUMachine *first_machine = NULL;
1605 QEMUMachine *current_machine = NULL;
1607 int qemu_register_machine(QEMUMachine *m)
1609 QEMUMachine **pm;
1610 pm = &first_machine;
1611 while (*pm != NULL)
1612 pm = &(*pm)->next;
1613 m->next = NULL;
1614 *pm = m;
1615 return 0;
1618 static QEMUMachine *find_machine(const char *name)
1620 QEMUMachine *m;
1622 for(m = first_machine; m != NULL; m = m->next) {
1623 if (!strcmp(m->name, name))
1624 return m;
1625 if (m->alias && !strcmp(m->alias, name))
1626 return m;
1628 return NULL;
1631 static QEMUMachine *find_default_machine(void)
1633 QEMUMachine *m;
1635 for(m = first_machine; m != NULL; m = m->next) {
1636 if (m->is_default) {
1637 return m;
1640 return NULL;
1643 /***********************************************************/
1644 /* main execution loop */
1646 static void gui_update(void *opaque)
1648 uint64_t interval = GUI_REFRESH_INTERVAL;
1649 DisplayState *ds = opaque;
1650 DisplayChangeListener *dcl = ds->listeners;
1652 qemu_flush_coalesced_mmio_buffer();
1653 dpy_refresh(ds);
1655 while (dcl != NULL) {
1656 if (dcl->gui_timer_interval &&
1657 dcl->gui_timer_interval < interval)
1658 interval = dcl->gui_timer_interval;
1659 dcl = dcl->next;
1661 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1664 static void nographic_update(void *opaque)
1666 uint64_t interval = GUI_REFRESH_INTERVAL;
1668 qemu_flush_coalesced_mmio_buffer();
1669 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1672 struct vm_change_state_entry {
1673 VMChangeStateHandler *cb;
1674 void *opaque;
1675 QLIST_ENTRY (vm_change_state_entry) entries;
1678 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1680 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1681 void *opaque)
1683 VMChangeStateEntry *e;
1685 e = qemu_mallocz(sizeof (*e));
1687 e->cb = cb;
1688 e->opaque = opaque;
1689 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1690 return e;
1693 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1695 QLIST_REMOVE (e, entries);
1696 qemu_free (e);
1699 void vm_state_notify(int running, int reason)
1701 VMChangeStateEntry *e;
1703 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1704 e->cb(e->opaque, running, reason);
1708 void vm_start(void)
1710 if (!vm_running) {
1711 cpu_enable_ticks();
1712 vm_running = 1;
1713 vm_state_notify(1, 0);
1714 resume_all_vcpus();
1715 monitor_protocol_event(QEVENT_RESUME, NULL);
1719 /* reset/shutdown handler */
1721 typedef struct QEMUResetEntry {
1722 QTAILQ_ENTRY(QEMUResetEntry) entry;
1723 QEMUResetHandler *func;
1724 void *opaque;
1725 } QEMUResetEntry;
1727 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1728 QTAILQ_HEAD_INITIALIZER(reset_handlers);
1729 static int reset_requested;
1730 static int shutdown_requested;
1731 static int powerdown_requested;
1732 int debug_requested;
1733 int vmstop_requested;
1735 int qemu_no_shutdown(void)
1737 int r = no_shutdown;
1738 no_shutdown = 0;
1739 return r;
1742 int qemu_shutdown_requested(void)
1744 int r = shutdown_requested;
1745 shutdown_requested = 0;
1746 return r;
1749 int qemu_reset_requested(void)
1751 int r = reset_requested;
1752 reset_requested = 0;
1753 return r;
1756 int qemu_powerdown_requested(void)
1758 int r = powerdown_requested;
1759 powerdown_requested = 0;
1760 return r;
1763 static int qemu_debug_requested(void)
1765 int r = debug_requested;
1766 debug_requested = 0;
1767 return r;
1770 static int qemu_vmstop_requested(void)
1772 int r = vmstop_requested;
1773 vmstop_requested = 0;
1774 return r;
1777 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1779 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
1781 re->func = func;
1782 re->opaque = opaque;
1783 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1786 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1788 QEMUResetEntry *re;
1790 QTAILQ_FOREACH(re, &reset_handlers, entry) {
1791 if (re->func == func && re->opaque == opaque) {
1792 QTAILQ_REMOVE(&reset_handlers, re, entry);
1793 qemu_free(re);
1794 return;
1799 void qemu_system_reset(void)
1801 QEMUResetEntry *re, *nre;
1803 /* reset all devices */
1804 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1805 re->func(re->opaque);
1807 monitor_protocol_event(QEVENT_RESET, NULL);
1808 cpu_synchronize_all_post_reset();
1811 void qemu_system_reset_request(void)
1813 if (no_reboot) {
1814 shutdown_requested = 1;
1815 } else {
1816 reset_requested = 1;
1818 if (cpu_single_env) {
1819 cpu_single_env->stopped = 1;
1821 qemu_notify_event();
1824 void qemu_system_shutdown_request(void)
1826 shutdown_requested = 1;
1827 qemu_notify_event();
1830 void qemu_system_powerdown_request(void)
1832 powerdown_requested = 1;
1833 qemu_notify_event();
1836 #ifdef _WIN32
1837 static void host_main_loop_wait(int *timeout)
1839 int ret, ret2, i;
1840 PollingEntry *pe;
1843 /* XXX: need to suppress polling by better using win32 events */
1844 ret = 0;
1845 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
1846 ret |= pe->func(pe->opaque);
1848 if (ret == 0) {
1849 int err;
1850 WaitObjects *w = &wait_objects;
1852 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
1853 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
1854 if (w->func[ret - WAIT_OBJECT_0])
1855 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
1857 /* Check for additional signaled events */
1858 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
1860 /* Check if event is signaled */
1861 ret2 = WaitForSingleObject(w->events[i], 0);
1862 if(ret2 == WAIT_OBJECT_0) {
1863 if (w->func[i])
1864 w->func[i](w->opaque[i]);
1865 } else if (ret2 == WAIT_TIMEOUT) {
1866 } else {
1867 err = GetLastError();
1868 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
1871 } else if (ret == WAIT_TIMEOUT) {
1872 } else {
1873 err = GetLastError();
1874 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
1878 *timeout = 0;
1880 #else
1881 static void host_main_loop_wait(int *timeout)
1884 #endif
1886 void main_loop_wait(int nonblocking)
1888 IOHandlerRecord *ioh;
1889 fd_set rfds, wfds, xfds;
1890 int ret, nfds;
1891 struct timeval tv;
1892 int timeout;
1894 if (nonblocking)
1895 timeout = 0;
1896 else {
1897 timeout = qemu_calculate_timeout();
1898 qemu_bh_update_timeout(&timeout);
1901 host_main_loop_wait(&timeout);
1903 /* poll any events */
1904 /* XXX: separate device handlers from system ones */
1905 nfds = -1;
1906 FD_ZERO(&rfds);
1907 FD_ZERO(&wfds);
1908 FD_ZERO(&xfds);
1909 QLIST_FOREACH(ioh, &io_handlers, next) {
1910 if (ioh->deleted)
1911 continue;
1912 if (ioh->fd_read &&
1913 (!ioh->fd_read_poll ||
1914 ioh->fd_read_poll(ioh->opaque) != 0)) {
1915 FD_SET(ioh->fd, &rfds);
1916 if (ioh->fd > nfds)
1917 nfds = ioh->fd;
1919 if (ioh->fd_write) {
1920 FD_SET(ioh->fd, &wfds);
1921 if (ioh->fd > nfds)
1922 nfds = ioh->fd;
1926 tv.tv_sec = timeout / 1000;
1927 tv.tv_usec = (timeout % 1000) * 1000;
1929 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1931 qemu_mutex_unlock_iothread();
1932 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1933 qemu_mutex_lock_iothread();
1934 if (ret > 0) {
1935 IOHandlerRecord *pioh;
1937 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
1938 if (ioh->deleted) {
1939 QLIST_REMOVE(ioh, next);
1940 qemu_free(ioh);
1941 continue;
1943 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
1944 ioh->fd_read(ioh->opaque);
1945 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
1946 FD_CLR(ioh->fd, &rfds);
1948 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
1949 ioh->fd_write(ioh->opaque);
1954 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1956 qemu_run_all_timers();
1958 /* Check bottom-halves last in case any of the earlier events triggered
1959 them. */
1960 qemu_bh_poll();
1964 static int vm_can_run(void)
1966 if (powerdown_requested)
1967 return 0;
1968 if (reset_requested)
1969 return 0;
1970 if (shutdown_requested)
1971 return 0;
1972 if (debug_requested)
1973 return 0;
1974 return 1;
1977 qemu_irq qemu_system_powerdown;
1979 static void main_loop(void)
1981 int r;
1983 if (kvm_enabled()) {
1984 kvm_main_loop();
1985 cpu_disable_ticks();
1986 return;
1989 qemu_main_loop_start();
1991 for (;;) {
1992 do {
1993 bool nonblocking = false;
1994 #ifdef CONFIG_PROFILER
1995 int64_t ti;
1996 #endif
1997 #ifndef CONFIG_IOTHREAD
1998 nonblocking = tcg_cpu_exec();
1999 #endif
2000 #ifdef CONFIG_PROFILER
2001 ti = profile_getclock();
2002 #endif
2003 main_loop_wait(nonblocking);
2004 #ifdef CONFIG_PROFILER
2005 dev_time += profile_getclock() - ti;
2006 #endif
2007 } while (vm_can_run());
2009 if ((r = qemu_debug_requested())) {
2010 vm_stop(r);
2012 if (qemu_shutdown_requested()) {
2013 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2014 if (no_shutdown) {
2015 vm_stop(0);
2016 no_shutdown = 0;
2017 } else
2018 break;
2020 if (qemu_reset_requested()) {
2021 pause_all_vcpus();
2022 qemu_system_reset();
2023 resume_all_vcpus();
2025 if (qemu_powerdown_requested()) {
2026 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
2027 qemu_irq_raise(qemu_system_powerdown);
2029 if ((r = qemu_vmstop_requested())) {
2030 vm_stop(r);
2033 pause_all_vcpus();
2036 static void version(void)
2038 printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
2041 static void help(int exitcode)
2043 const char *options_help =
2044 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2045 opt_help
2046 #define DEFHEADING(text) stringify(text) "\n"
2047 #include "qemu-options.h"
2048 #undef DEF
2049 #undef DEFHEADING
2050 #undef GEN_DOCS
2052 version();
2053 printf("usage: %s [options] [disk_image]\n"
2054 "\n"
2055 "'disk_image' is a raw hard disk image for IDE hard disk 0\n"
2056 "\n"
2057 "%s\n"
2058 "During emulation, the following keys are useful:\n"
2059 "ctrl-alt-f toggle full screen\n"
2060 "ctrl-alt-n switch to virtual console 'n'\n"
2061 "ctrl-alt toggle mouse and keyboard grab\n"
2062 "\n"
2063 "When using -nographic, press 'ctrl-a h' to get some help.\n",
2064 "qemu",
2065 options_help);
2066 exit(exitcode);
2069 #define HAS_ARG 0x0001
2071 enum {
2072 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2073 opt_enum,
2074 #define DEFHEADING(text)
2075 #include "qemu-options.h"
2076 #undef DEF
2077 #undef DEFHEADING
2078 #undef GEN_DOCS
2081 typedef struct QEMUOption {
2082 const char *name;
2083 int flags;
2084 int index;
2085 uint32_t arch_mask;
2086 } QEMUOption;
2088 static const QEMUOption qemu_options[] = {
2089 { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
2090 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2091 { option, opt_arg, opt_enum, arch_mask },
2092 #define DEFHEADING(text)
2093 #include "qemu-options.h"
2094 #undef DEF
2095 #undef DEFHEADING
2096 #undef GEN_DOCS
2097 { NULL },
2099 static void select_vgahw (const char *p)
2101 const char *opts;
2103 default_vga = 0;
2104 vga_interface_type = VGA_NONE;
2105 if (strstart(p, "std", &opts)) {
2106 vga_interface_type = VGA_STD;
2107 } else if (strstart(p, "cirrus", &opts)) {
2108 vga_interface_type = VGA_CIRRUS;
2109 } else if (strstart(p, "vmware", &opts)) {
2110 vga_interface_type = VGA_VMWARE;
2111 } else if (strstart(p, "xenfb", &opts)) {
2112 vga_interface_type = VGA_XENFB;
2113 } else if (!strstart(p, "none", &opts)) {
2114 invalid_vga:
2115 fprintf(stderr, "Unknown vga type: %s\n", p);
2116 exit(1);
2118 while (*opts) {
2119 const char *nextopt;
2121 if (strstart(opts, ",retrace=", &nextopt)) {
2122 opts = nextopt;
2123 if (strstart(opts, "dumb", &nextopt))
2124 vga_retrace_method = VGA_RETRACE_DUMB;
2125 else if (strstart(opts, "precise", &nextopt))
2126 vga_retrace_method = VGA_RETRACE_PRECISE;
2127 else goto invalid_vga;
2128 } else goto invalid_vga;
2129 opts = nextopt;
2133 static int balloon_parse(const char *arg)
2135 QemuOpts *opts;
2137 if (strcmp(arg, "none") == 0) {
2138 return 0;
2141 if (!strncmp(arg, "virtio", 6)) {
2142 if (arg[6] == ',') {
2143 /* have params -> parse them */
2144 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
2145 if (!opts)
2146 return -1;
2147 } else {
2148 /* create empty opts */
2149 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2151 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
2152 return 0;
2155 return -1;
2158 #ifdef _WIN32
2159 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
2161 exit(STATUS_CONTROL_C_EXIT);
2162 return TRUE;
2164 #endif
2166 #ifndef _WIN32
2168 static void termsig_handler(int signal)
2170 qemu_system_shutdown_request();
2173 static void sigchld_handler(int signal)
2175 waitpid(-1, NULL, WNOHANG);
2178 static void sighandler_setup(void)
2180 struct sigaction act;
2182 memset(&act, 0, sizeof(act));
2183 act.sa_handler = termsig_handler;
2184 sigaction(SIGINT, &act, NULL);
2185 sigaction(SIGHUP, &act, NULL);
2186 sigaction(SIGTERM, &act, NULL);
2188 act.sa_handler = sigchld_handler;
2189 act.sa_flags = SA_NOCLDSTOP;
2190 sigaction(SIGCHLD, &act, NULL);
2193 #endif
2195 #ifdef _WIN32
2196 /* Look for support files in the same directory as the executable. */
2197 static char *find_datadir(const char *argv0)
2199 char *p;
2200 char buf[MAX_PATH];
2201 DWORD len;
2203 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
2204 if (len == 0) {
2205 return NULL;
2208 buf[len] = 0;
2209 p = buf + len - 1;
2210 while (p != buf && *p != '\\')
2211 p--;
2212 *p = 0;
2213 if (access(buf, R_OK) == 0) {
2214 return qemu_strdup(buf);
2216 return NULL;
2218 #else /* !_WIN32 */
2220 /* Find a likely location for support files using the location of the binary.
2221 For installed binaries this will be "$bindir/../share/qemu". When
2222 running from the build tree this will be "$bindir/../pc-bios". */
2223 #define SHARE_SUFFIX "/share/qemu"
2224 #define BUILD_SUFFIX "/pc-bios"
2225 static char *find_datadir(const char *argv0)
2227 char *dir;
2228 char *p = NULL;
2229 char *res;
2230 char buf[PATH_MAX];
2231 size_t max_len;
2233 #if defined(__linux__)
2235 int len;
2236 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
2237 if (len > 0) {
2238 buf[len] = 0;
2239 p = buf;
2242 #elif defined(__FreeBSD__)
2244 static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
2245 size_t len = sizeof(buf) - 1;
2247 *buf = '\0';
2248 if (!sysctl(mib, sizeof(mib)/sizeof(*mib), buf, &len, NULL, 0) &&
2249 *buf) {
2250 buf[sizeof(buf) - 1] = '\0';
2251 p = buf;
2254 #endif
2255 /* If we don't have any way of figuring out the actual executable
2256 location then try argv[0]. */
2257 if (!p) {
2258 p = realpath(argv0, buf);
2259 if (!p) {
2260 return NULL;
2263 dir = dirname(p);
2264 dir = dirname(dir);
2266 max_len = strlen(dir) +
2267 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
2268 res = qemu_mallocz(max_len);
2269 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
2270 if (access(res, R_OK)) {
2271 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
2272 if (access(res, R_OK)) {
2273 qemu_free(res);
2274 res = NULL;
2278 return res;
2280 #undef SHARE_SUFFIX
2281 #undef BUILD_SUFFIX
2282 #endif
2284 char *qemu_find_file(int type, const char *name)
2286 int len;
2287 const char *subdir;
2288 char *buf;
2290 /* If name contains path separators then try it as a straight path. */
2291 if ((strchr(name, '/') || strchr(name, '\\'))
2292 && access(name, R_OK) == 0) {
2293 return qemu_strdup(name);
2295 switch (type) {
2296 case QEMU_FILE_TYPE_BIOS:
2297 subdir = "";
2298 break;
2299 case QEMU_FILE_TYPE_KEYMAP:
2300 subdir = "keymaps/";
2301 break;
2302 default:
2303 abort();
2305 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
2306 buf = qemu_mallocz(len);
2307 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
2308 if (access(buf, R_OK)) {
2309 qemu_free(buf);
2310 return NULL;
2312 return buf;
2315 static int device_help_func(QemuOpts *opts, void *opaque)
2317 return qdev_device_help(opts);
2320 static int device_init_func(QemuOpts *opts, void *opaque)
2322 DeviceState *dev;
2324 dev = qdev_device_add(opts);
2325 if (!dev)
2326 return -1;
2327 return 0;
2330 static int chardev_init_func(QemuOpts *opts, void *opaque)
2332 CharDriverState *chr;
2334 chr = qemu_chr_open_opts(opts, NULL);
2335 if (!chr)
2336 return -1;
2337 return 0;
2340 #ifdef CONFIG_LINUX
2341 static int fsdev_init_func(QemuOpts *opts, void *opaque)
2343 int ret;
2344 ret = qemu_fsdev_add(opts);
2346 return ret;
2348 #endif
2350 static int mon_init_func(QemuOpts *opts, void *opaque)
2352 CharDriverState *chr;
2353 const char *chardev;
2354 const char *mode;
2355 int flags;
2357 mode = qemu_opt_get(opts, "mode");
2358 if (mode == NULL) {
2359 mode = "readline";
2361 if (strcmp(mode, "readline") == 0) {
2362 flags = MONITOR_USE_READLINE;
2363 } else if (strcmp(mode, "control") == 0) {
2364 flags = MONITOR_USE_CONTROL;
2365 } else {
2366 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2367 exit(1);
2370 if (qemu_opt_get_bool(opts, "default", 0))
2371 flags |= MONITOR_IS_DEFAULT;
2373 chardev = qemu_opt_get(opts, "chardev");
2374 chr = qemu_chr_find(chardev);
2375 if (chr == NULL) {
2376 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2377 exit(1);
2380 monitor_init(chr, flags);
2381 return 0;
2384 static void monitor_parse(const char *optarg, const char *mode)
2386 static int monitor_device_index = 0;
2387 QemuOpts *opts;
2388 const char *p;
2389 char label[32];
2390 int def = 0;
2392 if (strstart(optarg, "chardev:", &p)) {
2393 snprintf(label, sizeof(label), "%s", p);
2394 } else {
2395 snprintf(label, sizeof(label), "compat_monitor%d",
2396 monitor_device_index);
2397 if (monitor_device_index == 0) {
2398 def = 1;
2400 opts = qemu_chr_parse_compat(label, optarg);
2401 if (!opts) {
2402 fprintf(stderr, "parse error: %s\n", optarg);
2403 exit(1);
2407 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
2408 if (!opts) {
2409 fprintf(stderr, "duplicate chardev: %s\n", label);
2410 exit(1);
2412 qemu_opt_set(opts, "mode", mode);
2413 qemu_opt_set(opts, "chardev", label);
2414 if (def)
2415 qemu_opt_set(opts, "default", "on");
2416 monitor_device_index++;
2419 struct device_config {
2420 enum {
2421 DEV_USB, /* -usbdevice */
2422 DEV_BT, /* -bt */
2423 DEV_SERIAL, /* -serial */
2424 DEV_PARALLEL, /* -parallel */
2425 DEV_VIRTCON, /* -virtioconsole */
2426 DEV_DEBUGCON, /* -debugcon */
2427 } type;
2428 const char *cmdline;
2429 QTAILQ_ENTRY(device_config) next;
2431 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
2433 static void add_device_config(int type, const char *cmdline)
2435 struct device_config *conf;
2437 conf = qemu_mallocz(sizeof(*conf));
2438 conf->type = type;
2439 conf->cmdline = cmdline;
2440 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2443 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2445 struct device_config *conf;
2446 int rc;
2448 QTAILQ_FOREACH(conf, &device_configs, next) {
2449 if (conf->type != type)
2450 continue;
2451 rc = func(conf->cmdline);
2452 if (0 != rc)
2453 return rc;
2455 return 0;
2458 static int serial_parse(const char *devname)
2460 static int index = 0;
2461 char label[32];
2463 if (strcmp(devname, "none") == 0)
2464 return 0;
2465 if (index == MAX_SERIAL_PORTS) {
2466 fprintf(stderr, "qemu: too many serial ports\n");
2467 exit(1);
2469 snprintf(label, sizeof(label), "serial%d", index);
2470 serial_hds[index] = qemu_chr_open(label, devname, NULL);
2471 if (!serial_hds[index]) {
2472 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
2473 devname, strerror(errno));
2474 return -1;
2476 index++;
2477 return 0;
2480 static int parallel_parse(const char *devname)
2482 static int index = 0;
2483 char label[32];
2485 if (strcmp(devname, "none") == 0)
2486 return 0;
2487 if (index == MAX_PARALLEL_PORTS) {
2488 fprintf(stderr, "qemu: too many parallel ports\n");
2489 exit(1);
2491 snprintf(label, sizeof(label), "parallel%d", index);
2492 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
2493 if (!parallel_hds[index]) {
2494 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2495 devname, strerror(errno));
2496 return -1;
2498 index++;
2499 return 0;
2502 static int virtcon_parse(const char *devname)
2504 static int index = 0;
2505 char label[32];
2506 QemuOpts *bus_opts, *dev_opts;
2508 if (strcmp(devname, "none") == 0)
2509 return 0;
2510 if (index == MAX_VIRTIO_CONSOLES) {
2511 fprintf(stderr, "qemu: too many virtio consoles\n");
2512 exit(1);
2515 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2516 qemu_opt_set(bus_opts, "driver", "virtio-serial");
2518 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2519 qemu_opt_set(dev_opts, "driver", "virtconsole");
2521 snprintf(label, sizeof(label), "virtcon%d", index);
2522 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
2523 if (!virtcon_hds[index]) {
2524 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2525 devname, strerror(errno));
2526 return -1;
2528 qemu_opt_set(dev_opts, "chardev", label);
2530 index++;
2531 return 0;
2534 static int debugcon_parse(const char *devname)
2536 QemuOpts *opts;
2538 if (!qemu_chr_open("debugcon", devname, NULL)) {
2539 exit(1);
2541 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
2542 if (!opts) {
2543 fprintf(stderr, "qemu: already have a debugcon device\n");
2544 exit(1);
2546 qemu_opt_set(opts, "driver", "isa-debugcon");
2547 qemu_opt_set(opts, "chardev", "debugcon");
2548 return 0;
2551 static const QEMUOption *lookup_opt(int argc, char **argv,
2552 const char **poptarg, int *poptind)
2554 const QEMUOption *popt;
2555 int optind = *poptind;
2556 char *r = argv[optind];
2557 const char *optarg;
2559 loc_set_cmdline(argv, optind, 1);
2560 optind++;
2561 /* Treat --foo the same as -foo. */
2562 if (r[1] == '-')
2563 r++;
2564 popt = qemu_options;
2565 for(;;) {
2566 if (!popt->name) {
2567 error_report("invalid option");
2568 exit(1);
2570 if (!strcmp(popt->name, r + 1))
2571 break;
2572 popt++;
2574 if (popt->flags & HAS_ARG) {
2575 if (optind >= argc) {
2576 error_report("requires an argument");
2577 exit(1);
2579 optarg = argv[optind++];
2580 loc_set_cmdline(argv, optind - 2, 2);
2581 } else {
2582 optarg = NULL;
2585 *poptarg = optarg;
2586 *poptind = optind;
2588 return popt;
2591 int main(int argc, char **argv, char **envp)
2593 const char *gdbstub_dev = NULL;
2594 int i;
2595 int snapshot, linux_boot;
2596 const char *icount_option = NULL;
2597 const char *initrd_filename;
2598 const char *kernel_filename, *kernel_cmdline;
2599 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2600 DisplayState *ds;
2601 DisplayChangeListener *dcl;
2602 int cyls, heads, secs, translation;
2603 QemuOpts *hda_opts = NULL, *opts;
2604 int optind;
2605 const char *optarg;
2606 const char *loadvm = NULL;
2607 QEMUMachine *machine;
2608 const char *cpu_model;
2609 #ifndef _WIN32
2610 int fds[2];
2611 #endif
2612 int tb_size;
2613 const char *pid_file = NULL;
2614 const char *incoming = NULL;
2615 #ifndef _WIN32
2616 int fd = 0;
2617 struct passwd *pwd = NULL;
2618 const char *chroot_dir = NULL;
2619 const char *run_as = NULL;
2620 #endif
2621 int show_vnc_port = 0;
2622 int defconfig = 1;
2624 error_set_progname(argv[0]);
2626 init_clocks();
2628 qemu_cache_utils_init(envp);
2630 QLIST_INIT (&vm_change_state_head);
2631 #ifndef _WIN32
2633 struct sigaction act;
2634 sigfillset(&act.sa_mask);
2635 act.sa_flags = 0;
2636 act.sa_handler = SIG_IGN;
2637 sigaction(SIGPIPE, &act, NULL);
2639 #else
2640 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
2641 /* Note: cpu_interrupt() is currently not SMP safe, so we force
2642 QEMU to run on a single CPU */
2644 HANDLE h;
2645 DWORD mask, smask;
2646 int i;
2647 h = GetCurrentProcess();
2648 if (GetProcessAffinityMask(h, &mask, &smask)) {
2649 for(i = 0; i < 32; i++) {
2650 if (mask & (1 << i))
2651 break;
2653 if (i != 32) {
2654 mask = 1 << i;
2655 SetProcessAffinityMask(h, mask);
2659 #endif
2661 module_call_init(MODULE_INIT_MACHINE);
2662 machine = find_default_machine();
2663 cpu_model = NULL;
2664 initrd_filename = NULL;
2665 ram_size = 0;
2666 snapshot = 0;
2667 kernel_filename = NULL;
2668 kernel_cmdline = "";
2669 cyls = heads = secs = 0;
2670 translation = BIOS_ATA_TRANSLATION_AUTO;
2672 for (i = 0; i < MAX_NODES; i++) {
2673 node_mem[i] = 0;
2674 node_cpumask[i] = 0;
2677 assigned_devices_index = 0;
2679 nb_numa_nodes = 0;
2680 nb_nics = 0;
2682 tb_size = 0;
2683 autostart= 1;
2685 /* first pass of option parsing */
2686 optind = 1;
2687 while (optind < argc) {
2688 if (argv[optind][0] != '-') {
2689 /* disk image */
2690 optind++;
2691 continue;
2692 } else {
2693 const QEMUOption *popt;
2695 popt = lookup_opt(argc, argv, &optarg, &optind);
2696 switch (popt->index) {
2697 case QEMU_OPTION_nodefconfig:
2698 defconfig=0;
2699 break;
2704 if (defconfig) {
2705 int ret;
2707 ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");
2708 if (ret < 0 && ret != -ENOENT) {
2709 exit(1);
2712 ret = qemu_read_config_file(arch_config_name);
2713 if (ret < 0 && ret != -ENOENT) {
2714 exit(1);
2717 cpudef_init();
2719 /* second pass of option parsing */
2720 optind = 1;
2721 for(;;) {
2722 if (optind >= argc)
2723 break;
2724 if (argv[optind][0] != '-') {
2725 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
2726 } else {
2727 const QEMUOption *popt;
2729 popt = lookup_opt(argc, argv, &optarg, &optind);
2730 if (!(popt->arch_mask & arch_type)) {
2731 printf("Option %s not supported for this target\n", popt->name);
2732 exit(1);
2734 switch(popt->index) {
2735 case QEMU_OPTION_M:
2736 machine = find_machine(optarg);
2737 if (!machine) {
2738 QEMUMachine *m;
2739 printf("Supported machines are:\n");
2740 for(m = first_machine; m != NULL; m = m->next) {
2741 if (m->alias)
2742 printf("%-10s %s (alias of %s)\n",
2743 m->alias, m->desc, m->name);
2744 printf("%-10s %s%s\n",
2745 m->name, m->desc,
2746 m->is_default ? " (default)" : "");
2748 exit(*optarg != '?');
2750 break;
2751 case QEMU_OPTION_cpu:
2752 /* hw initialization will check this */
2753 if (*optarg == '?') {
2754 list_cpus(stdout, &fprintf, optarg);
2755 exit(0);
2756 } else {
2757 cpu_model = optarg;
2759 break;
2760 case QEMU_OPTION_initrd:
2761 initrd_filename = optarg;
2762 break;
2763 case QEMU_OPTION_hda:
2764 if (cyls == 0)
2765 hda_opts = drive_add(optarg, HD_ALIAS, 0);
2766 else
2767 hda_opts = drive_add(optarg, HD_ALIAS
2768 ",cyls=%d,heads=%d,secs=%d%s",
2769 0, cyls, heads, secs,
2770 translation == BIOS_ATA_TRANSLATION_LBA ?
2771 ",trans=lba" :
2772 translation == BIOS_ATA_TRANSLATION_NONE ?
2773 ",trans=none" : "");
2774 break;
2775 case QEMU_OPTION_hdb:
2776 case QEMU_OPTION_hdc:
2777 case QEMU_OPTION_hdd:
2778 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
2779 break;
2780 case QEMU_OPTION_drive:
2781 drive_add(NULL, "%s", optarg);
2782 break;
2783 case QEMU_OPTION_set:
2784 if (qemu_set_option(optarg) != 0)
2785 exit(1);
2786 break;
2787 case QEMU_OPTION_global:
2788 if (qemu_global_option(optarg) != 0)
2789 exit(1);
2790 break;
2791 case QEMU_OPTION_mtdblock:
2792 drive_add(optarg, MTD_ALIAS);
2793 break;
2794 case QEMU_OPTION_sd:
2795 drive_add(optarg, SD_ALIAS);
2796 break;
2797 case QEMU_OPTION_pflash:
2798 drive_add(optarg, PFLASH_ALIAS);
2799 break;
2800 case QEMU_OPTION_snapshot:
2801 snapshot = 1;
2802 break;
2803 case QEMU_OPTION_hdachs:
2805 const char *p;
2806 p = optarg;
2807 cyls = strtol(p, (char **)&p, 0);
2808 if (cyls < 1 || cyls > 16383)
2809 goto chs_fail;
2810 if (*p != ',')
2811 goto chs_fail;
2812 p++;
2813 heads = strtol(p, (char **)&p, 0);
2814 if (heads < 1 || heads > 16)
2815 goto chs_fail;
2816 if (*p != ',')
2817 goto chs_fail;
2818 p++;
2819 secs = strtol(p, (char **)&p, 0);
2820 if (secs < 1 || secs > 63)
2821 goto chs_fail;
2822 if (*p == ',') {
2823 p++;
2824 if (!strcmp(p, "none"))
2825 translation = BIOS_ATA_TRANSLATION_NONE;
2826 else if (!strcmp(p, "lba"))
2827 translation = BIOS_ATA_TRANSLATION_LBA;
2828 else if (!strcmp(p, "auto"))
2829 translation = BIOS_ATA_TRANSLATION_AUTO;
2830 else
2831 goto chs_fail;
2832 } else if (*p != '\0') {
2833 chs_fail:
2834 fprintf(stderr, "qemu: invalid physical CHS format\n");
2835 exit(1);
2837 if (hda_opts != NULL) {
2838 char num[16];
2839 snprintf(num, sizeof(num), "%d", cyls);
2840 qemu_opt_set(hda_opts, "cyls", num);
2841 snprintf(num, sizeof(num), "%d", heads);
2842 qemu_opt_set(hda_opts, "heads", num);
2843 snprintf(num, sizeof(num), "%d", secs);
2844 qemu_opt_set(hda_opts, "secs", num);
2845 if (translation == BIOS_ATA_TRANSLATION_LBA)
2846 qemu_opt_set(hda_opts, "trans", "lba");
2847 if (translation == BIOS_ATA_TRANSLATION_NONE)
2848 qemu_opt_set(hda_opts, "trans", "none");
2851 break;
2852 case QEMU_OPTION_numa:
2853 if (nb_numa_nodes >= MAX_NODES) {
2854 fprintf(stderr, "qemu: too many NUMA nodes\n");
2855 exit(1);
2857 numa_add(optarg);
2858 break;
2859 case QEMU_OPTION_nographic:
2860 display_type = DT_NOGRAPHIC;
2861 break;
2862 #ifdef CONFIG_CURSES
2863 case QEMU_OPTION_curses:
2864 display_type = DT_CURSES;
2865 break;
2866 #endif
2867 case QEMU_OPTION_portrait:
2868 graphic_rotate = 1;
2869 break;
2870 case QEMU_OPTION_kernel:
2871 kernel_filename = optarg;
2872 break;
2873 case QEMU_OPTION_append:
2874 kernel_cmdline = optarg;
2875 break;
2876 case QEMU_OPTION_cdrom:
2877 drive_add(optarg, CDROM_ALIAS);
2878 break;
2879 case QEMU_OPTION_boot:
2881 static const char * const params[] = {
2882 "order", "once", "menu", NULL
2884 char buf[sizeof(boot_devices)];
2885 char *standard_boot_devices;
2886 int legacy = 0;
2888 if (!strchr(optarg, '=')) {
2889 legacy = 1;
2890 pstrcpy(buf, sizeof(buf), optarg);
2891 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2892 fprintf(stderr,
2893 "qemu: unknown boot parameter '%s' in '%s'\n",
2894 buf, optarg);
2895 exit(1);
2898 if (legacy ||
2899 get_param_value(buf, sizeof(buf), "order", optarg)) {
2900 validate_bootdevices(buf);
2901 pstrcpy(boot_devices, sizeof(boot_devices), buf);
2903 if (!legacy) {
2904 if (get_param_value(buf, sizeof(buf),
2905 "once", optarg)) {
2906 validate_bootdevices(buf);
2907 standard_boot_devices = qemu_strdup(boot_devices);
2908 pstrcpy(boot_devices, sizeof(boot_devices), buf);
2909 qemu_register_reset(restore_boot_devices,
2910 standard_boot_devices);
2912 if (get_param_value(buf, sizeof(buf),
2913 "menu", optarg)) {
2914 if (!strcmp(buf, "on")) {
2915 boot_menu = 1;
2916 } else if (!strcmp(buf, "off")) {
2917 boot_menu = 0;
2918 } else {
2919 fprintf(stderr,
2920 "qemu: invalid option value '%s'\n",
2921 buf);
2922 exit(1);
2927 break;
2928 case QEMU_OPTION_fda:
2929 case QEMU_OPTION_fdb:
2930 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
2931 break;
2932 case QEMU_OPTION_no_fd_bootchk:
2933 fd_bootchk = 0;
2934 break;
2935 case QEMU_OPTION_netdev:
2936 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
2937 exit(1);
2939 break;
2940 case QEMU_OPTION_net:
2941 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
2942 exit(1);
2944 break;
2945 #ifdef CONFIG_SLIRP
2946 case QEMU_OPTION_tftp:
2947 legacy_tftp_prefix = optarg;
2948 break;
2949 case QEMU_OPTION_bootp:
2950 legacy_bootp_filename = optarg;
2951 break;
2952 #ifndef _WIN32
2953 case QEMU_OPTION_smb:
2954 if (net_slirp_smb(optarg) < 0)
2955 exit(1);
2956 break;
2957 #endif
2958 case QEMU_OPTION_redir:
2959 if (net_slirp_redir(optarg) < 0)
2960 exit(1);
2961 break;
2962 #endif
2963 case QEMU_OPTION_bt:
2964 add_device_config(DEV_BT, optarg);
2965 break;
2966 case QEMU_OPTION_audio_help:
2967 if (!(audio_available())) {
2968 printf("Option %s not supported for this target\n", popt->name);
2969 exit(1);
2971 AUD_help ();
2972 exit (0);
2973 break;
2974 case QEMU_OPTION_soundhw:
2975 if (!(audio_available())) {
2976 printf("Option %s not supported for this target\n", popt->name);
2977 exit(1);
2979 select_soundhw (optarg);
2980 break;
2981 case QEMU_OPTION_h:
2982 help(0);
2983 break;
2984 case QEMU_OPTION_version:
2985 version();
2986 exit(0);
2987 break;
2988 case QEMU_OPTION_m: {
2989 uint64_t value;
2990 char *ptr;
2992 value = strtoul(optarg, &ptr, 10);
2993 switch (*ptr) {
2994 case 0: case 'M': case 'm':
2995 value <<= 20;
2996 break;
2997 case 'G': case 'g':
2998 value <<= 30;
2999 break;
3000 default:
3001 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
3002 exit(1);
3005 /* On 32-bit hosts, QEMU is limited by virtual address space */
3006 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
3007 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3008 exit(1);
3010 if (value != (uint64_t)(ram_addr_t)value) {
3011 fprintf(stderr, "qemu: ram size too large\n");
3012 exit(1);
3014 ram_size = value;
3015 break;
3017 case QEMU_OPTION_mempath:
3018 mem_path = optarg;
3019 break;
3020 #ifdef MAP_POPULATE
3021 case QEMU_OPTION_mem_prealloc:
3022 mem_prealloc = 1;
3023 break;
3024 #endif
3025 case QEMU_OPTION_d:
3026 set_cpu_log(optarg);
3027 break;
3028 case QEMU_OPTION_s:
3029 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
3030 break;
3031 case QEMU_OPTION_gdb:
3032 gdbstub_dev = optarg;
3033 break;
3034 case QEMU_OPTION_L:
3035 data_dir = optarg;
3036 break;
3037 case QEMU_OPTION_bios:
3038 bios_name = optarg;
3039 break;
3040 case QEMU_OPTION_singlestep:
3041 singlestep = 1;
3042 break;
3043 case QEMU_OPTION_S:
3044 autostart = 0;
3045 break;
3046 case QEMU_OPTION_k:
3047 keyboard_layout = optarg;
3048 break;
3049 case QEMU_OPTION_localtime:
3050 rtc_utc = 0;
3051 break;
3052 case QEMU_OPTION_vga:
3053 select_vgahw (optarg);
3054 break;
3055 case QEMU_OPTION_g:
3057 const char *p;
3058 int w, h, depth;
3059 p = optarg;
3060 w = strtol(p, (char **)&p, 10);
3061 if (w <= 0) {
3062 graphic_error:
3063 fprintf(stderr, "qemu: invalid resolution or depth\n");
3064 exit(1);
3066 if (*p != 'x')
3067 goto graphic_error;
3068 p++;
3069 h = strtol(p, (char **)&p, 10);
3070 if (h <= 0)
3071 goto graphic_error;
3072 if (*p == 'x') {
3073 p++;
3074 depth = strtol(p, (char **)&p, 10);
3075 if (depth != 8 && depth != 15 && depth != 16 &&
3076 depth != 24 && depth != 32)
3077 goto graphic_error;
3078 } else if (*p == '\0') {
3079 depth = graphic_depth;
3080 } else {
3081 goto graphic_error;
3084 graphic_width = w;
3085 graphic_height = h;
3086 graphic_depth = depth;
3088 break;
3089 case QEMU_OPTION_echr:
3091 char *r;
3092 term_escape_char = strtol(optarg, &r, 0);
3093 if (r == optarg)
3094 printf("Bad argument to echr\n");
3095 break;
3097 case QEMU_OPTION_monitor:
3098 monitor_parse(optarg, "readline");
3099 default_monitor = 0;
3100 break;
3101 case QEMU_OPTION_qmp:
3102 monitor_parse(optarg, "control");
3103 default_monitor = 0;
3104 break;
3105 case QEMU_OPTION_mon:
3106 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
3107 if (!opts) {
3108 exit(1);
3110 default_monitor = 0;
3111 break;
3112 case QEMU_OPTION_chardev:
3113 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
3114 if (!opts) {
3115 exit(1);
3117 break;
3118 #ifdef CONFIG_LINUX
3119 case QEMU_OPTION_fsdev:
3120 opts = qemu_opts_parse(&qemu_fsdev_opts, optarg, 1);
3121 if (!opts) {
3122 fprintf(stderr, "parse error: %s\n", optarg);
3123 exit(1);
3125 break;
3126 case QEMU_OPTION_virtfs: {
3127 char *arg_fsdev = NULL;
3128 char *arg_9p = NULL;
3129 int len = 0;
3131 opts = qemu_opts_parse(&qemu_virtfs_opts, optarg, 1);
3132 if (!opts) {
3133 fprintf(stderr, "parse error: %s\n", optarg);
3134 exit(1);
3137 len = strlen(",id=,path=");
3138 len += strlen(qemu_opt_get(opts, "fstype"));
3139 len += strlen(qemu_opt_get(opts, "mount_tag"));
3140 len += strlen(qemu_opt_get(opts, "path"));
3141 arg_fsdev = qemu_malloc((len + 1) * sizeof(*arg_fsdev));
3143 if (!arg_fsdev) {
3144 fprintf(stderr, "No memory to parse -fsdev for %s\n",
3145 optarg);
3146 exit(1);
3149 sprintf(arg_fsdev, "%s,id=%s,path=%s",
3150 qemu_opt_get(opts, "fstype"),
3151 qemu_opt_get(opts, "mount_tag"),
3152 qemu_opt_get(opts, "path"));
3154 len = strlen("virtio-9p-pci,fsdev=,mount_tag=");
3155 len += 2*strlen(qemu_opt_get(opts, "mount_tag"));
3156 arg_9p = qemu_malloc((len + 1) * sizeof(*arg_9p));
3158 if (!arg_9p) {
3159 fprintf(stderr, "No memory to parse -device for %s\n",
3160 optarg);
3161 exit(1);
3164 sprintf(arg_9p, "virtio-9p-pci,fsdev=%s,mount_tag=%s",
3165 qemu_opt_get(opts, "mount_tag"),
3166 qemu_opt_get(opts, "mount_tag"));
3168 if (!qemu_opts_parse(&qemu_fsdev_opts, arg_fsdev, 1)) {
3169 fprintf(stderr, "parse error [fsdev]: %s\n", optarg);
3170 exit(1);
3173 if (!qemu_opts_parse(&qemu_device_opts, arg_9p, 1)) {
3174 fprintf(stderr, "parse error [device]: %s\n", optarg);
3175 exit(1);
3178 qemu_free(arg_fsdev);
3179 qemu_free(arg_9p);
3180 break;
3182 #endif
3183 case QEMU_OPTION_serial:
3184 add_device_config(DEV_SERIAL, optarg);
3185 default_serial = 0;
3186 if (strncmp(optarg, "mon:", 4) == 0) {
3187 default_monitor = 0;
3189 break;
3190 case QEMU_OPTION_watchdog:
3191 if (watchdog) {
3192 fprintf(stderr,
3193 "qemu: only one watchdog option may be given\n");
3194 return 1;
3196 watchdog = optarg;
3197 break;
3198 case QEMU_OPTION_watchdog_action:
3199 if (select_watchdog_action(optarg) == -1) {
3200 fprintf(stderr, "Unknown -watchdog-action parameter\n");
3201 exit(1);
3203 break;
3204 case QEMU_OPTION_virtiocon:
3205 add_device_config(DEV_VIRTCON, optarg);
3206 default_virtcon = 0;
3207 if (strncmp(optarg, "mon:", 4) == 0) {
3208 default_monitor = 0;
3210 break;
3211 case QEMU_OPTION_parallel:
3212 add_device_config(DEV_PARALLEL, optarg);
3213 default_parallel = 0;
3214 if (strncmp(optarg, "mon:", 4) == 0) {
3215 default_monitor = 0;
3217 break;
3218 case QEMU_OPTION_debugcon:
3219 add_device_config(DEV_DEBUGCON, optarg);
3220 break;
3221 case QEMU_OPTION_loadvm:
3222 loadvm = optarg;
3223 break;
3224 case QEMU_OPTION_full_screen:
3225 full_screen = 1;
3226 break;
3227 #ifdef CONFIG_SDL
3228 case QEMU_OPTION_no_frame:
3229 no_frame = 1;
3230 break;
3231 case QEMU_OPTION_alt_grab:
3232 alt_grab = 1;
3233 break;
3234 case QEMU_OPTION_ctrl_grab:
3235 ctrl_grab = 1;
3236 break;
3237 case QEMU_OPTION_no_quit:
3238 no_quit = 1;
3239 break;
3240 case QEMU_OPTION_sdl:
3241 display_type = DT_SDL;
3242 break;
3243 #endif
3244 case QEMU_OPTION_pidfile:
3245 pid_file = optarg;
3246 break;
3247 case QEMU_OPTION_win2k_hack:
3248 win2k_install_hack = 1;
3249 break;
3250 case QEMU_OPTION_rtc_td_hack:
3251 rtc_td_hack = 1;
3252 break;
3253 case QEMU_OPTION_acpitable:
3254 do_acpitable_option(optarg);
3255 break;
3256 case QEMU_OPTION_smbios:
3257 do_smbios_option(optarg);
3258 break;
3259 #ifdef KVM_UPSTREAM
3260 case QEMU_OPTION_enable_kvm:
3261 kvm_allowed = 1;
3262 #endif
3263 break;
3264 case QEMU_OPTION_no_kvm:
3265 kvm_allowed = 0;
3266 break;
3267 case QEMU_OPTION_no_kvm_irqchip: {
3268 kvm_irqchip = 0;
3269 kvm_pit = 0;
3270 break;
3272 case QEMU_OPTION_no_kvm_pit: {
3273 kvm_pit = 0;
3274 break;
3276 case QEMU_OPTION_no_kvm_pit_reinjection: {
3277 kvm_pit_reinject = 0;
3278 break;
3280 case QEMU_OPTION_enable_nesting: {
3281 kvm_nested = 1;
3282 break;
3284 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
3285 case QEMU_OPTION_pcidevice:
3286 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
3287 fprintf(stderr, "Too many assigned devices\n");
3288 exit(1);
3290 assigned_devices[assigned_devices_index] = optarg;
3291 assigned_devices_index++;
3292 break;
3293 #endif
3294 case QEMU_OPTION_usb:
3295 usb_enabled = 1;
3296 break;
3297 case QEMU_OPTION_usbdevice:
3298 usb_enabled = 1;
3299 add_device_config(DEV_USB, optarg);
3300 break;
3301 case QEMU_OPTION_device:
3302 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
3303 exit(1);
3305 break;
3306 case QEMU_OPTION_smp:
3307 smp_parse(optarg);
3308 if (smp_cpus < 1) {
3309 fprintf(stderr, "Invalid number of CPUs\n");
3310 exit(1);
3312 if (max_cpus < smp_cpus) {
3313 fprintf(stderr, "maxcpus must be equal to or greater than "
3314 "smp\n");
3315 exit(1);
3317 if (max_cpus > 255) {
3318 fprintf(stderr, "Unsupported number of maxcpus\n");
3319 exit(1);
3321 break;
3322 case QEMU_OPTION_vnc:
3323 display_type = DT_VNC;
3324 vnc_display = optarg;
3325 break;
3326 case QEMU_OPTION_no_acpi:
3327 acpi_enabled = 0;
3328 break;
3329 case QEMU_OPTION_no_hpet:
3330 no_hpet = 1;
3331 break;
3332 case QEMU_OPTION_balloon:
3333 if (balloon_parse(optarg) < 0) {
3334 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3335 exit(1);
3337 break;
3338 case QEMU_OPTION_no_reboot:
3339 no_reboot = 1;
3340 break;
3341 case QEMU_OPTION_no_shutdown:
3342 no_shutdown = 1;
3343 break;
3344 case QEMU_OPTION_show_cursor:
3345 cursor_hide = 0;
3346 break;
3347 case QEMU_OPTION_uuid:
3348 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3349 fprintf(stderr, "Fail to parse UUID string."
3350 " Wrong format.\n");
3351 exit(1);
3353 break;
3354 #ifndef _WIN32
3355 case QEMU_OPTION_daemonize:
3356 daemonize = 1;
3357 break;
3358 #endif
3359 case QEMU_OPTION_option_rom:
3360 if (nb_option_roms >= MAX_OPTION_ROMS) {
3361 fprintf(stderr, "Too many option ROMs\n");
3362 exit(1);
3364 option_rom[nb_option_roms] = optarg;
3365 nb_option_roms++;
3366 break;
3367 case QEMU_OPTION_semihosting:
3368 semihosting_enabled = 1;
3369 break;
3370 case QEMU_OPTION_tdf:
3371 time_drift_fix = 1;
3372 break;
3373 case QEMU_OPTION_kvm_shadow_memory:
3374 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
3375 break;
3376 case QEMU_OPTION_name:
3377 qemu_name = qemu_strdup(optarg);
3379 char *p = strchr(qemu_name, ',');
3380 if (p != NULL) {
3381 *p++ = 0;
3382 if (strncmp(p, "process=", 8)) {
3383 fprintf(stderr, "Unknown subargument %s to -name", p);
3384 exit(1);
3386 p += 8;
3387 set_proc_name(p);
3390 break;
3391 case QEMU_OPTION_prom_env:
3392 if (nb_prom_envs >= MAX_PROM_ENVS) {
3393 fprintf(stderr, "Too many prom variables\n");
3394 exit(1);
3396 prom_envs[nb_prom_envs] = optarg;
3397 nb_prom_envs++;
3398 break;
3399 case QEMU_OPTION_old_param:
3400 old_param = 1;
3401 break;
3402 case QEMU_OPTION_clock:
3403 configure_alarms(optarg);
3404 break;
3405 case QEMU_OPTION_startdate:
3406 configure_rtc_date_offset(optarg, 1);
3407 break;
3408 case QEMU_OPTION_rtc:
3409 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
3410 if (!opts) {
3411 exit(1);
3413 configure_rtc(opts);
3414 break;
3415 case QEMU_OPTION_tb_size:
3416 tb_size = strtol(optarg, NULL, 0);
3417 if (tb_size < 0)
3418 tb_size = 0;
3419 break;
3420 case QEMU_OPTION_icount:
3421 icount_option = optarg;
3422 break;
3423 case QEMU_OPTION_incoming:
3424 incoming = optarg;
3425 break;
3426 case QEMU_OPTION_nodefaults:
3427 default_serial = 0;
3428 default_parallel = 0;
3429 default_virtcon = 0;
3430 default_monitor = 0;
3431 default_vga = 0;
3432 default_net = 0;
3433 default_floppy = 0;
3434 default_cdrom = 0;
3435 default_sdcard = 0;
3436 break;
3437 #ifndef _WIN32
3438 case QEMU_OPTION_chroot:
3439 chroot_dir = optarg;
3440 break;
3441 case QEMU_OPTION_runas:
3442 run_as = optarg;
3443 break;
3444 case QEMU_OPTION_nvram:
3445 nvram = optarg;
3446 break;
3447 #endif
3448 case QEMU_OPTION_xen_domid:
3449 if (!(xen_available())) {
3450 printf("Option %s not supported for this target\n", popt->name);
3451 exit(1);
3453 xen_domid = atoi(optarg);
3454 break;
3455 case QEMU_OPTION_xen_create:
3456 if (!(xen_available())) {
3457 printf("Option %s not supported for this target\n", popt->name);
3458 exit(1);
3460 xen_mode = XEN_CREATE;
3461 break;
3462 case QEMU_OPTION_xen_attach:
3463 if (!(xen_available())) {
3464 printf("Option %s not supported for this target\n", popt->name);
3465 exit(1);
3467 xen_mode = XEN_ATTACH;
3468 break;
3469 case QEMU_OPTION_readconfig:
3471 int ret = qemu_read_config_file(optarg);
3472 if (ret < 0) {
3473 fprintf(stderr, "read config %s: %s\n", optarg,
3474 strerror(-ret));
3475 exit(1);
3477 break;
3479 case QEMU_OPTION_writeconfig:
3481 FILE *fp;
3482 if (strcmp(optarg, "-") == 0) {
3483 fp = stdout;
3484 } else {
3485 fp = fopen(optarg, "w");
3486 if (fp == NULL) {
3487 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3488 exit(1);
3491 qemu_config_write(fp);
3492 fclose(fp);
3493 break;
3498 loc_set_none();
3500 /* If no data_dir is specified then try to find it relative to the
3501 executable path. */
3502 if (!data_dir) {
3503 data_dir = find_datadir(argv[0]);
3505 /* If all else fails use the install patch specified when building. */
3506 if (!data_dir) {
3507 data_dir = CONFIG_QEMU_DATADIR;
3511 * Default to max_cpus = smp_cpus, in case the user doesn't
3512 * specify a max_cpus value.
3514 if (!max_cpus)
3515 max_cpus = smp_cpus;
3517 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3518 if (smp_cpus > machine->max_cpus) {
3519 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3520 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
3521 machine->max_cpus);
3522 exit(1);
3525 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
3526 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
3528 if (machine->no_serial) {
3529 default_serial = 0;
3531 if (machine->no_parallel) {
3532 default_parallel = 0;
3534 if (!machine->use_virtcon) {
3535 default_virtcon = 0;
3537 if (machine->no_vga) {
3538 default_vga = 0;
3540 if (machine->no_floppy) {
3541 default_floppy = 0;
3543 if (machine->no_cdrom) {
3544 default_cdrom = 0;
3546 if (machine->no_sdcard) {
3547 default_sdcard = 0;
3550 if (display_type == DT_NOGRAPHIC) {
3551 if (default_parallel)
3552 add_device_config(DEV_PARALLEL, "null");
3553 if (default_serial && default_monitor) {
3554 add_device_config(DEV_SERIAL, "mon:stdio");
3555 } else if (default_virtcon && default_monitor) {
3556 add_device_config(DEV_VIRTCON, "mon:stdio");
3557 } else {
3558 if (default_serial)
3559 add_device_config(DEV_SERIAL, "stdio");
3560 if (default_virtcon)
3561 add_device_config(DEV_VIRTCON, "stdio");
3562 if (default_monitor)
3563 monitor_parse("stdio", "readline");
3565 } else {
3566 if (default_serial)
3567 add_device_config(DEV_SERIAL, "vc:80Cx24C");
3568 if (default_parallel)
3569 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3570 if (default_monitor)
3571 monitor_parse("vc:80Cx24C", "readline");
3572 if (default_virtcon)
3573 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3575 if (default_vga)
3576 vga_interface_type = VGA_CIRRUS;
3578 socket_init();
3580 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
3581 exit(1);
3582 #ifdef CONFIG_LINUX
3583 if (qemu_opts_foreach(&qemu_fsdev_opts, fsdev_init_func, NULL, 1) != 0) {
3584 exit(1);
3586 #endif
3588 #ifndef _WIN32
3589 if (daemonize) {
3590 pid_t pid;
3592 if (pipe(fds) == -1)
3593 exit(1);
3595 pid = fork();
3596 if (pid > 0) {
3597 uint8_t status;
3598 ssize_t len;
3600 close(fds[1]);
3602 again:
3603 len = read(fds[0], &status, 1);
3604 if (len == -1 && (errno == EINTR))
3605 goto again;
3607 if (len != 1)
3608 exit(1);
3609 else if (status == 1) {
3610 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
3611 exit(1);
3612 } else
3613 exit(0);
3614 } else if (pid < 0)
3615 exit(1);
3617 close(fds[0]);
3618 qemu_set_cloexec(fds[1]);
3620 setsid();
3622 pid = fork();
3623 if (pid > 0)
3624 exit(0);
3625 else if (pid < 0)
3626 exit(1);
3628 umask(027);
3630 signal(SIGTSTP, SIG_IGN);
3631 signal(SIGTTOU, SIG_IGN);
3632 signal(SIGTTIN, SIG_IGN);
3634 #endif
3636 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3637 #ifndef _WIN32
3638 if (daemonize) {
3639 uint8_t status = 1;
3640 if (write(fds[1], &status, 1) != 1) {
3641 perror("daemonize. Writing to pipe\n");
3643 } else
3644 #endif
3645 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
3646 exit(1);
3649 if (kvm_allowed) {
3650 int ret = kvm_init(smp_cpus);
3651 if (ret < 0) {
3652 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
3653 if (!kvm_available()) {
3654 printf("KVM not supported for this target\n");
3655 } else {
3656 fprintf(stderr, "failed to initialize KVM: %s\n", strerror(-ret));
3658 exit(1);
3659 #endif
3660 #ifdef CONFIG_KVM
3661 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
3662 kvm_allowed = 0;
3663 #endif
3667 if (qemu_init_main_loop()) {
3668 fprintf(stderr, "qemu_init_main_loop failed\n");
3669 exit(1);
3671 linux_boot = (kernel_filename != NULL);
3673 if (!linux_boot && *kernel_cmdline != '\0') {
3674 fprintf(stderr, "-append only allowed with -kernel option\n");
3675 exit(1);
3678 if (!linux_boot && initrd_filename != NULL) {
3679 fprintf(stderr, "-initrd only allowed with -kernel option\n");
3680 exit(1);
3683 #ifndef _WIN32
3684 /* Win32 doesn't support line-buffering and requires size >= 2 */
3685 setvbuf(stdout, NULL, _IOLBF, 0);
3686 #endif
3688 if (init_timer_alarm() < 0) {
3689 fprintf(stderr, "could not initialize alarm timer\n");
3690 exit(1);
3692 configure_icount(icount_option);
3694 if (net_init_clients() < 0) {
3695 exit(1);
3698 /* init the bluetooth world */
3699 if (foreach_device_config(DEV_BT, bt_parse))
3700 exit(1);
3702 /* init the memory */
3703 if (ram_size == 0)
3704 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3706 /* init the dynamic translator */
3707 cpu_exec_init_all(tb_size * 1024 * 1024);
3709 bdrv_init_with_whitelist();
3711 blk_mig_init();
3713 if (default_cdrom) {
3714 /* we always create the cdrom drive, even if no disk is there */
3715 drive_add(NULL, CDROM_ALIAS);
3718 if (default_floppy) {
3719 /* we always create at least one floppy */
3720 drive_add(NULL, FD_ALIAS, 0);
3723 if (default_sdcard) {
3724 /* we always create one sd slot, even if no card is in it */
3725 drive_add(NULL, SD_ALIAS);
3728 /* open the virtual block devices */
3729 if (snapshot)
3730 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
3731 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
3732 exit(1);
3734 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
3735 ram_load, NULL);
3737 if (nb_numa_nodes > 0) {
3738 int i;
3740 if (nb_numa_nodes > smp_cpus) {
3741 nb_numa_nodes = smp_cpus;
3744 /* If no memory size if given for any node, assume the default case
3745 * and distribute the available memory equally across all nodes
3747 for (i = 0; i < nb_numa_nodes; i++) {
3748 if (node_mem[i] != 0)
3749 break;
3751 if (i == nb_numa_nodes) {
3752 uint64_t usedmem = 0;
3754 /* On Linux, the each node's border has to be 8MB aligned,
3755 * the final node gets the rest.
3757 for (i = 0; i < nb_numa_nodes - 1; i++) {
3758 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3759 usedmem += node_mem[i];
3761 node_mem[i] = ram_size - usedmem;
3764 for (i = 0; i < nb_numa_nodes; i++) {
3765 if (node_cpumask[i] != 0)
3766 break;
3768 /* assigning the VCPUs round-robin is easier to implement, guest OSes
3769 * must cope with this anyway, because there are BIOSes out there in
3770 * real machines which also use this scheme.
3772 if (i == nb_numa_nodes) {
3773 for (i = 0; i < smp_cpus; i++) {
3774 node_cpumask[i % nb_numa_nodes] |= 1 << i;
3779 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0) {
3780 exit(1);
3783 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3784 exit(1);
3785 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3786 exit(1);
3787 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3788 exit(1);
3789 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3790 exit(1);
3792 module_call_init(MODULE_INIT_DEVICE);
3794 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
3795 exit(0);
3797 if (watchdog) {
3798 i = select_watchdog(watchdog);
3799 if (i > 0)
3800 exit (i == 1 ? 1 : 0);
3803 if (machine->compat_props) {
3804 qdev_prop_register_global_list(machine->compat_props);
3806 qemu_add_globals();
3808 machine->init(ram_size, boot_devices,
3809 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3811 cpu_synchronize_all_post_init();
3813 #ifndef _WIN32
3814 /* must be after terminal init, SDL library changes signal handlers */
3815 sighandler_setup();
3816 #endif
3818 set_numa_modes();
3820 current_machine = machine;
3822 /* init USB devices */
3823 if (usb_enabled) {
3824 if (foreach_device_config(DEV_USB, usb_parse) < 0)
3825 exit(1);
3828 /* init generic devices */
3829 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
3830 exit(1);
3832 net_check_clients();
3834 /* just use the first displaystate for the moment */
3835 ds = get_displaystate();
3837 if (display_type == DT_DEFAULT) {
3838 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3839 display_type = DT_SDL;
3840 #else
3841 display_type = DT_VNC;
3842 vnc_display = "localhost:0,to=99";
3843 show_vnc_port = 1;
3844 #endif
3848 switch (display_type) {
3849 case DT_NOGRAPHIC:
3850 break;
3851 #if defined(CONFIG_CURSES)
3852 case DT_CURSES:
3853 curses_display_init(ds, full_screen);
3854 break;
3855 #endif
3856 #if defined(CONFIG_SDL)
3857 case DT_SDL:
3858 sdl_display_init(ds, full_screen, no_frame);
3859 break;
3860 #elif defined(CONFIG_COCOA)
3861 case DT_SDL:
3862 cocoa_display_init(ds, full_screen);
3863 break;
3864 #endif
3865 case DT_VNC:
3866 vnc_display_init(ds);
3867 if (vnc_display_open(ds, vnc_display) < 0)
3868 exit(1);
3870 if (show_vnc_port) {
3871 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3873 break;
3874 default:
3875 break;
3877 dpy_resize(ds);
3879 dcl = ds->listeners;
3880 while (dcl != NULL) {
3881 if (dcl->dpy_refresh != NULL) {
3882 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
3883 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
3885 dcl = dcl->next;
3888 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
3889 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
3890 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
3893 text_consoles_set_display(ds);
3895 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3896 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3897 gdbstub_dev);
3898 exit(1);
3901 qdev_machine_creation_done();
3903 if (rom_load_all() != 0) {
3904 fprintf(stderr, "rom loading failed\n");
3905 exit(1);
3908 qemu_system_reset();
3909 if (loadvm) {
3910 if (load_vmstate(loadvm) < 0) {
3911 autostart = 0;
3915 if (incoming) {
3916 qemu_start_incoming_migration(incoming);
3917 } else if (autostart) {
3918 vm_start();
3921 #ifndef _WIN32
3922 if (daemonize) {
3923 uint8_t status = 0;
3924 ssize_t len;
3926 again1:
3927 len = write(fds[1], &status, 1);
3928 if (len == -1 && (errno == EINTR))
3929 goto again1;
3931 if (len != 1)
3932 exit(1);
3934 if (chdir("/")) {
3935 perror("not able to chdir to /");
3936 exit(1);
3938 TFR(fd = qemu_open("/dev/null", O_RDWR));
3939 if (fd == -1)
3940 exit(1);
3943 if (run_as) {
3944 pwd = getpwnam(run_as);
3945 if (!pwd) {
3946 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
3947 exit(1);
3951 if (chroot_dir) {
3952 if (chroot(chroot_dir) < 0) {
3953 fprintf(stderr, "chroot failed\n");
3954 exit(1);
3956 if (chdir("/")) {
3957 perror("not able to chdir to /");
3958 exit(1);
3962 if (run_as) {
3963 if (setgid(pwd->pw_gid) < 0) {
3964 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
3965 exit(1);
3967 if (setuid(pwd->pw_uid) < 0) {
3968 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
3969 exit(1);
3971 if (setuid(0) != -1) {
3972 fprintf(stderr, "Dropping privileges failed\n");
3973 exit(1);
3977 if (daemonize) {
3978 dup2(fd, 0);
3979 dup2(fd, 1);
3980 dup2(fd, 2);
3982 close(fd);
3984 #endif
3986 main_loop();
3987 quit_timers();
3988 net_cleanup();
3990 return 0;