Add m68k_cpu_list()
[qemu/mini2440.git] / vl.c
blob846d798a4244d351a554c0a788c640c814a772a6
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 HOST_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <pwd.h>
37 #include <sys/times.h>
38 #include <sys/wait.h>
39 #include <termios.h>
40 #include <sys/mman.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <net/if.h>
46 #if defined(__NetBSD__)
47 #include <net/if_tap.h>
48 #endif
49 #ifdef __linux__
50 #include <linux/if_tun.h>
51 #endif
52 #include <arpa/inet.h>
53 #include <dirent.h>
54 #include <netdb.h>
55 #include <sys/select.h>
56 #ifdef HOST_BSD
57 #include <sys/stat.h>
58 #if defined(__FreeBSD__) || defined(__DragonFly__)
59 #include <libutil.h>
60 #else
61 #include <util.h>
62 #endif
63 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
64 #include <freebsd/stdlib.h>
65 #else
66 #ifdef __linux__
67 #include <pty.h>
68 #include <malloc.h>
69 #include <linux/rtc.h>
71 /* For the benefit of older linux systems which don't supply it,
72 we use a local copy of hpet.h. */
73 /* #include <linux/hpet.h> */
74 #include "hpet.h"
76 #include <linux/ppdev.h>
77 #include <linux/parport.h>
78 #endif
79 #ifdef __sun__
80 #include <sys/stat.h>
81 #include <sys/ethernet.h>
82 #include <sys/sockio.h>
83 #include <netinet/arp.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #include <netinet/ip_icmp.h> // must come after ip.h
88 #include <netinet/udp.h>
89 #include <netinet/tcp.h>
90 #include <net/if.h>
91 #include <syslog.h>
92 #include <stropts.h>
93 #endif
94 #endif
95 #endif
97 #if defined(__OpenBSD__)
98 #include <util.h>
99 #endif
101 #if defined(CONFIG_VDE)
102 #include <libvdeplug.h>
103 #endif
105 #ifdef _WIN32
106 #include <windows.h>
107 #include <malloc.h>
108 #include <sys/timeb.h>
109 #include <mmsystem.h>
110 #define getopt_long_only getopt_long
111 #define memalign(align, size) malloc(size)
112 #endif
114 #ifdef CONFIG_SDL
115 #ifdef __APPLE__
116 #include <SDL/SDL.h>
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 qemu_main(argc, argv, NULL);
122 #undef main
123 #define main qemu_main
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "hw/hw.h"
133 #include "hw/boards.h"
134 #include "hw/usb.h"
135 #include "hw/pcmcia.h"
136 #include "hw/pc.h"
137 #include "hw/audiodev.h"
138 #include "hw/isa.h"
139 #include "hw/baum.h"
140 #include "hw/bt.h"
141 #include "hw/watchdog.h"
142 #include "hw/smbios.h"
143 #include "hw/xen.h"
144 #include "bt-host.h"
145 #include "net.h"
146 #include "monitor.h"
147 #include "console.h"
148 #include "sysemu.h"
149 #include "gdbstub.h"
150 #include "qemu-timer.h"
151 #include "qemu-char.h"
152 #include "cache-utils.h"
153 #include "block.h"
154 #include "dma.h"
155 #include "audio/audio.h"
156 #include "migration.h"
157 #include "kvm.h"
158 #include "balloon.h"
160 #include "disas.h"
162 #include "exec-all.h"
164 #include "qemu_socket.h"
166 #if defined(CONFIG_SLIRP)
167 #include "libslirp.h"
168 #endif
170 //#define DEBUG_UNUSED_IOPORT
171 //#define DEBUG_IOPORT
172 //#define DEBUG_NET
173 //#define DEBUG_SLIRP
176 #ifdef DEBUG_IOPORT
177 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
178 #else
179 # define LOG_IOPORT(...) do { } while (0)
180 #endif
182 #define DEFAULT_RAM_SIZE 128
184 /* Max number of USB devices that can be specified on the commandline. */
185 #define MAX_USB_CMDLINE 8
187 /* Max number of bluetooth switches on the commandline. */
188 #define MAX_BT_CMDLINE 10
190 /* XXX: use a two level table to limit memory usage */
191 #define MAX_IOPORTS 65536
193 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
194 const char *bios_name = NULL;
195 static void *ioport_opaque[MAX_IOPORTS];
196 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
197 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
198 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
199 to store the VM snapshots */
200 DriveInfo drives_table[MAX_DRIVES+1];
201 int nb_drives;
202 static int vga_ram_size;
203 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
204 static DisplayState *display_state;
205 int nographic;
206 static int curses;
207 static int sdl;
208 const char* keyboard_layout = NULL;
209 int64_t ticks_per_sec;
210 ram_addr_t ram_size;
211 int nb_nics;
212 NICInfo nd_table[MAX_NICS];
213 int vm_running;
214 static int autostart;
215 static int rtc_utc = 1;
216 static int rtc_date_offset = -1; /* -1 means no change */
217 int cirrus_vga_enabled = 1;
218 int std_vga_enabled = 0;
219 int vmsvga_enabled = 0;
220 int xenfb_enabled = 0;
221 #ifdef TARGET_SPARC
222 int graphic_width = 1024;
223 int graphic_height = 768;
224 int graphic_depth = 8;
225 #else
226 int graphic_width = 800;
227 int graphic_height = 600;
228 int graphic_depth = 15;
229 #endif
230 static int full_screen = 0;
231 #ifdef CONFIG_SDL
232 static int no_frame = 0;
233 #endif
234 int no_quit = 0;
235 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
236 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
237 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
238 #ifdef TARGET_I386
239 int win2k_install_hack = 0;
240 int rtc_td_hack = 0;
241 #endif
242 int usb_enabled = 0;
243 int singlestep = 0;
244 int smp_cpus = 1;
245 const char *vnc_display;
246 int acpi_enabled = 1;
247 int no_hpet = 0;
248 int fd_bootchk = 1;
249 int no_reboot = 0;
250 int no_shutdown = 0;
251 int cursor_hide = 1;
252 int graphic_rotate = 0;
253 #ifndef _WIN32
254 int daemonize = 0;
255 #endif
256 WatchdogTimerModel *watchdog = NULL;
257 int watchdog_action = WDT_RESET;
258 const char *option_rom[MAX_OPTION_ROMS];
259 int nb_option_roms;
260 int semihosting_enabled = 0;
261 #ifdef TARGET_ARM
262 int old_param = 0;
263 #endif
264 const char *qemu_name;
265 int alt_grab = 0;
266 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
267 unsigned int nb_prom_envs = 0;
268 const char *prom_envs[MAX_PROM_ENVS];
269 #endif
270 int nb_drives_opt;
271 struct drive_opt drives_opt[MAX_DRIVES];
273 int nb_numa_nodes;
274 uint64_t node_mem[MAX_NODES];
275 uint64_t node_cpumask[MAX_NODES];
277 static CPUState *cur_cpu;
278 static CPUState *next_cpu;
279 static int timer_alarm_pending = 1;
280 /* Conversion factor from emulated instructions to virtual clock ticks. */
281 static int icount_time_shift;
282 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
283 #define MAX_ICOUNT_SHIFT 10
284 /* Compensate for varying guest execution speed. */
285 static int64_t qemu_icount_bias;
286 static QEMUTimer *icount_rt_timer;
287 static QEMUTimer *icount_vm_timer;
288 static QEMUTimer *nographic_timer;
290 uint8_t qemu_uuid[16];
292 /***********************************************************/
293 /* x86 ISA bus support */
295 target_phys_addr_t isa_mem_base = 0;
296 PicState2 *isa_pic;
298 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
299 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
301 static uint32_t ioport_read(int index, uint32_t address)
303 static IOPortReadFunc *default_func[3] = {
304 default_ioport_readb,
305 default_ioport_readw,
306 default_ioport_readl
308 IOPortReadFunc *func = ioport_read_table[index][address];
309 if (!func)
310 func = default_func[index];
311 return func(ioport_opaque[address], address);
314 static void ioport_write(int index, uint32_t address, uint32_t data)
316 static IOPortWriteFunc *default_func[3] = {
317 default_ioport_writeb,
318 default_ioport_writew,
319 default_ioport_writel
321 IOPortWriteFunc *func = ioport_write_table[index][address];
322 if (!func)
323 func = default_func[index];
324 func(ioport_opaque[address], address, data);
327 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
329 #ifdef DEBUG_UNUSED_IOPORT
330 fprintf(stderr, "unused inb: port=0x%04x\n", address);
331 #endif
332 return 0xff;
335 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
337 #ifdef DEBUG_UNUSED_IOPORT
338 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
339 #endif
342 /* default is to make two byte accesses */
343 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
345 uint32_t data;
346 data = ioport_read(0, address);
347 address = (address + 1) & (MAX_IOPORTS - 1);
348 data |= ioport_read(0, address) << 8;
349 return data;
352 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
354 ioport_write(0, address, data & 0xff);
355 address = (address + 1) & (MAX_IOPORTS - 1);
356 ioport_write(0, address, (data >> 8) & 0xff);
359 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
361 #ifdef DEBUG_UNUSED_IOPORT
362 fprintf(stderr, "unused inl: port=0x%04x\n", address);
363 #endif
364 return 0xffffffff;
367 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
369 #ifdef DEBUG_UNUSED_IOPORT
370 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
371 #endif
374 /* size is the word size in byte */
375 int register_ioport_read(int start, int length, int size,
376 IOPortReadFunc *func, void *opaque)
378 int i, bsize;
380 if (size == 1) {
381 bsize = 0;
382 } else if (size == 2) {
383 bsize = 1;
384 } else if (size == 4) {
385 bsize = 2;
386 } else {
387 hw_error("register_ioport_read: invalid size");
388 return -1;
390 for(i = start; i < start + length; i += size) {
391 ioport_read_table[bsize][i] = func;
392 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
393 hw_error("register_ioport_read: invalid opaque");
394 ioport_opaque[i] = opaque;
396 return 0;
399 /* size is the word size in byte */
400 int register_ioport_write(int start, int length, int size,
401 IOPortWriteFunc *func, void *opaque)
403 int i, bsize;
405 if (size == 1) {
406 bsize = 0;
407 } else if (size == 2) {
408 bsize = 1;
409 } else if (size == 4) {
410 bsize = 2;
411 } else {
412 hw_error("register_ioport_write: invalid size");
413 return -1;
415 for(i = start; i < start + length; i += size) {
416 ioport_write_table[bsize][i] = func;
417 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
418 hw_error("register_ioport_write: invalid opaque");
419 ioport_opaque[i] = opaque;
421 return 0;
424 void isa_unassign_ioport(int start, int length)
426 int i;
428 for(i = start; i < start + length; i++) {
429 ioport_read_table[0][i] = default_ioport_readb;
430 ioport_read_table[1][i] = default_ioport_readw;
431 ioport_read_table[2][i] = default_ioport_readl;
433 ioport_write_table[0][i] = default_ioport_writeb;
434 ioport_write_table[1][i] = default_ioport_writew;
435 ioport_write_table[2][i] = default_ioport_writel;
437 ioport_opaque[i] = NULL;
441 /***********************************************************/
443 void cpu_outb(CPUState *env, int addr, int val)
445 LOG_IOPORT("outb: %04x %02x\n", addr, val);
446 ioport_write(0, addr, val);
447 #ifdef CONFIG_KQEMU
448 if (env)
449 env->last_io_time = cpu_get_time_fast();
450 #endif
453 void cpu_outw(CPUState *env, int addr, int val)
455 LOG_IOPORT("outw: %04x %04x\n", addr, val);
456 ioport_write(1, addr, val);
457 #ifdef CONFIG_KQEMU
458 if (env)
459 env->last_io_time = cpu_get_time_fast();
460 #endif
463 void cpu_outl(CPUState *env, int addr, int val)
465 LOG_IOPORT("outl: %04x %08x\n", addr, val);
466 ioport_write(2, addr, val);
467 #ifdef CONFIG_KQEMU
468 if (env)
469 env->last_io_time = cpu_get_time_fast();
470 #endif
473 int cpu_inb(CPUState *env, int addr)
475 int val;
476 val = ioport_read(0, addr);
477 LOG_IOPORT("inb : %04x %02x\n", addr, val);
478 #ifdef CONFIG_KQEMU
479 if (env)
480 env->last_io_time = cpu_get_time_fast();
481 #endif
482 return val;
485 int cpu_inw(CPUState *env, int addr)
487 int val;
488 val = ioport_read(1, addr);
489 LOG_IOPORT("inw : %04x %04x\n", addr, val);
490 #ifdef CONFIG_KQEMU
491 if (env)
492 env->last_io_time = cpu_get_time_fast();
493 #endif
494 return val;
497 int cpu_inl(CPUState *env, int addr)
499 int val;
500 val = ioport_read(2, addr);
501 LOG_IOPORT("inl : %04x %08x\n", addr, val);
502 #ifdef CONFIG_KQEMU
503 if (env)
504 env->last_io_time = cpu_get_time_fast();
505 #endif
506 return val;
509 /***********************************************************/
510 void hw_error(const char *fmt, ...)
512 va_list ap;
513 CPUState *env;
515 va_start(ap, fmt);
516 fprintf(stderr, "qemu: hardware error: ");
517 vfprintf(stderr, fmt, ap);
518 fprintf(stderr, "\n");
519 for(env = first_cpu; env != NULL; env = env->next_cpu) {
520 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
521 #ifdef TARGET_I386
522 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
523 #else
524 cpu_dump_state(env, stderr, fprintf, 0);
525 #endif
527 va_end(ap);
528 abort();
531 /***************/
532 /* ballooning */
534 static QEMUBalloonEvent *qemu_balloon_event;
535 void *qemu_balloon_event_opaque;
537 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
539 qemu_balloon_event = func;
540 qemu_balloon_event_opaque = opaque;
543 void qemu_balloon(ram_addr_t target)
545 if (qemu_balloon_event)
546 qemu_balloon_event(qemu_balloon_event_opaque, target);
549 ram_addr_t qemu_balloon_status(void)
551 if (qemu_balloon_event)
552 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
553 return 0;
556 /***********************************************************/
557 /* keyboard/mouse */
559 static QEMUPutKBDEvent *qemu_put_kbd_event;
560 static void *qemu_put_kbd_event_opaque;
561 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
562 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
564 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
566 qemu_put_kbd_event_opaque = opaque;
567 qemu_put_kbd_event = func;
570 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
571 void *opaque, int absolute,
572 const char *name)
574 QEMUPutMouseEntry *s, *cursor;
576 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
578 s->qemu_put_mouse_event = func;
579 s->qemu_put_mouse_event_opaque = opaque;
580 s->qemu_put_mouse_event_absolute = absolute;
581 s->qemu_put_mouse_event_name = qemu_strdup(name);
582 s->next = NULL;
584 if (!qemu_put_mouse_event_head) {
585 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
586 return s;
589 cursor = qemu_put_mouse_event_head;
590 while (cursor->next != NULL)
591 cursor = cursor->next;
593 cursor->next = s;
594 qemu_put_mouse_event_current = s;
596 return s;
599 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
601 QEMUPutMouseEntry *prev = NULL, *cursor;
603 if (!qemu_put_mouse_event_head || entry == NULL)
604 return;
606 cursor = qemu_put_mouse_event_head;
607 while (cursor != NULL && cursor != entry) {
608 prev = cursor;
609 cursor = cursor->next;
612 if (cursor == NULL) // does not exist or list empty
613 return;
614 else if (prev == NULL) { // entry is head
615 qemu_put_mouse_event_head = cursor->next;
616 if (qemu_put_mouse_event_current == entry)
617 qemu_put_mouse_event_current = cursor->next;
618 qemu_free(entry->qemu_put_mouse_event_name);
619 qemu_free(entry);
620 return;
623 prev->next = entry->next;
625 if (qemu_put_mouse_event_current == entry)
626 qemu_put_mouse_event_current = prev;
628 qemu_free(entry->qemu_put_mouse_event_name);
629 qemu_free(entry);
632 void kbd_put_keycode(int keycode)
634 if (qemu_put_kbd_event) {
635 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
639 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
641 QEMUPutMouseEvent *mouse_event;
642 void *mouse_event_opaque;
643 int width;
645 if (!qemu_put_mouse_event_current) {
646 return;
649 mouse_event =
650 qemu_put_mouse_event_current->qemu_put_mouse_event;
651 mouse_event_opaque =
652 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
654 if (mouse_event) {
655 if (graphic_rotate) {
656 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
657 width = 0x7fff;
658 else
659 width = graphic_width - 1;
660 mouse_event(mouse_event_opaque,
661 width - dy, dx, dz, buttons_state);
662 } else
663 mouse_event(mouse_event_opaque,
664 dx, dy, dz, buttons_state);
668 int kbd_mouse_is_absolute(void)
670 if (!qemu_put_mouse_event_current)
671 return 0;
673 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
676 void do_info_mice(Monitor *mon)
678 QEMUPutMouseEntry *cursor;
679 int index = 0;
681 if (!qemu_put_mouse_event_head) {
682 monitor_printf(mon, "No mouse devices connected\n");
683 return;
686 monitor_printf(mon, "Mouse devices available:\n");
687 cursor = qemu_put_mouse_event_head;
688 while (cursor != NULL) {
689 monitor_printf(mon, "%c Mouse #%d: %s\n",
690 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
691 index, cursor->qemu_put_mouse_event_name);
692 index++;
693 cursor = cursor->next;
697 void do_mouse_set(Monitor *mon, int index)
699 QEMUPutMouseEntry *cursor;
700 int i = 0;
702 if (!qemu_put_mouse_event_head) {
703 monitor_printf(mon, "No mouse devices connected\n");
704 return;
707 cursor = qemu_put_mouse_event_head;
708 while (cursor != NULL && index != i) {
709 i++;
710 cursor = cursor->next;
713 if (cursor != NULL)
714 qemu_put_mouse_event_current = cursor;
715 else
716 monitor_printf(mon, "Mouse at given index not found\n");
719 /* compute with 96 bit intermediate result: (a*b)/c */
720 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
722 union {
723 uint64_t ll;
724 struct {
725 #ifdef WORDS_BIGENDIAN
726 uint32_t high, low;
727 #else
728 uint32_t low, high;
729 #endif
730 } l;
731 } u, res;
732 uint64_t rl, rh;
734 u.ll = a;
735 rl = (uint64_t)u.l.low * (uint64_t)b;
736 rh = (uint64_t)u.l.high * (uint64_t)b;
737 rh += (rl >> 32);
738 res.l.high = rh / c;
739 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
740 return res.ll;
743 /***********************************************************/
744 /* real time host monotonic timer */
746 #define QEMU_TIMER_BASE 1000000000LL
748 #ifdef WIN32
750 static int64_t clock_freq;
752 static void init_get_clock(void)
754 LARGE_INTEGER freq;
755 int ret;
756 ret = QueryPerformanceFrequency(&freq);
757 if (ret == 0) {
758 fprintf(stderr, "Could not calibrate ticks\n");
759 exit(1);
761 clock_freq = freq.QuadPart;
764 static int64_t get_clock(void)
766 LARGE_INTEGER ti;
767 QueryPerformanceCounter(&ti);
768 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
771 #else
773 static int use_rt_clock;
775 static void init_get_clock(void)
777 use_rt_clock = 0;
778 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
779 || defined(__DragonFly__)
781 struct timespec ts;
782 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
783 use_rt_clock = 1;
786 #endif
789 static int64_t get_clock(void)
791 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
792 || defined(__DragonFly__)
793 if (use_rt_clock) {
794 struct timespec ts;
795 clock_gettime(CLOCK_MONOTONIC, &ts);
796 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
797 } else
798 #endif
800 /* XXX: using gettimeofday leads to problems if the date
801 changes, so it should be avoided. */
802 struct timeval tv;
803 gettimeofday(&tv, NULL);
804 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
807 #endif
809 /* Return the virtual CPU time, based on the instruction counter. */
810 static int64_t cpu_get_icount(void)
812 int64_t icount;
813 CPUState *env = cpu_single_env;;
814 icount = qemu_icount;
815 if (env) {
816 if (!can_do_io(env))
817 fprintf(stderr, "Bad clock read\n");
818 icount -= (env->icount_decr.u16.low + env->icount_extra);
820 return qemu_icount_bias + (icount << icount_time_shift);
823 /***********************************************************/
824 /* guest cycle counter */
826 static int64_t cpu_ticks_prev;
827 static int64_t cpu_ticks_offset;
828 static int64_t cpu_clock_offset;
829 static int cpu_ticks_enabled;
831 /* return the host CPU cycle counter and handle stop/restart */
832 int64_t cpu_get_ticks(void)
834 if (use_icount) {
835 return cpu_get_icount();
837 if (!cpu_ticks_enabled) {
838 return cpu_ticks_offset;
839 } else {
840 int64_t ticks;
841 ticks = cpu_get_real_ticks();
842 if (cpu_ticks_prev > ticks) {
843 /* Note: non increasing ticks may happen if the host uses
844 software suspend */
845 cpu_ticks_offset += cpu_ticks_prev - ticks;
847 cpu_ticks_prev = ticks;
848 return ticks + cpu_ticks_offset;
852 /* return the host CPU monotonic timer and handle stop/restart */
853 static int64_t cpu_get_clock(void)
855 int64_t ti;
856 if (!cpu_ticks_enabled) {
857 return cpu_clock_offset;
858 } else {
859 ti = get_clock();
860 return ti + cpu_clock_offset;
864 /* enable cpu_get_ticks() */
865 void cpu_enable_ticks(void)
867 if (!cpu_ticks_enabled) {
868 cpu_ticks_offset -= cpu_get_real_ticks();
869 cpu_clock_offset -= get_clock();
870 cpu_ticks_enabled = 1;
874 /* disable cpu_get_ticks() : the clock is stopped. You must not call
875 cpu_get_ticks() after that. */
876 void cpu_disable_ticks(void)
878 if (cpu_ticks_enabled) {
879 cpu_ticks_offset = cpu_get_ticks();
880 cpu_clock_offset = cpu_get_clock();
881 cpu_ticks_enabled = 0;
885 /***********************************************************/
886 /* timers */
888 #define QEMU_TIMER_REALTIME 0
889 #define QEMU_TIMER_VIRTUAL 1
891 struct QEMUClock {
892 int type;
893 /* XXX: add frequency */
896 struct QEMUTimer {
897 QEMUClock *clock;
898 int64_t expire_time;
899 QEMUTimerCB *cb;
900 void *opaque;
901 struct QEMUTimer *next;
904 struct qemu_alarm_timer {
905 char const *name;
906 unsigned int flags;
908 int (*start)(struct qemu_alarm_timer *t);
909 void (*stop)(struct qemu_alarm_timer *t);
910 void (*rearm)(struct qemu_alarm_timer *t);
911 void *priv;
914 #define ALARM_FLAG_DYNTICKS 0x1
915 #define ALARM_FLAG_EXPIRED 0x2
917 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
919 return t->flags & ALARM_FLAG_DYNTICKS;
922 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
924 if (!alarm_has_dynticks(t))
925 return;
927 t->rearm(t);
930 /* TODO: MIN_TIMER_REARM_US should be optimized */
931 #define MIN_TIMER_REARM_US 250
933 static struct qemu_alarm_timer *alarm_timer;
935 #ifdef _WIN32
937 struct qemu_alarm_win32 {
938 MMRESULT timerId;
939 unsigned int period;
940 } alarm_win32_data = {0, -1};
942 static int win32_start_timer(struct qemu_alarm_timer *t);
943 static void win32_stop_timer(struct qemu_alarm_timer *t);
944 static void win32_rearm_timer(struct qemu_alarm_timer *t);
946 #else
948 static int unix_start_timer(struct qemu_alarm_timer *t);
949 static void unix_stop_timer(struct qemu_alarm_timer *t);
951 #ifdef __linux__
953 static int dynticks_start_timer(struct qemu_alarm_timer *t);
954 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
955 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
957 static int hpet_start_timer(struct qemu_alarm_timer *t);
958 static void hpet_stop_timer(struct qemu_alarm_timer *t);
960 static int rtc_start_timer(struct qemu_alarm_timer *t);
961 static void rtc_stop_timer(struct qemu_alarm_timer *t);
963 #endif /* __linux__ */
965 #endif /* _WIN32 */
967 /* Correlation between real and virtual time is always going to be
968 fairly approximate, so ignore small variation.
969 When the guest is idle real and virtual time will be aligned in
970 the IO wait loop. */
971 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
973 static void icount_adjust(void)
975 int64_t cur_time;
976 int64_t cur_icount;
977 int64_t delta;
978 static int64_t last_delta;
979 /* If the VM is not running, then do nothing. */
980 if (!vm_running)
981 return;
983 cur_time = cpu_get_clock();
984 cur_icount = qemu_get_clock(vm_clock);
985 delta = cur_icount - cur_time;
986 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
987 if (delta > 0
988 && last_delta + ICOUNT_WOBBLE < delta * 2
989 && icount_time_shift > 0) {
990 /* The guest is getting too far ahead. Slow time down. */
991 icount_time_shift--;
993 if (delta < 0
994 && last_delta - ICOUNT_WOBBLE > delta * 2
995 && icount_time_shift < MAX_ICOUNT_SHIFT) {
996 /* The guest is getting too far behind. Speed time up. */
997 icount_time_shift++;
999 last_delta = delta;
1000 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1003 static void icount_adjust_rt(void * opaque)
1005 qemu_mod_timer(icount_rt_timer,
1006 qemu_get_clock(rt_clock) + 1000);
1007 icount_adjust();
1010 static void icount_adjust_vm(void * opaque)
1012 qemu_mod_timer(icount_vm_timer,
1013 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1014 icount_adjust();
1017 static void init_icount_adjust(void)
1019 /* Have both realtime and virtual time triggers for speed adjustment.
1020 The realtime trigger catches emulated time passing too slowly,
1021 the virtual time trigger catches emulated time passing too fast.
1022 Realtime triggers occur even when idle, so use them less frequently
1023 than VM triggers. */
1024 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1025 qemu_mod_timer(icount_rt_timer,
1026 qemu_get_clock(rt_clock) + 1000);
1027 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1028 qemu_mod_timer(icount_vm_timer,
1029 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1032 static struct qemu_alarm_timer alarm_timers[] = {
1033 #ifndef _WIN32
1034 #ifdef __linux__
1035 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1036 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1037 /* HPET - if available - is preferred */
1038 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1039 /* ...otherwise try RTC */
1040 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1041 #endif
1042 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1043 #else
1044 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1045 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1046 {"win32", 0, win32_start_timer,
1047 win32_stop_timer, NULL, &alarm_win32_data},
1048 #endif
1049 {NULL, }
1052 static void show_available_alarms(void)
1054 int i;
1056 printf("Available alarm timers, in order of precedence:\n");
1057 for (i = 0; alarm_timers[i].name; i++)
1058 printf("%s\n", alarm_timers[i].name);
1061 static void configure_alarms(char const *opt)
1063 int i;
1064 int cur = 0;
1065 int count = ARRAY_SIZE(alarm_timers) - 1;
1066 char *arg;
1067 char *name;
1068 struct qemu_alarm_timer tmp;
1070 if (!strcmp(opt, "?")) {
1071 show_available_alarms();
1072 exit(0);
1075 arg = strdup(opt);
1077 /* Reorder the array */
1078 name = strtok(arg, ",");
1079 while (name) {
1080 for (i = 0; i < count && alarm_timers[i].name; i++) {
1081 if (!strcmp(alarm_timers[i].name, name))
1082 break;
1085 if (i == count) {
1086 fprintf(stderr, "Unknown clock %s\n", name);
1087 goto next;
1090 if (i < cur)
1091 /* Ignore */
1092 goto next;
1094 /* Swap */
1095 tmp = alarm_timers[i];
1096 alarm_timers[i] = alarm_timers[cur];
1097 alarm_timers[cur] = tmp;
1099 cur++;
1100 next:
1101 name = strtok(NULL, ",");
1104 free(arg);
1106 if (cur) {
1107 /* Disable remaining timers */
1108 for (i = cur; i < count; i++)
1109 alarm_timers[i].name = NULL;
1110 } else {
1111 show_available_alarms();
1112 exit(1);
1116 QEMUClock *rt_clock;
1117 QEMUClock *vm_clock;
1119 static QEMUTimer *active_timers[2];
1121 static QEMUClock *qemu_new_clock(int type)
1123 QEMUClock *clock;
1124 clock = qemu_mallocz(sizeof(QEMUClock));
1125 clock->type = type;
1126 return clock;
1129 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1131 QEMUTimer *ts;
1133 ts = qemu_mallocz(sizeof(QEMUTimer));
1134 ts->clock = clock;
1135 ts->cb = cb;
1136 ts->opaque = opaque;
1137 return ts;
1140 void qemu_free_timer(QEMUTimer *ts)
1142 qemu_free(ts);
1145 /* stop a timer, but do not dealloc it */
1146 void qemu_del_timer(QEMUTimer *ts)
1148 QEMUTimer **pt, *t;
1150 /* NOTE: this code must be signal safe because
1151 qemu_timer_expired() can be called from a signal. */
1152 pt = &active_timers[ts->clock->type];
1153 for(;;) {
1154 t = *pt;
1155 if (!t)
1156 break;
1157 if (t == ts) {
1158 *pt = t->next;
1159 break;
1161 pt = &t->next;
1165 /* modify the current timer so that it will be fired when current_time
1166 >= expire_time. The corresponding callback will be called. */
1167 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1169 QEMUTimer **pt, *t;
1171 qemu_del_timer(ts);
1173 /* add the timer in the sorted list */
1174 /* NOTE: this code must be signal safe because
1175 qemu_timer_expired() can be called from a signal. */
1176 pt = &active_timers[ts->clock->type];
1177 for(;;) {
1178 t = *pt;
1179 if (!t)
1180 break;
1181 if (t->expire_time > expire_time)
1182 break;
1183 pt = &t->next;
1185 ts->expire_time = expire_time;
1186 ts->next = *pt;
1187 *pt = ts;
1189 /* Rearm if necessary */
1190 if (pt == &active_timers[ts->clock->type]) {
1191 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1192 qemu_rearm_alarm_timer(alarm_timer);
1194 /* Interrupt execution to force deadline recalculation. */
1195 if (use_icount)
1196 qemu_notify_event();
1200 int qemu_timer_pending(QEMUTimer *ts)
1202 QEMUTimer *t;
1203 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1204 if (t == ts)
1205 return 1;
1207 return 0;
1210 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1212 if (!timer_head)
1213 return 0;
1214 return (timer_head->expire_time <= current_time);
1217 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1219 QEMUTimer *ts;
1221 for(;;) {
1222 ts = *ptimer_head;
1223 if (!ts || ts->expire_time > current_time)
1224 break;
1225 /* remove timer from the list before calling the callback */
1226 *ptimer_head = ts->next;
1227 ts->next = NULL;
1229 /* run the callback (the timer list can be modified) */
1230 ts->cb(ts->opaque);
1234 int64_t qemu_get_clock(QEMUClock *clock)
1236 switch(clock->type) {
1237 case QEMU_TIMER_REALTIME:
1238 return get_clock() / 1000000;
1239 default:
1240 case QEMU_TIMER_VIRTUAL:
1241 if (use_icount) {
1242 return cpu_get_icount();
1243 } else {
1244 return cpu_get_clock();
1249 static void init_timers(void)
1251 init_get_clock();
1252 ticks_per_sec = QEMU_TIMER_BASE;
1253 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1254 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1257 /* save a timer */
1258 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1260 uint64_t expire_time;
1262 if (qemu_timer_pending(ts)) {
1263 expire_time = ts->expire_time;
1264 } else {
1265 expire_time = -1;
1267 qemu_put_be64(f, expire_time);
1270 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1272 uint64_t expire_time;
1274 expire_time = qemu_get_be64(f);
1275 if (expire_time != -1) {
1276 qemu_mod_timer(ts, expire_time);
1277 } else {
1278 qemu_del_timer(ts);
1282 static void timer_save(QEMUFile *f, void *opaque)
1284 if (cpu_ticks_enabled) {
1285 hw_error("cannot save state if virtual timers are running");
1287 qemu_put_be64(f, cpu_ticks_offset);
1288 qemu_put_be64(f, ticks_per_sec);
1289 qemu_put_be64(f, cpu_clock_offset);
1292 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1294 if (version_id != 1 && version_id != 2)
1295 return -EINVAL;
1296 if (cpu_ticks_enabled) {
1297 return -EINVAL;
1299 cpu_ticks_offset=qemu_get_be64(f);
1300 ticks_per_sec=qemu_get_be64(f);
1301 if (version_id == 2) {
1302 cpu_clock_offset=qemu_get_be64(f);
1304 return 0;
1307 static void qemu_event_increment(void);
1309 #ifdef _WIN32
1310 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1311 DWORD_PTR dwUser, DWORD_PTR dw1,
1312 DWORD_PTR dw2)
1313 #else
1314 static void host_alarm_handler(int host_signum)
1315 #endif
1317 #if 0
1318 #define DISP_FREQ 1000
1320 static int64_t delta_min = INT64_MAX;
1321 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1322 static int count;
1323 ti = qemu_get_clock(vm_clock);
1324 if (last_clock != 0) {
1325 delta = ti - last_clock;
1326 if (delta < delta_min)
1327 delta_min = delta;
1328 if (delta > delta_max)
1329 delta_max = delta;
1330 delta_cum += delta;
1331 if (++count == DISP_FREQ) {
1332 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1333 muldiv64(delta_min, 1000000, ticks_per_sec),
1334 muldiv64(delta_max, 1000000, ticks_per_sec),
1335 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1336 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1337 count = 0;
1338 delta_min = INT64_MAX;
1339 delta_max = 0;
1340 delta_cum = 0;
1343 last_clock = ti;
1345 #endif
1346 if (alarm_has_dynticks(alarm_timer) ||
1347 (!use_icount &&
1348 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1349 qemu_get_clock(vm_clock))) ||
1350 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1351 qemu_get_clock(rt_clock))) {
1352 qemu_event_increment();
1353 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1355 #ifndef CONFIG_IOTHREAD
1356 if (next_cpu) {
1357 /* stop the currently executing cpu because a timer occured */
1358 cpu_exit(next_cpu);
1359 #ifdef CONFIG_KQEMU
1360 if (next_cpu->kqemu_enabled) {
1361 kqemu_cpu_interrupt(next_cpu);
1363 #endif
1365 #endif
1366 timer_alarm_pending = 1;
1367 qemu_notify_event();
1371 static int64_t qemu_next_deadline(void)
1373 int64_t delta;
1375 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1376 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1377 qemu_get_clock(vm_clock);
1378 } else {
1379 /* To avoid problems with overflow limit this to 2^32. */
1380 delta = INT32_MAX;
1383 if (delta < 0)
1384 delta = 0;
1386 return delta;
1389 #if defined(__linux__) || defined(_WIN32)
1390 static uint64_t qemu_next_deadline_dyntick(void)
1392 int64_t delta;
1393 int64_t rtdelta;
1395 if (use_icount)
1396 delta = INT32_MAX;
1397 else
1398 delta = (qemu_next_deadline() + 999) / 1000;
1400 if (active_timers[QEMU_TIMER_REALTIME]) {
1401 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1402 qemu_get_clock(rt_clock))*1000;
1403 if (rtdelta < delta)
1404 delta = rtdelta;
1407 if (delta < MIN_TIMER_REARM_US)
1408 delta = MIN_TIMER_REARM_US;
1410 return delta;
1412 #endif
1414 #ifndef _WIN32
1416 /* Sets a specific flag */
1417 static int fcntl_setfl(int fd, int flag)
1419 int flags;
1421 flags = fcntl(fd, F_GETFL);
1422 if (flags == -1)
1423 return -errno;
1425 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1426 return -errno;
1428 return 0;
1431 #if defined(__linux__)
1433 #define RTC_FREQ 1024
1435 static void enable_sigio_timer(int fd)
1437 struct sigaction act;
1439 /* timer signal */
1440 sigfillset(&act.sa_mask);
1441 act.sa_flags = 0;
1442 act.sa_handler = host_alarm_handler;
1444 sigaction(SIGIO, &act, NULL);
1445 fcntl_setfl(fd, O_ASYNC);
1446 fcntl(fd, F_SETOWN, getpid());
1449 static int hpet_start_timer(struct qemu_alarm_timer *t)
1451 struct hpet_info info;
1452 int r, fd;
1454 fd = open("/dev/hpet", O_RDONLY);
1455 if (fd < 0)
1456 return -1;
1458 /* Set frequency */
1459 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1460 if (r < 0) {
1461 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1462 "error, but for better emulation accuracy type:\n"
1463 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1464 goto fail;
1467 /* Check capabilities */
1468 r = ioctl(fd, HPET_INFO, &info);
1469 if (r < 0)
1470 goto fail;
1472 /* Enable periodic mode */
1473 r = ioctl(fd, HPET_EPI, 0);
1474 if (info.hi_flags && (r < 0))
1475 goto fail;
1477 /* Enable interrupt */
1478 r = ioctl(fd, HPET_IE_ON, 0);
1479 if (r < 0)
1480 goto fail;
1482 enable_sigio_timer(fd);
1483 t->priv = (void *)(long)fd;
1485 return 0;
1486 fail:
1487 close(fd);
1488 return -1;
1491 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1493 int fd = (long)t->priv;
1495 close(fd);
1498 static int rtc_start_timer(struct qemu_alarm_timer *t)
1500 int rtc_fd;
1501 unsigned long current_rtc_freq = 0;
1503 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1504 if (rtc_fd < 0)
1505 return -1;
1506 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1507 if (current_rtc_freq != RTC_FREQ &&
1508 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1509 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1510 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1511 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1512 goto fail;
1514 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1515 fail:
1516 close(rtc_fd);
1517 return -1;
1520 enable_sigio_timer(rtc_fd);
1522 t->priv = (void *)(long)rtc_fd;
1524 return 0;
1527 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1529 int rtc_fd = (long)t->priv;
1531 close(rtc_fd);
1534 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1536 struct sigevent ev;
1537 timer_t host_timer;
1538 struct sigaction act;
1540 sigfillset(&act.sa_mask);
1541 act.sa_flags = 0;
1542 act.sa_handler = host_alarm_handler;
1544 sigaction(SIGALRM, &act, NULL);
1546 ev.sigev_value.sival_int = 0;
1547 ev.sigev_notify = SIGEV_SIGNAL;
1548 ev.sigev_signo = SIGALRM;
1550 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1551 perror("timer_create");
1553 /* disable dynticks */
1554 fprintf(stderr, "Dynamic Ticks disabled\n");
1556 return -1;
1559 t->priv = (void *)(long)host_timer;
1561 return 0;
1564 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1566 timer_t host_timer = (timer_t)(long)t->priv;
1568 timer_delete(host_timer);
1571 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1573 timer_t host_timer = (timer_t)(long)t->priv;
1574 struct itimerspec timeout;
1575 int64_t nearest_delta_us = INT64_MAX;
1576 int64_t current_us;
1578 if (!active_timers[QEMU_TIMER_REALTIME] &&
1579 !active_timers[QEMU_TIMER_VIRTUAL])
1580 return;
1582 nearest_delta_us = qemu_next_deadline_dyntick();
1584 /* check whether a timer is already running */
1585 if (timer_gettime(host_timer, &timeout)) {
1586 perror("gettime");
1587 fprintf(stderr, "Internal timer error: aborting\n");
1588 exit(1);
1590 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1591 if (current_us && current_us <= nearest_delta_us)
1592 return;
1594 timeout.it_interval.tv_sec = 0;
1595 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1596 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1597 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1598 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1599 perror("settime");
1600 fprintf(stderr, "Internal timer error: aborting\n");
1601 exit(1);
1605 #endif /* defined(__linux__) */
1607 static int unix_start_timer(struct qemu_alarm_timer *t)
1609 struct sigaction act;
1610 struct itimerval itv;
1611 int err;
1613 /* timer signal */
1614 sigfillset(&act.sa_mask);
1615 act.sa_flags = 0;
1616 act.sa_handler = host_alarm_handler;
1618 sigaction(SIGALRM, &act, NULL);
1620 itv.it_interval.tv_sec = 0;
1621 /* for i386 kernel 2.6 to get 1 ms */
1622 itv.it_interval.tv_usec = 999;
1623 itv.it_value.tv_sec = 0;
1624 itv.it_value.tv_usec = 10 * 1000;
1626 err = setitimer(ITIMER_REAL, &itv, NULL);
1627 if (err)
1628 return -1;
1630 return 0;
1633 static void unix_stop_timer(struct qemu_alarm_timer *t)
1635 struct itimerval itv;
1637 memset(&itv, 0, sizeof(itv));
1638 setitimer(ITIMER_REAL, &itv, NULL);
1641 #endif /* !defined(_WIN32) */
1644 #ifdef _WIN32
1646 static int win32_start_timer(struct qemu_alarm_timer *t)
1648 TIMECAPS tc;
1649 struct qemu_alarm_win32 *data = t->priv;
1650 UINT flags;
1652 memset(&tc, 0, sizeof(tc));
1653 timeGetDevCaps(&tc, sizeof(tc));
1655 if (data->period < tc.wPeriodMin)
1656 data->period = tc.wPeriodMin;
1658 timeBeginPeriod(data->period);
1660 flags = TIME_CALLBACK_FUNCTION;
1661 if (alarm_has_dynticks(t))
1662 flags |= TIME_ONESHOT;
1663 else
1664 flags |= TIME_PERIODIC;
1666 data->timerId = timeSetEvent(1, // interval (ms)
1667 data->period, // resolution
1668 host_alarm_handler, // function
1669 (DWORD)t, // parameter
1670 flags);
1672 if (!data->timerId) {
1673 perror("Failed to initialize win32 alarm timer");
1674 timeEndPeriod(data->period);
1675 return -1;
1678 return 0;
1681 static void win32_stop_timer(struct qemu_alarm_timer *t)
1683 struct qemu_alarm_win32 *data = t->priv;
1685 timeKillEvent(data->timerId);
1686 timeEndPeriod(data->period);
1689 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1691 struct qemu_alarm_win32 *data = t->priv;
1692 uint64_t nearest_delta_us;
1694 if (!active_timers[QEMU_TIMER_REALTIME] &&
1695 !active_timers[QEMU_TIMER_VIRTUAL])
1696 return;
1698 nearest_delta_us = qemu_next_deadline_dyntick();
1699 nearest_delta_us /= 1000;
1701 timeKillEvent(data->timerId);
1703 data->timerId = timeSetEvent(1,
1704 data->period,
1705 host_alarm_handler,
1706 (DWORD)t,
1707 TIME_ONESHOT | TIME_PERIODIC);
1709 if (!data->timerId) {
1710 perror("Failed to re-arm win32 alarm timer");
1712 timeEndPeriod(data->period);
1713 exit(1);
1717 #endif /* _WIN32 */
1719 static int init_timer_alarm(void)
1721 struct qemu_alarm_timer *t = NULL;
1722 int i, err = -1;
1724 for (i = 0; alarm_timers[i].name; i++) {
1725 t = &alarm_timers[i];
1727 err = t->start(t);
1728 if (!err)
1729 break;
1732 if (err) {
1733 err = -ENOENT;
1734 goto fail;
1737 alarm_timer = t;
1739 return 0;
1741 fail:
1742 return err;
1745 static void quit_timers(void)
1747 alarm_timer->stop(alarm_timer);
1748 alarm_timer = NULL;
1751 /***********************************************************/
1752 /* host time/date access */
1753 void qemu_get_timedate(struct tm *tm, int offset)
1755 time_t ti;
1756 struct tm *ret;
1758 time(&ti);
1759 ti += offset;
1760 if (rtc_date_offset == -1) {
1761 if (rtc_utc)
1762 ret = gmtime(&ti);
1763 else
1764 ret = localtime(&ti);
1765 } else {
1766 ti -= rtc_date_offset;
1767 ret = gmtime(&ti);
1770 memcpy(tm, ret, sizeof(struct tm));
1773 int qemu_timedate_diff(struct tm *tm)
1775 time_t seconds;
1777 if (rtc_date_offset == -1)
1778 if (rtc_utc)
1779 seconds = mktimegm(tm);
1780 else
1781 seconds = mktime(tm);
1782 else
1783 seconds = mktimegm(tm) + rtc_date_offset;
1785 return seconds - time(NULL);
1788 #ifdef _WIN32
1789 static void socket_cleanup(void)
1791 WSACleanup();
1794 static int socket_init(void)
1796 WSADATA Data;
1797 int ret, err;
1799 ret = WSAStartup(MAKEWORD(2,2), &Data);
1800 if (ret != 0) {
1801 err = WSAGetLastError();
1802 fprintf(stderr, "WSAStartup: %d\n", err);
1803 return -1;
1805 atexit(socket_cleanup);
1806 return 0;
1808 #endif
1810 const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
1812 char *q;
1814 q = buf;
1815 while (*p != '\0' && *p != delim) {
1816 if (q && (q - buf) < buf_size - 1)
1817 *q++ = *p;
1818 p++;
1820 if (q)
1821 *q = '\0';
1823 return p;
1826 const char *get_opt_value(char *buf, int buf_size, const char *p)
1828 char *q;
1830 q = buf;
1831 while (*p != '\0') {
1832 if (*p == ',') {
1833 if (*(p + 1) != ',')
1834 break;
1835 p++;
1837 if (q && (q - buf) < buf_size - 1)
1838 *q++ = *p;
1839 p++;
1841 if (q)
1842 *q = '\0';
1844 return p;
1847 int get_param_value(char *buf, int buf_size,
1848 const char *tag, const char *str)
1850 const char *p;
1851 char option[128];
1853 p = str;
1854 for(;;) {
1855 p = get_opt_name(option, sizeof(option), p, '=');
1856 if (*p != '=')
1857 break;
1858 p++;
1859 if (!strcmp(tag, option)) {
1860 (void)get_opt_value(buf, buf_size, p);
1861 return strlen(buf);
1862 } else {
1863 p = get_opt_value(NULL, 0, p);
1865 if (*p != ',')
1866 break;
1867 p++;
1869 return 0;
1872 int check_params(const char * const *params, const char *str)
1874 int name_buf_size = 1;
1875 const char *p;
1876 char *name_buf;
1877 int i, len;
1878 int ret = 0;
1880 for (i = 0; params[i] != NULL; i++) {
1881 len = strlen(params[i]) + 1;
1882 if (len > name_buf_size) {
1883 name_buf_size = len;
1886 name_buf = qemu_malloc(name_buf_size);
1888 p = str;
1889 while (*p != '\0') {
1890 p = get_opt_name(name_buf, name_buf_size, p, '=');
1891 if (*p != '=') {
1892 ret = -1;
1893 break;
1895 p++;
1896 for(i = 0; params[i] != NULL; i++)
1897 if (!strcmp(params[i], name_buf))
1898 break;
1899 if (params[i] == NULL) {
1900 ret = -1;
1901 break;
1903 p = get_opt_value(NULL, 0, p);
1904 if (*p != ',')
1905 break;
1906 p++;
1909 qemu_free(name_buf);
1910 return ret;
1913 /***********************************************************/
1914 /* Bluetooth support */
1915 static int nb_hcis;
1916 static int cur_hci;
1917 static struct HCIInfo *hci_table[MAX_NICS];
1919 static struct bt_vlan_s {
1920 struct bt_scatternet_s net;
1921 int id;
1922 struct bt_vlan_s *next;
1923 } *first_bt_vlan;
1925 /* find or alloc a new bluetooth "VLAN" */
1926 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1928 struct bt_vlan_s **pvlan, *vlan;
1929 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1930 if (vlan->id == id)
1931 return &vlan->net;
1933 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1934 vlan->id = id;
1935 pvlan = &first_bt_vlan;
1936 while (*pvlan != NULL)
1937 pvlan = &(*pvlan)->next;
1938 *pvlan = vlan;
1939 return &vlan->net;
1942 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1946 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1948 return -ENOTSUP;
1951 static struct HCIInfo null_hci = {
1952 .cmd_send = null_hci_send,
1953 .sco_send = null_hci_send,
1954 .acl_send = null_hci_send,
1955 .bdaddr_set = null_hci_addr_set,
1958 struct HCIInfo *qemu_next_hci(void)
1960 if (cur_hci == nb_hcis)
1961 return &null_hci;
1963 return hci_table[cur_hci++];
1966 static struct HCIInfo *hci_init(const char *str)
1968 char *endp;
1969 struct bt_scatternet_s *vlan = 0;
1971 if (!strcmp(str, "null"))
1972 /* null */
1973 return &null_hci;
1974 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1975 /* host[:hciN] */
1976 return bt_host_hci(str[4] ? str + 5 : "hci0");
1977 else if (!strncmp(str, "hci", 3)) {
1978 /* hci[,vlan=n] */
1979 if (str[3]) {
1980 if (!strncmp(str + 3, ",vlan=", 6)) {
1981 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1982 if (*endp)
1983 vlan = 0;
1985 } else
1986 vlan = qemu_find_bt_vlan(0);
1987 if (vlan)
1988 return bt_new_hci(vlan);
1991 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1993 return 0;
1996 static int bt_hci_parse(const char *str)
1998 struct HCIInfo *hci;
1999 bdaddr_t bdaddr;
2001 if (nb_hcis >= MAX_NICS) {
2002 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2003 return -1;
2006 hci = hci_init(str);
2007 if (!hci)
2008 return -1;
2010 bdaddr.b[0] = 0x52;
2011 bdaddr.b[1] = 0x54;
2012 bdaddr.b[2] = 0x00;
2013 bdaddr.b[3] = 0x12;
2014 bdaddr.b[4] = 0x34;
2015 bdaddr.b[5] = 0x56 + nb_hcis;
2016 hci->bdaddr_set(hci, bdaddr.b);
2018 hci_table[nb_hcis++] = hci;
2020 return 0;
2023 static void bt_vhci_add(int vlan_id)
2025 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2027 if (!vlan->slave)
2028 fprintf(stderr, "qemu: warning: adding a VHCI to "
2029 "an empty scatternet %i\n", vlan_id);
2031 bt_vhci_init(bt_new_hci(vlan));
2034 static struct bt_device_s *bt_device_add(const char *opt)
2036 struct bt_scatternet_s *vlan;
2037 int vlan_id = 0;
2038 char *endp = strstr(opt, ",vlan=");
2039 int len = (endp ? endp - opt : strlen(opt)) + 1;
2040 char devname[10];
2042 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2044 if (endp) {
2045 vlan_id = strtol(endp + 6, &endp, 0);
2046 if (*endp) {
2047 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2048 return 0;
2052 vlan = qemu_find_bt_vlan(vlan_id);
2054 if (!vlan->slave)
2055 fprintf(stderr, "qemu: warning: adding a slave device to "
2056 "an empty scatternet %i\n", vlan_id);
2058 if (!strcmp(devname, "keyboard"))
2059 return bt_keyboard_init(vlan);
2061 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2062 return 0;
2065 static int bt_parse(const char *opt)
2067 const char *endp, *p;
2068 int vlan;
2070 if (strstart(opt, "hci", &endp)) {
2071 if (!*endp || *endp == ',') {
2072 if (*endp)
2073 if (!strstart(endp, ",vlan=", 0))
2074 opt = endp + 1;
2076 return bt_hci_parse(opt);
2078 } else if (strstart(opt, "vhci", &endp)) {
2079 if (!*endp || *endp == ',') {
2080 if (*endp) {
2081 if (strstart(endp, ",vlan=", &p)) {
2082 vlan = strtol(p, (char **) &endp, 0);
2083 if (*endp) {
2084 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2085 return 1;
2087 } else {
2088 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2089 return 1;
2091 } else
2092 vlan = 0;
2094 bt_vhci_add(vlan);
2095 return 0;
2097 } else if (strstart(opt, "device:", &endp))
2098 return !bt_device_add(endp);
2100 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2101 return 1;
2104 /***********************************************************/
2105 /* QEMU Block devices */
2107 #define HD_ALIAS "index=%d,media=disk"
2108 #define CDROM_ALIAS "index=2,media=cdrom"
2109 #define FD_ALIAS "index=%d,if=floppy"
2110 #define PFLASH_ALIAS "if=pflash"
2111 #define MTD_ALIAS "if=mtd"
2112 #define SD_ALIAS "index=0,if=sd"
2114 static int drive_opt_get_free_idx(void)
2116 int index;
2118 for (index = 0; index < MAX_DRIVES; index++)
2119 if (!drives_opt[index].used) {
2120 drives_opt[index].used = 1;
2121 return index;
2124 return -1;
2127 static int drive_get_free_idx(void)
2129 int index;
2131 for (index = 0; index < MAX_DRIVES; index++)
2132 if (!drives_table[index].used) {
2133 drives_table[index].used = 1;
2134 return index;
2137 return -1;
2140 int drive_add(const char *file, const char *fmt, ...)
2142 va_list ap;
2143 int index = drive_opt_get_free_idx();
2145 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2146 fprintf(stderr, "qemu: too many drives\n");
2147 return -1;
2150 drives_opt[index].file = file;
2151 va_start(ap, fmt);
2152 vsnprintf(drives_opt[index].opt,
2153 sizeof(drives_opt[0].opt), fmt, ap);
2154 va_end(ap);
2156 nb_drives_opt++;
2157 return index;
2160 void drive_remove(int index)
2162 drives_opt[index].used = 0;
2163 nb_drives_opt--;
2166 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2168 int index;
2170 /* seek interface, bus and unit */
2172 for (index = 0; index < MAX_DRIVES; index++)
2173 if (drives_table[index].type == type &&
2174 drives_table[index].bus == bus &&
2175 drives_table[index].unit == unit &&
2176 drives_table[index].used)
2177 return index;
2179 return -1;
2182 int drive_get_max_bus(BlockInterfaceType type)
2184 int max_bus;
2185 int index;
2187 max_bus = -1;
2188 for (index = 0; index < nb_drives; index++) {
2189 if(drives_table[index].type == type &&
2190 drives_table[index].bus > max_bus)
2191 max_bus = drives_table[index].bus;
2193 return max_bus;
2196 const char *drive_get_serial(BlockDriverState *bdrv)
2198 int index;
2200 for (index = 0; index < nb_drives; index++)
2201 if (drives_table[index].bdrv == bdrv)
2202 return drives_table[index].serial;
2204 return "\0";
2207 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2209 int index;
2211 for (index = 0; index < nb_drives; index++)
2212 if (drives_table[index].bdrv == bdrv)
2213 return drives_table[index].onerror;
2215 return BLOCK_ERR_STOP_ENOSPC;
2218 static void bdrv_format_print(void *opaque, const char *name)
2220 fprintf(stderr, " %s", name);
2223 void drive_uninit(BlockDriverState *bdrv)
2225 int i;
2227 for (i = 0; i < MAX_DRIVES; i++)
2228 if (drives_table[i].bdrv == bdrv) {
2229 drives_table[i].bdrv = NULL;
2230 drives_table[i].used = 0;
2231 drive_remove(drives_table[i].drive_opt_idx);
2232 nb_drives--;
2233 break;
2237 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2239 char buf[128];
2240 char file[1024];
2241 char devname[128];
2242 char serial[21];
2243 const char *mediastr = "";
2244 BlockInterfaceType type;
2245 enum { MEDIA_DISK, MEDIA_CDROM } media;
2246 int bus_id, unit_id;
2247 int cyls, heads, secs, translation;
2248 BlockDriverState *bdrv;
2249 BlockDriver *drv = NULL;
2250 QEMUMachine *machine = opaque;
2251 int max_devs;
2252 int index;
2253 int cache;
2254 int bdrv_flags, onerror;
2255 int drives_table_idx;
2256 char *str = arg->opt;
2257 static const char * const params[] = { "bus", "unit", "if", "index",
2258 "cyls", "heads", "secs", "trans",
2259 "media", "snapshot", "file",
2260 "cache", "format", "serial", "werror",
2261 NULL };
2263 if (check_params(params, str) < 0) {
2264 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2265 buf, str);
2266 return -1;
2269 file[0] = 0;
2270 cyls = heads = secs = 0;
2271 bus_id = 0;
2272 unit_id = -1;
2273 translation = BIOS_ATA_TRANSLATION_AUTO;
2274 index = -1;
2275 cache = 3;
2277 if (machine->use_scsi) {
2278 type = IF_SCSI;
2279 max_devs = MAX_SCSI_DEVS;
2280 pstrcpy(devname, sizeof(devname), "scsi");
2281 } else {
2282 type = IF_IDE;
2283 max_devs = MAX_IDE_DEVS;
2284 pstrcpy(devname, sizeof(devname), "ide");
2286 media = MEDIA_DISK;
2288 /* extract parameters */
2290 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2291 bus_id = strtol(buf, NULL, 0);
2292 if (bus_id < 0) {
2293 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2294 return -1;
2298 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2299 unit_id = strtol(buf, NULL, 0);
2300 if (unit_id < 0) {
2301 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2302 return -1;
2306 if (get_param_value(buf, sizeof(buf), "if", str)) {
2307 pstrcpy(devname, sizeof(devname), buf);
2308 if (!strcmp(buf, "ide")) {
2309 type = IF_IDE;
2310 max_devs = MAX_IDE_DEVS;
2311 } else if (!strcmp(buf, "scsi")) {
2312 type = IF_SCSI;
2313 max_devs = MAX_SCSI_DEVS;
2314 } else if (!strcmp(buf, "floppy")) {
2315 type = IF_FLOPPY;
2316 max_devs = 0;
2317 } else if (!strcmp(buf, "pflash")) {
2318 type = IF_PFLASH;
2319 max_devs = 0;
2320 } else if (!strcmp(buf, "mtd")) {
2321 type = IF_MTD;
2322 max_devs = 0;
2323 } else if (!strcmp(buf, "sd")) {
2324 type = IF_SD;
2325 max_devs = 0;
2326 } else if (!strcmp(buf, "virtio")) {
2327 type = IF_VIRTIO;
2328 max_devs = 0;
2329 } else if (!strcmp(buf, "xen")) {
2330 type = IF_XEN;
2331 max_devs = 0;
2332 } else {
2333 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2334 return -1;
2338 if (get_param_value(buf, sizeof(buf), "index", str)) {
2339 index = strtol(buf, NULL, 0);
2340 if (index < 0) {
2341 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2342 return -1;
2346 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2347 cyls = strtol(buf, NULL, 0);
2350 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2351 heads = strtol(buf, NULL, 0);
2354 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2355 secs = strtol(buf, NULL, 0);
2358 if (cyls || heads || secs) {
2359 if (cyls < 1 || cyls > 16383) {
2360 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2361 return -1;
2363 if (heads < 1 || heads > 16) {
2364 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2365 return -1;
2367 if (secs < 1 || secs > 63) {
2368 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2369 return -1;
2373 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2374 if (!cyls) {
2375 fprintf(stderr,
2376 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2377 str);
2378 return -1;
2380 if (!strcmp(buf, "none"))
2381 translation = BIOS_ATA_TRANSLATION_NONE;
2382 else if (!strcmp(buf, "lba"))
2383 translation = BIOS_ATA_TRANSLATION_LBA;
2384 else if (!strcmp(buf, "auto"))
2385 translation = BIOS_ATA_TRANSLATION_AUTO;
2386 else {
2387 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2388 return -1;
2392 if (get_param_value(buf, sizeof(buf), "media", str)) {
2393 if (!strcmp(buf, "disk")) {
2394 media = MEDIA_DISK;
2395 } else if (!strcmp(buf, "cdrom")) {
2396 if (cyls || secs || heads) {
2397 fprintf(stderr,
2398 "qemu: '%s' invalid physical CHS format\n", str);
2399 return -1;
2401 media = MEDIA_CDROM;
2402 } else {
2403 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2404 return -1;
2408 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2409 if (!strcmp(buf, "on"))
2410 snapshot = 1;
2411 else if (!strcmp(buf, "off"))
2412 snapshot = 0;
2413 else {
2414 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2415 return -1;
2419 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2420 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2421 cache = 0;
2422 else if (!strcmp(buf, "writethrough"))
2423 cache = 1;
2424 else if (!strcmp(buf, "writeback"))
2425 cache = 2;
2426 else {
2427 fprintf(stderr, "qemu: invalid cache option\n");
2428 return -1;
2432 if (get_param_value(buf, sizeof(buf), "format", str)) {
2433 if (strcmp(buf, "?") == 0) {
2434 fprintf(stderr, "qemu: Supported formats:");
2435 bdrv_iterate_format(bdrv_format_print, NULL);
2436 fprintf(stderr, "\n");
2437 return -1;
2439 drv = bdrv_find_format(buf);
2440 if (!drv) {
2441 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2442 return -1;
2446 if (arg->file == NULL)
2447 get_param_value(file, sizeof(file), "file", str);
2448 else
2449 pstrcpy(file, sizeof(file), arg->file);
2451 if (!get_param_value(serial, sizeof(serial), "serial", str))
2452 memset(serial, 0, sizeof(serial));
2454 onerror = BLOCK_ERR_STOP_ENOSPC;
2455 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2456 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2457 fprintf(stderr, "werror is no supported by this format\n");
2458 return -1;
2460 if (!strcmp(buf, "ignore"))
2461 onerror = BLOCK_ERR_IGNORE;
2462 else if (!strcmp(buf, "enospc"))
2463 onerror = BLOCK_ERR_STOP_ENOSPC;
2464 else if (!strcmp(buf, "stop"))
2465 onerror = BLOCK_ERR_STOP_ANY;
2466 else if (!strcmp(buf, "report"))
2467 onerror = BLOCK_ERR_REPORT;
2468 else {
2469 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2470 return -1;
2474 /* compute bus and unit according index */
2476 if (index != -1) {
2477 if (bus_id != 0 || unit_id != -1) {
2478 fprintf(stderr,
2479 "qemu: '%s' index cannot be used with bus and unit\n", str);
2480 return -1;
2482 if (max_devs == 0)
2484 unit_id = index;
2485 bus_id = 0;
2486 } else {
2487 unit_id = index % max_devs;
2488 bus_id = index / max_devs;
2492 /* if user doesn't specify a unit_id,
2493 * try to find the first free
2496 if (unit_id == -1) {
2497 unit_id = 0;
2498 while (drive_get_index(type, bus_id, unit_id) != -1) {
2499 unit_id++;
2500 if (max_devs && unit_id >= max_devs) {
2501 unit_id -= max_devs;
2502 bus_id++;
2507 /* check unit id */
2509 if (max_devs && unit_id >= max_devs) {
2510 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2511 str, unit_id, max_devs - 1);
2512 return -1;
2516 * ignore multiple definitions
2519 if (drive_get_index(type, bus_id, unit_id) != -1)
2520 return -2;
2522 /* init */
2524 if (type == IF_IDE || type == IF_SCSI)
2525 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2526 if (max_devs)
2527 snprintf(buf, sizeof(buf), "%s%i%s%i",
2528 devname, bus_id, mediastr, unit_id);
2529 else
2530 snprintf(buf, sizeof(buf), "%s%s%i",
2531 devname, mediastr, unit_id);
2532 bdrv = bdrv_new(buf);
2533 drives_table_idx = drive_get_free_idx();
2534 drives_table[drives_table_idx].bdrv = bdrv;
2535 drives_table[drives_table_idx].type = type;
2536 drives_table[drives_table_idx].bus = bus_id;
2537 drives_table[drives_table_idx].unit = unit_id;
2538 drives_table[drives_table_idx].onerror = onerror;
2539 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2540 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2541 nb_drives++;
2543 switch(type) {
2544 case IF_IDE:
2545 case IF_SCSI:
2546 case IF_XEN:
2547 switch(media) {
2548 case MEDIA_DISK:
2549 if (cyls != 0) {
2550 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2551 bdrv_set_translation_hint(bdrv, translation);
2553 break;
2554 case MEDIA_CDROM:
2555 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2556 break;
2558 break;
2559 case IF_SD:
2560 /* FIXME: This isn't really a floppy, but it's a reasonable
2561 approximation. */
2562 case IF_FLOPPY:
2563 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2564 break;
2565 case IF_PFLASH:
2566 case IF_MTD:
2567 case IF_VIRTIO:
2568 break;
2570 if (!file[0])
2571 return -2;
2572 bdrv_flags = 0;
2573 if (snapshot) {
2574 bdrv_flags |= BDRV_O_SNAPSHOT;
2575 cache = 2; /* always use write-back with snapshot */
2577 if (cache == 0) /* no caching */
2578 bdrv_flags |= BDRV_O_NOCACHE;
2579 else if (cache == 2) /* write-back */
2580 bdrv_flags |= BDRV_O_CACHE_WB;
2581 else if (cache == 3) /* not specified */
2582 bdrv_flags |= BDRV_O_CACHE_DEF;
2583 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2584 fprintf(stderr, "qemu: could not open disk image %s\n",
2585 file);
2586 return -1;
2588 if (bdrv_key_required(bdrv))
2589 autostart = 0;
2590 return drives_table_idx;
2593 static void numa_add(const char *optarg)
2595 char option[128];
2596 char *endptr;
2597 unsigned long long value, endvalue;
2598 int nodenr;
2600 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2601 if (!strcmp(option, "node")) {
2602 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2603 nodenr = nb_numa_nodes;
2604 } else {
2605 nodenr = strtoull(option, NULL, 10);
2608 if (get_param_value(option, 128, "mem", optarg) == 0) {
2609 node_mem[nodenr] = 0;
2610 } else {
2611 value = strtoull(option, &endptr, 0);
2612 switch (*endptr) {
2613 case 0: case 'M': case 'm':
2614 value <<= 20;
2615 break;
2616 case 'G': case 'g':
2617 value <<= 30;
2618 break;
2620 node_mem[nodenr] = value;
2622 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2623 node_cpumask[nodenr] = 0;
2624 } else {
2625 value = strtoull(option, &endptr, 10);
2626 if (value >= 64) {
2627 value = 63;
2628 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2629 } else {
2630 if (*endptr == '-') {
2631 endvalue = strtoull(endptr+1, &endptr, 10);
2632 if (endvalue >= 63) {
2633 endvalue = 62;
2634 fprintf(stderr,
2635 "only 63 CPUs in NUMA mode supported.\n");
2637 value = (1 << (endvalue + 1)) - (1 << value);
2638 } else {
2639 value = 1 << value;
2642 node_cpumask[nodenr] = value;
2644 nb_numa_nodes++;
2646 return;
2649 /***********************************************************/
2650 /* USB devices */
2652 static USBPort *used_usb_ports;
2653 static USBPort *free_usb_ports;
2655 /* ??? Maybe change this to register a hub to keep track of the topology. */
2656 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2657 usb_attachfn attach)
2659 port->opaque = opaque;
2660 port->index = index;
2661 port->attach = attach;
2662 port->next = free_usb_ports;
2663 free_usb_ports = port;
2666 int usb_device_add_dev(USBDevice *dev)
2668 USBPort *port;
2670 /* Find a USB port to add the device to. */
2671 port = free_usb_ports;
2672 if (!port->next) {
2673 USBDevice *hub;
2675 /* Create a new hub and chain it on. */
2676 free_usb_ports = NULL;
2677 port->next = used_usb_ports;
2678 used_usb_ports = port;
2680 hub = usb_hub_init(VM_USB_HUB_SIZE);
2681 usb_attach(port, hub);
2682 port = free_usb_ports;
2685 free_usb_ports = port->next;
2686 port->next = used_usb_ports;
2687 used_usb_ports = port;
2688 usb_attach(port, dev);
2689 return 0;
2692 static void usb_msd_password_cb(void *opaque, int err)
2694 USBDevice *dev = opaque;
2696 if (!err)
2697 usb_device_add_dev(dev);
2698 else
2699 dev->handle_destroy(dev);
2702 static int usb_device_add(const char *devname, int is_hotplug)
2704 const char *p;
2705 USBDevice *dev;
2707 if (!free_usb_ports)
2708 return -1;
2710 if (strstart(devname, "host:", &p)) {
2711 dev = usb_host_device_open(p);
2712 } else if (!strcmp(devname, "mouse")) {
2713 dev = usb_mouse_init();
2714 } else if (!strcmp(devname, "tablet")) {
2715 dev = usb_tablet_init();
2716 } else if (!strcmp(devname, "keyboard")) {
2717 dev = usb_keyboard_init();
2718 } else if (strstart(devname, "disk:", &p)) {
2719 BlockDriverState *bs;
2721 dev = usb_msd_init(p);
2722 if (!dev)
2723 return -1;
2724 bs = usb_msd_get_bdrv(dev);
2725 if (bdrv_key_required(bs)) {
2726 autostart = 0;
2727 if (is_hotplug) {
2728 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2729 dev);
2730 return 0;
2733 } else if (!strcmp(devname, "wacom-tablet")) {
2734 dev = usb_wacom_init();
2735 } else if (strstart(devname, "serial:", &p)) {
2736 dev = usb_serial_init(p);
2737 #ifdef CONFIG_BRLAPI
2738 } else if (!strcmp(devname, "braille")) {
2739 dev = usb_baum_init();
2740 #endif
2741 } else if (strstart(devname, "net:", &p)) {
2742 int nic = nb_nics;
2744 if (net_client_init("nic", p) < 0)
2745 return -1;
2746 nd_table[nic].model = "usb";
2747 dev = usb_net_init(&nd_table[nic]);
2748 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2749 dev = usb_bt_init(devname[2] ? hci_init(p) :
2750 bt_new_hci(qemu_find_bt_vlan(0)));
2751 } else {
2752 return -1;
2754 if (!dev)
2755 return -1;
2757 return usb_device_add_dev(dev);
2760 int usb_device_del_addr(int bus_num, int addr)
2762 USBPort *port;
2763 USBPort **lastp;
2764 USBDevice *dev;
2766 if (!used_usb_ports)
2767 return -1;
2769 if (bus_num != 0)
2770 return -1;
2772 lastp = &used_usb_ports;
2773 port = used_usb_ports;
2774 while (port && port->dev->addr != addr) {
2775 lastp = &port->next;
2776 port = port->next;
2779 if (!port)
2780 return -1;
2782 dev = port->dev;
2783 *lastp = port->next;
2784 usb_attach(port, NULL);
2785 dev->handle_destroy(dev);
2786 port->next = free_usb_ports;
2787 free_usb_ports = port;
2788 return 0;
2791 static int usb_device_del(const char *devname)
2793 int bus_num, addr;
2794 const char *p;
2796 if (strstart(devname, "host:", &p))
2797 return usb_host_device_close(p);
2799 if (!used_usb_ports)
2800 return -1;
2802 p = strchr(devname, '.');
2803 if (!p)
2804 return -1;
2805 bus_num = strtoul(devname, NULL, 0);
2806 addr = strtoul(p + 1, NULL, 0);
2808 return usb_device_del_addr(bus_num, addr);
2811 void do_usb_add(Monitor *mon, const char *devname)
2813 usb_device_add(devname, 1);
2816 void do_usb_del(Monitor *mon, const char *devname)
2818 usb_device_del(devname);
2821 void usb_info(Monitor *mon)
2823 USBDevice *dev;
2824 USBPort *port;
2825 const char *speed_str;
2827 if (!usb_enabled) {
2828 monitor_printf(mon, "USB support not enabled\n");
2829 return;
2832 for (port = used_usb_ports; port; port = port->next) {
2833 dev = port->dev;
2834 if (!dev)
2835 continue;
2836 switch(dev->speed) {
2837 case USB_SPEED_LOW:
2838 speed_str = "1.5";
2839 break;
2840 case USB_SPEED_FULL:
2841 speed_str = "12";
2842 break;
2843 case USB_SPEED_HIGH:
2844 speed_str = "480";
2845 break;
2846 default:
2847 speed_str = "?";
2848 break;
2850 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2851 0, dev->addr, speed_str, dev->devname);
2855 /***********************************************************/
2856 /* PCMCIA/Cardbus */
2858 static struct pcmcia_socket_entry_s {
2859 struct pcmcia_socket_s *socket;
2860 struct pcmcia_socket_entry_s *next;
2861 } *pcmcia_sockets = 0;
2863 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2865 struct pcmcia_socket_entry_s *entry;
2867 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2868 entry->socket = socket;
2869 entry->next = pcmcia_sockets;
2870 pcmcia_sockets = entry;
2873 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2875 struct pcmcia_socket_entry_s *entry, **ptr;
2877 ptr = &pcmcia_sockets;
2878 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2879 if (entry->socket == socket) {
2880 *ptr = entry->next;
2881 qemu_free(entry);
2885 void pcmcia_info(Monitor *mon)
2887 struct pcmcia_socket_entry_s *iter;
2889 if (!pcmcia_sockets)
2890 monitor_printf(mon, "No PCMCIA sockets\n");
2892 for (iter = pcmcia_sockets; iter; iter = iter->next)
2893 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2894 iter->socket->attached ? iter->socket->card_string :
2895 "Empty");
2898 /***********************************************************/
2899 /* register display */
2901 struct DisplayAllocator default_allocator = {
2902 defaultallocator_create_displaysurface,
2903 defaultallocator_resize_displaysurface,
2904 defaultallocator_free_displaysurface
2907 void register_displaystate(DisplayState *ds)
2909 DisplayState **s;
2910 s = &display_state;
2911 while (*s != NULL)
2912 s = &(*s)->next;
2913 ds->next = NULL;
2914 *s = ds;
2917 DisplayState *get_displaystate(void)
2919 return display_state;
2922 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2924 if(ds->allocator == &default_allocator) ds->allocator = da;
2925 return ds->allocator;
2928 /* dumb display */
2930 static void dumb_display_init(void)
2932 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2933 ds->allocator = &default_allocator;
2934 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2935 register_displaystate(ds);
2938 /***********************************************************/
2939 /* I/O handling */
2941 typedef struct IOHandlerRecord {
2942 int fd;
2943 IOCanRWHandler *fd_read_poll;
2944 IOHandler *fd_read;
2945 IOHandler *fd_write;
2946 int deleted;
2947 void *opaque;
2948 /* temporary data */
2949 struct pollfd *ufd;
2950 struct IOHandlerRecord *next;
2951 } IOHandlerRecord;
2953 static IOHandlerRecord *first_io_handler;
2955 /* XXX: fd_read_poll should be suppressed, but an API change is
2956 necessary in the character devices to suppress fd_can_read(). */
2957 int qemu_set_fd_handler2(int fd,
2958 IOCanRWHandler *fd_read_poll,
2959 IOHandler *fd_read,
2960 IOHandler *fd_write,
2961 void *opaque)
2963 IOHandlerRecord **pioh, *ioh;
2965 if (!fd_read && !fd_write) {
2966 pioh = &first_io_handler;
2967 for(;;) {
2968 ioh = *pioh;
2969 if (ioh == NULL)
2970 break;
2971 if (ioh->fd == fd) {
2972 ioh->deleted = 1;
2973 break;
2975 pioh = &ioh->next;
2977 } else {
2978 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2979 if (ioh->fd == fd)
2980 goto found;
2982 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2983 ioh->next = first_io_handler;
2984 first_io_handler = ioh;
2985 found:
2986 ioh->fd = fd;
2987 ioh->fd_read_poll = fd_read_poll;
2988 ioh->fd_read = fd_read;
2989 ioh->fd_write = fd_write;
2990 ioh->opaque = opaque;
2991 ioh->deleted = 0;
2993 return 0;
2996 int qemu_set_fd_handler(int fd,
2997 IOHandler *fd_read,
2998 IOHandler *fd_write,
2999 void *opaque)
3001 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3004 #ifdef _WIN32
3005 /***********************************************************/
3006 /* Polling handling */
3008 typedef struct PollingEntry {
3009 PollingFunc *func;
3010 void *opaque;
3011 struct PollingEntry *next;
3012 } PollingEntry;
3014 static PollingEntry *first_polling_entry;
3016 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3018 PollingEntry **ppe, *pe;
3019 pe = qemu_mallocz(sizeof(PollingEntry));
3020 pe->func = func;
3021 pe->opaque = opaque;
3022 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3023 *ppe = pe;
3024 return 0;
3027 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3029 PollingEntry **ppe, *pe;
3030 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3031 pe = *ppe;
3032 if (pe->func == func && pe->opaque == opaque) {
3033 *ppe = pe->next;
3034 qemu_free(pe);
3035 break;
3040 /***********************************************************/
3041 /* Wait objects support */
3042 typedef struct WaitObjects {
3043 int num;
3044 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3045 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3046 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3047 } WaitObjects;
3049 static WaitObjects wait_objects = {0};
3051 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3053 WaitObjects *w = &wait_objects;
3055 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3056 return -1;
3057 w->events[w->num] = handle;
3058 w->func[w->num] = func;
3059 w->opaque[w->num] = opaque;
3060 w->num++;
3061 return 0;
3064 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3066 int i, found;
3067 WaitObjects *w = &wait_objects;
3069 found = 0;
3070 for (i = 0; i < w->num; i++) {
3071 if (w->events[i] == handle)
3072 found = 1;
3073 if (found) {
3074 w->events[i] = w->events[i + 1];
3075 w->func[i] = w->func[i + 1];
3076 w->opaque[i] = w->opaque[i + 1];
3079 if (found)
3080 w->num--;
3082 #endif
3084 /***********************************************************/
3085 /* ram save/restore */
3087 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3089 int v;
3091 v = qemu_get_byte(f);
3092 switch(v) {
3093 case 0:
3094 if (qemu_get_buffer(f, buf, len) != len)
3095 return -EIO;
3096 break;
3097 case 1:
3098 v = qemu_get_byte(f);
3099 memset(buf, v, len);
3100 break;
3101 default:
3102 return -EINVAL;
3105 if (qemu_file_has_error(f))
3106 return -EIO;
3108 return 0;
3111 static int ram_load_v1(QEMUFile *f, void *opaque)
3113 int ret;
3114 ram_addr_t i;
3116 if (qemu_get_be32(f) != last_ram_offset)
3117 return -EINVAL;
3118 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3119 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3120 if (ret)
3121 return ret;
3123 return 0;
3126 #define BDRV_HASH_BLOCK_SIZE 1024
3127 #define IOBUF_SIZE 4096
3128 #define RAM_CBLOCK_MAGIC 0xfabe
3130 typedef struct RamDecompressState {
3131 z_stream zstream;
3132 QEMUFile *f;
3133 uint8_t buf[IOBUF_SIZE];
3134 } RamDecompressState;
3136 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3138 int ret;
3139 memset(s, 0, sizeof(*s));
3140 s->f = f;
3141 ret = inflateInit(&s->zstream);
3142 if (ret != Z_OK)
3143 return -1;
3144 return 0;
3147 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3149 int ret, clen;
3151 s->zstream.avail_out = len;
3152 s->zstream.next_out = buf;
3153 while (s->zstream.avail_out > 0) {
3154 if (s->zstream.avail_in == 0) {
3155 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3156 return -1;
3157 clen = qemu_get_be16(s->f);
3158 if (clen > IOBUF_SIZE)
3159 return -1;
3160 qemu_get_buffer(s->f, s->buf, clen);
3161 s->zstream.avail_in = clen;
3162 s->zstream.next_in = s->buf;
3164 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3165 if (ret != Z_OK && ret != Z_STREAM_END) {
3166 return -1;
3169 return 0;
3172 static void ram_decompress_close(RamDecompressState *s)
3174 inflateEnd(&s->zstream);
3177 #define RAM_SAVE_FLAG_FULL 0x01
3178 #define RAM_SAVE_FLAG_COMPRESS 0x02
3179 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3180 #define RAM_SAVE_FLAG_PAGE 0x08
3181 #define RAM_SAVE_FLAG_EOS 0x10
3183 static int is_dup_page(uint8_t *page, uint8_t ch)
3185 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3186 uint32_t *array = (uint32_t *)page;
3187 int i;
3189 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3190 if (array[i] != val)
3191 return 0;
3194 return 1;
3197 static int ram_save_block(QEMUFile *f)
3199 static ram_addr_t current_addr = 0;
3200 ram_addr_t saved_addr = current_addr;
3201 ram_addr_t addr = 0;
3202 int found = 0;
3204 while (addr < last_ram_offset) {
3205 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3206 uint8_t *p;
3208 cpu_physical_memory_reset_dirty(current_addr,
3209 current_addr + TARGET_PAGE_SIZE,
3210 MIGRATION_DIRTY_FLAG);
3212 p = qemu_get_ram_ptr(current_addr);
3214 if (is_dup_page(p, *p)) {
3215 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3216 qemu_put_byte(f, *p);
3217 } else {
3218 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3219 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3222 found = 1;
3223 break;
3225 addr += TARGET_PAGE_SIZE;
3226 current_addr = (saved_addr + addr) % last_ram_offset;
3229 return found;
3232 static ram_addr_t ram_save_threshold = 10;
3234 static ram_addr_t ram_save_remaining(void)
3236 ram_addr_t addr;
3237 ram_addr_t count = 0;
3239 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3240 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3241 count++;
3244 return count;
3247 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3249 ram_addr_t addr;
3251 if (stage == 1) {
3252 /* Make sure all dirty bits are set */
3253 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3254 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3255 cpu_physical_memory_set_dirty(addr);
3258 /* Enable dirty memory tracking */
3259 cpu_physical_memory_set_dirty_tracking(1);
3261 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3264 while (!qemu_file_rate_limit(f)) {
3265 int ret;
3267 ret = ram_save_block(f);
3268 if (ret == 0) /* no more blocks */
3269 break;
3272 /* try transferring iterative blocks of memory */
3274 if (stage == 3) {
3276 /* flush all remaining blocks regardless of rate limiting */
3277 while (ram_save_block(f) != 0);
3278 cpu_physical_memory_set_dirty_tracking(0);
3281 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3283 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3286 static int ram_load_dead(QEMUFile *f, void *opaque)
3288 RamDecompressState s1, *s = &s1;
3289 uint8_t buf[10];
3290 ram_addr_t i;
3292 if (ram_decompress_open(s, f) < 0)
3293 return -EINVAL;
3294 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3295 if (ram_decompress_buf(s, buf, 1) < 0) {
3296 fprintf(stderr, "Error while reading ram block header\n");
3297 goto error;
3299 if (buf[0] == 0) {
3300 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3301 BDRV_HASH_BLOCK_SIZE) < 0) {
3302 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3303 goto error;
3305 } else {
3306 error:
3307 printf("Error block header\n");
3308 return -EINVAL;
3311 ram_decompress_close(s);
3313 return 0;
3316 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3318 ram_addr_t addr;
3319 int flags;
3321 if (version_id == 1)
3322 return ram_load_v1(f, opaque);
3324 if (version_id == 2) {
3325 if (qemu_get_be32(f) != last_ram_offset)
3326 return -EINVAL;
3327 return ram_load_dead(f, opaque);
3330 if (version_id != 3)
3331 return -EINVAL;
3333 do {
3334 addr = qemu_get_be64(f);
3336 flags = addr & ~TARGET_PAGE_MASK;
3337 addr &= TARGET_PAGE_MASK;
3339 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3340 if (addr != last_ram_offset)
3341 return -EINVAL;
3344 if (flags & RAM_SAVE_FLAG_FULL) {
3345 if (ram_load_dead(f, opaque) < 0)
3346 return -EINVAL;
3349 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3350 uint8_t ch = qemu_get_byte(f);
3351 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3352 } else if (flags & RAM_SAVE_FLAG_PAGE)
3353 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3354 } while (!(flags & RAM_SAVE_FLAG_EOS));
3356 return 0;
3359 void qemu_service_io(void)
3361 qemu_notify_event();
3364 /***********************************************************/
3365 /* bottom halves (can be seen as timers which expire ASAP) */
3367 struct QEMUBH {
3368 QEMUBHFunc *cb;
3369 void *opaque;
3370 int scheduled;
3371 int idle;
3372 int deleted;
3373 QEMUBH *next;
3376 static QEMUBH *first_bh = NULL;
3378 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3380 QEMUBH *bh;
3381 bh = qemu_mallocz(sizeof(QEMUBH));
3382 bh->cb = cb;
3383 bh->opaque = opaque;
3384 bh->next = first_bh;
3385 first_bh = bh;
3386 return bh;
3389 int qemu_bh_poll(void)
3391 QEMUBH *bh, **bhp;
3392 int ret;
3394 ret = 0;
3395 for (bh = first_bh; bh; bh = bh->next) {
3396 if (!bh->deleted && bh->scheduled) {
3397 bh->scheduled = 0;
3398 if (!bh->idle)
3399 ret = 1;
3400 bh->idle = 0;
3401 bh->cb(bh->opaque);
3405 /* remove deleted bhs */
3406 bhp = &first_bh;
3407 while (*bhp) {
3408 bh = *bhp;
3409 if (bh->deleted) {
3410 *bhp = bh->next;
3411 qemu_free(bh);
3412 } else
3413 bhp = &bh->next;
3416 return ret;
3419 void qemu_bh_schedule_idle(QEMUBH *bh)
3421 if (bh->scheduled)
3422 return;
3423 bh->scheduled = 1;
3424 bh->idle = 1;
3427 void qemu_bh_schedule(QEMUBH *bh)
3429 if (bh->scheduled)
3430 return;
3431 bh->scheduled = 1;
3432 bh->idle = 0;
3433 /* stop the currently executing CPU to execute the BH ASAP */
3434 qemu_notify_event();
3437 void qemu_bh_cancel(QEMUBH *bh)
3439 bh->scheduled = 0;
3442 void qemu_bh_delete(QEMUBH *bh)
3444 bh->scheduled = 0;
3445 bh->deleted = 1;
3448 static void qemu_bh_update_timeout(int *timeout)
3450 QEMUBH *bh;
3452 for (bh = first_bh; bh; bh = bh->next) {
3453 if (!bh->deleted && bh->scheduled) {
3454 if (bh->idle) {
3455 /* idle bottom halves will be polled at least
3456 * every 10ms */
3457 *timeout = MIN(10, *timeout);
3458 } else {
3459 /* non-idle bottom halves will be executed
3460 * immediately */
3461 *timeout = 0;
3462 break;
3468 /***********************************************************/
3469 /* machine registration */
3471 static QEMUMachine *first_machine = NULL;
3472 QEMUMachine *current_machine = NULL;
3474 int qemu_register_machine(QEMUMachine *m)
3476 QEMUMachine **pm;
3477 pm = &first_machine;
3478 while (*pm != NULL)
3479 pm = &(*pm)->next;
3480 m->next = NULL;
3481 *pm = m;
3482 return 0;
3485 static QEMUMachine *find_machine(const char *name)
3487 QEMUMachine *m;
3489 for(m = first_machine; m != NULL; m = m->next) {
3490 if (!strcmp(m->name, name))
3491 return m;
3493 return NULL;
3496 /***********************************************************/
3497 /* main execution loop */
3499 static void gui_update(void *opaque)
3501 uint64_t interval = GUI_REFRESH_INTERVAL;
3502 DisplayState *ds = opaque;
3503 DisplayChangeListener *dcl = ds->listeners;
3505 dpy_refresh(ds);
3507 while (dcl != NULL) {
3508 if (dcl->gui_timer_interval &&
3509 dcl->gui_timer_interval < interval)
3510 interval = dcl->gui_timer_interval;
3511 dcl = dcl->next;
3513 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3516 static void nographic_update(void *opaque)
3518 uint64_t interval = GUI_REFRESH_INTERVAL;
3520 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3523 struct vm_change_state_entry {
3524 VMChangeStateHandler *cb;
3525 void *opaque;
3526 LIST_ENTRY (vm_change_state_entry) entries;
3529 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3531 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3532 void *opaque)
3534 VMChangeStateEntry *e;
3536 e = qemu_mallocz(sizeof (*e));
3538 e->cb = cb;
3539 e->opaque = opaque;
3540 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3541 return e;
3544 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3546 LIST_REMOVE (e, entries);
3547 qemu_free (e);
3550 static void vm_state_notify(int running, int reason)
3552 VMChangeStateEntry *e;
3554 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3555 e->cb(e->opaque, running, reason);
3559 static void resume_all_vcpus(void);
3560 static void pause_all_vcpus(void);
3562 void vm_start(void)
3564 if (!vm_running) {
3565 cpu_enable_ticks();
3566 vm_running = 1;
3567 vm_state_notify(1, 0);
3568 qemu_rearm_alarm_timer(alarm_timer);
3569 resume_all_vcpus();
3573 /* reset/shutdown handler */
3575 typedef struct QEMUResetEntry {
3576 QEMUResetHandler *func;
3577 void *opaque;
3578 struct QEMUResetEntry *next;
3579 } QEMUResetEntry;
3581 static QEMUResetEntry *first_reset_entry;
3582 static int reset_requested;
3583 static int shutdown_requested;
3584 static int powerdown_requested;
3585 static int debug_requested;
3586 static int vmstop_requested;
3588 int qemu_shutdown_requested(void)
3590 int r = shutdown_requested;
3591 shutdown_requested = 0;
3592 return r;
3595 int qemu_reset_requested(void)
3597 int r = reset_requested;
3598 reset_requested = 0;
3599 return r;
3602 int qemu_powerdown_requested(void)
3604 int r = powerdown_requested;
3605 powerdown_requested = 0;
3606 return r;
3609 static int qemu_debug_requested(void)
3611 int r = debug_requested;
3612 debug_requested = 0;
3613 return r;
3616 static int qemu_vmstop_requested(void)
3618 int r = vmstop_requested;
3619 vmstop_requested = 0;
3620 return r;
3623 static void do_vm_stop(int reason)
3625 if (vm_running) {
3626 cpu_disable_ticks();
3627 vm_running = 0;
3628 pause_all_vcpus();
3629 vm_state_notify(0, reason);
3633 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3635 QEMUResetEntry **pre, *re;
3637 pre = &first_reset_entry;
3638 while (*pre != NULL)
3639 pre = &(*pre)->next;
3640 re = qemu_mallocz(sizeof(QEMUResetEntry));
3641 re->func = func;
3642 re->opaque = opaque;
3643 re->next = NULL;
3644 *pre = re;
3647 void qemu_system_reset(void)
3649 QEMUResetEntry *re;
3651 /* reset all devices */
3652 for(re = first_reset_entry; re != NULL; re = re->next) {
3653 re->func(re->opaque);
3655 if (kvm_enabled())
3656 kvm_sync_vcpus();
3659 void qemu_system_reset_request(void)
3661 if (no_reboot) {
3662 shutdown_requested = 1;
3663 } else {
3664 reset_requested = 1;
3666 qemu_notify_event();
3669 void qemu_system_shutdown_request(void)
3671 shutdown_requested = 1;
3672 qemu_notify_event();
3675 void qemu_system_powerdown_request(void)
3677 powerdown_requested = 1;
3678 qemu_notify_event();
3681 #ifdef CONFIG_IOTHREAD
3682 static void qemu_system_vmstop_request(int reason)
3684 vmstop_requested = reason;
3685 qemu_notify_event();
3687 #endif
3689 #ifndef _WIN32
3690 static int io_thread_fd = -1;
3692 static void qemu_event_increment(void)
3694 static const char byte = 0;
3696 if (io_thread_fd == -1)
3697 return;
3699 write(io_thread_fd, &byte, sizeof(byte));
3702 static void qemu_event_read(void *opaque)
3704 int fd = (unsigned long)opaque;
3705 ssize_t len;
3707 /* Drain the notify pipe */
3708 do {
3709 char buffer[512];
3710 len = read(fd, buffer, sizeof(buffer));
3711 } while ((len == -1 && errno == EINTR) || len > 0);
3714 static int qemu_event_init(void)
3716 int err;
3717 int fds[2];
3719 err = pipe(fds);
3720 if (err == -1)
3721 return -errno;
3723 err = fcntl_setfl(fds[0], O_NONBLOCK);
3724 if (err < 0)
3725 goto fail;
3727 err = fcntl_setfl(fds[1], O_NONBLOCK);
3728 if (err < 0)
3729 goto fail;
3731 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3732 (void *)(unsigned long)fds[0]);
3734 io_thread_fd = fds[1];
3735 return 0;
3737 fail:
3738 close(fds[0]);
3739 close(fds[1]);
3740 return err;
3742 #else
3743 HANDLE qemu_event_handle;
3745 static void dummy_event_handler(void *opaque)
3749 static int qemu_event_init(void)
3751 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3752 if (!qemu_event_handle) {
3753 perror("Failed CreateEvent");
3754 return -1;
3756 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3757 return 0;
3760 static void qemu_event_increment(void)
3762 SetEvent(qemu_event_handle);
3764 #endif
3766 static int cpu_can_run(CPUState *env)
3768 if (env->stop)
3769 return 0;
3770 if (env->stopped)
3771 return 0;
3772 return 1;
3775 #ifndef CONFIG_IOTHREAD
3776 static int qemu_init_main_loop(void)
3778 return qemu_event_init();
3781 void qemu_init_vcpu(void *_env)
3783 CPUState *env = _env;
3785 if (kvm_enabled())
3786 kvm_init_vcpu(env);
3787 return;
3790 int qemu_cpu_self(void *env)
3792 return 1;
3795 static void resume_all_vcpus(void)
3799 static void pause_all_vcpus(void)
3803 void qemu_cpu_kick(void *env)
3805 return;
3808 void qemu_notify_event(void)
3810 CPUState *env = cpu_single_env;
3812 if (env) {
3813 cpu_exit(env);
3814 #ifdef USE_KQEMU
3815 if (env->kqemu_enabled)
3816 kqemu_cpu_interrupt(env);
3817 #endif
3821 #define qemu_mutex_lock_iothread() do { } while (0)
3822 #define qemu_mutex_unlock_iothread() do { } while (0)
3824 void vm_stop(int reason)
3826 do_vm_stop(reason);
3829 #else /* CONFIG_IOTHREAD */
3831 #include "qemu-thread.h"
3833 QemuMutex qemu_global_mutex;
3834 static QemuMutex qemu_fair_mutex;
3836 static QemuThread io_thread;
3838 static QemuThread *tcg_cpu_thread;
3839 static QemuCond *tcg_halt_cond;
3841 static int qemu_system_ready;
3842 /* cpu creation */
3843 static QemuCond qemu_cpu_cond;
3844 /* system init */
3845 static QemuCond qemu_system_cond;
3846 static QemuCond qemu_pause_cond;
3848 static void block_io_signals(void);
3849 static void unblock_io_signals(void);
3850 static int tcg_has_work(void);
3852 static int qemu_init_main_loop(void)
3854 int ret;
3856 ret = qemu_event_init();
3857 if (ret)
3858 return ret;
3860 qemu_cond_init(&qemu_pause_cond);
3861 qemu_mutex_init(&qemu_fair_mutex);
3862 qemu_mutex_init(&qemu_global_mutex);
3863 qemu_mutex_lock(&qemu_global_mutex);
3865 unblock_io_signals();
3866 qemu_thread_self(&io_thread);
3868 return 0;
3871 static void qemu_wait_io_event(CPUState *env)
3873 while (!tcg_has_work())
3874 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3876 qemu_mutex_unlock(&qemu_global_mutex);
3879 * Users of qemu_global_mutex can be starved, having no chance
3880 * to acquire it since this path will get to it first.
3881 * So use another lock to provide fairness.
3883 qemu_mutex_lock(&qemu_fair_mutex);
3884 qemu_mutex_unlock(&qemu_fair_mutex);
3886 qemu_mutex_lock(&qemu_global_mutex);
3887 if (env->stop) {
3888 env->stop = 0;
3889 env->stopped = 1;
3890 qemu_cond_signal(&qemu_pause_cond);
3894 static int qemu_cpu_exec(CPUState *env);
3896 static void *kvm_cpu_thread_fn(void *arg)
3898 CPUState *env = arg;
3900 block_io_signals();
3901 qemu_thread_self(env->thread);
3903 /* signal CPU creation */
3904 qemu_mutex_lock(&qemu_global_mutex);
3905 env->created = 1;
3906 qemu_cond_signal(&qemu_cpu_cond);
3908 /* and wait for machine initialization */
3909 while (!qemu_system_ready)
3910 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3912 while (1) {
3913 if (cpu_can_run(env))
3914 qemu_cpu_exec(env);
3915 qemu_wait_io_event(env);
3918 return NULL;
3921 static void tcg_cpu_exec(void);
3923 static void *tcg_cpu_thread_fn(void *arg)
3925 CPUState *env = arg;
3927 block_io_signals();
3928 qemu_thread_self(env->thread);
3930 /* signal CPU creation */
3931 qemu_mutex_lock(&qemu_global_mutex);
3932 for (env = first_cpu; env != NULL; env = env->next_cpu)
3933 env->created = 1;
3934 qemu_cond_signal(&qemu_cpu_cond);
3936 /* and wait for machine initialization */
3937 while (!qemu_system_ready)
3938 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3940 while (1) {
3941 tcg_cpu_exec();
3942 qemu_wait_io_event(cur_cpu);
3945 return NULL;
3948 void qemu_cpu_kick(void *_env)
3950 CPUState *env = _env;
3951 qemu_cond_broadcast(env->halt_cond);
3952 if (kvm_enabled())
3953 qemu_thread_signal(env->thread, SIGUSR1);
3956 int qemu_cpu_self(void *env)
3958 return (cpu_single_env != NULL);
3961 static void cpu_signal(int sig)
3963 if (cpu_single_env)
3964 cpu_exit(cpu_single_env);
3967 static void block_io_signals(void)
3969 sigset_t set;
3970 struct sigaction sigact;
3972 sigemptyset(&set);
3973 sigaddset(&set, SIGUSR2);
3974 sigaddset(&set, SIGIO);
3975 sigaddset(&set, SIGALRM);
3976 pthread_sigmask(SIG_BLOCK, &set, NULL);
3978 sigemptyset(&set);
3979 sigaddset(&set, SIGUSR1);
3980 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3982 memset(&sigact, 0, sizeof(sigact));
3983 sigact.sa_handler = cpu_signal;
3984 sigaction(SIGUSR1, &sigact, NULL);
3987 static void unblock_io_signals(void)
3989 sigset_t set;
3991 sigemptyset(&set);
3992 sigaddset(&set, SIGUSR2);
3993 sigaddset(&set, SIGIO);
3994 sigaddset(&set, SIGALRM);
3995 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3997 sigemptyset(&set);
3998 sigaddset(&set, SIGUSR1);
3999 pthread_sigmask(SIG_BLOCK, &set, NULL);
4002 static void qemu_signal_lock(unsigned int msecs)
4004 qemu_mutex_lock(&qemu_fair_mutex);
4006 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4007 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4008 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4009 break;
4011 qemu_mutex_unlock(&qemu_fair_mutex);
4014 static void qemu_mutex_lock_iothread(void)
4016 if (kvm_enabled()) {
4017 qemu_mutex_lock(&qemu_fair_mutex);
4018 qemu_mutex_lock(&qemu_global_mutex);
4019 qemu_mutex_unlock(&qemu_fair_mutex);
4020 } else
4021 qemu_signal_lock(100);
4024 static void qemu_mutex_unlock_iothread(void)
4026 qemu_mutex_unlock(&qemu_global_mutex);
4029 static int all_vcpus_paused(void)
4031 CPUState *penv = first_cpu;
4033 while (penv) {
4034 if (!penv->stopped)
4035 return 0;
4036 penv = (CPUState *)penv->next_cpu;
4039 return 1;
4042 static void pause_all_vcpus(void)
4044 CPUState *penv = first_cpu;
4046 while (penv) {
4047 penv->stop = 1;
4048 qemu_thread_signal(penv->thread, SIGUSR1);
4049 qemu_cpu_kick(penv);
4050 penv = (CPUState *)penv->next_cpu;
4053 while (!all_vcpus_paused()) {
4054 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4055 penv = first_cpu;
4056 while (penv) {
4057 qemu_thread_signal(penv->thread, SIGUSR1);
4058 penv = (CPUState *)penv->next_cpu;
4063 static void resume_all_vcpus(void)
4065 CPUState *penv = first_cpu;
4067 while (penv) {
4068 penv->stop = 0;
4069 penv->stopped = 0;
4070 qemu_thread_signal(penv->thread, SIGUSR1);
4071 qemu_cpu_kick(penv);
4072 penv = (CPUState *)penv->next_cpu;
4076 static void tcg_init_vcpu(void *_env)
4078 CPUState *env = _env;
4079 /* share a single thread for all cpus with TCG */
4080 if (!tcg_cpu_thread) {
4081 env->thread = qemu_mallocz(sizeof(QemuThread));
4082 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4083 qemu_cond_init(env->halt_cond);
4084 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4085 while (env->created == 0)
4086 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4087 tcg_cpu_thread = env->thread;
4088 tcg_halt_cond = env->halt_cond;
4089 } else {
4090 env->thread = tcg_cpu_thread;
4091 env->halt_cond = tcg_halt_cond;
4095 static void kvm_start_vcpu(CPUState *env)
4097 kvm_init_vcpu(env);
4098 env->thread = qemu_mallocz(sizeof(QemuThread));
4099 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4100 qemu_cond_init(env->halt_cond);
4101 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4102 while (env->created == 0)
4103 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4106 void qemu_init_vcpu(void *_env)
4108 CPUState *env = _env;
4110 if (kvm_enabled())
4111 kvm_start_vcpu(env);
4112 else
4113 tcg_init_vcpu(env);
4116 void qemu_notify_event(void)
4118 qemu_event_increment();
4121 void vm_stop(int reason)
4123 QemuThread me;
4124 qemu_thread_self(&me);
4126 if (!qemu_thread_equal(&me, &io_thread)) {
4127 qemu_system_vmstop_request(reason);
4129 * FIXME: should not return to device code in case
4130 * vm_stop() has been requested.
4132 if (cpu_single_env) {
4133 cpu_exit(cpu_single_env);
4134 cpu_single_env->stop = 1;
4136 return;
4138 do_vm_stop(reason);
4141 #endif
4144 #ifdef _WIN32
4145 static void host_main_loop_wait(int *timeout)
4147 int ret, ret2, i;
4148 PollingEntry *pe;
4151 /* XXX: need to suppress polling by better using win32 events */
4152 ret = 0;
4153 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4154 ret |= pe->func(pe->opaque);
4156 if (ret == 0) {
4157 int err;
4158 WaitObjects *w = &wait_objects;
4160 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4161 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4162 if (w->func[ret - WAIT_OBJECT_0])
4163 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4165 /* Check for additional signaled events */
4166 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4168 /* Check if event is signaled */
4169 ret2 = WaitForSingleObject(w->events[i], 0);
4170 if(ret2 == WAIT_OBJECT_0) {
4171 if (w->func[i])
4172 w->func[i](w->opaque[i]);
4173 } else if (ret2 == WAIT_TIMEOUT) {
4174 } else {
4175 err = GetLastError();
4176 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4179 } else if (ret == WAIT_TIMEOUT) {
4180 } else {
4181 err = GetLastError();
4182 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4186 *timeout = 0;
4188 #else
4189 static void host_main_loop_wait(int *timeout)
4192 #endif
4194 void main_loop_wait(int timeout)
4196 IOHandlerRecord *ioh;
4197 fd_set rfds, wfds, xfds;
4198 int ret, nfds;
4199 struct timeval tv;
4201 qemu_bh_update_timeout(&timeout);
4203 host_main_loop_wait(&timeout);
4205 /* poll any events */
4206 /* XXX: separate device handlers from system ones */
4207 nfds = -1;
4208 FD_ZERO(&rfds);
4209 FD_ZERO(&wfds);
4210 FD_ZERO(&xfds);
4211 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4212 if (ioh->deleted)
4213 continue;
4214 if (ioh->fd_read &&
4215 (!ioh->fd_read_poll ||
4216 ioh->fd_read_poll(ioh->opaque) != 0)) {
4217 FD_SET(ioh->fd, &rfds);
4218 if (ioh->fd > nfds)
4219 nfds = ioh->fd;
4221 if (ioh->fd_write) {
4222 FD_SET(ioh->fd, &wfds);
4223 if (ioh->fd > nfds)
4224 nfds = ioh->fd;
4228 tv.tv_sec = timeout / 1000;
4229 tv.tv_usec = (timeout % 1000) * 1000;
4231 #if defined(CONFIG_SLIRP)
4232 if (slirp_is_inited()) {
4233 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4235 #endif
4236 qemu_mutex_unlock_iothread();
4237 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4238 qemu_mutex_lock_iothread();
4239 if (ret > 0) {
4240 IOHandlerRecord **pioh;
4242 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4243 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4244 ioh->fd_read(ioh->opaque);
4246 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4247 ioh->fd_write(ioh->opaque);
4251 /* remove deleted IO handlers */
4252 pioh = &first_io_handler;
4253 while (*pioh) {
4254 ioh = *pioh;
4255 if (ioh->deleted) {
4256 *pioh = ioh->next;
4257 qemu_free(ioh);
4258 } else
4259 pioh = &ioh->next;
4262 #if defined(CONFIG_SLIRP)
4263 if (slirp_is_inited()) {
4264 if (ret < 0) {
4265 FD_ZERO(&rfds);
4266 FD_ZERO(&wfds);
4267 FD_ZERO(&xfds);
4269 slirp_select_poll(&rfds, &wfds, &xfds);
4271 #endif
4273 /* rearm timer, if not periodic */
4274 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4275 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4276 qemu_rearm_alarm_timer(alarm_timer);
4279 /* vm time timers */
4280 if (vm_running) {
4281 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4282 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4283 qemu_get_clock(vm_clock));
4286 /* real time timers */
4287 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4288 qemu_get_clock(rt_clock));
4290 /* Check bottom-halves last in case any of the earlier events triggered
4291 them. */
4292 qemu_bh_poll();
4296 static int qemu_cpu_exec(CPUState *env)
4298 int ret;
4299 #ifdef CONFIG_PROFILER
4300 int64_t ti;
4301 #endif
4303 #ifdef CONFIG_PROFILER
4304 ti = profile_getclock();
4305 #endif
4306 if (use_icount) {
4307 int64_t count;
4308 int decr;
4309 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4310 env->icount_decr.u16.low = 0;
4311 env->icount_extra = 0;
4312 count = qemu_next_deadline();
4313 count = (count + (1 << icount_time_shift) - 1)
4314 >> icount_time_shift;
4315 qemu_icount += count;
4316 decr = (count > 0xffff) ? 0xffff : count;
4317 count -= decr;
4318 env->icount_decr.u16.low = decr;
4319 env->icount_extra = count;
4321 ret = cpu_exec(env);
4322 #ifdef CONFIG_PROFILER
4323 qemu_time += profile_getclock() - ti;
4324 #endif
4325 if (use_icount) {
4326 /* Fold pending instructions back into the
4327 instruction counter, and clear the interrupt flag. */
4328 qemu_icount -= (env->icount_decr.u16.low
4329 + env->icount_extra);
4330 env->icount_decr.u32 = 0;
4331 env->icount_extra = 0;
4333 return ret;
4336 static void tcg_cpu_exec(void)
4338 int ret = 0;
4340 if (next_cpu == NULL)
4341 next_cpu = first_cpu;
4342 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4343 CPUState *env = cur_cpu = next_cpu;
4345 if (!vm_running)
4346 break;
4347 if (timer_alarm_pending) {
4348 timer_alarm_pending = 0;
4349 break;
4351 if (cpu_can_run(env))
4352 ret = qemu_cpu_exec(env);
4353 if (ret == EXCP_DEBUG) {
4354 gdb_set_stop_cpu(env);
4355 debug_requested = 1;
4356 break;
4361 static int cpu_has_work(CPUState *env)
4363 if (env->stop)
4364 return 1;
4365 if (env->stopped)
4366 return 0;
4367 if (!env->halted)
4368 return 1;
4369 if (qemu_cpu_has_work(env))
4370 return 1;
4371 return 0;
4374 static int tcg_has_work(void)
4376 CPUState *env;
4378 for (env = first_cpu; env != NULL; env = env->next_cpu)
4379 if (cpu_has_work(env))
4380 return 1;
4381 return 0;
4384 static int qemu_calculate_timeout(void)
4386 int timeout;
4388 if (!vm_running)
4389 timeout = 5000;
4390 else if (tcg_has_work())
4391 timeout = 0;
4392 else if (!use_icount)
4393 timeout = 5000;
4394 else {
4395 /* XXX: use timeout computed from timers */
4396 int64_t add;
4397 int64_t delta;
4398 /* Advance virtual time to the next event. */
4399 if (use_icount == 1) {
4400 /* When not using an adaptive execution frequency
4401 we tend to get badly out of sync with real time,
4402 so just delay for a reasonable amount of time. */
4403 delta = 0;
4404 } else {
4405 delta = cpu_get_icount() - cpu_get_clock();
4407 if (delta > 0) {
4408 /* If virtual time is ahead of real time then just
4409 wait for IO. */
4410 timeout = (delta / 1000000) + 1;
4411 } else {
4412 /* Wait for either IO to occur or the next
4413 timer event. */
4414 add = qemu_next_deadline();
4415 /* We advance the timer before checking for IO.
4416 Limit the amount we advance so that early IO
4417 activity won't get the guest too far ahead. */
4418 if (add > 10000000)
4419 add = 10000000;
4420 delta += add;
4421 add = (add + (1 << icount_time_shift) - 1)
4422 >> icount_time_shift;
4423 qemu_icount += add;
4424 timeout = delta / 1000000;
4425 if (timeout < 0)
4426 timeout = 0;
4430 return timeout;
4433 static int vm_can_run(void)
4435 if (powerdown_requested)
4436 return 0;
4437 if (reset_requested)
4438 return 0;
4439 if (shutdown_requested)
4440 return 0;
4441 if (debug_requested)
4442 return 0;
4443 return 1;
4446 static void main_loop(void)
4448 int r;
4450 #ifdef CONFIG_IOTHREAD
4451 qemu_system_ready = 1;
4452 qemu_cond_broadcast(&qemu_system_cond);
4453 #endif
4455 for (;;) {
4456 do {
4457 #ifdef CONFIG_PROFILER
4458 int64_t ti;
4459 #endif
4460 #ifndef CONFIG_IOTHREAD
4461 tcg_cpu_exec();
4462 #endif
4463 #ifdef CONFIG_PROFILER
4464 ti = profile_getclock();
4465 #endif
4466 #ifdef CONFIG_IOTHREAD
4467 main_loop_wait(1000);
4468 #else
4469 main_loop_wait(qemu_calculate_timeout());
4470 #endif
4471 #ifdef CONFIG_PROFILER
4472 dev_time += profile_getclock() - ti;
4473 #endif
4474 } while (vm_can_run());
4476 if (qemu_debug_requested())
4477 vm_stop(EXCP_DEBUG);
4478 if (qemu_shutdown_requested()) {
4479 if (no_shutdown) {
4480 vm_stop(0);
4481 no_shutdown = 0;
4482 } else
4483 break;
4485 if (qemu_reset_requested()) {
4486 pause_all_vcpus();
4487 qemu_system_reset();
4488 resume_all_vcpus();
4490 if (qemu_powerdown_requested())
4491 qemu_system_powerdown();
4492 if ((r = qemu_vmstop_requested()))
4493 vm_stop(r);
4495 pause_all_vcpus();
4498 static void version(void)
4500 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4503 static void help(int exitcode)
4505 version();
4506 printf("usage: %s [options] [disk_image]\n"
4507 "\n"
4508 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4509 "\n"
4510 #define DEF(option, opt_arg, opt_enum, opt_help) \
4511 opt_help
4512 #define DEFHEADING(text) stringify(text) "\n"
4513 #include "qemu-options.h"
4514 #undef DEF
4515 #undef DEFHEADING
4516 #undef GEN_DOCS
4517 "\n"
4518 "During emulation, the following keys are useful:\n"
4519 "ctrl-alt-f toggle full screen\n"
4520 "ctrl-alt-n switch to virtual console 'n'\n"
4521 "ctrl-alt toggle mouse and keyboard grab\n"
4522 "\n"
4523 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4525 "qemu",
4526 DEFAULT_RAM_SIZE,
4527 #ifndef _WIN32
4528 DEFAULT_NETWORK_SCRIPT,
4529 DEFAULT_NETWORK_DOWN_SCRIPT,
4530 #endif
4531 DEFAULT_GDBSTUB_PORT,
4532 "/tmp/qemu.log");
4533 exit(exitcode);
4536 #define HAS_ARG 0x0001
4538 enum {
4539 #define DEF(option, opt_arg, opt_enum, opt_help) \
4540 opt_enum,
4541 #define DEFHEADING(text)
4542 #include "qemu-options.h"
4543 #undef DEF
4544 #undef DEFHEADING
4545 #undef GEN_DOCS
4548 typedef struct QEMUOption {
4549 const char *name;
4550 int flags;
4551 int index;
4552 } QEMUOption;
4554 static const QEMUOption qemu_options[] = {
4555 { "h", 0, QEMU_OPTION_h },
4556 #define DEF(option, opt_arg, opt_enum, opt_help) \
4557 { option, opt_arg, opt_enum },
4558 #define DEFHEADING(text)
4559 #include "qemu-options.h"
4560 #undef DEF
4561 #undef DEFHEADING
4562 #undef GEN_DOCS
4563 { NULL },
4566 #ifdef HAS_AUDIO
4567 struct soundhw soundhw[] = {
4568 #ifdef HAS_AUDIO_CHOICE
4569 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4571 "pcspk",
4572 "PC speaker",
4575 { .init_isa = pcspk_audio_init }
4577 #endif
4579 #ifdef CONFIG_SB16
4581 "sb16",
4582 "Creative Sound Blaster 16",
4585 { .init_isa = SB16_init }
4587 #endif
4589 #ifdef CONFIG_CS4231A
4591 "cs4231a",
4592 "CS4231A",
4595 { .init_isa = cs4231a_init }
4597 #endif
4599 #ifdef CONFIG_ADLIB
4601 "adlib",
4602 #ifdef HAS_YMF262
4603 "Yamaha YMF262 (OPL3)",
4604 #else
4605 "Yamaha YM3812 (OPL2)",
4606 #endif
4609 { .init_isa = Adlib_init }
4611 #endif
4613 #ifdef CONFIG_GUS
4615 "gus",
4616 "Gravis Ultrasound GF1",
4619 { .init_isa = GUS_init }
4621 #endif
4623 #ifdef CONFIG_AC97
4625 "ac97",
4626 "Intel 82801AA AC97 Audio",
4629 { .init_pci = ac97_init }
4631 #endif
4633 #ifdef CONFIG_ES1370
4635 "es1370",
4636 "ENSONIQ AudioPCI ES1370",
4639 { .init_pci = es1370_init }
4641 #endif
4643 #endif /* HAS_AUDIO_CHOICE */
4645 { NULL, NULL, 0, 0, { NULL } }
4648 static void select_soundhw (const char *optarg)
4650 struct soundhw *c;
4652 if (*optarg == '?') {
4653 show_valid_cards:
4655 printf ("Valid sound card names (comma separated):\n");
4656 for (c = soundhw; c->name; ++c) {
4657 printf ("%-11s %s\n", c->name, c->descr);
4659 printf ("\n-soundhw all will enable all of the above\n");
4660 exit (*optarg != '?');
4662 else {
4663 size_t l;
4664 const char *p;
4665 char *e;
4666 int bad_card = 0;
4668 if (!strcmp (optarg, "all")) {
4669 for (c = soundhw; c->name; ++c) {
4670 c->enabled = 1;
4672 return;
4675 p = optarg;
4676 while (*p) {
4677 e = strchr (p, ',');
4678 l = !e ? strlen (p) : (size_t) (e - p);
4680 for (c = soundhw; c->name; ++c) {
4681 if (!strncmp (c->name, p, l)) {
4682 c->enabled = 1;
4683 break;
4687 if (!c->name) {
4688 if (l > 80) {
4689 fprintf (stderr,
4690 "Unknown sound card name (too big to show)\n");
4692 else {
4693 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4694 (int) l, p);
4696 bad_card = 1;
4698 p += l + (e != NULL);
4701 if (bad_card)
4702 goto show_valid_cards;
4705 #endif
4707 static void select_vgahw (const char *p)
4709 const char *opts;
4711 cirrus_vga_enabled = 0;
4712 std_vga_enabled = 0;
4713 vmsvga_enabled = 0;
4714 xenfb_enabled = 0;
4715 if (strstart(p, "std", &opts)) {
4716 std_vga_enabled = 1;
4717 } else if (strstart(p, "cirrus", &opts)) {
4718 cirrus_vga_enabled = 1;
4719 } else if (strstart(p, "vmware", &opts)) {
4720 vmsvga_enabled = 1;
4721 } else if (strstart(p, "xenfb", &opts)) {
4722 xenfb_enabled = 1;
4723 } else if (!strstart(p, "none", &opts)) {
4724 invalid_vga:
4725 fprintf(stderr, "Unknown vga type: %s\n", p);
4726 exit(1);
4728 while (*opts) {
4729 const char *nextopt;
4731 if (strstart(opts, ",retrace=", &nextopt)) {
4732 opts = nextopt;
4733 if (strstart(opts, "dumb", &nextopt))
4734 vga_retrace_method = VGA_RETRACE_DUMB;
4735 else if (strstart(opts, "precise", &nextopt))
4736 vga_retrace_method = VGA_RETRACE_PRECISE;
4737 else goto invalid_vga;
4738 } else goto invalid_vga;
4739 opts = nextopt;
4743 #ifdef _WIN32
4744 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4746 exit(STATUS_CONTROL_C_EXIT);
4747 return TRUE;
4749 #endif
4751 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4753 int ret;
4755 if(strlen(str) != 36)
4756 return -1;
4758 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4759 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4760 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4762 if(ret != 16)
4763 return -1;
4765 #ifdef TARGET_I386
4766 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4767 #endif
4769 return 0;
4772 #define MAX_NET_CLIENTS 32
4774 #ifndef _WIN32
4776 static void termsig_handler(int signal)
4778 qemu_system_shutdown_request();
4781 static void termsig_setup(void)
4783 struct sigaction act;
4785 memset(&act, 0, sizeof(act));
4786 act.sa_handler = termsig_handler;
4787 sigaction(SIGINT, &act, NULL);
4788 sigaction(SIGHUP, &act, NULL);
4789 sigaction(SIGTERM, &act, NULL);
4792 #endif
4794 int main(int argc, char **argv, char **envp)
4796 const char *gdbstub_dev = NULL;
4797 uint32_t boot_devices_bitmap = 0;
4798 int i;
4799 int snapshot, linux_boot, net_boot;
4800 const char *initrd_filename;
4801 const char *kernel_filename, *kernel_cmdline;
4802 const char *boot_devices = "";
4803 DisplayState *ds;
4804 DisplayChangeListener *dcl;
4805 int cyls, heads, secs, translation;
4806 const char *net_clients[MAX_NET_CLIENTS];
4807 int nb_net_clients;
4808 const char *bt_opts[MAX_BT_CMDLINE];
4809 int nb_bt_opts;
4810 int hda_index;
4811 int optind;
4812 const char *r, *optarg;
4813 CharDriverState *monitor_hd = NULL;
4814 const char *monitor_device;
4815 const char *serial_devices[MAX_SERIAL_PORTS];
4816 int serial_device_index;
4817 const char *parallel_devices[MAX_PARALLEL_PORTS];
4818 int parallel_device_index;
4819 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4820 int virtio_console_index;
4821 const char *loadvm = NULL;
4822 QEMUMachine *machine;
4823 const char *cpu_model;
4824 const char *usb_devices[MAX_USB_CMDLINE];
4825 int usb_devices_index;
4826 #ifndef _WIN32
4827 int fds[2];
4828 #endif
4829 int tb_size;
4830 const char *pid_file = NULL;
4831 const char *incoming = NULL;
4832 #ifndef _WIN32
4833 int fd = 0;
4834 struct passwd *pwd = NULL;
4835 const char *chroot_dir = NULL;
4836 const char *run_as = NULL;
4837 #endif
4838 CPUState *env;
4840 qemu_cache_utils_init(envp);
4842 LIST_INIT (&vm_change_state_head);
4843 #ifndef _WIN32
4845 struct sigaction act;
4846 sigfillset(&act.sa_mask);
4847 act.sa_flags = 0;
4848 act.sa_handler = SIG_IGN;
4849 sigaction(SIGPIPE, &act, NULL);
4851 #else
4852 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4853 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4854 QEMU to run on a single CPU */
4856 HANDLE h;
4857 DWORD mask, smask;
4858 int i;
4859 h = GetCurrentProcess();
4860 if (GetProcessAffinityMask(h, &mask, &smask)) {
4861 for(i = 0; i < 32; i++) {
4862 if (mask & (1 << i))
4863 break;
4865 if (i != 32) {
4866 mask = 1 << i;
4867 SetProcessAffinityMask(h, mask);
4871 #endif
4873 register_machines();
4874 machine = first_machine;
4875 cpu_model = NULL;
4876 initrd_filename = NULL;
4877 ram_size = 0;
4878 vga_ram_size = VGA_RAM_SIZE;
4879 snapshot = 0;
4880 nographic = 0;
4881 curses = 0;
4882 kernel_filename = NULL;
4883 kernel_cmdline = "";
4884 cyls = heads = secs = 0;
4885 translation = BIOS_ATA_TRANSLATION_AUTO;
4886 monitor_device = "vc:80Cx24C";
4888 serial_devices[0] = "vc:80Cx24C";
4889 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4890 serial_devices[i] = NULL;
4891 serial_device_index = 0;
4893 parallel_devices[0] = "vc:80Cx24C";
4894 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4895 parallel_devices[i] = NULL;
4896 parallel_device_index = 0;
4898 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4899 virtio_consoles[i] = NULL;
4900 virtio_console_index = 0;
4902 for (i = 0; i < MAX_NODES; i++) {
4903 node_mem[i] = 0;
4904 node_cpumask[i] = 0;
4907 usb_devices_index = 0;
4909 nb_net_clients = 0;
4910 nb_bt_opts = 0;
4911 nb_drives = 0;
4912 nb_drives_opt = 0;
4913 nb_numa_nodes = 0;
4914 hda_index = -1;
4916 nb_nics = 0;
4918 tb_size = 0;
4919 autostart= 1;
4921 register_watchdogs();
4923 optind = 1;
4924 for(;;) {
4925 if (optind >= argc)
4926 break;
4927 r = argv[optind];
4928 if (r[0] != '-') {
4929 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4930 } else {
4931 const QEMUOption *popt;
4933 optind++;
4934 /* Treat --foo the same as -foo. */
4935 if (r[1] == '-')
4936 r++;
4937 popt = qemu_options;
4938 for(;;) {
4939 if (!popt->name) {
4940 fprintf(stderr, "%s: invalid option -- '%s'\n",
4941 argv[0], r);
4942 exit(1);
4944 if (!strcmp(popt->name, r + 1))
4945 break;
4946 popt++;
4948 if (popt->flags & HAS_ARG) {
4949 if (optind >= argc) {
4950 fprintf(stderr, "%s: option '%s' requires an argument\n",
4951 argv[0], r);
4952 exit(1);
4954 optarg = argv[optind++];
4955 } else {
4956 optarg = NULL;
4959 switch(popt->index) {
4960 case QEMU_OPTION_M:
4961 machine = find_machine(optarg);
4962 if (!machine) {
4963 QEMUMachine *m;
4964 printf("Supported machines are:\n");
4965 for(m = first_machine; m != NULL; m = m->next) {
4966 printf("%-10s %s%s\n",
4967 m->name, m->desc,
4968 m == first_machine ? " (default)" : "");
4970 exit(*optarg != '?');
4972 break;
4973 case QEMU_OPTION_cpu:
4974 /* hw initialization will check this */
4975 if (*optarg == '?') {
4976 /* XXX: implement xxx_cpu_list for targets that still miss it */
4977 #if defined(cpu_list)
4978 cpu_list(stdout, &fprintf);
4979 #endif
4980 exit(0);
4981 } else {
4982 cpu_model = optarg;
4984 break;
4985 case QEMU_OPTION_initrd:
4986 initrd_filename = optarg;
4987 break;
4988 case QEMU_OPTION_hda:
4989 if (cyls == 0)
4990 hda_index = drive_add(optarg, HD_ALIAS, 0);
4991 else
4992 hda_index = drive_add(optarg, HD_ALIAS
4993 ",cyls=%d,heads=%d,secs=%d%s",
4994 0, cyls, heads, secs,
4995 translation == BIOS_ATA_TRANSLATION_LBA ?
4996 ",trans=lba" :
4997 translation == BIOS_ATA_TRANSLATION_NONE ?
4998 ",trans=none" : "");
4999 break;
5000 case QEMU_OPTION_hdb:
5001 case QEMU_OPTION_hdc:
5002 case QEMU_OPTION_hdd:
5003 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5004 break;
5005 case QEMU_OPTION_drive:
5006 drive_add(NULL, "%s", optarg);
5007 break;
5008 case QEMU_OPTION_mtdblock:
5009 drive_add(optarg, MTD_ALIAS);
5010 break;
5011 case QEMU_OPTION_sd:
5012 drive_add(optarg, SD_ALIAS);
5013 break;
5014 case QEMU_OPTION_pflash:
5015 drive_add(optarg, PFLASH_ALIAS);
5016 break;
5017 case QEMU_OPTION_snapshot:
5018 snapshot = 1;
5019 break;
5020 case QEMU_OPTION_hdachs:
5022 const char *p;
5023 p = optarg;
5024 cyls = strtol(p, (char **)&p, 0);
5025 if (cyls < 1 || cyls > 16383)
5026 goto chs_fail;
5027 if (*p != ',')
5028 goto chs_fail;
5029 p++;
5030 heads = strtol(p, (char **)&p, 0);
5031 if (heads < 1 || heads > 16)
5032 goto chs_fail;
5033 if (*p != ',')
5034 goto chs_fail;
5035 p++;
5036 secs = strtol(p, (char **)&p, 0);
5037 if (secs < 1 || secs > 63)
5038 goto chs_fail;
5039 if (*p == ',') {
5040 p++;
5041 if (!strcmp(p, "none"))
5042 translation = BIOS_ATA_TRANSLATION_NONE;
5043 else if (!strcmp(p, "lba"))
5044 translation = BIOS_ATA_TRANSLATION_LBA;
5045 else if (!strcmp(p, "auto"))
5046 translation = BIOS_ATA_TRANSLATION_AUTO;
5047 else
5048 goto chs_fail;
5049 } else if (*p != '\0') {
5050 chs_fail:
5051 fprintf(stderr, "qemu: invalid physical CHS format\n");
5052 exit(1);
5054 if (hda_index != -1)
5055 snprintf(drives_opt[hda_index].opt,
5056 sizeof(drives_opt[hda_index].opt),
5057 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5058 0, cyls, heads, secs,
5059 translation == BIOS_ATA_TRANSLATION_LBA ?
5060 ",trans=lba" :
5061 translation == BIOS_ATA_TRANSLATION_NONE ?
5062 ",trans=none" : "");
5064 break;
5065 case QEMU_OPTION_numa:
5066 if (nb_numa_nodes >= MAX_NODES) {
5067 fprintf(stderr, "qemu: too many NUMA nodes\n");
5068 exit(1);
5070 numa_add(optarg);
5071 break;
5072 case QEMU_OPTION_nographic:
5073 nographic = 1;
5074 break;
5075 #ifdef CONFIG_CURSES
5076 case QEMU_OPTION_curses:
5077 curses = 1;
5078 break;
5079 #endif
5080 case QEMU_OPTION_portrait:
5081 graphic_rotate = 1;
5082 break;
5083 case QEMU_OPTION_kernel:
5084 kernel_filename = optarg;
5085 break;
5086 case QEMU_OPTION_append:
5087 kernel_cmdline = optarg;
5088 break;
5089 case QEMU_OPTION_cdrom:
5090 drive_add(optarg, CDROM_ALIAS);
5091 break;
5092 case QEMU_OPTION_boot:
5093 boot_devices = optarg;
5094 /* We just do some generic consistency checks */
5096 /* Could easily be extended to 64 devices if needed */
5097 const char *p;
5099 boot_devices_bitmap = 0;
5100 for (p = boot_devices; *p != '\0'; p++) {
5101 /* Allowed boot devices are:
5102 * a b : floppy disk drives
5103 * c ... f : IDE disk drives
5104 * g ... m : machine implementation dependant drives
5105 * n ... p : network devices
5106 * It's up to each machine implementation to check
5107 * if the given boot devices match the actual hardware
5108 * implementation and firmware features.
5110 if (*p < 'a' || *p > 'q') {
5111 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5112 exit(1);
5114 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5115 fprintf(stderr,
5116 "Boot device '%c' was given twice\n",*p);
5117 exit(1);
5119 boot_devices_bitmap |= 1 << (*p - 'a');
5122 break;
5123 case QEMU_OPTION_fda:
5124 case QEMU_OPTION_fdb:
5125 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5126 break;
5127 #ifdef TARGET_I386
5128 case QEMU_OPTION_no_fd_bootchk:
5129 fd_bootchk = 0;
5130 break;
5131 #endif
5132 case QEMU_OPTION_net:
5133 if (nb_net_clients >= MAX_NET_CLIENTS) {
5134 fprintf(stderr, "qemu: too many network clients\n");
5135 exit(1);
5137 net_clients[nb_net_clients] = optarg;
5138 nb_net_clients++;
5139 break;
5140 #ifdef CONFIG_SLIRP
5141 case QEMU_OPTION_tftp:
5142 tftp_prefix = optarg;
5143 break;
5144 case QEMU_OPTION_bootp:
5145 bootp_filename = optarg;
5146 break;
5147 #ifndef _WIN32
5148 case QEMU_OPTION_smb:
5149 net_slirp_smb(optarg);
5150 break;
5151 #endif
5152 case QEMU_OPTION_redir:
5153 net_slirp_redir(NULL, optarg);
5154 break;
5155 #endif
5156 case QEMU_OPTION_bt:
5157 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5158 fprintf(stderr, "qemu: too many bluetooth options\n");
5159 exit(1);
5161 bt_opts[nb_bt_opts++] = optarg;
5162 break;
5163 #ifdef HAS_AUDIO
5164 case QEMU_OPTION_audio_help:
5165 AUD_help ();
5166 exit (0);
5167 break;
5168 case QEMU_OPTION_soundhw:
5169 select_soundhw (optarg);
5170 break;
5171 #endif
5172 case QEMU_OPTION_h:
5173 help(0);
5174 break;
5175 case QEMU_OPTION_version:
5176 version();
5177 exit(0);
5178 break;
5179 case QEMU_OPTION_m: {
5180 uint64_t value;
5181 char *ptr;
5183 value = strtoul(optarg, &ptr, 10);
5184 switch (*ptr) {
5185 case 0: case 'M': case 'm':
5186 value <<= 20;
5187 break;
5188 case 'G': case 'g':
5189 value <<= 30;
5190 break;
5191 default:
5192 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5193 exit(1);
5196 /* On 32-bit hosts, QEMU is limited by virtual address space */
5197 if (value > (2047 << 20)
5198 #ifndef CONFIG_KQEMU
5199 && HOST_LONG_BITS == 32
5200 #endif
5202 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5203 exit(1);
5205 if (value != (uint64_t)(ram_addr_t)value) {
5206 fprintf(stderr, "qemu: ram size too large\n");
5207 exit(1);
5209 ram_size = value;
5210 break;
5212 case QEMU_OPTION_d:
5214 int mask;
5215 const CPULogItem *item;
5217 mask = cpu_str_to_log_mask(optarg);
5218 if (!mask) {
5219 printf("Log items (comma separated):\n");
5220 for(item = cpu_log_items; item->mask != 0; item++) {
5221 printf("%-10s %s\n", item->name, item->help);
5223 exit(1);
5225 cpu_set_log(mask);
5227 break;
5228 case QEMU_OPTION_s:
5229 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5230 break;
5231 case QEMU_OPTION_gdb:
5232 gdbstub_dev = optarg;
5233 break;
5234 case QEMU_OPTION_L:
5235 bios_dir = optarg;
5236 break;
5237 case QEMU_OPTION_bios:
5238 bios_name = optarg;
5239 break;
5240 case QEMU_OPTION_singlestep:
5241 singlestep = 1;
5242 break;
5243 case QEMU_OPTION_S:
5244 autostart = 0;
5245 break;
5246 #ifndef _WIN32
5247 case QEMU_OPTION_k:
5248 keyboard_layout = optarg;
5249 break;
5250 #endif
5251 case QEMU_OPTION_localtime:
5252 rtc_utc = 0;
5253 break;
5254 case QEMU_OPTION_vga:
5255 select_vgahw (optarg);
5256 break;
5257 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5258 case QEMU_OPTION_g:
5260 const char *p;
5261 int w, h, depth;
5262 p = optarg;
5263 w = strtol(p, (char **)&p, 10);
5264 if (w <= 0) {
5265 graphic_error:
5266 fprintf(stderr, "qemu: invalid resolution or depth\n");
5267 exit(1);
5269 if (*p != 'x')
5270 goto graphic_error;
5271 p++;
5272 h = strtol(p, (char **)&p, 10);
5273 if (h <= 0)
5274 goto graphic_error;
5275 if (*p == 'x') {
5276 p++;
5277 depth = strtol(p, (char **)&p, 10);
5278 if (depth != 8 && depth != 15 && depth != 16 &&
5279 depth != 24 && depth != 32)
5280 goto graphic_error;
5281 } else if (*p == '\0') {
5282 depth = graphic_depth;
5283 } else {
5284 goto graphic_error;
5287 graphic_width = w;
5288 graphic_height = h;
5289 graphic_depth = depth;
5291 break;
5292 #endif
5293 case QEMU_OPTION_echr:
5295 char *r;
5296 term_escape_char = strtol(optarg, &r, 0);
5297 if (r == optarg)
5298 printf("Bad argument to echr\n");
5299 break;
5301 case QEMU_OPTION_monitor:
5302 monitor_device = optarg;
5303 break;
5304 case QEMU_OPTION_serial:
5305 if (serial_device_index >= MAX_SERIAL_PORTS) {
5306 fprintf(stderr, "qemu: too many serial ports\n");
5307 exit(1);
5309 serial_devices[serial_device_index] = optarg;
5310 serial_device_index++;
5311 break;
5312 case QEMU_OPTION_watchdog:
5313 i = select_watchdog(optarg);
5314 if (i > 0)
5315 exit (i == 1 ? 1 : 0);
5316 break;
5317 case QEMU_OPTION_watchdog_action:
5318 if (select_watchdog_action(optarg) == -1) {
5319 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5320 exit(1);
5322 break;
5323 case QEMU_OPTION_virtiocon:
5324 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5325 fprintf(stderr, "qemu: too many virtio consoles\n");
5326 exit(1);
5328 virtio_consoles[virtio_console_index] = optarg;
5329 virtio_console_index++;
5330 break;
5331 case QEMU_OPTION_parallel:
5332 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5333 fprintf(stderr, "qemu: too many parallel ports\n");
5334 exit(1);
5336 parallel_devices[parallel_device_index] = optarg;
5337 parallel_device_index++;
5338 break;
5339 case QEMU_OPTION_loadvm:
5340 loadvm = optarg;
5341 break;
5342 case QEMU_OPTION_full_screen:
5343 full_screen = 1;
5344 break;
5345 #ifdef CONFIG_SDL
5346 case QEMU_OPTION_no_frame:
5347 no_frame = 1;
5348 break;
5349 case QEMU_OPTION_alt_grab:
5350 alt_grab = 1;
5351 break;
5352 case QEMU_OPTION_no_quit:
5353 no_quit = 1;
5354 break;
5355 case QEMU_OPTION_sdl:
5356 sdl = 1;
5357 break;
5358 #endif
5359 case QEMU_OPTION_pidfile:
5360 pid_file = optarg;
5361 break;
5362 #ifdef TARGET_I386
5363 case QEMU_OPTION_win2k_hack:
5364 win2k_install_hack = 1;
5365 break;
5366 case QEMU_OPTION_rtc_td_hack:
5367 rtc_td_hack = 1;
5368 break;
5369 case QEMU_OPTION_acpitable:
5370 if(acpi_table_add(optarg) < 0) {
5371 fprintf(stderr, "Wrong acpi table provided\n");
5372 exit(1);
5374 break;
5375 case QEMU_OPTION_smbios:
5376 if(smbios_entry_add(optarg) < 0) {
5377 fprintf(stderr, "Wrong smbios provided\n");
5378 exit(1);
5380 break;
5381 #endif
5382 #ifdef CONFIG_KQEMU
5383 case QEMU_OPTION_no_kqemu:
5384 kqemu_allowed = 0;
5385 break;
5386 case QEMU_OPTION_kernel_kqemu:
5387 kqemu_allowed = 2;
5388 break;
5389 #endif
5390 #ifdef CONFIG_KVM
5391 case QEMU_OPTION_enable_kvm:
5392 kvm_allowed = 1;
5393 #ifdef CONFIG_KQEMU
5394 kqemu_allowed = 0;
5395 #endif
5396 break;
5397 #endif
5398 case QEMU_OPTION_usb:
5399 usb_enabled = 1;
5400 break;
5401 case QEMU_OPTION_usbdevice:
5402 usb_enabled = 1;
5403 if (usb_devices_index >= MAX_USB_CMDLINE) {
5404 fprintf(stderr, "Too many USB devices\n");
5405 exit(1);
5407 usb_devices[usb_devices_index] = optarg;
5408 usb_devices_index++;
5409 break;
5410 case QEMU_OPTION_smp:
5411 smp_cpus = atoi(optarg);
5412 if (smp_cpus < 1) {
5413 fprintf(stderr, "Invalid number of CPUs\n");
5414 exit(1);
5416 break;
5417 case QEMU_OPTION_vnc:
5418 vnc_display = optarg;
5419 break;
5420 #ifdef TARGET_I386
5421 case QEMU_OPTION_no_acpi:
5422 acpi_enabled = 0;
5423 break;
5424 case QEMU_OPTION_no_hpet:
5425 no_hpet = 1;
5426 break;
5427 #endif
5428 case QEMU_OPTION_no_reboot:
5429 no_reboot = 1;
5430 break;
5431 case QEMU_OPTION_no_shutdown:
5432 no_shutdown = 1;
5433 break;
5434 case QEMU_OPTION_show_cursor:
5435 cursor_hide = 0;
5436 break;
5437 case QEMU_OPTION_uuid:
5438 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5439 fprintf(stderr, "Fail to parse UUID string."
5440 " Wrong format.\n");
5441 exit(1);
5443 break;
5444 #ifndef _WIN32
5445 case QEMU_OPTION_daemonize:
5446 daemonize = 1;
5447 break;
5448 #endif
5449 case QEMU_OPTION_option_rom:
5450 if (nb_option_roms >= MAX_OPTION_ROMS) {
5451 fprintf(stderr, "Too many option ROMs\n");
5452 exit(1);
5454 option_rom[nb_option_roms] = optarg;
5455 nb_option_roms++;
5456 break;
5457 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5458 case QEMU_OPTION_semihosting:
5459 semihosting_enabled = 1;
5460 break;
5461 #endif
5462 case QEMU_OPTION_name:
5463 qemu_name = optarg;
5464 break;
5465 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5466 case QEMU_OPTION_prom_env:
5467 if (nb_prom_envs >= MAX_PROM_ENVS) {
5468 fprintf(stderr, "Too many prom variables\n");
5469 exit(1);
5471 prom_envs[nb_prom_envs] = optarg;
5472 nb_prom_envs++;
5473 break;
5474 #endif
5475 #ifdef TARGET_ARM
5476 case QEMU_OPTION_old_param:
5477 old_param = 1;
5478 break;
5479 #endif
5480 case QEMU_OPTION_clock:
5481 configure_alarms(optarg);
5482 break;
5483 case QEMU_OPTION_startdate:
5485 struct tm tm;
5486 time_t rtc_start_date;
5487 if (!strcmp(optarg, "now")) {
5488 rtc_date_offset = -1;
5489 } else {
5490 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5491 &tm.tm_year,
5492 &tm.tm_mon,
5493 &tm.tm_mday,
5494 &tm.tm_hour,
5495 &tm.tm_min,
5496 &tm.tm_sec) == 6) {
5497 /* OK */
5498 } else if (sscanf(optarg, "%d-%d-%d",
5499 &tm.tm_year,
5500 &tm.tm_mon,
5501 &tm.tm_mday) == 3) {
5502 tm.tm_hour = 0;
5503 tm.tm_min = 0;
5504 tm.tm_sec = 0;
5505 } else {
5506 goto date_fail;
5508 tm.tm_year -= 1900;
5509 tm.tm_mon--;
5510 rtc_start_date = mktimegm(&tm);
5511 if (rtc_start_date == -1) {
5512 date_fail:
5513 fprintf(stderr, "Invalid date format. Valid format are:\n"
5514 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5515 exit(1);
5517 rtc_date_offset = time(NULL) - rtc_start_date;
5520 break;
5521 case QEMU_OPTION_tb_size:
5522 tb_size = strtol(optarg, NULL, 0);
5523 if (tb_size < 0)
5524 tb_size = 0;
5525 break;
5526 case QEMU_OPTION_icount:
5527 use_icount = 1;
5528 if (strcmp(optarg, "auto") == 0) {
5529 icount_time_shift = -1;
5530 } else {
5531 icount_time_shift = strtol(optarg, NULL, 0);
5533 break;
5534 case QEMU_OPTION_incoming:
5535 incoming = optarg;
5536 break;
5537 #ifndef _WIN32
5538 case QEMU_OPTION_chroot:
5539 chroot_dir = optarg;
5540 break;
5541 case QEMU_OPTION_runas:
5542 run_as = optarg;
5543 break;
5544 #endif
5545 #ifdef CONFIG_XEN
5546 case QEMU_OPTION_xen_domid:
5547 xen_domid = atoi(optarg);
5548 break;
5549 case QEMU_OPTION_xen_create:
5550 xen_mode = XEN_CREATE;
5551 break;
5552 case QEMU_OPTION_xen_attach:
5553 xen_mode = XEN_ATTACH;
5554 break;
5555 #endif
5560 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5561 if (kvm_allowed && kqemu_allowed) {
5562 fprintf(stderr,
5563 "You can not enable both KVM and kqemu at the same time\n");
5564 exit(1);
5566 #endif
5568 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5569 if (smp_cpus > machine->max_cpus) {
5570 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5571 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5572 machine->max_cpus);
5573 exit(1);
5576 if (nographic) {
5577 if (serial_device_index == 0)
5578 serial_devices[0] = "stdio";
5579 if (parallel_device_index == 0)
5580 parallel_devices[0] = "null";
5581 if (strncmp(monitor_device, "vc", 2) == 0)
5582 monitor_device = "stdio";
5585 #ifndef _WIN32
5586 if (daemonize) {
5587 pid_t pid;
5589 if (pipe(fds) == -1)
5590 exit(1);
5592 pid = fork();
5593 if (pid > 0) {
5594 uint8_t status;
5595 ssize_t len;
5597 close(fds[1]);
5599 again:
5600 len = read(fds[0], &status, 1);
5601 if (len == -1 && (errno == EINTR))
5602 goto again;
5604 if (len != 1)
5605 exit(1);
5606 else if (status == 1) {
5607 fprintf(stderr, "Could not acquire pidfile\n");
5608 exit(1);
5609 } else
5610 exit(0);
5611 } else if (pid < 0)
5612 exit(1);
5614 setsid();
5616 pid = fork();
5617 if (pid > 0)
5618 exit(0);
5619 else if (pid < 0)
5620 exit(1);
5622 umask(027);
5624 signal(SIGTSTP, SIG_IGN);
5625 signal(SIGTTOU, SIG_IGN);
5626 signal(SIGTTIN, SIG_IGN);
5629 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5630 if (daemonize) {
5631 uint8_t status = 1;
5632 write(fds[1], &status, 1);
5633 } else
5634 fprintf(stderr, "Could not acquire pid file\n");
5635 exit(1);
5637 #endif
5639 #ifdef CONFIG_KQEMU
5640 if (smp_cpus > 1)
5641 kqemu_allowed = 0;
5642 #endif
5643 if (qemu_init_main_loop()) {
5644 fprintf(stderr, "qemu_init_main_loop failed\n");
5645 exit(1);
5647 linux_boot = (kernel_filename != NULL);
5648 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5650 if (!linux_boot && *kernel_cmdline != '\0') {
5651 fprintf(stderr, "-append only allowed with -kernel option\n");
5652 exit(1);
5655 if (!linux_boot && initrd_filename != NULL) {
5656 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5657 exit(1);
5660 /* boot to floppy or the default cd if no hard disk defined yet */
5661 if (!boot_devices[0]) {
5662 boot_devices = "cad";
5664 setvbuf(stdout, NULL, _IOLBF, 0);
5666 init_timers();
5667 if (init_timer_alarm() < 0) {
5668 fprintf(stderr, "could not initialize alarm timer\n");
5669 exit(1);
5671 if (use_icount && icount_time_shift < 0) {
5672 use_icount = 2;
5673 /* 125MIPS seems a reasonable initial guess at the guest speed.
5674 It will be corrected fairly quickly anyway. */
5675 icount_time_shift = 3;
5676 init_icount_adjust();
5679 #ifdef _WIN32
5680 socket_init();
5681 #endif
5683 /* init network clients */
5684 if (nb_net_clients == 0) {
5685 /* if no clients, we use a default config */
5686 net_clients[nb_net_clients++] = "nic";
5687 #ifdef CONFIG_SLIRP
5688 net_clients[nb_net_clients++] = "user";
5689 #endif
5692 for(i = 0;i < nb_net_clients; i++) {
5693 if (net_client_parse(net_clients[i]) < 0)
5694 exit(1);
5696 net_client_check();
5698 #ifdef TARGET_I386
5699 /* XXX: this should be moved in the PC machine instantiation code */
5700 if (net_boot != 0) {
5701 int netroms = 0;
5702 for (i = 0; i < nb_nics && i < 4; i++) {
5703 const char *model = nd_table[i].model;
5704 char buf[1024];
5705 if (net_boot & (1 << i)) {
5706 if (model == NULL)
5707 model = "ne2k_pci";
5708 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5709 if (get_image_size(buf) > 0) {
5710 if (nb_option_roms >= MAX_OPTION_ROMS) {
5711 fprintf(stderr, "Too many option ROMs\n");
5712 exit(1);
5714 option_rom[nb_option_roms] = strdup(buf);
5715 nb_option_roms++;
5716 netroms++;
5720 if (netroms == 0) {
5721 fprintf(stderr, "No valid PXE rom found for network device\n");
5722 exit(1);
5725 #endif
5727 /* init the bluetooth world */
5728 for (i = 0; i < nb_bt_opts; i++)
5729 if (bt_parse(bt_opts[i]))
5730 exit(1);
5732 /* init the memory */
5733 if (ram_size == 0)
5734 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5736 #ifdef CONFIG_KQEMU
5737 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5738 guest ram allocation. It needs to go away. */
5739 if (kqemu_allowed) {
5740 kqemu_phys_ram_size = ram_size + VGA_RAM_SIZE + 4 * 1024 * 1024;
5741 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5742 if (!kqemu_phys_ram_base) {
5743 fprintf(stderr, "Could not allocate physical memory\n");
5744 exit(1);
5747 #endif
5749 /* init the dynamic translator */
5750 cpu_exec_init_all(tb_size * 1024 * 1024);
5752 bdrv_init();
5753 dma_helper_init();
5755 /* we always create the cdrom drive, even if no disk is there */
5757 if (nb_drives_opt < MAX_DRIVES)
5758 drive_add(NULL, CDROM_ALIAS);
5760 /* we always create at least one floppy */
5762 if (nb_drives_opt < MAX_DRIVES)
5763 drive_add(NULL, FD_ALIAS, 0);
5765 /* we always create one sd slot, even if no card is in it */
5767 if (nb_drives_opt < MAX_DRIVES)
5768 drive_add(NULL, SD_ALIAS);
5770 /* open the virtual block devices */
5772 for(i = 0; i < nb_drives_opt; i++)
5773 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5774 exit(1);
5776 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5777 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5779 #ifndef _WIN32
5780 /* must be after terminal init, SDL library changes signal handlers */
5781 termsig_setup();
5782 #endif
5784 /* Maintain compatibility with multiple stdio monitors */
5785 if (!strcmp(monitor_device,"stdio")) {
5786 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5787 const char *devname = serial_devices[i];
5788 if (devname && !strcmp(devname,"mon:stdio")) {
5789 monitor_device = NULL;
5790 break;
5791 } else if (devname && !strcmp(devname,"stdio")) {
5792 monitor_device = NULL;
5793 serial_devices[i] = "mon:stdio";
5794 break;
5799 if (nb_numa_nodes > 0) {
5800 int i;
5802 if (nb_numa_nodes > smp_cpus) {
5803 nb_numa_nodes = smp_cpus;
5806 /* If no memory size if given for any node, assume the default case
5807 * and distribute the available memory equally across all nodes
5809 for (i = 0; i < nb_numa_nodes; i++) {
5810 if (node_mem[i] != 0)
5811 break;
5813 if (i == nb_numa_nodes) {
5814 uint64_t usedmem = 0;
5816 /* On Linux, the each node's border has to be 8MB aligned,
5817 * the final node gets the rest.
5819 for (i = 0; i < nb_numa_nodes - 1; i++) {
5820 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5821 usedmem += node_mem[i];
5823 node_mem[i] = ram_size - usedmem;
5826 for (i = 0; i < nb_numa_nodes; i++) {
5827 if (node_cpumask[i] != 0)
5828 break;
5830 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5831 * must cope with this anyway, because there are BIOSes out there in
5832 * real machines which also use this scheme.
5834 if (i == nb_numa_nodes) {
5835 for (i = 0; i < smp_cpus; i++) {
5836 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5841 if (kvm_enabled()) {
5842 int ret;
5844 ret = kvm_init(smp_cpus);
5845 if (ret < 0) {
5846 fprintf(stderr, "failed to initialize KVM\n");
5847 exit(1);
5851 if (monitor_device) {
5852 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5853 if (!monitor_hd) {
5854 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5855 exit(1);
5859 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5860 const char *devname = serial_devices[i];
5861 if (devname && strcmp(devname, "none")) {
5862 char label[32];
5863 snprintf(label, sizeof(label), "serial%d", i);
5864 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5865 if (!serial_hds[i]) {
5866 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5867 devname);
5868 exit(1);
5873 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5874 const char *devname = parallel_devices[i];
5875 if (devname && strcmp(devname, "none")) {
5876 char label[32];
5877 snprintf(label, sizeof(label), "parallel%d", i);
5878 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5879 if (!parallel_hds[i]) {
5880 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5881 devname);
5882 exit(1);
5887 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5888 const char *devname = virtio_consoles[i];
5889 if (devname && strcmp(devname, "none")) {
5890 char label[32];
5891 snprintf(label, sizeof(label), "virtcon%d", i);
5892 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5893 if (!virtcon_hds[i]) {
5894 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5895 devname);
5896 exit(1);
5901 machine->init(ram_size, vga_ram_size, boot_devices,
5902 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5905 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5906 for (i = 0; i < nb_numa_nodes; i++) {
5907 if (node_cpumask[i] & (1 << env->cpu_index)) {
5908 env->numa_node = i;
5913 current_machine = machine;
5915 /* Set KVM's vcpu state to qemu's initial CPUState. */
5916 if (kvm_enabled()) {
5917 int ret;
5919 ret = kvm_sync_vcpus();
5920 if (ret < 0) {
5921 fprintf(stderr, "failed to initialize vcpus\n");
5922 exit(1);
5926 /* init USB devices */
5927 if (usb_enabled) {
5928 for(i = 0; i < usb_devices_index; i++) {
5929 if (usb_device_add(usb_devices[i], 0) < 0) {
5930 fprintf(stderr, "Warning: could not add USB device %s\n",
5931 usb_devices[i]);
5936 if (!display_state)
5937 dumb_display_init();
5938 /* just use the first displaystate for the moment */
5939 ds = display_state;
5940 /* terminal init */
5941 if (nographic) {
5942 if (curses) {
5943 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5944 exit(1);
5946 } else {
5947 #if defined(CONFIG_CURSES)
5948 if (curses) {
5949 /* At the moment curses cannot be used with other displays */
5950 curses_display_init(ds, full_screen);
5951 } else
5952 #endif
5954 if (vnc_display != NULL) {
5955 vnc_display_init(ds);
5956 if (vnc_display_open(ds, vnc_display) < 0)
5957 exit(1);
5959 #if defined(CONFIG_SDL)
5960 if (sdl || !vnc_display)
5961 sdl_display_init(ds, full_screen, no_frame);
5962 #elif defined(CONFIG_COCOA)
5963 if (sdl || !vnc_display)
5964 cocoa_display_init(ds, full_screen);
5965 #endif
5968 dpy_resize(ds);
5970 dcl = ds->listeners;
5971 while (dcl != NULL) {
5972 if (dcl->dpy_refresh != NULL) {
5973 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5974 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5976 dcl = dcl->next;
5979 if (nographic || (vnc_display && !sdl)) {
5980 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5981 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5984 text_consoles_set_display(display_state);
5985 qemu_chr_initial_reset();
5987 if (monitor_device && monitor_hd)
5988 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5990 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5991 const char *devname = serial_devices[i];
5992 if (devname && strcmp(devname, "none")) {
5993 char label[32];
5994 snprintf(label, sizeof(label), "serial%d", i);
5995 if (strstart(devname, "vc", 0))
5996 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6000 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6001 const char *devname = parallel_devices[i];
6002 if (devname && strcmp(devname, "none")) {
6003 char label[32];
6004 snprintf(label, sizeof(label), "parallel%d", i);
6005 if (strstart(devname, "vc", 0))
6006 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6010 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6011 const char *devname = virtio_consoles[i];
6012 if (virtcon_hds[i] && devname) {
6013 char label[32];
6014 snprintf(label, sizeof(label), "virtcon%d", i);
6015 if (strstart(devname, "vc", 0))
6016 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6020 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6021 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6022 gdbstub_dev);
6023 exit(1);
6026 if (loadvm)
6027 do_loadvm(cur_mon, loadvm);
6029 if (incoming) {
6030 autostart = 0; /* fixme how to deal with -daemonize */
6031 qemu_start_incoming_migration(incoming);
6034 if (autostart)
6035 vm_start();
6037 #ifndef _WIN32
6038 if (daemonize) {
6039 uint8_t status = 0;
6040 ssize_t len;
6042 again1:
6043 len = write(fds[1], &status, 1);
6044 if (len == -1 && (errno == EINTR))
6045 goto again1;
6047 if (len != 1)
6048 exit(1);
6050 chdir("/");
6051 TFR(fd = open("/dev/null", O_RDWR));
6052 if (fd == -1)
6053 exit(1);
6056 if (run_as) {
6057 pwd = getpwnam(run_as);
6058 if (!pwd) {
6059 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6060 exit(1);
6064 if (chroot_dir) {
6065 if (chroot(chroot_dir) < 0) {
6066 fprintf(stderr, "chroot failed\n");
6067 exit(1);
6069 chdir("/");
6072 if (run_as) {
6073 if (setgid(pwd->pw_gid) < 0) {
6074 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6075 exit(1);
6077 if (setuid(pwd->pw_uid) < 0) {
6078 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6079 exit(1);
6081 if (setuid(0) != -1) {
6082 fprintf(stderr, "Dropping privileges failed\n");
6083 exit(1);
6087 if (daemonize) {
6088 dup2(fd, 0);
6089 dup2(fd, 1);
6090 dup2(fd, 2);
6092 close(fd);
6094 #endif
6096 main_loop();
6097 quit_timers();
6098 net_cleanup();
6100 return 0;