Convert atexit users to exit_notifier
[qemu/aliguori-queue.git] / vl.c
blobeda96aaa6c5f81a0046346471bbabe5fdeb56f1f
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #include <arpa/inet.h>
48 #include <dirent.h>
49 #include <netdb.h>
50 #include <sys/select.h>
51 #ifdef CONFIG_BSD
52 #include <sys/stat.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54 #include <libutil.h>
55 #else
56 #include <util.h>
57 #endif
58 #else
59 #ifdef __linux__
60 #include <pty.h>
61 #include <malloc.h>
62 #include <sys/prctl.h>
64 #include <linux/ppdev.h>
65 #include <linux/parport.h>
66 #endif
67 #ifdef __sun__
68 #include <sys/stat.h>
69 #include <sys/ethernet.h>
70 #include <sys/sockio.h>
71 #include <netinet/arp.h>
72 #include <netinet/in.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/ip_icmp.h> // must come after ip.h
76 #include <netinet/udp.h>
77 #include <netinet/tcp.h>
78 #include <net/if.h>
79 #include <syslog.h>
80 #include <stropts.h>
81 /* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
82 discussion about Solaris header problems */
83 extern int madvise(caddr_t, size_t, int);
84 #endif
85 #endif
86 #endif
88 #if defined(__OpenBSD__)
89 #include <util.h>
90 #endif
92 #if defined(CONFIG_VDE)
93 #include <libvdeplug.h>
94 #endif
96 #ifdef _WIN32
97 #include <windows.h>
98 #endif
100 #ifdef CONFIG_SDL
101 #if defined(__APPLE__) || defined(main)
102 #include <SDL.h>
103 int qemu_main(int argc, char **argv, char **envp);
104 int main(int argc, char **argv)
106 return qemu_main(argc, argv, NULL);
108 #undef main
109 #define main qemu_main
110 #endif
111 #endif /* CONFIG_SDL */
113 #ifdef CONFIG_COCOA
114 #undef main
115 #define main qemu_main
116 #endif /* CONFIG_COCOA */
118 #include "hw/hw.h"
119 #include "hw/boards.h"
120 #include "hw/usb.h"
121 #include "hw/pcmcia.h"
122 #include "hw/pc.h"
123 #include "hw/audiodev.h"
124 #include "hw/isa.h"
125 #include "hw/baum.h"
126 #include "hw/bt.h"
127 #include "hw/watchdog.h"
128 #include "hw/smbios.h"
129 #include "hw/xen.h"
130 #include "hw/qdev.h"
131 #include "hw/loader.h"
132 #include "bt-host.h"
133 #include "net.h"
134 #include "net/slirp.h"
135 #include "monitor.h"
136 #include "console.h"
137 #include "sysemu.h"
138 #include "gdbstub.h"
139 #include "qemu-timer.h"
140 #include "qemu-char.h"
141 #include "cache-utils.h"
142 #include "block.h"
143 #include "block_int.h"
144 #include "block-migration.h"
145 #include "dma.h"
146 #include "audio/audio.h"
147 #include "migration.h"
148 #include "kvm.h"
149 #include "balloon.h"
150 #include "qemu-option.h"
151 #include "qemu-config.h"
152 #include "qemu-objects.h"
153 #include "notify.h"
155 #include "disas.h"
157 #include "exec-all.h"
159 #include "qemu_socket.h"
161 #include "slirp/libslirp.h"
163 #include "qemu-queue.h"
165 //#define DEBUG_NET
166 //#define DEBUG_SLIRP
168 #define DEFAULT_RAM_SIZE 128
170 #define MAX_VIRTIO_CONSOLES 1
172 static const char *data_dir;
173 const char *bios_name = NULL;
174 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
175 to store the VM snapshots */
176 struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
177 struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
178 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
179 DisplayType display_type = DT_DEFAULT;
180 const char* keyboard_layout = NULL;
181 ram_addr_t ram_size;
182 const char *mem_path = NULL;
183 #ifdef MAP_POPULATE
184 int mem_prealloc = 0; /* force preallocation of physical target memory */
185 #endif
186 int nb_nics;
187 NICInfo nd_table[MAX_NICS];
188 int vm_running;
189 int autostart;
190 static int rtc_utc = 1;
191 static int rtc_date_offset = -1; /* -1 means no change */
192 QEMUClock *rtc_clock;
193 int vga_interface_type = VGA_NONE;
194 #ifdef TARGET_SPARC
195 int graphic_width = 1024;
196 int graphic_height = 768;
197 int graphic_depth = 8;
198 #else
199 int graphic_width = 800;
200 int graphic_height = 600;
201 int graphic_depth = 15;
202 #endif
203 static int full_screen = 0;
204 #ifdef CONFIG_SDL
205 static int no_frame = 0;
206 #endif
207 int no_quit = 0;
208 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
209 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
210 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
211 #ifdef TARGET_I386
212 int win2k_install_hack = 0;
213 int rtc_td_hack = 0;
214 #endif
215 int usb_enabled = 0;
216 int singlestep = 0;
217 int smp_cpus = 1;
218 int max_cpus = 0;
219 int smp_cores = 1;
220 int smp_threads = 1;
221 const char *vnc_display;
222 int acpi_enabled = 1;
223 int no_hpet = 0;
224 int fd_bootchk = 1;
225 int no_reboot = 0;
226 int no_shutdown = 0;
227 int cursor_hide = 1;
228 int graphic_rotate = 0;
229 uint8_t irq0override = 1;
230 #ifndef _WIN32
231 int daemonize = 0;
232 #endif
233 const char *watchdog;
234 const char *option_rom[MAX_OPTION_ROMS];
235 int nb_option_roms;
236 int semihosting_enabled = 0;
237 #ifdef TARGET_ARM
238 int old_param = 0;
239 #endif
240 const char *qemu_name;
241 int alt_grab = 0;
242 int ctrl_grab = 0;
243 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
244 unsigned int nb_prom_envs = 0;
245 const char *prom_envs[MAX_PROM_ENVS];
246 #endif
247 int boot_menu;
249 int nb_numa_nodes;
250 uint64_t node_mem[MAX_NODES];
251 uint64_t node_cpumask[MAX_NODES];
253 static CPUState *cur_cpu;
254 static CPUState *next_cpu;
255 static QEMUTimer *nographic_timer;
257 uint8_t qemu_uuid[16];
259 static QEMUBootSetHandler *boot_set_handler;
260 static void *boot_set_opaque;
262 #ifdef SIGRTMIN
263 #define SIG_IPI (SIGRTMIN+4)
264 #else
265 #define SIG_IPI SIGUSR1
266 #endif
268 static int default_serial = 1;
269 static int default_parallel = 1;
270 static int default_virtcon = 1;
271 static int default_monitor = 1;
272 static int default_vga = 1;
273 static int default_floppy = 1;
274 static int default_cdrom = 1;
275 static int default_sdcard = 1;
277 static struct {
278 const char *driver;
279 int *flag;
280 } default_list[] = {
281 { .driver = "isa-serial", .flag = &default_serial },
282 { .driver = "isa-parallel", .flag = &default_parallel },
283 { .driver = "isa-fdc", .flag = &default_floppy },
284 { .driver = "ide-drive", .flag = &default_cdrom },
285 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
286 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
287 { .driver = "virtio-serial", .flag = &default_virtcon },
288 { .driver = "VGA", .flag = &default_vga },
289 { .driver = "cirrus-vga", .flag = &default_vga },
290 { .driver = "vmware-svga", .flag = &default_vga },
293 static int default_driver_check(QemuOpts *opts, void *opaque)
295 const char *driver = qemu_opt_get(opts, "driver");
296 int i;
298 if (!driver)
299 return 0;
300 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
301 if (strcmp(default_list[i].driver, driver) != 0)
302 continue;
303 *(default_list[i].flag) = 0;
305 return 0;
308 /***********************************************************/
309 /* x86 ISA bus support */
311 target_phys_addr_t isa_mem_base = 0;
312 PicState2 *isa_pic;
314 /***********************************************************/
315 void hw_error(const char *fmt, ...)
317 va_list ap;
318 CPUState *env;
320 va_start(ap, fmt);
321 fprintf(stderr, "qemu: hardware error: ");
322 vfprintf(stderr, fmt, ap);
323 fprintf(stderr, "\n");
324 for(env = first_cpu; env != NULL; env = env->next_cpu) {
325 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
326 #ifdef TARGET_I386
327 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
328 #else
329 cpu_dump_state(env, stderr, fprintf, 0);
330 #endif
332 va_end(ap);
333 abort();
336 static void set_proc_name(const char *s)
338 #if defined(__linux__) && defined(PR_SET_NAME)
339 char name[16];
340 if (!s)
341 return;
342 name[sizeof(name) - 1] = 0;
343 strncpy(name, s, sizeof(name));
344 /* Could rewrite argv[0] too, but that's a bit more complicated.
345 This simple way is enough for `top'. */
346 prctl(PR_SET_NAME, name);
347 #endif
350 /***************/
351 /* ballooning */
353 static QEMUBalloonEvent *qemu_balloon_event;
354 void *qemu_balloon_event_opaque;
356 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
358 qemu_balloon_event = func;
359 qemu_balloon_event_opaque = opaque;
362 int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
364 if (qemu_balloon_event) {
365 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
366 return 1;
367 } else {
368 return 0;
372 int qemu_balloon_status(MonitorCompletion cb, void *opaque)
374 if (qemu_balloon_event) {
375 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
376 return 1;
377 } else {
378 return 0;
383 /***********************************************************/
384 /* real time host monotonic timer */
386 /* compute with 96 bit intermediate result: (a*b)/c */
387 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
389 union {
390 uint64_t ll;
391 struct {
392 #ifdef HOST_WORDS_BIGENDIAN
393 uint32_t high, low;
394 #else
395 uint32_t low, high;
396 #endif
397 } l;
398 } u, res;
399 uint64_t rl, rh;
401 u.ll = a;
402 rl = (uint64_t)u.l.low * (uint64_t)b;
403 rh = (uint64_t)u.l.high * (uint64_t)b;
404 rh += (rl >> 32);
405 res.l.high = rh / c;
406 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
407 return res.ll;
410 /***********************************************************/
411 /* host time/date access */
412 void qemu_get_timedate(struct tm *tm, int offset)
414 time_t ti;
415 struct tm *ret;
417 time(&ti);
418 ti += offset;
419 if (rtc_date_offset == -1) {
420 if (rtc_utc)
421 ret = gmtime(&ti);
422 else
423 ret = localtime(&ti);
424 } else {
425 ti -= rtc_date_offset;
426 ret = gmtime(&ti);
429 memcpy(tm, ret, sizeof(struct tm));
432 int qemu_timedate_diff(struct tm *tm)
434 time_t seconds;
436 if (rtc_date_offset == -1)
437 if (rtc_utc)
438 seconds = mktimegm(tm);
439 else
440 seconds = mktime(tm);
441 else
442 seconds = mktimegm(tm) + rtc_date_offset;
444 return seconds - time(NULL);
447 void rtc_change_mon_event(struct tm *tm)
449 QObject *data;
451 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
452 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
453 qobject_decref(data);
456 static void configure_rtc_date_offset(const char *startdate, int legacy)
458 time_t rtc_start_date;
459 struct tm tm;
461 if (!strcmp(startdate, "now") && legacy) {
462 rtc_date_offset = -1;
463 } else {
464 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
465 &tm.tm_year,
466 &tm.tm_mon,
467 &tm.tm_mday,
468 &tm.tm_hour,
469 &tm.tm_min,
470 &tm.tm_sec) == 6) {
471 /* OK */
472 } else if (sscanf(startdate, "%d-%d-%d",
473 &tm.tm_year,
474 &tm.tm_mon,
475 &tm.tm_mday) == 3) {
476 tm.tm_hour = 0;
477 tm.tm_min = 0;
478 tm.tm_sec = 0;
479 } else {
480 goto date_fail;
482 tm.tm_year -= 1900;
483 tm.tm_mon--;
484 rtc_start_date = mktimegm(&tm);
485 if (rtc_start_date == -1) {
486 date_fail:
487 fprintf(stderr, "Invalid date format. Valid formats are:\n"
488 "'2006-06-17T16:01:21' or '2006-06-17'\n");
489 exit(1);
491 rtc_date_offset = time(NULL) - rtc_start_date;
495 static void configure_rtc(QemuOpts *opts)
497 const char *value;
499 value = qemu_opt_get(opts, "base");
500 if (value) {
501 if (!strcmp(value, "utc")) {
502 rtc_utc = 1;
503 } else if (!strcmp(value, "localtime")) {
504 rtc_utc = 0;
505 } else {
506 configure_rtc_date_offset(value, 0);
509 value = qemu_opt_get(opts, "clock");
510 if (value) {
511 if (!strcmp(value, "host")) {
512 rtc_clock = host_clock;
513 } else if (!strcmp(value, "vm")) {
514 rtc_clock = vm_clock;
515 } else {
516 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
517 exit(1);
520 #ifdef CONFIG_TARGET_I386
521 value = qemu_opt_get(opts, "driftfix");
522 if (value) {
523 if (!strcmp(buf, "slew")) {
524 rtc_td_hack = 1;
525 } else if (!strcmp(buf, "none")) {
526 rtc_td_hack = 0;
527 } else {
528 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
529 exit(1);
532 #endif
535 #ifdef _WIN32
536 static void socket_cleanup(Notifier *obj)
538 WSACleanup();
541 static int socket_init(void)
543 WSADATA Data;
544 int ret, err;
545 static Notifier notifier = { .notify = socket_cleanup };
547 ret = WSAStartup(MAKEWORD(2,2), &Data);
548 if (ret != 0) {
549 err = WSAGetLastError();
550 fprintf(stderr, "WSAStartup: %d\n", err);
551 return -1;
553 exit_notifier_add(&notifier);
554 return 0;
556 #endif
558 /*********************/
559 /* Exit notifiers */
560 /*********************/
562 static NotifierList exit_notifiers = NOTIFIER_LIST_INITIALIZER(exit_notifiers);
564 void exit_notifier_add(Notifier *notifier)
566 notifier_list_add(&exit_notifiers, notifier);
569 void exit_notifier_remove(Notifier *notifier)
571 notifier_list_remove(&exit_notifiers, notifier);
574 static void exit_notifier_notify(void)
576 notifier_list_notify(&exit_notifiers);
579 static void exit_notifier_init(void)
581 atexit(exit_notifier_notify);
584 /***********************************************************/
585 /* Bluetooth support */
586 static int nb_hcis;
587 static int cur_hci;
588 static struct HCIInfo *hci_table[MAX_NICS];
590 static struct bt_vlan_s {
591 struct bt_scatternet_s net;
592 int id;
593 struct bt_vlan_s *next;
594 } *first_bt_vlan;
596 /* find or alloc a new bluetooth "VLAN" */
597 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
599 struct bt_vlan_s **pvlan, *vlan;
600 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
601 if (vlan->id == id)
602 return &vlan->net;
604 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
605 vlan->id = id;
606 pvlan = &first_bt_vlan;
607 while (*pvlan != NULL)
608 pvlan = &(*pvlan)->next;
609 *pvlan = vlan;
610 return &vlan->net;
613 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
617 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
619 return -ENOTSUP;
622 static struct HCIInfo null_hci = {
623 .cmd_send = null_hci_send,
624 .sco_send = null_hci_send,
625 .acl_send = null_hci_send,
626 .bdaddr_set = null_hci_addr_set,
629 struct HCIInfo *qemu_next_hci(void)
631 if (cur_hci == nb_hcis)
632 return &null_hci;
634 return hci_table[cur_hci++];
637 static struct HCIInfo *hci_init(const char *str)
639 char *endp;
640 struct bt_scatternet_s *vlan = 0;
642 if (!strcmp(str, "null"))
643 /* null */
644 return &null_hci;
645 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
646 /* host[:hciN] */
647 return bt_host_hci(str[4] ? str + 5 : "hci0");
648 else if (!strncmp(str, "hci", 3)) {
649 /* hci[,vlan=n] */
650 if (str[3]) {
651 if (!strncmp(str + 3, ",vlan=", 6)) {
652 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
653 if (*endp)
654 vlan = 0;
656 } else
657 vlan = qemu_find_bt_vlan(0);
658 if (vlan)
659 return bt_new_hci(vlan);
662 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
664 return 0;
667 static int bt_hci_parse(const char *str)
669 struct HCIInfo *hci;
670 bdaddr_t bdaddr;
672 if (nb_hcis >= MAX_NICS) {
673 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
674 return -1;
677 hci = hci_init(str);
678 if (!hci)
679 return -1;
681 bdaddr.b[0] = 0x52;
682 bdaddr.b[1] = 0x54;
683 bdaddr.b[2] = 0x00;
684 bdaddr.b[3] = 0x12;
685 bdaddr.b[4] = 0x34;
686 bdaddr.b[5] = 0x56 + nb_hcis;
687 hci->bdaddr_set(hci, bdaddr.b);
689 hci_table[nb_hcis++] = hci;
691 return 0;
694 static void bt_vhci_add(int vlan_id)
696 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
698 if (!vlan->slave)
699 fprintf(stderr, "qemu: warning: adding a VHCI to "
700 "an empty scatternet %i\n", vlan_id);
702 bt_vhci_init(bt_new_hci(vlan));
705 static struct bt_device_s *bt_device_add(const char *opt)
707 struct bt_scatternet_s *vlan;
708 int vlan_id = 0;
709 char *endp = strstr(opt, ",vlan=");
710 int len = (endp ? endp - opt : strlen(opt)) + 1;
711 char devname[10];
713 pstrcpy(devname, MIN(sizeof(devname), len), opt);
715 if (endp) {
716 vlan_id = strtol(endp + 6, &endp, 0);
717 if (*endp) {
718 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
719 return 0;
723 vlan = qemu_find_bt_vlan(vlan_id);
725 if (!vlan->slave)
726 fprintf(stderr, "qemu: warning: adding a slave device to "
727 "an empty scatternet %i\n", vlan_id);
729 if (!strcmp(devname, "keyboard"))
730 return bt_keyboard_init(vlan);
732 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
733 return 0;
736 static int bt_parse(const char *opt)
738 const char *endp, *p;
739 int vlan;
741 if (strstart(opt, "hci", &endp)) {
742 if (!*endp || *endp == ',') {
743 if (*endp)
744 if (!strstart(endp, ",vlan=", 0))
745 opt = endp + 1;
747 return bt_hci_parse(opt);
749 } else if (strstart(opt, "vhci", &endp)) {
750 if (!*endp || *endp == ',') {
751 if (*endp) {
752 if (strstart(endp, ",vlan=", &p)) {
753 vlan = strtol(p, (char **) &endp, 0);
754 if (*endp) {
755 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
756 return 1;
758 } else {
759 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
760 return 1;
762 } else
763 vlan = 0;
765 bt_vhci_add(vlan);
766 return 0;
768 } else if (strstart(opt, "device:", &endp))
769 return !bt_device_add(endp);
771 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
772 return 1;
775 /***********************************************************/
776 /* QEMU Block devices */
778 #define HD_ALIAS "index=%d,media=disk"
779 #define CDROM_ALIAS "index=2,media=cdrom"
780 #define FD_ALIAS "index=%d,if=floppy"
781 #define PFLASH_ALIAS "if=pflash"
782 #define MTD_ALIAS "if=mtd"
783 #define SD_ALIAS "index=0,if=sd"
785 QemuOpts *drive_add(const char *file, const char *fmt, ...)
787 va_list ap;
788 char optstr[1024];
789 QemuOpts *opts;
791 va_start(ap, fmt);
792 vsnprintf(optstr, sizeof(optstr), fmt, ap);
793 va_end(ap);
795 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
796 if (!opts) {
797 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
798 __FUNCTION__, optstr);
799 return NULL;
801 if (file)
802 qemu_opt_set(opts, "file", file);
803 return opts;
806 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
808 DriveInfo *dinfo;
810 /* seek interface, bus and unit */
812 QTAILQ_FOREACH(dinfo, &drives, next) {
813 if (dinfo->type == type &&
814 dinfo->bus == bus &&
815 dinfo->unit == unit)
816 return dinfo;
819 return NULL;
822 DriveInfo *drive_get_by_id(const char *id)
824 DriveInfo *dinfo;
826 QTAILQ_FOREACH(dinfo, &drives, next) {
827 if (strcmp(id, dinfo->id))
828 continue;
829 return dinfo;
831 return NULL;
834 int drive_get_max_bus(BlockInterfaceType type)
836 int max_bus;
837 DriveInfo *dinfo;
839 max_bus = -1;
840 QTAILQ_FOREACH(dinfo, &drives, next) {
841 if(dinfo->type == type &&
842 dinfo->bus > max_bus)
843 max_bus = dinfo->bus;
845 return max_bus;
848 const char *drive_get_serial(BlockDriverState *bdrv)
850 DriveInfo *dinfo;
852 QTAILQ_FOREACH(dinfo, &drives, next) {
853 if (dinfo->bdrv == bdrv)
854 return dinfo->serial;
857 return "\0";
860 BlockInterfaceErrorAction drive_get_on_error(
861 BlockDriverState *bdrv, int is_read)
863 DriveInfo *dinfo;
865 QTAILQ_FOREACH(dinfo, &drives, next) {
866 if (dinfo->bdrv == bdrv)
867 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
870 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
873 static void bdrv_format_print(void *opaque, const char *name)
875 fprintf(stderr, " %s", name);
878 void drive_uninit(DriveInfo *dinfo)
880 qemu_opts_del(dinfo->opts);
881 bdrv_delete(dinfo->bdrv);
882 QTAILQ_REMOVE(&drives, dinfo, next);
883 qemu_free(dinfo);
886 static int parse_block_error_action(const char *buf, int is_read)
888 if (!strcmp(buf, "ignore")) {
889 return BLOCK_ERR_IGNORE;
890 } else if (!is_read && !strcmp(buf, "enospc")) {
891 return BLOCK_ERR_STOP_ENOSPC;
892 } else if (!strcmp(buf, "stop")) {
893 return BLOCK_ERR_STOP_ANY;
894 } else if (!strcmp(buf, "report")) {
895 return BLOCK_ERR_REPORT;
896 } else {
897 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
898 buf, is_read ? "read" : "write");
899 return -1;
903 DriveInfo *drive_init(QemuOpts *opts, void *opaque,
904 int *fatal_error)
906 const char *buf;
907 const char *file = NULL;
908 char devname[128];
909 const char *serial;
910 const char *mediastr = "";
911 BlockInterfaceType type;
912 enum { MEDIA_DISK, MEDIA_CDROM } media;
913 int bus_id, unit_id;
914 int cyls, heads, secs, translation;
915 BlockDriver *drv = NULL;
916 QEMUMachine *machine = opaque;
917 int max_devs;
918 int index;
919 int cache;
920 int aio = 0;
921 int ro = 0;
922 int bdrv_flags;
923 int on_read_error, on_write_error;
924 const char *devaddr;
925 DriveInfo *dinfo;
926 int snapshot = 0;
928 *fatal_error = 1;
930 translation = BIOS_ATA_TRANSLATION_AUTO;
931 cache = 1;
933 if (machine && machine->use_scsi) {
934 type = IF_SCSI;
935 max_devs = MAX_SCSI_DEVS;
936 pstrcpy(devname, sizeof(devname), "scsi");
937 } else {
938 type = IF_IDE;
939 max_devs = MAX_IDE_DEVS;
940 pstrcpy(devname, sizeof(devname), "ide");
942 media = MEDIA_DISK;
944 /* extract parameters */
945 bus_id = qemu_opt_get_number(opts, "bus", 0);
946 unit_id = qemu_opt_get_number(opts, "unit", -1);
947 index = qemu_opt_get_number(opts, "index", -1);
949 cyls = qemu_opt_get_number(opts, "cyls", 0);
950 heads = qemu_opt_get_number(opts, "heads", 0);
951 secs = qemu_opt_get_number(opts, "secs", 0);
953 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
954 ro = qemu_opt_get_bool(opts, "readonly", 0);
956 file = qemu_opt_get(opts, "file");
957 serial = qemu_opt_get(opts, "serial");
959 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
960 pstrcpy(devname, sizeof(devname), buf);
961 if (!strcmp(buf, "ide")) {
962 type = IF_IDE;
963 max_devs = MAX_IDE_DEVS;
964 } else if (!strcmp(buf, "scsi")) {
965 type = IF_SCSI;
966 max_devs = MAX_SCSI_DEVS;
967 } else if (!strcmp(buf, "floppy")) {
968 type = IF_FLOPPY;
969 max_devs = 0;
970 } else if (!strcmp(buf, "pflash")) {
971 type = IF_PFLASH;
972 max_devs = 0;
973 } else if (!strcmp(buf, "mtd")) {
974 type = IF_MTD;
975 max_devs = 0;
976 } else if (!strcmp(buf, "sd")) {
977 type = IF_SD;
978 max_devs = 0;
979 } else if (!strcmp(buf, "virtio")) {
980 type = IF_VIRTIO;
981 max_devs = 0;
982 } else if (!strcmp(buf, "xen")) {
983 type = IF_XEN;
984 max_devs = 0;
985 } else if (!strcmp(buf, "none")) {
986 type = IF_NONE;
987 max_devs = 0;
988 } else {
989 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
990 return NULL;
994 if (cyls || heads || secs) {
995 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
996 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
997 return NULL;
999 if (heads < 1 || (type == IF_IDE && heads > 16)) {
1000 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1001 return NULL;
1003 if (secs < 1 || (type == IF_IDE && secs > 63)) {
1004 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1005 return NULL;
1009 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1010 if (!cyls) {
1011 fprintf(stderr,
1012 "qemu: '%s' trans must be used with cyls,heads and secs\n",
1013 buf);
1014 return NULL;
1016 if (!strcmp(buf, "none"))
1017 translation = BIOS_ATA_TRANSLATION_NONE;
1018 else if (!strcmp(buf, "lba"))
1019 translation = BIOS_ATA_TRANSLATION_LBA;
1020 else if (!strcmp(buf, "auto"))
1021 translation = BIOS_ATA_TRANSLATION_AUTO;
1022 else {
1023 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
1024 return NULL;
1028 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
1029 if (!strcmp(buf, "disk")) {
1030 media = MEDIA_DISK;
1031 } else if (!strcmp(buf, "cdrom")) {
1032 if (cyls || secs || heads) {
1033 fprintf(stderr,
1034 "qemu: '%s' invalid physical CHS format\n", buf);
1035 return NULL;
1037 media = MEDIA_CDROM;
1038 } else {
1039 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
1040 return NULL;
1044 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
1045 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
1046 cache = 0;
1047 else if (!strcmp(buf, "writethrough"))
1048 cache = 1;
1049 else if (!strcmp(buf, "writeback"))
1050 cache = 2;
1051 else {
1052 fprintf(stderr, "qemu: invalid cache option\n");
1053 return NULL;
1057 #ifdef CONFIG_LINUX_AIO
1058 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1059 if (!strcmp(buf, "threads"))
1060 aio = 0;
1061 else if (!strcmp(buf, "native"))
1062 aio = 1;
1063 else {
1064 fprintf(stderr, "qemu: invalid aio option\n");
1065 return NULL;
1068 #endif
1070 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1071 if (strcmp(buf, "?") == 0) {
1072 fprintf(stderr, "qemu: Supported formats:");
1073 bdrv_iterate_format(bdrv_format_print, NULL);
1074 fprintf(stderr, "\n");
1075 return NULL;
1077 drv = bdrv_find_whitelisted_format(buf);
1078 if (!drv) {
1079 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1080 return NULL;
1084 on_write_error = BLOCK_ERR_STOP_ENOSPC;
1085 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1086 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1087 fprintf(stderr, "werror is no supported by this format\n");
1088 return NULL;
1091 on_write_error = parse_block_error_action(buf, 0);
1092 if (on_write_error < 0) {
1093 return NULL;
1097 on_read_error = BLOCK_ERR_REPORT;
1098 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1099 if (type != IF_IDE && type != IF_VIRTIO) {
1100 fprintf(stderr, "rerror is no supported by this format\n");
1101 return NULL;
1104 on_read_error = parse_block_error_action(buf, 1);
1105 if (on_read_error < 0) {
1106 return NULL;
1110 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1111 if (type != IF_VIRTIO) {
1112 fprintf(stderr, "addr is not supported\n");
1113 return NULL;
1117 /* compute bus and unit according index */
1119 if (index != -1) {
1120 if (bus_id != 0 || unit_id != -1) {
1121 fprintf(stderr,
1122 "qemu: index cannot be used with bus and unit\n");
1123 return NULL;
1125 if (max_devs == 0)
1127 unit_id = index;
1128 bus_id = 0;
1129 } else {
1130 unit_id = index % max_devs;
1131 bus_id = index / max_devs;
1135 /* if user doesn't specify a unit_id,
1136 * try to find the first free
1139 if (unit_id == -1) {
1140 unit_id = 0;
1141 while (drive_get(type, bus_id, unit_id) != NULL) {
1142 unit_id++;
1143 if (max_devs && unit_id >= max_devs) {
1144 unit_id -= max_devs;
1145 bus_id++;
1150 /* check unit id */
1152 if (max_devs && unit_id >= max_devs) {
1153 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1154 unit_id, max_devs - 1);
1155 return NULL;
1159 * ignore multiple definitions
1162 if (drive_get(type, bus_id, unit_id) != NULL) {
1163 *fatal_error = 0;
1164 return NULL;
1167 /* init */
1169 dinfo = qemu_mallocz(sizeof(*dinfo));
1170 if ((buf = qemu_opts_id(opts)) != NULL) {
1171 dinfo->id = qemu_strdup(buf);
1172 } else {
1173 /* no id supplied -> create one */
1174 dinfo->id = qemu_mallocz(32);
1175 if (type == IF_IDE || type == IF_SCSI)
1176 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1177 if (max_devs)
1178 snprintf(dinfo->id, 32, "%s%i%s%i",
1179 devname, bus_id, mediastr, unit_id);
1180 else
1181 snprintf(dinfo->id, 32, "%s%s%i",
1182 devname, mediastr, unit_id);
1184 dinfo->bdrv = bdrv_new(dinfo->id);
1185 dinfo->devaddr = devaddr;
1186 dinfo->type = type;
1187 dinfo->bus = bus_id;
1188 dinfo->unit = unit_id;
1189 dinfo->on_read_error = on_read_error;
1190 dinfo->on_write_error = on_write_error;
1191 dinfo->opts = opts;
1192 if (serial)
1193 strncpy(dinfo->serial, serial, sizeof(serial));
1194 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1196 switch(type) {
1197 case IF_IDE:
1198 case IF_SCSI:
1199 case IF_XEN:
1200 case IF_NONE:
1201 switch(media) {
1202 case MEDIA_DISK:
1203 if (cyls != 0) {
1204 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1205 bdrv_set_translation_hint(dinfo->bdrv, translation);
1207 break;
1208 case MEDIA_CDROM:
1209 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1210 break;
1212 break;
1213 case IF_SD:
1214 /* FIXME: This isn't really a floppy, but it's a reasonable
1215 approximation. */
1216 case IF_FLOPPY:
1217 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1218 break;
1219 case IF_PFLASH:
1220 case IF_MTD:
1221 break;
1222 case IF_VIRTIO:
1223 /* add virtio block device */
1224 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1225 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1226 qemu_opt_set(opts, "drive", dinfo->id);
1227 if (devaddr)
1228 qemu_opt_set(opts, "addr", devaddr);
1229 break;
1230 case IF_COUNT:
1231 abort();
1233 if (!file) {
1234 *fatal_error = 0;
1235 return NULL;
1237 bdrv_flags = 0;
1238 if (snapshot) {
1239 bdrv_flags |= BDRV_O_SNAPSHOT;
1240 cache = 2; /* always use write-back with snapshot */
1242 if (cache == 0) /* no caching */
1243 bdrv_flags |= BDRV_O_NOCACHE;
1244 else if (cache == 2) /* write-back */
1245 bdrv_flags |= BDRV_O_CACHE_WB;
1247 if (aio == 1) {
1248 bdrv_flags |= BDRV_O_NATIVE_AIO;
1249 } else {
1250 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1253 if (ro == 1) {
1254 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1255 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1256 return NULL;
1260 * cdrom is read-only. Set it now, after above interface checking
1261 * since readonly attribute not explicitly required, so no error.
1263 if (media == MEDIA_CDROM) {
1264 ro = 1;
1266 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1268 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1269 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1270 file, strerror(errno));
1271 return NULL;
1274 if (bdrv_key_required(dinfo->bdrv))
1275 autostart = 0;
1276 *fatal_error = 0;
1277 return dinfo;
1280 static int drive_init_func(QemuOpts *opts, void *opaque)
1282 QEMUMachine *machine = opaque;
1283 int fatal_error = 0;
1285 if (drive_init(opts, machine, &fatal_error) == NULL) {
1286 if (fatal_error)
1287 return 1;
1289 return 0;
1292 static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1294 if (NULL == qemu_opt_get(opts, "snapshot")) {
1295 qemu_opt_set(opts, "snapshot", "on");
1297 return 0;
1300 void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1302 boot_set_handler = func;
1303 boot_set_opaque = opaque;
1306 int qemu_boot_set(const char *boot_devices)
1308 if (!boot_set_handler) {
1309 return -EINVAL;
1311 return boot_set_handler(boot_set_opaque, boot_devices);
1314 static int parse_bootdevices(char *devices)
1316 /* We just do some generic consistency checks */
1317 const char *p;
1318 int bitmap = 0;
1320 for (p = devices; *p != '\0'; p++) {
1321 /* Allowed boot devices are:
1322 * a-b: floppy disk drives
1323 * c-f: IDE disk drives
1324 * g-m: machine implementation dependant drives
1325 * n-p: network devices
1326 * It's up to each machine implementation to check if the given boot
1327 * devices match the actual hardware implementation and firmware
1328 * features.
1330 if (*p < 'a' || *p > 'p') {
1331 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1332 exit(1);
1334 if (bitmap & (1 << (*p - 'a'))) {
1335 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1336 exit(1);
1338 bitmap |= 1 << (*p - 'a');
1340 return bitmap;
1343 static void restore_boot_devices(void *opaque)
1345 char *standard_boot_devices = opaque;
1347 qemu_boot_set(standard_boot_devices);
1349 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1350 qemu_free(standard_boot_devices);
1353 static void numa_add(const char *optarg)
1355 char option[128];
1356 char *endptr;
1357 unsigned long long value, endvalue;
1358 int nodenr;
1360 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1361 if (!strcmp(option, "node")) {
1362 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1363 nodenr = nb_numa_nodes;
1364 } else {
1365 nodenr = strtoull(option, NULL, 10);
1368 if (get_param_value(option, 128, "mem", optarg) == 0) {
1369 node_mem[nodenr] = 0;
1370 } else {
1371 value = strtoull(option, &endptr, 0);
1372 switch (*endptr) {
1373 case 0: case 'M': case 'm':
1374 value <<= 20;
1375 break;
1376 case 'G': case 'g':
1377 value <<= 30;
1378 break;
1380 node_mem[nodenr] = value;
1382 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1383 node_cpumask[nodenr] = 0;
1384 } else {
1385 value = strtoull(option, &endptr, 10);
1386 if (value >= 64) {
1387 value = 63;
1388 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1389 } else {
1390 if (*endptr == '-') {
1391 endvalue = strtoull(endptr+1, &endptr, 10);
1392 if (endvalue >= 63) {
1393 endvalue = 62;
1394 fprintf(stderr,
1395 "only 63 CPUs in NUMA mode supported.\n");
1397 value = (2ULL << endvalue) - (1ULL << value);
1398 } else {
1399 value = 1ULL << value;
1402 node_cpumask[nodenr] = value;
1404 nb_numa_nodes++;
1406 return;
1409 static void smp_parse(const char *optarg)
1411 int smp, sockets = 0, threads = 0, cores = 0;
1412 char *endptr;
1413 char option[128];
1415 smp = strtoul(optarg, &endptr, 10);
1416 if (endptr != optarg) {
1417 if (*endptr == ',') {
1418 endptr++;
1421 if (get_param_value(option, 128, "sockets", endptr) != 0)
1422 sockets = strtoull(option, NULL, 10);
1423 if (get_param_value(option, 128, "cores", endptr) != 0)
1424 cores = strtoull(option, NULL, 10);
1425 if (get_param_value(option, 128, "threads", endptr) != 0)
1426 threads = strtoull(option, NULL, 10);
1427 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1428 max_cpus = strtoull(option, NULL, 10);
1430 /* compute missing values, prefer sockets over cores over threads */
1431 if (smp == 0 || sockets == 0) {
1432 sockets = sockets > 0 ? sockets : 1;
1433 cores = cores > 0 ? cores : 1;
1434 threads = threads > 0 ? threads : 1;
1435 if (smp == 0) {
1436 smp = cores * threads * sockets;
1438 } else {
1439 if (cores == 0) {
1440 threads = threads > 0 ? threads : 1;
1441 cores = smp / (sockets * threads);
1442 } else {
1443 if (sockets) {
1444 threads = smp / (cores * sockets);
1448 smp_cpus = smp;
1449 smp_cores = cores > 0 ? cores : 1;
1450 smp_threads = threads > 0 ? threads : 1;
1451 if (max_cpus == 0)
1452 max_cpus = smp_cpus;
1455 /***********************************************************/
1456 /* USB devices */
1458 static int usb_device_add(const char *devname, int is_hotplug)
1460 const char *p;
1461 USBDevice *dev = NULL;
1463 if (!usb_enabled)
1464 return -1;
1466 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1467 dev = usbdevice_create(devname);
1468 if (dev)
1469 goto done;
1471 /* the other ones */
1472 if (strstart(devname, "host:", &p)) {
1473 dev = usb_host_device_open(p);
1474 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1475 dev = usb_bt_init(devname[2] ? hci_init(p) :
1476 bt_new_hci(qemu_find_bt_vlan(0)));
1477 } else {
1478 return -1;
1480 if (!dev)
1481 return -1;
1483 done:
1484 return 0;
1487 static int usb_device_del(const char *devname)
1489 int bus_num, addr;
1490 const char *p;
1492 if (strstart(devname, "host:", &p))
1493 return usb_host_device_close(p);
1495 if (!usb_enabled)
1496 return -1;
1498 p = strchr(devname, '.');
1499 if (!p)
1500 return -1;
1501 bus_num = strtoul(devname, NULL, 0);
1502 addr = strtoul(p + 1, NULL, 0);
1504 return usb_device_delete_addr(bus_num, addr);
1507 static int usb_parse(const char *cmdline)
1509 int r;
1510 r = usb_device_add(cmdline, 0);
1511 if (r < 0) {
1512 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1514 return r;
1517 void do_usb_add(Monitor *mon, const QDict *qdict)
1519 const char *devname = qdict_get_str(qdict, "devname");
1520 if (usb_device_add(devname, 1) < 0) {
1521 error_report("could not add USB device '%s'", devname);
1525 void do_usb_del(Monitor *mon, const QDict *qdict)
1527 const char *devname = qdict_get_str(qdict, "devname");
1528 if (usb_device_del(devname) < 0) {
1529 error_report("could not delete USB device '%s'", devname);
1533 /***********************************************************/
1534 /* PCMCIA/Cardbus */
1536 static struct pcmcia_socket_entry_s {
1537 PCMCIASocket *socket;
1538 struct pcmcia_socket_entry_s *next;
1539 } *pcmcia_sockets = 0;
1541 void pcmcia_socket_register(PCMCIASocket *socket)
1543 struct pcmcia_socket_entry_s *entry;
1545 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1546 entry->socket = socket;
1547 entry->next = pcmcia_sockets;
1548 pcmcia_sockets = entry;
1551 void pcmcia_socket_unregister(PCMCIASocket *socket)
1553 struct pcmcia_socket_entry_s *entry, **ptr;
1555 ptr = &pcmcia_sockets;
1556 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1557 if (entry->socket == socket) {
1558 *ptr = entry->next;
1559 qemu_free(entry);
1563 void pcmcia_info(Monitor *mon)
1565 struct pcmcia_socket_entry_s *iter;
1567 if (!pcmcia_sockets)
1568 monitor_printf(mon, "No PCMCIA sockets\n");
1570 for (iter = pcmcia_sockets; iter; iter = iter->next)
1571 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1572 iter->socket->attached ? iter->socket->card_string :
1573 "Empty");
1576 /***********************************************************/
1577 /* I/O handling */
1579 typedef struct IOHandlerRecord {
1580 int fd;
1581 IOCanReadHandler *fd_read_poll;
1582 IOHandler *fd_read;
1583 IOHandler *fd_write;
1584 int deleted;
1585 void *opaque;
1586 /* temporary data */
1587 struct pollfd *ufd;
1588 QLIST_ENTRY(IOHandlerRecord) next;
1589 } IOHandlerRecord;
1591 static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1592 QLIST_HEAD_INITIALIZER(io_handlers);
1595 /* XXX: fd_read_poll should be suppressed, but an API change is
1596 necessary in the character devices to suppress fd_can_read(). */
1597 int qemu_set_fd_handler2(int fd,
1598 IOCanReadHandler *fd_read_poll,
1599 IOHandler *fd_read,
1600 IOHandler *fd_write,
1601 void *opaque)
1603 IOHandlerRecord *ioh;
1605 if (!fd_read && !fd_write) {
1606 QLIST_FOREACH(ioh, &io_handlers, next) {
1607 if (ioh->fd == fd) {
1608 ioh->deleted = 1;
1609 break;
1612 } else {
1613 QLIST_FOREACH(ioh, &io_handlers, next) {
1614 if (ioh->fd == fd)
1615 goto found;
1617 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1618 QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1619 found:
1620 ioh->fd = fd;
1621 ioh->fd_read_poll = fd_read_poll;
1622 ioh->fd_read = fd_read;
1623 ioh->fd_write = fd_write;
1624 ioh->opaque = opaque;
1625 ioh->deleted = 0;
1627 return 0;
1630 int qemu_set_fd_handler(int fd,
1631 IOHandler *fd_read,
1632 IOHandler *fd_write,
1633 void *opaque)
1635 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1638 #ifdef _WIN32
1639 /***********************************************************/
1640 /* Polling handling */
1642 typedef struct PollingEntry {
1643 PollingFunc *func;
1644 void *opaque;
1645 struct PollingEntry *next;
1646 } PollingEntry;
1648 static PollingEntry *first_polling_entry;
1650 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1652 PollingEntry **ppe, *pe;
1653 pe = qemu_mallocz(sizeof(PollingEntry));
1654 pe->func = func;
1655 pe->opaque = opaque;
1656 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1657 *ppe = pe;
1658 return 0;
1661 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1663 PollingEntry **ppe, *pe;
1664 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1665 pe = *ppe;
1666 if (pe->func == func && pe->opaque == opaque) {
1667 *ppe = pe->next;
1668 qemu_free(pe);
1669 break;
1674 /***********************************************************/
1675 /* Wait objects support */
1676 typedef struct WaitObjects {
1677 int num;
1678 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1679 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1680 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1681 } WaitObjects;
1683 static WaitObjects wait_objects = {0};
1685 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1687 WaitObjects *w = &wait_objects;
1689 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1690 return -1;
1691 w->events[w->num] = handle;
1692 w->func[w->num] = func;
1693 w->opaque[w->num] = opaque;
1694 w->num++;
1695 return 0;
1698 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1700 int i, found;
1701 WaitObjects *w = &wait_objects;
1703 found = 0;
1704 for (i = 0; i < w->num; i++) {
1705 if (w->events[i] == handle)
1706 found = 1;
1707 if (found) {
1708 w->events[i] = w->events[i + 1];
1709 w->func[i] = w->func[i + 1];
1710 w->opaque[i] = w->opaque[i + 1];
1713 if (found)
1714 w->num--;
1716 #endif
1718 /***********************************************************/
1719 /* ram save/restore */
1721 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
1722 #define RAM_SAVE_FLAG_COMPRESS 0x02
1723 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
1724 #define RAM_SAVE_FLAG_PAGE 0x08
1725 #define RAM_SAVE_FLAG_EOS 0x10
1727 static int is_dup_page(uint8_t *page, uint8_t ch)
1729 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1730 uint32_t *array = (uint32_t *)page;
1731 int i;
1733 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1734 if (array[i] != val)
1735 return 0;
1738 return 1;
1741 static int ram_save_block(QEMUFile *f)
1743 static ram_addr_t current_addr = 0;
1744 ram_addr_t saved_addr = current_addr;
1745 ram_addr_t addr = 0;
1746 int found = 0;
1748 while (addr < last_ram_offset) {
1749 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1750 uint8_t *p;
1752 cpu_physical_memory_reset_dirty(current_addr,
1753 current_addr + TARGET_PAGE_SIZE,
1754 MIGRATION_DIRTY_FLAG);
1756 p = qemu_get_ram_ptr(current_addr);
1758 if (is_dup_page(p, *p)) {
1759 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1760 qemu_put_byte(f, *p);
1761 } else {
1762 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1763 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1766 found = 1;
1767 break;
1769 addr += TARGET_PAGE_SIZE;
1770 current_addr = (saved_addr + addr) % last_ram_offset;
1773 return found;
1776 static uint64_t bytes_transferred;
1778 static ram_addr_t ram_save_remaining(void)
1780 ram_addr_t addr;
1781 ram_addr_t count = 0;
1783 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1784 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1785 count++;
1788 return count;
1791 uint64_t ram_bytes_remaining(void)
1793 return ram_save_remaining() * TARGET_PAGE_SIZE;
1796 uint64_t ram_bytes_transferred(void)
1798 return bytes_transferred;
1801 uint64_t ram_bytes_total(void)
1803 return last_ram_offset;
1806 static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1808 ram_addr_t addr;
1809 uint64_t bytes_transferred_last;
1810 double bwidth = 0;
1811 uint64_t expected_time = 0;
1813 if (stage < 0) {
1814 cpu_physical_memory_set_dirty_tracking(0);
1815 return 0;
1818 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1819 qemu_file_set_error(f);
1820 return 0;
1823 if (stage == 1) {
1824 bytes_transferred = 0;
1826 /* Make sure all dirty bits are set */
1827 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1828 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1829 cpu_physical_memory_set_dirty(addr);
1832 /* Enable dirty memory tracking */
1833 cpu_physical_memory_set_dirty_tracking(1);
1835 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1838 bytes_transferred_last = bytes_transferred;
1839 bwidth = qemu_get_clock_ns(rt_clock);
1841 while (!qemu_file_rate_limit(f)) {
1842 int ret;
1844 ret = ram_save_block(f);
1845 bytes_transferred += ret * TARGET_PAGE_SIZE;
1846 if (ret == 0) /* no more blocks */
1847 break;
1850 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1851 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1853 /* if we haven't transferred anything this round, force expected_time to a
1854 * a very high value, but without crashing */
1855 if (bwidth == 0)
1856 bwidth = 0.000001;
1858 /* try transferring iterative blocks of memory */
1859 if (stage == 3) {
1860 /* flush all remaining blocks regardless of rate limiting */
1861 while (ram_save_block(f) != 0) {
1862 bytes_transferred += TARGET_PAGE_SIZE;
1864 cpu_physical_memory_set_dirty_tracking(0);
1867 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1869 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1871 return (stage == 2) && (expected_time <= migrate_max_downtime());
1874 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1876 ram_addr_t addr;
1877 int flags;
1879 if (version_id != 3)
1880 return -EINVAL;
1882 do {
1883 addr = qemu_get_be64(f);
1885 flags = addr & ~TARGET_PAGE_MASK;
1886 addr &= TARGET_PAGE_MASK;
1888 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1889 if (addr != last_ram_offset)
1890 return -EINVAL;
1893 if (flags & RAM_SAVE_FLAG_COMPRESS) {
1894 uint8_t ch = qemu_get_byte(f);
1895 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1896 #ifndef _WIN32
1897 if (ch == 0 &&
1898 (!kvm_enabled() || kvm_has_sync_mmu())) {
1899 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1901 #endif
1902 } else if (flags & RAM_SAVE_FLAG_PAGE) {
1903 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1905 if (qemu_file_has_error(f)) {
1906 return -EIO;
1908 } while (!(flags & RAM_SAVE_FLAG_EOS));
1910 return 0;
1913 void qemu_service_io(void)
1915 qemu_notify_event();
1918 /***********************************************************/
1919 /* machine registration */
1921 static QEMUMachine *first_machine = NULL;
1922 QEMUMachine *current_machine = NULL;
1924 int qemu_register_machine(QEMUMachine *m)
1926 QEMUMachine **pm;
1927 pm = &first_machine;
1928 while (*pm != NULL)
1929 pm = &(*pm)->next;
1930 m->next = NULL;
1931 *pm = m;
1932 return 0;
1935 static QEMUMachine *find_machine(const char *name)
1937 QEMUMachine *m;
1939 for(m = first_machine; m != NULL; m = m->next) {
1940 if (!strcmp(m->name, name))
1941 return m;
1942 if (m->alias && !strcmp(m->alias, name))
1943 return m;
1945 return NULL;
1948 static QEMUMachine *find_default_machine(void)
1950 QEMUMachine *m;
1952 for(m = first_machine; m != NULL; m = m->next) {
1953 if (m->is_default) {
1954 return m;
1957 return NULL;
1960 /***********************************************************/
1961 /* main execution loop */
1963 static void gui_update(void *opaque)
1965 uint64_t interval = GUI_REFRESH_INTERVAL;
1966 DisplayState *ds = opaque;
1967 DisplayChangeListener *dcl = ds->listeners;
1969 qemu_flush_coalesced_mmio_buffer();
1970 dpy_refresh(ds);
1972 while (dcl != NULL) {
1973 if (dcl->gui_timer_interval &&
1974 dcl->gui_timer_interval < interval)
1975 interval = dcl->gui_timer_interval;
1976 dcl = dcl->next;
1978 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1981 static void nographic_update(void *opaque)
1983 uint64_t interval = GUI_REFRESH_INTERVAL;
1985 qemu_flush_coalesced_mmio_buffer();
1986 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1989 void cpu_synchronize_all_states(void)
1991 CPUState *cpu;
1993 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1994 cpu_synchronize_state(cpu);
1998 void cpu_synchronize_all_post_reset(void)
2000 CPUState *cpu;
2002 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2003 cpu_synchronize_post_reset(cpu);
2007 void cpu_synchronize_all_post_init(void)
2009 CPUState *cpu;
2011 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2012 cpu_synchronize_post_init(cpu);
2016 struct vm_change_state_entry {
2017 VMChangeStateHandler *cb;
2018 void *opaque;
2019 QLIST_ENTRY (vm_change_state_entry) entries;
2022 static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
2024 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
2025 void *opaque)
2027 VMChangeStateEntry *e;
2029 e = qemu_mallocz(sizeof (*e));
2031 e->cb = cb;
2032 e->opaque = opaque;
2033 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
2034 return e;
2037 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
2039 QLIST_REMOVE (e, entries);
2040 qemu_free (e);
2043 static void vm_state_notify(int running, int reason)
2045 VMChangeStateEntry *e;
2047 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
2048 e->cb(e->opaque, running, reason);
2052 static void resume_all_vcpus(void);
2053 static void pause_all_vcpus(void);
2055 void vm_start(void)
2057 if (!vm_running) {
2058 cpu_enable_ticks();
2059 vm_running = 1;
2060 vm_state_notify(1, 0);
2061 resume_all_vcpus();
2065 /* reset/shutdown handler */
2067 typedef struct QEMUResetEntry {
2068 QTAILQ_ENTRY(QEMUResetEntry) entry;
2069 QEMUResetHandler *func;
2070 void *opaque;
2071 } QEMUResetEntry;
2073 static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
2074 QTAILQ_HEAD_INITIALIZER(reset_handlers);
2075 static int reset_requested;
2076 static int shutdown_requested;
2077 static int powerdown_requested;
2078 static int debug_requested;
2079 static int vmstop_requested;
2081 int qemu_shutdown_requested(void)
2083 int r = shutdown_requested;
2084 shutdown_requested = 0;
2085 return r;
2088 int qemu_reset_requested(void)
2090 int r = reset_requested;
2091 reset_requested = 0;
2092 return r;
2095 int qemu_powerdown_requested(void)
2097 int r = powerdown_requested;
2098 powerdown_requested = 0;
2099 return r;
2102 static int qemu_debug_requested(void)
2104 int r = debug_requested;
2105 debug_requested = 0;
2106 return r;
2109 static int qemu_vmstop_requested(void)
2111 int r = vmstop_requested;
2112 vmstop_requested = 0;
2113 return r;
2116 static void do_vm_stop(int reason)
2118 if (vm_running) {
2119 cpu_disable_ticks();
2120 vm_running = 0;
2121 pause_all_vcpus();
2122 vm_state_notify(0, reason);
2123 monitor_protocol_event(QEVENT_STOP, NULL);
2127 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2129 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2131 re->func = func;
2132 re->opaque = opaque;
2133 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2136 void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2138 QEMUResetEntry *re;
2140 QTAILQ_FOREACH(re, &reset_handlers, entry) {
2141 if (re->func == func && re->opaque == opaque) {
2142 QTAILQ_REMOVE(&reset_handlers, re, entry);
2143 qemu_free(re);
2144 return;
2149 void qemu_system_reset(void)
2151 QEMUResetEntry *re, *nre;
2153 /* reset all devices */
2154 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2155 re->func(re->opaque);
2157 monitor_protocol_event(QEVENT_RESET, NULL);
2158 cpu_synchronize_all_post_reset();
2161 void qemu_system_reset_request(void)
2163 if (no_reboot) {
2164 shutdown_requested = 1;
2165 } else {
2166 reset_requested = 1;
2168 qemu_notify_event();
2171 void qemu_system_shutdown_request(void)
2173 shutdown_requested = 1;
2174 qemu_notify_event();
2177 void qemu_system_powerdown_request(void)
2179 powerdown_requested = 1;
2180 qemu_notify_event();
2183 static int cpu_can_run(CPUState *env)
2185 if (env->stop)
2186 return 0;
2187 if (env->stopped)
2188 return 0;
2189 if (!vm_running)
2190 return 0;
2191 return 1;
2194 static int cpu_has_work(CPUState *env)
2196 if (env->stop)
2197 return 1;
2198 if (env->stopped)
2199 return 0;
2200 if (!env->halted)
2201 return 1;
2202 if (qemu_cpu_has_work(env))
2203 return 1;
2204 return 0;
2207 static int tcg_has_work(void)
2209 CPUState *env;
2211 for (env = first_cpu; env != NULL; env = env->next_cpu)
2212 if (cpu_has_work(env))
2213 return 1;
2214 return 0;
2217 #ifndef _WIN32
2218 static int io_thread_fd = -1;
2220 static void qemu_event_increment(void)
2222 /* Write 8 bytes to be compatible with eventfd. */
2223 static uint64_t val = 1;
2224 ssize_t ret;
2226 if (io_thread_fd == -1)
2227 return;
2229 do {
2230 ret = write(io_thread_fd, &val, sizeof(val));
2231 } while (ret < 0 && errno == EINTR);
2233 /* EAGAIN is fine, a read must be pending. */
2234 if (ret < 0 && errno != EAGAIN) {
2235 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
2236 strerror(errno));
2237 exit (1);
2241 static void qemu_event_read(void *opaque)
2243 int fd = (unsigned long)opaque;
2244 ssize_t len;
2245 char buffer[512];
2247 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
2248 do {
2249 len = read(fd, buffer, sizeof(buffer));
2250 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
2253 static int qemu_event_init(void)
2255 int err;
2256 int fds[2];
2258 err = qemu_eventfd(fds);
2259 if (err == -1)
2260 return -errno;
2262 err = fcntl_setfl(fds[0], O_NONBLOCK);
2263 if (err < 0)
2264 goto fail;
2266 err = fcntl_setfl(fds[1], O_NONBLOCK);
2267 if (err < 0)
2268 goto fail;
2270 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
2271 (void *)(unsigned long)fds[0]);
2273 io_thread_fd = fds[1];
2274 return 0;
2276 fail:
2277 close(fds[0]);
2278 close(fds[1]);
2279 return err;
2281 #else
2282 HANDLE qemu_event_handle;
2284 static void dummy_event_handler(void *opaque)
2288 static int qemu_event_init(void)
2290 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
2291 if (!qemu_event_handle) {
2292 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
2293 return -1;
2295 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
2296 return 0;
2299 static void qemu_event_increment(void)
2301 if (!SetEvent(qemu_event_handle)) {
2302 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
2303 GetLastError());
2304 exit (1);
2307 #endif
2309 #ifndef CONFIG_IOTHREAD
2310 static int qemu_init_main_loop(void)
2312 return qemu_event_init();
2315 void qemu_init_vcpu(void *_env)
2317 CPUState *env = _env;
2319 env->nr_cores = smp_cores;
2320 env->nr_threads = smp_threads;
2321 if (kvm_enabled())
2322 kvm_init_vcpu(env);
2323 return;
2326 int qemu_cpu_self(void *env)
2328 return 1;
2331 static void resume_all_vcpus(void)
2335 static void pause_all_vcpus(void)
2339 void qemu_cpu_kick(void *env)
2341 return;
2344 void qemu_notify_event(void)
2346 CPUState *env = cpu_single_env;
2348 qemu_event_increment ();
2349 if (env) {
2350 cpu_exit(env);
2352 if (next_cpu && env != next_cpu) {
2353 cpu_exit(next_cpu);
2357 void qemu_mutex_lock_iothread(void) {}
2358 void qemu_mutex_unlock_iothread(void) {}
2360 void vm_stop(int reason)
2362 do_vm_stop(reason);
2365 #else /* CONFIG_IOTHREAD */
2367 #include "qemu-thread.h"
2369 QemuMutex qemu_global_mutex;
2370 static QemuMutex qemu_fair_mutex;
2372 static QemuThread io_thread;
2374 static QemuThread *tcg_cpu_thread;
2375 static QemuCond *tcg_halt_cond;
2377 static int qemu_system_ready;
2378 /* cpu creation */
2379 static QemuCond qemu_cpu_cond;
2380 /* system init */
2381 static QemuCond qemu_system_cond;
2382 static QemuCond qemu_pause_cond;
2384 static void tcg_block_io_signals(void);
2385 static void kvm_block_io_signals(CPUState *env);
2386 static void unblock_io_signals(void);
2388 static int qemu_init_main_loop(void)
2390 int ret;
2392 ret = qemu_event_init();
2393 if (ret)
2394 return ret;
2396 qemu_cond_init(&qemu_pause_cond);
2397 qemu_mutex_init(&qemu_fair_mutex);
2398 qemu_mutex_init(&qemu_global_mutex);
2399 qemu_mutex_lock(&qemu_global_mutex);
2401 unblock_io_signals();
2402 qemu_thread_self(&io_thread);
2404 return 0;
2407 static void qemu_wait_io_event_common(CPUState *env)
2409 if (env->stop) {
2410 env->stop = 0;
2411 env->stopped = 1;
2412 qemu_cond_signal(&qemu_pause_cond);
2416 static void qemu_wait_io_event(CPUState *env)
2418 while (!tcg_has_work())
2419 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2421 qemu_mutex_unlock(&qemu_global_mutex);
2424 * Users of qemu_global_mutex can be starved, having no chance
2425 * to acquire it since this path will get to it first.
2426 * So use another lock to provide fairness.
2428 qemu_mutex_lock(&qemu_fair_mutex);
2429 qemu_mutex_unlock(&qemu_fair_mutex);
2431 qemu_mutex_lock(&qemu_global_mutex);
2432 qemu_wait_io_event_common(env);
2435 static void qemu_kvm_eat_signal(CPUState *env, int timeout)
2437 struct timespec ts;
2438 int r, e;
2439 siginfo_t siginfo;
2440 sigset_t waitset;
2442 ts.tv_sec = timeout / 1000;
2443 ts.tv_nsec = (timeout % 1000) * 1000000;
2445 sigemptyset(&waitset);
2446 sigaddset(&waitset, SIG_IPI);
2448 qemu_mutex_unlock(&qemu_global_mutex);
2449 r = sigtimedwait(&waitset, &siginfo, &ts);
2450 e = errno;
2451 qemu_mutex_lock(&qemu_global_mutex);
2453 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
2454 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
2455 exit(1);
2459 static void qemu_kvm_wait_io_event(CPUState *env)
2461 while (!cpu_has_work(env))
2462 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2464 qemu_kvm_eat_signal(env, 0);
2465 qemu_wait_io_event_common(env);
2468 static int qemu_cpu_exec(CPUState *env);
2470 static void *kvm_cpu_thread_fn(void *arg)
2472 CPUState *env = arg;
2474 qemu_thread_self(env->thread);
2475 if (kvm_enabled())
2476 kvm_init_vcpu(env);
2478 kvm_block_io_signals(env);
2480 /* signal CPU creation */
2481 qemu_mutex_lock(&qemu_global_mutex);
2482 env->created = 1;
2483 qemu_cond_signal(&qemu_cpu_cond);
2485 /* and wait for machine initialization */
2486 while (!qemu_system_ready)
2487 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2489 while (1) {
2490 if (cpu_can_run(env))
2491 qemu_cpu_exec(env);
2492 qemu_kvm_wait_io_event(env);
2495 return NULL;
2498 static bool tcg_cpu_exec(void);
2500 static void *tcg_cpu_thread_fn(void *arg)
2502 CPUState *env = arg;
2504 tcg_block_io_signals();
2505 qemu_thread_self(env->thread);
2507 /* signal CPU creation */
2508 qemu_mutex_lock(&qemu_global_mutex);
2509 for (env = first_cpu; env != NULL; env = env->next_cpu)
2510 env->created = 1;
2511 qemu_cond_signal(&qemu_cpu_cond);
2513 /* and wait for machine initialization */
2514 while (!qemu_system_ready)
2515 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2517 while (1) {
2518 tcg_cpu_exec();
2519 qemu_wait_io_event(cur_cpu);
2522 return NULL;
2525 void qemu_cpu_kick(void *_env)
2527 CPUState *env = _env;
2528 qemu_cond_broadcast(env->halt_cond);
2529 if (kvm_enabled())
2530 qemu_thread_signal(env->thread, SIG_IPI);
2533 int qemu_cpu_self(void *_env)
2535 CPUState *env = _env;
2536 QemuThread this;
2538 qemu_thread_self(&this);
2540 return qemu_thread_equal(&this, env->thread);
2543 static void cpu_signal(int sig)
2545 if (cpu_single_env)
2546 cpu_exit(cpu_single_env);
2549 static void tcg_block_io_signals(void)
2551 sigset_t set;
2552 struct sigaction sigact;
2554 sigemptyset(&set);
2555 sigaddset(&set, SIGUSR2);
2556 sigaddset(&set, SIGIO);
2557 sigaddset(&set, SIGALRM);
2558 sigaddset(&set, SIGCHLD);
2559 pthread_sigmask(SIG_BLOCK, &set, NULL);
2561 sigemptyset(&set);
2562 sigaddset(&set, SIG_IPI);
2563 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2565 memset(&sigact, 0, sizeof(sigact));
2566 sigact.sa_handler = cpu_signal;
2567 sigaction(SIG_IPI, &sigact, NULL);
2570 static void dummy_signal(int sig)
2574 static void kvm_block_io_signals(CPUState *env)
2576 int r;
2577 sigset_t set;
2578 struct sigaction sigact;
2580 sigemptyset(&set);
2581 sigaddset(&set, SIGUSR2);
2582 sigaddset(&set, SIGIO);
2583 sigaddset(&set, SIGALRM);
2584 sigaddset(&set, SIGCHLD);
2585 sigaddset(&set, SIG_IPI);
2586 pthread_sigmask(SIG_BLOCK, &set, NULL);
2588 pthread_sigmask(SIG_BLOCK, NULL, &set);
2589 sigdelset(&set, SIG_IPI);
2591 memset(&sigact, 0, sizeof(sigact));
2592 sigact.sa_handler = dummy_signal;
2593 sigaction(SIG_IPI, &sigact, NULL);
2595 r = kvm_set_signal_mask(env, &set);
2596 if (r) {
2597 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
2598 exit(1);
2602 static void unblock_io_signals(void)
2604 sigset_t set;
2606 sigemptyset(&set);
2607 sigaddset(&set, SIGUSR2);
2608 sigaddset(&set, SIGIO);
2609 sigaddset(&set, SIGALRM);
2610 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2612 sigemptyset(&set);
2613 sigaddset(&set, SIG_IPI);
2614 pthread_sigmask(SIG_BLOCK, &set, NULL);
2617 static void qemu_signal_lock(unsigned int msecs)
2619 qemu_mutex_lock(&qemu_fair_mutex);
2621 while (qemu_mutex_trylock(&qemu_global_mutex)) {
2622 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
2623 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
2624 break;
2626 qemu_mutex_unlock(&qemu_fair_mutex);
2629 void qemu_mutex_lock_iothread(void)
2631 if (kvm_enabled()) {
2632 qemu_mutex_lock(&qemu_fair_mutex);
2633 qemu_mutex_lock(&qemu_global_mutex);
2634 qemu_mutex_unlock(&qemu_fair_mutex);
2635 } else
2636 qemu_signal_lock(100);
2639 void qemu_mutex_unlock_iothread(void)
2641 qemu_mutex_unlock(&qemu_global_mutex);
2644 static int all_vcpus_paused(void)
2646 CPUState *penv = first_cpu;
2648 while (penv) {
2649 if (!penv->stopped)
2650 return 0;
2651 penv = (CPUState *)penv->next_cpu;
2654 return 1;
2657 static void pause_all_vcpus(void)
2659 CPUState *penv = first_cpu;
2661 while (penv) {
2662 penv->stop = 1;
2663 qemu_thread_signal(penv->thread, SIG_IPI);
2664 qemu_cpu_kick(penv);
2665 penv = (CPUState *)penv->next_cpu;
2668 while (!all_vcpus_paused()) {
2669 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
2670 penv = first_cpu;
2671 while (penv) {
2672 qemu_thread_signal(penv->thread, SIG_IPI);
2673 penv = (CPUState *)penv->next_cpu;
2678 static void resume_all_vcpus(void)
2680 CPUState *penv = first_cpu;
2682 while (penv) {
2683 penv->stop = 0;
2684 penv->stopped = 0;
2685 qemu_thread_signal(penv->thread, SIG_IPI);
2686 qemu_cpu_kick(penv);
2687 penv = (CPUState *)penv->next_cpu;
2691 static void tcg_init_vcpu(void *_env)
2693 CPUState *env = _env;
2694 /* share a single thread for all cpus with TCG */
2695 if (!tcg_cpu_thread) {
2696 env->thread = qemu_mallocz(sizeof(QemuThread));
2697 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2698 qemu_cond_init(env->halt_cond);
2699 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
2700 while (env->created == 0)
2701 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2702 tcg_cpu_thread = env->thread;
2703 tcg_halt_cond = env->halt_cond;
2704 } else {
2705 env->thread = tcg_cpu_thread;
2706 env->halt_cond = tcg_halt_cond;
2710 static void kvm_start_vcpu(CPUState *env)
2712 env->thread = qemu_mallocz(sizeof(QemuThread));
2713 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2714 qemu_cond_init(env->halt_cond);
2715 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
2716 while (env->created == 0)
2717 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2720 void qemu_init_vcpu(void *_env)
2722 CPUState *env = _env;
2724 env->nr_cores = smp_cores;
2725 env->nr_threads = smp_threads;
2726 if (kvm_enabled())
2727 kvm_start_vcpu(env);
2728 else
2729 tcg_init_vcpu(env);
2732 void qemu_notify_event(void)
2734 qemu_event_increment();
2737 static void qemu_system_vmstop_request(int reason)
2739 vmstop_requested = reason;
2740 qemu_notify_event();
2743 void vm_stop(int reason)
2745 QemuThread me;
2746 qemu_thread_self(&me);
2748 if (!qemu_thread_equal(&me, &io_thread)) {
2749 qemu_system_vmstop_request(reason);
2751 * FIXME: should not return to device code in case
2752 * vm_stop() has been requested.
2754 if (cpu_single_env) {
2755 cpu_exit(cpu_single_env);
2756 cpu_single_env->stop = 1;
2758 return;
2760 do_vm_stop(reason);
2763 #endif
2766 #ifdef _WIN32
2767 static void host_main_loop_wait(int *timeout)
2769 int ret, ret2, i;
2770 PollingEntry *pe;
2773 /* XXX: need to suppress polling by better using win32 events */
2774 ret = 0;
2775 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2776 ret |= pe->func(pe->opaque);
2778 if (ret == 0) {
2779 int err;
2780 WaitObjects *w = &wait_objects;
2782 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2783 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2784 if (w->func[ret - WAIT_OBJECT_0])
2785 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2787 /* Check for additional signaled events */
2788 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2790 /* Check if event is signaled */
2791 ret2 = WaitForSingleObject(w->events[i], 0);
2792 if(ret2 == WAIT_OBJECT_0) {
2793 if (w->func[i])
2794 w->func[i](w->opaque[i]);
2795 } else if (ret2 == WAIT_TIMEOUT) {
2796 } else {
2797 err = GetLastError();
2798 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2801 } else if (ret == WAIT_TIMEOUT) {
2802 } else {
2803 err = GetLastError();
2804 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2808 *timeout = 0;
2810 #else
2811 static void host_main_loop_wait(int *timeout)
2814 #endif
2816 void main_loop_wait(int nonblocking)
2818 IOHandlerRecord *ioh;
2819 fd_set rfds, wfds, xfds;
2820 int ret, nfds;
2821 struct timeval tv;
2822 int timeout;
2824 if (nonblocking)
2825 timeout = 0;
2826 else {
2827 timeout = qemu_calculate_timeout();
2828 qemu_bh_update_timeout(&timeout);
2831 host_main_loop_wait(&timeout);
2833 /* poll any events */
2834 /* XXX: separate device handlers from system ones */
2835 nfds = -1;
2836 FD_ZERO(&rfds);
2837 FD_ZERO(&wfds);
2838 FD_ZERO(&xfds);
2839 QLIST_FOREACH(ioh, &io_handlers, next) {
2840 if (ioh->deleted)
2841 continue;
2842 if (ioh->fd_read &&
2843 (!ioh->fd_read_poll ||
2844 ioh->fd_read_poll(ioh->opaque) != 0)) {
2845 FD_SET(ioh->fd, &rfds);
2846 if (ioh->fd > nfds)
2847 nfds = ioh->fd;
2849 if (ioh->fd_write) {
2850 FD_SET(ioh->fd, &wfds);
2851 if (ioh->fd > nfds)
2852 nfds = ioh->fd;
2856 tv.tv_sec = timeout / 1000;
2857 tv.tv_usec = (timeout % 1000) * 1000;
2859 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2861 qemu_mutex_unlock_iothread();
2862 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2863 qemu_mutex_lock_iothread();
2864 if (ret > 0) {
2865 IOHandlerRecord *pioh;
2867 QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
2868 if (ioh->deleted) {
2869 QLIST_REMOVE(ioh, next);
2870 qemu_free(ioh);
2871 continue;
2873 if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2874 ioh->fd_read(ioh->opaque);
2876 if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2877 ioh->fd_write(ioh->opaque);
2882 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2884 qemu_run_all_timers();
2886 /* Check bottom-halves last in case any of the earlier events triggered
2887 them. */
2888 qemu_bh_poll();
2892 static int qemu_cpu_exec(CPUState *env)
2894 int ret;
2895 #ifdef CONFIG_PROFILER
2896 int64_t ti;
2897 #endif
2899 #ifdef CONFIG_PROFILER
2900 ti = profile_getclock();
2901 #endif
2902 if (use_icount) {
2903 int64_t count;
2904 int decr;
2905 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
2906 env->icount_decr.u16.low = 0;
2907 env->icount_extra = 0;
2908 count = qemu_icount_round (qemu_next_deadline());
2909 qemu_icount += count;
2910 decr = (count > 0xffff) ? 0xffff : count;
2911 count -= decr;
2912 env->icount_decr.u16.low = decr;
2913 env->icount_extra = count;
2915 ret = cpu_exec(env);
2916 #ifdef CONFIG_PROFILER
2917 qemu_time += profile_getclock() - ti;
2918 #endif
2919 if (use_icount) {
2920 /* Fold pending instructions back into the
2921 instruction counter, and clear the interrupt flag. */
2922 qemu_icount -= (env->icount_decr.u16.low
2923 + env->icount_extra);
2924 env->icount_decr.u32 = 0;
2925 env->icount_extra = 0;
2927 return ret;
2930 static bool tcg_cpu_exec(void)
2932 int ret = 0;
2934 if (next_cpu == NULL)
2935 next_cpu = first_cpu;
2936 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
2937 CPUState *env = cur_cpu = next_cpu;
2939 qemu_clock_enable(vm_clock,
2940 (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
2942 if (qemu_alarm_pending())
2943 break;
2944 if (cpu_can_run(env))
2945 ret = qemu_cpu_exec(env);
2946 else if (env->stop)
2947 break;
2949 if (ret == EXCP_DEBUG) {
2950 gdb_set_stop_cpu(env);
2951 debug_requested = 1;
2952 break;
2955 return tcg_has_work();
2958 static int vm_can_run(void)
2960 if (powerdown_requested)
2961 return 0;
2962 if (reset_requested)
2963 return 0;
2964 if (shutdown_requested)
2965 return 0;
2966 if (debug_requested)
2967 return 0;
2968 return 1;
2971 qemu_irq qemu_system_powerdown;
2973 static void main_loop(void)
2975 int r;
2977 #ifdef CONFIG_IOTHREAD
2978 qemu_system_ready = 1;
2979 qemu_cond_broadcast(&qemu_system_cond);
2980 #endif
2982 for (;;) {
2983 do {
2984 bool nonblocking = false;
2985 #ifdef CONFIG_PROFILER
2986 int64_t ti;
2987 #endif
2988 #ifndef CONFIG_IOTHREAD
2989 nonblocking = tcg_cpu_exec();
2990 #endif
2991 #ifdef CONFIG_PROFILER
2992 ti = profile_getclock();
2993 #endif
2994 main_loop_wait(nonblocking);
2995 #ifdef CONFIG_PROFILER
2996 dev_time += profile_getclock() - ti;
2997 #endif
2998 } while (vm_can_run());
3000 if (qemu_debug_requested()) {
3001 vm_stop(EXCP_DEBUG);
3003 if (qemu_shutdown_requested()) {
3004 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
3005 if (no_shutdown) {
3006 vm_stop(0);
3007 no_shutdown = 0;
3008 } else
3009 break;
3011 if (qemu_reset_requested()) {
3012 pause_all_vcpus();
3013 qemu_system_reset();
3014 resume_all_vcpus();
3016 if (qemu_powerdown_requested()) {
3017 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
3018 qemu_irq_raise(qemu_system_powerdown);
3020 if ((r = qemu_vmstop_requested())) {
3021 vm_stop(r);
3024 pause_all_vcpus();
3027 static void version(void)
3029 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3032 static void help(int exitcode)
3034 const char *options_help =
3035 #define DEF(option, opt_arg, opt_enum, opt_help) \
3036 opt_help
3037 #define DEFHEADING(text) stringify(text) "\n"
3038 #include "qemu-options.h"
3039 #undef DEF
3040 #undef DEFHEADING
3041 #undef GEN_DOCS
3043 version();
3044 printf("usage: %s [options] [disk_image]\n"
3045 "\n"
3046 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3047 "\n"
3048 "%s\n"
3049 "During emulation, the following keys are useful:\n"
3050 "ctrl-alt-f toggle full screen\n"
3051 "ctrl-alt-n switch to virtual console 'n'\n"
3052 "ctrl-alt toggle mouse and keyboard grab\n"
3053 "\n"
3054 "When using -nographic, press 'ctrl-a h' to get some help.\n",
3055 "qemu",
3056 options_help);
3057 exit(exitcode);
3060 #define HAS_ARG 0x0001
3062 enum {
3063 #define DEF(option, opt_arg, opt_enum, opt_help) \
3064 opt_enum,
3065 #define DEFHEADING(text)
3066 #include "qemu-options.h"
3067 #undef DEF
3068 #undef DEFHEADING
3069 #undef GEN_DOCS
3072 typedef struct QEMUOption {
3073 const char *name;
3074 int flags;
3075 int index;
3076 } QEMUOption;
3078 static const QEMUOption qemu_options[] = {
3079 { "h", 0, QEMU_OPTION_h },
3080 #define DEF(option, opt_arg, opt_enum, opt_help) \
3081 { option, opt_arg, opt_enum },
3082 #define DEFHEADING(text)
3083 #include "qemu-options.h"
3084 #undef DEF
3085 #undef DEFHEADING
3086 #undef GEN_DOCS
3087 { NULL },
3090 #ifdef HAS_AUDIO
3091 struct soundhw soundhw[] = {
3092 #ifdef HAS_AUDIO_CHOICE
3093 #if defined(TARGET_I386) || defined(TARGET_MIPS)
3095 "pcspk",
3096 "PC speaker",
3099 { .init_isa = pcspk_audio_init }
3101 #endif
3103 #ifdef CONFIG_SB16
3105 "sb16",
3106 "Creative Sound Blaster 16",
3109 { .init_isa = SB16_init }
3111 #endif
3113 #ifdef CONFIG_CS4231A
3115 "cs4231a",
3116 "CS4231A",
3119 { .init_isa = cs4231a_init }
3121 #endif
3123 #ifdef CONFIG_ADLIB
3125 "adlib",
3126 #ifdef HAS_YMF262
3127 "Yamaha YMF262 (OPL3)",
3128 #else
3129 "Yamaha YM3812 (OPL2)",
3130 #endif
3133 { .init_isa = Adlib_init }
3135 #endif
3137 #ifdef CONFIG_GUS
3139 "gus",
3140 "Gravis Ultrasound GF1",
3143 { .init_isa = GUS_init }
3145 #endif
3147 #ifdef CONFIG_AC97
3149 "ac97",
3150 "Intel 82801AA AC97 Audio",
3153 { .init_pci = ac97_init }
3155 #endif
3157 #ifdef CONFIG_ES1370
3159 "es1370",
3160 "ENSONIQ AudioPCI ES1370",
3163 { .init_pci = es1370_init }
3165 #endif
3167 #endif /* HAS_AUDIO_CHOICE */
3169 { NULL, NULL, 0, 0, { NULL } }
3172 static void select_soundhw (const char *optarg)
3174 struct soundhw *c;
3176 if (*optarg == '?') {
3177 show_valid_cards:
3179 printf ("Valid sound card names (comma separated):\n");
3180 for (c = soundhw; c->name; ++c) {
3181 printf ("%-11s %s\n", c->name, c->descr);
3183 printf ("\n-soundhw all will enable all of the above\n");
3184 exit (*optarg != '?');
3186 else {
3187 size_t l;
3188 const char *p;
3189 char *e;
3190 int bad_card = 0;
3192 if (!strcmp (optarg, "all")) {
3193 for (c = soundhw; c->name; ++c) {
3194 c->enabled = 1;
3196 return;
3199 p = optarg;
3200 while (*p) {
3201 e = strchr (p, ',');
3202 l = !e ? strlen (p) : (size_t) (e - p);
3204 for (c = soundhw; c->name; ++c) {
3205 if (!strncmp (c->name, p, l) && !c->name[l]) {
3206 c->enabled = 1;
3207 break;
3211 if (!c->name) {
3212 if (l > 80) {
3213 fprintf (stderr,
3214 "Unknown sound card name (too big to show)\n");
3216 else {
3217 fprintf (stderr, "Unknown sound card name `%.*s'\n",
3218 (int) l, p);
3220 bad_card = 1;
3222 p += l + (e != NULL);
3225 if (bad_card)
3226 goto show_valid_cards;
3229 #endif
3231 static void select_vgahw (const char *p)
3233 const char *opts;
3235 default_vga = 0;
3236 vga_interface_type = VGA_NONE;
3237 if (strstart(p, "std", &opts)) {
3238 vga_interface_type = VGA_STD;
3239 } else if (strstart(p, "cirrus", &opts)) {
3240 vga_interface_type = VGA_CIRRUS;
3241 } else if (strstart(p, "vmware", &opts)) {
3242 vga_interface_type = VGA_VMWARE;
3243 } else if (strstart(p, "xenfb", &opts)) {
3244 vga_interface_type = VGA_XENFB;
3245 } else if (!strstart(p, "none", &opts)) {
3246 invalid_vga:
3247 fprintf(stderr, "Unknown vga type: %s\n", p);
3248 exit(1);
3250 while (*opts) {
3251 const char *nextopt;
3253 if (strstart(opts, ",retrace=", &nextopt)) {
3254 opts = nextopt;
3255 if (strstart(opts, "dumb", &nextopt))
3256 vga_retrace_method = VGA_RETRACE_DUMB;
3257 else if (strstart(opts, "precise", &nextopt))
3258 vga_retrace_method = VGA_RETRACE_PRECISE;
3259 else goto invalid_vga;
3260 } else goto invalid_vga;
3261 opts = nextopt;
3265 #ifdef TARGET_I386
3266 static int balloon_parse(const char *arg)
3268 QemuOpts *opts;
3270 if (strcmp(arg, "none") == 0) {
3271 return 0;
3274 if (!strncmp(arg, "virtio", 6)) {
3275 if (arg[6] == ',') {
3276 /* have params -> parse them */
3277 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
3278 if (!opts)
3279 return -1;
3280 } else {
3281 /* create empty opts */
3282 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3284 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
3285 return 0;
3288 return -1;
3290 #endif
3292 #ifdef _WIN32
3293 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
3295 exit(STATUS_CONTROL_C_EXIT);
3296 return TRUE;
3298 #endif
3300 int qemu_uuid_parse(const char *str, uint8_t *uuid)
3302 int ret;
3304 if(strlen(str) != 36)
3305 return -1;
3307 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
3308 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
3309 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
3311 if(ret != 16)
3312 return -1;
3314 #ifdef TARGET_I386
3315 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
3316 #endif
3318 return 0;
3321 #ifndef _WIN32
3323 static void termsig_handler(int signal)
3325 qemu_system_shutdown_request();
3328 static void sigchld_handler(int signal)
3330 waitpid(-1, NULL, WNOHANG);
3333 static void sighandler_setup(void)
3335 struct sigaction act;
3337 memset(&act, 0, sizeof(act));
3338 act.sa_handler = termsig_handler;
3339 sigaction(SIGINT, &act, NULL);
3340 sigaction(SIGHUP, &act, NULL);
3341 sigaction(SIGTERM, &act, NULL);
3343 act.sa_handler = sigchld_handler;
3344 act.sa_flags = SA_NOCLDSTOP;
3345 sigaction(SIGCHLD, &act, NULL);
3348 #endif
3350 #ifdef _WIN32
3351 /* Look for support files in the same directory as the executable. */
3352 static char *find_datadir(const char *argv0)
3354 char *p;
3355 char buf[MAX_PATH];
3356 DWORD len;
3358 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
3359 if (len == 0) {
3360 return NULL;
3363 buf[len] = 0;
3364 p = buf + len - 1;
3365 while (p != buf && *p != '\\')
3366 p--;
3367 *p = 0;
3368 if (access(buf, R_OK) == 0) {
3369 return qemu_strdup(buf);
3371 return NULL;
3373 #else /* !_WIN32 */
3375 /* Find a likely location for support files using the location of the binary.
3376 For installed binaries this will be "$bindir/../share/qemu". When
3377 running from the build tree this will be "$bindir/../pc-bios". */
3378 #define SHARE_SUFFIX "/share/qemu"
3379 #define BUILD_SUFFIX "/pc-bios"
3380 static char *find_datadir(const char *argv0)
3382 char *dir;
3383 char *p = NULL;
3384 char *res;
3385 char buf[PATH_MAX];
3386 size_t max_len;
3388 #if defined(__linux__)
3390 int len;
3391 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
3392 if (len > 0) {
3393 buf[len] = 0;
3394 p = buf;
3397 #elif defined(__FreeBSD__)
3399 int len;
3400 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
3401 if (len > 0) {
3402 buf[len] = 0;
3403 p = buf;
3406 #endif
3407 /* If we don't have any way of figuring out the actual executable
3408 location then try argv[0]. */
3409 if (!p) {
3410 p = realpath(argv0, buf);
3411 if (!p) {
3412 return NULL;
3415 dir = dirname(p);
3416 dir = dirname(dir);
3418 max_len = strlen(dir) +
3419 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
3420 res = qemu_mallocz(max_len);
3421 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
3422 if (access(res, R_OK)) {
3423 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
3424 if (access(res, R_OK)) {
3425 qemu_free(res);
3426 res = NULL;
3430 return res;
3432 #undef SHARE_SUFFIX
3433 #undef BUILD_SUFFIX
3434 #endif
3436 char *qemu_find_file(int type, const char *name)
3438 int len;
3439 const char *subdir;
3440 char *buf;
3442 /* If name contains path separators then try it as a straight path. */
3443 if ((strchr(name, '/') || strchr(name, '\\'))
3444 && access(name, R_OK) == 0) {
3445 return qemu_strdup(name);
3447 switch (type) {
3448 case QEMU_FILE_TYPE_BIOS:
3449 subdir = "";
3450 break;
3451 case QEMU_FILE_TYPE_KEYMAP:
3452 subdir = "keymaps/";
3453 break;
3454 default:
3455 abort();
3457 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
3458 buf = qemu_mallocz(len);
3459 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
3460 if (access(buf, R_OK)) {
3461 qemu_free(buf);
3462 return NULL;
3464 return buf;
3467 static int device_help_func(QemuOpts *opts, void *opaque)
3469 return qdev_device_help(opts);
3472 static int device_init_func(QemuOpts *opts, void *opaque)
3474 DeviceState *dev;
3476 dev = qdev_device_add(opts);
3477 if (!dev)
3478 return -1;
3479 return 0;
3482 static int chardev_init_func(QemuOpts *opts, void *opaque)
3484 CharDriverState *chr;
3486 chr = qemu_chr_open_opts(opts, NULL);
3487 if (!chr)
3488 return -1;
3489 return 0;
3492 static int mon_init_func(QemuOpts *opts, void *opaque)
3494 CharDriverState *chr;
3495 const char *chardev;
3496 const char *mode;
3497 int flags;
3499 mode = qemu_opt_get(opts, "mode");
3500 if (mode == NULL) {
3501 mode = "readline";
3503 if (strcmp(mode, "readline") == 0) {
3504 flags = MONITOR_USE_READLINE;
3505 } else if (strcmp(mode, "control") == 0) {
3506 flags = MONITOR_USE_CONTROL;
3507 } else {
3508 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
3509 exit(1);
3512 if (qemu_opt_get_bool(opts, "default", 0))
3513 flags |= MONITOR_IS_DEFAULT;
3515 chardev = qemu_opt_get(opts, "chardev");
3516 chr = qemu_chr_find(chardev);
3517 if (chr == NULL) {
3518 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
3519 exit(1);
3522 monitor_init(chr, flags);
3523 return 0;
3526 static void monitor_parse(const char *optarg, const char *mode)
3528 static int monitor_device_index = 0;
3529 QemuOpts *opts;
3530 const char *p;
3531 char label[32];
3532 int def = 0;
3534 if (strstart(optarg, "chardev:", &p)) {
3535 snprintf(label, sizeof(label), "%s", p);
3536 } else {
3537 if (monitor_device_index) {
3538 snprintf(label, sizeof(label), "monitor%d",
3539 monitor_device_index);
3540 } else {
3541 snprintf(label, sizeof(label), "monitor");
3542 def = 1;
3544 opts = qemu_chr_parse_compat(label, optarg);
3545 if (!opts) {
3546 fprintf(stderr, "parse error: %s\n", optarg);
3547 exit(1);
3551 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
3552 if (!opts) {
3553 fprintf(stderr, "duplicate chardev: %s\n", label);
3554 exit(1);
3556 qemu_opt_set(opts, "mode", mode);
3557 qemu_opt_set(opts, "chardev", label);
3558 if (def)
3559 qemu_opt_set(opts, "default", "on");
3560 monitor_device_index++;
3563 struct device_config {
3564 enum {
3565 DEV_USB, /* -usbdevice */
3566 DEV_BT, /* -bt */
3567 DEV_SERIAL, /* -serial */
3568 DEV_PARALLEL, /* -parallel */
3569 DEV_VIRTCON, /* -virtioconsole */
3570 DEV_DEBUGCON, /* -debugcon */
3571 } type;
3572 const char *cmdline;
3573 QTAILQ_ENTRY(device_config) next;
3575 QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
3577 static void add_device_config(int type, const char *cmdline)
3579 struct device_config *conf;
3581 conf = qemu_mallocz(sizeof(*conf));
3582 conf->type = type;
3583 conf->cmdline = cmdline;
3584 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
3587 static int foreach_device_config(int type, int (*func)(const char *cmdline))
3589 struct device_config *conf;
3590 int rc;
3592 QTAILQ_FOREACH(conf, &device_configs, next) {
3593 if (conf->type != type)
3594 continue;
3595 rc = func(conf->cmdline);
3596 if (0 != rc)
3597 return rc;
3599 return 0;
3602 static int serial_parse(const char *devname)
3604 static int index = 0;
3605 char label[32];
3607 if (strcmp(devname, "none") == 0)
3608 return 0;
3609 if (index == MAX_SERIAL_PORTS) {
3610 fprintf(stderr, "qemu: too many serial ports\n");
3611 exit(1);
3613 snprintf(label, sizeof(label), "serial%d", index);
3614 serial_hds[index] = qemu_chr_open(label, devname, NULL);
3615 if (!serial_hds[index]) {
3616 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
3617 devname, strerror(errno));
3618 return -1;
3620 index++;
3621 return 0;
3624 static int parallel_parse(const char *devname)
3626 static int index = 0;
3627 char label[32];
3629 if (strcmp(devname, "none") == 0)
3630 return 0;
3631 if (index == MAX_PARALLEL_PORTS) {
3632 fprintf(stderr, "qemu: too many parallel ports\n");
3633 exit(1);
3635 snprintf(label, sizeof(label), "parallel%d", index);
3636 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
3637 if (!parallel_hds[index]) {
3638 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
3639 devname, strerror(errno));
3640 return -1;
3642 index++;
3643 return 0;
3646 static int virtcon_parse(const char *devname)
3648 static int index = 0;
3649 char label[32];
3650 QemuOpts *bus_opts, *dev_opts;
3652 if (strcmp(devname, "none") == 0)
3653 return 0;
3654 if (index == MAX_VIRTIO_CONSOLES) {
3655 fprintf(stderr, "qemu: too many virtio consoles\n");
3656 exit(1);
3659 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3660 qemu_opt_set(bus_opts, "driver", "virtio-serial");
3662 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3663 qemu_opt_set(dev_opts, "driver", "virtconsole");
3665 snprintf(label, sizeof(label), "virtcon%d", index);
3666 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
3667 if (!virtcon_hds[index]) {
3668 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
3669 devname, strerror(errno));
3670 return -1;
3672 qemu_opt_set(dev_opts, "chardev", label);
3674 index++;
3675 return 0;
3678 static int debugcon_parse(const char *devname)
3680 QemuOpts *opts;
3682 if (!qemu_chr_open("debugcon", devname, NULL)) {
3683 exit(1);
3685 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
3686 if (!opts) {
3687 fprintf(stderr, "qemu: already have a debugcon device\n");
3688 exit(1);
3690 qemu_opt_set(opts, "driver", "isa-debugcon");
3691 qemu_opt_set(opts, "chardev", "debugcon");
3692 return 0;
3695 static const QEMUOption *lookup_opt(int argc, char **argv,
3696 const char **poptarg, int *poptind)
3698 const QEMUOption *popt;
3699 int optind = *poptind;
3700 char *r = argv[optind];
3701 const char *optarg;
3703 loc_set_cmdline(argv, optind, 1);
3704 optind++;
3705 /* Treat --foo the same as -foo. */
3706 if (r[1] == '-')
3707 r++;
3708 popt = qemu_options;
3709 for(;;) {
3710 if (!popt->name) {
3711 error_report("invalid option");
3712 exit(1);
3714 if (!strcmp(popt->name, r + 1))
3715 break;
3716 popt++;
3718 if (popt->flags & HAS_ARG) {
3719 if (optind >= argc) {
3720 error_report("requires an argument");
3721 exit(1);
3723 optarg = argv[optind++];
3724 loc_set_cmdline(argv, optind - 2, 2);
3725 } else {
3726 optarg = NULL;
3729 *poptarg = optarg;
3730 *poptind = optind;
3732 return popt;
3735 int main(int argc, char **argv, char **envp)
3737 const char *gdbstub_dev = NULL;
3738 uint32_t boot_devices_bitmap = 0;
3739 int i;
3740 int snapshot, linux_boot, net_boot;
3741 const char *icount_option = NULL;
3742 const char *initrd_filename;
3743 const char *kernel_filename, *kernel_cmdline;
3744 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3745 DisplayState *ds;
3746 DisplayChangeListener *dcl;
3747 int cyls, heads, secs, translation;
3748 QemuOpts *hda_opts = NULL, *opts;
3749 int optind;
3750 const char *optarg;
3751 const char *loadvm = NULL;
3752 QEMUMachine *machine;
3753 const char *cpu_model;
3754 #ifndef _WIN32
3755 int fds[2];
3756 #endif
3757 int tb_size;
3758 const char *pid_file = NULL;
3759 const char *incoming = NULL;
3760 #ifndef _WIN32
3761 int fd = 0;
3762 struct passwd *pwd = NULL;
3763 const char *chroot_dir = NULL;
3764 const char *run_as = NULL;
3765 #endif
3766 CPUState *env;
3767 int show_vnc_port = 0;
3768 int defconfig = 1;
3770 error_set_progname(argv[0]);
3772 exit_notifier_init();
3774 init_clocks();
3776 qemu_cache_utils_init(envp);
3778 QLIST_INIT (&vm_change_state_head);
3779 #ifndef _WIN32
3781 struct sigaction act;
3782 sigfillset(&act.sa_mask);
3783 act.sa_flags = 0;
3784 act.sa_handler = SIG_IGN;
3785 sigaction(SIGPIPE, &act, NULL);
3787 #else
3788 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3789 /* Note: cpu_interrupt() is currently not SMP safe, so we force
3790 QEMU to run on a single CPU */
3792 HANDLE h;
3793 DWORD mask, smask;
3794 int i;
3795 h = GetCurrentProcess();
3796 if (GetProcessAffinityMask(h, &mask, &smask)) {
3797 for(i = 0; i < 32; i++) {
3798 if (mask & (1 << i))
3799 break;
3801 if (i != 32) {
3802 mask = 1 << i;
3803 SetProcessAffinityMask(h, mask);
3807 #endif
3809 module_call_init(MODULE_INIT_MACHINE);
3810 machine = find_default_machine();
3811 cpu_model = NULL;
3812 initrd_filename = NULL;
3813 ram_size = 0;
3814 snapshot = 0;
3815 kernel_filename = NULL;
3816 kernel_cmdline = "";
3817 cyls = heads = secs = 0;
3818 translation = BIOS_ATA_TRANSLATION_AUTO;
3820 for (i = 0; i < MAX_NODES; i++) {
3821 node_mem[i] = 0;
3822 node_cpumask[i] = 0;
3825 nb_numa_nodes = 0;
3826 nb_nics = 0;
3828 tb_size = 0;
3829 autostart= 1;
3831 /* first pass of option parsing */
3832 optind = 1;
3833 while (optind < argc) {
3834 if (argv[optind][0] != '-') {
3835 /* disk image */
3836 optind++;
3837 continue;
3838 } else {
3839 const QEMUOption *popt;
3841 popt = lookup_opt(argc, argv, &optarg, &optind);
3842 switch (popt->index) {
3843 case QEMU_OPTION_nodefconfig:
3844 defconfig=0;
3845 break;
3850 if (defconfig) {
3851 const char *fname;
3852 FILE *fp;
3854 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3855 fp = fopen(fname, "r");
3856 if (fp) {
3857 if (qemu_config_parse(fp, fname) != 0) {
3858 exit(1);
3860 fclose(fp);
3863 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3864 fp = fopen(fname, "r");
3865 if (fp) {
3866 if (qemu_config_parse(fp, fname) != 0) {
3867 exit(1);
3869 fclose(fp);
3872 #if defined(cpudef_setup)
3873 cpudef_setup(); /* parse cpu definitions in target config file */
3874 #endif
3876 /* second pass of option parsing */
3877 optind = 1;
3878 for(;;) {
3879 if (optind >= argc)
3880 break;
3881 if (argv[optind][0] != '-') {
3882 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3883 } else {
3884 const QEMUOption *popt;
3886 popt = lookup_opt(argc, argv, &optarg, &optind);
3887 switch(popt->index) {
3888 case QEMU_OPTION_M:
3889 machine = find_machine(optarg);
3890 if (!machine) {
3891 QEMUMachine *m;
3892 printf("Supported machines are:\n");
3893 for(m = first_machine; m != NULL; m = m->next) {
3894 if (m->alias)
3895 printf("%-10s %s (alias of %s)\n",
3896 m->alias, m->desc, m->name);
3897 printf("%-10s %s%s\n",
3898 m->name, m->desc,
3899 m->is_default ? " (default)" : "");
3901 exit(*optarg != '?');
3903 break;
3904 case QEMU_OPTION_cpu:
3905 /* hw initialization will check this */
3906 if (*optarg == '?') {
3907 /* XXX: implement xxx_cpu_list for targets that still miss it */
3908 #if defined(cpu_list_id)
3909 cpu_list_id(stdout, &fprintf, optarg);
3910 #elif defined(cpu_list)
3911 cpu_list(stdout, &fprintf); /* deprecated */
3912 #endif
3913 exit(0);
3914 } else {
3915 cpu_model = optarg;
3917 break;
3918 case QEMU_OPTION_initrd:
3919 initrd_filename = optarg;
3920 break;
3921 case QEMU_OPTION_hda:
3922 if (cyls == 0)
3923 hda_opts = drive_add(optarg, HD_ALIAS, 0);
3924 else
3925 hda_opts = drive_add(optarg, HD_ALIAS
3926 ",cyls=%d,heads=%d,secs=%d%s",
3927 0, cyls, heads, secs,
3928 translation == BIOS_ATA_TRANSLATION_LBA ?
3929 ",trans=lba" :
3930 translation == BIOS_ATA_TRANSLATION_NONE ?
3931 ",trans=none" : "");
3932 break;
3933 case QEMU_OPTION_hdb:
3934 case QEMU_OPTION_hdc:
3935 case QEMU_OPTION_hdd:
3936 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
3937 break;
3938 case QEMU_OPTION_drive:
3939 drive_add(NULL, "%s", optarg);
3940 break;
3941 case QEMU_OPTION_set:
3942 if (qemu_set_option(optarg) != 0)
3943 exit(1);
3944 break;
3945 case QEMU_OPTION_global:
3946 if (qemu_global_option(optarg) != 0)
3947 exit(1);
3948 break;
3949 case QEMU_OPTION_mtdblock:
3950 drive_add(optarg, MTD_ALIAS);
3951 break;
3952 case QEMU_OPTION_sd:
3953 drive_add(optarg, SD_ALIAS);
3954 break;
3955 case QEMU_OPTION_pflash:
3956 drive_add(optarg, PFLASH_ALIAS);
3957 break;
3958 case QEMU_OPTION_snapshot:
3959 snapshot = 1;
3960 break;
3961 case QEMU_OPTION_hdachs:
3963 const char *p;
3964 p = optarg;
3965 cyls = strtol(p, (char **)&p, 0);
3966 if (cyls < 1 || cyls > 16383)
3967 goto chs_fail;
3968 if (*p != ',')
3969 goto chs_fail;
3970 p++;
3971 heads = strtol(p, (char **)&p, 0);
3972 if (heads < 1 || heads > 16)
3973 goto chs_fail;
3974 if (*p != ',')
3975 goto chs_fail;
3976 p++;
3977 secs = strtol(p, (char **)&p, 0);
3978 if (secs < 1 || secs > 63)
3979 goto chs_fail;
3980 if (*p == ',') {
3981 p++;
3982 if (!strcmp(p, "none"))
3983 translation = BIOS_ATA_TRANSLATION_NONE;
3984 else if (!strcmp(p, "lba"))
3985 translation = BIOS_ATA_TRANSLATION_LBA;
3986 else if (!strcmp(p, "auto"))
3987 translation = BIOS_ATA_TRANSLATION_AUTO;
3988 else
3989 goto chs_fail;
3990 } else if (*p != '\0') {
3991 chs_fail:
3992 fprintf(stderr, "qemu: invalid physical CHS format\n");
3993 exit(1);
3995 if (hda_opts != NULL) {
3996 char num[16];
3997 snprintf(num, sizeof(num), "%d", cyls);
3998 qemu_opt_set(hda_opts, "cyls", num);
3999 snprintf(num, sizeof(num), "%d", heads);
4000 qemu_opt_set(hda_opts, "heads", num);
4001 snprintf(num, sizeof(num), "%d", secs);
4002 qemu_opt_set(hda_opts, "secs", num);
4003 if (translation == BIOS_ATA_TRANSLATION_LBA)
4004 qemu_opt_set(hda_opts, "trans", "lba");
4005 if (translation == BIOS_ATA_TRANSLATION_NONE)
4006 qemu_opt_set(hda_opts, "trans", "none");
4009 break;
4010 case QEMU_OPTION_numa:
4011 if (nb_numa_nodes >= MAX_NODES) {
4012 fprintf(stderr, "qemu: too many NUMA nodes\n");
4013 exit(1);
4015 numa_add(optarg);
4016 break;
4017 case QEMU_OPTION_nographic:
4018 display_type = DT_NOGRAPHIC;
4019 break;
4020 #ifdef CONFIG_CURSES
4021 case QEMU_OPTION_curses:
4022 display_type = DT_CURSES;
4023 break;
4024 #endif
4025 case QEMU_OPTION_portrait:
4026 graphic_rotate = 1;
4027 break;
4028 case QEMU_OPTION_kernel:
4029 kernel_filename = optarg;
4030 break;
4031 case QEMU_OPTION_append:
4032 kernel_cmdline = optarg;
4033 break;
4034 case QEMU_OPTION_cdrom:
4035 drive_add(optarg, CDROM_ALIAS);
4036 break;
4037 case QEMU_OPTION_boot:
4039 static const char * const params[] = {
4040 "order", "once", "menu", NULL
4042 char buf[sizeof(boot_devices)];
4043 char *standard_boot_devices;
4044 int legacy = 0;
4046 if (!strchr(optarg, '=')) {
4047 legacy = 1;
4048 pstrcpy(buf, sizeof(buf), optarg);
4049 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4050 fprintf(stderr,
4051 "qemu: unknown boot parameter '%s' in '%s'\n",
4052 buf, optarg);
4053 exit(1);
4056 if (legacy ||
4057 get_param_value(buf, sizeof(buf), "order", optarg)) {
4058 boot_devices_bitmap = parse_bootdevices(buf);
4059 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4061 if (!legacy) {
4062 if (get_param_value(buf, sizeof(buf),
4063 "once", optarg)) {
4064 boot_devices_bitmap |= parse_bootdevices(buf);
4065 standard_boot_devices = qemu_strdup(boot_devices);
4066 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4067 qemu_register_reset(restore_boot_devices,
4068 standard_boot_devices);
4070 if (get_param_value(buf, sizeof(buf),
4071 "menu", optarg)) {
4072 if (!strcmp(buf, "on")) {
4073 boot_menu = 1;
4074 } else if (!strcmp(buf, "off")) {
4075 boot_menu = 0;
4076 } else {
4077 fprintf(stderr,
4078 "qemu: invalid option value '%s'\n",
4079 buf);
4080 exit(1);
4085 break;
4086 case QEMU_OPTION_fda:
4087 case QEMU_OPTION_fdb:
4088 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4089 break;
4090 #ifdef TARGET_I386
4091 case QEMU_OPTION_no_fd_bootchk:
4092 fd_bootchk = 0;
4093 break;
4094 #endif
4095 case QEMU_OPTION_netdev:
4096 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4097 exit(1);
4099 break;
4100 case QEMU_OPTION_net:
4101 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4102 exit(1);
4104 break;
4105 #ifdef CONFIG_SLIRP
4106 case QEMU_OPTION_tftp:
4107 legacy_tftp_prefix = optarg;
4108 break;
4109 case QEMU_OPTION_bootp:
4110 legacy_bootp_filename = optarg;
4111 break;
4112 #ifndef _WIN32
4113 case QEMU_OPTION_smb:
4114 if (net_slirp_smb(optarg) < 0)
4115 exit(1);
4116 break;
4117 #endif
4118 case QEMU_OPTION_redir:
4119 if (net_slirp_redir(optarg) < 0)
4120 exit(1);
4121 break;
4122 #endif
4123 case QEMU_OPTION_bt:
4124 add_device_config(DEV_BT, optarg);
4125 break;
4126 #ifdef HAS_AUDIO
4127 case QEMU_OPTION_audio_help:
4128 AUD_help ();
4129 exit (0);
4130 break;
4131 case QEMU_OPTION_soundhw:
4132 select_soundhw (optarg);
4133 break;
4134 #endif
4135 case QEMU_OPTION_h:
4136 help(0);
4137 break;
4138 case QEMU_OPTION_version:
4139 version();
4140 exit(0);
4141 break;
4142 case QEMU_OPTION_m: {
4143 uint64_t value;
4144 char *ptr;
4146 value = strtoul(optarg, &ptr, 10);
4147 switch (*ptr) {
4148 case 0: case 'M': case 'm':
4149 value <<= 20;
4150 break;
4151 case 'G': case 'g':
4152 value <<= 30;
4153 break;
4154 default:
4155 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4156 exit(1);
4159 /* On 32-bit hosts, QEMU is limited by virtual address space */
4160 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
4161 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4162 exit(1);
4164 if (value != (uint64_t)(ram_addr_t)value) {
4165 fprintf(stderr, "qemu: ram size too large\n");
4166 exit(1);
4168 ram_size = value;
4169 break;
4171 case QEMU_OPTION_mempath:
4172 mem_path = optarg;
4173 break;
4174 #ifdef MAP_POPULATE
4175 case QEMU_OPTION_mem_prealloc:
4176 mem_prealloc = 1;
4177 break;
4178 #endif
4179 case QEMU_OPTION_d:
4181 int mask;
4182 const CPULogItem *item;
4184 mask = cpu_str_to_log_mask(optarg);
4185 if (!mask) {
4186 printf("Log items (comma separated):\n");
4187 for(item = cpu_log_items; item->mask != 0; item++) {
4188 printf("%-10s %s\n", item->name, item->help);
4190 exit(1);
4192 cpu_set_log(mask);
4194 break;
4195 case QEMU_OPTION_s:
4196 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4197 break;
4198 case QEMU_OPTION_gdb:
4199 gdbstub_dev = optarg;
4200 break;
4201 case QEMU_OPTION_L:
4202 data_dir = optarg;
4203 break;
4204 case QEMU_OPTION_bios:
4205 bios_name = optarg;
4206 break;
4207 case QEMU_OPTION_singlestep:
4208 singlestep = 1;
4209 break;
4210 case QEMU_OPTION_S:
4211 autostart = 0;
4212 break;
4213 case QEMU_OPTION_k:
4214 keyboard_layout = optarg;
4215 break;
4216 case QEMU_OPTION_localtime:
4217 rtc_utc = 0;
4218 break;
4219 case QEMU_OPTION_vga:
4220 select_vgahw (optarg);
4221 break;
4222 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4223 case QEMU_OPTION_g:
4225 const char *p;
4226 int w, h, depth;
4227 p = optarg;
4228 w = strtol(p, (char **)&p, 10);
4229 if (w <= 0) {
4230 graphic_error:
4231 fprintf(stderr, "qemu: invalid resolution or depth\n");
4232 exit(1);
4234 if (*p != 'x')
4235 goto graphic_error;
4236 p++;
4237 h = strtol(p, (char **)&p, 10);
4238 if (h <= 0)
4239 goto graphic_error;
4240 if (*p == 'x') {
4241 p++;
4242 depth = strtol(p, (char **)&p, 10);
4243 if (depth != 8 && depth != 15 && depth != 16 &&
4244 depth != 24 && depth != 32)
4245 goto graphic_error;
4246 } else if (*p == '\0') {
4247 depth = graphic_depth;
4248 } else {
4249 goto graphic_error;
4252 graphic_width = w;
4253 graphic_height = h;
4254 graphic_depth = depth;
4256 break;
4257 #endif
4258 case QEMU_OPTION_echr:
4260 char *r;
4261 term_escape_char = strtol(optarg, &r, 0);
4262 if (r == optarg)
4263 printf("Bad argument to echr\n");
4264 break;
4266 case QEMU_OPTION_monitor:
4267 monitor_parse(optarg, "readline");
4268 default_monitor = 0;
4269 break;
4270 case QEMU_OPTION_qmp:
4271 monitor_parse(optarg, "control");
4272 default_monitor = 0;
4273 break;
4274 case QEMU_OPTION_mon:
4275 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
4276 if (!opts) {
4277 fprintf(stderr, "parse error: %s\n", optarg);
4278 exit(1);
4280 default_monitor = 0;
4281 break;
4282 case QEMU_OPTION_chardev:
4283 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
4284 if (!opts) {
4285 fprintf(stderr, "parse error: %s\n", optarg);
4286 exit(1);
4288 break;
4289 case QEMU_OPTION_serial:
4290 add_device_config(DEV_SERIAL, optarg);
4291 default_serial = 0;
4292 if (strncmp(optarg, "mon:", 4) == 0) {
4293 default_monitor = 0;
4295 break;
4296 case QEMU_OPTION_watchdog:
4297 if (watchdog) {
4298 fprintf(stderr,
4299 "qemu: only one watchdog option may be given\n");
4300 return 1;
4302 watchdog = optarg;
4303 break;
4304 case QEMU_OPTION_watchdog_action:
4305 if (select_watchdog_action(optarg) == -1) {
4306 fprintf(stderr, "Unknown -watchdog-action parameter\n");
4307 exit(1);
4309 break;
4310 case QEMU_OPTION_virtiocon:
4311 add_device_config(DEV_VIRTCON, optarg);
4312 default_virtcon = 0;
4313 if (strncmp(optarg, "mon:", 4) == 0) {
4314 default_monitor = 0;
4316 break;
4317 case QEMU_OPTION_parallel:
4318 add_device_config(DEV_PARALLEL, optarg);
4319 default_parallel = 0;
4320 if (strncmp(optarg, "mon:", 4) == 0) {
4321 default_monitor = 0;
4323 break;
4324 case QEMU_OPTION_debugcon:
4325 add_device_config(DEV_DEBUGCON, optarg);
4326 break;
4327 case QEMU_OPTION_loadvm:
4328 loadvm = optarg;
4329 break;
4330 case QEMU_OPTION_full_screen:
4331 full_screen = 1;
4332 break;
4333 #ifdef CONFIG_SDL
4334 case QEMU_OPTION_no_frame:
4335 no_frame = 1;
4336 break;
4337 case QEMU_OPTION_alt_grab:
4338 alt_grab = 1;
4339 break;
4340 case QEMU_OPTION_ctrl_grab:
4341 ctrl_grab = 1;
4342 break;
4343 case QEMU_OPTION_no_quit:
4344 no_quit = 1;
4345 break;
4346 case QEMU_OPTION_sdl:
4347 display_type = DT_SDL;
4348 break;
4349 #endif
4350 case QEMU_OPTION_pidfile:
4351 pid_file = optarg;
4352 break;
4353 #ifdef TARGET_I386
4354 case QEMU_OPTION_win2k_hack:
4355 win2k_install_hack = 1;
4356 break;
4357 case QEMU_OPTION_rtc_td_hack:
4358 rtc_td_hack = 1;
4359 break;
4360 case QEMU_OPTION_acpitable:
4361 if(acpi_table_add(optarg) < 0) {
4362 fprintf(stderr, "Wrong acpi table provided\n");
4363 exit(1);
4365 break;
4366 case QEMU_OPTION_smbios:
4367 if(smbios_entry_add(optarg) < 0) {
4368 fprintf(stderr, "Wrong smbios provided\n");
4369 exit(1);
4371 break;
4372 #endif
4373 #ifdef CONFIG_KVM
4374 case QEMU_OPTION_enable_kvm:
4375 kvm_allowed = 1;
4376 break;
4377 #endif
4378 case QEMU_OPTION_usb:
4379 usb_enabled = 1;
4380 break;
4381 case QEMU_OPTION_usbdevice:
4382 usb_enabled = 1;
4383 add_device_config(DEV_USB, optarg);
4384 break;
4385 case QEMU_OPTION_device:
4386 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
4387 exit(1);
4389 break;
4390 case QEMU_OPTION_smp:
4391 smp_parse(optarg);
4392 if (smp_cpus < 1) {
4393 fprintf(stderr, "Invalid number of CPUs\n");
4394 exit(1);
4396 if (max_cpus < smp_cpus) {
4397 fprintf(stderr, "maxcpus must be equal to or greater than "
4398 "smp\n");
4399 exit(1);
4401 if (max_cpus > 255) {
4402 fprintf(stderr, "Unsupported number of maxcpus\n");
4403 exit(1);
4405 break;
4406 case QEMU_OPTION_vnc:
4407 display_type = DT_VNC;
4408 vnc_display = optarg;
4409 break;
4410 #ifdef TARGET_I386
4411 case QEMU_OPTION_no_acpi:
4412 acpi_enabled = 0;
4413 break;
4414 case QEMU_OPTION_no_hpet:
4415 no_hpet = 1;
4416 break;
4417 case QEMU_OPTION_balloon:
4418 if (balloon_parse(optarg) < 0) {
4419 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
4420 exit(1);
4422 break;
4423 #endif
4424 case QEMU_OPTION_no_reboot:
4425 no_reboot = 1;
4426 break;
4427 case QEMU_OPTION_no_shutdown:
4428 no_shutdown = 1;
4429 break;
4430 case QEMU_OPTION_show_cursor:
4431 cursor_hide = 0;
4432 break;
4433 case QEMU_OPTION_uuid:
4434 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4435 fprintf(stderr, "Fail to parse UUID string."
4436 " Wrong format.\n");
4437 exit(1);
4439 break;
4440 #ifndef _WIN32
4441 case QEMU_OPTION_daemonize:
4442 daemonize = 1;
4443 break;
4444 #endif
4445 case QEMU_OPTION_option_rom:
4446 if (nb_option_roms >= MAX_OPTION_ROMS) {
4447 fprintf(stderr, "Too many option ROMs\n");
4448 exit(1);
4450 option_rom[nb_option_roms] = optarg;
4451 nb_option_roms++;
4452 break;
4453 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4454 case QEMU_OPTION_semihosting:
4455 semihosting_enabled = 1;
4456 break;
4457 #endif
4458 case QEMU_OPTION_name:
4459 qemu_name = qemu_strdup(optarg);
4461 char *p = strchr(qemu_name, ',');
4462 if (p != NULL) {
4463 *p++ = 0;
4464 if (strncmp(p, "process=", 8)) {
4465 fprintf(stderr, "Unknown subargument %s to -name", p);
4466 exit(1);
4468 p += 8;
4469 set_proc_name(p);
4472 break;
4473 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4474 case QEMU_OPTION_prom_env:
4475 if (nb_prom_envs >= MAX_PROM_ENVS) {
4476 fprintf(stderr, "Too many prom variables\n");
4477 exit(1);
4479 prom_envs[nb_prom_envs] = optarg;
4480 nb_prom_envs++;
4481 break;
4482 #endif
4483 #ifdef TARGET_ARM
4484 case QEMU_OPTION_old_param:
4485 old_param = 1;
4486 break;
4487 #endif
4488 case QEMU_OPTION_clock:
4489 configure_alarms(optarg);
4490 break;
4491 case QEMU_OPTION_startdate:
4492 configure_rtc_date_offset(optarg, 1);
4493 break;
4494 case QEMU_OPTION_rtc:
4495 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
4496 if (!opts) {
4497 fprintf(stderr, "parse error: %s\n", optarg);
4498 exit(1);
4500 configure_rtc(opts);
4501 break;
4502 case QEMU_OPTION_tb_size:
4503 tb_size = strtol(optarg, NULL, 0);
4504 if (tb_size < 0)
4505 tb_size = 0;
4506 break;
4507 case QEMU_OPTION_icount:
4508 icount_option = optarg;
4509 break;
4510 case QEMU_OPTION_incoming:
4511 incoming = optarg;
4512 break;
4513 case QEMU_OPTION_nodefaults:
4514 default_serial = 0;
4515 default_parallel = 0;
4516 default_virtcon = 0;
4517 default_monitor = 0;
4518 default_vga = 0;
4519 default_net = 0;
4520 default_floppy = 0;
4521 default_cdrom = 0;
4522 default_sdcard = 0;
4523 break;
4524 #ifndef _WIN32
4525 case QEMU_OPTION_chroot:
4526 chroot_dir = optarg;
4527 break;
4528 case QEMU_OPTION_runas:
4529 run_as = optarg;
4530 break;
4531 #endif
4532 #ifdef CONFIG_XEN
4533 case QEMU_OPTION_xen_domid:
4534 xen_domid = atoi(optarg);
4535 break;
4536 case QEMU_OPTION_xen_create:
4537 xen_mode = XEN_CREATE;
4538 break;
4539 case QEMU_OPTION_xen_attach:
4540 xen_mode = XEN_ATTACH;
4541 break;
4542 #endif
4543 case QEMU_OPTION_readconfig:
4545 FILE *fp;
4546 fp = fopen(optarg, "r");
4547 if (fp == NULL) {
4548 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4549 exit(1);
4551 if (qemu_config_parse(fp, optarg) != 0) {
4552 exit(1);
4554 fclose(fp);
4555 break;
4557 case QEMU_OPTION_writeconfig:
4559 FILE *fp;
4560 if (strcmp(optarg, "-") == 0) {
4561 fp = stdout;
4562 } else {
4563 fp = fopen(optarg, "w");
4564 if (fp == NULL) {
4565 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4566 exit(1);
4569 qemu_config_write(fp);
4570 fclose(fp);
4571 break;
4576 loc_set_none();
4578 /* If no data_dir is specified then try to find it relative to the
4579 executable path. */
4580 if (!data_dir) {
4581 data_dir = find_datadir(argv[0]);
4583 /* If all else fails use the install patch specified when building. */
4584 if (!data_dir) {
4585 data_dir = CONFIG_QEMU_SHAREDIR;
4589 * Default to max_cpus = smp_cpus, in case the user doesn't
4590 * specify a max_cpus value.
4592 if (!max_cpus)
4593 max_cpus = smp_cpus;
4595 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4596 if (smp_cpus > machine->max_cpus) {
4597 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4598 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
4599 machine->max_cpus);
4600 exit(1);
4603 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
4604 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
4606 if (machine->no_serial) {
4607 default_serial = 0;
4609 if (machine->no_parallel) {
4610 default_parallel = 0;
4612 if (!machine->use_virtcon) {
4613 default_virtcon = 0;
4615 if (machine->no_vga) {
4616 default_vga = 0;
4618 if (machine->no_floppy) {
4619 default_floppy = 0;
4621 if (machine->no_cdrom) {
4622 default_cdrom = 0;
4624 if (machine->no_sdcard) {
4625 default_sdcard = 0;
4628 if (display_type == DT_NOGRAPHIC) {
4629 if (default_parallel)
4630 add_device_config(DEV_PARALLEL, "null");
4631 if (default_serial && default_monitor) {
4632 add_device_config(DEV_SERIAL, "mon:stdio");
4633 } else if (default_virtcon && default_monitor) {
4634 add_device_config(DEV_VIRTCON, "mon:stdio");
4635 } else {
4636 if (default_serial)
4637 add_device_config(DEV_SERIAL, "stdio");
4638 if (default_virtcon)
4639 add_device_config(DEV_VIRTCON, "stdio");
4640 if (default_monitor)
4641 monitor_parse("stdio", "readline");
4643 } else {
4644 if (default_serial)
4645 add_device_config(DEV_SERIAL, "vc:80Cx24C");
4646 if (default_parallel)
4647 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4648 if (default_monitor)
4649 monitor_parse("vc:80Cx24C", "readline");
4650 if (default_virtcon)
4651 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4653 if (default_vga)
4654 vga_interface_type = VGA_CIRRUS;
4656 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
4657 exit(1);
4659 #ifndef _WIN32
4660 if (daemonize) {
4661 pid_t pid;
4663 if (pipe(fds) == -1)
4664 exit(1);
4666 pid = fork();
4667 if (pid > 0) {
4668 uint8_t status;
4669 ssize_t len;
4671 close(fds[1]);
4673 again:
4674 len = read(fds[0], &status, 1);
4675 if (len == -1 && (errno == EINTR))
4676 goto again;
4678 if (len != 1)
4679 exit(1);
4680 else if (status == 1) {
4681 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
4682 exit(1);
4683 } else
4684 exit(0);
4685 } else if (pid < 0)
4686 exit(1);
4688 close(fds[0]);
4689 qemu_set_cloexec(fds[1]);
4691 setsid();
4693 pid = fork();
4694 if (pid > 0)
4695 exit(0);
4696 else if (pid < 0)
4697 exit(1);
4699 umask(027);
4701 signal(SIGTSTP, SIG_IGN);
4702 signal(SIGTTOU, SIG_IGN);
4703 signal(SIGTTIN, SIG_IGN);
4705 #endif
4707 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4708 #ifndef _WIN32
4709 if (daemonize) {
4710 uint8_t status = 1;
4711 if (write(fds[1], &status, 1) != 1) {
4712 perror("daemonize. Writing to pipe\n");
4714 } else
4715 #endif
4716 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
4717 exit(1);
4720 if (kvm_enabled()) {
4721 int ret;
4723 ret = kvm_init(smp_cpus);
4724 if (ret < 0) {
4725 fprintf(stderr, "failed to initialize KVM\n");
4726 exit(1);
4730 if (qemu_init_main_loop()) {
4731 fprintf(stderr, "qemu_init_main_loop failed\n");
4732 exit(1);
4734 linux_boot = (kernel_filename != NULL);
4736 if (!linux_boot && *kernel_cmdline != '\0') {
4737 fprintf(stderr, "-append only allowed with -kernel option\n");
4738 exit(1);
4741 if (!linux_boot && initrd_filename != NULL) {
4742 fprintf(stderr, "-initrd only allowed with -kernel option\n");
4743 exit(1);
4746 #ifndef _WIN32
4747 /* Win32 doesn't support line-buffering and requires size >= 2 */
4748 setvbuf(stdout, NULL, _IOLBF, 0);
4749 #endif
4751 if (init_timer_alarm() < 0) {
4752 fprintf(stderr, "could not initialize alarm timer\n");
4753 exit(1);
4755 configure_icount(icount_option);
4757 #ifdef _WIN32
4758 socket_init();
4759 #endif
4761 if (net_init_clients() < 0) {
4762 exit(1);
4765 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4766 net_set_boot_mask(net_boot);
4768 /* init the bluetooth world */
4769 if (foreach_device_config(DEV_BT, bt_parse))
4770 exit(1);
4772 /* init the memory */
4773 if (ram_size == 0)
4774 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4776 /* init the dynamic translator */
4777 cpu_exec_init_all(tb_size * 1024 * 1024);
4779 bdrv_init_with_whitelist();
4781 blk_mig_init();
4783 if (default_cdrom) {
4784 /* we always create the cdrom drive, even if no disk is there */
4785 drive_add(NULL, CDROM_ALIAS);
4788 if (default_floppy) {
4789 /* we always create at least one floppy */
4790 drive_add(NULL, FD_ALIAS, 0);
4793 if (default_sdcard) {
4794 /* we always create one sd slot, even if no card is in it */
4795 drive_add(NULL, SD_ALIAS);
4798 /* open the virtual block devices */
4799 if (snapshot)
4800 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4801 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4802 exit(1);
4804 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
4805 ram_load, NULL);
4807 if (nb_numa_nodes > 0) {
4808 int i;
4810 if (nb_numa_nodes > smp_cpus) {
4811 nb_numa_nodes = smp_cpus;
4814 /* If no memory size if given for any node, assume the default case
4815 * and distribute the available memory equally across all nodes
4817 for (i = 0; i < nb_numa_nodes; i++) {
4818 if (node_mem[i] != 0)
4819 break;
4821 if (i == nb_numa_nodes) {
4822 uint64_t usedmem = 0;
4824 /* On Linux, the each node's border has to be 8MB aligned,
4825 * the final node gets the rest.
4827 for (i = 0; i < nb_numa_nodes - 1; i++) {
4828 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4829 usedmem += node_mem[i];
4831 node_mem[i] = ram_size - usedmem;
4834 for (i = 0; i < nb_numa_nodes; i++) {
4835 if (node_cpumask[i] != 0)
4836 break;
4838 /* assigning the VCPUs round-robin is easier to implement, guest OSes
4839 * must cope with this anyway, because there are BIOSes out there in
4840 * real machines which also use this scheme.
4842 if (i == nb_numa_nodes) {
4843 for (i = 0; i < smp_cpus; i++) {
4844 node_cpumask[i % nb_numa_nodes] |= 1 << i;
4849 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4850 exit(1);
4851 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4852 exit(1);
4853 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4854 exit(1);
4855 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4856 exit(1);
4858 module_call_init(MODULE_INIT_DEVICE);
4860 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
4861 exit(0);
4863 if (watchdog) {
4864 i = select_watchdog(watchdog);
4865 if (i > 0)
4866 exit (i == 1 ? 1 : 0);
4869 if (machine->compat_props) {
4870 qdev_prop_register_global_list(machine->compat_props);
4872 qemu_add_globals();
4874 machine->init(ram_size, boot_devices,
4875 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
4877 cpu_synchronize_all_post_init();
4879 #ifndef _WIN32
4880 /* must be after terminal init, SDL library changes signal handlers */
4881 sighandler_setup();
4882 #endif
4884 for (env = first_cpu; env != NULL; env = env->next_cpu) {
4885 for (i = 0; i < nb_numa_nodes; i++) {
4886 if (node_cpumask[i] & (1 << env->cpu_index)) {
4887 env->numa_node = i;
4892 current_machine = machine;
4894 /* init USB devices */
4895 if (usb_enabled) {
4896 if (foreach_device_config(DEV_USB, usb_parse) < 0)
4897 exit(1);
4900 /* init generic devices */
4901 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
4902 exit(1);
4904 net_check_clients();
4906 /* just use the first displaystate for the moment */
4907 ds = get_displaystate();
4909 if (display_type == DT_DEFAULT) {
4910 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4911 display_type = DT_SDL;
4912 #else
4913 display_type = DT_VNC;
4914 vnc_display = "localhost:0,to=99";
4915 show_vnc_port = 1;
4916 #endif
4920 switch (display_type) {
4921 case DT_NOGRAPHIC:
4922 break;
4923 #if defined(CONFIG_CURSES)
4924 case DT_CURSES:
4925 curses_display_init(ds, full_screen);
4926 break;
4927 #endif
4928 #if defined(CONFIG_SDL)
4929 case DT_SDL:
4930 sdl_display_init(ds, full_screen, no_frame);
4931 break;
4932 #elif defined(CONFIG_COCOA)
4933 case DT_SDL:
4934 cocoa_display_init(ds, full_screen);
4935 break;
4936 #endif
4937 case DT_VNC:
4938 vnc_display_init(ds);
4939 if (vnc_display_open(ds, vnc_display) < 0)
4940 exit(1);
4942 if (show_vnc_port) {
4943 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
4945 break;
4946 default:
4947 break;
4949 dpy_resize(ds);
4951 dcl = ds->listeners;
4952 while (dcl != NULL) {
4953 if (dcl->dpy_refresh != NULL) {
4954 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
4955 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
4957 dcl = dcl->next;
4960 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
4961 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
4962 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
4965 text_consoles_set_display(ds);
4967 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
4968 exit(1);
4970 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
4971 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
4972 gdbstub_dev);
4973 exit(1);
4976 qdev_machine_creation_done();
4978 if (rom_load_all() != 0) {
4979 fprintf(stderr, "rom loading failed\n");
4980 exit(1);
4983 qemu_system_reset();
4984 if (loadvm) {
4985 if (load_vmstate(loadvm) < 0) {
4986 autostart = 0;
4990 if (incoming) {
4991 qemu_start_incoming_migration(incoming);
4992 } else if (autostart) {
4993 vm_start();
4996 #ifndef _WIN32
4997 if (daemonize) {
4998 uint8_t status = 0;
4999 ssize_t len;
5001 again1:
5002 len = write(fds[1], &status, 1);
5003 if (len == -1 && (errno == EINTR))
5004 goto again1;
5006 if (len != 1)
5007 exit(1);
5009 if (chdir("/")) {
5010 perror("not able to chdir to /");
5011 exit(1);
5013 TFR(fd = qemu_open("/dev/null", O_RDWR));
5014 if (fd == -1)
5015 exit(1);
5018 if (run_as) {
5019 pwd = getpwnam(run_as);
5020 if (!pwd) {
5021 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5022 exit(1);
5026 if (chroot_dir) {
5027 if (chroot(chroot_dir) < 0) {
5028 fprintf(stderr, "chroot failed\n");
5029 exit(1);
5031 if (chdir("/")) {
5032 perror("not able to chdir to /");
5033 exit(1);
5037 if (run_as) {
5038 if (setgid(pwd->pw_gid) < 0) {
5039 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5040 exit(1);
5042 if (setuid(pwd->pw_uid) < 0) {
5043 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5044 exit(1);
5046 if (setuid(0) != -1) {
5047 fprintf(stderr, "Dropping privileges failed\n");
5048 exit(1);
5052 if (daemonize) {
5053 dup2(fd, 0);
5054 dup2(fd, 1);
5055 dup2(fd, 2);
5057 close(fd);
5059 #endif
5061 main_loop();
5062 quit_timers();
5063 net_cleanup();
5065 return 0;