move targphys.h and hw/poison.h inclusion to cpu-common.h
[qemu/aliguori-queue.git] / vl.c
blob2c5e9efd2eb9c3487ac37ae56af010b410ebfec2
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 /***********************************************************/
296 static void set_proc_name(const char *s)
298 #if defined(__linux__) && defined(PR_SET_NAME)
299 char name[16];
300 if (!s)
301 return;
302 name[sizeof(name) - 1] = 0;
303 strncpy(name, s, sizeof(name));
304 /* Could rewrite argv[0] too, but that's a bit more complicated.
305 This simple way is enough for `top'. */
306 prctl(PR_SET_NAME, name);
307 #endif
310 /***************/
311 /* ballooning */
313 static QEMUBalloonEvent *qemu_balloon_event;
314 void *qemu_balloon_event_opaque;
316 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
318 qemu_balloon_event = func;
319 qemu_balloon_event_opaque = opaque;
322 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
324 if (qemu_balloon_event) {
325 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
326 return 1;
327 } else {
328 return 0;
332 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
334 if (qemu_balloon_event) {
335 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
336 return 1;
337 } else {
338 return 0;
343 /***********************************************************/
344 /* real time host monotonic timer */
346 /* compute with 96 bit intermediate result: (a*b)/c */
347 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
349 union {
350 uint64_t ll;
351 struct {
352 #ifdef HOST_WORDS_BIGENDIAN
353 uint32_t high, low;
354 #else
355 uint32_t low, high;
356 #endif
357 } l;
358 } u, res;
359 uint64_t rl, rh;
361 u.ll = a;
362 rl = (uint64_t)u.l.low * (uint64_t)b;
363 rh = (uint64_t)u.l.high * (uint64_t)b;
364 rh += (rl >> 32);
365 res.l.high = rh / c;
366 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
367 return res.ll;
370 /***********************************************************/
371 /* host time/date access */
372 void qemu_get_timedate(struct tm *tm, int offset)
374 time_t ti;
375 struct tm *ret;
377 time(&ti);
378 ti += offset;
379 if (rtc_date_offset == -1) {
380 if (rtc_utc)
381 ret = gmtime(&ti);
382 else
383 ret = localtime(&ti);
384 } else {
385 ti -= rtc_date_offset;
386 ret = gmtime(&ti);
389 memcpy(tm, ret, sizeof(struct tm));
392 int qemu_timedate_diff(struct tm *tm)
394 time_t seconds;
396 if (rtc_date_offset == -1)
397 if (rtc_utc)
398 seconds = mktimegm(tm);
399 else
400 seconds = mktime(tm);
401 else
402 seconds = mktimegm(tm) + rtc_date_offset;
404 return seconds - time(NULL);
407 void rtc_change_mon_event(struct tm *tm)
409 QObject *data;
411 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
412 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
413 qobject_decref(data);
416 static void configure_rtc_date_offset(const char *startdate, int legacy)
418 time_t rtc_start_date;
419 struct tm tm;
421 if (!strcmp(startdate, "now") && legacy) {
422 rtc_date_offset = -1;
423 } else {
424 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
425 &tm.tm_year,
426 &tm.tm_mon,
427 &tm.tm_mday,
428 &tm.tm_hour,
429 &tm.tm_min,
430 &tm.tm_sec) == 6) {
431 /* OK */
432 } else if (sscanf(startdate, "%d-%d-%d",
433 &tm.tm_year,
434 &tm.tm_mon,
435 &tm.tm_mday) == 3) {
436 tm.tm_hour = 0;
437 tm.tm_min = 0;
438 tm.tm_sec = 0;
439 } else {
440 goto date_fail;
442 tm.tm_year -= 1900;
443 tm.tm_mon--;
444 rtc_start_date = mktimegm(&tm);
445 if (rtc_start_date == -1) {
446 date_fail:
447 fprintf(stderr, "Invalid date format. Valid formats are:\n"
448 "'2006-06-17T16:01:21' or '2006-06-17'\n");
449 exit(1);
451 rtc_date_offset = time(NULL) - rtc_start_date;
455 static void configure_rtc(QemuOpts *opts)
457 const char *value;
459 value = qemu_opt_get(opts, "base");
460 if (value) {
461 if (!strcmp(value, "utc")) {
462 rtc_utc = 1;
463 } else if (!strcmp(value, "localtime")) {
464 rtc_utc = 0;
465 } else {
466 configure_rtc_date_offset(value, 0);
469 value = qemu_opt_get(opts, "clock");
470 if (value) {
471 if (!strcmp(value, "host")) {
472 rtc_clock = host_clock;
473 } else if (!strcmp(value, "vm")) {
474 rtc_clock = vm_clock;
475 } else {
476 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
477 exit(1);
480 value = qemu_opt_get(opts, "driftfix");
481 if (value) {
482 if (!strcmp(value, "slew")) {
483 rtc_td_hack = 1;
484 } else if (!strcmp(value, "none")) {
485 rtc_td_hack = 0;
486 } else {
487 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
488 exit(1);
493 /***********************************************************/
494 /* Bluetooth support */
495 static int nb_hcis;
496 static int cur_hci;
497 static struct HCIInfo *hci_table[MAX_NICS];
499 static struct bt_vlan_s {
500 struct bt_scatternet_s net;
501 int id;
502 struct bt_vlan_s *next;
503 } *first_bt_vlan;
505 /* find or alloc a new bluetooth "VLAN" */
506 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
508 struct bt_vlan_s **pvlan, *vlan;
509 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
510 if (vlan->id == id)
511 return &vlan->net;
513 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
514 vlan->id = id;
515 pvlan = &first_bt_vlan;
516 while (*pvlan != NULL)
517 pvlan = &(*pvlan)->next;
518 *pvlan = vlan;
519 return &vlan->net;
522 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
526 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
528 return -ENOTSUP;
531 static struct HCIInfo null_hci = {
532 .cmd_send = null_hci_send,
533 .sco_send = null_hci_send,
534 .acl_send = null_hci_send,
535 .bdaddr_set = null_hci_addr_set,
538 struct HCIInfo *qemu_next_hci(void)
540 if (cur_hci == nb_hcis)
541 return &null_hci;
543 return hci_table[cur_hci++];
546 static struct HCIInfo *hci_init(const char *str)
548 char *endp;
549 struct bt_scatternet_s *vlan = 0;
551 if (!strcmp(str, "null"))
552 /* null */
553 return &null_hci;
554 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
555 /* host[:hciN] */
556 return bt_host_hci(str[4] ? str + 5 : "hci0");
557 else if (!strncmp(str, "hci", 3)) {
558 /* hci[,vlan=n] */
559 if (str[3]) {
560 if (!strncmp(str + 3, ",vlan=", 6)) {
561 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
562 if (*endp)
563 vlan = 0;
565 } else
566 vlan = qemu_find_bt_vlan(0);
567 if (vlan)
568 return bt_new_hci(vlan);
571 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
573 return 0;
576 static int bt_hci_parse(const char *str)
578 struct HCIInfo *hci;
579 bdaddr_t bdaddr;
581 if (nb_hcis >= MAX_NICS) {
582 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
583 return -1;
586 hci = hci_init(str);
587 if (!hci)
588 return -1;
590 bdaddr.b[0] = 0x52;
591 bdaddr.b[1] = 0x54;
592 bdaddr.b[2] = 0x00;
593 bdaddr.b[3] = 0x12;
594 bdaddr.b[4] = 0x34;
595 bdaddr.b[5] = 0x56 + nb_hcis;
596 hci->bdaddr_set(hci, bdaddr.b);
598 hci_table[nb_hcis++] = hci;
600 return 0;
603 static void bt_vhci_add(int vlan_id)
605 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
607 if (!vlan->slave)
608 fprintf(stderr, "qemu: warning: adding a VHCI to "
609 "an empty scatternet %i\n", vlan_id);
611 bt_vhci_init(bt_new_hci(vlan));
614 static struct bt_device_s *bt_device_add(const char *opt)
616 struct bt_scatternet_s *vlan;
617 int vlan_id = 0;
618 char *endp = strstr(opt, ",vlan=");
619 int len = (endp ? endp - opt : strlen(opt)) + 1;
620 char devname[10];
622 pstrcpy(devname, MIN(sizeof(devname), len), opt);
624 if (endp) {
625 vlan_id = strtol(endp + 6, &endp, 0);
626 if (*endp) {
627 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
628 return 0;
632 vlan = qemu_find_bt_vlan(vlan_id);
634 if (!vlan->slave)
635 fprintf(stderr, "qemu: warning: adding a slave device to "
636 "an empty scatternet %i\n", vlan_id);
638 if (!strcmp(devname, "keyboard"))
639 return bt_keyboard_init(vlan);
641 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
642 return 0;
645 static int bt_parse(const char *opt)
647 const char *endp, *p;
648 int vlan;
650 if (strstart(opt, "hci", &endp)) {
651 if (!*endp || *endp == ',') {
652 if (*endp)
653 if (!strstart(endp, ",vlan=", 0))
654 opt = endp + 1;
656 return bt_hci_parse(opt);
658 } else if (strstart(opt, "vhci", &endp)) {
659 if (!*endp || *endp == ',') {
660 if (*endp) {
661 if (strstart(endp, ",vlan=", &p)) {
662 vlan = strtol(p, (char **) &endp, 0);
663 if (*endp) {
664 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
665 return 1;
667 } else {
668 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
669 return 1;
671 } else
672 vlan = 0;
674 bt_vhci_add(vlan);
675 return 0;
677 } else if (strstart(opt, "device:", &endp))
678 return !bt_device_add(endp);
680 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
681 return 1;
684 /***********************************************************/
685 /* QEMU Block devices */
687 #define HD_ALIAS "index=%d,media=disk"
688 #define CDROM_ALIAS "index=2,media=cdrom"
689 #define FD_ALIAS "index=%d,if=floppy"
690 #define PFLASH_ALIAS "if=pflash"
691 #define MTD_ALIAS "if=mtd"
692 #define SD_ALIAS "index=0,if=sd"
694 QemuOpts *drive_add(const char *file, const char *fmt, ...)
696 va_list ap;
697 char optstr[1024];
698 QemuOpts *opts;
700 va_start(ap, fmt);
701 vsnprintf(optstr, sizeof(optstr), fmt, ap);
702 va_end(ap);
704 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
705 if (!opts) {
706 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
707 __FUNCTION__, optstr);
708 return NULL;
710 if (file)
711 qemu_opt_set(opts, "file", file);
712 return opts;
715 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
717 DriveInfo *dinfo;
719 /* seek interface, bus and unit */
721 QTAILQ_FOREACH(dinfo, &drives, next) {
722 if (dinfo->type == type &&
723 dinfo->bus == bus &&
724 dinfo->unit == unit)
725 return dinfo;
728 return NULL;
731 DriveInfo *drive_get_by_id(const char *id)
733 DriveInfo *dinfo;
735 QTAILQ_FOREACH(dinfo, &drives, next) {
736 if (strcmp(id, dinfo->id))
737 continue;
738 return dinfo;
740 return NULL;
743 int drive_get_max_bus(BlockInterfaceType type)
745 int max_bus;
746 DriveInfo *dinfo;
748 max_bus = -1;
749 QTAILQ_FOREACH(dinfo, &drives, next) {
750 if(dinfo->type == type &&
751 dinfo->bus > max_bus)
752 max_bus = dinfo->bus;
754 return max_bus;
757 const char *drive_get_serial(BlockDriverState *bdrv)
759 DriveInfo *dinfo;
761 QTAILQ_FOREACH(dinfo, &drives, next) {
762 if (dinfo->bdrv == bdrv)
763 return dinfo->serial;
766 return "\0";
769 BlockInterfaceErrorAction drive_get_on_error(
770 BlockDriverState *bdrv, int is_read)
772 DriveInfo *dinfo;
774 QTAILQ_FOREACH(dinfo, &drives, next) {
775 if (dinfo->bdrv == bdrv)
776 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
779 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
782 static void bdrv_format_print(void *opaque, const char *name)
784 fprintf(stderr, " %s", name);
787 void drive_uninit(DriveInfo *dinfo)
789 qemu_opts_del(dinfo->opts);
790 bdrv_delete(dinfo->bdrv);
791 QTAILQ_REMOVE(&drives, dinfo, next);
792 qemu_free(dinfo);
795 static int parse_block_error_action(const char *buf, int is_read)
797 if (!strcmp(buf, "ignore")) {
798 return BLOCK_ERR_IGNORE;
799 } else if (!is_read && !strcmp(buf, "enospc")) {
800 return BLOCK_ERR_STOP_ENOSPC;
801 } else if (!strcmp(buf, "stop")) {
802 return BLOCK_ERR_STOP_ANY;
803 } else if (!strcmp(buf, "report")) {
804 return BLOCK_ERR_REPORT;
805 } else {
806 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
807 buf, is_read ? "read" : "write");
808 return -1;
812 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
813 int *fatal_error)
815 const char *buf;
816 const char *file = NULL;
817 char devname[128];
818 const char *serial;
819 const char *mediastr = "";
820 BlockInterfaceType type;
821 enum { MEDIA_DISK, MEDIA_CDROM } media;
822 int bus_id, unit_id;
823 int cyls, heads, secs, translation;
824 BlockDriver *drv = NULL;
825 QEMUMachine *machine = opaque;
826 int max_devs;
827 int index;
828 int cache;
829 int aio = 0;
830 int ro = 0;
831 int bdrv_flags;
832 int on_read_error, on_write_error;
833 const char *devaddr;
834 DriveInfo *dinfo;
835 int snapshot = 0;
837 *fatal_error = 1;
839 translation = BIOS_ATA_TRANSLATION_AUTO;
840 cache = 1;
842 if (machine && machine->use_scsi) {
843 type = IF_SCSI;
844 max_devs = MAX_SCSI_DEVS;
845 pstrcpy(devname, sizeof(devname), "scsi");
846 } else {
847 type = IF_IDE;
848 max_devs = MAX_IDE_DEVS;
849 pstrcpy(devname, sizeof(devname), "ide");
851 media = MEDIA_DISK;
853 /* extract parameters */
854 bus_id = qemu_opt_get_number(opts, "bus", 0);
855 unit_id = qemu_opt_get_number(opts, "unit", -1);
856 index = qemu_opt_get_number(opts, "index", -1);
858 cyls = qemu_opt_get_number(opts, "cyls", 0);
859 heads = qemu_opt_get_number(opts, "heads", 0);
860 secs = qemu_opt_get_number(opts, "secs", 0);
862 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
863 ro = qemu_opt_get_bool(opts, "readonly", 0);
865 file = qemu_opt_get(opts, "file");
866 serial = qemu_opt_get(opts, "serial");
868 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
869 pstrcpy(devname, sizeof(devname), buf);
870 if (!strcmp(buf, "ide")) {
871 type = IF_IDE;
872 max_devs = MAX_IDE_DEVS;
873 } else if (!strcmp(buf, "scsi")) {
874 type = IF_SCSI;
875 max_devs = MAX_SCSI_DEVS;
876 } else if (!strcmp(buf, "floppy")) {
877 type = IF_FLOPPY;
878 max_devs = 0;
879 } else if (!strcmp(buf, "pflash")) {
880 type = IF_PFLASH;
881 max_devs = 0;
882 } else if (!strcmp(buf, "mtd")) {
883 type = IF_MTD;
884 max_devs = 0;
885 } else if (!strcmp(buf, "sd")) {
886 type = IF_SD;
887 max_devs = 0;
888 } else if (!strcmp(buf, "virtio")) {
889 type = IF_VIRTIO;
890 max_devs = 0;
891 } else if (!strcmp(buf, "xen")) {
892 type = IF_XEN;
893 max_devs = 0;
894 } else if (!strcmp(buf, "none")) {
895 type = IF_NONE;
896 max_devs = 0;
897 } else {
898 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
899 return NULL;
903 if (cyls || heads || secs) {
904 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
905 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
906 return NULL;
908 if (heads < 1 || (type == IF_IDE && heads > 16)) {
909 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
910 return NULL;
912 if (secs < 1 || (type == IF_IDE && secs > 63)) {
913 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
914 return NULL;
918 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
919 if (!cyls) {
920 fprintf(stderr,
921 "qemu: '%s' trans must be used with cyls,heads and secs\n",
922 buf);
923 return NULL;
925 if (!strcmp(buf, "none"))
926 translation = BIOS_ATA_TRANSLATION_NONE;
927 else if (!strcmp(buf, "lba"))
928 translation = BIOS_ATA_TRANSLATION_LBA;
929 else if (!strcmp(buf, "auto"))
930 translation = BIOS_ATA_TRANSLATION_AUTO;
931 else {
932 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
933 return NULL;
937 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
938 if (!strcmp(buf, "disk")) {
939 media = MEDIA_DISK;
940 } else if (!strcmp(buf, "cdrom")) {
941 if (cyls || secs || heads) {
942 fprintf(stderr,
943 "qemu: '%s' invalid physical CHS format\n", buf);
944 return NULL;
946 media = MEDIA_CDROM;
947 } else {
948 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
949 return NULL;
953 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
954 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
955 cache = 0;
956 else if (!strcmp(buf, "writethrough"))
957 cache = 1;
958 else if (!strcmp(buf, "writeback"))
959 cache = 2;
960 else {
961 fprintf(stderr, "qemu: invalid cache option\n");
962 return NULL;
966 #ifdef CONFIG_LINUX_AIO
967 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
968 if (!strcmp(buf, "threads"))
969 aio = 0;
970 else if (!strcmp(buf, "native"))
971 aio = 1;
972 else {
973 fprintf(stderr, "qemu: invalid aio option\n");
974 return NULL;
977 #endif
979 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
980 if (strcmp(buf, "?") == 0) {
981 fprintf(stderr, "qemu: Supported formats:");
982 bdrv_iterate_format(bdrv_format_print, NULL);
983 fprintf(stderr, "\n");
984 return NULL;
986 drv = bdrv_find_whitelisted_format(buf);
987 if (!drv) {
988 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
989 return NULL;
993 on_write_error = BLOCK_ERR_STOP_ENOSPC;
994 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
995 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
996 fprintf(stderr, "werror is no supported by this format\n");
997 return NULL;
1000 on_write_error = parse_block_error_action(buf, 0);
1001 if (on_write_error < 0) {
1002 return NULL;
1006 on_read_error = BLOCK_ERR_REPORT;
1007 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1008 if (type != IF_IDE && type != IF_VIRTIO) {
1009 fprintf(stderr, "rerror is no supported by this format\n");
1010 return NULL;
1013 on_read_error = parse_block_error_action(buf, 1);
1014 if (on_read_error < 0) {
1015 return NULL;
1019 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1020 if (type != IF_VIRTIO) {
1021 fprintf(stderr, "addr is not supported\n");
1022 return NULL;
1026 /* compute bus and unit according index */
1028 if (index != -1) {
1029 if (bus_id != 0 || unit_id != -1) {
1030 fprintf(stderr,
1031 "qemu: index cannot be used with bus and unit\n");
1032 return NULL;
1034 if (max_devs == 0)
1036 unit_id = index;
1037 bus_id = 0;
1038 } else {
1039 unit_id = index % max_devs;
1040 bus_id = index / max_devs;
1044 /* if user doesn't specify a unit_id,
1045 * try to find the first free
1048 if (unit_id == -1) {
1049 unit_id = 0;
1050 while (drive_get(type, bus_id, unit_id) != NULL) {
1051 unit_id++;
1052 if (max_devs && unit_id >= max_devs) {
1053 unit_id -= max_devs;
1054 bus_id++;
1059 /* check unit id */
1061 if (max_devs && unit_id >= max_devs) {
1062 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1063 unit_id, max_devs - 1);
1064 return NULL;
1068 * ignore multiple definitions
1071 if (drive_get(type, bus_id, unit_id) != NULL) {
1072 *fatal_error = 0;
1073 return NULL;
1076 /* init */
1078 dinfo = qemu_mallocz(sizeof(*dinfo));
1079 if ((buf = qemu_opts_id(opts)) != NULL) {
1080 dinfo->id = qemu_strdup(buf);
1081 } else {
1082 /* no id supplied -> create one */
1083 dinfo->id = qemu_mallocz(32);
1084 if (type == IF_IDE || type == IF_SCSI)
1085 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1086 if (max_devs)
1087 snprintf(dinfo->id, 32, "%s%i%s%i",
1088 devname, bus_id, mediastr, unit_id);
1089 else
1090 snprintf(dinfo->id, 32, "%s%s%i",
1091 devname, mediastr, unit_id);
1093 dinfo->bdrv = bdrv_new(dinfo->id);
1094 dinfo->devaddr = devaddr;
1095 dinfo->type = type;
1096 dinfo->bus = bus_id;
1097 dinfo->unit = unit_id;
1098 dinfo->on_read_error = on_read_error;
1099 dinfo->on_write_error = on_write_error;
1100 dinfo->opts = opts;
1101 if (serial)
1102 strncpy(dinfo->serial, serial, sizeof(serial));
1103 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1105 switch(type) {
1106 case IF_IDE:
1107 case IF_SCSI:
1108 case IF_XEN:
1109 case IF_NONE:
1110 switch(media) {
1111 case MEDIA_DISK:
1112 if (cyls != 0) {
1113 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1114 bdrv_set_translation_hint(dinfo->bdrv, translation);
1116 break;
1117 case MEDIA_CDROM:
1118 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1119 break;
1121 break;
1122 case IF_SD:
1123 /* FIXME: This isn't really a floppy, but it's a reasonable
1124 approximation. */
1125 case IF_FLOPPY:
1126 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1127 break;
1128 case IF_PFLASH:
1129 case IF_MTD:
1130 break;
1131 case IF_VIRTIO:
1132 /* add virtio block device */
1133 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1134 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1135 qemu_opt_set(opts, "drive", dinfo->id);
1136 if (devaddr)
1137 qemu_opt_set(opts, "addr", devaddr);
1138 break;
1139 case IF_COUNT:
1140 abort();
1142 if (!file) {
1143 *fatal_error = 0;
1144 return NULL;
1146 bdrv_flags = 0;
1147 if (snapshot) {
1148 bdrv_flags |= BDRV_O_SNAPSHOT;
1149 cache = 2; /* always use write-back with snapshot */
1151 if (cache == 0) /* no caching */
1152 bdrv_flags |= BDRV_O_NOCACHE;
1153 else if (cache == 2) /* write-back */
1154 bdrv_flags |= BDRV_O_CACHE_WB;
1156 if (aio == 1) {
1157 bdrv_flags |= BDRV_O_NATIVE_AIO;
1158 } else {
1159 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1162 if (media == MEDIA_CDROM) {
1163 /* CDROM is fine for any interface, don't check. */
1164 ro = 1;
1165 } else if (ro == 1) {
1166 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1167 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1168 return NULL;
1172 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1174 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1175 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1176 file, strerror(errno));
1177 return NULL;
1180 if (bdrv_key_required(dinfo->bdrv))
1181 autostart = 0;
1182 *fatal_error = 0;
1183 return dinfo;
1186 static int drive_init_func(QemuOpts *opts, void *opaque)
1188 QEMUMachine *machine = opaque;
1189 int fatal_error = 0;
1191 if (drive_init(opts, machine, &fatal_error) == NULL) {
1192 if (fatal_error)
1193 return 1;
1195 return 0;
1198 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1200 if (NULL == qemu_opt_get(opts, "snapshot")) {
1201 qemu_opt_set(opts, "snapshot", "on");
1203 return 0;
1206 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1208 boot_set_handler = func;
1209 boot_set_opaque = opaque;
1212 int qemu_boot_set(const char *boot_devices)
1214 if (!boot_set_handler) {
1215 return -EINVAL;
1217 return boot_set_handler(boot_set_opaque, boot_devices);
1220 static int parse_bootdevices(char *devices)
1222 /* We just do some generic consistency checks */
1223 const char *p;
1224 int bitmap = 0;
1226 for (p = devices; *p != '\0'; p++) {
1227 /* Allowed boot devices are:
1228 * a-b: floppy disk drives
1229 * c-f: IDE disk drives
1230 * g-m: machine implementation dependant drives
1231 * n-p: network devices
1232 * It's up to each machine implementation to check if the given boot
1233 * devices match the actual hardware implementation and firmware
1234 * features.
1236 if (*p < 'a' || *p > 'p') {
1237 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1238 exit(1);
1240 if (bitmap & (1 << (*p - 'a'))) {
1241 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1242 exit(1);
1244 bitmap |= 1 << (*p - 'a');
1246 return bitmap;
1249 static void restore_boot_devices(void *opaque)
1251 char *standard_boot_devices = opaque;
1253 qemu_boot_set(standard_boot_devices);
1255 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1256 qemu_free(standard_boot_devices);
1259 static void numa_add(const char *optarg)
1261 char option[128];
1262 char *endptr;
1263 unsigned long long value, endvalue;
1264 int nodenr;
1266 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1267 if (!strcmp(option, "node")) {
1268 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1269 nodenr = nb_numa_nodes;
1270 } else {
1271 nodenr = strtoull(option, NULL, 10);
1274 if (get_param_value(option, 128, "mem", optarg) == 0) {
1275 node_mem[nodenr] = 0;
1276 } else {
1277 value = strtoull(option, &endptr, 0);
1278 switch (*endptr) {
1279 case 0: case 'M': case 'm':
1280 value <<= 20;
1281 break;
1282 case 'G': case 'g':
1283 value <<= 30;
1284 break;
1286 node_mem[nodenr] = value;
1288 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1289 node_cpumask[nodenr] = 0;
1290 } else {
1291 value = strtoull(option, &endptr, 10);
1292 if (value >= 64) {
1293 value = 63;
1294 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1295 } else {
1296 if (*endptr == '-') {
1297 endvalue = strtoull(endptr+1, &endptr, 10);
1298 if (endvalue >= 63) {
1299 endvalue = 62;
1300 fprintf(stderr,
1301 "only 63 CPUs in NUMA mode supported.\n");
1303 value = (2ULL << endvalue) - (1ULL << value);
1304 } else {
1305 value = 1ULL << value;
1308 node_cpumask[nodenr] = value;
1310 nb_numa_nodes++;
1312 return;
1315 static void smp_parse(const char *optarg)
1317 int smp, sockets = 0, threads = 0, cores = 0;
1318 char *endptr;
1319 char option[128];
1321 smp = strtoul(optarg, &endptr, 10);
1322 if (endptr != optarg) {
1323 if (*endptr == ',') {
1324 endptr++;
1327 if (get_param_value(option, 128, "sockets", endptr) != 0)
1328 sockets = strtoull(option, NULL, 10);
1329 if (get_param_value(option, 128, "cores", endptr) != 0)
1330 cores = strtoull(option, NULL, 10);
1331 if (get_param_value(option, 128, "threads", endptr) != 0)
1332 threads = strtoull(option, NULL, 10);
1333 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1334 max_cpus = strtoull(option, NULL, 10);
1336 /* compute missing values, prefer sockets over cores over threads */
1337 if (smp == 0 || sockets == 0) {
1338 sockets = sockets > 0 ? sockets : 1;
1339 cores = cores > 0 ? cores : 1;
1340 threads = threads > 0 ? threads : 1;
1341 if (smp == 0) {
1342 smp = cores * threads * sockets;
1344 } else {
1345 if (cores == 0) {
1346 threads = threads > 0 ? threads : 1;
1347 cores = smp / (sockets * threads);
1348 } else {
1349 if (sockets) {
1350 threads = smp / (cores * sockets);
1354 smp_cpus = smp;
1355 smp_cores = cores > 0 ? cores : 1;
1356 smp_threads = threads > 0 ? threads : 1;
1357 if (max_cpus == 0)
1358 max_cpus = smp_cpus;
1361 /***********************************************************/
1362 /* USB devices */
1364 static int usb_device_add(const char *devname, int is_hotplug)
1366 const char *p;
1367 USBDevice *dev = NULL;
1369 if (!usb_enabled)
1370 return -1;
1372 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1373 dev = usbdevice_create(devname);
1374 if (dev)
1375 goto done;
1377 /* the other ones */
1378 if (strstart(devname, "host:", &p)) {
1379 dev = usb_host_device_open(p);
1380 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1381 dev = usb_bt_init(devname[2] ? hci_init(p) :
1382 bt_new_hci(qemu_find_bt_vlan(0)));
1383 } else {
1384 return -1;
1386 if (!dev)
1387 return -1;
1389 done:
1390 return 0;
1393 static int usb_device_del(const char *devname)
1395 int bus_num, addr;
1396 const char *p;
1398 if (strstart(devname, "host:", &p))
1399 return usb_host_device_close(p);
1401 if (!usb_enabled)
1402 return -1;
1404 p = strchr(devname, '.');
1405 if (!p)
1406 return -1;
1407 bus_num = strtoul(devname, NULL, 0);
1408 addr = strtoul(p + 1, NULL, 0);
1410 return usb_device_delete_addr(bus_num, addr);
1413 static int usb_parse(const char *cmdline)
1415 int r;
1416 r = usb_device_add(cmdline, 0);
1417 if (r < 0) {
1418 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1420 return r;
1423 void do_usb_add(Monitor *mon, const QDict *qdict)
1425 const char *devname = qdict_get_str(qdict, "devname");
1426 if (usb_device_add(devname, 1) < 0) {
1427 error_report("could not add USB device '%s'", devname);
1431 void do_usb_del(Monitor *mon, const QDict *qdict)
1433 const char *devname = qdict_get_str(qdict, "devname");
1434 if (usb_device_del(devname) < 0) {
1435 error_report("could not delete USB device '%s'", devname);
1439 /***********************************************************/
1440 /* PCMCIA/Cardbus */
1442 static struct pcmcia_socket_entry_s {
1443 PCMCIASocket *socket;
1444 struct pcmcia_socket_entry_s *next;
1445 } *pcmcia_sockets = 0;
1447 void pcmcia_socket_register(PCMCIASocket *socket)
1449 struct pcmcia_socket_entry_s *entry;
1451 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1452 entry->socket = socket;
1453 entry->next = pcmcia_sockets;
1454 pcmcia_sockets = entry;
1457 void pcmcia_socket_unregister(PCMCIASocket *socket)
1459 struct pcmcia_socket_entry_s *entry, **ptr;
1461 ptr = &pcmcia_sockets;
1462 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1463 if (entry->socket == socket) {
1464 *ptr = entry->next;
1465 qemu_free(entry);
1469 void pcmcia_info(Monitor *mon)
1471 struct pcmcia_socket_entry_s *iter;
1473 if (!pcmcia_sockets)
1474 monitor_printf(mon, "No PCMCIA sockets\n");
1476 for (iter = pcmcia_sockets; iter; iter = iter->next)
1477 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1478 iter->socket->attached ? iter->socket->card_string :
1479 "Empty");
1482 /***********************************************************/
1483 /* I/O handling */
1485 typedef struct IOHandlerRecord {
1486 int fd;
1487 IOCanReadHandler *fd_read_poll;
1488 IOHandler *fd_read;
1489 IOHandler *fd_write;
1490 int deleted;
1491 void *opaque;
1492 /* temporary data */
1493 struct pollfd *ufd;
1494 QLIST_ENTRY(IOHandlerRecord) next;
1495 } IOHandlerRecord;
1497 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1498 QLIST_HEAD_INITIALIZER(io_handlers);
1501 /* XXX: fd_read_poll should be suppressed, but an API change is
1502 necessary in the character devices to suppress fd_can_read(). */
1503 int qemu_set_fd_handler2(int fd,
1504 IOCanReadHandler *fd_read_poll,
1505 IOHandler *fd_read,
1506 IOHandler *fd_write,
1507 void *opaque)
1509 IOHandlerRecord *ioh;
1511 if (!fd_read && !fd_write) {
1512 QLIST_FOREACH(ioh, &io_handlers, next) {
1513 if (ioh->fd == fd) {
1514 ioh->deleted = 1;
1515 break;
1518 } else {
1519 QLIST_FOREACH(ioh, &io_handlers, next) {
1520 if (ioh->fd == fd)
1521 goto found;
1523 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1524 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1525 found:
1526 ioh->fd = fd;
1527 ioh->fd_read_poll = fd_read_poll;
1528 ioh->fd_read = fd_read;
1529 ioh->fd_write = fd_write;
1530 ioh->opaque = opaque;
1531 ioh->deleted = 0;
1533 return 0;
1536 int qemu_set_fd_handler(int fd,
1537 IOHandler *fd_read,
1538 IOHandler *fd_write,
1539 void *opaque)
1541 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1544 #ifdef _WIN32
1545 /***********************************************************/
1546 /* Polling handling */
1548 typedef struct PollingEntry {
1549 PollingFunc *func;
1550 void *opaque;
1551 struct PollingEntry *next;
1552 } PollingEntry;
1554 static PollingEntry *first_polling_entry;
1556 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1558 PollingEntry **ppe, *pe;
1559 pe = qemu_mallocz(sizeof(PollingEntry));
1560 pe->func = func;
1561 pe->opaque = opaque;
1562 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1563 *ppe = pe;
1564 return 0;
1567 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1569 PollingEntry **ppe, *pe;
1570 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1571 pe = *ppe;
1572 if (pe->func == func && pe->opaque == opaque) {
1573 *ppe = pe->next;
1574 qemu_free(pe);
1575 break;
1580 /***********************************************************/
1581 /* Wait objects support */
1582 typedef struct WaitObjects {
1583 int num;
1584 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1585 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1586 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1587 } WaitObjects;
1589 static WaitObjects wait_objects = {0};
1591 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1593 WaitObjects *w = &wait_objects;
1595 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1596 return -1;
1597 w->events[w->num] = handle;
1598 w->func[w->num] = func;
1599 w->opaque[w->num] = opaque;
1600 w->num++;
1601 return 0;
1604 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1606 int i, found;
1607 WaitObjects *w = &wait_objects;
1609 found = 0;
1610 for (i = 0; i < w->num; i++) {
1611 if (w->events[i] == handle)
1612 found = 1;
1613 if (found) {
1614 w->events[i] = w->events[i + 1];
1615 w->func[i] = w->func[i + 1];
1616 w->opaque[i] = w->opaque[i + 1];
1619 if (found)
1620 w->num--;
1622 #endif
1624 /***********************************************************/
1625 /* machine registration */
1627 static QEMUMachine *first_machine = NULL;
1628 QEMUMachine *current_machine = NULL;
1630 int qemu_register_machine(QEMUMachine *m)
1632 QEMUMachine **pm;
1633 pm = &first_machine;
1634 while (*pm != NULL)
1635 pm = &(*pm)->next;
1636 m->next = NULL;
1637 *pm = m;
1638 return 0;
1641 static QEMUMachine *find_machine(const char *name)
1643 QEMUMachine *m;
1645 for(m = first_machine; m != NULL; m = m->next) {
1646 if (!strcmp(m->name, name))
1647 return m;
1648 if (m->alias && !strcmp(m->alias, name))
1649 return m;
1651 return NULL;
1654 static QEMUMachine *find_default_machine(void)
1656 QEMUMachine *m;
1658 for(m = first_machine; m != NULL; m = m->next) {
1659 if (m->is_default) {
1660 return m;
1663 return NULL;
1666 /***********************************************************/
1667 /* main execution loop */
1669 static void gui_update(void *opaque)
1671 uint64_t interval = GUI_REFRESH_INTERVAL;
1672 DisplayState *ds = opaque;
1673 DisplayChangeListener *dcl = ds->listeners;
1675 qemu_flush_coalesced_mmio_buffer();
1676 dpy_refresh(ds);
1678 while (dcl != NULL) {
1679 if (dcl->gui_timer_interval &&
1680 dcl->gui_timer_interval < interval)
1681 interval = dcl->gui_timer_interval;
1682 dcl = dcl->next;
1684 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1687 static void nographic_update(void *opaque)
1689 uint64_t interval = GUI_REFRESH_INTERVAL;
1691 qemu_flush_coalesced_mmio_buffer();
1692 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1695 struct vm_change_state_entry {
1696 VMChangeStateHandler *cb;
1697 void *opaque;
1698 QLIST_ENTRY (vm_change_state_entry) entries;
1701 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1703 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1704 void *opaque)
1706 VMChangeStateEntry *e;
1708 e = qemu_mallocz(sizeof (*e));
1710 e->cb = cb;
1711 e->opaque = opaque;
1712 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1713 return e;
1716 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1718 QLIST_REMOVE (e, entries);
1719 qemu_free (e);
1722 void vm_state_notify(int running, int reason)
1724 VMChangeStateEntry *e;
1726 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1727 e->cb(e->opaque, running, reason);
1731 void vm_start(void)
1733 if (!vm_running) {
1734 cpu_enable_ticks();
1735 vm_running = 1;
1736 vm_state_notify(1, 0);
1737 resume_all_vcpus();
1741 /* reset/shutdown handler */
1743 typedef struct QEMUResetEntry {
1744 QTAILQ_ENTRY(QEMUResetEntry) entry;
1745 QEMUResetHandler *func;
1746 void *opaque;
1747 } QEMUResetEntry;
1749 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1750 QTAILQ_HEAD_INITIALIZER(reset_handlers);
1751 static int reset_requested;
1752 static int shutdown_requested;
1753 static int powerdown_requested;
1754 int debug_requested;
1755 static int vmstop_requested;
1757 int qemu_shutdown_requested(void)
1759 int r = shutdown_requested;
1760 shutdown_requested = 0;
1761 return r;
1764 int qemu_reset_requested(void)
1766 int r = reset_requested;
1767 reset_requested = 0;
1768 return r;
1771 int qemu_powerdown_requested(void)
1773 int r = powerdown_requested;
1774 powerdown_requested = 0;
1775 return r;
1778 static int qemu_debug_requested(void)
1780 int r = debug_requested;
1781 debug_requested = 0;
1782 return r;
1785 static int qemu_vmstop_requested(void)
1787 int r = vmstop_requested;
1788 vmstop_requested = 0;
1789 return r;
1792 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1794 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
1796 re->func = func;
1797 re->opaque = opaque;
1798 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1801 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1803 QEMUResetEntry *re;
1805 QTAILQ_FOREACH(re, &reset_handlers, entry) {
1806 if (re->func == func && re->opaque == opaque) {
1807 QTAILQ_REMOVE(&reset_handlers, re, entry);
1808 qemu_free(re);
1809 return;
1814 void qemu_system_reset(void)
1816 QEMUResetEntry *re, *nre;
1818 /* reset all devices */
1819 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1820 re->func(re->opaque);
1822 monitor_protocol_event(QEVENT_RESET, NULL);
1823 cpu_synchronize_all_post_reset();
1826 void qemu_system_reset_request(void)
1828 if (no_reboot) {
1829 shutdown_requested = 1;
1830 } else {
1831 reset_requested = 1;
1833 qemu_notify_event();
1836 void qemu_system_shutdown_request(void)
1838 shutdown_requested = 1;
1839 qemu_notify_event();
1842 void qemu_system_powerdown_request(void)
1844 powerdown_requested = 1;
1845 qemu_notify_event();
1848 #ifdef _WIN32
1849 static void host_main_loop_wait(int *timeout)
1851 int ret, ret2, i;
1852 PollingEntry *pe;
1855 /* XXX: need to suppress polling by better using win32 events */
1856 ret = 0;
1857 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
1858 ret |= pe->func(pe->opaque);
1860 if (ret == 0) {
1861 int err;
1862 WaitObjects *w = &wait_objects;
1864 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
1865 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
1866 if (w->func[ret - WAIT_OBJECT_0])
1867 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
1869 /* Check for additional signaled events */
1870 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
1872 /* Check if event is signaled */
1873 ret2 = WaitForSingleObject(w->events[i], 0);
1874 if(ret2 == WAIT_OBJECT_0) {
1875 if (w->func[i])
1876 w->func[i](w->opaque[i]);
1877 } else if (ret2 == WAIT_TIMEOUT) {
1878 } else {
1879 err = GetLastError();
1880 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
1883 } else if (ret == WAIT_TIMEOUT) {
1884 } else {
1885 err = GetLastError();
1886 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
1890 *timeout = 0;
1892 #else
1893 static void host_main_loop_wait(int *timeout)
1896 #endif
1898 void main_loop_wait(int nonblocking)
1900 IOHandlerRecord *ioh;
1901 fd_set rfds, wfds, xfds;
1902 int ret, nfds;
1903 struct timeval tv;
1904 int timeout;
1906 if (nonblocking)
1907 timeout = 0;
1908 else {
1909 timeout = qemu_calculate_timeout();
1910 qemu_bh_update_timeout(&timeout);
1913 host_main_loop_wait(&timeout);
1915 /* poll any events */
1916 /* XXX: separate device handlers from system ones */
1917 nfds = -1;
1918 FD_ZERO(&rfds);
1919 FD_ZERO(&wfds);
1920 FD_ZERO(&xfds);
1921 QLIST_FOREACH(ioh, &io_handlers, next) {
1922 if (ioh->deleted)
1923 continue;
1924 if (ioh->fd_read &&
1925 (!ioh->fd_read_poll ||
1926 ioh->fd_read_poll(ioh->opaque) != 0)) {
1927 FD_SET(ioh->fd, &rfds);
1928 if (ioh->fd > nfds)
1929 nfds = ioh->fd;
1931 if (ioh->fd_write) {
1932 FD_SET(ioh->fd, &wfds);
1933 if (ioh->fd > nfds)
1934 nfds = ioh->fd;
1938 tv.tv_sec = timeout / 1000;
1939 tv.tv_usec = (timeout % 1000) * 1000;
1941 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1943 qemu_mutex_unlock_iothread();
1944 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1945 qemu_mutex_lock_iothread();
1946 if (ret > 0) {
1947 IOHandlerRecord *pioh;
1949 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
1950 if (ioh->deleted) {
1951 QLIST_REMOVE(ioh, next);
1952 qemu_free(ioh);
1953 continue;
1955 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
1956 ioh->fd_read(ioh->opaque);
1958 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
1959 ioh->fd_write(ioh->opaque);
1964 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1966 qemu_run_all_timers();
1968 /* Check bottom-halves last in case any of the earlier events triggered
1969 them. */
1970 qemu_bh_poll();
1974 static int vm_can_run(void)
1976 if (powerdown_requested)
1977 return 0;
1978 if (reset_requested)
1979 return 0;
1980 if (shutdown_requested)
1981 return 0;
1982 if (debug_requested)
1983 return 0;
1984 return 1;
1987 qemu_irq qemu_system_powerdown;
1989 static void main_loop(void)
1991 int r;
1993 #ifdef CONFIG_IOTHREAD
1994 qemu_system_ready = 1;
1995 qemu_cond_broadcast(&qemu_system_cond);
1996 #endif
1998 for (;;) {
1999 do {
2000 bool nonblocking = false;
2001 #ifdef CONFIG_PROFILER
2002 int64_t ti;
2003 #endif
2004 #ifndef CONFIG_IOTHREAD
2005 nonblocking = tcg_cpu_exec();
2006 #endif
2007 #ifdef CONFIG_PROFILER
2008 ti = profile_getclock();
2009 #endif
2010 main_loop_wait(nonblocking);
2011 #ifdef CONFIG_PROFILER
2012 dev_time += profile_getclock() - ti;
2013 #endif
2014 } while (vm_can_run());
2016 if ((r = qemu_debug_requested())) {
2017 vm_stop(r);
2019 if (qemu_shutdown_requested()) {
2020 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2021 if (no_shutdown) {
2022 vm_stop(0);
2023 no_shutdown = 0;
2024 } else
2025 break;
2027 if (qemu_reset_requested()) {
2028 pause_all_vcpus();
2029 qemu_system_reset();
2030 resume_all_vcpus();
2032 if (qemu_powerdown_requested()) {
2033 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
2034 qemu_irq_raise(qemu_system_powerdown);
2036 if ((r = qemu_vmstop_requested())) {
2037 vm_stop(r);
2040 pause_all_vcpus();
2043 static void version(void)
2045 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
2048 static void help(int exitcode)
2050 const char *options_help =
2051 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2052 opt_help
2053 #define DEFHEADING(text) stringify(text) "\n"
2054 #include "qemu-options.h"
2055 #undef DEF
2056 #undef DEFHEADING
2057 #undef GEN_DOCS
2059 version();
2060 printf("usage: %s [options] [disk_image]\n"
2061 "\n"
2062 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2063 "\n"
2064 "%s\n"
2065 "During emulation, the following keys are useful:\n"
2066 "ctrl-alt-f toggle full screen\n"
2067 "ctrl-alt-n switch to virtual console 'n'\n"
2068 "ctrl-alt toggle mouse and keyboard grab\n"
2069 "\n"
2070 "When using -nographic, press 'ctrl-a h' to get some help.\n",
2071 "qemu",
2072 options_help);
2073 exit(exitcode);
2076 #define HAS_ARG 0x0001
2078 enum {
2079 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2080 opt_enum,
2081 #define DEFHEADING(text)
2082 #include "qemu-options.h"
2083 #undef DEF
2084 #undef DEFHEADING
2085 #undef GEN_DOCS
2088 typedef struct QEMUOption {
2089 const char *name;
2090 int flags;
2091 int index;
2092 uint32_t arch_mask;
2093 } QEMUOption;
2095 static const QEMUOption qemu_options[] = {
2096 { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
2097 #define DEF(option, opt_arg, opt_enum, opt_help, arch_mask) \
2098 { option, opt_arg, opt_enum, arch_mask },
2099 #define DEFHEADING(text)
2100 #include "qemu-options.h"
2101 #undef DEF
2102 #undef DEFHEADING
2103 #undef GEN_DOCS
2104 { NULL },
2106 static void select_vgahw (const char *p)
2108 const char *opts;
2110 default_vga = 0;
2111 vga_interface_type = VGA_NONE;
2112 if (strstart(p, "std", &opts)) {
2113 vga_interface_type = VGA_STD;
2114 } else if (strstart(p, "cirrus", &opts)) {
2115 vga_interface_type = VGA_CIRRUS;
2116 } else if (strstart(p, "vmware", &opts)) {
2117 vga_interface_type = VGA_VMWARE;
2118 } else if (strstart(p, "xenfb", &opts)) {
2119 vga_interface_type = VGA_XENFB;
2120 } else if (!strstart(p, "none", &opts)) {
2121 invalid_vga:
2122 fprintf(stderr, "Unknown vga type: %s\n", p);
2123 exit(1);
2125 while (*opts) {
2126 const char *nextopt;
2128 if (strstart(opts, ",retrace=", &nextopt)) {
2129 opts = nextopt;
2130 if (strstart(opts, "dumb", &nextopt))
2131 vga_retrace_method = VGA_RETRACE_DUMB;
2132 else if (strstart(opts, "precise", &nextopt))
2133 vga_retrace_method = VGA_RETRACE_PRECISE;
2134 else goto invalid_vga;
2135 } else goto invalid_vga;
2136 opts = nextopt;
2140 static int balloon_parse(const char *arg)
2142 QemuOpts *opts;
2144 if (strcmp(arg, "none") == 0) {
2145 return 0;
2148 if (!strncmp(arg, "virtio", 6)) {
2149 if (arg[6] == ',') {
2150 /* have params -> parse them */
2151 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
2152 if (!opts)
2153 return -1;
2154 } else {
2155 /* create empty opts */
2156 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2158 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
2159 return 0;
2162 return -1;
2165 #ifdef _WIN32
2166 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
2168 exit(STATUS_CONTROL_C_EXIT);
2169 return TRUE;
2171 #endif
2173 #ifndef _WIN32
2175 static void termsig_handler(int signal)
2177 qemu_system_shutdown_request();
2180 static void sigchld_handler(int signal)
2182 waitpid(-1, NULL, WNOHANG);
2185 static void sighandler_setup(void)
2187 struct sigaction act;
2189 memset(&act, 0, sizeof(act));
2190 act.sa_handler = termsig_handler;
2191 sigaction(SIGINT, &act, NULL);
2192 sigaction(SIGHUP, &act, NULL);
2193 sigaction(SIGTERM, &act, NULL);
2195 act.sa_handler = sigchld_handler;
2196 act.sa_flags = SA_NOCLDSTOP;
2197 sigaction(SIGCHLD, &act, NULL);
2200 #endif
2202 #ifdef _WIN32
2203 /* Look for support files in the same directory as the executable. */
2204 static char *find_datadir(const char *argv0)
2206 char *p;
2207 char buf[MAX_PATH];
2208 DWORD len;
2210 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
2211 if (len == 0) {
2212 return NULL;
2215 buf[len] = 0;
2216 p = buf + len - 1;
2217 while (p != buf && *p != '\\')
2218 p--;
2219 *p = 0;
2220 if (access(buf, R_OK) == 0) {
2221 return qemu_strdup(buf);
2223 return NULL;
2225 #else /* !_WIN32 */
2227 /* Find a likely location for support files using the location of the binary.
2228 For installed binaries this will be "$bindir/../share/qemu". When
2229 running from the build tree this will be "$bindir/../pc-bios". */
2230 #define SHARE_SUFFIX "/share/qemu"
2231 #define BUILD_SUFFIX "/pc-bios"
2232 static char *find_datadir(const char *argv0)
2234 char *dir;
2235 char *p = NULL;
2236 char *res;
2237 char buf[PATH_MAX];
2238 size_t max_len;
2240 #if defined(__linux__)
2242 int len;
2243 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
2244 if (len > 0) {
2245 buf[len] = 0;
2246 p = buf;
2249 #elif defined(__FreeBSD__)
2251 static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
2252 size_t len = sizeof(buf) - 1;
2254 *buf = '\0';
2255 if (!sysctl(mib, sizeof(mib)/sizeof(*mib), buf, &len, NULL, 0) &&
2256 *buf) {
2257 buf[sizeof(buf) - 1] = '\0';
2258 p = buf;
2261 #endif
2262 /* If we don't have any way of figuring out the actual executable
2263 location then try argv[0]. */
2264 if (!p) {
2265 p = realpath(argv0, buf);
2266 if (!p) {
2267 return NULL;
2270 dir = dirname(p);
2271 dir = dirname(dir);
2273 max_len = strlen(dir) +
2274 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
2275 res = qemu_mallocz(max_len);
2276 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
2277 if (access(res, R_OK)) {
2278 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
2279 if (access(res, R_OK)) {
2280 qemu_free(res);
2281 res = NULL;
2285 return res;
2287 #undef SHARE_SUFFIX
2288 #undef BUILD_SUFFIX
2289 #endif
2291 char *qemu_find_file(int type, const char *name)
2293 int len;
2294 const char *subdir;
2295 char *buf;
2297 /* If name contains path separators then try it as a straight path. */
2298 if ((strchr(name, '/') || strchr(name, '\\'))
2299 && access(name, R_OK) == 0) {
2300 return qemu_strdup(name);
2302 switch (type) {
2303 case QEMU_FILE_TYPE_BIOS:
2304 subdir = "";
2305 break;
2306 case QEMU_FILE_TYPE_KEYMAP:
2307 subdir = "keymaps/";
2308 break;
2309 default:
2310 abort();
2312 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
2313 buf = qemu_mallocz(len);
2314 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
2315 if (access(buf, R_OK)) {
2316 qemu_free(buf);
2317 return NULL;
2319 return buf;
2322 static int device_help_func(QemuOpts *opts, void *opaque)
2324 return qdev_device_help(opts);
2327 static int device_init_func(QemuOpts *opts, void *opaque)
2329 DeviceState *dev;
2331 dev = qdev_device_add(opts);
2332 if (!dev)
2333 return -1;
2334 return 0;
2337 static int chardev_init_func(QemuOpts *opts, void *opaque)
2339 CharDriverState *chr;
2341 chr = qemu_chr_open_opts(opts, NULL);
2342 if (!chr)
2343 return -1;
2344 return 0;
2347 static int mon_init_func(QemuOpts *opts, void *opaque)
2349 CharDriverState *chr;
2350 const char *chardev;
2351 const char *mode;
2352 int flags;
2354 mode = qemu_opt_get(opts, "mode");
2355 if (mode == NULL) {
2356 mode = "readline";
2358 if (strcmp(mode, "readline") == 0) {
2359 flags = MONITOR_USE_READLINE;
2360 } else if (strcmp(mode, "control") == 0) {
2361 flags = MONITOR_USE_CONTROL;
2362 } else {
2363 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2364 exit(1);
2367 if (qemu_opt_get_bool(opts, "default", 0))
2368 flags |= MONITOR_IS_DEFAULT;
2370 chardev = qemu_opt_get(opts, "chardev");
2371 chr = qemu_chr_find(chardev);
2372 if (chr == NULL) {
2373 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2374 exit(1);
2377 monitor_init(chr, flags);
2378 return 0;
2381 static void monitor_parse(const char *optarg, const char *mode)
2383 static int monitor_device_index = 0;
2384 QemuOpts *opts;
2385 const char *p;
2386 char label[32];
2387 int def = 0;
2389 if (strstart(optarg, "chardev:", &p)) {
2390 snprintf(label, sizeof(label), "%s", p);
2391 } else {
2392 if (monitor_device_index) {
2393 snprintf(label, sizeof(label), "monitor%d",
2394 monitor_device_index);
2395 } else {
2396 snprintf(label, sizeof(label), "monitor");
2397 def = 1;
2399 opts = qemu_chr_parse_compat(label, optarg);
2400 if (!opts) {
2401 fprintf(stderr, "parse error: %s\n", optarg);
2402 exit(1);
2406 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
2407 if (!opts) {
2408 fprintf(stderr, "duplicate chardev: %s\n", label);
2409 exit(1);
2411 qemu_opt_set(opts, "mode", mode);
2412 qemu_opt_set(opts, "chardev", label);
2413 if (def)
2414 qemu_opt_set(opts, "default", "on");
2415 monitor_device_index++;
2418 struct device_config {
2419 enum {
2420 DEV_USB, /* -usbdevice */
2421 DEV_BT, /* -bt */
2422 DEV_SERIAL, /* -serial */
2423 DEV_PARALLEL, /* -parallel */
2424 DEV_VIRTCON, /* -virtioconsole */
2425 DEV_DEBUGCON, /* -debugcon */
2426 } type;
2427 const char *cmdline;
2428 QTAILQ_ENTRY(device_config) next;
2430 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
2432 static void add_device_config(int type, const char *cmdline)
2434 struct device_config *conf;
2436 conf = qemu_mallocz(sizeof(*conf));
2437 conf->type = type;
2438 conf->cmdline = cmdline;
2439 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2442 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2444 struct device_config *conf;
2445 int rc;
2447 QTAILQ_FOREACH(conf, &device_configs, next) {
2448 if (conf->type != type)
2449 continue;
2450 rc = func(conf->cmdline);
2451 if (0 != rc)
2452 return rc;
2454 return 0;
2457 static int serial_parse(const char *devname)
2459 static int index = 0;
2460 char label[32];
2462 if (strcmp(devname, "none") == 0)
2463 return 0;
2464 if (index == MAX_SERIAL_PORTS) {
2465 fprintf(stderr, "qemu: too many serial ports\n");
2466 exit(1);
2468 snprintf(label, sizeof(label), "serial%d", index);
2469 serial_hds[index] = qemu_chr_open(label, devname, NULL);
2470 if (!serial_hds[index]) {
2471 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
2472 devname, strerror(errno));
2473 return -1;
2475 index++;
2476 return 0;
2479 static int parallel_parse(const char *devname)
2481 static int index = 0;
2482 char label[32];
2484 if (strcmp(devname, "none") == 0)
2485 return 0;
2486 if (index == MAX_PARALLEL_PORTS) {
2487 fprintf(stderr, "qemu: too many parallel ports\n");
2488 exit(1);
2490 snprintf(label, sizeof(label), "parallel%d", index);
2491 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
2492 if (!parallel_hds[index]) {
2493 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2494 devname, strerror(errno));
2495 return -1;
2497 index++;
2498 return 0;
2501 static int virtcon_parse(const char *devname)
2503 static int index = 0;
2504 char label[32];
2505 QemuOpts *bus_opts, *dev_opts;
2507 if (strcmp(devname, "none") == 0)
2508 return 0;
2509 if (index == MAX_VIRTIO_CONSOLES) {
2510 fprintf(stderr, "qemu: too many virtio consoles\n");
2511 exit(1);
2514 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2515 qemu_opt_set(bus_opts, "driver", "virtio-serial");
2517 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2518 qemu_opt_set(dev_opts, "driver", "virtconsole");
2520 snprintf(label, sizeof(label), "virtcon%d", index);
2521 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
2522 if (!virtcon_hds[index]) {
2523 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2524 devname, strerror(errno));
2525 return -1;
2527 qemu_opt_set(dev_opts, "chardev", label);
2529 index++;
2530 return 0;
2533 static int debugcon_parse(const char *devname)
2535 QemuOpts *opts;
2537 if (!qemu_chr_open("debugcon", devname, NULL)) {
2538 exit(1);
2540 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
2541 if (!opts) {
2542 fprintf(stderr, "qemu: already have a debugcon device\n");
2543 exit(1);
2545 qemu_opt_set(opts, "driver", "isa-debugcon");
2546 qemu_opt_set(opts, "chardev", "debugcon");
2547 return 0;
2550 static const QEMUOption *lookup_opt(int argc, char **argv,
2551 const char **poptarg, int *poptind)
2553 const QEMUOption *popt;
2554 int optind = *poptind;
2555 char *r = argv[optind];
2556 const char *optarg;
2558 loc_set_cmdline(argv, optind, 1);
2559 optind++;
2560 /* Treat --foo the same as -foo. */
2561 if (r[1] == '-')
2562 r++;
2563 popt = qemu_options;
2564 for(;;) {
2565 if (!popt->name) {
2566 error_report("invalid option");
2567 exit(1);
2569 if (!strcmp(popt->name, r + 1))
2570 break;
2571 popt++;
2573 if (popt->flags & HAS_ARG) {
2574 if (optind >= argc) {
2575 error_report("requires an argument");
2576 exit(1);
2578 optarg = argv[optind++];
2579 loc_set_cmdline(argv, optind - 2, 2);
2580 } else {
2581 optarg = NULL;
2584 *poptarg = optarg;
2585 *poptind = optind;
2587 return popt;
2590 int main(int argc, char **argv, char **envp)
2592 const char *gdbstub_dev = NULL;
2593 uint32_t boot_devices_bitmap = 0;
2594 int i;
2595 int snapshot, linux_boot, net_boot;
2596 const char *icount_option = NULL;
2597 const char *initrd_filename;
2598 const char *kernel_filename, *kernel_cmdline;
2599 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2600 DisplayState *ds;
2601 DisplayChangeListener *dcl;
2602 int cyls, heads, secs, translation;
2603 QemuOpts *hda_opts = NULL, *opts;
2604 int optind;
2605 const char *optarg;
2606 const char *loadvm = NULL;
2607 QEMUMachine *machine;
2608 const char *cpu_model;
2609 #ifndef _WIN32
2610 int fds[2];
2611 #endif
2612 int tb_size;
2613 const char *pid_file = NULL;
2614 const char *incoming = NULL;
2615 #ifndef _WIN32
2616 int fd = 0;
2617 struct passwd *pwd = NULL;
2618 const char *chroot_dir = NULL;
2619 const char *run_as = NULL;
2620 #endif
2621 int show_vnc_port = 0;
2622 int defconfig = 1;
2624 error_set_progname(argv[0]);
2626 init_clocks();
2628 qemu_cache_utils_init(envp);
2630 QLIST_INIT (&vm_change_state_head);
2631 #ifndef _WIN32
2633 struct sigaction act;
2634 sigfillset(&act.sa_mask);
2635 act.sa_flags = 0;
2636 act.sa_handler = SIG_IGN;
2637 sigaction(SIGPIPE, &act, NULL);
2639 #else
2640 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
2641 /* Note: cpu_interrupt() is currently not SMP safe, so we force
2642 QEMU to run on a single CPU */
2644 HANDLE h;
2645 DWORD mask, smask;
2646 int i;
2647 h = GetCurrentProcess();
2648 if (GetProcessAffinityMask(h, &mask, &smask)) {
2649 for(i = 0; i < 32; i++) {
2650 if (mask & (1 << i))
2651 break;
2653 if (i != 32) {
2654 mask = 1 << i;
2655 SetProcessAffinityMask(h, mask);
2659 #endif
2661 module_call_init(MODULE_INIT_MACHINE);
2662 machine = find_default_machine();
2663 cpu_model = NULL;
2664 initrd_filename = NULL;
2665 ram_size = 0;
2666 snapshot = 0;
2667 kernel_filename = NULL;
2668 kernel_cmdline = "";
2669 cyls = heads = secs = 0;
2670 translation = BIOS_ATA_TRANSLATION_AUTO;
2672 for (i = 0; i < MAX_NODES; i++) {
2673 node_mem[i] = 0;
2674 node_cpumask[i] = 0;
2677 nb_numa_nodes = 0;
2678 nb_nics = 0;
2680 tb_size = 0;
2681 autostart= 1;
2683 /* first pass of option parsing */
2684 optind = 1;
2685 while (optind < argc) {
2686 if (argv[optind][0] != '-') {
2687 /* disk image */
2688 optind++;
2689 continue;
2690 } else {
2691 const QEMUOption *popt;
2693 popt = lookup_opt(argc, argv, &optarg, &optind);
2694 switch (popt->index) {
2695 case QEMU_OPTION_nodefconfig:
2696 defconfig=0;
2697 break;
2702 if (defconfig) {
2703 const char *fname;
2704 FILE *fp;
2706 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
2707 fp = fopen(fname, "r");
2708 if (fp) {
2709 if (qemu_config_parse(fp, fname) != 0) {
2710 exit(1);
2712 fclose(fp);
2715 fname = arch_config_name;
2716 fp = fopen(fname, "r");
2717 if (fp) {
2718 if (qemu_config_parse(fp, fname) != 0) {
2719 exit(1);
2721 fclose(fp);
2724 cpudef_init();
2726 /* second pass of option parsing */
2727 optind = 1;
2728 for(;;) {
2729 if (optind >= argc)
2730 break;
2731 if (argv[optind][0] != '-') {
2732 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
2733 } else {
2734 const QEMUOption *popt;
2736 popt = lookup_opt(argc, argv, &optarg, &optind);
2737 if (!(popt->arch_mask & arch_type)) {
2738 printf("Option %s not supported for this target\n", popt->name);
2739 exit(1);
2741 switch(popt->index) {
2742 case QEMU_OPTION_M:
2743 machine = find_machine(optarg);
2744 if (!machine) {
2745 QEMUMachine *m;
2746 printf("Supported machines are:\n");
2747 for(m = first_machine; m != NULL; m = m->next) {
2748 if (m->alias)
2749 printf("%-10s %s (alias of %s)\n",
2750 m->alias, m->desc, m->name);
2751 printf("%-10s %s%s\n",
2752 m->name, m->desc,
2753 m->is_default ? " (default)" : "");
2755 exit(*optarg != '?');
2757 break;
2758 case QEMU_OPTION_cpu:
2759 /* hw initialization will check this */
2760 if (*optarg == '?') {
2761 /* XXX: implement xxx_cpu_list for targets that still miss it */
2762 #if defined(cpu_list_id)
2763 cpu_list_id(stdout, &fprintf, optarg);
2764 #elif defined(cpu_list)
2765 cpu_list(stdout, &fprintf); /* deprecated */
2766 #endif
2767 exit(0);
2768 } else {
2769 cpu_model = optarg;
2771 break;
2772 case QEMU_OPTION_initrd:
2773 initrd_filename = optarg;
2774 break;
2775 case QEMU_OPTION_hda:
2776 if (cyls == 0)
2777 hda_opts = drive_add(optarg, HD_ALIAS, 0);
2778 else
2779 hda_opts = drive_add(optarg, HD_ALIAS
2780 ",cyls=%d,heads=%d,secs=%d%s",
2781 0, cyls, heads, secs,
2782 translation == BIOS_ATA_TRANSLATION_LBA ?
2783 ",trans=lba" :
2784 translation == BIOS_ATA_TRANSLATION_NONE ?
2785 ",trans=none" : "");
2786 break;
2787 case QEMU_OPTION_hdb:
2788 case QEMU_OPTION_hdc:
2789 case QEMU_OPTION_hdd:
2790 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
2791 break;
2792 case QEMU_OPTION_drive:
2793 drive_add(NULL, "%s", optarg);
2794 break;
2795 case QEMU_OPTION_set:
2796 if (qemu_set_option(optarg) != 0)
2797 exit(1);
2798 break;
2799 case QEMU_OPTION_global:
2800 if (qemu_global_option(optarg) != 0)
2801 exit(1);
2802 break;
2803 case QEMU_OPTION_mtdblock:
2804 drive_add(optarg, MTD_ALIAS);
2805 break;
2806 case QEMU_OPTION_sd:
2807 drive_add(optarg, SD_ALIAS);
2808 break;
2809 case QEMU_OPTION_pflash:
2810 drive_add(optarg, PFLASH_ALIAS);
2811 break;
2812 case QEMU_OPTION_snapshot:
2813 snapshot = 1;
2814 break;
2815 case QEMU_OPTION_hdachs:
2817 const char *p;
2818 p = optarg;
2819 cyls = strtol(p, (char **)&p, 0);
2820 if (cyls < 1 || cyls > 16383)
2821 goto chs_fail;
2822 if (*p != ',')
2823 goto chs_fail;
2824 p++;
2825 heads = strtol(p, (char **)&p, 0);
2826 if (heads < 1 || heads > 16)
2827 goto chs_fail;
2828 if (*p != ',')
2829 goto chs_fail;
2830 p++;
2831 secs = strtol(p, (char **)&p, 0);
2832 if (secs < 1 || secs > 63)
2833 goto chs_fail;
2834 if (*p == ',') {
2835 p++;
2836 if (!strcmp(p, "none"))
2837 translation = BIOS_ATA_TRANSLATION_NONE;
2838 else if (!strcmp(p, "lba"))
2839 translation = BIOS_ATA_TRANSLATION_LBA;
2840 else if (!strcmp(p, "auto"))
2841 translation = BIOS_ATA_TRANSLATION_AUTO;
2842 else
2843 goto chs_fail;
2844 } else if (*p != '\0') {
2845 chs_fail:
2846 fprintf(stderr, "qemu: invalid physical CHS format\n");
2847 exit(1);
2849 if (hda_opts != NULL) {
2850 char num[16];
2851 snprintf(num, sizeof(num), "%d", cyls);
2852 qemu_opt_set(hda_opts, "cyls", num);
2853 snprintf(num, sizeof(num), "%d", heads);
2854 qemu_opt_set(hda_opts, "heads", num);
2855 snprintf(num, sizeof(num), "%d", secs);
2856 qemu_opt_set(hda_opts, "secs", num);
2857 if (translation == BIOS_ATA_TRANSLATION_LBA)
2858 qemu_opt_set(hda_opts, "trans", "lba");
2859 if (translation == BIOS_ATA_TRANSLATION_NONE)
2860 qemu_opt_set(hda_opts, "trans", "none");
2863 break;
2864 case QEMU_OPTION_numa:
2865 if (nb_numa_nodes >= MAX_NODES) {
2866 fprintf(stderr, "qemu: too many NUMA nodes\n");
2867 exit(1);
2869 numa_add(optarg);
2870 break;
2871 case QEMU_OPTION_nographic:
2872 display_type = DT_NOGRAPHIC;
2873 break;
2874 #ifdef CONFIG_CURSES
2875 case QEMU_OPTION_curses:
2876 display_type = DT_CURSES;
2877 break;
2878 #endif
2879 case QEMU_OPTION_portrait:
2880 graphic_rotate = 1;
2881 break;
2882 case QEMU_OPTION_kernel:
2883 kernel_filename = optarg;
2884 break;
2885 case QEMU_OPTION_append:
2886 kernel_cmdline = optarg;
2887 break;
2888 case QEMU_OPTION_cdrom:
2889 drive_add(optarg, CDROM_ALIAS);
2890 break;
2891 case QEMU_OPTION_boot:
2893 static const char * const params[] = {
2894 "order", "once", "menu", NULL
2896 char buf[sizeof(boot_devices)];
2897 char *standard_boot_devices;
2898 int legacy = 0;
2900 if (!strchr(optarg, '=')) {
2901 legacy = 1;
2902 pstrcpy(buf, sizeof(buf), optarg);
2903 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2904 fprintf(stderr,
2905 "qemu: unknown boot parameter '%s' in '%s'\n",
2906 buf, optarg);
2907 exit(1);
2910 if (legacy ||
2911 get_param_value(buf, sizeof(buf), "order", optarg)) {
2912 boot_devices_bitmap = parse_bootdevices(buf);
2913 pstrcpy(boot_devices, sizeof(boot_devices), buf);
2915 if (!legacy) {
2916 if (get_param_value(buf, sizeof(buf),
2917 "once", optarg)) {
2918 boot_devices_bitmap |= parse_bootdevices(buf);
2919 standard_boot_devices = qemu_strdup(boot_devices);
2920 pstrcpy(boot_devices, sizeof(boot_devices), buf);
2921 qemu_register_reset(restore_boot_devices,
2922 standard_boot_devices);
2924 if (get_param_value(buf, sizeof(buf),
2925 "menu", optarg)) {
2926 if (!strcmp(buf, "on")) {
2927 boot_menu = 1;
2928 } else if (!strcmp(buf, "off")) {
2929 boot_menu = 0;
2930 } else {
2931 fprintf(stderr,
2932 "qemu: invalid option value '%s'\n",
2933 buf);
2934 exit(1);
2939 break;
2940 case QEMU_OPTION_fda:
2941 case QEMU_OPTION_fdb:
2942 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
2943 break;
2944 case QEMU_OPTION_no_fd_bootchk:
2945 fd_bootchk = 0;
2946 break;
2947 case QEMU_OPTION_netdev:
2948 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
2949 exit(1);
2951 break;
2952 case QEMU_OPTION_net:
2953 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
2954 exit(1);
2956 break;
2957 #ifdef CONFIG_SLIRP
2958 case QEMU_OPTION_tftp:
2959 legacy_tftp_prefix = optarg;
2960 break;
2961 case QEMU_OPTION_bootp:
2962 legacy_bootp_filename = optarg;
2963 break;
2964 #ifndef _WIN32
2965 case QEMU_OPTION_smb:
2966 if (net_slirp_smb(optarg) < 0)
2967 exit(1);
2968 break;
2969 #endif
2970 case QEMU_OPTION_redir:
2971 if (net_slirp_redir(optarg) < 0)
2972 exit(1);
2973 break;
2974 #endif
2975 case QEMU_OPTION_bt:
2976 add_device_config(DEV_BT, optarg);
2977 break;
2978 case QEMU_OPTION_audio_help:
2979 if (!(audio_available())) {
2980 printf("Option %s not supported for this target\n", popt->name);
2981 exit(1);
2983 AUD_help ();
2984 exit (0);
2985 break;
2986 case QEMU_OPTION_soundhw:
2987 if (!(audio_available())) {
2988 printf("Option %s not supported for this target\n", popt->name);
2989 exit(1);
2991 select_soundhw (optarg);
2992 break;
2993 case QEMU_OPTION_h:
2994 help(0);
2995 break;
2996 case QEMU_OPTION_version:
2997 version();
2998 exit(0);
2999 break;
3000 case QEMU_OPTION_m: {
3001 uint64_t value;
3002 char *ptr;
3004 value = strtoul(optarg, &ptr, 10);
3005 switch (*ptr) {
3006 case 0: case 'M': case 'm':
3007 value <<= 20;
3008 break;
3009 case 'G': case 'g':
3010 value <<= 30;
3011 break;
3012 default:
3013 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
3014 exit(1);
3017 /* On 32-bit hosts, QEMU is limited by virtual address space */
3018 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
3019 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3020 exit(1);
3022 if (value != (uint64_t)(ram_addr_t)value) {
3023 fprintf(stderr, "qemu: ram size too large\n");
3024 exit(1);
3026 ram_size = value;
3027 break;
3029 case QEMU_OPTION_mempath:
3030 mem_path = optarg;
3031 break;
3032 #ifdef MAP_POPULATE
3033 case QEMU_OPTION_mem_prealloc:
3034 mem_prealloc = 1;
3035 break;
3036 #endif
3037 case QEMU_OPTION_d:
3038 set_cpu_log(optarg);
3039 break;
3040 case QEMU_OPTION_s:
3041 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
3042 break;
3043 case QEMU_OPTION_gdb:
3044 gdbstub_dev = optarg;
3045 break;
3046 case QEMU_OPTION_L:
3047 data_dir = optarg;
3048 break;
3049 case QEMU_OPTION_bios:
3050 bios_name = optarg;
3051 break;
3052 case QEMU_OPTION_singlestep:
3053 singlestep = 1;
3054 break;
3055 case QEMU_OPTION_S:
3056 autostart = 0;
3057 break;
3058 case QEMU_OPTION_k:
3059 keyboard_layout = optarg;
3060 break;
3061 case QEMU_OPTION_localtime:
3062 rtc_utc = 0;
3063 break;
3064 case QEMU_OPTION_vga:
3065 select_vgahw (optarg);
3066 break;
3067 case QEMU_OPTION_g:
3069 const char *p;
3070 int w, h, depth;
3071 p = optarg;
3072 w = strtol(p, (char **)&p, 10);
3073 if (w <= 0) {
3074 graphic_error:
3075 fprintf(stderr, "qemu: invalid resolution or depth\n");
3076 exit(1);
3078 if (*p != 'x')
3079 goto graphic_error;
3080 p++;
3081 h = strtol(p, (char **)&p, 10);
3082 if (h <= 0)
3083 goto graphic_error;
3084 if (*p == 'x') {
3085 p++;
3086 depth = strtol(p, (char **)&p, 10);
3087 if (depth != 8 && depth != 15 && depth != 16 &&
3088 depth != 24 && depth != 32)
3089 goto graphic_error;
3090 } else if (*p == '\0') {
3091 depth = graphic_depth;
3092 } else {
3093 goto graphic_error;
3096 graphic_width = w;
3097 graphic_height = h;
3098 graphic_depth = depth;
3100 break;
3101 case QEMU_OPTION_echr:
3103 char *r;
3104 term_escape_char = strtol(optarg, &r, 0);
3105 if (r == optarg)
3106 printf("Bad argument to echr\n");
3107 break;
3109 case QEMU_OPTION_monitor:
3110 monitor_parse(optarg, "readline");
3111 default_monitor = 0;
3112 break;
3113 case QEMU_OPTION_qmp:
3114 monitor_parse(optarg, "control");
3115 default_monitor = 0;
3116 break;
3117 case QEMU_OPTION_mon:
3118 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
3119 if (!opts) {
3120 fprintf(stderr, "parse error: %s\n", optarg);
3121 exit(1);
3123 default_monitor = 0;
3124 break;
3125 case QEMU_OPTION_chardev:
3126 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
3127 if (!opts) {
3128 fprintf(stderr, "parse error: %s\n", optarg);
3129 exit(1);
3131 break;
3132 case QEMU_OPTION_serial:
3133 add_device_config(DEV_SERIAL, optarg);
3134 default_serial = 0;
3135 if (strncmp(optarg, "mon:", 4) == 0) {
3136 default_monitor = 0;
3138 break;
3139 case QEMU_OPTION_watchdog:
3140 if (watchdog) {
3141 fprintf(stderr,
3142 "qemu: only one watchdog option may be given\n");
3143 return 1;
3145 watchdog = optarg;
3146 break;
3147 case QEMU_OPTION_watchdog_action:
3148 if (select_watchdog_action(optarg) == -1) {
3149 fprintf(stderr, "Unknown -watchdog-action parameter\n");
3150 exit(1);
3152 break;
3153 case QEMU_OPTION_virtiocon:
3154 add_device_config(DEV_VIRTCON, optarg);
3155 default_virtcon = 0;
3156 if (strncmp(optarg, "mon:", 4) == 0) {
3157 default_monitor = 0;
3159 break;
3160 case QEMU_OPTION_parallel:
3161 add_device_config(DEV_PARALLEL, optarg);
3162 default_parallel = 0;
3163 if (strncmp(optarg, "mon:", 4) == 0) {
3164 default_monitor = 0;
3166 break;
3167 case QEMU_OPTION_debugcon:
3168 add_device_config(DEV_DEBUGCON, optarg);
3169 break;
3170 case QEMU_OPTION_loadvm:
3171 loadvm = optarg;
3172 break;
3173 case QEMU_OPTION_full_screen:
3174 full_screen = 1;
3175 break;
3176 #ifdef CONFIG_SDL
3177 case QEMU_OPTION_no_frame:
3178 no_frame = 1;
3179 break;
3180 case QEMU_OPTION_alt_grab:
3181 alt_grab = 1;
3182 break;
3183 case QEMU_OPTION_ctrl_grab:
3184 ctrl_grab = 1;
3185 break;
3186 case QEMU_OPTION_no_quit:
3187 no_quit = 1;
3188 break;
3189 case QEMU_OPTION_sdl:
3190 display_type = DT_SDL;
3191 break;
3192 #endif
3193 case QEMU_OPTION_pidfile:
3194 pid_file = optarg;
3195 break;
3196 case QEMU_OPTION_win2k_hack:
3197 win2k_install_hack = 1;
3198 break;
3199 case QEMU_OPTION_rtc_td_hack:
3200 rtc_td_hack = 1;
3201 break;
3202 case QEMU_OPTION_acpitable:
3203 do_acpitable_option(optarg);
3204 break;
3205 case QEMU_OPTION_smbios:
3206 do_smbios_option(optarg);
3207 break;
3208 case QEMU_OPTION_enable_kvm:
3209 if (!(kvm_available())) {
3210 printf("Option %s not supported for this target\n", popt->name);
3211 exit(1);
3213 kvm_allowed = 1;
3214 break;
3215 case QEMU_OPTION_usb:
3216 usb_enabled = 1;
3217 break;
3218 case QEMU_OPTION_usbdevice:
3219 usb_enabled = 1;
3220 add_device_config(DEV_USB, optarg);
3221 break;
3222 case QEMU_OPTION_device:
3223 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
3224 exit(1);
3226 break;
3227 case QEMU_OPTION_smp:
3228 smp_parse(optarg);
3229 if (smp_cpus < 1) {
3230 fprintf(stderr, "Invalid number of CPUs\n");
3231 exit(1);
3233 if (max_cpus < smp_cpus) {
3234 fprintf(stderr, "maxcpus must be equal to or greater than "
3235 "smp\n");
3236 exit(1);
3238 if (max_cpus > 255) {
3239 fprintf(stderr, "Unsupported number of maxcpus\n");
3240 exit(1);
3242 break;
3243 case QEMU_OPTION_vnc:
3244 display_type = DT_VNC;
3245 vnc_display = optarg;
3246 break;
3247 case QEMU_OPTION_no_acpi:
3248 acpi_enabled = 0;
3249 break;
3250 case QEMU_OPTION_no_hpet:
3251 no_hpet = 1;
3252 break;
3253 case QEMU_OPTION_balloon:
3254 if (balloon_parse(optarg) < 0) {
3255 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3256 exit(1);
3258 break;
3259 case QEMU_OPTION_no_reboot:
3260 no_reboot = 1;
3261 break;
3262 case QEMU_OPTION_no_shutdown:
3263 no_shutdown = 1;
3264 break;
3265 case QEMU_OPTION_show_cursor:
3266 cursor_hide = 0;
3267 break;
3268 case QEMU_OPTION_uuid:
3269 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3270 fprintf(stderr, "Fail to parse UUID string."
3271 " Wrong format.\n");
3272 exit(1);
3274 break;
3275 #ifndef _WIN32
3276 case QEMU_OPTION_daemonize:
3277 daemonize = 1;
3278 break;
3279 #endif
3280 case QEMU_OPTION_option_rom:
3281 if (nb_option_roms >= MAX_OPTION_ROMS) {
3282 fprintf(stderr, "Too many option ROMs\n");
3283 exit(1);
3285 option_rom[nb_option_roms] = optarg;
3286 nb_option_roms++;
3287 break;
3288 case QEMU_OPTION_semihosting:
3289 semihosting_enabled = 1;
3290 break;
3291 case QEMU_OPTION_name:
3292 qemu_name = qemu_strdup(optarg);
3294 char *p = strchr(qemu_name, ',');
3295 if (p != NULL) {
3296 *p++ = 0;
3297 if (strncmp(p, "process=", 8)) {
3298 fprintf(stderr, "Unknown subargument %s to -name", p);
3299 exit(1);
3301 p += 8;
3302 set_proc_name(p);
3305 break;
3306 case QEMU_OPTION_prom_env:
3307 if (nb_prom_envs >= MAX_PROM_ENVS) {
3308 fprintf(stderr, "Too many prom variables\n");
3309 exit(1);
3311 prom_envs[nb_prom_envs] = optarg;
3312 nb_prom_envs++;
3313 break;
3314 case QEMU_OPTION_old_param:
3315 old_param = 1;
3316 break;
3317 case QEMU_OPTION_clock:
3318 configure_alarms(optarg);
3319 break;
3320 case QEMU_OPTION_startdate:
3321 configure_rtc_date_offset(optarg, 1);
3322 break;
3323 case QEMU_OPTION_rtc:
3324 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
3325 if (!opts) {
3326 fprintf(stderr, "parse error: %s\n", optarg);
3327 exit(1);
3329 configure_rtc(opts);
3330 break;
3331 case QEMU_OPTION_tb_size:
3332 tb_size = strtol(optarg, NULL, 0);
3333 if (tb_size < 0)
3334 tb_size = 0;
3335 break;
3336 case QEMU_OPTION_icount:
3337 icount_option = optarg;
3338 break;
3339 case QEMU_OPTION_incoming:
3340 incoming = optarg;
3341 break;
3342 case QEMU_OPTION_nodefaults:
3343 default_serial = 0;
3344 default_parallel = 0;
3345 default_virtcon = 0;
3346 default_monitor = 0;
3347 default_vga = 0;
3348 default_net = 0;
3349 default_floppy = 0;
3350 default_cdrom = 0;
3351 default_sdcard = 0;
3352 break;
3353 #ifndef _WIN32
3354 case QEMU_OPTION_chroot:
3355 chroot_dir = optarg;
3356 break;
3357 case QEMU_OPTION_runas:
3358 run_as = optarg;
3359 break;
3360 #endif
3361 case QEMU_OPTION_xen_domid:
3362 if (!(xen_available())) {
3363 printf("Option %s not supported for this target\n", popt->name);
3364 exit(1);
3366 xen_domid = atoi(optarg);
3367 break;
3368 case QEMU_OPTION_xen_create:
3369 if (!(xen_available())) {
3370 printf("Option %s not supported for this target\n", popt->name);
3371 exit(1);
3373 xen_mode = XEN_CREATE;
3374 break;
3375 case QEMU_OPTION_xen_attach:
3376 if (!(xen_available())) {
3377 printf("Option %s not supported for this target\n", popt->name);
3378 exit(1);
3380 xen_mode = XEN_ATTACH;
3381 break;
3382 case QEMU_OPTION_readconfig:
3384 FILE *fp;
3385 fp = fopen(optarg, "r");
3386 if (fp == NULL) {
3387 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3388 exit(1);
3390 if (qemu_config_parse(fp, optarg) != 0) {
3391 exit(1);
3393 fclose(fp);
3394 break;
3396 case QEMU_OPTION_writeconfig:
3398 FILE *fp;
3399 if (strcmp(optarg, "-") == 0) {
3400 fp = stdout;
3401 } else {
3402 fp = fopen(optarg, "w");
3403 if (fp == NULL) {
3404 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3405 exit(1);
3408 qemu_config_write(fp);
3409 fclose(fp);
3410 break;
3415 loc_set_none();
3417 /* If no data_dir is specified then try to find it relative to the
3418 executable path. */
3419 if (!data_dir) {
3420 data_dir = find_datadir(argv[0]);
3422 /* If all else fails use the install patch specified when building. */
3423 if (!data_dir) {
3424 data_dir = CONFIG_QEMU_SHAREDIR;
3428 * Default to max_cpus = smp_cpus, in case the user doesn't
3429 * specify a max_cpus value.
3431 if (!max_cpus)
3432 max_cpus = smp_cpus;
3434 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3435 if (smp_cpus > machine->max_cpus) {
3436 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3437 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
3438 machine->max_cpus);
3439 exit(1);
3442 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
3443 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
3445 if (machine->no_serial) {
3446 default_serial = 0;
3448 if (machine->no_parallel) {
3449 default_parallel = 0;
3451 if (!machine->use_virtcon) {
3452 default_virtcon = 0;
3454 if (machine->no_vga) {
3455 default_vga = 0;
3457 if (machine->no_floppy) {
3458 default_floppy = 0;
3460 if (machine->no_cdrom) {
3461 default_cdrom = 0;
3463 if (machine->no_sdcard) {
3464 default_sdcard = 0;
3467 if (display_type == DT_NOGRAPHIC) {
3468 if (default_parallel)
3469 add_device_config(DEV_PARALLEL, "null");
3470 if (default_serial && default_monitor) {
3471 add_device_config(DEV_SERIAL, "mon:stdio");
3472 } else if (default_virtcon && default_monitor) {
3473 add_device_config(DEV_VIRTCON, "mon:stdio");
3474 } else {
3475 if (default_serial)
3476 add_device_config(DEV_SERIAL, "stdio");
3477 if (default_virtcon)
3478 add_device_config(DEV_VIRTCON, "stdio");
3479 if (default_monitor)
3480 monitor_parse("stdio", "readline");
3482 } else {
3483 if (default_serial)
3484 add_device_config(DEV_SERIAL, "vc:80Cx24C");
3485 if (default_parallel)
3486 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3487 if (default_monitor)
3488 monitor_parse("vc:80Cx24C", "readline");
3489 if (default_virtcon)
3490 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3492 if (default_vga)
3493 vga_interface_type = VGA_CIRRUS;
3495 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
3496 exit(1);
3498 #ifndef _WIN32
3499 if (daemonize) {
3500 pid_t pid;
3502 if (pipe(fds) == -1)
3503 exit(1);
3505 pid = fork();
3506 if (pid > 0) {
3507 uint8_t status;
3508 ssize_t len;
3510 close(fds[1]);
3512 again:
3513 len = read(fds[0], &status, 1);
3514 if (len == -1 && (errno == EINTR))
3515 goto again;
3517 if (len != 1)
3518 exit(1);
3519 else if (status == 1) {
3520 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
3521 exit(1);
3522 } else
3523 exit(0);
3524 } else if (pid < 0)
3525 exit(1);
3527 close(fds[0]);
3528 qemu_set_cloexec(fds[1]);
3530 setsid();
3532 pid = fork();
3533 if (pid > 0)
3534 exit(0);
3535 else if (pid < 0)
3536 exit(1);
3538 umask(027);
3540 signal(SIGTSTP, SIG_IGN);
3541 signal(SIGTTOU, SIG_IGN);
3542 signal(SIGTTIN, SIG_IGN);
3544 #endif
3546 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3547 #ifndef _WIN32
3548 if (daemonize) {
3549 uint8_t status = 1;
3550 if (write(fds[1], &status, 1) != 1) {
3551 perror("daemonize. Writing to pipe\n");
3553 } else
3554 #endif
3555 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
3556 exit(1);
3559 if (kvm_enabled()) {
3560 int ret;
3562 ret = kvm_init(smp_cpus);
3563 if (ret < 0) {
3564 fprintf(stderr, "failed to initialize KVM\n");
3565 exit(1);
3569 if (qemu_init_main_loop()) {
3570 fprintf(stderr, "qemu_init_main_loop failed\n");
3571 exit(1);
3573 linux_boot = (kernel_filename != NULL);
3575 if (!linux_boot && *kernel_cmdline != '\0') {
3576 fprintf(stderr, "-append only allowed with -kernel option\n");
3577 exit(1);
3580 if (!linux_boot && initrd_filename != NULL) {
3581 fprintf(stderr, "-initrd only allowed with -kernel option\n");
3582 exit(1);
3585 #ifndef _WIN32
3586 /* Win32 doesn't support line-buffering and requires size >= 2 */
3587 setvbuf(stdout, NULL, _IOLBF, 0);
3588 #endif
3590 if (init_timer_alarm() < 0) {
3591 fprintf(stderr, "could not initialize alarm timer\n");
3592 exit(1);
3594 configure_icount(icount_option);
3596 socket_init();
3598 if (net_init_clients() < 0) {
3599 exit(1);
3602 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
3603 net_set_boot_mask(net_boot);
3605 /* init the bluetooth world */
3606 if (foreach_device_config(DEV_BT, bt_parse))
3607 exit(1);
3609 /* init the memory */
3610 if (ram_size == 0)
3611 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3613 /* init the dynamic translator */
3614 cpu_exec_init_all(tb_size * 1024 * 1024);
3616 bdrv_init_with_whitelist();
3618 blk_mig_init();
3620 if (default_cdrom) {
3621 /* we always create the cdrom drive, even if no disk is there */
3622 drive_add(NULL, CDROM_ALIAS);
3625 if (default_floppy) {
3626 /* we always create at least one floppy */
3627 drive_add(NULL, FD_ALIAS, 0);
3630 if (default_sdcard) {
3631 /* we always create one sd slot, even if no card is in it */
3632 drive_add(NULL, SD_ALIAS);
3635 /* open the virtual block devices */
3636 if (snapshot)
3637 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
3638 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
3639 exit(1);
3641 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
3642 ram_load, NULL);
3644 if (nb_numa_nodes > 0) {
3645 int i;
3647 if (nb_numa_nodes > smp_cpus) {
3648 nb_numa_nodes = smp_cpus;
3651 /* If no memory size if given for any node, assume the default case
3652 * and distribute the available memory equally across all nodes
3654 for (i = 0; i < nb_numa_nodes; i++) {
3655 if (node_mem[i] != 0)
3656 break;
3658 if (i == nb_numa_nodes) {
3659 uint64_t usedmem = 0;
3661 /* On Linux, the each node's border has to be 8MB aligned,
3662 * the final node gets the rest.
3664 for (i = 0; i < nb_numa_nodes - 1; i++) {
3665 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3666 usedmem += node_mem[i];
3668 node_mem[i] = ram_size - usedmem;
3671 for (i = 0; i < nb_numa_nodes; i++) {
3672 if (node_cpumask[i] != 0)
3673 break;
3675 /* assigning the VCPUs round-robin is easier to implement, guest OSes
3676 * must cope with this anyway, because there are BIOSes out there in
3677 * real machines which also use this scheme.
3679 if (i == nb_numa_nodes) {
3680 for (i = 0; i < smp_cpus; i++) {
3681 node_cpumask[i % nb_numa_nodes] |= 1 << i;
3686 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3687 exit(1);
3688 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3689 exit(1);
3690 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3691 exit(1);
3692 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3693 exit(1);
3695 module_call_init(MODULE_INIT_DEVICE);
3697 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
3698 exit(0);
3700 if (watchdog) {
3701 i = select_watchdog(watchdog);
3702 if (i > 0)
3703 exit (i == 1 ? 1 : 0);
3706 if (machine->compat_props) {
3707 qdev_prop_register_global_list(machine->compat_props);
3709 qemu_add_globals();
3711 machine->init(ram_size, boot_devices,
3712 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3714 cpu_synchronize_all_post_init();
3716 #ifndef _WIN32
3717 /* must be after terminal init, SDL library changes signal handlers */
3718 sighandler_setup();
3719 #endif
3721 set_numa_modes();
3723 current_machine = machine;
3725 /* init USB devices */
3726 if (usb_enabled) {
3727 if (foreach_device_config(DEV_USB, usb_parse) < 0)
3728 exit(1);
3731 /* init generic devices */
3732 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
3733 exit(1);
3735 net_check_clients();
3737 /* just use the first displaystate for the moment */
3738 ds = get_displaystate();
3740 if (display_type == DT_DEFAULT) {
3741 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3742 display_type = DT_SDL;
3743 #else
3744 display_type = DT_VNC;
3745 vnc_display = "localhost:0,to=99";
3746 show_vnc_port = 1;
3747 #endif
3751 switch (display_type) {
3752 case DT_NOGRAPHIC:
3753 break;
3754 #if defined(CONFIG_CURSES)
3755 case DT_CURSES:
3756 curses_display_init(ds, full_screen);
3757 break;
3758 #endif
3759 #if defined(CONFIG_SDL)
3760 case DT_SDL:
3761 sdl_display_init(ds, full_screen, no_frame);
3762 break;
3763 #elif defined(CONFIG_COCOA)
3764 case DT_SDL:
3765 cocoa_display_init(ds, full_screen);
3766 break;
3767 #endif
3768 case DT_VNC:
3769 vnc_display_init(ds);
3770 if (vnc_display_open(ds, vnc_display) < 0)
3771 exit(1);
3773 if (show_vnc_port) {
3774 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3776 break;
3777 default:
3778 break;
3780 dpy_resize(ds);
3782 dcl = ds->listeners;
3783 while (dcl != NULL) {
3784 if (dcl->dpy_refresh != NULL) {
3785 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
3786 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
3788 dcl = dcl->next;
3791 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
3792 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
3793 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
3796 text_consoles_set_display(ds);
3798 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
3799 exit(1);
3801 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3802 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3803 gdbstub_dev);
3804 exit(1);
3807 qdev_machine_creation_done();
3809 if (rom_load_all() != 0) {
3810 fprintf(stderr, "rom loading failed\n");
3811 exit(1);
3814 qemu_system_reset();
3815 if (loadvm) {
3816 if (load_vmstate(loadvm) < 0) {
3817 autostart = 0;
3821 if (incoming) {
3822 qemu_start_incoming_migration(incoming);
3823 } else if (autostart) {
3824 vm_start();
3827 #ifndef _WIN32
3828 if (daemonize) {
3829 uint8_t status = 0;
3830 ssize_t len;
3832 again1:
3833 len = write(fds[1], &status, 1);
3834 if (len == -1 && (errno == EINTR))
3835 goto again1;
3837 if (len != 1)
3838 exit(1);
3840 if (chdir("/")) {
3841 perror("not able to chdir to /");
3842 exit(1);
3844 TFR(fd = qemu_open("/dev/null", O_RDWR));
3845 if (fd == -1)
3846 exit(1);
3849 if (run_as) {
3850 pwd = getpwnam(run_as);
3851 if (!pwd) {
3852 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
3853 exit(1);
3857 if (chroot_dir) {
3858 if (chroot(chroot_dir) < 0) {
3859 fprintf(stderr, "chroot failed\n");
3860 exit(1);
3862 if (chdir("/")) {
3863 perror("not able to chdir to /");
3864 exit(1);
3868 if (run_as) {
3869 if (setgid(pwd->pw_gid) < 0) {
3870 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
3871 exit(1);
3873 if (setuid(pwd->pw_uid) < 0) {
3874 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
3875 exit(1);
3877 if (setuid(0) != -1) {
3878 fprintf(stderr, "Dropping privileges failed\n");
3879 exit(1);
3883 if (daemonize) {
3884 dup2(fd, 0);
3885 dup2(fd, 1);
3886 dup2(fd, 2);
3888 close(fd);
3890 #endif
3892 main_loop();
3893 quit_timers();
3894 net_cleanup();
3896 return 0;