tcg/ppc: Fix not_i32
[qemu.git] / vl.c
blob6768cf125185aa0c67932cb56cc41f05f090b4fe
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 "balloon.h"
150 #include "qemu-option.h"
151 #include "qemu-config.h"
152 #include "qemu-objects.h"
154 #include "disas.h"
156 #include "qemu_socket.h"
158 #include "slirp/libslirp.h"
160 #include "qemu-queue.h"
161 #include "cpus.h"
162 #include "arch_init.h"
164 //#define DEBUG_NET
165 //#define DEBUG_SLIRP
167 #define DEFAULT_RAM_SIZE 128
169 #define MAX_VIRTIO_CONSOLES 1
171 static const char *data_dir;
172 const char *bios_name = NULL;
173 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
174 to store the VM snapshots */
175 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
176 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
177 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
178 DisplayType display_type = DT_DEFAULT;
179 const char* keyboard_layout = NULL;
180 ram_addr_t ram_size;
181 const char *mem_path = NULL;
182 #ifdef MAP_POPULATE
183 int mem_prealloc = 0; /* force preallocation of physical target memory */
184 #endif
185 int nb_nics;
186 NICInfo nd_table[MAX_NICS];
187 int vm_running;
188 int autostart;
189 static int rtc_utc = 1;
190 static int rtc_date_offset = -1; /* -1 means no change */
191 QEMUClock *rtc_clock;
192 int vga_interface_type = VGA_NONE;
193 static int full_screen = 0;
194 #ifdef CONFIG_SDL
195 static int no_frame = 0;
196 #endif
197 int no_quit = 0;
198 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
199 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
200 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
201 int win2k_install_hack = 0;
202 int rtc_td_hack = 0;
203 int usb_enabled = 0;
204 int singlestep = 0;
205 int smp_cpus = 1;
206 int max_cpus = 0;
207 int smp_cores = 1;
208 int smp_threads = 1;
209 const char *vnc_display;
210 int acpi_enabled = 1;
211 int no_hpet = 0;
212 int fd_bootchk = 1;
213 int no_reboot = 0;
214 int no_shutdown = 0;
215 int cursor_hide = 1;
216 int graphic_rotate = 0;
217 uint8_t irq0override = 1;
218 #ifndef _WIN32
219 int daemonize = 0;
220 #endif
221 const char *watchdog;
222 const char *option_rom[MAX_OPTION_ROMS];
223 int nb_option_roms;
224 int semihosting_enabled = 0;
225 int old_param = 0;
226 const char *qemu_name;
227 int alt_grab = 0;
228 int ctrl_grab = 0;
229 unsigned int nb_prom_envs = 0;
230 const char *prom_envs[MAX_PROM_ENVS];
231 int boot_menu;
233 int nb_numa_nodes;
234 uint64_t node_mem[MAX_NODES];
235 uint64_t node_cpumask[MAX_NODES];
237 static QEMUTimer *nographic_timer;
239 uint8_t qemu_uuid[16];
241 static QEMUBootSetHandler *boot_set_handler;
242 static void *boot_set_opaque;
244 int kvm_allowed = 0;
245 uint32_t xen_domid;
246 enum xen_mode xen_mode = XEN_EMULATE;
248 #ifdef SIGRTMIN
249 #define SIG_IPI (SIGRTMIN+4)
250 #else
251 #define SIG_IPI SIGUSR1
252 #endif
254 static int default_serial = 1;
255 static int default_parallel = 1;
256 static int default_virtcon = 1;
257 static int default_monitor = 1;
258 static int default_vga = 1;
259 static int default_floppy = 1;
260 static int default_cdrom = 1;
261 static int default_sdcard = 1;
263 static struct {
264 const char *driver;
265 int *flag;
266 } default_list[] = {
267 { .driver = "isa-serial", .flag = &default_serial },
268 { .driver = "isa-parallel", .flag = &default_parallel },
269 { .driver = "isa-fdc", .flag = &default_floppy },
270 { .driver = "ide-drive", .flag = &default_cdrom },
271 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
272 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
273 { .driver = "virtio-serial", .flag = &default_virtcon },
274 { .driver = "VGA", .flag = &default_vga },
275 { .driver = "cirrus-vga", .flag = &default_vga },
276 { .driver = "vmware-svga", .flag = &default_vga },
279 static int default_driver_check(QemuOpts *opts, void *opaque)
281 const char *driver = qemu_opt_get(opts, "driver");
282 int i;
284 if (!driver)
285 return 0;
286 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
287 if (strcmp(default_list[i].driver, driver) != 0)
288 continue;
289 *(default_list[i].flag) = 0;
291 return 0;
294 /***********************************************************/
295 /* x86 ISA bus support */
297 target_phys_addr_t isa_mem_base = 0;
298 PicState2 *isa_pic;
300 static void set_proc_name(const char *s)
302 #if defined(__linux__) && defined(PR_SET_NAME)
303 char name[16];
304 if (!s)
305 return;
306 name[sizeof(name) - 1] = 0;
307 strncpy(name, s, sizeof(name));
308 /* Could rewrite argv[0] too, but that's a bit more complicated.
309 This simple way is enough for `top'. */
310 prctl(PR_SET_NAME, name);
311 #endif
314 /***************/
315 /* ballooning */
317 static QEMUBalloonEvent *qemu_balloon_event;
318 void *qemu_balloon_event_opaque;
320 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
322 qemu_balloon_event = func;
323 qemu_balloon_event_opaque = opaque;
326 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
328 if (qemu_balloon_event) {
329 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
330 return 1;
331 } else {
332 return 0;
336 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
338 if (qemu_balloon_event) {
339 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
340 return 1;
341 } else {
342 return 0;
347 /***********************************************************/
348 /* real time host monotonic timer */
350 /* compute with 96 bit intermediate result: (a*b)/c */
351 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
353 union {
354 uint64_t ll;
355 struct {
356 #ifdef HOST_WORDS_BIGENDIAN
357 uint32_t high, low;
358 #else
359 uint32_t low, high;
360 #endif
361 } l;
362 } u, res;
363 uint64_t rl, rh;
365 u.ll = a;
366 rl = (uint64_t)u.l.low * (uint64_t)b;
367 rh = (uint64_t)u.l.high * (uint64_t)b;
368 rh += (rl >> 32);
369 res.l.high = rh / c;
370 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
371 return res.ll;
374 /***********************************************************/
375 /* host time/date access */
376 void qemu_get_timedate(struct tm *tm, int offset)
378 time_t ti;
379 struct tm *ret;
381 time(&ti);
382 ti += offset;
383 if (rtc_date_offset == -1) {
384 if (rtc_utc)
385 ret = gmtime(&ti);
386 else
387 ret = localtime(&ti);
388 } else {
389 ti -= rtc_date_offset;
390 ret = gmtime(&ti);
393 memcpy(tm, ret, sizeof(struct tm));
396 int qemu_timedate_diff(struct tm *tm)
398 time_t seconds;
400 if (rtc_date_offset == -1)
401 if (rtc_utc)
402 seconds = mktimegm(tm);
403 else
404 seconds = mktime(tm);
405 else
406 seconds = mktimegm(tm) + rtc_date_offset;
408 return seconds - time(NULL);
411 void rtc_change_mon_event(struct tm *tm)
413 QObject *data;
415 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
416 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
417 qobject_decref(data);
420 static void configure_rtc_date_offset(const char *startdate, int legacy)
422 time_t rtc_start_date;
423 struct tm tm;
425 if (!strcmp(startdate, "now") && legacy) {
426 rtc_date_offset = -1;
427 } else {
428 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
429 &tm.tm_year,
430 &tm.tm_mon,
431 &tm.tm_mday,
432 &tm.tm_hour,
433 &tm.tm_min,
434 &tm.tm_sec) == 6) {
435 /* OK */
436 } else if (sscanf(startdate, "%d-%d-%d",
437 &tm.tm_year,
438 &tm.tm_mon,
439 &tm.tm_mday) == 3) {
440 tm.tm_hour = 0;
441 tm.tm_min = 0;
442 tm.tm_sec = 0;
443 } else {
444 goto date_fail;
446 tm.tm_year -= 1900;
447 tm.tm_mon--;
448 rtc_start_date = mktimegm(&tm);
449 if (rtc_start_date == -1) {
450 date_fail:
451 fprintf(stderr, "Invalid date format. Valid formats are:\n"
452 "'2006-06-17T16:01:21' or '2006-06-17'\n");
453 exit(1);
455 rtc_date_offset = time(NULL) - rtc_start_date;
459 static void configure_rtc(QemuOpts *opts)
461 const char *value;
463 value = qemu_opt_get(opts, "base");
464 if (value) {
465 if (!strcmp(value, "utc")) {
466 rtc_utc = 1;
467 } else if (!strcmp(value, "localtime")) {
468 rtc_utc = 0;
469 } else {
470 configure_rtc_date_offset(value, 0);
473 value = qemu_opt_get(opts, "clock");
474 if (value) {
475 if (!strcmp(value, "host")) {
476 rtc_clock = host_clock;
477 } else if (!strcmp(value, "vm")) {
478 rtc_clock = vm_clock;
479 } else {
480 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
481 exit(1);
484 value = qemu_opt_get(opts, "driftfix");
485 if (value) {
486 if (!strcmp(value, "slew")) {
487 rtc_td_hack = 1;
488 } else if (!strcmp(value, "none")) {
489 rtc_td_hack = 0;
490 } else {
491 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
492 exit(1);
497 #ifdef _WIN32
498 static void socket_cleanup(void)
500 WSACleanup();
503 static int socket_init(void)
505 WSADATA Data;
506 int ret, err;
508 ret = WSAStartup(MAKEWORD(2,2), &Data);
509 if (ret != 0) {
510 err = WSAGetLastError();
511 fprintf(stderr, "WSAStartup: %d\n", err);
512 return -1;
514 atexit(socket_cleanup);
515 return 0;
517 #endif
519 /***********************************************************/
520 /* Bluetooth support */
521 static int nb_hcis;
522 static int cur_hci;
523 static struct HCIInfo *hci_table[MAX_NICS];
525 static struct bt_vlan_s {
526 struct bt_scatternet_s net;
527 int id;
528 struct bt_vlan_s *next;
529 } *first_bt_vlan;
531 /* find or alloc a new bluetooth "VLAN" */
532 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
534 struct bt_vlan_s **pvlan, *vlan;
535 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
536 if (vlan->id == id)
537 return &vlan->net;
539 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
540 vlan->id = id;
541 pvlan = &first_bt_vlan;
542 while (*pvlan != NULL)
543 pvlan = &(*pvlan)->next;
544 *pvlan = vlan;
545 return &vlan->net;
548 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
552 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
554 return -ENOTSUP;
557 static struct HCIInfo null_hci = {
558 .cmd_send = null_hci_send,
559 .sco_send = null_hci_send,
560 .acl_send = null_hci_send,
561 .bdaddr_set = null_hci_addr_set,
564 struct HCIInfo *qemu_next_hci(void)
566 if (cur_hci == nb_hcis)
567 return &null_hci;
569 return hci_table[cur_hci++];
572 static struct HCIInfo *hci_init(const char *str)
574 char *endp;
575 struct bt_scatternet_s *vlan = 0;
577 if (!strcmp(str, "null"))
578 /* null */
579 return &null_hci;
580 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
581 /* host[:hciN] */
582 return bt_host_hci(str[4] ? str + 5 : "hci0");
583 else if (!strncmp(str, "hci", 3)) {
584 /* hci[,vlan=n] */
585 if (str[3]) {
586 if (!strncmp(str + 3, ",vlan=", 6)) {
587 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
588 if (*endp)
589 vlan = 0;
591 } else
592 vlan = qemu_find_bt_vlan(0);
593 if (vlan)
594 return bt_new_hci(vlan);
597 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
599 return 0;
602 static int bt_hci_parse(const char *str)
604 struct HCIInfo *hci;
605 bdaddr_t bdaddr;
607 if (nb_hcis >= MAX_NICS) {
608 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
609 return -1;
612 hci = hci_init(str);
613 if (!hci)
614 return -1;
616 bdaddr.b[0] = 0x52;
617 bdaddr.b[1] = 0x54;
618 bdaddr.b[2] = 0x00;
619 bdaddr.b[3] = 0x12;
620 bdaddr.b[4] = 0x34;
621 bdaddr.b[5] = 0x56 + nb_hcis;
622 hci->bdaddr_set(hci, bdaddr.b);
624 hci_table[nb_hcis++] = hci;
626 return 0;
629 static void bt_vhci_add(int vlan_id)
631 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
633 if (!vlan->slave)
634 fprintf(stderr, "qemu: warning: adding a VHCI to "
635 "an empty scatternet %i\n", vlan_id);
637 bt_vhci_init(bt_new_hci(vlan));
640 static struct bt_device_s *bt_device_add(const char *opt)
642 struct bt_scatternet_s *vlan;
643 int vlan_id = 0;
644 char *endp = strstr(opt, ",vlan=");
645 int len = (endp ? endp - opt : strlen(opt)) + 1;
646 char devname[10];
648 pstrcpy(devname, MIN(sizeof(devname), len), opt);
650 if (endp) {
651 vlan_id = strtol(endp + 6, &endp, 0);
652 if (*endp) {
653 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
654 return 0;
658 vlan = qemu_find_bt_vlan(vlan_id);
660 if (!vlan->slave)
661 fprintf(stderr, "qemu: warning: adding a slave device to "
662 "an empty scatternet %i\n", vlan_id);
664 if (!strcmp(devname, "keyboard"))
665 return bt_keyboard_init(vlan);
667 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
668 return 0;
671 static int bt_parse(const char *opt)
673 const char *endp, *p;
674 int vlan;
676 if (strstart(opt, "hci", &endp)) {
677 if (!*endp || *endp == ',') {
678 if (*endp)
679 if (!strstart(endp, ",vlan=", 0))
680 opt = endp + 1;
682 return bt_hci_parse(opt);
684 } else if (strstart(opt, "vhci", &endp)) {
685 if (!*endp || *endp == ',') {
686 if (*endp) {
687 if (strstart(endp, ",vlan=", &p)) {
688 vlan = strtol(p, (char **) &endp, 0);
689 if (*endp) {
690 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
691 return 1;
693 } else {
694 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
695 return 1;
697 } else
698 vlan = 0;
700 bt_vhci_add(vlan);
701 return 0;
703 } else if (strstart(opt, "device:", &endp))
704 return !bt_device_add(endp);
706 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
707 return 1;
710 /***********************************************************/
711 /* QEMU Block devices */
713 #define HD_ALIAS "index=%d,media=disk"
714 #define CDROM_ALIAS "index=2,media=cdrom"
715 #define FD_ALIAS "index=%d,if=floppy"
716 #define PFLASH_ALIAS "if=pflash"
717 #define MTD_ALIAS "if=mtd"
718 #define SD_ALIAS "index=0,if=sd"
720 QemuOpts *drive_add(const char *file, const char *fmt, ...)
722 va_list ap;
723 char optstr[1024];
724 QemuOpts *opts;
726 va_start(ap, fmt);
727 vsnprintf(optstr, sizeof(optstr), fmt, ap);
728 va_end(ap);
730 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
731 if (!opts) {
732 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
733 __FUNCTION__, optstr);
734 return NULL;
736 if (file)
737 qemu_opt_set(opts, "file", file);
738 return opts;
741 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
743 DriveInfo *dinfo;
745 /* seek interface, bus and unit */
747 QTAILQ_FOREACH(dinfo, &drives, next) {
748 if (dinfo->type == type &&
749 dinfo->bus == bus &&
750 dinfo->unit == unit)
751 return dinfo;
754 return NULL;
757 DriveInfo *drive_get_by_id(const char *id)
759 DriveInfo *dinfo;
761 QTAILQ_FOREACH(dinfo, &drives, next) {
762 if (strcmp(id, dinfo->id))
763 continue;
764 return dinfo;
766 return NULL;
769 int drive_get_max_bus(BlockInterfaceType type)
771 int max_bus;
772 DriveInfo *dinfo;
774 max_bus = -1;
775 QTAILQ_FOREACH(dinfo, &drives, next) {
776 if(dinfo->type == type &&
777 dinfo->bus > max_bus)
778 max_bus = dinfo->bus;
780 return max_bus;
783 const char *drive_get_serial(BlockDriverState *bdrv)
785 DriveInfo *dinfo;
787 QTAILQ_FOREACH(dinfo, &drives, next) {
788 if (dinfo->bdrv == bdrv)
789 return dinfo->serial;
792 return "\0";
795 BlockInterfaceErrorAction drive_get_on_error(
796 BlockDriverState *bdrv, int is_read)
798 DriveInfo *dinfo;
800 QTAILQ_FOREACH(dinfo, &drives, next) {
801 if (dinfo->bdrv == bdrv)
802 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
805 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
808 static void bdrv_format_print(void *opaque, const char *name)
810 fprintf(stderr, " %s", name);
813 void drive_uninit(DriveInfo *dinfo)
815 qemu_opts_del(dinfo->opts);
816 bdrv_delete(dinfo->bdrv);
817 QTAILQ_REMOVE(&drives, dinfo, next);
818 qemu_free(dinfo);
821 static int parse_block_error_action(const char *buf, int is_read)
823 if (!strcmp(buf, "ignore")) {
824 return BLOCK_ERR_IGNORE;
825 } else if (!is_read && !strcmp(buf, "enospc")) {
826 return BLOCK_ERR_STOP_ENOSPC;
827 } else if (!strcmp(buf, "stop")) {
828 return BLOCK_ERR_STOP_ANY;
829 } else if (!strcmp(buf, "report")) {
830 return BLOCK_ERR_REPORT;
831 } else {
832 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
833 buf, is_read ? "read" : "write");
834 return -1;
838 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
839 int *fatal_error)
841 const char *buf;
842 const char *file = NULL;
843 char devname[128];
844 const char *serial;
845 const char *mediastr = "";
846 BlockInterfaceType type;
847 enum { MEDIA_DISK, MEDIA_CDROM } media;
848 int bus_id, unit_id;
849 int cyls, heads, secs, translation;
850 BlockDriver *drv = NULL;
851 QEMUMachine *machine = opaque;
852 int max_devs;
853 int index;
854 int cache;
855 int aio = 0;
856 int ro = 0;
857 int bdrv_flags;
858 int on_read_error, on_write_error;
859 const char *devaddr;
860 DriveInfo *dinfo;
861 int snapshot = 0;
863 *fatal_error = 1;
865 translation = BIOS_ATA_TRANSLATION_AUTO;
866 cache = 1;
868 if (machine && machine->use_scsi) {
869 type = IF_SCSI;
870 max_devs = MAX_SCSI_DEVS;
871 pstrcpy(devname, sizeof(devname), "scsi");
872 } else {
873 type = IF_IDE;
874 max_devs = MAX_IDE_DEVS;
875 pstrcpy(devname, sizeof(devname), "ide");
877 media = MEDIA_DISK;
879 /* extract parameters */
880 bus_id = qemu_opt_get_number(opts, "bus", 0);
881 unit_id = qemu_opt_get_number(opts, "unit", -1);
882 index = qemu_opt_get_number(opts, "index", -1);
884 cyls = qemu_opt_get_number(opts, "cyls", 0);
885 heads = qemu_opt_get_number(opts, "heads", 0);
886 secs = qemu_opt_get_number(opts, "secs", 0);
888 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
889 ro = qemu_opt_get_bool(opts, "readonly", 0);
891 file = qemu_opt_get(opts, "file");
892 serial = qemu_opt_get(opts, "serial");
894 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
895 pstrcpy(devname, sizeof(devname), buf);
896 if (!strcmp(buf, "ide")) {
897 type = IF_IDE;
898 max_devs = MAX_IDE_DEVS;
899 } else if (!strcmp(buf, "scsi")) {
900 type = IF_SCSI;
901 max_devs = MAX_SCSI_DEVS;
902 } else if (!strcmp(buf, "floppy")) {
903 type = IF_FLOPPY;
904 max_devs = 0;
905 } else if (!strcmp(buf, "pflash")) {
906 type = IF_PFLASH;
907 max_devs = 0;
908 } else if (!strcmp(buf, "mtd")) {
909 type = IF_MTD;
910 max_devs = 0;
911 } else if (!strcmp(buf, "sd")) {
912 type = IF_SD;
913 max_devs = 0;
914 } else if (!strcmp(buf, "virtio")) {
915 type = IF_VIRTIO;
916 max_devs = 0;
917 } else if (!strcmp(buf, "xen")) {
918 type = IF_XEN;
919 max_devs = 0;
920 } else if (!strcmp(buf, "none")) {
921 type = IF_NONE;
922 max_devs = 0;
923 } else {
924 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
925 return NULL;
929 if (cyls || heads || secs) {
930 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
931 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
932 return NULL;
934 if (heads < 1 || (type == IF_IDE && heads > 16)) {
935 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
936 return NULL;
938 if (secs < 1 || (type == IF_IDE && secs > 63)) {
939 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
940 return NULL;
944 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
945 if (!cyls) {
946 fprintf(stderr,
947 "qemu: '%s' trans must be used with cyls,heads and secs\n",
948 buf);
949 return NULL;
951 if (!strcmp(buf, "none"))
952 translation = BIOS_ATA_TRANSLATION_NONE;
953 else if (!strcmp(buf, "lba"))
954 translation = BIOS_ATA_TRANSLATION_LBA;
955 else if (!strcmp(buf, "auto"))
956 translation = BIOS_ATA_TRANSLATION_AUTO;
957 else {
958 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
959 return NULL;
963 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
964 if (!strcmp(buf, "disk")) {
965 media = MEDIA_DISK;
966 } else if (!strcmp(buf, "cdrom")) {
967 if (cyls || secs || heads) {
968 fprintf(stderr,
969 "qemu: '%s' invalid physical CHS format\n", buf);
970 return NULL;
972 media = MEDIA_CDROM;
973 } else {
974 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
975 return NULL;
979 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
980 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
981 cache = 0;
982 else if (!strcmp(buf, "writethrough"))
983 cache = 1;
984 else if (!strcmp(buf, "writeback"))
985 cache = 2;
986 else {
987 fprintf(stderr, "qemu: invalid cache option\n");
988 return NULL;
992 #ifdef CONFIG_LINUX_AIO
993 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
994 if (!strcmp(buf, "threads"))
995 aio = 0;
996 else if (!strcmp(buf, "native"))
997 aio = 1;
998 else {
999 fprintf(stderr, "qemu: invalid aio option\n");
1000 return NULL;
1003 #endif
1005 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1006 if (strcmp(buf, "?") == 0) {
1007 fprintf(stderr, "qemu: Supported formats:");
1008 bdrv_iterate_format(bdrv_format_print, NULL);
1009 fprintf(stderr, "\n");
1010 return NULL;
1012 drv = bdrv_find_whitelisted_format(buf);
1013 if (!drv) {
1014 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1015 return NULL;
1019 on_write_error = BLOCK_ERR_STOP_ENOSPC;
1020 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1021 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1022 fprintf(stderr, "werror is no supported by this format\n");
1023 return NULL;
1026 on_write_error = parse_block_error_action(buf, 0);
1027 if (on_write_error < 0) {
1028 return NULL;
1032 on_read_error = BLOCK_ERR_REPORT;
1033 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1034 if (type != IF_IDE && type != IF_VIRTIO) {
1035 fprintf(stderr, "rerror is no supported by this format\n");
1036 return NULL;
1039 on_read_error = parse_block_error_action(buf, 1);
1040 if (on_read_error < 0) {
1041 return NULL;
1045 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1046 if (type != IF_VIRTIO) {
1047 fprintf(stderr, "addr is not supported\n");
1048 return NULL;
1052 /* compute bus and unit according index */
1054 if (index != -1) {
1055 if (bus_id != 0 || unit_id != -1) {
1056 fprintf(stderr,
1057 "qemu: index cannot be used with bus and unit\n");
1058 return NULL;
1060 if (max_devs == 0)
1062 unit_id = index;
1063 bus_id = 0;
1064 } else {
1065 unit_id = index % max_devs;
1066 bus_id = index / max_devs;
1070 /* if user doesn't specify a unit_id,
1071 * try to find the first free
1074 if (unit_id == -1) {
1075 unit_id = 0;
1076 while (drive_get(type, bus_id, unit_id) != NULL) {
1077 unit_id++;
1078 if (max_devs && unit_id >= max_devs) {
1079 unit_id -= max_devs;
1080 bus_id++;
1085 /* check unit id */
1087 if (max_devs && unit_id >= max_devs) {
1088 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1089 unit_id, max_devs - 1);
1090 return NULL;
1094 * ignore multiple definitions
1097 if (drive_get(type, bus_id, unit_id) != NULL) {
1098 *fatal_error = 0;
1099 return NULL;
1102 /* init */
1104 dinfo = qemu_mallocz(sizeof(*dinfo));
1105 if ((buf = qemu_opts_id(opts)) != NULL) {
1106 dinfo->id = qemu_strdup(buf);
1107 } else {
1108 /* no id supplied -> create one */
1109 dinfo->id = qemu_mallocz(32);
1110 if (type == IF_IDE || type == IF_SCSI)
1111 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1112 if (max_devs)
1113 snprintf(dinfo->id, 32, "%s%i%s%i",
1114 devname, bus_id, mediastr, unit_id);
1115 else
1116 snprintf(dinfo->id, 32, "%s%s%i",
1117 devname, mediastr, unit_id);
1119 dinfo->bdrv = bdrv_new(dinfo->id);
1120 dinfo->devaddr = devaddr;
1121 dinfo->type = type;
1122 dinfo->bus = bus_id;
1123 dinfo->unit = unit_id;
1124 dinfo->on_read_error = on_read_error;
1125 dinfo->on_write_error = on_write_error;
1126 dinfo->opts = opts;
1127 if (serial)
1128 strncpy(dinfo->serial, serial, sizeof(serial));
1129 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1131 switch(type) {
1132 case IF_IDE:
1133 case IF_SCSI:
1134 case IF_XEN:
1135 case IF_NONE:
1136 switch(media) {
1137 case MEDIA_DISK:
1138 if (cyls != 0) {
1139 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1140 bdrv_set_translation_hint(dinfo->bdrv, translation);
1142 break;
1143 case MEDIA_CDROM:
1144 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1145 break;
1147 break;
1148 case IF_SD:
1149 /* FIXME: This isn't really a floppy, but it's a reasonable
1150 approximation. */
1151 case IF_FLOPPY:
1152 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1153 break;
1154 case IF_PFLASH:
1155 case IF_MTD:
1156 break;
1157 case IF_VIRTIO:
1158 /* add virtio block device */
1159 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1160 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1161 qemu_opt_set(opts, "drive", dinfo->id);
1162 if (devaddr)
1163 qemu_opt_set(opts, "addr", devaddr);
1164 break;
1165 case IF_COUNT:
1166 abort();
1168 if (!file) {
1169 *fatal_error = 0;
1170 return NULL;
1172 bdrv_flags = 0;
1173 if (snapshot) {
1174 bdrv_flags |= BDRV_O_SNAPSHOT;
1175 cache = 2; /* always use write-back with snapshot */
1177 if (cache == 0) /* no caching */
1178 bdrv_flags |= BDRV_O_NOCACHE;
1179 else if (cache == 2) /* write-back */
1180 bdrv_flags |= BDRV_O_CACHE_WB;
1182 if (aio == 1) {
1183 bdrv_flags |= BDRV_O_NATIVE_AIO;
1184 } else {
1185 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1188 if (ro == 1) {
1189 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1190 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1191 return NULL;
1195 * cdrom is read-only. Set it now, after above interface checking
1196 * since readonly attribute not explicitly required, so no error.
1198 if (media == MEDIA_CDROM) {
1199 ro = 1;
1201 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1203 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1204 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1205 file, strerror(errno));
1206 return NULL;
1209 if (bdrv_key_required(dinfo->bdrv))
1210 autostart = 0;
1211 *fatal_error = 0;
1212 return dinfo;
1215 static int drive_init_func(QemuOpts *opts, void *opaque)
1217 QEMUMachine *machine = opaque;
1218 int fatal_error = 0;
1220 if (drive_init(opts, machine, &fatal_error) == NULL) {
1221 if (fatal_error)
1222 return 1;
1224 return 0;
1227 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1229 if (NULL == qemu_opt_get(opts, "snapshot")) {
1230 qemu_opt_set(opts, "snapshot", "on");
1232 return 0;
1235 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1237 boot_set_handler = func;
1238 boot_set_opaque = opaque;
1241 int qemu_boot_set(const char *boot_devices)
1243 if (!boot_set_handler) {
1244 return -EINVAL;
1246 return boot_set_handler(boot_set_opaque, boot_devices);
1249 static int parse_bootdevices(char *devices)
1251 /* We just do some generic consistency checks */
1252 const char *p;
1253 int bitmap = 0;
1255 for (p = devices; *p != '\0'; p++) {
1256 /* Allowed boot devices are:
1257 * a-b: floppy disk drives
1258 * c-f: IDE disk drives
1259 * g-m: machine implementation dependant drives
1260 * n-p: network devices
1261 * It's up to each machine implementation to check if the given boot
1262 * devices match the actual hardware implementation and firmware
1263 * features.
1265 if (*p < 'a' || *p > 'p') {
1266 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1267 exit(1);
1269 if (bitmap & (1 << (*p - 'a'))) {
1270 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1271 exit(1);
1273 bitmap |= 1 << (*p - 'a');
1275 return bitmap;
1278 static void restore_boot_devices(void *opaque)
1280 char *standard_boot_devices = opaque;
1282 qemu_boot_set(standard_boot_devices);
1284 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1285 qemu_free(standard_boot_devices);
1288 static void numa_add(const char *optarg)
1290 char option[128];
1291 char *endptr;
1292 unsigned long long value, endvalue;
1293 int nodenr;
1295 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1296 if (!strcmp(option, "node")) {
1297 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1298 nodenr = nb_numa_nodes;
1299 } else {
1300 nodenr = strtoull(option, NULL, 10);
1303 if (get_param_value(option, 128, "mem", optarg) == 0) {
1304 node_mem[nodenr] = 0;
1305 } else {
1306 value = strtoull(option, &endptr, 0);
1307 switch (*endptr) {
1308 case 0: case 'M': case 'm':
1309 value <<= 20;
1310 break;
1311 case 'G': case 'g':
1312 value <<= 30;
1313 break;
1315 node_mem[nodenr] = value;
1317 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1318 node_cpumask[nodenr] = 0;
1319 } else {
1320 value = strtoull(option, &endptr, 10);
1321 if (value >= 64) {
1322 value = 63;
1323 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1324 } else {
1325 if (*endptr == '-') {
1326 endvalue = strtoull(endptr+1, &endptr, 10);
1327 if (endvalue >= 63) {
1328 endvalue = 62;
1329 fprintf(stderr,
1330 "only 63 CPUs in NUMA mode supported.\n");
1332 value = (2ULL << endvalue) - (1ULL << value);
1333 } else {
1334 value = 1ULL << value;
1337 node_cpumask[nodenr] = value;
1339 nb_numa_nodes++;
1341 return;
1344 static void smp_parse(const char *optarg)
1346 int smp, sockets = 0, threads = 0, cores = 0;
1347 char *endptr;
1348 char option[128];
1350 smp = strtoul(optarg, &endptr, 10);
1351 if (endptr != optarg) {
1352 if (*endptr == ',') {
1353 endptr++;
1356 if (get_param_value(option, 128, "sockets", endptr) != 0)
1357 sockets = strtoull(option, NULL, 10);
1358 if (get_param_value(option, 128, "cores", endptr) != 0)
1359 cores = strtoull(option, NULL, 10);
1360 if (get_param_value(option, 128, "threads", endptr) != 0)
1361 threads = strtoull(option, NULL, 10);
1362 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1363 max_cpus = strtoull(option, NULL, 10);
1365 /* compute missing values, prefer sockets over cores over threads */
1366 if (smp == 0 || sockets == 0) {
1367 sockets = sockets > 0 ? sockets : 1;
1368 cores = cores > 0 ? cores : 1;
1369 threads = threads > 0 ? threads : 1;
1370 if (smp == 0) {
1371 smp = cores * threads * sockets;
1373 } else {
1374 if (cores == 0) {
1375 threads = threads > 0 ? threads : 1;
1376 cores = smp / (sockets * threads);
1377 } else {
1378 if (sockets) {
1379 threads = smp / (cores * sockets);
1383 smp_cpus = smp;
1384 smp_cores = cores > 0 ? cores : 1;
1385 smp_threads = threads > 0 ? threads : 1;
1386 if (max_cpus == 0)
1387 max_cpus = smp_cpus;
1390 /***********************************************************/
1391 /* USB devices */
1393 static int usb_device_add(const char *devname, int is_hotplug)
1395 const char *p;
1396 USBDevice *dev = NULL;
1398 if (!usb_enabled)
1399 return -1;
1401 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1402 dev = usbdevice_create(devname);
1403 if (dev)
1404 goto done;
1406 /* the other ones */
1407 if (strstart(devname, "host:", &p)) {
1408 dev = usb_host_device_open(p);
1409 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1410 dev = usb_bt_init(devname[2] ? hci_init(p) :
1411 bt_new_hci(qemu_find_bt_vlan(0)));
1412 } else {
1413 return -1;
1415 if (!dev)
1416 return -1;
1418 done:
1419 return 0;
1422 static int usb_device_del(const char *devname)
1424 int bus_num, addr;
1425 const char *p;
1427 if (strstart(devname, "host:", &p))
1428 return usb_host_device_close(p);
1430 if (!usb_enabled)
1431 return -1;
1433 p = strchr(devname, '.');
1434 if (!p)
1435 return -1;
1436 bus_num = strtoul(devname, NULL, 0);
1437 addr = strtoul(p + 1, NULL, 0);
1439 return usb_device_delete_addr(bus_num, addr);
1442 static int usb_parse(const char *cmdline)
1444 int r;
1445 r = usb_device_add(cmdline, 0);
1446 if (r < 0) {
1447 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1449 return r;
1452 void do_usb_add(Monitor *mon, const QDict *qdict)
1454 const char *devname = qdict_get_str(qdict, "devname");
1455 if (usb_device_add(devname, 1) < 0) {
1456 error_report("could not add USB device '%s'", devname);
1460 void do_usb_del(Monitor *mon, const QDict *qdict)
1462 const char *devname = qdict_get_str(qdict, "devname");
1463 if (usb_device_del(devname) < 0) {
1464 error_report("could not delete USB device '%s'", devname);
1468 /***********************************************************/
1469 /* PCMCIA/Cardbus */
1471 static struct pcmcia_socket_entry_s {
1472 PCMCIASocket *socket;
1473 struct pcmcia_socket_entry_s *next;
1474 } *pcmcia_sockets = 0;
1476 void pcmcia_socket_register(PCMCIASocket *socket)
1478 struct pcmcia_socket_entry_s *entry;
1480 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1481 entry->socket = socket;
1482 entry->next = pcmcia_sockets;
1483 pcmcia_sockets = entry;
1486 void pcmcia_socket_unregister(PCMCIASocket *socket)
1488 struct pcmcia_socket_entry_s *entry, **ptr;
1490 ptr = &pcmcia_sockets;
1491 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1492 if (entry->socket == socket) {
1493 *ptr = entry->next;
1494 qemu_free(entry);
1498 void pcmcia_info(Monitor *mon)
1500 struct pcmcia_socket_entry_s *iter;
1502 if (!pcmcia_sockets)
1503 monitor_printf(mon, "No PCMCIA sockets\n");
1505 for (iter = pcmcia_sockets; iter; iter = iter->next)
1506 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1507 iter->socket->attached ? iter->socket->card_string :
1508 "Empty");
1511 /***********************************************************/
1512 /* I/O handling */
1514 typedef struct IOHandlerRecord {
1515 int fd;
1516 IOCanReadHandler *fd_read_poll;
1517 IOHandler *fd_read;
1518 IOHandler *fd_write;
1519 int deleted;
1520 void *opaque;
1521 /* temporary data */
1522 struct pollfd *ufd;
1523 QLIST_ENTRY(IOHandlerRecord) next;
1524 } IOHandlerRecord;
1526 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1527 QLIST_HEAD_INITIALIZER(io_handlers);
1530 /* XXX: fd_read_poll should be suppressed, but an API change is
1531 necessary in the character devices to suppress fd_can_read(). */
1532 int qemu_set_fd_handler2(int fd,
1533 IOCanReadHandler *fd_read_poll,
1534 IOHandler *fd_read,
1535 IOHandler *fd_write,
1536 void *opaque)
1538 IOHandlerRecord *ioh;
1540 if (!fd_read && !fd_write) {
1541 QLIST_FOREACH(ioh, &io_handlers, next) {
1542 if (ioh->fd == fd) {
1543 ioh->deleted = 1;
1544 break;
1547 } else {
1548 QLIST_FOREACH(ioh, &io_handlers, next) {
1549 if (ioh->fd == fd)
1550 goto found;
1552 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1553 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1554 found:
1555 ioh->fd = fd;
1556 ioh->fd_read_poll = fd_read_poll;
1557 ioh->fd_read = fd_read;
1558 ioh->fd_write = fd_write;
1559 ioh->opaque = opaque;
1560 ioh->deleted = 0;
1562 return 0;
1565 int qemu_set_fd_handler(int fd,
1566 IOHandler *fd_read,
1567 IOHandler *fd_write,
1568 void *opaque)
1570 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1573 #ifdef _WIN32
1574 /***********************************************************/
1575 /* Polling handling */
1577 typedef struct PollingEntry {
1578 PollingFunc *func;
1579 void *opaque;
1580 struct PollingEntry *next;
1581 } PollingEntry;
1583 static PollingEntry *first_polling_entry;
1585 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1587 PollingEntry **ppe, *pe;
1588 pe = qemu_mallocz(sizeof(PollingEntry));
1589 pe->func = func;
1590 pe->opaque = opaque;
1591 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1592 *ppe = pe;
1593 return 0;
1596 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1598 PollingEntry **ppe, *pe;
1599 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1600 pe = *ppe;
1601 if (pe->func == func && pe->opaque == opaque) {
1602 *ppe = pe->next;
1603 qemu_free(pe);
1604 break;
1609 /***********************************************************/
1610 /* Wait objects support */
1611 typedef struct WaitObjects {
1612 int num;
1613 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1614 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1615 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1616 } WaitObjects;
1618 static WaitObjects wait_objects = {0};
1620 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1622 WaitObjects *w = &wait_objects;
1624 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1625 return -1;
1626 w->events[w->num] = handle;
1627 w->func[w->num] = func;
1628 w->opaque[w->num] = opaque;
1629 w->num++;
1630 return 0;
1633 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1635 int i, found;
1636 WaitObjects *w = &wait_objects;
1638 found = 0;
1639 for (i = 0; i < w->num; i++) {
1640 if (w->events[i] == handle)
1641 found = 1;
1642 if (found) {
1643 w->events[i] = w->events[i + 1];
1644 w->func[i] = w->func[i + 1];
1645 w->opaque[i] = w->opaque[i + 1];
1648 if (found)
1649 w->num--;
1651 #endif
1653 /***********************************************************/
1654 /* machine registration */
1656 static QEMUMachine *first_machine = NULL;
1657 QEMUMachine *current_machine = NULL;
1659 int qemu_register_machine(QEMUMachine *m)
1661 QEMUMachine **pm;
1662 pm = &first_machine;
1663 while (*pm != NULL)
1664 pm = &(*pm)->next;
1665 m->next = NULL;
1666 *pm = m;
1667 return 0;
1670 static QEMUMachine *find_machine(const char *name)
1672 QEMUMachine *m;
1674 for(m = first_machine; m != NULL; m = m->next) {
1675 if (!strcmp(m->name, name))
1676 return m;
1677 if (m->alias && !strcmp(m->alias, name))
1678 return m;
1680 return NULL;
1683 static QEMUMachine *find_default_machine(void)
1685 QEMUMachine *m;
1687 for(m = first_machine; m != NULL; m = m->next) {
1688 if (m->is_default) {
1689 return m;
1692 return NULL;
1695 /***********************************************************/
1696 /* main execution loop */
1698 static void gui_update(void *opaque)
1700 uint64_t interval = GUI_REFRESH_INTERVAL;
1701 DisplayState *ds = opaque;
1702 DisplayChangeListener *dcl = ds->listeners;
1704 qemu_flush_coalesced_mmio_buffer();
1705 dpy_refresh(ds);
1707 while (dcl != NULL) {
1708 if (dcl->gui_timer_interval &&
1709 dcl->gui_timer_interval < interval)
1710 interval = dcl->gui_timer_interval;
1711 dcl = dcl->next;
1713 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1716 static void nographic_update(void *opaque)
1718 uint64_t interval = GUI_REFRESH_INTERVAL;
1720 qemu_flush_coalesced_mmio_buffer();
1721 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1724 struct vm_change_state_entry {
1725 VMChangeStateHandler *cb;
1726 void *opaque;
1727 QLIST_ENTRY (vm_change_state_entry) entries;
1730 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1732 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1733 void *opaque)
1735 VMChangeStateEntry *e;
1737 e = qemu_mallocz(sizeof (*e));
1739 e->cb = cb;
1740 e->opaque = opaque;
1741 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1742 return e;
1745 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1747 QLIST_REMOVE (e, entries);
1748 qemu_free (e);
1751 void vm_state_notify(int running, int reason)
1753 VMChangeStateEntry *e;
1755 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1756 e->cb(e->opaque, running, reason);
1760 void vm_start(void)
1762 if (!vm_running) {
1763 cpu_enable_ticks();
1764 vm_running = 1;
1765 vm_state_notify(1, 0);
1766 resume_all_vcpus();
1770 /* reset/shutdown handler */
1772 typedef struct QEMUResetEntry {
1773 QTAILQ_ENTRY(QEMUResetEntry) entry;
1774 QEMUResetHandler *func;
1775 void *opaque;
1776 } QEMUResetEntry;
1778 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1779 QTAILQ_HEAD_INITIALIZER(reset_handlers);
1780 static int reset_requested;
1781 static int shutdown_requested;
1782 static int powerdown_requested;
1783 int debug_requested;
1784 static int vmstop_requested;
1786 int qemu_shutdown_requested(void)
1788 int r = shutdown_requested;
1789 shutdown_requested = 0;
1790 return r;
1793 int qemu_reset_requested(void)
1795 int r = reset_requested;
1796 reset_requested = 0;
1797 return r;
1800 int qemu_powerdown_requested(void)
1802 int r = powerdown_requested;
1803 powerdown_requested = 0;
1804 return r;
1807 static int qemu_debug_requested(void)
1809 int r = debug_requested;
1810 debug_requested = 0;
1811 return r;
1814 static int qemu_vmstop_requested(void)
1816 int r = vmstop_requested;
1817 vmstop_requested = 0;
1818 return r;
1821 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1823 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
1825 re->func = func;
1826 re->opaque = opaque;
1827 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1830 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1832 QEMUResetEntry *re;
1834 QTAILQ_FOREACH(re, &reset_handlers, entry) {
1835 if (re->func == func && re->opaque == opaque) {
1836 QTAILQ_REMOVE(&reset_handlers, re, entry);
1837 qemu_free(re);
1838 return;
1843 void qemu_system_reset(void)
1845 QEMUResetEntry *re, *nre;
1847 /* reset all devices */
1848 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1849 re->func(re->opaque);
1851 monitor_protocol_event(QEVENT_RESET, NULL);
1852 cpu_synchronize_all_post_reset();
1855 void qemu_system_reset_request(void)
1857 if (no_reboot) {
1858 shutdown_requested = 1;
1859 } else {
1860 reset_requested = 1;
1862 qemu_notify_event();
1865 void qemu_system_shutdown_request(void)
1867 shutdown_requested = 1;
1868 qemu_notify_event();
1871 void qemu_system_powerdown_request(void)
1873 powerdown_requested = 1;
1874 qemu_notify_event();
1877 #ifdef _WIN32
1878 static void host_main_loop_wait(int *timeout)
1880 int ret, ret2, i;
1881 PollingEntry *pe;
1884 /* XXX: need to suppress polling by better using win32 events */
1885 ret = 0;
1886 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
1887 ret |= pe->func(pe->opaque);
1889 if (ret == 0) {
1890 int err;
1891 WaitObjects *w = &wait_objects;
1893 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
1894 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
1895 if (w->func[ret - WAIT_OBJECT_0])
1896 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
1898 /* Check for additional signaled events */
1899 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
1901 /* Check if event is signaled */
1902 ret2 = WaitForSingleObject(w->events[i], 0);
1903 if(ret2 == WAIT_OBJECT_0) {
1904 if (w->func[i])
1905 w->func[i](w->opaque[i]);
1906 } else if (ret2 == WAIT_TIMEOUT) {
1907 } else {
1908 err = GetLastError();
1909 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
1912 } else if (ret == WAIT_TIMEOUT) {
1913 } else {
1914 err = GetLastError();
1915 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
1919 *timeout = 0;
1921 #else
1922 static void host_main_loop_wait(int *timeout)
1925 #endif
1927 void main_loop_wait(int nonblocking)
1929 IOHandlerRecord *ioh;
1930 fd_set rfds, wfds, xfds;
1931 int ret, nfds;
1932 struct timeval tv;
1933 int timeout;
1935 if (nonblocking)
1936 timeout = 0;
1937 else {
1938 timeout = qemu_calculate_timeout();
1939 qemu_bh_update_timeout(&timeout);
1942 host_main_loop_wait(&timeout);
1944 /* poll any events */
1945 /* XXX: separate device handlers from system ones */
1946 nfds = -1;
1947 FD_ZERO(&rfds);
1948 FD_ZERO(&wfds);
1949 FD_ZERO(&xfds);
1950 QLIST_FOREACH(ioh, &io_handlers, next) {
1951 if (ioh->deleted)
1952 continue;
1953 if (ioh->fd_read &&
1954 (!ioh->fd_read_poll ||
1955 ioh->fd_read_poll(ioh->opaque) != 0)) {
1956 FD_SET(ioh->fd, &rfds);
1957 if (ioh->fd > nfds)
1958 nfds = ioh->fd;
1960 if (ioh->fd_write) {
1961 FD_SET(ioh->fd, &wfds);
1962 if (ioh->fd > nfds)
1963 nfds = ioh->fd;
1967 tv.tv_sec = timeout / 1000;
1968 tv.tv_usec = (timeout % 1000) * 1000;
1970 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1972 qemu_mutex_unlock_iothread();
1973 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1974 qemu_mutex_lock_iothread();
1975 if (ret > 0) {
1976 IOHandlerRecord *pioh;
1978 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
1979 if (ioh->deleted) {
1980 QLIST_REMOVE(ioh, next);
1981 qemu_free(ioh);
1982 continue;
1984 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
1985 ioh->fd_read(ioh->opaque);
1987 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
1988 ioh->fd_write(ioh->opaque);
1993 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1995 qemu_run_all_timers();
1997 /* Check bottom-halves last in case any of the earlier events triggered
1998 them. */
1999 qemu_bh_poll();
2003 static int vm_can_run(void)
2005 if (powerdown_requested)
2006 return 0;
2007 if (reset_requested)
2008 return 0;
2009 if (shutdown_requested)
2010 return 0;
2011 if (debug_requested)
2012 return 0;
2013 return 1;
2016 qemu_irq qemu_system_powerdown;
2018 static void main_loop(void)
2020 int r;
2022 #ifdef CONFIG_IOTHREAD
2023 qemu_system_ready = 1;
2024 qemu_cond_broadcast(&qemu_system_cond);
2025 #endif
2027 for (;;) {
2028 do {
2029 bool nonblocking = false;
2030 #ifdef CONFIG_PROFILER
2031 int64_t ti;
2032 #endif
2033 #ifndef CONFIG_IOTHREAD
2034 nonblocking = tcg_cpu_exec();
2035 #endif
2036 #ifdef CONFIG_PROFILER
2037 ti = profile_getclock();
2038 #endif
2039 main_loop_wait(nonblocking);
2040 #ifdef CONFIG_PROFILER
2041 dev_time += profile_getclock() - ti;
2042 #endif
2043 } while (vm_can_run());
2045 if ((r = qemu_debug_requested())) {
2046 vm_stop(r);
2048 if (qemu_shutdown_requested()) {
2049 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2050 if (no_shutdown) {
2051 vm_stop(0);
2052 no_shutdown = 0;
2053 } else
2054 break;
2056 if (qemu_reset_requested()) {
2057 pause_all_vcpus();
2058 qemu_system_reset();
2059 resume_all_vcpus();
2061 if (qemu_powerdown_requested()) {
2062 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
2063 qemu_irq_raise(qemu_system_powerdown);
2065 if ((r = qemu_vmstop_requested())) {
2066 vm_stop(r);
2069 pause_all_vcpus();
2072 static void version(void)
2074 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
2077 static void help(int exitcode)
2079 const char *options_help =
2080 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2081 opt_help
2082 #define DEFHEADING(text) stringify(text) "\n"
2083 #include "qemu-options.h"
2084 #undef DEF
2085 #undef DEFHEADING
2086 #undef GEN_DOCS
2088 version();
2089 printf("usage: %s [options] [disk_image]\n"
2090 "\n"
2091 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2092 "\n"
2093 "%s\n"
2094 "During emulation, the following keys are useful:\n"
2095 "ctrl-alt-f toggle full screen\n"
2096 "ctrl-alt-n switch to virtual console 'n'\n"
2097 "ctrl-alt toggle mouse and keyboard grab\n"
2098 "\n"
2099 "When using -nographic, press 'ctrl-a h' to get some help.\n",
2100 "qemu",
2101 options_help);
2102 exit(exitcode);
2105 #define HAS_ARG 0x0001
2107 enum {
2108 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2109 opt_enum,
2110 #define DEFHEADING(text)
2111 #include "qemu-options.h"
2112 #undef DEF
2113 #undef DEFHEADING
2114 #undef GEN_DOCS
2117 typedef struct QEMUOption {
2118 const char *name;
2119 int flags;
2120 int index;
2121 uint32_t arch_mask;
2122 } QEMUOption;
2124 static const QEMUOption qemu_options[] = {
2125 { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
2126 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2127 { option, opt_arg, opt_enum, arch_mask },
2128 #define DEFHEADING(text)
2129 #include "qemu-options.h"
2130 #undef DEF
2131 #undef DEFHEADING
2132 #undef GEN_DOCS
2133 { NULL },
2135 static void select_vgahw (const char *p)
2137 const char *opts;
2139 default_vga = 0;
2140 vga_interface_type = VGA_NONE;
2141 if (strstart(p, "std", &opts)) {
2142 vga_interface_type = VGA_STD;
2143 } else if (strstart(p, "cirrus", &opts)) {
2144 vga_interface_type = VGA_CIRRUS;
2145 } else if (strstart(p, "vmware", &opts)) {
2146 vga_interface_type = VGA_VMWARE;
2147 } else if (strstart(p, "xenfb", &opts)) {
2148 vga_interface_type = VGA_XENFB;
2149 } else if (!strstart(p, "none", &opts)) {
2150 invalid_vga:
2151 fprintf(stderr, "Unknown vga type: %s\n", p);
2152 exit(1);
2154 while (*opts) {
2155 const char *nextopt;
2157 if (strstart(opts, ",retrace=", &nextopt)) {
2158 opts = nextopt;
2159 if (strstart(opts, "dumb", &nextopt))
2160 vga_retrace_method = VGA_RETRACE_DUMB;
2161 else if (strstart(opts, "precise", &nextopt))
2162 vga_retrace_method = VGA_RETRACE_PRECISE;
2163 else goto invalid_vga;
2164 } else goto invalid_vga;
2165 opts = nextopt;
2169 static int balloon_parse(const char *arg)
2171 QemuOpts *opts;
2173 if (strcmp(arg, "none") == 0) {
2174 return 0;
2177 if (!strncmp(arg, "virtio", 6)) {
2178 if (arg[6] == ',') {
2179 /* have params -> parse them */
2180 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
2181 if (!opts)
2182 return -1;
2183 } else {
2184 /* create empty opts */
2185 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2187 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
2188 return 0;
2191 return -1;
2194 #ifdef _WIN32
2195 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
2197 exit(STATUS_CONTROL_C_EXIT);
2198 return TRUE;
2200 #endif
2202 #ifndef _WIN32
2204 static void termsig_handler(int signal)
2206 qemu_system_shutdown_request();
2209 static void sigchld_handler(int signal)
2211 waitpid(-1, NULL, WNOHANG);
2214 static void sighandler_setup(void)
2216 struct sigaction act;
2218 memset(&act, 0, sizeof(act));
2219 act.sa_handler = termsig_handler;
2220 sigaction(SIGINT, &act, NULL);
2221 sigaction(SIGHUP, &act, NULL);
2222 sigaction(SIGTERM, &act, NULL);
2224 act.sa_handler = sigchld_handler;
2225 act.sa_flags = SA_NOCLDSTOP;
2226 sigaction(SIGCHLD, &act, NULL);
2229 #endif
2231 #ifdef _WIN32
2232 /* Look for support files in the same directory as the executable. */
2233 static char *find_datadir(const char *argv0)
2235 char *p;
2236 char buf[MAX_PATH];
2237 DWORD len;
2239 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
2240 if (len == 0) {
2241 return NULL;
2244 buf[len] = 0;
2245 p = buf + len - 1;
2246 while (p != buf && *p != '\\')
2247 p--;
2248 *p = 0;
2249 if (access(buf, R_OK) == 0) {
2250 return qemu_strdup(buf);
2252 return NULL;
2254 #else /* !_WIN32 */
2256 /* Find a likely location for support files using the location of the binary.
2257 For installed binaries this will be "$bindir/../share/qemu". When
2258 running from the build tree this will be "$bindir/../pc-bios". */
2259 #define SHARE_SUFFIX "/share/qemu"
2260 #define BUILD_SUFFIX "/pc-bios"
2261 static char *find_datadir(const char *argv0)
2263 char *dir;
2264 char *p = NULL;
2265 char *res;
2266 char buf[PATH_MAX];
2267 size_t max_len;
2269 #if defined(__linux__)
2271 int len;
2272 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
2273 if (len > 0) {
2274 buf[len] = 0;
2275 p = buf;
2278 #elif defined(__FreeBSD__)
2280 static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
2281 size_t len = sizeof(buf) - 1;
2283 *buf = '\0';
2284 if (!sysctl(mib, sizeof(mib)/sizeof(*mib), buf, &len, NULL, 0) &&
2285 *buf) {
2286 buf[sizeof(buf) - 1] = '\0';
2287 p = buf;
2290 #endif
2291 /* If we don't have any way of figuring out the actual executable
2292 location then try argv[0]. */
2293 if (!p) {
2294 p = realpath(argv0, buf);
2295 if (!p) {
2296 return NULL;
2299 dir = dirname(p);
2300 dir = dirname(dir);
2302 max_len = strlen(dir) +
2303 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
2304 res = qemu_mallocz(max_len);
2305 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
2306 if (access(res, R_OK)) {
2307 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
2308 if (access(res, R_OK)) {
2309 qemu_free(res);
2310 res = NULL;
2314 return res;
2316 #undef SHARE_SUFFIX
2317 #undef BUILD_SUFFIX
2318 #endif
2320 char *qemu_find_file(int type, const char *name)
2322 int len;
2323 const char *subdir;
2324 char *buf;
2326 /* If name contains path separators then try it as a straight path. */
2327 if ((strchr(name, '/') || strchr(name, '\\'))
2328 && access(name, R_OK) == 0) {
2329 return qemu_strdup(name);
2331 switch (type) {
2332 case QEMU_FILE_TYPE_BIOS:
2333 subdir = "";
2334 break;
2335 case QEMU_FILE_TYPE_KEYMAP:
2336 subdir = "keymaps/";
2337 break;
2338 default:
2339 abort();
2341 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
2342 buf = qemu_mallocz(len);
2343 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
2344 if (access(buf, R_OK)) {
2345 qemu_free(buf);
2346 return NULL;
2348 return buf;
2351 static int device_help_func(QemuOpts *opts, void *opaque)
2353 return qdev_device_help(opts);
2356 static int device_init_func(QemuOpts *opts, void *opaque)
2358 DeviceState *dev;
2360 dev = qdev_device_add(opts);
2361 if (!dev)
2362 return -1;
2363 return 0;
2366 static int chardev_init_func(QemuOpts *opts, void *opaque)
2368 CharDriverState *chr;
2370 chr = qemu_chr_open_opts(opts, NULL);
2371 if (!chr)
2372 return -1;
2373 return 0;
2376 static int mon_init_func(QemuOpts *opts, void *opaque)
2378 CharDriverState *chr;
2379 const char *chardev;
2380 const char *mode;
2381 int flags;
2383 mode = qemu_opt_get(opts, "mode");
2384 if (mode == NULL) {
2385 mode = "readline";
2387 if (strcmp(mode, "readline") == 0) {
2388 flags = MONITOR_USE_READLINE;
2389 } else if (strcmp(mode, "control") == 0) {
2390 flags = MONITOR_USE_CONTROL;
2391 } else {
2392 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2393 exit(1);
2396 if (qemu_opt_get_bool(opts, "default", 0))
2397 flags |= MONITOR_IS_DEFAULT;
2399 chardev = qemu_opt_get(opts, "chardev");
2400 chr = qemu_chr_find(chardev);
2401 if (chr == NULL) {
2402 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2403 exit(1);
2406 monitor_init(chr, flags);
2407 return 0;
2410 static void monitor_parse(const char *optarg, const char *mode)
2412 static int monitor_device_index = 0;
2413 QemuOpts *opts;
2414 const char *p;
2415 char label[32];
2416 int def = 0;
2418 if (strstart(optarg, "chardev:", &p)) {
2419 snprintf(label, sizeof(label), "%s", p);
2420 } else {
2421 if (monitor_device_index) {
2422 snprintf(label, sizeof(label), "monitor%d",
2423 monitor_device_index);
2424 } else {
2425 snprintf(label, sizeof(label), "monitor");
2426 def = 1;
2428 opts = qemu_chr_parse_compat(label, optarg);
2429 if (!opts) {
2430 fprintf(stderr, "parse error: %s\n", optarg);
2431 exit(1);
2435 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
2436 if (!opts) {
2437 fprintf(stderr, "duplicate chardev: %s\n", label);
2438 exit(1);
2440 qemu_opt_set(opts, "mode", mode);
2441 qemu_opt_set(opts, "chardev", label);
2442 if (def)
2443 qemu_opt_set(opts, "default", "on");
2444 monitor_device_index++;
2447 struct device_config {
2448 enum {
2449 DEV_USB, /* -usbdevice */
2450 DEV_BT, /* -bt */
2451 DEV_SERIAL, /* -serial */
2452 DEV_PARALLEL, /* -parallel */
2453 DEV_VIRTCON, /* -virtioconsole */
2454 DEV_DEBUGCON, /* -debugcon */
2455 } type;
2456 const char *cmdline;
2457 QTAILQ_ENTRY(device_config) next;
2459 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
2461 static void add_device_config(int type, const char *cmdline)
2463 struct device_config *conf;
2465 conf = qemu_mallocz(sizeof(*conf));
2466 conf->type = type;
2467 conf->cmdline = cmdline;
2468 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2471 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2473 struct device_config *conf;
2474 int rc;
2476 QTAILQ_FOREACH(conf, &device_configs, next) {
2477 if (conf->type != type)
2478 continue;
2479 rc = func(conf->cmdline);
2480 if (0 != rc)
2481 return rc;
2483 return 0;
2486 static int serial_parse(const char *devname)
2488 static int index = 0;
2489 char label[32];
2491 if (strcmp(devname, "none") == 0)
2492 return 0;
2493 if (index == MAX_SERIAL_PORTS) {
2494 fprintf(stderr, "qemu: too many serial ports\n");
2495 exit(1);
2497 snprintf(label, sizeof(label), "serial%d", index);
2498 serial_hds[index] = qemu_chr_open(label, devname, NULL);
2499 if (!serial_hds[index]) {
2500 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
2501 devname, strerror(errno));
2502 return -1;
2504 index++;
2505 return 0;
2508 static int parallel_parse(const char *devname)
2510 static int index = 0;
2511 char label[32];
2513 if (strcmp(devname, "none") == 0)
2514 return 0;
2515 if (index == MAX_PARALLEL_PORTS) {
2516 fprintf(stderr, "qemu: too many parallel ports\n");
2517 exit(1);
2519 snprintf(label, sizeof(label), "parallel%d", index);
2520 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
2521 if (!parallel_hds[index]) {
2522 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2523 devname, strerror(errno));
2524 return -1;
2526 index++;
2527 return 0;
2530 static int virtcon_parse(const char *devname)
2532 static int index = 0;
2533 char label[32];
2534 QemuOpts *bus_opts, *dev_opts;
2536 if (strcmp(devname, "none") == 0)
2537 return 0;
2538 if (index == MAX_VIRTIO_CONSOLES) {
2539 fprintf(stderr, "qemu: too many virtio consoles\n");
2540 exit(1);
2543 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2544 qemu_opt_set(bus_opts, "driver", "virtio-serial");
2546 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2547 qemu_opt_set(dev_opts, "driver", "virtconsole");
2549 snprintf(label, sizeof(label), "virtcon%d", index);
2550 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
2551 if (!virtcon_hds[index]) {
2552 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2553 devname, strerror(errno));
2554 return -1;
2556 qemu_opt_set(dev_opts, "chardev", label);
2558 index++;
2559 return 0;
2562 static int debugcon_parse(const char *devname)
2564 QemuOpts *opts;
2566 if (!qemu_chr_open("debugcon", devname, NULL)) {
2567 exit(1);
2569 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
2570 if (!opts) {
2571 fprintf(stderr, "qemu: already have a debugcon device\n");
2572 exit(1);
2574 qemu_opt_set(opts, "driver", "isa-debugcon");
2575 qemu_opt_set(opts, "chardev", "debugcon");
2576 return 0;
2579 static const QEMUOption *lookup_opt(int argc, char **argv,
2580 const char **poptarg, int *poptind)
2582 const QEMUOption *popt;
2583 int optind = *poptind;
2584 char *r = argv[optind];
2585 const char *optarg;
2587 loc_set_cmdline(argv, optind, 1);
2588 optind++;
2589 /* Treat --foo the same as -foo. */
2590 if (r[1] == '-')
2591 r++;
2592 popt = qemu_options;
2593 for(;;) {
2594 if (!popt->name) {
2595 error_report("invalid option");
2596 exit(1);
2598 if (!strcmp(popt->name, r + 1))
2599 break;
2600 popt++;
2602 if (popt->flags & HAS_ARG) {
2603 if (optind >= argc) {
2604 error_report("requires an argument");
2605 exit(1);
2607 optarg = argv[optind++];
2608 loc_set_cmdline(argv, optind - 2, 2);
2609 } else {
2610 optarg = NULL;
2613 *poptarg = optarg;
2614 *poptind = optind;
2616 return popt;
2619 int main(int argc, char **argv, char **envp)
2621 const char *gdbstub_dev = NULL;
2622 uint32_t boot_devices_bitmap = 0;
2623 int i;
2624 int snapshot, linux_boot, net_boot;
2625 const char *icount_option = NULL;
2626 const char *initrd_filename;
2627 const char *kernel_filename, *kernel_cmdline;
2628 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2629 DisplayState *ds;
2630 DisplayChangeListener *dcl;
2631 int cyls, heads, secs, translation;
2632 QemuOpts *hda_opts = NULL, *opts;
2633 int optind;
2634 const char *optarg;
2635 const char *loadvm = NULL;
2636 QEMUMachine *machine;
2637 const char *cpu_model;
2638 #ifndef _WIN32
2639 int fds[2];
2640 #endif
2641 int tb_size;
2642 const char *pid_file = NULL;
2643 const char *incoming = NULL;
2644 #ifndef _WIN32
2645 int fd = 0;
2646 struct passwd *pwd = NULL;
2647 const char *chroot_dir = NULL;
2648 const char *run_as = NULL;
2649 #endif
2650 int show_vnc_port = 0;
2651 int defconfig = 1;
2653 error_set_progname(argv[0]);
2655 init_clocks();
2657 qemu_cache_utils_init(envp);
2659 QLIST_INIT (&vm_change_state_head);
2660 #ifndef _WIN32
2662 struct sigaction act;
2663 sigfillset(&act.sa_mask);
2664 act.sa_flags = 0;
2665 act.sa_handler = SIG_IGN;
2666 sigaction(SIGPIPE, &act, NULL);
2668 #else
2669 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
2670 /* Note: cpu_interrupt() is currently not SMP safe, so we force
2671 QEMU to run on a single CPU */
2673 HANDLE h;
2674 DWORD mask, smask;
2675 int i;
2676 h = GetCurrentProcess();
2677 if (GetProcessAffinityMask(h, &mask, &smask)) {
2678 for(i = 0; i < 32; i++) {
2679 if (mask & (1 << i))
2680 break;
2682 if (i != 32) {
2683 mask = 1 << i;
2684 SetProcessAffinityMask(h, mask);
2688 #endif
2690 module_call_init(MODULE_INIT_MACHINE);
2691 machine = find_default_machine();
2692 cpu_model = NULL;
2693 initrd_filename = NULL;
2694 ram_size = 0;
2695 snapshot = 0;
2696 kernel_filename = NULL;
2697 kernel_cmdline = "";
2698 cyls = heads = secs = 0;
2699 translation = BIOS_ATA_TRANSLATION_AUTO;
2701 for (i = 0; i < MAX_NODES; i++) {
2702 node_mem[i] = 0;
2703 node_cpumask[i] = 0;
2706 nb_numa_nodes = 0;
2707 nb_nics = 0;
2709 tb_size = 0;
2710 autostart= 1;
2712 /* first pass of option parsing */
2713 optind = 1;
2714 while (optind < argc) {
2715 if (argv[optind][0] != '-') {
2716 /* disk image */
2717 optind++;
2718 continue;
2719 } else {
2720 const QEMUOption *popt;
2722 popt = lookup_opt(argc, argv, &optarg, &optind);
2723 switch (popt->index) {
2724 case QEMU_OPTION_nodefconfig:
2725 defconfig=0;
2726 break;
2731 if (defconfig) {
2732 const char *fname;
2733 FILE *fp;
2735 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
2736 fp = fopen(fname, "r");
2737 if (fp) {
2738 if (qemu_config_parse(fp, fname) != 0) {
2739 exit(1);
2741 fclose(fp);
2744 fname = arch_config_name;
2745 fp = fopen(fname, "r");
2746 if (fp) {
2747 if (qemu_config_parse(fp, fname) != 0) {
2748 exit(1);
2750 fclose(fp);
2753 cpudef_init();
2755 /* second pass of option parsing */
2756 optind = 1;
2757 for(;;) {
2758 if (optind >= argc)
2759 break;
2760 if (argv[optind][0] != '-') {
2761 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
2762 } else {
2763 const QEMUOption *popt;
2765 popt = lookup_opt(argc, argv, &optarg, &optind);
2766 if (!(popt->arch_mask & arch_type)) {
2767 printf("Option %s not supported for this target\n", popt->name);
2768 exit(1);
2770 switch(popt->index) {
2771 case QEMU_OPTION_M:
2772 machine = find_machine(optarg);
2773 if (!machine) {
2774 QEMUMachine *m;
2775 printf("Supported machines are:\n");
2776 for(m = first_machine; m != NULL; m = m->next) {
2777 if (m->alias)
2778 printf("%-10s %s (alias of %s)\n",
2779 m->alias, m->desc, m->name);
2780 printf("%-10s %s%s\n",
2781 m->name, m->desc,
2782 m->is_default ? " (default)" : "");
2784 exit(*optarg != '?');
2786 break;
2787 case QEMU_OPTION_cpu:
2788 /* hw initialization will check this */
2789 if (*optarg == '?') {
2790 /* XXX: implement xxx_cpu_list for targets that still miss it */
2791 #if defined(cpu_list_id)
2792 cpu_list_id(stdout, &fprintf, optarg);
2793 #elif defined(cpu_list)
2794 cpu_list(stdout, &fprintf); /* deprecated */
2795 #endif
2796 exit(0);
2797 } else {
2798 cpu_model = optarg;
2800 break;
2801 case QEMU_OPTION_initrd:
2802 initrd_filename = optarg;
2803 break;
2804 case QEMU_OPTION_hda:
2805 if (cyls == 0)
2806 hda_opts = drive_add(optarg, HD_ALIAS, 0);
2807 else
2808 hda_opts = drive_add(optarg, HD_ALIAS
2809 ",cyls=%d,heads=%d,secs=%d%s",
2810 0, cyls, heads, secs,
2811 translation == BIOS_ATA_TRANSLATION_LBA ?
2812 ",trans=lba" :
2813 translation == BIOS_ATA_TRANSLATION_NONE ?
2814 ",trans=none" : "");
2815 break;
2816 case QEMU_OPTION_hdb:
2817 case QEMU_OPTION_hdc:
2818 case QEMU_OPTION_hdd:
2819 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
2820 break;
2821 case QEMU_OPTION_drive:
2822 drive_add(NULL, "%s", optarg);
2823 break;
2824 case QEMU_OPTION_set:
2825 if (qemu_set_option(optarg) != 0)
2826 exit(1);
2827 break;
2828 case QEMU_OPTION_global:
2829 if (qemu_global_option(optarg) != 0)
2830 exit(1);
2831 break;
2832 case QEMU_OPTION_mtdblock:
2833 drive_add(optarg, MTD_ALIAS);
2834 break;
2835 case QEMU_OPTION_sd:
2836 drive_add(optarg, SD_ALIAS);
2837 break;
2838 case QEMU_OPTION_pflash:
2839 drive_add(optarg, PFLASH_ALIAS);
2840 break;
2841 case QEMU_OPTION_snapshot:
2842 snapshot = 1;
2843 break;
2844 case QEMU_OPTION_hdachs:
2846 const char *p;
2847 p = optarg;
2848 cyls = strtol(p, (char **)&p, 0);
2849 if (cyls < 1 || cyls > 16383)
2850 goto chs_fail;
2851 if (*p != ',')
2852 goto chs_fail;
2853 p++;
2854 heads = strtol(p, (char **)&p, 0);
2855 if (heads < 1 || heads > 16)
2856 goto chs_fail;
2857 if (*p != ',')
2858 goto chs_fail;
2859 p++;
2860 secs = strtol(p, (char **)&p, 0);
2861 if (secs < 1 || secs > 63)
2862 goto chs_fail;
2863 if (*p == ',') {
2864 p++;
2865 if (!strcmp(p, "none"))
2866 translation = BIOS_ATA_TRANSLATION_NONE;
2867 else if (!strcmp(p, "lba"))
2868 translation = BIOS_ATA_TRANSLATION_LBA;
2869 else if (!strcmp(p, "auto"))
2870 translation = BIOS_ATA_TRANSLATION_AUTO;
2871 else
2872 goto chs_fail;
2873 } else if (*p != '\0') {
2874 chs_fail:
2875 fprintf(stderr, "qemu: invalid physical CHS format\n");
2876 exit(1);
2878 if (hda_opts != NULL) {
2879 char num[16];
2880 snprintf(num, sizeof(num), "%d", cyls);
2881 qemu_opt_set(hda_opts, "cyls", num);
2882 snprintf(num, sizeof(num), "%d", heads);
2883 qemu_opt_set(hda_opts, "heads", num);
2884 snprintf(num, sizeof(num), "%d", secs);
2885 qemu_opt_set(hda_opts, "secs", num);
2886 if (translation == BIOS_ATA_TRANSLATION_LBA)
2887 qemu_opt_set(hda_opts, "trans", "lba");
2888 if (translation == BIOS_ATA_TRANSLATION_NONE)
2889 qemu_opt_set(hda_opts, "trans", "none");
2892 break;
2893 case QEMU_OPTION_numa:
2894 if (nb_numa_nodes >= MAX_NODES) {
2895 fprintf(stderr, "qemu: too many NUMA nodes\n");
2896 exit(1);
2898 numa_add(optarg);
2899 break;
2900 case QEMU_OPTION_nographic:
2901 display_type = DT_NOGRAPHIC;
2902 break;
2903 #ifdef CONFIG_CURSES
2904 case QEMU_OPTION_curses:
2905 display_type = DT_CURSES;
2906 break;
2907 #endif
2908 case QEMU_OPTION_portrait:
2909 graphic_rotate = 1;
2910 break;
2911 case QEMU_OPTION_kernel:
2912 kernel_filename = optarg;
2913 break;
2914 case QEMU_OPTION_append:
2915 kernel_cmdline = optarg;
2916 break;
2917 case QEMU_OPTION_cdrom:
2918 drive_add(optarg, CDROM_ALIAS);
2919 break;
2920 case QEMU_OPTION_boot:
2922 static const char * const params[] = {
2923 "order", "once", "menu", NULL
2925 char buf[sizeof(boot_devices)];
2926 char *standard_boot_devices;
2927 int legacy = 0;
2929 if (!strchr(optarg, '=')) {
2930 legacy = 1;
2931 pstrcpy(buf, sizeof(buf), optarg);
2932 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2933 fprintf(stderr,
2934 "qemu: unknown boot parameter '%s' in '%s'\n",
2935 buf, optarg);
2936 exit(1);
2939 if (legacy ||
2940 get_param_value(buf, sizeof(buf), "order", optarg)) {
2941 boot_devices_bitmap = parse_bootdevices(buf);
2942 pstrcpy(boot_devices, sizeof(boot_devices), buf);
2944 if (!legacy) {
2945 if (get_param_value(buf, sizeof(buf),
2946 "once", optarg)) {
2947 boot_devices_bitmap |= parse_bootdevices(buf);
2948 standard_boot_devices = qemu_strdup(boot_devices);
2949 pstrcpy(boot_devices, sizeof(boot_devices), buf);
2950 qemu_register_reset(restore_boot_devices,
2951 standard_boot_devices);
2953 if (get_param_value(buf, sizeof(buf),
2954 "menu", optarg)) {
2955 if (!strcmp(buf, "on")) {
2956 boot_menu = 1;
2957 } else if (!strcmp(buf, "off")) {
2958 boot_menu = 0;
2959 } else {
2960 fprintf(stderr,
2961 "qemu: invalid option value '%s'\n",
2962 buf);
2963 exit(1);
2968 break;
2969 case QEMU_OPTION_fda:
2970 case QEMU_OPTION_fdb:
2971 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
2972 break;
2973 case QEMU_OPTION_no_fd_bootchk:
2974 fd_bootchk = 0;
2975 break;
2976 case QEMU_OPTION_netdev:
2977 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
2978 exit(1);
2980 break;
2981 case QEMU_OPTION_net:
2982 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
2983 exit(1);
2985 break;
2986 #ifdef CONFIG_SLIRP
2987 case QEMU_OPTION_tftp:
2988 legacy_tftp_prefix = optarg;
2989 break;
2990 case QEMU_OPTION_bootp:
2991 legacy_bootp_filename = optarg;
2992 break;
2993 #ifndef _WIN32
2994 case QEMU_OPTION_smb:
2995 if (net_slirp_smb(optarg) < 0)
2996 exit(1);
2997 break;
2998 #endif
2999 case QEMU_OPTION_redir:
3000 if (net_slirp_redir(optarg) < 0)
3001 exit(1);
3002 break;
3003 #endif
3004 case QEMU_OPTION_bt:
3005 add_device_config(DEV_BT, optarg);
3006 break;
3007 case QEMU_OPTION_audio_help:
3008 if (!(audio_available())) {
3009 printf("Option %s not supported for this target\n", popt->name);
3010 exit(1);
3012 AUD_help ();
3013 exit (0);
3014 break;
3015 case QEMU_OPTION_soundhw:
3016 if (!(audio_available())) {
3017 printf("Option %s not supported for this target\n", popt->name);
3018 exit(1);
3020 select_soundhw (optarg);
3021 break;
3022 case QEMU_OPTION_h:
3023 help(0);
3024 break;
3025 case QEMU_OPTION_version:
3026 version();
3027 exit(0);
3028 break;
3029 case QEMU_OPTION_m: {
3030 uint64_t value;
3031 char *ptr;
3033 value = strtoul(optarg, &ptr, 10);
3034 switch (*ptr) {
3035 case 0: case 'M': case 'm':
3036 value <<= 20;
3037 break;
3038 case 'G': case 'g':
3039 value <<= 30;
3040 break;
3041 default:
3042 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
3043 exit(1);
3046 /* On 32-bit hosts, QEMU is limited by virtual address space */
3047 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
3048 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3049 exit(1);
3051 if (value != (uint64_t)(ram_addr_t)value) {
3052 fprintf(stderr, "qemu: ram size too large\n");
3053 exit(1);
3055 ram_size = value;
3056 break;
3058 case QEMU_OPTION_mempath:
3059 mem_path = optarg;
3060 break;
3061 #ifdef MAP_POPULATE
3062 case QEMU_OPTION_mem_prealloc:
3063 mem_prealloc = 1;
3064 break;
3065 #endif
3066 case QEMU_OPTION_d:
3067 set_cpu_log(optarg);
3068 break;
3069 case QEMU_OPTION_s:
3070 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
3071 break;
3072 case QEMU_OPTION_gdb:
3073 gdbstub_dev = optarg;
3074 break;
3075 case QEMU_OPTION_L:
3076 data_dir = optarg;
3077 break;
3078 case QEMU_OPTION_bios:
3079 bios_name = optarg;
3080 break;
3081 case QEMU_OPTION_singlestep:
3082 singlestep = 1;
3083 break;
3084 case QEMU_OPTION_S:
3085 autostart = 0;
3086 break;
3087 case QEMU_OPTION_k:
3088 keyboard_layout = optarg;
3089 break;
3090 case QEMU_OPTION_localtime:
3091 rtc_utc = 0;
3092 break;
3093 case QEMU_OPTION_vga:
3094 select_vgahw (optarg);
3095 break;
3096 case QEMU_OPTION_g:
3098 const char *p;
3099 int w, h, depth;
3100 p = optarg;
3101 w = strtol(p, (char **)&p, 10);
3102 if (w <= 0) {
3103 graphic_error:
3104 fprintf(stderr, "qemu: invalid resolution or depth\n");
3105 exit(1);
3107 if (*p != 'x')
3108 goto graphic_error;
3109 p++;
3110 h = strtol(p, (char **)&p, 10);
3111 if (h <= 0)
3112 goto graphic_error;
3113 if (*p == 'x') {
3114 p++;
3115 depth = strtol(p, (char **)&p, 10);
3116 if (depth != 8 && depth != 15 && depth != 16 &&
3117 depth != 24 && depth != 32)
3118 goto graphic_error;
3119 } else if (*p == '\0') {
3120 depth = graphic_depth;
3121 } else {
3122 goto graphic_error;
3125 graphic_width = w;
3126 graphic_height = h;
3127 graphic_depth = depth;
3129 break;
3130 case QEMU_OPTION_echr:
3132 char *r;
3133 term_escape_char = strtol(optarg, &r, 0);
3134 if (r == optarg)
3135 printf("Bad argument to echr\n");
3136 break;
3138 case QEMU_OPTION_monitor:
3139 monitor_parse(optarg, "readline");
3140 default_monitor = 0;
3141 break;
3142 case QEMU_OPTION_qmp:
3143 monitor_parse(optarg, "control");
3144 default_monitor = 0;
3145 break;
3146 case QEMU_OPTION_mon:
3147 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
3148 if (!opts) {
3149 fprintf(stderr, "parse error: %s\n", optarg);
3150 exit(1);
3152 default_monitor = 0;
3153 break;
3154 case QEMU_OPTION_chardev:
3155 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
3156 if (!opts) {
3157 fprintf(stderr, "parse error: %s\n", optarg);
3158 exit(1);
3160 break;
3161 case QEMU_OPTION_serial:
3162 add_device_config(DEV_SERIAL, optarg);
3163 default_serial = 0;
3164 if (strncmp(optarg, "mon:", 4) == 0) {
3165 default_monitor = 0;
3167 break;
3168 case QEMU_OPTION_watchdog:
3169 if (watchdog) {
3170 fprintf(stderr,
3171 "qemu: only one watchdog option may be given\n");
3172 return 1;
3174 watchdog = optarg;
3175 break;
3176 case QEMU_OPTION_watchdog_action:
3177 if (select_watchdog_action(optarg) == -1) {
3178 fprintf(stderr, "Unknown -watchdog-action parameter\n");
3179 exit(1);
3181 break;
3182 case QEMU_OPTION_virtiocon:
3183 add_device_config(DEV_VIRTCON, optarg);
3184 default_virtcon = 0;
3185 if (strncmp(optarg, "mon:", 4) == 0) {
3186 default_monitor = 0;
3188 break;
3189 case QEMU_OPTION_parallel:
3190 add_device_config(DEV_PARALLEL, optarg);
3191 default_parallel = 0;
3192 if (strncmp(optarg, "mon:", 4) == 0) {
3193 default_monitor = 0;
3195 break;
3196 case QEMU_OPTION_debugcon:
3197 add_device_config(DEV_DEBUGCON, optarg);
3198 break;
3199 case QEMU_OPTION_loadvm:
3200 loadvm = optarg;
3201 break;
3202 case QEMU_OPTION_full_screen:
3203 full_screen = 1;
3204 break;
3205 #ifdef CONFIG_SDL
3206 case QEMU_OPTION_no_frame:
3207 no_frame = 1;
3208 break;
3209 case QEMU_OPTION_alt_grab:
3210 alt_grab = 1;
3211 break;
3212 case QEMU_OPTION_ctrl_grab:
3213 ctrl_grab = 1;
3214 break;
3215 case QEMU_OPTION_no_quit:
3216 no_quit = 1;
3217 break;
3218 case QEMU_OPTION_sdl:
3219 display_type = DT_SDL;
3220 break;
3221 #endif
3222 case QEMU_OPTION_pidfile:
3223 pid_file = optarg;
3224 break;
3225 case QEMU_OPTION_win2k_hack:
3226 win2k_install_hack = 1;
3227 break;
3228 case QEMU_OPTION_rtc_td_hack:
3229 rtc_td_hack = 1;
3230 break;
3231 case QEMU_OPTION_acpitable:
3232 do_acpitable_option(optarg);
3233 break;
3234 case QEMU_OPTION_smbios:
3235 do_smbios_option(optarg);
3236 break;
3237 case QEMU_OPTION_enable_kvm:
3238 if (!(kvm_available())) {
3239 printf("Option %s not supported for this target\n", popt->name);
3240 exit(1);
3242 kvm_allowed = 1;
3243 break;
3244 case QEMU_OPTION_usb:
3245 usb_enabled = 1;
3246 break;
3247 case QEMU_OPTION_usbdevice:
3248 usb_enabled = 1;
3249 add_device_config(DEV_USB, optarg);
3250 break;
3251 case QEMU_OPTION_device:
3252 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
3253 exit(1);
3255 break;
3256 case QEMU_OPTION_smp:
3257 smp_parse(optarg);
3258 if (smp_cpus < 1) {
3259 fprintf(stderr, "Invalid number of CPUs\n");
3260 exit(1);
3262 if (max_cpus < smp_cpus) {
3263 fprintf(stderr, "maxcpus must be equal to or greater than "
3264 "smp\n");
3265 exit(1);
3267 if (max_cpus > 255) {
3268 fprintf(stderr, "Unsupported number of maxcpus\n");
3269 exit(1);
3271 break;
3272 case QEMU_OPTION_vnc:
3273 display_type = DT_VNC;
3274 vnc_display = optarg;
3275 break;
3276 case QEMU_OPTION_no_acpi:
3277 acpi_enabled = 0;
3278 break;
3279 case QEMU_OPTION_no_hpet:
3280 no_hpet = 1;
3281 break;
3282 case QEMU_OPTION_balloon:
3283 if (balloon_parse(optarg) < 0) {
3284 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3285 exit(1);
3287 break;
3288 case QEMU_OPTION_no_reboot:
3289 no_reboot = 1;
3290 break;
3291 case QEMU_OPTION_no_shutdown:
3292 no_shutdown = 1;
3293 break;
3294 case QEMU_OPTION_show_cursor:
3295 cursor_hide = 0;
3296 break;
3297 case QEMU_OPTION_uuid:
3298 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3299 fprintf(stderr, "Fail to parse UUID string."
3300 " Wrong format.\n");
3301 exit(1);
3303 break;
3304 #ifndef _WIN32
3305 case QEMU_OPTION_daemonize:
3306 daemonize = 1;
3307 break;
3308 #endif
3309 case QEMU_OPTION_option_rom:
3310 if (nb_option_roms >= MAX_OPTION_ROMS) {
3311 fprintf(stderr, "Too many option ROMs\n");
3312 exit(1);
3314 option_rom[nb_option_roms] = optarg;
3315 nb_option_roms++;
3316 break;
3317 case QEMU_OPTION_semihosting:
3318 semihosting_enabled = 1;
3319 break;
3320 case QEMU_OPTION_name:
3321 qemu_name = qemu_strdup(optarg);
3323 char *p = strchr(qemu_name, ',');
3324 if (p != NULL) {
3325 *p++ = 0;
3326 if (strncmp(p, "process=", 8)) {
3327 fprintf(stderr, "Unknown subargument %s to -name", p);
3328 exit(1);
3330 p += 8;
3331 set_proc_name(p);
3334 break;
3335 case QEMU_OPTION_prom_env:
3336 if (nb_prom_envs >= MAX_PROM_ENVS) {
3337 fprintf(stderr, "Too many prom variables\n");
3338 exit(1);
3340 prom_envs[nb_prom_envs] = optarg;
3341 nb_prom_envs++;
3342 break;
3343 case QEMU_OPTION_old_param:
3344 old_param = 1;
3345 break;
3346 case QEMU_OPTION_clock:
3347 configure_alarms(optarg);
3348 break;
3349 case QEMU_OPTION_startdate:
3350 configure_rtc_date_offset(optarg, 1);
3351 break;
3352 case QEMU_OPTION_rtc:
3353 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
3354 if (!opts) {
3355 fprintf(stderr, "parse error: %s\n", optarg);
3356 exit(1);
3358 configure_rtc(opts);
3359 break;
3360 case QEMU_OPTION_tb_size:
3361 tb_size = strtol(optarg, NULL, 0);
3362 if (tb_size < 0)
3363 tb_size = 0;
3364 break;
3365 case QEMU_OPTION_icount:
3366 icount_option = optarg;
3367 break;
3368 case QEMU_OPTION_incoming:
3369 incoming = optarg;
3370 break;
3371 case QEMU_OPTION_nodefaults:
3372 default_serial = 0;
3373 default_parallel = 0;
3374 default_virtcon = 0;
3375 default_monitor = 0;
3376 default_vga = 0;
3377 default_net = 0;
3378 default_floppy = 0;
3379 default_cdrom = 0;
3380 default_sdcard = 0;
3381 break;
3382 #ifndef _WIN32
3383 case QEMU_OPTION_chroot:
3384 chroot_dir = optarg;
3385 break;
3386 case QEMU_OPTION_runas:
3387 run_as = optarg;
3388 break;
3389 #endif
3390 case QEMU_OPTION_xen_domid:
3391 if (!(xen_available())) {
3392 printf("Option %s not supported for this target\n", popt->name);
3393 exit(1);
3395 xen_domid = atoi(optarg);
3396 break;
3397 case QEMU_OPTION_xen_create:
3398 if (!(xen_available())) {
3399 printf("Option %s not supported for this target\n", popt->name);
3400 exit(1);
3402 xen_mode = XEN_CREATE;
3403 break;
3404 case QEMU_OPTION_xen_attach:
3405 if (!(xen_available())) {
3406 printf("Option %s not supported for this target\n", popt->name);
3407 exit(1);
3409 xen_mode = XEN_ATTACH;
3410 break;
3411 case QEMU_OPTION_readconfig:
3413 FILE *fp;
3414 fp = fopen(optarg, "r");
3415 if (fp == NULL) {
3416 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3417 exit(1);
3419 if (qemu_config_parse(fp, optarg) != 0) {
3420 exit(1);
3422 fclose(fp);
3423 break;
3425 case QEMU_OPTION_writeconfig:
3427 FILE *fp;
3428 if (strcmp(optarg, "-") == 0) {
3429 fp = stdout;
3430 } else {
3431 fp = fopen(optarg, "w");
3432 if (fp == NULL) {
3433 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3434 exit(1);
3437 qemu_config_write(fp);
3438 fclose(fp);
3439 break;
3444 loc_set_none();
3446 /* If no data_dir is specified then try to find it relative to the
3447 executable path. */
3448 if (!data_dir) {
3449 data_dir = find_datadir(argv[0]);
3451 /* If all else fails use the install patch specified when building. */
3452 if (!data_dir) {
3453 data_dir = CONFIG_QEMU_SHAREDIR;
3457 * Default to max_cpus = smp_cpus, in case the user doesn't
3458 * specify a max_cpus value.
3460 if (!max_cpus)
3461 max_cpus = smp_cpus;
3463 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3464 if (smp_cpus > machine->max_cpus) {
3465 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3466 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
3467 machine->max_cpus);
3468 exit(1);
3471 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
3472 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
3474 if (machine->no_serial) {
3475 default_serial = 0;
3477 if (machine->no_parallel) {
3478 default_parallel = 0;
3480 if (!machine->use_virtcon) {
3481 default_virtcon = 0;
3483 if (machine->no_vga) {
3484 default_vga = 0;
3486 if (machine->no_floppy) {
3487 default_floppy = 0;
3489 if (machine->no_cdrom) {
3490 default_cdrom = 0;
3492 if (machine->no_sdcard) {
3493 default_sdcard = 0;
3496 if (display_type == DT_NOGRAPHIC) {
3497 if (default_parallel)
3498 add_device_config(DEV_PARALLEL, "null");
3499 if (default_serial && default_monitor) {
3500 add_device_config(DEV_SERIAL, "mon:stdio");
3501 } else if (default_virtcon && default_monitor) {
3502 add_device_config(DEV_VIRTCON, "mon:stdio");
3503 } else {
3504 if (default_serial)
3505 add_device_config(DEV_SERIAL, "stdio");
3506 if (default_virtcon)
3507 add_device_config(DEV_VIRTCON, "stdio");
3508 if (default_monitor)
3509 monitor_parse("stdio", "readline");
3511 } else {
3512 if (default_serial)
3513 add_device_config(DEV_SERIAL, "vc:80Cx24C");
3514 if (default_parallel)
3515 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3516 if (default_monitor)
3517 monitor_parse("vc:80Cx24C", "readline");
3518 if (default_virtcon)
3519 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3521 if (default_vga)
3522 vga_interface_type = VGA_CIRRUS;
3524 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
3525 exit(1);
3527 #ifndef _WIN32
3528 if (daemonize) {
3529 pid_t pid;
3531 if (pipe(fds) == -1)
3532 exit(1);
3534 pid = fork();
3535 if (pid > 0) {
3536 uint8_t status;
3537 ssize_t len;
3539 close(fds[1]);
3541 again:
3542 len = read(fds[0], &status, 1);
3543 if (len == -1 && (errno == EINTR))
3544 goto again;
3546 if (len != 1)
3547 exit(1);
3548 else if (status == 1) {
3549 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
3550 exit(1);
3551 } else
3552 exit(0);
3553 } else if (pid < 0)
3554 exit(1);
3556 close(fds[0]);
3557 qemu_set_cloexec(fds[1]);
3559 setsid();
3561 pid = fork();
3562 if (pid > 0)
3563 exit(0);
3564 else if (pid < 0)
3565 exit(1);
3567 umask(027);
3569 signal(SIGTSTP, SIG_IGN);
3570 signal(SIGTTOU, SIG_IGN);
3571 signal(SIGTTIN, SIG_IGN);
3573 #endif
3575 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3576 #ifndef _WIN32
3577 if (daemonize) {
3578 uint8_t status = 1;
3579 if (write(fds[1], &status, 1) != 1) {
3580 perror("daemonize. Writing to pipe\n");
3582 } else
3583 #endif
3584 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
3585 exit(1);
3588 if (kvm_enabled()) {
3589 int ret;
3591 ret = kvm_init(smp_cpus);
3592 if (ret < 0) {
3593 fprintf(stderr, "failed to initialize KVM\n");
3594 exit(1);
3598 if (qemu_init_main_loop()) {
3599 fprintf(stderr, "qemu_init_main_loop failed\n");
3600 exit(1);
3602 linux_boot = (kernel_filename != NULL);
3604 if (!linux_boot && *kernel_cmdline != '\0') {
3605 fprintf(stderr, "-append only allowed with -kernel option\n");
3606 exit(1);
3609 if (!linux_boot && initrd_filename != NULL) {
3610 fprintf(stderr, "-initrd only allowed with -kernel option\n");
3611 exit(1);
3614 #ifndef _WIN32
3615 /* Win32 doesn't support line-buffering and requires size >= 2 */
3616 setvbuf(stdout, NULL, _IOLBF, 0);
3617 #endif
3619 if (init_timer_alarm() < 0) {
3620 fprintf(stderr, "could not initialize alarm timer\n");
3621 exit(1);
3623 configure_icount(icount_option);
3625 #ifdef _WIN32
3626 socket_init();
3627 #endif
3629 if (net_init_clients() < 0) {
3630 exit(1);
3633 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
3634 net_set_boot_mask(net_boot);
3636 /* init the bluetooth world */
3637 if (foreach_device_config(DEV_BT, bt_parse))
3638 exit(1);
3640 /* init the memory */
3641 if (ram_size == 0)
3642 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3644 /* init the dynamic translator */
3645 cpu_exec_init_all(tb_size * 1024 * 1024);
3647 bdrv_init_with_whitelist();
3649 blk_mig_init();
3651 if (default_cdrom) {
3652 /* we always create the cdrom drive, even if no disk is there */
3653 drive_add(NULL, CDROM_ALIAS);
3656 if (default_floppy) {
3657 /* we always create at least one floppy */
3658 drive_add(NULL, FD_ALIAS, 0);
3661 if (default_sdcard) {
3662 /* we always create one sd slot, even if no card is in it */
3663 drive_add(NULL, SD_ALIAS);
3666 /* open the virtual block devices */
3667 if (snapshot)
3668 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
3669 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
3670 exit(1);
3672 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
3673 ram_load, NULL);
3675 if (nb_numa_nodes > 0) {
3676 int i;
3678 if (nb_numa_nodes > smp_cpus) {
3679 nb_numa_nodes = smp_cpus;
3682 /* If no memory size if given for any node, assume the default case
3683 * and distribute the available memory equally across all nodes
3685 for (i = 0; i < nb_numa_nodes; i++) {
3686 if (node_mem[i] != 0)
3687 break;
3689 if (i == nb_numa_nodes) {
3690 uint64_t usedmem = 0;
3692 /* On Linux, the each node's border has to be 8MB aligned,
3693 * the final node gets the rest.
3695 for (i = 0; i < nb_numa_nodes - 1; i++) {
3696 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3697 usedmem += node_mem[i];
3699 node_mem[i] = ram_size - usedmem;
3702 for (i = 0; i < nb_numa_nodes; i++) {
3703 if (node_cpumask[i] != 0)
3704 break;
3706 /* assigning the VCPUs round-robin is easier to implement, guest OSes
3707 * must cope with this anyway, because there are BIOSes out there in
3708 * real machines which also use this scheme.
3710 if (i == nb_numa_nodes) {
3711 for (i = 0; i < smp_cpus; i++) {
3712 node_cpumask[i % nb_numa_nodes] |= 1 << i;
3717 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3718 exit(1);
3719 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3720 exit(1);
3721 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3722 exit(1);
3723 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3724 exit(1);
3726 module_call_init(MODULE_INIT_DEVICE);
3728 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
3729 exit(0);
3731 if (watchdog) {
3732 i = select_watchdog(watchdog);
3733 if (i > 0)
3734 exit (i == 1 ? 1 : 0);
3737 if (machine->compat_props) {
3738 qdev_prop_register_global_list(machine->compat_props);
3740 qemu_add_globals();
3742 machine->init(ram_size, boot_devices,
3743 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3745 cpu_synchronize_all_post_init();
3747 #ifndef _WIN32
3748 /* must be after terminal init, SDL library changes signal handlers */
3749 sighandler_setup();
3750 #endif
3752 set_numa_modes();
3754 current_machine = machine;
3756 /* init USB devices */
3757 if (usb_enabled) {
3758 if (foreach_device_config(DEV_USB, usb_parse) < 0)
3759 exit(1);
3762 /* init generic devices */
3763 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
3764 exit(1);
3766 net_check_clients();
3768 /* just use the first displaystate for the moment */
3769 ds = get_displaystate();
3771 if (display_type == DT_DEFAULT) {
3772 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3773 display_type = DT_SDL;
3774 #else
3775 display_type = DT_VNC;
3776 vnc_display = "localhost:0,to=99";
3777 show_vnc_port = 1;
3778 #endif
3782 switch (display_type) {
3783 case DT_NOGRAPHIC:
3784 break;
3785 #if defined(CONFIG_CURSES)
3786 case DT_CURSES:
3787 curses_display_init(ds, full_screen);
3788 break;
3789 #endif
3790 #if defined(CONFIG_SDL)
3791 case DT_SDL:
3792 sdl_display_init(ds, full_screen, no_frame);
3793 break;
3794 #elif defined(CONFIG_COCOA)
3795 case DT_SDL:
3796 cocoa_display_init(ds, full_screen);
3797 break;
3798 #endif
3799 case DT_VNC:
3800 vnc_display_init(ds);
3801 if (vnc_display_open(ds, vnc_display) < 0)
3802 exit(1);
3804 if (show_vnc_port) {
3805 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3807 break;
3808 default:
3809 break;
3811 dpy_resize(ds);
3813 dcl = ds->listeners;
3814 while (dcl != NULL) {
3815 if (dcl->dpy_refresh != NULL) {
3816 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
3817 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
3819 dcl = dcl->next;
3822 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
3823 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
3824 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
3827 text_consoles_set_display(ds);
3829 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
3830 exit(1);
3832 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3833 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3834 gdbstub_dev);
3835 exit(1);
3838 qdev_machine_creation_done();
3840 if (rom_load_all() != 0) {
3841 fprintf(stderr, "rom loading failed\n");
3842 exit(1);
3845 qemu_system_reset();
3846 if (loadvm) {
3847 if (load_vmstate(loadvm) < 0) {
3848 autostart = 0;
3852 if (incoming) {
3853 qemu_start_incoming_migration(incoming);
3854 } else if (autostart) {
3855 vm_start();
3858 #ifndef _WIN32
3859 if (daemonize) {
3860 uint8_t status = 0;
3861 ssize_t len;
3863 again1:
3864 len = write(fds[1], &status, 1);
3865 if (len == -1 && (errno == EINTR))
3866 goto again1;
3868 if (len != 1)
3869 exit(1);
3871 if (chdir("/")) {
3872 perror("not able to chdir to /");
3873 exit(1);
3875 TFR(fd = qemu_open("/dev/null", O_RDWR));
3876 if (fd == -1)
3877 exit(1);
3880 if (run_as) {
3881 pwd = getpwnam(run_as);
3882 if (!pwd) {
3883 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
3884 exit(1);
3888 if (chroot_dir) {
3889 if (chroot(chroot_dir) < 0) {
3890 fprintf(stderr, "chroot failed\n");
3891 exit(1);
3893 if (chdir("/")) {
3894 perror("not able to chdir to /");
3895 exit(1);
3899 if (run_as) {
3900 if (setgid(pwd->pw_gid) < 0) {
3901 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
3902 exit(1);
3904 if (setuid(pwd->pw_uid) < 0) {
3905 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
3906 exit(1);
3908 if (setuid(0) != -1) {
3909 fprintf(stderr, "Dropping privileges failed\n");
3910 exit(1);
3914 if (daemonize) {
3915 dup2(fd, 0);
3916 dup2(fd, 1);
3917 dup2(fd, 2);
3919 close(fd);
3921 #endif
3923 main_loop();
3924 quit_timers();
3925 net_cleanup();
3927 return 0;