Merge commit '80a1ab598c6960e7a941e38c5d8638c532c585c3' into upstream-merge
[qemu-kvm/amd-iommu.git] / vl.c
blobbbc3c7e96ce41fab9d21fd73c5cca860b57456c2
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 #if defined(CONFIG_UUID)
97 #include <uuid/uuid.h>
98 #endif
100 #ifdef _WIN32
101 #include <windows.h>
102 #endif
104 #ifdef CONFIG_SDL
105 #if defined(__APPLE__) || defined(main)
106 #include <SDL.h>
107 int qemu_main(int argc, char **argv, char **envp);
108 int main(int argc, char **argv)
110 return qemu_main(argc, argv, NULL);
112 #undef main
113 #define main qemu_main
114 #endif
115 #endif /* CONFIG_SDL */
117 #ifdef CONFIG_COCOA
118 #undef main
119 #define main qemu_main
120 #endif /* CONFIG_COCOA */
122 #include "hw/hw.h"
123 #include "hw/boards.h"
124 #include "hw/usb.h"
125 #include "hw/pcmcia.h"
126 #include "hw/pc.h"
127 #include "hw/audiodev.h"
128 #include "hw/isa.h"
129 #include "hw/baum.h"
130 #include "hw/bt.h"
131 #include "hw/watchdog.h"
132 #include "hw/smbios.h"
133 #include "hw/xen.h"
134 #include "hw/qdev.h"
135 #include "hw/loader.h"
136 #include "bt-host.h"
137 #include "net.h"
138 #include "net/slirp.h"
139 #include "monitor.h"
140 #include "console.h"
141 #include "sysemu.h"
142 #include "gdbstub.h"
143 #include "qemu-timer.h"
144 #include "qemu-char.h"
145 #include "cache-utils.h"
146 #include "block.h"
147 #include "block_int.h"
148 #include "block-migration.h"
149 #include "dma.h"
150 #include "audio/audio.h"
151 #include "migration.h"
152 #include "kvm.h"
153 #include "balloon.h"
154 #include "qemu-option.h"
155 #include "qemu-config.h"
156 #include "qemu-objects.h"
157 #include "hw/device-assignment.h"
158 #include "notify.h"
160 #include "disas.h"
162 #include "exec-all.h"
164 #include "qemu_socket.h"
166 #include "slirp/libslirp.h"
168 #include "qemu-queue.h"
170 //#define DEBUG_NET
171 //#define DEBUG_SLIRP
173 #define DEFAULT_RAM_SIZE 128
175 #define MAX_VIRTIO_CONSOLES 1
177 static const char *data_dir;
178 const char *bios_name = NULL;
179 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
180 to store the VM snapshots */
181 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
182 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
183 DriveInfo *extboot_drive = NULL;
184 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
185 DisplayType display_type = DT_DEFAULT;
186 const char* keyboard_layout = NULL;
187 ram_addr_t ram_size;
188 const char *mem_path = NULL;
189 #ifdef MAP_POPULATE
190 int mem_prealloc = 0; /* force preallocation of physical target memory */
191 #endif
192 int nb_nics;
193 NICInfo nd_table[MAX_NICS];
194 int vm_running;
195 int autostart;
196 static int rtc_utc = 1;
197 static int rtc_date_offset = -1; /* -1 means no change */
198 QEMUClock *rtc_clock;
199 int vga_interface_type = VGA_NONE;
200 #ifdef TARGET_SPARC
201 int graphic_width = 1024;
202 int graphic_height = 768;
203 int graphic_depth = 8;
204 #else
205 int graphic_width = 800;
206 int graphic_height = 600;
207 int graphic_depth = 15;
208 #endif
209 static int full_screen = 0;
210 #ifdef CONFIG_SDL
211 static int no_frame = 0;
212 #endif
213 int no_quit = 0;
214 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
215 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
216 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
217 #ifdef TARGET_I386
218 int win2k_install_hack = 0;
219 int rtc_td_hack = 0;
220 #endif
221 int usb_enabled = 0;
222 int singlestep = 0;
223 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
224 int assigned_devices_index;
225 int smp_cpus = 1;
226 int max_cpus = 0;
227 int smp_cores = 1;
228 int smp_threads = 1;
229 const char *vnc_display;
230 int acpi_enabled = 1;
231 #ifdef TARGET_I386
232 int no_hpet = 0;
233 #endif
234 int fd_bootchk = 1;
235 int no_reboot = 0;
236 int no_shutdown = 0;
237 int cursor_hide = 1;
238 int graphic_rotate = 0;
239 uint8_t irq0override = 1;
240 #ifndef _WIN32
241 int daemonize = 0;
242 #endif
243 const char *watchdog;
244 const char *option_rom[MAX_OPTION_ROMS];
245 int nb_option_roms;
246 int semihosting_enabled = 0;
247 int time_drift_fix = 0;
248 unsigned int kvm_shadow_memory = 0;
249 #ifdef TARGET_ARM
250 int old_param = 0;
251 #endif
252 const char *qemu_name;
253 int alt_grab = 0;
254 int ctrl_grab = 0;
255 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
256 unsigned int nb_prom_envs = 0;
257 const char *prom_envs[MAX_PROM_ENVS];
258 #endif
259 const char *nvram = NULL;
260 int boot_menu;
262 int nb_numa_nodes;
263 uint64_t node_mem[MAX_NODES];
264 uint64_t node_cpumask[MAX_NODES];
266 static CPUState *cur_cpu;
267 static CPUState *next_cpu;
268 static QEMUTimer *nographic_timer;
270 uint8_t qemu_uuid[16];
272 static QEMUBootSetHandler *boot_set_handler;
273 static void *boot_set_opaque;
275 #ifdef SIGRTMIN
276 #define SIG_IPI (SIGRTMIN+4)
277 #else
278 #define SIG_IPI SIGUSR1
279 #endif
281 static int default_serial = 1;
282 static int default_parallel = 1;
283 static int default_virtcon = 1;
284 static int default_monitor = 1;
285 static int default_vga = 1;
286 static int default_floppy = 1;
287 static int default_cdrom = 1;
288 static int default_sdcard = 1;
289 static int default_qmp = 1;
291 static struct {
292 const char *driver;
293 int *flag;
294 } default_list[] = {
295 { .driver = "isa-serial", .flag = &default_serial },
296 { .driver = "isa-parallel", .flag = &default_parallel },
297 { .driver = "isa-fdc", .flag = &default_floppy },
298 { .driver = "ide-drive", .flag = &default_cdrom },
299 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
300 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
301 { .driver = "virtio-serial", .flag = &default_virtcon },
302 { .driver = "VGA", .flag = &default_vga },
303 { .driver = "cirrus-vga", .flag = &default_vga },
304 { .driver = "vmware-svga", .flag = &default_vga },
307 static int default_driver_check(QemuOpts *opts, void *opaque)
309 const char *driver = qemu_opt_get(opts, "driver");
310 int i;
312 if (!driver)
313 return 0;
314 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
315 if (strcmp(default_list[i].driver, driver) != 0)
316 continue;
317 *(default_list[i].flag) = 0;
319 return 0;
322 /***********************************************************/
323 /* x86 ISA bus support */
325 target_phys_addr_t isa_mem_base = 0;
326 PicState2 *isa_pic;
328 /***********************************************************/
329 void hw_error(const char *fmt, ...)
331 va_list ap;
332 CPUState *env;
334 va_start(ap, fmt);
335 fprintf(stderr, "qemu: hardware error: ");
336 vfprintf(stderr, fmt, ap);
337 fprintf(stderr, "\n");
338 for(env = first_cpu; env != NULL; env = env->next_cpu) {
339 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
340 #ifdef TARGET_I386
341 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
342 #else
343 cpu_dump_state(env, stderr, fprintf, 0);
344 #endif
346 va_end(ap);
347 abort();
350 static void set_proc_name(const char *s)
352 #if defined(__linux__) && defined(PR_SET_NAME)
353 char name[16];
354 if (!s)
355 return;
356 name[sizeof(name) - 1] = 0;
357 strncpy(name, s, sizeof(name));
358 /* Could rewrite argv[0] too, but that's a bit more complicated.
359 This simple way is enough for `top'. */
360 prctl(PR_SET_NAME, name);
361 #endif
364 /***************/
365 /* ballooning */
367 static QEMUBalloonEvent *qemu_balloon_event;
368 void *qemu_balloon_event_opaque;
370 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
372 qemu_balloon_event = func;
373 qemu_balloon_event_opaque = opaque;
376 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
378 if (qemu_balloon_event) {
379 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
380 return 1;
381 } else {
382 return 0;
386 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
388 if (qemu_balloon_event) {
389 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
390 return 1;
391 } else {
392 return 0;
397 /***********************************************************/
398 /* real time host monotonic timer */
400 /* compute with 96 bit intermediate result: (a*b)/c */
401 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
403 union {
404 uint64_t ll;
405 struct {
406 #ifdef HOST_WORDS_BIGENDIAN
407 uint32_t high, low;
408 #else
409 uint32_t low, high;
410 #endif
411 } l;
412 } u, res;
413 uint64_t rl, rh;
415 u.ll = a;
416 rl = (uint64_t)u.l.low * (uint64_t)b;
417 rh = (uint64_t)u.l.high * (uint64_t)b;
418 rh += (rl >> 32);
419 res.l.high = rh / c;
420 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
421 return res.ll;
424 /***********************************************************/
425 /* host time/date access */
426 void qemu_get_timedate(struct tm *tm, int offset)
428 time_t ti;
429 struct tm *ret;
431 time(&ti);
432 ti += offset;
433 if (rtc_date_offset == -1) {
434 if (rtc_utc)
435 ret = gmtime(&ti);
436 else
437 ret = localtime(&ti);
438 } else {
439 ti -= rtc_date_offset;
440 ret = gmtime(&ti);
443 memcpy(tm, ret, sizeof(struct tm));
446 int qemu_timedate_diff(struct tm *tm)
448 time_t seconds;
450 if (rtc_date_offset == -1)
451 if (rtc_utc)
452 seconds = mktimegm(tm);
453 else
454 seconds = mktime(tm);
455 else
456 seconds = mktimegm(tm) + rtc_date_offset;
458 return seconds - time(NULL);
461 void rtc_change_mon_event(struct tm *tm)
463 QObject *data;
465 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
466 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
467 qobject_decref(data);
470 static void configure_rtc_date_offset(const char *startdate, int legacy)
472 time_t rtc_start_date;
473 struct tm tm;
475 if (!strcmp(startdate, "now") && legacy) {
476 rtc_date_offset = -1;
477 } else {
478 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
479 &tm.tm_year,
480 &tm.tm_mon,
481 &tm.tm_mday,
482 &tm.tm_hour,
483 &tm.tm_min,
484 &tm.tm_sec) == 6) {
485 /* OK */
486 } else if (sscanf(startdate, "%d-%d-%d",
487 &tm.tm_year,
488 &tm.tm_mon,
489 &tm.tm_mday) == 3) {
490 tm.tm_hour = 0;
491 tm.tm_min = 0;
492 tm.tm_sec = 0;
493 } else {
494 goto date_fail;
496 tm.tm_year -= 1900;
497 tm.tm_mon--;
498 rtc_start_date = mktimegm(&tm);
499 if (rtc_start_date == -1) {
500 date_fail:
501 fprintf(stderr, "Invalid date format. Valid formats are:\n"
502 "'2006-06-17T16:01:21' or '2006-06-17'\n");
503 exit(1);
505 rtc_date_offset = time(NULL) - rtc_start_date;
509 static void configure_rtc(QemuOpts *opts)
511 const char *value;
513 value = qemu_opt_get(opts, "base");
514 if (value) {
515 if (!strcmp(value, "utc")) {
516 rtc_utc = 1;
517 } else if (!strcmp(value, "localtime")) {
518 rtc_utc = 0;
519 } else {
520 configure_rtc_date_offset(value, 0);
523 value = qemu_opt_get(opts, "clock");
524 if (value) {
525 if (!strcmp(value, "host")) {
526 rtc_clock = host_clock;
527 } else if (!strcmp(value, "vm")) {
528 rtc_clock = vm_clock;
529 } else {
530 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
531 exit(1);
534 #ifdef CONFIG_TARGET_I386
535 value = qemu_opt_get(opts, "driftfix");
536 if (value) {
537 if (!strcmp(buf, "slew")) {
538 rtc_td_hack = 1;
539 } else if (!strcmp(buf, "none")) {
540 rtc_td_hack = 0;
541 } else {
542 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
543 exit(1);
546 #endif
549 #ifdef _WIN32
550 static void socket_cleanup(Notifier *obj)
552 WSACleanup();
555 static int socket_init(void)
557 WSADATA Data;
558 int ret, err;
559 static Notifier notifier = { .notify = socket_cleanup };
561 ret = WSAStartup(MAKEWORD(2,2), &Data);
562 if (ret != 0) {
563 err = WSAGetLastError();
564 fprintf(stderr, "WSAStartup: %d\n", err);
565 return -1;
567 exit_notifier_add(&notifier);
568 return 0;
570 #endif
572 /*********************/
573 /* Exit notifiers */
574 /*********************/
576 static NotifierList exit_notifiers = NOTIFIER_LIST_INITIALIZER(exit_notifiers);
578 void exit_notifier_add(Notifier *notifier)
580 notifier_list_add(&exit_notifiers, notifier);
583 void exit_notifier_remove(Notifier *notifier)
585 notifier_list_remove(&exit_notifiers, notifier);
588 static void exit_notifier_notify(void)
590 notifier_list_notify(&exit_notifiers);
593 static void exit_notifier_init(void)
595 atexit(exit_notifier_notify);
598 /***********************************************************/
599 /* Bluetooth support */
600 static int nb_hcis;
601 static int cur_hci;
602 static struct HCIInfo *hci_table[MAX_NICS];
604 static struct bt_vlan_s {
605 struct bt_scatternet_s net;
606 int id;
607 struct bt_vlan_s *next;
608 } *first_bt_vlan;
610 /* find or alloc a new bluetooth "VLAN" */
611 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
613 struct bt_vlan_s **pvlan, *vlan;
614 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
615 if (vlan->id == id)
616 return &vlan->net;
618 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
619 vlan->id = id;
620 pvlan = &first_bt_vlan;
621 while (*pvlan != NULL)
622 pvlan = &(*pvlan)->next;
623 *pvlan = vlan;
624 return &vlan->net;
627 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
631 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
633 return -ENOTSUP;
636 static struct HCIInfo null_hci = {
637 .cmd_send = null_hci_send,
638 .sco_send = null_hci_send,
639 .acl_send = null_hci_send,
640 .bdaddr_set = null_hci_addr_set,
643 struct HCIInfo *qemu_next_hci(void)
645 if (cur_hci == nb_hcis)
646 return &null_hci;
648 return hci_table[cur_hci++];
651 static struct HCIInfo *hci_init(const char *str)
653 char *endp;
654 struct bt_scatternet_s *vlan = 0;
656 if (!strcmp(str, "null"))
657 /* null */
658 return &null_hci;
659 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
660 /* host[:hciN] */
661 return bt_host_hci(str[4] ? str + 5 : "hci0");
662 else if (!strncmp(str, "hci", 3)) {
663 /* hci[,vlan=n] */
664 if (str[3]) {
665 if (!strncmp(str + 3, ",vlan=", 6)) {
666 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
667 if (*endp)
668 vlan = 0;
670 } else
671 vlan = qemu_find_bt_vlan(0);
672 if (vlan)
673 return bt_new_hci(vlan);
676 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
678 return 0;
681 static int bt_hci_parse(const char *str)
683 struct HCIInfo *hci;
684 bdaddr_t bdaddr;
686 if (nb_hcis >= MAX_NICS) {
687 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
688 return -1;
691 hci = hci_init(str);
692 if (!hci)
693 return -1;
695 bdaddr.b[0] = 0x52;
696 bdaddr.b[1] = 0x54;
697 bdaddr.b[2] = 0x00;
698 bdaddr.b[3] = 0x12;
699 bdaddr.b[4] = 0x34;
700 bdaddr.b[5] = 0x56 + nb_hcis;
701 hci->bdaddr_set(hci, bdaddr.b);
703 hci_table[nb_hcis++] = hci;
705 return 0;
708 static void bt_vhci_add(int vlan_id)
710 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
712 if (!vlan->slave)
713 fprintf(stderr, "qemu: warning: adding a VHCI to "
714 "an empty scatternet %i\n", vlan_id);
716 bt_vhci_init(bt_new_hci(vlan));
719 static struct bt_device_s *bt_device_add(const char *opt)
721 struct bt_scatternet_s *vlan;
722 int vlan_id = 0;
723 char *endp = strstr(opt, ",vlan=");
724 int len = (endp ? endp - opt : strlen(opt)) + 1;
725 char devname[10];
727 pstrcpy(devname, MIN(sizeof(devname), len), opt);
729 if (endp) {
730 vlan_id = strtol(endp + 6, &endp, 0);
731 if (*endp) {
732 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
733 return 0;
737 vlan = qemu_find_bt_vlan(vlan_id);
739 if (!vlan->slave)
740 fprintf(stderr, "qemu: warning: adding a slave device to "
741 "an empty scatternet %i\n", vlan_id);
743 if (!strcmp(devname, "keyboard"))
744 return bt_keyboard_init(vlan);
746 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
747 return 0;
750 static int bt_parse(const char *opt)
752 const char *endp, *p;
753 int vlan;
755 if (strstart(opt, "hci", &endp)) {
756 if (!*endp || *endp == ',') {
757 if (*endp)
758 if (!strstart(endp, ",vlan=", 0))
759 opt = endp + 1;
761 return bt_hci_parse(opt);
763 } else if (strstart(opt, "vhci", &endp)) {
764 if (!*endp || *endp == ',') {
765 if (*endp) {
766 if (strstart(endp, ",vlan=", &p)) {
767 vlan = strtol(p, (char **) &endp, 0);
768 if (*endp) {
769 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
770 return 1;
772 } else {
773 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
774 return 1;
776 } else
777 vlan = 0;
779 bt_vhci_add(vlan);
780 return 0;
782 } else if (strstart(opt, "device:", &endp))
783 return !bt_device_add(endp);
785 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
786 return 1;
789 /***********************************************************/
790 /* QEMU Block devices */
792 #define HD_ALIAS "index=%d,media=disk"
793 #define CDROM_ALIAS "index=2,media=cdrom"
794 #define FD_ALIAS "index=%d,if=floppy"
795 #define PFLASH_ALIAS "if=pflash"
796 #define MTD_ALIAS "if=mtd"
797 #define SD_ALIAS "index=0,if=sd"
799 QemuOpts *drive_add(const char *file, const char *fmt, ...)
801 va_list ap;
802 char optstr[1024];
803 QemuOpts *opts;
805 va_start(ap, fmt);
806 vsnprintf(optstr, sizeof(optstr), fmt, ap);
807 va_end(ap);
809 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
810 if (!opts) {
811 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
812 __FUNCTION__, optstr);
813 return NULL;
815 if (file)
816 qemu_opt_set(opts, "file", file);
817 return opts;
820 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
822 DriveInfo *dinfo;
824 /* seek interface, bus and unit */
826 QTAILQ_FOREACH(dinfo, &drives, next) {
827 if (dinfo->type == type &&
828 dinfo->bus == bus &&
829 dinfo->unit == unit)
830 return dinfo;
833 return NULL;
836 DriveInfo *drive_get_by_id(const char *id)
838 DriveInfo *dinfo;
840 QTAILQ_FOREACH(dinfo, &drives, next) {
841 if (strcmp(id, dinfo->id))
842 continue;
843 return dinfo;
845 return NULL;
848 int drive_get_max_bus(BlockInterfaceType type)
850 int max_bus;
851 DriveInfo *dinfo;
853 max_bus = -1;
854 QTAILQ_FOREACH(dinfo, &drives, next) {
855 if(dinfo->type == type &&
856 dinfo->bus > max_bus)
857 max_bus = dinfo->bus;
859 return max_bus;
862 const char *drive_get_serial(BlockDriverState *bdrv)
864 DriveInfo *dinfo;
866 QTAILQ_FOREACH(dinfo, &drives, next) {
867 if (dinfo->bdrv == bdrv)
868 return dinfo->serial;
871 return "\0";
874 BlockInterfaceErrorAction drive_get_on_error(
875 BlockDriverState *bdrv, int is_read)
877 DriveInfo *dinfo;
879 QTAILQ_FOREACH(dinfo, &drives, next) {
880 if (dinfo->bdrv == bdrv)
881 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
884 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
887 static void bdrv_format_print(void *opaque, const char *name)
889 fprintf(stderr, " %s", name);
892 void drive_uninit(DriveInfo *dinfo)
894 qemu_opts_del(dinfo->opts);
895 bdrv_delete(dinfo->bdrv);
896 QTAILQ_REMOVE(&drives, dinfo, next);
897 qemu_free(dinfo);
900 static int parse_block_error_action(const char *buf, int is_read)
902 if (!strcmp(buf, "ignore")) {
903 return BLOCK_ERR_IGNORE;
904 } else if (!is_read && !strcmp(buf, "enospc")) {
905 return BLOCK_ERR_STOP_ENOSPC;
906 } else if (!strcmp(buf, "stop")) {
907 return BLOCK_ERR_STOP_ANY;
908 } else if (!strcmp(buf, "report")) {
909 return BLOCK_ERR_REPORT;
910 } else {
911 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
912 buf, is_read ? "read" : "write");
913 return -1;
917 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
918 int *fatal_error)
920 const char *buf;
921 const char *file = NULL;
922 char devname[128];
923 const char *serial;
924 const char *mediastr = "";
925 BlockInterfaceType type;
926 enum { MEDIA_DISK, MEDIA_CDROM } media;
927 int bus_id, unit_id;
928 int cyls, heads, secs, translation;
929 BlockDriver *drv = NULL;
930 QEMUMachine *machine = opaque;
931 int max_devs;
932 int index;
933 int cache;
934 int aio = 0;
935 int ro = 0;
936 int bdrv_flags;
937 int on_read_error, on_write_error;
938 const char *devaddr;
939 DriveInfo *dinfo;
940 int is_extboot = 0;
941 int snapshot = 0;
943 *fatal_error = 1;
945 translation = BIOS_ATA_TRANSLATION_AUTO;
946 cache = 1;
948 if (machine && machine->use_scsi) {
949 type = IF_SCSI;
950 max_devs = MAX_SCSI_DEVS;
951 pstrcpy(devname, sizeof(devname), "scsi");
952 } else {
953 type = IF_IDE;
954 max_devs = MAX_IDE_DEVS;
955 pstrcpy(devname, sizeof(devname), "ide");
957 media = MEDIA_DISK;
959 /* extract parameters */
960 bus_id = qemu_opt_get_number(opts, "bus", 0);
961 unit_id = qemu_opt_get_number(opts, "unit", -1);
962 index = qemu_opt_get_number(opts, "index", -1);
964 cyls = qemu_opt_get_number(opts, "cyls", 0);
965 heads = qemu_opt_get_number(opts, "heads", 0);
966 secs = qemu_opt_get_number(opts, "secs", 0);
968 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
969 ro = qemu_opt_get_bool(opts, "readonly", 0);
971 file = qemu_opt_get(opts, "file");
972 serial = qemu_opt_get(opts, "serial");
974 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
975 pstrcpy(devname, sizeof(devname), buf);
976 if (!strcmp(buf, "ide")) {
977 type = IF_IDE;
978 max_devs = MAX_IDE_DEVS;
979 } else if (!strcmp(buf, "scsi")) {
980 type = IF_SCSI;
981 max_devs = MAX_SCSI_DEVS;
982 } else if (!strcmp(buf, "floppy")) {
983 type = IF_FLOPPY;
984 max_devs = 0;
985 } else if (!strcmp(buf, "pflash")) {
986 type = IF_PFLASH;
987 max_devs = 0;
988 } else if (!strcmp(buf, "mtd")) {
989 type = IF_MTD;
990 max_devs = 0;
991 } else if (!strcmp(buf, "sd")) {
992 type = IF_SD;
993 max_devs = 0;
994 } else if (!strcmp(buf, "virtio")) {
995 type = IF_VIRTIO;
996 max_devs = 0;
997 } else if (!strcmp(buf, "xen")) {
998 type = IF_XEN;
999 max_devs = 0;
1000 } else if (!strcmp(buf, "none")) {
1001 type = IF_NONE;
1002 max_devs = 0;
1003 } else {
1004 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1005 return NULL;
1009 if (cyls || heads || secs) {
1010 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
1011 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1012 return NULL;
1014 if (heads < 1 || (type == IF_IDE && heads > 16)) {
1015 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1016 return NULL;
1018 if (secs < 1 || (type == IF_IDE && secs > 63)) {
1019 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1020 return NULL;
1024 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1025 if (!cyls) {
1026 fprintf(stderr,
1027 "qemu: '%s' trans must be used with cyls,heads and secs\n",
1028 buf);
1029 return NULL;
1031 if (!strcmp(buf, "none"))
1032 translation = BIOS_ATA_TRANSLATION_NONE;
1033 else if (!strcmp(buf, "lba"))
1034 translation = BIOS_ATA_TRANSLATION_LBA;
1035 else if (!strcmp(buf, "auto"))
1036 translation = BIOS_ATA_TRANSLATION_AUTO;
1037 else {
1038 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
1039 return NULL;
1043 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
1044 if (!strcmp(buf, "disk")) {
1045 media = MEDIA_DISK;
1046 } else if (!strcmp(buf, "cdrom")) {
1047 if (cyls || secs || heads) {
1048 fprintf(stderr,
1049 "qemu: '%s' invalid physical CHS format\n", buf);
1050 return NULL;
1052 media = MEDIA_CDROM;
1053 } else {
1054 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
1055 return NULL;
1059 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
1060 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
1061 cache = 0;
1062 else if (!strcmp(buf, "writethrough"))
1063 cache = 1;
1064 else if (!strcmp(buf, "writeback"))
1065 cache = 2;
1066 else {
1067 fprintf(stderr, "qemu: invalid cache option\n");
1068 return NULL;
1072 #ifdef CONFIG_LINUX_AIO
1073 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1074 if (!strcmp(buf, "threads"))
1075 aio = 0;
1076 else if (!strcmp(buf, "native"))
1077 aio = 1;
1078 else {
1079 fprintf(stderr, "qemu: invalid aio option\n");
1080 return NULL;
1083 #endif
1085 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1086 if (strcmp(buf, "?") == 0) {
1087 fprintf(stderr, "qemu: Supported formats:");
1088 bdrv_iterate_format(bdrv_format_print, NULL);
1089 fprintf(stderr, "\n");
1090 return NULL;
1092 drv = bdrv_find_whitelisted_format(buf);
1093 if (!drv) {
1094 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1095 return NULL;
1099 is_extboot = qemu_opt_get_bool(opts, "boot", 0);
1100 if (is_extboot && extboot_drive) {
1101 fprintf(stderr, "qemu: two bootable drives specified\n");
1102 return NULL;
1105 on_write_error = BLOCK_ERR_STOP_ENOSPC;
1106 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1107 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1108 fprintf(stderr, "werror is no supported by this format\n");
1109 return NULL;
1112 on_write_error = parse_block_error_action(buf, 0);
1113 if (on_write_error < 0) {
1114 return NULL;
1118 on_read_error = BLOCK_ERR_REPORT;
1119 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1120 if (type != IF_IDE && type != IF_VIRTIO) {
1121 fprintf(stderr, "rerror is no supported by this format\n");
1122 return NULL;
1125 on_read_error = parse_block_error_action(buf, 1);
1126 if (on_read_error < 0) {
1127 return NULL;
1131 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1132 if (type != IF_VIRTIO) {
1133 fprintf(stderr, "addr is not supported\n");
1134 return NULL;
1138 /* compute bus and unit according index */
1140 if (index != -1) {
1141 if (bus_id != 0 || unit_id != -1) {
1142 fprintf(stderr,
1143 "qemu: index cannot be used with bus and unit\n");
1144 return NULL;
1146 if (max_devs == 0)
1148 unit_id = index;
1149 bus_id = 0;
1150 } else {
1151 unit_id = index % max_devs;
1152 bus_id = index / max_devs;
1156 /* if user doesn't specify a unit_id,
1157 * try to find the first free
1160 if (unit_id == -1) {
1161 unit_id = 0;
1162 while (drive_get(type, bus_id, unit_id) != NULL) {
1163 unit_id++;
1164 if (max_devs && unit_id >= max_devs) {
1165 unit_id -= max_devs;
1166 bus_id++;
1171 /* check unit id */
1173 if (max_devs && unit_id >= max_devs) {
1174 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1175 unit_id, max_devs - 1);
1176 return NULL;
1180 * ignore multiple definitions
1183 if (drive_get(type, bus_id, unit_id) != NULL) {
1184 *fatal_error = 0;
1185 return NULL;
1188 /* init */
1190 dinfo = qemu_mallocz(sizeof(*dinfo));
1191 if ((buf = qemu_opts_id(opts)) != NULL) {
1192 dinfo->id = qemu_strdup(buf);
1193 } else {
1194 /* no id supplied -> create one */
1195 dinfo->id = qemu_mallocz(32);
1196 if (type == IF_IDE || type == IF_SCSI)
1197 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1198 if (max_devs)
1199 snprintf(dinfo->id, 32, "%s%i%s%i",
1200 devname, bus_id, mediastr, unit_id);
1201 else
1202 snprintf(dinfo->id, 32, "%s%s%i",
1203 devname, mediastr, unit_id);
1205 dinfo->bdrv = bdrv_new(dinfo->id);
1206 dinfo->devaddr = devaddr;
1207 dinfo->type = type;
1208 dinfo->bus = bus_id;
1209 dinfo->unit = unit_id;
1210 dinfo->on_read_error = on_read_error;
1211 dinfo->on_write_error = on_write_error;
1212 dinfo->opts = opts;
1213 if (serial)
1214 strncpy(dinfo->serial, serial, sizeof(serial));
1215 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1216 if (is_extboot) {
1217 extboot_drive = dinfo;
1220 switch(type) {
1221 case IF_IDE:
1222 case IF_SCSI:
1223 case IF_XEN:
1224 case IF_NONE:
1225 switch(media) {
1226 case MEDIA_DISK:
1227 if (cyls != 0) {
1228 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1229 bdrv_set_translation_hint(dinfo->bdrv, translation);
1231 break;
1232 case MEDIA_CDROM:
1233 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1234 break;
1236 break;
1237 case IF_SD:
1238 /* FIXME: This isn't really a floppy, but it's a reasonable
1239 approximation. */
1240 case IF_FLOPPY:
1241 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1242 break;
1243 case IF_PFLASH:
1244 case IF_MTD:
1245 break;
1246 case IF_VIRTIO:
1247 /* add virtio block device */
1248 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1249 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1250 qemu_opt_set(opts, "drive", dinfo->id);
1251 if (devaddr)
1252 qemu_opt_set(opts, "addr", devaddr);
1253 break;
1254 case IF_COUNT:
1255 abort();
1257 if (!file) {
1258 *fatal_error = 0;
1259 return NULL;
1261 bdrv_flags = 0;
1262 if (snapshot) {
1263 bdrv_flags |= BDRV_O_SNAPSHOT;
1264 cache = 2; /* always use write-back with snapshot */
1266 if (cache == 0) /* no caching */
1267 bdrv_flags |= BDRV_O_NOCACHE;
1268 else if (cache == 2) /* write-back */
1269 bdrv_flags |= BDRV_O_CACHE_WB;
1271 if (aio == 1) {
1272 bdrv_flags |= BDRV_O_NATIVE_AIO;
1273 } else {
1274 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1277 if (ro == 1) {
1278 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1279 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1280 return NULL;
1284 * cdrom is read-only. Set it now, after above interface checking
1285 * since readonly attribute not explicitly required, so no error.
1287 if (media == MEDIA_CDROM) {
1288 ro = 1;
1290 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1292 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1293 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1294 file, strerror(errno));
1295 return NULL;
1298 if (bdrv_key_required(dinfo->bdrv))
1299 autostart = 0;
1300 *fatal_error = 0;
1301 return dinfo;
1304 static int drive_init_func(QemuOpts *opts, void *opaque)
1306 QEMUMachine *machine = opaque;
1307 int fatal_error = 0;
1309 if (drive_init(opts, machine, &fatal_error) == NULL) {
1310 if (fatal_error)
1311 return 1;
1313 return 0;
1316 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1318 if (NULL == qemu_opt_get(opts, "snapshot")) {
1319 qemu_opt_set(opts, "snapshot", "on");
1321 return 0;
1324 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1326 boot_set_handler = func;
1327 boot_set_opaque = opaque;
1330 int qemu_boot_set(const char *boot_devices)
1332 if (!boot_set_handler) {
1333 return -EINVAL;
1335 return boot_set_handler(boot_set_opaque, boot_devices);
1338 static int parse_bootdevices(char *devices)
1340 /* We just do some generic consistency checks */
1341 const char *p;
1342 int bitmap = 0;
1344 for (p = devices; *p != '\0'; p++) {
1345 /* Allowed boot devices are:
1346 * a-b: floppy disk drives
1347 * c-f: IDE disk drives
1348 * g-m: machine implementation dependant drives
1349 * n-p: network devices
1350 * It's up to each machine implementation to check if the given boot
1351 * devices match the actual hardware implementation and firmware
1352 * features.
1354 if (*p < 'a' || *p > 'p') {
1355 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1356 exit(1);
1358 if (bitmap & (1 << (*p - 'a'))) {
1359 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1360 exit(1);
1362 bitmap |= 1 << (*p - 'a');
1364 return bitmap;
1367 static void restore_boot_devices(void *opaque)
1369 char *standard_boot_devices = opaque;
1371 qemu_boot_set(standard_boot_devices);
1373 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1374 qemu_free(standard_boot_devices);
1377 static void numa_add(const char *optarg)
1379 char option[128];
1380 char *endptr;
1381 unsigned long long value, endvalue;
1382 int nodenr;
1384 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1385 if (!strcmp(option, "node")) {
1386 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1387 nodenr = nb_numa_nodes;
1388 } else {
1389 nodenr = strtoull(option, NULL, 10);
1392 if (get_param_value(option, 128, "mem", optarg) == 0) {
1393 node_mem[nodenr] = 0;
1394 } else {
1395 value = strtoull(option, &endptr, 0);
1396 switch (*endptr) {
1397 case 0: case 'M': case 'm':
1398 value <<= 20;
1399 break;
1400 case 'G': case 'g':
1401 value <<= 30;
1402 break;
1404 node_mem[nodenr] = value;
1406 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1407 node_cpumask[nodenr] = 0;
1408 } else {
1409 value = strtoull(option, &endptr, 10);
1410 if (value >= 64) {
1411 value = 63;
1412 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1413 } else {
1414 if (*endptr == '-') {
1415 endvalue = strtoull(endptr+1, &endptr, 10);
1416 if (endvalue >= 63) {
1417 endvalue = 62;
1418 fprintf(stderr,
1419 "only 63 CPUs in NUMA mode supported.\n");
1421 value = (2ULL << endvalue) - (1ULL << value);
1422 } else {
1423 value = 1ULL << value;
1426 node_cpumask[nodenr] = value;
1428 nb_numa_nodes++;
1430 return;
1433 static void smp_parse(const char *optarg)
1435 int smp, sockets = 0, threads = 0, cores = 0;
1436 char *endptr;
1437 char option[128];
1439 smp = strtoul(optarg, &endptr, 10);
1440 if (endptr != optarg) {
1441 if (*endptr == ',') {
1442 endptr++;
1445 if (get_param_value(option, 128, "sockets", endptr) != 0)
1446 sockets = strtoull(option, NULL, 10);
1447 if (get_param_value(option, 128, "cores", endptr) != 0)
1448 cores = strtoull(option, NULL, 10);
1449 if (get_param_value(option, 128, "threads", endptr) != 0)
1450 threads = strtoull(option, NULL, 10);
1451 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1452 max_cpus = strtoull(option, NULL, 10);
1454 /* compute missing values, prefer sockets over cores over threads */
1455 if (smp == 0 || sockets == 0) {
1456 sockets = sockets > 0 ? sockets : 1;
1457 cores = cores > 0 ? cores : 1;
1458 threads = threads > 0 ? threads : 1;
1459 if (smp == 0) {
1460 smp = cores * threads * sockets;
1462 } else {
1463 if (cores == 0) {
1464 threads = threads > 0 ? threads : 1;
1465 cores = smp / (sockets * threads);
1466 } else {
1467 if (sockets) {
1468 threads = smp / (cores * sockets);
1472 smp_cpus = smp;
1473 smp_cores = cores > 0 ? cores : 1;
1474 smp_threads = threads > 0 ? threads : 1;
1475 if (max_cpus == 0)
1476 max_cpus = smp_cpus;
1479 /***********************************************************/
1480 /* USB devices */
1482 static int usb_device_add(const char *devname, int is_hotplug)
1484 const char *p;
1485 USBDevice *dev = NULL;
1487 if (!usb_enabled)
1488 return -1;
1490 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1491 dev = usbdevice_create(devname);
1492 if (dev)
1493 goto done;
1495 /* the other ones */
1496 if (strstart(devname, "host:", &p)) {
1497 dev = usb_host_device_open(p);
1498 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1499 dev = usb_bt_init(devname[2] ? hci_init(p) :
1500 bt_new_hci(qemu_find_bt_vlan(0)));
1501 } else {
1502 return -1;
1504 if (!dev)
1505 return -1;
1507 done:
1508 return 0;
1511 static int usb_device_del(const char *devname)
1513 int bus_num, addr;
1514 const char *p;
1516 if (strstart(devname, "host:", &p))
1517 return usb_host_device_close(p);
1519 if (!usb_enabled)
1520 return -1;
1522 p = strchr(devname, '.');
1523 if (!p)
1524 return -1;
1525 bus_num = strtoul(devname, NULL, 0);
1526 addr = strtoul(p + 1, NULL, 0);
1528 return usb_device_delete_addr(bus_num, addr);
1531 static int usb_parse(const char *cmdline)
1533 int r;
1534 r = usb_device_add(cmdline, 0);
1535 if (r < 0) {
1536 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1538 return r;
1541 void do_usb_add(Monitor *mon, const QDict *qdict)
1543 const char *devname = qdict_get_str(qdict, "devname");
1544 if (usb_device_add(devname, 1) < 0) {
1545 error_report("could not add USB device '%s'", devname);
1549 void do_usb_del(Monitor *mon, const QDict *qdict)
1551 const char *devname = qdict_get_str(qdict, "devname");
1552 if (usb_device_del(devname) < 0) {
1553 error_report("could not delete USB device '%s'", devname);
1557 /***********************************************************/
1558 /* PCMCIA/Cardbus */
1560 static struct pcmcia_socket_entry_s {
1561 PCMCIASocket *socket;
1562 struct pcmcia_socket_entry_s *next;
1563 } *pcmcia_sockets = 0;
1565 void pcmcia_socket_register(PCMCIASocket *socket)
1567 struct pcmcia_socket_entry_s *entry;
1569 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1570 entry->socket = socket;
1571 entry->next = pcmcia_sockets;
1572 pcmcia_sockets = entry;
1575 void pcmcia_socket_unregister(PCMCIASocket *socket)
1577 struct pcmcia_socket_entry_s *entry, **ptr;
1579 ptr = &pcmcia_sockets;
1580 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1581 if (entry->socket == socket) {
1582 *ptr = entry->next;
1583 qemu_free(entry);
1587 void pcmcia_info(Monitor *mon)
1589 struct pcmcia_socket_entry_s *iter;
1591 if (!pcmcia_sockets)
1592 monitor_printf(mon, "No PCMCIA sockets\n");
1594 for (iter = pcmcia_sockets; iter; iter = iter->next)
1595 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1596 iter->socket->attached ? iter->socket->card_string :
1597 "Empty");
1600 /***********************************************************/
1601 /* I/O handling */
1603 typedef struct IOHandlerRecord {
1604 int fd;
1605 IOCanReadHandler *fd_read_poll;
1606 IOHandler *fd_read;
1607 IOHandler *fd_write;
1608 int deleted;
1609 void *opaque;
1610 /* temporary data */
1611 struct pollfd *ufd;
1612 QLIST_ENTRY(IOHandlerRecord) next;
1613 } IOHandlerRecord;
1615 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1616 QLIST_HEAD_INITIALIZER(io_handlers);
1619 /* XXX: fd_read_poll should be suppressed, but an API change is
1620 necessary in the character devices to suppress fd_can_read(). */
1621 int qemu_set_fd_handler2(int fd,
1622 IOCanReadHandler *fd_read_poll,
1623 IOHandler *fd_read,
1624 IOHandler *fd_write,
1625 void *opaque)
1627 IOHandlerRecord *ioh;
1629 if (!fd_read && !fd_write) {
1630 QLIST_FOREACH(ioh, &io_handlers, next) {
1631 if (ioh->fd == fd) {
1632 ioh->deleted = 1;
1633 break;
1636 } else {
1637 QLIST_FOREACH(ioh, &io_handlers, next) {
1638 if (ioh->fd == fd)
1639 goto found;
1641 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1642 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1643 found:
1644 ioh->fd = fd;
1645 ioh->fd_read_poll = fd_read_poll;
1646 ioh->fd_read = fd_read;
1647 ioh->fd_write = fd_write;
1648 ioh->opaque = opaque;
1649 ioh->deleted = 0;
1651 qemu_notify_event();
1652 return 0;
1655 int qemu_set_fd_handler(int fd,
1656 IOHandler *fd_read,
1657 IOHandler *fd_write,
1658 void *opaque)
1660 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1663 #ifdef _WIN32
1664 /***********************************************************/
1665 /* Polling handling */
1667 typedef struct PollingEntry {
1668 PollingFunc *func;
1669 void *opaque;
1670 struct PollingEntry *next;
1671 } PollingEntry;
1673 static PollingEntry *first_polling_entry;
1675 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1677 PollingEntry **ppe, *pe;
1678 pe = qemu_mallocz(sizeof(PollingEntry));
1679 pe->func = func;
1680 pe->opaque = opaque;
1681 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1682 *ppe = pe;
1683 return 0;
1686 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1688 PollingEntry **ppe, *pe;
1689 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1690 pe = *ppe;
1691 if (pe->func == func && pe->opaque == opaque) {
1692 *ppe = pe->next;
1693 qemu_free(pe);
1694 break;
1699 /***********************************************************/
1700 /* Wait objects support */
1701 typedef struct WaitObjects {
1702 int num;
1703 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1704 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1705 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1706 } WaitObjects;
1708 static WaitObjects wait_objects = {0};
1710 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1712 WaitObjects *w = &wait_objects;
1714 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1715 return -1;
1716 w->events[w->num] = handle;
1717 w->func[w->num] = func;
1718 w->opaque[w->num] = opaque;
1719 w->num++;
1720 return 0;
1723 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1725 int i, found;
1726 WaitObjects *w = &wait_objects;
1728 found = 0;
1729 for (i = 0; i < w->num; i++) {
1730 if (w->events[i] == handle)
1731 found = 1;
1732 if (found) {
1733 w->events[i] = w->events[i + 1];
1734 w->func[i] = w->func[i + 1];
1735 w->opaque[i] = w->opaque[i + 1];
1738 if (found)
1739 w->num--;
1741 #endif
1743 /***********************************************************/
1744 /* ram save/restore */
1746 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
1747 #define RAM_SAVE_FLAG_COMPRESS 0x02
1748 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
1749 #define RAM_SAVE_FLAG_PAGE 0x08
1750 #define RAM_SAVE_FLAG_EOS 0x10
1752 static int is_dup_page(uint8_t *page, uint8_t ch)
1754 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1755 uint32_t *array = (uint32_t *)page;
1756 int i;
1758 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1759 if (array[i] != val)
1760 return 0;
1763 return 1;
1766 static int ram_save_block(QEMUFile *f)
1768 static ram_addr_t current_addr = 0;
1769 ram_addr_t saved_addr = current_addr;
1770 ram_addr_t addr = 0;
1771 int found = 0;
1773 while (addr < last_ram_offset) {
1774 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1775 uint8_t *p;
1777 cpu_physical_memory_reset_dirty(current_addr,
1778 current_addr + TARGET_PAGE_SIZE,
1779 MIGRATION_DIRTY_FLAG);
1781 p = qemu_get_ram_ptr(current_addr);
1783 if (is_dup_page(p, *p)) {
1784 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1785 qemu_put_byte(f, *p);
1786 } else {
1787 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1788 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1791 found = 1;
1792 break;
1794 addr += TARGET_PAGE_SIZE;
1795 current_addr = (saved_addr + addr) % last_ram_offset;
1798 return found;
1801 static uint64_t bytes_transferred;
1803 static ram_addr_t ram_save_remaining(void)
1805 ram_addr_t addr;
1806 ram_addr_t count = 0;
1808 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1809 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1810 count++;
1813 return count;
1816 uint64_t ram_bytes_remaining(void)
1818 return ram_save_remaining() * TARGET_PAGE_SIZE;
1821 uint64_t ram_bytes_transferred(void)
1823 return bytes_transferred;
1826 uint64_t ram_bytes_total(void)
1828 return last_ram_offset;
1831 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1833 ram_addr_t addr;
1834 uint64_t bytes_transferred_last;
1835 double bwidth = 0;
1836 uint64_t expected_time = 0;
1838 if (stage < 0) {
1839 cpu_physical_memory_set_dirty_tracking(0);
1840 return 0;
1843 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1844 qemu_file_set_error(f);
1845 return 0;
1848 if (stage == 1) {
1849 bytes_transferred = 0;
1851 /* Make sure all dirty bits are set */
1852 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1853 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1854 cpu_physical_memory_set_dirty(addr);
1857 /* Enable dirty memory tracking */
1858 cpu_physical_memory_set_dirty_tracking(1);
1860 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1863 bytes_transferred_last = bytes_transferred;
1864 bwidth = qemu_get_clock_ns(rt_clock);
1866 while (!qemu_file_rate_limit(f)) {
1867 int ret;
1869 ret = ram_save_block(f);
1870 bytes_transferred += ret * TARGET_PAGE_SIZE;
1871 if (ret == 0) /* no more blocks */
1872 break;
1875 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1876 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1878 /* if we haven't transferred anything this round, force expected_time to a
1879 * a very high value, but without crashing */
1880 if (bwidth == 0)
1881 bwidth = 0.000001;
1883 /* try transferring iterative blocks of memory */
1884 if (stage == 3) {
1885 /* flush all remaining blocks regardless of rate limiting */
1886 while (ram_save_block(f) != 0) {
1887 bytes_transferred += TARGET_PAGE_SIZE;
1889 cpu_physical_memory_set_dirty_tracking(0);
1892 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1894 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1896 return (stage == 2) && (expected_time <= migrate_max_downtime());
1899 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1901 ram_addr_t addr;
1902 int flags;
1904 if (version_id != 3)
1905 return -EINVAL;
1907 do {
1908 addr = qemu_get_be64(f);
1910 flags = addr & ~TARGET_PAGE_MASK;
1911 addr &= TARGET_PAGE_MASK;
1913 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1914 if (addr != last_ram_offset)
1915 return -EINVAL;
1918 if (flags & RAM_SAVE_FLAG_COMPRESS) {
1919 uint8_t ch = qemu_get_byte(f);
1920 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1921 #ifndef _WIN32
1922 if (ch == 0 &&
1923 (!kvm_enabled() || kvm_has_sync_mmu())) {
1924 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1926 #endif
1927 } else if (flags & RAM_SAVE_FLAG_PAGE) {
1928 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1930 if (qemu_file_has_error(f)) {
1931 return -EIO;
1933 } while (!(flags & RAM_SAVE_FLAG_EOS));
1935 return 0;
1938 void qemu_service_io(void)
1940 qemu_notify_event();
1943 /***********************************************************/
1944 /* machine registration */
1946 static QEMUMachine *first_machine = NULL;
1947 QEMUMachine *current_machine = NULL;
1949 int qemu_register_machine(QEMUMachine *m)
1951 QEMUMachine **pm;
1952 pm = &first_machine;
1953 while (*pm != NULL)
1954 pm = &(*pm)->next;
1955 m->next = NULL;
1956 *pm = m;
1957 return 0;
1960 static QEMUMachine *find_machine(const char *name)
1962 QEMUMachine *m;
1964 for(m = first_machine; m != NULL; m = m->next) {
1965 if (!strcmp(m->name, name))
1966 return m;
1967 if (m->alias && !strcmp(m->alias, name))
1968 return m;
1970 return NULL;
1973 static QEMUMachine *find_default_machine(void)
1975 QEMUMachine *m;
1977 for(m = first_machine; m != NULL; m = m->next) {
1978 if (m->is_default) {
1979 return m;
1982 return NULL;
1985 /***********************************************************/
1986 /* main execution loop */
1988 static void gui_update(void *opaque)
1990 uint64_t interval = GUI_REFRESH_INTERVAL;
1991 DisplayState *ds = opaque;
1992 DisplayChangeListener *dcl = ds->listeners;
1994 qemu_flush_coalesced_mmio_buffer();
1995 dpy_refresh(ds);
1997 while (dcl != NULL) {
1998 if (dcl->gui_timer_interval &&
1999 dcl->gui_timer_interval < interval)
2000 interval = dcl->gui_timer_interval;
2001 dcl = dcl->next;
2003 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
2006 static void nographic_update(void *opaque)
2008 uint64_t interval = GUI_REFRESH_INTERVAL;
2010 qemu_flush_coalesced_mmio_buffer();
2011 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
2014 void cpu_synchronize_all_states(void)
2016 CPUState *cpu;
2018 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2019 cpu_synchronize_state(cpu);
2023 void cpu_synchronize_all_post_reset(void)
2025 CPUState *cpu;
2027 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2028 cpu_synchronize_post_reset(cpu);
2032 void cpu_synchronize_all_post_init(void)
2034 CPUState *cpu;
2036 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2037 cpu_synchronize_post_init(cpu);
2041 struct vm_change_state_entry {
2042 VMChangeStateHandler *cb;
2043 void *opaque;
2044 QLIST_ENTRY (vm_change_state_entry) entries;
2047 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
2049 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
2050 void *opaque)
2052 VMChangeStateEntry *e;
2054 e = qemu_mallocz(sizeof (*e));
2056 e->cb = cb;
2057 e->opaque = opaque;
2058 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
2059 return e;
2062 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
2064 QLIST_REMOVE (e, entries);
2065 qemu_free (e);
2068 static void vm_state_notify(int running, int reason)
2070 VMChangeStateEntry *e;
2072 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
2073 e->cb(e->opaque, running, reason);
2077 static void resume_all_vcpus(void);
2078 static void pause_all_vcpus(void);
2080 void vm_start(void)
2082 if (!vm_running) {
2083 cpu_enable_ticks();
2084 vm_running = 1;
2085 vm_state_notify(1, 0);
2086 resume_all_vcpus();
2090 /* reset/shutdown handler */
2092 typedef struct QEMUResetEntry {
2093 QTAILQ_ENTRY(QEMUResetEntry) entry;
2094 QEMUResetHandler *func;
2095 void *opaque;
2096 } QEMUResetEntry;
2098 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
2099 QTAILQ_HEAD_INITIALIZER(reset_handlers);
2100 static int reset_requested;
2101 static int shutdown_requested;
2102 static int powerdown_requested;
2103 static int debug_requested;
2104 static int vmstop_requested;
2106 int qemu_no_shutdown(void)
2108 int r = no_shutdown;
2109 no_shutdown = 0;
2110 return r;
2113 int qemu_shutdown_requested(void)
2115 int r = shutdown_requested;
2116 shutdown_requested = 0;
2117 return r;
2120 int qemu_reset_requested(void)
2122 int r = reset_requested;
2123 reset_requested = 0;
2124 return r;
2127 int qemu_powerdown_requested(void)
2129 int r = powerdown_requested;
2130 powerdown_requested = 0;
2131 return r;
2134 static int qemu_debug_requested(void)
2136 int r = debug_requested;
2137 debug_requested = 0;
2138 return r;
2141 static int qemu_vmstop_requested(void)
2143 int r = vmstop_requested;
2144 vmstop_requested = 0;
2145 return r;
2148 static void do_vm_stop(int reason)
2150 if (vm_running) {
2151 cpu_disable_ticks();
2152 vm_running = 0;
2153 pause_all_vcpus();
2154 vm_state_notify(0, reason);
2155 monitor_protocol_event(QEVENT_STOP, NULL);
2159 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2161 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2163 re->func = func;
2164 re->opaque = opaque;
2165 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2168 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2170 QEMUResetEntry *re;
2172 QTAILQ_FOREACH(re, &reset_handlers, entry) {
2173 if (re->func == func && re->opaque == opaque) {
2174 QTAILQ_REMOVE(&reset_handlers, re, entry);
2175 qemu_free(re);
2176 return;
2181 void qemu_system_reset(void)
2183 QEMUResetEntry *re, *nre;
2185 /* reset all devices */
2186 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2187 re->func(re->opaque);
2189 monitor_protocol_event(QEVENT_RESET, NULL);
2190 cpu_synchronize_all_post_reset();
2193 void qemu_system_reset_request(void)
2195 if (no_reboot) {
2196 shutdown_requested = 1;
2197 } else {
2198 reset_requested = 1;
2200 if (cpu_single_env) {
2201 cpu_single_env->stopped = 1;
2203 qemu_notify_event();
2206 void qemu_system_shutdown_request(void)
2208 shutdown_requested = 1;
2209 qemu_notify_event();
2212 void qemu_system_powerdown_request(void)
2214 powerdown_requested = 1;
2215 qemu_notify_event();
2218 static int cpu_can_run(CPUState *env)
2220 if (env->stop)
2221 return 0;
2222 if (env->stopped)
2223 return 0;
2224 if (!vm_running)
2225 return 0;
2226 return 1;
2229 static int cpu_has_work(CPUState *env)
2231 if (env->stop)
2232 return 1;
2233 if (env->stopped)
2234 return 0;
2235 if (!env->halted)
2236 return 1;
2237 if (qemu_cpu_has_work(env))
2238 return 1;
2239 return 0;
2242 static int tcg_has_work(void)
2244 CPUState *env;
2246 for (env = first_cpu; env != NULL; env = env->next_cpu)
2247 if (cpu_has_work(env))
2248 return 1;
2249 return 0;
2252 #ifndef _WIN32
2253 static int io_thread_fd = -1;
2255 static void qemu_event_increment(void)
2257 /* Write 8 bytes to be compatible with eventfd. */
2258 static uint64_t val = 1;
2259 ssize_t ret;
2261 if (io_thread_fd == -1)
2262 return;
2264 do {
2265 ret = write(io_thread_fd, &val, sizeof(val));
2266 } while (ret < 0 && errno == EINTR);
2268 /* EAGAIN is fine, a read must be pending. */
2269 if (ret < 0 && errno != EAGAIN) {
2270 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
2271 strerror(errno));
2272 exit (1);
2276 static void qemu_event_read(void *opaque)
2278 int fd = (unsigned long)opaque;
2279 ssize_t len;
2280 char buffer[512];
2282 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
2283 do {
2284 len = read(fd, buffer, sizeof(buffer));
2285 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
2288 static int qemu_event_init(void)
2290 int err;
2291 int fds[2];
2293 err = qemu_eventfd(fds);
2294 if (err == -1)
2295 return -errno;
2297 err = fcntl_setfl(fds[0], O_NONBLOCK);
2298 if (err < 0)
2299 goto fail;
2301 err = fcntl_setfl(fds[1], O_NONBLOCK);
2302 if (err < 0)
2303 goto fail;
2305 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
2306 (void *)(unsigned long)fds[0]);
2308 io_thread_fd = fds[1];
2309 return 0;
2311 fail:
2312 close(fds[0]);
2313 close(fds[1]);
2314 return err;
2316 #else
2317 HANDLE qemu_event_handle;
2319 static void dummy_event_handler(void *opaque)
2323 static int qemu_event_init(void)
2325 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
2326 if (!qemu_event_handle) {
2327 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
2328 return -1;
2330 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
2331 return 0;
2334 static void qemu_event_increment(void)
2336 if (!SetEvent(qemu_event_handle)) {
2337 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
2338 GetLastError());
2339 exit (1);
2342 #endif
2344 #ifndef CONFIG_IOTHREAD
2345 static int qemu_init_main_loop(void)
2347 return qemu_event_init();
2350 void qemu_init_vcpu(void *_env)
2352 CPUState *env = _env;
2354 env->nr_cores = smp_cores;
2355 env->nr_threads = smp_threads;
2356 if (kvm_enabled())
2357 kvm_init_vcpu(env);
2358 return;
2361 int qemu_cpu_self(void *env)
2363 return 1;
2366 static void resume_all_vcpus(void)
2370 static void pause_all_vcpus(void)
2374 void qemu_cpu_kick(void *env)
2376 return;
2379 void qemu_notify_event(void)
2381 CPUState *env = cpu_single_env;
2383 if (kvm_enabled()) {
2384 qemu_kvm_notify_work();
2385 return;
2388 qemu_event_increment ();
2389 if (env) {
2390 cpu_exit(env);
2392 if (next_cpu && env != next_cpu) {
2393 cpu_exit(next_cpu);
2397 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
2398 void qemu_mutex_lock_iothread(void) {}
2399 void qemu_mutex_unlock_iothread(void) {}
2400 #endif
2402 void vm_stop(int reason)
2404 do_vm_stop(reason);
2407 #else /* CONFIG_IOTHREAD */
2409 #include "qemu-thread.h"
2411 QemuMutex qemu_global_mutex;
2412 static QemuMutex qemu_fair_mutex;
2414 static QemuThread io_thread;
2416 static QemuThread *tcg_cpu_thread;
2417 static QemuCond *tcg_halt_cond;
2419 static int qemu_system_ready;
2420 /* cpu creation */
2421 static QemuCond qemu_cpu_cond;
2422 /* system init */
2423 static QemuCond qemu_system_cond;
2424 static QemuCond qemu_pause_cond;
2426 static void tcg_block_io_signals(void);
2427 static void kvm_block_io_signals(CPUState *env);
2428 static void unblock_io_signals(void);
2430 static int qemu_init_main_loop(void)
2432 int ret;
2434 ret = qemu_event_init();
2435 if (ret)
2436 return ret;
2438 qemu_cond_init(&qemu_pause_cond);
2439 qemu_mutex_init(&qemu_fair_mutex);
2440 qemu_mutex_init(&qemu_global_mutex);
2441 qemu_mutex_lock(&qemu_global_mutex);
2443 unblock_io_signals();
2444 qemu_thread_self(&io_thread);
2446 return 0;
2449 static void qemu_wait_io_event_common(CPUState *env)
2451 if (env->stop) {
2452 env->stop = 0;
2453 env->stopped = 1;
2454 qemu_cond_signal(&qemu_pause_cond);
2458 static void qemu_wait_io_event(CPUState *env)
2460 while (!tcg_has_work())
2461 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2463 qemu_mutex_unlock(&qemu_global_mutex);
2466 * Users of qemu_global_mutex can be starved, having no chance
2467 * to acquire it since this path will get to it first.
2468 * So use another lock to provide fairness.
2470 qemu_mutex_lock(&qemu_fair_mutex);
2471 qemu_mutex_unlock(&qemu_fair_mutex);
2473 qemu_mutex_lock(&qemu_global_mutex);
2474 qemu_wait_io_event_common(env);
2477 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
2479 struct timespec ts;
2480 int r, e;
2481 siginfo_t siginfo;
2482 sigset_t waitset;
2484 ts.tv_sec = timeout / 1000;
2485 ts.tv_nsec = (timeout % 1000) * 1000000;
2487 sigemptyset(&waitset);
2488 sigaddset(&waitset, SIG_IPI);
2490 qemu_mutex_unlock(&qemu_global_mutex);
2491 r = sigtimedwait(&waitset, &siginfo, &ts);
2492 e = errno;
2493 qemu_mutex_lock(&qemu_global_mutex);
2495 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
2496 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
2497 exit(1);
2501 static void qemu_kvm_wait_io_event(CPUState *env)
2503 while (!cpu_has_work(env))
2504 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2506 qemu_kvm_eat_signal(env, 0);
2507 qemu_wait_io_event_common(env);
2510 static int qemu_cpu_exec(CPUState *env);
2512 static void *kvm_cpu_thread_fn(void *arg)
2514 CPUState *env = arg;
2516 qemu_thread_self(env->thread);
2517 if (kvm_enabled())
2518 kvm_init_vcpu(env);
2520 kvm_block_io_signals(env);
2522 /* signal CPU creation */
2523 qemu_mutex_lock(&qemu_global_mutex);
2524 env->created = 1;
2525 qemu_cond_signal(&qemu_cpu_cond);
2527 /* and wait for machine initialization */
2528 while (!qemu_system_ready)
2529 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2531 while (1) {
2532 if (cpu_can_run(env))
2533 qemu_cpu_exec(env);
2534 qemu_kvm_wait_io_event(env);
2537 return NULL;
2540 static bool tcg_cpu_exec(void);
2542 static void *tcg_cpu_thread_fn(void *arg)
2544 CPUState *env = arg;
2546 tcg_block_io_signals();
2547 qemu_thread_self(env->thread);
2549 /* signal CPU creation */
2550 qemu_mutex_lock(&qemu_global_mutex);
2551 for (env = first_cpu; env != NULL; env = env->next_cpu)
2552 env->created = 1;
2553 qemu_cond_signal(&qemu_cpu_cond);
2555 /* and wait for machine initialization */
2556 while (!qemu_system_ready)
2557 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2559 while (1) {
2560 tcg_cpu_exec();
2561 qemu_wait_io_event(cur_cpu);
2564 return NULL;
2567 void qemu_cpu_kick(void *_env)
2569 CPUState *env = _env;
2570 qemu_cond_broadcast(env->halt_cond);
2571 if (kvm_enabled())
2572 qemu_thread_signal(env->thread, SIG_IPI);
2575 int qemu_cpu_self(void *_env)
2577 CPUState *env = _env;
2578 QemuThread this;
2580 qemu_thread_self(&this);
2582 return qemu_thread_equal(&this, env->thread);
2585 static void cpu_signal(int sig)
2587 if (cpu_single_env)
2588 cpu_exit(cpu_single_env);
2591 static void tcg_block_io_signals(void)
2593 sigset_t set;
2594 struct sigaction sigact;
2596 sigemptyset(&set);
2597 sigaddset(&set, SIGUSR2);
2598 sigaddset(&set, SIGIO);
2599 sigaddset(&set, SIGALRM);
2600 sigaddset(&set, SIGCHLD);
2601 pthread_sigmask(SIG_BLOCK, &set, NULL);
2603 sigemptyset(&set);
2604 sigaddset(&set, SIG_IPI);
2605 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2607 memset(&sigact, 0, sizeof(sigact));
2608 sigact.sa_handler = cpu_signal;
2609 sigaction(SIG_IPI, &sigact, NULL);
2612 static void dummy_signal(int sig)
2616 static void kvm_block_io_signals(CPUState *env)
2618 int r;
2619 sigset_t set;
2620 struct sigaction sigact;
2622 sigemptyset(&set);
2623 sigaddset(&set, SIGUSR2);
2624 sigaddset(&set, SIGIO);
2625 sigaddset(&set, SIGALRM);
2626 sigaddset(&set, SIGCHLD);
2627 sigaddset(&set, SIG_IPI);
2628 pthread_sigmask(SIG_BLOCK, &set, NULL);
2630 pthread_sigmask(SIG_BLOCK, NULL, &set);
2631 sigdelset(&set, SIG_IPI);
2633 memset(&sigact, 0, sizeof(sigact));
2634 sigact.sa_handler = dummy_signal;
2635 sigaction(SIG_IPI, &sigact, NULL);
2637 r = kvm_set_signal_mask(env, &set);
2638 if (r) {
2639 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
2640 exit(1);
2644 static void unblock_io_signals(void)
2646 sigset_t set;
2648 sigemptyset(&set);
2649 sigaddset(&set, SIGUSR2);
2650 sigaddset(&set, SIGIO);
2651 sigaddset(&set, SIGALRM);
2652 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2654 sigemptyset(&set);
2655 sigaddset(&set, SIG_IPI);
2656 pthread_sigmask(SIG_BLOCK, &set, NULL);
2659 static void qemu_signal_lock(unsigned int msecs)
2661 qemu_mutex_lock(&qemu_fair_mutex);
2663 while (qemu_mutex_trylock(&qemu_global_mutex)) {
2664 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
2665 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
2666 break;
2668 qemu_mutex_unlock(&qemu_fair_mutex);
2671 void qemu_mutex_lock_iothread(void)
2673 if (kvm_enabled()) {
2674 qemu_mutex_lock(&qemu_fair_mutex);
2675 qemu_mutex_lock(&qemu_global_mutex);
2676 qemu_mutex_unlock(&qemu_fair_mutex);
2677 } else
2678 qemu_signal_lock(100);
2681 void qemu_mutex_unlock_iothread(void)
2683 qemu_mutex_unlock(&qemu_global_mutex);
2686 static int all_vcpus_paused(void)
2688 CPUState *penv = first_cpu;
2690 while (penv) {
2691 if (!penv->stopped)
2692 return 0;
2693 penv = (CPUState *)penv->next_cpu;
2696 return 1;
2699 static void pause_all_vcpus(void)
2701 CPUState *penv = first_cpu;
2703 while (penv) {
2704 penv->stop = 1;
2705 qemu_thread_signal(penv->thread, SIG_IPI);
2706 qemu_cpu_kick(penv);
2707 penv = (CPUState *)penv->next_cpu;
2710 while (!all_vcpus_paused()) {
2711 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
2712 penv = first_cpu;
2713 while (penv) {
2714 qemu_thread_signal(penv->thread, SIG_IPI);
2715 penv = (CPUState *)penv->next_cpu;
2720 static void resume_all_vcpus(void)
2722 CPUState *penv = first_cpu;
2724 while (penv) {
2725 penv->stop = 0;
2726 penv->stopped = 0;
2727 qemu_thread_signal(penv->thread, SIG_IPI);
2728 qemu_cpu_kick(penv);
2729 penv = (CPUState *)penv->next_cpu;
2733 static void tcg_init_vcpu(void *_env)
2735 CPUState *env = _env;
2736 /* share a single thread for all cpus with TCG */
2737 if (!tcg_cpu_thread) {
2738 env->thread = qemu_mallocz(sizeof(QemuThread));
2739 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2740 qemu_cond_init(env->halt_cond);
2741 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
2742 while (env->created == 0)
2743 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2744 tcg_cpu_thread = env->thread;
2745 tcg_halt_cond = env->halt_cond;
2746 } else {
2747 env->thread = tcg_cpu_thread;
2748 env->halt_cond = tcg_halt_cond;
2752 static void kvm_start_vcpu(CPUState *env)
2754 env->thread = qemu_mallocz(sizeof(QemuThread));
2755 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2756 qemu_cond_init(env->halt_cond);
2757 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
2758 while (env->created == 0)
2759 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2762 void qemu_init_vcpu(void *_env)
2764 CPUState *env = _env;
2766 env->nr_cores = smp_cores;
2767 env->nr_threads = smp_threads;
2768 if (kvm_enabled())
2769 kvm_start_vcpu(env);
2770 else
2771 tcg_init_vcpu(env);
2774 void qemu_notify_event(void)
2776 qemu_event_increment();
2779 static void qemu_system_vmstop_request(int reason)
2781 vmstop_requested = reason;
2782 qemu_notify_event();
2785 void vm_stop(int reason)
2787 QemuThread me;
2788 qemu_thread_self(&me);
2790 if (!qemu_thread_equal(&me, &io_thread)) {
2791 qemu_system_vmstop_request(reason);
2793 * FIXME: should not return to device code in case
2794 * vm_stop() has been requested.
2796 if (cpu_single_env) {
2797 cpu_exit(cpu_single_env);
2798 cpu_single_env->stop = 1;
2800 return;
2802 do_vm_stop(reason);
2805 #endif
2808 #ifdef _WIN32
2809 static void host_main_loop_wait(int *timeout)
2811 int ret, ret2, i;
2812 PollingEntry *pe;
2815 /* XXX: need to suppress polling by better using win32 events */
2816 ret = 0;
2817 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2818 ret |= pe->func(pe->opaque);
2820 if (ret == 0) {
2821 int err;
2822 WaitObjects *w = &wait_objects;
2824 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2825 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2826 if (w->func[ret - WAIT_OBJECT_0])
2827 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2829 /* Check for additional signaled events */
2830 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2832 /* Check if event is signaled */
2833 ret2 = WaitForSingleObject(w->events[i], 0);
2834 if(ret2 == WAIT_OBJECT_0) {
2835 if (w->func[i])
2836 w->func[i](w->opaque[i]);
2837 } else if (ret2 == WAIT_TIMEOUT) {
2838 } else {
2839 err = GetLastError();
2840 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2843 } else if (ret == WAIT_TIMEOUT) {
2844 } else {
2845 err = GetLastError();
2846 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2850 *timeout = 0;
2852 #else
2853 static void host_main_loop_wait(int *timeout)
2856 #endif
2858 void main_loop_wait(int nonblocking)
2860 IOHandlerRecord *ioh;
2861 fd_set rfds, wfds, xfds;
2862 int ret, nfds;
2863 struct timeval tv;
2864 int timeout;
2866 if (nonblocking)
2867 timeout = 0;
2868 else {
2869 timeout = qemu_calculate_timeout();
2870 qemu_bh_update_timeout(&timeout);
2873 host_main_loop_wait(&timeout);
2875 /* poll any events */
2876 /* XXX: separate device handlers from system ones */
2877 nfds = -1;
2878 FD_ZERO(&rfds);
2879 FD_ZERO(&wfds);
2880 FD_ZERO(&xfds);
2881 QLIST_FOREACH(ioh, &io_handlers, next) {
2882 if (ioh->deleted)
2883 continue;
2884 if (ioh->fd_read &&
2885 (!ioh->fd_read_poll ||
2886 ioh->fd_read_poll(ioh->opaque) != 0)) {
2887 FD_SET(ioh->fd, &rfds);
2888 if (ioh->fd > nfds)
2889 nfds = ioh->fd;
2891 if (ioh->fd_write) {
2892 FD_SET(ioh->fd, &wfds);
2893 if (ioh->fd > nfds)
2894 nfds = ioh->fd;
2898 tv.tv_sec = timeout / 1000;
2899 tv.tv_usec = (timeout % 1000) * 1000;
2901 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2903 qemu_mutex_unlock_iothread();
2904 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2905 qemu_mutex_lock_iothread();
2906 if (ret > 0) {
2907 IOHandlerRecord *pioh;
2909 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
2910 if (ioh->deleted) {
2911 QLIST_REMOVE(ioh, next);
2912 qemu_free(ioh);
2913 continue;
2915 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2916 ioh->fd_read(ioh->opaque);
2917 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
2918 FD_CLR(ioh->fd, &rfds);
2920 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2921 ioh->fd_write(ioh->opaque);
2926 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2928 qemu_run_all_timers();
2930 /* Check bottom-halves last in case any of the earlier events triggered
2931 them. */
2932 qemu_bh_poll();
2936 static int qemu_cpu_exec(CPUState *env)
2938 int ret;
2939 #ifdef CONFIG_PROFILER
2940 int64_t ti;
2941 #endif
2943 #ifdef CONFIG_PROFILER
2944 ti = profile_getclock();
2945 #endif
2946 if (use_icount) {
2947 int64_t count;
2948 int decr;
2949 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
2950 env->icount_decr.u16.low = 0;
2951 env->icount_extra = 0;
2952 count = qemu_icount_round (qemu_next_deadline());
2953 qemu_icount += count;
2954 decr = (count > 0xffff) ? 0xffff : count;
2955 count -= decr;
2956 env->icount_decr.u16.low = decr;
2957 env->icount_extra = count;
2959 ret = cpu_exec(env);
2960 #ifdef CONFIG_PROFILER
2961 qemu_time += profile_getclock() - ti;
2962 #endif
2963 if (use_icount) {
2964 /* Fold pending instructions back into the
2965 instruction counter, and clear the interrupt flag. */
2966 qemu_icount -= (env->icount_decr.u16.low
2967 + env->icount_extra);
2968 env->icount_decr.u32 = 0;
2969 env->icount_extra = 0;
2971 return ret;
2974 static bool tcg_cpu_exec(void)
2976 int ret = 0;
2978 if (next_cpu == NULL)
2979 next_cpu = first_cpu;
2980 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
2981 CPUState *env = cur_cpu = next_cpu;
2983 qemu_clock_enable(vm_clock,
2984 (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
2986 if (qemu_alarm_pending())
2987 break;
2988 if (cpu_can_run(env))
2989 ret = qemu_cpu_exec(env);
2990 else if (env->stop)
2991 break;
2993 if (ret == EXCP_DEBUG) {
2994 gdb_set_stop_cpu(env);
2995 debug_requested = 1;
2996 break;
2999 return tcg_has_work();
3002 static int vm_can_run(void)
3004 if (powerdown_requested)
3005 return 0;
3006 if (reset_requested)
3007 return 0;
3008 if (shutdown_requested)
3009 return 0;
3010 if (debug_requested)
3011 return 0;
3012 return 1;
3015 qemu_irq qemu_system_powerdown;
3017 static void main_loop(void)
3019 int r;
3021 if (kvm_enabled()) {
3022 kvm_main_loop();
3023 cpu_disable_ticks();
3024 return;
3027 #ifdef CONFIG_IOTHREAD
3028 qemu_system_ready = 1;
3029 qemu_cond_broadcast(&qemu_system_cond);
3030 #endif
3032 for (;;) {
3033 do {
3034 bool nonblocking = false;
3035 #ifdef CONFIG_PROFILER
3036 int64_t ti;
3037 #endif
3038 #ifndef CONFIG_IOTHREAD
3039 nonblocking = tcg_cpu_exec();
3040 #endif
3041 #ifdef CONFIG_PROFILER
3042 ti = profile_getclock();
3043 #endif
3044 main_loop_wait(nonblocking);
3045 #ifdef CONFIG_PROFILER
3046 dev_time += profile_getclock() - ti;
3047 #endif
3048 } while (vm_can_run());
3050 if (qemu_debug_requested()) {
3051 vm_stop(EXCP_DEBUG);
3053 if (qemu_shutdown_requested()) {
3054 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
3055 if (no_shutdown) {
3056 vm_stop(0);
3057 no_shutdown = 0;
3058 } else
3059 break;
3061 if (qemu_reset_requested()) {
3062 pause_all_vcpus();
3063 qemu_system_reset();
3064 resume_all_vcpus();
3066 if (qemu_powerdown_requested()) {
3067 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
3068 qemu_irq_raise(qemu_system_powerdown);
3070 if ((r = qemu_vmstop_requested())) {
3071 vm_stop(r);
3074 pause_all_vcpus();
3077 static void version(void)
3079 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3082 static void help(int exitcode)
3084 const char *options_help =
3085 #define DEF(option, opt_arg, opt_enum, opt_help) \
3086 opt_help
3087 #define DEFHEADING(text) stringify(text) "\n"
3088 #include "qemu-options.h"
3089 #undef DEF
3090 #undef DEFHEADING
3091 #undef GEN_DOCS
3093 version();
3094 printf("usage: %s [options] [disk_image]\n"
3095 "\n"
3096 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3097 "\n"
3098 "%s\n"
3099 "During emulation, the following keys are useful:\n"
3100 "ctrl-alt-f toggle full screen\n"
3101 "ctrl-alt-n switch to virtual console 'n'\n"
3102 "ctrl-alt toggle mouse and keyboard grab\n"
3103 "\n"
3104 "When using -nographic, press 'ctrl-a h' to get some help.\n",
3105 "qemu",
3106 options_help);
3107 exit(exitcode);
3110 #define HAS_ARG 0x0001
3112 enum {
3113 #define DEF(option, opt_arg, opt_enum, opt_help) \
3114 opt_enum,
3115 #define DEFHEADING(text)
3116 #include "qemu-options.h"
3117 #undef DEF
3118 #undef DEFHEADING
3119 #undef GEN_DOCS
3122 typedef struct QEMUOption {
3123 const char *name;
3124 int flags;
3125 int index;
3126 } QEMUOption;
3128 static const QEMUOption qemu_options[] = {
3129 { "h", 0, QEMU_OPTION_h },
3130 #define DEF(option, opt_arg, opt_enum, opt_help) \
3131 { option, opt_arg, opt_enum },
3132 #define DEFHEADING(text)
3133 #include "qemu-options.h"
3134 #undef DEF
3135 #undef DEFHEADING
3136 #undef GEN_DOCS
3137 { NULL },
3140 #ifdef HAS_AUDIO
3141 struct soundhw soundhw[] = {
3142 #ifdef HAS_AUDIO_CHOICE
3143 #if defined(TARGET_I386) || defined(TARGET_MIPS)
3145 "pcspk",
3146 "PC speaker",
3149 { .init_isa = pcspk_audio_init }
3151 #endif
3153 #ifdef CONFIG_SB16
3155 "sb16",
3156 "Creative Sound Blaster 16",
3159 { .init_isa = SB16_init }
3161 #endif
3163 #ifdef CONFIG_CS4231A
3165 "cs4231a",
3166 "CS4231A",
3169 { .init_isa = cs4231a_init }
3171 #endif
3173 #ifdef CONFIG_ADLIB
3175 "adlib",
3176 #ifdef HAS_YMF262
3177 "Yamaha YMF262 (OPL3)",
3178 #else
3179 "Yamaha YM3812 (OPL2)",
3180 #endif
3183 { .init_isa = Adlib_init }
3185 #endif
3187 #ifdef CONFIG_GUS
3189 "gus",
3190 "Gravis Ultrasound GF1",
3193 { .init_isa = GUS_init }
3195 #endif
3197 #ifdef CONFIG_AC97
3199 "ac97",
3200 "Intel 82801AA AC97 Audio",
3203 { .init_pci = ac97_init }
3205 #endif
3207 #ifdef CONFIG_ES1370
3209 "es1370",
3210 "ENSONIQ AudioPCI ES1370",
3213 { .init_pci = es1370_init }
3215 #endif
3217 #endif /* HAS_AUDIO_CHOICE */
3219 { NULL, NULL, 0, 0, { NULL } }
3222 static void select_soundhw (const char *optarg)
3224 struct soundhw *c;
3226 if (*optarg == '?') {
3227 show_valid_cards:
3229 printf ("Valid sound card names (comma separated):\n");
3230 for (c = soundhw; c->name; ++c) {
3231 printf ("%-11s %s\n", c->name, c->descr);
3233 printf ("\n-soundhw all will enable all of the above\n");
3234 exit (*optarg != '?');
3236 else {
3237 size_t l;
3238 const char *p;
3239 char *e;
3240 int bad_card = 0;
3242 if (!strcmp (optarg, "all")) {
3243 for (c = soundhw; c->name; ++c) {
3244 c->enabled = 1;
3246 return;
3249 p = optarg;
3250 while (*p) {
3251 e = strchr (p, ',');
3252 l = !e ? strlen (p) : (size_t) (e - p);
3254 for (c = soundhw; c->name; ++c) {
3255 if (!strncmp (c->name, p, l) && !c->name[l]) {
3256 c->enabled = 1;
3257 break;
3261 if (!c->name) {
3262 if (l > 80) {
3263 fprintf (stderr,
3264 "Unknown sound card name (too big to show)\n");
3266 else {
3267 fprintf (stderr, "Unknown sound card name `%.*s'\n",
3268 (int) l, p);
3270 bad_card = 1;
3272 p += l + (e != NULL);
3275 if (bad_card)
3276 goto show_valid_cards;
3279 #endif
3281 static void select_vgahw (const char *p)
3283 const char *opts;
3285 default_vga = 0;
3286 vga_interface_type = VGA_NONE;
3287 if (strstart(p, "std", &opts)) {
3288 vga_interface_type = VGA_STD;
3289 } else if (strstart(p, "cirrus", &opts)) {
3290 vga_interface_type = VGA_CIRRUS;
3291 } else if (strstart(p, "vmware", &opts)) {
3292 vga_interface_type = VGA_VMWARE;
3293 } else if (strstart(p, "xenfb", &opts)) {
3294 vga_interface_type = VGA_XENFB;
3295 } else if (!strstart(p, "none", &opts)) {
3296 invalid_vga:
3297 fprintf(stderr, "Unknown vga type: %s\n", p);
3298 exit(1);
3300 while (*opts) {
3301 const char *nextopt;
3303 if (strstart(opts, ",retrace=", &nextopt)) {
3304 opts = nextopt;
3305 if (strstart(opts, "dumb", &nextopt))
3306 vga_retrace_method = VGA_RETRACE_DUMB;
3307 else if (strstart(opts, "precise", &nextopt))
3308 vga_retrace_method = VGA_RETRACE_PRECISE;
3309 else goto invalid_vga;
3310 } else goto invalid_vga;
3311 opts = nextopt;
3315 #ifdef TARGET_I386
3316 static int balloon_parse(const char *arg)
3318 QemuOpts *opts;
3320 if (strcmp(arg, "none") == 0) {
3321 return 0;
3324 if (!strncmp(arg, "virtio", 6)) {
3325 if (arg[6] == ',') {
3326 /* have params -> parse them */
3327 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
3328 if (!opts)
3329 return -1;
3330 } else {
3331 /* create empty opts */
3332 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3334 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
3335 return 0;
3338 return -1;
3340 #endif
3342 #ifdef _WIN32
3343 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
3345 exit(STATUS_CONTROL_C_EXIT);
3346 return TRUE;
3348 #endif
3350 int qemu_uuid_parse(const char *str, uint8_t *uuid)
3352 int ret;
3354 if(strlen(str) != 36)
3355 return -1;
3357 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
3358 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
3359 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
3361 if(ret != 16)
3362 return -1;
3364 #ifdef TARGET_I386
3365 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
3366 #endif
3368 return 0;
3371 #ifndef _WIN32
3373 static void termsig_handler(int signal)
3375 qemu_system_shutdown_request();
3378 static void sigchld_handler(int signal)
3380 waitpid(-1, NULL, WNOHANG);
3383 static void sighandler_setup(void)
3385 struct sigaction act;
3387 memset(&act, 0, sizeof(act));
3388 act.sa_handler = termsig_handler;
3389 sigaction(SIGINT, &act, NULL);
3390 sigaction(SIGHUP, &act, NULL);
3391 sigaction(SIGTERM, &act, NULL);
3393 act.sa_handler = sigchld_handler;
3394 act.sa_flags = SA_NOCLDSTOP;
3395 sigaction(SIGCHLD, &act, NULL);
3398 #endif
3400 #ifdef _WIN32
3401 /* Look for support files in the same directory as the executable. */
3402 static char *find_datadir(const char *argv0)
3404 char *p;
3405 char buf[MAX_PATH];
3406 DWORD len;
3408 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
3409 if (len == 0) {
3410 return NULL;
3413 buf[len] = 0;
3414 p = buf + len - 1;
3415 while (p != buf && *p != '\\')
3416 p--;
3417 *p = 0;
3418 if (access(buf, R_OK) == 0) {
3419 return qemu_strdup(buf);
3421 return NULL;
3423 #else /* !_WIN32 */
3425 /* Find a likely location for support files using the location of the binary.
3426 For installed binaries this will be "$bindir/../share/qemu". When
3427 running from the build tree this will be "$bindir/../pc-bios". */
3428 #define SHARE_SUFFIX "/share/qemu"
3429 #define BUILD_SUFFIX "/pc-bios"
3430 static char *find_datadir(const char *argv0)
3432 char *dir;
3433 char *p = NULL;
3434 char *res;
3435 char buf[PATH_MAX];
3436 size_t max_len;
3438 #if defined(__linux__)
3440 int len;
3441 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
3442 if (len > 0) {
3443 buf[len] = 0;
3444 p = buf;
3447 #elif defined(__FreeBSD__)
3449 int len;
3450 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
3451 if (len > 0) {
3452 buf[len] = 0;
3453 p = buf;
3456 #endif
3457 /* If we don't have any way of figuring out the actual executable
3458 location then try argv[0]. */
3459 if (!p) {
3460 p = realpath(argv0, buf);
3461 if (!p) {
3462 return NULL;
3465 dir = dirname(p);
3466 dir = dirname(dir);
3468 max_len = strlen(dir) +
3469 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
3470 res = qemu_mallocz(max_len);
3471 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
3472 if (access(res, R_OK)) {
3473 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
3474 if (access(res, R_OK)) {
3475 qemu_free(res);
3476 res = NULL;
3480 return res;
3482 #undef SHARE_SUFFIX
3483 #undef BUILD_SUFFIX
3484 #endif
3486 char *qemu_find_file(int type, const char *name)
3488 int len;
3489 const char *subdir;
3490 char *buf;
3492 /* If name contains path separators then try it as a straight path. */
3493 if ((strchr(name, '/') || strchr(name, '\\'))
3494 && access(name, R_OK) == 0) {
3495 return qemu_strdup(name);
3497 switch (type) {
3498 case QEMU_FILE_TYPE_BIOS:
3499 subdir = "";
3500 break;
3501 case QEMU_FILE_TYPE_KEYMAP:
3502 subdir = "keymaps/";
3503 break;
3504 default:
3505 abort();
3507 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
3508 buf = qemu_mallocz(len);
3509 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
3510 if (access(buf, R_OK)) {
3511 qemu_free(buf);
3512 return NULL;
3514 return buf;
3517 static int device_help_func(QemuOpts *opts, void *opaque)
3519 return qdev_device_help(opts);
3522 static int device_init_func(QemuOpts *opts, void *opaque)
3524 DeviceState *dev;
3526 dev = qdev_device_add(opts);
3527 if (!dev)
3528 return -1;
3529 return 0;
3532 static int chardev_init_func(QemuOpts *opts, void *opaque)
3534 CharDriverState *chr;
3536 chr = qemu_chr_open_opts(opts, NULL);
3537 if (!chr)
3538 return -1;
3539 return 0;
3542 static int mon_init_func(QemuOpts *opts, void *opaque)
3544 CharDriverState *chr;
3545 const char *chardev;
3546 const char *mode;
3547 int flags;
3549 mode = qemu_opt_get(opts, "mode");
3550 if (mode == NULL) {
3551 mode = "readline";
3553 if (strcmp(mode, "readline") == 0) {
3554 flags = MONITOR_USE_READLINE;
3555 } else if (strcmp(mode, "control") == 0) {
3556 flags = MONITOR_USE_CONTROL;
3557 } else {
3558 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
3559 exit(1);
3562 if (qemu_opt_get_bool(opts, "default", 0))
3563 flags |= MONITOR_IS_DEFAULT;
3565 chardev = qemu_opt_get(opts, "chardev");
3566 chr = qemu_chr_find(chardev);
3567 if (chr == NULL) {
3568 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
3569 exit(1);
3572 monitor_init(chr, flags);
3573 return 0;
3576 static void monitor_parse(const char *optarg, const char *mode)
3578 static int monitor_device_index = 0;
3579 QemuOpts *opts;
3580 const char *p;
3581 char label[32];
3582 int def = 0;
3584 if (strstart(optarg, "chardev:", &p)) {
3585 snprintf(label, sizeof(label), "%s", p);
3586 } else {
3587 if (monitor_device_index) {
3588 snprintf(label, sizeof(label), "monitor%d",
3589 monitor_device_index);
3590 } else {
3591 snprintf(label, sizeof(label), "monitor");
3592 def = 1;
3594 opts = qemu_chr_parse_compat(label, optarg);
3595 if (!opts) {
3596 fprintf(stderr, "parse error: %s\n", optarg);
3597 exit(1);
3601 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
3602 if (!opts) {
3603 fprintf(stderr, "duplicate chardev: %s\n", label);
3604 exit(1);
3606 qemu_opt_set(opts, "mode", mode);
3607 qemu_opt_set(opts, "chardev", label);
3608 if (def)
3609 qemu_opt_set(opts, "default", "on");
3610 monitor_device_index++;
3613 struct device_config {
3614 enum {
3615 DEV_USB, /* -usbdevice */
3616 DEV_BT, /* -bt */
3617 DEV_SERIAL, /* -serial */
3618 DEV_PARALLEL, /* -parallel */
3619 DEV_VIRTCON, /* -virtioconsole */
3620 DEV_DEBUGCON, /* -debugcon */
3621 } type;
3622 const char *cmdline;
3623 QTAILQ_ENTRY(device_config) next;
3625 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
3627 static void add_device_config(int type, const char *cmdline)
3629 struct device_config *conf;
3631 conf = qemu_mallocz(sizeof(*conf));
3632 conf->type = type;
3633 conf->cmdline = cmdline;
3634 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
3637 static int foreach_device_config(int type, int (*func)(const char *cmdline))
3639 struct device_config *conf;
3640 int rc;
3642 QTAILQ_FOREACH(conf, &device_configs, next) {
3643 if (conf->type != type)
3644 continue;
3645 rc = func(conf->cmdline);
3646 if (0 != rc)
3647 return rc;
3649 return 0;
3652 static int serial_parse(const char *devname)
3654 static int index = 0;
3655 char label[32];
3657 if (strcmp(devname, "none") == 0)
3658 return 0;
3659 if (index == MAX_SERIAL_PORTS) {
3660 fprintf(stderr, "qemu: too many serial ports\n");
3661 exit(1);
3663 snprintf(label, sizeof(label), "serial%d", index);
3664 serial_hds[index] = qemu_chr_open(label, devname, NULL);
3665 if (!serial_hds[index]) {
3666 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
3667 devname, strerror(errno));
3668 return -1;
3670 index++;
3671 return 0;
3674 static int parallel_parse(const char *devname)
3676 static int index = 0;
3677 char label[32];
3679 if (strcmp(devname, "none") == 0)
3680 return 0;
3681 if (index == MAX_PARALLEL_PORTS) {
3682 fprintf(stderr, "qemu: too many parallel ports\n");
3683 exit(1);
3685 snprintf(label, sizeof(label), "parallel%d", index);
3686 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
3687 if (!parallel_hds[index]) {
3688 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
3689 devname, strerror(errno));
3690 return -1;
3692 index++;
3693 return 0;
3696 static int virtcon_parse(const char *devname)
3698 static int index = 0;
3699 char label[32];
3700 QemuOpts *bus_opts, *dev_opts;
3702 if (strcmp(devname, "none") == 0)
3703 return 0;
3704 if (index == MAX_VIRTIO_CONSOLES) {
3705 fprintf(stderr, "qemu: too many virtio consoles\n");
3706 exit(1);
3709 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3710 qemu_opt_set(bus_opts, "driver", "virtio-serial");
3712 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3713 qemu_opt_set(dev_opts, "driver", "virtconsole");
3715 snprintf(label, sizeof(label), "virtcon%d", index);
3716 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
3717 if (!virtcon_hds[index]) {
3718 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
3719 devname, strerror(errno));
3720 return -1;
3722 qemu_opt_set(dev_opts, "chardev", label);
3724 index++;
3725 return 0;
3728 static int debugcon_parse(const char *devname)
3730 QemuOpts *opts;
3732 if (!qemu_chr_open("debugcon", devname, NULL)) {
3733 exit(1);
3735 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
3736 if (!opts) {
3737 fprintf(stderr, "qemu: already have a debugcon device\n");
3738 exit(1);
3740 qemu_opt_set(opts, "driver", "isa-debugcon");
3741 qemu_opt_set(opts, "chardev", "debugcon");
3742 return 0;
3745 static const QEMUOption *lookup_opt(int argc, char **argv,
3746 const char **poptarg, int *poptind)
3748 const QEMUOption *popt;
3749 int optind = *poptind;
3750 char *r = argv[optind];
3751 const char *optarg;
3753 loc_set_cmdline(argv, optind, 1);
3754 optind++;
3755 /* Treat --foo the same as -foo. */
3756 if (r[1] == '-')
3757 r++;
3758 popt = qemu_options;
3759 for(;;) {
3760 if (!popt->name) {
3761 error_report("invalid option");
3762 exit(1);
3764 if (!strcmp(popt->name, r + 1))
3765 break;
3766 popt++;
3768 if (popt->flags & HAS_ARG) {
3769 if (optind >= argc) {
3770 error_report("requires an argument");
3771 exit(1);
3773 optarg = argv[optind++];
3774 loc_set_cmdline(argv, optind - 2, 2);
3775 } else {
3776 optarg = NULL;
3779 *poptarg = optarg;
3780 *poptind = optind;
3782 return popt;
3785 static void qmp_add_default(void)
3787 char buffer[4096];
3788 const char *home;
3789 static uint8_t null_uuid[16];
3790 uint8_t uuid[16];
3792 home = getenv("HOME");
3793 if (!home) {
3794 return;
3797 if (memcmp(qemu_uuid, null_uuid, sizeof(null_uuid)) == 0) {
3798 #if defined(CONFIG_UUID)
3799 uuid_generate(uuid);
3800 #else
3801 return;
3802 #endif
3803 } else {
3804 memcpy(uuid, qemu_uuid, sizeof(qemu_uuid));
3807 snprintf(buffer, sizeof(buffer), "%s/.qemu", home);
3808 if (mkdir(buffer, 0755) == -1 && errno != EEXIST) {
3809 fprintf(stderr, "could not open default QMP port\n");
3810 return;
3813 snprintf(buffer, sizeof(buffer), "%s/.qemu/qmp", home);
3814 if (mkdir(buffer, 0755) == -1 && errno != EEXIST) {
3815 fprintf(stderr, "could not open default QMP port\n");
3816 return;
3819 snprintf(buffer, sizeof(buffer),
3820 "unix:%s/.qemu/qmp/" UUID_FMT ".sock,server,nowait",
3821 home,
3822 uuid[0], uuid[1], uuid[2], uuid[3],
3823 uuid[4], uuid[5], uuid[6], uuid[7],
3824 uuid[8], uuid[9], uuid[10], uuid[11],
3825 uuid[12], uuid[13], uuid[14], uuid[15]);
3827 monitor_parse(buffer, "control");
3830 int main(int argc, char **argv, char **envp)
3832 const char *gdbstub_dev = NULL;
3833 uint32_t boot_devices_bitmap = 0;
3834 int i;
3835 int snapshot, linux_boot, net_boot;
3836 const char *icount_option = NULL;
3837 const char *initrd_filename;
3838 const char *kernel_filename, *kernel_cmdline;
3839 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3840 DisplayState *ds;
3841 DisplayChangeListener *dcl;
3842 int cyls, heads, secs, translation;
3843 QemuOpts *hda_opts = NULL, *opts;
3844 int optind;
3845 const char *optarg;
3846 const char *loadvm = NULL;
3847 QEMUMachine *machine;
3848 const char *cpu_model;
3849 #ifndef _WIN32
3850 int fds[2];
3851 #endif
3852 int tb_size;
3853 const char *pid_file = NULL;
3854 const char *incoming = NULL;
3855 #ifndef _WIN32
3856 int fd = 0;
3857 struct passwd *pwd = NULL;
3858 const char *chroot_dir = NULL;
3859 const char *run_as = NULL;
3860 #endif
3861 CPUState *env;
3862 int show_vnc_port = 0;
3863 int defconfig = 1;
3865 error_set_progname(argv[0]);
3867 exit_notifier_init();
3869 init_clocks();
3871 qemu_cache_utils_init(envp);
3873 QLIST_INIT (&vm_change_state_head);
3874 #ifndef _WIN32
3876 struct sigaction act;
3877 sigfillset(&act.sa_mask);
3878 act.sa_flags = 0;
3879 act.sa_handler = SIG_IGN;
3880 sigaction(SIGPIPE, &act, NULL);
3882 #else
3883 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3884 /* Note: cpu_interrupt() is currently not SMP safe, so we force
3885 QEMU to run on a single CPU */
3887 HANDLE h;
3888 DWORD mask, smask;
3889 int i;
3890 h = GetCurrentProcess();
3891 if (GetProcessAffinityMask(h, &mask, &smask)) {
3892 for(i = 0; i < 32; i++) {
3893 if (mask & (1 << i))
3894 break;
3896 if (i != 32) {
3897 mask = 1 << i;
3898 SetProcessAffinityMask(h, mask);
3902 #endif
3904 module_call_init(MODULE_INIT_MACHINE);
3905 machine = find_default_machine();
3906 cpu_model = NULL;
3907 initrd_filename = NULL;
3908 ram_size = 0;
3909 snapshot = 0;
3910 kernel_filename = NULL;
3911 kernel_cmdline = "";
3912 cyls = heads = secs = 0;
3913 translation = BIOS_ATA_TRANSLATION_AUTO;
3915 for (i = 0; i < MAX_NODES; i++) {
3916 node_mem[i] = 0;
3917 node_cpumask[i] = 0;
3920 assigned_devices_index = 0;
3922 nb_numa_nodes = 0;
3923 nb_nics = 0;
3925 tb_size = 0;
3926 autostart= 1;
3928 /* first pass of option parsing */
3929 optind = 1;
3930 while (optind < argc) {
3931 if (argv[optind][0] != '-') {
3932 /* disk image */
3933 optind++;
3934 continue;
3935 } else {
3936 const QEMUOption *popt;
3938 popt = lookup_opt(argc, argv, &optarg, &optind);
3939 switch (popt->index) {
3940 case QEMU_OPTION_nodefconfig:
3941 defconfig=0;
3942 break;
3947 if (defconfig) {
3948 const char *fname;
3949 FILE *fp;
3951 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3952 fp = fopen(fname, "r");
3953 if (fp) {
3954 if (qemu_config_parse(fp, fname) != 0) {
3955 exit(1);
3957 fclose(fp);
3960 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3961 fp = fopen(fname, "r");
3962 if (fp) {
3963 if (qemu_config_parse(fp, fname) != 0) {
3964 exit(1);
3966 fclose(fp);
3969 #if defined(cpudef_setup)
3970 cpudef_setup(); /* parse cpu definitions in target config file */
3971 #endif
3973 /* second pass of option parsing */
3974 optind = 1;
3975 for(;;) {
3976 if (optind >= argc)
3977 break;
3978 if (argv[optind][0] != '-') {
3979 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3980 } else {
3981 const QEMUOption *popt;
3983 popt = lookup_opt(argc, argv, &optarg, &optind);
3984 switch(popt->index) {
3985 case QEMU_OPTION_M:
3986 machine = find_machine(optarg);
3987 if (!machine) {
3988 QEMUMachine *m;
3989 printf("Supported machines are:\n");
3990 for(m = first_machine; m != NULL; m = m->next) {
3991 if (m->alias)
3992 printf("%-10s %s (alias of %s)\n",
3993 m->alias, m->desc, m->name);
3994 printf("%-10s %s%s\n",
3995 m->name, m->desc,
3996 m->is_default ? " (default)" : "");
3998 exit(*optarg != '?');
4000 break;
4001 case QEMU_OPTION_cpu:
4002 /* hw initialization will check this */
4003 if (*optarg == '?') {
4004 /* XXX: implement xxx_cpu_list for targets that still miss it */
4005 #if defined(cpu_list_id)
4006 cpu_list_id(stdout, &fprintf, optarg);
4007 #elif defined(cpu_list)
4008 cpu_list(stdout, &fprintf); /* deprecated */
4009 #endif
4010 exit(0);
4011 } else {
4012 cpu_model = optarg;
4014 break;
4015 case QEMU_OPTION_initrd:
4016 initrd_filename = optarg;
4017 break;
4018 case QEMU_OPTION_hda:
4019 if (cyls == 0)
4020 hda_opts = drive_add(optarg, HD_ALIAS, 0);
4021 else
4022 hda_opts = drive_add(optarg, HD_ALIAS
4023 ",cyls=%d,heads=%d,secs=%d%s",
4024 0, cyls, heads, secs,
4025 translation == BIOS_ATA_TRANSLATION_LBA ?
4026 ",trans=lba" :
4027 translation == BIOS_ATA_TRANSLATION_NONE ?
4028 ",trans=none" : "");
4029 break;
4030 case QEMU_OPTION_hdb:
4031 case QEMU_OPTION_hdc:
4032 case QEMU_OPTION_hdd:
4033 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4034 break;
4035 case QEMU_OPTION_drive:
4036 drive_add(NULL, "%s", optarg);
4037 break;
4038 case QEMU_OPTION_set:
4039 if (qemu_set_option(optarg) != 0)
4040 exit(1);
4041 break;
4042 case QEMU_OPTION_global:
4043 if (qemu_global_option(optarg) != 0)
4044 exit(1);
4045 break;
4046 case QEMU_OPTION_mtdblock:
4047 drive_add(optarg, MTD_ALIAS);
4048 break;
4049 case QEMU_OPTION_sd:
4050 drive_add(optarg, SD_ALIAS);
4051 break;
4052 case QEMU_OPTION_pflash:
4053 drive_add(optarg, PFLASH_ALIAS);
4054 break;
4055 case QEMU_OPTION_snapshot:
4056 snapshot = 1;
4057 break;
4058 case QEMU_OPTION_hdachs:
4060 const char *p;
4061 p = optarg;
4062 cyls = strtol(p, (char **)&p, 0);
4063 if (cyls < 1 || cyls > 16383)
4064 goto chs_fail;
4065 if (*p != ',')
4066 goto chs_fail;
4067 p++;
4068 heads = strtol(p, (char **)&p, 0);
4069 if (heads < 1 || heads > 16)
4070 goto chs_fail;
4071 if (*p != ',')
4072 goto chs_fail;
4073 p++;
4074 secs = strtol(p, (char **)&p, 0);
4075 if (secs < 1 || secs > 63)
4076 goto chs_fail;
4077 if (*p == ',') {
4078 p++;
4079 if (!strcmp(p, "none"))
4080 translation = BIOS_ATA_TRANSLATION_NONE;
4081 else if (!strcmp(p, "lba"))
4082 translation = BIOS_ATA_TRANSLATION_LBA;
4083 else if (!strcmp(p, "auto"))
4084 translation = BIOS_ATA_TRANSLATION_AUTO;
4085 else
4086 goto chs_fail;
4087 } else if (*p != '\0') {
4088 chs_fail:
4089 fprintf(stderr, "qemu: invalid physical CHS format\n");
4090 exit(1);
4092 if (hda_opts != NULL) {
4093 char num[16];
4094 snprintf(num, sizeof(num), "%d", cyls);
4095 qemu_opt_set(hda_opts, "cyls", num);
4096 snprintf(num, sizeof(num), "%d", heads);
4097 qemu_opt_set(hda_opts, "heads", num);
4098 snprintf(num, sizeof(num), "%d", secs);
4099 qemu_opt_set(hda_opts, "secs", num);
4100 if (translation == BIOS_ATA_TRANSLATION_LBA)
4101 qemu_opt_set(hda_opts, "trans", "lba");
4102 if (translation == BIOS_ATA_TRANSLATION_NONE)
4103 qemu_opt_set(hda_opts, "trans", "none");
4106 break;
4107 case QEMU_OPTION_numa:
4108 if (nb_numa_nodes >= MAX_NODES) {
4109 fprintf(stderr, "qemu: too many NUMA nodes\n");
4110 exit(1);
4112 numa_add(optarg);
4113 break;
4114 case QEMU_OPTION_nographic:
4115 display_type = DT_NOGRAPHIC;
4116 break;
4117 #ifdef CONFIG_CURSES
4118 case QEMU_OPTION_curses:
4119 display_type = DT_CURSES;
4120 break;
4121 #endif
4122 case QEMU_OPTION_portrait:
4123 graphic_rotate = 1;
4124 break;
4125 case QEMU_OPTION_kernel:
4126 kernel_filename = optarg;
4127 break;
4128 case QEMU_OPTION_append:
4129 kernel_cmdline = optarg;
4130 break;
4131 case QEMU_OPTION_cdrom:
4132 drive_add(optarg, CDROM_ALIAS);
4133 break;
4134 case QEMU_OPTION_boot:
4136 static const char * const params[] = {
4137 "order", "once", "menu", NULL
4139 char buf[sizeof(boot_devices)];
4140 char *standard_boot_devices;
4141 int legacy = 0;
4143 if (!strchr(optarg, '=')) {
4144 legacy = 1;
4145 pstrcpy(buf, sizeof(buf), optarg);
4146 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4147 fprintf(stderr,
4148 "qemu: unknown boot parameter '%s' in '%s'\n",
4149 buf, optarg);
4150 exit(1);
4153 if (legacy ||
4154 get_param_value(buf, sizeof(buf), "order", optarg)) {
4155 boot_devices_bitmap = parse_bootdevices(buf);
4156 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4158 if (!legacy) {
4159 if (get_param_value(buf, sizeof(buf),
4160 "once", optarg)) {
4161 boot_devices_bitmap |= parse_bootdevices(buf);
4162 standard_boot_devices = qemu_strdup(boot_devices);
4163 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4164 qemu_register_reset(restore_boot_devices,
4165 standard_boot_devices);
4167 if (get_param_value(buf, sizeof(buf),
4168 "menu", optarg)) {
4169 if (!strcmp(buf, "on")) {
4170 boot_menu = 1;
4171 } else if (!strcmp(buf, "off")) {
4172 boot_menu = 0;
4173 } else {
4174 fprintf(stderr,
4175 "qemu: invalid option value '%s'\n",
4176 buf);
4177 exit(1);
4182 break;
4183 case QEMU_OPTION_fda:
4184 case QEMU_OPTION_fdb:
4185 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4186 break;
4187 #ifdef TARGET_I386
4188 case QEMU_OPTION_no_fd_bootchk:
4189 fd_bootchk = 0;
4190 break;
4191 #endif
4192 case QEMU_OPTION_netdev:
4193 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4194 exit(1);
4196 break;
4197 case QEMU_OPTION_net:
4198 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4199 exit(1);
4201 break;
4202 #ifdef CONFIG_SLIRP
4203 case QEMU_OPTION_tftp:
4204 legacy_tftp_prefix = optarg;
4205 break;
4206 case QEMU_OPTION_bootp:
4207 legacy_bootp_filename = optarg;
4208 break;
4209 #ifndef _WIN32
4210 case QEMU_OPTION_smb:
4211 if (net_slirp_smb(optarg) < 0)
4212 exit(1);
4213 break;
4214 #endif
4215 case QEMU_OPTION_redir:
4216 if (net_slirp_redir(optarg) < 0)
4217 exit(1);
4218 break;
4219 #endif
4220 case QEMU_OPTION_bt:
4221 add_device_config(DEV_BT, optarg);
4222 break;
4223 #ifdef HAS_AUDIO
4224 case QEMU_OPTION_audio_help:
4225 AUD_help ();
4226 exit (0);
4227 break;
4228 case QEMU_OPTION_soundhw:
4229 select_soundhw (optarg);
4230 break;
4231 #endif
4232 case QEMU_OPTION_h:
4233 help(0);
4234 break;
4235 case QEMU_OPTION_version:
4236 version();
4237 exit(0);
4238 break;
4239 case QEMU_OPTION_m: {
4240 uint64_t value;
4241 char *ptr;
4243 value = strtoul(optarg, &ptr, 10);
4244 switch (*ptr) {
4245 case 0: case 'M': case 'm':
4246 value <<= 20;
4247 break;
4248 case 'G': case 'g':
4249 value <<= 30;
4250 break;
4251 default:
4252 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4253 exit(1);
4256 /* On 32-bit hosts, QEMU is limited by virtual address space */
4257 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
4258 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4259 exit(1);
4261 if (value != (uint64_t)(ram_addr_t)value) {
4262 fprintf(stderr, "qemu: ram size too large\n");
4263 exit(1);
4265 ram_size = value;
4266 break;
4268 case QEMU_OPTION_mempath:
4269 mem_path = optarg;
4270 break;
4271 #ifdef MAP_POPULATE
4272 case QEMU_OPTION_mem_prealloc:
4273 mem_prealloc = 1;
4274 break;
4275 #endif
4276 case QEMU_OPTION_d:
4278 int mask;
4279 const CPULogItem *item;
4281 mask = cpu_str_to_log_mask(optarg);
4282 if (!mask) {
4283 printf("Log items (comma separated):\n");
4284 for(item = cpu_log_items; item->mask != 0; item++) {
4285 printf("%-10s %s\n", item->name, item->help);
4287 exit(1);
4289 cpu_set_log(mask);
4291 break;
4292 case QEMU_OPTION_s:
4293 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4294 break;
4295 case QEMU_OPTION_gdb:
4296 gdbstub_dev = optarg;
4297 break;
4298 case QEMU_OPTION_L:
4299 data_dir = optarg;
4300 break;
4301 case QEMU_OPTION_bios:
4302 bios_name = optarg;
4303 break;
4304 case QEMU_OPTION_singlestep:
4305 singlestep = 1;
4306 break;
4307 case QEMU_OPTION_S:
4308 autostart = 0;
4309 break;
4310 case QEMU_OPTION_k:
4311 keyboard_layout = optarg;
4312 break;
4313 case QEMU_OPTION_localtime:
4314 rtc_utc = 0;
4315 break;
4316 case QEMU_OPTION_vga:
4317 select_vgahw (optarg);
4318 break;
4319 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4320 case QEMU_OPTION_g:
4322 const char *p;
4323 int w, h, depth;
4324 p = optarg;
4325 w = strtol(p, (char **)&p, 10);
4326 if (w <= 0) {
4327 graphic_error:
4328 fprintf(stderr, "qemu: invalid resolution or depth\n");
4329 exit(1);
4331 if (*p != 'x')
4332 goto graphic_error;
4333 p++;
4334 h = strtol(p, (char **)&p, 10);
4335 if (h <= 0)
4336 goto graphic_error;
4337 if (*p == 'x') {
4338 p++;
4339 depth = strtol(p, (char **)&p, 10);
4340 if (depth != 8 && depth != 15 && depth != 16 &&
4341 depth != 24 && depth != 32)
4342 goto graphic_error;
4343 } else if (*p == '\0') {
4344 depth = graphic_depth;
4345 } else {
4346 goto graphic_error;
4349 graphic_width = w;
4350 graphic_height = h;
4351 graphic_depth = depth;
4353 break;
4354 #endif
4355 case QEMU_OPTION_echr:
4357 char *r;
4358 term_escape_char = strtol(optarg, &r, 0);
4359 if (r == optarg)
4360 printf("Bad argument to echr\n");
4361 break;
4363 case QEMU_OPTION_monitor:
4364 monitor_parse(optarg, "readline");
4365 default_monitor = 0;
4366 break;
4367 case QEMU_OPTION_qmp:
4368 monitor_parse(optarg, "control");
4369 default_qmp = 0;
4370 break;
4371 case QEMU_OPTION_mon:
4372 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
4373 if (!opts) {
4374 fprintf(stderr, "parse error: %s\n", optarg);
4375 exit(1);
4376 } else {
4377 const char *mode;
4378 mode = qemu_opt_get(opts, "mode");
4379 if (mode == NULL || strcmp(mode, "readline") == 0) {
4380 default_monitor = 0;
4381 } else if (strcmp(mode, "control") == 0) {
4382 default_qmp = 0;
4385 break;
4386 case QEMU_OPTION_chardev:
4387 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
4388 if (!opts) {
4389 fprintf(stderr, "parse error: %s\n", optarg);
4390 exit(1);
4392 break;
4393 case QEMU_OPTION_serial:
4394 add_device_config(DEV_SERIAL, optarg);
4395 default_serial = 0;
4396 if (strncmp(optarg, "mon:", 4) == 0) {
4397 default_monitor = 0;
4399 break;
4400 case QEMU_OPTION_watchdog:
4401 if (watchdog) {
4402 fprintf(stderr,
4403 "qemu: only one watchdog option may be given\n");
4404 return 1;
4406 watchdog = optarg;
4407 break;
4408 case QEMU_OPTION_watchdog_action:
4409 if (select_watchdog_action(optarg) == -1) {
4410 fprintf(stderr, "Unknown -watchdog-action parameter\n");
4411 exit(1);
4413 break;
4414 case QEMU_OPTION_virtiocon:
4415 add_device_config(DEV_VIRTCON, optarg);
4416 default_virtcon = 0;
4417 if (strncmp(optarg, "mon:", 4) == 0) {
4418 default_monitor = 0;
4420 break;
4421 case QEMU_OPTION_parallel:
4422 add_device_config(DEV_PARALLEL, optarg);
4423 default_parallel = 0;
4424 if (strncmp(optarg, "mon:", 4) == 0) {
4425 default_monitor = 0;
4427 break;
4428 case QEMU_OPTION_debugcon:
4429 add_device_config(DEV_DEBUGCON, optarg);
4430 break;
4431 case QEMU_OPTION_loadvm:
4432 loadvm = optarg;
4433 break;
4434 case QEMU_OPTION_full_screen:
4435 full_screen = 1;
4436 break;
4437 #ifdef CONFIG_SDL
4438 case QEMU_OPTION_no_frame:
4439 no_frame = 1;
4440 break;
4441 case QEMU_OPTION_alt_grab:
4442 alt_grab = 1;
4443 break;
4444 case QEMU_OPTION_ctrl_grab:
4445 ctrl_grab = 1;
4446 break;
4447 case QEMU_OPTION_no_quit:
4448 no_quit = 1;
4449 break;
4450 case QEMU_OPTION_sdl:
4451 display_type = DT_SDL;
4452 break;
4453 #endif
4454 case QEMU_OPTION_pidfile:
4455 pid_file = optarg;
4456 break;
4457 #ifdef TARGET_I386
4458 case QEMU_OPTION_win2k_hack:
4459 win2k_install_hack = 1;
4460 break;
4461 case QEMU_OPTION_rtc_td_hack:
4462 rtc_td_hack = 1;
4463 break;
4464 case QEMU_OPTION_acpitable:
4465 if(acpi_table_add(optarg) < 0) {
4466 fprintf(stderr, "Wrong acpi table provided\n");
4467 exit(1);
4469 break;
4470 case QEMU_OPTION_smbios:
4471 if(smbios_entry_add(optarg) < 0) {
4472 fprintf(stderr, "Wrong smbios provided\n");
4473 exit(1);
4475 break;
4476 #endif
4477 #ifdef CONFIG_KVM
4478 #ifdef KVM_UPSTREAM
4479 case QEMU_OPTION_enable_kvm:
4480 kvm_allowed = 1;
4481 #endif
4482 break;
4483 case QEMU_OPTION_no_kvm:
4484 kvm_allowed = 0;
4485 break;
4486 case QEMU_OPTION_no_kvm_irqchip: {
4487 kvm_irqchip = 0;
4488 kvm_pit = 0;
4489 break;
4491 case QEMU_OPTION_no_kvm_pit: {
4492 kvm_pit = 0;
4493 break;
4495 case QEMU_OPTION_no_kvm_pit_reinjection: {
4496 kvm_pit_reinject = 0;
4497 break;
4499 case QEMU_OPTION_enable_nesting: {
4500 kvm_nested = 1;
4501 break;
4503 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4504 case QEMU_OPTION_pcidevice:
4505 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
4506 fprintf(stderr, "Too many assigned devices\n");
4507 exit(1);
4509 assigned_devices[assigned_devices_index] = optarg;
4510 assigned_devices_index++;
4511 break;
4512 #endif
4513 #endif
4514 case QEMU_OPTION_usb:
4515 usb_enabled = 1;
4516 break;
4517 case QEMU_OPTION_usbdevice:
4518 usb_enabled = 1;
4519 add_device_config(DEV_USB, optarg);
4520 break;
4521 case QEMU_OPTION_device:
4522 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
4523 exit(1);
4525 break;
4526 case QEMU_OPTION_smp:
4527 smp_parse(optarg);
4528 if (smp_cpus < 1) {
4529 fprintf(stderr, "Invalid number of CPUs\n");
4530 exit(1);
4532 if (max_cpus < smp_cpus) {
4533 fprintf(stderr, "maxcpus must be equal to or greater than "
4534 "smp\n");
4535 exit(1);
4537 if (max_cpus > 255) {
4538 fprintf(stderr, "Unsupported number of maxcpus\n");
4539 exit(1);
4541 break;
4542 case QEMU_OPTION_vnc:
4543 display_type = DT_VNC;
4544 vnc_display = optarg;
4545 break;
4546 #ifdef TARGET_I386
4547 case QEMU_OPTION_no_acpi:
4548 acpi_enabled = 0;
4549 break;
4550 case QEMU_OPTION_no_hpet:
4551 no_hpet = 1;
4552 break;
4553 case QEMU_OPTION_balloon:
4554 if (balloon_parse(optarg) < 0) {
4555 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
4556 exit(1);
4558 break;
4559 #endif
4560 case QEMU_OPTION_no_reboot:
4561 no_reboot = 1;
4562 break;
4563 case QEMU_OPTION_no_shutdown:
4564 no_shutdown = 1;
4565 break;
4566 case QEMU_OPTION_show_cursor:
4567 cursor_hide = 0;
4568 break;
4569 case QEMU_OPTION_uuid:
4570 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4571 fprintf(stderr, "Fail to parse UUID string."
4572 " Wrong format.\n");
4573 exit(1);
4575 break;
4576 #ifndef _WIN32
4577 case QEMU_OPTION_daemonize:
4578 daemonize = 1;
4579 break;
4580 #endif
4581 case QEMU_OPTION_option_rom:
4582 if (nb_option_roms >= MAX_OPTION_ROMS) {
4583 fprintf(stderr, "Too many option ROMs\n");
4584 exit(1);
4586 option_rom[nb_option_roms] = optarg;
4587 nb_option_roms++;
4588 break;
4589 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4590 case QEMU_OPTION_semihosting:
4591 semihosting_enabled = 1;
4592 break;
4593 #endif
4594 case QEMU_OPTION_tdf:
4595 time_drift_fix = 1;
4596 break;
4597 case QEMU_OPTION_kvm_shadow_memory:
4598 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
4599 break;
4600 case QEMU_OPTION_name:
4601 qemu_name = qemu_strdup(optarg);
4603 char *p = strchr(qemu_name, ',');
4604 if (p != NULL) {
4605 *p++ = 0;
4606 if (strncmp(p, "process=", 8)) {
4607 fprintf(stderr, "Unknown subargument %s to -name", p);
4608 exit(1);
4610 p += 8;
4611 set_proc_name(p);
4614 break;
4615 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4616 case QEMU_OPTION_prom_env:
4617 if (nb_prom_envs >= MAX_PROM_ENVS) {
4618 fprintf(stderr, "Too many prom variables\n");
4619 exit(1);
4621 prom_envs[nb_prom_envs] = optarg;
4622 nb_prom_envs++;
4623 break;
4624 #endif
4625 #ifdef TARGET_ARM
4626 case QEMU_OPTION_old_param:
4627 old_param = 1;
4628 break;
4629 #endif
4630 case QEMU_OPTION_clock:
4631 configure_alarms(optarg);
4632 break;
4633 case QEMU_OPTION_startdate:
4634 configure_rtc_date_offset(optarg, 1);
4635 break;
4636 case QEMU_OPTION_rtc:
4637 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
4638 if (!opts) {
4639 fprintf(stderr, "parse error: %s\n", optarg);
4640 exit(1);
4642 configure_rtc(opts);
4643 break;
4644 case QEMU_OPTION_tb_size:
4645 tb_size = strtol(optarg, NULL, 0);
4646 if (tb_size < 0)
4647 tb_size = 0;
4648 break;
4649 case QEMU_OPTION_icount:
4650 icount_option = optarg;
4651 break;
4652 case QEMU_OPTION_incoming:
4653 incoming = optarg;
4654 break;
4655 case QEMU_OPTION_nodefaults:
4656 default_serial = 0;
4657 default_parallel = 0;
4658 default_virtcon = 0;
4659 default_monitor = 0;
4660 default_qmp = 0;
4661 default_vga = 0;
4662 default_net = 0;
4663 default_floppy = 0;
4664 default_cdrom = 0;
4665 default_sdcard = 0;
4666 break;
4667 #ifndef _WIN32
4668 case QEMU_OPTION_chroot:
4669 chroot_dir = optarg;
4670 break;
4671 case QEMU_OPTION_runas:
4672 run_as = optarg;
4673 break;
4674 case QEMU_OPTION_nvram:
4675 nvram = optarg;
4676 break;
4677 #endif
4678 #ifdef CONFIG_XEN
4679 case QEMU_OPTION_xen_domid:
4680 xen_domid = atoi(optarg);
4681 break;
4682 case QEMU_OPTION_xen_create:
4683 xen_mode = XEN_CREATE;
4684 break;
4685 case QEMU_OPTION_xen_attach:
4686 xen_mode = XEN_ATTACH;
4687 break;
4688 #endif
4689 case QEMU_OPTION_readconfig:
4691 FILE *fp;
4692 fp = fopen(optarg, "r");
4693 if (fp == NULL) {
4694 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4695 exit(1);
4697 if (qemu_config_parse(fp, optarg) != 0) {
4698 exit(1);
4700 fclose(fp);
4701 break;
4703 case QEMU_OPTION_writeconfig:
4705 FILE *fp;
4706 if (strcmp(optarg, "-") == 0) {
4707 fp = stdout;
4708 } else {
4709 fp = fopen(optarg, "w");
4710 if (fp == NULL) {
4711 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4712 exit(1);
4715 qemu_config_write(fp);
4716 fclose(fp);
4717 break;
4722 loc_set_none();
4724 /* If no data_dir is specified then try to find it relative to the
4725 executable path. */
4726 if (!data_dir) {
4727 data_dir = find_datadir(argv[0]);
4729 /* If all else fails use the install patch specified when building. */
4730 if (!data_dir) {
4731 data_dir = CONFIG_QEMU_SHAREDIR;
4735 * Default to max_cpus = smp_cpus, in case the user doesn't
4736 * specify a max_cpus value.
4738 if (!max_cpus)
4739 max_cpus = smp_cpus;
4741 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4742 if (smp_cpus > machine->max_cpus) {
4743 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4744 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
4745 machine->max_cpus);
4746 exit(1);
4749 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
4750 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
4752 if (machine->no_serial) {
4753 default_serial = 0;
4755 if (machine->no_parallel) {
4756 default_parallel = 0;
4758 if (!machine->use_virtcon) {
4759 default_virtcon = 0;
4761 if (machine->no_vga) {
4762 default_vga = 0;
4764 if (machine->no_floppy) {
4765 default_floppy = 0;
4767 if (machine->no_cdrom) {
4768 default_cdrom = 0;
4770 if (machine->no_sdcard) {
4771 default_sdcard = 0;
4774 if (display_type == DT_NOGRAPHIC) {
4775 if (default_parallel)
4776 add_device_config(DEV_PARALLEL, "null");
4777 if (default_serial && default_monitor) {
4778 add_device_config(DEV_SERIAL, "mon:stdio");
4779 } else if (default_virtcon && default_monitor) {
4780 add_device_config(DEV_VIRTCON, "mon:stdio");
4781 } else {
4782 if (default_serial)
4783 add_device_config(DEV_SERIAL, "stdio");
4784 if (default_virtcon)
4785 add_device_config(DEV_VIRTCON, "stdio");
4786 if (default_monitor)
4787 monitor_parse("stdio", "readline");
4789 } else {
4790 if (default_serial)
4791 add_device_config(DEV_SERIAL, "vc:80Cx24C");
4792 if (default_parallel)
4793 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4794 if (default_monitor)
4795 monitor_parse("vc:80Cx24C", "readline");
4796 if (default_virtcon)
4797 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4799 if (default_qmp) {
4800 qmp_add_default();
4802 if (default_vga)
4803 vga_interface_type = VGA_CIRRUS;
4805 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
4806 exit(1);
4808 #ifndef _WIN32
4809 if (daemonize) {
4810 pid_t pid;
4812 if (pipe(fds) == -1)
4813 exit(1);
4815 pid = fork();
4816 if (pid > 0) {
4817 uint8_t status;
4818 ssize_t len;
4820 close(fds[1]);
4822 again:
4823 len = read(fds[0], &status, 1);
4824 if (len == -1 && (errno == EINTR))
4825 goto again;
4827 if (len != 1)
4828 exit(1);
4829 else if (status == 1) {
4830 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
4831 exit(1);
4832 } else
4833 exit(0);
4834 } else if (pid < 0)
4835 exit(1);
4837 close(fds[0]);
4838 qemu_set_cloexec(fds[1]);
4840 setsid();
4842 pid = fork();
4843 if (pid > 0)
4844 exit(0);
4845 else if (pid < 0)
4846 exit(1);
4848 umask(027);
4850 signal(SIGTSTP, SIG_IGN);
4851 signal(SIGTTOU, SIG_IGN);
4852 signal(SIGTTIN, SIG_IGN);
4854 #endif
4856 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4857 #ifndef _WIN32
4858 if (daemonize) {
4859 uint8_t status = 1;
4860 if (write(fds[1], &status, 1) != 1) {
4861 perror("daemonize. Writing to pipe\n");
4863 } else
4864 #endif
4865 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
4866 exit(1);
4869 if (kvm_enabled()) {
4870 int ret;
4872 ret = kvm_init(smp_cpus);
4873 if (ret < 0) {
4874 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
4875 fprintf(stderr, "failed to initialize KVM\n");
4876 exit(1);
4877 #endif
4878 #ifdef CONFIG_KVM
4879 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
4880 kvm_allowed = 0;
4881 #endif
4885 if (qemu_init_main_loop()) {
4886 fprintf(stderr, "qemu_init_main_loop failed\n");
4887 exit(1);
4889 linux_boot = (kernel_filename != NULL);
4891 if (!linux_boot && *kernel_cmdline != '\0') {
4892 fprintf(stderr, "-append only allowed with -kernel option\n");
4893 exit(1);
4896 if (!linux_boot && initrd_filename != NULL) {
4897 fprintf(stderr, "-initrd only allowed with -kernel option\n");
4898 exit(1);
4901 #ifndef _WIN32
4902 /* Win32 doesn't support line-buffering and requires size >= 2 */
4903 setvbuf(stdout, NULL, _IOLBF, 0);
4904 #endif
4906 if (init_timer_alarm() < 0) {
4907 fprintf(stderr, "could not initialize alarm timer\n");
4908 exit(1);
4910 configure_icount(icount_option);
4912 #ifdef _WIN32
4913 socket_init();
4914 #endif
4916 if (net_init_clients() < 0) {
4917 exit(1);
4920 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4921 net_set_boot_mask(net_boot);
4923 /* init the bluetooth world */
4924 if (foreach_device_config(DEV_BT, bt_parse))
4925 exit(1);
4927 /* init the memory */
4928 if (ram_size == 0)
4929 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4931 /* init the dynamic translator */
4932 cpu_exec_init_all(tb_size * 1024 * 1024);
4934 bdrv_init_with_whitelist();
4936 blk_mig_init();
4938 if (default_cdrom) {
4939 /* we always create the cdrom drive, even if no disk is there */
4940 drive_add(NULL, CDROM_ALIAS);
4943 if (default_floppy) {
4944 /* we always create at least one floppy */
4945 drive_add(NULL, FD_ALIAS, 0);
4948 if (default_sdcard) {
4949 /* we always create one sd slot, even if no card is in it */
4950 drive_add(NULL, SD_ALIAS);
4953 /* open the virtual block devices */
4954 if (snapshot)
4955 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4956 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4957 exit(1);
4959 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
4960 ram_load, NULL);
4962 if (nb_numa_nodes > 0) {
4963 int i;
4965 if (nb_numa_nodes > smp_cpus) {
4966 nb_numa_nodes = smp_cpus;
4969 /* If no memory size if given for any node, assume the default case
4970 * and distribute the available memory equally across all nodes
4972 for (i = 0; i < nb_numa_nodes; i++) {
4973 if (node_mem[i] != 0)
4974 break;
4976 if (i == nb_numa_nodes) {
4977 uint64_t usedmem = 0;
4979 /* On Linux, the each node's border has to be 8MB aligned,
4980 * the final node gets the rest.
4982 for (i = 0; i < nb_numa_nodes - 1; i++) {
4983 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4984 usedmem += node_mem[i];
4986 node_mem[i] = ram_size - usedmem;
4989 for (i = 0; i < nb_numa_nodes; i++) {
4990 if (node_cpumask[i] != 0)
4991 break;
4993 /* assigning the VCPUs round-robin is easier to implement, guest OSes
4994 * must cope with this anyway, because there are BIOSes out there in
4995 * real machines which also use this scheme.
4997 if (i == nb_numa_nodes) {
4998 for (i = 0; i < smp_cpus; i++) {
4999 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5004 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5005 exit(1);
5006 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5007 exit(1);
5008 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5009 exit(1);
5010 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5011 exit(1);
5013 module_call_init(MODULE_INIT_DEVICE);
5015 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5016 exit(0);
5018 if (watchdog) {
5019 i = select_watchdog(watchdog);
5020 if (i > 0)
5021 exit (i == 1 ? 1 : 0);
5024 if (machine->compat_props) {
5025 qdev_prop_register_global_list(machine->compat_props);
5027 qemu_add_globals();
5029 machine->init(ram_size, boot_devices,
5030 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5032 cpu_synchronize_all_post_init();
5034 #ifndef _WIN32
5035 /* must be after terminal init, SDL library changes signal handlers */
5036 sighandler_setup();
5037 #endif
5039 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5040 for (i = 0; i < nb_numa_nodes; i++) {
5041 if (node_cpumask[i] & (1 << env->cpu_index)) {
5042 env->numa_node = i;
5047 current_machine = machine;
5049 /* init USB devices */
5050 if (usb_enabled) {
5051 if (foreach_device_config(DEV_USB, usb_parse) < 0)
5052 exit(1);
5055 /* init generic devices */
5056 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5057 exit(1);
5059 net_check_clients();
5061 /* just use the first displaystate for the moment */
5062 ds = get_displaystate();
5064 if (display_type == DT_DEFAULT) {
5065 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5066 display_type = DT_SDL;
5067 #else
5068 display_type = DT_VNC;
5069 vnc_display = "localhost:0,to=99";
5070 show_vnc_port = 1;
5071 #endif
5075 switch (display_type) {
5076 case DT_NOGRAPHIC:
5077 break;
5078 #if defined(CONFIG_CURSES)
5079 case DT_CURSES:
5080 curses_display_init(ds, full_screen);
5081 break;
5082 #endif
5083 #if defined(CONFIG_SDL)
5084 case DT_SDL:
5085 sdl_display_init(ds, full_screen, no_frame);
5086 break;
5087 #elif defined(CONFIG_COCOA)
5088 case DT_SDL:
5089 cocoa_display_init(ds, full_screen);
5090 break;
5091 #endif
5092 case DT_VNC:
5093 vnc_display_init(ds);
5094 if (vnc_display_open(ds, vnc_display) < 0)
5095 exit(1);
5097 if (show_vnc_port) {
5098 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5100 break;
5101 default:
5102 break;
5104 dpy_resize(ds);
5106 dcl = ds->listeners;
5107 while (dcl != NULL) {
5108 if (dcl->dpy_refresh != NULL) {
5109 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5110 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5112 dcl = dcl->next;
5115 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5116 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5117 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5120 text_consoles_set_display(ds);
5122 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5123 exit(1);
5125 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5126 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5127 gdbstub_dev);
5128 exit(1);
5131 qdev_machine_creation_done();
5133 if (rom_load_all() != 0) {
5134 fprintf(stderr, "rom loading failed\n");
5135 exit(1);
5138 qemu_system_reset();
5139 if (loadvm) {
5140 if (load_vmstate(loadvm) < 0) {
5141 autostart = 0;
5145 if (incoming) {
5146 qemu_start_incoming_migration(incoming);
5147 } else if (autostart) {
5148 vm_start();
5151 #ifndef _WIN32
5152 if (daemonize) {
5153 uint8_t status = 0;
5154 ssize_t len;
5156 again1:
5157 len = write(fds[1], &status, 1);
5158 if (len == -1 && (errno == EINTR))
5159 goto again1;
5161 if (len != 1)
5162 exit(1);
5164 if (chdir("/")) {
5165 perror("not able to chdir to /");
5166 exit(1);
5168 TFR(fd = qemu_open("/dev/null", O_RDWR));
5169 if (fd == -1)
5170 exit(1);
5173 if (run_as) {
5174 pwd = getpwnam(run_as);
5175 if (!pwd) {
5176 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5177 exit(1);
5181 if (chroot_dir) {
5182 if (chroot(chroot_dir) < 0) {
5183 fprintf(stderr, "chroot failed\n");
5184 exit(1);
5186 if (chdir("/")) {
5187 perror("not able to chdir to /");
5188 exit(1);
5192 if (run_as) {
5193 if (setgid(pwd->pw_gid) < 0) {
5194 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5195 exit(1);
5197 if (setuid(pwd->pw_uid) < 0) {
5198 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5199 exit(1);
5201 if (setuid(0) != -1) {
5202 fprintf(stderr, "Dropping privileges failed\n");
5203 exit(1);
5207 if (daemonize) {
5208 dup2(fd, 0);
5209 dup2(fd, 1);
5210 dup2(fd, 2);
5212 close(fd);
5214 #endif
5216 main_loop();
5217 quit_timers();
5218 net_cleanup();
5220 return 0;