Revert "Add exit notifiers"
[qemu/aliguori-queue.git] / vl.c
blob8274c1ddda15271f0f0924719c799c6637ea1a7a
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;
279 static int default_qmp = 1;
281 static struct {
282 const char *driver;
283 int *flag;
284 } default_list[] = {
285 { .driver = "isa-serial", .flag = &default_serial },
286 { .driver = "isa-parallel", .flag = &default_parallel },
287 { .driver = "isa-fdc", .flag = &default_floppy },
288 { .driver = "ide-drive", .flag = &default_cdrom },
289 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
290 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
291 { .driver = "virtio-serial", .flag = &default_virtcon },
292 { .driver = "VGA", .flag = &default_vga },
293 { .driver = "cirrus-vga", .flag = &default_vga },
294 { .driver = "vmware-svga", .flag = &default_vga },
297 static int default_driver_check(QemuOpts *opts, void *opaque)
299 const char *driver = qemu_opt_get(opts, "driver");
300 int i;
302 if (!driver)
303 return 0;
304 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
305 if (strcmp(default_list[i].driver, driver) != 0)
306 continue;
307 *(default_list[i].flag) = 0;
309 return 0;
312 /***********************************************************/
313 /* x86 ISA bus support */
315 target_phys_addr_t isa_mem_base = 0;
316 PicState2 *isa_pic;
318 /***********************************************************/
319 void hw_error(const char *fmt, ...)
321 va_list ap;
322 CPUState *env;
324 va_start(ap, fmt);
325 fprintf(stderr, "qemu: hardware error: ");
326 vfprintf(stderr, fmt, ap);
327 fprintf(stderr, "\n");
328 for(env = first_cpu; env != NULL; env = env->next_cpu) {
329 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
330 #ifdef TARGET_I386
331 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
332 #else
333 cpu_dump_state(env, stderr, fprintf, 0);
334 #endif
336 va_end(ap);
337 abort();
340 static void set_proc_name(const char *s)
342 #if defined(__linux__) && defined(PR_SET_NAME)
343 char name[16];
344 if (!s)
345 return;
346 name[sizeof(name) - 1] = 0;
347 strncpy(name, s, sizeof(name));
348 /* Could rewrite argv[0] too, but that's a bit more complicated.
349 This simple way is enough for `top'. */
350 prctl(PR_SET_NAME, name);
351 #endif
354 /***************/
355 /* ballooning */
357 static QEMUBalloonEvent *qemu_balloon_event;
358 void *qemu_balloon_event_opaque;
360 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
362 qemu_balloon_event = func;
363 qemu_balloon_event_opaque = opaque;
366 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
368 if (qemu_balloon_event) {
369 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
370 return 1;
371 } else {
372 return 0;
376 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
378 if (qemu_balloon_event) {
379 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
380 return 1;
381 } else {
382 return 0;
387 /***********************************************************/
388 /* real time host monotonic timer */
390 /* compute with 96 bit intermediate result: (a*b)/c */
391 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
393 union {
394 uint64_t ll;
395 struct {
396 #ifdef HOST_WORDS_BIGENDIAN
397 uint32_t high, low;
398 #else
399 uint32_t low, high;
400 #endif
401 } l;
402 } u, res;
403 uint64_t rl, rh;
405 u.ll = a;
406 rl = (uint64_t)u.l.low * (uint64_t)b;
407 rh = (uint64_t)u.l.high * (uint64_t)b;
408 rh += (rl >> 32);
409 res.l.high = rh / c;
410 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
411 return res.ll;
414 /***********************************************************/
415 /* host time/date access */
416 void qemu_get_timedate(struct tm *tm, int offset)
418 time_t ti;
419 struct tm *ret;
421 time(&ti);
422 ti += offset;
423 if (rtc_date_offset == -1) {
424 if (rtc_utc)
425 ret = gmtime(&ti);
426 else
427 ret = localtime(&ti);
428 } else {
429 ti -= rtc_date_offset;
430 ret = gmtime(&ti);
433 memcpy(tm, ret, sizeof(struct tm));
436 int qemu_timedate_diff(struct tm *tm)
438 time_t seconds;
440 if (rtc_date_offset == -1)
441 if (rtc_utc)
442 seconds = mktimegm(tm);
443 else
444 seconds = mktime(tm);
445 else
446 seconds = mktimegm(tm) + rtc_date_offset;
448 return seconds - time(NULL);
451 void rtc_change_mon_event(struct tm *tm)
453 QObject *data;
455 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
456 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
457 qobject_decref(data);
460 static void configure_rtc_date_offset(const char *startdate, int legacy)
462 time_t rtc_start_date;
463 struct tm tm;
465 if (!strcmp(startdate, "now") && legacy) {
466 rtc_date_offset = -1;
467 } else {
468 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
469 &tm.tm_year,
470 &tm.tm_mon,
471 &tm.tm_mday,
472 &tm.tm_hour,
473 &tm.tm_min,
474 &tm.tm_sec) == 6) {
475 /* OK */
476 } else if (sscanf(startdate, "%d-%d-%d",
477 &tm.tm_year,
478 &tm.tm_mon,
479 &tm.tm_mday) == 3) {
480 tm.tm_hour = 0;
481 tm.tm_min = 0;
482 tm.tm_sec = 0;
483 } else {
484 goto date_fail;
486 tm.tm_year -= 1900;
487 tm.tm_mon--;
488 rtc_start_date = mktimegm(&tm);
489 if (rtc_start_date == -1) {
490 date_fail:
491 fprintf(stderr, "Invalid date format. Valid formats are:\n"
492 "'2006-06-17T16:01:21' or '2006-06-17'\n");
493 exit(1);
495 rtc_date_offset = time(NULL) - rtc_start_date;
499 static void configure_rtc(QemuOpts *opts)
501 const char *value;
503 value = qemu_opt_get(opts, "base");
504 if (value) {
505 if (!strcmp(value, "utc")) {
506 rtc_utc = 1;
507 } else if (!strcmp(value, "localtime")) {
508 rtc_utc = 0;
509 } else {
510 configure_rtc_date_offset(value, 0);
513 value = qemu_opt_get(opts, "clock");
514 if (value) {
515 if (!strcmp(value, "host")) {
516 rtc_clock = host_clock;
517 } else if (!strcmp(value, "vm")) {
518 rtc_clock = vm_clock;
519 } else {
520 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
521 exit(1);
524 #ifdef CONFIG_TARGET_I386
525 value = qemu_opt_get(opts, "driftfix");
526 if (value) {
527 if (!strcmp(buf, "slew")) {
528 rtc_td_hack = 1;
529 } else if (!strcmp(buf, "none")) {
530 rtc_td_hack = 0;
531 } else {
532 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
533 exit(1);
536 #endif
539 #ifdef _WIN32
540 static void socket_cleanup(Notifier *obj)
542 WSACleanup();
545 static int socket_init(void)
547 WSADATA Data;
548 int ret, err;
549 static Notifier notifier = { .notify = socket_cleanup };
551 ret = WSAStartup(MAKEWORD(2,2), &Data);
552 if (ret != 0) {
553 err = WSAGetLastError();
554 fprintf(stderr, "WSAStartup: %d\n", err);
555 return -1;
557 exit_notifier_add(&notifier);
558 return 0;
560 #endif
562 /***********************************************************/
563 /* Bluetooth support */
564 static int nb_hcis;
565 static int cur_hci;
566 static struct HCIInfo *hci_table[MAX_NICS];
568 static struct bt_vlan_s {
569 struct bt_scatternet_s net;
570 int id;
571 struct bt_vlan_s *next;
572 } *first_bt_vlan;
574 /* find or alloc a new bluetooth "VLAN" */
575 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
577 struct bt_vlan_s **pvlan, *vlan;
578 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
579 if (vlan->id == id)
580 return &vlan->net;
582 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
583 vlan->id = id;
584 pvlan = &first_bt_vlan;
585 while (*pvlan != NULL)
586 pvlan = &(*pvlan)->next;
587 *pvlan = vlan;
588 return &vlan->net;
591 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
595 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
597 return -ENOTSUP;
600 static struct HCIInfo null_hci = {
601 .cmd_send = null_hci_send,
602 .sco_send = null_hci_send,
603 .acl_send = null_hci_send,
604 .bdaddr_set = null_hci_addr_set,
607 struct HCIInfo *qemu_next_hci(void)
609 if (cur_hci == nb_hcis)
610 return &null_hci;
612 return hci_table[cur_hci++];
615 static struct HCIInfo *hci_init(const char *str)
617 char *endp;
618 struct bt_scatternet_s *vlan = 0;
620 if (!strcmp(str, "null"))
621 /* null */
622 return &null_hci;
623 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
624 /* host[:hciN] */
625 return bt_host_hci(str[4] ? str + 5 : "hci0");
626 else if (!strncmp(str, "hci", 3)) {
627 /* hci[,vlan=n] */
628 if (str[3]) {
629 if (!strncmp(str + 3, ",vlan=", 6)) {
630 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
631 if (*endp)
632 vlan = 0;
634 } else
635 vlan = qemu_find_bt_vlan(0);
636 if (vlan)
637 return bt_new_hci(vlan);
640 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
642 return 0;
645 static int bt_hci_parse(const char *str)
647 struct HCIInfo *hci;
648 bdaddr_t bdaddr;
650 if (nb_hcis >= MAX_NICS) {
651 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
652 return -1;
655 hci = hci_init(str);
656 if (!hci)
657 return -1;
659 bdaddr.b[0] = 0x52;
660 bdaddr.b[1] = 0x54;
661 bdaddr.b[2] = 0x00;
662 bdaddr.b[3] = 0x12;
663 bdaddr.b[4] = 0x34;
664 bdaddr.b[5] = 0x56 + nb_hcis;
665 hci->bdaddr_set(hci, bdaddr.b);
667 hci_table[nb_hcis++] = hci;
669 return 0;
672 static void bt_vhci_add(int vlan_id)
674 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
676 if (!vlan->slave)
677 fprintf(stderr, "qemu: warning: adding a VHCI to "
678 "an empty scatternet %i\n", vlan_id);
680 bt_vhci_init(bt_new_hci(vlan));
683 static struct bt_device_s *bt_device_add(const char *opt)
685 struct bt_scatternet_s *vlan;
686 int vlan_id = 0;
687 char *endp = strstr(opt, ",vlan=");
688 int len = (endp ? endp - opt : strlen(opt)) + 1;
689 char devname[10];
691 pstrcpy(devname, MIN(sizeof(devname), len), opt);
693 if (endp) {
694 vlan_id = strtol(endp + 6, &endp, 0);
695 if (*endp) {
696 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
697 return 0;
701 vlan = qemu_find_bt_vlan(vlan_id);
703 if (!vlan->slave)
704 fprintf(stderr, "qemu: warning: adding a slave device to "
705 "an empty scatternet %i\n", vlan_id);
707 if (!strcmp(devname, "keyboard"))
708 return bt_keyboard_init(vlan);
710 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
711 return 0;
714 static int bt_parse(const char *opt)
716 const char *endp, *p;
717 int vlan;
719 if (strstart(opt, "hci", &endp)) {
720 if (!*endp || *endp == ',') {
721 if (*endp)
722 if (!strstart(endp, ",vlan=", 0))
723 opt = endp + 1;
725 return bt_hci_parse(opt);
727 } else if (strstart(opt, "vhci", &endp)) {
728 if (!*endp || *endp == ',') {
729 if (*endp) {
730 if (strstart(endp, ",vlan=", &p)) {
731 vlan = strtol(p, (char **) &endp, 0);
732 if (*endp) {
733 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
734 return 1;
736 } else {
737 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
738 return 1;
740 } else
741 vlan = 0;
743 bt_vhci_add(vlan);
744 return 0;
746 } else if (strstart(opt, "device:", &endp))
747 return !bt_device_add(endp);
749 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
750 return 1;
753 /***********************************************************/
754 /* QEMU Block devices */
756 #define HD_ALIAS "index=%d,media=disk"
757 #define CDROM_ALIAS "index=2,media=cdrom"
758 #define FD_ALIAS "index=%d,if=floppy"
759 #define PFLASH_ALIAS "if=pflash"
760 #define MTD_ALIAS "if=mtd"
761 #define SD_ALIAS "index=0,if=sd"
763 QemuOpts *drive_add(const char *file, const char *fmt, ...)
765 va_list ap;
766 char optstr[1024];
767 QemuOpts *opts;
769 va_start(ap, fmt);
770 vsnprintf(optstr, sizeof(optstr), fmt, ap);
771 va_end(ap);
773 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
774 if (!opts) {
775 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
776 __FUNCTION__, optstr);
777 return NULL;
779 if (file)
780 qemu_opt_set(opts, "file", file);
781 return opts;
784 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
786 DriveInfo *dinfo;
788 /* seek interface, bus and unit */
790 QTAILQ_FOREACH(dinfo, &drives, next) {
791 if (dinfo->type == type &&
792 dinfo->bus == bus &&
793 dinfo->unit == unit)
794 return dinfo;
797 return NULL;
800 DriveInfo *drive_get_by_id(const char *id)
802 DriveInfo *dinfo;
804 QTAILQ_FOREACH(dinfo, &drives, next) {
805 if (strcmp(id, dinfo->id))
806 continue;
807 return dinfo;
809 return NULL;
812 int drive_get_max_bus(BlockInterfaceType type)
814 int max_bus;
815 DriveInfo *dinfo;
817 max_bus = -1;
818 QTAILQ_FOREACH(dinfo, &drives, next) {
819 if(dinfo->type == type &&
820 dinfo->bus > max_bus)
821 max_bus = dinfo->bus;
823 return max_bus;
826 const char *drive_get_serial(BlockDriverState *bdrv)
828 DriveInfo *dinfo;
830 QTAILQ_FOREACH(dinfo, &drives, next) {
831 if (dinfo->bdrv == bdrv)
832 return dinfo->serial;
835 return "\0";
838 BlockInterfaceErrorAction drive_get_on_error(
839 BlockDriverState *bdrv, int is_read)
841 DriveInfo *dinfo;
843 QTAILQ_FOREACH(dinfo, &drives, next) {
844 if (dinfo->bdrv == bdrv)
845 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
848 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
851 static void bdrv_format_print(void *opaque, const char *name)
853 fprintf(stderr, " %s", name);
856 void drive_uninit(DriveInfo *dinfo)
858 qemu_opts_del(dinfo->opts);
859 bdrv_delete(dinfo->bdrv);
860 QTAILQ_REMOVE(&drives, dinfo, next);
861 qemu_free(dinfo);
864 static int parse_block_error_action(const char *buf, int is_read)
866 if (!strcmp(buf, "ignore")) {
867 return BLOCK_ERR_IGNORE;
868 } else if (!is_read && !strcmp(buf, "enospc")) {
869 return BLOCK_ERR_STOP_ENOSPC;
870 } else if (!strcmp(buf, "stop")) {
871 return BLOCK_ERR_STOP_ANY;
872 } else if (!strcmp(buf, "report")) {
873 return BLOCK_ERR_REPORT;
874 } else {
875 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
876 buf, is_read ? "read" : "write");
877 return -1;
881 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
882 int *fatal_error)
884 const char *buf;
885 const char *file = NULL;
886 char devname[128];
887 const char *serial;
888 const char *mediastr = "";
889 BlockInterfaceType type;
890 enum { MEDIA_DISK, MEDIA_CDROM } media;
891 int bus_id, unit_id;
892 int cyls, heads, secs, translation;
893 BlockDriver *drv = NULL;
894 QEMUMachine *machine = opaque;
895 int max_devs;
896 int index;
897 int cache;
898 int aio = 0;
899 int ro = 0;
900 int bdrv_flags;
901 int on_read_error, on_write_error;
902 const char *devaddr;
903 DriveInfo *dinfo;
904 int snapshot = 0;
906 *fatal_error = 1;
908 translation = BIOS_ATA_TRANSLATION_AUTO;
909 cache = 1;
911 if (machine && machine->use_scsi) {
912 type = IF_SCSI;
913 max_devs = MAX_SCSI_DEVS;
914 pstrcpy(devname, sizeof(devname), "scsi");
915 } else {
916 type = IF_IDE;
917 max_devs = MAX_IDE_DEVS;
918 pstrcpy(devname, sizeof(devname), "ide");
920 media = MEDIA_DISK;
922 /* extract parameters */
923 bus_id = qemu_opt_get_number(opts, "bus", 0);
924 unit_id = qemu_opt_get_number(opts, "unit", -1);
925 index = qemu_opt_get_number(opts, "index", -1);
927 cyls = qemu_opt_get_number(opts, "cyls", 0);
928 heads = qemu_opt_get_number(opts, "heads", 0);
929 secs = qemu_opt_get_number(opts, "secs", 0);
931 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
932 ro = qemu_opt_get_bool(opts, "readonly", 0);
934 file = qemu_opt_get(opts, "file");
935 serial = qemu_opt_get(opts, "serial");
937 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
938 pstrcpy(devname, sizeof(devname), buf);
939 if (!strcmp(buf, "ide")) {
940 type = IF_IDE;
941 max_devs = MAX_IDE_DEVS;
942 } else if (!strcmp(buf, "scsi")) {
943 type = IF_SCSI;
944 max_devs = MAX_SCSI_DEVS;
945 } else if (!strcmp(buf, "floppy")) {
946 type = IF_FLOPPY;
947 max_devs = 0;
948 } else if (!strcmp(buf, "pflash")) {
949 type = IF_PFLASH;
950 max_devs = 0;
951 } else if (!strcmp(buf, "mtd")) {
952 type = IF_MTD;
953 max_devs = 0;
954 } else if (!strcmp(buf, "sd")) {
955 type = IF_SD;
956 max_devs = 0;
957 } else if (!strcmp(buf, "virtio")) {
958 type = IF_VIRTIO;
959 max_devs = 0;
960 } else if (!strcmp(buf, "xen")) {
961 type = IF_XEN;
962 max_devs = 0;
963 } else if (!strcmp(buf, "none")) {
964 type = IF_NONE;
965 max_devs = 0;
966 } else {
967 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
968 return NULL;
972 if (cyls || heads || secs) {
973 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
974 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
975 return NULL;
977 if (heads < 1 || (type == IF_IDE && heads > 16)) {
978 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
979 return NULL;
981 if (secs < 1 || (type == IF_IDE && secs > 63)) {
982 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
983 return NULL;
987 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
988 if (!cyls) {
989 fprintf(stderr,
990 "qemu: '%s' trans must be used with cyls,heads and secs\n",
991 buf);
992 return NULL;
994 if (!strcmp(buf, "none"))
995 translation = BIOS_ATA_TRANSLATION_NONE;
996 else if (!strcmp(buf, "lba"))
997 translation = BIOS_ATA_TRANSLATION_LBA;
998 else if (!strcmp(buf, "auto"))
999 translation = BIOS_ATA_TRANSLATION_AUTO;
1000 else {
1001 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
1002 return NULL;
1006 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
1007 if (!strcmp(buf, "disk")) {
1008 media = MEDIA_DISK;
1009 } else if (!strcmp(buf, "cdrom")) {
1010 if (cyls || secs || heads) {
1011 fprintf(stderr,
1012 "qemu: '%s' invalid physical CHS format\n", buf);
1013 return NULL;
1015 media = MEDIA_CDROM;
1016 } else {
1017 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
1018 return NULL;
1022 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
1023 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
1024 cache = 0;
1025 else if (!strcmp(buf, "writethrough"))
1026 cache = 1;
1027 else if (!strcmp(buf, "writeback"))
1028 cache = 2;
1029 else {
1030 fprintf(stderr, "qemu: invalid cache option\n");
1031 return NULL;
1035 #ifdef CONFIG_LINUX_AIO
1036 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1037 if (!strcmp(buf, "threads"))
1038 aio = 0;
1039 else if (!strcmp(buf, "native"))
1040 aio = 1;
1041 else {
1042 fprintf(stderr, "qemu: invalid aio option\n");
1043 return NULL;
1046 #endif
1048 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1049 if (strcmp(buf, "?") == 0) {
1050 fprintf(stderr, "qemu: Supported formats:");
1051 bdrv_iterate_format(bdrv_format_print, NULL);
1052 fprintf(stderr, "\n");
1053 return NULL;
1055 drv = bdrv_find_whitelisted_format(buf);
1056 if (!drv) {
1057 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1058 return NULL;
1062 on_write_error = BLOCK_ERR_STOP_ENOSPC;
1063 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1064 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1065 fprintf(stderr, "werror is no supported by this format\n");
1066 return NULL;
1069 on_write_error = parse_block_error_action(buf, 0);
1070 if (on_write_error < 0) {
1071 return NULL;
1075 on_read_error = BLOCK_ERR_REPORT;
1076 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1077 if (type != IF_IDE && type != IF_VIRTIO) {
1078 fprintf(stderr, "rerror is no supported by this format\n");
1079 return NULL;
1082 on_read_error = parse_block_error_action(buf, 1);
1083 if (on_read_error < 0) {
1084 return NULL;
1088 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1089 if (type != IF_VIRTIO) {
1090 fprintf(stderr, "addr is not supported\n");
1091 return NULL;
1095 /* compute bus and unit according index */
1097 if (index != -1) {
1098 if (bus_id != 0 || unit_id != -1) {
1099 fprintf(stderr,
1100 "qemu: index cannot be used with bus and unit\n");
1101 return NULL;
1103 if (max_devs == 0)
1105 unit_id = index;
1106 bus_id = 0;
1107 } else {
1108 unit_id = index % max_devs;
1109 bus_id = index / max_devs;
1113 /* if user doesn't specify a unit_id,
1114 * try to find the first free
1117 if (unit_id == -1) {
1118 unit_id = 0;
1119 while (drive_get(type, bus_id, unit_id) != NULL) {
1120 unit_id++;
1121 if (max_devs && unit_id >= max_devs) {
1122 unit_id -= max_devs;
1123 bus_id++;
1128 /* check unit id */
1130 if (max_devs && unit_id >= max_devs) {
1131 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1132 unit_id, max_devs - 1);
1133 return NULL;
1137 * ignore multiple definitions
1140 if (drive_get(type, bus_id, unit_id) != NULL) {
1141 *fatal_error = 0;
1142 return NULL;
1145 /* init */
1147 dinfo = qemu_mallocz(sizeof(*dinfo));
1148 if ((buf = qemu_opts_id(opts)) != NULL) {
1149 dinfo->id = qemu_strdup(buf);
1150 } else {
1151 /* no id supplied -> create one */
1152 dinfo->id = qemu_mallocz(32);
1153 if (type == IF_IDE || type == IF_SCSI)
1154 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1155 if (max_devs)
1156 snprintf(dinfo->id, 32, "%s%i%s%i",
1157 devname, bus_id, mediastr, unit_id);
1158 else
1159 snprintf(dinfo->id, 32, "%s%s%i",
1160 devname, mediastr, unit_id);
1162 dinfo->bdrv = bdrv_new(dinfo->id);
1163 dinfo->devaddr = devaddr;
1164 dinfo->type = type;
1165 dinfo->bus = bus_id;
1166 dinfo->unit = unit_id;
1167 dinfo->on_read_error = on_read_error;
1168 dinfo->on_write_error = on_write_error;
1169 dinfo->opts = opts;
1170 if (serial)
1171 strncpy(dinfo->serial, serial, sizeof(serial));
1172 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1174 switch(type) {
1175 case IF_IDE:
1176 case IF_SCSI:
1177 case IF_XEN:
1178 case IF_NONE:
1179 switch(media) {
1180 case MEDIA_DISK:
1181 if (cyls != 0) {
1182 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1183 bdrv_set_translation_hint(dinfo->bdrv, translation);
1185 break;
1186 case MEDIA_CDROM:
1187 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1188 break;
1190 break;
1191 case IF_SD:
1192 /* FIXME: This isn't really a floppy, but it's a reasonable
1193 approximation. */
1194 case IF_FLOPPY:
1195 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1196 break;
1197 case IF_PFLASH:
1198 case IF_MTD:
1199 break;
1200 case IF_VIRTIO:
1201 /* add virtio block device */
1202 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1203 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1204 qemu_opt_set(opts, "drive", dinfo->id);
1205 if (devaddr)
1206 qemu_opt_set(opts, "addr", devaddr);
1207 break;
1208 case IF_COUNT:
1209 abort();
1211 if (!file) {
1212 *fatal_error = 0;
1213 return NULL;
1215 bdrv_flags = 0;
1216 if (snapshot) {
1217 bdrv_flags |= BDRV_O_SNAPSHOT;
1218 cache = 2; /* always use write-back with snapshot */
1220 if (cache == 0) /* no caching */
1221 bdrv_flags |= BDRV_O_NOCACHE;
1222 else if (cache == 2) /* write-back */
1223 bdrv_flags |= BDRV_O_CACHE_WB;
1225 if (aio == 1) {
1226 bdrv_flags |= BDRV_O_NATIVE_AIO;
1227 } else {
1228 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1231 if (ro == 1) {
1232 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1233 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1234 return NULL;
1238 * cdrom is read-only. Set it now, after above interface checking
1239 * since readonly attribute not explicitly required, so no error.
1241 if (media == MEDIA_CDROM) {
1242 ro = 1;
1244 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1246 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1247 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1248 file, strerror(errno));
1249 return NULL;
1252 if (bdrv_key_required(dinfo->bdrv))
1253 autostart = 0;
1254 *fatal_error = 0;
1255 return dinfo;
1258 static int drive_init_func(QemuOpts *opts, void *opaque)
1260 QEMUMachine *machine = opaque;
1261 int fatal_error = 0;
1263 if (drive_init(opts, machine, &fatal_error) == NULL) {
1264 if (fatal_error)
1265 return 1;
1267 return 0;
1270 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1272 if (NULL == qemu_opt_get(opts, "snapshot")) {
1273 qemu_opt_set(opts, "snapshot", "on");
1275 return 0;
1278 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1280 boot_set_handler = func;
1281 boot_set_opaque = opaque;
1284 int qemu_boot_set(const char *boot_devices)
1286 if (!boot_set_handler) {
1287 return -EINVAL;
1289 return boot_set_handler(boot_set_opaque, boot_devices);
1292 static int parse_bootdevices(char *devices)
1294 /* We just do some generic consistency checks */
1295 const char *p;
1296 int bitmap = 0;
1298 for (p = devices; *p != '\0'; p++) {
1299 /* Allowed boot devices are:
1300 * a-b: floppy disk drives
1301 * c-f: IDE disk drives
1302 * g-m: machine implementation dependant drives
1303 * n-p: network devices
1304 * It's up to each machine implementation to check if the given boot
1305 * devices match the actual hardware implementation and firmware
1306 * features.
1308 if (*p < 'a' || *p > 'p') {
1309 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1310 exit(1);
1312 if (bitmap & (1 << (*p - 'a'))) {
1313 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1314 exit(1);
1316 bitmap |= 1 << (*p - 'a');
1318 return bitmap;
1321 static void restore_boot_devices(void *opaque)
1323 char *standard_boot_devices = opaque;
1325 qemu_boot_set(standard_boot_devices);
1327 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1328 qemu_free(standard_boot_devices);
1331 static void numa_add(const char *optarg)
1333 char option[128];
1334 char *endptr;
1335 unsigned long long value, endvalue;
1336 int nodenr;
1338 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1339 if (!strcmp(option, "node")) {
1340 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1341 nodenr = nb_numa_nodes;
1342 } else {
1343 nodenr = strtoull(option, NULL, 10);
1346 if (get_param_value(option, 128, "mem", optarg) == 0) {
1347 node_mem[nodenr] = 0;
1348 } else {
1349 value = strtoull(option, &endptr, 0);
1350 switch (*endptr) {
1351 case 0: case 'M': case 'm':
1352 value <<= 20;
1353 break;
1354 case 'G': case 'g':
1355 value <<= 30;
1356 break;
1358 node_mem[nodenr] = value;
1360 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1361 node_cpumask[nodenr] = 0;
1362 } else {
1363 value = strtoull(option, &endptr, 10);
1364 if (value >= 64) {
1365 value = 63;
1366 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1367 } else {
1368 if (*endptr == '-') {
1369 endvalue = strtoull(endptr+1, &endptr, 10);
1370 if (endvalue >= 63) {
1371 endvalue = 62;
1372 fprintf(stderr,
1373 "only 63 CPUs in NUMA mode supported.\n");
1375 value = (2ULL << endvalue) - (1ULL << value);
1376 } else {
1377 value = 1ULL << value;
1380 node_cpumask[nodenr] = value;
1382 nb_numa_nodes++;
1384 return;
1387 static void smp_parse(const char *optarg)
1389 int smp, sockets = 0, threads = 0, cores = 0;
1390 char *endptr;
1391 char option[128];
1393 smp = strtoul(optarg, &endptr, 10);
1394 if (endptr != optarg) {
1395 if (*endptr == ',') {
1396 endptr++;
1399 if (get_param_value(option, 128, "sockets", endptr) != 0)
1400 sockets = strtoull(option, NULL, 10);
1401 if (get_param_value(option, 128, "cores", endptr) != 0)
1402 cores = strtoull(option, NULL, 10);
1403 if (get_param_value(option, 128, "threads", endptr) != 0)
1404 threads = strtoull(option, NULL, 10);
1405 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1406 max_cpus = strtoull(option, NULL, 10);
1408 /* compute missing values, prefer sockets over cores over threads */
1409 if (smp == 0 || sockets == 0) {
1410 sockets = sockets > 0 ? sockets : 1;
1411 cores = cores > 0 ? cores : 1;
1412 threads = threads > 0 ? threads : 1;
1413 if (smp == 0) {
1414 smp = cores * threads * sockets;
1416 } else {
1417 if (cores == 0) {
1418 threads = threads > 0 ? threads : 1;
1419 cores = smp / (sockets * threads);
1420 } else {
1421 if (sockets) {
1422 threads = smp / (cores * sockets);
1426 smp_cpus = smp;
1427 smp_cores = cores > 0 ? cores : 1;
1428 smp_threads = threads > 0 ? threads : 1;
1429 if (max_cpus == 0)
1430 max_cpus = smp_cpus;
1433 /***********************************************************/
1434 /* USB devices */
1436 static int usb_device_add(const char *devname, int is_hotplug)
1438 const char *p;
1439 USBDevice *dev = NULL;
1441 if (!usb_enabled)
1442 return -1;
1444 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1445 dev = usbdevice_create(devname);
1446 if (dev)
1447 goto done;
1449 /* the other ones */
1450 if (strstart(devname, "host:", &p)) {
1451 dev = usb_host_device_open(p);
1452 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1453 dev = usb_bt_init(devname[2] ? hci_init(p) :
1454 bt_new_hci(qemu_find_bt_vlan(0)));
1455 } else {
1456 return -1;
1458 if (!dev)
1459 return -1;
1461 done:
1462 return 0;
1465 static int usb_device_del(const char *devname)
1467 int bus_num, addr;
1468 const char *p;
1470 if (strstart(devname, "host:", &p))
1471 return usb_host_device_close(p);
1473 if (!usb_enabled)
1474 return -1;
1476 p = strchr(devname, '.');
1477 if (!p)
1478 return -1;
1479 bus_num = strtoul(devname, NULL, 0);
1480 addr = strtoul(p + 1, NULL, 0);
1482 return usb_device_delete_addr(bus_num, addr);
1485 static int usb_parse(const char *cmdline)
1487 int r;
1488 r = usb_device_add(cmdline, 0);
1489 if (r < 0) {
1490 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1492 return r;
1495 void do_usb_add(Monitor *mon, const QDict *qdict)
1497 const char *devname = qdict_get_str(qdict, "devname");
1498 if (usb_device_add(devname, 1) < 0) {
1499 error_report("could not add USB device '%s'", devname);
1503 void do_usb_del(Monitor *mon, const QDict *qdict)
1505 const char *devname = qdict_get_str(qdict, "devname");
1506 if (usb_device_del(devname) < 0) {
1507 error_report("could not delete USB device '%s'", devname);
1511 /***********************************************************/
1512 /* PCMCIA/Cardbus */
1514 static struct pcmcia_socket_entry_s {
1515 PCMCIASocket *socket;
1516 struct pcmcia_socket_entry_s *next;
1517 } *pcmcia_sockets = 0;
1519 void pcmcia_socket_register(PCMCIASocket *socket)
1521 struct pcmcia_socket_entry_s *entry;
1523 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1524 entry->socket = socket;
1525 entry->next = pcmcia_sockets;
1526 pcmcia_sockets = entry;
1529 void pcmcia_socket_unregister(PCMCIASocket *socket)
1531 struct pcmcia_socket_entry_s *entry, **ptr;
1533 ptr = &pcmcia_sockets;
1534 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1535 if (entry->socket == socket) {
1536 *ptr = entry->next;
1537 qemu_free(entry);
1541 void pcmcia_info(Monitor *mon)
1543 struct pcmcia_socket_entry_s *iter;
1545 if (!pcmcia_sockets)
1546 monitor_printf(mon, "No PCMCIA sockets\n");
1548 for (iter = pcmcia_sockets; iter; iter = iter->next)
1549 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1550 iter->socket->attached ? iter->socket->card_string :
1551 "Empty");
1554 /***********************************************************/
1555 /* I/O handling */
1557 typedef struct IOHandlerRecord {
1558 int fd;
1559 IOCanReadHandler *fd_read_poll;
1560 IOHandler *fd_read;
1561 IOHandler *fd_write;
1562 int deleted;
1563 void *opaque;
1564 /* temporary data */
1565 struct pollfd *ufd;
1566 QLIST_ENTRY(IOHandlerRecord) next;
1567 } IOHandlerRecord;
1569 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1570 QLIST_HEAD_INITIALIZER(io_handlers);
1573 /* XXX: fd_read_poll should be suppressed, but an API change is
1574 necessary in the character devices to suppress fd_can_read(). */
1575 int qemu_set_fd_handler2(int fd,
1576 IOCanReadHandler *fd_read_poll,
1577 IOHandler *fd_read,
1578 IOHandler *fd_write,
1579 void *opaque)
1581 IOHandlerRecord *ioh;
1583 if (!fd_read && !fd_write) {
1584 QLIST_FOREACH(ioh, &io_handlers, next) {
1585 if (ioh->fd == fd) {
1586 ioh->deleted = 1;
1587 break;
1590 } else {
1591 QLIST_FOREACH(ioh, &io_handlers, next) {
1592 if (ioh->fd == fd)
1593 goto found;
1595 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1596 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1597 found:
1598 ioh->fd = fd;
1599 ioh->fd_read_poll = fd_read_poll;
1600 ioh->fd_read = fd_read;
1601 ioh->fd_write = fd_write;
1602 ioh->opaque = opaque;
1603 ioh->deleted = 0;
1605 return 0;
1608 int qemu_set_fd_handler(int fd,
1609 IOHandler *fd_read,
1610 IOHandler *fd_write,
1611 void *opaque)
1613 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1616 #ifdef _WIN32
1617 /***********************************************************/
1618 /* Polling handling */
1620 typedef struct PollingEntry {
1621 PollingFunc *func;
1622 void *opaque;
1623 struct PollingEntry *next;
1624 } PollingEntry;
1626 static PollingEntry *first_polling_entry;
1628 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1630 PollingEntry **ppe, *pe;
1631 pe = qemu_mallocz(sizeof(PollingEntry));
1632 pe->func = func;
1633 pe->opaque = opaque;
1634 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1635 *ppe = pe;
1636 return 0;
1639 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1641 PollingEntry **ppe, *pe;
1642 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1643 pe = *ppe;
1644 if (pe->func == func && pe->opaque == opaque) {
1645 *ppe = pe->next;
1646 qemu_free(pe);
1647 break;
1652 /***********************************************************/
1653 /* Wait objects support */
1654 typedef struct WaitObjects {
1655 int num;
1656 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1657 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1658 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1659 } WaitObjects;
1661 static WaitObjects wait_objects = {0};
1663 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1665 WaitObjects *w = &wait_objects;
1667 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1668 return -1;
1669 w->events[w->num] = handle;
1670 w->func[w->num] = func;
1671 w->opaque[w->num] = opaque;
1672 w->num++;
1673 return 0;
1676 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1678 int i, found;
1679 WaitObjects *w = &wait_objects;
1681 found = 0;
1682 for (i = 0; i < w->num; i++) {
1683 if (w->events[i] == handle)
1684 found = 1;
1685 if (found) {
1686 w->events[i] = w->events[i + 1];
1687 w->func[i] = w->func[i + 1];
1688 w->opaque[i] = w->opaque[i + 1];
1691 if (found)
1692 w->num--;
1694 #endif
1696 /***********************************************************/
1697 /* ram save/restore */
1699 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
1700 #define RAM_SAVE_FLAG_COMPRESS 0x02
1701 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
1702 #define RAM_SAVE_FLAG_PAGE 0x08
1703 #define RAM_SAVE_FLAG_EOS 0x10
1705 static int is_dup_page(uint8_t *page, uint8_t ch)
1707 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1708 uint32_t *array = (uint32_t *)page;
1709 int i;
1711 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1712 if (array[i] != val)
1713 return 0;
1716 return 1;
1719 static int ram_save_block(QEMUFile *f)
1721 static ram_addr_t current_addr = 0;
1722 ram_addr_t saved_addr = current_addr;
1723 ram_addr_t addr = 0;
1724 int found = 0;
1726 while (addr < last_ram_offset) {
1727 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1728 uint8_t *p;
1730 cpu_physical_memory_reset_dirty(current_addr,
1731 current_addr + TARGET_PAGE_SIZE,
1732 MIGRATION_DIRTY_FLAG);
1734 p = qemu_get_ram_ptr(current_addr);
1736 if (is_dup_page(p, *p)) {
1737 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1738 qemu_put_byte(f, *p);
1739 } else {
1740 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1741 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1744 found = 1;
1745 break;
1747 addr += TARGET_PAGE_SIZE;
1748 current_addr = (saved_addr + addr) % last_ram_offset;
1751 return found;
1754 static uint64_t bytes_transferred;
1756 static ram_addr_t ram_save_remaining(void)
1758 ram_addr_t addr;
1759 ram_addr_t count = 0;
1761 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1762 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1763 count++;
1766 return count;
1769 uint64_t ram_bytes_remaining(void)
1771 return ram_save_remaining() * TARGET_PAGE_SIZE;
1774 uint64_t ram_bytes_transferred(void)
1776 return bytes_transferred;
1779 uint64_t ram_bytes_total(void)
1781 return last_ram_offset;
1784 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1786 ram_addr_t addr;
1787 uint64_t bytes_transferred_last;
1788 double bwidth = 0;
1789 uint64_t expected_time = 0;
1791 if (stage < 0) {
1792 cpu_physical_memory_set_dirty_tracking(0);
1793 return 0;
1796 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1797 qemu_file_set_error(f);
1798 return 0;
1801 if (stage == 1) {
1802 bytes_transferred = 0;
1804 /* Make sure all dirty bits are set */
1805 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1806 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1807 cpu_physical_memory_set_dirty(addr);
1810 /* Enable dirty memory tracking */
1811 cpu_physical_memory_set_dirty_tracking(1);
1813 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1816 bytes_transferred_last = bytes_transferred;
1817 bwidth = qemu_get_clock_ns(rt_clock);
1819 while (!qemu_file_rate_limit(f)) {
1820 int ret;
1822 ret = ram_save_block(f);
1823 bytes_transferred += ret * TARGET_PAGE_SIZE;
1824 if (ret == 0) /* no more blocks */
1825 break;
1828 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1829 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1831 /* if we haven't transferred anything this round, force expected_time to a
1832 * a very high value, but without crashing */
1833 if (bwidth == 0)
1834 bwidth = 0.000001;
1836 /* try transferring iterative blocks of memory */
1837 if (stage == 3) {
1838 /* flush all remaining blocks regardless of rate limiting */
1839 while (ram_save_block(f) != 0) {
1840 bytes_transferred += TARGET_PAGE_SIZE;
1842 cpu_physical_memory_set_dirty_tracking(0);
1845 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1847 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1849 return (stage == 2) && (expected_time <= migrate_max_downtime());
1852 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1854 ram_addr_t addr;
1855 int flags;
1857 if (version_id != 3)
1858 return -EINVAL;
1860 do {
1861 addr = qemu_get_be64(f);
1863 flags = addr & ~TARGET_PAGE_MASK;
1864 addr &= TARGET_PAGE_MASK;
1866 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1867 if (addr != last_ram_offset)
1868 return -EINVAL;
1871 if (flags & RAM_SAVE_FLAG_COMPRESS) {
1872 uint8_t ch = qemu_get_byte(f);
1873 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1874 #ifndef _WIN32
1875 if (ch == 0 &&
1876 (!kvm_enabled() || kvm_has_sync_mmu())) {
1877 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1879 #endif
1880 } else if (flags & RAM_SAVE_FLAG_PAGE) {
1881 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1883 if (qemu_file_has_error(f)) {
1884 return -EIO;
1886 } while (!(flags & RAM_SAVE_FLAG_EOS));
1888 return 0;
1891 void qemu_service_io(void)
1893 qemu_notify_event();
1896 /***********************************************************/
1897 /* machine registration */
1899 static QEMUMachine *first_machine = NULL;
1900 QEMUMachine *current_machine = NULL;
1902 int qemu_register_machine(QEMUMachine *m)
1904 QEMUMachine **pm;
1905 pm = &first_machine;
1906 while (*pm != NULL)
1907 pm = &(*pm)->next;
1908 m->next = NULL;
1909 *pm = m;
1910 return 0;
1913 static QEMUMachine *find_machine(const char *name)
1915 QEMUMachine *m;
1917 for(m = first_machine; m != NULL; m = m->next) {
1918 if (!strcmp(m->name, name))
1919 return m;
1920 if (m->alias && !strcmp(m->alias, name))
1921 return m;
1923 return NULL;
1926 static QEMUMachine *find_default_machine(void)
1928 QEMUMachine *m;
1930 for(m = first_machine; m != NULL; m = m->next) {
1931 if (m->is_default) {
1932 return m;
1935 return NULL;
1938 /***********************************************************/
1939 /* main execution loop */
1941 static void gui_update(void *opaque)
1943 uint64_t interval = GUI_REFRESH_INTERVAL;
1944 DisplayState *ds = opaque;
1945 DisplayChangeListener *dcl = ds->listeners;
1947 qemu_flush_coalesced_mmio_buffer();
1948 dpy_refresh(ds);
1950 while (dcl != NULL) {
1951 if (dcl->gui_timer_interval &&
1952 dcl->gui_timer_interval < interval)
1953 interval = dcl->gui_timer_interval;
1954 dcl = dcl->next;
1956 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1959 static void nographic_update(void *opaque)
1961 uint64_t interval = GUI_REFRESH_INTERVAL;
1963 qemu_flush_coalesced_mmio_buffer();
1964 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1967 void cpu_synchronize_all_states(void)
1969 CPUState *cpu;
1971 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1972 cpu_synchronize_state(cpu);
1976 void cpu_synchronize_all_post_reset(void)
1978 CPUState *cpu;
1980 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1981 cpu_synchronize_post_reset(cpu);
1985 void cpu_synchronize_all_post_init(void)
1987 CPUState *cpu;
1989 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1990 cpu_synchronize_post_init(cpu);
1994 struct vm_change_state_entry {
1995 VMChangeStateHandler *cb;
1996 void *opaque;
1997 QLIST_ENTRY (vm_change_state_entry) entries;
2000 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
2002 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
2003 void *opaque)
2005 VMChangeStateEntry *e;
2007 e = qemu_mallocz(sizeof (*e));
2009 e->cb = cb;
2010 e->opaque = opaque;
2011 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
2012 return e;
2015 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
2017 QLIST_REMOVE (e, entries);
2018 qemu_free (e);
2021 static void vm_state_notify(int running, int reason)
2023 VMChangeStateEntry *e;
2025 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
2026 e->cb(e->opaque, running, reason);
2030 static void resume_all_vcpus(void);
2031 static void pause_all_vcpus(void);
2033 void vm_start(void)
2035 if (!vm_running) {
2036 cpu_enable_ticks();
2037 vm_running = 1;
2038 vm_state_notify(1, 0);
2039 resume_all_vcpus();
2043 /* reset/shutdown handler */
2045 typedef struct QEMUResetEntry {
2046 QTAILQ_ENTRY(QEMUResetEntry) entry;
2047 QEMUResetHandler *func;
2048 void *opaque;
2049 } QEMUResetEntry;
2051 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
2052 QTAILQ_HEAD_INITIALIZER(reset_handlers);
2053 static int reset_requested;
2054 static int shutdown_requested;
2055 static int powerdown_requested;
2056 static int debug_requested;
2057 static int vmstop_requested;
2059 int qemu_shutdown_requested(void)
2061 int r = shutdown_requested;
2062 shutdown_requested = 0;
2063 return r;
2066 int qemu_reset_requested(void)
2068 int r = reset_requested;
2069 reset_requested = 0;
2070 return r;
2073 int qemu_powerdown_requested(void)
2075 int r = powerdown_requested;
2076 powerdown_requested = 0;
2077 return r;
2080 static int qemu_debug_requested(void)
2082 int r = debug_requested;
2083 debug_requested = 0;
2084 return r;
2087 static int qemu_vmstop_requested(void)
2089 int r = vmstop_requested;
2090 vmstop_requested = 0;
2091 return r;
2094 static void do_vm_stop(int reason)
2096 if (vm_running) {
2097 cpu_disable_ticks();
2098 vm_running = 0;
2099 pause_all_vcpus();
2100 vm_state_notify(0, reason);
2101 monitor_protocol_event(QEVENT_STOP, NULL);
2105 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2107 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2109 re->func = func;
2110 re->opaque = opaque;
2111 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2114 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2116 QEMUResetEntry *re;
2118 QTAILQ_FOREACH(re, &reset_handlers, entry) {
2119 if (re->func == func && re->opaque == opaque) {
2120 QTAILQ_REMOVE(&reset_handlers, re, entry);
2121 qemu_free(re);
2122 return;
2127 void qemu_system_reset(void)
2129 QEMUResetEntry *re, *nre;
2131 /* reset all devices */
2132 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2133 re->func(re->opaque);
2135 monitor_protocol_event(QEVENT_RESET, NULL);
2136 cpu_synchronize_all_post_reset();
2139 void qemu_system_reset_request(void)
2141 if (no_reboot) {
2142 shutdown_requested = 1;
2143 } else {
2144 reset_requested = 1;
2146 qemu_notify_event();
2149 void qemu_system_shutdown_request(void)
2151 shutdown_requested = 1;
2152 qemu_notify_event();
2155 void qemu_system_powerdown_request(void)
2157 powerdown_requested = 1;
2158 qemu_notify_event();
2161 static int cpu_can_run(CPUState *env)
2163 if (env->stop)
2164 return 0;
2165 if (env->stopped)
2166 return 0;
2167 if (!vm_running)
2168 return 0;
2169 return 1;
2172 static int cpu_has_work(CPUState *env)
2174 if (env->stop)
2175 return 1;
2176 if (env->stopped)
2177 return 0;
2178 if (!env->halted)
2179 return 1;
2180 if (qemu_cpu_has_work(env))
2181 return 1;
2182 return 0;
2185 static int tcg_has_work(void)
2187 CPUState *env;
2189 for (env = first_cpu; env != NULL; env = env->next_cpu)
2190 if (cpu_has_work(env))
2191 return 1;
2192 return 0;
2195 #ifndef _WIN32
2196 static int io_thread_fd = -1;
2198 static void qemu_event_increment(void)
2200 /* Write 8 bytes to be compatible with eventfd. */
2201 static uint64_t val = 1;
2202 ssize_t ret;
2204 if (io_thread_fd == -1)
2205 return;
2207 do {
2208 ret = write(io_thread_fd, &val, sizeof(val));
2209 } while (ret < 0 && errno == EINTR);
2211 /* EAGAIN is fine, a read must be pending. */
2212 if (ret < 0 && errno != EAGAIN) {
2213 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
2214 strerror(errno));
2215 exit (1);
2219 static void qemu_event_read(void *opaque)
2221 int fd = (unsigned long)opaque;
2222 ssize_t len;
2223 char buffer[512];
2225 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
2226 do {
2227 len = read(fd, buffer, sizeof(buffer));
2228 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
2231 static int qemu_event_init(void)
2233 int err;
2234 int fds[2];
2236 err = qemu_eventfd(fds);
2237 if (err == -1)
2238 return -errno;
2240 err = fcntl_setfl(fds[0], O_NONBLOCK);
2241 if (err < 0)
2242 goto fail;
2244 err = fcntl_setfl(fds[1], O_NONBLOCK);
2245 if (err < 0)
2246 goto fail;
2248 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
2249 (void *)(unsigned long)fds[0]);
2251 io_thread_fd = fds[1];
2252 return 0;
2254 fail:
2255 close(fds[0]);
2256 close(fds[1]);
2257 return err;
2259 #else
2260 HANDLE qemu_event_handle;
2262 static void dummy_event_handler(void *opaque)
2266 static int qemu_event_init(void)
2268 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
2269 if (!qemu_event_handle) {
2270 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
2271 return -1;
2273 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
2274 return 0;
2277 static void qemu_event_increment(void)
2279 if (!SetEvent(qemu_event_handle)) {
2280 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
2281 GetLastError());
2282 exit (1);
2285 #endif
2287 #ifndef CONFIG_IOTHREAD
2288 static int qemu_init_main_loop(void)
2290 return qemu_event_init();
2293 void qemu_init_vcpu(void *_env)
2295 CPUState *env = _env;
2297 env->nr_cores = smp_cores;
2298 env->nr_threads = smp_threads;
2299 if (kvm_enabled())
2300 kvm_init_vcpu(env);
2301 return;
2304 int qemu_cpu_self(void *env)
2306 return 1;
2309 static void resume_all_vcpus(void)
2313 static void pause_all_vcpus(void)
2317 void qemu_cpu_kick(void *env)
2319 return;
2322 void qemu_notify_event(void)
2324 CPUState *env = cpu_single_env;
2326 qemu_event_increment ();
2327 if (env) {
2328 cpu_exit(env);
2330 if (next_cpu && env != next_cpu) {
2331 cpu_exit(next_cpu);
2335 void qemu_mutex_lock_iothread(void) {}
2336 void qemu_mutex_unlock_iothread(void) {}
2338 void vm_stop(int reason)
2340 do_vm_stop(reason);
2343 #else /* CONFIG_IOTHREAD */
2345 #include "qemu-thread.h"
2347 QemuMutex qemu_global_mutex;
2348 static QemuMutex qemu_fair_mutex;
2350 static QemuThread io_thread;
2352 static QemuThread *tcg_cpu_thread;
2353 static QemuCond *tcg_halt_cond;
2355 static int qemu_system_ready;
2356 /* cpu creation */
2357 static QemuCond qemu_cpu_cond;
2358 /* system init */
2359 static QemuCond qemu_system_cond;
2360 static QemuCond qemu_pause_cond;
2362 static void tcg_block_io_signals(void);
2363 static void kvm_block_io_signals(CPUState *env);
2364 static void unblock_io_signals(void);
2366 static int qemu_init_main_loop(void)
2368 int ret;
2370 ret = qemu_event_init();
2371 if (ret)
2372 return ret;
2374 qemu_cond_init(&qemu_pause_cond);
2375 qemu_mutex_init(&qemu_fair_mutex);
2376 qemu_mutex_init(&qemu_global_mutex);
2377 qemu_mutex_lock(&qemu_global_mutex);
2379 unblock_io_signals();
2380 qemu_thread_self(&io_thread);
2382 return 0;
2385 static void qemu_wait_io_event_common(CPUState *env)
2387 if (env->stop) {
2388 env->stop = 0;
2389 env->stopped = 1;
2390 qemu_cond_signal(&qemu_pause_cond);
2394 static void qemu_wait_io_event(CPUState *env)
2396 while (!tcg_has_work())
2397 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2399 qemu_mutex_unlock(&qemu_global_mutex);
2402 * Users of qemu_global_mutex can be starved, having no chance
2403 * to acquire it since this path will get to it first.
2404 * So use another lock to provide fairness.
2406 qemu_mutex_lock(&qemu_fair_mutex);
2407 qemu_mutex_unlock(&qemu_fair_mutex);
2409 qemu_mutex_lock(&qemu_global_mutex);
2410 qemu_wait_io_event_common(env);
2413 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
2415 struct timespec ts;
2416 int r, e;
2417 siginfo_t siginfo;
2418 sigset_t waitset;
2420 ts.tv_sec = timeout / 1000;
2421 ts.tv_nsec = (timeout % 1000) * 1000000;
2423 sigemptyset(&waitset);
2424 sigaddset(&waitset, SIG_IPI);
2426 qemu_mutex_unlock(&qemu_global_mutex);
2427 r = sigtimedwait(&waitset, &siginfo, &ts);
2428 e = errno;
2429 qemu_mutex_lock(&qemu_global_mutex);
2431 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
2432 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
2433 exit(1);
2437 static void qemu_kvm_wait_io_event(CPUState *env)
2439 while (!cpu_has_work(env))
2440 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2442 qemu_kvm_eat_signal(env, 0);
2443 qemu_wait_io_event_common(env);
2446 static int qemu_cpu_exec(CPUState *env);
2448 static void *kvm_cpu_thread_fn(void *arg)
2450 CPUState *env = arg;
2452 qemu_thread_self(env->thread);
2453 if (kvm_enabled())
2454 kvm_init_vcpu(env);
2456 kvm_block_io_signals(env);
2458 /* signal CPU creation */
2459 qemu_mutex_lock(&qemu_global_mutex);
2460 env->created = 1;
2461 qemu_cond_signal(&qemu_cpu_cond);
2463 /* and wait for machine initialization */
2464 while (!qemu_system_ready)
2465 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2467 while (1) {
2468 if (cpu_can_run(env))
2469 qemu_cpu_exec(env);
2470 qemu_kvm_wait_io_event(env);
2473 return NULL;
2476 static bool tcg_cpu_exec(void);
2478 static void *tcg_cpu_thread_fn(void *arg)
2480 CPUState *env = arg;
2482 tcg_block_io_signals();
2483 qemu_thread_self(env->thread);
2485 /* signal CPU creation */
2486 qemu_mutex_lock(&qemu_global_mutex);
2487 for (env = first_cpu; env != NULL; env = env->next_cpu)
2488 env->created = 1;
2489 qemu_cond_signal(&qemu_cpu_cond);
2491 /* and wait for machine initialization */
2492 while (!qemu_system_ready)
2493 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2495 while (1) {
2496 tcg_cpu_exec();
2497 qemu_wait_io_event(cur_cpu);
2500 return NULL;
2503 void qemu_cpu_kick(void *_env)
2505 CPUState *env = _env;
2506 qemu_cond_broadcast(env->halt_cond);
2507 if (kvm_enabled())
2508 qemu_thread_signal(env->thread, SIG_IPI);
2511 int qemu_cpu_self(void *_env)
2513 CPUState *env = _env;
2514 QemuThread this;
2516 qemu_thread_self(&this);
2518 return qemu_thread_equal(&this, env->thread);
2521 static void cpu_signal(int sig)
2523 if (cpu_single_env)
2524 cpu_exit(cpu_single_env);
2527 static void tcg_block_io_signals(void)
2529 sigset_t set;
2530 struct sigaction sigact;
2532 sigemptyset(&set);
2533 sigaddset(&set, SIGUSR2);
2534 sigaddset(&set, SIGIO);
2535 sigaddset(&set, SIGALRM);
2536 sigaddset(&set, SIGCHLD);
2537 pthread_sigmask(SIG_BLOCK, &set, NULL);
2539 sigemptyset(&set);
2540 sigaddset(&set, SIG_IPI);
2541 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2543 memset(&sigact, 0, sizeof(sigact));
2544 sigact.sa_handler = cpu_signal;
2545 sigaction(SIG_IPI, &sigact, NULL);
2548 static void dummy_signal(int sig)
2552 static void kvm_block_io_signals(CPUState *env)
2554 int r;
2555 sigset_t set;
2556 struct sigaction sigact;
2558 sigemptyset(&set);
2559 sigaddset(&set, SIGUSR2);
2560 sigaddset(&set, SIGIO);
2561 sigaddset(&set, SIGALRM);
2562 sigaddset(&set, SIGCHLD);
2563 sigaddset(&set, SIG_IPI);
2564 pthread_sigmask(SIG_BLOCK, &set, NULL);
2566 pthread_sigmask(SIG_BLOCK, NULL, &set);
2567 sigdelset(&set, SIG_IPI);
2569 memset(&sigact, 0, sizeof(sigact));
2570 sigact.sa_handler = dummy_signal;
2571 sigaction(SIG_IPI, &sigact, NULL);
2573 r = kvm_set_signal_mask(env, &set);
2574 if (r) {
2575 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
2576 exit(1);
2580 static void unblock_io_signals(void)
2582 sigset_t set;
2584 sigemptyset(&set);
2585 sigaddset(&set, SIGUSR2);
2586 sigaddset(&set, SIGIO);
2587 sigaddset(&set, SIGALRM);
2588 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2590 sigemptyset(&set);
2591 sigaddset(&set, SIG_IPI);
2592 pthread_sigmask(SIG_BLOCK, &set, NULL);
2595 static void qemu_signal_lock(unsigned int msecs)
2597 qemu_mutex_lock(&qemu_fair_mutex);
2599 while (qemu_mutex_trylock(&qemu_global_mutex)) {
2600 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
2601 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
2602 break;
2604 qemu_mutex_unlock(&qemu_fair_mutex);
2607 void qemu_mutex_lock_iothread(void)
2609 if (kvm_enabled()) {
2610 qemu_mutex_lock(&qemu_fair_mutex);
2611 qemu_mutex_lock(&qemu_global_mutex);
2612 qemu_mutex_unlock(&qemu_fair_mutex);
2613 } else
2614 qemu_signal_lock(100);
2617 void qemu_mutex_unlock_iothread(void)
2619 qemu_mutex_unlock(&qemu_global_mutex);
2622 static int all_vcpus_paused(void)
2624 CPUState *penv = first_cpu;
2626 while (penv) {
2627 if (!penv->stopped)
2628 return 0;
2629 penv = (CPUState *)penv->next_cpu;
2632 return 1;
2635 static void pause_all_vcpus(void)
2637 CPUState *penv = first_cpu;
2639 while (penv) {
2640 penv->stop = 1;
2641 qemu_thread_signal(penv->thread, SIG_IPI);
2642 qemu_cpu_kick(penv);
2643 penv = (CPUState *)penv->next_cpu;
2646 while (!all_vcpus_paused()) {
2647 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
2648 penv = first_cpu;
2649 while (penv) {
2650 qemu_thread_signal(penv->thread, SIG_IPI);
2651 penv = (CPUState *)penv->next_cpu;
2656 static void resume_all_vcpus(void)
2658 CPUState *penv = first_cpu;
2660 while (penv) {
2661 penv->stop = 0;
2662 penv->stopped = 0;
2663 qemu_thread_signal(penv->thread, SIG_IPI);
2664 qemu_cpu_kick(penv);
2665 penv = (CPUState *)penv->next_cpu;
2669 static void tcg_init_vcpu(void *_env)
2671 CPUState *env = _env;
2672 /* share a single thread for all cpus with TCG */
2673 if (!tcg_cpu_thread) {
2674 env->thread = qemu_mallocz(sizeof(QemuThread));
2675 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2676 qemu_cond_init(env->halt_cond);
2677 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
2678 while (env->created == 0)
2679 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2680 tcg_cpu_thread = env->thread;
2681 tcg_halt_cond = env->halt_cond;
2682 } else {
2683 env->thread = tcg_cpu_thread;
2684 env->halt_cond = tcg_halt_cond;
2688 static void kvm_start_vcpu(CPUState *env)
2690 env->thread = qemu_mallocz(sizeof(QemuThread));
2691 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2692 qemu_cond_init(env->halt_cond);
2693 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
2694 while (env->created == 0)
2695 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2698 void qemu_init_vcpu(void *_env)
2700 CPUState *env = _env;
2702 env->nr_cores = smp_cores;
2703 env->nr_threads = smp_threads;
2704 if (kvm_enabled())
2705 kvm_start_vcpu(env);
2706 else
2707 tcg_init_vcpu(env);
2710 void qemu_notify_event(void)
2712 qemu_event_increment();
2715 static void qemu_system_vmstop_request(int reason)
2717 vmstop_requested = reason;
2718 qemu_notify_event();
2721 void vm_stop(int reason)
2723 QemuThread me;
2724 qemu_thread_self(&me);
2726 if (!qemu_thread_equal(&me, &io_thread)) {
2727 qemu_system_vmstop_request(reason);
2729 * FIXME: should not return to device code in case
2730 * vm_stop() has been requested.
2732 if (cpu_single_env) {
2733 cpu_exit(cpu_single_env);
2734 cpu_single_env->stop = 1;
2736 return;
2738 do_vm_stop(reason);
2741 #endif
2744 #ifdef _WIN32
2745 static void host_main_loop_wait(int *timeout)
2747 int ret, ret2, i;
2748 PollingEntry *pe;
2751 /* XXX: need to suppress polling by better using win32 events */
2752 ret = 0;
2753 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2754 ret |= pe->func(pe->opaque);
2756 if (ret == 0) {
2757 int err;
2758 WaitObjects *w = &wait_objects;
2760 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2761 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2762 if (w->func[ret - WAIT_OBJECT_0])
2763 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2765 /* Check for additional signaled events */
2766 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2768 /* Check if event is signaled */
2769 ret2 = WaitForSingleObject(w->events[i], 0);
2770 if(ret2 == WAIT_OBJECT_0) {
2771 if (w->func[i])
2772 w->func[i](w->opaque[i]);
2773 } else if (ret2 == WAIT_TIMEOUT) {
2774 } else {
2775 err = GetLastError();
2776 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2779 } else if (ret == WAIT_TIMEOUT) {
2780 } else {
2781 err = GetLastError();
2782 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2786 *timeout = 0;
2788 #else
2789 static void host_main_loop_wait(int *timeout)
2792 #endif
2794 void main_loop_wait(int nonblocking)
2796 IOHandlerRecord *ioh;
2797 fd_set rfds, wfds, xfds;
2798 int ret, nfds;
2799 struct timeval tv;
2800 int timeout;
2802 if (nonblocking)
2803 timeout = 0;
2804 else {
2805 timeout = qemu_calculate_timeout();
2806 qemu_bh_update_timeout(&timeout);
2809 host_main_loop_wait(&timeout);
2811 /* poll any events */
2812 /* XXX: separate device handlers from system ones */
2813 nfds = -1;
2814 FD_ZERO(&rfds);
2815 FD_ZERO(&wfds);
2816 FD_ZERO(&xfds);
2817 QLIST_FOREACH(ioh, &io_handlers, next) {
2818 if (ioh->deleted)
2819 continue;
2820 if (ioh->fd_read &&
2821 (!ioh->fd_read_poll ||
2822 ioh->fd_read_poll(ioh->opaque) != 0)) {
2823 FD_SET(ioh->fd, &rfds);
2824 if (ioh->fd > nfds)
2825 nfds = ioh->fd;
2827 if (ioh->fd_write) {
2828 FD_SET(ioh->fd, &wfds);
2829 if (ioh->fd > nfds)
2830 nfds = ioh->fd;
2834 tv.tv_sec = timeout / 1000;
2835 tv.tv_usec = (timeout % 1000) * 1000;
2837 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2839 qemu_mutex_unlock_iothread();
2840 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2841 qemu_mutex_lock_iothread();
2842 if (ret > 0) {
2843 IOHandlerRecord *pioh;
2845 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
2846 if (ioh->deleted) {
2847 QLIST_REMOVE(ioh, next);
2848 qemu_free(ioh);
2849 continue;
2851 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2852 ioh->fd_read(ioh->opaque);
2854 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2855 ioh->fd_write(ioh->opaque);
2860 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2862 qemu_run_all_timers();
2864 /* Check bottom-halves last in case any of the earlier events triggered
2865 them. */
2866 qemu_bh_poll();
2870 static int qemu_cpu_exec(CPUState *env)
2872 int ret;
2873 #ifdef CONFIG_PROFILER
2874 int64_t ti;
2875 #endif
2877 #ifdef CONFIG_PROFILER
2878 ti = profile_getclock();
2879 #endif
2880 if (use_icount) {
2881 int64_t count;
2882 int decr;
2883 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
2884 env->icount_decr.u16.low = 0;
2885 env->icount_extra = 0;
2886 count = qemu_icount_round (qemu_next_deadline());
2887 qemu_icount += count;
2888 decr = (count > 0xffff) ? 0xffff : count;
2889 count -= decr;
2890 env->icount_decr.u16.low = decr;
2891 env->icount_extra = count;
2893 ret = cpu_exec(env);
2894 #ifdef CONFIG_PROFILER
2895 qemu_time += profile_getclock() - ti;
2896 #endif
2897 if (use_icount) {
2898 /* Fold pending instructions back into the
2899 instruction counter, and clear the interrupt flag. */
2900 qemu_icount -= (env->icount_decr.u16.low
2901 + env->icount_extra);
2902 env->icount_decr.u32 = 0;
2903 env->icount_extra = 0;
2905 return ret;
2908 static bool tcg_cpu_exec(void)
2910 int ret = 0;
2912 if (next_cpu == NULL)
2913 next_cpu = first_cpu;
2914 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
2915 CPUState *env = cur_cpu = next_cpu;
2917 qemu_clock_enable(vm_clock,
2918 (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
2920 if (qemu_alarm_pending())
2921 break;
2922 if (cpu_can_run(env))
2923 ret = qemu_cpu_exec(env);
2924 else if (env->stop)
2925 break;
2927 if (ret == EXCP_DEBUG) {
2928 gdb_set_stop_cpu(env);
2929 debug_requested = 1;
2930 break;
2933 return tcg_has_work();
2936 static int vm_can_run(void)
2938 if (powerdown_requested)
2939 return 0;
2940 if (reset_requested)
2941 return 0;
2942 if (shutdown_requested)
2943 return 0;
2944 if (debug_requested)
2945 return 0;
2946 return 1;
2949 qemu_irq qemu_system_powerdown;
2951 static void main_loop(void)
2953 int r;
2955 #ifdef CONFIG_IOTHREAD
2956 qemu_system_ready = 1;
2957 qemu_cond_broadcast(&qemu_system_cond);
2958 #endif
2960 for (;;) {
2961 do {
2962 bool nonblocking = false;
2963 #ifdef CONFIG_PROFILER
2964 int64_t ti;
2965 #endif
2966 #ifndef CONFIG_IOTHREAD
2967 nonblocking = tcg_cpu_exec();
2968 #endif
2969 #ifdef CONFIG_PROFILER
2970 ti = profile_getclock();
2971 #endif
2972 main_loop_wait(nonblocking);
2973 #ifdef CONFIG_PROFILER
2974 dev_time += profile_getclock() - ti;
2975 #endif
2976 } while (vm_can_run());
2978 if (qemu_debug_requested()) {
2979 vm_stop(EXCP_DEBUG);
2981 if (qemu_shutdown_requested()) {
2982 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2983 if (no_shutdown) {
2984 vm_stop(0);
2985 no_shutdown = 0;
2986 } else
2987 break;
2989 if (qemu_reset_requested()) {
2990 pause_all_vcpus();
2991 qemu_system_reset();
2992 resume_all_vcpus();
2994 if (qemu_powerdown_requested()) {
2995 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
2996 qemu_irq_raise(qemu_system_powerdown);
2998 if ((r = qemu_vmstop_requested())) {
2999 vm_stop(r);
3002 pause_all_vcpus();
3005 static void version(void)
3007 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3010 static void help(int exitcode)
3012 const char *options_help =
3013 #define DEF(option, opt_arg, opt_enum, opt_help) \
3014 opt_help
3015 #define DEFHEADING(text) stringify(text) "\n"
3016 #include "qemu-options.h"
3017 #undef DEF
3018 #undef DEFHEADING
3019 #undef GEN_DOCS
3021 version();
3022 printf("usage: %s [options] [disk_image]\n"
3023 "\n"
3024 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3025 "\n"
3026 "%s\n"
3027 "During emulation, the following keys are useful:\n"
3028 "ctrl-alt-f toggle full screen\n"
3029 "ctrl-alt-n switch to virtual console 'n'\n"
3030 "ctrl-alt toggle mouse and keyboard grab\n"
3031 "\n"
3032 "When using -nographic, press 'ctrl-a h' to get some help.\n",
3033 "qemu",
3034 options_help);
3035 exit(exitcode);
3038 #define HAS_ARG 0x0001
3040 enum {
3041 #define DEF(option, opt_arg, opt_enum, opt_help) \
3042 opt_enum,
3043 #define DEFHEADING(text)
3044 #include "qemu-options.h"
3045 #undef DEF
3046 #undef DEFHEADING
3047 #undef GEN_DOCS
3050 typedef struct QEMUOption {
3051 const char *name;
3052 int flags;
3053 int index;
3054 } QEMUOption;
3056 static const QEMUOption qemu_options[] = {
3057 { "h", 0, QEMU_OPTION_h },
3058 #define DEF(option, opt_arg, opt_enum, opt_help) \
3059 { option, opt_arg, opt_enum },
3060 #define DEFHEADING(text)
3061 #include "qemu-options.h"
3062 #undef DEF
3063 #undef DEFHEADING
3064 #undef GEN_DOCS
3065 { NULL },
3068 #ifdef HAS_AUDIO
3069 struct soundhw soundhw[] = {
3070 #ifdef HAS_AUDIO_CHOICE
3071 #if defined(TARGET_I386) || defined(TARGET_MIPS)
3073 "pcspk",
3074 "PC speaker",
3077 { .init_isa = pcspk_audio_init }
3079 #endif
3081 #ifdef CONFIG_SB16
3083 "sb16",
3084 "Creative Sound Blaster 16",
3087 { .init_isa = SB16_init }
3089 #endif
3091 #ifdef CONFIG_CS4231A
3093 "cs4231a",
3094 "CS4231A",
3097 { .init_isa = cs4231a_init }
3099 #endif
3101 #ifdef CONFIG_ADLIB
3103 "adlib",
3104 #ifdef HAS_YMF262
3105 "Yamaha YMF262 (OPL3)",
3106 #else
3107 "Yamaha YM3812 (OPL2)",
3108 #endif
3111 { .init_isa = Adlib_init }
3113 #endif
3115 #ifdef CONFIG_GUS
3117 "gus",
3118 "Gravis Ultrasound GF1",
3121 { .init_isa = GUS_init }
3123 #endif
3125 #ifdef CONFIG_AC97
3127 "ac97",
3128 "Intel 82801AA AC97 Audio",
3131 { .init_pci = ac97_init }
3133 #endif
3135 #ifdef CONFIG_ES1370
3137 "es1370",
3138 "ENSONIQ AudioPCI ES1370",
3141 { .init_pci = es1370_init }
3143 #endif
3145 #endif /* HAS_AUDIO_CHOICE */
3147 { NULL, NULL, 0, 0, { NULL } }
3150 static void select_soundhw (const char *optarg)
3152 struct soundhw *c;
3154 if (*optarg == '?') {
3155 show_valid_cards:
3157 printf ("Valid sound card names (comma separated):\n");
3158 for (c = soundhw; c->name; ++c) {
3159 printf ("%-11s %s\n", c->name, c->descr);
3161 printf ("\n-soundhw all will enable all of the above\n");
3162 exit (*optarg != '?');
3164 else {
3165 size_t l;
3166 const char *p;
3167 char *e;
3168 int bad_card = 0;
3170 if (!strcmp (optarg, "all")) {
3171 for (c = soundhw; c->name; ++c) {
3172 c->enabled = 1;
3174 return;
3177 p = optarg;
3178 while (*p) {
3179 e = strchr (p, ',');
3180 l = !e ? strlen (p) : (size_t) (e - p);
3182 for (c = soundhw; c->name; ++c) {
3183 if (!strncmp (c->name, p, l) && !c->name[l]) {
3184 c->enabled = 1;
3185 break;
3189 if (!c->name) {
3190 if (l > 80) {
3191 fprintf (stderr,
3192 "Unknown sound card name (too big to show)\n");
3194 else {
3195 fprintf (stderr, "Unknown sound card name `%.*s'\n",
3196 (int) l, p);
3198 bad_card = 1;
3200 p += l + (e != NULL);
3203 if (bad_card)
3204 goto show_valid_cards;
3207 #endif
3209 static void select_vgahw (const char *p)
3211 const char *opts;
3213 default_vga = 0;
3214 vga_interface_type = VGA_NONE;
3215 if (strstart(p, "std", &opts)) {
3216 vga_interface_type = VGA_STD;
3217 } else if (strstart(p, "cirrus", &opts)) {
3218 vga_interface_type = VGA_CIRRUS;
3219 } else if (strstart(p, "vmware", &opts)) {
3220 vga_interface_type = VGA_VMWARE;
3221 } else if (strstart(p, "xenfb", &opts)) {
3222 vga_interface_type = VGA_XENFB;
3223 } else if (!strstart(p, "none", &opts)) {
3224 invalid_vga:
3225 fprintf(stderr, "Unknown vga type: %s\n", p);
3226 exit(1);
3228 while (*opts) {
3229 const char *nextopt;
3231 if (strstart(opts, ",retrace=", &nextopt)) {
3232 opts = nextopt;
3233 if (strstart(opts, "dumb", &nextopt))
3234 vga_retrace_method = VGA_RETRACE_DUMB;
3235 else if (strstart(opts, "precise", &nextopt))
3236 vga_retrace_method = VGA_RETRACE_PRECISE;
3237 else goto invalid_vga;
3238 } else goto invalid_vga;
3239 opts = nextopt;
3243 #ifdef TARGET_I386
3244 static int balloon_parse(const char *arg)
3246 QemuOpts *opts;
3248 if (strcmp(arg, "none") == 0) {
3249 return 0;
3252 if (!strncmp(arg, "virtio", 6)) {
3253 if (arg[6] == ',') {
3254 /* have params -> parse them */
3255 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
3256 if (!opts)
3257 return -1;
3258 } else {
3259 /* create empty opts */
3260 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3262 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
3263 return 0;
3266 return -1;
3268 #endif
3270 #ifdef _WIN32
3271 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
3273 exit(STATUS_CONTROL_C_EXIT);
3274 return TRUE;
3276 #endif
3278 int qemu_uuid_parse(const char *str, uint8_t *uuid)
3280 int ret;
3282 if(strlen(str) != 36)
3283 return -1;
3285 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
3286 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
3287 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
3289 if(ret != 16)
3290 return -1;
3292 #ifdef TARGET_I386
3293 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
3294 #endif
3296 return 0;
3299 #ifndef _WIN32
3301 static void termsig_handler(int signal)
3303 qemu_system_shutdown_request();
3306 static void sigchld_handler(int signal)
3308 waitpid(-1, NULL, WNOHANG);
3311 static void sighandler_setup(void)
3313 struct sigaction act;
3315 memset(&act, 0, sizeof(act));
3316 act.sa_handler = termsig_handler;
3317 sigaction(SIGINT, &act, NULL);
3318 sigaction(SIGHUP, &act, NULL);
3319 sigaction(SIGTERM, &act, NULL);
3321 act.sa_handler = sigchld_handler;
3322 act.sa_flags = SA_NOCLDSTOP;
3323 sigaction(SIGCHLD, &act, NULL);
3326 #endif
3328 #ifdef _WIN32
3329 /* Look for support files in the same directory as the executable. */
3330 static char *find_datadir(const char *argv0)
3332 char *p;
3333 char buf[MAX_PATH];
3334 DWORD len;
3336 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
3337 if (len == 0) {
3338 return NULL;
3341 buf[len] = 0;
3342 p = buf + len - 1;
3343 while (p != buf && *p != '\\')
3344 p--;
3345 *p = 0;
3346 if (access(buf, R_OK) == 0) {
3347 return qemu_strdup(buf);
3349 return NULL;
3351 #else /* !_WIN32 */
3353 /* Find a likely location for support files using the location of the binary.
3354 For installed binaries this will be "$bindir/../share/qemu". When
3355 running from the build tree this will be "$bindir/../pc-bios". */
3356 #define SHARE_SUFFIX "/share/qemu"
3357 #define BUILD_SUFFIX "/pc-bios"
3358 static char *find_datadir(const char *argv0)
3360 char *dir;
3361 char *p = NULL;
3362 char *res;
3363 char buf[PATH_MAX];
3364 size_t max_len;
3366 #if defined(__linux__)
3368 int len;
3369 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
3370 if (len > 0) {
3371 buf[len] = 0;
3372 p = buf;
3375 #elif defined(__FreeBSD__)
3377 int len;
3378 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
3379 if (len > 0) {
3380 buf[len] = 0;
3381 p = buf;
3384 #endif
3385 /* If we don't have any way of figuring out the actual executable
3386 location then try argv[0]. */
3387 if (!p) {
3388 p = realpath(argv0, buf);
3389 if (!p) {
3390 return NULL;
3393 dir = dirname(p);
3394 dir = dirname(dir);
3396 max_len = strlen(dir) +
3397 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
3398 res = qemu_mallocz(max_len);
3399 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
3400 if (access(res, R_OK)) {
3401 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
3402 if (access(res, R_OK)) {
3403 qemu_free(res);
3404 res = NULL;
3408 return res;
3410 #undef SHARE_SUFFIX
3411 #undef BUILD_SUFFIX
3412 #endif
3414 char *qemu_find_file(int type, const char *name)
3416 int len;
3417 const char *subdir;
3418 char *buf;
3420 /* If name contains path separators then try it as a straight path. */
3421 if ((strchr(name, '/') || strchr(name, '\\'))
3422 && access(name, R_OK) == 0) {
3423 return qemu_strdup(name);
3425 switch (type) {
3426 case QEMU_FILE_TYPE_BIOS:
3427 subdir = "";
3428 break;
3429 case QEMU_FILE_TYPE_KEYMAP:
3430 subdir = "keymaps/";
3431 break;
3432 default:
3433 abort();
3435 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
3436 buf = qemu_mallocz(len);
3437 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
3438 if (access(buf, R_OK)) {
3439 qemu_free(buf);
3440 return NULL;
3442 return buf;
3445 static int device_help_func(QemuOpts *opts, void *opaque)
3447 return qdev_device_help(opts);
3450 static int device_init_func(QemuOpts *opts, void *opaque)
3452 DeviceState *dev;
3454 dev = qdev_device_add(opts);
3455 if (!dev)
3456 return -1;
3457 return 0;
3460 static int chardev_init_func(QemuOpts *opts, void *opaque)
3462 CharDriverState *chr;
3464 chr = qemu_chr_open_opts(opts, NULL);
3465 if (!chr)
3466 return -1;
3467 return 0;
3470 static int mon_init_func(QemuOpts *opts, void *opaque)
3472 CharDriverState *chr;
3473 const char *chardev;
3474 const char *mode;
3475 int flags;
3477 mode = qemu_opt_get(opts, "mode");
3478 if (mode == NULL) {
3479 mode = "readline";
3481 if (strcmp(mode, "readline") == 0) {
3482 flags = MONITOR_USE_READLINE;
3483 } else if (strcmp(mode, "control") == 0) {
3484 flags = MONITOR_USE_CONTROL;
3485 } else {
3486 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
3487 exit(1);
3490 if (qemu_opt_get_bool(opts, "default", 0))
3491 flags |= MONITOR_IS_DEFAULT;
3493 chardev = qemu_opt_get(opts, "chardev");
3494 chr = qemu_chr_find(chardev);
3495 if (chr == NULL) {
3496 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
3497 exit(1);
3500 monitor_init(chr, flags);
3501 return 0;
3504 static void monitor_parse(const char *optarg, const char *mode)
3506 static int monitor_device_index = 0;
3507 QemuOpts *opts;
3508 const char *p;
3509 char label[32];
3510 int def = 0;
3512 if (strstart(optarg, "chardev:", &p)) {
3513 snprintf(label, sizeof(label), "%s", p);
3514 } else {
3515 if (monitor_device_index) {
3516 snprintf(label, sizeof(label), "monitor%d",
3517 monitor_device_index);
3518 } else {
3519 snprintf(label, sizeof(label), "monitor");
3520 def = 1;
3522 opts = qemu_chr_parse_compat(label, optarg);
3523 if (!opts) {
3524 fprintf(stderr, "parse error: %s\n", optarg);
3525 exit(1);
3529 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
3530 if (!opts) {
3531 fprintf(stderr, "duplicate chardev: %s\n", label);
3532 exit(1);
3534 qemu_opt_set(opts, "mode", mode);
3535 qemu_opt_set(opts, "chardev", label);
3536 if (def)
3537 qemu_opt_set(opts, "default", "on");
3538 monitor_device_index++;
3541 struct device_config {
3542 enum {
3543 DEV_USB, /* -usbdevice */
3544 DEV_BT, /* -bt */
3545 DEV_SERIAL, /* -serial */
3546 DEV_PARALLEL, /* -parallel */
3547 DEV_VIRTCON, /* -virtioconsole */
3548 DEV_DEBUGCON, /* -debugcon */
3549 } type;
3550 const char *cmdline;
3551 QTAILQ_ENTRY(device_config) next;
3553 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
3555 static void add_device_config(int type, const char *cmdline)
3557 struct device_config *conf;
3559 conf = qemu_mallocz(sizeof(*conf));
3560 conf->type = type;
3561 conf->cmdline = cmdline;
3562 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
3565 static int foreach_device_config(int type, int (*func)(const char *cmdline))
3567 struct device_config *conf;
3568 int rc;
3570 QTAILQ_FOREACH(conf, &device_configs, next) {
3571 if (conf->type != type)
3572 continue;
3573 rc = func(conf->cmdline);
3574 if (0 != rc)
3575 return rc;
3577 return 0;
3580 static int serial_parse(const char *devname)
3582 static int index = 0;
3583 char label[32];
3585 if (strcmp(devname, "none") == 0)
3586 return 0;
3587 if (index == MAX_SERIAL_PORTS) {
3588 fprintf(stderr, "qemu: too many serial ports\n");
3589 exit(1);
3591 snprintf(label, sizeof(label), "serial%d", index);
3592 serial_hds[index] = qemu_chr_open(label, devname, NULL);
3593 if (!serial_hds[index]) {
3594 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
3595 devname, strerror(errno));
3596 return -1;
3598 index++;
3599 return 0;
3602 static int parallel_parse(const char *devname)
3604 static int index = 0;
3605 char label[32];
3607 if (strcmp(devname, "none") == 0)
3608 return 0;
3609 if (index == MAX_PARALLEL_PORTS) {
3610 fprintf(stderr, "qemu: too many parallel ports\n");
3611 exit(1);
3613 snprintf(label, sizeof(label), "parallel%d", index);
3614 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
3615 if (!parallel_hds[index]) {
3616 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
3617 devname, strerror(errno));
3618 return -1;
3620 index++;
3621 return 0;
3624 static int virtcon_parse(const char *devname)
3626 static int index = 0;
3627 char label[32];
3628 QemuOpts *bus_opts, *dev_opts;
3630 if (strcmp(devname, "none") == 0)
3631 return 0;
3632 if (index == MAX_VIRTIO_CONSOLES) {
3633 fprintf(stderr, "qemu: too many virtio consoles\n");
3634 exit(1);
3637 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3638 qemu_opt_set(bus_opts, "driver", "virtio-serial");
3640 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3641 qemu_opt_set(dev_opts, "driver", "virtconsole");
3643 snprintf(label, sizeof(label), "virtcon%d", index);
3644 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
3645 if (!virtcon_hds[index]) {
3646 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
3647 devname, strerror(errno));
3648 return -1;
3650 qemu_opt_set(dev_opts, "chardev", label);
3652 index++;
3653 return 0;
3656 static int debugcon_parse(const char *devname)
3658 QemuOpts *opts;
3660 if (!qemu_chr_open("debugcon", devname, NULL)) {
3661 exit(1);
3663 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
3664 if (!opts) {
3665 fprintf(stderr, "qemu: already have a debugcon device\n");
3666 exit(1);
3668 qemu_opt_set(opts, "driver", "isa-debugcon");
3669 qemu_opt_set(opts, "chardev", "debugcon");
3670 return 0;
3673 static const QEMUOption *lookup_opt(int argc, char **argv,
3674 const char **poptarg, int *poptind)
3676 const QEMUOption *popt;
3677 int optind = *poptind;
3678 char *r = argv[optind];
3679 const char *optarg;
3681 loc_set_cmdline(argv, optind, 1);
3682 optind++;
3683 /* Treat --foo the same as -foo. */
3684 if (r[1] == '-')
3685 r++;
3686 popt = qemu_options;
3687 for(;;) {
3688 if (!popt->name) {
3689 error_report("invalid option");
3690 exit(1);
3692 if (!strcmp(popt->name, r + 1))
3693 break;
3694 popt++;
3696 if (popt->flags & HAS_ARG) {
3697 if (optind >= argc) {
3698 error_report("requires an argument");
3699 exit(1);
3701 optarg = argv[optind++];
3702 loc_set_cmdline(argv, optind - 2, 2);
3703 } else {
3704 optarg = NULL;
3707 *poptarg = optarg;
3708 *poptind = optind;
3710 return popt;
3713 static void qmp_add_default(void)
3715 char buffer[4096];
3716 const char *home;
3717 static uint8_t null_uuid[16];
3718 uint8_t uuid[16];
3719 int ret;
3721 home = getenv("HOME");
3722 if (!home) {
3723 return;
3726 if (memcmp(qemu_uuid, null_uuid, sizeof(null_uuid)) == 0) {
3727 #if defined(CONFIG_UUID)
3728 uuid_generate(uuid);
3729 #else
3730 return;
3731 #endif
3732 } else {
3733 memcpy(uuid, qemu_uuid, sizeof(qemu_uuid));
3736 snprintf(buffer, sizeof(buffer), "%s/.qemu", home);
3737 #ifdef __MINGW32__
3738 ret = mkdir(buffer);
3739 #else
3740 ret = mkdir(buffer, 0755);
3741 #endif
3742 if (ret == -1 && errno != EEXIST) {
3743 fprintf(stderr, "could not open default QMP port\n");
3744 return;
3747 snprintf(buffer, sizeof(buffer), "%s/.qemu/qmp", home);
3748 #ifdef __MINGW32__
3749 ret = mkdir(buffer);
3750 #else
3751 ret = mkdir(buffer, 0755);
3752 #endif
3753 if (ret == -1 && errno != EEXIST) {
3754 fprintf(stderr, "could not open default QMP port\n");
3755 return;
3758 snprintf(buffer, sizeof(buffer),
3759 "unix:%s/.qemu/qmp/" UUID_FMT ".sock,server,nowait",
3760 home,
3761 uuid[0], uuid[1], uuid[2], uuid[3],
3762 uuid[4], uuid[5], uuid[6], uuid[7],
3763 uuid[8], uuid[9], uuid[10], uuid[11],
3764 uuid[12], uuid[13], uuid[14], uuid[15]);
3766 monitor_parse(buffer, "control");
3769 int main(int argc, char **argv, char **envp)
3771 const char *gdbstub_dev = NULL;
3772 uint32_t boot_devices_bitmap = 0;
3773 int i;
3774 int snapshot, linux_boot, net_boot;
3775 const char *icount_option = NULL;
3776 const char *initrd_filename;
3777 const char *kernel_filename, *kernel_cmdline;
3778 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3779 DisplayState *ds;
3780 DisplayChangeListener *dcl;
3781 int cyls, heads, secs, translation;
3782 QemuOpts *hda_opts = NULL, *opts;
3783 int optind;
3784 const char *optarg;
3785 const char *loadvm = NULL;
3786 QEMUMachine *machine;
3787 const char *cpu_model;
3788 #ifndef _WIN32
3789 int fds[2];
3790 #endif
3791 int tb_size;
3792 const char *pid_file = NULL;
3793 const char *incoming = NULL;
3794 #ifndef _WIN32
3795 int fd = 0;
3796 struct passwd *pwd = NULL;
3797 const char *chroot_dir = NULL;
3798 const char *run_as = NULL;
3799 #endif
3800 CPUState *env;
3801 int show_vnc_port = 0;
3802 int defconfig = 1;
3804 error_set_progname(argv[0]);
3806 exit_notifier_init();
3808 init_clocks();
3810 qemu_cache_utils_init(envp);
3812 QLIST_INIT (&vm_change_state_head);
3813 #ifndef _WIN32
3815 struct sigaction act;
3816 sigfillset(&act.sa_mask);
3817 act.sa_flags = 0;
3818 act.sa_handler = SIG_IGN;
3819 sigaction(SIGPIPE, &act, NULL);
3821 #else
3822 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3823 /* Note: cpu_interrupt() is currently not SMP safe, so we force
3824 QEMU to run on a single CPU */
3826 HANDLE h;
3827 DWORD mask, smask;
3828 int i;
3829 h = GetCurrentProcess();
3830 if (GetProcessAffinityMask(h, &mask, &smask)) {
3831 for(i = 0; i < 32; i++) {
3832 if (mask & (1 << i))
3833 break;
3835 if (i != 32) {
3836 mask = 1 << i;
3837 SetProcessAffinityMask(h, mask);
3841 #endif
3843 module_call_init(MODULE_INIT_MACHINE);
3844 machine = find_default_machine();
3845 cpu_model = NULL;
3846 initrd_filename = NULL;
3847 ram_size = 0;
3848 snapshot = 0;
3849 kernel_filename = NULL;
3850 kernel_cmdline = "";
3851 cyls = heads = secs = 0;
3852 translation = BIOS_ATA_TRANSLATION_AUTO;
3854 for (i = 0; i < MAX_NODES; i++) {
3855 node_mem[i] = 0;
3856 node_cpumask[i] = 0;
3859 nb_numa_nodes = 0;
3860 nb_nics = 0;
3862 tb_size = 0;
3863 autostart= 1;
3865 /* first pass of option parsing */
3866 optind = 1;
3867 while (optind < argc) {
3868 if (argv[optind][0] != '-') {
3869 /* disk image */
3870 optind++;
3871 continue;
3872 } else {
3873 const QEMUOption *popt;
3875 popt = lookup_opt(argc, argv, &optarg, &optind);
3876 switch (popt->index) {
3877 case QEMU_OPTION_nodefconfig:
3878 defconfig=0;
3879 break;
3884 if (defconfig) {
3885 const char *fname;
3886 FILE *fp;
3888 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3889 fp = fopen(fname, "r");
3890 if (fp) {
3891 if (qemu_config_parse(fp, fname) != 0) {
3892 exit(1);
3894 fclose(fp);
3897 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3898 fp = fopen(fname, "r");
3899 if (fp) {
3900 if (qemu_config_parse(fp, fname) != 0) {
3901 exit(1);
3903 fclose(fp);
3906 #if defined(cpudef_setup)
3907 cpudef_setup(); /* parse cpu definitions in target config file */
3908 #endif
3910 /* second pass of option parsing */
3911 optind = 1;
3912 for(;;) {
3913 if (optind >= argc)
3914 break;
3915 if (argv[optind][0] != '-') {
3916 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3917 } else {
3918 const QEMUOption *popt;
3920 popt = lookup_opt(argc, argv, &optarg, &optind);
3921 switch(popt->index) {
3922 case QEMU_OPTION_M:
3923 machine = find_machine(optarg);
3924 if (!machine) {
3925 QEMUMachine *m;
3926 printf("Supported machines are:\n");
3927 for(m = first_machine; m != NULL; m = m->next) {
3928 if (m->alias)
3929 printf("%-10s %s (alias of %s)\n",
3930 m->alias, m->desc, m->name);
3931 printf("%-10s %s%s\n",
3932 m->name, m->desc,
3933 m->is_default ? " (default)" : "");
3935 exit(*optarg != '?');
3937 break;
3938 case QEMU_OPTION_cpu:
3939 /* hw initialization will check this */
3940 if (*optarg == '?') {
3941 /* XXX: implement xxx_cpu_list for targets that still miss it */
3942 #if defined(cpu_list_id)
3943 cpu_list_id(stdout, &fprintf, optarg);
3944 #elif defined(cpu_list)
3945 cpu_list(stdout, &fprintf); /* deprecated */
3946 #endif
3947 exit(0);
3948 } else {
3949 cpu_model = optarg;
3951 break;
3952 case QEMU_OPTION_initrd:
3953 initrd_filename = optarg;
3954 break;
3955 case QEMU_OPTION_hda:
3956 if (cyls == 0)
3957 hda_opts = drive_add(optarg, HD_ALIAS, 0);
3958 else
3959 hda_opts = drive_add(optarg, HD_ALIAS
3960 ",cyls=%d,heads=%d,secs=%d%s",
3961 0, cyls, heads, secs,
3962 translation == BIOS_ATA_TRANSLATION_LBA ?
3963 ",trans=lba" :
3964 translation == BIOS_ATA_TRANSLATION_NONE ?
3965 ",trans=none" : "");
3966 break;
3967 case QEMU_OPTION_hdb:
3968 case QEMU_OPTION_hdc:
3969 case QEMU_OPTION_hdd:
3970 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
3971 break;
3972 case QEMU_OPTION_drive:
3973 drive_add(NULL, "%s", optarg);
3974 break;
3975 case QEMU_OPTION_set:
3976 if (qemu_set_option(optarg) != 0)
3977 exit(1);
3978 break;
3979 case QEMU_OPTION_global:
3980 if (qemu_global_option(optarg) != 0)
3981 exit(1);
3982 break;
3983 case QEMU_OPTION_mtdblock:
3984 drive_add(optarg, MTD_ALIAS);
3985 break;
3986 case QEMU_OPTION_sd:
3987 drive_add(optarg, SD_ALIAS);
3988 break;
3989 case QEMU_OPTION_pflash:
3990 drive_add(optarg, PFLASH_ALIAS);
3991 break;
3992 case QEMU_OPTION_snapshot:
3993 snapshot = 1;
3994 break;
3995 case QEMU_OPTION_hdachs:
3997 const char *p;
3998 p = optarg;
3999 cyls = strtol(p, (char **)&p, 0);
4000 if (cyls < 1 || cyls > 16383)
4001 goto chs_fail;
4002 if (*p != ',')
4003 goto chs_fail;
4004 p++;
4005 heads = strtol(p, (char **)&p, 0);
4006 if (heads < 1 || heads > 16)
4007 goto chs_fail;
4008 if (*p != ',')
4009 goto chs_fail;
4010 p++;
4011 secs = strtol(p, (char **)&p, 0);
4012 if (secs < 1 || secs > 63)
4013 goto chs_fail;
4014 if (*p == ',') {
4015 p++;
4016 if (!strcmp(p, "none"))
4017 translation = BIOS_ATA_TRANSLATION_NONE;
4018 else if (!strcmp(p, "lba"))
4019 translation = BIOS_ATA_TRANSLATION_LBA;
4020 else if (!strcmp(p, "auto"))
4021 translation = BIOS_ATA_TRANSLATION_AUTO;
4022 else
4023 goto chs_fail;
4024 } else if (*p != '\0') {
4025 chs_fail:
4026 fprintf(stderr, "qemu: invalid physical CHS format\n");
4027 exit(1);
4029 if (hda_opts != NULL) {
4030 char num[16];
4031 snprintf(num, sizeof(num), "%d", cyls);
4032 qemu_opt_set(hda_opts, "cyls", num);
4033 snprintf(num, sizeof(num), "%d", heads);
4034 qemu_opt_set(hda_opts, "heads", num);
4035 snprintf(num, sizeof(num), "%d", secs);
4036 qemu_opt_set(hda_opts, "secs", num);
4037 if (translation == BIOS_ATA_TRANSLATION_LBA)
4038 qemu_opt_set(hda_opts, "trans", "lba");
4039 if (translation == BIOS_ATA_TRANSLATION_NONE)
4040 qemu_opt_set(hda_opts, "trans", "none");
4043 break;
4044 case QEMU_OPTION_numa:
4045 if (nb_numa_nodes >= MAX_NODES) {
4046 fprintf(stderr, "qemu: too many NUMA nodes\n");
4047 exit(1);
4049 numa_add(optarg);
4050 break;
4051 case QEMU_OPTION_nographic:
4052 display_type = DT_NOGRAPHIC;
4053 break;
4054 #ifdef CONFIG_CURSES
4055 case QEMU_OPTION_curses:
4056 display_type = DT_CURSES;
4057 break;
4058 #endif
4059 case QEMU_OPTION_portrait:
4060 graphic_rotate = 1;
4061 break;
4062 case QEMU_OPTION_kernel:
4063 kernel_filename = optarg;
4064 break;
4065 case QEMU_OPTION_append:
4066 kernel_cmdline = optarg;
4067 break;
4068 case QEMU_OPTION_cdrom:
4069 drive_add(optarg, CDROM_ALIAS);
4070 break;
4071 case QEMU_OPTION_boot:
4073 static const char * const params[] = {
4074 "order", "once", "menu", NULL
4076 char buf[sizeof(boot_devices)];
4077 char *standard_boot_devices;
4078 int legacy = 0;
4080 if (!strchr(optarg, '=')) {
4081 legacy = 1;
4082 pstrcpy(buf, sizeof(buf), optarg);
4083 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4084 fprintf(stderr,
4085 "qemu: unknown boot parameter '%s' in '%s'\n",
4086 buf, optarg);
4087 exit(1);
4090 if (legacy ||
4091 get_param_value(buf, sizeof(buf), "order", optarg)) {
4092 boot_devices_bitmap = parse_bootdevices(buf);
4093 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4095 if (!legacy) {
4096 if (get_param_value(buf, sizeof(buf),
4097 "once", optarg)) {
4098 boot_devices_bitmap |= parse_bootdevices(buf);
4099 standard_boot_devices = qemu_strdup(boot_devices);
4100 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4101 qemu_register_reset(restore_boot_devices,
4102 standard_boot_devices);
4104 if (get_param_value(buf, sizeof(buf),
4105 "menu", optarg)) {
4106 if (!strcmp(buf, "on")) {
4107 boot_menu = 1;
4108 } else if (!strcmp(buf, "off")) {
4109 boot_menu = 0;
4110 } else {
4111 fprintf(stderr,
4112 "qemu: invalid option value '%s'\n",
4113 buf);
4114 exit(1);
4119 break;
4120 case QEMU_OPTION_fda:
4121 case QEMU_OPTION_fdb:
4122 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4123 break;
4124 #ifdef TARGET_I386
4125 case QEMU_OPTION_no_fd_bootchk:
4126 fd_bootchk = 0;
4127 break;
4128 #endif
4129 case QEMU_OPTION_netdev:
4130 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4131 exit(1);
4133 break;
4134 case QEMU_OPTION_net:
4135 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4136 exit(1);
4138 break;
4139 #ifdef CONFIG_SLIRP
4140 case QEMU_OPTION_tftp:
4141 legacy_tftp_prefix = optarg;
4142 break;
4143 case QEMU_OPTION_bootp:
4144 legacy_bootp_filename = optarg;
4145 break;
4146 #ifndef _WIN32
4147 case QEMU_OPTION_smb:
4148 if (net_slirp_smb(optarg) < 0)
4149 exit(1);
4150 break;
4151 #endif
4152 case QEMU_OPTION_redir:
4153 if (net_slirp_redir(optarg) < 0)
4154 exit(1);
4155 break;
4156 #endif
4157 case QEMU_OPTION_bt:
4158 add_device_config(DEV_BT, optarg);
4159 break;
4160 #ifdef HAS_AUDIO
4161 case QEMU_OPTION_audio_help:
4162 AUD_help ();
4163 exit (0);
4164 break;
4165 case QEMU_OPTION_soundhw:
4166 select_soundhw (optarg);
4167 break;
4168 #endif
4169 case QEMU_OPTION_h:
4170 help(0);
4171 break;
4172 case QEMU_OPTION_version:
4173 version();
4174 exit(0);
4175 break;
4176 case QEMU_OPTION_m: {
4177 uint64_t value;
4178 char *ptr;
4180 value = strtoul(optarg, &ptr, 10);
4181 switch (*ptr) {
4182 case 0: case 'M': case 'm':
4183 value <<= 20;
4184 break;
4185 case 'G': case 'g':
4186 value <<= 30;
4187 break;
4188 default:
4189 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4190 exit(1);
4193 /* On 32-bit hosts, QEMU is limited by virtual address space */
4194 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
4195 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4196 exit(1);
4198 if (value != (uint64_t)(ram_addr_t)value) {
4199 fprintf(stderr, "qemu: ram size too large\n");
4200 exit(1);
4202 ram_size = value;
4203 break;
4205 case QEMU_OPTION_mempath:
4206 mem_path = optarg;
4207 break;
4208 #ifdef MAP_POPULATE
4209 case QEMU_OPTION_mem_prealloc:
4210 mem_prealloc = 1;
4211 break;
4212 #endif
4213 case QEMU_OPTION_d:
4215 int mask;
4216 const CPULogItem *item;
4218 mask = cpu_str_to_log_mask(optarg);
4219 if (!mask) {
4220 printf("Log items (comma separated):\n");
4221 for(item = cpu_log_items; item->mask != 0; item++) {
4222 printf("%-10s %s\n", item->name, item->help);
4224 exit(1);
4226 cpu_set_log(mask);
4228 break;
4229 case QEMU_OPTION_s:
4230 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4231 break;
4232 case QEMU_OPTION_gdb:
4233 gdbstub_dev = optarg;
4234 break;
4235 case QEMU_OPTION_L:
4236 data_dir = optarg;
4237 break;
4238 case QEMU_OPTION_bios:
4239 bios_name = optarg;
4240 break;
4241 case QEMU_OPTION_singlestep:
4242 singlestep = 1;
4243 break;
4244 case QEMU_OPTION_S:
4245 autostart = 0;
4246 break;
4247 case QEMU_OPTION_k:
4248 keyboard_layout = optarg;
4249 break;
4250 case QEMU_OPTION_localtime:
4251 rtc_utc = 0;
4252 break;
4253 case QEMU_OPTION_vga:
4254 select_vgahw (optarg);
4255 break;
4256 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4257 case QEMU_OPTION_g:
4259 const char *p;
4260 int w, h, depth;
4261 p = optarg;
4262 w = strtol(p, (char **)&p, 10);
4263 if (w <= 0) {
4264 graphic_error:
4265 fprintf(stderr, "qemu: invalid resolution or depth\n");
4266 exit(1);
4268 if (*p != 'x')
4269 goto graphic_error;
4270 p++;
4271 h = strtol(p, (char **)&p, 10);
4272 if (h <= 0)
4273 goto graphic_error;
4274 if (*p == 'x') {
4275 p++;
4276 depth = strtol(p, (char **)&p, 10);
4277 if (depth != 8 && depth != 15 && depth != 16 &&
4278 depth != 24 && depth != 32)
4279 goto graphic_error;
4280 } else if (*p == '\0') {
4281 depth = graphic_depth;
4282 } else {
4283 goto graphic_error;
4286 graphic_width = w;
4287 graphic_height = h;
4288 graphic_depth = depth;
4290 break;
4291 #endif
4292 case QEMU_OPTION_echr:
4294 char *r;
4295 term_escape_char = strtol(optarg, &r, 0);
4296 if (r == optarg)
4297 printf("Bad argument to echr\n");
4298 break;
4300 case QEMU_OPTION_monitor:
4301 monitor_parse(optarg, "readline");
4302 default_monitor = 0;
4303 break;
4304 case QEMU_OPTION_qmp:
4305 monitor_parse(optarg, "control");
4306 default_qmp = 0;
4307 break;
4308 case QEMU_OPTION_mon:
4309 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
4310 if (!opts) {
4311 fprintf(stderr, "parse error: %s\n", optarg);
4312 exit(1);
4313 } else {
4314 const char *mode;
4315 mode = qemu_opt_get(opts, "mode");
4316 if (mode == NULL || strcmp(mode, "readline") == 0) {
4317 default_monitor = 0;
4318 } else if (strcmp(mode, "control") == 0) {
4319 default_qmp = 0;
4322 break;
4323 case QEMU_OPTION_chardev:
4324 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
4325 if (!opts) {
4326 fprintf(stderr, "parse error: %s\n", optarg);
4327 exit(1);
4329 break;
4330 case QEMU_OPTION_serial:
4331 add_device_config(DEV_SERIAL, optarg);
4332 default_serial = 0;
4333 if (strncmp(optarg, "mon:", 4) == 0) {
4334 default_monitor = 0;
4336 break;
4337 case QEMU_OPTION_watchdog:
4338 if (watchdog) {
4339 fprintf(stderr,
4340 "qemu: only one watchdog option may be given\n");
4341 return 1;
4343 watchdog = optarg;
4344 break;
4345 case QEMU_OPTION_watchdog_action:
4346 if (select_watchdog_action(optarg) == -1) {
4347 fprintf(stderr, "Unknown -watchdog-action parameter\n");
4348 exit(1);
4350 break;
4351 case QEMU_OPTION_virtiocon:
4352 add_device_config(DEV_VIRTCON, optarg);
4353 default_virtcon = 0;
4354 if (strncmp(optarg, "mon:", 4) == 0) {
4355 default_monitor = 0;
4357 break;
4358 case QEMU_OPTION_parallel:
4359 add_device_config(DEV_PARALLEL, optarg);
4360 default_parallel = 0;
4361 if (strncmp(optarg, "mon:", 4) == 0) {
4362 default_monitor = 0;
4364 break;
4365 case QEMU_OPTION_debugcon:
4366 add_device_config(DEV_DEBUGCON, optarg);
4367 break;
4368 case QEMU_OPTION_loadvm:
4369 loadvm = optarg;
4370 break;
4371 case QEMU_OPTION_full_screen:
4372 full_screen = 1;
4373 break;
4374 #ifdef CONFIG_SDL
4375 case QEMU_OPTION_no_frame:
4376 no_frame = 1;
4377 break;
4378 case QEMU_OPTION_alt_grab:
4379 alt_grab = 1;
4380 break;
4381 case QEMU_OPTION_ctrl_grab:
4382 ctrl_grab = 1;
4383 break;
4384 case QEMU_OPTION_no_quit:
4385 no_quit = 1;
4386 break;
4387 case QEMU_OPTION_sdl:
4388 display_type = DT_SDL;
4389 break;
4390 #endif
4391 case QEMU_OPTION_pidfile:
4392 pid_file = optarg;
4393 break;
4394 #ifdef TARGET_I386
4395 case QEMU_OPTION_win2k_hack:
4396 win2k_install_hack = 1;
4397 break;
4398 case QEMU_OPTION_rtc_td_hack:
4399 rtc_td_hack = 1;
4400 break;
4401 case QEMU_OPTION_acpitable:
4402 if(acpi_table_add(optarg) < 0) {
4403 fprintf(stderr, "Wrong acpi table provided\n");
4404 exit(1);
4406 break;
4407 case QEMU_OPTION_smbios:
4408 if(smbios_entry_add(optarg) < 0) {
4409 fprintf(stderr, "Wrong smbios provided\n");
4410 exit(1);
4412 break;
4413 #endif
4414 #ifdef CONFIG_KVM
4415 case QEMU_OPTION_enable_kvm:
4416 kvm_allowed = 1;
4417 break;
4418 #endif
4419 case QEMU_OPTION_usb:
4420 usb_enabled = 1;
4421 break;
4422 case QEMU_OPTION_usbdevice:
4423 usb_enabled = 1;
4424 add_device_config(DEV_USB, optarg);
4425 break;
4426 case QEMU_OPTION_device:
4427 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
4428 exit(1);
4430 break;
4431 case QEMU_OPTION_smp:
4432 smp_parse(optarg);
4433 if (smp_cpus < 1) {
4434 fprintf(stderr, "Invalid number of CPUs\n");
4435 exit(1);
4437 if (max_cpus < smp_cpus) {
4438 fprintf(stderr, "maxcpus must be equal to or greater than "
4439 "smp\n");
4440 exit(1);
4442 if (max_cpus > 255) {
4443 fprintf(stderr, "Unsupported number of maxcpus\n");
4444 exit(1);
4446 break;
4447 case QEMU_OPTION_vnc:
4448 display_type = DT_VNC;
4449 vnc_display = optarg;
4450 break;
4451 #ifdef TARGET_I386
4452 case QEMU_OPTION_no_acpi:
4453 acpi_enabled = 0;
4454 break;
4455 case QEMU_OPTION_no_hpet:
4456 no_hpet = 1;
4457 break;
4458 case QEMU_OPTION_balloon:
4459 if (balloon_parse(optarg) < 0) {
4460 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
4461 exit(1);
4463 break;
4464 #endif
4465 case QEMU_OPTION_no_reboot:
4466 no_reboot = 1;
4467 break;
4468 case QEMU_OPTION_no_shutdown:
4469 no_shutdown = 1;
4470 break;
4471 case QEMU_OPTION_show_cursor:
4472 cursor_hide = 0;
4473 break;
4474 case QEMU_OPTION_uuid:
4475 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4476 fprintf(stderr, "Fail to parse UUID string."
4477 " Wrong format.\n");
4478 exit(1);
4480 break;
4481 #ifndef _WIN32
4482 case QEMU_OPTION_daemonize:
4483 daemonize = 1;
4484 break;
4485 #endif
4486 case QEMU_OPTION_option_rom:
4487 if (nb_option_roms >= MAX_OPTION_ROMS) {
4488 fprintf(stderr, "Too many option ROMs\n");
4489 exit(1);
4491 option_rom[nb_option_roms] = optarg;
4492 nb_option_roms++;
4493 break;
4494 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4495 case QEMU_OPTION_semihosting:
4496 semihosting_enabled = 1;
4497 break;
4498 #endif
4499 case QEMU_OPTION_name:
4500 qemu_name = qemu_strdup(optarg);
4502 char *p = strchr(qemu_name, ',');
4503 if (p != NULL) {
4504 *p++ = 0;
4505 if (strncmp(p, "process=", 8)) {
4506 fprintf(stderr, "Unknown subargument %s to -name", p);
4507 exit(1);
4509 p += 8;
4510 set_proc_name(p);
4513 break;
4514 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4515 case QEMU_OPTION_prom_env:
4516 if (nb_prom_envs >= MAX_PROM_ENVS) {
4517 fprintf(stderr, "Too many prom variables\n");
4518 exit(1);
4520 prom_envs[nb_prom_envs] = optarg;
4521 nb_prom_envs++;
4522 break;
4523 #endif
4524 #ifdef TARGET_ARM
4525 case QEMU_OPTION_old_param:
4526 old_param = 1;
4527 break;
4528 #endif
4529 case QEMU_OPTION_clock:
4530 configure_alarms(optarg);
4531 break;
4532 case QEMU_OPTION_startdate:
4533 configure_rtc_date_offset(optarg, 1);
4534 break;
4535 case QEMU_OPTION_rtc:
4536 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
4537 if (!opts) {
4538 fprintf(stderr, "parse error: %s\n", optarg);
4539 exit(1);
4541 configure_rtc(opts);
4542 break;
4543 case QEMU_OPTION_tb_size:
4544 tb_size = strtol(optarg, NULL, 0);
4545 if (tb_size < 0)
4546 tb_size = 0;
4547 break;
4548 case QEMU_OPTION_icount:
4549 icount_option = optarg;
4550 break;
4551 case QEMU_OPTION_incoming:
4552 incoming = optarg;
4553 break;
4554 case QEMU_OPTION_nodefaults:
4555 default_serial = 0;
4556 default_parallel = 0;
4557 default_virtcon = 0;
4558 default_monitor = 0;
4559 default_qmp = 0;
4560 default_vga = 0;
4561 default_net = 0;
4562 default_floppy = 0;
4563 default_cdrom = 0;
4564 default_sdcard = 0;
4565 break;
4566 #ifndef _WIN32
4567 case QEMU_OPTION_chroot:
4568 chroot_dir = optarg;
4569 break;
4570 case QEMU_OPTION_runas:
4571 run_as = optarg;
4572 break;
4573 #endif
4574 #ifdef CONFIG_XEN
4575 case QEMU_OPTION_xen_domid:
4576 xen_domid = atoi(optarg);
4577 break;
4578 case QEMU_OPTION_xen_create:
4579 xen_mode = XEN_CREATE;
4580 break;
4581 case QEMU_OPTION_xen_attach:
4582 xen_mode = XEN_ATTACH;
4583 break;
4584 #endif
4585 case QEMU_OPTION_readconfig:
4587 FILE *fp;
4588 fp = fopen(optarg, "r");
4589 if (fp == NULL) {
4590 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4591 exit(1);
4593 if (qemu_config_parse(fp, optarg) != 0) {
4594 exit(1);
4596 fclose(fp);
4597 break;
4599 case QEMU_OPTION_writeconfig:
4601 FILE *fp;
4602 if (strcmp(optarg, "-") == 0) {
4603 fp = stdout;
4604 } else {
4605 fp = fopen(optarg, "w");
4606 if (fp == NULL) {
4607 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4608 exit(1);
4611 qemu_config_write(fp);
4612 fclose(fp);
4613 break;
4618 loc_set_none();
4620 /* If no data_dir is specified then try to find it relative to the
4621 executable path. */
4622 if (!data_dir) {
4623 data_dir = find_datadir(argv[0]);
4625 /* If all else fails use the install patch specified when building. */
4626 if (!data_dir) {
4627 data_dir = CONFIG_QEMU_SHAREDIR;
4631 * Default to max_cpus = smp_cpus, in case the user doesn't
4632 * specify a max_cpus value.
4634 if (!max_cpus)
4635 max_cpus = smp_cpus;
4637 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4638 if (smp_cpus > machine->max_cpus) {
4639 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4640 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
4641 machine->max_cpus);
4642 exit(1);
4645 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
4646 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
4648 if (machine->no_serial) {
4649 default_serial = 0;
4651 if (machine->no_parallel) {
4652 default_parallel = 0;
4654 if (!machine->use_virtcon) {
4655 default_virtcon = 0;
4657 if (machine->no_vga) {
4658 default_vga = 0;
4660 if (machine->no_floppy) {
4661 default_floppy = 0;
4663 if (machine->no_cdrom) {
4664 default_cdrom = 0;
4666 if (machine->no_sdcard) {
4667 default_sdcard = 0;
4670 if (display_type == DT_NOGRAPHIC) {
4671 if (default_parallel)
4672 add_device_config(DEV_PARALLEL, "null");
4673 if (default_serial && default_monitor) {
4674 add_device_config(DEV_SERIAL, "mon:stdio");
4675 } else if (default_virtcon && default_monitor) {
4676 add_device_config(DEV_VIRTCON, "mon:stdio");
4677 } else {
4678 if (default_serial)
4679 add_device_config(DEV_SERIAL, "stdio");
4680 if (default_virtcon)
4681 add_device_config(DEV_VIRTCON, "stdio");
4682 if (default_monitor)
4683 monitor_parse("stdio", "readline");
4685 } else {
4686 if (default_serial)
4687 add_device_config(DEV_SERIAL, "vc:80Cx24C");
4688 if (default_parallel)
4689 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4690 if (default_monitor)
4691 monitor_parse("vc:80Cx24C", "readline");
4692 if (default_virtcon)
4693 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4695 if (default_qmp) {
4696 qmp_add_default();
4698 if (default_vga)
4699 vga_interface_type = VGA_CIRRUS;
4701 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
4702 exit(1);
4704 #ifndef _WIN32
4705 if (daemonize) {
4706 pid_t pid;
4708 if (pipe(fds) == -1)
4709 exit(1);
4711 pid = fork();
4712 if (pid > 0) {
4713 uint8_t status;
4714 ssize_t len;
4716 close(fds[1]);
4718 again:
4719 len = read(fds[0], &status, 1);
4720 if (len == -1 && (errno == EINTR))
4721 goto again;
4723 if (len != 1)
4724 exit(1);
4725 else if (status == 1) {
4726 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
4727 exit(1);
4728 } else
4729 exit(0);
4730 } else if (pid < 0)
4731 exit(1);
4733 close(fds[0]);
4734 qemu_set_cloexec(fds[1]);
4736 setsid();
4738 pid = fork();
4739 if (pid > 0)
4740 exit(0);
4741 else if (pid < 0)
4742 exit(1);
4744 umask(027);
4746 signal(SIGTSTP, SIG_IGN);
4747 signal(SIGTTOU, SIG_IGN);
4748 signal(SIGTTIN, SIG_IGN);
4750 #endif
4752 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4753 #ifndef _WIN32
4754 if (daemonize) {
4755 uint8_t status = 1;
4756 if (write(fds[1], &status, 1) != 1) {
4757 perror("daemonize. Writing to pipe\n");
4759 } else
4760 #endif
4761 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
4762 exit(1);
4765 if (kvm_enabled()) {
4766 int ret;
4768 ret = kvm_init(smp_cpus);
4769 if (ret < 0) {
4770 fprintf(stderr, "failed to initialize KVM\n");
4771 exit(1);
4775 if (qemu_init_main_loop()) {
4776 fprintf(stderr, "qemu_init_main_loop failed\n");
4777 exit(1);
4779 linux_boot = (kernel_filename != NULL);
4781 if (!linux_boot && *kernel_cmdline != '\0') {
4782 fprintf(stderr, "-append only allowed with -kernel option\n");
4783 exit(1);
4786 if (!linux_boot && initrd_filename != NULL) {
4787 fprintf(stderr, "-initrd only allowed with -kernel option\n");
4788 exit(1);
4791 #ifndef _WIN32
4792 /* Win32 doesn't support line-buffering and requires size >= 2 */
4793 setvbuf(stdout, NULL, _IOLBF, 0);
4794 #endif
4796 if (init_timer_alarm() < 0) {
4797 fprintf(stderr, "could not initialize alarm timer\n");
4798 exit(1);
4800 configure_icount(icount_option);
4802 #ifdef _WIN32
4803 socket_init();
4804 #endif
4806 if (net_init_clients() < 0) {
4807 exit(1);
4810 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4811 net_set_boot_mask(net_boot);
4813 /* init the bluetooth world */
4814 if (foreach_device_config(DEV_BT, bt_parse))
4815 exit(1);
4817 /* init the memory */
4818 if (ram_size == 0)
4819 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4821 /* init the dynamic translator */
4822 cpu_exec_init_all(tb_size * 1024 * 1024);
4824 bdrv_init_with_whitelist();
4826 blk_mig_init();
4828 if (default_cdrom) {
4829 /* we always create the cdrom drive, even if no disk is there */
4830 drive_add(NULL, CDROM_ALIAS);
4833 if (default_floppy) {
4834 /* we always create at least one floppy */
4835 drive_add(NULL, FD_ALIAS, 0);
4838 if (default_sdcard) {
4839 /* we always create one sd slot, even if no card is in it */
4840 drive_add(NULL, SD_ALIAS);
4843 /* open the virtual block devices */
4844 if (snapshot)
4845 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4846 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4847 exit(1);
4849 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
4850 ram_load, NULL);
4852 if (nb_numa_nodes > 0) {
4853 int i;
4855 if (nb_numa_nodes > smp_cpus) {
4856 nb_numa_nodes = smp_cpus;
4859 /* If no memory size if given for any node, assume the default case
4860 * and distribute the available memory equally across all nodes
4862 for (i = 0; i < nb_numa_nodes; i++) {
4863 if (node_mem[i] != 0)
4864 break;
4866 if (i == nb_numa_nodes) {
4867 uint64_t usedmem = 0;
4869 /* On Linux, the each node's border has to be 8MB aligned,
4870 * the final node gets the rest.
4872 for (i = 0; i < nb_numa_nodes - 1; i++) {
4873 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4874 usedmem += node_mem[i];
4876 node_mem[i] = ram_size - usedmem;
4879 for (i = 0; i < nb_numa_nodes; i++) {
4880 if (node_cpumask[i] != 0)
4881 break;
4883 /* assigning the VCPUs round-robin is easier to implement, guest OSes
4884 * must cope with this anyway, because there are BIOSes out there in
4885 * real machines which also use this scheme.
4887 if (i == nb_numa_nodes) {
4888 for (i = 0; i < smp_cpus; i++) {
4889 node_cpumask[i % nb_numa_nodes] |= 1 << i;
4894 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4895 exit(1);
4896 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4897 exit(1);
4898 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4899 exit(1);
4900 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4901 exit(1);
4903 module_call_init(MODULE_INIT_DEVICE);
4905 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
4906 exit(0);
4908 if (watchdog) {
4909 i = select_watchdog(watchdog);
4910 if (i > 0)
4911 exit (i == 1 ? 1 : 0);
4914 if (machine->compat_props) {
4915 qdev_prop_register_global_list(machine->compat_props);
4917 qemu_add_globals();
4919 machine->init(ram_size, boot_devices,
4920 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
4922 cpu_synchronize_all_post_init();
4924 #ifndef _WIN32
4925 /* must be after terminal init, SDL library changes signal handlers */
4926 sighandler_setup();
4927 #endif
4929 for (env = first_cpu; env != NULL; env = env->next_cpu) {
4930 for (i = 0; i < nb_numa_nodes; i++) {
4931 if (node_cpumask[i] & (1 << env->cpu_index)) {
4932 env->numa_node = i;
4937 current_machine = machine;
4939 /* init USB devices */
4940 if (usb_enabled) {
4941 if (foreach_device_config(DEV_USB, usb_parse) < 0)
4942 exit(1);
4945 /* init generic devices */
4946 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
4947 exit(1);
4949 net_check_clients();
4951 /* just use the first displaystate for the moment */
4952 ds = get_displaystate();
4954 if (display_type == DT_DEFAULT) {
4955 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4956 display_type = DT_SDL;
4957 #else
4958 display_type = DT_VNC;
4959 vnc_display = "localhost:0,to=99";
4960 show_vnc_port = 1;
4961 #endif
4965 switch (display_type) {
4966 case DT_NOGRAPHIC:
4967 break;
4968 #if defined(CONFIG_CURSES)
4969 case DT_CURSES:
4970 curses_display_init(ds, full_screen);
4971 break;
4972 #endif
4973 #if defined(CONFIG_SDL)
4974 case DT_SDL:
4975 sdl_display_init(ds, full_screen, no_frame);
4976 break;
4977 #elif defined(CONFIG_COCOA)
4978 case DT_SDL:
4979 cocoa_display_init(ds, full_screen);
4980 break;
4981 #endif
4982 case DT_VNC:
4983 vnc_display_init(ds);
4984 if (vnc_display_open(ds, vnc_display) < 0)
4985 exit(1);
4987 if (show_vnc_port) {
4988 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
4990 break;
4991 default:
4992 break;
4994 dpy_resize(ds);
4996 dcl = ds->listeners;
4997 while (dcl != NULL) {
4998 if (dcl->dpy_refresh != NULL) {
4999 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5000 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5002 dcl = dcl->next;
5005 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5006 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5007 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5010 text_consoles_set_display(ds);
5012 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5013 exit(1);
5015 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5016 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5017 gdbstub_dev);
5018 exit(1);
5021 qdev_machine_creation_done();
5023 if (rom_load_all() != 0) {
5024 fprintf(stderr, "rom loading failed\n");
5025 exit(1);
5028 qemu_system_reset();
5029 if (loadvm) {
5030 if (load_vmstate(loadvm) < 0) {
5031 autostart = 0;
5035 if (incoming) {
5036 qemu_start_incoming_migration(incoming);
5037 } else if (autostart) {
5038 vm_start();
5041 #ifndef _WIN32
5042 if (daemonize) {
5043 uint8_t status = 0;
5044 ssize_t len;
5046 again1:
5047 len = write(fds[1], &status, 1);
5048 if (len == -1 && (errno == EINTR))
5049 goto again1;
5051 if (len != 1)
5052 exit(1);
5054 if (chdir("/")) {
5055 perror("not able to chdir to /");
5056 exit(1);
5058 TFR(fd = qemu_open("/dev/null", O_RDWR));
5059 if (fd == -1)
5060 exit(1);
5063 if (run_as) {
5064 pwd = getpwnam(run_as);
5065 if (!pwd) {
5066 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5067 exit(1);
5071 if (chroot_dir) {
5072 if (chroot(chroot_dir) < 0) {
5073 fprintf(stderr, "chroot failed\n");
5074 exit(1);
5076 if (chdir("/")) {
5077 perror("not able to chdir to /");
5078 exit(1);
5082 if (run_as) {
5083 if (setgid(pwd->pw_gid) < 0) {
5084 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5085 exit(1);
5087 if (setuid(pwd->pw_uid) < 0) {
5088 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5089 exit(1);
5091 if (setuid(0) != -1) {
5092 fprintf(stderr, "Dropping privileges failed\n");
5093 exit(1);
5097 if (daemonize) {
5098 dup2(fd, 0);
5099 dup2(fd, 1);
5100 dup2(fd, 2);
5102 close(fd);
5104 #endif
5106 main_loop();
5107 quit_timers();
5108 net_cleanup();
5110 return 0;