Revert "tap: invoke downscript when we exit abnormally"
[qemu/ar7.git] / vl.c
blob26b638c11dca740c6924f9a0cb8a1fb8c7ffebde
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(void)
542 WSACleanup();
545 static int socket_init(void)
547 WSADATA Data;
548 int ret, err;
550 ret = WSAStartup(MAKEWORD(2,2), &Data);
551 if (ret != 0) {
552 err = WSAGetLastError();
553 fprintf(stderr, "WSAStartup: %d\n", err);
554 return -1;
556 atexit(socket_cleanup);
557 return 0;
559 #endif
561 /***********************************************************/
562 /* Bluetooth support */
563 static int nb_hcis;
564 static int cur_hci;
565 static struct HCIInfo *hci_table[MAX_NICS];
567 static struct bt_vlan_s {
568 struct bt_scatternet_s net;
569 int id;
570 struct bt_vlan_s *next;
571 } *first_bt_vlan;
573 /* find or alloc a new bluetooth "VLAN" */
574 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
576 struct bt_vlan_s **pvlan, *vlan;
577 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
578 if (vlan->id == id)
579 return &vlan->net;
581 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
582 vlan->id = id;
583 pvlan = &first_bt_vlan;
584 while (*pvlan != NULL)
585 pvlan = &(*pvlan)->next;
586 *pvlan = vlan;
587 return &vlan->net;
590 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
594 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
596 return -ENOTSUP;
599 static struct HCIInfo null_hci = {
600 .cmd_send = null_hci_send,
601 .sco_send = null_hci_send,
602 .acl_send = null_hci_send,
603 .bdaddr_set = null_hci_addr_set,
606 struct HCIInfo *qemu_next_hci(void)
608 if (cur_hci == nb_hcis)
609 return &null_hci;
611 return hci_table[cur_hci++];
614 static struct HCIInfo *hci_init(const char *str)
616 char *endp;
617 struct bt_scatternet_s *vlan = 0;
619 if (!strcmp(str, "null"))
620 /* null */
621 return &null_hci;
622 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
623 /* host[:hciN] */
624 return bt_host_hci(str[4] ? str + 5 : "hci0");
625 else if (!strncmp(str, "hci", 3)) {
626 /* hci[,vlan=n] */
627 if (str[3]) {
628 if (!strncmp(str + 3, ",vlan=", 6)) {
629 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
630 if (*endp)
631 vlan = 0;
633 } else
634 vlan = qemu_find_bt_vlan(0);
635 if (vlan)
636 return bt_new_hci(vlan);
639 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
641 return 0;
644 static int bt_hci_parse(const char *str)
646 struct HCIInfo *hci;
647 bdaddr_t bdaddr;
649 if (nb_hcis >= MAX_NICS) {
650 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
651 return -1;
654 hci = hci_init(str);
655 if (!hci)
656 return -1;
658 bdaddr.b[0] = 0x52;
659 bdaddr.b[1] = 0x54;
660 bdaddr.b[2] = 0x00;
661 bdaddr.b[3] = 0x12;
662 bdaddr.b[4] = 0x34;
663 bdaddr.b[5] = 0x56 + nb_hcis;
664 hci->bdaddr_set(hci, bdaddr.b);
666 hci_table[nb_hcis++] = hci;
668 return 0;
671 static void bt_vhci_add(int vlan_id)
673 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
675 if (!vlan->slave)
676 fprintf(stderr, "qemu: warning: adding a VHCI to "
677 "an empty scatternet %i\n", vlan_id);
679 bt_vhci_init(bt_new_hci(vlan));
682 static struct bt_device_s *bt_device_add(const char *opt)
684 struct bt_scatternet_s *vlan;
685 int vlan_id = 0;
686 char *endp = strstr(opt, ",vlan=");
687 int len = (endp ? endp - opt : strlen(opt)) + 1;
688 char devname[10];
690 pstrcpy(devname, MIN(sizeof(devname), len), opt);
692 if (endp) {
693 vlan_id = strtol(endp + 6, &endp, 0);
694 if (*endp) {
695 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
696 return 0;
700 vlan = qemu_find_bt_vlan(vlan_id);
702 if (!vlan->slave)
703 fprintf(stderr, "qemu: warning: adding a slave device to "
704 "an empty scatternet %i\n", vlan_id);
706 if (!strcmp(devname, "keyboard"))
707 return bt_keyboard_init(vlan);
709 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
710 return 0;
713 static int bt_parse(const char *opt)
715 const char *endp, *p;
716 int vlan;
718 if (strstart(opt, "hci", &endp)) {
719 if (!*endp || *endp == ',') {
720 if (*endp)
721 if (!strstart(endp, ",vlan=", 0))
722 opt = endp + 1;
724 return bt_hci_parse(opt);
726 } else if (strstart(opt, "vhci", &endp)) {
727 if (!*endp || *endp == ',') {
728 if (*endp) {
729 if (strstart(endp, ",vlan=", &p)) {
730 vlan = strtol(p, (char **) &endp, 0);
731 if (*endp) {
732 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
733 return 1;
735 } else {
736 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
737 return 1;
739 } else
740 vlan = 0;
742 bt_vhci_add(vlan);
743 return 0;
745 } else if (strstart(opt, "device:", &endp))
746 return !bt_device_add(endp);
748 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
749 return 1;
752 /***********************************************************/
753 /* QEMU Block devices */
755 #define HD_ALIAS "index=%d,media=disk"
756 #define CDROM_ALIAS "index=2,media=cdrom"
757 #define FD_ALIAS "index=%d,if=floppy"
758 #define PFLASH_ALIAS "if=pflash"
759 #define MTD_ALIAS "if=mtd"
760 #define SD_ALIAS "index=0,if=sd"
762 QemuOpts *drive_add(const char *file, const char *fmt, ...)
764 va_list ap;
765 char optstr[1024];
766 QemuOpts *opts;
768 va_start(ap, fmt);
769 vsnprintf(optstr, sizeof(optstr), fmt, ap);
770 va_end(ap);
772 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
773 if (!opts) {
774 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
775 __FUNCTION__, optstr);
776 return NULL;
778 if (file)
779 qemu_opt_set(opts, "file", file);
780 return opts;
783 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
785 DriveInfo *dinfo;
787 /* seek interface, bus and unit */
789 QTAILQ_FOREACH(dinfo, &drives, next) {
790 if (dinfo->type == type &&
791 dinfo->bus == bus &&
792 dinfo->unit == unit)
793 return dinfo;
796 return NULL;
799 DriveInfo *drive_get_by_id(const char *id)
801 DriveInfo *dinfo;
803 QTAILQ_FOREACH(dinfo, &drives, next) {
804 if (strcmp(id, dinfo->id))
805 continue;
806 return dinfo;
808 return NULL;
811 int drive_get_max_bus(BlockInterfaceType type)
813 int max_bus;
814 DriveInfo *dinfo;
816 max_bus = -1;
817 QTAILQ_FOREACH(dinfo, &drives, next) {
818 if(dinfo->type == type &&
819 dinfo->bus > max_bus)
820 max_bus = dinfo->bus;
822 return max_bus;
825 const char *drive_get_serial(BlockDriverState *bdrv)
827 DriveInfo *dinfo;
829 QTAILQ_FOREACH(dinfo, &drives, next) {
830 if (dinfo->bdrv == bdrv)
831 return dinfo->serial;
834 return "\0";
837 BlockInterfaceErrorAction drive_get_on_error(
838 BlockDriverState *bdrv, int is_read)
840 DriveInfo *dinfo;
842 QTAILQ_FOREACH(dinfo, &drives, next) {
843 if (dinfo->bdrv == bdrv)
844 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
847 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
850 static void bdrv_format_print(void *opaque, const char *name)
852 fprintf(stderr, " %s", name);
855 void drive_uninit(DriveInfo *dinfo)
857 qemu_opts_del(dinfo->opts);
858 bdrv_delete(dinfo->bdrv);
859 QTAILQ_REMOVE(&drives, dinfo, next);
860 qemu_free(dinfo);
863 static int parse_block_error_action(const char *buf, int is_read)
865 if (!strcmp(buf, "ignore")) {
866 return BLOCK_ERR_IGNORE;
867 } else if (!is_read && !strcmp(buf, "enospc")) {
868 return BLOCK_ERR_STOP_ENOSPC;
869 } else if (!strcmp(buf, "stop")) {
870 return BLOCK_ERR_STOP_ANY;
871 } else if (!strcmp(buf, "report")) {
872 return BLOCK_ERR_REPORT;
873 } else {
874 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
875 buf, is_read ? "read" : "write");
876 return -1;
880 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
881 int *fatal_error)
883 const char *buf;
884 const char *file = NULL;
885 char devname[128];
886 const char *serial;
887 const char *mediastr = "";
888 BlockInterfaceType type;
889 enum { MEDIA_DISK, MEDIA_CDROM } media;
890 int bus_id, unit_id;
891 int cyls, heads, secs, translation;
892 BlockDriver *drv = NULL;
893 QEMUMachine *machine = opaque;
894 int max_devs;
895 int index;
896 int cache;
897 int aio = 0;
898 int ro = 0;
899 int bdrv_flags;
900 int on_read_error, on_write_error;
901 const char *devaddr;
902 DriveInfo *dinfo;
903 int snapshot = 0;
905 *fatal_error = 1;
907 translation = BIOS_ATA_TRANSLATION_AUTO;
908 cache = 1;
910 if (machine && machine->use_scsi) {
911 type = IF_SCSI;
912 max_devs = MAX_SCSI_DEVS;
913 pstrcpy(devname, sizeof(devname), "scsi");
914 } else {
915 type = IF_IDE;
916 max_devs = MAX_IDE_DEVS;
917 pstrcpy(devname, sizeof(devname), "ide");
919 media = MEDIA_DISK;
921 /* extract parameters */
922 bus_id = qemu_opt_get_number(opts, "bus", 0);
923 unit_id = qemu_opt_get_number(opts, "unit", -1);
924 index = qemu_opt_get_number(opts, "index", -1);
926 cyls = qemu_opt_get_number(opts, "cyls", 0);
927 heads = qemu_opt_get_number(opts, "heads", 0);
928 secs = qemu_opt_get_number(opts, "secs", 0);
930 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
931 ro = qemu_opt_get_bool(opts, "readonly", 0);
933 file = qemu_opt_get(opts, "file");
934 serial = qemu_opt_get(opts, "serial");
936 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
937 pstrcpy(devname, sizeof(devname), buf);
938 if (!strcmp(buf, "ide")) {
939 type = IF_IDE;
940 max_devs = MAX_IDE_DEVS;
941 } else if (!strcmp(buf, "scsi")) {
942 type = IF_SCSI;
943 max_devs = MAX_SCSI_DEVS;
944 } else if (!strcmp(buf, "floppy")) {
945 type = IF_FLOPPY;
946 max_devs = 0;
947 } else if (!strcmp(buf, "pflash")) {
948 type = IF_PFLASH;
949 max_devs = 0;
950 } else if (!strcmp(buf, "mtd")) {
951 type = IF_MTD;
952 max_devs = 0;
953 } else if (!strcmp(buf, "sd")) {
954 type = IF_SD;
955 max_devs = 0;
956 } else if (!strcmp(buf, "virtio")) {
957 type = IF_VIRTIO;
958 max_devs = 0;
959 } else if (!strcmp(buf, "xen")) {
960 type = IF_XEN;
961 max_devs = 0;
962 } else if (!strcmp(buf, "none")) {
963 type = IF_NONE;
964 max_devs = 0;
965 } else {
966 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
967 return NULL;
971 if (cyls || heads || secs) {
972 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
973 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
974 return NULL;
976 if (heads < 1 || (type == IF_IDE && heads > 16)) {
977 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
978 return NULL;
980 if (secs < 1 || (type == IF_IDE && secs > 63)) {
981 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
982 return NULL;
986 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
987 if (!cyls) {
988 fprintf(stderr,
989 "qemu: '%s' trans must be used with cyls,heads and secs\n",
990 buf);
991 return NULL;
993 if (!strcmp(buf, "none"))
994 translation = BIOS_ATA_TRANSLATION_NONE;
995 else if (!strcmp(buf, "lba"))
996 translation = BIOS_ATA_TRANSLATION_LBA;
997 else if (!strcmp(buf, "auto"))
998 translation = BIOS_ATA_TRANSLATION_AUTO;
999 else {
1000 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
1001 return NULL;
1005 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
1006 if (!strcmp(buf, "disk")) {
1007 media = MEDIA_DISK;
1008 } else if (!strcmp(buf, "cdrom")) {
1009 if (cyls || secs || heads) {
1010 fprintf(stderr,
1011 "qemu: '%s' invalid physical CHS format\n", buf);
1012 return NULL;
1014 media = MEDIA_CDROM;
1015 } else {
1016 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
1017 return NULL;
1021 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
1022 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
1023 cache = 0;
1024 else if (!strcmp(buf, "writethrough"))
1025 cache = 1;
1026 else if (!strcmp(buf, "writeback"))
1027 cache = 2;
1028 else {
1029 fprintf(stderr, "qemu: invalid cache option\n");
1030 return NULL;
1034 #ifdef CONFIG_LINUX_AIO
1035 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1036 if (!strcmp(buf, "threads"))
1037 aio = 0;
1038 else if (!strcmp(buf, "native"))
1039 aio = 1;
1040 else {
1041 fprintf(stderr, "qemu: invalid aio option\n");
1042 return NULL;
1045 #endif
1047 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1048 if (strcmp(buf, "?") == 0) {
1049 fprintf(stderr, "qemu: Supported formats:");
1050 bdrv_iterate_format(bdrv_format_print, NULL);
1051 fprintf(stderr, "\n");
1052 return NULL;
1054 drv = bdrv_find_whitelisted_format(buf);
1055 if (!drv) {
1056 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1057 return NULL;
1061 on_write_error = BLOCK_ERR_STOP_ENOSPC;
1062 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1063 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1064 fprintf(stderr, "werror is no supported by this format\n");
1065 return NULL;
1068 on_write_error = parse_block_error_action(buf, 0);
1069 if (on_write_error < 0) {
1070 return NULL;
1074 on_read_error = BLOCK_ERR_REPORT;
1075 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1076 if (type != IF_IDE && type != IF_VIRTIO) {
1077 fprintf(stderr, "rerror is no supported by this format\n");
1078 return NULL;
1081 on_read_error = parse_block_error_action(buf, 1);
1082 if (on_read_error < 0) {
1083 return NULL;
1087 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1088 if (type != IF_VIRTIO) {
1089 fprintf(stderr, "addr is not supported\n");
1090 return NULL;
1094 /* compute bus and unit according index */
1096 if (index != -1) {
1097 if (bus_id != 0 || unit_id != -1) {
1098 fprintf(stderr,
1099 "qemu: index cannot be used with bus and unit\n");
1100 return NULL;
1102 if (max_devs == 0)
1104 unit_id = index;
1105 bus_id = 0;
1106 } else {
1107 unit_id = index % max_devs;
1108 bus_id = index / max_devs;
1112 /* if user doesn't specify a unit_id,
1113 * try to find the first free
1116 if (unit_id == -1) {
1117 unit_id = 0;
1118 while (drive_get(type, bus_id, unit_id) != NULL) {
1119 unit_id++;
1120 if (max_devs && unit_id >= max_devs) {
1121 unit_id -= max_devs;
1122 bus_id++;
1127 /* check unit id */
1129 if (max_devs && unit_id >= max_devs) {
1130 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1131 unit_id, max_devs - 1);
1132 return NULL;
1136 * ignore multiple definitions
1139 if (drive_get(type, bus_id, unit_id) != NULL) {
1140 *fatal_error = 0;
1141 return NULL;
1144 /* init */
1146 dinfo = qemu_mallocz(sizeof(*dinfo));
1147 if ((buf = qemu_opts_id(opts)) != NULL) {
1148 dinfo->id = qemu_strdup(buf);
1149 } else {
1150 /* no id supplied -> create one */
1151 dinfo->id = qemu_mallocz(32);
1152 if (type == IF_IDE || type == IF_SCSI)
1153 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1154 if (max_devs)
1155 snprintf(dinfo->id, 32, "%s%i%s%i",
1156 devname, bus_id, mediastr, unit_id);
1157 else
1158 snprintf(dinfo->id, 32, "%s%s%i",
1159 devname, mediastr, unit_id);
1161 dinfo->bdrv = bdrv_new(dinfo->id);
1162 dinfo->devaddr = devaddr;
1163 dinfo->type = type;
1164 dinfo->bus = bus_id;
1165 dinfo->unit = unit_id;
1166 dinfo->on_read_error = on_read_error;
1167 dinfo->on_write_error = on_write_error;
1168 dinfo->opts = opts;
1169 if (serial)
1170 strncpy(dinfo->serial, serial, sizeof(serial));
1171 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1173 switch(type) {
1174 case IF_IDE:
1175 case IF_SCSI:
1176 case IF_XEN:
1177 case IF_NONE:
1178 switch(media) {
1179 case MEDIA_DISK:
1180 if (cyls != 0) {
1181 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1182 bdrv_set_translation_hint(dinfo->bdrv, translation);
1184 break;
1185 case MEDIA_CDROM:
1186 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1187 break;
1189 break;
1190 case IF_SD:
1191 /* FIXME: This isn't really a floppy, but it's a reasonable
1192 approximation. */
1193 case IF_FLOPPY:
1194 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1195 break;
1196 case IF_PFLASH:
1197 case IF_MTD:
1198 break;
1199 case IF_VIRTIO:
1200 /* add virtio block device */
1201 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1202 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1203 qemu_opt_set(opts, "drive", dinfo->id);
1204 if (devaddr)
1205 qemu_opt_set(opts, "addr", devaddr);
1206 break;
1207 case IF_COUNT:
1208 abort();
1210 if (!file) {
1211 *fatal_error = 0;
1212 return NULL;
1214 bdrv_flags = 0;
1215 if (snapshot) {
1216 bdrv_flags |= BDRV_O_SNAPSHOT;
1217 cache = 2; /* always use write-back with snapshot */
1219 if (cache == 0) /* no caching */
1220 bdrv_flags |= BDRV_O_NOCACHE;
1221 else if (cache == 2) /* write-back */
1222 bdrv_flags |= BDRV_O_CACHE_WB;
1224 if (aio == 1) {
1225 bdrv_flags |= BDRV_O_NATIVE_AIO;
1226 } else {
1227 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1230 if (ro == 1) {
1231 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1232 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1233 return NULL;
1237 * cdrom is read-only. Set it now, after above interface checking
1238 * since readonly attribute not explicitly required, so no error.
1240 if (media == MEDIA_CDROM) {
1241 ro = 1;
1243 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1245 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1246 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1247 file, strerror(errno));
1248 return NULL;
1251 if (bdrv_key_required(dinfo->bdrv))
1252 autostart = 0;
1253 *fatal_error = 0;
1254 return dinfo;
1257 static int drive_init_func(QemuOpts *opts, void *opaque)
1259 QEMUMachine *machine = opaque;
1260 int fatal_error = 0;
1262 if (drive_init(opts, machine, &fatal_error) == NULL) {
1263 if (fatal_error)
1264 return 1;
1266 return 0;
1269 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1271 if (NULL == qemu_opt_get(opts, "snapshot")) {
1272 qemu_opt_set(opts, "snapshot", "on");
1274 return 0;
1277 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1279 boot_set_handler = func;
1280 boot_set_opaque = opaque;
1283 int qemu_boot_set(const char *boot_devices)
1285 if (!boot_set_handler) {
1286 return -EINVAL;
1288 return boot_set_handler(boot_set_opaque, boot_devices);
1291 static int parse_bootdevices(char *devices)
1293 /* We just do some generic consistency checks */
1294 const char *p;
1295 int bitmap = 0;
1297 for (p = devices; *p != '\0'; p++) {
1298 /* Allowed boot devices are:
1299 * a-b: floppy disk drives
1300 * c-f: IDE disk drives
1301 * g-m: machine implementation dependant drives
1302 * n-p: network devices
1303 * It's up to each machine implementation to check if the given boot
1304 * devices match the actual hardware implementation and firmware
1305 * features.
1307 if (*p < 'a' || *p > 'p') {
1308 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1309 exit(1);
1311 if (bitmap & (1 << (*p - 'a'))) {
1312 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1313 exit(1);
1315 bitmap |= 1 << (*p - 'a');
1317 return bitmap;
1320 static void restore_boot_devices(void *opaque)
1322 char *standard_boot_devices = opaque;
1324 qemu_boot_set(standard_boot_devices);
1326 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1327 qemu_free(standard_boot_devices);
1330 static void numa_add(const char *optarg)
1332 char option[128];
1333 char *endptr;
1334 unsigned long long value, endvalue;
1335 int nodenr;
1337 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1338 if (!strcmp(option, "node")) {
1339 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1340 nodenr = nb_numa_nodes;
1341 } else {
1342 nodenr = strtoull(option, NULL, 10);
1345 if (get_param_value(option, 128, "mem", optarg) == 0) {
1346 node_mem[nodenr] = 0;
1347 } else {
1348 value = strtoull(option, &endptr, 0);
1349 switch (*endptr) {
1350 case 0: case 'M': case 'm':
1351 value <<= 20;
1352 break;
1353 case 'G': case 'g':
1354 value <<= 30;
1355 break;
1357 node_mem[nodenr] = value;
1359 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1360 node_cpumask[nodenr] = 0;
1361 } else {
1362 value = strtoull(option, &endptr, 10);
1363 if (value >= 64) {
1364 value = 63;
1365 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1366 } else {
1367 if (*endptr == '-') {
1368 endvalue = strtoull(endptr+1, &endptr, 10);
1369 if (endvalue >= 63) {
1370 endvalue = 62;
1371 fprintf(stderr,
1372 "only 63 CPUs in NUMA mode supported.\n");
1374 value = (2ULL << endvalue) - (1ULL << value);
1375 } else {
1376 value = 1ULL << value;
1379 node_cpumask[nodenr] = value;
1381 nb_numa_nodes++;
1383 return;
1386 static void smp_parse(const char *optarg)
1388 int smp, sockets = 0, threads = 0, cores = 0;
1389 char *endptr;
1390 char option[128];
1392 smp = strtoul(optarg, &endptr, 10);
1393 if (endptr != optarg) {
1394 if (*endptr == ',') {
1395 endptr++;
1398 if (get_param_value(option, 128, "sockets", endptr) != 0)
1399 sockets = strtoull(option, NULL, 10);
1400 if (get_param_value(option, 128, "cores", endptr) != 0)
1401 cores = strtoull(option, NULL, 10);
1402 if (get_param_value(option, 128, "threads", endptr) != 0)
1403 threads = strtoull(option, NULL, 10);
1404 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1405 max_cpus = strtoull(option, NULL, 10);
1407 /* compute missing values, prefer sockets over cores over threads */
1408 if (smp == 0 || sockets == 0) {
1409 sockets = sockets > 0 ? sockets : 1;
1410 cores = cores > 0 ? cores : 1;
1411 threads = threads > 0 ? threads : 1;
1412 if (smp == 0) {
1413 smp = cores * threads * sockets;
1415 } else {
1416 if (cores == 0) {
1417 threads = threads > 0 ? threads : 1;
1418 cores = smp / (sockets * threads);
1419 } else {
1420 if (sockets) {
1421 threads = smp / (cores * sockets);
1425 smp_cpus = smp;
1426 smp_cores = cores > 0 ? cores : 1;
1427 smp_threads = threads > 0 ? threads : 1;
1428 if (max_cpus == 0)
1429 max_cpus = smp_cpus;
1432 /***********************************************************/
1433 /* USB devices */
1435 static int usb_device_add(const char *devname, int is_hotplug)
1437 const char *p;
1438 USBDevice *dev = NULL;
1440 if (!usb_enabled)
1441 return -1;
1443 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1444 dev = usbdevice_create(devname);
1445 if (dev)
1446 goto done;
1448 /* the other ones */
1449 if (strstart(devname, "host:", &p)) {
1450 dev = usb_host_device_open(p);
1451 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1452 dev = usb_bt_init(devname[2] ? hci_init(p) :
1453 bt_new_hci(qemu_find_bt_vlan(0)));
1454 } else {
1455 return -1;
1457 if (!dev)
1458 return -1;
1460 done:
1461 return 0;
1464 static int usb_device_del(const char *devname)
1466 int bus_num, addr;
1467 const char *p;
1469 if (strstart(devname, "host:", &p))
1470 return usb_host_device_close(p);
1472 if (!usb_enabled)
1473 return -1;
1475 p = strchr(devname, '.');
1476 if (!p)
1477 return -1;
1478 bus_num = strtoul(devname, NULL, 0);
1479 addr = strtoul(p + 1, NULL, 0);
1481 return usb_device_delete_addr(bus_num, addr);
1484 static int usb_parse(const char *cmdline)
1486 int r;
1487 r = usb_device_add(cmdline, 0);
1488 if (r < 0) {
1489 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1491 return r;
1494 void do_usb_add(Monitor *mon, const QDict *qdict)
1496 const char *devname = qdict_get_str(qdict, "devname");
1497 if (usb_device_add(devname, 1) < 0) {
1498 error_report("could not add USB device '%s'", devname);
1502 void do_usb_del(Monitor *mon, const QDict *qdict)
1504 const char *devname = qdict_get_str(qdict, "devname");
1505 if (usb_device_del(devname) < 0) {
1506 error_report("could not delete USB device '%s'", devname);
1510 /***********************************************************/
1511 /* PCMCIA/Cardbus */
1513 static struct pcmcia_socket_entry_s {
1514 PCMCIASocket *socket;
1515 struct pcmcia_socket_entry_s *next;
1516 } *pcmcia_sockets = 0;
1518 void pcmcia_socket_register(PCMCIASocket *socket)
1520 struct pcmcia_socket_entry_s *entry;
1522 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1523 entry->socket = socket;
1524 entry->next = pcmcia_sockets;
1525 pcmcia_sockets = entry;
1528 void pcmcia_socket_unregister(PCMCIASocket *socket)
1530 struct pcmcia_socket_entry_s *entry, **ptr;
1532 ptr = &pcmcia_sockets;
1533 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1534 if (entry->socket == socket) {
1535 *ptr = entry->next;
1536 qemu_free(entry);
1540 void pcmcia_info(Monitor *mon)
1542 struct pcmcia_socket_entry_s *iter;
1544 if (!pcmcia_sockets)
1545 monitor_printf(mon, "No PCMCIA sockets\n");
1547 for (iter = pcmcia_sockets; iter; iter = iter->next)
1548 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1549 iter->socket->attached ? iter->socket->card_string :
1550 "Empty");
1553 /***********************************************************/
1554 /* I/O handling */
1556 typedef struct IOHandlerRecord {
1557 int fd;
1558 IOCanReadHandler *fd_read_poll;
1559 IOHandler *fd_read;
1560 IOHandler *fd_write;
1561 int deleted;
1562 void *opaque;
1563 /* temporary data */
1564 struct pollfd *ufd;
1565 QLIST_ENTRY(IOHandlerRecord) next;
1566 } IOHandlerRecord;
1568 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1569 QLIST_HEAD_INITIALIZER(io_handlers);
1572 /* XXX: fd_read_poll should be suppressed, but an API change is
1573 necessary in the character devices to suppress fd_can_read(). */
1574 int qemu_set_fd_handler2(int fd,
1575 IOCanReadHandler *fd_read_poll,
1576 IOHandler *fd_read,
1577 IOHandler *fd_write,
1578 void *opaque)
1580 IOHandlerRecord *ioh;
1582 if (!fd_read && !fd_write) {
1583 QLIST_FOREACH(ioh, &io_handlers, next) {
1584 if (ioh->fd == fd) {
1585 ioh->deleted = 1;
1586 break;
1589 } else {
1590 QLIST_FOREACH(ioh, &io_handlers, next) {
1591 if (ioh->fd == fd)
1592 goto found;
1594 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1595 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1596 found:
1597 ioh->fd = fd;
1598 ioh->fd_read_poll = fd_read_poll;
1599 ioh->fd_read = fd_read;
1600 ioh->fd_write = fd_write;
1601 ioh->opaque = opaque;
1602 ioh->deleted = 0;
1604 return 0;
1607 int qemu_set_fd_handler(int fd,
1608 IOHandler *fd_read,
1609 IOHandler *fd_write,
1610 void *opaque)
1612 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1615 #ifdef _WIN32
1616 /***********************************************************/
1617 /* Polling handling */
1619 typedef struct PollingEntry {
1620 PollingFunc *func;
1621 void *opaque;
1622 struct PollingEntry *next;
1623 } PollingEntry;
1625 static PollingEntry *first_polling_entry;
1627 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1629 PollingEntry **ppe, *pe;
1630 pe = qemu_mallocz(sizeof(PollingEntry));
1631 pe->func = func;
1632 pe->opaque = opaque;
1633 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1634 *ppe = pe;
1635 return 0;
1638 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1640 PollingEntry **ppe, *pe;
1641 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1642 pe = *ppe;
1643 if (pe->func == func && pe->opaque == opaque) {
1644 *ppe = pe->next;
1645 qemu_free(pe);
1646 break;
1651 /***********************************************************/
1652 /* Wait objects support */
1653 typedef struct WaitObjects {
1654 int num;
1655 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1656 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1657 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1658 } WaitObjects;
1660 static WaitObjects wait_objects = {0};
1662 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1664 WaitObjects *w = &wait_objects;
1666 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1667 return -1;
1668 w->events[w->num] = handle;
1669 w->func[w->num] = func;
1670 w->opaque[w->num] = opaque;
1671 w->num++;
1672 return 0;
1675 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1677 int i, found;
1678 WaitObjects *w = &wait_objects;
1680 found = 0;
1681 for (i = 0; i < w->num; i++) {
1682 if (w->events[i] == handle)
1683 found = 1;
1684 if (found) {
1685 w->events[i] = w->events[i + 1];
1686 w->func[i] = w->func[i + 1];
1687 w->opaque[i] = w->opaque[i + 1];
1690 if (found)
1691 w->num--;
1693 #endif
1695 /***********************************************************/
1696 /* ram save/restore */
1698 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
1699 #define RAM_SAVE_FLAG_COMPRESS 0x02
1700 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
1701 #define RAM_SAVE_FLAG_PAGE 0x08
1702 #define RAM_SAVE_FLAG_EOS 0x10
1704 static int is_dup_page(uint8_t *page, uint8_t ch)
1706 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1707 uint32_t *array = (uint32_t *)page;
1708 int i;
1710 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1711 if (array[i] != val)
1712 return 0;
1715 return 1;
1718 static int ram_save_block(QEMUFile *f)
1720 static ram_addr_t current_addr = 0;
1721 ram_addr_t saved_addr = current_addr;
1722 ram_addr_t addr = 0;
1723 int found = 0;
1725 while (addr < last_ram_offset) {
1726 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1727 uint8_t *p;
1729 cpu_physical_memory_reset_dirty(current_addr,
1730 current_addr + TARGET_PAGE_SIZE,
1731 MIGRATION_DIRTY_FLAG);
1733 p = qemu_get_ram_ptr(current_addr);
1735 if (is_dup_page(p, *p)) {
1736 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1737 qemu_put_byte(f, *p);
1738 } else {
1739 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1740 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1743 found = 1;
1744 break;
1746 addr += TARGET_PAGE_SIZE;
1747 current_addr = (saved_addr + addr) % last_ram_offset;
1750 return found;
1753 static uint64_t bytes_transferred;
1755 static ram_addr_t ram_save_remaining(void)
1757 ram_addr_t addr;
1758 ram_addr_t count = 0;
1760 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1761 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1762 count++;
1765 return count;
1768 uint64_t ram_bytes_remaining(void)
1770 return ram_save_remaining() * TARGET_PAGE_SIZE;
1773 uint64_t ram_bytes_transferred(void)
1775 return bytes_transferred;
1778 uint64_t ram_bytes_total(void)
1780 return last_ram_offset;
1783 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1785 ram_addr_t addr;
1786 uint64_t bytes_transferred_last;
1787 double bwidth = 0;
1788 uint64_t expected_time = 0;
1790 if (stage < 0) {
1791 cpu_physical_memory_set_dirty_tracking(0);
1792 return 0;
1795 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1796 qemu_file_set_error(f);
1797 return 0;
1800 if (stage == 1) {
1801 bytes_transferred = 0;
1803 /* Make sure all dirty bits are set */
1804 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1805 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1806 cpu_physical_memory_set_dirty(addr);
1809 /* Enable dirty memory tracking */
1810 cpu_physical_memory_set_dirty_tracking(1);
1812 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1815 bytes_transferred_last = bytes_transferred;
1816 bwidth = qemu_get_clock_ns(rt_clock);
1818 while (!qemu_file_rate_limit(f)) {
1819 int ret;
1821 ret = ram_save_block(f);
1822 bytes_transferred += ret * TARGET_PAGE_SIZE;
1823 if (ret == 0) /* no more blocks */
1824 break;
1827 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1828 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1830 /* if we haven't transferred anything this round, force expected_time to a
1831 * a very high value, but without crashing */
1832 if (bwidth == 0)
1833 bwidth = 0.000001;
1835 /* try transferring iterative blocks of memory */
1836 if (stage == 3) {
1837 /* flush all remaining blocks regardless of rate limiting */
1838 while (ram_save_block(f) != 0) {
1839 bytes_transferred += TARGET_PAGE_SIZE;
1841 cpu_physical_memory_set_dirty_tracking(0);
1844 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1846 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1848 return (stage == 2) && (expected_time <= migrate_max_downtime());
1851 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1853 ram_addr_t addr;
1854 int flags;
1856 if (version_id != 3)
1857 return -EINVAL;
1859 do {
1860 addr = qemu_get_be64(f);
1862 flags = addr & ~TARGET_PAGE_MASK;
1863 addr &= TARGET_PAGE_MASK;
1865 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1866 if (addr != last_ram_offset)
1867 return -EINVAL;
1870 if (flags & RAM_SAVE_FLAG_COMPRESS) {
1871 uint8_t ch = qemu_get_byte(f);
1872 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1873 #ifndef _WIN32
1874 if (ch == 0 &&
1875 (!kvm_enabled() || kvm_has_sync_mmu())) {
1876 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1878 #endif
1879 } else if (flags & RAM_SAVE_FLAG_PAGE) {
1880 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1882 if (qemu_file_has_error(f)) {
1883 return -EIO;
1885 } while (!(flags & RAM_SAVE_FLAG_EOS));
1887 return 0;
1890 void qemu_service_io(void)
1892 qemu_notify_event();
1895 /***********************************************************/
1896 /* machine registration */
1898 static QEMUMachine *first_machine = NULL;
1899 QEMUMachine *current_machine = NULL;
1901 int qemu_register_machine(QEMUMachine *m)
1903 QEMUMachine **pm;
1904 pm = &first_machine;
1905 while (*pm != NULL)
1906 pm = &(*pm)->next;
1907 m->next = NULL;
1908 *pm = m;
1909 return 0;
1912 static QEMUMachine *find_machine(const char *name)
1914 QEMUMachine *m;
1916 for(m = first_machine; m != NULL; m = m->next) {
1917 if (!strcmp(m->name, name))
1918 return m;
1919 if (m->alias && !strcmp(m->alias, name))
1920 return m;
1922 return NULL;
1925 static QEMUMachine *find_default_machine(void)
1927 QEMUMachine *m;
1929 for(m = first_machine; m != NULL; m = m->next) {
1930 if (m->is_default) {
1931 return m;
1934 return NULL;
1937 /***********************************************************/
1938 /* main execution loop */
1940 static void gui_update(void *opaque)
1942 uint64_t interval = GUI_REFRESH_INTERVAL;
1943 DisplayState *ds = opaque;
1944 DisplayChangeListener *dcl = ds->listeners;
1946 qemu_flush_coalesced_mmio_buffer();
1947 dpy_refresh(ds);
1949 while (dcl != NULL) {
1950 if (dcl->gui_timer_interval &&
1951 dcl->gui_timer_interval < interval)
1952 interval = dcl->gui_timer_interval;
1953 dcl = dcl->next;
1955 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1958 static void nographic_update(void *opaque)
1960 uint64_t interval = GUI_REFRESH_INTERVAL;
1962 qemu_flush_coalesced_mmio_buffer();
1963 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1966 void cpu_synchronize_all_states(void)
1968 CPUState *cpu;
1970 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1971 cpu_synchronize_state(cpu);
1975 void cpu_synchronize_all_post_reset(void)
1977 CPUState *cpu;
1979 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1980 cpu_synchronize_post_reset(cpu);
1984 void cpu_synchronize_all_post_init(void)
1986 CPUState *cpu;
1988 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1989 cpu_synchronize_post_init(cpu);
1993 struct vm_change_state_entry {
1994 VMChangeStateHandler *cb;
1995 void *opaque;
1996 QLIST_ENTRY (vm_change_state_entry) entries;
1999 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
2001 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
2002 void *opaque)
2004 VMChangeStateEntry *e;
2006 e = qemu_mallocz(sizeof (*e));
2008 e->cb = cb;
2009 e->opaque = opaque;
2010 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
2011 return e;
2014 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
2016 QLIST_REMOVE (e, entries);
2017 qemu_free (e);
2020 static void vm_state_notify(int running, int reason)
2022 VMChangeStateEntry *e;
2024 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
2025 e->cb(e->opaque, running, reason);
2029 static void resume_all_vcpus(void);
2030 static void pause_all_vcpus(void);
2032 void vm_start(void)
2034 if (!vm_running) {
2035 cpu_enable_ticks();
2036 vm_running = 1;
2037 vm_state_notify(1, 0);
2038 resume_all_vcpus();
2042 /* reset/shutdown handler */
2044 typedef struct QEMUResetEntry {
2045 QTAILQ_ENTRY(QEMUResetEntry) entry;
2046 QEMUResetHandler *func;
2047 void *opaque;
2048 } QEMUResetEntry;
2050 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
2051 QTAILQ_HEAD_INITIALIZER(reset_handlers);
2052 static int reset_requested;
2053 static int shutdown_requested;
2054 static int powerdown_requested;
2055 static int debug_requested;
2056 static int vmstop_requested;
2058 int qemu_shutdown_requested(void)
2060 int r = shutdown_requested;
2061 shutdown_requested = 0;
2062 return r;
2065 int qemu_reset_requested(void)
2067 int r = reset_requested;
2068 reset_requested = 0;
2069 return r;
2072 int qemu_powerdown_requested(void)
2074 int r = powerdown_requested;
2075 powerdown_requested = 0;
2076 return r;
2079 static int qemu_debug_requested(void)
2081 int r = debug_requested;
2082 debug_requested = 0;
2083 return r;
2086 static int qemu_vmstop_requested(void)
2088 int r = vmstop_requested;
2089 vmstop_requested = 0;
2090 return r;
2093 static void do_vm_stop(int reason)
2095 if (vm_running) {
2096 cpu_disable_ticks();
2097 vm_running = 0;
2098 pause_all_vcpus();
2099 vm_state_notify(0, reason);
2100 monitor_protocol_event(QEVENT_STOP, NULL);
2104 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2106 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2108 re->func = func;
2109 re->opaque = opaque;
2110 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2113 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2115 QEMUResetEntry *re;
2117 QTAILQ_FOREACH(re, &reset_handlers, entry) {
2118 if (re->func == func && re->opaque == opaque) {
2119 QTAILQ_REMOVE(&reset_handlers, re, entry);
2120 qemu_free(re);
2121 return;
2126 void qemu_system_reset(void)
2128 QEMUResetEntry *re, *nre;
2130 /* reset all devices */
2131 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2132 re->func(re->opaque);
2134 monitor_protocol_event(QEVENT_RESET, NULL);
2135 cpu_synchronize_all_post_reset();
2138 void qemu_system_reset_request(void)
2140 if (no_reboot) {
2141 shutdown_requested = 1;
2142 } else {
2143 reset_requested = 1;
2145 qemu_notify_event();
2148 void qemu_system_shutdown_request(void)
2150 shutdown_requested = 1;
2151 qemu_notify_event();
2154 void qemu_system_powerdown_request(void)
2156 powerdown_requested = 1;
2157 qemu_notify_event();
2160 static int cpu_can_run(CPUState *env)
2162 if (env->stop)
2163 return 0;
2164 if (env->stopped)
2165 return 0;
2166 if (!vm_running)
2167 return 0;
2168 return 1;
2171 static int cpu_has_work(CPUState *env)
2173 if (env->stop)
2174 return 1;
2175 if (env->stopped)
2176 return 0;
2177 if (!env->halted)
2178 return 1;
2179 if (qemu_cpu_has_work(env))
2180 return 1;
2181 return 0;
2184 static int tcg_has_work(void)
2186 CPUState *env;
2188 for (env = first_cpu; env != NULL; env = env->next_cpu)
2189 if (cpu_has_work(env))
2190 return 1;
2191 return 0;
2194 #ifndef _WIN32
2195 static int io_thread_fd = -1;
2197 static void qemu_event_increment(void)
2199 /* Write 8 bytes to be compatible with eventfd. */
2200 static uint64_t val = 1;
2201 ssize_t ret;
2203 if (io_thread_fd == -1)
2204 return;
2206 do {
2207 ret = write(io_thread_fd, &val, sizeof(val));
2208 } while (ret < 0 && errno == EINTR);
2210 /* EAGAIN is fine, a read must be pending. */
2211 if (ret < 0 && errno != EAGAIN) {
2212 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
2213 strerror(errno));
2214 exit (1);
2218 static void qemu_event_read(void *opaque)
2220 int fd = (unsigned long)opaque;
2221 ssize_t len;
2222 char buffer[512];
2224 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
2225 do {
2226 len = read(fd, buffer, sizeof(buffer));
2227 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
2230 static int qemu_event_init(void)
2232 int err;
2233 int fds[2];
2235 err = qemu_eventfd(fds);
2236 if (err == -1)
2237 return -errno;
2239 err = fcntl_setfl(fds[0], O_NONBLOCK);
2240 if (err < 0)
2241 goto fail;
2243 err = fcntl_setfl(fds[1], O_NONBLOCK);
2244 if (err < 0)
2245 goto fail;
2247 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
2248 (void *)(unsigned long)fds[0]);
2250 io_thread_fd = fds[1];
2251 return 0;
2253 fail:
2254 close(fds[0]);
2255 close(fds[1]);
2256 return err;
2258 #else
2259 HANDLE qemu_event_handle;
2261 static void dummy_event_handler(void *opaque)
2265 static int qemu_event_init(void)
2267 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
2268 if (!qemu_event_handle) {
2269 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
2270 return -1;
2272 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
2273 return 0;
2276 static void qemu_event_increment(void)
2278 if (!SetEvent(qemu_event_handle)) {
2279 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
2280 GetLastError());
2281 exit (1);
2284 #endif
2286 #ifndef CONFIG_IOTHREAD
2287 static int qemu_init_main_loop(void)
2289 return qemu_event_init();
2292 void qemu_init_vcpu(void *_env)
2294 CPUState *env = _env;
2296 env->nr_cores = smp_cores;
2297 env->nr_threads = smp_threads;
2298 if (kvm_enabled())
2299 kvm_init_vcpu(env);
2300 return;
2303 int qemu_cpu_self(void *env)
2305 return 1;
2308 static void resume_all_vcpus(void)
2312 static void pause_all_vcpus(void)
2316 void qemu_cpu_kick(void *env)
2318 return;
2321 void qemu_notify_event(void)
2323 CPUState *env = cpu_single_env;
2325 qemu_event_increment ();
2326 if (env) {
2327 cpu_exit(env);
2329 if (next_cpu && env != next_cpu) {
2330 cpu_exit(next_cpu);
2334 void qemu_mutex_lock_iothread(void) {}
2335 void qemu_mutex_unlock_iothread(void) {}
2337 void vm_stop(int reason)
2339 do_vm_stop(reason);
2342 #else /* CONFIG_IOTHREAD */
2344 #include "qemu-thread.h"
2346 QemuMutex qemu_global_mutex;
2347 static QemuMutex qemu_fair_mutex;
2349 static QemuThread io_thread;
2351 static QemuThread *tcg_cpu_thread;
2352 static QemuCond *tcg_halt_cond;
2354 static int qemu_system_ready;
2355 /* cpu creation */
2356 static QemuCond qemu_cpu_cond;
2357 /* system init */
2358 static QemuCond qemu_system_cond;
2359 static QemuCond qemu_pause_cond;
2361 static void tcg_block_io_signals(void);
2362 static void kvm_block_io_signals(CPUState *env);
2363 static void unblock_io_signals(void);
2365 static int qemu_init_main_loop(void)
2367 int ret;
2369 ret = qemu_event_init();
2370 if (ret)
2371 return ret;
2373 qemu_cond_init(&qemu_pause_cond);
2374 qemu_mutex_init(&qemu_fair_mutex);
2375 qemu_mutex_init(&qemu_global_mutex);
2376 qemu_mutex_lock(&qemu_global_mutex);
2378 unblock_io_signals();
2379 qemu_thread_self(&io_thread);
2381 return 0;
2384 static void qemu_wait_io_event_common(CPUState *env)
2386 if (env->stop) {
2387 env->stop = 0;
2388 env->stopped = 1;
2389 qemu_cond_signal(&qemu_pause_cond);
2393 static void qemu_wait_io_event(CPUState *env)
2395 while (!tcg_has_work())
2396 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2398 qemu_mutex_unlock(&qemu_global_mutex);
2401 * Users of qemu_global_mutex can be starved, having no chance
2402 * to acquire it since this path will get to it first.
2403 * So use another lock to provide fairness.
2405 qemu_mutex_lock(&qemu_fair_mutex);
2406 qemu_mutex_unlock(&qemu_fair_mutex);
2408 qemu_mutex_lock(&qemu_global_mutex);
2409 qemu_wait_io_event_common(env);
2412 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
2414 struct timespec ts;
2415 int r, e;
2416 siginfo_t siginfo;
2417 sigset_t waitset;
2419 ts.tv_sec = timeout / 1000;
2420 ts.tv_nsec = (timeout % 1000) * 1000000;
2422 sigemptyset(&waitset);
2423 sigaddset(&waitset, SIG_IPI);
2425 qemu_mutex_unlock(&qemu_global_mutex);
2426 r = sigtimedwait(&waitset, &siginfo, &ts);
2427 e = errno;
2428 qemu_mutex_lock(&qemu_global_mutex);
2430 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
2431 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
2432 exit(1);
2436 static void qemu_kvm_wait_io_event(CPUState *env)
2438 while (!cpu_has_work(env))
2439 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2441 qemu_kvm_eat_signal(env, 0);
2442 qemu_wait_io_event_common(env);
2445 static int qemu_cpu_exec(CPUState *env);
2447 static void *kvm_cpu_thread_fn(void *arg)
2449 CPUState *env = arg;
2451 qemu_thread_self(env->thread);
2452 if (kvm_enabled())
2453 kvm_init_vcpu(env);
2455 kvm_block_io_signals(env);
2457 /* signal CPU creation */
2458 qemu_mutex_lock(&qemu_global_mutex);
2459 env->created = 1;
2460 qemu_cond_signal(&qemu_cpu_cond);
2462 /* and wait for machine initialization */
2463 while (!qemu_system_ready)
2464 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2466 while (1) {
2467 if (cpu_can_run(env))
2468 qemu_cpu_exec(env);
2469 qemu_kvm_wait_io_event(env);
2472 return NULL;
2475 static bool tcg_cpu_exec(void);
2477 static void *tcg_cpu_thread_fn(void *arg)
2479 CPUState *env = arg;
2481 tcg_block_io_signals();
2482 qemu_thread_self(env->thread);
2484 /* signal CPU creation */
2485 qemu_mutex_lock(&qemu_global_mutex);
2486 for (env = first_cpu; env != NULL; env = env->next_cpu)
2487 env->created = 1;
2488 qemu_cond_signal(&qemu_cpu_cond);
2490 /* and wait for machine initialization */
2491 while (!qemu_system_ready)
2492 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2494 while (1) {
2495 tcg_cpu_exec();
2496 qemu_wait_io_event(cur_cpu);
2499 return NULL;
2502 void qemu_cpu_kick(void *_env)
2504 CPUState *env = _env;
2505 qemu_cond_broadcast(env->halt_cond);
2506 if (kvm_enabled())
2507 qemu_thread_signal(env->thread, SIG_IPI);
2510 int qemu_cpu_self(void *_env)
2512 CPUState *env = _env;
2513 QemuThread this;
2515 qemu_thread_self(&this);
2517 return qemu_thread_equal(&this, env->thread);
2520 static void cpu_signal(int sig)
2522 if (cpu_single_env)
2523 cpu_exit(cpu_single_env);
2526 static void tcg_block_io_signals(void)
2528 sigset_t set;
2529 struct sigaction sigact;
2531 sigemptyset(&set);
2532 sigaddset(&set, SIGUSR2);
2533 sigaddset(&set, SIGIO);
2534 sigaddset(&set, SIGALRM);
2535 sigaddset(&set, SIGCHLD);
2536 pthread_sigmask(SIG_BLOCK, &set, NULL);
2538 sigemptyset(&set);
2539 sigaddset(&set, SIG_IPI);
2540 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2542 memset(&sigact, 0, sizeof(sigact));
2543 sigact.sa_handler = cpu_signal;
2544 sigaction(SIG_IPI, &sigact, NULL);
2547 static void dummy_signal(int sig)
2551 static void kvm_block_io_signals(CPUState *env)
2553 int r;
2554 sigset_t set;
2555 struct sigaction sigact;
2557 sigemptyset(&set);
2558 sigaddset(&set, SIGUSR2);
2559 sigaddset(&set, SIGIO);
2560 sigaddset(&set, SIGALRM);
2561 sigaddset(&set, SIGCHLD);
2562 sigaddset(&set, SIG_IPI);
2563 pthread_sigmask(SIG_BLOCK, &set, NULL);
2565 pthread_sigmask(SIG_BLOCK, NULL, &set);
2566 sigdelset(&set, SIG_IPI);
2568 memset(&sigact, 0, sizeof(sigact));
2569 sigact.sa_handler = dummy_signal;
2570 sigaction(SIG_IPI, &sigact, NULL);
2572 r = kvm_set_signal_mask(env, &set);
2573 if (r) {
2574 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
2575 exit(1);
2579 static void unblock_io_signals(void)
2581 sigset_t set;
2583 sigemptyset(&set);
2584 sigaddset(&set, SIGUSR2);
2585 sigaddset(&set, SIGIO);
2586 sigaddset(&set, SIGALRM);
2587 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2589 sigemptyset(&set);
2590 sigaddset(&set, SIG_IPI);
2591 pthread_sigmask(SIG_BLOCK, &set, NULL);
2594 static void qemu_signal_lock(unsigned int msecs)
2596 qemu_mutex_lock(&qemu_fair_mutex);
2598 while (qemu_mutex_trylock(&qemu_global_mutex)) {
2599 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
2600 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
2601 break;
2603 qemu_mutex_unlock(&qemu_fair_mutex);
2606 void qemu_mutex_lock_iothread(void)
2608 if (kvm_enabled()) {
2609 qemu_mutex_lock(&qemu_fair_mutex);
2610 qemu_mutex_lock(&qemu_global_mutex);
2611 qemu_mutex_unlock(&qemu_fair_mutex);
2612 } else
2613 qemu_signal_lock(100);
2616 void qemu_mutex_unlock_iothread(void)
2618 qemu_mutex_unlock(&qemu_global_mutex);
2621 static int all_vcpus_paused(void)
2623 CPUState *penv = first_cpu;
2625 while (penv) {
2626 if (!penv->stopped)
2627 return 0;
2628 penv = (CPUState *)penv->next_cpu;
2631 return 1;
2634 static void pause_all_vcpus(void)
2636 CPUState *penv = first_cpu;
2638 while (penv) {
2639 penv->stop = 1;
2640 qemu_thread_signal(penv->thread, SIG_IPI);
2641 qemu_cpu_kick(penv);
2642 penv = (CPUState *)penv->next_cpu;
2645 while (!all_vcpus_paused()) {
2646 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
2647 penv = first_cpu;
2648 while (penv) {
2649 qemu_thread_signal(penv->thread, SIG_IPI);
2650 penv = (CPUState *)penv->next_cpu;
2655 static void resume_all_vcpus(void)
2657 CPUState *penv = first_cpu;
2659 while (penv) {
2660 penv->stop = 0;
2661 penv->stopped = 0;
2662 qemu_thread_signal(penv->thread, SIG_IPI);
2663 qemu_cpu_kick(penv);
2664 penv = (CPUState *)penv->next_cpu;
2668 static void tcg_init_vcpu(void *_env)
2670 CPUState *env = _env;
2671 /* share a single thread for all cpus with TCG */
2672 if (!tcg_cpu_thread) {
2673 env->thread = qemu_mallocz(sizeof(QemuThread));
2674 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2675 qemu_cond_init(env->halt_cond);
2676 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
2677 while (env->created == 0)
2678 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2679 tcg_cpu_thread = env->thread;
2680 tcg_halt_cond = env->halt_cond;
2681 } else {
2682 env->thread = tcg_cpu_thread;
2683 env->halt_cond = tcg_halt_cond;
2687 static void kvm_start_vcpu(CPUState *env)
2689 env->thread = qemu_mallocz(sizeof(QemuThread));
2690 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2691 qemu_cond_init(env->halt_cond);
2692 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
2693 while (env->created == 0)
2694 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2697 void qemu_init_vcpu(void *_env)
2699 CPUState *env = _env;
2701 env->nr_cores = smp_cores;
2702 env->nr_threads = smp_threads;
2703 if (kvm_enabled())
2704 kvm_start_vcpu(env);
2705 else
2706 tcg_init_vcpu(env);
2709 void qemu_notify_event(void)
2711 qemu_event_increment();
2714 static void qemu_system_vmstop_request(int reason)
2716 vmstop_requested = reason;
2717 qemu_notify_event();
2720 void vm_stop(int reason)
2722 QemuThread me;
2723 qemu_thread_self(&me);
2725 if (!qemu_thread_equal(&me, &io_thread)) {
2726 qemu_system_vmstop_request(reason);
2728 * FIXME: should not return to device code in case
2729 * vm_stop() has been requested.
2731 if (cpu_single_env) {
2732 cpu_exit(cpu_single_env);
2733 cpu_single_env->stop = 1;
2735 return;
2737 do_vm_stop(reason);
2740 #endif
2743 #ifdef _WIN32
2744 static void host_main_loop_wait(int *timeout)
2746 int ret, ret2, i;
2747 PollingEntry *pe;
2750 /* XXX: need to suppress polling by better using win32 events */
2751 ret = 0;
2752 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2753 ret |= pe->func(pe->opaque);
2755 if (ret == 0) {
2756 int err;
2757 WaitObjects *w = &wait_objects;
2759 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2760 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2761 if (w->func[ret - WAIT_OBJECT_0])
2762 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2764 /* Check for additional signaled events */
2765 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2767 /* Check if event is signaled */
2768 ret2 = WaitForSingleObject(w->events[i], 0);
2769 if(ret2 == WAIT_OBJECT_0) {
2770 if (w->func[i])
2771 w->func[i](w->opaque[i]);
2772 } else if (ret2 == WAIT_TIMEOUT) {
2773 } else {
2774 err = GetLastError();
2775 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2778 } else if (ret == WAIT_TIMEOUT) {
2779 } else {
2780 err = GetLastError();
2781 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2785 *timeout = 0;
2787 #else
2788 static void host_main_loop_wait(int *timeout)
2791 #endif
2793 void main_loop_wait(int nonblocking)
2795 IOHandlerRecord *ioh;
2796 fd_set rfds, wfds, xfds;
2797 int ret, nfds;
2798 struct timeval tv;
2799 int timeout;
2801 if (nonblocking)
2802 timeout = 0;
2803 else {
2804 timeout = qemu_calculate_timeout();
2805 qemu_bh_update_timeout(&timeout);
2808 host_main_loop_wait(&timeout);
2810 /* poll any events */
2811 /* XXX: separate device handlers from system ones */
2812 nfds = -1;
2813 FD_ZERO(&rfds);
2814 FD_ZERO(&wfds);
2815 FD_ZERO(&xfds);
2816 QLIST_FOREACH(ioh, &io_handlers, next) {
2817 if (ioh->deleted)
2818 continue;
2819 if (ioh->fd_read &&
2820 (!ioh->fd_read_poll ||
2821 ioh->fd_read_poll(ioh->opaque) != 0)) {
2822 FD_SET(ioh->fd, &rfds);
2823 if (ioh->fd > nfds)
2824 nfds = ioh->fd;
2826 if (ioh->fd_write) {
2827 FD_SET(ioh->fd, &wfds);
2828 if (ioh->fd > nfds)
2829 nfds = ioh->fd;
2833 tv.tv_sec = timeout / 1000;
2834 tv.tv_usec = (timeout % 1000) * 1000;
2836 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2838 qemu_mutex_unlock_iothread();
2839 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2840 qemu_mutex_lock_iothread();
2841 if (ret > 0) {
2842 IOHandlerRecord *pioh;
2844 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
2845 if (ioh->deleted) {
2846 QLIST_REMOVE(ioh, next);
2847 qemu_free(ioh);
2848 continue;
2850 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2851 ioh->fd_read(ioh->opaque);
2853 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2854 ioh->fd_write(ioh->opaque);
2859 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2861 qemu_run_all_timers();
2863 /* Check bottom-halves last in case any of the earlier events triggered
2864 them. */
2865 qemu_bh_poll();
2869 static int qemu_cpu_exec(CPUState *env)
2871 int ret;
2872 #ifdef CONFIG_PROFILER
2873 int64_t ti;
2874 #endif
2876 #ifdef CONFIG_PROFILER
2877 ti = profile_getclock();
2878 #endif
2879 if (use_icount) {
2880 int64_t count;
2881 int decr;
2882 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
2883 env->icount_decr.u16.low = 0;
2884 env->icount_extra = 0;
2885 count = qemu_icount_round (qemu_next_deadline());
2886 qemu_icount += count;
2887 decr = (count > 0xffff) ? 0xffff : count;
2888 count -= decr;
2889 env->icount_decr.u16.low = decr;
2890 env->icount_extra = count;
2892 ret = cpu_exec(env);
2893 #ifdef CONFIG_PROFILER
2894 qemu_time += profile_getclock() - ti;
2895 #endif
2896 if (use_icount) {
2897 /* Fold pending instructions back into the
2898 instruction counter, and clear the interrupt flag. */
2899 qemu_icount -= (env->icount_decr.u16.low
2900 + env->icount_extra);
2901 env->icount_decr.u32 = 0;
2902 env->icount_extra = 0;
2904 return ret;
2907 static bool tcg_cpu_exec(void)
2909 int ret = 0;
2911 if (next_cpu == NULL)
2912 next_cpu = first_cpu;
2913 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
2914 CPUState *env = cur_cpu = next_cpu;
2916 qemu_clock_enable(vm_clock,
2917 (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
2919 if (qemu_alarm_pending())
2920 break;
2921 if (cpu_can_run(env))
2922 ret = qemu_cpu_exec(env);
2923 else if (env->stop)
2924 break;
2926 if (ret == EXCP_DEBUG) {
2927 gdb_set_stop_cpu(env);
2928 debug_requested = 1;
2929 break;
2932 return tcg_has_work();
2935 static int vm_can_run(void)
2937 if (powerdown_requested)
2938 return 0;
2939 if (reset_requested)
2940 return 0;
2941 if (shutdown_requested)
2942 return 0;
2943 if (debug_requested)
2944 return 0;
2945 return 1;
2948 qemu_irq qemu_system_powerdown;
2950 static void main_loop(void)
2952 int r;
2954 #ifdef CONFIG_IOTHREAD
2955 qemu_system_ready = 1;
2956 qemu_cond_broadcast(&qemu_system_cond);
2957 #endif
2959 for (;;) {
2960 do {
2961 bool nonblocking = false;
2962 #ifdef CONFIG_PROFILER
2963 int64_t ti;
2964 #endif
2965 #ifndef CONFIG_IOTHREAD
2966 nonblocking = tcg_cpu_exec();
2967 #endif
2968 #ifdef CONFIG_PROFILER
2969 ti = profile_getclock();
2970 #endif
2971 main_loop_wait(nonblocking);
2972 #ifdef CONFIG_PROFILER
2973 dev_time += profile_getclock() - ti;
2974 #endif
2975 } while (vm_can_run());
2977 if (qemu_debug_requested()) {
2978 vm_stop(EXCP_DEBUG);
2980 if (qemu_shutdown_requested()) {
2981 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2982 if (no_shutdown) {
2983 vm_stop(0);
2984 no_shutdown = 0;
2985 } else
2986 break;
2988 if (qemu_reset_requested()) {
2989 pause_all_vcpus();
2990 qemu_system_reset();
2991 resume_all_vcpus();
2993 if (qemu_powerdown_requested()) {
2994 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
2995 qemu_irq_raise(qemu_system_powerdown);
2997 if ((r = qemu_vmstop_requested())) {
2998 vm_stop(r);
3001 pause_all_vcpus();
3004 static void version(void)
3006 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3009 static void help(int exitcode)
3011 const char *options_help =
3012 #define DEF(option, opt_arg, opt_enum, opt_help) \
3013 opt_help
3014 #define DEFHEADING(text) stringify(text) "\n"
3015 #include "qemu-options.h"
3016 #undef DEF
3017 #undef DEFHEADING
3018 #undef GEN_DOCS
3020 version();
3021 printf("usage: %s [options] [disk_image]\n"
3022 "\n"
3023 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3024 "\n"
3025 "%s\n"
3026 "During emulation, the following keys are useful:\n"
3027 "ctrl-alt-f toggle full screen\n"
3028 "ctrl-alt-n switch to virtual console 'n'\n"
3029 "ctrl-alt toggle mouse and keyboard grab\n"
3030 "\n"
3031 "When using -nographic, press 'ctrl-a h' to get some help.\n",
3032 "qemu",
3033 options_help);
3034 exit(exitcode);
3037 #define HAS_ARG 0x0001
3039 enum {
3040 #define DEF(option, opt_arg, opt_enum, opt_help) \
3041 opt_enum,
3042 #define DEFHEADING(text)
3043 #include "qemu-options.h"
3044 #undef DEF
3045 #undef DEFHEADING
3046 #undef GEN_DOCS
3049 typedef struct QEMUOption {
3050 const char *name;
3051 int flags;
3052 int index;
3053 } QEMUOption;
3055 static const QEMUOption qemu_options[] = {
3056 { "h", 0, QEMU_OPTION_h },
3057 #define DEF(option, opt_arg, opt_enum, opt_help) \
3058 { option, opt_arg, opt_enum },
3059 #define DEFHEADING(text)
3060 #include "qemu-options.h"
3061 #undef DEF
3062 #undef DEFHEADING
3063 #undef GEN_DOCS
3064 { NULL },
3067 #ifdef HAS_AUDIO
3068 struct soundhw soundhw[] = {
3069 #ifdef HAS_AUDIO_CHOICE
3070 #if defined(TARGET_I386) || defined(TARGET_MIPS)
3072 "pcspk",
3073 "PC speaker",
3076 { .init_isa = pcspk_audio_init }
3078 #endif
3080 #ifdef CONFIG_SB16
3082 "sb16",
3083 "Creative Sound Blaster 16",
3086 { .init_isa = SB16_init }
3088 #endif
3090 #ifdef CONFIG_CS4231A
3092 "cs4231a",
3093 "CS4231A",
3096 { .init_isa = cs4231a_init }
3098 #endif
3100 #ifdef CONFIG_ADLIB
3102 "adlib",
3103 #ifdef HAS_YMF262
3104 "Yamaha YMF262 (OPL3)",
3105 #else
3106 "Yamaha YM3812 (OPL2)",
3107 #endif
3110 { .init_isa = Adlib_init }
3112 #endif
3114 #ifdef CONFIG_GUS
3116 "gus",
3117 "Gravis Ultrasound GF1",
3120 { .init_isa = GUS_init }
3122 #endif
3124 #ifdef CONFIG_AC97
3126 "ac97",
3127 "Intel 82801AA AC97 Audio",
3130 { .init_pci = ac97_init }
3132 #endif
3134 #ifdef CONFIG_ES1370
3136 "es1370",
3137 "ENSONIQ AudioPCI ES1370",
3140 { .init_pci = es1370_init }
3142 #endif
3144 #endif /* HAS_AUDIO_CHOICE */
3146 { NULL, NULL, 0, 0, { NULL } }
3149 static void select_soundhw (const char *optarg)
3151 struct soundhw *c;
3153 if (*optarg == '?') {
3154 show_valid_cards:
3156 printf ("Valid sound card names (comma separated):\n");
3157 for (c = soundhw; c->name; ++c) {
3158 printf ("%-11s %s\n", c->name, c->descr);
3160 printf ("\n-soundhw all will enable all of the above\n");
3161 exit (*optarg != '?');
3163 else {
3164 size_t l;
3165 const char *p;
3166 char *e;
3167 int bad_card = 0;
3169 if (!strcmp (optarg, "all")) {
3170 for (c = soundhw; c->name; ++c) {
3171 c->enabled = 1;
3173 return;
3176 p = optarg;
3177 while (*p) {
3178 e = strchr (p, ',');
3179 l = !e ? strlen (p) : (size_t) (e - p);
3181 for (c = soundhw; c->name; ++c) {
3182 if (!strncmp (c->name, p, l) && !c->name[l]) {
3183 c->enabled = 1;
3184 break;
3188 if (!c->name) {
3189 if (l > 80) {
3190 fprintf (stderr,
3191 "Unknown sound card name (too big to show)\n");
3193 else {
3194 fprintf (stderr, "Unknown sound card name `%.*s'\n",
3195 (int) l, p);
3197 bad_card = 1;
3199 p += l + (e != NULL);
3202 if (bad_card)
3203 goto show_valid_cards;
3206 #endif
3208 static void select_vgahw (const char *p)
3210 const char *opts;
3212 default_vga = 0;
3213 vga_interface_type = VGA_NONE;
3214 if (strstart(p, "std", &opts)) {
3215 vga_interface_type = VGA_STD;
3216 } else if (strstart(p, "cirrus", &opts)) {
3217 vga_interface_type = VGA_CIRRUS;
3218 } else if (strstart(p, "vmware", &opts)) {
3219 vga_interface_type = VGA_VMWARE;
3220 } else if (strstart(p, "xenfb", &opts)) {
3221 vga_interface_type = VGA_XENFB;
3222 } else if (!strstart(p, "none", &opts)) {
3223 invalid_vga:
3224 fprintf(stderr, "Unknown vga type: %s\n", p);
3225 exit(1);
3227 while (*opts) {
3228 const char *nextopt;
3230 if (strstart(opts, ",retrace=", &nextopt)) {
3231 opts = nextopt;
3232 if (strstart(opts, "dumb", &nextopt))
3233 vga_retrace_method = VGA_RETRACE_DUMB;
3234 else if (strstart(opts, "precise", &nextopt))
3235 vga_retrace_method = VGA_RETRACE_PRECISE;
3236 else goto invalid_vga;
3237 } else goto invalid_vga;
3238 opts = nextopt;
3242 #ifdef TARGET_I386
3243 static int balloon_parse(const char *arg)
3245 QemuOpts *opts;
3247 if (strcmp(arg, "none") == 0) {
3248 return 0;
3251 if (!strncmp(arg, "virtio", 6)) {
3252 if (arg[6] == ',') {
3253 /* have params -> parse them */
3254 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
3255 if (!opts)
3256 return -1;
3257 } else {
3258 /* create empty opts */
3259 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3261 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
3262 return 0;
3265 return -1;
3267 #endif
3269 #ifdef _WIN32
3270 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
3272 exit(STATUS_CONTROL_C_EXIT);
3273 return TRUE;
3275 #endif
3277 int qemu_uuid_parse(const char *str, uint8_t *uuid)
3279 int ret;
3281 if(strlen(str) != 36)
3282 return -1;
3284 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
3285 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
3286 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
3288 if(ret != 16)
3289 return -1;
3291 #ifdef TARGET_I386
3292 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
3293 #endif
3295 return 0;
3298 #ifndef _WIN32
3300 static void termsig_handler(int signal)
3302 qemu_system_shutdown_request();
3305 static void sigchld_handler(int signal)
3307 waitpid(-1, NULL, WNOHANG);
3310 static void sighandler_setup(void)
3312 struct sigaction act;
3314 memset(&act, 0, sizeof(act));
3315 act.sa_handler = termsig_handler;
3316 sigaction(SIGINT, &act, NULL);
3317 sigaction(SIGHUP, &act, NULL);
3318 sigaction(SIGTERM, &act, NULL);
3320 act.sa_handler = sigchld_handler;
3321 act.sa_flags = SA_NOCLDSTOP;
3322 sigaction(SIGCHLD, &act, NULL);
3325 #endif
3327 #ifdef _WIN32
3328 /* Look for support files in the same directory as the executable. */
3329 static char *find_datadir(const char *argv0)
3331 char *p;
3332 char buf[MAX_PATH];
3333 DWORD len;
3335 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
3336 if (len == 0) {
3337 return NULL;
3340 buf[len] = 0;
3341 p = buf + len - 1;
3342 while (p != buf && *p != '\\')
3343 p--;
3344 *p = 0;
3345 if (access(buf, R_OK) == 0) {
3346 return qemu_strdup(buf);
3348 return NULL;
3350 #else /* !_WIN32 */
3352 /* Find a likely location for support files using the location of the binary.
3353 For installed binaries this will be "$bindir/../share/qemu". When
3354 running from the build tree this will be "$bindir/../pc-bios". */
3355 #define SHARE_SUFFIX "/share/qemu"
3356 #define BUILD_SUFFIX "/pc-bios"
3357 static char *find_datadir(const char *argv0)
3359 char *dir;
3360 char *p = NULL;
3361 char *res;
3362 char buf[PATH_MAX];
3363 size_t max_len;
3365 #if defined(__linux__)
3367 int len;
3368 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
3369 if (len > 0) {
3370 buf[len] = 0;
3371 p = buf;
3374 #elif defined(__FreeBSD__)
3376 int len;
3377 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
3378 if (len > 0) {
3379 buf[len] = 0;
3380 p = buf;
3383 #endif
3384 /* If we don't have any way of figuring out the actual executable
3385 location then try argv[0]. */
3386 if (!p) {
3387 p = realpath(argv0, buf);
3388 if (!p) {
3389 return NULL;
3392 dir = dirname(p);
3393 dir = dirname(dir);
3395 max_len = strlen(dir) +
3396 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
3397 res = qemu_mallocz(max_len);
3398 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
3399 if (access(res, R_OK)) {
3400 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
3401 if (access(res, R_OK)) {
3402 qemu_free(res);
3403 res = NULL;
3407 return res;
3409 #undef SHARE_SUFFIX
3410 #undef BUILD_SUFFIX
3411 #endif
3413 char *qemu_find_file(int type, const char *name)
3415 int len;
3416 const char *subdir;
3417 char *buf;
3419 /* If name contains path separators then try it as a straight path. */
3420 if ((strchr(name, '/') || strchr(name, '\\'))
3421 && access(name, R_OK) == 0) {
3422 return qemu_strdup(name);
3424 switch (type) {
3425 case QEMU_FILE_TYPE_BIOS:
3426 subdir = "";
3427 break;
3428 case QEMU_FILE_TYPE_KEYMAP:
3429 subdir = "keymaps/";
3430 break;
3431 default:
3432 abort();
3434 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
3435 buf = qemu_mallocz(len);
3436 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
3437 if (access(buf, R_OK)) {
3438 qemu_free(buf);
3439 return NULL;
3441 return buf;
3444 static int device_help_func(QemuOpts *opts, void *opaque)
3446 return qdev_device_help(opts);
3449 static int device_init_func(QemuOpts *opts, void *opaque)
3451 DeviceState *dev;
3453 dev = qdev_device_add(opts);
3454 if (!dev)
3455 return -1;
3456 return 0;
3459 static int chardev_init_func(QemuOpts *opts, void *opaque)
3461 CharDriverState *chr;
3463 chr = qemu_chr_open_opts(opts, NULL);
3464 if (!chr)
3465 return -1;
3466 return 0;
3469 static int mon_init_func(QemuOpts *opts, void *opaque)
3471 CharDriverState *chr;
3472 const char *chardev;
3473 const char *mode;
3474 int flags;
3476 mode = qemu_opt_get(opts, "mode");
3477 if (mode == NULL) {
3478 mode = "readline";
3480 if (strcmp(mode, "readline") == 0) {
3481 flags = MONITOR_USE_READLINE;
3482 } else if (strcmp(mode, "control") == 0) {
3483 flags = MONITOR_USE_CONTROL;
3484 } else {
3485 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
3486 exit(1);
3489 if (qemu_opt_get_bool(opts, "default", 0))
3490 flags |= MONITOR_IS_DEFAULT;
3492 chardev = qemu_opt_get(opts, "chardev");
3493 chr = qemu_chr_find(chardev);
3494 if (chr == NULL) {
3495 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
3496 exit(1);
3499 monitor_init(chr, flags);
3500 return 0;
3503 static void monitor_parse(const char *optarg, const char *mode)
3505 static int monitor_device_index = 0;
3506 QemuOpts *opts;
3507 const char *p;
3508 char label[32];
3509 int def = 0;
3511 if (strstart(optarg, "chardev:", &p)) {
3512 snprintf(label, sizeof(label), "%s", p);
3513 } else {
3514 if (monitor_device_index) {
3515 snprintf(label, sizeof(label), "monitor%d",
3516 monitor_device_index);
3517 } else {
3518 snprintf(label, sizeof(label), "monitor");
3519 def = 1;
3521 opts = qemu_chr_parse_compat(label, optarg);
3522 if (!opts) {
3523 fprintf(stderr, "parse error: %s\n", optarg);
3524 exit(1);
3528 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
3529 if (!opts) {
3530 fprintf(stderr, "duplicate chardev: %s\n", label);
3531 exit(1);
3533 qemu_opt_set(opts, "mode", mode);
3534 qemu_opt_set(opts, "chardev", label);
3535 if (def)
3536 qemu_opt_set(opts, "default", "on");
3537 monitor_device_index++;
3540 struct device_config {
3541 enum {
3542 DEV_USB, /* -usbdevice */
3543 DEV_BT, /* -bt */
3544 DEV_SERIAL, /* -serial */
3545 DEV_PARALLEL, /* -parallel */
3546 DEV_VIRTCON, /* -virtioconsole */
3547 DEV_DEBUGCON, /* -debugcon */
3548 } type;
3549 const char *cmdline;
3550 QTAILQ_ENTRY(device_config) next;
3552 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
3554 static void add_device_config(int type, const char *cmdline)
3556 struct device_config *conf;
3558 conf = qemu_mallocz(sizeof(*conf));
3559 conf->type = type;
3560 conf->cmdline = cmdline;
3561 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
3564 static int foreach_device_config(int type, int (*func)(const char *cmdline))
3566 struct device_config *conf;
3567 int rc;
3569 QTAILQ_FOREACH(conf, &device_configs, next) {
3570 if (conf->type != type)
3571 continue;
3572 rc = func(conf->cmdline);
3573 if (0 != rc)
3574 return rc;
3576 return 0;
3579 static int serial_parse(const char *devname)
3581 static int index = 0;
3582 char label[32];
3584 if (strcmp(devname, "none") == 0)
3585 return 0;
3586 if (index == MAX_SERIAL_PORTS) {
3587 fprintf(stderr, "qemu: too many serial ports\n");
3588 exit(1);
3590 snprintf(label, sizeof(label), "serial%d", index);
3591 serial_hds[index] = qemu_chr_open(label, devname, NULL);
3592 if (!serial_hds[index]) {
3593 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
3594 devname, strerror(errno));
3595 return -1;
3597 index++;
3598 return 0;
3601 static int parallel_parse(const char *devname)
3603 static int index = 0;
3604 char label[32];
3606 if (strcmp(devname, "none") == 0)
3607 return 0;
3608 if (index == MAX_PARALLEL_PORTS) {
3609 fprintf(stderr, "qemu: too many parallel ports\n");
3610 exit(1);
3612 snprintf(label, sizeof(label), "parallel%d", index);
3613 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
3614 if (!parallel_hds[index]) {
3615 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
3616 devname, strerror(errno));
3617 return -1;
3619 index++;
3620 return 0;
3623 static int virtcon_parse(const char *devname)
3625 static int index = 0;
3626 char label[32];
3627 QemuOpts *bus_opts, *dev_opts;
3629 if (strcmp(devname, "none") == 0)
3630 return 0;
3631 if (index == MAX_VIRTIO_CONSOLES) {
3632 fprintf(stderr, "qemu: too many virtio consoles\n");
3633 exit(1);
3636 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3637 qemu_opt_set(bus_opts, "driver", "virtio-serial");
3639 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3640 qemu_opt_set(dev_opts, "driver", "virtconsole");
3642 snprintf(label, sizeof(label), "virtcon%d", index);
3643 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
3644 if (!virtcon_hds[index]) {
3645 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
3646 devname, strerror(errno));
3647 return -1;
3649 qemu_opt_set(dev_opts, "chardev", label);
3651 index++;
3652 return 0;
3655 static int debugcon_parse(const char *devname)
3657 QemuOpts *opts;
3659 if (!qemu_chr_open("debugcon", devname, NULL)) {
3660 exit(1);
3662 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
3663 if (!opts) {
3664 fprintf(stderr, "qemu: already have a debugcon device\n");
3665 exit(1);
3667 qemu_opt_set(opts, "driver", "isa-debugcon");
3668 qemu_opt_set(opts, "chardev", "debugcon");
3669 return 0;
3672 static const QEMUOption *lookup_opt(int argc, char **argv,
3673 const char **poptarg, int *poptind)
3675 const QEMUOption *popt;
3676 int optind = *poptind;
3677 char *r = argv[optind];
3678 const char *optarg;
3680 loc_set_cmdline(argv, optind, 1);
3681 optind++;
3682 /* Treat --foo the same as -foo. */
3683 if (r[1] == '-')
3684 r++;
3685 popt = qemu_options;
3686 for(;;) {
3687 if (!popt->name) {
3688 error_report("invalid option");
3689 exit(1);
3691 if (!strcmp(popt->name, r + 1))
3692 break;
3693 popt++;
3695 if (popt->flags & HAS_ARG) {
3696 if (optind >= argc) {
3697 error_report("requires an argument");
3698 exit(1);
3700 optarg = argv[optind++];
3701 loc_set_cmdline(argv, optind - 2, 2);
3702 } else {
3703 optarg = NULL;
3706 *poptarg = optarg;
3707 *poptind = optind;
3709 return popt;
3712 static void qmp_add_default(void)
3714 char buffer[4096];
3715 const char *home;
3716 static uint8_t null_uuid[16];
3717 uint8_t uuid[16];
3718 int ret;
3720 home = getenv("HOME");
3721 if (!home) {
3722 return;
3725 if (memcmp(qemu_uuid, null_uuid, sizeof(null_uuid)) == 0) {
3726 #if defined(CONFIG_UUID)
3727 uuid_generate(uuid);
3728 #else
3729 return;
3730 #endif
3731 } else {
3732 memcpy(uuid, qemu_uuid, sizeof(qemu_uuid));
3735 snprintf(buffer, sizeof(buffer), "%s/.qemu", home);
3736 #ifdef __MINGW32__
3737 ret = mkdir(buffer);
3738 #else
3739 ret = mkdir(buffer, 0755);
3740 #endif
3741 if (ret == -1 && errno != EEXIST) {
3742 fprintf(stderr, "could not open default QMP port\n");
3743 return;
3746 snprintf(buffer, sizeof(buffer), "%s/.qemu/qmp", home);
3747 #ifdef __MINGW32__
3748 ret = mkdir(buffer);
3749 #else
3750 ret = mkdir(buffer, 0755);
3751 #endif
3752 if (ret == -1 && errno != EEXIST) {
3753 fprintf(stderr, "could not open default QMP port\n");
3754 return;
3757 snprintf(buffer, sizeof(buffer),
3758 "unix:%s/.qemu/qmp/" UUID_FMT ".sock,server,nowait",
3759 home,
3760 uuid[0], uuid[1], uuid[2], uuid[3],
3761 uuid[4], uuid[5], uuid[6], uuid[7],
3762 uuid[8], uuid[9], uuid[10], uuid[11],
3763 uuid[12], uuid[13], uuid[14], uuid[15]);
3765 monitor_parse(buffer, "control");
3768 int main(int argc, char **argv, char **envp)
3770 const char *gdbstub_dev = NULL;
3771 uint32_t boot_devices_bitmap = 0;
3772 int i;
3773 int snapshot, linux_boot, net_boot;
3774 const char *icount_option = NULL;
3775 const char *initrd_filename;
3776 const char *kernel_filename, *kernel_cmdline;
3777 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3778 DisplayState *ds;
3779 DisplayChangeListener *dcl;
3780 int cyls, heads, secs, translation;
3781 QemuOpts *hda_opts = NULL, *opts;
3782 int optind;
3783 const char *optarg;
3784 const char *loadvm = NULL;
3785 QEMUMachine *machine;
3786 const char *cpu_model;
3787 #ifndef _WIN32
3788 int fds[2];
3789 #endif
3790 int tb_size;
3791 const char *pid_file = NULL;
3792 const char *incoming = NULL;
3793 #ifndef _WIN32
3794 int fd = 0;
3795 struct passwd *pwd = NULL;
3796 const char *chroot_dir = NULL;
3797 const char *run_as = NULL;
3798 #endif
3799 CPUState *env;
3800 int show_vnc_port = 0;
3801 int defconfig = 1;
3803 error_set_progname(argv[0]);
3805 init_clocks();
3807 qemu_cache_utils_init(envp);
3809 QLIST_INIT (&vm_change_state_head);
3810 #ifndef _WIN32
3812 struct sigaction act;
3813 sigfillset(&act.sa_mask);
3814 act.sa_flags = 0;
3815 act.sa_handler = SIG_IGN;
3816 sigaction(SIGPIPE, &act, NULL);
3818 #else
3819 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3820 /* Note: cpu_interrupt() is currently not SMP safe, so we force
3821 QEMU to run on a single CPU */
3823 HANDLE h;
3824 DWORD mask, smask;
3825 int i;
3826 h = GetCurrentProcess();
3827 if (GetProcessAffinityMask(h, &mask, &smask)) {
3828 for(i = 0; i < 32; i++) {
3829 if (mask & (1 << i))
3830 break;
3832 if (i != 32) {
3833 mask = 1 << i;
3834 SetProcessAffinityMask(h, mask);
3838 #endif
3840 module_call_init(MODULE_INIT_MACHINE);
3841 machine = find_default_machine();
3842 cpu_model = NULL;
3843 initrd_filename = NULL;
3844 ram_size = 0;
3845 snapshot = 0;
3846 kernel_filename = NULL;
3847 kernel_cmdline = "";
3848 cyls = heads = secs = 0;
3849 translation = BIOS_ATA_TRANSLATION_AUTO;
3851 for (i = 0; i < MAX_NODES; i++) {
3852 node_mem[i] = 0;
3853 node_cpumask[i] = 0;
3856 nb_numa_nodes = 0;
3857 nb_nics = 0;
3859 tb_size = 0;
3860 autostart= 1;
3862 /* first pass of option parsing */
3863 optind = 1;
3864 while (optind < argc) {
3865 if (argv[optind][0] != '-') {
3866 /* disk image */
3867 optind++;
3868 continue;
3869 } else {
3870 const QEMUOption *popt;
3872 popt = lookup_opt(argc, argv, &optarg, &optind);
3873 switch (popt->index) {
3874 case QEMU_OPTION_nodefconfig:
3875 defconfig=0;
3876 break;
3881 if (defconfig) {
3882 const char *fname;
3883 FILE *fp;
3885 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3886 fp = fopen(fname, "r");
3887 if (fp) {
3888 if (qemu_config_parse(fp, fname) != 0) {
3889 exit(1);
3891 fclose(fp);
3894 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3895 fp = fopen(fname, "r");
3896 if (fp) {
3897 if (qemu_config_parse(fp, fname) != 0) {
3898 exit(1);
3900 fclose(fp);
3903 #if defined(cpudef_setup)
3904 cpudef_setup(); /* parse cpu definitions in target config file */
3905 #endif
3907 /* second pass of option parsing */
3908 optind = 1;
3909 for(;;) {
3910 if (optind >= argc)
3911 break;
3912 if (argv[optind][0] != '-') {
3913 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3914 } else {
3915 const QEMUOption *popt;
3917 popt = lookup_opt(argc, argv, &optarg, &optind);
3918 switch(popt->index) {
3919 case QEMU_OPTION_M:
3920 machine = find_machine(optarg);
3921 if (!machine) {
3922 QEMUMachine *m;
3923 printf("Supported machines are:\n");
3924 for(m = first_machine; m != NULL; m = m->next) {
3925 if (m->alias)
3926 printf("%-10s %s (alias of %s)\n",
3927 m->alias, m->desc, m->name);
3928 printf("%-10s %s%s\n",
3929 m->name, m->desc,
3930 m->is_default ? " (default)" : "");
3932 exit(*optarg != '?');
3934 break;
3935 case QEMU_OPTION_cpu:
3936 /* hw initialization will check this */
3937 if (*optarg == '?') {
3938 /* XXX: implement xxx_cpu_list for targets that still miss it */
3939 #if defined(cpu_list_id)
3940 cpu_list_id(stdout, &fprintf, optarg);
3941 #elif defined(cpu_list)
3942 cpu_list(stdout, &fprintf); /* deprecated */
3943 #endif
3944 exit(0);
3945 } else {
3946 cpu_model = optarg;
3948 break;
3949 case QEMU_OPTION_initrd:
3950 initrd_filename = optarg;
3951 break;
3952 case QEMU_OPTION_hda:
3953 if (cyls == 0)
3954 hda_opts = drive_add(optarg, HD_ALIAS, 0);
3955 else
3956 hda_opts = drive_add(optarg, HD_ALIAS
3957 ",cyls=%d,heads=%d,secs=%d%s",
3958 0, cyls, heads, secs,
3959 translation == BIOS_ATA_TRANSLATION_LBA ?
3960 ",trans=lba" :
3961 translation == BIOS_ATA_TRANSLATION_NONE ?
3962 ",trans=none" : "");
3963 break;
3964 case QEMU_OPTION_hdb:
3965 case QEMU_OPTION_hdc:
3966 case QEMU_OPTION_hdd:
3967 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
3968 break;
3969 case QEMU_OPTION_drive:
3970 drive_add(NULL, "%s", optarg);
3971 break;
3972 case QEMU_OPTION_set:
3973 if (qemu_set_option(optarg) != 0)
3974 exit(1);
3975 break;
3976 case QEMU_OPTION_global:
3977 if (qemu_global_option(optarg) != 0)
3978 exit(1);
3979 break;
3980 case QEMU_OPTION_mtdblock:
3981 drive_add(optarg, MTD_ALIAS);
3982 break;
3983 case QEMU_OPTION_sd:
3984 drive_add(optarg, SD_ALIAS);
3985 break;
3986 case QEMU_OPTION_pflash:
3987 drive_add(optarg, PFLASH_ALIAS);
3988 break;
3989 case QEMU_OPTION_snapshot:
3990 snapshot = 1;
3991 break;
3992 case QEMU_OPTION_hdachs:
3994 const char *p;
3995 p = optarg;
3996 cyls = strtol(p, (char **)&p, 0);
3997 if (cyls < 1 || cyls > 16383)
3998 goto chs_fail;
3999 if (*p != ',')
4000 goto chs_fail;
4001 p++;
4002 heads = strtol(p, (char **)&p, 0);
4003 if (heads < 1 || heads > 16)
4004 goto chs_fail;
4005 if (*p != ',')
4006 goto chs_fail;
4007 p++;
4008 secs = strtol(p, (char **)&p, 0);
4009 if (secs < 1 || secs > 63)
4010 goto chs_fail;
4011 if (*p == ',') {
4012 p++;
4013 if (!strcmp(p, "none"))
4014 translation = BIOS_ATA_TRANSLATION_NONE;
4015 else if (!strcmp(p, "lba"))
4016 translation = BIOS_ATA_TRANSLATION_LBA;
4017 else if (!strcmp(p, "auto"))
4018 translation = BIOS_ATA_TRANSLATION_AUTO;
4019 else
4020 goto chs_fail;
4021 } else if (*p != '\0') {
4022 chs_fail:
4023 fprintf(stderr, "qemu: invalid physical CHS format\n");
4024 exit(1);
4026 if (hda_opts != NULL) {
4027 char num[16];
4028 snprintf(num, sizeof(num), "%d", cyls);
4029 qemu_opt_set(hda_opts, "cyls", num);
4030 snprintf(num, sizeof(num), "%d", heads);
4031 qemu_opt_set(hda_opts, "heads", num);
4032 snprintf(num, sizeof(num), "%d", secs);
4033 qemu_opt_set(hda_opts, "secs", num);
4034 if (translation == BIOS_ATA_TRANSLATION_LBA)
4035 qemu_opt_set(hda_opts, "trans", "lba");
4036 if (translation == BIOS_ATA_TRANSLATION_NONE)
4037 qemu_opt_set(hda_opts, "trans", "none");
4040 break;
4041 case QEMU_OPTION_numa:
4042 if (nb_numa_nodes >= MAX_NODES) {
4043 fprintf(stderr, "qemu: too many NUMA nodes\n");
4044 exit(1);
4046 numa_add(optarg);
4047 break;
4048 case QEMU_OPTION_nographic:
4049 display_type = DT_NOGRAPHIC;
4050 break;
4051 #ifdef CONFIG_CURSES
4052 case QEMU_OPTION_curses:
4053 display_type = DT_CURSES;
4054 break;
4055 #endif
4056 case QEMU_OPTION_portrait:
4057 graphic_rotate = 1;
4058 break;
4059 case QEMU_OPTION_kernel:
4060 kernel_filename = optarg;
4061 break;
4062 case QEMU_OPTION_append:
4063 kernel_cmdline = optarg;
4064 break;
4065 case QEMU_OPTION_cdrom:
4066 drive_add(optarg, CDROM_ALIAS);
4067 break;
4068 case QEMU_OPTION_boot:
4070 static const char * const params[] = {
4071 "order", "once", "menu", NULL
4073 char buf[sizeof(boot_devices)];
4074 char *standard_boot_devices;
4075 int legacy = 0;
4077 if (!strchr(optarg, '=')) {
4078 legacy = 1;
4079 pstrcpy(buf, sizeof(buf), optarg);
4080 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4081 fprintf(stderr,
4082 "qemu: unknown boot parameter '%s' in '%s'\n",
4083 buf, optarg);
4084 exit(1);
4087 if (legacy ||
4088 get_param_value(buf, sizeof(buf), "order", optarg)) {
4089 boot_devices_bitmap = parse_bootdevices(buf);
4090 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4092 if (!legacy) {
4093 if (get_param_value(buf, sizeof(buf),
4094 "once", optarg)) {
4095 boot_devices_bitmap |= parse_bootdevices(buf);
4096 standard_boot_devices = qemu_strdup(boot_devices);
4097 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4098 qemu_register_reset(restore_boot_devices,
4099 standard_boot_devices);
4101 if (get_param_value(buf, sizeof(buf),
4102 "menu", optarg)) {
4103 if (!strcmp(buf, "on")) {
4104 boot_menu = 1;
4105 } else if (!strcmp(buf, "off")) {
4106 boot_menu = 0;
4107 } else {
4108 fprintf(stderr,
4109 "qemu: invalid option value '%s'\n",
4110 buf);
4111 exit(1);
4116 break;
4117 case QEMU_OPTION_fda:
4118 case QEMU_OPTION_fdb:
4119 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4120 break;
4121 #ifdef TARGET_I386
4122 case QEMU_OPTION_no_fd_bootchk:
4123 fd_bootchk = 0;
4124 break;
4125 #endif
4126 case QEMU_OPTION_netdev:
4127 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4128 exit(1);
4130 break;
4131 case QEMU_OPTION_net:
4132 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4133 exit(1);
4135 break;
4136 #ifdef CONFIG_SLIRP
4137 case QEMU_OPTION_tftp:
4138 legacy_tftp_prefix = optarg;
4139 break;
4140 case QEMU_OPTION_bootp:
4141 legacy_bootp_filename = optarg;
4142 break;
4143 #ifndef _WIN32
4144 case QEMU_OPTION_smb:
4145 if (net_slirp_smb(optarg) < 0)
4146 exit(1);
4147 break;
4148 #endif
4149 case QEMU_OPTION_redir:
4150 if (net_slirp_redir(optarg) < 0)
4151 exit(1);
4152 break;
4153 #endif
4154 case QEMU_OPTION_bt:
4155 add_device_config(DEV_BT, optarg);
4156 break;
4157 #ifdef HAS_AUDIO
4158 case QEMU_OPTION_audio_help:
4159 AUD_help ();
4160 exit (0);
4161 break;
4162 case QEMU_OPTION_soundhw:
4163 select_soundhw (optarg);
4164 break;
4165 #endif
4166 case QEMU_OPTION_h:
4167 help(0);
4168 break;
4169 case QEMU_OPTION_version:
4170 version();
4171 exit(0);
4172 break;
4173 case QEMU_OPTION_m: {
4174 uint64_t value;
4175 char *ptr;
4177 value = strtoul(optarg, &ptr, 10);
4178 switch (*ptr) {
4179 case 0: case 'M': case 'm':
4180 value <<= 20;
4181 break;
4182 case 'G': case 'g':
4183 value <<= 30;
4184 break;
4185 default:
4186 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4187 exit(1);
4190 /* On 32-bit hosts, QEMU is limited by virtual address space */
4191 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
4192 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4193 exit(1);
4195 if (value != (uint64_t)(ram_addr_t)value) {
4196 fprintf(stderr, "qemu: ram size too large\n");
4197 exit(1);
4199 ram_size = value;
4200 break;
4202 case QEMU_OPTION_mempath:
4203 mem_path = optarg;
4204 break;
4205 #ifdef MAP_POPULATE
4206 case QEMU_OPTION_mem_prealloc:
4207 mem_prealloc = 1;
4208 break;
4209 #endif
4210 case QEMU_OPTION_d:
4212 int mask;
4213 const CPULogItem *item;
4215 mask = cpu_str_to_log_mask(optarg);
4216 if (!mask) {
4217 printf("Log items (comma separated):\n");
4218 for(item = cpu_log_items; item->mask != 0; item++) {
4219 printf("%-10s %s\n", item->name, item->help);
4221 exit(1);
4223 cpu_set_log(mask);
4225 break;
4226 case QEMU_OPTION_s:
4227 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4228 break;
4229 case QEMU_OPTION_gdb:
4230 gdbstub_dev = optarg;
4231 break;
4232 case QEMU_OPTION_L:
4233 data_dir = optarg;
4234 break;
4235 case QEMU_OPTION_bios:
4236 bios_name = optarg;
4237 break;
4238 case QEMU_OPTION_singlestep:
4239 singlestep = 1;
4240 break;
4241 case QEMU_OPTION_S:
4242 autostart = 0;
4243 break;
4244 case QEMU_OPTION_k:
4245 keyboard_layout = optarg;
4246 break;
4247 case QEMU_OPTION_localtime:
4248 rtc_utc = 0;
4249 break;
4250 case QEMU_OPTION_vga:
4251 select_vgahw (optarg);
4252 break;
4253 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4254 case QEMU_OPTION_g:
4256 const char *p;
4257 int w, h, depth;
4258 p = optarg;
4259 w = strtol(p, (char **)&p, 10);
4260 if (w <= 0) {
4261 graphic_error:
4262 fprintf(stderr, "qemu: invalid resolution or depth\n");
4263 exit(1);
4265 if (*p != 'x')
4266 goto graphic_error;
4267 p++;
4268 h = strtol(p, (char **)&p, 10);
4269 if (h <= 0)
4270 goto graphic_error;
4271 if (*p == 'x') {
4272 p++;
4273 depth = strtol(p, (char **)&p, 10);
4274 if (depth != 8 && depth != 15 && depth != 16 &&
4275 depth != 24 && depth != 32)
4276 goto graphic_error;
4277 } else if (*p == '\0') {
4278 depth = graphic_depth;
4279 } else {
4280 goto graphic_error;
4283 graphic_width = w;
4284 graphic_height = h;
4285 graphic_depth = depth;
4287 break;
4288 #endif
4289 case QEMU_OPTION_echr:
4291 char *r;
4292 term_escape_char = strtol(optarg, &r, 0);
4293 if (r == optarg)
4294 printf("Bad argument to echr\n");
4295 break;
4297 case QEMU_OPTION_monitor:
4298 monitor_parse(optarg, "readline");
4299 default_monitor = 0;
4300 break;
4301 case QEMU_OPTION_qmp:
4302 monitor_parse(optarg, "control");
4303 default_qmp = 0;
4304 break;
4305 case QEMU_OPTION_mon:
4306 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
4307 if (!opts) {
4308 fprintf(stderr, "parse error: %s\n", optarg);
4309 exit(1);
4310 } else {
4311 const char *mode;
4312 mode = qemu_opt_get(opts, "mode");
4313 if (mode == NULL || strcmp(mode, "readline") == 0) {
4314 default_monitor = 0;
4315 } else if (strcmp(mode, "control") == 0) {
4316 default_qmp = 0;
4319 break;
4320 case QEMU_OPTION_chardev:
4321 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
4322 if (!opts) {
4323 fprintf(stderr, "parse error: %s\n", optarg);
4324 exit(1);
4326 break;
4327 case QEMU_OPTION_serial:
4328 add_device_config(DEV_SERIAL, optarg);
4329 default_serial = 0;
4330 if (strncmp(optarg, "mon:", 4) == 0) {
4331 default_monitor = 0;
4333 break;
4334 case QEMU_OPTION_watchdog:
4335 if (watchdog) {
4336 fprintf(stderr,
4337 "qemu: only one watchdog option may be given\n");
4338 return 1;
4340 watchdog = optarg;
4341 break;
4342 case QEMU_OPTION_watchdog_action:
4343 if (select_watchdog_action(optarg) == -1) {
4344 fprintf(stderr, "Unknown -watchdog-action parameter\n");
4345 exit(1);
4347 break;
4348 case QEMU_OPTION_virtiocon:
4349 add_device_config(DEV_VIRTCON, optarg);
4350 default_virtcon = 0;
4351 if (strncmp(optarg, "mon:", 4) == 0) {
4352 default_monitor = 0;
4354 break;
4355 case QEMU_OPTION_parallel:
4356 add_device_config(DEV_PARALLEL, optarg);
4357 default_parallel = 0;
4358 if (strncmp(optarg, "mon:", 4) == 0) {
4359 default_monitor = 0;
4361 break;
4362 case QEMU_OPTION_debugcon:
4363 add_device_config(DEV_DEBUGCON, optarg);
4364 break;
4365 case QEMU_OPTION_loadvm:
4366 loadvm = optarg;
4367 break;
4368 case QEMU_OPTION_full_screen:
4369 full_screen = 1;
4370 break;
4371 #ifdef CONFIG_SDL
4372 case QEMU_OPTION_no_frame:
4373 no_frame = 1;
4374 break;
4375 case QEMU_OPTION_alt_grab:
4376 alt_grab = 1;
4377 break;
4378 case QEMU_OPTION_ctrl_grab:
4379 ctrl_grab = 1;
4380 break;
4381 case QEMU_OPTION_no_quit:
4382 no_quit = 1;
4383 break;
4384 case QEMU_OPTION_sdl:
4385 display_type = DT_SDL;
4386 break;
4387 #endif
4388 case QEMU_OPTION_pidfile:
4389 pid_file = optarg;
4390 break;
4391 #ifdef TARGET_I386
4392 case QEMU_OPTION_win2k_hack:
4393 win2k_install_hack = 1;
4394 break;
4395 case QEMU_OPTION_rtc_td_hack:
4396 rtc_td_hack = 1;
4397 break;
4398 case QEMU_OPTION_acpitable:
4399 if(acpi_table_add(optarg) < 0) {
4400 fprintf(stderr, "Wrong acpi table provided\n");
4401 exit(1);
4403 break;
4404 case QEMU_OPTION_smbios:
4405 if(smbios_entry_add(optarg) < 0) {
4406 fprintf(stderr, "Wrong smbios provided\n");
4407 exit(1);
4409 break;
4410 #endif
4411 #ifdef CONFIG_KVM
4412 case QEMU_OPTION_enable_kvm:
4413 kvm_allowed = 1;
4414 break;
4415 #endif
4416 case QEMU_OPTION_usb:
4417 usb_enabled = 1;
4418 break;
4419 case QEMU_OPTION_usbdevice:
4420 usb_enabled = 1;
4421 add_device_config(DEV_USB, optarg);
4422 break;
4423 case QEMU_OPTION_device:
4424 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
4425 exit(1);
4427 break;
4428 case QEMU_OPTION_smp:
4429 smp_parse(optarg);
4430 if (smp_cpus < 1) {
4431 fprintf(stderr, "Invalid number of CPUs\n");
4432 exit(1);
4434 if (max_cpus < smp_cpus) {
4435 fprintf(stderr, "maxcpus must be equal to or greater than "
4436 "smp\n");
4437 exit(1);
4439 if (max_cpus > 255) {
4440 fprintf(stderr, "Unsupported number of maxcpus\n");
4441 exit(1);
4443 break;
4444 case QEMU_OPTION_vnc:
4445 display_type = DT_VNC;
4446 vnc_display = optarg;
4447 break;
4448 #ifdef TARGET_I386
4449 case QEMU_OPTION_no_acpi:
4450 acpi_enabled = 0;
4451 break;
4452 case QEMU_OPTION_no_hpet:
4453 no_hpet = 1;
4454 break;
4455 case QEMU_OPTION_balloon:
4456 if (balloon_parse(optarg) < 0) {
4457 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
4458 exit(1);
4460 break;
4461 #endif
4462 case QEMU_OPTION_no_reboot:
4463 no_reboot = 1;
4464 break;
4465 case QEMU_OPTION_no_shutdown:
4466 no_shutdown = 1;
4467 break;
4468 case QEMU_OPTION_show_cursor:
4469 cursor_hide = 0;
4470 break;
4471 case QEMU_OPTION_uuid:
4472 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4473 fprintf(stderr, "Fail to parse UUID string."
4474 " Wrong format.\n");
4475 exit(1);
4477 break;
4478 #ifndef _WIN32
4479 case QEMU_OPTION_daemonize:
4480 daemonize = 1;
4481 break;
4482 #endif
4483 case QEMU_OPTION_option_rom:
4484 if (nb_option_roms >= MAX_OPTION_ROMS) {
4485 fprintf(stderr, "Too many option ROMs\n");
4486 exit(1);
4488 option_rom[nb_option_roms] = optarg;
4489 nb_option_roms++;
4490 break;
4491 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4492 case QEMU_OPTION_semihosting:
4493 semihosting_enabled = 1;
4494 break;
4495 #endif
4496 case QEMU_OPTION_name:
4497 qemu_name = qemu_strdup(optarg);
4499 char *p = strchr(qemu_name, ',');
4500 if (p != NULL) {
4501 *p++ = 0;
4502 if (strncmp(p, "process=", 8)) {
4503 fprintf(stderr, "Unknown subargument %s to -name", p);
4504 exit(1);
4506 p += 8;
4507 set_proc_name(p);
4510 break;
4511 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4512 case QEMU_OPTION_prom_env:
4513 if (nb_prom_envs >= MAX_PROM_ENVS) {
4514 fprintf(stderr, "Too many prom variables\n");
4515 exit(1);
4517 prom_envs[nb_prom_envs] = optarg;
4518 nb_prom_envs++;
4519 break;
4520 #endif
4521 #ifdef TARGET_ARM
4522 case QEMU_OPTION_old_param:
4523 old_param = 1;
4524 break;
4525 #endif
4526 case QEMU_OPTION_clock:
4527 configure_alarms(optarg);
4528 break;
4529 case QEMU_OPTION_startdate:
4530 configure_rtc_date_offset(optarg, 1);
4531 break;
4532 case QEMU_OPTION_rtc:
4533 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
4534 if (!opts) {
4535 fprintf(stderr, "parse error: %s\n", optarg);
4536 exit(1);
4538 configure_rtc(opts);
4539 break;
4540 case QEMU_OPTION_tb_size:
4541 tb_size = strtol(optarg, NULL, 0);
4542 if (tb_size < 0)
4543 tb_size = 0;
4544 break;
4545 case QEMU_OPTION_icount:
4546 icount_option = optarg;
4547 break;
4548 case QEMU_OPTION_incoming:
4549 incoming = optarg;
4550 break;
4551 case QEMU_OPTION_nodefaults:
4552 default_serial = 0;
4553 default_parallel = 0;
4554 default_virtcon = 0;
4555 default_monitor = 0;
4556 default_qmp = 0;
4557 default_vga = 0;
4558 default_net = 0;
4559 default_floppy = 0;
4560 default_cdrom = 0;
4561 default_sdcard = 0;
4562 break;
4563 #ifndef _WIN32
4564 case QEMU_OPTION_chroot:
4565 chroot_dir = optarg;
4566 break;
4567 case QEMU_OPTION_runas:
4568 run_as = optarg;
4569 break;
4570 #endif
4571 #ifdef CONFIG_XEN
4572 case QEMU_OPTION_xen_domid:
4573 xen_domid = atoi(optarg);
4574 break;
4575 case QEMU_OPTION_xen_create:
4576 xen_mode = XEN_CREATE;
4577 break;
4578 case QEMU_OPTION_xen_attach:
4579 xen_mode = XEN_ATTACH;
4580 break;
4581 #endif
4582 case QEMU_OPTION_readconfig:
4584 FILE *fp;
4585 fp = fopen(optarg, "r");
4586 if (fp == NULL) {
4587 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4588 exit(1);
4590 if (qemu_config_parse(fp, optarg) != 0) {
4591 exit(1);
4593 fclose(fp);
4594 break;
4596 case QEMU_OPTION_writeconfig:
4598 FILE *fp;
4599 if (strcmp(optarg, "-") == 0) {
4600 fp = stdout;
4601 } else {
4602 fp = fopen(optarg, "w");
4603 if (fp == NULL) {
4604 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4605 exit(1);
4608 qemu_config_write(fp);
4609 fclose(fp);
4610 break;
4615 loc_set_none();
4617 /* If no data_dir is specified then try to find it relative to the
4618 executable path. */
4619 if (!data_dir) {
4620 data_dir = find_datadir(argv[0]);
4622 /* If all else fails use the install patch specified when building. */
4623 if (!data_dir) {
4624 data_dir = CONFIG_QEMU_SHAREDIR;
4628 * Default to max_cpus = smp_cpus, in case the user doesn't
4629 * specify a max_cpus value.
4631 if (!max_cpus)
4632 max_cpus = smp_cpus;
4634 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4635 if (smp_cpus > machine->max_cpus) {
4636 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4637 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
4638 machine->max_cpus);
4639 exit(1);
4642 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
4643 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
4645 if (machine->no_serial) {
4646 default_serial = 0;
4648 if (machine->no_parallel) {
4649 default_parallel = 0;
4651 if (!machine->use_virtcon) {
4652 default_virtcon = 0;
4654 if (machine->no_vga) {
4655 default_vga = 0;
4657 if (machine->no_floppy) {
4658 default_floppy = 0;
4660 if (machine->no_cdrom) {
4661 default_cdrom = 0;
4663 if (machine->no_sdcard) {
4664 default_sdcard = 0;
4667 if (display_type == DT_NOGRAPHIC) {
4668 if (default_parallel)
4669 add_device_config(DEV_PARALLEL, "null");
4670 if (default_serial && default_monitor) {
4671 add_device_config(DEV_SERIAL, "mon:stdio");
4672 } else if (default_virtcon && default_monitor) {
4673 add_device_config(DEV_VIRTCON, "mon:stdio");
4674 } else {
4675 if (default_serial)
4676 add_device_config(DEV_SERIAL, "stdio");
4677 if (default_virtcon)
4678 add_device_config(DEV_VIRTCON, "stdio");
4679 if (default_monitor)
4680 monitor_parse("stdio", "readline");
4682 } else {
4683 if (default_serial)
4684 add_device_config(DEV_SERIAL, "vc:80Cx24C");
4685 if (default_parallel)
4686 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4687 if (default_monitor)
4688 monitor_parse("vc:80Cx24C", "readline");
4689 if (default_virtcon)
4690 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4692 if (default_qmp) {
4693 qmp_add_default();
4695 if (default_vga)
4696 vga_interface_type = VGA_CIRRUS;
4698 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
4699 exit(1);
4701 #ifndef _WIN32
4702 if (daemonize) {
4703 pid_t pid;
4705 if (pipe(fds) == -1)
4706 exit(1);
4708 pid = fork();
4709 if (pid > 0) {
4710 uint8_t status;
4711 ssize_t len;
4713 close(fds[1]);
4715 again:
4716 len = read(fds[0], &status, 1);
4717 if (len == -1 && (errno == EINTR))
4718 goto again;
4720 if (len != 1)
4721 exit(1);
4722 else if (status == 1) {
4723 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
4724 exit(1);
4725 } else
4726 exit(0);
4727 } else if (pid < 0)
4728 exit(1);
4730 close(fds[0]);
4731 qemu_set_cloexec(fds[1]);
4733 setsid();
4735 pid = fork();
4736 if (pid > 0)
4737 exit(0);
4738 else if (pid < 0)
4739 exit(1);
4741 umask(027);
4743 signal(SIGTSTP, SIG_IGN);
4744 signal(SIGTTOU, SIG_IGN);
4745 signal(SIGTTIN, SIG_IGN);
4747 #endif
4749 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4750 #ifndef _WIN32
4751 if (daemonize) {
4752 uint8_t status = 1;
4753 if (write(fds[1], &status, 1) != 1) {
4754 perror("daemonize. Writing to pipe\n");
4756 } else
4757 #endif
4758 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
4759 exit(1);
4762 if (kvm_enabled()) {
4763 int ret;
4765 ret = kvm_init(smp_cpus);
4766 if (ret < 0) {
4767 fprintf(stderr, "failed to initialize KVM\n");
4768 exit(1);
4772 if (qemu_init_main_loop()) {
4773 fprintf(stderr, "qemu_init_main_loop failed\n");
4774 exit(1);
4776 linux_boot = (kernel_filename != NULL);
4778 if (!linux_boot && *kernel_cmdline != '\0') {
4779 fprintf(stderr, "-append only allowed with -kernel option\n");
4780 exit(1);
4783 if (!linux_boot && initrd_filename != NULL) {
4784 fprintf(stderr, "-initrd only allowed with -kernel option\n");
4785 exit(1);
4788 #ifndef _WIN32
4789 /* Win32 doesn't support line-buffering and requires size >= 2 */
4790 setvbuf(stdout, NULL, _IOLBF, 0);
4791 #endif
4793 if (init_timer_alarm() < 0) {
4794 fprintf(stderr, "could not initialize alarm timer\n");
4795 exit(1);
4797 configure_icount(icount_option);
4799 #ifdef _WIN32
4800 socket_init();
4801 #endif
4803 if (net_init_clients() < 0) {
4804 exit(1);
4807 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4808 net_set_boot_mask(net_boot);
4810 /* init the bluetooth world */
4811 if (foreach_device_config(DEV_BT, bt_parse))
4812 exit(1);
4814 /* init the memory */
4815 if (ram_size == 0)
4816 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4818 /* init the dynamic translator */
4819 cpu_exec_init_all(tb_size * 1024 * 1024);
4821 bdrv_init_with_whitelist();
4823 blk_mig_init();
4825 if (default_cdrom) {
4826 /* we always create the cdrom drive, even if no disk is there */
4827 drive_add(NULL, CDROM_ALIAS);
4830 if (default_floppy) {
4831 /* we always create at least one floppy */
4832 drive_add(NULL, FD_ALIAS, 0);
4835 if (default_sdcard) {
4836 /* we always create one sd slot, even if no card is in it */
4837 drive_add(NULL, SD_ALIAS);
4840 /* open the virtual block devices */
4841 if (snapshot)
4842 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4843 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4844 exit(1);
4846 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
4847 ram_load, NULL);
4849 if (nb_numa_nodes > 0) {
4850 int i;
4852 if (nb_numa_nodes > smp_cpus) {
4853 nb_numa_nodes = smp_cpus;
4856 /* If no memory size if given for any node, assume the default case
4857 * and distribute the available memory equally across all nodes
4859 for (i = 0; i < nb_numa_nodes; i++) {
4860 if (node_mem[i] != 0)
4861 break;
4863 if (i == nb_numa_nodes) {
4864 uint64_t usedmem = 0;
4866 /* On Linux, the each node's border has to be 8MB aligned,
4867 * the final node gets the rest.
4869 for (i = 0; i < nb_numa_nodes - 1; i++) {
4870 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4871 usedmem += node_mem[i];
4873 node_mem[i] = ram_size - usedmem;
4876 for (i = 0; i < nb_numa_nodes; i++) {
4877 if (node_cpumask[i] != 0)
4878 break;
4880 /* assigning the VCPUs round-robin is easier to implement, guest OSes
4881 * must cope with this anyway, because there are BIOSes out there in
4882 * real machines which also use this scheme.
4884 if (i == nb_numa_nodes) {
4885 for (i = 0; i < smp_cpus; i++) {
4886 node_cpumask[i % nb_numa_nodes] |= 1 << i;
4891 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4892 exit(1);
4893 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4894 exit(1);
4895 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4896 exit(1);
4897 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4898 exit(1);
4900 module_call_init(MODULE_INIT_DEVICE);
4902 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
4903 exit(0);
4905 if (watchdog) {
4906 i = select_watchdog(watchdog);
4907 if (i > 0)
4908 exit (i == 1 ? 1 : 0);
4911 if (machine->compat_props) {
4912 qdev_prop_register_global_list(machine->compat_props);
4914 qemu_add_globals();
4916 machine->init(ram_size, boot_devices,
4917 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
4919 cpu_synchronize_all_post_init();
4921 #ifndef _WIN32
4922 /* must be after terminal init, SDL library changes signal handlers */
4923 sighandler_setup();
4924 #endif
4926 for (env = first_cpu; env != NULL; env = env->next_cpu) {
4927 for (i = 0; i < nb_numa_nodes; i++) {
4928 if (node_cpumask[i] & (1 << env->cpu_index)) {
4929 env->numa_node = i;
4934 current_machine = machine;
4936 /* init USB devices */
4937 if (usb_enabled) {
4938 if (foreach_device_config(DEV_USB, usb_parse) < 0)
4939 exit(1);
4942 /* init generic devices */
4943 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
4944 exit(1);
4946 net_check_clients();
4948 /* just use the first displaystate for the moment */
4949 ds = get_displaystate();
4951 if (display_type == DT_DEFAULT) {
4952 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4953 display_type = DT_SDL;
4954 #else
4955 display_type = DT_VNC;
4956 vnc_display = "localhost:0,to=99";
4957 show_vnc_port = 1;
4958 #endif
4962 switch (display_type) {
4963 case DT_NOGRAPHIC:
4964 break;
4965 #if defined(CONFIG_CURSES)
4966 case DT_CURSES:
4967 curses_display_init(ds, full_screen);
4968 break;
4969 #endif
4970 #if defined(CONFIG_SDL)
4971 case DT_SDL:
4972 sdl_display_init(ds, full_screen, no_frame);
4973 break;
4974 #elif defined(CONFIG_COCOA)
4975 case DT_SDL:
4976 cocoa_display_init(ds, full_screen);
4977 break;
4978 #endif
4979 case DT_VNC:
4980 vnc_display_init(ds);
4981 if (vnc_display_open(ds, vnc_display) < 0)
4982 exit(1);
4984 if (show_vnc_port) {
4985 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
4987 break;
4988 default:
4989 break;
4991 dpy_resize(ds);
4993 dcl = ds->listeners;
4994 while (dcl != NULL) {
4995 if (dcl->dpy_refresh != NULL) {
4996 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
4997 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
4999 dcl = dcl->next;
5002 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5003 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5004 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5007 text_consoles_set_display(ds);
5009 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5010 exit(1);
5012 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5013 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5014 gdbstub_dev);
5015 exit(1);
5018 qdev_machine_creation_done();
5020 if (rom_load_all() != 0) {
5021 fprintf(stderr, "rom loading failed\n");
5022 exit(1);
5025 qemu_system_reset();
5026 if (loadvm) {
5027 if (load_vmstate(loadvm) < 0) {
5028 autostart = 0;
5032 if (incoming) {
5033 qemu_start_incoming_migration(incoming);
5034 } else if (autostart) {
5035 vm_start();
5038 #ifndef _WIN32
5039 if (daemonize) {
5040 uint8_t status = 0;
5041 ssize_t len;
5043 again1:
5044 len = write(fds[1], &status, 1);
5045 if (len == -1 && (errno == EINTR))
5046 goto again1;
5048 if (len != 1)
5049 exit(1);
5051 if (chdir("/")) {
5052 perror("not able to chdir to /");
5053 exit(1);
5055 TFR(fd = qemu_open("/dev/null", O_RDWR));
5056 if (fd == -1)
5057 exit(1);
5060 if (run_as) {
5061 pwd = getpwnam(run_as);
5062 if (!pwd) {
5063 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5064 exit(1);
5068 if (chroot_dir) {
5069 if (chroot(chroot_dir) < 0) {
5070 fprintf(stderr, "chroot failed\n");
5071 exit(1);
5073 if (chdir("/")) {
5074 perror("not able to chdir to /");
5075 exit(1);
5079 if (run_as) {
5080 if (setgid(pwd->pw_gid) < 0) {
5081 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5082 exit(1);
5084 if (setuid(pwd->pw_uid) < 0) {
5085 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5086 exit(1);
5088 if (setuid(0) != -1) {
5089 fprintf(stderr, "Dropping privileges failed\n");
5090 exit(1);
5094 if (daemonize) {
5095 dup2(fd, 0);
5096 dup2(fd, 1);
5097 dup2(fd, 2);
5099 close(fd);
5101 #endif
5103 main_loop();
5104 quit_timers();
5105 net_cleanup();
5107 return 0;