Introduce a default qmp session
[qemu/mdroth.git] / vl.c
blob5c62d97d6ae41e178823005342f1cf10ada3de32
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 "notify.h"
159 #include "disas.h"
161 #include "exec-all.h"
163 #include "qemu_socket.h"
165 #include "slirp/libslirp.h"
167 #include "qemu-queue.h"
169 //#define DEBUG_NET
170 //#define DEBUG_SLIRP
172 #define DEFAULT_RAM_SIZE 128
174 #define MAX_VIRTIO_CONSOLES 1
176 static const char *data_dir;
177 const char *bios_name = NULL;
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
181 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
182 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
183 DisplayType display_type = DT_DEFAULT;
184 const char* keyboard_layout = NULL;
185 ram_addr_t ram_size;
186 const char *mem_path = NULL;
187 #ifdef MAP_POPULATE
188 int mem_prealloc = 0; /* force preallocation of physical target memory */
189 #endif
190 int nb_nics;
191 NICInfo nd_table[MAX_NICS];
192 int vm_running;
193 int autostart;
194 static int rtc_utc = 1;
195 static int rtc_date_offset = -1; /* -1 means no change */
196 QEMUClock *rtc_clock;
197 int vga_interface_type = VGA_NONE;
198 #ifdef TARGET_SPARC
199 int graphic_width = 1024;
200 int graphic_height = 768;
201 int graphic_depth = 8;
202 #else
203 int graphic_width = 800;
204 int graphic_height = 600;
205 int graphic_depth = 15;
206 #endif
207 static int full_screen = 0;
208 #ifdef CONFIG_SDL
209 static int no_frame = 0;
210 #endif
211 int no_quit = 0;
212 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
213 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
214 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
215 #ifdef TARGET_I386
216 int win2k_install_hack = 0;
217 int rtc_td_hack = 0;
218 #endif
219 int usb_enabled = 0;
220 int singlestep = 0;
221 int smp_cpus = 1;
222 int max_cpus = 0;
223 int smp_cores = 1;
224 int smp_threads = 1;
225 const char *vnc_display;
226 int acpi_enabled = 1;
227 int no_hpet = 0;
228 int fd_bootchk = 1;
229 int no_reboot = 0;
230 int no_shutdown = 0;
231 int cursor_hide = 1;
232 int graphic_rotate = 0;
233 uint8_t irq0override = 1;
234 #ifndef _WIN32
235 int daemonize = 0;
236 #endif
237 const char *watchdog;
238 const char *option_rom[MAX_OPTION_ROMS];
239 int nb_option_roms;
240 int semihosting_enabled = 0;
241 #ifdef TARGET_ARM
242 int old_param = 0;
243 #endif
244 const char *qemu_name;
245 int alt_grab = 0;
246 int ctrl_grab = 0;
247 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
248 unsigned int nb_prom_envs = 0;
249 const char *prom_envs[MAX_PROM_ENVS];
250 #endif
251 int boot_menu;
253 int nb_numa_nodes;
254 uint64_t node_mem[MAX_NODES];
255 uint64_t node_cpumask[MAX_NODES];
257 static CPUState *cur_cpu;
258 static CPUState *next_cpu;
259 static QEMUTimer *nographic_timer;
261 uint8_t qemu_uuid[16];
263 static QEMUBootSetHandler *boot_set_handler;
264 static void *boot_set_opaque;
266 #ifdef SIGRTMIN
267 #define SIG_IPI (SIGRTMIN+4)
268 #else
269 #define SIG_IPI SIGUSR1
270 #endif
272 static int default_serial = 1;
273 static int default_parallel = 1;
274 static int default_virtcon = 1;
275 static int default_monitor = 1;
276 static int default_vga = 1;
277 static int default_floppy = 1;
278 static int default_cdrom = 1;
279 static int default_sdcard = 1;
280 static int default_qmp = 1;
282 static struct {
283 const char *driver;
284 int *flag;
285 } default_list[] = {
286 { .driver = "isa-serial", .flag = &default_serial },
287 { .driver = "isa-parallel", .flag = &default_parallel },
288 { .driver = "isa-fdc", .flag = &default_floppy },
289 { .driver = "ide-drive", .flag = &default_cdrom },
290 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
291 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
292 { .driver = "virtio-serial", .flag = &default_virtcon },
293 { .driver = "VGA", .flag = &default_vga },
294 { .driver = "cirrus-vga", .flag = &default_vga },
295 { .driver = "vmware-svga", .flag = &default_vga },
298 static int default_driver_check(QemuOpts *opts, void *opaque)
300 const char *driver = qemu_opt_get(opts, "driver");
301 int i;
303 if (!driver)
304 return 0;
305 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
306 if (strcmp(default_list[i].driver, driver) != 0)
307 continue;
308 *(default_list[i].flag) = 0;
310 return 0;
313 /***********************************************************/
314 /* x86 ISA bus support */
316 target_phys_addr_t isa_mem_base = 0;
317 PicState2 *isa_pic;
319 /***********************************************************/
320 void hw_error(const char *fmt, ...)
322 va_list ap;
323 CPUState *env;
325 va_start(ap, fmt);
326 fprintf(stderr, "qemu: hardware error: ");
327 vfprintf(stderr, fmt, ap);
328 fprintf(stderr, "\n");
329 for(env = first_cpu; env != NULL; env = env->next_cpu) {
330 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
331 #ifdef TARGET_I386
332 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
333 #else
334 cpu_dump_state(env, stderr, fprintf, 0);
335 #endif
337 va_end(ap);
338 abort();
341 static void set_proc_name(const char *s)
343 #if defined(__linux__) && defined(PR_SET_NAME)
344 char name[16];
345 if (!s)
346 return;
347 name[sizeof(name) - 1] = 0;
348 strncpy(name, s, sizeof(name));
349 /* Could rewrite argv[0] too, but that's a bit more complicated.
350 This simple way is enough for `top'. */
351 prctl(PR_SET_NAME, name);
352 #endif
355 /***************/
356 /* ballooning */
358 static QEMUBalloonEvent *qemu_balloon_event;
359 void *qemu_balloon_event_opaque;
361 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
363 qemu_balloon_event = func;
364 qemu_balloon_event_opaque = opaque;
367 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
369 if (qemu_balloon_event) {
370 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
371 return 1;
372 } else {
373 return 0;
377 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
379 if (qemu_balloon_event) {
380 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
381 return 1;
382 } else {
383 return 0;
388 /***********************************************************/
389 /* real time host monotonic timer */
391 /* compute with 96 bit intermediate result: (a*b)/c */
392 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
394 union {
395 uint64_t ll;
396 struct {
397 #ifdef HOST_WORDS_BIGENDIAN
398 uint32_t high, low;
399 #else
400 uint32_t low, high;
401 #endif
402 } l;
403 } u, res;
404 uint64_t rl, rh;
406 u.ll = a;
407 rl = (uint64_t)u.l.low * (uint64_t)b;
408 rh = (uint64_t)u.l.high * (uint64_t)b;
409 rh += (rl >> 32);
410 res.l.high = rh / c;
411 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
412 return res.ll;
415 /***********************************************************/
416 /* host time/date access */
417 void qemu_get_timedate(struct tm *tm, int offset)
419 time_t ti;
420 struct tm *ret;
422 time(&ti);
423 ti += offset;
424 if (rtc_date_offset == -1) {
425 if (rtc_utc)
426 ret = gmtime(&ti);
427 else
428 ret = localtime(&ti);
429 } else {
430 ti -= rtc_date_offset;
431 ret = gmtime(&ti);
434 memcpy(tm, ret, sizeof(struct tm));
437 int qemu_timedate_diff(struct tm *tm)
439 time_t seconds;
441 if (rtc_date_offset == -1)
442 if (rtc_utc)
443 seconds = mktimegm(tm);
444 else
445 seconds = mktime(tm);
446 else
447 seconds = mktimegm(tm) + rtc_date_offset;
449 return seconds - time(NULL);
452 void rtc_change_mon_event(struct tm *tm)
454 QObject *data;
456 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
457 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
458 qobject_decref(data);
461 static void configure_rtc_date_offset(const char *startdate, int legacy)
463 time_t rtc_start_date;
464 struct tm tm;
466 if (!strcmp(startdate, "now") && legacy) {
467 rtc_date_offset = -1;
468 } else {
469 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
470 &tm.tm_year,
471 &tm.tm_mon,
472 &tm.tm_mday,
473 &tm.tm_hour,
474 &tm.tm_min,
475 &tm.tm_sec) == 6) {
476 /* OK */
477 } else if (sscanf(startdate, "%d-%d-%d",
478 &tm.tm_year,
479 &tm.tm_mon,
480 &tm.tm_mday) == 3) {
481 tm.tm_hour = 0;
482 tm.tm_min = 0;
483 tm.tm_sec = 0;
484 } else {
485 goto date_fail;
487 tm.tm_year -= 1900;
488 tm.tm_mon--;
489 rtc_start_date = mktimegm(&tm);
490 if (rtc_start_date == -1) {
491 date_fail:
492 fprintf(stderr, "Invalid date format. Valid formats are:\n"
493 "'2006-06-17T16:01:21' or '2006-06-17'\n");
494 exit(1);
496 rtc_date_offset = time(NULL) - rtc_start_date;
500 static void configure_rtc(QemuOpts *opts)
502 const char *value;
504 value = qemu_opt_get(opts, "base");
505 if (value) {
506 if (!strcmp(value, "utc")) {
507 rtc_utc = 1;
508 } else if (!strcmp(value, "localtime")) {
509 rtc_utc = 0;
510 } else {
511 configure_rtc_date_offset(value, 0);
514 value = qemu_opt_get(opts, "clock");
515 if (value) {
516 if (!strcmp(value, "host")) {
517 rtc_clock = host_clock;
518 } else if (!strcmp(value, "vm")) {
519 rtc_clock = vm_clock;
520 } else {
521 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
522 exit(1);
525 #ifdef CONFIG_TARGET_I386
526 value = qemu_opt_get(opts, "driftfix");
527 if (value) {
528 if (!strcmp(buf, "slew")) {
529 rtc_td_hack = 1;
530 } else if (!strcmp(buf, "none")) {
531 rtc_td_hack = 0;
532 } else {
533 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
534 exit(1);
537 #endif
540 #ifdef _WIN32
541 static void socket_cleanup(Notifier *obj)
543 WSACleanup();
546 static int socket_init(void)
548 WSADATA Data;
549 int ret, err;
550 static Notifier notifier = { .notify = socket_cleanup };
552 ret = WSAStartup(MAKEWORD(2,2), &Data);
553 if (ret != 0) {
554 err = WSAGetLastError();
555 fprintf(stderr, "WSAStartup: %d\n", err);
556 return -1;
558 exit_notifier_add(&notifier);
559 return 0;
561 #endif
563 /*********************/
564 /* Exit notifiers */
565 /*********************/
567 static NotifierList exit_notifiers = NOTIFIER_LIST_INITIALIZER(exit_notifiers);
569 void exit_notifier_add(Notifier *notifier)
571 notifier_list_add(&exit_notifiers, notifier);
574 void exit_notifier_remove(Notifier *notifier)
576 notifier_list_remove(&exit_notifiers, notifier);
579 static void exit_notifier_notify(void)
581 notifier_list_notify(&exit_notifiers);
584 static void exit_notifier_init(void)
586 atexit(exit_notifier_notify);
589 /***********************************************************/
590 /* Bluetooth support */
591 static int nb_hcis;
592 static int cur_hci;
593 static struct HCIInfo *hci_table[MAX_NICS];
595 static struct bt_vlan_s {
596 struct bt_scatternet_s net;
597 int id;
598 struct bt_vlan_s *next;
599 } *first_bt_vlan;
601 /* find or alloc a new bluetooth "VLAN" */
602 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
604 struct bt_vlan_s **pvlan, *vlan;
605 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
606 if (vlan->id == id)
607 return &vlan->net;
609 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
610 vlan->id = id;
611 pvlan = &first_bt_vlan;
612 while (*pvlan != NULL)
613 pvlan = &(*pvlan)->next;
614 *pvlan = vlan;
615 return &vlan->net;
618 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
622 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
624 return -ENOTSUP;
627 static struct HCIInfo null_hci = {
628 .cmd_send = null_hci_send,
629 .sco_send = null_hci_send,
630 .acl_send = null_hci_send,
631 .bdaddr_set = null_hci_addr_set,
634 struct HCIInfo *qemu_next_hci(void)
636 if (cur_hci == nb_hcis)
637 return &null_hci;
639 return hci_table[cur_hci++];
642 static struct HCIInfo *hci_init(const char *str)
644 char *endp;
645 struct bt_scatternet_s *vlan = 0;
647 if (!strcmp(str, "null"))
648 /* null */
649 return &null_hci;
650 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
651 /* host[:hciN] */
652 return bt_host_hci(str[4] ? str + 5 : "hci0");
653 else if (!strncmp(str, "hci", 3)) {
654 /* hci[,vlan=n] */
655 if (str[3]) {
656 if (!strncmp(str + 3, ",vlan=", 6)) {
657 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
658 if (*endp)
659 vlan = 0;
661 } else
662 vlan = qemu_find_bt_vlan(0);
663 if (vlan)
664 return bt_new_hci(vlan);
667 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
669 return 0;
672 static int bt_hci_parse(const char *str)
674 struct HCIInfo *hci;
675 bdaddr_t bdaddr;
677 if (nb_hcis >= MAX_NICS) {
678 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
679 return -1;
682 hci = hci_init(str);
683 if (!hci)
684 return -1;
686 bdaddr.b[0] = 0x52;
687 bdaddr.b[1] = 0x54;
688 bdaddr.b[2] = 0x00;
689 bdaddr.b[3] = 0x12;
690 bdaddr.b[4] = 0x34;
691 bdaddr.b[5] = 0x56 + nb_hcis;
692 hci->bdaddr_set(hci, bdaddr.b);
694 hci_table[nb_hcis++] = hci;
696 return 0;
699 static void bt_vhci_add(int vlan_id)
701 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
703 if (!vlan->slave)
704 fprintf(stderr, "qemu: warning: adding a VHCI to "
705 "an empty scatternet %i\n", vlan_id);
707 bt_vhci_init(bt_new_hci(vlan));
710 static struct bt_device_s *bt_device_add(const char *opt)
712 struct bt_scatternet_s *vlan;
713 int vlan_id = 0;
714 char *endp = strstr(opt, ",vlan=");
715 int len = (endp ? endp - opt : strlen(opt)) + 1;
716 char devname[10];
718 pstrcpy(devname, MIN(sizeof(devname), len), opt);
720 if (endp) {
721 vlan_id = strtol(endp + 6, &endp, 0);
722 if (*endp) {
723 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
724 return 0;
728 vlan = qemu_find_bt_vlan(vlan_id);
730 if (!vlan->slave)
731 fprintf(stderr, "qemu: warning: adding a slave device to "
732 "an empty scatternet %i\n", vlan_id);
734 if (!strcmp(devname, "keyboard"))
735 return bt_keyboard_init(vlan);
737 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
738 return 0;
741 static int bt_parse(const char *opt)
743 const char *endp, *p;
744 int vlan;
746 if (strstart(opt, "hci", &endp)) {
747 if (!*endp || *endp == ',') {
748 if (*endp)
749 if (!strstart(endp, ",vlan=", 0))
750 opt = endp + 1;
752 return bt_hci_parse(opt);
754 } else if (strstart(opt, "vhci", &endp)) {
755 if (!*endp || *endp == ',') {
756 if (*endp) {
757 if (strstart(endp, ",vlan=", &p)) {
758 vlan = strtol(p, (char **) &endp, 0);
759 if (*endp) {
760 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
761 return 1;
763 } else {
764 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
765 return 1;
767 } else
768 vlan = 0;
770 bt_vhci_add(vlan);
771 return 0;
773 } else if (strstart(opt, "device:", &endp))
774 return !bt_device_add(endp);
776 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
777 return 1;
780 /***********************************************************/
781 /* QEMU Block devices */
783 #define HD_ALIAS "index=%d,media=disk"
784 #define CDROM_ALIAS "index=2,media=cdrom"
785 #define FD_ALIAS "index=%d,if=floppy"
786 #define PFLASH_ALIAS "if=pflash"
787 #define MTD_ALIAS "if=mtd"
788 #define SD_ALIAS "index=0,if=sd"
790 QemuOpts *drive_add(const char *file, const char *fmt, ...)
792 va_list ap;
793 char optstr[1024];
794 QemuOpts *opts;
796 va_start(ap, fmt);
797 vsnprintf(optstr, sizeof(optstr), fmt, ap);
798 va_end(ap);
800 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
801 if (!opts) {
802 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
803 __FUNCTION__, optstr);
804 return NULL;
806 if (file)
807 qemu_opt_set(opts, "file", file);
808 return opts;
811 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
813 DriveInfo *dinfo;
815 /* seek interface, bus and unit */
817 QTAILQ_FOREACH(dinfo, &drives, next) {
818 if (dinfo->type == type &&
819 dinfo->bus == bus &&
820 dinfo->unit == unit)
821 return dinfo;
824 return NULL;
827 DriveInfo *drive_get_by_id(const char *id)
829 DriveInfo *dinfo;
831 QTAILQ_FOREACH(dinfo, &drives, next) {
832 if (strcmp(id, dinfo->id))
833 continue;
834 return dinfo;
836 return NULL;
839 int drive_get_max_bus(BlockInterfaceType type)
841 int max_bus;
842 DriveInfo *dinfo;
844 max_bus = -1;
845 QTAILQ_FOREACH(dinfo, &drives, next) {
846 if(dinfo->type == type &&
847 dinfo->bus > max_bus)
848 max_bus = dinfo->bus;
850 return max_bus;
853 const char *drive_get_serial(BlockDriverState *bdrv)
855 DriveInfo *dinfo;
857 QTAILQ_FOREACH(dinfo, &drives, next) {
858 if (dinfo->bdrv == bdrv)
859 return dinfo->serial;
862 return "\0";
865 BlockInterfaceErrorAction drive_get_on_error(
866 BlockDriverState *bdrv, int is_read)
868 DriveInfo *dinfo;
870 QTAILQ_FOREACH(dinfo, &drives, next) {
871 if (dinfo->bdrv == bdrv)
872 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
875 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
878 static void bdrv_format_print(void *opaque, const char *name)
880 fprintf(stderr, " %s", name);
883 void drive_uninit(DriveInfo *dinfo)
885 qemu_opts_del(dinfo->opts);
886 bdrv_delete(dinfo->bdrv);
887 QTAILQ_REMOVE(&drives, dinfo, next);
888 qemu_free(dinfo);
891 static int parse_block_error_action(const char *buf, int is_read)
893 if (!strcmp(buf, "ignore")) {
894 return BLOCK_ERR_IGNORE;
895 } else if (!is_read && !strcmp(buf, "enospc")) {
896 return BLOCK_ERR_STOP_ENOSPC;
897 } else if (!strcmp(buf, "stop")) {
898 return BLOCK_ERR_STOP_ANY;
899 } else if (!strcmp(buf, "report")) {
900 return BLOCK_ERR_REPORT;
901 } else {
902 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
903 buf, is_read ? "read" : "write");
904 return -1;
908 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
909 int *fatal_error)
911 const char *buf;
912 const char *file = NULL;
913 char devname[128];
914 const char *serial;
915 const char *mediastr = "";
916 BlockInterfaceType type;
917 enum { MEDIA_DISK, MEDIA_CDROM } media;
918 int bus_id, unit_id;
919 int cyls, heads, secs, translation;
920 BlockDriver *drv = NULL;
921 QEMUMachine *machine = opaque;
922 int max_devs;
923 int index;
924 int cache;
925 int aio = 0;
926 int ro = 0;
927 int bdrv_flags;
928 int on_read_error, on_write_error;
929 const char *devaddr;
930 DriveInfo *dinfo;
931 int snapshot = 0;
933 *fatal_error = 1;
935 translation = BIOS_ATA_TRANSLATION_AUTO;
936 cache = 1;
938 if (machine && machine->use_scsi) {
939 type = IF_SCSI;
940 max_devs = MAX_SCSI_DEVS;
941 pstrcpy(devname, sizeof(devname), "scsi");
942 } else {
943 type = IF_IDE;
944 max_devs = MAX_IDE_DEVS;
945 pstrcpy(devname, sizeof(devname), "ide");
947 media = MEDIA_DISK;
949 /* extract parameters */
950 bus_id = qemu_opt_get_number(opts, "bus", 0);
951 unit_id = qemu_opt_get_number(opts, "unit", -1);
952 index = qemu_opt_get_number(opts, "index", -1);
954 cyls = qemu_opt_get_number(opts, "cyls", 0);
955 heads = qemu_opt_get_number(opts, "heads", 0);
956 secs = qemu_opt_get_number(opts, "secs", 0);
958 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
959 ro = qemu_opt_get_bool(opts, "readonly", 0);
961 file = qemu_opt_get(opts, "file");
962 serial = qemu_opt_get(opts, "serial");
964 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
965 pstrcpy(devname, sizeof(devname), buf);
966 if (!strcmp(buf, "ide")) {
967 type = IF_IDE;
968 max_devs = MAX_IDE_DEVS;
969 } else if (!strcmp(buf, "scsi")) {
970 type = IF_SCSI;
971 max_devs = MAX_SCSI_DEVS;
972 } else if (!strcmp(buf, "floppy")) {
973 type = IF_FLOPPY;
974 max_devs = 0;
975 } else if (!strcmp(buf, "pflash")) {
976 type = IF_PFLASH;
977 max_devs = 0;
978 } else if (!strcmp(buf, "mtd")) {
979 type = IF_MTD;
980 max_devs = 0;
981 } else if (!strcmp(buf, "sd")) {
982 type = IF_SD;
983 max_devs = 0;
984 } else if (!strcmp(buf, "virtio")) {
985 type = IF_VIRTIO;
986 max_devs = 0;
987 } else if (!strcmp(buf, "xen")) {
988 type = IF_XEN;
989 max_devs = 0;
990 } else if (!strcmp(buf, "none")) {
991 type = IF_NONE;
992 max_devs = 0;
993 } else {
994 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
995 return NULL;
999 if (cyls || heads || secs) {
1000 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
1001 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1002 return NULL;
1004 if (heads < 1 || (type == IF_IDE && heads > 16)) {
1005 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1006 return NULL;
1008 if (secs < 1 || (type == IF_IDE && secs > 63)) {
1009 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1010 return NULL;
1014 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1015 if (!cyls) {
1016 fprintf(stderr,
1017 "qemu: '%s' trans must be used with cyls,heads and secs\n",
1018 buf);
1019 return NULL;
1021 if (!strcmp(buf, "none"))
1022 translation = BIOS_ATA_TRANSLATION_NONE;
1023 else if (!strcmp(buf, "lba"))
1024 translation = BIOS_ATA_TRANSLATION_LBA;
1025 else if (!strcmp(buf, "auto"))
1026 translation = BIOS_ATA_TRANSLATION_AUTO;
1027 else {
1028 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
1029 return NULL;
1033 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
1034 if (!strcmp(buf, "disk")) {
1035 media = MEDIA_DISK;
1036 } else if (!strcmp(buf, "cdrom")) {
1037 if (cyls || secs || heads) {
1038 fprintf(stderr,
1039 "qemu: '%s' invalid physical CHS format\n", buf);
1040 return NULL;
1042 media = MEDIA_CDROM;
1043 } else {
1044 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
1045 return NULL;
1049 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
1050 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
1051 cache = 0;
1052 else if (!strcmp(buf, "writethrough"))
1053 cache = 1;
1054 else if (!strcmp(buf, "writeback"))
1055 cache = 2;
1056 else {
1057 fprintf(stderr, "qemu: invalid cache option\n");
1058 return NULL;
1062 #ifdef CONFIG_LINUX_AIO
1063 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1064 if (!strcmp(buf, "threads"))
1065 aio = 0;
1066 else if (!strcmp(buf, "native"))
1067 aio = 1;
1068 else {
1069 fprintf(stderr, "qemu: invalid aio option\n");
1070 return NULL;
1073 #endif
1075 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1076 if (strcmp(buf, "?") == 0) {
1077 fprintf(stderr, "qemu: Supported formats:");
1078 bdrv_iterate_format(bdrv_format_print, NULL);
1079 fprintf(stderr, "\n");
1080 return NULL;
1082 drv = bdrv_find_whitelisted_format(buf);
1083 if (!drv) {
1084 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1085 return NULL;
1089 on_write_error = BLOCK_ERR_STOP_ENOSPC;
1090 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1091 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1092 fprintf(stderr, "werror is no supported by this format\n");
1093 return NULL;
1096 on_write_error = parse_block_error_action(buf, 0);
1097 if (on_write_error < 0) {
1098 return NULL;
1102 on_read_error = BLOCK_ERR_REPORT;
1103 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1104 if (type != IF_IDE && type != IF_VIRTIO) {
1105 fprintf(stderr, "rerror is no supported by this format\n");
1106 return NULL;
1109 on_read_error = parse_block_error_action(buf, 1);
1110 if (on_read_error < 0) {
1111 return NULL;
1115 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1116 if (type != IF_VIRTIO) {
1117 fprintf(stderr, "addr is not supported\n");
1118 return NULL;
1122 /* compute bus and unit according index */
1124 if (index != -1) {
1125 if (bus_id != 0 || unit_id != -1) {
1126 fprintf(stderr,
1127 "qemu: index cannot be used with bus and unit\n");
1128 return NULL;
1130 if (max_devs == 0)
1132 unit_id = index;
1133 bus_id = 0;
1134 } else {
1135 unit_id = index % max_devs;
1136 bus_id = index / max_devs;
1140 /* if user doesn't specify a unit_id,
1141 * try to find the first free
1144 if (unit_id == -1) {
1145 unit_id = 0;
1146 while (drive_get(type, bus_id, unit_id) != NULL) {
1147 unit_id++;
1148 if (max_devs && unit_id >= max_devs) {
1149 unit_id -= max_devs;
1150 bus_id++;
1155 /* check unit id */
1157 if (max_devs && unit_id >= max_devs) {
1158 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1159 unit_id, max_devs - 1);
1160 return NULL;
1164 * ignore multiple definitions
1167 if (drive_get(type, bus_id, unit_id) != NULL) {
1168 *fatal_error = 0;
1169 return NULL;
1172 /* init */
1174 dinfo = qemu_mallocz(sizeof(*dinfo));
1175 if ((buf = qemu_opts_id(opts)) != NULL) {
1176 dinfo->id = qemu_strdup(buf);
1177 } else {
1178 /* no id supplied -> create one */
1179 dinfo->id = qemu_mallocz(32);
1180 if (type == IF_IDE || type == IF_SCSI)
1181 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1182 if (max_devs)
1183 snprintf(dinfo->id, 32, "%s%i%s%i",
1184 devname, bus_id, mediastr, unit_id);
1185 else
1186 snprintf(dinfo->id, 32, "%s%s%i",
1187 devname, mediastr, unit_id);
1189 dinfo->bdrv = bdrv_new(dinfo->id);
1190 dinfo->devaddr = devaddr;
1191 dinfo->type = type;
1192 dinfo->bus = bus_id;
1193 dinfo->unit = unit_id;
1194 dinfo->on_read_error = on_read_error;
1195 dinfo->on_write_error = on_write_error;
1196 dinfo->opts = opts;
1197 if (serial)
1198 strncpy(dinfo->serial, serial, sizeof(serial));
1199 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1201 switch(type) {
1202 case IF_IDE:
1203 case IF_SCSI:
1204 case IF_XEN:
1205 case IF_NONE:
1206 switch(media) {
1207 case MEDIA_DISK:
1208 if (cyls != 0) {
1209 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1210 bdrv_set_translation_hint(dinfo->bdrv, translation);
1212 break;
1213 case MEDIA_CDROM:
1214 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1215 break;
1217 break;
1218 case IF_SD:
1219 /* FIXME: This isn't really a floppy, but it's a reasonable
1220 approximation. */
1221 case IF_FLOPPY:
1222 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1223 break;
1224 case IF_PFLASH:
1225 case IF_MTD:
1226 break;
1227 case IF_VIRTIO:
1228 /* add virtio block device */
1229 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1230 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1231 qemu_opt_set(opts, "drive", dinfo->id);
1232 if (devaddr)
1233 qemu_opt_set(opts, "addr", devaddr);
1234 break;
1235 case IF_COUNT:
1236 abort();
1238 if (!file) {
1239 *fatal_error = 0;
1240 return NULL;
1242 bdrv_flags = 0;
1243 if (snapshot) {
1244 bdrv_flags |= BDRV_O_SNAPSHOT;
1245 cache = 2; /* always use write-back with snapshot */
1247 if (cache == 0) /* no caching */
1248 bdrv_flags |= BDRV_O_NOCACHE;
1249 else if (cache == 2) /* write-back */
1250 bdrv_flags |= BDRV_O_CACHE_WB;
1252 if (aio == 1) {
1253 bdrv_flags |= BDRV_O_NATIVE_AIO;
1254 } else {
1255 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1258 if (ro == 1) {
1259 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1260 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1261 return NULL;
1265 * cdrom is read-only. Set it now, after above interface checking
1266 * since readonly attribute not explicitly required, so no error.
1268 if (media == MEDIA_CDROM) {
1269 ro = 1;
1271 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1273 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1274 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1275 file, strerror(errno));
1276 return NULL;
1279 if (bdrv_key_required(dinfo->bdrv))
1280 autostart = 0;
1281 *fatal_error = 0;
1282 return dinfo;
1285 static int drive_init_func(QemuOpts *opts, void *opaque)
1287 QEMUMachine *machine = opaque;
1288 int fatal_error = 0;
1290 if (drive_init(opts, machine, &fatal_error) == NULL) {
1291 if (fatal_error)
1292 return 1;
1294 return 0;
1297 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1299 if (NULL == qemu_opt_get(opts, "snapshot")) {
1300 qemu_opt_set(opts, "snapshot", "on");
1302 return 0;
1305 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1307 boot_set_handler = func;
1308 boot_set_opaque = opaque;
1311 int qemu_boot_set(const char *boot_devices)
1313 if (!boot_set_handler) {
1314 return -EINVAL;
1316 return boot_set_handler(boot_set_opaque, boot_devices);
1319 static int parse_bootdevices(char *devices)
1321 /* We just do some generic consistency checks */
1322 const char *p;
1323 int bitmap = 0;
1325 for (p = devices; *p != '\0'; p++) {
1326 /* Allowed boot devices are:
1327 * a-b: floppy disk drives
1328 * c-f: IDE disk drives
1329 * g-m: machine implementation dependant drives
1330 * n-p: network devices
1331 * It's up to each machine implementation to check if the given boot
1332 * devices match the actual hardware implementation and firmware
1333 * features.
1335 if (*p < 'a' || *p > 'p') {
1336 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1337 exit(1);
1339 if (bitmap & (1 << (*p - 'a'))) {
1340 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1341 exit(1);
1343 bitmap |= 1 << (*p - 'a');
1345 return bitmap;
1348 static void restore_boot_devices(void *opaque)
1350 char *standard_boot_devices = opaque;
1352 qemu_boot_set(standard_boot_devices);
1354 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1355 qemu_free(standard_boot_devices);
1358 static void numa_add(const char *optarg)
1360 char option[128];
1361 char *endptr;
1362 unsigned long long value, endvalue;
1363 int nodenr;
1365 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1366 if (!strcmp(option, "node")) {
1367 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1368 nodenr = nb_numa_nodes;
1369 } else {
1370 nodenr = strtoull(option, NULL, 10);
1373 if (get_param_value(option, 128, "mem", optarg) == 0) {
1374 node_mem[nodenr] = 0;
1375 } else {
1376 value = strtoull(option, &endptr, 0);
1377 switch (*endptr) {
1378 case 0: case 'M': case 'm':
1379 value <<= 20;
1380 break;
1381 case 'G': case 'g':
1382 value <<= 30;
1383 break;
1385 node_mem[nodenr] = value;
1387 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1388 node_cpumask[nodenr] = 0;
1389 } else {
1390 value = strtoull(option, &endptr, 10);
1391 if (value >= 64) {
1392 value = 63;
1393 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1394 } else {
1395 if (*endptr == '-') {
1396 endvalue = strtoull(endptr+1, &endptr, 10);
1397 if (endvalue >= 63) {
1398 endvalue = 62;
1399 fprintf(stderr,
1400 "only 63 CPUs in NUMA mode supported.\n");
1402 value = (2ULL << endvalue) - (1ULL << value);
1403 } else {
1404 value = 1ULL << value;
1407 node_cpumask[nodenr] = value;
1409 nb_numa_nodes++;
1411 return;
1414 static void smp_parse(const char *optarg)
1416 int smp, sockets = 0, threads = 0, cores = 0;
1417 char *endptr;
1418 char option[128];
1420 smp = strtoul(optarg, &endptr, 10);
1421 if (endptr != optarg) {
1422 if (*endptr == ',') {
1423 endptr++;
1426 if (get_param_value(option, 128, "sockets", endptr) != 0)
1427 sockets = strtoull(option, NULL, 10);
1428 if (get_param_value(option, 128, "cores", endptr) != 0)
1429 cores = strtoull(option, NULL, 10);
1430 if (get_param_value(option, 128, "threads", endptr) != 0)
1431 threads = strtoull(option, NULL, 10);
1432 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1433 max_cpus = strtoull(option, NULL, 10);
1435 /* compute missing values, prefer sockets over cores over threads */
1436 if (smp == 0 || sockets == 0) {
1437 sockets = sockets > 0 ? sockets : 1;
1438 cores = cores > 0 ? cores : 1;
1439 threads = threads > 0 ? threads : 1;
1440 if (smp == 0) {
1441 smp = cores * threads * sockets;
1443 } else {
1444 if (cores == 0) {
1445 threads = threads > 0 ? threads : 1;
1446 cores = smp / (sockets * threads);
1447 } else {
1448 if (sockets) {
1449 threads = smp / (cores * sockets);
1453 smp_cpus = smp;
1454 smp_cores = cores > 0 ? cores : 1;
1455 smp_threads = threads > 0 ? threads : 1;
1456 if (max_cpus == 0)
1457 max_cpus = smp_cpus;
1460 /***********************************************************/
1461 /* USB devices */
1463 static int usb_device_add(const char *devname, int is_hotplug)
1465 const char *p;
1466 USBDevice *dev = NULL;
1468 if (!usb_enabled)
1469 return -1;
1471 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1472 dev = usbdevice_create(devname);
1473 if (dev)
1474 goto done;
1476 /* the other ones */
1477 if (strstart(devname, "host:", &p)) {
1478 dev = usb_host_device_open(p);
1479 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1480 dev = usb_bt_init(devname[2] ? hci_init(p) :
1481 bt_new_hci(qemu_find_bt_vlan(0)));
1482 } else {
1483 return -1;
1485 if (!dev)
1486 return -1;
1488 done:
1489 return 0;
1492 static int usb_device_del(const char *devname)
1494 int bus_num, addr;
1495 const char *p;
1497 if (strstart(devname, "host:", &p))
1498 return usb_host_device_close(p);
1500 if (!usb_enabled)
1501 return -1;
1503 p = strchr(devname, '.');
1504 if (!p)
1505 return -1;
1506 bus_num = strtoul(devname, NULL, 0);
1507 addr = strtoul(p + 1, NULL, 0);
1509 return usb_device_delete_addr(bus_num, addr);
1512 static int usb_parse(const char *cmdline)
1514 int r;
1515 r = usb_device_add(cmdline, 0);
1516 if (r < 0) {
1517 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1519 return r;
1522 void do_usb_add(Monitor *mon, const QDict *qdict)
1524 const char *devname = qdict_get_str(qdict, "devname");
1525 if (usb_device_add(devname, 1) < 0) {
1526 error_report("could not add USB device '%s'", devname);
1530 void do_usb_del(Monitor *mon, const QDict *qdict)
1532 const char *devname = qdict_get_str(qdict, "devname");
1533 if (usb_device_del(devname) < 0) {
1534 error_report("could not delete USB device '%s'", devname);
1538 /***********************************************************/
1539 /* PCMCIA/Cardbus */
1541 static struct pcmcia_socket_entry_s {
1542 PCMCIASocket *socket;
1543 struct pcmcia_socket_entry_s *next;
1544 } *pcmcia_sockets = 0;
1546 void pcmcia_socket_register(PCMCIASocket *socket)
1548 struct pcmcia_socket_entry_s *entry;
1550 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1551 entry->socket = socket;
1552 entry->next = pcmcia_sockets;
1553 pcmcia_sockets = entry;
1556 void pcmcia_socket_unregister(PCMCIASocket *socket)
1558 struct pcmcia_socket_entry_s *entry, **ptr;
1560 ptr = &pcmcia_sockets;
1561 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1562 if (entry->socket == socket) {
1563 *ptr = entry->next;
1564 qemu_free(entry);
1568 void pcmcia_info(Monitor *mon)
1570 struct pcmcia_socket_entry_s *iter;
1572 if (!pcmcia_sockets)
1573 monitor_printf(mon, "No PCMCIA sockets\n");
1575 for (iter = pcmcia_sockets; iter; iter = iter->next)
1576 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1577 iter->socket->attached ? iter->socket->card_string :
1578 "Empty");
1581 /***********************************************************/
1582 /* I/O handling */
1584 typedef struct IOHandlerRecord {
1585 int fd;
1586 IOCanReadHandler *fd_read_poll;
1587 IOHandler *fd_read;
1588 IOHandler *fd_write;
1589 int deleted;
1590 void *opaque;
1591 /* temporary data */
1592 struct pollfd *ufd;
1593 QLIST_ENTRY(IOHandlerRecord) next;
1594 } IOHandlerRecord;
1596 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1597 QLIST_HEAD_INITIALIZER(io_handlers);
1600 /* XXX: fd_read_poll should be suppressed, but an API change is
1601 necessary in the character devices to suppress fd_can_read(). */
1602 int qemu_set_fd_handler2(int fd,
1603 IOCanReadHandler *fd_read_poll,
1604 IOHandler *fd_read,
1605 IOHandler *fd_write,
1606 void *opaque)
1608 IOHandlerRecord *ioh;
1610 if (!fd_read && !fd_write) {
1611 QLIST_FOREACH(ioh, &io_handlers, next) {
1612 if (ioh->fd == fd) {
1613 ioh->deleted = 1;
1614 break;
1617 } else {
1618 QLIST_FOREACH(ioh, &io_handlers, next) {
1619 if (ioh->fd == fd)
1620 goto found;
1622 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1623 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1624 found:
1625 ioh->fd = fd;
1626 ioh->fd_read_poll = fd_read_poll;
1627 ioh->fd_read = fd_read;
1628 ioh->fd_write = fd_write;
1629 ioh->opaque = opaque;
1630 ioh->deleted = 0;
1632 return 0;
1635 int qemu_set_fd_handler(int fd,
1636 IOHandler *fd_read,
1637 IOHandler *fd_write,
1638 void *opaque)
1640 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1643 #ifdef _WIN32
1644 /***********************************************************/
1645 /* Polling handling */
1647 typedef struct PollingEntry {
1648 PollingFunc *func;
1649 void *opaque;
1650 struct PollingEntry *next;
1651 } PollingEntry;
1653 static PollingEntry *first_polling_entry;
1655 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1657 PollingEntry **ppe, *pe;
1658 pe = qemu_mallocz(sizeof(PollingEntry));
1659 pe->func = func;
1660 pe->opaque = opaque;
1661 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1662 *ppe = pe;
1663 return 0;
1666 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1668 PollingEntry **ppe, *pe;
1669 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1670 pe = *ppe;
1671 if (pe->func == func && pe->opaque == opaque) {
1672 *ppe = pe->next;
1673 qemu_free(pe);
1674 break;
1679 /***********************************************************/
1680 /* Wait objects support */
1681 typedef struct WaitObjects {
1682 int num;
1683 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1684 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1685 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1686 } WaitObjects;
1688 static WaitObjects wait_objects = {0};
1690 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1692 WaitObjects *w = &wait_objects;
1694 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1695 return -1;
1696 w->events[w->num] = handle;
1697 w->func[w->num] = func;
1698 w->opaque[w->num] = opaque;
1699 w->num++;
1700 return 0;
1703 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1705 int i, found;
1706 WaitObjects *w = &wait_objects;
1708 found = 0;
1709 for (i = 0; i < w->num; i++) {
1710 if (w->events[i] == handle)
1711 found = 1;
1712 if (found) {
1713 w->events[i] = w->events[i + 1];
1714 w->func[i] = w->func[i + 1];
1715 w->opaque[i] = w->opaque[i + 1];
1718 if (found)
1719 w->num--;
1721 #endif
1723 /***********************************************************/
1724 /* ram save/restore */
1726 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
1727 #define RAM_SAVE_FLAG_COMPRESS 0x02
1728 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
1729 #define RAM_SAVE_FLAG_PAGE 0x08
1730 #define RAM_SAVE_FLAG_EOS 0x10
1732 static int is_dup_page(uint8_t *page, uint8_t ch)
1734 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1735 uint32_t *array = (uint32_t *)page;
1736 int i;
1738 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1739 if (array[i] != val)
1740 return 0;
1743 return 1;
1746 static int ram_save_block(QEMUFile *f)
1748 static ram_addr_t current_addr = 0;
1749 ram_addr_t saved_addr = current_addr;
1750 ram_addr_t addr = 0;
1751 int found = 0;
1753 while (addr < last_ram_offset) {
1754 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1755 uint8_t *p;
1757 cpu_physical_memory_reset_dirty(current_addr,
1758 current_addr + TARGET_PAGE_SIZE,
1759 MIGRATION_DIRTY_FLAG);
1761 p = qemu_get_ram_ptr(current_addr);
1763 if (is_dup_page(p, *p)) {
1764 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1765 qemu_put_byte(f, *p);
1766 } else {
1767 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1768 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1771 found = 1;
1772 break;
1774 addr += TARGET_PAGE_SIZE;
1775 current_addr = (saved_addr + addr) % last_ram_offset;
1778 return found;
1781 static uint64_t bytes_transferred;
1783 static ram_addr_t ram_save_remaining(void)
1785 ram_addr_t addr;
1786 ram_addr_t count = 0;
1788 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1789 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1790 count++;
1793 return count;
1796 uint64_t ram_bytes_remaining(void)
1798 return ram_save_remaining() * TARGET_PAGE_SIZE;
1801 uint64_t ram_bytes_transferred(void)
1803 return bytes_transferred;
1806 uint64_t ram_bytes_total(void)
1808 return last_ram_offset;
1811 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1813 ram_addr_t addr;
1814 uint64_t bytes_transferred_last;
1815 double bwidth = 0;
1816 uint64_t expected_time = 0;
1818 if (stage < 0) {
1819 cpu_physical_memory_set_dirty_tracking(0);
1820 return 0;
1823 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1824 qemu_file_set_error(f);
1825 return 0;
1828 if (stage == 1) {
1829 bytes_transferred = 0;
1831 /* Make sure all dirty bits are set */
1832 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1833 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1834 cpu_physical_memory_set_dirty(addr);
1837 /* Enable dirty memory tracking */
1838 cpu_physical_memory_set_dirty_tracking(1);
1840 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1843 bytes_transferred_last = bytes_transferred;
1844 bwidth = qemu_get_clock_ns(rt_clock);
1846 while (!qemu_file_rate_limit(f)) {
1847 int ret;
1849 ret = ram_save_block(f);
1850 bytes_transferred += ret * TARGET_PAGE_SIZE;
1851 if (ret == 0) /* no more blocks */
1852 break;
1855 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1856 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1858 /* if we haven't transferred anything this round, force expected_time to a
1859 * a very high value, but without crashing */
1860 if (bwidth == 0)
1861 bwidth = 0.000001;
1863 /* try transferring iterative blocks of memory */
1864 if (stage == 3) {
1865 /* flush all remaining blocks regardless of rate limiting */
1866 while (ram_save_block(f) != 0) {
1867 bytes_transferred += TARGET_PAGE_SIZE;
1869 cpu_physical_memory_set_dirty_tracking(0);
1872 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1874 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1876 return (stage == 2) && (expected_time <= migrate_max_downtime());
1879 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1881 ram_addr_t addr;
1882 int flags;
1884 if (version_id != 3)
1885 return -EINVAL;
1887 do {
1888 addr = qemu_get_be64(f);
1890 flags = addr & ~TARGET_PAGE_MASK;
1891 addr &= TARGET_PAGE_MASK;
1893 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1894 if (addr != last_ram_offset)
1895 return -EINVAL;
1898 if (flags & RAM_SAVE_FLAG_COMPRESS) {
1899 uint8_t ch = qemu_get_byte(f);
1900 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1901 #ifndef _WIN32
1902 if (ch == 0 &&
1903 (!kvm_enabled() || kvm_has_sync_mmu())) {
1904 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1906 #endif
1907 } else if (flags & RAM_SAVE_FLAG_PAGE) {
1908 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1910 if (qemu_file_has_error(f)) {
1911 return -EIO;
1913 } while (!(flags & RAM_SAVE_FLAG_EOS));
1915 return 0;
1918 void qemu_service_io(void)
1920 qemu_notify_event();
1923 /***********************************************************/
1924 /* machine registration */
1926 static QEMUMachine *first_machine = NULL;
1927 QEMUMachine *current_machine = NULL;
1929 int qemu_register_machine(QEMUMachine *m)
1931 QEMUMachine **pm;
1932 pm = &first_machine;
1933 while (*pm != NULL)
1934 pm = &(*pm)->next;
1935 m->next = NULL;
1936 *pm = m;
1937 return 0;
1940 static QEMUMachine *find_machine(const char *name)
1942 QEMUMachine *m;
1944 for(m = first_machine; m != NULL; m = m->next) {
1945 if (!strcmp(m->name, name))
1946 return m;
1947 if (m->alias && !strcmp(m->alias, name))
1948 return m;
1950 return NULL;
1953 static QEMUMachine *find_default_machine(void)
1955 QEMUMachine *m;
1957 for(m = first_machine; m != NULL; m = m->next) {
1958 if (m->is_default) {
1959 return m;
1962 return NULL;
1965 /***********************************************************/
1966 /* main execution loop */
1968 static void gui_update(void *opaque)
1970 uint64_t interval = GUI_REFRESH_INTERVAL;
1971 DisplayState *ds = opaque;
1972 DisplayChangeListener *dcl = ds->listeners;
1974 qemu_flush_coalesced_mmio_buffer();
1975 dpy_refresh(ds);
1977 while (dcl != NULL) {
1978 if (dcl->gui_timer_interval &&
1979 dcl->gui_timer_interval < interval)
1980 interval = dcl->gui_timer_interval;
1981 dcl = dcl->next;
1983 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1986 static void nographic_update(void *opaque)
1988 uint64_t interval = GUI_REFRESH_INTERVAL;
1990 qemu_flush_coalesced_mmio_buffer();
1991 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1994 void cpu_synchronize_all_states(void)
1996 CPUState *cpu;
1998 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1999 cpu_synchronize_state(cpu);
2003 void cpu_synchronize_all_post_reset(void)
2005 CPUState *cpu;
2007 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2008 cpu_synchronize_post_reset(cpu);
2012 void cpu_synchronize_all_post_init(void)
2014 CPUState *cpu;
2016 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2017 cpu_synchronize_post_init(cpu);
2021 struct vm_change_state_entry {
2022 VMChangeStateHandler *cb;
2023 void *opaque;
2024 QLIST_ENTRY (vm_change_state_entry) entries;
2027 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
2029 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
2030 void *opaque)
2032 VMChangeStateEntry *e;
2034 e = qemu_mallocz(sizeof (*e));
2036 e->cb = cb;
2037 e->opaque = opaque;
2038 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
2039 return e;
2042 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
2044 QLIST_REMOVE (e, entries);
2045 qemu_free (e);
2048 static void vm_state_notify(int running, int reason)
2050 VMChangeStateEntry *e;
2052 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
2053 e->cb(e->opaque, running, reason);
2057 static void resume_all_vcpus(void);
2058 static void pause_all_vcpus(void);
2060 void vm_start(void)
2062 if (!vm_running) {
2063 cpu_enable_ticks();
2064 vm_running = 1;
2065 vm_state_notify(1, 0);
2066 resume_all_vcpus();
2070 /* reset/shutdown handler */
2072 typedef struct QEMUResetEntry {
2073 QTAILQ_ENTRY(QEMUResetEntry) entry;
2074 QEMUResetHandler *func;
2075 void *opaque;
2076 } QEMUResetEntry;
2078 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
2079 QTAILQ_HEAD_INITIALIZER(reset_handlers);
2080 static int reset_requested;
2081 static int shutdown_requested;
2082 static int powerdown_requested;
2083 static int debug_requested;
2084 static int vmstop_requested;
2086 int qemu_shutdown_requested(void)
2088 int r = shutdown_requested;
2089 shutdown_requested = 0;
2090 return r;
2093 int qemu_reset_requested(void)
2095 int r = reset_requested;
2096 reset_requested = 0;
2097 return r;
2100 int qemu_powerdown_requested(void)
2102 int r = powerdown_requested;
2103 powerdown_requested = 0;
2104 return r;
2107 static int qemu_debug_requested(void)
2109 int r = debug_requested;
2110 debug_requested = 0;
2111 return r;
2114 static int qemu_vmstop_requested(void)
2116 int r = vmstop_requested;
2117 vmstop_requested = 0;
2118 return r;
2121 static void do_vm_stop(int reason)
2123 if (vm_running) {
2124 cpu_disable_ticks();
2125 vm_running = 0;
2126 pause_all_vcpus();
2127 vm_state_notify(0, reason);
2128 monitor_protocol_event(QEVENT_STOP, NULL);
2132 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2134 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2136 re->func = func;
2137 re->opaque = opaque;
2138 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2141 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2143 QEMUResetEntry *re;
2145 QTAILQ_FOREACH(re, &reset_handlers, entry) {
2146 if (re->func == func && re->opaque == opaque) {
2147 QTAILQ_REMOVE(&reset_handlers, re, entry);
2148 qemu_free(re);
2149 return;
2154 void qemu_system_reset(void)
2156 QEMUResetEntry *re, *nre;
2158 /* reset all devices */
2159 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2160 re->func(re->opaque);
2162 monitor_protocol_event(QEVENT_RESET, NULL);
2163 cpu_synchronize_all_post_reset();
2166 void qemu_system_reset_request(void)
2168 if (no_reboot) {
2169 shutdown_requested = 1;
2170 } else {
2171 reset_requested = 1;
2173 qemu_notify_event();
2176 void qemu_system_shutdown_request(void)
2178 shutdown_requested = 1;
2179 qemu_notify_event();
2182 void qemu_system_powerdown_request(void)
2184 powerdown_requested = 1;
2185 qemu_notify_event();
2188 static int cpu_can_run(CPUState *env)
2190 if (env->stop)
2191 return 0;
2192 if (env->stopped)
2193 return 0;
2194 if (!vm_running)
2195 return 0;
2196 return 1;
2199 static int cpu_has_work(CPUState *env)
2201 if (env->stop)
2202 return 1;
2203 if (env->stopped)
2204 return 0;
2205 if (!env->halted)
2206 return 1;
2207 if (qemu_cpu_has_work(env))
2208 return 1;
2209 return 0;
2212 static int tcg_has_work(void)
2214 CPUState *env;
2216 for (env = first_cpu; env != NULL; env = env->next_cpu)
2217 if (cpu_has_work(env))
2218 return 1;
2219 return 0;
2222 #ifndef _WIN32
2223 static int io_thread_fd = -1;
2225 static void qemu_event_increment(void)
2227 /* Write 8 bytes to be compatible with eventfd. */
2228 static uint64_t val = 1;
2229 ssize_t ret;
2231 if (io_thread_fd == -1)
2232 return;
2234 do {
2235 ret = write(io_thread_fd, &val, sizeof(val));
2236 } while (ret < 0 && errno == EINTR);
2238 /* EAGAIN is fine, a read must be pending. */
2239 if (ret < 0 && errno != EAGAIN) {
2240 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
2241 strerror(errno));
2242 exit (1);
2246 static void qemu_event_read(void *opaque)
2248 int fd = (unsigned long)opaque;
2249 ssize_t len;
2250 char buffer[512];
2252 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
2253 do {
2254 len = read(fd, buffer, sizeof(buffer));
2255 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
2258 static int qemu_event_init(void)
2260 int err;
2261 int fds[2];
2263 err = qemu_eventfd(fds);
2264 if (err == -1)
2265 return -errno;
2267 err = fcntl_setfl(fds[0], O_NONBLOCK);
2268 if (err < 0)
2269 goto fail;
2271 err = fcntl_setfl(fds[1], O_NONBLOCK);
2272 if (err < 0)
2273 goto fail;
2275 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
2276 (void *)(unsigned long)fds[0]);
2278 io_thread_fd = fds[1];
2279 return 0;
2281 fail:
2282 close(fds[0]);
2283 close(fds[1]);
2284 return err;
2286 #else
2287 HANDLE qemu_event_handle;
2289 static void dummy_event_handler(void *opaque)
2293 static int qemu_event_init(void)
2295 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
2296 if (!qemu_event_handle) {
2297 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
2298 return -1;
2300 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
2301 return 0;
2304 static void qemu_event_increment(void)
2306 if (!SetEvent(qemu_event_handle)) {
2307 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
2308 GetLastError());
2309 exit (1);
2312 #endif
2314 #ifndef CONFIG_IOTHREAD
2315 static int qemu_init_main_loop(void)
2317 return qemu_event_init();
2320 void qemu_init_vcpu(void *_env)
2322 CPUState *env = _env;
2324 env->nr_cores = smp_cores;
2325 env->nr_threads = smp_threads;
2326 if (kvm_enabled())
2327 kvm_init_vcpu(env);
2328 return;
2331 int qemu_cpu_self(void *env)
2333 return 1;
2336 static void resume_all_vcpus(void)
2340 static void pause_all_vcpus(void)
2344 void qemu_cpu_kick(void *env)
2346 return;
2349 void qemu_notify_event(void)
2351 CPUState *env = cpu_single_env;
2353 qemu_event_increment ();
2354 if (env) {
2355 cpu_exit(env);
2357 if (next_cpu && env != next_cpu) {
2358 cpu_exit(next_cpu);
2362 void qemu_mutex_lock_iothread(void) {}
2363 void qemu_mutex_unlock_iothread(void) {}
2365 void vm_stop(int reason)
2367 do_vm_stop(reason);
2370 #else /* CONFIG_IOTHREAD */
2372 #include "qemu-thread.h"
2374 QemuMutex qemu_global_mutex;
2375 static QemuMutex qemu_fair_mutex;
2377 static QemuThread io_thread;
2379 static QemuThread *tcg_cpu_thread;
2380 static QemuCond *tcg_halt_cond;
2382 static int qemu_system_ready;
2383 /* cpu creation */
2384 static QemuCond qemu_cpu_cond;
2385 /* system init */
2386 static QemuCond qemu_system_cond;
2387 static QemuCond qemu_pause_cond;
2389 static void tcg_block_io_signals(void);
2390 static void kvm_block_io_signals(CPUState *env);
2391 static void unblock_io_signals(void);
2393 static int qemu_init_main_loop(void)
2395 int ret;
2397 ret = qemu_event_init();
2398 if (ret)
2399 return ret;
2401 qemu_cond_init(&qemu_pause_cond);
2402 qemu_mutex_init(&qemu_fair_mutex);
2403 qemu_mutex_init(&qemu_global_mutex);
2404 qemu_mutex_lock(&qemu_global_mutex);
2406 unblock_io_signals();
2407 qemu_thread_self(&io_thread);
2409 return 0;
2412 static void qemu_wait_io_event_common(CPUState *env)
2414 if (env->stop) {
2415 env->stop = 0;
2416 env->stopped = 1;
2417 qemu_cond_signal(&qemu_pause_cond);
2421 static void qemu_wait_io_event(CPUState *env)
2423 while (!tcg_has_work())
2424 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2426 qemu_mutex_unlock(&qemu_global_mutex);
2429 * Users of qemu_global_mutex can be starved, having no chance
2430 * to acquire it since this path will get to it first.
2431 * So use another lock to provide fairness.
2433 qemu_mutex_lock(&qemu_fair_mutex);
2434 qemu_mutex_unlock(&qemu_fair_mutex);
2436 qemu_mutex_lock(&qemu_global_mutex);
2437 qemu_wait_io_event_common(env);
2440 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
2442 struct timespec ts;
2443 int r, e;
2444 siginfo_t siginfo;
2445 sigset_t waitset;
2447 ts.tv_sec = timeout / 1000;
2448 ts.tv_nsec = (timeout % 1000) * 1000000;
2450 sigemptyset(&waitset);
2451 sigaddset(&waitset, SIG_IPI);
2453 qemu_mutex_unlock(&qemu_global_mutex);
2454 r = sigtimedwait(&waitset, &siginfo, &ts);
2455 e = errno;
2456 qemu_mutex_lock(&qemu_global_mutex);
2458 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
2459 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
2460 exit(1);
2464 static void qemu_kvm_wait_io_event(CPUState *env)
2466 while (!cpu_has_work(env))
2467 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2469 qemu_kvm_eat_signal(env, 0);
2470 qemu_wait_io_event_common(env);
2473 static int qemu_cpu_exec(CPUState *env);
2475 static void *kvm_cpu_thread_fn(void *arg)
2477 CPUState *env = arg;
2479 qemu_thread_self(env->thread);
2480 if (kvm_enabled())
2481 kvm_init_vcpu(env);
2483 kvm_block_io_signals(env);
2485 /* signal CPU creation */
2486 qemu_mutex_lock(&qemu_global_mutex);
2487 env->created = 1;
2488 qemu_cond_signal(&qemu_cpu_cond);
2490 /* and wait for machine initialization */
2491 while (!qemu_system_ready)
2492 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2494 while (1) {
2495 if (cpu_can_run(env))
2496 qemu_cpu_exec(env);
2497 qemu_kvm_wait_io_event(env);
2500 return NULL;
2503 static bool tcg_cpu_exec(void);
2505 static void *tcg_cpu_thread_fn(void *arg)
2507 CPUState *env = arg;
2509 tcg_block_io_signals();
2510 qemu_thread_self(env->thread);
2512 /* signal CPU creation */
2513 qemu_mutex_lock(&qemu_global_mutex);
2514 for (env = first_cpu; env != NULL; env = env->next_cpu)
2515 env->created = 1;
2516 qemu_cond_signal(&qemu_cpu_cond);
2518 /* and wait for machine initialization */
2519 while (!qemu_system_ready)
2520 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2522 while (1) {
2523 tcg_cpu_exec();
2524 qemu_wait_io_event(cur_cpu);
2527 return NULL;
2530 void qemu_cpu_kick(void *_env)
2532 CPUState *env = _env;
2533 qemu_cond_broadcast(env->halt_cond);
2534 if (kvm_enabled())
2535 qemu_thread_signal(env->thread, SIG_IPI);
2538 int qemu_cpu_self(void *_env)
2540 CPUState *env = _env;
2541 QemuThread this;
2543 qemu_thread_self(&this);
2545 return qemu_thread_equal(&this, env->thread);
2548 static void cpu_signal(int sig)
2550 if (cpu_single_env)
2551 cpu_exit(cpu_single_env);
2554 static void tcg_block_io_signals(void)
2556 sigset_t set;
2557 struct sigaction sigact;
2559 sigemptyset(&set);
2560 sigaddset(&set, SIGUSR2);
2561 sigaddset(&set, SIGIO);
2562 sigaddset(&set, SIGALRM);
2563 sigaddset(&set, SIGCHLD);
2564 pthread_sigmask(SIG_BLOCK, &set, NULL);
2566 sigemptyset(&set);
2567 sigaddset(&set, SIG_IPI);
2568 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2570 memset(&sigact, 0, sizeof(sigact));
2571 sigact.sa_handler = cpu_signal;
2572 sigaction(SIG_IPI, &sigact, NULL);
2575 static void dummy_signal(int sig)
2579 static void kvm_block_io_signals(CPUState *env)
2581 int r;
2582 sigset_t set;
2583 struct sigaction sigact;
2585 sigemptyset(&set);
2586 sigaddset(&set, SIGUSR2);
2587 sigaddset(&set, SIGIO);
2588 sigaddset(&set, SIGALRM);
2589 sigaddset(&set, SIGCHLD);
2590 sigaddset(&set, SIG_IPI);
2591 pthread_sigmask(SIG_BLOCK, &set, NULL);
2593 pthread_sigmask(SIG_BLOCK, NULL, &set);
2594 sigdelset(&set, SIG_IPI);
2596 memset(&sigact, 0, sizeof(sigact));
2597 sigact.sa_handler = dummy_signal;
2598 sigaction(SIG_IPI, &sigact, NULL);
2600 r = kvm_set_signal_mask(env, &set);
2601 if (r) {
2602 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
2603 exit(1);
2607 static void unblock_io_signals(void)
2609 sigset_t set;
2611 sigemptyset(&set);
2612 sigaddset(&set, SIGUSR2);
2613 sigaddset(&set, SIGIO);
2614 sigaddset(&set, SIGALRM);
2615 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2617 sigemptyset(&set);
2618 sigaddset(&set, SIG_IPI);
2619 pthread_sigmask(SIG_BLOCK, &set, NULL);
2622 static void qemu_signal_lock(unsigned int msecs)
2624 qemu_mutex_lock(&qemu_fair_mutex);
2626 while (qemu_mutex_trylock(&qemu_global_mutex)) {
2627 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
2628 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
2629 break;
2631 qemu_mutex_unlock(&qemu_fair_mutex);
2634 void qemu_mutex_lock_iothread(void)
2636 if (kvm_enabled()) {
2637 qemu_mutex_lock(&qemu_fair_mutex);
2638 qemu_mutex_lock(&qemu_global_mutex);
2639 qemu_mutex_unlock(&qemu_fair_mutex);
2640 } else
2641 qemu_signal_lock(100);
2644 void qemu_mutex_unlock_iothread(void)
2646 qemu_mutex_unlock(&qemu_global_mutex);
2649 static int all_vcpus_paused(void)
2651 CPUState *penv = first_cpu;
2653 while (penv) {
2654 if (!penv->stopped)
2655 return 0;
2656 penv = (CPUState *)penv->next_cpu;
2659 return 1;
2662 static void pause_all_vcpus(void)
2664 CPUState *penv = first_cpu;
2666 while (penv) {
2667 penv->stop = 1;
2668 qemu_thread_signal(penv->thread, SIG_IPI);
2669 qemu_cpu_kick(penv);
2670 penv = (CPUState *)penv->next_cpu;
2673 while (!all_vcpus_paused()) {
2674 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
2675 penv = first_cpu;
2676 while (penv) {
2677 qemu_thread_signal(penv->thread, SIG_IPI);
2678 penv = (CPUState *)penv->next_cpu;
2683 static void resume_all_vcpus(void)
2685 CPUState *penv = first_cpu;
2687 while (penv) {
2688 penv->stop = 0;
2689 penv->stopped = 0;
2690 qemu_thread_signal(penv->thread, SIG_IPI);
2691 qemu_cpu_kick(penv);
2692 penv = (CPUState *)penv->next_cpu;
2696 static void tcg_init_vcpu(void *_env)
2698 CPUState *env = _env;
2699 /* share a single thread for all cpus with TCG */
2700 if (!tcg_cpu_thread) {
2701 env->thread = qemu_mallocz(sizeof(QemuThread));
2702 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2703 qemu_cond_init(env->halt_cond);
2704 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
2705 while (env->created == 0)
2706 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2707 tcg_cpu_thread = env->thread;
2708 tcg_halt_cond = env->halt_cond;
2709 } else {
2710 env->thread = tcg_cpu_thread;
2711 env->halt_cond = tcg_halt_cond;
2715 static void kvm_start_vcpu(CPUState *env)
2717 env->thread = qemu_mallocz(sizeof(QemuThread));
2718 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2719 qemu_cond_init(env->halt_cond);
2720 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
2721 while (env->created == 0)
2722 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2725 void qemu_init_vcpu(void *_env)
2727 CPUState *env = _env;
2729 env->nr_cores = smp_cores;
2730 env->nr_threads = smp_threads;
2731 if (kvm_enabled())
2732 kvm_start_vcpu(env);
2733 else
2734 tcg_init_vcpu(env);
2737 void qemu_notify_event(void)
2739 qemu_event_increment();
2742 static void qemu_system_vmstop_request(int reason)
2744 vmstop_requested = reason;
2745 qemu_notify_event();
2748 void vm_stop(int reason)
2750 QemuThread me;
2751 qemu_thread_self(&me);
2753 if (!qemu_thread_equal(&me, &io_thread)) {
2754 qemu_system_vmstop_request(reason);
2756 * FIXME: should not return to device code in case
2757 * vm_stop() has been requested.
2759 if (cpu_single_env) {
2760 cpu_exit(cpu_single_env);
2761 cpu_single_env->stop = 1;
2763 return;
2765 do_vm_stop(reason);
2768 #endif
2771 #ifdef _WIN32
2772 static void host_main_loop_wait(int *timeout)
2774 int ret, ret2, i;
2775 PollingEntry *pe;
2778 /* XXX: need to suppress polling by better using win32 events */
2779 ret = 0;
2780 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2781 ret |= pe->func(pe->opaque);
2783 if (ret == 0) {
2784 int err;
2785 WaitObjects *w = &wait_objects;
2787 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2788 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2789 if (w->func[ret - WAIT_OBJECT_0])
2790 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2792 /* Check for additional signaled events */
2793 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2795 /* Check if event is signaled */
2796 ret2 = WaitForSingleObject(w->events[i], 0);
2797 if(ret2 == WAIT_OBJECT_0) {
2798 if (w->func[i])
2799 w->func[i](w->opaque[i]);
2800 } else if (ret2 == WAIT_TIMEOUT) {
2801 } else {
2802 err = GetLastError();
2803 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2806 } else if (ret == WAIT_TIMEOUT) {
2807 } else {
2808 err = GetLastError();
2809 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2813 *timeout = 0;
2815 #else
2816 static void host_main_loop_wait(int *timeout)
2819 #endif
2821 void main_loop_wait(int nonblocking)
2823 IOHandlerRecord *ioh;
2824 fd_set rfds, wfds, xfds;
2825 int ret, nfds;
2826 struct timeval tv;
2827 int timeout;
2829 if (nonblocking)
2830 timeout = 0;
2831 else {
2832 timeout = qemu_calculate_timeout();
2833 qemu_bh_update_timeout(&timeout);
2836 host_main_loop_wait(&timeout);
2838 /* poll any events */
2839 /* XXX: separate device handlers from system ones */
2840 nfds = -1;
2841 FD_ZERO(&rfds);
2842 FD_ZERO(&wfds);
2843 FD_ZERO(&xfds);
2844 QLIST_FOREACH(ioh, &io_handlers, next) {
2845 if (ioh->deleted)
2846 continue;
2847 if (ioh->fd_read &&
2848 (!ioh->fd_read_poll ||
2849 ioh->fd_read_poll(ioh->opaque) != 0)) {
2850 FD_SET(ioh->fd, &rfds);
2851 if (ioh->fd > nfds)
2852 nfds = ioh->fd;
2854 if (ioh->fd_write) {
2855 FD_SET(ioh->fd, &wfds);
2856 if (ioh->fd > nfds)
2857 nfds = ioh->fd;
2861 tv.tv_sec = timeout / 1000;
2862 tv.tv_usec = (timeout % 1000) * 1000;
2864 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2866 qemu_mutex_unlock_iothread();
2867 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2868 qemu_mutex_lock_iothread();
2869 if (ret > 0) {
2870 IOHandlerRecord *pioh;
2872 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
2873 if (ioh->deleted) {
2874 QLIST_REMOVE(ioh, next);
2875 qemu_free(ioh);
2876 continue;
2878 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2879 ioh->fd_read(ioh->opaque);
2881 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2882 ioh->fd_write(ioh->opaque);
2887 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2889 qemu_run_all_timers();
2891 /* Check bottom-halves last in case any of the earlier events triggered
2892 them. */
2893 qemu_bh_poll();
2897 static int qemu_cpu_exec(CPUState *env)
2899 int ret;
2900 #ifdef CONFIG_PROFILER
2901 int64_t ti;
2902 #endif
2904 #ifdef CONFIG_PROFILER
2905 ti = profile_getclock();
2906 #endif
2907 if (use_icount) {
2908 int64_t count;
2909 int decr;
2910 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
2911 env->icount_decr.u16.low = 0;
2912 env->icount_extra = 0;
2913 count = qemu_icount_round (qemu_next_deadline());
2914 qemu_icount += count;
2915 decr = (count > 0xffff) ? 0xffff : count;
2916 count -= decr;
2917 env->icount_decr.u16.low = decr;
2918 env->icount_extra = count;
2920 ret = cpu_exec(env);
2921 #ifdef CONFIG_PROFILER
2922 qemu_time += profile_getclock() - ti;
2923 #endif
2924 if (use_icount) {
2925 /* Fold pending instructions back into the
2926 instruction counter, and clear the interrupt flag. */
2927 qemu_icount -= (env->icount_decr.u16.low
2928 + env->icount_extra);
2929 env->icount_decr.u32 = 0;
2930 env->icount_extra = 0;
2932 return ret;
2935 static bool tcg_cpu_exec(void)
2937 int ret = 0;
2939 if (next_cpu == NULL)
2940 next_cpu = first_cpu;
2941 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
2942 CPUState *env = cur_cpu = next_cpu;
2944 qemu_clock_enable(vm_clock,
2945 (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
2947 if (qemu_alarm_pending())
2948 break;
2949 if (cpu_can_run(env))
2950 ret = qemu_cpu_exec(env);
2951 else if (env->stop)
2952 break;
2954 if (ret == EXCP_DEBUG) {
2955 gdb_set_stop_cpu(env);
2956 debug_requested = 1;
2957 break;
2960 return tcg_has_work();
2963 static int vm_can_run(void)
2965 if (powerdown_requested)
2966 return 0;
2967 if (reset_requested)
2968 return 0;
2969 if (shutdown_requested)
2970 return 0;
2971 if (debug_requested)
2972 return 0;
2973 return 1;
2976 qemu_irq qemu_system_powerdown;
2978 static void main_loop(void)
2980 int r;
2982 #ifdef CONFIG_IOTHREAD
2983 qemu_system_ready = 1;
2984 qemu_cond_broadcast(&qemu_system_cond);
2985 #endif
2987 for (;;) {
2988 do {
2989 bool nonblocking = false;
2990 #ifdef CONFIG_PROFILER
2991 int64_t ti;
2992 #endif
2993 #ifndef CONFIG_IOTHREAD
2994 nonblocking = tcg_cpu_exec();
2995 #endif
2996 #ifdef CONFIG_PROFILER
2997 ti = profile_getclock();
2998 #endif
2999 main_loop_wait(nonblocking);
3000 #ifdef CONFIG_PROFILER
3001 dev_time += profile_getclock() - ti;
3002 #endif
3003 } while (vm_can_run());
3005 if (qemu_debug_requested()) {
3006 vm_stop(EXCP_DEBUG);
3008 if (qemu_shutdown_requested()) {
3009 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
3010 if (no_shutdown) {
3011 vm_stop(0);
3012 no_shutdown = 0;
3013 } else
3014 break;
3016 if (qemu_reset_requested()) {
3017 pause_all_vcpus();
3018 qemu_system_reset();
3019 resume_all_vcpus();
3021 if (qemu_powerdown_requested()) {
3022 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
3023 qemu_irq_raise(qemu_system_powerdown);
3025 if ((r = qemu_vmstop_requested())) {
3026 vm_stop(r);
3029 pause_all_vcpus();
3032 static void version(void)
3034 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3037 static void help(int exitcode)
3039 const char *options_help =
3040 #define DEF(option, opt_arg, opt_enum, opt_help) \
3041 opt_help
3042 #define DEFHEADING(text) stringify(text) "\n"
3043 #include "qemu-options.h"
3044 #undef DEF
3045 #undef DEFHEADING
3046 #undef GEN_DOCS
3048 version();
3049 printf("usage: %s [options] [disk_image]\n"
3050 "\n"
3051 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3052 "\n"
3053 "%s\n"
3054 "During emulation, the following keys are useful:\n"
3055 "ctrl-alt-f toggle full screen\n"
3056 "ctrl-alt-n switch to virtual console 'n'\n"
3057 "ctrl-alt toggle mouse and keyboard grab\n"
3058 "\n"
3059 "When using -nographic, press 'ctrl-a h' to get some help.\n",
3060 "qemu",
3061 options_help);
3062 exit(exitcode);
3065 #define HAS_ARG 0x0001
3067 enum {
3068 #define DEF(option, opt_arg, opt_enum, opt_help) \
3069 opt_enum,
3070 #define DEFHEADING(text)
3071 #include "qemu-options.h"
3072 #undef DEF
3073 #undef DEFHEADING
3074 #undef GEN_DOCS
3077 typedef struct QEMUOption {
3078 const char *name;
3079 int flags;
3080 int index;
3081 } QEMUOption;
3083 static const QEMUOption qemu_options[] = {
3084 { "h", 0, QEMU_OPTION_h },
3085 #define DEF(option, opt_arg, opt_enum, opt_help) \
3086 { option, opt_arg, opt_enum },
3087 #define DEFHEADING(text)
3088 #include "qemu-options.h"
3089 #undef DEF
3090 #undef DEFHEADING
3091 #undef GEN_DOCS
3092 { NULL },
3095 #ifdef HAS_AUDIO
3096 struct soundhw soundhw[] = {
3097 #ifdef HAS_AUDIO_CHOICE
3098 #if defined(TARGET_I386) || defined(TARGET_MIPS)
3100 "pcspk",
3101 "PC speaker",
3104 { .init_isa = pcspk_audio_init }
3106 #endif
3108 #ifdef CONFIG_SB16
3110 "sb16",
3111 "Creative Sound Blaster 16",
3114 { .init_isa = SB16_init }
3116 #endif
3118 #ifdef CONFIG_CS4231A
3120 "cs4231a",
3121 "CS4231A",
3124 { .init_isa = cs4231a_init }
3126 #endif
3128 #ifdef CONFIG_ADLIB
3130 "adlib",
3131 #ifdef HAS_YMF262
3132 "Yamaha YMF262 (OPL3)",
3133 #else
3134 "Yamaha YM3812 (OPL2)",
3135 #endif
3138 { .init_isa = Adlib_init }
3140 #endif
3142 #ifdef CONFIG_GUS
3144 "gus",
3145 "Gravis Ultrasound GF1",
3148 { .init_isa = GUS_init }
3150 #endif
3152 #ifdef CONFIG_AC97
3154 "ac97",
3155 "Intel 82801AA AC97 Audio",
3158 { .init_pci = ac97_init }
3160 #endif
3162 #ifdef CONFIG_ES1370
3164 "es1370",
3165 "ENSONIQ AudioPCI ES1370",
3168 { .init_pci = es1370_init }
3170 #endif
3172 #endif /* HAS_AUDIO_CHOICE */
3174 { NULL, NULL, 0, 0, { NULL } }
3177 static void select_soundhw (const char *optarg)
3179 struct soundhw *c;
3181 if (*optarg == '?') {
3182 show_valid_cards:
3184 printf ("Valid sound card names (comma separated):\n");
3185 for (c = soundhw; c->name; ++c) {
3186 printf ("%-11s %s\n", c->name, c->descr);
3188 printf ("\n-soundhw all will enable all of the above\n");
3189 exit (*optarg != '?');
3191 else {
3192 size_t l;
3193 const char *p;
3194 char *e;
3195 int bad_card = 0;
3197 if (!strcmp (optarg, "all")) {
3198 for (c = soundhw; c->name; ++c) {
3199 c->enabled = 1;
3201 return;
3204 p = optarg;
3205 while (*p) {
3206 e = strchr (p, ',');
3207 l = !e ? strlen (p) : (size_t) (e - p);
3209 for (c = soundhw; c->name; ++c) {
3210 if (!strncmp (c->name, p, l) && !c->name[l]) {
3211 c->enabled = 1;
3212 break;
3216 if (!c->name) {
3217 if (l > 80) {
3218 fprintf (stderr,
3219 "Unknown sound card name (too big to show)\n");
3221 else {
3222 fprintf (stderr, "Unknown sound card name `%.*s'\n",
3223 (int) l, p);
3225 bad_card = 1;
3227 p += l + (e != NULL);
3230 if (bad_card)
3231 goto show_valid_cards;
3234 #endif
3236 static void select_vgahw (const char *p)
3238 const char *opts;
3240 default_vga = 0;
3241 vga_interface_type = VGA_NONE;
3242 if (strstart(p, "std", &opts)) {
3243 vga_interface_type = VGA_STD;
3244 } else if (strstart(p, "cirrus", &opts)) {
3245 vga_interface_type = VGA_CIRRUS;
3246 } else if (strstart(p, "vmware", &opts)) {
3247 vga_interface_type = VGA_VMWARE;
3248 } else if (strstart(p, "xenfb", &opts)) {
3249 vga_interface_type = VGA_XENFB;
3250 } else if (!strstart(p, "none", &opts)) {
3251 invalid_vga:
3252 fprintf(stderr, "Unknown vga type: %s\n", p);
3253 exit(1);
3255 while (*opts) {
3256 const char *nextopt;
3258 if (strstart(opts, ",retrace=", &nextopt)) {
3259 opts = nextopt;
3260 if (strstart(opts, "dumb", &nextopt))
3261 vga_retrace_method = VGA_RETRACE_DUMB;
3262 else if (strstart(opts, "precise", &nextopt))
3263 vga_retrace_method = VGA_RETRACE_PRECISE;
3264 else goto invalid_vga;
3265 } else goto invalid_vga;
3266 opts = nextopt;
3270 #ifdef TARGET_I386
3271 static int balloon_parse(const char *arg)
3273 QemuOpts *opts;
3275 if (strcmp(arg, "none") == 0) {
3276 return 0;
3279 if (!strncmp(arg, "virtio", 6)) {
3280 if (arg[6] == ',') {
3281 /* have params -> parse them */
3282 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
3283 if (!opts)
3284 return -1;
3285 } else {
3286 /* create empty opts */
3287 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3289 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
3290 return 0;
3293 return -1;
3295 #endif
3297 #ifdef _WIN32
3298 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
3300 exit(STATUS_CONTROL_C_EXIT);
3301 return TRUE;
3303 #endif
3305 int qemu_uuid_parse(const char *str, uint8_t *uuid)
3307 int ret;
3309 if(strlen(str) != 36)
3310 return -1;
3312 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
3313 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
3314 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
3316 if(ret != 16)
3317 return -1;
3319 #ifdef TARGET_I386
3320 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
3321 #endif
3323 return 0;
3326 #ifndef _WIN32
3328 static void termsig_handler(int signal)
3330 qemu_system_shutdown_request();
3333 static void sigchld_handler(int signal)
3335 waitpid(-1, NULL, WNOHANG);
3338 static void sighandler_setup(void)
3340 struct sigaction act;
3342 memset(&act, 0, sizeof(act));
3343 act.sa_handler = termsig_handler;
3344 sigaction(SIGINT, &act, NULL);
3345 sigaction(SIGHUP, &act, NULL);
3346 sigaction(SIGTERM, &act, NULL);
3348 act.sa_handler = sigchld_handler;
3349 act.sa_flags = SA_NOCLDSTOP;
3350 sigaction(SIGCHLD, &act, NULL);
3353 #endif
3355 #ifdef _WIN32
3356 /* Look for support files in the same directory as the executable. */
3357 static char *find_datadir(const char *argv0)
3359 char *p;
3360 char buf[MAX_PATH];
3361 DWORD len;
3363 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
3364 if (len == 0) {
3365 return NULL;
3368 buf[len] = 0;
3369 p = buf + len - 1;
3370 while (p != buf && *p != '\\')
3371 p--;
3372 *p = 0;
3373 if (access(buf, R_OK) == 0) {
3374 return qemu_strdup(buf);
3376 return NULL;
3378 #else /* !_WIN32 */
3380 /* Find a likely location for support files using the location of the binary.
3381 For installed binaries this will be "$bindir/../share/qemu". When
3382 running from the build tree this will be "$bindir/../pc-bios". */
3383 #define SHARE_SUFFIX "/share/qemu"
3384 #define BUILD_SUFFIX "/pc-bios"
3385 static char *find_datadir(const char *argv0)
3387 char *dir;
3388 char *p = NULL;
3389 char *res;
3390 char buf[PATH_MAX];
3391 size_t max_len;
3393 #if defined(__linux__)
3395 int len;
3396 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
3397 if (len > 0) {
3398 buf[len] = 0;
3399 p = buf;
3402 #elif defined(__FreeBSD__)
3404 int len;
3405 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
3406 if (len > 0) {
3407 buf[len] = 0;
3408 p = buf;
3411 #endif
3412 /* If we don't have any way of figuring out the actual executable
3413 location then try argv[0]. */
3414 if (!p) {
3415 p = realpath(argv0, buf);
3416 if (!p) {
3417 return NULL;
3420 dir = dirname(p);
3421 dir = dirname(dir);
3423 max_len = strlen(dir) +
3424 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
3425 res = qemu_mallocz(max_len);
3426 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
3427 if (access(res, R_OK)) {
3428 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
3429 if (access(res, R_OK)) {
3430 qemu_free(res);
3431 res = NULL;
3435 return res;
3437 #undef SHARE_SUFFIX
3438 #undef BUILD_SUFFIX
3439 #endif
3441 char *qemu_find_file(int type, const char *name)
3443 int len;
3444 const char *subdir;
3445 char *buf;
3447 /* If name contains path separators then try it as a straight path. */
3448 if ((strchr(name, '/') || strchr(name, '\\'))
3449 && access(name, R_OK) == 0) {
3450 return qemu_strdup(name);
3452 switch (type) {
3453 case QEMU_FILE_TYPE_BIOS:
3454 subdir = "";
3455 break;
3456 case QEMU_FILE_TYPE_KEYMAP:
3457 subdir = "keymaps/";
3458 break;
3459 default:
3460 abort();
3462 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
3463 buf = qemu_mallocz(len);
3464 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
3465 if (access(buf, R_OK)) {
3466 qemu_free(buf);
3467 return NULL;
3469 return buf;
3472 static int device_help_func(QemuOpts *opts, void *opaque)
3474 return qdev_device_help(opts);
3477 static int device_init_func(QemuOpts *opts, void *opaque)
3479 DeviceState *dev;
3481 dev = qdev_device_add(opts);
3482 if (!dev)
3483 return -1;
3484 return 0;
3487 static int chardev_init_func(QemuOpts *opts, void *opaque)
3489 CharDriverState *chr;
3491 chr = qemu_chr_open_opts(opts, NULL);
3492 if (!chr)
3493 return -1;
3494 return 0;
3497 static int mon_init_func(QemuOpts *opts, void *opaque)
3499 CharDriverState *chr;
3500 const char *chardev;
3501 const char *mode;
3502 int flags;
3504 mode = qemu_opt_get(opts, "mode");
3505 if (mode == NULL) {
3506 mode = "readline";
3508 if (strcmp(mode, "readline") == 0) {
3509 flags = MONITOR_USE_READLINE;
3510 } else if (strcmp(mode, "control") == 0) {
3511 flags = MONITOR_USE_CONTROL;
3512 } else {
3513 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
3514 exit(1);
3517 if (qemu_opt_get_bool(opts, "default", 0))
3518 flags |= MONITOR_IS_DEFAULT;
3520 chardev = qemu_opt_get(opts, "chardev");
3521 chr = qemu_chr_find(chardev);
3522 if (chr == NULL) {
3523 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
3524 exit(1);
3527 monitor_init(chr, flags);
3528 return 0;
3531 static void monitor_parse(const char *optarg, const char *mode)
3533 static int monitor_device_index = 0;
3534 QemuOpts *opts;
3535 const char *p;
3536 char label[32];
3537 int def = 0;
3539 if (strstart(optarg, "chardev:", &p)) {
3540 snprintf(label, sizeof(label), "%s", p);
3541 } else {
3542 if (monitor_device_index) {
3543 snprintf(label, sizeof(label), "monitor%d",
3544 monitor_device_index);
3545 } else {
3546 snprintf(label, sizeof(label), "monitor");
3547 def = 1;
3549 opts = qemu_chr_parse_compat(label, optarg);
3550 if (!opts) {
3551 fprintf(stderr, "parse error: %s\n", optarg);
3552 exit(1);
3556 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
3557 if (!opts) {
3558 fprintf(stderr, "duplicate chardev: %s\n", label);
3559 exit(1);
3561 qemu_opt_set(opts, "mode", mode);
3562 qemu_opt_set(opts, "chardev", label);
3563 if (def)
3564 qemu_opt_set(opts, "default", "on");
3565 monitor_device_index++;
3568 struct device_config {
3569 enum {
3570 DEV_USB, /* -usbdevice */
3571 DEV_BT, /* -bt */
3572 DEV_SERIAL, /* -serial */
3573 DEV_PARALLEL, /* -parallel */
3574 DEV_VIRTCON, /* -virtioconsole */
3575 DEV_DEBUGCON, /* -debugcon */
3576 } type;
3577 const char *cmdline;
3578 QTAILQ_ENTRY(device_config) next;
3580 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
3582 static void add_device_config(int type, const char *cmdline)
3584 struct device_config *conf;
3586 conf = qemu_mallocz(sizeof(*conf));
3587 conf->type = type;
3588 conf->cmdline = cmdline;
3589 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
3592 static int foreach_device_config(int type, int (*func)(const char *cmdline))
3594 struct device_config *conf;
3595 int rc;
3597 QTAILQ_FOREACH(conf, &device_configs, next) {
3598 if (conf->type != type)
3599 continue;
3600 rc = func(conf->cmdline);
3601 if (0 != rc)
3602 return rc;
3604 return 0;
3607 static int serial_parse(const char *devname)
3609 static int index = 0;
3610 char label[32];
3612 if (strcmp(devname, "none") == 0)
3613 return 0;
3614 if (index == MAX_SERIAL_PORTS) {
3615 fprintf(stderr, "qemu: too many serial ports\n");
3616 exit(1);
3618 snprintf(label, sizeof(label), "serial%d", index);
3619 serial_hds[index] = qemu_chr_open(label, devname, NULL);
3620 if (!serial_hds[index]) {
3621 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
3622 devname, strerror(errno));
3623 return -1;
3625 index++;
3626 return 0;
3629 static int parallel_parse(const char *devname)
3631 static int index = 0;
3632 char label[32];
3634 if (strcmp(devname, "none") == 0)
3635 return 0;
3636 if (index == MAX_PARALLEL_PORTS) {
3637 fprintf(stderr, "qemu: too many parallel ports\n");
3638 exit(1);
3640 snprintf(label, sizeof(label), "parallel%d", index);
3641 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
3642 if (!parallel_hds[index]) {
3643 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
3644 devname, strerror(errno));
3645 return -1;
3647 index++;
3648 return 0;
3651 static int virtcon_parse(const char *devname)
3653 static int index = 0;
3654 char label[32];
3655 QemuOpts *bus_opts, *dev_opts;
3657 if (strcmp(devname, "none") == 0)
3658 return 0;
3659 if (index == MAX_VIRTIO_CONSOLES) {
3660 fprintf(stderr, "qemu: too many virtio consoles\n");
3661 exit(1);
3664 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3665 qemu_opt_set(bus_opts, "driver", "virtio-serial");
3667 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3668 qemu_opt_set(dev_opts, "driver", "virtconsole");
3670 snprintf(label, sizeof(label), "virtcon%d", index);
3671 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
3672 if (!virtcon_hds[index]) {
3673 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
3674 devname, strerror(errno));
3675 return -1;
3677 qemu_opt_set(dev_opts, "chardev", label);
3679 index++;
3680 return 0;
3683 static int debugcon_parse(const char *devname)
3685 QemuOpts *opts;
3687 if (!qemu_chr_open("debugcon", devname, NULL)) {
3688 exit(1);
3690 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
3691 if (!opts) {
3692 fprintf(stderr, "qemu: already have a debugcon device\n");
3693 exit(1);
3695 qemu_opt_set(opts, "driver", "isa-debugcon");
3696 qemu_opt_set(opts, "chardev", "debugcon");
3697 return 0;
3700 static const QEMUOption *lookup_opt(int argc, char **argv,
3701 const char **poptarg, int *poptind)
3703 const QEMUOption *popt;
3704 int optind = *poptind;
3705 char *r = argv[optind];
3706 const char *optarg;
3708 loc_set_cmdline(argv, optind, 1);
3709 optind++;
3710 /* Treat --foo the same as -foo. */
3711 if (r[1] == '-')
3712 r++;
3713 popt = qemu_options;
3714 for(;;) {
3715 if (!popt->name) {
3716 error_report("invalid option");
3717 exit(1);
3719 if (!strcmp(popt->name, r + 1))
3720 break;
3721 popt++;
3723 if (popt->flags & HAS_ARG) {
3724 if (optind >= argc) {
3725 error_report("requires an argument");
3726 exit(1);
3728 optarg = argv[optind++];
3729 loc_set_cmdline(argv, optind - 2, 2);
3730 } else {
3731 optarg = NULL;
3734 *poptarg = optarg;
3735 *poptind = optind;
3737 return popt;
3740 static void qmp_add_default(void)
3742 char buffer[4096];
3743 const char *home;
3744 static uint8_t null_uuid[16];
3745 uint8_t uuid[16];
3747 home = getenv("HOME");
3748 if (!home) {
3749 return;
3752 if (memcmp(qemu_uuid, null_uuid, sizeof(null_uuid)) == 0) {
3753 #if defined(CONFIG_UUID)
3754 uuid_generate(uuid);
3755 #else
3756 return;
3757 #endif
3758 } else {
3759 memcpy(uuid, qemu_uuid, sizeof(qemu_uuid));
3762 snprintf(buffer, sizeof(buffer), "%s/.qemu", home);
3763 if (mkdir(buffer, 0755) == -1 && errno != EEXIST) {
3764 fprintf(stderr, "could not open default QMP port\n");
3765 return;
3768 snprintf(buffer, sizeof(buffer), "%s/.qemu/qmp", home);
3769 if (mkdir(buffer, 0755) == -1 && errno != EEXIST) {
3770 fprintf(stderr, "could not open default QMP port\n");
3771 return;
3774 snprintf(buffer, sizeof(buffer),
3775 "unix:%s/.qemu/qmp/" UUID_FMT ".sock,server,nowait",
3776 home,
3777 uuid[0], uuid[1], uuid[2], uuid[3],
3778 uuid[4], uuid[5], uuid[6], uuid[7],
3779 uuid[8], uuid[9], uuid[10], uuid[11],
3780 uuid[12], uuid[13], uuid[14], uuid[15]);
3782 monitor_parse(buffer, "control");
3785 int main(int argc, char **argv, char **envp)
3787 const char *gdbstub_dev = NULL;
3788 uint32_t boot_devices_bitmap = 0;
3789 int i;
3790 int snapshot, linux_boot, net_boot;
3791 const char *icount_option = NULL;
3792 const char *initrd_filename;
3793 const char *kernel_filename, *kernel_cmdline;
3794 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3795 DisplayState *ds;
3796 DisplayChangeListener *dcl;
3797 int cyls, heads, secs, translation;
3798 QemuOpts *hda_opts = NULL, *opts;
3799 int optind;
3800 const char *optarg;
3801 const char *loadvm = NULL;
3802 QEMUMachine *machine;
3803 const char *cpu_model;
3804 #ifndef _WIN32
3805 int fds[2];
3806 #endif
3807 int tb_size;
3808 const char *pid_file = NULL;
3809 const char *incoming = NULL;
3810 #ifndef _WIN32
3811 int fd = 0;
3812 struct passwd *pwd = NULL;
3813 const char *chroot_dir = NULL;
3814 const char *run_as = NULL;
3815 #endif
3816 CPUState *env;
3817 int show_vnc_port = 0;
3818 int defconfig = 1;
3820 error_set_progname(argv[0]);
3822 exit_notifier_init();
3824 init_clocks();
3826 qemu_cache_utils_init(envp);
3828 QLIST_INIT (&vm_change_state_head);
3829 #ifndef _WIN32
3831 struct sigaction act;
3832 sigfillset(&act.sa_mask);
3833 act.sa_flags = 0;
3834 act.sa_handler = SIG_IGN;
3835 sigaction(SIGPIPE, &act, NULL);
3837 #else
3838 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3839 /* Note: cpu_interrupt() is currently not SMP safe, so we force
3840 QEMU to run on a single CPU */
3842 HANDLE h;
3843 DWORD mask, smask;
3844 int i;
3845 h = GetCurrentProcess();
3846 if (GetProcessAffinityMask(h, &mask, &smask)) {
3847 for(i = 0; i < 32; i++) {
3848 if (mask & (1 << i))
3849 break;
3851 if (i != 32) {
3852 mask = 1 << i;
3853 SetProcessAffinityMask(h, mask);
3857 #endif
3859 module_call_init(MODULE_INIT_MACHINE);
3860 machine = find_default_machine();
3861 cpu_model = NULL;
3862 initrd_filename = NULL;
3863 ram_size = 0;
3864 snapshot = 0;
3865 kernel_filename = NULL;
3866 kernel_cmdline = "";
3867 cyls = heads = secs = 0;
3868 translation = BIOS_ATA_TRANSLATION_AUTO;
3870 for (i = 0; i < MAX_NODES; i++) {
3871 node_mem[i] = 0;
3872 node_cpumask[i] = 0;
3875 nb_numa_nodes = 0;
3876 nb_nics = 0;
3878 tb_size = 0;
3879 autostart= 1;
3881 /* first pass of option parsing */
3882 optind = 1;
3883 while (optind < argc) {
3884 if (argv[optind][0] != '-') {
3885 /* disk image */
3886 optind++;
3887 continue;
3888 } else {
3889 const QEMUOption *popt;
3891 popt = lookup_opt(argc, argv, &optarg, &optind);
3892 switch (popt->index) {
3893 case QEMU_OPTION_nodefconfig:
3894 defconfig=0;
3895 break;
3900 if (defconfig) {
3901 const char *fname;
3902 FILE *fp;
3904 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3905 fp = fopen(fname, "r");
3906 if (fp) {
3907 if (qemu_config_parse(fp, fname) != 0) {
3908 exit(1);
3910 fclose(fp);
3913 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3914 fp = fopen(fname, "r");
3915 if (fp) {
3916 if (qemu_config_parse(fp, fname) != 0) {
3917 exit(1);
3919 fclose(fp);
3922 #if defined(cpudef_setup)
3923 cpudef_setup(); /* parse cpu definitions in target config file */
3924 #endif
3926 /* second pass of option parsing */
3927 optind = 1;
3928 for(;;) {
3929 if (optind >= argc)
3930 break;
3931 if (argv[optind][0] != '-') {
3932 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3933 } else {
3934 const QEMUOption *popt;
3936 popt = lookup_opt(argc, argv, &optarg, &optind);
3937 switch(popt->index) {
3938 case QEMU_OPTION_M:
3939 machine = find_machine(optarg);
3940 if (!machine) {
3941 QEMUMachine *m;
3942 printf("Supported machines are:\n");
3943 for(m = first_machine; m != NULL; m = m->next) {
3944 if (m->alias)
3945 printf("%-10s %s (alias of %s)\n",
3946 m->alias, m->desc, m->name);
3947 printf("%-10s %s%s\n",
3948 m->name, m->desc,
3949 m->is_default ? " (default)" : "");
3951 exit(*optarg != '?');
3953 break;
3954 case QEMU_OPTION_cpu:
3955 /* hw initialization will check this */
3956 if (*optarg == '?') {
3957 /* XXX: implement xxx_cpu_list for targets that still miss it */
3958 #if defined(cpu_list_id)
3959 cpu_list_id(stdout, &fprintf, optarg);
3960 #elif defined(cpu_list)
3961 cpu_list(stdout, &fprintf); /* deprecated */
3962 #endif
3963 exit(0);
3964 } else {
3965 cpu_model = optarg;
3967 break;
3968 case QEMU_OPTION_initrd:
3969 initrd_filename = optarg;
3970 break;
3971 case QEMU_OPTION_hda:
3972 if (cyls == 0)
3973 hda_opts = drive_add(optarg, HD_ALIAS, 0);
3974 else
3975 hda_opts = drive_add(optarg, HD_ALIAS
3976 ",cyls=%d,heads=%d,secs=%d%s",
3977 0, cyls, heads, secs,
3978 translation == BIOS_ATA_TRANSLATION_LBA ?
3979 ",trans=lba" :
3980 translation == BIOS_ATA_TRANSLATION_NONE ?
3981 ",trans=none" : "");
3982 break;
3983 case QEMU_OPTION_hdb:
3984 case QEMU_OPTION_hdc:
3985 case QEMU_OPTION_hdd:
3986 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
3987 break;
3988 case QEMU_OPTION_drive:
3989 drive_add(NULL, "%s", optarg);
3990 break;
3991 case QEMU_OPTION_set:
3992 if (qemu_set_option(optarg) != 0)
3993 exit(1);
3994 break;
3995 case QEMU_OPTION_global:
3996 if (qemu_global_option(optarg) != 0)
3997 exit(1);
3998 break;
3999 case QEMU_OPTION_mtdblock:
4000 drive_add(optarg, MTD_ALIAS);
4001 break;
4002 case QEMU_OPTION_sd:
4003 drive_add(optarg, SD_ALIAS);
4004 break;
4005 case QEMU_OPTION_pflash:
4006 drive_add(optarg, PFLASH_ALIAS);
4007 break;
4008 case QEMU_OPTION_snapshot:
4009 snapshot = 1;
4010 break;
4011 case QEMU_OPTION_hdachs:
4013 const char *p;
4014 p = optarg;
4015 cyls = strtol(p, (char **)&p, 0);
4016 if (cyls < 1 || cyls > 16383)
4017 goto chs_fail;
4018 if (*p != ',')
4019 goto chs_fail;
4020 p++;
4021 heads = strtol(p, (char **)&p, 0);
4022 if (heads < 1 || heads > 16)
4023 goto chs_fail;
4024 if (*p != ',')
4025 goto chs_fail;
4026 p++;
4027 secs = strtol(p, (char **)&p, 0);
4028 if (secs < 1 || secs > 63)
4029 goto chs_fail;
4030 if (*p == ',') {
4031 p++;
4032 if (!strcmp(p, "none"))
4033 translation = BIOS_ATA_TRANSLATION_NONE;
4034 else if (!strcmp(p, "lba"))
4035 translation = BIOS_ATA_TRANSLATION_LBA;
4036 else if (!strcmp(p, "auto"))
4037 translation = BIOS_ATA_TRANSLATION_AUTO;
4038 else
4039 goto chs_fail;
4040 } else if (*p != '\0') {
4041 chs_fail:
4042 fprintf(stderr, "qemu: invalid physical CHS format\n");
4043 exit(1);
4045 if (hda_opts != NULL) {
4046 char num[16];
4047 snprintf(num, sizeof(num), "%d", cyls);
4048 qemu_opt_set(hda_opts, "cyls", num);
4049 snprintf(num, sizeof(num), "%d", heads);
4050 qemu_opt_set(hda_opts, "heads", num);
4051 snprintf(num, sizeof(num), "%d", secs);
4052 qemu_opt_set(hda_opts, "secs", num);
4053 if (translation == BIOS_ATA_TRANSLATION_LBA)
4054 qemu_opt_set(hda_opts, "trans", "lba");
4055 if (translation == BIOS_ATA_TRANSLATION_NONE)
4056 qemu_opt_set(hda_opts, "trans", "none");
4059 break;
4060 case QEMU_OPTION_numa:
4061 if (nb_numa_nodes >= MAX_NODES) {
4062 fprintf(stderr, "qemu: too many NUMA nodes\n");
4063 exit(1);
4065 numa_add(optarg);
4066 break;
4067 case QEMU_OPTION_nographic:
4068 display_type = DT_NOGRAPHIC;
4069 break;
4070 #ifdef CONFIG_CURSES
4071 case QEMU_OPTION_curses:
4072 display_type = DT_CURSES;
4073 break;
4074 #endif
4075 case QEMU_OPTION_portrait:
4076 graphic_rotate = 1;
4077 break;
4078 case QEMU_OPTION_kernel:
4079 kernel_filename = optarg;
4080 break;
4081 case QEMU_OPTION_append:
4082 kernel_cmdline = optarg;
4083 break;
4084 case QEMU_OPTION_cdrom:
4085 drive_add(optarg, CDROM_ALIAS);
4086 break;
4087 case QEMU_OPTION_boot:
4089 static const char * const params[] = {
4090 "order", "once", "menu", NULL
4092 char buf[sizeof(boot_devices)];
4093 char *standard_boot_devices;
4094 int legacy = 0;
4096 if (!strchr(optarg, '=')) {
4097 legacy = 1;
4098 pstrcpy(buf, sizeof(buf), optarg);
4099 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4100 fprintf(stderr,
4101 "qemu: unknown boot parameter '%s' in '%s'\n",
4102 buf, optarg);
4103 exit(1);
4106 if (legacy ||
4107 get_param_value(buf, sizeof(buf), "order", optarg)) {
4108 boot_devices_bitmap = parse_bootdevices(buf);
4109 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4111 if (!legacy) {
4112 if (get_param_value(buf, sizeof(buf),
4113 "once", optarg)) {
4114 boot_devices_bitmap |= parse_bootdevices(buf);
4115 standard_boot_devices = qemu_strdup(boot_devices);
4116 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4117 qemu_register_reset(restore_boot_devices,
4118 standard_boot_devices);
4120 if (get_param_value(buf, sizeof(buf),
4121 "menu", optarg)) {
4122 if (!strcmp(buf, "on")) {
4123 boot_menu = 1;
4124 } else if (!strcmp(buf, "off")) {
4125 boot_menu = 0;
4126 } else {
4127 fprintf(stderr,
4128 "qemu: invalid option value '%s'\n",
4129 buf);
4130 exit(1);
4135 break;
4136 case QEMU_OPTION_fda:
4137 case QEMU_OPTION_fdb:
4138 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4139 break;
4140 #ifdef TARGET_I386
4141 case QEMU_OPTION_no_fd_bootchk:
4142 fd_bootchk = 0;
4143 break;
4144 #endif
4145 case QEMU_OPTION_netdev:
4146 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4147 exit(1);
4149 break;
4150 case QEMU_OPTION_net:
4151 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4152 exit(1);
4154 break;
4155 #ifdef CONFIG_SLIRP
4156 case QEMU_OPTION_tftp:
4157 legacy_tftp_prefix = optarg;
4158 break;
4159 case QEMU_OPTION_bootp:
4160 legacy_bootp_filename = optarg;
4161 break;
4162 #ifndef _WIN32
4163 case QEMU_OPTION_smb:
4164 if (net_slirp_smb(optarg) < 0)
4165 exit(1);
4166 break;
4167 #endif
4168 case QEMU_OPTION_redir:
4169 if (net_slirp_redir(optarg) < 0)
4170 exit(1);
4171 break;
4172 #endif
4173 case QEMU_OPTION_bt:
4174 add_device_config(DEV_BT, optarg);
4175 break;
4176 #ifdef HAS_AUDIO
4177 case QEMU_OPTION_audio_help:
4178 AUD_help ();
4179 exit (0);
4180 break;
4181 case QEMU_OPTION_soundhw:
4182 select_soundhw (optarg);
4183 break;
4184 #endif
4185 case QEMU_OPTION_h:
4186 help(0);
4187 break;
4188 case QEMU_OPTION_version:
4189 version();
4190 exit(0);
4191 break;
4192 case QEMU_OPTION_m: {
4193 uint64_t value;
4194 char *ptr;
4196 value = strtoul(optarg, &ptr, 10);
4197 switch (*ptr) {
4198 case 0: case 'M': case 'm':
4199 value <<= 20;
4200 break;
4201 case 'G': case 'g':
4202 value <<= 30;
4203 break;
4204 default:
4205 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4206 exit(1);
4209 /* On 32-bit hosts, QEMU is limited by virtual address space */
4210 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
4211 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4212 exit(1);
4214 if (value != (uint64_t)(ram_addr_t)value) {
4215 fprintf(stderr, "qemu: ram size too large\n");
4216 exit(1);
4218 ram_size = value;
4219 break;
4221 case QEMU_OPTION_mempath:
4222 mem_path = optarg;
4223 break;
4224 #ifdef MAP_POPULATE
4225 case QEMU_OPTION_mem_prealloc:
4226 mem_prealloc = 1;
4227 break;
4228 #endif
4229 case QEMU_OPTION_d:
4231 int mask;
4232 const CPULogItem *item;
4234 mask = cpu_str_to_log_mask(optarg);
4235 if (!mask) {
4236 printf("Log items (comma separated):\n");
4237 for(item = cpu_log_items; item->mask != 0; item++) {
4238 printf("%-10s %s\n", item->name, item->help);
4240 exit(1);
4242 cpu_set_log(mask);
4244 break;
4245 case QEMU_OPTION_s:
4246 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4247 break;
4248 case QEMU_OPTION_gdb:
4249 gdbstub_dev = optarg;
4250 break;
4251 case QEMU_OPTION_L:
4252 data_dir = optarg;
4253 break;
4254 case QEMU_OPTION_bios:
4255 bios_name = optarg;
4256 break;
4257 case QEMU_OPTION_singlestep:
4258 singlestep = 1;
4259 break;
4260 case QEMU_OPTION_S:
4261 autostart = 0;
4262 break;
4263 case QEMU_OPTION_k:
4264 keyboard_layout = optarg;
4265 break;
4266 case QEMU_OPTION_localtime:
4267 rtc_utc = 0;
4268 break;
4269 case QEMU_OPTION_vga:
4270 select_vgahw (optarg);
4271 break;
4272 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4273 case QEMU_OPTION_g:
4275 const char *p;
4276 int w, h, depth;
4277 p = optarg;
4278 w = strtol(p, (char **)&p, 10);
4279 if (w <= 0) {
4280 graphic_error:
4281 fprintf(stderr, "qemu: invalid resolution or depth\n");
4282 exit(1);
4284 if (*p != 'x')
4285 goto graphic_error;
4286 p++;
4287 h = strtol(p, (char **)&p, 10);
4288 if (h <= 0)
4289 goto graphic_error;
4290 if (*p == 'x') {
4291 p++;
4292 depth = strtol(p, (char **)&p, 10);
4293 if (depth != 8 && depth != 15 && depth != 16 &&
4294 depth != 24 && depth != 32)
4295 goto graphic_error;
4296 } else if (*p == '\0') {
4297 depth = graphic_depth;
4298 } else {
4299 goto graphic_error;
4302 graphic_width = w;
4303 graphic_height = h;
4304 graphic_depth = depth;
4306 break;
4307 #endif
4308 case QEMU_OPTION_echr:
4310 char *r;
4311 term_escape_char = strtol(optarg, &r, 0);
4312 if (r == optarg)
4313 printf("Bad argument to echr\n");
4314 break;
4316 case QEMU_OPTION_monitor:
4317 monitor_parse(optarg, "readline");
4318 default_monitor = 0;
4319 break;
4320 case QEMU_OPTION_qmp:
4321 monitor_parse(optarg, "control");
4322 default_qmp = 0;
4323 break;
4324 case QEMU_OPTION_mon:
4325 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
4326 if (!opts) {
4327 fprintf(stderr, "parse error: %s\n", optarg);
4328 exit(1);
4329 } else {
4330 const char *mode;
4331 mode = qemu_opt_get(opts, "mode");
4332 if (mode == NULL || strcmp(mode, "readline") == 0) {
4333 default_monitor = 0;
4334 } else if (strcmp(mode, "control") == 0) {
4335 default_qmp = 0;
4338 break;
4339 case QEMU_OPTION_chardev:
4340 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
4341 if (!opts) {
4342 fprintf(stderr, "parse error: %s\n", optarg);
4343 exit(1);
4345 break;
4346 case QEMU_OPTION_serial:
4347 add_device_config(DEV_SERIAL, optarg);
4348 default_serial = 0;
4349 if (strncmp(optarg, "mon:", 4) == 0) {
4350 default_monitor = 0;
4352 break;
4353 case QEMU_OPTION_watchdog:
4354 if (watchdog) {
4355 fprintf(stderr,
4356 "qemu: only one watchdog option may be given\n");
4357 return 1;
4359 watchdog = optarg;
4360 break;
4361 case QEMU_OPTION_watchdog_action:
4362 if (select_watchdog_action(optarg) == -1) {
4363 fprintf(stderr, "Unknown -watchdog-action parameter\n");
4364 exit(1);
4366 break;
4367 case QEMU_OPTION_virtiocon:
4368 add_device_config(DEV_VIRTCON, optarg);
4369 default_virtcon = 0;
4370 if (strncmp(optarg, "mon:", 4) == 0) {
4371 default_monitor = 0;
4373 break;
4374 case QEMU_OPTION_parallel:
4375 add_device_config(DEV_PARALLEL, optarg);
4376 default_parallel = 0;
4377 if (strncmp(optarg, "mon:", 4) == 0) {
4378 default_monitor = 0;
4380 break;
4381 case QEMU_OPTION_debugcon:
4382 add_device_config(DEV_DEBUGCON, optarg);
4383 break;
4384 case QEMU_OPTION_loadvm:
4385 loadvm = optarg;
4386 break;
4387 case QEMU_OPTION_full_screen:
4388 full_screen = 1;
4389 break;
4390 #ifdef CONFIG_SDL
4391 case QEMU_OPTION_no_frame:
4392 no_frame = 1;
4393 break;
4394 case QEMU_OPTION_alt_grab:
4395 alt_grab = 1;
4396 break;
4397 case QEMU_OPTION_ctrl_grab:
4398 ctrl_grab = 1;
4399 break;
4400 case QEMU_OPTION_no_quit:
4401 no_quit = 1;
4402 break;
4403 case QEMU_OPTION_sdl:
4404 display_type = DT_SDL;
4405 break;
4406 #endif
4407 case QEMU_OPTION_pidfile:
4408 pid_file = optarg;
4409 break;
4410 #ifdef TARGET_I386
4411 case QEMU_OPTION_win2k_hack:
4412 win2k_install_hack = 1;
4413 break;
4414 case QEMU_OPTION_rtc_td_hack:
4415 rtc_td_hack = 1;
4416 break;
4417 case QEMU_OPTION_acpitable:
4418 if(acpi_table_add(optarg) < 0) {
4419 fprintf(stderr, "Wrong acpi table provided\n");
4420 exit(1);
4422 break;
4423 case QEMU_OPTION_smbios:
4424 if(smbios_entry_add(optarg) < 0) {
4425 fprintf(stderr, "Wrong smbios provided\n");
4426 exit(1);
4428 break;
4429 #endif
4430 #ifdef CONFIG_KVM
4431 case QEMU_OPTION_enable_kvm:
4432 kvm_allowed = 1;
4433 break;
4434 #endif
4435 case QEMU_OPTION_usb:
4436 usb_enabled = 1;
4437 break;
4438 case QEMU_OPTION_usbdevice:
4439 usb_enabled = 1;
4440 add_device_config(DEV_USB, optarg);
4441 break;
4442 case QEMU_OPTION_device:
4443 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
4444 exit(1);
4446 break;
4447 case QEMU_OPTION_smp:
4448 smp_parse(optarg);
4449 if (smp_cpus < 1) {
4450 fprintf(stderr, "Invalid number of CPUs\n");
4451 exit(1);
4453 if (max_cpus < smp_cpus) {
4454 fprintf(stderr, "maxcpus must be equal to or greater than "
4455 "smp\n");
4456 exit(1);
4458 if (max_cpus > 255) {
4459 fprintf(stderr, "Unsupported number of maxcpus\n");
4460 exit(1);
4462 break;
4463 case QEMU_OPTION_vnc:
4464 display_type = DT_VNC;
4465 vnc_display = optarg;
4466 break;
4467 #ifdef TARGET_I386
4468 case QEMU_OPTION_no_acpi:
4469 acpi_enabled = 0;
4470 break;
4471 case QEMU_OPTION_no_hpet:
4472 no_hpet = 1;
4473 break;
4474 case QEMU_OPTION_balloon:
4475 if (balloon_parse(optarg) < 0) {
4476 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
4477 exit(1);
4479 break;
4480 #endif
4481 case QEMU_OPTION_no_reboot:
4482 no_reboot = 1;
4483 break;
4484 case QEMU_OPTION_no_shutdown:
4485 no_shutdown = 1;
4486 break;
4487 case QEMU_OPTION_show_cursor:
4488 cursor_hide = 0;
4489 break;
4490 case QEMU_OPTION_uuid:
4491 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4492 fprintf(stderr, "Fail to parse UUID string."
4493 " Wrong format.\n");
4494 exit(1);
4496 break;
4497 #ifndef _WIN32
4498 case QEMU_OPTION_daemonize:
4499 daemonize = 1;
4500 break;
4501 #endif
4502 case QEMU_OPTION_option_rom:
4503 if (nb_option_roms >= MAX_OPTION_ROMS) {
4504 fprintf(stderr, "Too many option ROMs\n");
4505 exit(1);
4507 option_rom[nb_option_roms] = optarg;
4508 nb_option_roms++;
4509 break;
4510 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4511 case QEMU_OPTION_semihosting:
4512 semihosting_enabled = 1;
4513 break;
4514 #endif
4515 case QEMU_OPTION_name:
4516 qemu_name = qemu_strdup(optarg);
4518 char *p = strchr(qemu_name, ',');
4519 if (p != NULL) {
4520 *p++ = 0;
4521 if (strncmp(p, "process=", 8)) {
4522 fprintf(stderr, "Unknown subargument %s to -name", p);
4523 exit(1);
4525 p += 8;
4526 set_proc_name(p);
4529 break;
4530 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4531 case QEMU_OPTION_prom_env:
4532 if (nb_prom_envs >= MAX_PROM_ENVS) {
4533 fprintf(stderr, "Too many prom variables\n");
4534 exit(1);
4536 prom_envs[nb_prom_envs] = optarg;
4537 nb_prom_envs++;
4538 break;
4539 #endif
4540 #ifdef TARGET_ARM
4541 case QEMU_OPTION_old_param:
4542 old_param = 1;
4543 break;
4544 #endif
4545 case QEMU_OPTION_clock:
4546 configure_alarms(optarg);
4547 break;
4548 case QEMU_OPTION_startdate:
4549 configure_rtc_date_offset(optarg, 1);
4550 break;
4551 case QEMU_OPTION_rtc:
4552 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
4553 if (!opts) {
4554 fprintf(stderr, "parse error: %s\n", optarg);
4555 exit(1);
4557 configure_rtc(opts);
4558 break;
4559 case QEMU_OPTION_tb_size:
4560 tb_size = strtol(optarg, NULL, 0);
4561 if (tb_size < 0)
4562 tb_size = 0;
4563 break;
4564 case QEMU_OPTION_icount:
4565 icount_option = optarg;
4566 break;
4567 case QEMU_OPTION_incoming:
4568 incoming = optarg;
4569 break;
4570 case QEMU_OPTION_nodefaults:
4571 default_serial = 0;
4572 default_parallel = 0;
4573 default_virtcon = 0;
4574 default_monitor = 0;
4575 default_qmp = 0;
4576 default_vga = 0;
4577 default_net = 0;
4578 default_floppy = 0;
4579 default_cdrom = 0;
4580 default_sdcard = 0;
4581 break;
4582 #ifndef _WIN32
4583 case QEMU_OPTION_chroot:
4584 chroot_dir = optarg;
4585 break;
4586 case QEMU_OPTION_runas:
4587 run_as = optarg;
4588 break;
4589 #endif
4590 #ifdef CONFIG_XEN
4591 case QEMU_OPTION_xen_domid:
4592 xen_domid = atoi(optarg);
4593 break;
4594 case QEMU_OPTION_xen_create:
4595 xen_mode = XEN_CREATE;
4596 break;
4597 case QEMU_OPTION_xen_attach:
4598 xen_mode = XEN_ATTACH;
4599 break;
4600 #endif
4601 case QEMU_OPTION_readconfig:
4603 FILE *fp;
4604 fp = fopen(optarg, "r");
4605 if (fp == NULL) {
4606 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4607 exit(1);
4609 if (qemu_config_parse(fp, optarg) != 0) {
4610 exit(1);
4612 fclose(fp);
4613 break;
4615 case QEMU_OPTION_writeconfig:
4617 FILE *fp;
4618 if (strcmp(optarg, "-") == 0) {
4619 fp = stdout;
4620 } else {
4621 fp = fopen(optarg, "w");
4622 if (fp == NULL) {
4623 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4624 exit(1);
4627 qemu_config_write(fp);
4628 fclose(fp);
4629 break;
4634 loc_set_none();
4636 /* If no data_dir is specified then try to find it relative to the
4637 executable path. */
4638 if (!data_dir) {
4639 data_dir = find_datadir(argv[0]);
4641 /* If all else fails use the install patch specified when building. */
4642 if (!data_dir) {
4643 data_dir = CONFIG_QEMU_SHAREDIR;
4647 * Default to max_cpus = smp_cpus, in case the user doesn't
4648 * specify a max_cpus value.
4650 if (!max_cpus)
4651 max_cpus = smp_cpus;
4653 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4654 if (smp_cpus > machine->max_cpus) {
4655 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4656 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
4657 machine->max_cpus);
4658 exit(1);
4661 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
4662 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
4664 if (machine->no_serial) {
4665 default_serial = 0;
4667 if (machine->no_parallel) {
4668 default_parallel = 0;
4670 if (!machine->use_virtcon) {
4671 default_virtcon = 0;
4673 if (machine->no_vga) {
4674 default_vga = 0;
4676 if (machine->no_floppy) {
4677 default_floppy = 0;
4679 if (machine->no_cdrom) {
4680 default_cdrom = 0;
4682 if (machine->no_sdcard) {
4683 default_sdcard = 0;
4686 if (display_type == DT_NOGRAPHIC) {
4687 if (default_parallel)
4688 add_device_config(DEV_PARALLEL, "null");
4689 if (default_serial && default_monitor) {
4690 add_device_config(DEV_SERIAL, "mon:stdio");
4691 } else if (default_virtcon && default_monitor) {
4692 add_device_config(DEV_VIRTCON, "mon:stdio");
4693 } else {
4694 if (default_serial)
4695 add_device_config(DEV_SERIAL, "stdio");
4696 if (default_virtcon)
4697 add_device_config(DEV_VIRTCON, "stdio");
4698 if (default_monitor)
4699 monitor_parse("stdio", "readline");
4701 } else {
4702 if (default_serial)
4703 add_device_config(DEV_SERIAL, "vc:80Cx24C");
4704 if (default_parallel)
4705 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4706 if (default_monitor)
4707 monitor_parse("vc:80Cx24C", "readline");
4708 if (default_virtcon)
4709 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4711 if (default_qmp) {
4712 qmp_add_default();
4714 if (default_vga)
4715 vga_interface_type = VGA_CIRRUS;
4717 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
4718 exit(1);
4720 #ifndef _WIN32
4721 if (daemonize) {
4722 pid_t pid;
4724 if (pipe(fds) == -1)
4725 exit(1);
4727 pid = fork();
4728 if (pid > 0) {
4729 uint8_t status;
4730 ssize_t len;
4732 close(fds[1]);
4734 again:
4735 len = read(fds[0], &status, 1);
4736 if (len == -1 && (errno == EINTR))
4737 goto again;
4739 if (len != 1)
4740 exit(1);
4741 else if (status == 1) {
4742 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
4743 exit(1);
4744 } else
4745 exit(0);
4746 } else if (pid < 0)
4747 exit(1);
4749 close(fds[0]);
4750 qemu_set_cloexec(fds[1]);
4752 setsid();
4754 pid = fork();
4755 if (pid > 0)
4756 exit(0);
4757 else if (pid < 0)
4758 exit(1);
4760 umask(027);
4762 signal(SIGTSTP, SIG_IGN);
4763 signal(SIGTTOU, SIG_IGN);
4764 signal(SIGTTIN, SIG_IGN);
4766 #endif
4768 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4769 #ifndef _WIN32
4770 if (daemonize) {
4771 uint8_t status = 1;
4772 if (write(fds[1], &status, 1) != 1) {
4773 perror("daemonize. Writing to pipe\n");
4775 } else
4776 #endif
4777 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
4778 exit(1);
4781 if (kvm_enabled()) {
4782 int ret;
4784 ret = kvm_init(smp_cpus);
4785 if (ret < 0) {
4786 fprintf(stderr, "failed to initialize KVM\n");
4787 exit(1);
4791 if (qemu_init_main_loop()) {
4792 fprintf(stderr, "qemu_init_main_loop failed\n");
4793 exit(1);
4795 linux_boot = (kernel_filename != NULL);
4797 if (!linux_boot && *kernel_cmdline != '\0') {
4798 fprintf(stderr, "-append only allowed with -kernel option\n");
4799 exit(1);
4802 if (!linux_boot && initrd_filename != NULL) {
4803 fprintf(stderr, "-initrd only allowed with -kernel option\n");
4804 exit(1);
4807 #ifndef _WIN32
4808 /* Win32 doesn't support line-buffering and requires size >= 2 */
4809 setvbuf(stdout, NULL, _IOLBF, 0);
4810 #endif
4812 if (init_timer_alarm() < 0) {
4813 fprintf(stderr, "could not initialize alarm timer\n");
4814 exit(1);
4816 configure_icount(icount_option);
4818 #ifdef _WIN32
4819 socket_init();
4820 #endif
4822 if (net_init_clients() < 0) {
4823 exit(1);
4826 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4827 net_set_boot_mask(net_boot);
4829 /* init the bluetooth world */
4830 if (foreach_device_config(DEV_BT, bt_parse))
4831 exit(1);
4833 /* init the memory */
4834 if (ram_size == 0)
4835 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4837 /* init the dynamic translator */
4838 cpu_exec_init_all(tb_size * 1024 * 1024);
4840 bdrv_init_with_whitelist();
4842 blk_mig_init();
4844 if (default_cdrom) {
4845 /* we always create the cdrom drive, even if no disk is there */
4846 drive_add(NULL, CDROM_ALIAS);
4849 if (default_floppy) {
4850 /* we always create at least one floppy */
4851 drive_add(NULL, FD_ALIAS, 0);
4854 if (default_sdcard) {
4855 /* we always create one sd slot, even if no card is in it */
4856 drive_add(NULL, SD_ALIAS);
4859 /* open the virtual block devices */
4860 if (snapshot)
4861 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4862 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4863 exit(1);
4865 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
4866 ram_load, NULL);
4868 if (nb_numa_nodes > 0) {
4869 int i;
4871 if (nb_numa_nodes > smp_cpus) {
4872 nb_numa_nodes = smp_cpus;
4875 /* If no memory size if given for any node, assume the default case
4876 * and distribute the available memory equally across all nodes
4878 for (i = 0; i < nb_numa_nodes; i++) {
4879 if (node_mem[i] != 0)
4880 break;
4882 if (i == nb_numa_nodes) {
4883 uint64_t usedmem = 0;
4885 /* On Linux, the each node's border has to be 8MB aligned,
4886 * the final node gets the rest.
4888 for (i = 0; i < nb_numa_nodes - 1; i++) {
4889 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4890 usedmem += node_mem[i];
4892 node_mem[i] = ram_size - usedmem;
4895 for (i = 0; i < nb_numa_nodes; i++) {
4896 if (node_cpumask[i] != 0)
4897 break;
4899 /* assigning the VCPUs round-robin is easier to implement, guest OSes
4900 * must cope with this anyway, because there are BIOSes out there in
4901 * real machines which also use this scheme.
4903 if (i == nb_numa_nodes) {
4904 for (i = 0; i < smp_cpus; i++) {
4905 node_cpumask[i % nb_numa_nodes] |= 1 << i;
4910 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4911 exit(1);
4912 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4913 exit(1);
4914 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4915 exit(1);
4916 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4917 exit(1);
4919 module_call_init(MODULE_INIT_DEVICE);
4921 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
4922 exit(0);
4924 if (watchdog) {
4925 i = select_watchdog(watchdog);
4926 if (i > 0)
4927 exit (i == 1 ? 1 : 0);
4930 if (machine->compat_props) {
4931 qdev_prop_register_global_list(machine->compat_props);
4933 qemu_add_globals();
4935 machine->init(ram_size, boot_devices,
4936 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
4938 cpu_synchronize_all_post_init();
4940 #ifndef _WIN32
4941 /* must be after terminal init, SDL library changes signal handlers */
4942 sighandler_setup();
4943 #endif
4945 for (env = first_cpu; env != NULL; env = env->next_cpu) {
4946 for (i = 0; i < nb_numa_nodes; i++) {
4947 if (node_cpumask[i] & (1 << env->cpu_index)) {
4948 env->numa_node = i;
4953 current_machine = machine;
4955 /* init USB devices */
4956 if (usb_enabled) {
4957 if (foreach_device_config(DEV_USB, usb_parse) < 0)
4958 exit(1);
4961 /* init generic devices */
4962 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
4963 exit(1);
4965 net_check_clients();
4967 /* just use the first displaystate for the moment */
4968 ds = get_displaystate();
4970 if (display_type == DT_DEFAULT) {
4971 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4972 display_type = DT_SDL;
4973 #else
4974 display_type = DT_VNC;
4975 vnc_display = "localhost:0,to=99";
4976 show_vnc_port = 1;
4977 #endif
4981 switch (display_type) {
4982 case DT_NOGRAPHIC:
4983 break;
4984 #if defined(CONFIG_CURSES)
4985 case DT_CURSES:
4986 curses_display_init(ds, full_screen);
4987 break;
4988 #endif
4989 #if defined(CONFIG_SDL)
4990 case DT_SDL:
4991 sdl_display_init(ds, full_screen, no_frame);
4992 break;
4993 #elif defined(CONFIG_COCOA)
4994 case DT_SDL:
4995 cocoa_display_init(ds, full_screen);
4996 break;
4997 #endif
4998 case DT_VNC:
4999 vnc_display_init(ds);
5000 if (vnc_display_open(ds, vnc_display) < 0)
5001 exit(1);
5003 if (show_vnc_port) {
5004 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5006 break;
5007 default:
5008 break;
5010 dpy_resize(ds);
5012 dcl = ds->listeners;
5013 while (dcl != NULL) {
5014 if (dcl->dpy_refresh != NULL) {
5015 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5016 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5018 dcl = dcl->next;
5021 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5022 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5023 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5026 text_consoles_set_display(ds);
5028 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5029 exit(1);
5031 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5032 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5033 gdbstub_dev);
5034 exit(1);
5037 qdev_machine_creation_done();
5039 if (rom_load_all() != 0) {
5040 fprintf(stderr, "rom loading failed\n");
5041 exit(1);
5044 qemu_system_reset();
5045 if (loadvm) {
5046 if (load_vmstate(loadvm) < 0) {
5047 autostart = 0;
5051 if (incoming) {
5052 qemu_start_incoming_migration(incoming);
5053 } else if (autostart) {
5054 vm_start();
5057 #ifndef _WIN32
5058 if (daemonize) {
5059 uint8_t status = 0;
5060 ssize_t len;
5062 again1:
5063 len = write(fds[1], &status, 1);
5064 if (len == -1 && (errno == EINTR))
5065 goto again1;
5067 if (len != 1)
5068 exit(1);
5070 if (chdir("/")) {
5071 perror("not able to chdir to /");
5072 exit(1);
5074 TFR(fd = qemu_open("/dev/null", O_RDWR));
5075 if (fd == -1)
5076 exit(1);
5079 if (run_as) {
5080 pwd = getpwnam(run_as);
5081 if (!pwd) {
5082 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5083 exit(1);
5087 if (chroot_dir) {
5088 if (chroot(chroot_dir) < 0) {
5089 fprintf(stderr, "chroot failed\n");
5090 exit(1);
5092 if (chdir("/")) {
5093 perror("not able to chdir to /");
5094 exit(1);
5098 if (run_as) {
5099 if (setgid(pwd->pw_gid) < 0) {
5100 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5101 exit(1);
5103 if (setuid(pwd->pw_uid) < 0) {
5104 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5105 exit(1);
5107 if (setuid(0) != -1) {
5108 fprintf(stderr, "Dropping privileges failed\n");
5109 exit(1);
5113 if (daemonize) {
5114 dup2(fd, 0);
5115 dup2(fd, 1);
5116 dup2(fd, 2);
5118 close(fd);
5120 #endif
5122 main_loop();
5123 quit_timers();
5124 net_cleanup();
5126 return 0;