Revert "qmp: don't make -qmp disable the default monitor"
[qemu/aliguori-queue.git] / vl.c
bloba4d6bc25911843872651032e47768dcd486f4812
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #include <arpa/inet.h>
48 #include <dirent.h>
49 #include <netdb.h>
50 #include <sys/select.h>
51 #ifdef CONFIG_BSD
52 #include <sys/stat.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54 #include <libutil.h>
55 #else
56 #include <util.h>
57 #endif
58 #else
59 #ifdef __linux__
60 #include <pty.h>
61 #include <malloc.h>
62 #include <sys/prctl.h>
64 #include <linux/ppdev.h>
65 #include <linux/parport.h>
66 #endif
67 #ifdef __sun__
68 #include <sys/stat.h>
69 #include <sys/ethernet.h>
70 #include <sys/sockio.h>
71 #include <netinet/arp.h>
72 #include <netinet/in.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/ip_icmp.h> // must come after ip.h
76 #include <netinet/udp.h>
77 #include <netinet/tcp.h>
78 #include <net/if.h>
79 #include <syslog.h>
80 #include <stropts.h>
81 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
82 discussion about Solaris header problems */
83 extern int madvise(caddr_t, size_t, int);
84 #endif
85 #endif
86 #endif
88 #if defined(__OpenBSD__)
89 #include <util.h>
90 #endif
92 #if defined(CONFIG_VDE)
93 #include <libvdeplug.h>
94 #endif
96 #if defined(CONFIG_UUID)
97 #include <uuid/uuid.h>
98 #endif
100 #ifdef _WIN32
101 #include <windows.h>
102 #endif
104 #ifdef CONFIG_SDL
105 #if defined(__APPLE__) || defined(main)
106 #include <SDL.h>
107 int qemu_main(int argc, char **argv, char **envp);
108 int main(int argc, char **argv)
110 return qemu_main(argc, argv, NULL);
112 #undef main
113 #define main qemu_main
114 #endif
115 #endif /* CONFIG_SDL */
117 #ifdef CONFIG_COCOA
118 #undef main
119 #define main qemu_main
120 #endif /* CONFIG_COCOA */
122 #include "hw/hw.h"
123 #include "hw/boards.h"
124 #include "hw/usb.h"
125 #include "hw/pcmcia.h"
126 #include "hw/pc.h"
127 #include "hw/audiodev.h"
128 #include "hw/isa.h"
129 #include "hw/baum.h"
130 #include "hw/bt.h"
131 #include "hw/watchdog.h"
132 #include "hw/smbios.h"
133 #include "hw/xen.h"
134 #include "hw/qdev.h"
135 #include "hw/loader.h"
136 #include "bt-host.h"
137 #include "net.h"
138 #include "net/slirp.h"
139 #include "monitor.h"
140 #include "console.h"
141 #include "sysemu.h"
142 #include "gdbstub.h"
143 #include "qemu-timer.h"
144 #include "qemu-char.h"
145 #include "cache-utils.h"
146 #include "block.h"
147 #include "block_int.h"
148 #include "block-migration.h"
149 #include "dma.h"
150 #include "audio/audio.h"
151 #include "migration.h"
152 #include "kvm.h"
153 #include "balloon.h"
154 #include "qemu-option.h"
155 #include "qemu-config.h"
156 #include "qemu-objects.h"
158 #include "disas.h"
160 #include "exec-all.h"
162 #include "qemu_socket.h"
164 #include "slirp/libslirp.h"
166 #include "qemu-queue.h"
168 //#define DEBUG_NET
169 //#define DEBUG_SLIRP
171 #define DEFAULT_RAM_SIZE 128
173 #define MAX_VIRTIO_CONSOLES 1
175 static const char *data_dir;
176 const char *bios_name = NULL;
177 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
178 to store the VM snapshots */
179 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
180 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
181 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
182 DisplayType display_type = DT_DEFAULT;
183 const char* keyboard_layout = NULL;
184 ram_addr_t ram_size;
185 const char *mem_path = NULL;
186 #ifdef MAP_POPULATE
187 int mem_prealloc = 0; /* force preallocation of physical target memory */
188 #endif
189 int nb_nics;
190 NICInfo nd_table[MAX_NICS];
191 int vm_running;
192 int autostart;
193 static int rtc_utc = 1;
194 static int rtc_date_offset = -1; /* -1 means no change */
195 QEMUClock *rtc_clock;
196 int vga_interface_type = VGA_NONE;
197 #ifdef TARGET_SPARC
198 int graphic_width = 1024;
199 int graphic_height = 768;
200 int graphic_depth = 8;
201 #else
202 int graphic_width = 800;
203 int graphic_height = 600;
204 int graphic_depth = 15;
205 #endif
206 static int full_screen = 0;
207 #ifdef CONFIG_SDL
208 static int no_frame = 0;
209 #endif
210 int no_quit = 0;
211 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
212 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
213 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
214 #ifdef TARGET_I386
215 int win2k_install_hack = 0;
216 int rtc_td_hack = 0;
217 #endif
218 int usb_enabled = 0;
219 int singlestep = 0;
220 int smp_cpus = 1;
221 int max_cpus = 0;
222 int smp_cores = 1;
223 int smp_threads = 1;
224 const char *vnc_display;
225 int acpi_enabled = 1;
226 int no_hpet = 0;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 uint8_t irq0override = 1;
233 #ifndef _WIN32
234 int daemonize = 0;
235 #endif
236 const char *watchdog;
237 const char *option_rom[MAX_OPTION_ROMS];
238 int nb_option_roms;
239 int semihosting_enabled = 0;
240 #ifdef TARGET_ARM
241 int old_param = 0;
242 #endif
243 const char *qemu_name;
244 int alt_grab = 0;
245 int ctrl_grab = 0;
246 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
247 unsigned int nb_prom_envs = 0;
248 const char *prom_envs[MAX_PROM_ENVS];
249 #endif
250 int boot_menu;
252 int nb_numa_nodes;
253 uint64_t node_mem[MAX_NODES];
254 uint64_t node_cpumask[MAX_NODES];
256 static CPUState *cur_cpu;
257 static CPUState *next_cpu;
258 static QEMUTimer *nographic_timer;
260 uint8_t qemu_uuid[16];
262 static QEMUBootSetHandler *boot_set_handler;
263 static void *boot_set_opaque;
265 #ifdef SIGRTMIN
266 #define SIG_IPI (SIGRTMIN+4)
267 #else
268 #define SIG_IPI SIGUSR1
269 #endif
271 static int default_serial = 1;
272 static int default_parallel = 1;
273 static int default_virtcon = 1;
274 static int default_monitor = 1;
275 static int default_vga = 1;
276 static int default_floppy = 1;
277 static int default_cdrom = 1;
278 static int default_sdcard = 1;
280 static struct {
281 const char *driver;
282 int *flag;
283 } default_list[] = {
284 { .driver = "isa-serial", .flag = &default_serial },
285 { .driver = "isa-parallel", .flag = &default_parallel },
286 { .driver = "isa-fdc", .flag = &default_floppy },
287 { .driver = "ide-drive", .flag = &default_cdrom },
288 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
289 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
290 { .driver = "virtio-serial", .flag = &default_virtcon },
291 { .driver = "VGA", .flag = &default_vga },
292 { .driver = "cirrus-vga", .flag = &default_vga },
293 { .driver = "vmware-svga", .flag = &default_vga },
296 static int default_driver_check(QemuOpts *opts, void *opaque)
298 const char *driver = qemu_opt_get(opts, "driver");
299 int i;
301 if (!driver)
302 return 0;
303 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
304 if (strcmp(default_list[i].driver, driver) != 0)
305 continue;
306 *(default_list[i].flag) = 0;
308 return 0;
311 /***********************************************************/
312 /* x86 ISA bus support */
314 target_phys_addr_t isa_mem_base = 0;
315 PicState2 *isa_pic;
317 /***********************************************************/
318 void hw_error(const char *fmt, ...)
320 va_list ap;
321 CPUState *env;
323 va_start(ap, fmt);
324 fprintf(stderr, "qemu: hardware error: ");
325 vfprintf(stderr, fmt, ap);
326 fprintf(stderr, "\n");
327 for(env = first_cpu; env != NULL; env = env->next_cpu) {
328 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
329 #ifdef TARGET_I386
330 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
331 #else
332 cpu_dump_state(env, stderr, fprintf, 0);
333 #endif
335 va_end(ap);
336 abort();
339 static void set_proc_name(const char *s)
341 #if defined(__linux__) && defined(PR_SET_NAME)
342 char name[16];
343 if (!s)
344 return;
345 name[sizeof(name) - 1] = 0;
346 strncpy(name, s, sizeof(name));
347 /* Could rewrite argv[0] too, but that's a bit more complicated.
348 This simple way is enough for `top'. */
349 prctl(PR_SET_NAME, name);
350 #endif
353 /***************/
354 /* ballooning */
356 static QEMUBalloonEvent *qemu_balloon_event;
357 void *qemu_balloon_event_opaque;
359 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
361 qemu_balloon_event = func;
362 qemu_balloon_event_opaque = opaque;
365 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
367 if (qemu_balloon_event) {
368 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
369 return 1;
370 } else {
371 return 0;
375 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
377 if (qemu_balloon_event) {
378 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
379 return 1;
380 } else {
381 return 0;
386 /***********************************************************/
387 /* real time host monotonic timer */
389 /* compute with 96 bit intermediate result: (a*b)/c */
390 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
392 union {
393 uint64_t ll;
394 struct {
395 #ifdef HOST_WORDS_BIGENDIAN
396 uint32_t high, low;
397 #else
398 uint32_t low, high;
399 #endif
400 } l;
401 } u, res;
402 uint64_t rl, rh;
404 u.ll = a;
405 rl = (uint64_t)u.l.low * (uint64_t)b;
406 rh = (uint64_t)u.l.high * (uint64_t)b;
407 rh += (rl >> 32);
408 res.l.high = rh / c;
409 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
410 return res.ll;
413 /***********************************************************/
414 /* host time/date access */
415 void qemu_get_timedate(struct tm *tm, int offset)
417 time_t ti;
418 struct tm *ret;
420 time(&ti);
421 ti += offset;
422 if (rtc_date_offset == -1) {
423 if (rtc_utc)
424 ret = gmtime(&ti);
425 else
426 ret = localtime(&ti);
427 } else {
428 ti -= rtc_date_offset;
429 ret = gmtime(&ti);
432 memcpy(tm, ret, sizeof(struct tm));
435 int qemu_timedate_diff(struct tm *tm)
437 time_t seconds;
439 if (rtc_date_offset == -1)
440 if (rtc_utc)
441 seconds = mktimegm(tm);
442 else
443 seconds = mktime(tm);
444 else
445 seconds = mktimegm(tm) + rtc_date_offset;
447 return seconds - time(NULL);
450 void rtc_change_mon_event(struct tm *tm)
452 QObject *data;
454 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
455 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
456 qobject_decref(data);
459 static void configure_rtc_date_offset(const char *startdate, int legacy)
461 time_t rtc_start_date;
462 struct tm tm;
464 if (!strcmp(startdate, "now") && legacy) {
465 rtc_date_offset = -1;
466 } else {
467 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
468 &tm.tm_year,
469 &tm.tm_mon,
470 &tm.tm_mday,
471 &tm.tm_hour,
472 &tm.tm_min,
473 &tm.tm_sec) == 6) {
474 /* OK */
475 } else if (sscanf(startdate, "%d-%d-%d",
476 &tm.tm_year,
477 &tm.tm_mon,
478 &tm.tm_mday) == 3) {
479 tm.tm_hour = 0;
480 tm.tm_min = 0;
481 tm.tm_sec = 0;
482 } else {
483 goto date_fail;
485 tm.tm_year -= 1900;
486 tm.tm_mon--;
487 rtc_start_date = mktimegm(&tm);
488 if (rtc_start_date == -1) {
489 date_fail:
490 fprintf(stderr, "Invalid date format. Valid formats are:\n"
491 "'2006-06-17T16:01:21' or '2006-06-17'\n");
492 exit(1);
494 rtc_date_offset = time(NULL) - rtc_start_date;
498 static void configure_rtc(QemuOpts *opts)
500 const char *value;
502 value = qemu_opt_get(opts, "base");
503 if (value) {
504 if (!strcmp(value, "utc")) {
505 rtc_utc = 1;
506 } else if (!strcmp(value, "localtime")) {
507 rtc_utc = 0;
508 } else {
509 configure_rtc_date_offset(value, 0);
512 value = qemu_opt_get(opts, "clock");
513 if (value) {
514 if (!strcmp(value, "host")) {
515 rtc_clock = host_clock;
516 } else if (!strcmp(value, "vm")) {
517 rtc_clock = vm_clock;
518 } else {
519 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
520 exit(1);
523 #ifdef CONFIG_TARGET_I386
524 value = qemu_opt_get(opts, "driftfix");
525 if (value) {
526 if (!strcmp(buf, "slew")) {
527 rtc_td_hack = 1;
528 } else if (!strcmp(buf, "none")) {
529 rtc_td_hack = 0;
530 } else {
531 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
532 exit(1);
535 #endif
538 #ifdef _WIN32
539 static void socket_cleanup(void)
541 WSACleanup();
544 static int socket_init(void)
546 WSADATA Data;
547 int ret, err;
549 ret = WSAStartup(MAKEWORD(2,2), &Data);
550 if (ret != 0) {
551 err = WSAGetLastError();
552 fprintf(stderr, "WSAStartup: %d\n", err);
553 return -1;
555 atexit(socket_cleanup);
556 return 0;
558 #endif
560 /***********************************************************/
561 /* Bluetooth support */
562 static int nb_hcis;
563 static int cur_hci;
564 static struct HCIInfo *hci_table[MAX_NICS];
566 static struct bt_vlan_s {
567 struct bt_scatternet_s net;
568 int id;
569 struct bt_vlan_s *next;
570 } *first_bt_vlan;
572 /* find or alloc a new bluetooth "VLAN" */
573 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
575 struct bt_vlan_s **pvlan, *vlan;
576 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
577 if (vlan->id == id)
578 return &vlan->net;
580 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
581 vlan->id = id;
582 pvlan = &first_bt_vlan;
583 while (*pvlan != NULL)
584 pvlan = &(*pvlan)->next;
585 *pvlan = vlan;
586 return &vlan->net;
589 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
593 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
595 return -ENOTSUP;
598 static struct HCIInfo null_hci = {
599 .cmd_send = null_hci_send,
600 .sco_send = null_hci_send,
601 .acl_send = null_hci_send,
602 .bdaddr_set = null_hci_addr_set,
605 struct HCIInfo *qemu_next_hci(void)
607 if (cur_hci == nb_hcis)
608 return &null_hci;
610 return hci_table[cur_hci++];
613 static struct HCIInfo *hci_init(const char *str)
615 char *endp;
616 struct bt_scatternet_s *vlan = 0;
618 if (!strcmp(str, "null"))
619 /* null */
620 return &null_hci;
621 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
622 /* host[:hciN] */
623 return bt_host_hci(str[4] ? str + 5 : "hci0");
624 else if (!strncmp(str, "hci", 3)) {
625 /* hci[,vlan=n] */
626 if (str[3]) {
627 if (!strncmp(str + 3, ",vlan=", 6)) {
628 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
629 if (*endp)
630 vlan = 0;
632 } else
633 vlan = qemu_find_bt_vlan(0);
634 if (vlan)
635 return bt_new_hci(vlan);
638 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
640 return 0;
643 static int bt_hci_parse(const char *str)
645 struct HCIInfo *hci;
646 bdaddr_t bdaddr;
648 if (nb_hcis >= MAX_NICS) {
649 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
650 return -1;
653 hci = hci_init(str);
654 if (!hci)
655 return -1;
657 bdaddr.b[0] = 0x52;
658 bdaddr.b[1] = 0x54;
659 bdaddr.b[2] = 0x00;
660 bdaddr.b[3] = 0x12;
661 bdaddr.b[4] = 0x34;
662 bdaddr.b[5] = 0x56 + nb_hcis;
663 hci->bdaddr_set(hci, bdaddr.b);
665 hci_table[nb_hcis++] = hci;
667 return 0;
670 static void bt_vhci_add(int vlan_id)
672 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
674 if (!vlan->slave)
675 fprintf(stderr, "qemu: warning: adding a VHCI to "
676 "an empty scatternet %i\n", vlan_id);
678 bt_vhci_init(bt_new_hci(vlan));
681 static struct bt_device_s *bt_device_add(const char *opt)
683 struct bt_scatternet_s *vlan;
684 int vlan_id = 0;
685 char *endp = strstr(opt, ",vlan=");
686 int len = (endp ? endp - opt : strlen(opt)) + 1;
687 char devname[10];
689 pstrcpy(devname, MIN(sizeof(devname), len), opt);
691 if (endp) {
692 vlan_id = strtol(endp + 6, &endp, 0);
693 if (*endp) {
694 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
695 return 0;
699 vlan = qemu_find_bt_vlan(vlan_id);
701 if (!vlan->slave)
702 fprintf(stderr, "qemu: warning: adding a slave device to "
703 "an empty scatternet %i\n", vlan_id);
705 if (!strcmp(devname, "keyboard"))
706 return bt_keyboard_init(vlan);
708 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
709 return 0;
712 static int bt_parse(const char *opt)
714 const char *endp, *p;
715 int vlan;
717 if (strstart(opt, "hci", &endp)) {
718 if (!*endp || *endp == ',') {
719 if (*endp)
720 if (!strstart(endp, ",vlan=", 0))
721 opt = endp + 1;
723 return bt_hci_parse(opt);
725 } else if (strstart(opt, "vhci", &endp)) {
726 if (!*endp || *endp == ',') {
727 if (*endp) {
728 if (strstart(endp, ",vlan=", &p)) {
729 vlan = strtol(p, (char **) &endp, 0);
730 if (*endp) {
731 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
732 return 1;
734 } else {
735 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
736 return 1;
738 } else
739 vlan = 0;
741 bt_vhci_add(vlan);
742 return 0;
744 } else if (strstart(opt, "device:", &endp))
745 return !bt_device_add(endp);
747 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
748 return 1;
751 /***********************************************************/
752 /* QEMU Block devices */
754 #define HD_ALIAS "index=%d,media=disk"
755 #define CDROM_ALIAS "index=2,media=cdrom"
756 #define FD_ALIAS "index=%d,if=floppy"
757 #define PFLASH_ALIAS "if=pflash"
758 #define MTD_ALIAS "if=mtd"
759 #define SD_ALIAS "index=0,if=sd"
761 QemuOpts *drive_add(const char *file, const char *fmt, ...)
763 va_list ap;
764 char optstr[1024];
765 QemuOpts *opts;
767 va_start(ap, fmt);
768 vsnprintf(optstr, sizeof(optstr), fmt, ap);
769 va_end(ap);
771 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
772 if (!opts) {
773 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
774 __FUNCTION__, optstr);
775 return NULL;
777 if (file)
778 qemu_opt_set(opts, "file", file);
779 return opts;
782 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
784 DriveInfo *dinfo;
786 /* seek interface, bus and unit */
788 QTAILQ_FOREACH(dinfo, &drives, next) {
789 if (dinfo->type == type &&
790 dinfo->bus == bus &&
791 dinfo->unit == unit)
792 return dinfo;
795 return NULL;
798 DriveInfo *drive_get_by_id(const char *id)
800 DriveInfo *dinfo;
802 QTAILQ_FOREACH(dinfo, &drives, next) {
803 if (strcmp(id, dinfo->id))
804 continue;
805 return dinfo;
807 return NULL;
810 int drive_get_max_bus(BlockInterfaceType type)
812 int max_bus;
813 DriveInfo *dinfo;
815 max_bus = -1;
816 QTAILQ_FOREACH(dinfo, &drives, next) {
817 if(dinfo->type == type &&
818 dinfo->bus > max_bus)
819 max_bus = dinfo->bus;
821 return max_bus;
824 const char *drive_get_serial(BlockDriverState *bdrv)
826 DriveInfo *dinfo;
828 QTAILQ_FOREACH(dinfo, &drives, next) {
829 if (dinfo->bdrv == bdrv)
830 return dinfo->serial;
833 return "\0";
836 BlockInterfaceErrorAction drive_get_on_error(
837 BlockDriverState *bdrv, int is_read)
839 DriveInfo *dinfo;
841 QTAILQ_FOREACH(dinfo, &drives, next) {
842 if (dinfo->bdrv == bdrv)
843 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
846 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
849 static void bdrv_format_print(void *opaque, const char *name)
851 fprintf(stderr, " %s", name);
854 void drive_uninit(DriveInfo *dinfo)
856 qemu_opts_del(dinfo->opts);
857 bdrv_delete(dinfo->bdrv);
858 QTAILQ_REMOVE(&drives, dinfo, next);
859 qemu_free(dinfo);
862 static int parse_block_error_action(const char *buf, int is_read)
864 if (!strcmp(buf, "ignore")) {
865 return BLOCK_ERR_IGNORE;
866 } else if (!is_read && !strcmp(buf, "enospc")) {
867 return BLOCK_ERR_STOP_ENOSPC;
868 } else if (!strcmp(buf, "stop")) {
869 return BLOCK_ERR_STOP_ANY;
870 } else if (!strcmp(buf, "report")) {
871 return BLOCK_ERR_REPORT;
872 } else {
873 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
874 buf, is_read ? "read" : "write");
875 return -1;
879 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
880 int *fatal_error)
882 const char *buf;
883 const char *file = NULL;
884 char devname[128];
885 const char *serial;
886 const char *mediastr = "";
887 BlockInterfaceType type;
888 enum { MEDIA_DISK, MEDIA_CDROM } media;
889 int bus_id, unit_id;
890 int cyls, heads, secs, translation;
891 BlockDriver *drv = NULL;
892 QEMUMachine *machine = opaque;
893 int max_devs;
894 int index;
895 int cache;
896 int aio = 0;
897 int ro = 0;
898 int bdrv_flags;
899 int on_read_error, on_write_error;
900 const char *devaddr;
901 DriveInfo *dinfo;
902 int snapshot = 0;
904 *fatal_error = 1;
906 translation = BIOS_ATA_TRANSLATION_AUTO;
907 cache = 1;
909 if (machine && machine->use_scsi) {
910 type = IF_SCSI;
911 max_devs = MAX_SCSI_DEVS;
912 pstrcpy(devname, sizeof(devname), "scsi");
913 } else {
914 type = IF_IDE;
915 max_devs = MAX_IDE_DEVS;
916 pstrcpy(devname, sizeof(devname), "ide");
918 media = MEDIA_DISK;
920 /* extract parameters */
921 bus_id = qemu_opt_get_number(opts, "bus", 0);
922 unit_id = qemu_opt_get_number(opts, "unit", -1);
923 index = qemu_opt_get_number(opts, "index", -1);
925 cyls = qemu_opt_get_number(opts, "cyls", 0);
926 heads = qemu_opt_get_number(opts, "heads", 0);
927 secs = qemu_opt_get_number(opts, "secs", 0);
929 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
930 ro = qemu_opt_get_bool(opts, "readonly", 0);
932 file = qemu_opt_get(opts, "file");
933 serial = qemu_opt_get(opts, "serial");
935 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
936 pstrcpy(devname, sizeof(devname), buf);
937 if (!strcmp(buf, "ide")) {
938 type = IF_IDE;
939 max_devs = MAX_IDE_DEVS;
940 } else if (!strcmp(buf, "scsi")) {
941 type = IF_SCSI;
942 max_devs = MAX_SCSI_DEVS;
943 } else if (!strcmp(buf, "floppy")) {
944 type = IF_FLOPPY;
945 max_devs = 0;
946 } else if (!strcmp(buf, "pflash")) {
947 type = IF_PFLASH;
948 max_devs = 0;
949 } else if (!strcmp(buf, "mtd")) {
950 type = IF_MTD;
951 max_devs = 0;
952 } else if (!strcmp(buf, "sd")) {
953 type = IF_SD;
954 max_devs = 0;
955 } else if (!strcmp(buf, "virtio")) {
956 type = IF_VIRTIO;
957 max_devs = 0;
958 } else if (!strcmp(buf, "xen")) {
959 type = IF_XEN;
960 max_devs = 0;
961 } else if (!strcmp(buf, "none")) {
962 type = IF_NONE;
963 max_devs = 0;
964 } else {
965 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
966 return NULL;
970 if (cyls || heads || secs) {
971 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
972 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
973 return NULL;
975 if (heads < 1 || (type == IF_IDE && heads > 16)) {
976 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
977 return NULL;
979 if (secs < 1 || (type == IF_IDE && secs > 63)) {
980 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
981 return NULL;
985 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
986 if (!cyls) {
987 fprintf(stderr,
988 "qemu: '%s' trans must be used with cyls,heads and secs\n",
989 buf);
990 return NULL;
992 if (!strcmp(buf, "none"))
993 translation = BIOS_ATA_TRANSLATION_NONE;
994 else if (!strcmp(buf, "lba"))
995 translation = BIOS_ATA_TRANSLATION_LBA;
996 else if (!strcmp(buf, "auto"))
997 translation = BIOS_ATA_TRANSLATION_AUTO;
998 else {
999 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
1000 return NULL;
1004 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
1005 if (!strcmp(buf, "disk")) {
1006 media = MEDIA_DISK;
1007 } else if (!strcmp(buf, "cdrom")) {
1008 if (cyls || secs || heads) {
1009 fprintf(stderr,
1010 "qemu: '%s' invalid physical CHS format\n", buf);
1011 return NULL;
1013 media = MEDIA_CDROM;
1014 } else {
1015 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
1016 return NULL;
1020 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
1021 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
1022 cache = 0;
1023 else if (!strcmp(buf, "writethrough"))
1024 cache = 1;
1025 else if (!strcmp(buf, "writeback"))
1026 cache = 2;
1027 else {
1028 fprintf(stderr, "qemu: invalid cache option\n");
1029 return NULL;
1033 #ifdef CONFIG_LINUX_AIO
1034 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1035 if (!strcmp(buf, "threads"))
1036 aio = 0;
1037 else if (!strcmp(buf, "native"))
1038 aio = 1;
1039 else {
1040 fprintf(stderr, "qemu: invalid aio option\n");
1041 return NULL;
1044 #endif
1046 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1047 if (strcmp(buf, "?") == 0) {
1048 fprintf(stderr, "qemu: Supported formats:");
1049 bdrv_iterate_format(bdrv_format_print, NULL);
1050 fprintf(stderr, "\n");
1051 return NULL;
1053 drv = bdrv_find_whitelisted_format(buf);
1054 if (!drv) {
1055 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1056 return NULL;
1060 on_write_error = BLOCK_ERR_STOP_ENOSPC;
1061 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1062 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1063 fprintf(stderr, "werror is no supported by this format\n");
1064 return NULL;
1067 on_write_error = parse_block_error_action(buf, 0);
1068 if (on_write_error < 0) {
1069 return NULL;
1073 on_read_error = BLOCK_ERR_REPORT;
1074 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1075 if (type != IF_IDE && type != IF_VIRTIO) {
1076 fprintf(stderr, "rerror is no supported by this format\n");
1077 return NULL;
1080 on_read_error = parse_block_error_action(buf, 1);
1081 if (on_read_error < 0) {
1082 return NULL;
1086 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1087 if (type != IF_VIRTIO) {
1088 fprintf(stderr, "addr is not supported\n");
1089 return NULL;
1093 /* compute bus and unit according index */
1095 if (index != -1) {
1096 if (bus_id != 0 || unit_id != -1) {
1097 fprintf(stderr,
1098 "qemu: index cannot be used with bus and unit\n");
1099 return NULL;
1101 if (max_devs == 0)
1103 unit_id = index;
1104 bus_id = 0;
1105 } else {
1106 unit_id = index % max_devs;
1107 bus_id = index / max_devs;
1111 /* if user doesn't specify a unit_id,
1112 * try to find the first free
1115 if (unit_id == -1) {
1116 unit_id = 0;
1117 while (drive_get(type, bus_id, unit_id) != NULL) {
1118 unit_id++;
1119 if (max_devs && unit_id >= max_devs) {
1120 unit_id -= max_devs;
1121 bus_id++;
1126 /* check unit id */
1128 if (max_devs && unit_id >= max_devs) {
1129 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1130 unit_id, max_devs - 1);
1131 return NULL;
1135 * ignore multiple definitions
1138 if (drive_get(type, bus_id, unit_id) != NULL) {
1139 *fatal_error = 0;
1140 return NULL;
1143 /* init */
1145 dinfo = qemu_mallocz(sizeof(*dinfo));
1146 if ((buf = qemu_opts_id(opts)) != NULL) {
1147 dinfo->id = qemu_strdup(buf);
1148 } else {
1149 /* no id supplied -> create one */
1150 dinfo->id = qemu_mallocz(32);
1151 if (type == IF_IDE || type == IF_SCSI)
1152 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1153 if (max_devs)
1154 snprintf(dinfo->id, 32, "%s%i%s%i",
1155 devname, bus_id, mediastr, unit_id);
1156 else
1157 snprintf(dinfo->id, 32, "%s%s%i",
1158 devname, mediastr, unit_id);
1160 dinfo->bdrv = bdrv_new(dinfo->id);
1161 dinfo->devaddr = devaddr;
1162 dinfo->type = type;
1163 dinfo->bus = bus_id;
1164 dinfo->unit = unit_id;
1165 dinfo->on_read_error = on_read_error;
1166 dinfo->on_write_error = on_write_error;
1167 dinfo->opts = opts;
1168 if (serial)
1169 strncpy(dinfo->serial, serial, sizeof(serial));
1170 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1172 switch(type) {
1173 case IF_IDE:
1174 case IF_SCSI:
1175 case IF_XEN:
1176 case IF_NONE:
1177 switch(media) {
1178 case MEDIA_DISK:
1179 if (cyls != 0) {
1180 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1181 bdrv_set_translation_hint(dinfo->bdrv, translation);
1183 break;
1184 case MEDIA_CDROM:
1185 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1186 break;
1188 break;
1189 case IF_SD:
1190 /* FIXME: This isn't really a floppy, but it's a reasonable
1191 approximation. */
1192 case IF_FLOPPY:
1193 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1194 break;
1195 case IF_PFLASH:
1196 case IF_MTD:
1197 break;
1198 case IF_VIRTIO:
1199 /* add virtio block device */
1200 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1201 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1202 qemu_opt_set(opts, "drive", dinfo->id);
1203 if (devaddr)
1204 qemu_opt_set(opts, "addr", devaddr);
1205 break;
1206 case IF_COUNT:
1207 abort();
1209 if (!file) {
1210 *fatal_error = 0;
1211 return NULL;
1213 bdrv_flags = 0;
1214 if (snapshot) {
1215 bdrv_flags |= BDRV_O_SNAPSHOT;
1216 cache = 2; /* always use write-back with snapshot */
1218 if (cache == 0) /* no caching */
1219 bdrv_flags |= BDRV_O_NOCACHE;
1220 else if (cache == 2) /* write-back */
1221 bdrv_flags |= BDRV_O_CACHE_WB;
1223 if (aio == 1) {
1224 bdrv_flags |= BDRV_O_NATIVE_AIO;
1225 } else {
1226 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1229 if (ro == 1) {
1230 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1231 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1232 return NULL;
1236 * cdrom is read-only. Set it now, after above interface checking
1237 * since readonly attribute not explicitly required, so no error.
1239 if (media == MEDIA_CDROM) {
1240 ro = 1;
1242 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1244 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1245 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1246 file, strerror(errno));
1247 return NULL;
1250 if (bdrv_key_required(dinfo->bdrv))
1251 autostart = 0;
1252 *fatal_error = 0;
1253 return dinfo;
1256 static int drive_init_func(QemuOpts *opts, void *opaque)
1258 QEMUMachine *machine = opaque;
1259 int fatal_error = 0;
1261 if (drive_init(opts, machine, &fatal_error) == NULL) {
1262 if (fatal_error)
1263 return 1;
1265 return 0;
1268 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1270 if (NULL == qemu_opt_get(opts, "snapshot")) {
1271 qemu_opt_set(opts, "snapshot", "on");
1273 return 0;
1276 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1278 boot_set_handler = func;
1279 boot_set_opaque = opaque;
1282 int qemu_boot_set(const char *boot_devices)
1284 if (!boot_set_handler) {
1285 return -EINVAL;
1287 return boot_set_handler(boot_set_opaque, boot_devices);
1290 static int parse_bootdevices(char *devices)
1292 /* We just do some generic consistency checks */
1293 const char *p;
1294 int bitmap = 0;
1296 for (p = devices; *p != '\0'; p++) {
1297 /* Allowed boot devices are:
1298 * a-b: floppy disk drives
1299 * c-f: IDE disk drives
1300 * g-m: machine implementation dependant drives
1301 * n-p: network devices
1302 * It's up to each machine implementation to check if the given boot
1303 * devices match the actual hardware implementation and firmware
1304 * features.
1306 if (*p < 'a' || *p > 'p') {
1307 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1308 exit(1);
1310 if (bitmap & (1 << (*p - 'a'))) {
1311 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1312 exit(1);
1314 bitmap |= 1 << (*p - 'a');
1316 return bitmap;
1319 static void restore_boot_devices(void *opaque)
1321 char *standard_boot_devices = opaque;
1323 qemu_boot_set(standard_boot_devices);
1325 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1326 qemu_free(standard_boot_devices);
1329 static void numa_add(const char *optarg)
1331 char option[128];
1332 char *endptr;
1333 unsigned long long value, endvalue;
1334 int nodenr;
1336 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1337 if (!strcmp(option, "node")) {
1338 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1339 nodenr = nb_numa_nodes;
1340 } else {
1341 nodenr = strtoull(option, NULL, 10);
1344 if (get_param_value(option, 128, "mem", optarg) == 0) {
1345 node_mem[nodenr] = 0;
1346 } else {
1347 value = strtoull(option, &endptr, 0);
1348 switch (*endptr) {
1349 case 0: case 'M': case 'm':
1350 value <<= 20;
1351 break;
1352 case 'G': case 'g':
1353 value <<= 30;
1354 break;
1356 node_mem[nodenr] = value;
1358 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1359 node_cpumask[nodenr] = 0;
1360 } else {
1361 value = strtoull(option, &endptr, 10);
1362 if (value >= 64) {
1363 value = 63;
1364 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1365 } else {
1366 if (*endptr == '-') {
1367 endvalue = strtoull(endptr+1, &endptr, 10);
1368 if (endvalue >= 63) {
1369 endvalue = 62;
1370 fprintf(stderr,
1371 "only 63 CPUs in NUMA mode supported.\n");
1373 value = (2ULL << endvalue) - (1ULL << value);
1374 } else {
1375 value = 1ULL << value;
1378 node_cpumask[nodenr] = value;
1380 nb_numa_nodes++;
1382 return;
1385 static void smp_parse(const char *optarg)
1387 int smp, sockets = 0, threads = 0, cores = 0;
1388 char *endptr;
1389 char option[128];
1391 smp = strtoul(optarg, &endptr, 10);
1392 if (endptr != optarg) {
1393 if (*endptr == ',') {
1394 endptr++;
1397 if (get_param_value(option, 128, "sockets", endptr) != 0)
1398 sockets = strtoull(option, NULL, 10);
1399 if (get_param_value(option, 128, "cores", endptr) != 0)
1400 cores = strtoull(option, NULL, 10);
1401 if (get_param_value(option, 128, "threads", endptr) != 0)
1402 threads = strtoull(option, NULL, 10);
1403 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1404 max_cpus = strtoull(option, NULL, 10);
1406 /* compute missing values, prefer sockets over cores over threads */
1407 if (smp == 0 || sockets == 0) {
1408 sockets = sockets > 0 ? sockets : 1;
1409 cores = cores > 0 ? cores : 1;
1410 threads = threads > 0 ? threads : 1;
1411 if (smp == 0) {
1412 smp = cores * threads * sockets;
1414 } else {
1415 if (cores == 0) {
1416 threads = threads > 0 ? threads : 1;
1417 cores = smp / (sockets * threads);
1418 } else {
1419 if (sockets) {
1420 threads = smp / (cores * sockets);
1424 smp_cpus = smp;
1425 smp_cores = cores > 0 ? cores : 1;
1426 smp_threads = threads > 0 ? threads : 1;
1427 if (max_cpus == 0)
1428 max_cpus = smp_cpus;
1431 /***********************************************************/
1432 /* USB devices */
1434 static int usb_device_add(const char *devname, int is_hotplug)
1436 const char *p;
1437 USBDevice *dev = NULL;
1439 if (!usb_enabled)
1440 return -1;
1442 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1443 dev = usbdevice_create(devname);
1444 if (dev)
1445 goto done;
1447 /* the other ones */
1448 if (strstart(devname, "host:", &p)) {
1449 dev = usb_host_device_open(p);
1450 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1451 dev = usb_bt_init(devname[2] ? hci_init(p) :
1452 bt_new_hci(qemu_find_bt_vlan(0)));
1453 } else {
1454 return -1;
1456 if (!dev)
1457 return -1;
1459 done:
1460 return 0;
1463 static int usb_device_del(const char *devname)
1465 int bus_num, addr;
1466 const char *p;
1468 if (strstart(devname, "host:", &p))
1469 return usb_host_device_close(p);
1471 if (!usb_enabled)
1472 return -1;
1474 p = strchr(devname, '.');
1475 if (!p)
1476 return -1;
1477 bus_num = strtoul(devname, NULL, 0);
1478 addr = strtoul(p + 1, NULL, 0);
1480 return usb_device_delete_addr(bus_num, addr);
1483 static int usb_parse(const char *cmdline)
1485 int r;
1486 r = usb_device_add(cmdline, 0);
1487 if (r < 0) {
1488 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1490 return r;
1493 void do_usb_add(Monitor *mon, const QDict *qdict)
1495 const char *devname = qdict_get_str(qdict, "devname");
1496 if (usb_device_add(devname, 1) < 0) {
1497 error_report("could not add USB device '%s'", devname);
1501 void do_usb_del(Monitor *mon, const QDict *qdict)
1503 const char *devname = qdict_get_str(qdict, "devname");
1504 if (usb_device_del(devname) < 0) {
1505 error_report("could not delete USB device '%s'", devname);
1509 /***********************************************************/
1510 /* PCMCIA/Cardbus */
1512 static struct pcmcia_socket_entry_s {
1513 PCMCIASocket *socket;
1514 struct pcmcia_socket_entry_s *next;
1515 } *pcmcia_sockets = 0;
1517 void pcmcia_socket_register(PCMCIASocket *socket)
1519 struct pcmcia_socket_entry_s *entry;
1521 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1522 entry->socket = socket;
1523 entry->next = pcmcia_sockets;
1524 pcmcia_sockets = entry;
1527 void pcmcia_socket_unregister(PCMCIASocket *socket)
1529 struct pcmcia_socket_entry_s *entry, **ptr;
1531 ptr = &pcmcia_sockets;
1532 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1533 if (entry->socket == socket) {
1534 *ptr = entry->next;
1535 qemu_free(entry);
1539 void pcmcia_info(Monitor *mon)
1541 struct pcmcia_socket_entry_s *iter;
1543 if (!pcmcia_sockets)
1544 monitor_printf(mon, "No PCMCIA sockets\n");
1546 for (iter = pcmcia_sockets; iter; iter = iter->next)
1547 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1548 iter->socket->attached ? iter->socket->card_string :
1549 "Empty");
1552 /***********************************************************/
1553 /* I/O handling */
1555 typedef struct IOHandlerRecord {
1556 int fd;
1557 IOCanReadHandler *fd_read_poll;
1558 IOHandler *fd_read;
1559 IOHandler *fd_write;
1560 int deleted;
1561 void *opaque;
1562 /* temporary data */
1563 struct pollfd *ufd;
1564 QLIST_ENTRY(IOHandlerRecord) next;
1565 } IOHandlerRecord;
1567 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1568 QLIST_HEAD_INITIALIZER(io_handlers);
1571 /* XXX: fd_read_poll should be suppressed, but an API change is
1572 necessary in the character devices to suppress fd_can_read(). */
1573 int qemu_set_fd_handler2(int fd,
1574 IOCanReadHandler *fd_read_poll,
1575 IOHandler *fd_read,
1576 IOHandler *fd_write,
1577 void *opaque)
1579 IOHandlerRecord *ioh;
1581 if (!fd_read && !fd_write) {
1582 QLIST_FOREACH(ioh, &io_handlers, next) {
1583 if (ioh->fd == fd) {
1584 ioh->deleted = 1;
1585 break;
1588 } else {
1589 QLIST_FOREACH(ioh, &io_handlers, next) {
1590 if (ioh->fd == fd)
1591 goto found;
1593 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1594 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1595 found:
1596 ioh->fd = fd;
1597 ioh->fd_read_poll = fd_read_poll;
1598 ioh->fd_read = fd_read;
1599 ioh->fd_write = fd_write;
1600 ioh->opaque = opaque;
1601 ioh->deleted = 0;
1603 return 0;
1606 int qemu_set_fd_handler(int fd,
1607 IOHandler *fd_read,
1608 IOHandler *fd_write,
1609 void *opaque)
1611 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1614 #ifdef _WIN32
1615 /***********************************************************/
1616 /* Polling handling */
1618 typedef struct PollingEntry {
1619 PollingFunc *func;
1620 void *opaque;
1621 struct PollingEntry *next;
1622 } PollingEntry;
1624 static PollingEntry *first_polling_entry;
1626 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1628 PollingEntry **ppe, *pe;
1629 pe = qemu_mallocz(sizeof(PollingEntry));
1630 pe->func = func;
1631 pe->opaque = opaque;
1632 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1633 *ppe = pe;
1634 return 0;
1637 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1639 PollingEntry **ppe, *pe;
1640 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1641 pe = *ppe;
1642 if (pe->func == func && pe->opaque == opaque) {
1643 *ppe = pe->next;
1644 qemu_free(pe);
1645 break;
1650 /***********************************************************/
1651 /* Wait objects support */
1652 typedef struct WaitObjects {
1653 int num;
1654 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1655 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1656 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1657 } WaitObjects;
1659 static WaitObjects wait_objects = {0};
1661 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1663 WaitObjects *w = &wait_objects;
1665 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1666 return -1;
1667 w->events[w->num] = handle;
1668 w->func[w->num] = func;
1669 w->opaque[w->num] = opaque;
1670 w->num++;
1671 return 0;
1674 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1676 int i, found;
1677 WaitObjects *w = &wait_objects;
1679 found = 0;
1680 for (i = 0; i < w->num; i++) {
1681 if (w->events[i] == handle)
1682 found = 1;
1683 if (found) {
1684 w->events[i] = w->events[i + 1];
1685 w->func[i] = w->func[i + 1];
1686 w->opaque[i] = w->opaque[i + 1];
1689 if (found)
1690 w->num--;
1692 #endif
1694 /***********************************************************/
1695 /* ram save/restore */
1697 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
1698 #define RAM_SAVE_FLAG_COMPRESS 0x02
1699 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
1700 #define RAM_SAVE_FLAG_PAGE 0x08
1701 #define RAM_SAVE_FLAG_EOS 0x10
1703 static int is_dup_page(uint8_t *page, uint8_t ch)
1705 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1706 uint32_t *array = (uint32_t *)page;
1707 int i;
1709 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1710 if (array[i] != val)
1711 return 0;
1714 return 1;
1717 static int ram_save_block(QEMUFile *f)
1719 static ram_addr_t current_addr = 0;
1720 ram_addr_t saved_addr = current_addr;
1721 ram_addr_t addr = 0;
1722 int found = 0;
1724 while (addr < last_ram_offset) {
1725 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1726 uint8_t *p;
1728 cpu_physical_memory_reset_dirty(current_addr,
1729 current_addr + TARGET_PAGE_SIZE,
1730 MIGRATION_DIRTY_FLAG);
1732 p = qemu_get_ram_ptr(current_addr);
1734 if (is_dup_page(p, *p)) {
1735 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1736 qemu_put_byte(f, *p);
1737 } else {
1738 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1739 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1742 found = 1;
1743 break;
1745 addr += TARGET_PAGE_SIZE;
1746 current_addr = (saved_addr + addr) % last_ram_offset;
1749 return found;
1752 static uint64_t bytes_transferred;
1754 static ram_addr_t ram_save_remaining(void)
1756 ram_addr_t addr;
1757 ram_addr_t count = 0;
1759 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1760 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1761 count++;
1764 return count;
1767 uint64_t ram_bytes_remaining(void)
1769 return ram_save_remaining() * TARGET_PAGE_SIZE;
1772 uint64_t ram_bytes_transferred(void)
1774 return bytes_transferred;
1777 uint64_t ram_bytes_total(void)
1779 return last_ram_offset;
1782 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1784 ram_addr_t addr;
1785 uint64_t bytes_transferred_last;
1786 double bwidth = 0;
1787 uint64_t expected_time = 0;
1789 if (stage < 0) {
1790 cpu_physical_memory_set_dirty_tracking(0);
1791 return 0;
1794 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1795 qemu_file_set_error(f);
1796 return 0;
1799 if (stage == 1) {
1800 bytes_transferred = 0;
1802 /* Make sure all dirty bits are set */
1803 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1804 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1805 cpu_physical_memory_set_dirty(addr);
1808 /* Enable dirty memory tracking */
1809 cpu_physical_memory_set_dirty_tracking(1);
1811 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1814 bytes_transferred_last = bytes_transferred;
1815 bwidth = qemu_get_clock_ns(rt_clock);
1817 while (!qemu_file_rate_limit(f)) {
1818 int ret;
1820 ret = ram_save_block(f);
1821 bytes_transferred += ret * TARGET_PAGE_SIZE;
1822 if (ret == 0) /* no more blocks */
1823 break;
1826 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1827 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1829 /* if we haven't transferred anything this round, force expected_time to a
1830 * a very high value, but without crashing */
1831 if (bwidth == 0)
1832 bwidth = 0.000001;
1834 /* try transferring iterative blocks of memory */
1835 if (stage == 3) {
1836 /* flush all remaining blocks regardless of rate limiting */
1837 while (ram_save_block(f) != 0) {
1838 bytes_transferred += TARGET_PAGE_SIZE;
1840 cpu_physical_memory_set_dirty_tracking(0);
1843 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1845 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1847 return (stage == 2) && (expected_time <= migrate_max_downtime());
1850 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1852 ram_addr_t addr;
1853 int flags;
1855 if (version_id != 3)
1856 return -EINVAL;
1858 do {
1859 addr = qemu_get_be64(f);
1861 flags = addr & ~TARGET_PAGE_MASK;
1862 addr &= TARGET_PAGE_MASK;
1864 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1865 if (addr != last_ram_offset)
1866 return -EINVAL;
1869 if (flags & RAM_SAVE_FLAG_COMPRESS) {
1870 uint8_t ch = qemu_get_byte(f);
1871 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1872 #ifndef _WIN32
1873 if (ch == 0 &&
1874 (!kvm_enabled() || kvm_has_sync_mmu())) {
1875 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1877 #endif
1878 } else if (flags & RAM_SAVE_FLAG_PAGE) {
1879 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1881 if (qemu_file_has_error(f)) {
1882 return -EIO;
1884 } while (!(flags & RAM_SAVE_FLAG_EOS));
1886 return 0;
1889 void qemu_service_io(void)
1891 qemu_notify_event();
1894 /***********************************************************/
1895 /* machine registration */
1897 static QEMUMachine *first_machine = NULL;
1898 QEMUMachine *current_machine = NULL;
1900 int qemu_register_machine(QEMUMachine *m)
1902 QEMUMachine **pm;
1903 pm = &first_machine;
1904 while (*pm != NULL)
1905 pm = &(*pm)->next;
1906 m->next = NULL;
1907 *pm = m;
1908 return 0;
1911 static QEMUMachine *find_machine(const char *name)
1913 QEMUMachine *m;
1915 for(m = first_machine; m != NULL; m = m->next) {
1916 if (!strcmp(m->name, name))
1917 return m;
1918 if (m->alias && !strcmp(m->alias, name))
1919 return m;
1921 return NULL;
1924 static QEMUMachine *find_default_machine(void)
1926 QEMUMachine *m;
1928 for(m = first_machine; m != NULL; m = m->next) {
1929 if (m->is_default) {
1930 return m;
1933 return NULL;
1936 /***********************************************************/
1937 /* main execution loop */
1939 static void gui_update(void *opaque)
1941 uint64_t interval = GUI_REFRESH_INTERVAL;
1942 DisplayState *ds = opaque;
1943 DisplayChangeListener *dcl = ds->listeners;
1945 qemu_flush_coalesced_mmio_buffer();
1946 dpy_refresh(ds);
1948 while (dcl != NULL) {
1949 if (dcl->gui_timer_interval &&
1950 dcl->gui_timer_interval < interval)
1951 interval = dcl->gui_timer_interval;
1952 dcl = dcl->next;
1954 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1957 static void nographic_update(void *opaque)
1959 uint64_t interval = GUI_REFRESH_INTERVAL;
1961 qemu_flush_coalesced_mmio_buffer();
1962 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1965 void cpu_synchronize_all_states(void)
1967 CPUState *cpu;
1969 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1970 cpu_synchronize_state(cpu);
1974 void cpu_synchronize_all_post_reset(void)
1976 CPUState *cpu;
1978 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1979 cpu_synchronize_post_reset(cpu);
1983 void cpu_synchronize_all_post_init(void)
1985 CPUState *cpu;
1987 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1988 cpu_synchronize_post_init(cpu);
1992 struct vm_change_state_entry {
1993 VMChangeStateHandler *cb;
1994 void *opaque;
1995 QLIST_ENTRY (vm_change_state_entry) entries;
1998 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
2000 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
2001 void *opaque)
2003 VMChangeStateEntry *e;
2005 e = qemu_mallocz(sizeof (*e));
2007 e->cb = cb;
2008 e->opaque = opaque;
2009 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
2010 return e;
2013 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
2015 QLIST_REMOVE (e, entries);
2016 qemu_free (e);
2019 static void vm_state_notify(int running, int reason)
2021 VMChangeStateEntry *e;
2023 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
2024 e->cb(e->opaque, running, reason);
2028 static void resume_all_vcpus(void);
2029 static void pause_all_vcpus(void);
2031 void vm_start(void)
2033 if (!vm_running) {
2034 cpu_enable_ticks();
2035 vm_running = 1;
2036 vm_state_notify(1, 0);
2037 resume_all_vcpus();
2041 /* reset/shutdown handler */
2043 typedef struct QEMUResetEntry {
2044 QTAILQ_ENTRY(QEMUResetEntry) entry;
2045 QEMUResetHandler *func;
2046 void *opaque;
2047 } QEMUResetEntry;
2049 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
2050 QTAILQ_HEAD_INITIALIZER(reset_handlers);
2051 static int reset_requested;
2052 static int shutdown_requested;
2053 static int powerdown_requested;
2054 static int debug_requested;
2055 static int vmstop_requested;
2057 int qemu_shutdown_requested(void)
2059 int r = shutdown_requested;
2060 shutdown_requested = 0;
2061 return r;
2064 int qemu_reset_requested(void)
2066 int r = reset_requested;
2067 reset_requested = 0;
2068 return r;
2071 int qemu_powerdown_requested(void)
2073 int r = powerdown_requested;
2074 powerdown_requested = 0;
2075 return r;
2078 static int qemu_debug_requested(void)
2080 int r = debug_requested;
2081 debug_requested = 0;
2082 return r;
2085 static int qemu_vmstop_requested(void)
2087 int r = vmstop_requested;
2088 vmstop_requested = 0;
2089 return r;
2092 static void do_vm_stop(int reason)
2094 if (vm_running) {
2095 cpu_disable_ticks();
2096 vm_running = 0;
2097 pause_all_vcpus();
2098 vm_state_notify(0, reason);
2099 monitor_protocol_event(QEVENT_STOP, NULL);
2103 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2105 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2107 re->func = func;
2108 re->opaque = opaque;
2109 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2112 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2114 QEMUResetEntry *re;
2116 QTAILQ_FOREACH(re, &reset_handlers, entry) {
2117 if (re->func == func && re->opaque == opaque) {
2118 QTAILQ_REMOVE(&reset_handlers, re, entry);
2119 qemu_free(re);
2120 return;
2125 void qemu_system_reset(void)
2127 QEMUResetEntry *re, *nre;
2129 /* reset all devices */
2130 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2131 re->func(re->opaque);
2133 monitor_protocol_event(QEVENT_RESET, NULL);
2134 cpu_synchronize_all_post_reset();
2137 void qemu_system_reset_request(void)
2139 if (no_reboot) {
2140 shutdown_requested = 1;
2141 } else {
2142 reset_requested = 1;
2144 qemu_notify_event();
2147 void qemu_system_shutdown_request(void)
2149 shutdown_requested = 1;
2150 qemu_notify_event();
2153 void qemu_system_powerdown_request(void)
2155 powerdown_requested = 1;
2156 qemu_notify_event();
2159 static int cpu_can_run(CPUState *env)
2161 if (env->stop)
2162 return 0;
2163 if (env->stopped)
2164 return 0;
2165 if (!vm_running)
2166 return 0;
2167 return 1;
2170 static int cpu_has_work(CPUState *env)
2172 if (env->stop)
2173 return 1;
2174 if (env->stopped)
2175 return 0;
2176 if (!env->halted)
2177 return 1;
2178 if (qemu_cpu_has_work(env))
2179 return 1;
2180 return 0;
2183 static int tcg_has_work(void)
2185 CPUState *env;
2187 for (env = first_cpu; env != NULL; env = env->next_cpu)
2188 if (cpu_has_work(env))
2189 return 1;
2190 return 0;
2193 #ifndef _WIN32
2194 static int io_thread_fd = -1;
2196 static void qemu_event_increment(void)
2198 /* Write 8 bytes to be compatible with eventfd. */
2199 static uint64_t val = 1;
2200 ssize_t ret;
2202 if (io_thread_fd == -1)
2203 return;
2205 do {
2206 ret = write(io_thread_fd, &val, sizeof(val));
2207 } while (ret < 0 && errno == EINTR);
2209 /* EAGAIN is fine, a read must be pending. */
2210 if (ret < 0 && errno != EAGAIN) {
2211 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
2212 strerror(errno));
2213 exit (1);
2217 static void qemu_event_read(void *opaque)
2219 int fd = (unsigned long)opaque;
2220 ssize_t len;
2221 char buffer[512];
2223 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
2224 do {
2225 len = read(fd, buffer, sizeof(buffer));
2226 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
2229 static int qemu_event_init(void)
2231 int err;
2232 int fds[2];
2234 err = qemu_eventfd(fds);
2235 if (err == -1)
2236 return -errno;
2238 err = fcntl_setfl(fds[0], O_NONBLOCK);
2239 if (err < 0)
2240 goto fail;
2242 err = fcntl_setfl(fds[1], O_NONBLOCK);
2243 if (err < 0)
2244 goto fail;
2246 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
2247 (void *)(unsigned long)fds[0]);
2249 io_thread_fd = fds[1];
2250 return 0;
2252 fail:
2253 close(fds[0]);
2254 close(fds[1]);
2255 return err;
2257 #else
2258 HANDLE qemu_event_handle;
2260 static void dummy_event_handler(void *opaque)
2264 static int qemu_event_init(void)
2266 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
2267 if (!qemu_event_handle) {
2268 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
2269 return -1;
2271 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
2272 return 0;
2275 static void qemu_event_increment(void)
2277 if (!SetEvent(qemu_event_handle)) {
2278 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
2279 GetLastError());
2280 exit (1);
2283 #endif
2285 #ifndef CONFIG_IOTHREAD
2286 static int qemu_init_main_loop(void)
2288 return qemu_event_init();
2291 void qemu_init_vcpu(void *_env)
2293 CPUState *env = _env;
2295 env->nr_cores = smp_cores;
2296 env->nr_threads = smp_threads;
2297 if (kvm_enabled())
2298 kvm_init_vcpu(env);
2299 return;
2302 int qemu_cpu_self(void *env)
2304 return 1;
2307 static void resume_all_vcpus(void)
2311 static void pause_all_vcpus(void)
2315 void qemu_cpu_kick(void *env)
2317 return;
2320 void qemu_notify_event(void)
2322 CPUState *env = cpu_single_env;
2324 qemu_event_increment ();
2325 if (env) {
2326 cpu_exit(env);
2328 if (next_cpu && env != next_cpu) {
2329 cpu_exit(next_cpu);
2333 void qemu_mutex_lock_iothread(void) {}
2334 void qemu_mutex_unlock_iothread(void) {}
2336 void vm_stop(int reason)
2338 do_vm_stop(reason);
2341 #else /* CONFIG_IOTHREAD */
2343 #include "qemu-thread.h"
2345 QemuMutex qemu_global_mutex;
2346 static QemuMutex qemu_fair_mutex;
2348 static QemuThread io_thread;
2350 static QemuThread *tcg_cpu_thread;
2351 static QemuCond *tcg_halt_cond;
2353 static int qemu_system_ready;
2354 /* cpu creation */
2355 static QemuCond qemu_cpu_cond;
2356 /* system init */
2357 static QemuCond qemu_system_cond;
2358 static QemuCond qemu_pause_cond;
2360 static void tcg_block_io_signals(void);
2361 static void kvm_block_io_signals(CPUState *env);
2362 static void unblock_io_signals(void);
2364 static int qemu_init_main_loop(void)
2366 int ret;
2368 ret = qemu_event_init();
2369 if (ret)
2370 return ret;
2372 qemu_cond_init(&qemu_pause_cond);
2373 qemu_mutex_init(&qemu_fair_mutex);
2374 qemu_mutex_init(&qemu_global_mutex);
2375 qemu_mutex_lock(&qemu_global_mutex);
2377 unblock_io_signals();
2378 qemu_thread_self(&io_thread);
2380 return 0;
2383 static void qemu_wait_io_event_common(CPUState *env)
2385 if (env->stop) {
2386 env->stop = 0;
2387 env->stopped = 1;
2388 qemu_cond_signal(&qemu_pause_cond);
2392 static void qemu_wait_io_event(CPUState *env)
2394 while (!tcg_has_work())
2395 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2397 qemu_mutex_unlock(&qemu_global_mutex);
2400 * Users of qemu_global_mutex can be starved, having no chance
2401 * to acquire it since this path will get to it first.
2402 * So use another lock to provide fairness.
2404 qemu_mutex_lock(&qemu_fair_mutex);
2405 qemu_mutex_unlock(&qemu_fair_mutex);
2407 qemu_mutex_lock(&qemu_global_mutex);
2408 qemu_wait_io_event_common(env);
2411 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
2413 struct timespec ts;
2414 int r, e;
2415 siginfo_t siginfo;
2416 sigset_t waitset;
2418 ts.tv_sec = timeout / 1000;
2419 ts.tv_nsec = (timeout % 1000) * 1000000;
2421 sigemptyset(&waitset);
2422 sigaddset(&waitset, SIG_IPI);
2424 qemu_mutex_unlock(&qemu_global_mutex);
2425 r = sigtimedwait(&waitset, &siginfo, &ts);
2426 e = errno;
2427 qemu_mutex_lock(&qemu_global_mutex);
2429 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
2430 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
2431 exit(1);
2435 static void qemu_kvm_wait_io_event(CPUState *env)
2437 while (!cpu_has_work(env))
2438 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2440 qemu_kvm_eat_signal(env, 0);
2441 qemu_wait_io_event_common(env);
2444 static int qemu_cpu_exec(CPUState *env);
2446 static void *kvm_cpu_thread_fn(void *arg)
2448 CPUState *env = arg;
2450 qemu_thread_self(env->thread);
2451 if (kvm_enabled())
2452 kvm_init_vcpu(env);
2454 kvm_block_io_signals(env);
2456 /* signal CPU creation */
2457 qemu_mutex_lock(&qemu_global_mutex);
2458 env->created = 1;
2459 qemu_cond_signal(&qemu_cpu_cond);
2461 /* and wait for machine initialization */
2462 while (!qemu_system_ready)
2463 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2465 while (1) {
2466 if (cpu_can_run(env))
2467 qemu_cpu_exec(env);
2468 qemu_kvm_wait_io_event(env);
2471 return NULL;
2474 static bool tcg_cpu_exec(void);
2476 static void *tcg_cpu_thread_fn(void *arg)
2478 CPUState *env = arg;
2480 tcg_block_io_signals();
2481 qemu_thread_self(env->thread);
2483 /* signal CPU creation */
2484 qemu_mutex_lock(&qemu_global_mutex);
2485 for (env = first_cpu; env != NULL; env = env->next_cpu)
2486 env->created = 1;
2487 qemu_cond_signal(&qemu_cpu_cond);
2489 /* and wait for machine initialization */
2490 while (!qemu_system_ready)
2491 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2493 while (1) {
2494 tcg_cpu_exec();
2495 qemu_wait_io_event(cur_cpu);
2498 return NULL;
2501 void qemu_cpu_kick(void *_env)
2503 CPUState *env = _env;
2504 qemu_cond_broadcast(env->halt_cond);
2505 if (kvm_enabled())
2506 qemu_thread_signal(env->thread, SIG_IPI);
2509 int qemu_cpu_self(void *_env)
2511 CPUState *env = _env;
2512 QemuThread this;
2514 qemu_thread_self(&this);
2516 return qemu_thread_equal(&this, env->thread);
2519 static void cpu_signal(int sig)
2521 if (cpu_single_env)
2522 cpu_exit(cpu_single_env);
2525 static void tcg_block_io_signals(void)
2527 sigset_t set;
2528 struct sigaction sigact;
2530 sigemptyset(&set);
2531 sigaddset(&set, SIGUSR2);
2532 sigaddset(&set, SIGIO);
2533 sigaddset(&set, SIGALRM);
2534 sigaddset(&set, SIGCHLD);
2535 pthread_sigmask(SIG_BLOCK, &set, NULL);
2537 sigemptyset(&set);
2538 sigaddset(&set, SIG_IPI);
2539 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2541 memset(&sigact, 0, sizeof(sigact));
2542 sigact.sa_handler = cpu_signal;
2543 sigaction(SIG_IPI, &sigact, NULL);
2546 static void dummy_signal(int sig)
2550 static void kvm_block_io_signals(CPUState *env)
2552 int r;
2553 sigset_t set;
2554 struct sigaction sigact;
2556 sigemptyset(&set);
2557 sigaddset(&set, SIGUSR2);
2558 sigaddset(&set, SIGIO);
2559 sigaddset(&set, SIGALRM);
2560 sigaddset(&set, SIGCHLD);
2561 sigaddset(&set, SIG_IPI);
2562 pthread_sigmask(SIG_BLOCK, &set, NULL);
2564 pthread_sigmask(SIG_BLOCK, NULL, &set);
2565 sigdelset(&set, SIG_IPI);
2567 memset(&sigact, 0, sizeof(sigact));
2568 sigact.sa_handler = dummy_signal;
2569 sigaction(SIG_IPI, &sigact, NULL);
2571 r = kvm_set_signal_mask(env, &set);
2572 if (r) {
2573 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
2574 exit(1);
2578 static void unblock_io_signals(void)
2580 sigset_t set;
2582 sigemptyset(&set);
2583 sigaddset(&set, SIGUSR2);
2584 sigaddset(&set, SIGIO);
2585 sigaddset(&set, SIGALRM);
2586 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2588 sigemptyset(&set);
2589 sigaddset(&set, SIG_IPI);
2590 pthread_sigmask(SIG_BLOCK, &set, NULL);
2593 static void qemu_signal_lock(unsigned int msecs)
2595 qemu_mutex_lock(&qemu_fair_mutex);
2597 while (qemu_mutex_trylock(&qemu_global_mutex)) {
2598 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
2599 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
2600 break;
2602 qemu_mutex_unlock(&qemu_fair_mutex);
2605 void qemu_mutex_lock_iothread(void)
2607 if (kvm_enabled()) {
2608 qemu_mutex_lock(&qemu_fair_mutex);
2609 qemu_mutex_lock(&qemu_global_mutex);
2610 qemu_mutex_unlock(&qemu_fair_mutex);
2611 } else
2612 qemu_signal_lock(100);
2615 void qemu_mutex_unlock_iothread(void)
2617 qemu_mutex_unlock(&qemu_global_mutex);
2620 static int all_vcpus_paused(void)
2622 CPUState *penv = first_cpu;
2624 while (penv) {
2625 if (!penv->stopped)
2626 return 0;
2627 penv = (CPUState *)penv->next_cpu;
2630 return 1;
2633 static void pause_all_vcpus(void)
2635 CPUState *penv = first_cpu;
2637 while (penv) {
2638 penv->stop = 1;
2639 qemu_thread_signal(penv->thread, SIG_IPI);
2640 qemu_cpu_kick(penv);
2641 penv = (CPUState *)penv->next_cpu;
2644 while (!all_vcpus_paused()) {
2645 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
2646 penv = first_cpu;
2647 while (penv) {
2648 qemu_thread_signal(penv->thread, SIG_IPI);
2649 penv = (CPUState *)penv->next_cpu;
2654 static void resume_all_vcpus(void)
2656 CPUState *penv = first_cpu;
2658 while (penv) {
2659 penv->stop = 0;
2660 penv->stopped = 0;
2661 qemu_thread_signal(penv->thread, SIG_IPI);
2662 qemu_cpu_kick(penv);
2663 penv = (CPUState *)penv->next_cpu;
2667 static void tcg_init_vcpu(void *_env)
2669 CPUState *env = _env;
2670 /* share a single thread for all cpus with TCG */
2671 if (!tcg_cpu_thread) {
2672 env->thread = qemu_mallocz(sizeof(QemuThread));
2673 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2674 qemu_cond_init(env->halt_cond);
2675 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
2676 while (env->created == 0)
2677 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2678 tcg_cpu_thread = env->thread;
2679 tcg_halt_cond = env->halt_cond;
2680 } else {
2681 env->thread = tcg_cpu_thread;
2682 env->halt_cond = tcg_halt_cond;
2686 static void kvm_start_vcpu(CPUState *env)
2688 env->thread = qemu_mallocz(sizeof(QemuThread));
2689 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2690 qemu_cond_init(env->halt_cond);
2691 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
2692 while (env->created == 0)
2693 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2696 void qemu_init_vcpu(void *_env)
2698 CPUState *env = _env;
2700 env->nr_cores = smp_cores;
2701 env->nr_threads = smp_threads;
2702 if (kvm_enabled())
2703 kvm_start_vcpu(env);
2704 else
2705 tcg_init_vcpu(env);
2708 void qemu_notify_event(void)
2710 qemu_event_increment();
2713 static void qemu_system_vmstop_request(int reason)
2715 vmstop_requested = reason;
2716 qemu_notify_event();
2719 void vm_stop(int reason)
2721 QemuThread me;
2722 qemu_thread_self(&me);
2724 if (!qemu_thread_equal(&me, &io_thread)) {
2725 qemu_system_vmstop_request(reason);
2727 * FIXME: should not return to device code in case
2728 * vm_stop() has been requested.
2730 if (cpu_single_env) {
2731 cpu_exit(cpu_single_env);
2732 cpu_single_env->stop = 1;
2734 return;
2736 do_vm_stop(reason);
2739 #endif
2742 #ifdef _WIN32
2743 static void host_main_loop_wait(int *timeout)
2745 int ret, ret2, i;
2746 PollingEntry *pe;
2749 /* XXX: need to suppress polling by better using win32 events */
2750 ret = 0;
2751 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2752 ret |= pe->func(pe->opaque);
2754 if (ret == 0) {
2755 int err;
2756 WaitObjects *w = &wait_objects;
2758 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2759 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2760 if (w->func[ret - WAIT_OBJECT_0])
2761 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2763 /* Check for additional signaled events */
2764 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2766 /* Check if event is signaled */
2767 ret2 = WaitForSingleObject(w->events[i], 0);
2768 if(ret2 == WAIT_OBJECT_0) {
2769 if (w->func[i])
2770 w->func[i](w->opaque[i]);
2771 } else if (ret2 == WAIT_TIMEOUT) {
2772 } else {
2773 err = GetLastError();
2774 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2777 } else if (ret == WAIT_TIMEOUT) {
2778 } else {
2779 err = GetLastError();
2780 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2784 *timeout = 0;
2786 #else
2787 static void host_main_loop_wait(int *timeout)
2790 #endif
2792 void main_loop_wait(int nonblocking)
2794 IOHandlerRecord *ioh;
2795 fd_set rfds, wfds, xfds;
2796 int ret, nfds;
2797 struct timeval tv;
2798 int timeout;
2800 if (nonblocking)
2801 timeout = 0;
2802 else {
2803 timeout = qemu_calculate_timeout();
2804 qemu_bh_update_timeout(&timeout);
2807 host_main_loop_wait(&timeout);
2809 /* poll any events */
2810 /* XXX: separate device handlers from system ones */
2811 nfds = -1;
2812 FD_ZERO(&rfds);
2813 FD_ZERO(&wfds);
2814 FD_ZERO(&xfds);
2815 QLIST_FOREACH(ioh, &io_handlers, next) {
2816 if (ioh->deleted)
2817 continue;
2818 if (ioh->fd_read &&
2819 (!ioh->fd_read_poll ||
2820 ioh->fd_read_poll(ioh->opaque) != 0)) {
2821 FD_SET(ioh->fd, &rfds);
2822 if (ioh->fd > nfds)
2823 nfds = ioh->fd;
2825 if (ioh->fd_write) {
2826 FD_SET(ioh->fd, &wfds);
2827 if (ioh->fd > nfds)
2828 nfds = ioh->fd;
2832 tv.tv_sec = timeout / 1000;
2833 tv.tv_usec = (timeout % 1000) * 1000;
2835 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2837 qemu_mutex_unlock_iothread();
2838 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2839 qemu_mutex_lock_iothread();
2840 if (ret > 0) {
2841 IOHandlerRecord *pioh;
2843 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
2844 if (ioh->deleted) {
2845 QLIST_REMOVE(ioh, next);
2846 qemu_free(ioh);
2847 continue;
2849 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2850 ioh->fd_read(ioh->opaque);
2852 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2853 ioh->fd_write(ioh->opaque);
2858 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2860 qemu_run_all_timers();
2862 /* Check bottom-halves last in case any of the earlier events triggered
2863 them. */
2864 qemu_bh_poll();
2868 static int qemu_cpu_exec(CPUState *env)
2870 int ret;
2871 #ifdef CONFIG_PROFILER
2872 int64_t ti;
2873 #endif
2875 #ifdef CONFIG_PROFILER
2876 ti = profile_getclock();
2877 #endif
2878 if (use_icount) {
2879 int64_t count;
2880 int decr;
2881 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
2882 env->icount_decr.u16.low = 0;
2883 env->icount_extra = 0;
2884 count = qemu_icount_round (qemu_next_deadline());
2885 qemu_icount += count;
2886 decr = (count > 0xffff) ? 0xffff : count;
2887 count -= decr;
2888 env->icount_decr.u16.low = decr;
2889 env->icount_extra = count;
2891 ret = cpu_exec(env);
2892 #ifdef CONFIG_PROFILER
2893 qemu_time += profile_getclock() - ti;
2894 #endif
2895 if (use_icount) {
2896 /* Fold pending instructions back into the
2897 instruction counter, and clear the interrupt flag. */
2898 qemu_icount -= (env->icount_decr.u16.low
2899 + env->icount_extra);
2900 env->icount_decr.u32 = 0;
2901 env->icount_extra = 0;
2903 return ret;
2906 static bool tcg_cpu_exec(void)
2908 int ret = 0;
2910 if (next_cpu == NULL)
2911 next_cpu = first_cpu;
2912 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
2913 CPUState *env = cur_cpu = next_cpu;
2915 qemu_clock_enable(vm_clock,
2916 (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
2918 if (qemu_alarm_pending())
2919 break;
2920 if (cpu_can_run(env))
2921 ret = qemu_cpu_exec(env);
2922 else if (env->stop)
2923 break;
2925 if (ret == EXCP_DEBUG) {
2926 gdb_set_stop_cpu(env);
2927 debug_requested = 1;
2928 break;
2931 return tcg_has_work();
2934 static int vm_can_run(void)
2936 if (powerdown_requested)
2937 return 0;
2938 if (reset_requested)
2939 return 0;
2940 if (shutdown_requested)
2941 return 0;
2942 if (debug_requested)
2943 return 0;
2944 return 1;
2947 qemu_irq qemu_system_powerdown;
2949 static void main_loop(void)
2951 int r;
2953 #ifdef CONFIG_IOTHREAD
2954 qemu_system_ready = 1;
2955 qemu_cond_broadcast(&qemu_system_cond);
2956 #endif
2958 for (;;) {
2959 do {
2960 bool nonblocking = false;
2961 #ifdef CONFIG_PROFILER
2962 int64_t ti;
2963 #endif
2964 #ifndef CONFIG_IOTHREAD
2965 nonblocking = tcg_cpu_exec();
2966 #endif
2967 #ifdef CONFIG_PROFILER
2968 ti = profile_getclock();
2969 #endif
2970 main_loop_wait(nonblocking);
2971 #ifdef CONFIG_PROFILER
2972 dev_time += profile_getclock() - ti;
2973 #endif
2974 } while (vm_can_run());
2976 if (qemu_debug_requested()) {
2977 vm_stop(EXCP_DEBUG);
2979 if (qemu_shutdown_requested()) {
2980 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2981 if (no_shutdown) {
2982 vm_stop(0);
2983 no_shutdown = 0;
2984 } else
2985 break;
2987 if (qemu_reset_requested()) {
2988 pause_all_vcpus();
2989 qemu_system_reset();
2990 resume_all_vcpus();
2992 if (qemu_powerdown_requested()) {
2993 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
2994 qemu_irq_raise(qemu_system_powerdown);
2996 if ((r = qemu_vmstop_requested())) {
2997 vm_stop(r);
3000 pause_all_vcpus();
3003 static void version(void)
3005 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3008 static void help(int exitcode)
3010 const char *options_help =
3011 #define DEF(option, opt_arg, opt_enum, opt_help) \
3012 opt_help
3013 #define DEFHEADING(text) stringify(text) "\n"
3014 #include "qemu-options.h"
3015 #undef DEF
3016 #undef DEFHEADING
3017 #undef GEN_DOCS
3019 version();
3020 printf("usage: %s [options] [disk_image]\n"
3021 "\n"
3022 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3023 "\n"
3024 "%s\n"
3025 "During emulation, the following keys are useful:\n"
3026 "ctrl-alt-f toggle full screen\n"
3027 "ctrl-alt-n switch to virtual console 'n'\n"
3028 "ctrl-alt toggle mouse and keyboard grab\n"
3029 "\n"
3030 "When using -nographic, press 'ctrl-a h' to get some help.\n",
3031 "qemu",
3032 options_help);
3033 exit(exitcode);
3036 #define HAS_ARG 0x0001
3038 enum {
3039 #define DEF(option, opt_arg, opt_enum, opt_help) \
3040 opt_enum,
3041 #define DEFHEADING(text)
3042 #include "qemu-options.h"
3043 #undef DEF
3044 #undef DEFHEADING
3045 #undef GEN_DOCS
3048 typedef struct QEMUOption {
3049 const char *name;
3050 int flags;
3051 int index;
3052 } QEMUOption;
3054 static const QEMUOption qemu_options[] = {
3055 { "h", 0, QEMU_OPTION_h },
3056 #define DEF(option, opt_arg, opt_enum, opt_help) \
3057 { option, opt_arg, opt_enum },
3058 #define DEFHEADING(text)
3059 #include "qemu-options.h"
3060 #undef DEF
3061 #undef DEFHEADING
3062 #undef GEN_DOCS
3063 { NULL },
3066 #ifdef HAS_AUDIO
3067 struct soundhw soundhw[] = {
3068 #ifdef HAS_AUDIO_CHOICE
3069 #if defined(TARGET_I386) || defined(TARGET_MIPS)
3071 "pcspk",
3072 "PC speaker",
3075 { .init_isa = pcspk_audio_init }
3077 #endif
3079 #ifdef CONFIG_SB16
3081 "sb16",
3082 "Creative Sound Blaster 16",
3085 { .init_isa = SB16_init }
3087 #endif
3089 #ifdef CONFIG_CS4231A
3091 "cs4231a",
3092 "CS4231A",
3095 { .init_isa = cs4231a_init }
3097 #endif
3099 #ifdef CONFIG_ADLIB
3101 "adlib",
3102 #ifdef HAS_YMF262
3103 "Yamaha YMF262 (OPL3)",
3104 #else
3105 "Yamaha YM3812 (OPL2)",
3106 #endif
3109 { .init_isa = Adlib_init }
3111 #endif
3113 #ifdef CONFIG_GUS
3115 "gus",
3116 "Gravis Ultrasound GF1",
3119 { .init_isa = GUS_init }
3121 #endif
3123 #ifdef CONFIG_AC97
3125 "ac97",
3126 "Intel 82801AA AC97 Audio",
3129 { .init_pci = ac97_init }
3131 #endif
3133 #ifdef CONFIG_ES1370
3135 "es1370",
3136 "ENSONIQ AudioPCI ES1370",
3139 { .init_pci = es1370_init }
3141 #endif
3143 #endif /* HAS_AUDIO_CHOICE */
3145 { NULL, NULL, 0, 0, { NULL } }
3148 static void select_soundhw (const char *optarg)
3150 struct soundhw *c;
3152 if (*optarg == '?') {
3153 show_valid_cards:
3155 printf ("Valid sound card names (comma separated):\n");
3156 for (c = soundhw; c->name; ++c) {
3157 printf ("%-11s %s\n", c->name, c->descr);
3159 printf ("\n-soundhw all will enable all of the above\n");
3160 exit (*optarg != '?');
3162 else {
3163 size_t l;
3164 const char *p;
3165 char *e;
3166 int bad_card = 0;
3168 if (!strcmp (optarg, "all")) {
3169 for (c = soundhw; c->name; ++c) {
3170 c->enabled = 1;
3172 return;
3175 p = optarg;
3176 while (*p) {
3177 e = strchr (p, ',');
3178 l = !e ? strlen (p) : (size_t) (e - p);
3180 for (c = soundhw; c->name; ++c) {
3181 if (!strncmp (c->name, p, l) && !c->name[l]) {
3182 c->enabled = 1;
3183 break;
3187 if (!c->name) {
3188 if (l > 80) {
3189 fprintf (stderr,
3190 "Unknown sound card name (too big to show)\n");
3192 else {
3193 fprintf (stderr, "Unknown sound card name `%.*s'\n",
3194 (int) l, p);
3196 bad_card = 1;
3198 p += l + (e != NULL);
3201 if (bad_card)
3202 goto show_valid_cards;
3205 #endif
3207 static void select_vgahw (const char *p)
3209 const char *opts;
3211 default_vga = 0;
3212 vga_interface_type = VGA_NONE;
3213 if (strstart(p, "std", &opts)) {
3214 vga_interface_type = VGA_STD;
3215 } else if (strstart(p, "cirrus", &opts)) {
3216 vga_interface_type = VGA_CIRRUS;
3217 } else if (strstart(p, "vmware", &opts)) {
3218 vga_interface_type = VGA_VMWARE;
3219 } else if (strstart(p, "xenfb", &opts)) {
3220 vga_interface_type = VGA_XENFB;
3221 } else if (!strstart(p, "none", &opts)) {
3222 invalid_vga:
3223 fprintf(stderr, "Unknown vga type: %s\n", p);
3224 exit(1);
3226 while (*opts) {
3227 const char *nextopt;
3229 if (strstart(opts, ",retrace=", &nextopt)) {
3230 opts = nextopt;
3231 if (strstart(opts, "dumb", &nextopt))
3232 vga_retrace_method = VGA_RETRACE_DUMB;
3233 else if (strstart(opts, "precise", &nextopt))
3234 vga_retrace_method = VGA_RETRACE_PRECISE;
3235 else goto invalid_vga;
3236 } else goto invalid_vga;
3237 opts = nextopt;
3241 #ifdef TARGET_I386
3242 static int balloon_parse(const char *arg)
3244 QemuOpts *opts;
3246 if (strcmp(arg, "none") == 0) {
3247 return 0;
3250 if (!strncmp(arg, "virtio", 6)) {
3251 if (arg[6] == ',') {
3252 /* have params -> parse them */
3253 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
3254 if (!opts)
3255 return -1;
3256 } else {
3257 /* create empty opts */
3258 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3260 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
3261 return 0;
3264 return -1;
3266 #endif
3268 #ifdef _WIN32
3269 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
3271 exit(STATUS_CONTROL_C_EXIT);
3272 return TRUE;
3274 #endif
3276 int qemu_uuid_parse(const char *str, uint8_t *uuid)
3278 int ret;
3280 if(strlen(str) != 36)
3281 return -1;
3283 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
3284 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
3285 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
3287 if(ret != 16)
3288 return -1;
3290 #ifdef TARGET_I386
3291 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
3292 #endif
3294 return 0;
3297 #ifndef _WIN32
3299 static void termsig_handler(int signal)
3301 qemu_system_shutdown_request();
3304 static void sigchld_handler(int signal)
3306 waitpid(-1, NULL, WNOHANG);
3309 static void sighandler_setup(void)
3311 struct sigaction act;
3313 memset(&act, 0, sizeof(act));
3314 act.sa_handler = termsig_handler;
3315 sigaction(SIGINT, &act, NULL);
3316 sigaction(SIGHUP, &act, NULL);
3317 sigaction(SIGTERM, &act, NULL);
3319 act.sa_handler = sigchld_handler;
3320 act.sa_flags = SA_NOCLDSTOP;
3321 sigaction(SIGCHLD, &act, NULL);
3324 #endif
3326 #ifdef _WIN32
3327 /* Look for support files in the same directory as the executable. */
3328 static char *find_datadir(const char *argv0)
3330 char *p;
3331 char buf[MAX_PATH];
3332 DWORD len;
3334 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
3335 if (len == 0) {
3336 return NULL;
3339 buf[len] = 0;
3340 p = buf + len - 1;
3341 while (p != buf && *p != '\\')
3342 p--;
3343 *p = 0;
3344 if (access(buf, R_OK) == 0) {
3345 return qemu_strdup(buf);
3347 return NULL;
3349 #else /* !_WIN32 */
3351 /* Find a likely location for support files using the location of the binary.
3352 For installed binaries this will be "$bindir/../share/qemu". When
3353 running from the build tree this will be "$bindir/../pc-bios". */
3354 #define SHARE_SUFFIX "/share/qemu"
3355 #define BUILD_SUFFIX "/pc-bios"
3356 static char *find_datadir(const char *argv0)
3358 char *dir;
3359 char *p = NULL;
3360 char *res;
3361 char buf[PATH_MAX];
3362 size_t max_len;
3364 #if defined(__linux__)
3366 int len;
3367 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
3368 if (len > 0) {
3369 buf[len] = 0;
3370 p = buf;
3373 #elif defined(__FreeBSD__)
3375 int len;
3376 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
3377 if (len > 0) {
3378 buf[len] = 0;
3379 p = buf;
3382 #endif
3383 /* If we don't have any way of figuring out the actual executable
3384 location then try argv[0]. */
3385 if (!p) {
3386 p = realpath(argv0, buf);
3387 if (!p) {
3388 return NULL;
3391 dir = dirname(p);
3392 dir = dirname(dir);
3394 max_len = strlen(dir) +
3395 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
3396 res = qemu_mallocz(max_len);
3397 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
3398 if (access(res, R_OK)) {
3399 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
3400 if (access(res, R_OK)) {
3401 qemu_free(res);
3402 res = NULL;
3406 return res;
3408 #undef SHARE_SUFFIX
3409 #undef BUILD_SUFFIX
3410 #endif
3412 char *qemu_find_file(int type, const char *name)
3414 int len;
3415 const char *subdir;
3416 char *buf;
3418 /* If name contains path separators then try it as a straight path. */
3419 if ((strchr(name, '/') || strchr(name, '\\'))
3420 && access(name, R_OK) == 0) {
3421 return qemu_strdup(name);
3423 switch (type) {
3424 case QEMU_FILE_TYPE_BIOS:
3425 subdir = "";
3426 break;
3427 case QEMU_FILE_TYPE_KEYMAP:
3428 subdir = "keymaps/";
3429 break;
3430 default:
3431 abort();
3433 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
3434 buf = qemu_mallocz(len);
3435 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
3436 if (access(buf, R_OK)) {
3437 qemu_free(buf);
3438 return NULL;
3440 return buf;
3443 static int device_help_func(QemuOpts *opts, void *opaque)
3445 return qdev_device_help(opts);
3448 static int device_init_func(QemuOpts *opts, void *opaque)
3450 DeviceState *dev;
3452 dev = qdev_device_add(opts);
3453 if (!dev)
3454 return -1;
3455 return 0;
3458 static int chardev_init_func(QemuOpts *opts, void *opaque)
3460 CharDriverState *chr;
3462 chr = qemu_chr_open_opts(opts, NULL);
3463 if (!chr)
3464 return -1;
3465 return 0;
3468 static int mon_init_func(QemuOpts *opts, void *opaque)
3470 CharDriverState *chr;
3471 const char *chardev;
3472 const char *mode;
3473 int flags;
3475 mode = qemu_opt_get(opts, "mode");
3476 if (mode == NULL) {
3477 mode = "readline";
3479 if (strcmp(mode, "readline") == 0) {
3480 flags = MONITOR_USE_READLINE;
3481 } else if (strcmp(mode, "control") == 0) {
3482 flags = MONITOR_USE_CONTROL;
3483 } else {
3484 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
3485 exit(1);
3488 if (qemu_opt_get_bool(opts, "default", 0))
3489 flags |= MONITOR_IS_DEFAULT;
3491 chardev = qemu_opt_get(opts, "chardev");
3492 chr = qemu_chr_find(chardev);
3493 if (chr == NULL) {
3494 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
3495 exit(1);
3498 monitor_init(chr, flags);
3499 return 0;
3502 static void monitor_parse(const char *optarg, const char *mode)
3504 static int monitor_device_index = 0;
3505 QemuOpts *opts;
3506 const char *p;
3507 char label[32];
3508 int def = 0;
3510 if (strstart(optarg, "chardev:", &p)) {
3511 snprintf(label, sizeof(label), "%s", p);
3512 } else {
3513 if (monitor_device_index) {
3514 snprintf(label, sizeof(label), "monitor%d",
3515 monitor_device_index);
3516 } else {
3517 snprintf(label, sizeof(label), "monitor");
3518 def = 1;
3520 opts = qemu_chr_parse_compat(label, optarg);
3521 if (!opts) {
3522 fprintf(stderr, "parse error: %s\n", optarg);
3523 exit(1);
3527 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
3528 if (!opts) {
3529 fprintf(stderr, "duplicate chardev: %s\n", label);
3530 exit(1);
3532 qemu_opt_set(opts, "mode", mode);
3533 qemu_opt_set(opts, "chardev", label);
3534 if (def)
3535 qemu_opt_set(opts, "default", "on");
3536 monitor_device_index++;
3539 struct device_config {
3540 enum {
3541 DEV_USB, /* -usbdevice */
3542 DEV_BT, /* -bt */
3543 DEV_SERIAL, /* -serial */
3544 DEV_PARALLEL, /* -parallel */
3545 DEV_VIRTCON, /* -virtioconsole */
3546 DEV_DEBUGCON, /* -debugcon */
3547 } type;
3548 const char *cmdline;
3549 QTAILQ_ENTRY(device_config) next;
3551 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
3553 static void add_device_config(int type, const char *cmdline)
3555 struct device_config *conf;
3557 conf = qemu_mallocz(sizeof(*conf));
3558 conf->type = type;
3559 conf->cmdline = cmdline;
3560 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
3563 static int foreach_device_config(int type, int (*func)(const char *cmdline))
3565 struct device_config *conf;
3566 int rc;
3568 QTAILQ_FOREACH(conf, &device_configs, next) {
3569 if (conf->type != type)
3570 continue;
3571 rc = func(conf->cmdline);
3572 if (0 != rc)
3573 return rc;
3575 return 0;
3578 static int serial_parse(const char *devname)
3580 static int index = 0;
3581 char label[32];
3583 if (strcmp(devname, "none") == 0)
3584 return 0;
3585 if (index == MAX_SERIAL_PORTS) {
3586 fprintf(stderr, "qemu: too many serial ports\n");
3587 exit(1);
3589 snprintf(label, sizeof(label), "serial%d", index);
3590 serial_hds[index] = qemu_chr_open(label, devname, NULL);
3591 if (!serial_hds[index]) {
3592 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
3593 devname, strerror(errno));
3594 return -1;
3596 index++;
3597 return 0;
3600 static int parallel_parse(const char *devname)
3602 static int index = 0;
3603 char label[32];
3605 if (strcmp(devname, "none") == 0)
3606 return 0;
3607 if (index == MAX_PARALLEL_PORTS) {
3608 fprintf(stderr, "qemu: too many parallel ports\n");
3609 exit(1);
3611 snprintf(label, sizeof(label), "parallel%d", index);
3612 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
3613 if (!parallel_hds[index]) {
3614 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
3615 devname, strerror(errno));
3616 return -1;
3618 index++;
3619 return 0;
3622 static int virtcon_parse(const char *devname)
3624 static int index = 0;
3625 char label[32];
3626 QemuOpts *bus_opts, *dev_opts;
3628 if (strcmp(devname, "none") == 0)
3629 return 0;
3630 if (index == MAX_VIRTIO_CONSOLES) {
3631 fprintf(stderr, "qemu: too many virtio consoles\n");
3632 exit(1);
3635 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3636 qemu_opt_set(bus_opts, "driver", "virtio-serial");
3638 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3639 qemu_opt_set(dev_opts, "driver", "virtconsole");
3641 snprintf(label, sizeof(label), "virtcon%d", index);
3642 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
3643 if (!virtcon_hds[index]) {
3644 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
3645 devname, strerror(errno));
3646 return -1;
3648 qemu_opt_set(dev_opts, "chardev", label);
3650 index++;
3651 return 0;
3654 static int debugcon_parse(const char *devname)
3656 QemuOpts *opts;
3658 if (!qemu_chr_open("debugcon", devname, NULL)) {
3659 exit(1);
3661 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
3662 if (!opts) {
3663 fprintf(stderr, "qemu: already have a debugcon device\n");
3664 exit(1);
3666 qemu_opt_set(opts, "driver", "isa-debugcon");
3667 qemu_opt_set(opts, "chardev", "debugcon");
3668 return 0;
3671 static const QEMUOption *lookup_opt(int argc, char **argv,
3672 const char **poptarg, int *poptind)
3674 const QEMUOption *popt;
3675 int optind = *poptind;
3676 char *r = argv[optind];
3677 const char *optarg;
3679 loc_set_cmdline(argv, optind, 1);
3680 optind++;
3681 /* Treat --foo the same as -foo. */
3682 if (r[1] == '-')
3683 r++;
3684 popt = qemu_options;
3685 for(;;) {
3686 if (!popt->name) {
3687 error_report("invalid option");
3688 exit(1);
3690 if (!strcmp(popt->name, r + 1))
3691 break;
3692 popt++;
3694 if (popt->flags & HAS_ARG) {
3695 if (optind >= argc) {
3696 error_report("requires an argument");
3697 exit(1);
3699 optarg = argv[optind++];
3700 loc_set_cmdline(argv, optind - 2, 2);
3701 } else {
3702 optarg = NULL;
3705 *poptarg = optarg;
3706 *poptind = optind;
3708 return popt;
3711 static void qmp_add_default(void)
3713 char buffer[4096];
3714 const char *home;
3715 static uint8_t null_uuid[16];
3716 uint8_t uuid[16];
3717 int ret;
3719 home = getenv("HOME");
3720 if (!home) {
3721 return;
3724 if (memcmp(qemu_uuid, null_uuid, sizeof(null_uuid)) == 0) {
3725 #if defined(CONFIG_UUID)
3726 uuid_generate(uuid);
3727 #else
3728 return;
3729 #endif
3730 } else {
3731 memcpy(uuid, qemu_uuid, sizeof(qemu_uuid));
3734 snprintf(buffer, sizeof(buffer), "%s/.qemu", home);
3735 #ifdef __MINGW32__
3736 ret = mkdir(buffer);
3737 #else
3738 ret = mkdir(buffer, 0755);
3739 #endif
3740 if (ret == -1 && errno != EEXIST) {
3741 fprintf(stderr, "could not open default QMP port\n");
3742 return;
3745 snprintf(buffer, sizeof(buffer), "%s/.qemu/qmp", home);
3746 #ifdef __MINGW32__
3747 ret = mkdir(buffer);
3748 #else
3749 ret = mkdir(buffer, 0755);
3750 #endif
3751 if (ret == -1 && errno != EEXIST) {
3752 fprintf(stderr, "could not open default QMP port\n");
3753 return;
3756 snprintf(buffer, sizeof(buffer),
3757 "unix:%s/.qemu/qmp/" UUID_FMT ".sock,server,nowait",
3758 home,
3759 uuid[0], uuid[1], uuid[2], uuid[3],
3760 uuid[4], uuid[5], uuid[6], uuid[7],
3761 uuid[8], uuid[9], uuid[10], uuid[11],
3762 uuid[12], uuid[13], uuid[14], uuid[15]);
3764 monitor_parse(buffer, "control");
3767 int main(int argc, char **argv, char **envp)
3769 const char *gdbstub_dev = NULL;
3770 uint32_t boot_devices_bitmap = 0;
3771 int i;
3772 int snapshot, linux_boot, net_boot;
3773 const char *icount_option = NULL;
3774 const char *initrd_filename;
3775 const char *kernel_filename, *kernel_cmdline;
3776 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3777 DisplayState *ds;
3778 DisplayChangeListener *dcl;
3779 int cyls, heads, secs, translation;
3780 QemuOpts *hda_opts = NULL, *opts;
3781 int optind;
3782 const char *optarg;
3783 const char *loadvm = NULL;
3784 QEMUMachine *machine;
3785 const char *cpu_model;
3786 #ifndef _WIN32
3787 int fds[2];
3788 #endif
3789 int tb_size;
3790 const char *pid_file = NULL;
3791 const char *incoming = NULL;
3792 #ifndef _WIN32
3793 int fd = 0;
3794 struct passwd *pwd = NULL;
3795 const char *chroot_dir = NULL;
3796 const char *run_as = NULL;
3797 #endif
3798 CPUState *env;
3799 int show_vnc_port = 0;
3800 int defconfig = 1;
3802 error_set_progname(argv[0]);
3804 init_clocks();
3806 qemu_cache_utils_init(envp);
3808 QLIST_INIT (&vm_change_state_head);
3809 #ifndef _WIN32
3811 struct sigaction act;
3812 sigfillset(&act.sa_mask);
3813 act.sa_flags = 0;
3814 act.sa_handler = SIG_IGN;
3815 sigaction(SIGPIPE, &act, NULL);
3817 #else
3818 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3819 /* Note: cpu_interrupt() is currently not SMP safe, so we force
3820 QEMU to run on a single CPU */
3822 HANDLE h;
3823 DWORD mask, smask;
3824 int i;
3825 h = GetCurrentProcess();
3826 if (GetProcessAffinityMask(h, &mask, &smask)) {
3827 for(i = 0; i < 32; i++) {
3828 if (mask & (1 << i))
3829 break;
3831 if (i != 32) {
3832 mask = 1 << i;
3833 SetProcessAffinityMask(h, mask);
3837 #endif
3839 module_call_init(MODULE_INIT_MACHINE);
3840 machine = find_default_machine();
3841 cpu_model = NULL;
3842 initrd_filename = NULL;
3843 ram_size = 0;
3844 snapshot = 0;
3845 kernel_filename = NULL;
3846 kernel_cmdline = "";
3847 cyls = heads = secs = 0;
3848 translation = BIOS_ATA_TRANSLATION_AUTO;
3850 for (i = 0; i < MAX_NODES; i++) {
3851 node_mem[i] = 0;
3852 node_cpumask[i] = 0;
3855 nb_numa_nodes = 0;
3856 nb_nics = 0;
3858 tb_size = 0;
3859 autostart= 1;
3861 /* first pass of option parsing */
3862 optind = 1;
3863 while (optind < argc) {
3864 if (argv[optind][0] != '-') {
3865 /* disk image */
3866 optind++;
3867 continue;
3868 } else {
3869 const QEMUOption *popt;
3871 popt = lookup_opt(argc, argv, &optarg, &optind);
3872 switch (popt->index) {
3873 case QEMU_OPTION_nodefconfig:
3874 defconfig=0;
3875 break;
3880 if (defconfig) {
3881 const char *fname;
3882 FILE *fp;
3884 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3885 fp = fopen(fname, "r");
3886 if (fp) {
3887 if (qemu_config_parse(fp, fname) != 0) {
3888 exit(1);
3890 fclose(fp);
3893 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3894 fp = fopen(fname, "r");
3895 if (fp) {
3896 if (qemu_config_parse(fp, fname) != 0) {
3897 exit(1);
3899 fclose(fp);
3902 #if defined(cpudef_setup)
3903 cpudef_setup(); /* parse cpu definitions in target config file */
3904 #endif
3906 /* second pass of option parsing */
3907 optind = 1;
3908 for(;;) {
3909 if (optind >= argc)
3910 break;
3911 if (argv[optind][0] != '-') {
3912 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3913 } else {
3914 const QEMUOption *popt;
3916 popt = lookup_opt(argc, argv, &optarg, &optind);
3917 switch(popt->index) {
3918 case QEMU_OPTION_M:
3919 machine = find_machine(optarg);
3920 if (!machine) {
3921 QEMUMachine *m;
3922 printf("Supported machines are:\n");
3923 for(m = first_machine; m != NULL; m = m->next) {
3924 if (m->alias)
3925 printf("%-10s %s (alias of %s)\n",
3926 m->alias, m->desc, m->name);
3927 printf("%-10s %s%s\n",
3928 m->name, m->desc,
3929 m->is_default ? " (default)" : "");
3931 exit(*optarg != '?');
3933 break;
3934 case QEMU_OPTION_cpu:
3935 /* hw initialization will check this */
3936 if (*optarg == '?') {
3937 /* XXX: implement xxx_cpu_list for targets that still miss it */
3938 #if defined(cpu_list_id)
3939 cpu_list_id(stdout, &fprintf, optarg);
3940 #elif defined(cpu_list)
3941 cpu_list(stdout, &fprintf); /* deprecated */
3942 #endif
3943 exit(0);
3944 } else {
3945 cpu_model = optarg;
3947 break;
3948 case QEMU_OPTION_initrd:
3949 initrd_filename = optarg;
3950 break;
3951 case QEMU_OPTION_hda:
3952 if (cyls == 0)
3953 hda_opts = drive_add(optarg, HD_ALIAS, 0);
3954 else
3955 hda_opts = drive_add(optarg, HD_ALIAS
3956 ",cyls=%d,heads=%d,secs=%d%s",
3957 0, cyls, heads, secs,
3958 translation == BIOS_ATA_TRANSLATION_LBA ?
3959 ",trans=lba" :
3960 translation == BIOS_ATA_TRANSLATION_NONE ?
3961 ",trans=none" : "");
3962 break;
3963 case QEMU_OPTION_hdb:
3964 case QEMU_OPTION_hdc:
3965 case QEMU_OPTION_hdd:
3966 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
3967 break;
3968 case QEMU_OPTION_drive:
3969 drive_add(NULL, "%s", optarg);
3970 break;
3971 case QEMU_OPTION_set:
3972 if (qemu_set_option(optarg) != 0)
3973 exit(1);
3974 break;
3975 case QEMU_OPTION_global:
3976 if (qemu_global_option(optarg) != 0)
3977 exit(1);
3978 break;
3979 case QEMU_OPTION_mtdblock:
3980 drive_add(optarg, MTD_ALIAS);
3981 break;
3982 case QEMU_OPTION_sd:
3983 drive_add(optarg, SD_ALIAS);
3984 break;
3985 case QEMU_OPTION_pflash:
3986 drive_add(optarg, PFLASH_ALIAS);
3987 break;
3988 case QEMU_OPTION_snapshot:
3989 snapshot = 1;
3990 break;
3991 case QEMU_OPTION_hdachs:
3993 const char *p;
3994 p = optarg;
3995 cyls = strtol(p, (char **)&p, 0);
3996 if (cyls < 1 || cyls > 16383)
3997 goto chs_fail;
3998 if (*p != ',')
3999 goto chs_fail;
4000 p++;
4001 heads = strtol(p, (char **)&p, 0);
4002 if (heads < 1 || heads > 16)
4003 goto chs_fail;
4004 if (*p != ',')
4005 goto chs_fail;
4006 p++;
4007 secs = strtol(p, (char **)&p, 0);
4008 if (secs < 1 || secs > 63)
4009 goto chs_fail;
4010 if (*p == ',') {
4011 p++;
4012 if (!strcmp(p, "none"))
4013 translation = BIOS_ATA_TRANSLATION_NONE;
4014 else if (!strcmp(p, "lba"))
4015 translation = BIOS_ATA_TRANSLATION_LBA;
4016 else if (!strcmp(p, "auto"))
4017 translation = BIOS_ATA_TRANSLATION_AUTO;
4018 else
4019 goto chs_fail;
4020 } else if (*p != '\0') {
4021 chs_fail:
4022 fprintf(stderr, "qemu: invalid physical CHS format\n");
4023 exit(1);
4025 if (hda_opts != NULL) {
4026 char num[16];
4027 snprintf(num, sizeof(num), "%d", cyls);
4028 qemu_opt_set(hda_opts, "cyls", num);
4029 snprintf(num, sizeof(num), "%d", heads);
4030 qemu_opt_set(hda_opts, "heads", num);
4031 snprintf(num, sizeof(num), "%d", secs);
4032 qemu_opt_set(hda_opts, "secs", num);
4033 if (translation == BIOS_ATA_TRANSLATION_LBA)
4034 qemu_opt_set(hda_opts, "trans", "lba");
4035 if (translation == BIOS_ATA_TRANSLATION_NONE)
4036 qemu_opt_set(hda_opts, "trans", "none");
4039 break;
4040 case QEMU_OPTION_numa:
4041 if (nb_numa_nodes >= MAX_NODES) {
4042 fprintf(stderr, "qemu: too many NUMA nodes\n");
4043 exit(1);
4045 numa_add(optarg);
4046 break;
4047 case QEMU_OPTION_nographic:
4048 display_type = DT_NOGRAPHIC;
4049 break;
4050 #ifdef CONFIG_CURSES
4051 case QEMU_OPTION_curses:
4052 display_type = DT_CURSES;
4053 break;
4054 #endif
4055 case QEMU_OPTION_portrait:
4056 graphic_rotate = 1;
4057 break;
4058 case QEMU_OPTION_kernel:
4059 kernel_filename = optarg;
4060 break;
4061 case QEMU_OPTION_append:
4062 kernel_cmdline = optarg;
4063 break;
4064 case QEMU_OPTION_cdrom:
4065 drive_add(optarg, CDROM_ALIAS);
4066 break;
4067 case QEMU_OPTION_boot:
4069 static const char * const params[] = {
4070 "order", "once", "menu", NULL
4072 char buf[sizeof(boot_devices)];
4073 char *standard_boot_devices;
4074 int legacy = 0;
4076 if (!strchr(optarg, '=')) {
4077 legacy = 1;
4078 pstrcpy(buf, sizeof(buf), optarg);
4079 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4080 fprintf(stderr,
4081 "qemu: unknown boot parameter '%s' in '%s'\n",
4082 buf, optarg);
4083 exit(1);
4086 if (legacy ||
4087 get_param_value(buf, sizeof(buf), "order", optarg)) {
4088 boot_devices_bitmap = parse_bootdevices(buf);
4089 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4091 if (!legacy) {
4092 if (get_param_value(buf, sizeof(buf),
4093 "once", optarg)) {
4094 boot_devices_bitmap |= parse_bootdevices(buf);
4095 standard_boot_devices = qemu_strdup(boot_devices);
4096 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4097 qemu_register_reset(restore_boot_devices,
4098 standard_boot_devices);
4100 if (get_param_value(buf, sizeof(buf),
4101 "menu", optarg)) {
4102 if (!strcmp(buf, "on")) {
4103 boot_menu = 1;
4104 } else if (!strcmp(buf, "off")) {
4105 boot_menu = 0;
4106 } else {
4107 fprintf(stderr,
4108 "qemu: invalid option value '%s'\n",
4109 buf);
4110 exit(1);
4115 break;
4116 case QEMU_OPTION_fda:
4117 case QEMU_OPTION_fdb:
4118 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4119 break;
4120 #ifdef TARGET_I386
4121 case QEMU_OPTION_no_fd_bootchk:
4122 fd_bootchk = 0;
4123 break;
4124 #endif
4125 case QEMU_OPTION_netdev:
4126 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4127 exit(1);
4129 break;
4130 case QEMU_OPTION_net:
4131 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4132 exit(1);
4134 break;
4135 #ifdef CONFIG_SLIRP
4136 case QEMU_OPTION_tftp:
4137 legacy_tftp_prefix = optarg;
4138 break;
4139 case QEMU_OPTION_bootp:
4140 legacy_bootp_filename = optarg;
4141 break;
4142 #ifndef _WIN32
4143 case QEMU_OPTION_smb:
4144 if (net_slirp_smb(optarg) < 0)
4145 exit(1);
4146 break;
4147 #endif
4148 case QEMU_OPTION_redir:
4149 if (net_slirp_redir(optarg) < 0)
4150 exit(1);
4151 break;
4152 #endif
4153 case QEMU_OPTION_bt:
4154 add_device_config(DEV_BT, optarg);
4155 break;
4156 #ifdef HAS_AUDIO
4157 case QEMU_OPTION_audio_help:
4158 AUD_help ();
4159 exit (0);
4160 break;
4161 case QEMU_OPTION_soundhw:
4162 select_soundhw (optarg);
4163 break;
4164 #endif
4165 case QEMU_OPTION_h:
4166 help(0);
4167 break;
4168 case QEMU_OPTION_version:
4169 version();
4170 exit(0);
4171 break;
4172 case QEMU_OPTION_m: {
4173 uint64_t value;
4174 char *ptr;
4176 value = strtoul(optarg, &ptr, 10);
4177 switch (*ptr) {
4178 case 0: case 'M': case 'm':
4179 value <<= 20;
4180 break;
4181 case 'G': case 'g':
4182 value <<= 30;
4183 break;
4184 default:
4185 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4186 exit(1);
4189 /* On 32-bit hosts, QEMU is limited by virtual address space */
4190 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
4191 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4192 exit(1);
4194 if (value != (uint64_t)(ram_addr_t)value) {
4195 fprintf(stderr, "qemu: ram size too large\n");
4196 exit(1);
4198 ram_size = value;
4199 break;
4201 case QEMU_OPTION_mempath:
4202 mem_path = optarg;
4203 break;
4204 #ifdef MAP_POPULATE
4205 case QEMU_OPTION_mem_prealloc:
4206 mem_prealloc = 1;
4207 break;
4208 #endif
4209 case QEMU_OPTION_d:
4211 int mask;
4212 const CPULogItem *item;
4214 mask = cpu_str_to_log_mask(optarg);
4215 if (!mask) {
4216 printf("Log items (comma separated):\n");
4217 for(item = cpu_log_items; item->mask != 0; item++) {
4218 printf("%-10s %s\n", item->name, item->help);
4220 exit(1);
4222 cpu_set_log(mask);
4224 break;
4225 case QEMU_OPTION_s:
4226 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4227 break;
4228 case QEMU_OPTION_gdb:
4229 gdbstub_dev = optarg;
4230 break;
4231 case QEMU_OPTION_L:
4232 data_dir = optarg;
4233 break;
4234 case QEMU_OPTION_bios:
4235 bios_name = optarg;
4236 break;
4237 case QEMU_OPTION_singlestep:
4238 singlestep = 1;
4239 break;
4240 case QEMU_OPTION_S:
4241 autostart = 0;
4242 break;
4243 case QEMU_OPTION_k:
4244 keyboard_layout = optarg;
4245 break;
4246 case QEMU_OPTION_localtime:
4247 rtc_utc = 0;
4248 break;
4249 case QEMU_OPTION_vga:
4250 select_vgahw (optarg);
4251 break;
4252 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4253 case QEMU_OPTION_g:
4255 const char *p;
4256 int w, h, depth;
4257 p = optarg;
4258 w = strtol(p, (char **)&p, 10);
4259 if (w <= 0) {
4260 graphic_error:
4261 fprintf(stderr, "qemu: invalid resolution or depth\n");
4262 exit(1);
4264 if (*p != 'x')
4265 goto graphic_error;
4266 p++;
4267 h = strtol(p, (char **)&p, 10);
4268 if (h <= 0)
4269 goto graphic_error;
4270 if (*p == 'x') {
4271 p++;
4272 depth = strtol(p, (char **)&p, 10);
4273 if (depth != 8 && depth != 15 && depth != 16 &&
4274 depth != 24 && depth != 32)
4275 goto graphic_error;
4276 } else if (*p == '\0') {
4277 depth = graphic_depth;
4278 } else {
4279 goto graphic_error;
4282 graphic_width = w;
4283 graphic_height = h;
4284 graphic_depth = depth;
4286 break;
4287 #endif
4288 case QEMU_OPTION_echr:
4290 char *r;
4291 term_escape_char = strtol(optarg, &r, 0);
4292 if (r == optarg)
4293 printf("Bad argument to echr\n");
4294 break;
4296 case QEMU_OPTION_monitor:
4297 monitor_parse(optarg, "readline");
4298 default_monitor = 0;
4299 break;
4300 case QEMU_OPTION_qmp:
4301 monitor_parse(optarg, "control");
4302 default_monitor = 0;
4303 break;
4304 case QEMU_OPTION_mon:
4305 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
4306 if (!opts) {
4307 fprintf(stderr, "parse error: %s\n", optarg);
4308 exit(1);
4310 default_monitor = 0;
4311 break;
4312 case QEMU_OPTION_chardev:
4313 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
4314 if (!opts) {
4315 fprintf(stderr, "parse error: %s\n", optarg);
4316 exit(1);
4318 break;
4319 case QEMU_OPTION_serial:
4320 add_device_config(DEV_SERIAL, optarg);
4321 default_serial = 0;
4322 if (strncmp(optarg, "mon:", 4) == 0) {
4323 default_monitor = 0;
4325 break;
4326 case QEMU_OPTION_watchdog:
4327 if (watchdog) {
4328 fprintf(stderr,
4329 "qemu: only one watchdog option may be given\n");
4330 return 1;
4332 watchdog = optarg;
4333 break;
4334 case QEMU_OPTION_watchdog_action:
4335 if (select_watchdog_action(optarg) == -1) {
4336 fprintf(stderr, "Unknown -watchdog-action parameter\n");
4337 exit(1);
4339 break;
4340 case QEMU_OPTION_virtiocon:
4341 add_device_config(DEV_VIRTCON, optarg);
4342 default_virtcon = 0;
4343 if (strncmp(optarg, "mon:", 4) == 0) {
4344 default_monitor = 0;
4346 break;
4347 case QEMU_OPTION_parallel:
4348 add_device_config(DEV_PARALLEL, optarg);
4349 default_parallel = 0;
4350 if (strncmp(optarg, "mon:", 4) == 0) {
4351 default_monitor = 0;
4353 break;
4354 case QEMU_OPTION_debugcon:
4355 add_device_config(DEV_DEBUGCON, optarg);
4356 break;
4357 case QEMU_OPTION_loadvm:
4358 loadvm = optarg;
4359 break;
4360 case QEMU_OPTION_full_screen:
4361 full_screen = 1;
4362 break;
4363 #ifdef CONFIG_SDL
4364 case QEMU_OPTION_no_frame:
4365 no_frame = 1;
4366 break;
4367 case QEMU_OPTION_alt_grab:
4368 alt_grab = 1;
4369 break;
4370 case QEMU_OPTION_ctrl_grab:
4371 ctrl_grab = 1;
4372 break;
4373 case QEMU_OPTION_no_quit:
4374 no_quit = 1;
4375 break;
4376 case QEMU_OPTION_sdl:
4377 display_type = DT_SDL;
4378 break;
4379 #endif
4380 case QEMU_OPTION_pidfile:
4381 pid_file = optarg;
4382 break;
4383 #ifdef TARGET_I386
4384 case QEMU_OPTION_win2k_hack:
4385 win2k_install_hack = 1;
4386 break;
4387 case QEMU_OPTION_rtc_td_hack:
4388 rtc_td_hack = 1;
4389 break;
4390 case QEMU_OPTION_acpitable:
4391 if(acpi_table_add(optarg) < 0) {
4392 fprintf(stderr, "Wrong acpi table provided\n");
4393 exit(1);
4395 break;
4396 case QEMU_OPTION_smbios:
4397 if(smbios_entry_add(optarg) < 0) {
4398 fprintf(stderr, "Wrong smbios provided\n");
4399 exit(1);
4401 break;
4402 #endif
4403 #ifdef CONFIG_KVM
4404 case QEMU_OPTION_enable_kvm:
4405 kvm_allowed = 1;
4406 break;
4407 #endif
4408 case QEMU_OPTION_usb:
4409 usb_enabled = 1;
4410 break;
4411 case QEMU_OPTION_usbdevice:
4412 usb_enabled = 1;
4413 add_device_config(DEV_USB, optarg);
4414 break;
4415 case QEMU_OPTION_device:
4416 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
4417 exit(1);
4419 break;
4420 case QEMU_OPTION_smp:
4421 smp_parse(optarg);
4422 if (smp_cpus < 1) {
4423 fprintf(stderr, "Invalid number of CPUs\n");
4424 exit(1);
4426 if (max_cpus < smp_cpus) {
4427 fprintf(stderr, "maxcpus must be equal to or greater than "
4428 "smp\n");
4429 exit(1);
4431 if (max_cpus > 255) {
4432 fprintf(stderr, "Unsupported number of maxcpus\n");
4433 exit(1);
4435 break;
4436 case QEMU_OPTION_vnc:
4437 display_type = DT_VNC;
4438 vnc_display = optarg;
4439 break;
4440 #ifdef TARGET_I386
4441 case QEMU_OPTION_no_acpi:
4442 acpi_enabled = 0;
4443 break;
4444 case QEMU_OPTION_no_hpet:
4445 no_hpet = 1;
4446 break;
4447 case QEMU_OPTION_balloon:
4448 if (balloon_parse(optarg) < 0) {
4449 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
4450 exit(1);
4452 break;
4453 #endif
4454 case QEMU_OPTION_no_reboot:
4455 no_reboot = 1;
4456 break;
4457 case QEMU_OPTION_no_shutdown:
4458 no_shutdown = 1;
4459 break;
4460 case QEMU_OPTION_show_cursor:
4461 cursor_hide = 0;
4462 break;
4463 case QEMU_OPTION_uuid:
4464 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4465 fprintf(stderr, "Fail to parse UUID string."
4466 " Wrong format.\n");
4467 exit(1);
4469 break;
4470 #ifndef _WIN32
4471 case QEMU_OPTION_daemonize:
4472 daemonize = 1;
4473 break;
4474 #endif
4475 case QEMU_OPTION_option_rom:
4476 if (nb_option_roms >= MAX_OPTION_ROMS) {
4477 fprintf(stderr, "Too many option ROMs\n");
4478 exit(1);
4480 option_rom[nb_option_roms] = optarg;
4481 nb_option_roms++;
4482 break;
4483 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4484 case QEMU_OPTION_semihosting:
4485 semihosting_enabled = 1;
4486 break;
4487 #endif
4488 case QEMU_OPTION_name:
4489 qemu_name = qemu_strdup(optarg);
4491 char *p = strchr(qemu_name, ',');
4492 if (p != NULL) {
4493 *p++ = 0;
4494 if (strncmp(p, "process=", 8)) {
4495 fprintf(stderr, "Unknown subargument %s to -name", p);
4496 exit(1);
4498 p += 8;
4499 set_proc_name(p);
4502 break;
4503 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4504 case QEMU_OPTION_prom_env:
4505 if (nb_prom_envs >= MAX_PROM_ENVS) {
4506 fprintf(stderr, "Too many prom variables\n");
4507 exit(1);
4509 prom_envs[nb_prom_envs] = optarg;
4510 nb_prom_envs++;
4511 break;
4512 #endif
4513 #ifdef TARGET_ARM
4514 case QEMU_OPTION_old_param:
4515 old_param = 1;
4516 break;
4517 #endif
4518 case QEMU_OPTION_clock:
4519 configure_alarms(optarg);
4520 break;
4521 case QEMU_OPTION_startdate:
4522 configure_rtc_date_offset(optarg, 1);
4523 break;
4524 case QEMU_OPTION_rtc:
4525 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
4526 if (!opts) {
4527 fprintf(stderr, "parse error: %s\n", optarg);
4528 exit(1);
4530 configure_rtc(opts);
4531 break;
4532 case QEMU_OPTION_tb_size:
4533 tb_size = strtol(optarg, NULL, 0);
4534 if (tb_size < 0)
4535 tb_size = 0;
4536 break;
4537 case QEMU_OPTION_icount:
4538 icount_option = optarg;
4539 break;
4540 case QEMU_OPTION_incoming:
4541 incoming = optarg;
4542 break;
4543 case QEMU_OPTION_nodefaults:
4544 default_serial = 0;
4545 default_parallel = 0;
4546 default_virtcon = 0;
4547 default_monitor = 0;
4548 default_vga = 0;
4549 default_net = 0;
4550 default_floppy = 0;
4551 default_cdrom = 0;
4552 default_sdcard = 0;
4553 break;
4554 #ifndef _WIN32
4555 case QEMU_OPTION_chroot:
4556 chroot_dir = optarg;
4557 break;
4558 case QEMU_OPTION_runas:
4559 run_as = optarg;
4560 break;
4561 #endif
4562 #ifdef CONFIG_XEN
4563 case QEMU_OPTION_xen_domid:
4564 xen_domid = atoi(optarg);
4565 break;
4566 case QEMU_OPTION_xen_create:
4567 xen_mode = XEN_CREATE;
4568 break;
4569 case QEMU_OPTION_xen_attach:
4570 xen_mode = XEN_ATTACH;
4571 break;
4572 #endif
4573 case QEMU_OPTION_readconfig:
4575 FILE *fp;
4576 fp = fopen(optarg, "r");
4577 if (fp == NULL) {
4578 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4579 exit(1);
4581 if (qemu_config_parse(fp, optarg) != 0) {
4582 exit(1);
4584 fclose(fp);
4585 break;
4587 case QEMU_OPTION_writeconfig:
4589 FILE *fp;
4590 if (strcmp(optarg, "-") == 0) {
4591 fp = stdout;
4592 } else {
4593 fp = fopen(optarg, "w");
4594 if (fp == NULL) {
4595 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4596 exit(1);
4599 qemu_config_write(fp);
4600 fclose(fp);
4601 break;
4606 loc_set_none();
4608 /* If no data_dir is specified then try to find it relative to the
4609 executable path. */
4610 if (!data_dir) {
4611 data_dir = find_datadir(argv[0]);
4613 /* If all else fails use the install patch specified when building. */
4614 if (!data_dir) {
4615 data_dir = CONFIG_QEMU_SHAREDIR;
4619 * Default to max_cpus = smp_cpus, in case the user doesn't
4620 * specify a max_cpus value.
4622 if (!max_cpus)
4623 max_cpus = smp_cpus;
4625 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4626 if (smp_cpus > machine->max_cpus) {
4627 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4628 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
4629 machine->max_cpus);
4630 exit(1);
4633 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
4634 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
4636 if (machine->no_serial) {
4637 default_serial = 0;
4639 if (machine->no_parallel) {
4640 default_parallel = 0;
4642 if (!machine->use_virtcon) {
4643 default_virtcon = 0;
4645 if (machine->no_vga) {
4646 default_vga = 0;
4648 if (machine->no_floppy) {
4649 default_floppy = 0;
4651 if (machine->no_cdrom) {
4652 default_cdrom = 0;
4654 if (machine->no_sdcard) {
4655 default_sdcard = 0;
4658 if (display_type == DT_NOGRAPHIC) {
4659 if (default_parallel)
4660 add_device_config(DEV_PARALLEL, "null");
4661 if (default_serial && default_monitor) {
4662 add_device_config(DEV_SERIAL, "mon:stdio");
4663 } else if (default_virtcon && default_monitor) {
4664 add_device_config(DEV_VIRTCON, "mon:stdio");
4665 } else {
4666 if (default_serial)
4667 add_device_config(DEV_SERIAL, "stdio");
4668 if (default_virtcon)
4669 add_device_config(DEV_VIRTCON, "stdio");
4670 if (default_monitor)
4671 monitor_parse("stdio", "readline");
4673 } else {
4674 if (default_serial)
4675 add_device_config(DEV_SERIAL, "vc:80Cx24C");
4676 if (default_parallel)
4677 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4678 if (default_monitor)
4679 monitor_parse("vc:80Cx24C", "readline");
4680 if (default_virtcon)
4681 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4683 if (default_qmp) {
4684 qmp_add_default();
4686 if (default_vga)
4687 vga_interface_type = VGA_CIRRUS;
4689 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
4690 exit(1);
4692 #ifndef _WIN32
4693 if (daemonize) {
4694 pid_t pid;
4696 if (pipe(fds) == -1)
4697 exit(1);
4699 pid = fork();
4700 if (pid > 0) {
4701 uint8_t status;
4702 ssize_t len;
4704 close(fds[1]);
4706 again:
4707 len = read(fds[0], &status, 1);
4708 if (len == -1 && (errno == EINTR))
4709 goto again;
4711 if (len != 1)
4712 exit(1);
4713 else if (status == 1) {
4714 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
4715 exit(1);
4716 } else
4717 exit(0);
4718 } else if (pid < 0)
4719 exit(1);
4721 close(fds[0]);
4722 qemu_set_cloexec(fds[1]);
4724 setsid();
4726 pid = fork();
4727 if (pid > 0)
4728 exit(0);
4729 else if (pid < 0)
4730 exit(1);
4732 umask(027);
4734 signal(SIGTSTP, SIG_IGN);
4735 signal(SIGTTOU, SIG_IGN);
4736 signal(SIGTTIN, SIG_IGN);
4738 #endif
4740 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4741 #ifndef _WIN32
4742 if (daemonize) {
4743 uint8_t status = 1;
4744 if (write(fds[1], &status, 1) != 1) {
4745 perror("daemonize. Writing to pipe\n");
4747 } else
4748 #endif
4749 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
4750 exit(1);
4753 if (kvm_enabled()) {
4754 int ret;
4756 ret = kvm_init(smp_cpus);
4757 if (ret < 0) {
4758 fprintf(stderr, "failed to initialize KVM\n");
4759 exit(1);
4763 if (qemu_init_main_loop()) {
4764 fprintf(stderr, "qemu_init_main_loop failed\n");
4765 exit(1);
4767 linux_boot = (kernel_filename != NULL);
4769 if (!linux_boot && *kernel_cmdline != '\0') {
4770 fprintf(stderr, "-append only allowed with -kernel option\n");
4771 exit(1);
4774 if (!linux_boot && initrd_filename != NULL) {
4775 fprintf(stderr, "-initrd only allowed with -kernel option\n");
4776 exit(1);
4779 #ifndef _WIN32
4780 /* Win32 doesn't support line-buffering and requires size >= 2 */
4781 setvbuf(stdout, NULL, _IOLBF, 0);
4782 #endif
4784 if (init_timer_alarm() < 0) {
4785 fprintf(stderr, "could not initialize alarm timer\n");
4786 exit(1);
4788 configure_icount(icount_option);
4790 #ifdef _WIN32
4791 socket_init();
4792 #endif
4794 if (net_init_clients() < 0) {
4795 exit(1);
4798 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4799 net_set_boot_mask(net_boot);
4801 /* init the bluetooth world */
4802 if (foreach_device_config(DEV_BT, bt_parse))
4803 exit(1);
4805 /* init the memory */
4806 if (ram_size == 0)
4807 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4809 /* init the dynamic translator */
4810 cpu_exec_init_all(tb_size * 1024 * 1024);
4812 bdrv_init_with_whitelist();
4814 blk_mig_init();
4816 if (default_cdrom) {
4817 /* we always create the cdrom drive, even if no disk is there */
4818 drive_add(NULL, CDROM_ALIAS);
4821 if (default_floppy) {
4822 /* we always create at least one floppy */
4823 drive_add(NULL, FD_ALIAS, 0);
4826 if (default_sdcard) {
4827 /* we always create one sd slot, even if no card is in it */
4828 drive_add(NULL, SD_ALIAS);
4831 /* open the virtual block devices */
4832 if (snapshot)
4833 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4834 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4835 exit(1);
4837 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
4838 ram_load, NULL);
4840 if (nb_numa_nodes > 0) {
4841 int i;
4843 if (nb_numa_nodes > smp_cpus) {
4844 nb_numa_nodes = smp_cpus;
4847 /* If no memory size if given for any node, assume the default case
4848 * and distribute the available memory equally across all nodes
4850 for (i = 0; i < nb_numa_nodes; i++) {
4851 if (node_mem[i] != 0)
4852 break;
4854 if (i == nb_numa_nodes) {
4855 uint64_t usedmem = 0;
4857 /* On Linux, the each node's border has to be 8MB aligned,
4858 * the final node gets the rest.
4860 for (i = 0; i < nb_numa_nodes - 1; i++) {
4861 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4862 usedmem += node_mem[i];
4864 node_mem[i] = ram_size - usedmem;
4867 for (i = 0; i < nb_numa_nodes; i++) {
4868 if (node_cpumask[i] != 0)
4869 break;
4871 /* assigning the VCPUs round-robin is easier to implement, guest OSes
4872 * must cope with this anyway, because there are BIOSes out there in
4873 * real machines which also use this scheme.
4875 if (i == nb_numa_nodes) {
4876 for (i = 0; i < smp_cpus; i++) {
4877 node_cpumask[i % nb_numa_nodes] |= 1 << i;
4882 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4883 exit(1);
4884 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4885 exit(1);
4886 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4887 exit(1);
4888 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4889 exit(1);
4891 module_call_init(MODULE_INIT_DEVICE);
4893 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
4894 exit(0);
4896 if (watchdog) {
4897 i = select_watchdog(watchdog);
4898 if (i > 0)
4899 exit (i == 1 ? 1 : 0);
4902 if (machine->compat_props) {
4903 qdev_prop_register_global_list(machine->compat_props);
4905 qemu_add_globals();
4907 machine->init(ram_size, boot_devices,
4908 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
4910 cpu_synchronize_all_post_init();
4912 #ifndef _WIN32
4913 /* must be after terminal init, SDL library changes signal handlers */
4914 sighandler_setup();
4915 #endif
4917 for (env = first_cpu; env != NULL; env = env->next_cpu) {
4918 for (i = 0; i < nb_numa_nodes; i++) {
4919 if (node_cpumask[i] & (1 << env->cpu_index)) {
4920 env->numa_node = i;
4925 current_machine = machine;
4927 /* init USB devices */
4928 if (usb_enabled) {
4929 if (foreach_device_config(DEV_USB, usb_parse) < 0)
4930 exit(1);
4933 /* init generic devices */
4934 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
4935 exit(1);
4937 net_check_clients();
4939 /* just use the first displaystate for the moment */
4940 ds = get_displaystate();
4942 if (display_type == DT_DEFAULT) {
4943 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4944 display_type = DT_SDL;
4945 #else
4946 display_type = DT_VNC;
4947 vnc_display = "localhost:0,to=99";
4948 show_vnc_port = 1;
4949 #endif
4953 switch (display_type) {
4954 case DT_NOGRAPHIC:
4955 break;
4956 #if defined(CONFIG_CURSES)
4957 case DT_CURSES:
4958 curses_display_init(ds, full_screen);
4959 break;
4960 #endif
4961 #if defined(CONFIG_SDL)
4962 case DT_SDL:
4963 sdl_display_init(ds, full_screen, no_frame);
4964 break;
4965 #elif defined(CONFIG_COCOA)
4966 case DT_SDL:
4967 cocoa_display_init(ds, full_screen);
4968 break;
4969 #endif
4970 case DT_VNC:
4971 vnc_display_init(ds);
4972 if (vnc_display_open(ds, vnc_display) < 0)
4973 exit(1);
4975 if (show_vnc_port) {
4976 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
4978 break;
4979 default:
4980 break;
4982 dpy_resize(ds);
4984 dcl = ds->listeners;
4985 while (dcl != NULL) {
4986 if (dcl->dpy_refresh != NULL) {
4987 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
4988 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
4990 dcl = dcl->next;
4993 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
4994 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
4995 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
4998 text_consoles_set_display(ds);
5000 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5001 exit(1);
5003 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5004 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5005 gdbstub_dev);
5006 exit(1);
5009 qdev_machine_creation_done();
5011 if (rom_load_all() != 0) {
5012 fprintf(stderr, "rom loading failed\n");
5013 exit(1);
5016 qemu_system_reset();
5017 if (loadvm) {
5018 if (load_vmstate(loadvm) < 0) {
5019 autostart = 0;
5023 if (incoming) {
5024 qemu_start_incoming_migration(incoming);
5025 } else if (autostart) {
5026 vm_start();
5029 #ifndef _WIN32
5030 if (daemonize) {
5031 uint8_t status = 0;
5032 ssize_t len;
5034 again1:
5035 len = write(fds[1], &status, 1);
5036 if (len == -1 && (errno == EINTR))
5037 goto again1;
5039 if (len != 1)
5040 exit(1);
5042 if (chdir("/")) {
5043 perror("not able to chdir to /");
5044 exit(1);
5046 TFR(fd = qemu_open("/dev/null", O_RDWR));
5047 if (fd == -1)
5048 exit(1);
5051 if (run_as) {
5052 pwd = getpwnam(run_as);
5053 if (!pwd) {
5054 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5055 exit(1);
5059 if (chroot_dir) {
5060 if (chroot(chroot_dir) < 0) {
5061 fprintf(stderr, "chroot failed\n");
5062 exit(1);
5064 if (chdir("/")) {
5065 perror("not able to chdir to /");
5066 exit(1);
5070 if (run_as) {
5071 if (setgid(pwd->pw_gid) < 0) {
5072 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5073 exit(1);
5075 if (setuid(pwd->pw_uid) < 0) {
5076 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5077 exit(1);
5079 if (setuid(0) != -1) {
5080 fprintf(stderr, "Dropping privileges failed\n");
5081 exit(1);
5085 if (daemonize) {
5086 dup2(fd, 0);
5087 dup2(fd, 1);
5088 dup2(fd, 2);
5090 close(fd);
5092 #endif
5094 main_loop();
5095 quit_timers();
5096 net_cleanup();
5098 return 0;