Refactor CPUState handling out of vl.c
[qemu/aliguori-queue.git] / vl.c
blob15ab44c624e51a5b7366673e138437c389494766
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 #else
56 #include <util.h>
57 #endif
58 #else
59 #ifdef __linux__
60 #include <pty.h>
61 #include <malloc.h>
62 #include <sys/prctl.h>
64 #include <linux/ppdev.h>
65 #include <linux/parport.h>
66 #endif
67 #ifdef __sun__
68 #include <sys/stat.h>
69 #include <sys/ethernet.h>
70 #include <sys/sockio.h>
71 #include <netinet/arp.h>
72 #include <netinet/in.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/ip_icmp.h> // must come after ip.h
76 #include <netinet/udp.h>
77 #include <netinet/tcp.h>
78 #include <net/if.h>
79 #include <syslog.h>
80 #include <stropts.h>
81 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
82 discussion about Solaris header problems */
83 extern int madvise(caddr_t, size_t, int);
84 #endif
85 #endif
86 #endif
88 #if defined(__OpenBSD__)
89 #include <util.h>
90 #endif
92 #if defined(CONFIG_VDE)
93 #include <libvdeplug.h>
94 #endif
96 #ifdef _WIN32
97 #include <windows.h>
98 #endif
100 #ifdef CONFIG_SDL
101 #if defined(__APPLE__) || defined(main)
102 #include <SDL.h>
103 int qemu_main(int argc, char **argv, char **envp);
104 int main(int argc, char **argv)
106 return qemu_main(argc, argv, NULL);
108 #undef main
109 #define main qemu_main
110 #endif
111 #endif /* CONFIG_SDL */
113 #ifdef CONFIG_COCOA
114 #undef main
115 #define main qemu_main
116 #endif /* CONFIG_COCOA */
118 #include "hw/hw.h"
119 #include "hw/boards.h"
120 #include "hw/usb.h"
121 #include "hw/pcmcia.h"
122 #include "hw/pc.h"
123 #include "hw/audiodev.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 "exec-all.h"
158 #include "qemu_socket.h"
160 #include "slirp/libslirp.h"
162 #include "qemu-queue.h"
163 #include "cpus.h"
165 //#define DEBUG_NET
166 //#define DEBUG_SLIRP
168 #define DEFAULT_RAM_SIZE 128
170 #define MAX_VIRTIO_CONSOLES 1
172 static const char *data_dir;
173 const char *bios_name = NULL;
174 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
175 to store the VM snapshots */
176 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
177 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
178 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
179 DisplayType display_type = DT_DEFAULT;
180 const char* keyboard_layout = NULL;
181 ram_addr_t ram_size;
182 const char *mem_path = NULL;
183 #ifdef MAP_POPULATE
184 int mem_prealloc = 0; /* force preallocation of physical target memory */
185 #endif
186 int nb_nics;
187 NICInfo nd_table[MAX_NICS];
188 int vm_running;
189 int autostart;
190 static int rtc_utc = 1;
191 static int rtc_date_offset = -1; /* -1 means no change */
192 QEMUClock *rtc_clock;
193 int vga_interface_type = VGA_NONE;
194 #ifdef TARGET_SPARC
195 int graphic_width = 1024;
196 int graphic_height = 768;
197 int graphic_depth = 8;
198 #else
199 int graphic_width = 800;
200 int graphic_height = 600;
201 int graphic_depth = 15;
202 #endif
203 static int full_screen = 0;
204 #ifdef CONFIG_SDL
205 static int no_frame = 0;
206 #endif
207 int no_quit = 0;
208 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
209 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
210 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
211 int win2k_install_hack = 0;
212 #ifdef TARGET_I386
213 int rtc_td_hack = 0;
214 #endif
215 int usb_enabled = 0;
216 int singlestep = 0;
217 int smp_cpus = 1;
218 int max_cpus = 0;
219 int smp_cores = 1;
220 int smp_threads = 1;
221 const char *vnc_display;
222 int acpi_enabled = 1;
223 int no_hpet = 0;
224 int fd_bootchk = 1;
225 int no_reboot = 0;
226 int no_shutdown = 0;
227 int cursor_hide = 1;
228 int graphic_rotate = 0;
229 uint8_t irq0override = 1;
230 #ifndef _WIN32
231 int daemonize = 0;
232 #endif
233 const char *watchdog;
234 const char *option_rom[MAX_OPTION_ROMS];
235 int nb_option_roms;
236 int semihosting_enabled = 0;
237 #ifdef TARGET_ARM
238 int old_param = 0;
239 #endif
240 const char *qemu_name;
241 int alt_grab = 0;
242 int ctrl_grab = 0;
243 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
244 unsigned int nb_prom_envs = 0;
245 const char *prom_envs[MAX_PROM_ENVS];
246 #endif
247 int boot_menu;
249 int nb_numa_nodes;
250 uint64_t node_mem[MAX_NODES];
251 uint64_t node_cpumask[MAX_NODES];
253 static QEMUTimer *nographic_timer;
255 uint8_t qemu_uuid[16];
257 static QEMUBootSetHandler *boot_set_handler;
258 static void *boot_set_opaque;
260 int kvm_allowed = 0;
261 uint32_t xen_domid;
262 enum xen_mode xen_mode = XEN_EMULATE;
264 #ifdef SIGRTMIN
265 #define SIG_IPI (SIGRTMIN+4)
266 #else
267 #define SIG_IPI SIGUSR1
268 #endif
270 static int default_serial = 1;
271 static int default_parallel = 1;
272 static int default_virtcon = 1;
273 static int default_monitor = 1;
274 static int default_vga = 1;
275 static int default_floppy = 1;
276 static int default_cdrom = 1;
277 static int default_sdcard = 1;
279 static struct {
280 const char *driver;
281 int *flag;
282 } default_list[] = {
283 { .driver = "isa-serial", .flag = &default_serial },
284 { .driver = "isa-parallel", .flag = &default_parallel },
285 { .driver = "isa-fdc", .flag = &default_floppy },
286 { .driver = "ide-drive", .flag = &default_cdrom },
287 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
288 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
289 { .driver = "virtio-serial", .flag = &default_virtcon },
290 { .driver = "VGA", .flag = &default_vga },
291 { .driver = "cirrus-vga", .flag = &default_vga },
292 { .driver = "vmware-svga", .flag = &default_vga },
295 static int default_driver_check(QemuOpts *opts, void *opaque)
297 const char *driver = qemu_opt_get(opts, "driver");
298 int i;
300 if (!driver)
301 return 0;
302 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
303 if (strcmp(default_list[i].driver, driver) != 0)
304 continue;
305 *(default_list[i].flag) = 0;
307 return 0;
310 /***********************************************************/
311 /* x86 ISA bus support */
313 target_phys_addr_t isa_mem_base = 0;
314 PicState2 *isa_pic;
316 static void set_proc_name(const char *s)
318 #if defined(__linux__) && defined(PR_SET_NAME)
319 char name[16];
320 if (!s)
321 return;
322 name[sizeof(name) - 1] = 0;
323 strncpy(name, s, sizeof(name));
324 /* Could rewrite argv[0] too, but that's a bit more complicated.
325 This simple way is enough for `top'. */
326 prctl(PR_SET_NAME, name);
327 #endif
330 /***************/
331 /* ballooning */
333 static QEMUBalloonEvent *qemu_balloon_event;
334 void *qemu_balloon_event_opaque;
336 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
338 qemu_balloon_event = func;
339 qemu_balloon_event_opaque = opaque;
342 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
344 if (qemu_balloon_event) {
345 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
346 return 1;
347 } else {
348 return 0;
352 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
354 if (qemu_balloon_event) {
355 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
356 return 1;
357 } else {
358 return 0;
363 /***********************************************************/
364 /* real time host monotonic timer */
366 /* compute with 96 bit intermediate result: (a*b)/c */
367 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
369 union {
370 uint64_t ll;
371 struct {
372 #ifdef HOST_WORDS_BIGENDIAN
373 uint32_t high, low;
374 #else
375 uint32_t low, high;
376 #endif
377 } l;
378 } u, res;
379 uint64_t rl, rh;
381 u.ll = a;
382 rl = (uint64_t)u.l.low * (uint64_t)b;
383 rh = (uint64_t)u.l.high * (uint64_t)b;
384 rh += (rl >> 32);
385 res.l.high = rh / c;
386 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
387 return res.ll;
390 /***********************************************************/
391 /* host time/date access */
392 void qemu_get_timedate(struct tm *tm, int offset)
394 time_t ti;
395 struct tm *ret;
397 time(&ti);
398 ti += offset;
399 if (rtc_date_offset == -1) {
400 if (rtc_utc)
401 ret = gmtime(&ti);
402 else
403 ret = localtime(&ti);
404 } else {
405 ti -= rtc_date_offset;
406 ret = gmtime(&ti);
409 memcpy(tm, ret, sizeof(struct tm));
412 int qemu_timedate_diff(struct tm *tm)
414 time_t seconds;
416 if (rtc_date_offset == -1)
417 if (rtc_utc)
418 seconds = mktimegm(tm);
419 else
420 seconds = mktime(tm);
421 else
422 seconds = mktimegm(tm) + rtc_date_offset;
424 return seconds - time(NULL);
427 void rtc_change_mon_event(struct tm *tm)
429 QObject *data;
431 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
432 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
433 qobject_decref(data);
436 static void configure_rtc_date_offset(const char *startdate, int legacy)
438 time_t rtc_start_date;
439 struct tm tm;
441 if (!strcmp(startdate, "now") && legacy) {
442 rtc_date_offset = -1;
443 } else {
444 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
445 &tm.tm_year,
446 &tm.tm_mon,
447 &tm.tm_mday,
448 &tm.tm_hour,
449 &tm.tm_min,
450 &tm.tm_sec) == 6) {
451 /* OK */
452 } else if (sscanf(startdate, "%d-%d-%d",
453 &tm.tm_year,
454 &tm.tm_mon,
455 &tm.tm_mday) == 3) {
456 tm.tm_hour = 0;
457 tm.tm_min = 0;
458 tm.tm_sec = 0;
459 } else {
460 goto date_fail;
462 tm.tm_year -= 1900;
463 tm.tm_mon--;
464 rtc_start_date = mktimegm(&tm);
465 if (rtc_start_date == -1) {
466 date_fail:
467 fprintf(stderr, "Invalid date format. Valid formats are:\n"
468 "'2006-06-17T16:01:21' or '2006-06-17'\n");
469 exit(1);
471 rtc_date_offset = time(NULL) - rtc_start_date;
475 static void configure_rtc(QemuOpts *opts)
477 const char *value;
479 value = qemu_opt_get(opts, "base");
480 if (value) {
481 if (!strcmp(value, "utc")) {
482 rtc_utc = 1;
483 } else if (!strcmp(value, "localtime")) {
484 rtc_utc = 0;
485 } else {
486 configure_rtc_date_offset(value, 0);
489 value = qemu_opt_get(opts, "clock");
490 if (value) {
491 if (!strcmp(value, "host")) {
492 rtc_clock = host_clock;
493 } else if (!strcmp(value, "vm")) {
494 rtc_clock = vm_clock;
495 } else {
496 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
497 exit(1);
500 #ifdef TARGET_I386
501 value = qemu_opt_get(opts, "driftfix");
502 if (value) {
503 if (!strcmp(value, "slew")) {
504 rtc_td_hack = 1;
505 } else if (!strcmp(value, "none")) {
506 rtc_td_hack = 0;
507 } else {
508 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
509 exit(1);
512 #endif
515 #ifdef _WIN32
516 static void socket_cleanup(void)
518 WSACleanup();
521 static int socket_init(void)
523 WSADATA Data;
524 int ret, err;
526 ret = WSAStartup(MAKEWORD(2,2), &Data);
527 if (ret != 0) {
528 err = WSAGetLastError();
529 fprintf(stderr, "WSAStartup: %d\n", err);
530 return -1;
532 atexit(socket_cleanup);
533 return 0;
535 #endif
537 /***********************************************************/
538 /* Bluetooth support */
539 static int nb_hcis;
540 static int cur_hci;
541 static struct HCIInfo *hci_table[MAX_NICS];
543 static struct bt_vlan_s {
544 struct bt_scatternet_s net;
545 int id;
546 struct bt_vlan_s *next;
547 } *first_bt_vlan;
549 /* find or alloc a new bluetooth "VLAN" */
550 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
552 struct bt_vlan_s **pvlan, *vlan;
553 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
554 if (vlan->id == id)
555 return &vlan->net;
557 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
558 vlan->id = id;
559 pvlan = &first_bt_vlan;
560 while (*pvlan != NULL)
561 pvlan = &(*pvlan)->next;
562 *pvlan = vlan;
563 return &vlan->net;
566 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
570 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
572 return -ENOTSUP;
575 static struct HCIInfo null_hci = {
576 .cmd_send = null_hci_send,
577 .sco_send = null_hci_send,
578 .acl_send = null_hci_send,
579 .bdaddr_set = null_hci_addr_set,
582 struct HCIInfo *qemu_next_hci(void)
584 if (cur_hci == nb_hcis)
585 return &null_hci;
587 return hci_table[cur_hci++];
590 static struct HCIInfo *hci_init(const char *str)
592 char *endp;
593 struct bt_scatternet_s *vlan = 0;
595 if (!strcmp(str, "null"))
596 /* null */
597 return &null_hci;
598 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
599 /* host[:hciN] */
600 return bt_host_hci(str[4] ? str + 5 : "hci0");
601 else if (!strncmp(str, "hci", 3)) {
602 /* hci[,vlan=n] */
603 if (str[3]) {
604 if (!strncmp(str + 3, ",vlan=", 6)) {
605 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
606 if (*endp)
607 vlan = 0;
609 } else
610 vlan = qemu_find_bt_vlan(0);
611 if (vlan)
612 return bt_new_hci(vlan);
615 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
617 return 0;
620 static int bt_hci_parse(const char *str)
622 struct HCIInfo *hci;
623 bdaddr_t bdaddr;
625 if (nb_hcis >= MAX_NICS) {
626 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
627 return -1;
630 hci = hci_init(str);
631 if (!hci)
632 return -1;
634 bdaddr.b[0] = 0x52;
635 bdaddr.b[1] = 0x54;
636 bdaddr.b[2] = 0x00;
637 bdaddr.b[3] = 0x12;
638 bdaddr.b[4] = 0x34;
639 bdaddr.b[5] = 0x56 + nb_hcis;
640 hci->bdaddr_set(hci, bdaddr.b);
642 hci_table[nb_hcis++] = hci;
644 return 0;
647 static void bt_vhci_add(int vlan_id)
649 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
651 if (!vlan->slave)
652 fprintf(stderr, "qemu: warning: adding a VHCI to "
653 "an empty scatternet %i\n", vlan_id);
655 bt_vhci_init(bt_new_hci(vlan));
658 static struct bt_device_s *bt_device_add(const char *opt)
660 struct bt_scatternet_s *vlan;
661 int vlan_id = 0;
662 char *endp = strstr(opt, ",vlan=");
663 int len = (endp ? endp - opt : strlen(opt)) + 1;
664 char devname[10];
666 pstrcpy(devname, MIN(sizeof(devname), len), opt);
668 if (endp) {
669 vlan_id = strtol(endp + 6, &endp, 0);
670 if (*endp) {
671 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
672 return 0;
676 vlan = qemu_find_bt_vlan(vlan_id);
678 if (!vlan->slave)
679 fprintf(stderr, "qemu: warning: adding a slave device to "
680 "an empty scatternet %i\n", vlan_id);
682 if (!strcmp(devname, "keyboard"))
683 return bt_keyboard_init(vlan);
685 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
686 return 0;
689 static int bt_parse(const char *opt)
691 const char *endp, *p;
692 int vlan;
694 if (strstart(opt, "hci", &endp)) {
695 if (!*endp || *endp == ',') {
696 if (*endp)
697 if (!strstart(endp, ",vlan=", 0))
698 opt = endp + 1;
700 return bt_hci_parse(opt);
702 } else if (strstart(opt, "vhci", &endp)) {
703 if (!*endp || *endp == ',') {
704 if (*endp) {
705 if (strstart(endp, ",vlan=", &p)) {
706 vlan = strtol(p, (char **) &endp, 0);
707 if (*endp) {
708 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
709 return 1;
711 } else {
712 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
713 return 1;
715 } else
716 vlan = 0;
718 bt_vhci_add(vlan);
719 return 0;
721 } else if (strstart(opt, "device:", &endp))
722 return !bt_device_add(endp);
724 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
725 return 1;
728 /***********************************************************/
729 /* QEMU Block devices */
731 #define HD_ALIAS "index=%d,media=disk"
732 #define CDROM_ALIAS "index=2,media=cdrom"
733 #define FD_ALIAS "index=%d,if=floppy"
734 #define PFLASH_ALIAS "if=pflash"
735 #define MTD_ALIAS "if=mtd"
736 #define SD_ALIAS "index=0,if=sd"
738 QemuOpts *drive_add(const char *file, const char *fmt, ...)
740 va_list ap;
741 char optstr[1024];
742 QemuOpts *opts;
744 va_start(ap, fmt);
745 vsnprintf(optstr, sizeof(optstr), fmt, ap);
746 va_end(ap);
748 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
749 if (!opts) {
750 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
751 __FUNCTION__, optstr);
752 return NULL;
754 if (file)
755 qemu_opt_set(opts, "file", file);
756 return opts;
759 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
761 DriveInfo *dinfo;
763 /* seek interface, bus and unit */
765 QTAILQ_FOREACH(dinfo, &drives, next) {
766 if (dinfo->type == type &&
767 dinfo->bus == bus &&
768 dinfo->unit == unit)
769 return dinfo;
772 return NULL;
775 DriveInfo *drive_get_by_id(const char *id)
777 DriveInfo *dinfo;
779 QTAILQ_FOREACH(dinfo, &drives, next) {
780 if (strcmp(id, dinfo->id))
781 continue;
782 return dinfo;
784 return NULL;
787 int drive_get_max_bus(BlockInterfaceType type)
789 int max_bus;
790 DriveInfo *dinfo;
792 max_bus = -1;
793 QTAILQ_FOREACH(dinfo, &drives, next) {
794 if(dinfo->type == type &&
795 dinfo->bus > max_bus)
796 max_bus = dinfo->bus;
798 return max_bus;
801 const char *drive_get_serial(BlockDriverState *bdrv)
803 DriveInfo *dinfo;
805 QTAILQ_FOREACH(dinfo, &drives, next) {
806 if (dinfo->bdrv == bdrv)
807 return dinfo->serial;
810 return "\0";
813 BlockInterfaceErrorAction drive_get_on_error(
814 BlockDriverState *bdrv, int is_read)
816 DriveInfo *dinfo;
818 QTAILQ_FOREACH(dinfo, &drives, next) {
819 if (dinfo->bdrv == bdrv)
820 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
823 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
826 static void bdrv_format_print(void *opaque, const char *name)
828 fprintf(stderr, " %s", name);
831 void drive_uninit(DriveInfo *dinfo)
833 qemu_opts_del(dinfo->opts);
834 bdrv_delete(dinfo->bdrv);
835 QTAILQ_REMOVE(&drives, dinfo, next);
836 qemu_free(dinfo);
839 static int parse_block_error_action(const char *buf, int is_read)
841 if (!strcmp(buf, "ignore")) {
842 return BLOCK_ERR_IGNORE;
843 } else if (!is_read && !strcmp(buf, "enospc")) {
844 return BLOCK_ERR_STOP_ENOSPC;
845 } else if (!strcmp(buf, "stop")) {
846 return BLOCK_ERR_STOP_ANY;
847 } else if (!strcmp(buf, "report")) {
848 return BLOCK_ERR_REPORT;
849 } else {
850 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
851 buf, is_read ? "read" : "write");
852 return -1;
856 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
857 int *fatal_error)
859 const char *buf;
860 const char *file = NULL;
861 char devname[128];
862 const char *serial;
863 const char *mediastr = "";
864 BlockInterfaceType type;
865 enum { MEDIA_DISK, MEDIA_CDROM } media;
866 int bus_id, unit_id;
867 int cyls, heads, secs, translation;
868 BlockDriver *drv = NULL;
869 QEMUMachine *machine = opaque;
870 int max_devs;
871 int index;
872 int cache;
873 int aio = 0;
874 int ro = 0;
875 int bdrv_flags;
876 int on_read_error, on_write_error;
877 const char *devaddr;
878 DriveInfo *dinfo;
879 int snapshot = 0;
881 *fatal_error = 1;
883 translation = BIOS_ATA_TRANSLATION_AUTO;
884 cache = 1;
886 if (machine && machine->use_scsi) {
887 type = IF_SCSI;
888 max_devs = MAX_SCSI_DEVS;
889 pstrcpy(devname, sizeof(devname), "scsi");
890 } else {
891 type = IF_IDE;
892 max_devs = MAX_IDE_DEVS;
893 pstrcpy(devname, sizeof(devname), "ide");
895 media = MEDIA_DISK;
897 /* extract parameters */
898 bus_id = qemu_opt_get_number(opts, "bus", 0);
899 unit_id = qemu_opt_get_number(opts, "unit", -1);
900 index = qemu_opt_get_number(opts, "index", -1);
902 cyls = qemu_opt_get_number(opts, "cyls", 0);
903 heads = qemu_opt_get_number(opts, "heads", 0);
904 secs = qemu_opt_get_number(opts, "secs", 0);
906 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
907 ro = qemu_opt_get_bool(opts, "readonly", 0);
909 file = qemu_opt_get(opts, "file");
910 serial = qemu_opt_get(opts, "serial");
912 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
913 pstrcpy(devname, sizeof(devname), buf);
914 if (!strcmp(buf, "ide")) {
915 type = IF_IDE;
916 max_devs = MAX_IDE_DEVS;
917 } else if (!strcmp(buf, "scsi")) {
918 type = IF_SCSI;
919 max_devs = MAX_SCSI_DEVS;
920 } else if (!strcmp(buf, "floppy")) {
921 type = IF_FLOPPY;
922 max_devs = 0;
923 } else if (!strcmp(buf, "pflash")) {
924 type = IF_PFLASH;
925 max_devs = 0;
926 } else if (!strcmp(buf, "mtd")) {
927 type = IF_MTD;
928 max_devs = 0;
929 } else if (!strcmp(buf, "sd")) {
930 type = IF_SD;
931 max_devs = 0;
932 } else if (!strcmp(buf, "virtio")) {
933 type = IF_VIRTIO;
934 max_devs = 0;
935 } else if (!strcmp(buf, "xen")) {
936 type = IF_XEN;
937 max_devs = 0;
938 } else if (!strcmp(buf, "none")) {
939 type = IF_NONE;
940 max_devs = 0;
941 } else {
942 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
943 return NULL;
947 if (cyls || heads || secs) {
948 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
949 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
950 return NULL;
952 if (heads < 1 || (type == IF_IDE && heads > 16)) {
953 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
954 return NULL;
956 if (secs < 1 || (type == IF_IDE && secs > 63)) {
957 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
958 return NULL;
962 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
963 if (!cyls) {
964 fprintf(stderr,
965 "qemu: '%s' trans must be used with cyls,heads and secs\n",
966 buf);
967 return NULL;
969 if (!strcmp(buf, "none"))
970 translation = BIOS_ATA_TRANSLATION_NONE;
971 else if (!strcmp(buf, "lba"))
972 translation = BIOS_ATA_TRANSLATION_LBA;
973 else if (!strcmp(buf, "auto"))
974 translation = BIOS_ATA_TRANSLATION_AUTO;
975 else {
976 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
977 return NULL;
981 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
982 if (!strcmp(buf, "disk")) {
983 media = MEDIA_DISK;
984 } else if (!strcmp(buf, "cdrom")) {
985 if (cyls || secs || heads) {
986 fprintf(stderr,
987 "qemu: '%s' invalid physical CHS format\n", buf);
988 return NULL;
990 media = MEDIA_CDROM;
991 } else {
992 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
993 return NULL;
997 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
998 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
999 cache = 0;
1000 else if (!strcmp(buf, "writethrough"))
1001 cache = 1;
1002 else if (!strcmp(buf, "writeback"))
1003 cache = 2;
1004 else {
1005 fprintf(stderr, "qemu: invalid cache option\n");
1006 return NULL;
1010 #ifdef CONFIG_LINUX_AIO
1011 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1012 if (!strcmp(buf, "threads"))
1013 aio = 0;
1014 else if (!strcmp(buf, "native"))
1015 aio = 1;
1016 else {
1017 fprintf(stderr, "qemu: invalid aio option\n");
1018 return NULL;
1021 #endif
1023 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1024 if (strcmp(buf, "?") == 0) {
1025 fprintf(stderr, "qemu: Supported formats:");
1026 bdrv_iterate_format(bdrv_format_print, NULL);
1027 fprintf(stderr, "\n");
1028 return NULL;
1030 drv = bdrv_find_whitelisted_format(buf);
1031 if (!drv) {
1032 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1033 return NULL;
1037 on_write_error = BLOCK_ERR_STOP_ENOSPC;
1038 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1039 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1040 fprintf(stderr, "werror is no supported by this format\n");
1041 return NULL;
1044 on_write_error = parse_block_error_action(buf, 0);
1045 if (on_write_error < 0) {
1046 return NULL;
1050 on_read_error = BLOCK_ERR_REPORT;
1051 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1052 if (type != IF_IDE && type != IF_VIRTIO) {
1053 fprintf(stderr, "rerror is no supported by this format\n");
1054 return NULL;
1057 on_read_error = parse_block_error_action(buf, 1);
1058 if (on_read_error < 0) {
1059 return NULL;
1063 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1064 if (type != IF_VIRTIO) {
1065 fprintf(stderr, "addr is not supported\n");
1066 return NULL;
1070 /* compute bus and unit according index */
1072 if (index != -1) {
1073 if (bus_id != 0 || unit_id != -1) {
1074 fprintf(stderr,
1075 "qemu: index cannot be used with bus and unit\n");
1076 return NULL;
1078 if (max_devs == 0)
1080 unit_id = index;
1081 bus_id = 0;
1082 } else {
1083 unit_id = index % max_devs;
1084 bus_id = index / max_devs;
1088 /* if user doesn't specify a unit_id,
1089 * try to find the first free
1092 if (unit_id == -1) {
1093 unit_id = 0;
1094 while (drive_get(type, bus_id, unit_id) != NULL) {
1095 unit_id++;
1096 if (max_devs && unit_id >= max_devs) {
1097 unit_id -= max_devs;
1098 bus_id++;
1103 /* check unit id */
1105 if (max_devs && unit_id >= max_devs) {
1106 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1107 unit_id, max_devs - 1);
1108 return NULL;
1112 * ignore multiple definitions
1115 if (drive_get(type, bus_id, unit_id) != NULL) {
1116 *fatal_error = 0;
1117 return NULL;
1120 /* init */
1122 dinfo = qemu_mallocz(sizeof(*dinfo));
1123 if ((buf = qemu_opts_id(opts)) != NULL) {
1124 dinfo->id = qemu_strdup(buf);
1125 } else {
1126 /* no id supplied -> create one */
1127 dinfo->id = qemu_mallocz(32);
1128 if (type == IF_IDE || type == IF_SCSI)
1129 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1130 if (max_devs)
1131 snprintf(dinfo->id, 32, "%s%i%s%i",
1132 devname, bus_id, mediastr, unit_id);
1133 else
1134 snprintf(dinfo->id, 32, "%s%s%i",
1135 devname, mediastr, unit_id);
1137 dinfo->bdrv = bdrv_new(dinfo->id);
1138 dinfo->devaddr = devaddr;
1139 dinfo->type = type;
1140 dinfo->bus = bus_id;
1141 dinfo->unit = unit_id;
1142 dinfo->on_read_error = on_read_error;
1143 dinfo->on_write_error = on_write_error;
1144 dinfo->opts = opts;
1145 if (serial)
1146 strncpy(dinfo->serial, serial, sizeof(serial));
1147 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1149 switch(type) {
1150 case IF_IDE:
1151 case IF_SCSI:
1152 case IF_XEN:
1153 case IF_NONE:
1154 switch(media) {
1155 case MEDIA_DISK:
1156 if (cyls != 0) {
1157 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1158 bdrv_set_translation_hint(dinfo->bdrv, translation);
1160 break;
1161 case MEDIA_CDROM:
1162 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1163 break;
1165 break;
1166 case IF_SD:
1167 /* FIXME: This isn't really a floppy, but it's a reasonable
1168 approximation. */
1169 case IF_FLOPPY:
1170 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1171 break;
1172 case IF_PFLASH:
1173 case IF_MTD:
1174 break;
1175 case IF_VIRTIO:
1176 /* add virtio block device */
1177 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1178 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1179 qemu_opt_set(opts, "drive", dinfo->id);
1180 if (devaddr)
1181 qemu_opt_set(opts, "addr", devaddr);
1182 break;
1183 case IF_COUNT:
1184 abort();
1186 if (!file) {
1187 *fatal_error = 0;
1188 return NULL;
1190 bdrv_flags = 0;
1191 if (snapshot) {
1192 bdrv_flags |= BDRV_O_SNAPSHOT;
1193 cache = 2; /* always use write-back with snapshot */
1195 if (cache == 0) /* no caching */
1196 bdrv_flags |= BDRV_O_NOCACHE;
1197 else if (cache == 2) /* write-back */
1198 bdrv_flags |= BDRV_O_CACHE_WB;
1200 if (aio == 1) {
1201 bdrv_flags |= BDRV_O_NATIVE_AIO;
1202 } else {
1203 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1206 if (ro == 1) {
1207 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1208 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1209 return NULL;
1213 * cdrom is read-only. Set it now, after above interface checking
1214 * since readonly attribute not explicitly required, so no error.
1216 if (media == MEDIA_CDROM) {
1217 ro = 1;
1219 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1221 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1222 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1223 file, strerror(errno));
1224 return NULL;
1227 if (bdrv_key_required(dinfo->bdrv))
1228 autostart = 0;
1229 *fatal_error = 0;
1230 return dinfo;
1233 static int drive_init_func(QemuOpts *opts, void *opaque)
1235 QEMUMachine *machine = opaque;
1236 int fatal_error = 0;
1238 if (drive_init(opts, machine, &fatal_error) == NULL) {
1239 if (fatal_error)
1240 return 1;
1242 return 0;
1245 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1247 if (NULL == qemu_opt_get(opts, "snapshot")) {
1248 qemu_opt_set(opts, "snapshot", "on");
1250 return 0;
1253 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1255 boot_set_handler = func;
1256 boot_set_opaque = opaque;
1259 int qemu_boot_set(const char *boot_devices)
1261 if (!boot_set_handler) {
1262 return -EINVAL;
1264 return boot_set_handler(boot_set_opaque, boot_devices);
1267 static int parse_bootdevices(char *devices)
1269 /* We just do some generic consistency checks */
1270 const char *p;
1271 int bitmap = 0;
1273 for (p = devices; *p != '\0'; p++) {
1274 /* Allowed boot devices are:
1275 * a-b: floppy disk drives
1276 * c-f: IDE disk drives
1277 * g-m: machine implementation dependant drives
1278 * n-p: network devices
1279 * It's up to each machine implementation to check if the given boot
1280 * devices match the actual hardware implementation and firmware
1281 * features.
1283 if (*p < 'a' || *p > 'p') {
1284 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1285 exit(1);
1287 if (bitmap & (1 << (*p - 'a'))) {
1288 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1289 exit(1);
1291 bitmap |= 1 << (*p - 'a');
1293 return bitmap;
1296 static void restore_boot_devices(void *opaque)
1298 char *standard_boot_devices = opaque;
1300 qemu_boot_set(standard_boot_devices);
1302 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1303 qemu_free(standard_boot_devices);
1306 static void numa_add(const char *optarg)
1308 char option[128];
1309 char *endptr;
1310 unsigned long long value, endvalue;
1311 int nodenr;
1313 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1314 if (!strcmp(option, "node")) {
1315 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1316 nodenr = nb_numa_nodes;
1317 } else {
1318 nodenr = strtoull(option, NULL, 10);
1321 if (get_param_value(option, 128, "mem", optarg) == 0) {
1322 node_mem[nodenr] = 0;
1323 } else {
1324 value = strtoull(option, &endptr, 0);
1325 switch (*endptr) {
1326 case 0: case 'M': case 'm':
1327 value <<= 20;
1328 break;
1329 case 'G': case 'g':
1330 value <<= 30;
1331 break;
1333 node_mem[nodenr] = value;
1335 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1336 node_cpumask[nodenr] = 0;
1337 } else {
1338 value = strtoull(option, &endptr, 10);
1339 if (value >= 64) {
1340 value = 63;
1341 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1342 } else {
1343 if (*endptr == '-') {
1344 endvalue = strtoull(endptr+1, &endptr, 10);
1345 if (endvalue >= 63) {
1346 endvalue = 62;
1347 fprintf(stderr,
1348 "only 63 CPUs in NUMA mode supported.\n");
1350 value = (2ULL << endvalue) - (1ULL << value);
1351 } else {
1352 value = 1ULL << value;
1355 node_cpumask[nodenr] = value;
1357 nb_numa_nodes++;
1359 return;
1362 static void smp_parse(const char *optarg)
1364 int smp, sockets = 0, threads = 0, cores = 0;
1365 char *endptr;
1366 char option[128];
1368 smp = strtoul(optarg, &endptr, 10);
1369 if (endptr != optarg) {
1370 if (*endptr == ',') {
1371 endptr++;
1374 if (get_param_value(option, 128, "sockets", endptr) != 0)
1375 sockets = strtoull(option, NULL, 10);
1376 if (get_param_value(option, 128, "cores", endptr) != 0)
1377 cores = strtoull(option, NULL, 10);
1378 if (get_param_value(option, 128, "threads", endptr) != 0)
1379 threads = strtoull(option, NULL, 10);
1380 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1381 max_cpus = strtoull(option, NULL, 10);
1383 /* compute missing values, prefer sockets over cores over threads */
1384 if (smp == 0 || sockets == 0) {
1385 sockets = sockets > 0 ? sockets : 1;
1386 cores = cores > 0 ? cores : 1;
1387 threads = threads > 0 ? threads : 1;
1388 if (smp == 0) {
1389 smp = cores * threads * sockets;
1391 } else {
1392 if (cores == 0) {
1393 threads = threads > 0 ? threads : 1;
1394 cores = smp / (sockets * threads);
1395 } else {
1396 if (sockets) {
1397 threads = smp / (cores * sockets);
1401 smp_cpus = smp;
1402 smp_cores = cores > 0 ? cores : 1;
1403 smp_threads = threads > 0 ? threads : 1;
1404 if (max_cpus == 0)
1405 max_cpus = smp_cpus;
1408 /***********************************************************/
1409 /* USB devices */
1411 static int usb_device_add(const char *devname, int is_hotplug)
1413 const char *p;
1414 USBDevice *dev = NULL;
1416 if (!usb_enabled)
1417 return -1;
1419 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1420 dev = usbdevice_create(devname);
1421 if (dev)
1422 goto done;
1424 /* the other ones */
1425 if (strstart(devname, "host:", &p)) {
1426 dev = usb_host_device_open(p);
1427 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1428 dev = usb_bt_init(devname[2] ? hci_init(p) :
1429 bt_new_hci(qemu_find_bt_vlan(0)));
1430 } else {
1431 return -1;
1433 if (!dev)
1434 return -1;
1436 done:
1437 return 0;
1440 static int usb_device_del(const char *devname)
1442 int bus_num, addr;
1443 const char *p;
1445 if (strstart(devname, "host:", &p))
1446 return usb_host_device_close(p);
1448 if (!usb_enabled)
1449 return -1;
1451 p = strchr(devname, '.');
1452 if (!p)
1453 return -1;
1454 bus_num = strtoul(devname, NULL, 0);
1455 addr = strtoul(p + 1, NULL, 0);
1457 return usb_device_delete_addr(bus_num, addr);
1460 static int usb_parse(const char *cmdline)
1462 int r;
1463 r = usb_device_add(cmdline, 0);
1464 if (r < 0) {
1465 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1467 return r;
1470 void do_usb_add(Monitor *mon, const QDict *qdict)
1472 const char *devname = qdict_get_str(qdict, "devname");
1473 if (usb_device_add(devname, 1) < 0) {
1474 error_report("could not add USB device '%s'", devname);
1478 void do_usb_del(Monitor *mon, const QDict *qdict)
1480 const char *devname = qdict_get_str(qdict, "devname");
1481 if (usb_device_del(devname) < 0) {
1482 error_report("could not delete USB device '%s'", devname);
1486 /***********************************************************/
1487 /* PCMCIA/Cardbus */
1489 static struct pcmcia_socket_entry_s {
1490 PCMCIASocket *socket;
1491 struct pcmcia_socket_entry_s *next;
1492 } *pcmcia_sockets = 0;
1494 void pcmcia_socket_register(PCMCIASocket *socket)
1496 struct pcmcia_socket_entry_s *entry;
1498 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1499 entry->socket = socket;
1500 entry->next = pcmcia_sockets;
1501 pcmcia_sockets = entry;
1504 void pcmcia_socket_unregister(PCMCIASocket *socket)
1506 struct pcmcia_socket_entry_s *entry, **ptr;
1508 ptr = &pcmcia_sockets;
1509 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1510 if (entry->socket == socket) {
1511 *ptr = entry->next;
1512 qemu_free(entry);
1516 void pcmcia_info(Monitor *mon)
1518 struct pcmcia_socket_entry_s *iter;
1520 if (!pcmcia_sockets)
1521 monitor_printf(mon, "No PCMCIA sockets\n");
1523 for (iter = pcmcia_sockets; iter; iter = iter->next)
1524 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1525 iter->socket->attached ? iter->socket->card_string :
1526 "Empty");
1529 /***********************************************************/
1530 /* I/O handling */
1532 typedef struct IOHandlerRecord {
1533 int fd;
1534 IOCanReadHandler *fd_read_poll;
1535 IOHandler *fd_read;
1536 IOHandler *fd_write;
1537 int deleted;
1538 void *opaque;
1539 /* temporary data */
1540 struct pollfd *ufd;
1541 QLIST_ENTRY(IOHandlerRecord) next;
1542 } IOHandlerRecord;
1544 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1545 QLIST_HEAD_INITIALIZER(io_handlers);
1548 /* XXX: fd_read_poll should be suppressed, but an API change is
1549 necessary in the character devices to suppress fd_can_read(). */
1550 int qemu_set_fd_handler2(int fd,
1551 IOCanReadHandler *fd_read_poll,
1552 IOHandler *fd_read,
1553 IOHandler *fd_write,
1554 void *opaque)
1556 IOHandlerRecord *ioh;
1558 if (!fd_read && !fd_write) {
1559 QLIST_FOREACH(ioh, &io_handlers, next) {
1560 if (ioh->fd == fd) {
1561 ioh->deleted = 1;
1562 break;
1565 } else {
1566 QLIST_FOREACH(ioh, &io_handlers, next) {
1567 if (ioh->fd == fd)
1568 goto found;
1570 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1571 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1572 found:
1573 ioh->fd = fd;
1574 ioh->fd_read_poll = fd_read_poll;
1575 ioh->fd_read = fd_read;
1576 ioh->fd_write = fd_write;
1577 ioh->opaque = opaque;
1578 ioh->deleted = 0;
1580 return 0;
1583 int qemu_set_fd_handler(int fd,
1584 IOHandler *fd_read,
1585 IOHandler *fd_write,
1586 void *opaque)
1588 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1591 #ifdef _WIN32
1592 /***********************************************************/
1593 /* Polling handling */
1595 typedef struct PollingEntry {
1596 PollingFunc *func;
1597 void *opaque;
1598 struct PollingEntry *next;
1599 } PollingEntry;
1601 static PollingEntry *first_polling_entry;
1603 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1605 PollingEntry **ppe, *pe;
1606 pe = qemu_mallocz(sizeof(PollingEntry));
1607 pe->func = func;
1608 pe->opaque = opaque;
1609 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1610 *ppe = pe;
1611 return 0;
1614 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1616 PollingEntry **ppe, *pe;
1617 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1618 pe = *ppe;
1619 if (pe->func == func && pe->opaque == opaque) {
1620 *ppe = pe->next;
1621 qemu_free(pe);
1622 break;
1627 /***********************************************************/
1628 /* Wait objects support */
1629 typedef struct WaitObjects {
1630 int num;
1631 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1632 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1633 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1634 } WaitObjects;
1636 static WaitObjects wait_objects = {0};
1638 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1640 WaitObjects *w = &wait_objects;
1642 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1643 return -1;
1644 w->events[w->num] = handle;
1645 w->func[w->num] = func;
1646 w->opaque[w->num] = opaque;
1647 w->num++;
1648 return 0;
1651 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1653 int i, found;
1654 WaitObjects *w = &wait_objects;
1656 found = 0;
1657 for (i = 0; i < w->num; i++) {
1658 if (w->events[i] == handle)
1659 found = 1;
1660 if (found) {
1661 w->events[i] = w->events[i + 1];
1662 w->func[i] = w->func[i + 1];
1663 w->opaque[i] = w->opaque[i + 1];
1666 if (found)
1667 w->num--;
1669 #endif
1671 /***********************************************************/
1672 /* ram save/restore */
1674 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
1675 #define RAM_SAVE_FLAG_COMPRESS 0x02
1676 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
1677 #define RAM_SAVE_FLAG_PAGE 0x08
1678 #define RAM_SAVE_FLAG_EOS 0x10
1680 static int is_dup_page(uint8_t *page, uint8_t ch)
1682 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1683 uint32_t *array = (uint32_t *)page;
1684 int i;
1686 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1687 if (array[i] != val)
1688 return 0;
1691 return 1;
1694 static int ram_save_block(QEMUFile *f)
1696 static ram_addr_t current_addr = 0;
1697 ram_addr_t saved_addr = current_addr;
1698 ram_addr_t addr = 0;
1699 int found = 0;
1701 while (addr < last_ram_offset) {
1702 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1703 uint8_t *p;
1705 cpu_physical_memory_reset_dirty(current_addr,
1706 current_addr + TARGET_PAGE_SIZE,
1707 MIGRATION_DIRTY_FLAG);
1709 p = qemu_get_ram_ptr(current_addr);
1711 if (is_dup_page(p, *p)) {
1712 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1713 qemu_put_byte(f, *p);
1714 } else {
1715 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1716 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1719 found = 1;
1720 break;
1722 addr += TARGET_PAGE_SIZE;
1723 current_addr = (saved_addr + addr) % last_ram_offset;
1726 return found;
1729 static uint64_t bytes_transferred;
1731 static ram_addr_t ram_save_remaining(void)
1733 ram_addr_t addr;
1734 ram_addr_t count = 0;
1736 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1737 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1738 count++;
1741 return count;
1744 uint64_t ram_bytes_remaining(void)
1746 return ram_save_remaining() * TARGET_PAGE_SIZE;
1749 uint64_t ram_bytes_transferred(void)
1751 return bytes_transferred;
1754 uint64_t ram_bytes_total(void)
1756 return last_ram_offset;
1759 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1761 ram_addr_t addr;
1762 uint64_t bytes_transferred_last;
1763 double bwidth = 0;
1764 uint64_t expected_time = 0;
1766 if (stage < 0) {
1767 cpu_physical_memory_set_dirty_tracking(0);
1768 return 0;
1771 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1772 qemu_file_set_error(f);
1773 return 0;
1776 if (stage == 1) {
1777 bytes_transferred = 0;
1779 /* Make sure all dirty bits are set */
1780 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1781 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1782 cpu_physical_memory_set_dirty(addr);
1785 /* Enable dirty memory tracking */
1786 cpu_physical_memory_set_dirty_tracking(1);
1788 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1791 bytes_transferred_last = bytes_transferred;
1792 bwidth = qemu_get_clock_ns(rt_clock);
1794 while (!qemu_file_rate_limit(f)) {
1795 int ret;
1797 ret = ram_save_block(f);
1798 bytes_transferred += ret * TARGET_PAGE_SIZE;
1799 if (ret == 0) /* no more blocks */
1800 break;
1803 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1804 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1806 /* if we haven't transferred anything this round, force expected_time to a
1807 * a very high value, but without crashing */
1808 if (bwidth == 0)
1809 bwidth = 0.000001;
1811 /* try transferring iterative blocks of memory */
1812 if (stage == 3) {
1813 /* flush all remaining blocks regardless of rate limiting */
1814 while (ram_save_block(f) != 0) {
1815 bytes_transferred += TARGET_PAGE_SIZE;
1817 cpu_physical_memory_set_dirty_tracking(0);
1820 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1822 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1824 return (stage == 2) && (expected_time <= migrate_max_downtime());
1827 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1829 ram_addr_t addr;
1830 int flags;
1832 if (version_id != 3)
1833 return -EINVAL;
1835 do {
1836 addr = qemu_get_be64(f);
1838 flags = addr & ~TARGET_PAGE_MASK;
1839 addr &= TARGET_PAGE_MASK;
1841 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1842 if (addr != last_ram_offset)
1843 return -EINVAL;
1846 if (flags & RAM_SAVE_FLAG_COMPRESS) {
1847 uint8_t ch = qemu_get_byte(f);
1848 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1849 #ifndef _WIN32
1850 if (ch == 0 &&
1851 (!kvm_enabled() || kvm_has_sync_mmu())) {
1852 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1854 #endif
1855 } else if (flags & RAM_SAVE_FLAG_PAGE) {
1856 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1858 if (qemu_file_has_error(f)) {
1859 return -EIO;
1861 } while (!(flags & RAM_SAVE_FLAG_EOS));
1863 return 0;
1866 void qemu_service_io(void)
1868 qemu_notify_event();
1871 /***********************************************************/
1872 /* machine registration */
1874 static QEMUMachine *first_machine = NULL;
1875 QEMUMachine *current_machine = NULL;
1877 int qemu_register_machine(QEMUMachine *m)
1879 QEMUMachine **pm;
1880 pm = &first_machine;
1881 while (*pm != NULL)
1882 pm = &(*pm)->next;
1883 m->next = NULL;
1884 *pm = m;
1885 return 0;
1888 static QEMUMachine *find_machine(const char *name)
1890 QEMUMachine *m;
1892 for(m = first_machine; m != NULL; m = m->next) {
1893 if (!strcmp(m->name, name))
1894 return m;
1895 if (m->alias && !strcmp(m->alias, name))
1896 return m;
1898 return NULL;
1901 static QEMUMachine *find_default_machine(void)
1903 QEMUMachine *m;
1905 for(m = first_machine; m != NULL; m = m->next) {
1906 if (m->is_default) {
1907 return m;
1910 return NULL;
1913 /***********************************************************/
1914 /* main execution loop */
1916 static void gui_update(void *opaque)
1918 uint64_t interval = GUI_REFRESH_INTERVAL;
1919 DisplayState *ds = opaque;
1920 DisplayChangeListener *dcl = ds->listeners;
1922 qemu_flush_coalesced_mmio_buffer();
1923 dpy_refresh(ds);
1925 while (dcl != NULL) {
1926 if (dcl->gui_timer_interval &&
1927 dcl->gui_timer_interval < interval)
1928 interval = dcl->gui_timer_interval;
1929 dcl = dcl->next;
1931 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1934 static void nographic_update(void *opaque)
1936 uint64_t interval = GUI_REFRESH_INTERVAL;
1938 qemu_flush_coalesced_mmio_buffer();
1939 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1942 struct vm_change_state_entry {
1943 VMChangeStateHandler *cb;
1944 void *opaque;
1945 QLIST_ENTRY (vm_change_state_entry) entries;
1948 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1950 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1951 void *opaque)
1953 VMChangeStateEntry *e;
1955 e = qemu_mallocz(sizeof (*e));
1957 e->cb = cb;
1958 e->opaque = opaque;
1959 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1960 return e;
1963 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1965 QLIST_REMOVE (e, entries);
1966 qemu_free (e);
1969 void vm_state_notify(int running, int reason)
1971 VMChangeStateEntry *e;
1973 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1974 e->cb(e->opaque, running, reason);
1978 void vm_start(void)
1980 if (!vm_running) {
1981 cpu_enable_ticks();
1982 vm_running = 1;
1983 vm_state_notify(1, 0);
1984 resume_all_vcpus();
1988 /* reset/shutdown handler */
1990 typedef struct QEMUResetEntry {
1991 QTAILQ_ENTRY(QEMUResetEntry) entry;
1992 QEMUResetHandler *func;
1993 void *opaque;
1994 } QEMUResetEntry;
1996 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1997 QTAILQ_HEAD_INITIALIZER(reset_handlers);
1998 static int reset_requested;
1999 static int shutdown_requested;
2000 static int powerdown_requested;
2001 int debug_requested;
2002 static int vmstop_requested;
2004 int qemu_shutdown_requested(void)
2006 int r = shutdown_requested;
2007 shutdown_requested = 0;
2008 return r;
2011 int qemu_reset_requested(void)
2013 int r = reset_requested;
2014 reset_requested = 0;
2015 return r;
2018 int qemu_powerdown_requested(void)
2020 int r = powerdown_requested;
2021 powerdown_requested = 0;
2022 return r;
2025 static int qemu_debug_requested(void)
2027 int r = debug_requested;
2028 debug_requested = 0;
2029 return r;
2032 static int qemu_vmstop_requested(void)
2034 int r = vmstop_requested;
2035 vmstop_requested = 0;
2036 return r;
2039 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2041 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2043 re->func = func;
2044 re->opaque = opaque;
2045 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2048 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2050 QEMUResetEntry *re;
2052 QTAILQ_FOREACH(re, &reset_handlers, entry) {
2053 if (re->func == func && re->opaque == opaque) {
2054 QTAILQ_REMOVE(&reset_handlers, re, entry);
2055 qemu_free(re);
2056 return;
2061 void qemu_system_reset(void)
2063 QEMUResetEntry *re, *nre;
2065 /* reset all devices */
2066 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2067 re->func(re->opaque);
2069 monitor_protocol_event(QEVENT_RESET, NULL);
2070 cpu_synchronize_all_post_reset();
2073 void qemu_system_reset_request(void)
2075 if (no_reboot) {
2076 shutdown_requested = 1;
2077 } else {
2078 reset_requested = 1;
2080 qemu_notify_event();
2083 void qemu_system_shutdown_request(void)
2085 shutdown_requested = 1;
2086 qemu_notify_event();
2089 void qemu_system_powerdown_request(void)
2091 powerdown_requested = 1;
2092 qemu_notify_event();
2095 #ifdef _WIN32
2096 static void host_main_loop_wait(int *timeout)
2098 int ret, ret2, i;
2099 PollingEntry *pe;
2102 /* XXX: need to suppress polling by better using win32 events */
2103 ret = 0;
2104 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2105 ret |= pe->func(pe->opaque);
2107 if (ret == 0) {
2108 int err;
2109 WaitObjects *w = &wait_objects;
2111 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2112 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2113 if (w->func[ret - WAIT_OBJECT_0])
2114 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2116 /* Check for additional signaled events */
2117 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2119 /* Check if event is signaled */
2120 ret2 = WaitForSingleObject(w->events[i], 0);
2121 if(ret2 == WAIT_OBJECT_0) {
2122 if (w->func[i])
2123 w->func[i](w->opaque[i]);
2124 } else if (ret2 == WAIT_TIMEOUT) {
2125 } else {
2126 err = GetLastError();
2127 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2130 } else if (ret == WAIT_TIMEOUT) {
2131 } else {
2132 err = GetLastError();
2133 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2137 *timeout = 0;
2139 #else
2140 static void host_main_loop_wait(int *timeout)
2143 #endif
2145 void main_loop_wait(int nonblocking)
2147 IOHandlerRecord *ioh;
2148 fd_set rfds, wfds, xfds;
2149 int ret, nfds;
2150 struct timeval tv;
2151 int timeout;
2153 if (nonblocking)
2154 timeout = 0;
2155 else {
2156 timeout = qemu_calculate_timeout();
2157 qemu_bh_update_timeout(&timeout);
2160 host_main_loop_wait(&timeout);
2162 /* poll any events */
2163 /* XXX: separate device handlers from system ones */
2164 nfds = -1;
2165 FD_ZERO(&rfds);
2166 FD_ZERO(&wfds);
2167 FD_ZERO(&xfds);
2168 QLIST_FOREACH(ioh, &io_handlers, next) {
2169 if (ioh->deleted)
2170 continue;
2171 if (ioh->fd_read &&
2172 (!ioh->fd_read_poll ||
2173 ioh->fd_read_poll(ioh->opaque) != 0)) {
2174 FD_SET(ioh->fd, &rfds);
2175 if (ioh->fd > nfds)
2176 nfds = ioh->fd;
2178 if (ioh->fd_write) {
2179 FD_SET(ioh->fd, &wfds);
2180 if (ioh->fd > nfds)
2181 nfds = ioh->fd;
2185 tv.tv_sec = timeout / 1000;
2186 tv.tv_usec = (timeout % 1000) * 1000;
2188 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2190 qemu_mutex_unlock_iothread();
2191 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2192 qemu_mutex_lock_iothread();
2193 if (ret > 0) {
2194 IOHandlerRecord *pioh;
2196 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
2197 if (ioh->deleted) {
2198 QLIST_REMOVE(ioh, next);
2199 qemu_free(ioh);
2200 continue;
2202 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2203 ioh->fd_read(ioh->opaque);
2205 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2206 ioh->fd_write(ioh->opaque);
2211 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2213 qemu_run_all_timers();
2215 /* Check bottom-halves last in case any of the earlier events triggered
2216 them. */
2217 qemu_bh_poll();
2221 static int vm_can_run(void)
2223 if (powerdown_requested)
2224 return 0;
2225 if (reset_requested)
2226 return 0;
2227 if (shutdown_requested)
2228 return 0;
2229 if (debug_requested)
2230 return 0;
2231 return 1;
2234 qemu_irq qemu_system_powerdown;
2236 static void main_loop(void)
2238 int r;
2240 #ifdef CONFIG_IOTHREAD
2241 qemu_system_ready = 1;
2242 qemu_cond_broadcast(&qemu_system_cond);
2243 #endif
2245 for (;;) {
2246 do {
2247 bool nonblocking = false;
2248 #ifdef CONFIG_PROFILER
2249 int64_t ti;
2250 #endif
2251 #ifndef CONFIG_IOTHREAD
2252 nonblocking = tcg_cpu_exec();
2253 #endif
2254 #ifdef CONFIG_PROFILER
2255 ti = profile_getclock();
2256 #endif
2257 main_loop_wait(nonblocking);
2258 #ifdef CONFIG_PROFILER
2259 dev_time += profile_getclock() - ti;
2260 #endif
2261 } while (vm_can_run());
2263 if ((r = qemu_debug_requested())) {
2264 vm_stop(r);
2266 if (qemu_shutdown_requested()) {
2267 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2268 if (no_shutdown) {
2269 vm_stop(0);
2270 no_shutdown = 0;
2271 } else
2272 break;
2274 if (qemu_reset_requested()) {
2275 pause_all_vcpus();
2276 qemu_system_reset();
2277 resume_all_vcpus();
2279 if (qemu_powerdown_requested()) {
2280 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
2281 qemu_irq_raise(qemu_system_powerdown);
2283 if ((r = qemu_vmstop_requested())) {
2284 vm_stop(r);
2287 pause_all_vcpus();
2290 static void version(void)
2292 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
2295 static void help(int exitcode)
2297 const char *options_help =
2298 #define DEF(option, opt_arg, opt_enum, opt_help) \
2299 opt_help
2300 #define DEFHEADING(text) stringify(text) "\n"
2301 #include "qemu-options.h"
2302 #undef DEF
2303 #undef DEFHEADING
2304 #undef GEN_DOCS
2306 version();
2307 printf("usage: %s [options] [disk_image]\n"
2308 "\n"
2309 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2310 "\n"
2311 "%s\n"
2312 "During emulation, the following keys are useful:\n"
2313 "ctrl-alt-f toggle full screen\n"
2314 "ctrl-alt-n switch to virtual console 'n'\n"
2315 "ctrl-alt toggle mouse and keyboard grab\n"
2316 "\n"
2317 "When using -nographic, press 'ctrl-a h' to get some help.\n",
2318 "qemu",
2319 options_help);
2320 exit(exitcode);
2323 #define HAS_ARG 0x0001
2325 enum {
2326 #define DEF(option, opt_arg, opt_enum, opt_help) \
2327 opt_enum,
2328 #define DEFHEADING(text)
2329 #include "qemu-options.h"
2330 #undef DEF
2331 #undef DEFHEADING
2332 #undef GEN_DOCS
2335 typedef struct QEMUOption {
2336 const char *name;
2337 int flags;
2338 int index;
2339 } QEMUOption;
2341 static const QEMUOption qemu_options[] = {
2342 { "h", 0, QEMU_OPTION_h },
2343 #define DEF(option, opt_arg, opt_enum, opt_help) \
2344 { option, opt_arg, opt_enum },
2345 #define DEFHEADING(text)
2346 #include "qemu-options.h"
2347 #undef DEF
2348 #undef DEFHEADING
2349 #undef GEN_DOCS
2350 { NULL },
2353 #ifdef HAS_AUDIO
2354 struct soundhw soundhw[] = {
2355 #ifdef HAS_AUDIO_CHOICE
2356 #if defined(TARGET_I386) || defined(TARGET_MIPS)
2358 "pcspk",
2359 "PC speaker",
2362 { .init_isa = pcspk_audio_init }
2364 #endif
2366 #ifdef CONFIG_SB16
2368 "sb16",
2369 "Creative Sound Blaster 16",
2372 { .init_isa = SB16_init }
2374 #endif
2376 #ifdef CONFIG_CS4231A
2378 "cs4231a",
2379 "CS4231A",
2382 { .init_isa = cs4231a_init }
2384 #endif
2386 #ifdef CONFIG_ADLIB
2388 "adlib",
2389 #ifdef HAS_YMF262
2390 "Yamaha YMF262 (OPL3)",
2391 #else
2392 "Yamaha YM3812 (OPL2)",
2393 #endif
2396 { .init_isa = Adlib_init }
2398 #endif
2400 #ifdef CONFIG_GUS
2402 "gus",
2403 "Gravis Ultrasound GF1",
2406 { .init_isa = GUS_init }
2408 #endif
2410 #ifdef CONFIG_AC97
2412 "ac97",
2413 "Intel 82801AA AC97 Audio",
2416 { .init_pci = ac97_init }
2418 #endif
2420 #ifdef CONFIG_ES1370
2422 "es1370",
2423 "ENSONIQ AudioPCI ES1370",
2426 { .init_pci = es1370_init }
2428 #endif
2430 #endif /* HAS_AUDIO_CHOICE */
2432 { NULL, NULL, 0, 0, { NULL } }
2435 static void select_soundhw (const char *optarg)
2437 struct soundhw *c;
2439 if (*optarg == '?') {
2440 show_valid_cards:
2442 printf ("Valid sound card names (comma separated):\n");
2443 for (c = soundhw; c->name; ++c) {
2444 printf ("%-11s %s\n", c->name, c->descr);
2446 printf ("\n-soundhw all will enable all of the above\n");
2447 exit (*optarg != '?');
2449 else {
2450 size_t l;
2451 const char *p;
2452 char *e;
2453 int bad_card = 0;
2455 if (!strcmp (optarg, "all")) {
2456 for (c = soundhw; c->name; ++c) {
2457 c->enabled = 1;
2459 return;
2462 p = optarg;
2463 while (*p) {
2464 e = strchr (p, ',');
2465 l = !e ? strlen (p) : (size_t) (e - p);
2467 for (c = soundhw; c->name; ++c) {
2468 if (!strncmp (c->name, p, l) && !c->name[l]) {
2469 c->enabled = 1;
2470 break;
2474 if (!c->name) {
2475 if (l > 80) {
2476 fprintf (stderr,
2477 "Unknown sound card name (too big to show)\n");
2479 else {
2480 fprintf (stderr, "Unknown sound card name `%.*s'\n",
2481 (int) l, p);
2483 bad_card = 1;
2485 p += l + (e != NULL);
2488 if (bad_card)
2489 goto show_valid_cards;
2492 #endif
2494 static void select_vgahw (const char *p)
2496 const char *opts;
2498 default_vga = 0;
2499 vga_interface_type = VGA_NONE;
2500 if (strstart(p, "std", &opts)) {
2501 vga_interface_type = VGA_STD;
2502 } else if (strstart(p, "cirrus", &opts)) {
2503 vga_interface_type = VGA_CIRRUS;
2504 } else if (strstart(p, "vmware", &opts)) {
2505 vga_interface_type = VGA_VMWARE;
2506 } else if (strstart(p, "xenfb", &opts)) {
2507 vga_interface_type = VGA_XENFB;
2508 } else if (!strstart(p, "none", &opts)) {
2509 invalid_vga:
2510 fprintf(stderr, "Unknown vga type: %s\n", p);
2511 exit(1);
2513 while (*opts) {
2514 const char *nextopt;
2516 if (strstart(opts, ",retrace=", &nextopt)) {
2517 opts = nextopt;
2518 if (strstart(opts, "dumb", &nextopt))
2519 vga_retrace_method = VGA_RETRACE_DUMB;
2520 else if (strstart(opts, "precise", &nextopt))
2521 vga_retrace_method = VGA_RETRACE_PRECISE;
2522 else goto invalid_vga;
2523 } else goto invalid_vga;
2524 opts = nextopt;
2528 #ifdef TARGET_I386
2529 static int balloon_parse(const char *arg)
2531 QemuOpts *opts;
2533 if (strcmp(arg, "none") == 0) {
2534 return 0;
2537 if (!strncmp(arg, "virtio", 6)) {
2538 if (arg[6] == ',') {
2539 /* have params -> parse them */
2540 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
2541 if (!opts)
2542 return -1;
2543 } else {
2544 /* create empty opts */
2545 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2547 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
2548 return 0;
2551 return -1;
2553 #endif
2555 #ifdef _WIN32
2556 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
2558 exit(STATUS_CONTROL_C_EXIT);
2559 return TRUE;
2561 #endif
2563 int qemu_uuid_parse(const char *str, uint8_t *uuid)
2565 int ret;
2567 if(strlen(str) != 36)
2568 return -1;
2570 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
2571 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
2572 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
2574 if(ret != 16)
2575 return -1;
2577 #ifdef TARGET_I386
2578 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
2579 #endif
2581 return 0;
2584 #ifdef TARGET_I386
2585 static void do_acpitable_option(const char *optarg)
2587 if (acpi_table_add(optarg) < 0) {
2588 fprintf(stderr, "Wrong acpi table provided\n");
2589 exit(1);
2592 #endif
2594 #ifdef TARGET_I386
2595 static void do_smbios_option(const char *optarg)
2597 if (smbios_entry_add(optarg) < 0) {
2598 fprintf(stderr, "Wrong smbios provided\n");
2599 exit(1);
2602 #endif
2604 static void cpudef_init(void)
2606 #if defined(cpudef_setup)
2607 cpudef_setup(); /* parse cpu definitions in target config file */
2608 #endif
2611 #ifndef _WIN32
2613 static void termsig_handler(int signal)
2615 qemu_system_shutdown_request();
2618 static void sigchld_handler(int signal)
2620 waitpid(-1, NULL, WNOHANG);
2623 static void sighandler_setup(void)
2625 struct sigaction act;
2627 memset(&act, 0, sizeof(act));
2628 act.sa_handler = termsig_handler;
2629 sigaction(SIGINT, &act, NULL);
2630 sigaction(SIGHUP, &act, NULL);
2631 sigaction(SIGTERM, &act, NULL);
2633 act.sa_handler = sigchld_handler;
2634 act.sa_flags = SA_NOCLDSTOP;
2635 sigaction(SIGCHLD, &act, NULL);
2638 #endif
2640 #ifdef _WIN32
2641 /* Look for support files in the same directory as the executable. */
2642 static char *find_datadir(const char *argv0)
2644 char *p;
2645 char buf[MAX_PATH];
2646 DWORD len;
2648 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
2649 if (len == 0) {
2650 return NULL;
2653 buf[len] = 0;
2654 p = buf + len - 1;
2655 while (p != buf && *p != '\\')
2656 p--;
2657 *p = 0;
2658 if (access(buf, R_OK) == 0) {
2659 return qemu_strdup(buf);
2661 return NULL;
2663 #else /* !_WIN32 */
2665 /* Find a likely location for support files using the location of the binary.
2666 For installed binaries this will be "$bindir/../share/qemu". When
2667 running from the build tree this will be "$bindir/../pc-bios". */
2668 #define SHARE_SUFFIX "/share/qemu"
2669 #define BUILD_SUFFIX "/pc-bios"
2670 static char *find_datadir(const char *argv0)
2672 char *dir;
2673 char *p = NULL;
2674 char *res;
2675 char buf[PATH_MAX];
2676 size_t max_len;
2678 #if defined(__linux__)
2680 int len;
2681 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
2682 if (len > 0) {
2683 buf[len] = 0;
2684 p = buf;
2687 #elif defined(__FreeBSD__)
2689 int len;
2690 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
2691 if (len > 0) {
2692 buf[len] = 0;
2693 p = buf;
2696 #endif
2697 /* If we don't have any way of figuring out the actual executable
2698 location then try argv[0]. */
2699 if (!p) {
2700 p = realpath(argv0, buf);
2701 if (!p) {
2702 return NULL;
2705 dir = dirname(p);
2706 dir = dirname(dir);
2708 max_len = strlen(dir) +
2709 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
2710 res = qemu_mallocz(max_len);
2711 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
2712 if (access(res, R_OK)) {
2713 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
2714 if (access(res, R_OK)) {
2715 qemu_free(res);
2716 res = NULL;
2720 return res;
2722 #undef SHARE_SUFFIX
2723 #undef BUILD_SUFFIX
2724 #endif
2726 char *qemu_find_file(int type, const char *name)
2728 int len;
2729 const char *subdir;
2730 char *buf;
2732 /* If name contains path separators then try it as a straight path. */
2733 if ((strchr(name, '/') || strchr(name, '\\'))
2734 && access(name, R_OK) == 0) {
2735 return qemu_strdup(name);
2737 switch (type) {
2738 case QEMU_FILE_TYPE_BIOS:
2739 subdir = "";
2740 break;
2741 case QEMU_FILE_TYPE_KEYMAP:
2742 subdir = "keymaps/";
2743 break;
2744 default:
2745 abort();
2747 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
2748 buf = qemu_mallocz(len);
2749 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
2750 if (access(buf, R_OK)) {
2751 qemu_free(buf);
2752 return NULL;
2754 return buf;
2757 static int device_help_func(QemuOpts *opts, void *opaque)
2759 return qdev_device_help(opts);
2762 static int device_init_func(QemuOpts *opts, void *opaque)
2764 DeviceState *dev;
2766 dev = qdev_device_add(opts);
2767 if (!dev)
2768 return -1;
2769 return 0;
2772 static int chardev_init_func(QemuOpts *opts, void *opaque)
2774 CharDriverState *chr;
2776 chr = qemu_chr_open_opts(opts, NULL);
2777 if (!chr)
2778 return -1;
2779 return 0;
2782 static int mon_init_func(QemuOpts *opts, void *opaque)
2784 CharDriverState *chr;
2785 const char *chardev;
2786 const char *mode;
2787 int flags;
2789 mode = qemu_opt_get(opts, "mode");
2790 if (mode == NULL) {
2791 mode = "readline";
2793 if (strcmp(mode, "readline") == 0) {
2794 flags = MONITOR_USE_READLINE;
2795 } else if (strcmp(mode, "control") == 0) {
2796 flags = MONITOR_USE_CONTROL;
2797 } else {
2798 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2799 exit(1);
2802 if (qemu_opt_get_bool(opts, "default", 0))
2803 flags |= MONITOR_IS_DEFAULT;
2805 chardev = qemu_opt_get(opts, "chardev");
2806 chr = qemu_chr_find(chardev);
2807 if (chr == NULL) {
2808 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2809 exit(1);
2812 monitor_init(chr, flags);
2813 return 0;
2816 static void monitor_parse(const char *optarg, const char *mode)
2818 static int monitor_device_index = 0;
2819 QemuOpts *opts;
2820 const char *p;
2821 char label[32];
2822 int def = 0;
2824 if (strstart(optarg, "chardev:", &p)) {
2825 snprintf(label, sizeof(label), "%s", p);
2826 } else {
2827 if (monitor_device_index) {
2828 snprintf(label, sizeof(label), "monitor%d",
2829 monitor_device_index);
2830 } else {
2831 snprintf(label, sizeof(label), "monitor");
2832 def = 1;
2834 opts = qemu_chr_parse_compat(label, optarg);
2835 if (!opts) {
2836 fprintf(stderr, "parse error: %s\n", optarg);
2837 exit(1);
2841 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
2842 if (!opts) {
2843 fprintf(stderr, "duplicate chardev: %s\n", label);
2844 exit(1);
2846 qemu_opt_set(opts, "mode", mode);
2847 qemu_opt_set(opts, "chardev", label);
2848 if (def)
2849 qemu_opt_set(opts, "default", "on");
2850 monitor_device_index++;
2853 struct device_config {
2854 enum {
2855 DEV_USB, /* -usbdevice */
2856 DEV_BT, /* -bt */
2857 DEV_SERIAL, /* -serial */
2858 DEV_PARALLEL, /* -parallel */
2859 DEV_VIRTCON, /* -virtioconsole */
2860 DEV_DEBUGCON, /* -debugcon */
2861 } type;
2862 const char *cmdline;
2863 QTAILQ_ENTRY(device_config) next;
2865 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
2867 static void add_device_config(int type, const char *cmdline)
2869 struct device_config *conf;
2871 conf = qemu_mallocz(sizeof(*conf));
2872 conf->type = type;
2873 conf->cmdline = cmdline;
2874 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2877 static int foreach_device_config(int type, int (*func)(const char *cmdline))
2879 struct device_config *conf;
2880 int rc;
2882 QTAILQ_FOREACH(conf, &device_configs, next) {
2883 if (conf->type != type)
2884 continue;
2885 rc = func(conf->cmdline);
2886 if (0 != rc)
2887 return rc;
2889 return 0;
2892 static int serial_parse(const char *devname)
2894 static int index = 0;
2895 char label[32];
2897 if (strcmp(devname, "none") == 0)
2898 return 0;
2899 if (index == MAX_SERIAL_PORTS) {
2900 fprintf(stderr, "qemu: too many serial ports\n");
2901 exit(1);
2903 snprintf(label, sizeof(label), "serial%d", index);
2904 serial_hds[index] = qemu_chr_open(label, devname, NULL);
2905 if (!serial_hds[index]) {
2906 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
2907 devname, strerror(errno));
2908 return -1;
2910 index++;
2911 return 0;
2914 static int parallel_parse(const char *devname)
2916 static int index = 0;
2917 char label[32];
2919 if (strcmp(devname, "none") == 0)
2920 return 0;
2921 if (index == MAX_PARALLEL_PORTS) {
2922 fprintf(stderr, "qemu: too many parallel ports\n");
2923 exit(1);
2925 snprintf(label, sizeof(label), "parallel%d", index);
2926 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
2927 if (!parallel_hds[index]) {
2928 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2929 devname, strerror(errno));
2930 return -1;
2932 index++;
2933 return 0;
2936 static int virtcon_parse(const char *devname)
2938 static int index = 0;
2939 char label[32];
2940 QemuOpts *bus_opts, *dev_opts;
2942 if (strcmp(devname, "none") == 0)
2943 return 0;
2944 if (index == MAX_VIRTIO_CONSOLES) {
2945 fprintf(stderr, "qemu: too many virtio consoles\n");
2946 exit(1);
2949 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2950 qemu_opt_set(bus_opts, "driver", "virtio-serial");
2952 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2953 qemu_opt_set(dev_opts, "driver", "virtconsole");
2955 snprintf(label, sizeof(label), "virtcon%d", index);
2956 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
2957 if (!virtcon_hds[index]) {
2958 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2959 devname, strerror(errno));
2960 return -1;
2962 qemu_opt_set(dev_opts, "chardev", label);
2964 index++;
2965 return 0;
2968 static int debugcon_parse(const char *devname)
2970 QemuOpts *opts;
2972 if (!qemu_chr_open("debugcon", devname, NULL)) {
2973 exit(1);
2975 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
2976 if (!opts) {
2977 fprintf(stderr, "qemu: already have a debugcon device\n");
2978 exit(1);
2980 qemu_opt_set(opts, "driver", "isa-debugcon");
2981 qemu_opt_set(opts, "chardev", "debugcon");
2982 return 0;
2985 static const QEMUOption *lookup_opt(int argc, char **argv,
2986 const char **poptarg, int *poptind)
2988 const QEMUOption *popt;
2989 int optind = *poptind;
2990 char *r = argv[optind];
2991 const char *optarg;
2993 loc_set_cmdline(argv, optind, 1);
2994 optind++;
2995 /* Treat --foo the same as -foo. */
2996 if (r[1] == '-')
2997 r++;
2998 popt = qemu_options;
2999 for(;;) {
3000 if (!popt->name) {
3001 error_report("invalid option");
3002 exit(1);
3004 if (!strcmp(popt->name, r + 1))
3005 break;
3006 popt++;
3008 if (popt->flags & HAS_ARG) {
3009 if (optind >= argc) {
3010 error_report("requires an argument");
3011 exit(1);
3013 optarg = argv[optind++];
3014 loc_set_cmdline(argv, optind - 2, 2);
3015 } else {
3016 optarg = NULL;
3019 *poptarg = optarg;
3020 *poptind = optind;
3022 return popt;
3025 int main(int argc, char **argv, char **envp)
3027 const char *gdbstub_dev = NULL;
3028 uint32_t boot_devices_bitmap = 0;
3029 int i;
3030 int snapshot, linux_boot, net_boot;
3031 const char *icount_option = NULL;
3032 const char *initrd_filename;
3033 const char *kernel_filename, *kernel_cmdline;
3034 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3035 DisplayState *ds;
3036 DisplayChangeListener *dcl;
3037 int cyls, heads, secs, translation;
3038 QemuOpts *hda_opts = NULL, *opts;
3039 int optind;
3040 const char *optarg;
3041 const char *loadvm = NULL;
3042 QEMUMachine *machine;
3043 const char *cpu_model;
3044 #ifndef _WIN32
3045 int fds[2];
3046 #endif
3047 int tb_size;
3048 const char *pid_file = NULL;
3049 const char *incoming = NULL;
3050 #ifndef _WIN32
3051 int fd = 0;
3052 struct passwd *pwd = NULL;
3053 const char *chroot_dir = NULL;
3054 const char *run_as = NULL;
3055 #endif
3056 int show_vnc_port = 0;
3057 int defconfig = 1;
3059 error_set_progname(argv[0]);
3061 init_clocks();
3063 qemu_cache_utils_init(envp);
3065 QLIST_INIT (&vm_change_state_head);
3066 #ifndef _WIN32
3068 struct sigaction act;
3069 sigfillset(&act.sa_mask);
3070 act.sa_flags = 0;
3071 act.sa_handler = SIG_IGN;
3072 sigaction(SIGPIPE, &act, NULL);
3074 #else
3075 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3076 /* Note: cpu_interrupt() is currently not SMP safe, so we force
3077 QEMU to run on a single CPU */
3079 HANDLE h;
3080 DWORD mask, smask;
3081 int i;
3082 h = GetCurrentProcess();
3083 if (GetProcessAffinityMask(h, &mask, &smask)) {
3084 for(i = 0; i < 32; i++) {
3085 if (mask & (1 << i))
3086 break;
3088 if (i != 32) {
3089 mask = 1 << i;
3090 SetProcessAffinityMask(h, mask);
3094 #endif
3096 module_call_init(MODULE_INIT_MACHINE);
3097 machine = find_default_machine();
3098 cpu_model = NULL;
3099 initrd_filename = NULL;
3100 ram_size = 0;
3101 snapshot = 0;
3102 kernel_filename = NULL;
3103 kernel_cmdline = "";
3104 cyls = heads = secs = 0;
3105 translation = BIOS_ATA_TRANSLATION_AUTO;
3107 for (i = 0; i < MAX_NODES; i++) {
3108 node_mem[i] = 0;
3109 node_cpumask[i] = 0;
3112 nb_numa_nodes = 0;
3113 nb_nics = 0;
3115 tb_size = 0;
3116 autostart= 1;
3118 /* first pass of option parsing */
3119 optind = 1;
3120 while (optind < argc) {
3121 if (argv[optind][0] != '-') {
3122 /* disk image */
3123 optind++;
3124 continue;
3125 } else {
3126 const QEMUOption *popt;
3128 popt = lookup_opt(argc, argv, &optarg, &optind);
3129 switch (popt->index) {
3130 case QEMU_OPTION_nodefconfig:
3131 defconfig=0;
3132 break;
3137 if (defconfig) {
3138 const char *fname;
3139 FILE *fp;
3141 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3142 fp = fopen(fname, "r");
3143 if (fp) {
3144 if (qemu_config_parse(fp, fname) != 0) {
3145 exit(1);
3147 fclose(fp);
3150 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3151 fp = fopen(fname, "r");
3152 if (fp) {
3153 if (qemu_config_parse(fp, fname) != 0) {
3154 exit(1);
3156 fclose(fp);
3159 cpudef_init();
3161 /* second pass of option parsing */
3162 optind = 1;
3163 for(;;) {
3164 if (optind >= argc)
3165 break;
3166 if (argv[optind][0] != '-') {
3167 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3168 } else {
3169 const QEMUOption *popt;
3171 popt = lookup_opt(argc, argv, &optarg, &optind);
3172 switch(popt->index) {
3173 case QEMU_OPTION_M:
3174 machine = find_machine(optarg);
3175 if (!machine) {
3176 QEMUMachine *m;
3177 printf("Supported machines are:\n");
3178 for(m = first_machine; m != NULL; m = m->next) {
3179 if (m->alias)
3180 printf("%-10s %s (alias of %s)\n",
3181 m->alias, m->desc, m->name);
3182 printf("%-10s %s%s\n",
3183 m->name, m->desc,
3184 m->is_default ? " (default)" : "");
3186 exit(*optarg != '?');
3188 break;
3189 case QEMU_OPTION_cpu:
3190 /* hw initialization will check this */
3191 if (*optarg == '?') {
3192 /* XXX: implement xxx_cpu_list for targets that still miss it */
3193 #if defined(cpu_list_id)
3194 cpu_list_id(stdout, &fprintf, optarg);
3195 #elif defined(cpu_list)
3196 cpu_list(stdout, &fprintf); /* deprecated */
3197 #endif
3198 exit(0);
3199 } else {
3200 cpu_model = optarg;
3202 break;
3203 case QEMU_OPTION_initrd:
3204 initrd_filename = optarg;
3205 break;
3206 case QEMU_OPTION_hda:
3207 if (cyls == 0)
3208 hda_opts = drive_add(optarg, HD_ALIAS, 0);
3209 else
3210 hda_opts = drive_add(optarg, HD_ALIAS
3211 ",cyls=%d,heads=%d,secs=%d%s",
3212 0, cyls, heads, secs,
3213 translation == BIOS_ATA_TRANSLATION_LBA ?
3214 ",trans=lba" :
3215 translation == BIOS_ATA_TRANSLATION_NONE ?
3216 ",trans=none" : "");
3217 break;
3218 case QEMU_OPTION_hdb:
3219 case QEMU_OPTION_hdc:
3220 case QEMU_OPTION_hdd:
3221 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
3222 break;
3223 case QEMU_OPTION_drive:
3224 drive_add(NULL, "%s", optarg);
3225 break;
3226 case QEMU_OPTION_set:
3227 if (qemu_set_option(optarg) != 0)
3228 exit(1);
3229 break;
3230 case QEMU_OPTION_global:
3231 if (qemu_global_option(optarg) != 0)
3232 exit(1);
3233 break;
3234 case QEMU_OPTION_mtdblock:
3235 drive_add(optarg, MTD_ALIAS);
3236 break;
3237 case QEMU_OPTION_sd:
3238 drive_add(optarg, SD_ALIAS);
3239 break;
3240 case QEMU_OPTION_pflash:
3241 drive_add(optarg, PFLASH_ALIAS);
3242 break;
3243 case QEMU_OPTION_snapshot:
3244 snapshot = 1;
3245 break;
3246 case QEMU_OPTION_hdachs:
3248 const char *p;
3249 p = optarg;
3250 cyls = strtol(p, (char **)&p, 0);
3251 if (cyls < 1 || cyls > 16383)
3252 goto chs_fail;
3253 if (*p != ',')
3254 goto chs_fail;
3255 p++;
3256 heads = strtol(p, (char **)&p, 0);
3257 if (heads < 1 || heads > 16)
3258 goto chs_fail;
3259 if (*p != ',')
3260 goto chs_fail;
3261 p++;
3262 secs = strtol(p, (char **)&p, 0);
3263 if (secs < 1 || secs > 63)
3264 goto chs_fail;
3265 if (*p == ',') {
3266 p++;
3267 if (!strcmp(p, "none"))
3268 translation = BIOS_ATA_TRANSLATION_NONE;
3269 else if (!strcmp(p, "lba"))
3270 translation = BIOS_ATA_TRANSLATION_LBA;
3271 else if (!strcmp(p, "auto"))
3272 translation = BIOS_ATA_TRANSLATION_AUTO;
3273 else
3274 goto chs_fail;
3275 } else if (*p != '\0') {
3276 chs_fail:
3277 fprintf(stderr, "qemu: invalid physical CHS format\n");
3278 exit(1);
3280 if (hda_opts != NULL) {
3281 char num[16];
3282 snprintf(num, sizeof(num), "%d", cyls);
3283 qemu_opt_set(hda_opts, "cyls", num);
3284 snprintf(num, sizeof(num), "%d", heads);
3285 qemu_opt_set(hda_opts, "heads", num);
3286 snprintf(num, sizeof(num), "%d", secs);
3287 qemu_opt_set(hda_opts, "secs", num);
3288 if (translation == BIOS_ATA_TRANSLATION_LBA)
3289 qemu_opt_set(hda_opts, "trans", "lba");
3290 if (translation == BIOS_ATA_TRANSLATION_NONE)
3291 qemu_opt_set(hda_opts, "trans", "none");
3294 break;
3295 case QEMU_OPTION_numa:
3296 if (nb_numa_nodes >= MAX_NODES) {
3297 fprintf(stderr, "qemu: too many NUMA nodes\n");
3298 exit(1);
3300 numa_add(optarg);
3301 break;
3302 case QEMU_OPTION_nographic:
3303 display_type = DT_NOGRAPHIC;
3304 break;
3305 #ifdef CONFIG_CURSES
3306 case QEMU_OPTION_curses:
3307 display_type = DT_CURSES;
3308 break;
3309 #endif
3310 case QEMU_OPTION_portrait:
3311 graphic_rotate = 1;
3312 break;
3313 case QEMU_OPTION_kernel:
3314 kernel_filename = optarg;
3315 break;
3316 case QEMU_OPTION_append:
3317 kernel_cmdline = optarg;
3318 break;
3319 case QEMU_OPTION_cdrom:
3320 drive_add(optarg, CDROM_ALIAS);
3321 break;
3322 case QEMU_OPTION_boot:
3324 static const char * const params[] = {
3325 "order", "once", "menu", NULL
3327 char buf[sizeof(boot_devices)];
3328 char *standard_boot_devices;
3329 int legacy = 0;
3331 if (!strchr(optarg, '=')) {
3332 legacy = 1;
3333 pstrcpy(buf, sizeof(buf), optarg);
3334 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
3335 fprintf(stderr,
3336 "qemu: unknown boot parameter '%s' in '%s'\n",
3337 buf, optarg);
3338 exit(1);
3341 if (legacy ||
3342 get_param_value(buf, sizeof(buf), "order", optarg)) {
3343 boot_devices_bitmap = parse_bootdevices(buf);
3344 pstrcpy(boot_devices, sizeof(boot_devices), buf);
3346 if (!legacy) {
3347 if (get_param_value(buf, sizeof(buf),
3348 "once", optarg)) {
3349 boot_devices_bitmap |= parse_bootdevices(buf);
3350 standard_boot_devices = qemu_strdup(boot_devices);
3351 pstrcpy(boot_devices, sizeof(boot_devices), buf);
3352 qemu_register_reset(restore_boot_devices,
3353 standard_boot_devices);
3355 if (get_param_value(buf, sizeof(buf),
3356 "menu", optarg)) {
3357 if (!strcmp(buf, "on")) {
3358 boot_menu = 1;
3359 } else if (!strcmp(buf, "off")) {
3360 boot_menu = 0;
3361 } else {
3362 fprintf(stderr,
3363 "qemu: invalid option value '%s'\n",
3364 buf);
3365 exit(1);
3370 break;
3371 case QEMU_OPTION_fda:
3372 case QEMU_OPTION_fdb:
3373 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
3374 break;
3375 #ifdef TARGET_I386
3376 case QEMU_OPTION_no_fd_bootchk:
3377 fd_bootchk = 0;
3378 break;
3379 #endif
3380 case QEMU_OPTION_netdev:
3381 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
3382 exit(1);
3384 break;
3385 case QEMU_OPTION_net:
3386 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
3387 exit(1);
3389 break;
3390 #ifdef CONFIG_SLIRP
3391 case QEMU_OPTION_tftp:
3392 legacy_tftp_prefix = optarg;
3393 break;
3394 case QEMU_OPTION_bootp:
3395 legacy_bootp_filename = optarg;
3396 break;
3397 #ifndef _WIN32
3398 case QEMU_OPTION_smb:
3399 if (net_slirp_smb(optarg) < 0)
3400 exit(1);
3401 break;
3402 #endif
3403 case QEMU_OPTION_redir:
3404 if (net_slirp_redir(optarg) < 0)
3405 exit(1);
3406 break;
3407 #endif
3408 case QEMU_OPTION_bt:
3409 add_device_config(DEV_BT, optarg);
3410 break;
3411 #ifdef HAS_AUDIO
3412 case QEMU_OPTION_audio_help:
3413 AUD_help ();
3414 exit (0);
3415 break;
3416 case QEMU_OPTION_soundhw:
3417 select_soundhw (optarg);
3418 break;
3419 #endif
3420 case QEMU_OPTION_h:
3421 help(0);
3422 break;
3423 case QEMU_OPTION_version:
3424 version();
3425 exit(0);
3426 break;
3427 case QEMU_OPTION_m: {
3428 uint64_t value;
3429 char *ptr;
3431 value = strtoul(optarg, &ptr, 10);
3432 switch (*ptr) {
3433 case 0: case 'M': case 'm':
3434 value <<= 20;
3435 break;
3436 case 'G': case 'g':
3437 value <<= 30;
3438 break;
3439 default:
3440 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
3441 exit(1);
3444 /* On 32-bit hosts, QEMU is limited by virtual address space */
3445 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
3446 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3447 exit(1);
3449 if (value != (uint64_t)(ram_addr_t)value) {
3450 fprintf(stderr, "qemu: ram size too large\n");
3451 exit(1);
3453 ram_size = value;
3454 break;
3456 case QEMU_OPTION_mempath:
3457 mem_path = optarg;
3458 break;
3459 #ifdef MAP_POPULATE
3460 case QEMU_OPTION_mem_prealloc:
3461 mem_prealloc = 1;
3462 break;
3463 #endif
3464 case QEMU_OPTION_d:
3465 set_cpu_log(optarg);
3466 break;
3467 case QEMU_OPTION_s:
3468 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
3469 break;
3470 case QEMU_OPTION_gdb:
3471 gdbstub_dev = optarg;
3472 break;
3473 case QEMU_OPTION_L:
3474 data_dir = optarg;
3475 break;
3476 case QEMU_OPTION_bios:
3477 bios_name = optarg;
3478 break;
3479 case QEMU_OPTION_singlestep:
3480 singlestep = 1;
3481 break;
3482 case QEMU_OPTION_S:
3483 autostart = 0;
3484 break;
3485 case QEMU_OPTION_k:
3486 keyboard_layout = optarg;
3487 break;
3488 case QEMU_OPTION_localtime:
3489 rtc_utc = 0;
3490 break;
3491 case QEMU_OPTION_vga:
3492 select_vgahw (optarg);
3493 break;
3494 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3495 case QEMU_OPTION_g:
3497 const char *p;
3498 int w, h, depth;
3499 p = optarg;
3500 w = strtol(p, (char **)&p, 10);
3501 if (w <= 0) {
3502 graphic_error:
3503 fprintf(stderr, "qemu: invalid resolution or depth\n");
3504 exit(1);
3506 if (*p != 'x')
3507 goto graphic_error;
3508 p++;
3509 h = strtol(p, (char **)&p, 10);
3510 if (h <= 0)
3511 goto graphic_error;
3512 if (*p == 'x') {
3513 p++;
3514 depth = strtol(p, (char **)&p, 10);
3515 if (depth != 8 && depth != 15 && depth != 16 &&
3516 depth != 24 && depth != 32)
3517 goto graphic_error;
3518 } else if (*p == '\0') {
3519 depth = graphic_depth;
3520 } else {
3521 goto graphic_error;
3524 graphic_width = w;
3525 graphic_height = h;
3526 graphic_depth = depth;
3528 break;
3529 #endif
3530 case QEMU_OPTION_echr:
3532 char *r;
3533 term_escape_char = strtol(optarg, &r, 0);
3534 if (r == optarg)
3535 printf("Bad argument to echr\n");
3536 break;
3538 case QEMU_OPTION_monitor:
3539 monitor_parse(optarg, "readline");
3540 default_monitor = 0;
3541 break;
3542 case QEMU_OPTION_qmp:
3543 monitor_parse(optarg, "control");
3544 default_monitor = 0;
3545 break;
3546 case QEMU_OPTION_mon:
3547 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
3548 if (!opts) {
3549 fprintf(stderr, "parse error: %s\n", optarg);
3550 exit(1);
3552 default_monitor = 0;
3553 break;
3554 case QEMU_OPTION_chardev:
3555 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
3556 if (!opts) {
3557 fprintf(stderr, "parse error: %s\n", optarg);
3558 exit(1);
3560 break;
3561 case QEMU_OPTION_serial:
3562 add_device_config(DEV_SERIAL, optarg);
3563 default_serial = 0;
3564 if (strncmp(optarg, "mon:", 4) == 0) {
3565 default_monitor = 0;
3567 break;
3568 case QEMU_OPTION_watchdog:
3569 if (watchdog) {
3570 fprintf(stderr,
3571 "qemu: only one watchdog option may be given\n");
3572 return 1;
3574 watchdog = optarg;
3575 break;
3576 case QEMU_OPTION_watchdog_action:
3577 if (select_watchdog_action(optarg) == -1) {
3578 fprintf(stderr, "Unknown -watchdog-action parameter\n");
3579 exit(1);
3581 break;
3582 case QEMU_OPTION_virtiocon:
3583 add_device_config(DEV_VIRTCON, optarg);
3584 default_virtcon = 0;
3585 if (strncmp(optarg, "mon:", 4) == 0) {
3586 default_monitor = 0;
3588 break;
3589 case QEMU_OPTION_parallel:
3590 add_device_config(DEV_PARALLEL, optarg);
3591 default_parallel = 0;
3592 if (strncmp(optarg, "mon:", 4) == 0) {
3593 default_monitor = 0;
3595 break;
3596 case QEMU_OPTION_debugcon:
3597 add_device_config(DEV_DEBUGCON, optarg);
3598 break;
3599 case QEMU_OPTION_loadvm:
3600 loadvm = optarg;
3601 break;
3602 case QEMU_OPTION_full_screen:
3603 full_screen = 1;
3604 break;
3605 #ifdef CONFIG_SDL
3606 case QEMU_OPTION_no_frame:
3607 no_frame = 1;
3608 break;
3609 case QEMU_OPTION_alt_grab:
3610 alt_grab = 1;
3611 break;
3612 case QEMU_OPTION_ctrl_grab:
3613 ctrl_grab = 1;
3614 break;
3615 case QEMU_OPTION_no_quit:
3616 no_quit = 1;
3617 break;
3618 case QEMU_OPTION_sdl:
3619 display_type = DT_SDL;
3620 break;
3621 #endif
3622 case QEMU_OPTION_pidfile:
3623 pid_file = optarg;
3624 break;
3625 #ifdef TARGET_I386
3626 case QEMU_OPTION_win2k_hack:
3627 win2k_install_hack = 1;
3628 break;
3629 case QEMU_OPTION_rtc_td_hack:
3630 rtc_td_hack = 1;
3631 break;
3632 case QEMU_OPTION_acpitable:
3633 do_acpitable_option(optarg);
3634 break;
3635 case QEMU_OPTION_smbios:
3636 do_smbios_option(optarg);
3637 break;
3638 #endif
3639 #ifdef CONFIG_KVM
3640 case QEMU_OPTION_enable_kvm:
3641 kvm_allowed = 1;
3642 break;
3643 #endif
3644 case QEMU_OPTION_usb:
3645 usb_enabled = 1;
3646 break;
3647 case QEMU_OPTION_usbdevice:
3648 usb_enabled = 1;
3649 add_device_config(DEV_USB, optarg);
3650 break;
3651 case QEMU_OPTION_device:
3652 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
3653 exit(1);
3655 break;
3656 case QEMU_OPTION_smp:
3657 smp_parse(optarg);
3658 if (smp_cpus < 1) {
3659 fprintf(stderr, "Invalid number of CPUs\n");
3660 exit(1);
3662 if (max_cpus < smp_cpus) {
3663 fprintf(stderr, "maxcpus must be equal to or greater than "
3664 "smp\n");
3665 exit(1);
3667 if (max_cpus > 255) {
3668 fprintf(stderr, "Unsupported number of maxcpus\n");
3669 exit(1);
3671 break;
3672 case QEMU_OPTION_vnc:
3673 display_type = DT_VNC;
3674 vnc_display = optarg;
3675 break;
3676 #ifdef TARGET_I386
3677 case QEMU_OPTION_no_acpi:
3678 acpi_enabled = 0;
3679 break;
3680 case QEMU_OPTION_no_hpet:
3681 no_hpet = 1;
3682 break;
3683 case QEMU_OPTION_balloon:
3684 if (balloon_parse(optarg) < 0) {
3685 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3686 exit(1);
3688 break;
3689 #endif
3690 case QEMU_OPTION_no_reboot:
3691 no_reboot = 1;
3692 break;
3693 case QEMU_OPTION_no_shutdown:
3694 no_shutdown = 1;
3695 break;
3696 case QEMU_OPTION_show_cursor:
3697 cursor_hide = 0;
3698 break;
3699 case QEMU_OPTION_uuid:
3700 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3701 fprintf(stderr, "Fail to parse UUID string."
3702 " Wrong format.\n");
3703 exit(1);
3705 break;
3706 #ifndef _WIN32
3707 case QEMU_OPTION_daemonize:
3708 daemonize = 1;
3709 break;
3710 #endif
3711 case QEMU_OPTION_option_rom:
3712 if (nb_option_roms >= MAX_OPTION_ROMS) {
3713 fprintf(stderr, "Too many option ROMs\n");
3714 exit(1);
3716 option_rom[nb_option_roms] = optarg;
3717 nb_option_roms++;
3718 break;
3719 #if defined(TARGET_ARM) || defined(TARGET_M68K)
3720 case QEMU_OPTION_semihosting:
3721 semihosting_enabled = 1;
3722 break;
3723 #endif
3724 case QEMU_OPTION_name:
3725 qemu_name = qemu_strdup(optarg);
3727 char *p = strchr(qemu_name, ',');
3728 if (p != NULL) {
3729 *p++ = 0;
3730 if (strncmp(p, "process=", 8)) {
3731 fprintf(stderr, "Unknown subargument %s to -name", p);
3732 exit(1);
3734 p += 8;
3735 set_proc_name(p);
3738 break;
3739 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
3740 case QEMU_OPTION_prom_env:
3741 if (nb_prom_envs >= MAX_PROM_ENVS) {
3742 fprintf(stderr, "Too many prom variables\n");
3743 exit(1);
3745 prom_envs[nb_prom_envs] = optarg;
3746 nb_prom_envs++;
3747 break;
3748 #endif
3749 #ifdef TARGET_ARM
3750 case QEMU_OPTION_old_param:
3751 old_param = 1;
3752 break;
3753 #endif
3754 case QEMU_OPTION_clock:
3755 configure_alarms(optarg);
3756 break;
3757 case QEMU_OPTION_startdate:
3758 configure_rtc_date_offset(optarg, 1);
3759 break;
3760 case QEMU_OPTION_rtc:
3761 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
3762 if (!opts) {
3763 fprintf(stderr, "parse error: %s\n", optarg);
3764 exit(1);
3766 configure_rtc(opts);
3767 break;
3768 case QEMU_OPTION_tb_size:
3769 tb_size = strtol(optarg, NULL, 0);
3770 if (tb_size < 0)
3771 tb_size = 0;
3772 break;
3773 case QEMU_OPTION_icount:
3774 icount_option = optarg;
3775 break;
3776 case QEMU_OPTION_incoming:
3777 incoming = optarg;
3778 break;
3779 case QEMU_OPTION_nodefaults:
3780 default_serial = 0;
3781 default_parallel = 0;
3782 default_virtcon = 0;
3783 default_monitor = 0;
3784 default_vga = 0;
3785 default_net = 0;
3786 default_floppy = 0;
3787 default_cdrom = 0;
3788 default_sdcard = 0;
3789 break;
3790 #ifndef _WIN32
3791 case QEMU_OPTION_chroot:
3792 chroot_dir = optarg;
3793 break;
3794 case QEMU_OPTION_runas:
3795 run_as = optarg;
3796 break;
3797 #endif
3798 #ifdef CONFIG_XEN
3799 case QEMU_OPTION_xen_domid:
3800 xen_domid = atoi(optarg);
3801 break;
3802 case QEMU_OPTION_xen_create:
3803 xen_mode = XEN_CREATE;
3804 break;
3805 case QEMU_OPTION_xen_attach:
3806 xen_mode = XEN_ATTACH;
3807 break;
3808 #endif
3809 case QEMU_OPTION_readconfig:
3811 FILE *fp;
3812 fp = fopen(optarg, "r");
3813 if (fp == NULL) {
3814 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3815 exit(1);
3817 if (qemu_config_parse(fp, optarg) != 0) {
3818 exit(1);
3820 fclose(fp);
3821 break;
3823 case QEMU_OPTION_writeconfig:
3825 FILE *fp;
3826 if (strcmp(optarg, "-") == 0) {
3827 fp = stdout;
3828 } else {
3829 fp = fopen(optarg, "w");
3830 if (fp == NULL) {
3831 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3832 exit(1);
3835 qemu_config_write(fp);
3836 fclose(fp);
3837 break;
3842 loc_set_none();
3844 /* If no data_dir is specified then try to find it relative to the
3845 executable path. */
3846 if (!data_dir) {
3847 data_dir = find_datadir(argv[0]);
3849 /* If all else fails use the install patch specified when building. */
3850 if (!data_dir) {
3851 data_dir = CONFIG_QEMU_SHAREDIR;
3855 * Default to max_cpus = smp_cpus, in case the user doesn't
3856 * specify a max_cpus value.
3858 if (!max_cpus)
3859 max_cpus = smp_cpus;
3861 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3862 if (smp_cpus > machine->max_cpus) {
3863 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3864 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
3865 machine->max_cpus);
3866 exit(1);
3869 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
3870 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
3872 if (machine->no_serial) {
3873 default_serial = 0;
3875 if (machine->no_parallel) {
3876 default_parallel = 0;
3878 if (!machine->use_virtcon) {
3879 default_virtcon = 0;
3881 if (machine->no_vga) {
3882 default_vga = 0;
3884 if (machine->no_floppy) {
3885 default_floppy = 0;
3887 if (machine->no_cdrom) {
3888 default_cdrom = 0;
3890 if (machine->no_sdcard) {
3891 default_sdcard = 0;
3894 if (display_type == DT_NOGRAPHIC) {
3895 if (default_parallel)
3896 add_device_config(DEV_PARALLEL, "null");
3897 if (default_serial && default_monitor) {
3898 add_device_config(DEV_SERIAL, "mon:stdio");
3899 } else if (default_virtcon && default_monitor) {
3900 add_device_config(DEV_VIRTCON, "mon:stdio");
3901 } else {
3902 if (default_serial)
3903 add_device_config(DEV_SERIAL, "stdio");
3904 if (default_virtcon)
3905 add_device_config(DEV_VIRTCON, "stdio");
3906 if (default_monitor)
3907 monitor_parse("stdio", "readline");
3909 } else {
3910 if (default_serial)
3911 add_device_config(DEV_SERIAL, "vc:80Cx24C");
3912 if (default_parallel)
3913 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3914 if (default_monitor)
3915 monitor_parse("vc:80Cx24C", "readline");
3916 if (default_virtcon)
3917 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3919 if (default_vga)
3920 vga_interface_type = VGA_CIRRUS;
3922 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
3923 exit(1);
3925 #ifndef _WIN32
3926 if (daemonize) {
3927 pid_t pid;
3929 if (pipe(fds) == -1)
3930 exit(1);
3932 pid = fork();
3933 if (pid > 0) {
3934 uint8_t status;
3935 ssize_t len;
3937 close(fds[1]);
3939 again:
3940 len = read(fds[0], &status, 1);
3941 if (len == -1 && (errno == EINTR))
3942 goto again;
3944 if (len != 1)
3945 exit(1);
3946 else if (status == 1) {
3947 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
3948 exit(1);
3949 } else
3950 exit(0);
3951 } else if (pid < 0)
3952 exit(1);
3954 close(fds[0]);
3955 qemu_set_cloexec(fds[1]);
3957 setsid();
3959 pid = fork();
3960 if (pid > 0)
3961 exit(0);
3962 else if (pid < 0)
3963 exit(1);
3965 umask(027);
3967 signal(SIGTSTP, SIG_IGN);
3968 signal(SIGTTOU, SIG_IGN);
3969 signal(SIGTTIN, SIG_IGN);
3971 #endif
3973 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3974 #ifndef _WIN32
3975 if (daemonize) {
3976 uint8_t status = 1;
3977 if (write(fds[1], &status, 1) != 1) {
3978 perror("daemonize. Writing to pipe\n");
3980 } else
3981 #endif
3982 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
3983 exit(1);
3986 if (kvm_enabled()) {
3987 int ret;
3989 ret = kvm_init(smp_cpus);
3990 if (ret < 0) {
3991 fprintf(stderr, "failed to initialize KVM\n");
3992 exit(1);
3996 if (qemu_init_main_loop()) {
3997 fprintf(stderr, "qemu_init_main_loop failed\n");
3998 exit(1);
4000 linux_boot = (kernel_filename != NULL);
4002 if (!linux_boot && *kernel_cmdline != '\0') {
4003 fprintf(stderr, "-append only allowed with -kernel option\n");
4004 exit(1);
4007 if (!linux_boot && initrd_filename != NULL) {
4008 fprintf(stderr, "-initrd only allowed with -kernel option\n");
4009 exit(1);
4012 #ifndef _WIN32
4013 /* Win32 doesn't support line-buffering and requires size >= 2 */
4014 setvbuf(stdout, NULL, _IOLBF, 0);
4015 #endif
4017 if (init_timer_alarm() < 0) {
4018 fprintf(stderr, "could not initialize alarm timer\n");
4019 exit(1);
4021 configure_icount(icount_option);
4023 #ifdef _WIN32
4024 socket_init();
4025 #endif
4027 if (net_init_clients() < 0) {
4028 exit(1);
4031 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4032 net_set_boot_mask(net_boot);
4034 /* init the bluetooth world */
4035 if (foreach_device_config(DEV_BT, bt_parse))
4036 exit(1);
4038 /* init the memory */
4039 if (ram_size == 0)
4040 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4042 /* init the dynamic translator */
4043 cpu_exec_init_all(tb_size * 1024 * 1024);
4045 bdrv_init_with_whitelist();
4047 blk_mig_init();
4049 if (default_cdrom) {
4050 /* we always create the cdrom drive, even if no disk is there */
4051 drive_add(NULL, CDROM_ALIAS);
4054 if (default_floppy) {
4055 /* we always create at least one floppy */
4056 drive_add(NULL, FD_ALIAS, 0);
4059 if (default_sdcard) {
4060 /* we always create one sd slot, even if no card is in it */
4061 drive_add(NULL, SD_ALIAS);
4064 /* open the virtual block devices */
4065 if (snapshot)
4066 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4067 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4068 exit(1);
4070 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
4071 ram_load, NULL);
4073 if (nb_numa_nodes > 0) {
4074 int i;
4076 if (nb_numa_nodes > smp_cpus) {
4077 nb_numa_nodes = smp_cpus;
4080 /* If no memory size if given for any node, assume the default case
4081 * and distribute the available memory equally across all nodes
4083 for (i = 0; i < nb_numa_nodes; i++) {
4084 if (node_mem[i] != 0)
4085 break;
4087 if (i == nb_numa_nodes) {
4088 uint64_t usedmem = 0;
4090 /* On Linux, the each node's border has to be 8MB aligned,
4091 * the final node gets the rest.
4093 for (i = 0; i < nb_numa_nodes - 1; i++) {
4094 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4095 usedmem += node_mem[i];
4097 node_mem[i] = ram_size - usedmem;
4100 for (i = 0; i < nb_numa_nodes; i++) {
4101 if (node_cpumask[i] != 0)
4102 break;
4104 /* assigning the VCPUs round-robin is easier to implement, guest OSes
4105 * must cope with this anyway, because there are BIOSes out there in
4106 * real machines which also use this scheme.
4108 if (i == nb_numa_nodes) {
4109 for (i = 0; i < smp_cpus; i++) {
4110 node_cpumask[i % nb_numa_nodes] |= 1 << i;
4115 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4116 exit(1);
4117 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4118 exit(1);
4119 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4120 exit(1);
4121 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4122 exit(1);
4124 module_call_init(MODULE_INIT_DEVICE);
4126 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
4127 exit(0);
4129 if (watchdog) {
4130 i = select_watchdog(watchdog);
4131 if (i > 0)
4132 exit (i == 1 ? 1 : 0);
4135 if (machine->compat_props) {
4136 qdev_prop_register_global_list(machine->compat_props);
4138 qemu_add_globals();
4140 machine->init(ram_size, boot_devices,
4141 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
4143 cpu_synchronize_all_post_init();
4145 #ifndef _WIN32
4146 /* must be after terminal init, SDL library changes signal handlers */
4147 sighandler_setup();
4148 #endif
4150 set_numa_modes();
4152 current_machine = machine;
4154 /* init USB devices */
4155 if (usb_enabled) {
4156 if (foreach_device_config(DEV_USB, usb_parse) < 0)
4157 exit(1);
4160 /* init generic devices */
4161 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
4162 exit(1);
4164 net_check_clients();
4166 /* just use the first displaystate for the moment */
4167 ds = get_displaystate();
4169 if (display_type == DT_DEFAULT) {
4170 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4171 display_type = DT_SDL;
4172 #else
4173 display_type = DT_VNC;
4174 vnc_display = "localhost:0,to=99";
4175 show_vnc_port = 1;
4176 #endif
4180 switch (display_type) {
4181 case DT_NOGRAPHIC:
4182 break;
4183 #if defined(CONFIG_CURSES)
4184 case DT_CURSES:
4185 curses_display_init(ds, full_screen);
4186 break;
4187 #endif
4188 #if defined(CONFIG_SDL)
4189 case DT_SDL:
4190 sdl_display_init(ds, full_screen, no_frame);
4191 break;
4192 #elif defined(CONFIG_COCOA)
4193 case DT_SDL:
4194 cocoa_display_init(ds, full_screen);
4195 break;
4196 #endif
4197 case DT_VNC:
4198 vnc_display_init(ds);
4199 if (vnc_display_open(ds, vnc_display) < 0)
4200 exit(1);
4202 if (show_vnc_port) {
4203 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
4205 break;
4206 default:
4207 break;
4209 dpy_resize(ds);
4211 dcl = ds->listeners;
4212 while (dcl != NULL) {
4213 if (dcl->dpy_refresh != NULL) {
4214 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
4215 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
4217 dcl = dcl->next;
4220 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
4221 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
4222 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
4225 text_consoles_set_display(ds);
4227 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
4228 exit(1);
4230 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
4231 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
4232 gdbstub_dev);
4233 exit(1);
4236 qdev_machine_creation_done();
4238 if (rom_load_all() != 0) {
4239 fprintf(stderr, "rom loading failed\n");
4240 exit(1);
4243 qemu_system_reset();
4244 if (loadvm) {
4245 if (load_vmstate(loadvm) < 0) {
4246 autostart = 0;
4250 if (incoming) {
4251 qemu_start_incoming_migration(incoming);
4252 } else if (autostart) {
4253 vm_start();
4256 #ifndef _WIN32
4257 if (daemonize) {
4258 uint8_t status = 0;
4259 ssize_t len;
4261 again1:
4262 len = write(fds[1], &status, 1);
4263 if (len == -1 && (errno == EINTR))
4264 goto again1;
4266 if (len != 1)
4267 exit(1);
4269 if (chdir("/")) {
4270 perror("not able to chdir to /");
4271 exit(1);
4273 TFR(fd = qemu_open("/dev/null", O_RDWR));
4274 if (fd == -1)
4275 exit(1);
4278 if (run_as) {
4279 pwd = getpwnam(run_as);
4280 if (!pwd) {
4281 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
4282 exit(1);
4286 if (chroot_dir) {
4287 if (chroot(chroot_dir) < 0) {
4288 fprintf(stderr, "chroot failed\n");
4289 exit(1);
4291 if (chdir("/")) {
4292 perror("not able to chdir to /");
4293 exit(1);
4297 if (run_as) {
4298 if (setgid(pwd->pw_gid) < 0) {
4299 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
4300 exit(1);
4302 if (setuid(pwd->pw_uid) < 0) {
4303 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
4304 exit(1);
4306 if (setuid(0) != -1) {
4307 fprintf(stderr, "Dropping privileges failed\n");
4308 exit(1);
4312 if (daemonize) {
4313 dup2(fd, 0);
4314 dup2(fd, 1);
4315 dup2(fd, 2);
4317 close(fd);
4319 #endif
4321 main_loop();
4322 quit_timers();
4323 net_cleanup();
4325 return 0;