qmp: don't make -qmp disable the default monitor
[qemu/aliguori-queue.git] / vl.c
blobe14f45eaeef42188b85089f11351b207bbd0d6c8
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #include <arpa/inet.h>
48 #include <dirent.h>
49 #include <netdb.h>
50 #include <sys/select.h>
51 #ifdef CONFIG_BSD
52 #include <sys/stat.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54 #include <libutil.h>
55 #else
56 #include <util.h>
57 #endif
58 #else
59 #ifdef __linux__
60 #include <pty.h>
61 #include <malloc.h>
62 #include <sys/prctl.h>
64 #include <linux/ppdev.h>
65 #include <linux/parport.h>
66 #endif
67 #ifdef __sun__
68 #include <sys/stat.h>
69 #include <sys/ethernet.h>
70 #include <sys/sockio.h>
71 #include <netinet/arp.h>
72 #include <netinet/in.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/ip_icmp.h> // must come after ip.h
76 #include <netinet/udp.h>
77 #include <netinet/tcp.h>
78 #include <net/if.h>
79 #include <syslog.h>
80 #include <stropts.h>
81 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
82 discussion about Solaris header problems */
83 extern int madvise(caddr_t, size_t, int);
84 #endif
85 #endif
86 #endif
88 #if defined(__OpenBSD__)
89 #include <util.h>
90 #endif
92 #if defined(CONFIG_VDE)
93 #include <libvdeplug.h>
94 #endif
96 #ifdef _WIN32
97 #include <windows.h>
98 #endif
100 #ifdef CONFIG_SDL
101 #if defined(__APPLE__) || defined(main)
102 #include <SDL.h>
103 int qemu_main(int argc, char **argv, char **envp);
104 int main(int argc, char **argv)
106 return qemu_main(argc, argv, NULL);
108 #undef main
109 #define main qemu_main
110 #endif
111 #endif /* CONFIG_SDL */
113 #ifdef CONFIG_COCOA
114 #undef main
115 #define main qemu_main
116 #endif /* CONFIG_COCOA */
118 #include "hw/hw.h"
119 #include "hw/boards.h"
120 #include "hw/usb.h"
121 #include "hw/pcmcia.h"
122 #include "hw/pc.h"
123 #include "hw/audiodev.h"
124 #include "hw/isa.h"
125 #include "hw/baum.h"
126 #include "hw/bt.h"
127 #include "hw/watchdog.h"
128 #include "hw/smbios.h"
129 #include "hw/xen.h"
130 #include "hw/qdev.h"
131 #include "hw/loader.h"
132 #include "bt-host.h"
133 #include "net.h"
134 #include "net/slirp.h"
135 #include "monitor.h"
136 #include "console.h"
137 #include "sysemu.h"
138 #include "gdbstub.h"
139 #include "qemu-timer.h"
140 #include "qemu-char.h"
141 #include "cache-utils.h"
142 #include "block.h"
143 #include "block_int.h"
144 #include "block-migration.h"
145 #include "dma.h"
146 #include "audio/audio.h"
147 #include "migration.h"
148 #include "kvm.h"
149 #include "balloon.h"
150 #include "qemu-option.h"
151 #include "qemu-config.h"
152 #include "qemu-objects.h"
153 #include "notify.h"
155 #include "disas.h"
157 #include "exec-all.h"
159 #include "qemu_socket.h"
161 #include "slirp/libslirp.h"
163 #include "qemu-queue.h"
165 //#define DEBUG_NET
166 //#define DEBUG_SLIRP
168 #define DEFAULT_RAM_SIZE 128
170 #define MAX_VIRTIO_CONSOLES 1
172 static const char *data_dir;
173 const char *bios_name = NULL;
174 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
175 to store the VM snapshots */
176 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
177 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
178 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
179 DisplayType display_type = DT_DEFAULT;
180 const char* keyboard_layout = NULL;
181 ram_addr_t ram_size;
182 const char *mem_path = NULL;
183 #ifdef MAP_POPULATE
184 int mem_prealloc = 0; /* force preallocation of physical target memory */
185 #endif
186 int nb_nics;
187 NICInfo nd_table[MAX_NICS];
188 int vm_running;
189 int autostart;
190 static int rtc_utc = 1;
191 static int rtc_date_offset = -1; /* -1 means no change */
192 QEMUClock *rtc_clock;
193 int vga_interface_type = VGA_NONE;
194 #ifdef TARGET_SPARC
195 int graphic_width = 1024;
196 int graphic_height = 768;
197 int graphic_depth = 8;
198 #else
199 int graphic_width = 800;
200 int graphic_height = 600;
201 int graphic_depth = 15;
202 #endif
203 static int full_screen = 0;
204 #ifdef CONFIG_SDL
205 static int no_frame = 0;
206 #endif
207 int no_quit = 0;
208 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
209 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
210 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
211 #ifdef TARGET_I386
212 int win2k_install_hack = 0;
213 int rtc_td_hack = 0;
214 #endif
215 int usb_enabled = 0;
216 int singlestep = 0;
217 int smp_cpus = 1;
218 int max_cpus = 0;
219 int smp_cores = 1;
220 int smp_threads = 1;
221 const char *vnc_display;
222 int acpi_enabled = 1;
223 int no_hpet = 0;
224 int fd_bootchk = 1;
225 int no_reboot = 0;
226 int no_shutdown = 0;
227 int cursor_hide = 1;
228 int graphic_rotate = 0;
229 uint8_t irq0override = 1;
230 #ifndef _WIN32
231 int daemonize = 0;
232 #endif
233 const char *watchdog;
234 const char *option_rom[MAX_OPTION_ROMS];
235 int nb_option_roms;
236 int semihosting_enabled = 0;
237 #ifdef TARGET_ARM
238 int old_param = 0;
239 #endif
240 const char *qemu_name;
241 int alt_grab = 0;
242 int ctrl_grab = 0;
243 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
244 unsigned int nb_prom_envs = 0;
245 const char *prom_envs[MAX_PROM_ENVS];
246 #endif
247 int boot_menu;
249 int nb_numa_nodes;
250 uint64_t node_mem[MAX_NODES];
251 uint64_t node_cpumask[MAX_NODES];
253 static CPUState *cur_cpu;
254 static CPUState *next_cpu;
255 static QEMUTimer *nographic_timer;
257 uint8_t qemu_uuid[16];
259 static QEMUBootSetHandler *boot_set_handler;
260 static void *boot_set_opaque;
262 #ifdef SIGRTMIN
263 #define SIG_IPI (SIGRTMIN+4)
264 #else
265 #define SIG_IPI SIGUSR1
266 #endif
268 static int default_serial = 1;
269 static int default_parallel = 1;
270 static int default_virtcon = 1;
271 static int default_monitor = 1;
272 static int default_vga = 1;
273 static int default_floppy = 1;
274 static int default_cdrom = 1;
275 static int default_sdcard = 1;
276 static int default_qmp = 1;
278 static struct {
279 const char *driver;
280 int *flag;
281 } default_list[] = {
282 { .driver = "isa-serial", .flag = &default_serial },
283 { .driver = "isa-parallel", .flag = &default_parallel },
284 { .driver = "isa-fdc", .flag = &default_floppy },
285 { .driver = "ide-drive", .flag = &default_cdrom },
286 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
287 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
288 { .driver = "virtio-serial", .flag = &default_virtcon },
289 { .driver = "VGA", .flag = &default_vga },
290 { .driver = "cirrus-vga", .flag = &default_vga },
291 { .driver = "vmware-svga", .flag = &default_vga },
294 static int default_driver_check(QemuOpts *opts, void *opaque)
296 const char *driver = qemu_opt_get(opts, "driver");
297 int i;
299 if (!driver)
300 return 0;
301 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
302 if (strcmp(default_list[i].driver, driver) != 0)
303 continue;
304 *(default_list[i].flag) = 0;
306 return 0;
309 /***********************************************************/
310 /* x86 ISA bus support */
312 target_phys_addr_t isa_mem_base = 0;
313 PicState2 *isa_pic;
315 /***********************************************************/
316 void hw_error(const char *fmt, ...)
318 va_list ap;
319 CPUState *env;
321 va_start(ap, fmt);
322 fprintf(stderr, "qemu: hardware error: ");
323 vfprintf(stderr, fmt, ap);
324 fprintf(stderr, "\n");
325 for(env = first_cpu; env != NULL; env = env->next_cpu) {
326 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
327 #ifdef TARGET_I386
328 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
329 #else
330 cpu_dump_state(env, stderr, fprintf, 0);
331 #endif
333 va_end(ap);
334 abort();
337 static void set_proc_name(const char *s)
339 #if defined(__linux__) && defined(PR_SET_NAME)
340 char name[16];
341 if (!s)
342 return;
343 name[sizeof(name) - 1] = 0;
344 strncpy(name, s, sizeof(name));
345 /* Could rewrite argv[0] too, but that's a bit more complicated.
346 This simple way is enough for `top'. */
347 prctl(PR_SET_NAME, name);
348 #endif
351 /***************/
352 /* ballooning */
354 static QEMUBalloonEvent *qemu_balloon_event;
355 void *qemu_balloon_event_opaque;
357 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
359 qemu_balloon_event = func;
360 qemu_balloon_event_opaque = opaque;
363 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
365 if (qemu_balloon_event) {
366 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
367 return 1;
368 } else {
369 return 0;
373 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
375 if (qemu_balloon_event) {
376 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
377 return 1;
378 } else {
379 return 0;
384 /***********************************************************/
385 /* real time host monotonic timer */
387 /* compute with 96 bit intermediate result: (a*b)/c */
388 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
390 union {
391 uint64_t ll;
392 struct {
393 #ifdef HOST_WORDS_BIGENDIAN
394 uint32_t high, low;
395 #else
396 uint32_t low, high;
397 #endif
398 } l;
399 } u, res;
400 uint64_t rl, rh;
402 u.ll = a;
403 rl = (uint64_t)u.l.low * (uint64_t)b;
404 rh = (uint64_t)u.l.high * (uint64_t)b;
405 rh += (rl >> 32);
406 res.l.high = rh / c;
407 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
408 return res.ll;
411 /***********************************************************/
412 /* host time/date access */
413 void qemu_get_timedate(struct tm *tm, int offset)
415 time_t ti;
416 struct tm *ret;
418 time(&ti);
419 ti += offset;
420 if (rtc_date_offset == -1) {
421 if (rtc_utc)
422 ret = gmtime(&ti);
423 else
424 ret = localtime(&ti);
425 } else {
426 ti -= rtc_date_offset;
427 ret = gmtime(&ti);
430 memcpy(tm, ret, sizeof(struct tm));
433 int qemu_timedate_diff(struct tm *tm)
435 time_t seconds;
437 if (rtc_date_offset == -1)
438 if (rtc_utc)
439 seconds = mktimegm(tm);
440 else
441 seconds = mktime(tm);
442 else
443 seconds = mktimegm(tm) + rtc_date_offset;
445 return seconds - time(NULL);
448 void rtc_change_mon_event(struct tm *tm)
450 QObject *data;
452 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
453 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
454 qobject_decref(data);
457 static void configure_rtc_date_offset(const char *startdate, int legacy)
459 time_t rtc_start_date;
460 struct tm tm;
462 if (!strcmp(startdate, "now") && legacy) {
463 rtc_date_offset = -1;
464 } else {
465 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
466 &tm.tm_year,
467 &tm.tm_mon,
468 &tm.tm_mday,
469 &tm.tm_hour,
470 &tm.tm_min,
471 &tm.tm_sec) == 6) {
472 /* OK */
473 } else if (sscanf(startdate, "%d-%d-%d",
474 &tm.tm_year,
475 &tm.tm_mon,
476 &tm.tm_mday) == 3) {
477 tm.tm_hour = 0;
478 tm.tm_min = 0;
479 tm.tm_sec = 0;
480 } else {
481 goto date_fail;
483 tm.tm_year -= 1900;
484 tm.tm_mon--;
485 rtc_start_date = mktimegm(&tm);
486 if (rtc_start_date == -1) {
487 date_fail:
488 fprintf(stderr, "Invalid date format. Valid formats are:\n"
489 "'2006-06-17T16:01:21' or '2006-06-17'\n");
490 exit(1);
492 rtc_date_offset = time(NULL) - rtc_start_date;
496 static void configure_rtc(QemuOpts *opts)
498 const char *value;
500 value = qemu_opt_get(opts, "base");
501 if (value) {
502 if (!strcmp(value, "utc")) {
503 rtc_utc = 1;
504 } else if (!strcmp(value, "localtime")) {
505 rtc_utc = 0;
506 } else {
507 configure_rtc_date_offset(value, 0);
510 value = qemu_opt_get(opts, "clock");
511 if (value) {
512 if (!strcmp(value, "host")) {
513 rtc_clock = host_clock;
514 } else if (!strcmp(value, "vm")) {
515 rtc_clock = vm_clock;
516 } else {
517 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
518 exit(1);
521 #ifdef CONFIG_TARGET_I386
522 value = qemu_opt_get(opts, "driftfix");
523 if (value) {
524 if (!strcmp(buf, "slew")) {
525 rtc_td_hack = 1;
526 } else if (!strcmp(buf, "none")) {
527 rtc_td_hack = 0;
528 } else {
529 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
530 exit(1);
533 #endif
536 #ifdef _WIN32
537 static void socket_cleanup(Notifier *obj)
539 WSACleanup();
542 static int socket_init(void)
544 WSADATA Data;
545 int ret, err;
546 static Notifier notifier = { .notify = socket_cleanup };
548 ret = WSAStartup(MAKEWORD(2,2), &Data);
549 if (ret != 0) {
550 err = WSAGetLastError();
551 fprintf(stderr, "WSAStartup: %d\n", err);
552 return -1;
554 exit_notifier_add(&notifier);
555 return 0;
557 #endif
559 /*********************/
560 /* Exit notifiers */
561 /*********************/
563 static NotifierList exit_notifiers = NOTIFIER_LIST_INITIALIZER(exit_notifiers);
565 void exit_notifier_add(Notifier *notifier)
567 notifier_list_add(&exit_notifiers, notifier);
570 void exit_notifier_remove(Notifier *notifier)
572 notifier_list_remove(&exit_notifiers, notifier);
575 static void exit_notifier_notify(void)
577 notifier_list_notify(&exit_notifiers);
580 static void exit_notifier_init(void)
582 atexit(exit_notifier_notify);
585 /***********************************************************/
586 /* Bluetooth support */
587 static int nb_hcis;
588 static int cur_hci;
589 static struct HCIInfo *hci_table[MAX_NICS];
591 static struct bt_vlan_s {
592 struct bt_scatternet_s net;
593 int id;
594 struct bt_vlan_s *next;
595 } *first_bt_vlan;
597 /* find or alloc a new bluetooth "VLAN" */
598 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
600 struct bt_vlan_s **pvlan, *vlan;
601 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
602 if (vlan->id == id)
603 return &vlan->net;
605 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
606 vlan->id = id;
607 pvlan = &first_bt_vlan;
608 while (*pvlan != NULL)
609 pvlan = &(*pvlan)->next;
610 *pvlan = vlan;
611 return &vlan->net;
614 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
618 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
620 return -ENOTSUP;
623 static struct HCIInfo null_hci = {
624 .cmd_send = null_hci_send,
625 .sco_send = null_hci_send,
626 .acl_send = null_hci_send,
627 .bdaddr_set = null_hci_addr_set,
630 struct HCIInfo *qemu_next_hci(void)
632 if (cur_hci == nb_hcis)
633 return &null_hci;
635 return hci_table[cur_hci++];
638 static struct HCIInfo *hci_init(const char *str)
640 char *endp;
641 struct bt_scatternet_s *vlan = 0;
643 if (!strcmp(str, "null"))
644 /* null */
645 return &null_hci;
646 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
647 /* host[:hciN] */
648 return bt_host_hci(str[4] ? str + 5 : "hci0");
649 else if (!strncmp(str, "hci", 3)) {
650 /* hci[,vlan=n] */
651 if (str[3]) {
652 if (!strncmp(str + 3, ",vlan=", 6)) {
653 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
654 if (*endp)
655 vlan = 0;
657 } else
658 vlan = qemu_find_bt_vlan(0);
659 if (vlan)
660 return bt_new_hci(vlan);
663 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
665 return 0;
668 static int bt_hci_parse(const char *str)
670 struct HCIInfo *hci;
671 bdaddr_t bdaddr;
673 if (nb_hcis >= MAX_NICS) {
674 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
675 return -1;
678 hci = hci_init(str);
679 if (!hci)
680 return -1;
682 bdaddr.b[0] = 0x52;
683 bdaddr.b[1] = 0x54;
684 bdaddr.b[2] = 0x00;
685 bdaddr.b[3] = 0x12;
686 bdaddr.b[4] = 0x34;
687 bdaddr.b[5] = 0x56 + nb_hcis;
688 hci->bdaddr_set(hci, bdaddr.b);
690 hci_table[nb_hcis++] = hci;
692 return 0;
695 static void bt_vhci_add(int vlan_id)
697 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
699 if (!vlan->slave)
700 fprintf(stderr, "qemu: warning: adding a VHCI to "
701 "an empty scatternet %i\n", vlan_id);
703 bt_vhci_init(bt_new_hci(vlan));
706 static struct bt_device_s *bt_device_add(const char *opt)
708 struct bt_scatternet_s *vlan;
709 int vlan_id = 0;
710 char *endp = strstr(opt, ",vlan=");
711 int len = (endp ? endp - opt : strlen(opt)) + 1;
712 char devname[10];
714 pstrcpy(devname, MIN(sizeof(devname), len), opt);
716 if (endp) {
717 vlan_id = strtol(endp + 6, &endp, 0);
718 if (*endp) {
719 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
720 return 0;
724 vlan = qemu_find_bt_vlan(vlan_id);
726 if (!vlan->slave)
727 fprintf(stderr, "qemu: warning: adding a slave device to "
728 "an empty scatternet %i\n", vlan_id);
730 if (!strcmp(devname, "keyboard"))
731 return bt_keyboard_init(vlan);
733 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
734 return 0;
737 static int bt_parse(const char *opt)
739 const char *endp, *p;
740 int vlan;
742 if (strstart(opt, "hci", &endp)) {
743 if (!*endp || *endp == ',') {
744 if (*endp)
745 if (!strstart(endp, ",vlan=", 0))
746 opt = endp + 1;
748 return bt_hci_parse(opt);
750 } else if (strstart(opt, "vhci", &endp)) {
751 if (!*endp || *endp == ',') {
752 if (*endp) {
753 if (strstart(endp, ",vlan=", &p)) {
754 vlan = strtol(p, (char **) &endp, 0);
755 if (*endp) {
756 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
757 return 1;
759 } else {
760 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
761 return 1;
763 } else
764 vlan = 0;
766 bt_vhci_add(vlan);
767 return 0;
769 } else if (strstart(opt, "device:", &endp))
770 return !bt_device_add(endp);
772 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
773 return 1;
776 /***********************************************************/
777 /* QEMU Block devices */
779 #define HD_ALIAS "index=%d,media=disk"
780 #define CDROM_ALIAS "index=2,media=cdrom"
781 #define FD_ALIAS "index=%d,if=floppy"
782 #define PFLASH_ALIAS "if=pflash"
783 #define MTD_ALIAS "if=mtd"
784 #define SD_ALIAS "index=0,if=sd"
786 QemuOpts *drive_add(const char *file, const char *fmt, ...)
788 va_list ap;
789 char optstr[1024];
790 QemuOpts *opts;
792 va_start(ap, fmt);
793 vsnprintf(optstr, sizeof(optstr), fmt, ap);
794 va_end(ap);
796 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
797 if (!opts) {
798 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
799 __FUNCTION__, optstr);
800 return NULL;
802 if (file)
803 qemu_opt_set(opts, "file", file);
804 return opts;
807 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
809 DriveInfo *dinfo;
811 /* seek interface, bus and unit */
813 QTAILQ_FOREACH(dinfo, &drives, next) {
814 if (dinfo->type == type &&
815 dinfo->bus == bus &&
816 dinfo->unit == unit)
817 return dinfo;
820 return NULL;
823 DriveInfo *drive_get_by_id(const char *id)
825 DriveInfo *dinfo;
827 QTAILQ_FOREACH(dinfo, &drives, next) {
828 if (strcmp(id, dinfo->id))
829 continue;
830 return dinfo;
832 return NULL;
835 int drive_get_max_bus(BlockInterfaceType type)
837 int max_bus;
838 DriveInfo *dinfo;
840 max_bus = -1;
841 QTAILQ_FOREACH(dinfo, &drives, next) {
842 if(dinfo->type == type &&
843 dinfo->bus > max_bus)
844 max_bus = dinfo->bus;
846 return max_bus;
849 const char *drive_get_serial(BlockDriverState *bdrv)
851 DriveInfo *dinfo;
853 QTAILQ_FOREACH(dinfo, &drives, next) {
854 if (dinfo->bdrv == bdrv)
855 return dinfo->serial;
858 return "\0";
861 BlockInterfaceErrorAction drive_get_on_error(
862 BlockDriverState *bdrv, int is_read)
864 DriveInfo *dinfo;
866 QTAILQ_FOREACH(dinfo, &drives, next) {
867 if (dinfo->bdrv == bdrv)
868 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
871 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
874 static void bdrv_format_print(void *opaque, const char *name)
876 fprintf(stderr, " %s", name);
879 void drive_uninit(DriveInfo *dinfo)
881 qemu_opts_del(dinfo->opts);
882 bdrv_delete(dinfo->bdrv);
883 QTAILQ_REMOVE(&drives, dinfo, next);
884 qemu_free(dinfo);
887 static int parse_block_error_action(const char *buf, int is_read)
889 if (!strcmp(buf, "ignore")) {
890 return BLOCK_ERR_IGNORE;
891 } else if (!is_read && !strcmp(buf, "enospc")) {
892 return BLOCK_ERR_STOP_ENOSPC;
893 } else if (!strcmp(buf, "stop")) {
894 return BLOCK_ERR_STOP_ANY;
895 } else if (!strcmp(buf, "report")) {
896 return BLOCK_ERR_REPORT;
897 } else {
898 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
899 buf, is_read ? "read" : "write");
900 return -1;
904 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
905 int *fatal_error)
907 const char *buf;
908 const char *file = NULL;
909 char devname[128];
910 const char *serial;
911 const char *mediastr = "";
912 BlockInterfaceType type;
913 enum { MEDIA_DISK, MEDIA_CDROM } media;
914 int bus_id, unit_id;
915 int cyls, heads, secs, translation;
916 BlockDriver *drv = NULL;
917 QEMUMachine *machine = opaque;
918 int max_devs;
919 int index;
920 int cache;
921 int aio = 0;
922 int ro = 0;
923 int bdrv_flags;
924 int on_read_error, on_write_error;
925 const char *devaddr;
926 DriveInfo *dinfo;
927 int snapshot = 0;
929 *fatal_error = 1;
931 translation = BIOS_ATA_TRANSLATION_AUTO;
932 cache = 1;
934 if (machine && machine->use_scsi) {
935 type = IF_SCSI;
936 max_devs = MAX_SCSI_DEVS;
937 pstrcpy(devname, sizeof(devname), "scsi");
938 } else {
939 type = IF_IDE;
940 max_devs = MAX_IDE_DEVS;
941 pstrcpy(devname, sizeof(devname), "ide");
943 media = MEDIA_DISK;
945 /* extract parameters */
946 bus_id = qemu_opt_get_number(opts, "bus", 0);
947 unit_id = qemu_opt_get_number(opts, "unit", -1);
948 index = qemu_opt_get_number(opts, "index", -1);
950 cyls = qemu_opt_get_number(opts, "cyls", 0);
951 heads = qemu_opt_get_number(opts, "heads", 0);
952 secs = qemu_opt_get_number(opts, "secs", 0);
954 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
955 ro = qemu_opt_get_bool(opts, "readonly", 0);
957 file = qemu_opt_get(opts, "file");
958 serial = qemu_opt_get(opts, "serial");
960 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
961 pstrcpy(devname, sizeof(devname), buf);
962 if (!strcmp(buf, "ide")) {
963 type = IF_IDE;
964 max_devs = MAX_IDE_DEVS;
965 } else if (!strcmp(buf, "scsi")) {
966 type = IF_SCSI;
967 max_devs = MAX_SCSI_DEVS;
968 } else if (!strcmp(buf, "floppy")) {
969 type = IF_FLOPPY;
970 max_devs = 0;
971 } else if (!strcmp(buf, "pflash")) {
972 type = IF_PFLASH;
973 max_devs = 0;
974 } else if (!strcmp(buf, "mtd")) {
975 type = IF_MTD;
976 max_devs = 0;
977 } else if (!strcmp(buf, "sd")) {
978 type = IF_SD;
979 max_devs = 0;
980 } else if (!strcmp(buf, "virtio")) {
981 type = IF_VIRTIO;
982 max_devs = 0;
983 } else if (!strcmp(buf, "xen")) {
984 type = IF_XEN;
985 max_devs = 0;
986 } else if (!strcmp(buf, "none")) {
987 type = IF_NONE;
988 max_devs = 0;
989 } else {
990 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
991 return NULL;
995 if (cyls || heads || secs) {
996 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
997 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
998 return NULL;
1000 if (heads < 1 || (type == IF_IDE && heads > 16)) {
1001 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1002 return NULL;
1004 if (secs < 1 || (type == IF_IDE && secs > 63)) {
1005 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1006 return NULL;
1010 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1011 if (!cyls) {
1012 fprintf(stderr,
1013 "qemu: '%s' trans must be used with cyls,heads and secs\n",
1014 buf);
1015 return NULL;
1017 if (!strcmp(buf, "none"))
1018 translation = BIOS_ATA_TRANSLATION_NONE;
1019 else if (!strcmp(buf, "lba"))
1020 translation = BIOS_ATA_TRANSLATION_LBA;
1021 else if (!strcmp(buf, "auto"))
1022 translation = BIOS_ATA_TRANSLATION_AUTO;
1023 else {
1024 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
1025 return NULL;
1029 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
1030 if (!strcmp(buf, "disk")) {
1031 media = MEDIA_DISK;
1032 } else if (!strcmp(buf, "cdrom")) {
1033 if (cyls || secs || heads) {
1034 fprintf(stderr,
1035 "qemu: '%s' invalid physical CHS format\n", buf);
1036 return NULL;
1038 media = MEDIA_CDROM;
1039 } else {
1040 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
1041 return NULL;
1045 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
1046 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
1047 cache = 0;
1048 else if (!strcmp(buf, "writethrough"))
1049 cache = 1;
1050 else if (!strcmp(buf, "writeback"))
1051 cache = 2;
1052 else {
1053 fprintf(stderr, "qemu: invalid cache option\n");
1054 return NULL;
1058 #ifdef CONFIG_LINUX_AIO
1059 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1060 if (!strcmp(buf, "threads"))
1061 aio = 0;
1062 else if (!strcmp(buf, "native"))
1063 aio = 1;
1064 else {
1065 fprintf(stderr, "qemu: invalid aio option\n");
1066 return NULL;
1069 #endif
1071 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1072 if (strcmp(buf, "?") == 0) {
1073 fprintf(stderr, "qemu: Supported formats:");
1074 bdrv_iterate_format(bdrv_format_print, NULL);
1075 fprintf(stderr, "\n");
1076 return NULL;
1078 drv = bdrv_find_whitelisted_format(buf);
1079 if (!drv) {
1080 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1081 return NULL;
1085 on_write_error = BLOCK_ERR_STOP_ENOSPC;
1086 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1087 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1088 fprintf(stderr, "werror is no supported by this format\n");
1089 return NULL;
1092 on_write_error = parse_block_error_action(buf, 0);
1093 if (on_write_error < 0) {
1094 return NULL;
1098 on_read_error = BLOCK_ERR_REPORT;
1099 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1100 if (type != IF_IDE && type != IF_VIRTIO) {
1101 fprintf(stderr, "rerror is no supported by this format\n");
1102 return NULL;
1105 on_read_error = parse_block_error_action(buf, 1);
1106 if (on_read_error < 0) {
1107 return NULL;
1111 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1112 if (type != IF_VIRTIO) {
1113 fprintf(stderr, "addr is not supported\n");
1114 return NULL;
1118 /* compute bus and unit according index */
1120 if (index != -1) {
1121 if (bus_id != 0 || unit_id != -1) {
1122 fprintf(stderr,
1123 "qemu: index cannot be used with bus and unit\n");
1124 return NULL;
1126 if (max_devs == 0)
1128 unit_id = index;
1129 bus_id = 0;
1130 } else {
1131 unit_id = index % max_devs;
1132 bus_id = index / max_devs;
1136 /* if user doesn't specify a unit_id,
1137 * try to find the first free
1140 if (unit_id == -1) {
1141 unit_id = 0;
1142 while (drive_get(type, bus_id, unit_id) != NULL) {
1143 unit_id++;
1144 if (max_devs && unit_id >= max_devs) {
1145 unit_id -= max_devs;
1146 bus_id++;
1151 /* check unit id */
1153 if (max_devs && unit_id >= max_devs) {
1154 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1155 unit_id, max_devs - 1);
1156 return NULL;
1160 * ignore multiple definitions
1163 if (drive_get(type, bus_id, unit_id) != NULL) {
1164 *fatal_error = 0;
1165 return NULL;
1168 /* init */
1170 dinfo = qemu_mallocz(sizeof(*dinfo));
1171 if ((buf = qemu_opts_id(opts)) != NULL) {
1172 dinfo->id = qemu_strdup(buf);
1173 } else {
1174 /* no id supplied -> create one */
1175 dinfo->id = qemu_mallocz(32);
1176 if (type == IF_IDE || type == IF_SCSI)
1177 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1178 if (max_devs)
1179 snprintf(dinfo->id, 32, "%s%i%s%i",
1180 devname, bus_id, mediastr, unit_id);
1181 else
1182 snprintf(dinfo->id, 32, "%s%s%i",
1183 devname, mediastr, unit_id);
1185 dinfo->bdrv = bdrv_new(dinfo->id);
1186 dinfo->devaddr = devaddr;
1187 dinfo->type = type;
1188 dinfo->bus = bus_id;
1189 dinfo->unit = unit_id;
1190 dinfo->on_read_error = on_read_error;
1191 dinfo->on_write_error = on_write_error;
1192 dinfo->opts = opts;
1193 if (serial)
1194 strncpy(dinfo->serial, serial, sizeof(serial));
1195 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1197 switch(type) {
1198 case IF_IDE:
1199 case IF_SCSI:
1200 case IF_XEN:
1201 case IF_NONE:
1202 switch(media) {
1203 case MEDIA_DISK:
1204 if (cyls != 0) {
1205 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1206 bdrv_set_translation_hint(dinfo->bdrv, translation);
1208 break;
1209 case MEDIA_CDROM:
1210 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1211 break;
1213 break;
1214 case IF_SD:
1215 /* FIXME: This isn't really a floppy, but it's a reasonable
1216 approximation. */
1217 case IF_FLOPPY:
1218 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1219 break;
1220 case IF_PFLASH:
1221 case IF_MTD:
1222 break;
1223 case IF_VIRTIO:
1224 /* add virtio block device */
1225 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1226 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1227 qemu_opt_set(opts, "drive", dinfo->id);
1228 if (devaddr)
1229 qemu_opt_set(opts, "addr", devaddr);
1230 break;
1231 case IF_COUNT:
1232 abort();
1234 if (!file) {
1235 *fatal_error = 0;
1236 return NULL;
1238 bdrv_flags = 0;
1239 if (snapshot) {
1240 bdrv_flags |= BDRV_O_SNAPSHOT;
1241 cache = 2; /* always use write-back with snapshot */
1243 if (cache == 0) /* no caching */
1244 bdrv_flags |= BDRV_O_NOCACHE;
1245 else if (cache == 2) /* write-back */
1246 bdrv_flags |= BDRV_O_CACHE_WB;
1248 if (aio == 1) {
1249 bdrv_flags |= BDRV_O_NATIVE_AIO;
1250 } else {
1251 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1254 if (ro == 1) {
1255 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1256 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1257 return NULL;
1261 * cdrom is read-only. Set it now, after above interface checking
1262 * since readonly attribute not explicitly required, so no error.
1264 if (media == MEDIA_CDROM) {
1265 ro = 1;
1267 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1269 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1270 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1271 file, strerror(errno));
1272 return NULL;
1275 if (bdrv_key_required(dinfo->bdrv))
1276 autostart = 0;
1277 *fatal_error = 0;
1278 return dinfo;
1281 static int drive_init_func(QemuOpts *opts, void *opaque)
1283 QEMUMachine *machine = opaque;
1284 int fatal_error = 0;
1286 if (drive_init(opts, machine, &fatal_error) == NULL) {
1287 if (fatal_error)
1288 return 1;
1290 return 0;
1293 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1295 if (NULL == qemu_opt_get(opts, "snapshot")) {
1296 qemu_opt_set(opts, "snapshot", "on");
1298 return 0;
1301 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1303 boot_set_handler = func;
1304 boot_set_opaque = opaque;
1307 int qemu_boot_set(const char *boot_devices)
1309 if (!boot_set_handler) {
1310 return -EINVAL;
1312 return boot_set_handler(boot_set_opaque, boot_devices);
1315 static int parse_bootdevices(char *devices)
1317 /* We just do some generic consistency checks */
1318 const char *p;
1319 int bitmap = 0;
1321 for (p = devices; *p != '\0'; p++) {
1322 /* Allowed boot devices are:
1323 * a-b: floppy disk drives
1324 * c-f: IDE disk drives
1325 * g-m: machine implementation dependant drives
1326 * n-p: network devices
1327 * It's up to each machine implementation to check if the given boot
1328 * devices match the actual hardware implementation and firmware
1329 * features.
1331 if (*p < 'a' || *p > 'p') {
1332 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1333 exit(1);
1335 if (bitmap & (1 << (*p - 'a'))) {
1336 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1337 exit(1);
1339 bitmap |= 1 << (*p - 'a');
1341 return bitmap;
1344 static void restore_boot_devices(void *opaque)
1346 char *standard_boot_devices = opaque;
1348 qemu_boot_set(standard_boot_devices);
1350 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1351 qemu_free(standard_boot_devices);
1354 static void numa_add(const char *optarg)
1356 char option[128];
1357 char *endptr;
1358 unsigned long long value, endvalue;
1359 int nodenr;
1361 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1362 if (!strcmp(option, "node")) {
1363 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1364 nodenr = nb_numa_nodes;
1365 } else {
1366 nodenr = strtoull(option, NULL, 10);
1369 if (get_param_value(option, 128, "mem", optarg) == 0) {
1370 node_mem[nodenr] = 0;
1371 } else {
1372 value = strtoull(option, &endptr, 0);
1373 switch (*endptr) {
1374 case 0: case 'M': case 'm':
1375 value <<= 20;
1376 break;
1377 case 'G': case 'g':
1378 value <<= 30;
1379 break;
1381 node_mem[nodenr] = value;
1383 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1384 node_cpumask[nodenr] = 0;
1385 } else {
1386 value = strtoull(option, &endptr, 10);
1387 if (value >= 64) {
1388 value = 63;
1389 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1390 } else {
1391 if (*endptr == '-') {
1392 endvalue = strtoull(endptr+1, &endptr, 10);
1393 if (endvalue >= 63) {
1394 endvalue = 62;
1395 fprintf(stderr,
1396 "only 63 CPUs in NUMA mode supported.\n");
1398 value = (2ULL << endvalue) - (1ULL << value);
1399 } else {
1400 value = 1ULL << value;
1403 node_cpumask[nodenr] = value;
1405 nb_numa_nodes++;
1407 return;
1410 static void smp_parse(const char *optarg)
1412 int smp, sockets = 0, threads = 0, cores = 0;
1413 char *endptr;
1414 char option[128];
1416 smp = strtoul(optarg, &endptr, 10);
1417 if (endptr != optarg) {
1418 if (*endptr == ',') {
1419 endptr++;
1422 if (get_param_value(option, 128, "sockets", endptr) != 0)
1423 sockets = strtoull(option, NULL, 10);
1424 if (get_param_value(option, 128, "cores", endptr) != 0)
1425 cores = strtoull(option, NULL, 10);
1426 if (get_param_value(option, 128, "threads", endptr) != 0)
1427 threads = strtoull(option, NULL, 10);
1428 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1429 max_cpus = strtoull(option, NULL, 10);
1431 /* compute missing values, prefer sockets over cores over threads */
1432 if (smp == 0 || sockets == 0) {
1433 sockets = sockets > 0 ? sockets : 1;
1434 cores = cores > 0 ? cores : 1;
1435 threads = threads > 0 ? threads : 1;
1436 if (smp == 0) {
1437 smp = cores * threads * sockets;
1439 } else {
1440 if (cores == 0) {
1441 threads = threads > 0 ? threads : 1;
1442 cores = smp / (sockets * threads);
1443 } else {
1444 if (sockets) {
1445 threads = smp / (cores * sockets);
1449 smp_cpus = smp;
1450 smp_cores = cores > 0 ? cores : 1;
1451 smp_threads = threads > 0 ? threads : 1;
1452 if (max_cpus == 0)
1453 max_cpus = smp_cpus;
1456 /***********************************************************/
1457 /* USB devices */
1459 static int usb_device_add(const char *devname, int is_hotplug)
1461 const char *p;
1462 USBDevice *dev = NULL;
1464 if (!usb_enabled)
1465 return -1;
1467 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1468 dev = usbdevice_create(devname);
1469 if (dev)
1470 goto done;
1472 /* the other ones */
1473 if (strstart(devname, "host:", &p)) {
1474 dev = usb_host_device_open(p);
1475 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1476 dev = usb_bt_init(devname[2] ? hci_init(p) :
1477 bt_new_hci(qemu_find_bt_vlan(0)));
1478 } else {
1479 return -1;
1481 if (!dev)
1482 return -1;
1484 done:
1485 return 0;
1488 static int usb_device_del(const char *devname)
1490 int bus_num, addr;
1491 const char *p;
1493 if (strstart(devname, "host:", &p))
1494 return usb_host_device_close(p);
1496 if (!usb_enabled)
1497 return -1;
1499 p = strchr(devname, '.');
1500 if (!p)
1501 return -1;
1502 bus_num = strtoul(devname, NULL, 0);
1503 addr = strtoul(p + 1, NULL, 0);
1505 return usb_device_delete_addr(bus_num, addr);
1508 static int usb_parse(const char *cmdline)
1510 int r;
1511 r = usb_device_add(cmdline, 0);
1512 if (r < 0) {
1513 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1515 return r;
1518 void do_usb_add(Monitor *mon, const QDict *qdict)
1520 const char *devname = qdict_get_str(qdict, "devname");
1521 if (usb_device_add(devname, 1) < 0) {
1522 error_report("could not add USB device '%s'", devname);
1526 void do_usb_del(Monitor *mon, const QDict *qdict)
1528 const char *devname = qdict_get_str(qdict, "devname");
1529 if (usb_device_del(devname) < 0) {
1530 error_report("could not delete USB device '%s'", devname);
1534 /***********************************************************/
1535 /* PCMCIA/Cardbus */
1537 static struct pcmcia_socket_entry_s {
1538 PCMCIASocket *socket;
1539 struct pcmcia_socket_entry_s *next;
1540 } *pcmcia_sockets = 0;
1542 void pcmcia_socket_register(PCMCIASocket *socket)
1544 struct pcmcia_socket_entry_s *entry;
1546 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1547 entry->socket = socket;
1548 entry->next = pcmcia_sockets;
1549 pcmcia_sockets = entry;
1552 void pcmcia_socket_unregister(PCMCIASocket *socket)
1554 struct pcmcia_socket_entry_s *entry, **ptr;
1556 ptr = &pcmcia_sockets;
1557 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1558 if (entry->socket == socket) {
1559 *ptr = entry->next;
1560 qemu_free(entry);
1564 void pcmcia_info(Monitor *mon)
1566 struct pcmcia_socket_entry_s *iter;
1568 if (!pcmcia_sockets)
1569 monitor_printf(mon, "No PCMCIA sockets\n");
1571 for (iter = pcmcia_sockets; iter; iter = iter->next)
1572 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1573 iter->socket->attached ? iter->socket->card_string :
1574 "Empty");
1577 /***********************************************************/
1578 /* I/O handling */
1580 typedef struct IOHandlerRecord {
1581 int fd;
1582 IOCanReadHandler *fd_read_poll;
1583 IOHandler *fd_read;
1584 IOHandler *fd_write;
1585 int deleted;
1586 void *opaque;
1587 /* temporary data */
1588 struct pollfd *ufd;
1589 QLIST_ENTRY(IOHandlerRecord) next;
1590 } IOHandlerRecord;
1592 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1593 QLIST_HEAD_INITIALIZER(io_handlers);
1596 /* XXX: fd_read_poll should be suppressed, but an API change is
1597 necessary in the character devices to suppress fd_can_read(). */
1598 int qemu_set_fd_handler2(int fd,
1599 IOCanReadHandler *fd_read_poll,
1600 IOHandler *fd_read,
1601 IOHandler *fd_write,
1602 void *opaque)
1604 IOHandlerRecord *ioh;
1606 if (!fd_read && !fd_write) {
1607 QLIST_FOREACH(ioh, &io_handlers, next) {
1608 if (ioh->fd == fd) {
1609 ioh->deleted = 1;
1610 break;
1613 } else {
1614 QLIST_FOREACH(ioh, &io_handlers, next) {
1615 if (ioh->fd == fd)
1616 goto found;
1618 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1619 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1620 found:
1621 ioh->fd = fd;
1622 ioh->fd_read_poll = fd_read_poll;
1623 ioh->fd_read = fd_read;
1624 ioh->fd_write = fd_write;
1625 ioh->opaque = opaque;
1626 ioh->deleted = 0;
1628 return 0;
1631 int qemu_set_fd_handler(int fd,
1632 IOHandler *fd_read,
1633 IOHandler *fd_write,
1634 void *opaque)
1636 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1639 #ifdef _WIN32
1640 /***********************************************************/
1641 /* Polling handling */
1643 typedef struct PollingEntry {
1644 PollingFunc *func;
1645 void *opaque;
1646 struct PollingEntry *next;
1647 } PollingEntry;
1649 static PollingEntry *first_polling_entry;
1651 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1653 PollingEntry **ppe, *pe;
1654 pe = qemu_mallocz(sizeof(PollingEntry));
1655 pe->func = func;
1656 pe->opaque = opaque;
1657 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1658 *ppe = pe;
1659 return 0;
1662 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1664 PollingEntry **ppe, *pe;
1665 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1666 pe = *ppe;
1667 if (pe->func == func && pe->opaque == opaque) {
1668 *ppe = pe->next;
1669 qemu_free(pe);
1670 break;
1675 /***********************************************************/
1676 /* Wait objects support */
1677 typedef struct WaitObjects {
1678 int num;
1679 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1680 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1681 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1682 } WaitObjects;
1684 static WaitObjects wait_objects = {0};
1686 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1688 WaitObjects *w = &wait_objects;
1690 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1691 return -1;
1692 w->events[w->num] = handle;
1693 w->func[w->num] = func;
1694 w->opaque[w->num] = opaque;
1695 w->num++;
1696 return 0;
1699 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1701 int i, found;
1702 WaitObjects *w = &wait_objects;
1704 found = 0;
1705 for (i = 0; i < w->num; i++) {
1706 if (w->events[i] == handle)
1707 found = 1;
1708 if (found) {
1709 w->events[i] = w->events[i + 1];
1710 w->func[i] = w->func[i + 1];
1711 w->opaque[i] = w->opaque[i + 1];
1714 if (found)
1715 w->num--;
1717 #endif
1719 /***********************************************************/
1720 /* ram save/restore */
1722 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
1723 #define RAM_SAVE_FLAG_COMPRESS 0x02
1724 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
1725 #define RAM_SAVE_FLAG_PAGE 0x08
1726 #define RAM_SAVE_FLAG_EOS 0x10
1728 static int is_dup_page(uint8_t *page, uint8_t ch)
1730 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1731 uint32_t *array = (uint32_t *)page;
1732 int i;
1734 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1735 if (array[i] != val)
1736 return 0;
1739 return 1;
1742 static int ram_save_block(QEMUFile *f)
1744 static ram_addr_t current_addr = 0;
1745 ram_addr_t saved_addr = current_addr;
1746 ram_addr_t addr = 0;
1747 int found = 0;
1749 while (addr < last_ram_offset) {
1750 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1751 uint8_t *p;
1753 cpu_physical_memory_reset_dirty(current_addr,
1754 current_addr + TARGET_PAGE_SIZE,
1755 MIGRATION_DIRTY_FLAG);
1757 p = qemu_get_ram_ptr(current_addr);
1759 if (is_dup_page(p, *p)) {
1760 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1761 qemu_put_byte(f, *p);
1762 } else {
1763 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1764 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1767 found = 1;
1768 break;
1770 addr += TARGET_PAGE_SIZE;
1771 current_addr = (saved_addr + addr) % last_ram_offset;
1774 return found;
1777 static uint64_t bytes_transferred;
1779 static ram_addr_t ram_save_remaining(void)
1781 ram_addr_t addr;
1782 ram_addr_t count = 0;
1784 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1785 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1786 count++;
1789 return count;
1792 uint64_t ram_bytes_remaining(void)
1794 return ram_save_remaining() * TARGET_PAGE_SIZE;
1797 uint64_t ram_bytes_transferred(void)
1799 return bytes_transferred;
1802 uint64_t ram_bytes_total(void)
1804 return last_ram_offset;
1807 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1809 ram_addr_t addr;
1810 uint64_t bytes_transferred_last;
1811 double bwidth = 0;
1812 uint64_t expected_time = 0;
1814 if (stage < 0) {
1815 cpu_physical_memory_set_dirty_tracking(0);
1816 return 0;
1819 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1820 qemu_file_set_error(f);
1821 return 0;
1824 if (stage == 1) {
1825 bytes_transferred = 0;
1827 /* Make sure all dirty bits are set */
1828 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1829 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1830 cpu_physical_memory_set_dirty(addr);
1833 /* Enable dirty memory tracking */
1834 cpu_physical_memory_set_dirty_tracking(1);
1836 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1839 bytes_transferred_last = bytes_transferred;
1840 bwidth = qemu_get_clock_ns(rt_clock);
1842 while (!qemu_file_rate_limit(f)) {
1843 int ret;
1845 ret = ram_save_block(f);
1846 bytes_transferred += ret * TARGET_PAGE_SIZE;
1847 if (ret == 0) /* no more blocks */
1848 break;
1851 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1852 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1854 /* if we haven't transferred anything this round, force expected_time to a
1855 * a very high value, but without crashing */
1856 if (bwidth == 0)
1857 bwidth = 0.000001;
1859 /* try transferring iterative blocks of memory */
1860 if (stage == 3) {
1861 /* flush all remaining blocks regardless of rate limiting */
1862 while (ram_save_block(f) != 0) {
1863 bytes_transferred += TARGET_PAGE_SIZE;
1865 cpu_physical_memory_set_dirty_tracking(0);
1868 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1870 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1872 return (stage == 2) && (expected_time <= migrate_max_downtime());
1875 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1877 ram_addr_t addr;
1878 int flags;
1880 if (version_id != 3)
1881 return -EINVAL;
1883 do {
1884 addr = qemu_get_be64(f);
1886 flags = addr & ~TARGET_PAGE_MASK;
1887 addr &= TARGET_PAGE_MASK;
1889 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1890 if (addr != last_ram_offset)
1891 return -EINVAL;
1894 if (flags & RAM_SAVE_FLAG_COMPRESS) {
1895 uint8_t ch = qemu_get_byte(f);
1896 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1897 #ifndef _WIN32
1898 if (ch == 0 &&
1899 (!kvm_enabled() || kvm_has_sync_mmu())) {
1900 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1902 #endif
1903 } else if (flags & RAM_SAVE_FLAG_PAGE) {
1904 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1906 if (qemu_file_has_error(f)) {
1907 return -EIO;
1909 } while (!(flags & RAM_SAVE_FLAG_EOS));
1911 return 0;
1914 void qemu_service_io(void)
1916 qemu_notify_event();
1919 /***********************************************************/
1920 /* machine registration */
1922 static QEMUMachine *first_machine = NULL;
1923 QEMUMachine *current_machine = NULL;
1925 int qemu_register_machine(QEMUMachine *m)
1927 QEMUMachine **pm;
1928 pm = &first_machine;
1929 while (*pm != NULL)
1930 pm = &(*pm)->next;
1931 m->next = NULL;
1932 *pm = m;
1933 return 0;
1936 static QEMUMachine *find_machine(const char *name)
1938 QEMUMachine *m;
1940 for(m = first_machine; m != NULL; m = m->next) {
1941 if (!strcmp(m->name, name))
1942 return m;
1943 if (m->alias && !strcmp(m->alias, name))
1944 return m;
1946 return NULL;
1949 static QEMUMachine *find_default_machine(void)
1951 QEMUMachine *m;
1953 for(m = first_machine; m != NULL; m = m->next) {
1954 if (m->is_default) {
1955 return m;
1958 return NULL;
1961 /***********************************************************/
1962 /* main execution loop */
1964 static void gui_update(void *opaque)
1966 uint64_t interval = GUI_REFRESH_INTERVAL;
1967 DisplayState *ds = opaque;
1968 DisplayChangeListener *dcl = ds->listeners;
1970 qemu_flush_coalesced_mmio_buffer();
1971 dpy_refresh(ds);
1973 while (dcl != NULL) {
1974 if (dcl->gui_timer_interval &&
1975 dcl->gui_timer_interval < interval)
1976 interval = dcl->gui_timer_interval;
1977 dcl = dcl->next;
1979 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1982 static void nographic_update(void *opaque)
1984 uint64_t interval = GUI_REFRESH_INTERVAL;
1986 qemu_flush_coalesced_mmio_buffer();
1987 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1990 void cpu_synchronize_all_states(void)
1992 CPUState *cpu;
1994 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1995 cpu_synchronize_state(cpu);
1999 void cpu_synchronize_all_post_reset(void)
2001 CPUState *cpu;
2003 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2004 cpu_synchronize_post_reset(cpu);
2008 void cpu_synchronize_all_post_init(void)
2010 CPUState *cpu;
2012 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2013 cpu_synchronize_post_init(cpu);
2017 struct vm_change_state_entry {
2018 VMChangeStateHandler *cb;
2019 void *opaque;
2020 QLIST_ENTRY (vm_change_state_entry) entries;
2023 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
2025 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
2026 void *opaque)
2028 VMChangeStateEntry *e;
2030 e = qemu_mallocz(sizeof (*e));
2032 e->cb = cb;
2033 e->opaque = opaque;
2034 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
2035 return e;
2038 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
2040 QLIST_REMOVE (e, entries);
2041 qemu_free (e);
2044 static void vm_state_notify(int running, int reason)
2046 VMChangeStateEntry *e;
2048 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
2049 e->cb(e->opaque, running, reason);
2053 static void resume_all_vcpus(void);
2054 static void pause_all_vcpus(void);
2056 void vm_start(void)
2058 if (!vm_running) {
2059 cpu_enable_ticks();
2060 vm_running = 1;
2061 vm_state_notify(1, 0);
2062 resume_all_vcpus();
2066 /* reset/shutdown handler */
2068 typedef struct QEMUResetEntry {
2069 QTAILQ_ENTRY(QEMUResetEntry) entry;
2070 QEMUResetHandler *func;
2071 void *opaque;
2072 } QEMUResetEntry;
2074 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
2075 QTAILQ_HEAD_INITIALIZER(reset_handlers);
2076 static int reset_requested;
2077 static int shutdown_requested;
2078 static int powerdown_requested;
2079 static int debug_requested;
2080 static int vmstop_requested;
2082 int qemu_shutdown_requested(void)
2084 int r = shutdown_requested;
2085 shutdown_requested = 0;
2086 return r;
2089 int qemu_reset_requested(void)
2091 int r = reset_requested;
2092 reset_requested = 0;
2093 return r;
2096 int qemu_powerdown_requested(void)
2098 int r = powerdown_requested;
2099 powerdown_requested = 0;
2100 return r;
2103 static int qemu_debug_requested(void)
2105 int r = debug_requested;
2106 debug_requested = 0;
2107 return r;
2110 static int qemu_vmstop_requested(void)
2112 int r = vmstop_requested;
2113 vmstop_requested = 0;
2114 return r;
2117 static void do_vm_stop(int reason)
2119 if (vm_running) {
2120 cpu_disable_ticks();
2121 vm_running = 0;
2122 pause_all_vcpus();
2123 vm_state_notify(0, reason);
2124 monitor_protocol_event(QEVENT_STOP, NULL);
2128 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2130 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2132 re->func = func;
2133 re->opaque = opaque;
2134 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2137 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2139 QEMUResetEntry *re;
2141 QTAILQ_FOREACH(re, &reset_handlers, entry) {
2142 if (re->func == func && re->opaque == opaque) {
2143 QTAILQ_REMOVE(&reset_handlers, re, entry);
2144 qemu_free(re);
2145 return;
2150 void qemu_system_reset(void)
2152 QEMUResetEntry *re, *nre;
2154 /* reset all devices */
2155 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2156 re->func(re->opaque);
2158 monitor_protocol_event(QEVENT_RESET, NULL);
2159 cpu_synchronize_all_post_reset();
2162 void qemu_system_reset_request(void)
2164 if (no_reboot) {
2165 shutdown_requested = 1;
2166 } else {
2167 reset_requested = 1;
2169 qemu_notify_event();
2172 void qemu_system_shutdown_request(void)
2174 shutdown_requested = 1;
2175 qemu_notify_event();
2178 void qemu_system_powerdown_request(void)
2180 powerdown_requested = 1;
2181 qemu_notify_event();
2184 static int cpu_can_run(CPUState *env)
2186 if (env->stop)
2187 return 0;
2188 if (env->stopped)
2189 return 0;
2190 if (!vm_running)
2191 return 0;
2192 return 1;
2195 static int cpu_has_work(CPUState *env)
2197 if (env->stop)
2198 return 1;
2199 if (env->stopped)
2200 return 0;
2201 if (!env->halted)
2202 return 1;
2203 if (qemu_cpu_has_work(env))
2204 return 1;
2205 return 0;
2208 static int tcg_has_work(void)
2210 CPUState *env;
2212 for (env = first_cpu; env != NULL; env = env->next_cpu)
2213 if (cpu_has_work(env))
2214 return 1;
2215 return 0;
2218 #ifndef _WIN32
2219 static int io_thread_fd = -1;
2221 static void qemu_event_increment(void)
2223 /* Write 8 bytes to be compatible with eventfd. */
2224 static uint64_t val = 1;
2225 ssize_t ret;
2227 if (io_thread_fd == -1)
2228 return;
2230 do {
2231 ret = write(io_thread_fd, &val, sizeof(val));
2232 } while (ret < 0 && errno == EINTR);
2234 /* EAGAIN is fine, a read must be pending. */
2235 if (ret < 0 && errno != EAGAIN) {
2236 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
2237 strerror(errno));
2238 exit (1);
2242 static void qemu_event_read(void *opaque)
2244 int fd = (unsigned long)opaque;
2245 ssize_t len;
2246 char buffer[512];
2248 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
2249 do {
2250 len = read(fd, buffer, sizeof(buffer));
2251 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
2254 static int qemu_event_init(void)
2256 int err;
2257 int fds[2];
2259 err = qemu_eventfd(fds);
2260 if (err == -1)
2261 return -errno;
2263 err = fcntl_setfl(fds[0], O_NONBLOCK);
2264 if (err < 0)
2265 goto fail;
2267 err = fcntl_setfl(fds[1], O_NONBLOCK);
2268 if (err < 0)
2269 goto fail;
2271 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
2272 (void *)(unsigned long)fds[0]);
2274 io_thread_fd = fds[1];
2275 return 0;
2277 fail:
2278 close(fds[0]);
2279 close(fds[1]);
2280 return err;
2282 #else
2283 HANDLE qemu_event_handle;
2285 static void dummy_event_handler(void *opaque)
2289 static int qemu_event_init(void)
2291 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
2292 if (!qemu_event_handle) {
2293 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
2294 return -1;
2296 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
2297 return 0;
2300 static void qemu_event_increment(void)
2302 if (!SetEvent(qemu_event_handle)) {
2303 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
2304 GetLastError());
2305 exit (1);
2308 #endif
2310 #ifndef CONFIG_IOTHREAD
2311 static int qemu_init_main_loop(void)
2313 return qemu_event_init();
2316 void qemu_init_vcpu(void *_env)
2318 CPUState *env = _env;
2320 env->nr_cores = smp_cores;
2321 env->nr_threads = smp_threads;
2322 if (kvm_enabled())
2323 kvm_init_vcpu(env);
2324 return;
2327 int qemu_cpu_self(void *env)
2329 return 1;
2332 static void resume_all_vcpus(void)
2336 static void pause_all_vcpus(void)
2340 void qemu_cpu_kick(void *env)
2342 return;
2345 void qemu_notify_event(void)
2347 CPUState *env = cpu_single_env;
2349 qemu_event_increment ();
2350 if (env) {
2351 cpu_exit(env);
2353 if (next_cpu && env != next_cpu) {
2354 cpu_exit(next_cpu);
2358 void qemu_mutex_lock_iothread(void) {}
2359 void qemu_mutex_unlock_iothread(void) {}
2361 void vm_stop(int reason)
2363 do_vm_stop(reason);
2366 #else /* CONFIG_IOTHREAD */
2368 #include "qemu-thread.h"
2370 QemuMutex qemu_global_mutex;
2371 static QemuMutex qemu_fair_mutex;
2373 static QemuThread io_thread;
2375 static QemuThread *tcg_cpu_thread;
2376 static QemuCond *tcg_halt_cond;
2378 static int qemu_system_ready;
2379 /* cpu creation */
2380 static QemuCond qemu_cpu_cond;
2381 /* system init */
2382 static QemuCond qemu_system_cond;
2383 static QemuCond qemu_pause_cond;
2385 static void tcg_block_io_signals(void);
2386 static void kvm_block_io_signals(CPUState *env);
2387 static void unblock_io_signals(void);
2389 static int qemu_init_main_loop(void)
2391 int ret;
2393 ret = qemu_event_init();
2394 if (ret)
2395 return ret;
2397 qemu_cond_init(&qemu_pause_cond);
2398 qemu_mutex_init(&qemu_fair_mutex);
2399 qemu_mutex_init(&qemu_global_mutex);
2400 qemu_mutex_lock(&qemu_global_mutex);
2402 unblock_io_signals();
2403 qemu_thread_self(&io_thread);
2405 return 0;
2408 static void qemu_wait_io_event_common(CPUState *env)
2410 if (env->stop) {
2411 env->stop = 0;
2412 env->stopped = 1;
2413 qemu_cond_signal(&qemu_pause_cond);
2417 static void qemu_wait_io_event(CPUState *env)
2419 while (!tcg_has_work())
2420 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2422 qemu_mutex_unlock(&qemu_global_mutex);
2425 * Users of qemu_global_mutex can be starved, having no chance
2426 * to acquire it since this path will get to it first.
2427 * So use another lock to provide fairness.
2429 qemu_mutex_lock(&qemu_fair_mutex);
2430 qemu_mutex_unlock(&qemu_fair_mutex);
2432 qemu_mutex_lock(&qemu_global_mutex);
2433 qemu_wait_io_event_common(env);
2436 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
2438 struct timespec ts;
2439 int r, e;
2440 siginfo_t siginfo;
2441 sigset_t waitset;
2443 ts.tv_sec = timeout / 1000;
2444 ts.tv_nsec = (timeout % 1000) * 1000000;
2446 sigemptyset(&waitset);
2447 sigaddset(&waitset, SIG_IPI);
2449 qemu_mutex_unlock(&qemu_global_mutex);
2450 r = sigtimedwait(&waitset, &siginfo, &ts);
2451 e = errno;
2452 qemu_mutex_lock(&qemu_global_mutex);
2454 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
2455 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
2456 exit(1);
2460 static void qemu_kvm_wait_io_event(CPUState *env)
2462 while (!cpu_has_work(env))
2463 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2465 qemu_kvm_eat_signal(env, 0);
2466 qemu_wait_io_event_common(env);
2469 static int qemu_cpu_exec(CPUState *env);
2471 static void *kvm_cpu_thread_fn(void *arg)
2473 CPUState *env = arg;
2475 qemu_thread_self(env->thread);
2476 if (kvm_enabled())
2477 kvm_init_vcpu(env);
2479 kvm_block_io_signals(env);
2481 /* signal CPU creation */
2482 qemu_mutex_lock(&qemu_global_mutex);
2483 env->created = 1;
2484 qemu_cond_signal(&qemu_cpu_cond);
2486 /* and wait for machine initialization */
2487 while (!qemu_system_ready)
2488 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2490 while (1) {
2491 if (cpu_can_run(env))
2492 qemu_cpu_exec(env);
2493 qemu_kvm_wait_io_event(env);
2496 return NULL;
2499 static bool tcg_cpu_exec(void);
2501 static void *tcg_cpu_thread_fn(void *arg)
2503 CPUState *env = arg;
2505 tcg_block_io_signals();
2506 qemu_thread_self(env->thread);
2508 /* signal CPU creation */
2509 qemu_mutex_lock(&qemu_global_mutex);
2510 for (env = first_cpu; env != NULL; env = env->next_cpu)
2511 env->created = 1;
2512 qemu_cond_signal(&qemu_cpu_cond);
2514 /* and wait for machine initialization */
2515 while (!qemu_system_ready)
2516 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2518 while (1) {
2519 tcg_cpu_exec();
2520 qemu_wait_io_event(cur_cpu);
2523 return NULL;
2526 void qemu_cpu_kick(void *_env)
2528 CPUState *env = _env;
2529 qemu_cond_broadcast(env->halt_cond);
2530 if (kvm_enabled())
2531 qemu_thread_signal(env->thread, SIG_IPI);
2534 int qemu_cpu_self(void *_env)
2536 CPUState *env = _env;
2537 QemuThread this;
2539 qemu_thread_self(&this);
2541 return qemu_thread_equal(&this, env->thread);
2544 static void cpu_signal(int sig)
2546 if (cpu_single_env)
2547 cpu_exit(cpu_single_env);
2550 static void tcg_block_io_signals(void)
2552 sigset_t set;
2553 struct sigaction sigact;
2555 sigemptyset(&set);
2556 sigaddset(&set, SIGUSR2);
2557 sigaddset(&set, SIGIO);
2558 sigaddset(&set, SIGALRM);
2559 sigaddset(&set, SIGCHLD);
2560 pthread_sigmask(SIG_BLOCK, &set, NULL);
2562 sigemptyset(&set);
2563 sigaddset(&set, SIG_IPI);
2564 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2566 memset(&sigact, 0, sizeof(sigact));
2567 sigact.sa_handler = cpu_signal;
2568 sigaction(SIG_IPI, &sigact, NULL);
2571 static void dummy_signal(int sig)
2575 static void kvm_block_io_signals(CPUState *env)
2577 int r;
2578 sigset_t set;
2579 struct sigaction sigact;
2581 sigemptyset(&set);
2582 sigaddset(&set, SIGUSR2);
2583 sigaddset(&set, SIGIO);
2584 sigaddset(&set, SIGALRM);
2585 sigaddset(&set, SIGCHLD);
2586 sigaddset(&set, SIG_IPI);
2587 pthread_sigmask(SIG_BLOCK, &set, NULL);
2589 pthread_sigmask(SIG_BLOCK, NULL, &set);
2590 sigdelset(&set, SIG_IPI);
2592 memset(&sigact, 0, sizeof(sigact));
2593 sigact.sa_handler = dummy_signal;
2594 sigaction(SIG_IPI, &sigact, NULL);
2596 r = kvm_set_signal_mask(env, &set);
2597 if (r) {
2598 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
2599 exit(1);
2603 static void unblock_io_signals(void)
2605 sigset_t set;
2607 sigemptyset(&set);
2608 sigaddset(&set, SIGUSR2);
2609 sigaddset(&set, SIGIO);
2610 sigaddset(&set, SIGALRM);
2611 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2613 sigemptyset(&set);
2614 sigaddset(&set, SIG_IPI);
2615 pthread_sigmask(SIG_BLOCK, &set, NULL);
2618 static void qemu_signal_lock(unsigned int msecs)
2620 qemu_mutex_lock(&qemu_fair_mutex);
2622 while (qemu_mutex_trylock(&qemu_global_mutex)) {
2623 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
2624 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
2625 break;
2627 qemu_mutex_unlock(&qemu_fair_mutex);
2630 void qemu_mutex_lock_iothread(void)
2632 if (kvm_enabled()) {
2633 qemu_mutex_lock(&qemu_fair_mutex);
2634 qemu_mutex_lock(&qemu_global_mutex);
2635 qemu_mutex_unlock(&qemu_fair_mutex);
2636 } else
2637 qemu_signal_lock(100);
2640 void qemu_mutex_unlock_iothread(void)
2642 qemu_mutex_unlock(&qemu_global_mutex);
2645 static int all_vcpus_paused(void)
2647 CPUState *penv = first_cpu;
2649 while (penv) {
2650 if (!penv->stopped)
2651 return 0;
2652 penv = (CPUState *)penv->next_cpu;
2655 return 1;
2658 static void pause_all_vcpus(void)
2660 CPUState *penv = first_cpu;
2662 while (penv) {
2663 penv->stop = 1;
2664 qemu_thread_signal(penv->thread, SIG_IPI);
2665 qemu_cpu_kick(penv);
2666 penv = (CPUState *)penv->next_cpu;
2669 while (!all_vcpus_paused()) {
2670 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
2671 penv = first_cpu;
2672 while (penv) {
2673 qemu_thread_signal(penv->thread, SIG_IPI);
2674 penv = (CPUState *)penv->next_cpu;
2679 static void resume_all_vcpus(void)
2681 CPUState *penv = first_cpu;
2683 while (penv) {
2684 penv->stop = 0;
2685 penv->stopped = 0;
2686 qemu_thread_signal(penv->thread, SIG_IPI);
2687 qemu_cpu_kick(penv);
2688 penv = (CPUState *)penv->next_cpu;
2692 static void tcg_init_vcpu(void *_env)
2694 CPUState *env = _env;
2695 /* share a single thread for all cpus with TCG */
2696 if (!tcg_cpu_thread) {
2697 env->thread = qemu_mallocz(sizeof(QemuThread));
2698 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2699 qemu_cond_init(env->halt_cond);
2700 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
2701 while (env->created == 0)
2702 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2703 tcg_cpu_thread = env->thread;
2704 tcg_halt_cond = env->halt_cond;
2705 } else {
2706 env->thread = tcg_cpu_thread;
2707 env->halt_cond = tcg_halt_cond;
2711 static void kvm_start_vcpu(CPUState *env)
2713 env->thread = qemu_mallocz(sizeof(QemuThread));
2714 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2715 qemu_cond_init(env->halt_cond);
2716 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
2717 while (env->created == 0)
2718 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2721 void qemu_init_vcpu(void *_env)
2723 CPUState *env = _env;
2725 env->nr_cores = smp_cores;
2726 env->nr_threads = smp_threads;
2727 if (kvm_enabled())
2728 kvm_start_vcpu(env);
2729 else
2730 tcg_init_vcpu(env);
2733 void qemu_notify_event(void)
2735 qemu_event_increment();
2738 static void qemu_system_vmstop_request(int reason)
2740 vmstop_requested = reason;
2741 qemu_notify_event();
2744 void vm_stop(int reason)
2746 QemuThread me;
2747 qemu_thread_self(&me);
2749 if (!qemu_thread_equal(&me, &io_thread)) {
2750 qemu_system_vmstop_request(reason);
2752 * FIXME: should not return to device code in case
2753 * vm_stop() has been requested.
2755 if (cpu_single_env) {
2756 cpu_exit(cpu_single_env);
2757 cpu_single_env->stop = 1;
2759 return;
2761 do_vm_stop(reason);
2764 #endif
2767 #ifdef _WIN32
2768 static void host_main_loop_wait(int *timeout)
2770 int ret, ret2, i;
2771 PollingEntry *pe;
2774 /* XXX: need to suppress polling by better using win32 events */
2775 ret = 0;
2776 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2777 ret |= pe->func(pe->opaque);
2779 if (ret == 0) {
2780 int err;
2781 WaitObjects *w = &wait_objects;
2783 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2784 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2785 if (w->func[ret - WAIT_OBJECT_0])
2786 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2788 /* Check for additional signaled events */
2789 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2791 /* Check if event is signaled */
2792 ret2 = WaitForSingleObject(w->events[i], 0);
2793 if(ret2 == WAIT_OBJECT_0) {
2794 if (w->func[i])
2795 w->func[i](w->opaque[i]);
2796 } else if (ret2 == WAIT_TIMEOUT) {
2797 } else {
2798 err = GetLastError();
2799 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2802 } else if (ret == WAIT_TIMEOUT) {
2803 } else {
2804 err = GetLastError();
2805 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2809 *timeout = 0;
2811 #else
2812 static void host_main_loop_wait(int *timeout)
2815 #endif
2817 void main_loop_wait(int nonblocking)
2819 IOHandlerRecord *ioh;
2820 fd_set rfds, wfds, xfds;
2821 int ret, nfds;
2822 struct timeval tv;
2823 int timeout;
2825 if (nonblocking)
2826 timeout = 0;
2827 else {
2828 timeout = qemu_calculate_timeout();
2829 qemu_bh_update_timeout(&timeout);
2832 host_main_loop_wait(&timeout);
2834 /* poll any events */
2835 /* XXX: separate device handlers from system ones */
2836 nfds = -1;
2837 FD_ZERO(&rfds);
2838 FD_ZERO(&wfds);
2839 FD_ZERO(&xfds);
2840 QLIST_FOREACH(ioh, &io_handlers, next) {
2841 if (ioh->deleted)
2842 continue;
2843 if (ioh->fd_read &&
2844 (!ioh->fd_read_poll ||
2845 ioh->fd_read_poll(ioh->opaque) != 0)) {
2846 FD_SET(ioh->fd, &rfds);
2847 if (ioh->fd > nfds)
2848 nfds = ioh->fd;
2850 if (ioh->fd_write) {
2851 FD_SET(ioh->fd, &wfds);
2852 if (ioh->fd > nfds)
2853 nfds = ioh->fd;
2857 tv.tv_sec = timeout / 1000;
2858 tv.tv_usec = (timeout % 1000) * 1000;
2860 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2862 qemu_mutex_unlock_iothread();
2863 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2864 qemu_mutex_lock_iothread();
2865 if (ret > 0) {
2866 IOHandlerRecord *pioh;
2868 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
2869 if (ioh->deleted) {
2870 QLIST_REMOVE(ioh, next);
2871 qemu_free(ioh);
2872 continue;
2874 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2875 ioh->fd_read(ioh->opaque);
2877 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2878 ioh->fd_write(ioh->opaque);
2883 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2885 qemu_run_all_timers();
2887 /* Check bottom-halves last in case any of the earlier events triggered
2888 them. */
2889 qemu_bh_poll();
2893 static int qemu_cpu_exec(CPUState *env)
2895 int ret;
2896 #ifdef CONFIG_PROFILER
2897 int64_t ti;
2898 #endif
2900 #ifdef CONFIG_PROFILER
2901 ti = profile_getclock();
2902 #endif
2903 if (use_icount) {
2904 int64_t count;
2905 int decr;
2906 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
2907 env->icount_decr.u16.low = 0;
2908 env->icount_extra = 0;
2909 count = qemu_icount_round (qemu_next_deadline());
2910 qemu_icount += count;
2911 decr = (count > 0xffff) ? 0xffff : count;
2912 count -= decr;
2913 env->icount_decr.u16.low = decr;
2914 env->icount_extra = count;
2916 ret = cpu_exec(env);
2917 #ifdef CONFIG_PROFILER
2918 qemu_time += profile_getclock() - ti;
2919 #endif
2920 if (use_icount) {
2921 /* Fold pending instructions back into the
2922 instruction counter, and clear the interrupt flag. */
2923 qemu_icount -= (env->icount_decr.u16.low
2924 + env->icount_extra);
2925 env->icount_decr.u32 = 0;
2926 env->icount_extra = 0;
2928 return ret;
2931 static bool tcg_cpu_exec(void)
2933 int ret = 0;
2935 if (next_cpu == NULL)
2936 next_cpu = first_cpu;
2937 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
2938 CPUState *env = cur_cpu = next_cpu;
2940 qemu_clock_enable(vm_clock,
2941 (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
2943 if (qemu_alarm_pending())
2944 break;
2945 if (cpu_can_run(env))
2946 ret = qemu_cpu_exec(env);
2947 else if (env->stop)
2948 break;
2950 if (ret == EXCP_DEBUG) {
2951 gdb_set_stop_cpu(env);
2952 debug_requested = 1;
2953 break;
2956 return tcg_has_work();
2959 static int vm_can_run(void)
2961 if (powerdown_requested)
2962 return 0;
2963 if (reset_requested)
2964 return 0;
2965 if (shutdown_requested)
2966 return 0;
2967 if (debug_requested)
2968 return 0;
2969 return 1;
2972 qemu_irq qemu_system_powerdown;
2974 static void main_loop(void)
2976 int r;
2978 #ifdef CONFIG_IOTHREAD
2979 qemu_system_ready = 1;
2980 qemu_cond_broadcast(&qemu_system_cond);
2981 #endif
2983 for (;;) {
2984 do {
2985 bool nonblocking = false;
2986 #ifdef CONFIG_PROFILER
2987 int64_t ti;
2988 #endif
2989 #ifndef CONFIG_IOTHREAD
2990 nonblocking = tcg_cpu_exec();
2991 #endif
2992 #ifdef CONFIG_PROFILER
2993 ti = profile_getclock();
2994 #endif
2995 main_loop_wait(nonblocking);
2996 #ifdef CONFIG_PROFILER
2997 dev_time += profile_getclock() - ti;
2998 #endif
2999 } while (vm_can_run());
3001 if (qemu_debug_requested()) {
3002 vm_stop(EXCP_DEBUG);
3004 if (qemu_shutdown_requested()) {
3005 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
3006 if (no_shutdown) {
3007 vm_stop(0);
3008 no_shutdown = 0;
3009 } else
3010 break;
3012 if (qemu_reset_requested()) {
3013 pause_all_vcpus();
3014 qemu_system_reset();
3015 resume_all_vcpus();
3017 if (qemu_powerdown_requested()) {
3018 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
3019 qemu_irq_raise(qemu_system_powerdown);
3021 if ((r = qemu_vmstop_requested())) {
3022 vm_stop(r);
3025 pause_all_vcpus();
3028 static void version(void)
3030 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3033 static void help(int exitcode)
3035 const char *options_help =
3036 #define DEF(option, opt_arg, opt_enum, opt_help) \
3037 opt_help
3038 #define DEFHEADING(text) stringify(text) "\n"
3039 #include "qemu-options.h"
3040 #undef DEF
3041 #undef DEFHEADING
3042 #undef GEN_DOCS
3044 version();
3045 printf("usage: %s [options] [disk_image]\n"
3046 "\n"
3047 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3048 "\n"
3049 "%s\n"
3050 "During emulation, the following keys are useful:\n"
3051 "ctrl-alt-f toggle full screen\n"
3052 "ctrl-alt-n switch to virtual console 'n'\n"
3053 "ctrl-alt toggle mouse and keyboard grab\n"
3054 "\n"
3055 "When using -nographic, press 'ctrl-a h' to get some help.\n",
3056 "qemu",
3057 options_help);
3058 exit(exitcode);
3061 #define HAS_ARG 0x0001
3063 enum {
3064 #define DEF(option, opt_arg, opt_enum, opt_help) \
3065 opt_enum,
3066 #define DEFHEADING(text)
3067 #include "qemu-options.h"
3068 #undef DEF
3069 #undef DEFHEADING
3070 #undef GEN_DOCS
3073 typedef struct QEMUOption {
3074 const char *name;
3075 int flags;
3076 int index;
3077 } QEMUOption;
3079 static const QEMUOption qemu_options[] = {
3080 { "h", 0, QEMU_OPTION_h },
3081 #define DEF(option, opt_arg, opt_enum, opt_help) \
3082 { option, opt_arg, opt_enum },
3083 #define DEFHEADING(text)
3084 #include "qemu-options.h"
3085 #undef DEF
3086 #undef DEFHEADING
3087 #undef GEN_DOCS
3088 { NULL },
3091 #ifdef HAS_AUDIO
3092 struct soundhw soundhw[] = {
3093 #ifdef HAS_AUDIO_CHOICE
3094 #if defined(TARGET_I386) || defined(TARGET_MIPS)
3096 "pcspk",
3097 "PC speaker",
3100 { .init_isa = pcspk_audio_init }
3102 #endif
3104 #ifdef CONFIG_SB16
3106 "sb16",
3107 "Creative Sound Blaster 16",
3110 { .init_isa = SB16_init }
3112 #endif
3114 #ifdef CONFIG_CS4231A
3116 "cs4231a",
3117 "CS4231A",
3120 { .init_isa = cs4231a_init }
3122 #endif
3124 #ifdef CONFIG_ADLIB
3126 "adlib",
3127 #ifdef HAS_YMF262
3128 "Yamaha YMF262 (OPL3)",
3129 #else
3130 "Yamaha YM3812 (OPL2)",
3131 #endif
3134 { .init_isa = Adlib_init }
3136 #endif
3138 #ifdef CONFIG_GUS
3140 "gus",
3141 "Gravis Ultrasound GF1",
3144 { .init_isa = GUS_init }
3146 #endif
3148 #ifdef CONFIG_AC97
3150 "ac97",
3151 "Intel 82801AA AC97 Audio",
3154 { .init_pci = ac97_init }
3156 #endif
3158 #ifdef CONFIG_ES1370
3160 "es1370",
3161 "ENSONIQ AudioPCI ES1370",
3164 { .init_pci = es1370_init }
3166 #endif
3168 #endif /* HAS_AUDIO_CHOICE */
3170 { NULL, NULL, 0, 0, { NULL } }
3173 static void select_soundhw (const char *optarg)
3175 struct soundhw *c;
3177 if (*optarg == '?') {
3178 show_valid_cards:
3180 printf ("Valid sound card names (comma separated):\n");
3181 for (c = soundhw; c->name; ++c) {
3182 printf ("%-11s %s\n", c->name, c->descr);
3184 printf ("\n-soundhw all will enable all of the above\n");
3185 exit (*optarg != '?');
3187 else {
3188 size_t l;
3189 const char *p;
3190 char *e;
3191 int bad_card = 0;
3193 if (!strcmp (optarg, "all")) {
3194 for (c = soundhw; c->name; ++c) {
3195 c->enabled = 1;
3197 return;
3200 p = optarg;
3201 while (*p) {
3202 e = strchr (p, ',');
3203 l = !e ? strlen (p) : (size_t) (e - p);
3205 for (c = soundhw; c->name; ++c) {
3206 if (!strncmp (c->name, p, l) && !c->name[l]) {
3207 c->enabled = 1;
3208 break;
3212 if (!c->name) {
3213 if (l > 80) {
3214 fprintf (stderr,
3215 "Unknown sound card name (too big to show)\n");
3217 else {
3218 fprintf (stderr, "Unknown sound card name `%.*s'\n",
3219 (int) l, p);
3221 bad_card = 1;
3223 p += l + (e != NULL);
3226 if (bad_card)
3227 goto show_valid_cards;
3230 #endif
3232 static void select_vgahw (const char *p)
3234 const char *opts;
3236 default_vga = 0;
3237 vga_interface_type = VGA_NONE;
3238 if (strstart(p, "std", &opts)) {
3239 vga_interface_type = VGA_STD;
3240 } else if (strstart(p, "cirrus", &opts)) {
3241 vga_interface_type = VGA_CIRRUS;
3242 } else if (strstart(p, "vmware", &opts)) {
3243 vga_interface_type = VGA_VMWARE;
3244 } else if (strstart(p, "xenfb", &opts)) {
3245 vga_interface_type = VGA_XENFB;
3246 } else if (!strstart(p, "none", &opts)) {
3247 invalid_vga:
3248 fprintf(stderr, "Unknown vga type: %s\n", p);
3249 exit(1);
3251 while (*opts) {
3252 const char *nextopt;
3254 if (strstart(opts, ",retrace=", &nextopt)) {
3255 opts = nextopt;
3256 if (strstart(opts, "dumb", &nextopt))
3257 vga_retrace_method = VGA_RETRACE_DUMB;
3258 else if (strstart(opts, "precise", &nextopt))
3259 vga_retrace_method = VGA_RETRACE_PRECISE;
3260 else goto invalid_vga;
3261 } else goto invalid_vga;
3262 opts = nextopt;
3266 #ifdef TARGET_I386
3267 static int balloon_parse(const char *arg)
3269 QemuOpts *opts;
3271 if (strcmp(arg, "none") == 0) {
3272 return 0;
3275 if (!strncmp(arg, "virtio", 6)) {
3276 if (arg[6] == ',') {
3277 /* have params -> parse them */
3278 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
3279 if (!opts)
3280 return -1;
3281 } else {
3282 /* create empty opts */
3283 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3285 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
3286 return 0;
3289 return -1;
3291 #endif
3293 #ifdef _WIN32
3294 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
3296 exit(STATUS_CONTROL_C_EXIT);
3297 return TRUE;
3299 #endif
3301 int qemu_uuid_parse(const char *str, uint8_t *uuid)
3303 int ret;
3305 if(strlen(str) != 36)
3306 return -1;
3308 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
3309 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
3310 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
3312 if(ret != 16)
3313 return -1;
3315 #ifdef TARGET_I386
3316 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
3317 #endif
3319 return 0;
3322 #ifndef _WIN32
3324 static void termsig_handler(int signal)
3326 qemu_system_shutdown_request();
3329 static void sigchld_handler(int signal)
3331 waitpid(-1, NULL, WNOHANG);
3334 static void sighandler_setup(void)
3336 struct sigaction act;
3338 memset(&act, 0, sizeof(act));
3339 act.sa_handler = termsig_handler;
3340 sigaction(SIGINT, &act, NULL);
3341 sigaction(SIGHUP, &act, NULL);
3342 sigaction(SIGTERM, &act, NULL);
3344 act.sa_handler = sigchld_handler;
3345 act.sa_flags = SA_NOCLDSTOP;
3346 sigaction(SIGCHLD, &act, NULL);
3349 #endif
3351 #ifdef _WIN32
3352 /* Look for support files in the same directory as the executable. */
3353 static char *find_datadir(const char *argv0)
3355 char *p;
3356 char buf[MAX_PATH];
3357 DWORD len;
3359 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
3360 if (len == 0) {
3361 return NULL;
3364 buf[len] = 0;
3365 p = buf + len - 1;
3366 while (p != buf && *p != '\\')
3367 p--;
3368 *p = 0;
3369 if (access(buf, R_OK) == 0) {
3370 return qemu_strdup(buf);
3372 return NULL;
3374 #else /* !_WIN32 */
3376 /* Find a likely location for support files using the location of the binary.
3377 For installed binaries this will be "$bindir/../share/qemu". When
3378 running from the build tree this will be "$bindir/../pc-bios". */
3379 #define SHARE_SUFFIX "/share/qemu"
3380 #define BUILD_SUFFIX "/pc-bios"
3381 static char *find_datadir(const char *argv0)
3383 char *dir;
3384 char *p = NULL;
3385 char *res;
3386 char buf[PATH_MAX];
3387 size_t max_len;
3389 #if defined(__linux__)
3391 int len;
3392 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
3393 if (len > 0) {
3394 buf[len] = 0;
3395 p = buf;
3398 #elif defined(__FreeBSD__)
3400 int len;
3401 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
3402 if (len > 0) {
3403 buf[len] = 0;
3404 p = buf;
3407 #endif
3408 /* If we don't have any way of figuring out the actual executable
3409 location then try argv[0]. */
3410 if (!p) {
3411 p = realpath(argv0, buf);
3412 if (!p) {
3413 return NULL;
3416 dir = dirname(p);
3417 dir = dirname(dir);
3419 max_len = strlen(dir) +
3420 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
3421 res = qemu_mallocz(max_len);
3422 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
3423 if (access(res, R_OK)) {
3424 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
3425 if (access(res, R_OK)) {
3426 qemu_free(res);
3427 res = NULL;
3431 return res;
3433 #undef SHARE_SUFFIX
3434 #undef BUILD_SUFFIX
3435 #endif
3437 char *qemu_find_file(int type, const char *name)
3439 int len;
3440 const char *subdir;
3441 char *buf;
3443 /* If name contains path separators then try it as a straight path. */
3444 if ((strchr(name, '/') || strchr(name, '\\'))
3445 && access(name, R_OK) == 0) {
3446 return qemu_strdup(name);
3448 switch (type) {
3449 case QEMU_FILE_TYPE_BIOS:
3450 subdir = "";
3451 break;
3452 case QEMU_FILE_TYPE_KEYMAP:
3453 subdir = "keymaps/";
3454 break;
3455 default:
3456 abort();
3458 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
3459 buf = qemu_mallocz(len);
3460 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
3461 if (access(buf, R_OK)) {
3462 qemu_free(buf);
3463 return NULL;
3465 return buf;
3468 static int device_help_func(QemuOpts *opts, void *opaque)
3470 return qdev_device_help(opts);
3473 static int device_init_func(QemuOpts *opts, void *opaque)
3475 DeviceState *dev;
3477 dev = qdev_device_add(opts);
3478 if (!dev)
3479 return -1;
3480 return 0;
3483 static int chardev_init_func(QemuOpts *opts, void *opaque)
3485 CharDriverState *chr;
3487 chr = qemu_chr_open_opts(opts, NULL);
3488 if (!chr)
3489 return -1;
3490 return 0;
3493 static int mon_init_func(QemuOpts *opts, void *opaque)
3495 CharDriverState *chr;
3496 const char *chardev;
3497 const char *mode;
3498 int flags;
3500 mode = qemu_opt_get(opts, "mode");
3501 if (mode == NULL) {
3502 mode = "readline";
3504 if (strcmp(mode, "readline") == 0) {
3505 flags = MONITOR_USE_READLINE;
3506 } else if (strcmp(mode, "control") == 0) {
3507 flags = MONITOR_USE_CONTROL;
3508 } else {
3509 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
3510 exit(1);
3513 if (qemu_opt_get_bool(opts, "default", 0))
3514 flags |= MONITOR_IS_DEFAULT;
3516 chardev = qemu_opt_get(opts, "chardev");
3517 chr = qemu_chr_find(chardev);
3518 if (chr == NULL) {
3519 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
3520 exit(1);
3523 monitor_init(chr, flags);
3524 return 0;
3527 static void monitor_parse(const char *optarg, const char *mode)
3529 static int monitor_device_index = 0;
3530 QemuOpts *opts;
3531 const char *p;
3532 char label[32];
3533 int def = 0;
3535 if (strstart(optarg, "chardev:", &p)) {
3536 snprintf(label, sizeof(label), "%s", p);
3537 } else {
3538 if (monitor_device_index) {
3539 snprintf(label, sizeof(label), "monitor%d",
3540 monitor_device_index);
3541 } else {
3542 snprintf(label, sizeof(label), "monitor");
3543 def = 1;
3545 opts = qemu_chr_parse_compat(label, optarg);
3546 if (!opts) {
3547 fprintf(stderr, "parse error: %s\n", optarg);
3548 exit(1);
3552 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
3553 if (!opts) {
3554 fprintf(stderr, "duplicate chardev: %s\n", label);
3555 exit(1);
3557 qemu_opt_set(opts, "mode", mode);
3558 qemu_opt_set(opts, "chardev", label);
3559 if (def)
3560 qemu_opt_set(opts, "default", "on");
3561 monitor_device_index++;
3564 struct device_config {
3565 enum {
3566 DEV_USB, /* -usbdevice */
3567 DEV_BT, /* -bt */
3568 DEV_SERIAL, /* -serial */
3569 DEV_PARALLEL, /* -parallel */
3570 DEV_VIRTCON, /* -virtioconsole */
3571 DEV_DEBUGCON, /* -debugcon */
3572 } type;
3573 const char *cmdline;
3574 QTAILQ_ENTRY(device_config) next;
3576 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
3578 static void add_device_config(int type, const char *cmdline)
3580 struct device_config *conf;
3582 conf = qemu_mallocz(sizeof(*conf));
3583 conf->type = type;
3584 conf->cmdline = cmdline;
3585 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
3588 static int foreach_device_config(int type, int (*func)(const char *cmdline))
3590 struct device_config *conf;
3591 int rc;
3593 QTAILQ_FOREACH(conf, &device_configs, next) {
3594 if (conf->type != type)
3595 continue;
3596 rc = func(conf->cmdline);
3597 if (0 != rc)
3598 return rc;
3600 return 0;
3603 static int serial_parse(const char *devname)
3605 static int index = 0;
3606 char label[32];
3608 if (strcmp(devname, "none") == 0)
3609 return 0;
3610 if (index == MAX_SERIAL_PORTS) {
3611 fprintf(stderr, "qemu: too many serial ports\n");
3612 exit(1);
3614 snprintf(label, sizeof(label), "serial%d", index);
3615 serial_hds[index] = qemu_chr_open(label, devname, NULL);
3616 if (!serial_hds[index]) {
3617 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
3618 devname, strerror(errno));
3619 return -1;
3621 index++;
3622 return 0;
3625 static int parallel_parse(const char *devname)
3627 static int index = 0;
3628 char label[32];
3630 if (strcmp(devname, "none") == 0)
3631 return 0;
3632 if (index == MAX_PARALLEL_PORTS) {
3633 fprintf(stderr, "qemu: too many parallel ports\n");
3634 exit(1);
3636 snprintf(label, sizeof(label), "parallel%d", index);
3637 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
3638 if (!parallel_hds[index]) {
3639 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
3640 devname, strerror(errno));
3641 return -1;
3643 index++;
3644 return 0;
3647 static int virtcon_parse(const char *devname)
3649 static int index = 0;
3650 char label[32];
3651 QemuOpts *bus_opts, *dev_opts;
3653 if (strcmp(devname, "none") == 0)
3654 return 0;
3655 if (index == MAX_VIRTIO_CONSOLES) {
3656 fprintf(stderr, "qemu: too many virtio consoles\n");
3657 exit(1);
3660 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3661 qemu_opt_set(bus_opts, "driver", "virtio-serial");
3663 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3664 qemu_opt_set(dev_opts, "driver", "virtconsole");
3666 snprintf(label, sizeof(label), "virtcon%d", index);
3667 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
3668 if (!virtcon_hds[index]) {
3669 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
3670 devname, strerror(errno));
3671 return -1;
3673 qemu_opt_set(dev_opts, "chardev", label);
3675 index++;
3676 return 0;
3679 static int debugcon_parse(const char *devname)
3681 QemuOpts *opts;
3683 if (!qemu_chr_open("debugcon", devname, NULL)) {
3684 exit(1);
3686 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
3687 if (!opts) {
3688 fprintf(stderr, "qemu: already have a debugcon device\n");
3689 exit(1);
3691 qemu_opt_set(opts, "driver", "isa-debugcon");
3692 qemu_opt_set(opts, "chardev", "debugcon");
3693 return 0;
3696 static const QEMUOption *lookup_opt(int argc, char **argv,
3697 const char **poptarg, int *poptind)
3699 const QEMUOption *popt;
3700 int optind = *poptind;
3701 char *r = argv[optind];
3702 const char *optarg;
3704 loc_set_cmdline(argv, optind, 1);
3705 optind++;
3706 /* Treat --foo the same as -foo. */
3707 if (r[1] == '-')
3708 r++;
3709 popt = qemu_options;
3710 for(;;) {
3711 if (!popt->name) {
3712 error_report("invalid option");
3713 exit(1);
3715 if (!strcmp(popt->name, r + 1))
3716 break;
3717 popt++;
3719 if (popt->flags & HAS_ARG) {
3720 if (optind >= argc) {
3721 error_report("requires an argument");
3722 exit(1);
3724 optarg = argv[optind++];
3725 loc_set_cmdline(argv, optind - 2, 2);
3726 } else {
3727 optarg = NULL;
3730 *poptarg = optarg;
3731 *poptind = optind;
3733 return popt;
3736 int main(int argc, char **argv, char **envp)
3738 const char *gdbstub_dev = NULL;
3739 uint32_t boot_devices_bitmap = 0;
3740 int i;
3741 int snapshot, linux_boot, net_boot;
3742 const char *icount_option = NULL;
3743 const char *initrd_filename;
3744 const char *kernel_filename, *kernel_cmdline;
3745 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3746 DisplayState *ds;
3747 DisplayChangeListener *dcl;
3748 int cyls, heads, secs, translation;
3749 QemuOpts *hda_opts = NULL, *opts;
3750 int optind;
3751 const char *optarg;
3752 const char *loadvm = NULL;
3753 QEMUMachine *machine;
3754 const char *cpu_model;
3755 #ifndef _WIN32
3756 int fds[2];
3757 #endif
3758 int tb_size;
3759 const char *pid_file = NULL;
3760 const char *incoming = NULL;
3761 #ifndef _WIN32
3762 int fd = 0;
3763 struct passwd *pwd = NULL;
3764 const char *chroot_dir = NULL;
3765 const char *run_as = NULL;
3766 #endif
3767 CPUState *env;
3768 int show_vnc_port = 0;
3769 int defconfig = 1;
3771 error_set_progname(argv[0]);
3773 exit_notifier_init();
3775 init_clocks();
3777 qemu_cache_utils_init(envp);
3779 QLIST_INIT (&vm_change_state_head);
3780 #ifndef _WIN32
3782 struct sigaction act;
3783 sigfillset(&act.sa_mask);
3784 act.sa_flags = 0;
3785 act.sa_handler = SIG_IGN;
3786 sigaction(SIGPIPE, &act, NULL);
3788 #else
3789 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3790 /* Note: cpu_interrupt() is currently not SMP safe, so we force
3791 QEMU to run on a single CPU */
3793 HANDLE h;
3794 DWORD mask, smask;
3795 int i;
3796 h = GetCurrentProcess();
3797 if (GetProcessAffinityMask(h, &mask, &smask)) {
3798 for(i = 0; i < 32; i++) {
3799 if (mask & (1 << i))
3800 break;
3802 if (i != 32) {
3803 mask = 1 << i;
3804 SetProcessAffinityMask(h, mask);
3808 #endif
3810 module_call_init(MODULE_INIT_MACHINE);
3811 machine = find_default_machine();
3812 cpu_model = NULL;
3813 initrd_filename = NULL;
3814 ram_size = 0;
3815 snapshot = 0;
3816 kernel_filename = NULL;
3817 kernel_cmdline = "";
3818 cyls = heads = secs = 0;
3819 translation = BIOS_ATA_TRANSLATION_AUTO;
3821 for (i = 0; i < MAX_NODES; i++) {
3822 node_mem[i] = 0;
3823 node_cpumask[i] = 0;
3826 nb_numa_nodes = 0;
3827 nb_nics = 0;
3829 tb_size = 0;
3830 autostart= 1;
3832 /* first pass of option parsing */
3833 optind = 1;
3834 while (optind < argc) {
3835 if (argv[optind][0] != '-') {
3836 /* disk image */
3837 optind++;
3838 continue;
3839 } else {
3840 const QEMUOption *popt;
3842 popt = lookup_opt(argc, argv, &optarg, &optind);
3843 switch (popt->index) {
3844 case QEMU_OPTION_nodefconfig:
3845 defconfig=0;
3846 break;
3851 if (defconfig) {
3852 const char *fname;
3853 FILE *fp;
3855 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3856 fp = fopen(fname, "r");
3857 if (fp) {
3858 if (qemu_config_parse(fp, fname) != 0) {
3859 exit(1);
3861 fclose(fp);
3864 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3865 fp = fopen(fname, "r");
3866 if (fp) {
3867 if (qemu_config_parse(fp, fname) != 0) {
3868 exit(1);
3870 fclose(fp);
3873 #if defined(cpudef_setup)
3874 cpudef_setup(); /* parse cpu definitions in target config file */
3875 #endif
3877 /* second pass of option parsing */
3878 optind = 1;
3879 for(;;) {
3880 if (optind >= argc)
3881 break;
3882 if (argv[optind][0] != '-') {
3883 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3884 } else {
3885 const QEMUOption *popt;
3887 popt = lookup_opt(argc, argv, &optarg, &optind);
3888 switch(popt->index) {
3889 case QEMU_OPTION_M:
3890 machine = find_machine(optarg);
3891 if (!machine) {
3892 QEMUMachine *m;
3893 printf("Supported machines are:\n");
3894 for(m = first_machine; m != NULL; m = m->next) {
3895 if (m->alias)
3896 printf("%-10s %s (alias of %s)\n",
3897 m->alias, m->desc, m->name);
3898 printf("%-10s %s%s\n",
3899 m->name, m->desc,
3900 m->is_default ? " (default)" : "");
3902 exit(*optarg != '?');
3904 break;
3905 case QEMU_OPTION_cpu:
3906 /* hw initialization will check this */
3907 if (*optarg == '?') {
3908 /* XXX: implement xxx_cpu_list for targets that still miss it */
3909 #if defined(cpu_list_id)
3910 cpu_list_id(stdout, &fprintf, optarg);
3911 #elif defined(cpu_list)
3912 cpu_list(stdout, &fprintf); /* deprecated */
3913 #endif
3914 exit(0);
3915 } else {
3916 cpu_model = optarg;
3918 break;
3919 case QEMU_OPTION_initrd:
3920 initrd_filename = optarg;
3921 break;
3922 case QEMU_OPTION_hda:
3923 if (cyls == 0)
3924 hda_opts = drive_add(optarg, HD_ALIAS, 0);
3925 else
3926 hda_opts = drive_add(optarg, HD_ALIAS
3927 ",cyls=%d,heads=%d,secs=%d%s",
3928 0, cyls, heads, secs,
3929 translation == BIOS_ATA_TRANSLATION_LBA ?
3930 ",trans=lba" :
3931 translation == BIOS_ATA_TRANSLATION_NONE ?
3932 ",trans=none" : "");
3933 break;
3934 case QEMU_OPTION_hdb:
3935 case QEMU_OPTION_hdc:
3936 case QEMU_OPTION_hdd:
3937 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
3938 break;
3939 case QEMU_OPTION_drive:
3940 drive_add(NULL, "%s", optarg);
3941 break;
3942 case QEMU_OPTION_set:
3943 if (qemu_set_option(optarg) != 0)
3944 exit(1);
3945 break;
3946 case QEMU_OPTION_global:
3947 if (qemu_global_option(optarg) != 0)
3948 exit(1);
3949 break;
3950 case QEMU_OPTION_mtdblock:
3951 drive_add(optarg, MTD_ALIAS);
3952 break;
3953 case QEMU_OPTION_sd:
3954 drive_add(optarg, SD_ALIAS);
3955 break;
3956 case QEMU_OPTION_pflash:
3957 drive_add(optarg, PFLASH_ALIAS);
3958 break;
3959 case QEMU_OPTION_snapshot:
3960 snapshot = 1;
3961 break;
3962 case QEMU_OPTION_hdachs:
3964 const char *p;
3965 p = optarg;
3966 cyls = strtol(p, (char **)&p, 0);
3967 if (cyls < 1 || cyls > 16383)
3968 goto chs_fail;
3969 if (*p != ',')
3970 goto chs_fail;
3971 p++;
3972 heads = strtol(p, (char **)&p, 0);
3973 if (heads < 1 || heads > 16)
3974 goto chs_fail;
3975 if (*p != ',')
3976 goto chs_fail;
3977 p++;
3978 secs = strtol(p, (char **)&p, 0);
3979 if (secs < 1 || secs > 63)
3980 goto chs_fail;
3981 if (*p == ',') {
3982 p++;
3983 if (!strcmp(p, "none"))
3984 translation = BIOS_ATA_TRANSLATION_NONE;
3985 else if (!strcmp(p, "lba"))
3986 translation = BIOS_ATA_TRANSLATION_LBA;
3987 else if (!strcmp(p, "auto"))
3988 translation = BIOS_ATA_TRANSLATION_AUTO;
3989 else
3990 goto chs_fail;
3991 } else if (*p != '\0') {
3992 chs_fail:
3993 fprintf(stderr, "qemu: invalid physical CHS format\n");
3994 exit(1);
3996 if (hda_opts != NULL) {
3997 char num[16];
3998 snprintf(num, sizeof(num), "%d", cyls);
3999 qemu_opt_set(hda_opts, "cyls", num);
4000 snprintf(num, sizeof(num), "%d", heads);
4001 qemu_opt_set(hda_opts, "heads", num);
4002 snprintf(num, sizeof(num), "%d", secs);
4003 qemu_opt_set(hda_opts, "secs", num);
4004 if (translation == BIOS_ATA_TRANSLATION_LBA)
4005 qemu_opt_set(hda_opts, "trans", "lba");
4006 if (translation == BIOS_ATA_TRANSLATION_NONE)
4007 qemu_opt_set(hda_opts, "trans", "none");
4010 break;
4011 case QEMU_OPTION_numa:
4012 if (nb_numa_nodes >= MAX_NODES) {
4013 fprintf(stderr, "qemu: too many NUMA nodes\n");
4014 exit(1);
4016 numa_add(optarg);
4017 break;
4018 case QEMU_OPTION_nographic:
4019 display_type = DT_NOGRAPHIC;
4020 break;
4021 #ifdef CONFIG_CURSES
4022 case QEMU_OPTION_curses:
4023 display_type = DT_CURSES;
4024 break;
4025 #endif
4026 case QEMU_OPTION_portrait:
4027 graphic_rotate = 1;
4028 break;
4029 case QEMU_OPTION_kernel:
4030 kernel_filename = optarg;
4031 break;
4032 case QEMU_OPTION_append:
4033 kernel_cmdline = optarg;
4034 break;
4035 case QEMU_OPTION_cdrom:
4036 drive_add(optarg, CDROM_ALIAS);
4037 break;
4038 case QEMU_OPTION_boot:
4040 static const char * const params[] = {
4041 "order", "once", "menu", NULL
4043 char buf[sizeof(boot_devices)];
4044 char *standard_boot_devices;
4045 int legacy = 0;
4047 if (!strchr(optarg, '=')) {
4048 legacy = 1;
4049 pstrcpy(buf, sizeof(buf), optarg);
4050 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4051 fprintf(stderr,
4052 "qemu: unknown boot parameter '%s' in '%s'\n",
4053 buf, optarg);
4054 exit(1);
4057 if (legacy ||
4058 get_param_value(buf, sizeof(buf), "order", optarg)) {
4059 boot_devices_bitmap = parse_bootdevices(buf);
4060 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4062 if (!legacy) {
4063 if (get_param_value(buf, sizeof(buf),
4064 "once", optarg)) {
4065 boot_devices_bitmap |= parse_bootdevices(buf);
4066 standard_boot_devices = qemu_strdup(boot_devices);
4067 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4068 qemu_register_reset(restore_boot_devices,
4069 standard_boot_devices);
4071 if (get_param_value(buf, sizeof(buf),
4072 "menu", optarg)) {
4073 if (!strcmp(buf, "on")) {
4074 boot_menu = 1;
4075 } else if (!strcmp(buf, "off")) {
4076 boot_menu = 0;
4077 } else {
4078 fprintf(stderr,
4079 "qemu: invalid option value '%s'\n",
4080 buf);
4081 exit(1);
4086 break;
4087 case QEMU_OPTION_fda:
4088 case QEMU_OPTION_fdb:
4089 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4090 break;
4091 #ifdef TARGET_I386
4092 case QEMU_OPTION_no_fd_bootchk:
4093 fd_bootchk = 0;
4094 break;
4095 #endif
4096 case QEMU_OPTION_netdev:
4097 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4098 exit(1);
4100 break;
4101 case QEMU_OPTION_net:
4102 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4103 exit(1);
4105 break;
4106 #ifdef CONFIG_SLIRP
4107 case QEMU_OPTION_tftp:
4108 legacy_tftp_prefix = optarg;
4109 break;
4110 case QEMU_OPTION_bootp:
4111 legacy_bootp_filename = optarg;
4112 break;
4113 #ifndef _WIN32
4114 case QEMU_OPTION_smb:
4115 if (net_slirp_smb(optarg) < 0)
4116 exit(1);
4117 break;
4118 #endif
4119 case QEMU_OPTION_redir:
4120 if (net_slirp_redir(optarg) < 0)
4121 exit(1);
4122 break;
4123 #endif
4124 case QEMU_OPTION_bt:
4125 add_device_config(DEV_BT, optarg);
4126 break;
4127 #ifdef HAS_AUDIO
4128 case QEMU_OPTION_audio_help:
4129 AUD_help ();
4130 exit (0);
4131 break;
4132 case QEMU_OPTION_soundhw:
4133 select_soundhw (optarg);
4134 break;
4135 #endif
4136 case QEMU_OPTION_h:
4137 help(0);
4138 break;
4139 case QEMU_OPTION_version:
4140 version();
4141 exit(0);
4142 break;
4143 case QEMU_OPTION_m: {
4144 uint64_t value;
4145 char *ptr;
4147 value = strtoul(optarg, &ptr, 10);
4148 switch (*ptr) {
4149 case 0: case 'M': case 'm':
4150 value <<= 20;
4151 break;
4152 case 'G': case 'g':
4153 value <<= 30;
4154 break;
4155 default:
4156 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4157 exit(1);
4160 /* On 32-bit hosts, QEMU is limited by virtual address space */
4161 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
4162 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4163 exit(1);
4165 if (value != (uint64_t)(ram_addr_t)value) {
4166 fprintf(stderr, "qemu: ram size too large\n");
4167 exit(1);
4169 ram_size = value;
4170 break;
4172 case QEMU_OPTION_mempath:
4173 mem_path = optarg;
4174 break;
4175 #ifdef MAP_POPULATE
4176 case QEMU_OPTION_mem_prealloc:
4177 mem_prealloc = 1;
4178 break;
4179 #endif
4180 case QEMU_OPTION_d:
4182 int mask;
4183 const CPULogItem *item;
4185 mask = cpu_str_to_log_mask(optarg);
4186 if (!mask) {
4187 printf("Log items (comma separated):\n");
4188 for(item = cpu_log_items; item->mask != 0; item++) {
4189 printf("%-10s %s\n", item->name, item->help);
4191 exit(1);
4193 cpu_set_log(mask);
4195 break;
4196 case QEMU_OPTION_s:
4197 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4198 break;
4199 case QEMU_OPTION_gdb:
4200 gdbstub_dev = optarg;
4201 break;
4202 case QEMU_OPTION_L:
4203 data_dir = optarg;
4204 break;
4205 case QEMU_OPTION_bios:
4206 bios_name = optarg;
4207 break;
4208 case QEMU_OPTION_singlestep:
4209 singlestep = 1;
4210 break;
4211 case QEMU_OPTION_S:
4212 autostart = 0;
4213 break;
4214 case QEMU_OPTION_k:
4215 keyboard_layout = optarg;
4216 break;
4217 case QEMU_OPTION_localtime:
4218 rtc_utc = 0;
4219 break;
4220 case QEMU_OPTION_vga:
4221 select_vgahw (optarg);
4222 break;
4223 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4224 case QEMU_OPTION_g:
4226 const char *p;
4227 int w, h, depth;
4228 p = optarg;
4229 w = strtol(p, (char **)&p, 10);
4230 if (w <= 0) {
4231 graphic_error:
4232 fprintf(stderr, "qemu: invalid resolution or depth\n");
4233 exit(1);
4235 if (*p != 'x')
4236 goto graphic_error;
4237 p++;
4238 h = strtol(p, (char **)&p, 10);
4239 if (h <= 0)
4240 goto graphic_error;
4241 if (*p == 'x') {
4242 p++;
4243 depth = strtol(p, (char **)&p, 10);
4244 if (depth != 8 && depth != 15 && depth != 16 &&
4245 depth != 24 && depth != 32)
4246 goto graphic_error;
4247 } else if (*p == '\0') {
4248 depth = graphic_depth;
4249 } else {
4250 goto graphic_error;
4253 graphic_width = w;
4254 graphic_height = h;
4255 graphic_depth = depth;
4257 break;
4258 #endif
4259 case QEMU_OPTION_echr:
4261 char *r;
4262 term_escape_char = strtol(optarg, &r, 0);
4263 if (r == optarg)
4264 printf("Bad argument to echr\n");
4265 break;
4267 case QEMU_OPTION_monitor:
4268 monitor_parse(optarg, "readline");
4269 default_monitor = 0;
4270 break;
4271 case QEMU_OPTION_qmp:
4272 monitor_parse(optarg, "control");
4273 default_qmp = 0;
4274 break;
4275 case QEMU_OPTION_mon:
4276 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
4277 if (!opts) {
4278 fprintf(stderr, "parse error: %s\n", optarg);
4279 exit(1);
4280 } else {
4281 const char *mode;
4282 mode = qemu_opt_get(opts, "mode");
4283 if (mode == NULL || strcmp(mode, "readline") == 0) {
4284 default_monitor = 0;
4285 } else if (strcmp(mode, "control") == 0) {
4286 default_qmp = 0;
4289 break;
4290 case QEMU_OPTION_chardev:
4291 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
4292 if (!opts) {
4293 fprintf(stderr, "parse error: %s\n", optarg);
4294 exit(1);
4296 break;
4297 case QEMU_OPTION_serial:
4298 add_device_config(DEV_SERIAL, optarg);
4299 default_serial = 0;
4300 if (strncmp(optarg, "mon:", 4) == 0) {
4301 default_monitor = 0;
4303 break;
4304 case QEMU_OPTION_watchdog:
4305 if (watchdog) {
4306 fprintf(stderr,
4307 "qemu: only one watchdog option may be given\n");
4308 return 1;
4310 watchdog = optarg;
4311 break;
4312 case QEMU_OPTION_watchdog_action:
4313 if (select_watchdog_action(optarg) == -1) {
4314 fprintf(stderr, "Unknown -watchdog-action parameter\n");
4315 exit(1);
4317 break;
4318 case QEMU_OPTION_virtiocon:
4319 add_device_config(DEV_VIRTCON, optarg);
4320 default_virtcon = 0;
4321 if (strncmp(optarg, "mon:", 4) == 0) {
4322 default_monitor = 0;
4324 break;
4325 case QEMU_OPTION_parallel:
4326 add_device_config(DEV_PARALLEL, optarg);
4327 default_parallel = 0;
4328 if (strncmp(optarg, "mon:", 4) == 0) {
4329 default_monitor = 0;
4331 break;
4332 case QEMU_OPTION_debugcon:
4333 add_device_config(DEV_DEBUGCON, optarg);
4334 break;
4335 case QEMU_OPTION_loadvm:
4336 loadvm = optarg;
4337 break;
4338 case QEMU_OPTION_full_screen:
4339 full_screen = 1;
4340 break;
4341 #ifdef CONFIG_SDL
4342 case QEMU_OPTION_no_frame:
4343 no_frame = 1;
4344 break;
4345 case QEMU_OPTION_alt_grab:
4346 alt_grab = 1;
4347 break;
4348 case QEMU_OPTION_ctrl_grab:
4349 ctrl_grab = 1;
4350 break;
4351 case QEMU_OPTION_no_quit:
4352 no_quit = 1;
4353 break;
4354 case QEMU_OPTION_sdl:
4355 display_type = DT_SDL;
4356 break;
4357 #endif
4358 case QEMU_OPTION_pidfile:
4359 pid_file = optarg;
4360 break;
4361 #ifdef TARGET_I386
4362 case QEMU_OPTION_win2k_hack:
4363 win2k_install_hack = 1;
4364 break;
4365 case QEMU_OPTION_rtc_td_hack:
4366 rtc_td_hack = 1;
4367 break;
4368 case QEMU_OPTION_acpitable:
4369 if(acpi_table_add(optarg) < 0) {
4370 fprintf(stderr, "Wrong acpi table provided\n");
4371 exit(1);
4373 break;
4374 case QEMU_OPTION_smbios:
4375 if(smbios_entry_add(optarg) < 0) {
4376 fprintf(stderr, "Wrong smbios provided\n");
4377 exit(1);
4379 break;
4380 #endif
4381 #ifdef CONFIG_KVM
4382 case QEMU_OPTION_enable_kvm:
4383 kvm_allowed = 1;
4384 break;
4385 #endif
4386 case QEMU_OPTION_usb:
4387 usb_enabled = 1;
4388 break;
4389 case QEMU_OPTION_usbdevice:
4390 usb_enabled = 1;
4391 add_device_config(DEV_USB, optarg);
4392 break;
4393 case QEMU_OPTION_device:
4394 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
4395 exit(1);
4397 break;
4398 case QEMU_OPTION_smp:
4399 smp_parse(optarg);
4400 if (smp_cpus < 1) {
4401 fprintf(stderr, "Invalid number of CPUs\n");
4402 exit(1);
4404 if (max_cpus < smp_cpus) {
4405 fprintf(stderr, "maxcpus must be equal to or greater than "
4406 "smp\n");
4407 exit(1);
4409 if (max_cpus > 255) {
4410 fprintf(stderr, "Unsupported number of maxcpus\n");
4411 exit(1);
4413 break;
4414 case QEMU_OPTION_vnc:
4415 display_type = DT_VNC;
4416 vnc_display = optarg;
4417 break;
4418 #ifdef TARGET_I386
4419 case QEMU_OPTION_no_acpi:
4420 acpi_enabled = 0;
4421 break;
4422 case QEMU_OPTION_no_hpet:
4423 no_hpet = 1;
4424 break;
4425 case QEMU_OPTION_balloon:
4426 if (balloon_parse(optarg) < 0) {
4427 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
4428 exit(1);
4430 break;
4431 #endif
4432 case QEMU_OPTION_no_reboot:
4433 no_reboot = 1;
4434 break;
4435 case QEMU_OPTION_no_shutdown:
4436 no_shutdown = 1;
4437 break;
4438 case QEMU_OPTION_show_cursor:
4439 cursor_hide = 0;
4440 break;
4441 case QEMU_OPTION_uuid:
4442 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4443 fprintf(stderr, "Fail to parse UUID string."
4444 " Wrong format.\n");
4445 exit(1);
4447 break;
4448 #ifndef _WIN32
4449 case QEMU_OPTION_daemonize:
4450 daemonize = 1;
4451 break;
4452 #endif
4453 case QEMU_OPTION_option_rom:
4454 if (nb_option_roms >= MAX_OPTION_ROMS) {
4455 fprintf(stderr, "Too many option ROMs\n");
4456 exit(1);
4458 option_rom[nb_option_roms] = optarg;
4459 nb_option_roms++;
4460 break;
4461 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4462 case QEMU_OPTION_semihosting:
4463 semihosting_enabled = 1;
4464 break;
4465 #endif
4466 case QEMU_OPTION_name:
4467 qemu_name = qemu_strdup(optarg);
4469 char *p = strchr(qemu_name, ',');
4470 if (p != NULL) {
4471 *p++ = 0;
4472 if (strncmp(p, "process=", 8)) {
4473 fprintf(stderr, "Unknown subargument %s to -name", p);
4474 exit(1);
4476 p += 8;
4477 set_proc_name(p);
4480 break;
4481 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4482 case QEMU_OPTION_prom_env:
4483 if (nb_prom_envs >= MAX_PROM_ENVS) {
4484 fprintf(stderr, "Too many prom variables\n");
4485 exit(1);
4487 prom_envs[nb_prom_envs] = optarg;
4488 nb_prom_envs++;
4489 break;
4490 #endif
4491 #ifdef TARGET_ARM
4492 case QEMU_OPTION_old_param:
4493 old_param = 1;
4494 break;
4495 #endif
4496 case QEMU_OPTION_clock:
4497 configure_alarms(optarg);
4498 break;
4499 case QEMU_OPTION_startdate:
4500 configure_rtc_date_offset(optarg, 1);
4501 break;
4502 case QEMU_OPTION_rtc:
4503 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
4504 if (!opts) {
4505 fprintf(stderr, "parse error: %s\n", optarg);
4506 exit(1);
4508 configure_rtc(opts);
4509 break;
4510 case QEMU_OPTION_tb_size:
4511 tb_size = strtol(optarg, NULL, 0);
4512 if (tb_size < 0)
4513 tb_size = 0;
4514 break;
4515 case QEMU_OPTION_icount:
4516 icount_option = optarg;
4517 break;
4518 case QEMU_OPTION_incoming:
4519 incoming = optarg;
4520 break;
4521 case QEMU_OPTION_nodefaults:
4522 default_serial = 0;
4523 default_parallel = 0;
4524 default_virtcon = 0;
4525 default_monitor = 0;
4526 default_qmp = 0;
4527 default_vga = 0;
4528 default_net = 0;
4529 default_floppy = 0;
4530 default_cdrom = 0;
4531 default_sdcard = 0;
4532 break;
4533 #ifndef _WIN32
4534 case QEMU_OPTION_chroot:
4535 chroot_dir = optarg;
4536 break;
4537 case QEMU_OPTION_runas:
4538 run_as = optarg;
4539 break;
4540 #endif
4541 #ifdef CONFIG_XEN
4542 case QEMU_OPTION_xen_domid:
4543 xen_domid = atoi(optarg);
4544 break;
4545 case QEMU_OPTION_xen_create:
4546 xen_mode = XEN_CREATE;
4547 break;
4548 case QEMU_OPTION_xen_attach:
4549 xen_mode = XEN_ATTACH;
4550 break;
4551 #endif
4552 case QEMU_OPTION_readconfig:
4554 FILE *fp;
4555 fp = fopen(optarg, "r");
4556 if (fp == NULL) {
4557 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4558 exit(1);
4560 if (qemu_config_parse(fp, optarg) != 0) {
4561 exit(1);
4563 fclose(fp);
4564 break;
4566 case QEMU_OPTION_writeconfig:
4568 FILE *fp;
4569 if (strcmp(optarg, "-") == 0) {
4570 fp = stdout;
4571 } else {
4572 fp = fopen(optarg, "w");
4573 if (fp == NULL) {
4574 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4575 exit(1);
4578 qemu_config_write(fp);
4579 fclose(fp);
4580 break;
4585 loc_set_none();
4587 /* If no data_dir is specified then try to find it relative to the
4588 executable path. */
4589 if (!data_dir) {
4590 data_dir = find_datadir(argv[0]);
4592 /* If all else fails use the install patch specified when building. */
4593 if (!data_dir) {
4594 data_dir = CONFIG_QEMU_SHAREDIR;
4598 * Default to max_cpus = smp_cpus, in case the user doesn't
4599 * specify a max_cpus value.
4601 if (!max_cpus)
4602 max_cpus = smp_cpus;
4604 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4605 if (smp_cpus > machine->max_cpus) {
4606 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4607 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
4608 machine->max_cpus);
4609 exit(1);
4612 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
4613 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
4615 if (machine->no_serial) {
4616 default_serial = 0;
4618 if (machine->no_parallel) {
4619 default_parallel = 0;
4621 if (!machine->use_virtcon) {
4622 default_virtcon = 0;
4624 if (machine->no_vga) {
4625 default_vga = 0;
4627 if (machine->no_floppy) {
4628 default_floppy = 0;
4630 if (machine->no_cdrom) {
4631 default_cdrom = 0;
4633 if (machine->no_sdcard) {
4634 default_sdcard = 0;
4637 if (display_type == DT_NOGRAPHIC) {
4638 if (default_parallel)
4639 add_device_config(DEV_PARALLEL, "null");
4640 if (default_serial && default_monitor) {
4641 add_device_config(DEV_SERIAL, "mon:stdio");
4642 } else if (default_virtcon && default_monitor) {
4643 add_device_config(DEV_VIRTCON, "mon:stdio");
4644 } else {
4645 if (default_serial)
4646 add_device_config(DEV_SERIAL, "stdio");
4647 if (default_virtcon)
4648 add_device_config(DEV_VIRTCON, "stdio");
4649 if (default_monitor)
4650 monitor_parse("stdio", "readline");
4652 } else {
4653 if (default_serial)
4654 add_device_config(DEV_SERIAL, "vc:80Cx24C");
4655 if (default_parallel)
4656 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4657 if (default_monitor)
4658 monitor_parse("vc:80Cx24C", "readline");
4659 if (default_virtcon)
4660 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4662 if (default_vga)
4663 vga_interface_type = VGA_CIRRUS;
4665 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
4666 exit(1);
4668 #ifndef _WIN32
4669 if (daemonize) {
4670 pid_t pid;
4672 if (pipe(fds) == -1)
4673 exit(1);
4675 pid = fork();
4676 if (pid > 0) {
4677 uint8_t status;
4678 ssize_t len;
4680 close(fds[1]);
4682 again:
4683 len = read(fds[0], &status, 1);
4684 if (len == -1 && (errno == EINTR))
4685 goto again;
4687 if (len != 1)
4688 exit(1);
4689 else if (status == 1) {
4690 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
4691 exit(1);
4692 } else
4693 exit(0);
4694 } else if (pid < 0)
4695 exit(1);
4697 close(fds[0]);
4698 qemu_set_cloexec(fds[1]);
4700 setsid();
4702 pid = fork();
4703 if (pid > 0)
4704 exit(0);
4705 else if (pid < 0)
4706 exit(1);
4708 umask(027);
4710 signal(SIGTSTP, SIG_IGN);
4711 signal(SIGTTOU, SIG_IGN);
4712 signal(SIGTTIN, SIG_IGN);
4714 #endif
4716 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4717 #ifndef _WIN32
4718 if (daemonize) {
4719 uint8_t status = 1;
4720 if (write(fds[1], &status, 1) != 1) {
4721 perror("daemonize. Writing to pipe\n");
4723 } else
4724 #endif
4725 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
4726 exit(1);
4729 if (kvm_enabled()) {
4730 int ret;
4732 ret = kvm_init(smp_cpus);
4733 if (ret < 0) {
4734 fprintf(stderr, "failed to initialize KVM\n");
4735 exit(1);
4739 if (qemu_init_main_loop()) {
4740 fprintf(stderr, "qemu_init_main_loop failed\n");
4741 exit(1);
4743 linux_boot = (kernel_filename != NULL);
4745 if (!linux_boot && *kernel_cmdline != '\0') {
4746 fprintf(stderr, "-append only allowed with -kernel option\n");
4747 exit(1);
4750 if (!linux_boot && initrd_filename != NULL) {
4751 fprintf(stderr, "-initrd only allowed with -kernel option\n");
4752 exit(1);
4755 #ifndef _WIN32
4756 /* Win32 doesn't support line-buffering and requires size >= 2 */
4757 setvbuf(stdout, NULL, _IOLBF, 0);
4758 #endif
4760 if (init_timer_alarm() < 0) {
4761 fprintf(stderr, "could not initialize alarm timer\n");
4762 exit(1);
4764 configure_icount(icount_option);
4766 #ifdef _WIN32
4767 socket_init();
4768 #endif
4770 if (net_init_clients() < 0) {
4771 exit(1);
4774 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4775 net_set_boot_mask(net_boot);
4777 /* init the bluetooth world */
4778 if (foreach_device_config(DEV_BT, bt_parse))
4779 exit(1);
4781 /* init the memory */
4782 if (ram_size == 0)
4783 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4785 /* init the dynamic translator */
4786 cpu_exec_init_all(tb_size * 1024 * 1024);
4788 bdrv_init_with_whitelist();
4790 blk_mig_init();
4792 if (default_cdrom) {
4793 /* we always create the cdrom drive, even if no disk is there */
4794 drive_add(NULL, CDROM_ALIAS);
4797 if (default_floppy) {
4798 /* we always create at least one floppy */
4799 drive_add(NULL, FD_ALIAS, 0);
4802 if (default_sdcard) {
4803 /* we always create one sd slot, even if no card is in it */
4804 drive_add(NULL, SD_ALIAS);
4807 /* open the virtual block devices */
4808 if (snapshot)
4809 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4810 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4811 exit(1);
4813 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
4814 ram_load, NULL);
4816 if (nb_numa_nodes > 0) {
4817 int i;
4819 if (nb_numa_nodes > smp_cpus) {
4820 nb_numa_nodes = smp_cpus;
4823 /* If no memory size if given for any node, assume the default case
4824 * and distribute the available memory equally across all nodes
4826 for (i = 0; i < nb_numa_nodes; i++) {
4827 if (node_mem[i] != 0)
4828 break;
4830 if (i == nb_numa_nodes) {
4831 uint64_t usedmem = 0;
4833 /* On Linux, the each node's border has to be 8MB aligned,
4834 * the final node gets the rest.
4836 for (i = 0; i < nb_numa_nodes - 1; i++) {
4837 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4838 usedmem += node_mem[i];
4840 node_mem[i] = ram_size - usedmem;
4843 for (i = 0; i < nb_numa_nodes; i++) {
4844 if (node_cpumask[i] != 0)
4845 break;
4847 /* assigning the VCPUs round-robin is easier to implement, guest OSes
4848 * must cope with this anyway, because there are BIOSes out there in
4849 * real machines which also use this scheme.
4851 if (i == nb_numa_nodes) {
4852 for (i = 0; i < smp_cpus; i++) {
4853 node_cpumask[i % nb_numa_nodes] |= 1 << i;
4858 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4859 exit(1);
4860 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4861 exit(1);
4862 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4863 exit(1);
4864 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4865 exit(1);
4867 module_call_init(MODULE_INIT_DEVICE);
4869 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
4870 exit(0);
4872 if (watchdog) {
4873 i = select_watchdog(watchdog);
4874 if (i > 0)
4875 exit (i == 1 ? 1 : 0);
4878 if (machine->compat_props) {
4879 qdev_prop_register_global_list(machine->compat_props);
4881 qemu_add_globals();
4883 machine->init(ram_size, boot_devices,
4884 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
4886 cpu_synchronize_all_post_init();
4888 #ifndef _WIN32
4889 /* must be after terminal init, SDL library changes signal handlers */
4890 sighandler_setup();
4891 #endif
4893 for (env = first_cpu; env != NULL; env = env->next_cpu) {
4894 for (i = 0; i < nb_numa_nodes; i++) {
4895 if (node_cpumask[i] & (1 << env->cpu_index)) {
4896 env->numa_node = i;
4901 current_machine = machine;
4903 /* init USB devices */
4904 if (usb_enabled) {
4905 if (foreach_device_config(DEV_USB, usb_parse) < 0)
4906 exit(1);
4909 /* init generic devices */
4910 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
4911 exit(1);
4913 net_check_clients();
4915 /* just use the first displaystate for the moment */
4916 ds = get_displaystate();
4918 if (display_type == DT_DEFAULT) {
4919 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4920 display_type = DT_SDL;
4921 #else
4922 display_type = DT_VNC;
4923 vnc_display = "localhost:0,to=99";
4924 show_vnc_port = 1;
4925 #endif
4929 switch (display_type) {
4930 case DT_NOGRAPHIC:
4931 break;
4932 #if defined(CONFIG_CURSES)
4933 case DT_CURSES:
4934 curses_display_init(ds, full_screen);
4935 break;
4936 #endif
4937 #if defined(CONFIG_SDL)
4938 case DT_SDL:
4939 sdl_display_init(ds, full_screen, no_frame);
4940 break;
4941 #elif defined(CONFIG_COCOA)
4942 case DT_SDL:
4943 cocoa_display_init(ds, full_screen);
4944 break;
4945 #endif
4946 case DT_VNC:
4947 vnc_display_init(ds);
4948 if (vnc_display_open(ds, vnc_display) < 0)
4949 exit(1);
4951 if (show_vnc_port) {
4952 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
4954 break;
4955 default:
4956 break;
4958 dpy_resize(ds);
4960 dcl = ds->listeners;
4961 while (dcl != NULL) {
4962 if (dcl->dpy_refresh != NULL) {
4963 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
4964 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
4966 dcl = dcl->next;
4969 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
4970 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
4971 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
4974 text_consoles_set_display(ds);
4976 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
4977 exit(1);
4979 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
4980 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
4981 gdbstub_dev);
4982 exit(1);
4985 qdev_machine_creation_done();
4987 if (rom_load_all() != 0) {
4988 fprintf(stderr, "rom loading failed\n");
4989 exit(1);
4992 qemu_system_reset();
4993 if (loadvm) {
4994 if (load_vmstate(loadvm) < 0) {
4995 autostart = 0;
4999 if (incoming) {
5000 qemu_start_incoming_migration(incoming);
5001 } else if (autostart) {
5002 vm_start();
5005 #ifndef _WIN32
5006 if (daemonize) {
5007 uint8_t status = 0;
5008 ssize_t len;
5010 again1:
5011 len = write(fds[1], &status, 1);
5012 if (len == -1 && (errno == EINTR))
5013 goto again1;
5015 if (len != 1)
5016 exit(1);
5018 if (chdir("/")) {
5019 perror("not able to chdir to /");
5020 exit(1);
5022 TFR(fd = qemu_open("/dev/null", O_RDWR));
5023 if (fd == -1)
5024 exit(1);
5027 if (run_as) {
5028 pwd = getpwnam(run_as);
5029 if (!pwd) {
5030 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5031 exit(1);
5035 if (chroot_dir) {
5036 if (chroot(chroot_dir) < 0) {
5037 fprintf(stderr, "chroot failed\n");
5038 exit(1);
5040 if (chdir("/")) {
5041 perror("not able to chdir to /");
5042 exit(1);
5046 if (run_as) {
5047 if (setgid(pwd->pw_gid) < 0) {
5048 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5049 exit(1);
5051 if (setuid(pwd->pw_uid) < 0) {
5052 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5053 exit(1);
5055 if (setuid(0) != -1) {
5056 fprintf(stderr, "Dropping privileges failed\n");
5057 exit(1);
5061 if (daemonize) {
5062 dup2(fd, 0);
5063 dup2(fd, 1);
5064 dup2(fd, 2);
5066 close(fd);
5068 #endif
5070 main_loop();
5071 quit_timers();
5072 net_cleanup();
5074 return 0;