Init pci_option_rom_offset for VGA BIOS absence
[qemu-kvm/fedora.git] / vl.c
blob0fa5261aba58716ff6564a24f7c69f696f2d57d2
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 <sys/vfs.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef HOST_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
75 #include "hpet.h"
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
98 #if defined(__OpenBSD__)
99 #include <util.h>
100 #endif
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
104 #endif
106 #ifdef _WIN32
107 #include <windows.h>
108 #include <malloc.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
113 #endif
115 #ifdef CONFIG_SDL
116 #ifdef __APPLE__
117 #include <SDL/SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
144 #include "hw/xen.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #if defined(CONFIG_SLIRP)
170 #include "libslirp.h"
171 #endif
173 //#define DEBUG_UNUSED_IOPORT
174 //#define DEBUG_IOPORT
175 //#define DEBUG_NET
176 //#define DEBUG_SLIRP
179 #ifdef DEBUG_IOPORT
180 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
181 #else
182 # define LOG_IOPORT(...) do { } while (0)
183 #endif
185 #define DEFAULT_RAM_SIZE 128
187 /* Max number of USB devices that can be specified on the commandline. */
188 #define MAX_USB_CMDLINE 8
190 /* Max number of bluetooth switches on the commandline. */
191 #define MAX_BT_CMDLINE 10
193 /* XXX: use a two level table to limit memory usage */
194 #define MAX_IOPORTS 65536
196 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
197 const char *bios_name = NULL;
198 static void *ioport_opaque[MAX_IOPORTS];
199 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
200 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
201 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
202 to store the VM snapshots */
203 DriveInfo drives_table[MAX_DRIVES+1];
204 int nb_drives;
205 int extboot_drive = -1;
206 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
207 static DisplayState *display_state;
208 int nographic;
209 static int curses;
210 static int sdl = 1;
211 const char* keyboard_layout = NULL;
212 int64_t ticks_per_sec;
213 ram_addr_t ram_size;
214 int nb_nics;
215 NICInfo nd_table[MAX_NICS];
216 int vm_running;
217 static int autostart;
218 static int rtc_utc = 1;
219 static int rtc_date_offset = -1; /* -1 means no change */
220 int cirrus_vga_enabled = 1;
221 int std_vga_enabled = 0;
222 int vmsvga_enabled = 0;
223 int xenfb_enabled = 0;
224 #ifdef TARGET_SPARC
225 int graphic_width = 1024;
226 int graphic_height = 768;
227 int graphic_depth = 8;
228 #else
229 int graphic_width = 800;
230 int graphic_height = 600;
231 int graphic_depth = 15;
232 #endif
233 static int full_screen = 0;
234 #ifdef CONFIG_SDL
235 static int no_frame = 0;
236 #endif
237 int no_quit = 0;
238 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
239 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
240 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
241 #ifdef TARGET_I386
242 int win2k_install_hack = 0;
243 int rtc_td_hack = 0;
244 #endif
245 int usb_enabled = 0;
246 int singlestep = 0;
247 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
248 int assigned_devices_index;
249 int smp_cpus = 1;
250 const char *vnc_display;
251 int acpi_enabled = 1;
252 int no_hpet = 0;
253 int fd_bootchk = 1;
254 int no_reboot = 0;
255 int no_shutdown = 0;
256 int cursor_hide = 1;
257 int graphic_rotate = 0;
258 #ifndef _WIN32
259 int daemonize = 0;
260 #endif
261 WatchdogTimerModel *watchdog = NULL;
262 int watchdog_action = WDT_RESET;
263 const char *option_rom[MAX_OPTION_ROMS];
264 int nb_option_roms;
265 int semihosting_enabled = 0;
266 int time_drift_fix = 0;
267 unsigned int kvm_shadow_memory = 0;
268 const char *mem_path = NULL;
269 #ifdef MAP_POPULATE
270 int mem_prealloc = 1; /* force preallocation of physical target memory */
271 #endif
272 long hpagesize = 0;
273 #ifdef TARGET_ARM
274 int old_param = 0;
275 #endif
276 const char *qemu_name;
277 int alt_grab = 0;
278 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
279 unsigned int nb_prom_envs = 0;
280 const char *prom_envs[MAX_PROM_ENVS];
281 #endif
282 int nb_drives_opt;
283 const char *nvram = NULL;
284 struct drive_opt drives_opt[MAX_DRIVES];
286 int nb_numa_nodes;
287 uint64_t node_mem[MAX_NODES];
288 uint64_t node_cpumask[MAX_NODES];
290 static CPUState *cur_cpu;
291 static CPUState *next_cpu;
292 static int timer_alarm_pending = 1;
293 /* Conversion factor from emulated instructions to virtual clock ticks. */
294 static int icount_time_shift;
295 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
296 #define MAX_ICOUNT_SHIFT 10
297 /* Compensate for varying guest execution speed. */
298 static int64_t qemu_icount_bias;
299 static QEMUTimer *icount_rt_timer;
300 static QEMUTimer *icount_vm_timer;
301 static QEMUTimer *nographic_timer;
303 uint8_t qemu_uuid[16];
305 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
306 struct timeval *tv)
308 int ret;
310 /* KVM holds a mutex while QEMU code is running, we need hooks to
311 release the mutex whenever QEMU code sleeps. */
313 kvm_sleep_begin();
315 ret = select(max_fd, rfds, wfds, xfds, tv);
317 kvm_sleep_end();
319 return ret;
323 /***********************************************************/
324 /* x86 ISA bus support */
326 target_phys_addr_t isa_mem_base = 0;
327 PicState2 *isa_pic;
329 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
330 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
332 static uint32_t ioport_read(int index, uint32_t address)
334 static IOPortReadFunc *default_func[3] = {
335 default_ioport_readb,
336 default_ioport_readw,
337 default_ioport_readl
339 IOPortReadFunc *func = ioport_read_table[index][address];
340 if (!func)
341 func = default_func[index];
342 return func(ioport_opaque[address], address);
345 static void ioport_write(int index, uint32_t address, uint32_t data)
347 static IOPortWriteFunc *default_func[3] = {
348 default_ioport_writeb,
349 default_ioport_writew,
350 default_ioport_writel
352 IOPortWriteFunc *func = ioport_write_table[index][address];
353 if (!func)
354 func = default_func[index];
355 func(ioport_opaque[address], address, data);
358 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
360 #ifdef DEBUG_UNUSED_IOPORT
361 fprintf(stderr, "unused inb: port=0x%04x\n", address);
362 #endif
363 return 0xff;
366 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
368 #ifdef DEBUG_UNUSED_IOPORT
369 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
370 #endif
373 /* default is to make two byte accesses */
374 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
376 uint32_t data;
377 data = ioport_read(0, address);
378 address = (address + 1) & (MAX_IOPORTS - 1);
379 data |= ioport_read(0, address) << 8;
380 return data;
383 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
385 ioport_write(0, address, data & 0xff);
386 address = (address + 1) & (MAX_IOPORTS - 1);
387 ioport_write(0, address, (data >> 8) & 0xff);
390 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
392 #ifdef DEBUG_UNUSED_IOPORT
393 fprintf(stderr, "unused inl: port=0x%04x\n", address);
394 #endif
395 return 0xffffffff;
398 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
400 #ifdef DEBUG_UNUSED_IOPORT
401 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
402 #endif
405 /* size is the word size in byte */
406 int register_ioport_read(int start, int length, int size,
407 IOPortReadFunc *func, void *opaque)
409 int i, bsize;
411 if (size == 1) {
412 bsize = 0;
413 } else if (size == 2) {
414 bsize = 1;
415 } else if (size == 4) {
416 bsize = 2;
417 } else {
418 hw_error("register_ioport_read: invalid size");
419 return -1;
421 for(i = start; i < start + length; i += size) {
422 ioport_read_table[bsize][i] = func;
423 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
424 hw_error("register_ioport_read: invalid opaque");
425 ioport_opaque[i] = opaque;
427 return 0;
430 /* size is the word size in byte */
431 int register_ioport_write(int start, int length, int size,
432 IOPortWriteFunc *func, void *opaque)
434 int i, bsize;
436 if (size == 1) {
437 bsize = 0;
438 } else if (size == 2) {
439 bsize = 1;
440 } else if (size == 4) {
441 bsize = 2;
442 } else {
443 hw_error("register_ioport_write: invalid size");
444 return -1;
446 for(i = start; i < start + length; i += size) {
447 ioport_write_table[bsize][i] = func;
448 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
449 hw_error("register_ioport_write: invalid opaque");
450 ioport_opaque[i] = opaque;
452 return 0;
455 void isa_unassign_ioport(int start, int length)
457 int i;
459 for(i = start; i < start + length; i++) {
460 ioport_read_table[0][i] = default_ioport_readb;
461 ioport_read_table[1][i] = default_ioport_readw;
462 ioport_read_table[2][i] = default_ioport_readl;
464 ioport_write_table[0][i] = default_ioport_writeb;
465 ioport_write_table[1][i] = default_ioport_writew;
466 ioport_write_table[2][i] = default_ioport_writel;
468 ioport_opaque[i] = NULL;
472 /***********************************************************/
474 void cpu_outb(CPUState *env, int addr, int val)
476 LOG_IOPORT("outb: %04x %02x\n", addr, val);
477 ioport_write(0, addr, val);
478 #ifdef CONFIG_KQEMU
479 if (env)
480 env->last_io_time = cpu_get_time_fast();
481 #endif
484 void cpu_outw(CPUState *env, int addr, int val)
486 LOG_IOPORT("outw: %04x %04x\n", addr, val);
487 ioport_write(1, addr, val);
488 #ifdef CONFIG_KQEMU
489 if (env)
490 env->last_io_time = cpu_get_time_fast();
491 #endif
494 void cpu_outl(CPUState *env, int addr, int val)
496 LOG_IOPORT("outl: %04x %08x\n", addr, val);
497 ioport_write(2, addr, val);
498 #ifdef CONFIG_KQEMU
499 if (env)
500 env->last_io_time = cpu_get_time_fast();
501 #endif
504 int cpu_inb(CPUState *env, int addr)
506 int val;
507 val = ioport_read(0, addr);
508 LOG_IOPORT("inb : %04x %02x\n", addr, val);
509 #ifdef CONFIG_KQEMU
510 if (env)
511 env->last_io_time = cpu_get_time_fast();
512 #endif
513 return val;
516 int cpu_inw(CPUState *env, int addr)
518 int val;
519 val = ioport_read(1, addr);
520 LOG_IOPORT("inw : %04x %04x\n", addr, val);
521 #ifdef CONFIG_KQEMU
522 if (env)
523 env->last_io_time = cpu_get_time_fast();
524 #endif
525 return val;
528 int cpu_inl(CPUState *env, int addr)
530 int val;
531 val = ioport_read(2, addr);
532 LOG_IOPORT("inl : %04x %08x\n", addr, val);
533 #ifdef CONFIG_KQEMU
534 if (env)
535 env->last_io_time = cpu_get_time_fast();
536 #endif
537 return val;
540 /***********************************************************/
541 void hw_error(const char *fmt, ...)
543 va_list ap;
544 CPUState *env;
546 va_start(ap, fmt);
547 fprintf(stderr, "qemu: hardware error: ");
548 vfprintf(stderr, fmt, ap);
549 fprintf(stderr, "\n");
550 for(env = first_cpu; env != NULL; env = env->next_cpu) {
551 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
552 #ifdef TARGET_I386
553 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
554 #else
555 cpu_dump_state(env, stderr, fprintf, 0);
556 #endif
558 va_end(ap);
559 abort();
562 /***************/
563 /* ballooning */
565 static QEMUBalloonEvent *qemu_balloon_event;
566 void *qemu_balloon_event_opaque;
568 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
570 qemu_balloon_event = func;
571 qemu_balloon_event_opaque = opaque;
574 void qemu_balloon(ram_addr_t target)
576 if (qemu_balloon_event)
577 qemu_balloon_event(qemu_balloon_event_opaque, target);
580 ram_addr_t qemu_balloon_status(void)
582 if (qemu_balloon_event)
583 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
584 return 0;
587 /***********************************************************/
588 /* keyboard/mouse */
590 static QEMUPutKBDEvent *qemu_put_kbd_event;
591 static void *qemu_put_kbd_event_opaque;
592 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
593 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
595 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
597 qemu_put_kbd_event_opaque = opaque;
598 qemu_put_kbd_event = func;
601 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
602 void *opaque, int absolute,
603 const char *name)
605 QEMUPutMouseEntry *s, *cursor;
607 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
609 s->qemu_put_mouse_event = func;
610 s->qemu_put_mouse_event_opaque = opaque;
611 s->qemu_put_mouse_event_absolute = absolute;
612 s->qemu_put_mouse_event_name = qemu_strdup(name);
613 s->next = NULL;
615 if (!qemu_put_mouse_event_head) {
616 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
617 return s;
620 cursor = qemu_put_mouse_event_head;
621 while (cursor->next != NULL)
622 cursor = cursor->next;
624 cursor->next = s;
625 qemu_put_mouse_event_current = s;
627 return s;
630 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
632 QEMUPutMouseEntry *prev = NULL, *cursor;
634 if (!qemu_put_mouse_event_head || entry == NULL)
635 return;
637 cursor = qemu_put_mouse_event_head;
638 while (cursor != NULL && cursor != entry) {
639 prev = cursor;
640 cursor = cursor->next;
643 if (cursor == NULL) // does not exist or list empty
644 return;
645 else if (prev == NULL) { // entry is head
646 qemu_put_mouse_event_head = cursor->next;
647 if (qemu_put_mouse_event_current == entry)
648 qemu_put_mouse_event_current = cursor->next;
649 qemu_free(entry->qemu_put_mouse_event_name);
650 qemu_free(entry);
651 return;
654 prev->next = entry->next;
656 if (qemu_put_mouse_event_current == entry)
657 qemu_put_mouse_event_current = prev;
659 qemu_free(entry->qemu_put_mouse_event_name);
660 qemu_free(entry);
663 void kbd_put_keycode(int keycode)
665 if (qemu_put_kbd_event) {
666 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
670 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
672 QEMUPutMouseEvent *mouse_event;
673 void *mouse_event_opaque;
674 int width;
676 if (!qemu_put_mouse_event_current) {
677 return;
680 mouse_event =
681 qemu_put_mouse_event_current->qemu_put_mouse_event;
682 mouse_event_opaque =
683 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
685 if (mouse_event) {
686 if (graphic_rotate) {
687 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
688 width = 0x7fff;
689 else
690 width = graphic_width - 1;
691 mouse_event(mouse_event_opaque,
692 width - dy, dx, dz, buttons_state);
693 } else
694 mouse_event(mouse_event_opaque,
695 dx, dy, dz, buttons_state);
699 int kbd_mouse_is_absolute(void)
701 if (!qemu_put_mouse_event_current)
702 return 0;
704 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
707 void do_info_mice(Monitor *mon)
709 QEMUPutMouseEntry *cursor;
710 int index = 0;
712 if (!qemu_put_mouse_event_head) {
713 monitor_printf(mon, "No mouse devices connected\n");
714 return;
717 monitor_printf(mon, "Mouse devices available:\n");
718 cursor = qemu_put_mouse_event_head;
719 while (cursor != NULL) {
720 monitor_printf(mon, "%c Mouse #%d: %s\n",
721 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
722 index, cursor->qemu_put_mouse_event_name);
723 index++;
724 cursor = cursor->next;
728 void do_mouse_set(Monitor *mon, int index)
730 QEMUPutMouseEntry *cursor;
731 int i = 0;
733 if (!qemu_put_mouse_event_head) {
734 monitor_printf(mon, "No mouse devices connected\n");
735 return;
738 cursor = qemu_put_mouse_event_head;
739 while (cursor != NULL && index != i) {
740 i++;
741 cursor = cursor->next;
744 if (cursor != NULL)
745 qemu_put_mouse_event_current = cursor;
746 else
747 monitor_printf(mon, "Mouse at given index not found\n");
750 /* compute with 96 bit intermediate result: (a*b)/c */
751 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
753 union {
754 uint64_t ll;
755 struct {
756 #ifdef WORDS_BIGENDIAN
757 uint32_t high, low;
758 #else
759 uint32_t low, high;
760 #endif
761 } l;
762 } u, res;
763 uint64_t rl, rh;
765 u.ll = a;
766 rl = (uint64_t)u.l.low * (uint64_t)b;
767 rh = (uint64_t)u.l.high * (uint64_t)b;
768 rh += (rl >> 32);
769 res.l.high = rh / c;
770 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
771 return res.ll;
774 /***********************************************************/
775 /* real time host monotonic timer */
777 #define QEMU_TIMER_BASE 1000000000LL
779 #ifdef WIN32
781 static int64_t clock_freq;
783 static void init_get_clock(void)
785 LARGE_INTEGER freq;
786 int ret;
787 ret = QueryPerformanceFrequency(&freq);
788 if (ret == 0) {
789 fprintf(stderr, "Could not calibrate ticks\n");
790 exit(1);
792 clock_freq = freq.QuadPart;
795 static int64_t get_clock(void)
797 LARGE_INTEGER ti;
798 QueryPerformanceCounter(&ti);
799 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
802 #else
804 static int use_rt_clock;
806 static void init_get_clock(void)
808 use_rt_clock = 0;
809 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
810 || defined(__DragonFly__)
812 struct timespec ts;
813 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
814 use_rt_clock = 1;
817 #endif
820 static int64_t get_clock(void)
822 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
823 || defined(__DragonFly__)
824 if (use_rt_clock) {
825 struct timespec ts;
826 clock_gettime(CLOCK_MONOTONIC, &ts);
827 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
828 } else
829 #endif
831 /* XXX: using gettimeofday leads to problems if the date
832 changes, so it should be avoided. */
833 struct timeval tv;
834 gettimeofday(&tv, NULL);
835 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
838 #endif
840 /* Return the virtual CPU time, based on the instruction counter. */
841 static int64_t cpu_get_icount(void)
843 int64_t icount;
844 CPUState *env = cpu_single_env;;
845 icount = qemu_icount;
846 if (env) {
847 if (!can_do_io(env))
848 fprintf(stderr, "Bad clock read\n");
849 icount -= (env->icount_decr.u16.low + env->icount_extra);
851 return qemu_icount_bias + (icount << icount_time_shift);
854 /***********************************************************/
855 /* guest cycle counter */
857 static int64_t cpu_ticks_prev;
858 static int64_t cpu_ticks_offset;
859 static int64_t cpu_clock_offset;
860 static int cpu_ticks_enabled;
862 /* return the host CPU cycle counter and handle stop/restart */
863 int64_t cpu_get_ticks(void)
865 if (use_icount) {
866 return cpu_get_icount();
868 if (!cpu_ticks_enabled) {
869 return cpu_ticks_offset;
870 } else {
871 int64_t ticks;
872 ticks = cpu_get_real_ticks();
873 if (cpu_ticks_prev > ticks) {
874 /* Note: non increasing ticks may happen if the host uses
875 software suspend */
876 cpu_ticks_offset += cpu_ticks_prev - ticks;
878 cpu_ticks_prev = ticks;
879 return ticks + cpu_ticks_offset;
883 /* return the host CPU monotonic timer and handle stop/restart */
884 static int64_t cpu_get_clock(void)
886 int64_t ti;
887 if (!cpu_ticks_enabled) {
888 return cpu_clock_offset;
889 } else {
890 ti = get_clock();
891 return ti + cpu_clock_offset;
895 /* enable cpu_get_ticks() */
896 void cpu_enable_ticks(void)
898 if (!cpu_ticks_enabled) {
899 cpu_ticks_offset -= cpu_get_real_ticks();
900 cpu_clock_offset -= get_clock();
901 cpu_ticks_enabled = 1;
905 /* disable cpu_get_ticks() : the clock is stopped. You must not call
906 cpu_get_ticks() after that. */
907 void cpu_disable_ticks(void)
909 if (cpu_ticks_enabled) {
910 cpu_ticks_offset = cpu_get_ticks();
911 cpu_clock_offset = cpu_get_clock();
912 cpu_ticks_enabled = 0;
916 /***********************************************************/
917 /* timers */
919 #define QEMU_TIMER_REALTIME 0
920 #define QEMU_TIMER_VIRTUAL 1
922 struct QEMUClock {
923 int type;
924 /* XXX: add frequency */
927 struct QEMUTimer {
928 QEMUClock *clock;
929 int64_t expire_time;
930 QEMUTimerCB *cb;
931 void *opaque;
932 struct QEMUTimer *next;
935 struct qemu_alarm_timer {
936 char const *name;
937 unsigned int flags;
939 int (*start)(struct qemu_alarm_timer *t);
940 void (*stop)(struct qemu_alarm_timer *t);
941 void (*rearm)(struct qemu_alarm_timer *t);
942 void *priv;
945 #define ALARM_FLAG_DYNTICKS 0x1
946 #define ALARM_FLAG_EXPIRED 0x2
948 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
950 return t && (t->flags & ALARM_FLAG_DYNTICKS);
953 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
955 if (!alarm_has_dynticks(t))
956 return;
958 t->rearm(t);
961 /* TODO: MIN_TIMER_REARM_US should be optimized */
962 #define MIN_TIMER_REARM_US 250
964 static struct qemu_alarm_timer *alarm_timer;
966 #ifdef _WIN32
968 struct qemu_alarm_win32 {
969 MMRESULT timerId;
970 unsigned int period;
971 } alarm_win32_data = {0, -1};
973 static int win32_start_timer(struct qemu_alarm_timer *t);
974 static void win32_stop_timer(struct qemu_alarm_timer *t);
975 static void win32_rearm_timer(struct qemu_alarm_timer *t);
977 #else
979 static int unix_start_timer(struct qemu_alarm_timer *t);
980 static void unix_stop_timer(struct qemu_alarm_timer *t);
982 #ifdef __linux__
984 static int dynticks_start_timer(struct qemu_alarm_timer *t);
985 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
986 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
988 static int hpet_start_timer(struct qemu_alarm_timer *t);
989 static void hpet_stop_timer(struct qemu_alarm_timer *t);
991 static int rtc_start_timer(struct qemu_alarm_timer *t);
992 static void rtc_stop_timer(struct qemu_alarm_timer *t);
994 #endif /* __linux__ */
996 #endif /* _WIN32 */
998 /* Correlation between real and virtual time is always going to be
999 fairly approximate, so ignore small variation.
1000 When the guest is idle real and virtual time will be aligned in
1001 the IO wait loop. */
1002 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1004 static void icount_adjust(void)
1006 int64_t cur_time;
1007 int64_t cur_icount;
1008 int64_t delta;
1009 static int64_t last_delta;
1010 /* If the VM is not running, then do nothing. */
1011 if (!vm_running)
1012 return;
1014 cur_time = cpu_get_clock();
1015 cur_icount = qemu_get_clock(vm_clock);
1016 delta = cur_icount - cur_time;
1017 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1018 if (delta > 0
1019 && last_delta + ICOUNT_WOBBLE < delta * 2
1020 && icount_time_shift > 0) {
1021 /* The guest is getting too far ahead. Slow time down. */
1022 icount_time_shift--;
1024 if (delta < 0
1025 && last_delta - ICOUNT_WOBBLE > delta * 2
1026 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1027 /* The guest is getting too far behind. Speed time up. */
1028 icount_time_shift++;
1030 last_delta = delta;
1031 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1034 static void icount_adjust_rt(void * opaque)
1036 qemu_mod_timer(icount_rt_timer,
1037 qemu_get_clock(rt_clock) + 1000);
1038 icount_adjust();
1041 static void icount_adjust_vm(void * opaque)
1043 qemu_mod_timer(icount_vm_timer,
1044 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1045 icount_adjust();
1048 static void init_icount_adjust(void)
1050 /* Have both realtime and virtual time triggers for speed adjustment.
1051 The realtime trigger catches emulated time passing too slowly,
1052 the virtual time trigger catches emulated time passing too fast.
1053 Realtime triggers occur even when idle, so use them less frequently
1054 than VM triggers. */
1055 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1056 qemu_mod_timer(icount_rt_timer,
1057 qemu_get_clock(rt_clock) + 1000);
1058 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1059 qemu_mod_timer(icount_vm_timer,
1060 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1063 static struct qemu_alarm_timer alarm_timers[] = {
1064 #ifndef _WIN32
1065 #ifdef __linux__
1066 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1067 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1068 /* HPET - if available - is preferred */
1069 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1070 /* ...otherwise try RTC */
1071 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1072 #endif
1073 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1074 #else
1075 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1076 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1077 {"win32", 0, win32_start_timer,
1078 win32_stop_timer, NULL, &alarm_win32_data},
1079 #endif
1080 {NULL, }
1083 static void show_available_alarms(void)
1085 int i;
1087 printf("Available alarm timers, in order of precedence:\n");
1088 for (i = 0; alarm_timers[i].name; i++)
1089 printf("%s\n", alarm_timers[i].name);
1092 static void configure_alarms(char const *opt)
1094 int i;
1095 int cur = 0;
1096 int count = ARRAY_SIZE(alarm_timers) - 1;
1097 char *arg;
1098 char *name;
1099 struct qemu_alarm_timer tmp;
1101 if (!strcmp(opt, "?")) {
1102 show_available_alarms();
1103 exit(0);
1106 arg = strdup(opt);
1108 /* Reorder the array */
1109 name = strtok(arg, ",");
1110 while (name) {
1111 for (i = 0; i < count && alarm_timers[i].name; i++) {
1112 if (!strcmp(alarm_timers[i].name, name))
1113 break;
1116 if (i == count) {
1117 fprintf(stderr, "Unknown clock %s\n", name);
1118 goto next;
1121 if (i < cur)
1122 /* Ignore */
1123 goto next;
1125 /* Swap */
1126 tmp = alarm_timers[i];
1127 alarm_timers[i] = alarm_timers[cur];
1128 alarm_timers[cur] = tmp;
1130 cur++;
1131 next:
1132 name = strtok(NULL, ",");
1135 free(arg);
1137 if (cur) {
1138 /* Disable remaining timers */
1139 for (i = cur; i < count; i++)
1140 alarm_timers[i].name = NULL;
1141 } else {
1142 show_available_alarms();
1143 exit(1);
1147 QEMUClock *rt_clock;
1148 QEMUClock *vm_clock;
1150 static QEMUTimer *active_timers[2];
1152 static QEMUClock *qemu_new_clock(int type)
1154 QEMUClock *clock;
1155 clock = qemu_mallocz(sizeof(QEMUClock));
1156 clock->type = type;
1157 return clock;
1160 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1162 QEMUTimer *ts;
1164 ts = qemu_mallocz(sizeof(QEMUTimer));
1165 ts->clock = clock;
1166 ts->cb = cb;
1167 ts->opaque = opaque;
1168 return ts;
1171 void qemu_free_timer(QEMUTimer *ts)
1173 qemu_free(ts);
1176 /* stop a timer, but do not dealloc it */
1177 void qemu_del_timer(QEMUTimer *ts)
1179 QEMUTimer **pt, *t;
1181 /* NOTE: this code must be signal safe because
1182 qemu_timer_expired() can be called from a signal. */
1183 pt = &active_timers[ts->clock->type];
1184 for(;;) {
1185 t = *pt;
1186 if (!t)
1187 break;
1188 if (t == ts) {
1189 *pt = t->next;
1190 break;
1192 pt = &t->next;
1196 /* modify the current timer so that it will be fired when current_time
1197 >= expire_time. The corresponding callback will be called. */
1198 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1200 QEMUTimer **pt, *t;
1202 qemu_del_timer(ts);
1204 /* add the timer in the sorted list */
1205 /* NOTE: this code must be signal safe because
1206 qemu_timer_expired() can be called from a signal. */
1207 pt = &active_timers[ts->clock->type];
1208 for(;;) {
1209 t = *pt;
1210 if (!t)
1211 break;
1212 if (t->expire_time > expire_time)
1213 break;
1214 pt = &t->next;
1216 ts->expire_time = expire_time;
1217 ts->next = *pt;
1218 *pt = ts;
1220 /* Rearm if necessary */
1221 if (pt == &active_timers[ts->clock->type]) {
1222 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1223 qemu_rearm_alarm_timer(alarm_timer);
1225 /* Interrupt execution to force deadline recalculation. */
1226 if (use_icount)
1227 qemu_notify_event();
1231 int qemu_timer_pending(QEMUTimer *ts)
1233 QEMUTimer *t;
1234 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1235 if (t == ts)
1236 return 1;
1238 return 0;
1241 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1243 if (!timer_head)
1244 return 0;
1245 return (timer_head->expire_time <= current_time);
1248 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1250 QEMUTimer *ts;
1252 for(;;) {
1253 ts = *ptimer_head;
1254 if (!ts || ts->expire_time > current_time)
1255 break;
1256 /* remove timer from the list before calling the callback */
1257 *ptimer_head = ts->next;
1258 ts->next = NULL;
1260 /* run the callback (the timer list can be modified) */
1261 ts->cb(ts->opaque);
1265 int64_t qemu_get_clock(QEMUClock *clock)
1267 switch(clock->type) {
1268 case QEMU_TIMER_REALTIME:
1269 return get_clock() / 1000000;
1270 default:
1271 case QEMU_TIMER_VIRTUAL:
1272 if (use_icount) {
1273 return cpu_get_icount();
1274 } else {
1275 return cpu_get_clock();
1280 static void init_timers(void)
1282 init_get_clock();
1283 ticks_per_sec = QEMU_TIMER_BASE;
1284 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1285 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1288 /* save a timer */
1289 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1291 uint64_t expire_time;
1293 if (qemu_timer_pending(ts)) {
1294 expire_time = ts->expire_time;
1295 } else {
1296 expire_time = -1;
1298 qemu_put_be64(f, expire_time);
1301 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1303 uint64_t expire_time;
1305 expire_time = qemu_get_be64(f);
1306 if (expire_time != -1) {
1307 qemu_mod_timer(ts, expire_time);
1308 } else {
1309 qemu_del_timer(ts);
1313 static void timer_save(QEMUFile *f, void *opaque)
1315 if (cpu_ticks_enabled) {
1316 hw_error("cannot save state if virtual timers are running");
1318 qemu_put_be64(f, cpu_ticks_offset);
1319 qemu_put_be64(f, ticks_per_sec);
1320 qemu_put_be64(f, cpu_clock_offset);
1323 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1325 if (version_id != 1 && version_id != 2)
1326 return -EINVAL;
1327 if (cpu_ticks_enabled) {
1328 return -EINVAL;
1330 cpu_ticks_offset=qemu_get_be64(f);
1331 ticks_per_sec=qemu_get_be64(f);
1332 if (version_id == 2) {
1333 cpu_clock_offset=qemu_get_be64(f);
1335 return 0;
1338 static void qemu_event_increment(void);
1340 #ifdef _WIN32
1341 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1342 DWORD_PTR dwUser, DWORD_PTR dw1,
1343 DWORD_PTR dw2)
1344 #else
1345 static void host_alarm_handler(int host_signum)
1346 #endif
1348 #if 0
1349 #define DISP_FREQ 1000
1351 static int64_t delta_min = INT64_MAX;
1352 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1353 static int count;
1354 ti = qemu_get_clock(vm_clock);
1355 if (last_clock != 0) {
1356 delta = ti - last_clock;
1357 if (delta < delta_min)
1358 delta_min = delta;
1359 if (delta > delta_max)
1360 delta_max = delta;
1361 delta_cum += delta;
1362 if (++count == DISP_FREQ) {
1363 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1364 muldiv64(delta_min, 1000000, ticks_per_sec),
1365 muldiv64(delta_max, 1000000, ticks_per_sec),
1366 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1367 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1368 count = 0;
1369 delta_min = INT64_MAX;
1370 delta_max = 0;
1371 delta_cum = 0;
1374 last_clock = ti;
1376 #endif
1377 if (alarm_has_dynticks(alarm_timer) ||
1378 (!use_icount &&
1379 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1380 qemu_get_clock(vm_clock))) ||
1381 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1382 qemu_get_clock(rt_clock))) {
1383 qemu_event_increment();
1384 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1386 #ifndef CONFIG_IOTHREAD
1387 if (next_cpu) {
1388 /* stop the currently executing cpu because a timer occured */
1389 cpu_exit(next_cpu);
1390 #ifdef CONFIG_KQEMU
1391 if (next_cpu->kqemu_enabled) {
1392 kqemu_cpu_interrupt(next_cpu);
1394 #endif
1396 #endif
1397 timer_alarm_pending = 1;
1398 qemu_notify_event();
1402 static int64_t qemu_next_deadline(void)
1404 int64_t delta;
1406 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1407 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1408 qemu_get_clock(vm_clock);
1409 } else {
1410 /* To avoid problems with overflow limit this to 2^32. */
1411 delta = INT32_MAX;
1414 if (delta < 0)
1415 delta = 0;
1417 return delta;
1420 #if defined(__linux__) || defined(_WIN32)
1421 static uint64_t qemu_next_deadline_dyntick(void)
1423 int64_t delta;
1424 int64_t rtdelta;
1426 if (use_icount)
1427 delta = INT32_MAX;
1428 else
1429 delta = (qemu_next_deadline() + 999) / 1000;
1431 if (active_timers[QEMU_TIMER_REALTIME]) {
1432 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1433 qemu_get_clock(rt_clock))*1000;
1434 if (rtdelta < delta)
1435 delta = rtdelta;
1438 if (delta < MIN_TIMER_REARM_US)
1439 delta = MIN_TIMER_REARM_US;
1441 return delta;
1443 #endif
1445 #ifndef _WIN32
1447 /* Sets a specific flag */
1448 static int fcntl_setfl(int fd, int flag)
1450 int flags;
1452 flags = fcntl(fd, F_GETFL);
1453 if (flags == -1)
1454 return -errno;
1456 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1457 return -errno;
1459 return 0;
1462 #if defined(__linux__)
1464 #define RTC_FREQ 1024
1466 static void enable_sigio_timer(int fd)
1468 struct sigaction act;
1470 /* timer signal */
1471 sigfillset(&act.sa_mask);
1472 act.sa_flags = 0;
1473 act.sa_handler = host_alarm_handler;
1475 sigaction(SIGIO, &act, NULL);
1476 fcntl_setfl(fd, O_ASYNC);
1477 fcntl(fd, F_SETOWN, getpid());
1480 static int hpet_start_timer(struct qemu_alarm_timer *t)
1482 struct hpet_info info;
1483 int r, fd;
1485 fd = open("/dev/hpet", O_RDONLY);
1486 if (fd < 0)
1487 return -1;
1489 /* Set frequency */
1490 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1491 if (r < 0) {
1492 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1493 "error, but for better emulation accuracy type:\n"
1494 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1495 goto fail;
1498 /* Check capabilities */
1499 r = ioctl(fd, HPET_INFO, &info);
1500 if (r < 0)
1501 goto fail;
1503 /* Enable periodic mode */
1504 r = ioctl(fd, HPET_EPI, 0);
1505 if (info.hi_flags && (r < 0))
1506 goto fail;
1508 /* Enable interrupt */
1509 r = ioctl(fd, HPET_IE_ON, 0);
1510 if (r < 0)
1511 goto fail;
1513 enable_sigio_timer(fd);
1514 t->priv = (void *)(long)fd;
1516 return 0;
1517 fail:
1518 close(fd);
1519 return -1;
1522 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1524 int fd = (long)t->priv;
1526 close(fd);
1529 static int rtc_start_timer(struct qemu_alarm_timer *t)
1531 int rtc_fd;
1532 unsigned long current_rtc_freq = 0;
1534 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1535 if (rtc_fd < 0)
1536 return -1;
1537 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1538 if (current_rtc_freq != RTC_FREQ &&
1539 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1540 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1541 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1542 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1543 goto fail;
1545 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1546 fail:
1547 close(rtc_fd);
1548 return -1;
1551 enable_sigio_timer(rtc_fd);
1553 t->priv = (void *)(long)rtc_fd;
1555 return 0;
1558 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1560 int rtc_fd = (long)t->priv;
1562 close(rtc_fd);
1565 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1567 struct sigevent ev;
1568 timer_t host_timer;
1569 struct sigaction act;
1571 sigfillset(&act.sa_mask);
1572 act.sa_flags = 0;
1573 act.sa_handler = host_alarm_handler;
1575 sigaction(SIGALRM, &act, NULL);
1578 * Initialize ev struct to 0 to avoid valgrind complaining
1579 * about uninitialized data in timer_create call
1581 memset(&ev, 0, sizeof(ev));
1582 ev.sigev_value.sival_int = 0;
1583 ev.sigev_notify = SIGEV_SIGNAL;
1584 ev.sigev_signo = SIGALRM;
1586 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1587 perror("timer_create");
1589 /* disable dynticks */
1590 fprintf(stderr, "Dynamic Ticks disabled\n");
1592 return -1;
1595 t->priv = (void *)(long)host_timer;
1597 return 0;
1600 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1602 timer_t host_timer = (timer_t)(long)t->priv;
1604 timer_delete(host_timer);
1607 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1609 timer_t host_timer = (timer_t)(long)t->priv;
1610 struct itimerspec timeout;
1611 int64_t nearest_delta_us = INT64_MAX;
1612 int64_t current_us;
1614 if (!active_timers[QEMU_TIMER_REALTIME] &&
1615 !active_timers[QEMU_TIMER_VIRTUAL])
1616 return;
1618 nearest_delta_us = qemu_next_deadline_dyntick();
1620 /* check whether a timer is already running */
1621 if (timer_gettime(host_timer, &timeout)) {
1622 perror("gettime");
1623 fprintf(stderr, "Internal timer error: aborting\n");
1624 exit(1);
1626 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1627 if (current_us && current_us <= nearest_delta_us)
1628 return;
1630 timeout.it_interval.tv_sec = 0;
1631 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1632 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1633 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1634 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1635 perror("settime");
1636 fprintf(stderr, "Internal timer error: aborting\n");
1637 exit(1);
1641 #endif /* defined(__linux__) */
1643 static int unix_start_timer(struct qemu_alarm_timer *t)
1645 struct sigaction act;
1646 struct itimerval itv;
1647 int err;
1649 /* timer signal */
1650 sigfillset(&act.sa_mask);
1651 act.sa_flags = 0;
1652 act.sa_handler = host_alarm_handler;
1654 sigaction(SIGALRM, &act, NULL);
1656 itv.it_interval.tv_sec = 0;
1657 /* for i386 kernel 2.6 to get 1 ms */
1658 itv.it_interval.tv_usec = 999;
1659 itv.it_value.tv_sec = 0;
1660 itv.it_value.tv_usec = 10 * 1000;
1662 err = setitimer(ITIMER_REAL, &itv, NULL);
1663 if (err)
1664 return -1;
1666 return 0;
1669 static void unix_stop_timer(struct qemu_alarm_timer *t)
1671 struct itimerval itv;
1673 memset(&itv, 0, sizeof(itv));
1674 setitimer(ITIMER_REAL, &itv, NULL);
1677 #endif /* !defined(_WIN32) */
1680 #ifdef _WIN32
1682 static int win32_start_timer(struct qemu_alarm_timer *t)
1684 TIMECAPS tc;
1685 struct qemu_alarm_win32 *data = t->priv;
1686 UINT flags;
1688 memset(&tc, 0, sizeof(tc));
1689 timeGetDevCaps(&tc, sizeof(tc));
1691 if (data->period < tc.wPeriodMin)
1692 data->period = tc.wPeriodMin;
1694 timeBeginPeriod(data->period);
1696 flags = TIME_CALLBACK_FUNCTION;
1697 if (alarm_has_dynticks(t))
1698 flags |= TIME_ONESHOT;
1699 else
1700 flags |= TIME_PERIODIC;
1702 data->timerId = timeSetEvent(1, // interval (ms)
1703 data->period, // resolution
1704 host_alarm_handler, // function
1705 (DWORD)t, // parameter
1706 flags);
1708 if (!data->timerId) {
1709 perror("Failed to initialize win32 alarm timer");
1710 timeEndPeriod(data->period);
1711 return -1;
1714 return 0;
1717 static void win32_stop_timer(struct qemu_alarm_timer *t)
1719 struct qemu_alarm_win32 *data = t->priv;
1721 timeKillEvent(data->timerId);
1722 timeEndPeriod(data->period);
1725 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1727 struct qemu_alarm_win32 *data = t->priv;
1728 uint64_t nearest_delta_us;
1730 if (!active_timers[QEMU_TIMER_REALTIME] &&
1731 !active_timers[QEMU_TIMER_VIRTUAL])
1732 return;
1734 nearest_delta_us = qemu_next_deadline_dyntick();
1735 nearest_delta_us /= 1000;
1737 timeKillEvent(data->timerId);
1739 data->timerId = timeSetEvent(1,
1740 data->period,
1741 host_alarm_handler,
1742 (DWORD)t,
1743 TIME_ONESHOT | TIME_PERIODIC);
1745 if (!data->timerId) {
1746 perror("Failed to re-arm win32 alarm timer");
1748 timeEndPeriod(data->period);
1749 exit(1);
1753 #endif /* _WIN32 */
1755 static int init_timer_alarm(void)
1757 struct qemu_alarm_timer *t = NULL;
1758 int i, err = -1;
1760 for (i = 0; alarm_timers[i].name; i++) {
1761 t = &alarm_timers[i];
1763 err = t->start(t);
1764 if (!err)
1765 break;
1768 if (err) {
1769 err = -ENOENT;
1770 goto fail;
1773 alarm_timer = t;
1775 return 0;
1777 fail:
1778 return err;
1781 static void quit_timers(void)
1783 alarm_timer->stop(alarm_timer);
1784 alarm_timer = NULL;
1787 /***********************************************************/
1788 /* host time/date access */
1789 void qemu_get_timedate(struct tm *tm, int offset)
1791 time_t ti;
1792 struct tm *ret;
1794 time(&ti);
1795 ti += offset;
1796 if (rtc_date_offset == -1) {
1797 if (rtc_utc)
1798 ret = gmtime(&ti);
1799 else
1800 ret = localtime(&ti);
1801 } else {
1802 ti -= rtc_date_offset;
1803 ret = gmtime(&ti);
1806 memcpy(tm, ret, sizeof(struct tm));
1809 int qemu_timedate_diff(struct tm *tm)
1811 time_t seconds;
1813 if (rtc_date_offset == -1)
1814 if (rtc_utc)
1815 seconds = mktimegm(tm);
1816 else
1817 seconds = mktime(tm);
1818 else
1819 seconds = mktimegm(tm) + rtc_date_offset;
1821 return seconds - time(NULL);
1824 #ifdef _WIN32
1825 static void socket_cleanup(void)
1827 WSACleanup();
1830 static int socket_init(void)
1832 WSADATA Data;
1833 int ret, err;
1835 ret = WSAStartup(MAKEWORD(2,2), &Data);
1836 if (ret != 0) {
1837 err = WSAGetLastError();
1838 fprintf(stderr, "WSAStartup: %d\n", err);
1839 return -1;
1841 atexit(socket_cleanup);
1842 return 0;
1844 #endif
1846 const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
1848 char *q;
1850 q = buf;
1851 while (*p != '\0' && *p != delim) {
1852 if (q && (q - buf) < buf_size - 1)
1853 *q++ = *p;
1854 p++;
1856 if (q)
1857 *q = '\0';
1859 return p;
1862 const char *get_opt_value(char *buf, int buf_size, const char *p)
1864 char *q;
1866 q = buf;
1867 while (*p != '\0') {
1868 if (*p == ',') {
1869 if (*(p + 1) != ',')
1870 break;
1871 p++;
1873 if (q && (q - buf) < buf_size - 1)
1874 *q++ = *p;
1875 p++;
1877 if (q)
1878 *q = '\0';
1880 return p;
1883 int get_param_value(char *buf, int buf_size,
1884 const char *tag, const char *str)
1886 const char *p;
1887 char option[128];
1889 p = str;
1890 for(;;) {
1891 p = get_opt_name(option, sizeof(option), p, '=');
1892 if (*p != '=')
1893 break;
1894 p++;
1895 if (!strcmp(tag, option)) {
1896 (void)get_opt_value(buf, buf_size, p);
1897 return strlen(buf);
1898 } else {
1899 p = get_opt_value(NULL, 0, p);
1901 if (*p != ',')
1902 break;
1903 p++;
1905 return 0;
1908 int check_params(const char * const *params, const char *str)
1910 int name_buf_size = 1;
1911 const char *p;
1912 char *name_buf;
1913 int i, len;
1914 int ret = 0;
1916 for (i = 0; params[i] != NULL; i++) {
1917 len = strlen(params[i]) + 1;
1918 if (len > name_buf_size) {
1919 name_buf_size = len;
1922 name_buf = qemu_malloc(name_buf_size);
1924 p = str;
1925 while (*p != '\0') {
1926 p = get_opt_name(name_buf, name_buf_size, p, '=');
1927 if (*p != '=') {
1928 ret = -1;
1929 break;
1931 p++;
1932 for(i = 0; params[i] != NULL; i++)
1933 if (!strcmp(params[i], name_buf))
1934 break;
1935 if (params[i] == NULL) {
1936 ret = -1;
1937 break;
1939 p = get_opt_value(NULL, 0, p);
1940 if (*p != ',')
1941 break;
1942 p++;
1945 qemu_free(name_buf);
1946 return ret;
1949 /***********************************************************/
1950 /* Bluetooth support */
1951 static int nb_hcis;
1952 static int cur_hci;
1953 static struct HCIInfo *hci_table[MAX_NICS];
1955 static struct bt_vlan_s {
1956 struct bt_scatternet_s net;
1957 int id;
1958 struct bt_vlan_s *next;
1959 } *first_bt_vlan;
1961 /* find or alloc a new bluetooth "VLAN" */
1962 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1964 struct bt_vlan_s **pvlan, *vlan;
1965 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1966 if (vlan->id == id)
1967 return &vlan->net;
1969 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1970 vlan->id = id;
1971 pvlan = &first_bt_vlan;
1972 while (*pvlan != NULL)
1973 pvlan = &(*pvlan)->next;
1974 *pvlan = vlan;
1975 return &vlan->net;
1978 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1982 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1984 return -ENOTSUP;
1987 static struct HCIInfo null_hci = {
1988 .cmd_send = null_hci_send,
1989 .sco_send = null_hci_send,
1990 .acl_send = null_hci_send,
1991 .bdaddr_set = null_hci_addr_set,
1994 struct HCIInfo *qemu_next_hci(void)
1996 if (cur_hci == nb_hcis)
1997 return &null_hci;
1999 return hci_table[cur_hci++];
2002 static struct HCIInfo *hci_init(const char *str)
2004 char *endp;
2005 struct bt_scatternet_s *vlan = 0;
2007 if (!strcmp(str, "null"))
2008 /* null */
2009 return &null_hci;
2010 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2011 /* host[:hciN] */
2012 return bt_host_hci(str[4] ? str + 5 : "hci0");
2013 else if (!strncmp(str, "hci", 3)) {
2014 /* hci[,vlan=n] */
2015 if (str[3]) {
2016 if (!strncmp(str + 3, ",vlan=", 6)) {
2017 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2018 if (*endp)
2019 vlan = 0;
2021 } else
2022 vlan = qemu_find_bt_vlan(0);
2023 if (vlan)
2024 return bt_new_hci(vlan);
2027 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2029 return 0;
2032 static int bt_hci_parse(const char *str)
2034 struct HCIInfo *hci;
2035 bdaddr_t bdaddr;
2037 if (nb_hcis >= MAX_NICS) {
2038 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2039 return -1;
2042 hci = hci_init(str);
2043 if (!hci)
2044 return -1;
2046 bdaddr.b[0] = 0x52;
2047 bdaddr.b[1] = 0x54;
2048 bdaddr.b[2] = 0x00;
2049 bdaddr.b[3] = 0x12;
2050 bdaddr.b[4] = 0x34;
2051 bdaddr.b[5] = 0x56 + nb_hcis;
2052 hci->bdaddr_set(hci, bdaddr.b);
2054 hci_table[nb_hcis++] = hci;
2056 return 0;
2059 static void bt_vhci_add(int vlan_id)
2061 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2063 if (!vlan->slave)
2064 fprintf(stderr, "qemu: warning: adding a VHCI to "
2065 "an empty scatternet %i\n", vlan_id);
2067 bt_vhci_init(bt_new_hci(vlan));
2070 static struct bt_device_s *bt_device_add(const char *opt)
2072 struct bt_scatternet_s *vlan;
2073 int vlan_id = 0;
2074 char *endp = strstr(opt, ",vlan=");
2075 int len = (endp ? endp - opt : strlen(opt)) + 1;
2076 char devname[10];
2078 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2080 if (endp) {
2081 vlan_id = strtol(endp + 6, &endp, 0);
2082 if (*endp) {
2083 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2084 return 0;
2088 vlan = qemu_find_bt_vlan(vlan_id);
2090 if (!vlan->slave)
2091 fprintf(stderr, "qemu: warning: adding a slave device to "
2092 "an empty scatternet %i\n", vlan_id);
2094 if (!strcmp(devname, "keyboard"))
2095 return bt_keyboard_init(vlan);
2097 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2098 return 0;
2101 static int bt_parse(const char *opt)
2103 const char *endp, *p;
2104 int vlan;
2106 if (strstart(opt, "hci", &endp)) {
2107 if (!*endp || *endp == ',') {
2108 if (*endp)
2109 if (!strstart(endp, ",vlan=", 0))
2110 opt = endp + 1;
2112 return bt_hci_parse(opt);
2114 } else if (strstart(opt, "vhci", &endp)) {
2115 if (!*endp || *endp == ',') {
2116 if (*endp) {
2117 if (strstart(endp, ",vlan=", &p)) {
2118 vlan = strtol(p, (char **) &endp, 0);
2119 if (*endp) {
2120 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2121 return 1;
2123 } else {
2124 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2125 return 1;
2127 } else
2128 vlan = 0;
2130 bt_vhci_add(vlan);
2131 return 0;
2133 } else if (strstart(opt, "device:", &endp))
2134 return !bt_device_add(endp);
2136 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2137 return 1;
2140 /***********************************************************/
2141 /* QEMU Block devices */
2143 #define HD_ALIAS "index=%d,media=disk"
2144 #define CDROM_ALIAS "index=2,media=cdrom"
2145 #define FD_ALIAS "index=%d,if=floppy"
2146 #define PFLASH_ALIAS "if=pflash"
2147 #define MTD_ALIAS "if=mtd"
2148 #define SD_ALIAS "index=0,if=sd"
2150 static int drive_opt_get_free_idx(void)
2152 int index;
2154 for (index = 0; index < MAX_DRIVES; index++)
2155 if (!drives_opt[index].used) {
2156 drives_opt[index].used = 1;
2157 return index;
2160 return -1;
2163 static int drive_get_free_idx(void)
2165 int index;
2167 for (index = 0; index < MAX_DRIVES; index++)
2168 if (!drives_table[index].used) {
2169 drives_table[index].used = 1;
2170 return index;
2173 return -1;
2176 int drive_add(const char *file, const char *fmt, ...)
2178 va_list ap;
2179 int index = drive_opt_get_free_idx();
2181 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2182 fprintf(stderr, "qemu: too many drives\n");
2183 return -1;
2186 drives_opt[index].file = file;
2187 va_start(ap, fmt);
2188 vsnprintf(drives_opt[index].opt,
2189 sizeof(drives_opt[0].opt), fmt, ap);
2190 va_end(ap);
2192 nb_drives_opt++;
2193 return index;
2196 void drive_remove(int index)
2198 drives_opt[index].used = 0;
2199 nb_drives_opt--;
2202 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2204 int index;
2206 /* seek interface, bus and unit */
2208 for (index = 0; index < MAX_DRIVES; index++)
2209 if (drives_table[index].type == type &&
2210 drives_table[index].bus == bus &&
2211 drives_table[index].unit == unit &&
2212 drives_table[index].used)
2213 return index;
2215 return -1;
2218 int drive_get_max_bus(BlockInterfaceType type)
2220 int max_bus;
2221 int index;
2223 max_bus = -1;
2224 for (index = 0; index < nb_drives; index++) {
2225 if(drives_table[index].type == type &&
2226 drives_table[index].bus > max_bus)
2227 max_bus = drives_table[index].bus;
2229 return max_bus;
2232 const char *drive_get_serial(BlockDriverState *bdrv)
2234 int index;
2236 for (index = 0; index < nb_drives; index++)
2237 if (drives_table[index].bdrv == bdrv)
2238 return drives_table[index].serial;
2240 return "\0";
2243 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2245 int index;
2247 for (index = 0; index < nb_drives; index++)
2248 if (drives_table[index].bdrv == bdrv)
2249 return drives_table[index].onerror;
2251 return BLOCK_ERR_STOP_ENOSPC;
2254 static void bdrv_format_print(void *opaque, const char *name)
2256 fprintf(stderr, " %s", name);
2259 void drive_uninit(BlockDriverState *bdrv)
2261 int i;
2263 for (i = 0; i < MAX_DRIVES; i++)
2264 if (drives_table[i].bdrv == bdrv) {
2265 drives_table[i].bdrv = NULL;
2266 drives_table[i].used = 0;
2267 drive_remove(drives_table[i].drive_opt_idx);
2268 nb_drives--;
2269 break;
2273 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2275 char buf[128];
2276 char file[1024];
2277 char devname[128];
2278 char serial[21];
2279 const char *mediastr = "";
2280 BlockInterfaceType type;
2281 enum { MEDIA_DISK, MEDIA_CDROM } media;
2282 int bus_id, unit_id;
2283 int cyls, heads, secs, translation;
2284 BlockDriverState *bdrv;
2285 BlockDriver *drv = NULL;
2286 QEMUMachine *machine = opaque;
2287 int max_devs;
2288 int index;
2289 int cache;
2290 int bdrv_flags, onerror;
2291 int drives_table_idx;
2292 char *str = arg->opt;
2293 static const char * const params[] = { "bus", "unit", "if", "index",
2294 "cyls", "heads", "secs", "trans",
2295 "media", "snapshot", "file",
2296 "cache", "format", "serial", "werror",
2297 "boot", NULL };
2299 if (check_params(params, str) < 0) {
2300 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2301 buf, str);
2302 return -1;
2305 file[0] = 0;
2306 cyls = heads = secs = 0;
2307 bus_id = 0;
2308 unit_id = -1;
2309 translation = BIOS_ATA_TRANSLATION_AUTO;
2310 index = -1;
2311 cache = 3;
2313 if (machine->use_scsi) {
2314 type = IF_SCSI;
2315 max_devs = MAX_SCSI_DEVS;
2316 pstrcpy(devname, sizeof(devname), "scsi");
2317 } else {
2318 type = IF_IDE;
2319 max_devs = MAX_IDE_DEVS;
2320 pstrcpy(devname, sizeof(devname), "ide");
2322 media = MEDIA_DISK;
2324 /* extract parameters */
2326 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2327 bus_id = strtol(buf, NULL, 0);
2328 if (bus_id < 0) {
2329 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2330 return -1;
2334 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2335 unit_id = strtol(buf, NULL, 0);
2336 if (unit_id < 0) {
2337 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2338 return -1;
2342 if (get_param_value(buf, sizeof(buf), "if", str)) {
2343 pstrcpy(devname, sizeof(devname), buf);
2344 if (!strcmp(buf, "ide")) {
2345 type = IF_IDE;
2346 max_devs = MAX_IDE_DEVS;
2347 } else if (!strcmp(buf, "scsi")) {
2348 type = IF_SCSI;
2349 max_devs = MAX_SCSI_DEVS;
2350 } else if (!strcmp(buf, "floppy")) {
2351 type = IF_FLOPPY;
2352 max_devs = 0;
2353 } else if (!strcmp(buf, "pflash")) {
2354 type = IF_PFLASH;
2355 max_devs = 0;
2356 } else if (!strcmp(buf, "mtd")) {
2357 type = IF_MTD;
2358 max_devs = 0;
2359 } else if (!strcmp(buf, "sd")) {
2360 type = IF_SD;
2361 max_devs = 0;
2362 } else if (!strcmp(buf, "virtio")) {
2363 type = IF_VIRTIO;
2364 max_devs = 0;
2365 } else if (!strcmp(buf, "xen")) {
2366 type = IF_XEN;
2367 max_devs = 0;
2368 } else {
2369 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2370 return -1;
2374 if (get_param_value(buf, sizeof(buf), "index", str)) {
2375 index = strtol(buf, NULL, 0);
2376 if (index < 0) {
2377 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2378 return -1;
2382 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2383 cyls = strtol(buf, NULL, 0);
2386 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2387 heads = strtol(buf, NULL, 0);
2390 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2391 secs = strtol(buf, NULL, 0);
2394 if (cyls || heads || secs) {
2395 if (cyls < 1 || cyls > 16383) {
2396 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2397 return -1;
2399 if (heads < 1 || heads > 16) {
2400 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2401 return -1;
2403 if (secs < 1 || secs > 63) {
2404 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2405 return -1;
2409 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2410 if (!cyls) {
2411 fprintf(stderr,
2412 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2413 str);
2414 return -1;
2416 if (!strcmp(buf, "none"))
2417 translation = BIOS_ATA_TRANSLATION_NONE;
2418 else if (!strcmp(buf, "lba"))
2419 translation = BIOS_ATA_TRANSLATION_LBA;
2420 else if (!strcmp(buf, "auto"))
2421 translation = BIOS_ATA_TRANSLATION_AUTO;
2422 else {
2423 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2424 return -1;
2428 if (get_param_value(buf, sizeof(buf), "media", str)) {
2429 if (!strcmp(buf, "disk")) {
2430 media = MEDIA_DISK;
2431 } else if (!strcmp(buf, "cdrom")) {
2432 if (cyls || secs || heads) {
2433 fprintf(stderr,
2434 "qemu: '%s' invalid physical CHS format\n", str);
2435 return -1;
2437 media = MEDIA_CDROM;
2438 } else {
2439 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2440 return -1;
2444 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2445 if (!strcmp(buf, "on"))
2446 snapshot = 1;
2447 else if (!strcmp(buf, "off"))
2448 snapshot = 0;
2449 else {
2450 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2451 return -1;
2455 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2456 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2457 cache = 0;
2458 else if (!strcmp(buf, "writethrough"))
2459 cache = 1;
2460 else if (!strcmp(buf, "writeback"))
2461 cache = 2;
2462 else {
2463 fprintf(stderr, "qemu: invalid cache option\n");
2464 return -1;
2468 if (get_param_value(buf, sizeof(buf), "format", str)) {
2469 if (strcmp(buf, "?") == 0) {
2470 fprintf(stderr, "qemu: Supported formats:");
2471 bdrv_iterate_format(bdrv_format_print, NULL);
2472 fprintf(stderr, "\n");
2473 return -1;
2475 drv = bdrv_find_format(buf);
2476 if (!drv) {
2477 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2478 return -1;
2482 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2483 if (!strcmp(buf, "on")) {
2484 if (extboot_drive != -1) {
2485 fprintf(stderr, "qemu: two bootable drives specified\n");
2486 return -1;
2488 extboot_drive = nb_drives;
2489 } else if (strcmp(buf, "off")) {
2490 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2491 return -1;
2495 if (arg->file == NULL)
2496 get_param_value(file, sizeof(file), "file", str);
2497 else
2498 pstrcpy(file, sizeof(file), arg->file);
2500 if (!get_param_value(serial, sizeof(serial), "serial", str))
2501 memset(serial, 0, sizeof(serial));
2503 onerror = BLOCK_ERR_STOP_ENOSPC;
2504 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2505 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2506 fprintf(stderr, "werror is no supported by this format\n");
2507 return -1;
2509 if (!strcmp(buf, "ignore"))
2510 onerror = BLOCK_ERR_IGNORE;
2511 else if (!strcmp(buf, "enospc"))
2512 onerror = BLOCK_ERR_STOP_ENOSPC;
2513 else if (!strcmp(buf, "stop"))
2514 onerror = BLOCK_ERR_STOP_ANY;
2515 else if (!strcmp(buf, "report"))
2516 onerror = BLOCK_ERR_REPORT;
2517 else {
2518 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2519 return -1;
2523 /* compute bus and unit according index */
2525 if (index != -1) {
2526 if (bus_id != 0 || unit_id != -1) {
2527 fprintf(stderr,
2528 "qemu: '%s' index cannot be used with bus and unit\n", str);
2529 return -1;
2531 if (max_devs == 0)
2533 unit_id = index;
2534 bus_id = 0;
2535 } else {
2536 unit_id = index % max_devs;
2537 bus_id = index / max_devs;
2541 /* if user doesn't specify a unit_id,
2542 * try to find the first free
2545 if (unit_id == -1) {
2546 unit_id = 0;
2547 while (drive_get_index(type, bus_id, unit_id) != -1) {
2548 unit_id++;
2549 if (max_devs && unit_id >= max_devs) {
2550 unit_id -= max_devs;
2551 bus_id++;
2556 /* check unit id */
2558 if (max_devs && unit_id >= max_devs) {
2559 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2560 str, unit_id, max_devs - 1);
2561 return -1;
2565 * ignore multiple definitions
2568 if (drive_get_index(type, bus_id, unit_id) != -1)
2569 return -2;
2571 /* init */
2573 if (type == IF_IDE || type == IF_SCSI)
2574 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2575 if (max_devs)
2576 snprintf(buf, sizeof(buf), "%s%i%s%i",
2577 devname, bus_id, mediastr, unit_id);
2578 else
2579 snprintf(buf, sizeof(buf), "%s%s%i",
2580 devname, mediastr, unit_id);
2581 bdrv = bdrv_new(buf);
2582 drives_table_idx = drive_get_free_idx();
2583 drives_table[drives_table_idx].bdrv = bdrv;
2584 drives_table[drives_table_idx].type = type;
2585 drives_table[drives_table_idx].bus = bus_id;
2586 drives_table[drives_table_idx].unit = unit_id;
2587 drives_table[drives_table_idx].onerror = onerror;
2588 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2589 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2590 nb_drives++;
2592 switch(type) {
2593 case IF_IDE:
2594 case IF_SCSI:
2595 case IF_XEN:
2596 switch(media) {
2597 case MEDIA_DISK:
2598 if (cyls != 0) {
2599 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2600 bdrv_set_translation_hint(bdrv, translation);
2602 break;
2603 case MEDIA_CDROM:
2604 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2605 break;
2607 break;
2608 case IF_SD:
2609 /* FIXME: This isn't really a floppy, but it's a reasonable
2610 approximation. */
2611 case IF_FLOPPY:
2612 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2613 break;
2614 case IF_PFLASH:
2615 case IF_MTD:
2616 case IF_VIRTIO:
2617 break;
2618 case IF_COUNT:
2619 abort();
2621 if (!file[0])
2622 return -2;
2623 bdrv_flags = 0;
2624 if (snapshot) {
2625 bdrv_flags |= BDRV_O_SNAPSHOT;
2626 cache = 2; /* always use write-back with snapshot */
2628 if (cache == 0) /* no caching */
2629 bdrv_flags |= BDRV_O_NOCACHE;
2630 else if (cache == 2) /* write-back */
2631 bdrv_flags |= BDRV_O_CACHE_WB;
2632 else if (cache == 3) /* not specified */
2633 bdrv_flags |= BDRV_O_CACHE_DEF;
2634 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2635 fprintf(stderr, "qemu: could not open disk image %s\n",
2636 file);
2637 return -1;
2639 if (bdrv_key_required(bdrv))
2640 autostart = 0;
2641 return drives_table_idx;
2644 static void numa_add(const char *optarg)
2646 char option[128];
2647 char *endptr;
2648 unsigned long long value, endvalue;
2649 int nodenr;
2651 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2652 if (!strcmp(option, "node")) {
2653 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2654 nodenr = nb_numa_nodes;
2655 } else {
2656 nodenr = strtoull(option, NULL, 10);
2659 if (get_param_value(option, 128, "mem", optarg) == 0) {
2660 node_mem[nodenr] = 0;
2661 } else {
2662 value = strtoull(option, &endptr, 0);
2663 switch (*endptr) {
2664 case 0: case 'M': case 'm':
2665 value <<= 20;
2666 break;
2667 case 'G': case 'g':
2668 value <<= 30;
2669 break;
2671 node_mem[nodenr] = value;
2673 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2674 node_cpumask[nodenr] = 0;
2675 } else {
2676 value = strtoull(option, &endptr, 10);
2677 if (value >= 64) {
2678 value = 63;
2679 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2680 } else {
2681 if (*endptr == '-') {
2682 endvalue = strtoull(endptr+1, &endptr, 10);
2683 if (endvalue >= 63) {
2684 endvalue = 62;
2685 fprintf(stderr,
2686 "only 63 CPUs in NUMA mode supported.\n");
2688 value = (1 << (endvalue + 1)) - (1 << value);
2689 } else {
2690 value = 1 << value;
2693 node_cpumask[nodenr] = value;
2695 nb_numa_nodes++;
2697 return;
2700 /***********************************************************/
2701 /* USB devices */
2703 static USBPort *used_usb_ports;
2704 static USBPort *free_usb_ports;
2706 /* ??? Maybe change this to register a hub to keep track of the topology. */
2707 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2708 usb_attachfn attach)
2710 port->opaque = opaque;
2711 port->index = index;
2712 port->attach = attach;
2713 port->next = free_usb_ports;
2714 free_usb_ports = port;
2717 int usb_device_add_dev(USBDevice *dev)
2719 USBPort *port;
2721 /* Find a USB port to add the device to. */
2722 port = free_usb_ports;
2723 if (!port->next) {
2724 USBDevice *hub;
2726 /* Create a new hub and chain it on. */
2727 free_usb_ports = NULL;
2728 port->next = used_usb_ports;
2729 used_usb_ports = port;
2731 hub = usb_hub_init(VM_USB_HUB_SIZE);
2732 usb_attach(port, hub);
2733 port = free_usb_ports;
2736 free_usb_ports = port->next;
2737 port->next = used_usb_ports;
2738 used_usb_ports = port;
2739 usb_attach(port, dev);
2740 return 0;
2743 static void usb_msd_password_cb(void *opaque, int err)
2745 USBDevice *dev = opaque;
2747 if (!err)
2748 usb_device_add_dev(dev);
2749 else
2750 dev->handle_destroy(dev);
2753 static int usb_device_add(const char *devname, int is_hotplug)
2755 const char *p;
2756 USBDevice *dev;
2758 if (!free_usb_ports)
2759 return -1;
2761 if (strstart(devname, "host:", &p)) {
2762 dev = usb_host_device_open(p);
2763 } else if (!strcmp(devname, "mouse")) {
2764 dev = usb_mouse_init();
2765 } else if (!strcmp(devname, "tablet")) {
2766 dev = usb_tablet_init();
2767 } else if (!strcmp(devname, "keyboard")) {
2768 dev = usb_keyboard_init();
2769 } else if (strstart(devname, "disk:", &p)) {
2770 BlockDriverState *bs;
2772 dev = usb_msd_init(p);
2773 if (!dev)
2774 return -1;
2775 bs = usb_msd_get_bdrv(dev);
2776 if (bdrv_key_required(bs)) {
2777 autostart = 0;
2778 if (is_hotplug) {
2779 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2780 dev);
2781 return 0;
2784 } else if (!strcmp(devname, "wacom-tablet")) {
2785 dev = usb_wacom_init();
2786 } else if (strstart(devname, "serial:", &p)) {
2787 dev = usb_serial_init(p);
2788 #ifdef CONFIG_BRLAPI
2789 } else if (!strcmp(devname, "braille")) {
2790 dev = usb_baum_init();
2791 #endif
2792 } else if (strstart(devname, "net:", &p)) {
2793 int nic = nb_nics;
2795 if (net_client_init("nic", p) < 0)
2796 return -1;
2797 nd_table[nic].model = "usb";
2798 dev = usb_net_init(&nd_table[nic]);
2799 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2800 dev = usb_bt_init(devname[2] ? hci_init(p) :
2801 bt_new_hci(qemu_find_bt_vlan(0)));
2802 } else {
2803 return -1;
2805 if (!dev)
2806 return -1;
2808 return usb_device_add_dev(dev);
2811 int usb_device_del_addr(int bus_num, int addr)
2813 USBPort *port;
2814 USBPort **lastp;
2815 USBDevice *dev;
2817 if (!used_usb_ports)
2818 return -1;
2820 if (bus_num != 0)
2821 return -1;
2823 lastp = &used_usb_ports;
2824 port = used_usb_ports;
2825 while (port && port->dev->addr != addr) {
2826 lastp = &port->next;
2827 port = port->next;
2830 if (!port)
2831 return -1;
2833 dev = port->dev;
2834 *lastp = port->next;
2835 usb_attach(port, NULL);
2836 dev->handle_destroy(dev);
2837 port->next = free_usb_ports;
2838 free_usb_ports = port;
2839 return 0;
2842 static int usb_device_del(const char *devname)
2844 int bus_num, addr;
2845 const char *p;
2847 if (strstart(devname, "host:", &p))
2848 return usb_host_device_close(p);
2850 if (!used_usb_ports)
2851 return -1;
2853 p = strchr(devname, '.');
2854 if (!p)
2855 return -1;
2856 bus_num = strtoul(devname, NULL, 0);
2857 addr = strtoul(p + 1, NULL, 0);
2859 return usb_device_del_addr(bus_num, addr);
2862 void do_usb_add(Monitor *mon, const char *devname)
2864 usb_device_add(devname, 1);
2867 void do_usb_del(Monitor *mon, const char *devname)
2869 usb_device_del(devname);
2872 void usb_info(Monitor *mon)
2874 USBDevice *dev;
2875 USBPort *port;
2876 const char *speed_str;
2878 if (!usb_enabled) {
2879 monitor_printf(mon, "USB support not enabled\n");
2880 return;
2883 for (port = used_usb_ports; port; port = port->next) {
2884 dev = port->dev;
2885 if (!dev)
2886 continue;
2887 switch(dev->speed) {
2888 case USB_SPEED_LOW:
2889 speed_str = "1.5";
2890 break;
2891 case USB_SPEED_FULL:
2892 speed_str = "12";
2893 break;
2894 case USB_SPEED_HIGH:
2895 speed_str = "480";
2896 break;
2897 default:
2898 speed_str = "?";
2899 break;
2901 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2902 0, dev->addr, speed_str, dev->devname);
2906 /***********************************************************/
2907 /* PCMCIA/Cardbus */
2909 static struct pcmcia_socket_entry_s {
2910 PCMCIASocket *socket;
2911 struct pcmcia_socket_entry_s *next;
2912 } *pcmcia_sockets = 0;
2914 void pcmcia_socket_register(PCMCIASocket *socket)
2916 struct pcmcia_socket_entry_s *entry;
2918 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2919 entry->socket = socket;
2920 entry->next = pcmcia_sockets;
2921 pcmcia_sockets = entry;
2924 void pcmcia_socket_unregister(PCMCIASocket *socket)
2926 struct pcmcia_socket_entry_s *entry, **ptr;
2928 ptr = &pcmcia_sockets;
2929 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2930 if (entry->socket == socket) {
2931 *ptr = entry->next;
2932 qemu_free(entry);
2936 void pcmcia_info(Monitor *mon)
2938 struct pcmcia_socket_entry_s *iter;
2940 if (!pcmcia_sockets)
2941 monitor_printf(mon, "No PCMCIA sockets\n");
2943 for (iter = pcmcia_sockets; iter; iter = iter->next)
2944 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2945 iter->socket->attached ? iter->socket->card_string :
2946 "Empty");
2949 /***********************************************************/
2950 /* register display */
2952 struct DisplayAllocator default_allocator = {
2953 defaultallocator_create_displaysurface,
2954 defaultallocator_resize_displaysurface,
2955 defaultallocator_free_displaysurface
2958 void register_displaystate(DisplayState *ds)
2960 DisplayState **s;
2961 s = &display_state;
2962 while (*s != NULL)
2963 s = &(*s)->next;
2964 ds->next = NULL;
2965 *s = ds;
2968 DisplayState *get_displaystate(void)
2970 return display_state;
2973 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2975 if(ds->allocator == &default_allocator) ds->allocator = da;
2976 return ds->allocator;
2979 /* dumb display */
2981 static void dumb_display_init(void)
2983 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2984 ds->allocator = &default_allocator;
2985 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2986 register_displaystate(ds);
2989 /***********************************************************/
2990 /* I/O handling */
2992 typedef struct IOHandlerRecord {
2993 int fd;
2994 IOCanRWHandler *fd_read_poll;
2995 IOHandler *fd_read;
2996 IOHandler *fd_write;
2997 int deleted;
2998 void *opaque;
2999 /* temporary data */
3000 struct pollfd *ufd;
3001 struct IOHandlerRecord *next;
3002 } IOHandlerRecord;
3004 static IOHandlerRecord *first_io_handler;
3006 /* XXX: fd_read_poll should be suppressed, but an API change is
3007 necessary in the character devices to suppress fd_can_read(). */
3008 int qemu_set_fd_handler2(int fd,
3009 IOCanRWHandler *fd_read_poll,
3010 IOHandler *fd_read,
3011 IOHandler *fd_write,
3012 void *opaque)
3014 IOHandlerRecord **pioh, *ioh;
3016 if (!fd_read && !fd_write) {
3017 pioh = &first_io_handler;
3018 for(;;) {
3019 ioh = *pioh;
3020 if (ioh == NULL)
3021 break;
3022 if (ioh->fd == fd) {
3023 ioh->deleted = 1;
3024 break;
3026 pioh = &ioh->next;
3028 } else {
3029 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3030 if (ioh->fd == fd)
3031 goto found;
3033 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3034 ioh->next = first_io_handler;
3035 first_io_handler = ioh;
3036 found:
3037 ioh->fd = fd;
3038 ioh->fd_read_poll = fd_read_poll;
3039 ioh->fd_read = fd_read;
3040 ioh->fd_write = fd_write;
3041 ioh->opaque = opaque;
3042 ioh->deleted = 0;
3044 qemu_notify_event();
3045 return 0;
3048 int qemu_set_fd_handler(int fd,
3049 IOHandler *fd_read,
3050 IOHandler *fd_write,
3051 void *opaque)
3053 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3056 #ifdef _WIN32
3057 /***********************************************************/
3058 /* Polling handling */
3060 typedef struct PollingEntry {
3061 PollingFunc *func;
3062 void *opaque;
3063 struct PollingEntry *next;
3064 } PollingEntry;
3066 static PollingEntry *first_polling_entry;
3068 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3070 PollingEntry **ppe, *pe;
3071 pe = qemu_mallocz(sizeof(PollingEntry));
3072 pe->func = func;
3073 pe->opaque = opaque;
3074 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3075 *ppe = pe;
3076 return 0;
3079 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3081 PollingEntry **ppe, *pe;
3082 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3083 pe = *ppe;
3084 if (pe->func == func && pe->opaque == opaque) {
3085 *ppe = pe->next;
3086 qemu_free(pe);
3087 break;
3092 /***********************************************************/
3093 /* Wait objects support */
3094 typedef struct WaitObjects {
3095 int num;
3096 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3097 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3098 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3099 } WaitObjects;
3101 static WaitObjects wait_objects = {0};
3103 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3105 WaitObjects *w = &wait_objects;
3107 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3108 return -1;
3109 w->events[w->num] = handle;
3110 w->func[w->num] = func;
3111 w->opaque[w->num] = opaque;
3112 w->num++;
3113 return 0;
3116 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3118 int i, found;
3119 WaitObjects *w = &wait_objects;
3121 found = 0;
3122 for (i = 0; i < w->num; i++) {
3123 if (w->events[i] == handle)
3124 found = 1;
3125 if (found) {
3126 w->events[i] = w->events[i + 1];
3127 w->func[i] = w->func[i + 1];
3128 w->opaque[i] = w->opaque[i + 1];
3131 if (found)
3132 w->num--;
3134 #endif
3136 /***********************************************************/
3137 /* ram save/restore */
3139 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3141 int v;
3143 v = qemu_get_byte(f);
3144 switch(v) {
3145 case 0:
3146 if (qemu_get_buffer(f, buf, len) != len)
3147 return -EIO;
3148 break;
3149 case 1:
3150 v = qemu_get_byte(f);
3151 memset(buf, v, len);
3152 break;
3153 default:
3154 return -EINVAL;
3157 if (qemu_file_has_error(f))
3158 return -EIO;
3160 return 0;
3163 static int ram_load_v1(QEMUFile *f, void *opaque)
3165 int ret;
3166 ram_addr_t i;
3168 if (qemu_get_be32(f) != last_ram_offset)
3169 return -EINVAL;
3170 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3171 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3172 continue;
3173 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3174 if (ret)
3175 return ret;
3177 return 0;
3180 #define BDRV_HASH_BLOCK_SIZE 1024
3181 #define IOBUF_SIZE 4096
3182 #define RAM_CBLOCK_MAGIC 0xfabe
3184 typedef struct RamDecompressState {
3185 z_stream zstream;
3186 QEMUFile *f;
3187 uint8_t buf[IOBUF_SIZE];
3188 } RamDecompressState;
3190 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3192 int ret;
3193 memset(s, 0, sizeof(*s));
3194 s->f = f;
3195 ret = inflateInit(&s->zstream);
3196 if (ret != Z_OK)
3197 return -1;
3198 return 0;
3201 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3203 int ret, clen;
3205 s->zstream.avail_out = len;
3206 s->zstream.next_out = buf;
3207 while (s->zstream.avail_out > 0) {
3208 if (s->zstream.avail_in == 0) {
3209 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3210 return -1;
3211 clen = qemu_get_be16(s->f);
3212 if (clen > IOBUF_SIZE)
3213 return -1;
3214 qemu_get_buffer(s->f, s->buf, clen);
3215 s->zstream.avail_in = clen;
3216 s->zstream.next_in = s->buf;
3218 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3219 if (ret != Z_OK && ret != Z_STREAM_END) {
3220 return -1;
3223 return 0;
3226 static void ram_decompress_close(RamDecompressState *s)
3228 inflateEnd(&s->zstream);
3231 #define RAM_SAVE_FLAG_FULL 0x01
3232 #define RAM_SAVE_FLAG_COMPRESS 0x02
3233 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3234 #define RAM_SAVE_FLAG_PAGE 0x08
3235 #define RAM_SAVE_FLAG_EOS 0x10
3237 static int is_dup_page(uint8_t *page, uint8_t ch)
3239 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3240 uint32_t *array = (uint32_t *)page;
3241 int i;
3243 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3244 if (array[i] != val)
3245 return 0;
3248 return 1;
3251 static int ram_save_block(QEMUFile *f)
3253 static ram_addr_t current_addr = 0;
3254 ram_addr_t saved_addr = current_addr;
3255 ram_addr_t addr = 0;
3256 int found = 0;
3258 while (addr < last_ram_offset) {
3259 if (kvm_enabled() && current_addr == 0) {
3260 int r;
3261 r = kvm_update_dirty_pages_log();
3262 if (r) {
3263 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3264 qemu_file_set_error(f);
3265 return 0;
3268 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3269 uint8_t *p;
3271 cpu_physical_memory_reset_dirty(current_addr,
3272 current_addr + TARGET_PAGE_SIZE,
3273 MIGRATION_DIRTY_FLAG);
3275 p = qemu_get_ram_ptr(current_addr);
3277 if (is_dup_page(p, *p)) {
3278 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3279 qemu_put_byte(f, *p);
3280 } else {
3281 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3282 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3285 found = 1;
3286 break;
3288 addr += TARGET_PAGE_SIZE;
3289 current_addr = (saved_addr + addr) % last_ram_offset;
3292 return found;
3295 static ram_addr_t ram_save_threshold = 10;
3297 static ram_addr_t ram_save_remaining(void)
3299 ram_addr_t addr;
3300 ram_addr_t count = 0;
3302 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3303 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3304 count++;
3307 return count;
3310 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3312 ram_addr_t addr;
3314 if (stage == 1) {
3315 /* Make sure all dirty bits are set */
3316 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3317 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3318 cpu_physical_memory_set_dirty(addr);
3321 /* Enable dirty memory tracking */
3322 cpu_physical_memory_set_dirty_tracking(1);
3324 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3327 while (!qemu_file_rate_limit(f)) {
3328 int ret;
3330 ret = ram_save_block(f);
3331 if (ret == 0) /* no more blocks */
3332 break;
3335 /* try transferring iterative blocks of memory */
3337 if (stage == 3) {
3339 /* flush all remaining blocks regardless of rate limiting */
3340 while (ram_save_block(f) != 0);
3341 cpu_physical_memory_set_dirty_tracking(0);
3344 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3346 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3349 static int ram_load_dead(QEMUFile *f, void *opaque)
3351 RamDecompressState s1, *s = &s1;
3352 uint8_t buf[10];
3353 ram_addr_t i;
3355 if (ram_decompress_open(s, f) < 0)
3356 return -EINVAL;
3357 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3358 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3359 continue;
3360 if (ram_decompress_buf(s, buf, 1) < 0) {
3361 fprintf(stderr, "Error while reading ram block header\n");
3362 goto error;
3364 if (buf[0] == 0) {
3365 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3366 BDRV_HASH_BLOCK_SIZE) < 0) {
3367 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3368 goto error;
3370 } else {
3371 error:
3372 printf("Error block header\n");
3373 return -EINVAL;
3376 ram_decompress_close(s);
3378 return 0;
3381 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3383 ram_addr_t addr;
3384 int flags;
3386 if (version_id == 1)
3387 return ram_load_v1(f, opaque);
3389 if (version_id == 2) {
3390 if (qemu_get_be32(f) != last_ram_offset)
3391 return -EINVAL;
3392 return ram_load_dead(f, opaque);
3395 if (version_id != 3)
3396 return -EINVAL;
3398 do {
3399 addr = qemu_get_be64(f);
3401 flags = addr & ~TARGET_PAGE_MASK;
3402 addr &= TARGET_PAGE_MASK;
3404 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3405 if (addr != last_ram_offset)
3406 return -EINVAL;
3409 if (flags & RAM_SAVE_FLAG_FULL) {
3410 if (ram_load_dead(f, opaque) < 0)
3411 return -EINVAL;
3414 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3415 uint8_t ch = qemu_get_byte(f);
3416 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3417 } else if (flags & RAM_SAVE_FLAG_PAGE)
3418 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3419 } while (!(flags & RAM_SAVE_FLAG_EOS));
3421 return 0;
3424 void qemu_service_io(void)
3426 qemu_notify_event();
3429 /***********************************************************/
3430 /* bottom halves (can be seen as timers which expire ASAP) */
3432 struct QEMUBH {
3433 QEMUBHFunc *cb;
3434 void *opaque;
3435 int scheduled;
3436 int idle;
3437 int deleted;
3438 QEMUBH *next;
3441 static QEMUBH *first_bh = NULL;
3443 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3445 QEMUBH *bh;
3446 bh = qemu_mallocz(sizeof(QEMUBH));
3447 bh->cb = cb;
3448 bh->opaque = opaque;
3449 bh->next = first_bh;
3450 first_bh = bh;
3451 return bh;
3454 int qemu_bh_poll(void)
3456 QEMUBH *bh, **bhp;
3457 int ret;
3459 ret = 0;
3460 for (bh = first_bh; bh; bh = bh->next) {
3461 if (!bh->deleted && bh->scheduled) {
3462 bh->scheduled = 0;
3463 if (!bh->idle)
3464 ret = 1;
3465 bh->idle = 0;
3466 bh->cb(bh->opaque);
3470 /* remove deleted bhs */
3471 bhp = &first_bh;
3472 while (*bhp) {
3473 bh = *bhp;
3474 if (bh->deleted) {
3475 *bhp = bh->next;
3476 qemu_free(bh);
3477 } else
3478 bhp = &bh->next;
3481 return ret;
3484 void qemu_bh_schedule_idle(QEMUBH *bh)
3486 if (bh->scheduled)
3487 return;
3488 bh->scheduled = 1;
3489 bh->idle = 1;
3492 void qemu_bh_schedule(QEMUBH *bh)
3494 if (bh->scheduled)
3495 return;
3496 bh->scheduled = 1;
3497 bh->idle = 0;
3498 /* stop the currently executing CPU to execute the BH ASAP */
3499 qemu_notify_event();
3502 void qemu_bh_cancel(QEMUBH *bh)
3504 bh->scheduled = 0;
3507 void qemu_bh_delete(QEMUBH *bh)
3509 bh->scheduled = 0;
3510 bh->deleted = 1;
3513 static void qemu_bh_update_timeout(int *timeout)
3515 QEMUBH *bh;
3517 for (bh = first_bh; bh; bh = bh->next) {
3518 if (!bh->deleted && bh->scheduled) {
3519 if (bh->idle) {
3520 /* idle bottom halves will be polled at least
3521 * every 10ms */
3522 *timeout = MIN(10, *timeout);
3523 } else {
3524 /* non-idle bottom halves will be executed
3525 * immediately */
3526 *timeout = 0;
3527 break;
3533 /***********************************************************/
3534 /* machine registration */
3536 static QEMUMachine *first_machine = NULL;
3537 QEMUMachine *current_machine = NULL;
3539 int qemu_register_machine(QEMUMachine *m)
3541 QEMUMachine **pm;
3542 pm = &first_machine;
3543 while (*pm != NULL)
3544 pm = &(*pm)->next;
3545 m->next = NULL;
3546 *pm = m;
3547 return 0;
3550 static QEMUMachine *find_machine(const char *name)
3552 QEMUMachine *m;
3554 for(m = first_machine; m != NULL; m = m->next) {
3555 if (!strcmp(m->name, name))
3556 return m;
3558 return NULL;
3561 /***********************************************************/
3562 /* main execution loop */
3564 static void gui_update(void *opaque)
3566 uint64_t interval = GUI_REFRESH_INTERVAL;
3567 DisplayState *ds = opaque;
3568 DisplayChangeListener *dcl = ds->listeners;
3570 dpy_refresh(ds);
3572 while (dcl != NULL) {
3573 if (dcl->gui_timer_interval &&
3574 dcl->gui_timer_interval < interval)
3575 interval = dcl->gui_timer_interval;
3576 dcl = dcl->next;
3578 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3581 static void nographic_update(void *opaque)
3583 uint64_t interval = GUI_REFRESH_INTERVAL;
3585 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3588 struct vm_change_state_entry {
3589 VMChangeStateHandler *cb;
3590 void *opaque;
3591 LIST_ENTRY (vm_change_state_entry) entries;
3594 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3596 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3597 void *opaque)
3599 VMChangeStateEntry *e;
3601 e = qemu_mallocz(sizeof (*e));
3603 e->cb = cb;
3604 e->opaque = opaque;
3605 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3606 return e;
3609 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3611 LIST_REMOVE (e, entries);
3612 qemu_free (e);
3615 static void vm_state_notify(int running, int reason)
3617 VMChangeStateEntry *e;
3619 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3620 e->cb(e->opaque, running, reason);
3624 static void resume_all_vcpus(void);
3625 static void pause_all_vcpus(void);
3627 void vm_start(void)
3629 if (!vm_running) {
3630 cpu_enable_ticks();
3631 vm_running = 1;
3632 vm_state_notify(1, 0);
3633 qemu_rearm_alarm_timer(alarm_timer);
3634 resume_all_vcpus();
3638 /* reset/shutdown handler */
3640 typedef struct QEMUResetEntry {
3641 QEMUResetHandler *func;
3642 void *opaque;
3643 struct QEMUResetEntry *next;
3644 } QEMUResetEntry;
3646 static QEMUResetEntry *first_reset_entry;
3647 static int reset_requested;
3648 static int shutdown_requested;
3649 static int powerdown_requested;
3650 static int debug_requested;
3651 static int vmstop_requested;
3653 int qemu_no_shutdown(void)
3655 int r = no_shutdown;
3656 no_shutdown = 0;
3657 return r;
3660 int qemu_shutdown_requested(void)
3662 int r = shutdown_requested;
3663 shutdown_requested = 0;
3664 return r;
3667 int qemu_reset_requested(void)
3669 int r = reset_requested;
3670 reset_requested = 0;
3671 return r;
3674 int qemu_powerdown_requested(void)
3676 int r = powerdown_requested;
3677 powerdown_requested = 0;
3678 return r;
3681 static int qemu_debug_requested(void)
3683 int r = debug_requested;
3684 debug_requested = 0;
3685 return r;
3688 static int qemu_vmstop_requested(void)
3690 int r = vmstop_requested;
3691 vmstop_requested = 0;
3692 return r;
3695 static void do_vm_stop(int reason)
3697 if (vm_running) {
3698 cpu_disable_ticks();
3699 vm_running = 0;
3700 pause_all_vcpus();
3701 vm_state_notify(0, reason);
3705 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3707 QEMUResetEntry **pre, *re;
3709 pre = &first_reset_entry;
3710 while (*pre != NULL)
3711 pre = &(*pre)->next;
3712 re = qemu_mallocz(sizeof(QEMUResetEntry));
3713 re->func = func;
3714 re->opaque = opaque;
3715 re->next = NULL;
3716 *pre = re;
3719 void qemu_system_reset(void)
3721 QEMUResetEntry *re;
3723 /* reset all devices */
3724 for(re = first_reset_entry; re != NULL; re = re->next) {
3725 re->func(re->opaque);
3727 if (kvm_enabled())
3728 kvm_sync_vcpus();
3731 void qemu_system_reset_request(void)
3733 if (no_reboot) {
3734 shutdown_requested = 1;
3735 } else {
3736 reset_requested = 1;
3738 if (cpu_single_env) {
3739 qemu_kvm_cpu_stop(cpu_single_env);
3740 cpu_exit(cpu_single_env);
3742 qemu_notify_event();
3745 void qemu_system_shutdown_request(void)
3747 shutdown_requested = 1;
3748 qemu_notify_event();
3751 void qemu_system_powerdown_request(void)
3753 powerdown_requested = 1;
3754 qemu_notify_event();
3757 #ifdef CONFIG_IOTHREAD
3758 static void qemu_system_vmstop_request(int reason)
3760 vmstop_requested = reason;
3761 qemu_notify_event();
3763 #endif
3765 #ifndef _WIN32
3766 static int io_thread_fd = -1;
3768 static void qemu_event_increment(void)
3770 static const char byte = 0;
3772 if (io_thread_fd == -1)
3773 return;
3775 write(io_thread_fd, &byte, sizeof(byte));
3778 static void qemu_event_read(void *opaque)
3780 int fd = (unsigned long)opaque;
3781 ssize_t len;
3783 /* Drain the notify pipe */
3784 do {
3785 char buffer[512];
3786 len = read(fd, buffer, sizeof(buffer));
3787 } while ((len == -1 && errno == EINTR) || len > 0);
3790 static int qemu_event_init(void)
3792 int err;
3793 int fds[2];
3795 err = pipe(fds);
3796 if (err == -1)
3797 return -errno;
3799 err = fcntl_setfl(fds[0], O_NONBLOCK);
3800 if (err < 0)
3801 goto fail;
3803 err = fcntl_setfl(fds[1], O_NONBLOCK);
3804 if (err < 0)
3805 goto fail;
3807 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3808 (void *)(unsigned long)fds[0]);
3810 io_thread_fd = fds[1];
3811 return 0;
3813 fail:
3814 close(fds[0]);
3815 close(fds[1]);
3816 return err;
3818 #else
3819 HANDLE qemu_event_handle;
3821 static void dummy_event_handler(void *opaque)
3825 static int qemu_event_init(void)
3827 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3828 if (!qemu_event_handle) {
3829 perror("Failed CreateEvent");
3830 return -1;
3832 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3833 return 0;
3836 static void qemu_event_increment(void)
3838 SetEvent(qemu_event_handle);
3840 #endif
3842 static int cpu_can_run(CPUState *env)
3844 if (env->stop)
3845 return 0;
3846 if (env->stopped)
3847 return 0;
3848 return 1;
3851 #ifndef CONFIG_IOTHREAD
3852 static int qemu_init_main_loop(void)
3854 return qemu_event_init();
3857 void qemu_init_vcpu(void *_env)
3859 CPUState *env = _env;
3861 if (kvm_enabled())
3862 kvm_init_vcpu(env);
3863 return;
3866 int qemu_cpu_self(void *env)
3868 return 1;
3871 static void resume_all_vcpus(void)
3875 static void pause_all_vcpus(void)
3879 void qemu_cpu_kick(void *env)
3881 return;
3884 void qemu_notify_event(void)
3886 CPUState *env = cpu_single_env;
3888 if (kvm_enabled()) {
3889 qemu_kvm_notify_work();
3890 return;
3892 if (env) {
3893 cpu_exit(env);
3894 #ifdef USE_KQEMU
3895 if (env->kqemu_enabled)
3896 kqemu_cpu_interrupt(env);
3897 #endif
3901 #define qemu_mutex_lock_iothread() do { } while (0)
3902 #define qemu_mutex_unlock_iothread() do { } while (0)
3904 void vm_stop(int reason)
3906 do_vm_stop(reason);
3909 #else /* CONFIG_IOTHREAD */
3911 #include "qemu-thread.h"
3913 QemuMutex qemu_global_mutex;
3914 static QemuMutex qemu_fair_mutex;
3916 static QemuThread io_thread;
3918 static QemuThread *tcg_cpu_thread;
3919 static QemuCond *tcg_halt_cond;
3921 static int qemu_system_ready;
3922 /* cpu creation */
3923 static QemuCond qemu_cpu_cond;
3924 /* system init */
3925 static QemuCond qemu_system_cond;
3926 static QemuCond qemu_pause_cond;
3928 static void block_io_signals(void);
3929 static void unblock_io_signals(void);
3930 static int tcg_has_work(void);
3932 static int qemu_init_main_loop(void)
3934 int ret;
3936 ret = qemu_event_init();
3937 if (ret)
3938 return ret;
3940 qemu_cond_init(&qemu_pause_cond);
3941 qemu_mutex_init(&qemu_fair_mutex);
3942 qemu_mutex_init(&qemu_global_mutex);
3943 qemu_mutex_lock(&qemu_global_mutex);
3945 unblock_io_signals();
3946 qemu_thread_self(&io_thread);
3948 return 0;
3951 static void qemu_wait_io_event(CPUState *env)
3953 while (!tcg_has_work())
3954 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3956 qemu_mutex_unlock(&qemu_global_mutex);
3959 * Users of qemu_global_mutex can be starved, having no chance
3960 * to acquire it since this path will get to it first.
3961 * So use another lock to provide fairness.
3963 qemu_mutex_lock(&qemu_fair_mutex);
3964 qemu_mutex_unlock(&qemu_fair_mutex);
3966 qemu_mutex_lock(&qemu_global_mutex);
3967 if (env->stop) {
3968 env->stop = 0;
3969 env->stopped = 1;
3970 qemu_cond_signal(&qemu_pause_cond);
3974 static int qemu_cpu_exec(CPUState *env);
3976 static void *kvm_cpu_thread_fn(void *arg)
3978 CPUState *env = arg;
3980 block_io_signals();
3981 qemu_thread_self(env->thread);
3983 /* signal CPU creation */
3984 qemu_mutex_lock(&qemu_global_mutex);
3985 env->created = 1;
3986 qemu_cond_signal(&qemu_cpu_cond);
3988 /* and wait for machine initialization */
3989 while (!qemu_system_ready)
3990 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3992 while (1) {
3993 if (cpu_can_run(env))
3994 qemu_cpu_exec(env);
3995 qemu_wait_io_event(env);
3998 return NULL;
4001 static void tcg_cpu_exec(void);
4003 static void *tcg_cpu_thread_fn(void *arg)
4005 CPUState *env = arg;
4007 block_io_signals();
4008 qemu_thread_self(env->thread);
4010 /* signal CPU creation */
4011 qemu_mutex_lock(&qemu_global_mutex);
4012 for (env = first_cpu; env != NULL; env = env->next_cpu)
4013 env->created = 1;
4014 qemu_cond_signal(&qemu_cpu_cond);
4016 /* and wait for machine initialization */
4017 while (!qemu_system_ready)
4018 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4020 while (1) {
4021 tcg_cpu_exec();
4022 qemu_wait_io_event(cur_cpu);
4025 return NULL;
4028 void qemu_cpu_kick(void *_env)
4030 CPUState *env = _env;
4031 qemu_cond_broadcast(env->halt_cond);
4032 if (kvm_enabled())
4033 qemu_thread_signal(env->thread, SIGUSR1);
4036 int qemu_cpu_self(void *env)
4038 return (cpu_single_env != NULL);
4041 static void cpu_signal(int sig)
4043 if (cpu_single_env)
4044 cpu_exit(cpu_single_env);
4047 static void block_io_signals(void)
4049 sigset_t set;
4050 struct sigaction sigact;
4052 sigemptyset(&set);
4053 sigaddset(&set, SIGUSR2);
4054 sigaddset(&set, SIGIO);
4055 sigaddset(&set, SIGALRM);
4056 pthread_sigmask(SIG_BLOCK, &set, NULL);
4058 sigemptyset(&set);
4059 sigaddset(&set, SIGUSR1);
4060 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4062 memset(&sigact, 0, sizeof(sigact));
4063 sigact.sa_handler = cpu_signal;
4064 sigaction(SIGUSR1, &sigact, NULL);
4067 static void unblock_io_signals(void)
4069 sigset_t set;
4071 sigemptyset(&set);
4072 sigaddset(&set, SIGUSR2);
4073 sigaddset(&set, SIGIO);
4074 sigaddset(&set, SIGALRM);
4075 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4077 sigemptyset(&set);
4078 sigaddset(&set, SIGUSR1);
4079 pthread_sigmask(SIG_BLOCK, &set, NULL);
4082 static void qemu_signal_lock(unsigned int msecs)
4084 qemu_mutex_lock(&qemu_fair_mutex);
4086 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4087 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4088 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4089 break;
4091 qemu_mutex_unlock(&qemu_fair_mutex);
4094 static void qemu_mutex_lock_iothread(void)
4096 if (kvm_enabled()) {
4097 qemu_mutex_lock(&qemu_fair_mutex);
4098 qemu_mutex_lock(&qemu_global_mutex);
4099 qemu_mutex_unlock(&qemu_fair_mutex);
4100 } else
4101 qemu_signal_lock(100);
4104 static void qemu_mutex_unlock_iothread(void)
4106 qemu_mutex_unlock(&qemu_global_mutex);
4109 static int all_vcpus_paused(void)
4111 CPUState *penv = first_cpu;
4113 while (penv) {
4114 if (!penv->stopped)
4115 return 0;
4116 penv = (CPUState *)penv->next_cpu;
4119 return 1;
4122 static void pause_all_vcpus(void)
4124 CPUState *penv = first_cpu;
4126 while (penv) {
4127 penv->stop = 1;
4128 qemu_thread_signal(penv->thread, SIGUSR1);
4129 qemu_cpu_kick(penv);
4130 penv = (CPUState *)penv->next_cpu;
4133 while (!all_vcpus_paused()) {
4134 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4135 penv = first_cpu;
4136 while (penv) {
4137 qemu_thread_signal(penv->thread, SIGUSR1);
4138 penv = (CPUState *)penv->next_cpu;
4143 static void resume_all_vcpus(void)
4145 CPUState *penv = first_cpu;
4147 while (penv) {
4148 penv->stop = 0;
4149 penv->stopped = 0;
4150 qemu_thread_signal(penv->thread, SIGUSR1);
4151 qemu_cpu_kick(penv);
4152 penv = (CPUState *)penv->next_cpu;
4156 static void tcg_init_vcpu(void *_env)
4158 CPUState *env = _env;
4159 /* share a single thread for all cpus with TCG */
4160 if (!tcg_cpu_thread) {
4161 env->thread = qemu_mallocz(sizeof(QemuThread));
4162 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4163 qemu_cond_init(env->halt_cond);
4164 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4165 while (env->created == 0)
4166 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4167 tcg_cpu_thread = env->thread;
4168 tcg_halt_cond = env->halt_cond;
4169 } else {
4170 env->thread = tcg_cpu_thread;
4171 env->halt_cond = tcg_halt_cond;
4175 static void kvm_start_vcpu(CPUState *env)
4177 kvm_init_vcpu(env);
4178 env->thread = qemu_mallocz(sizeof(QemuThread));
4179 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4180 qemu_cond_init(env->halt_cond);
4181 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4182 while (env->created == 0)
4183 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4186 void qemu_init_vcpu(void *_env)
4188 CPUState *env = _env;
4190 if (kvm_enabled())
4191 kvm_start_vcpu(env);
4192 else
4193 tcg_init_vcpu(env);
4196 void qemu_notify_event(void)
4198 qemu_event_increment();
4201 void vm_stop(int reason)
4203 QemuThread me;
4204 qemu_thread_self(&me);
4206 if (!qemu_thread_equal(&me, &io_thread)) {
4207 qemu_system_vmstop_request(reason);
4209 * FIXME: should not return to device code in case
4210 * vm_stop() has been requested.
4212 if (cpu_single_env) {
4213 cpu_exit(cpu_single_env);
4214 cpu_single_env->stop = 1;
4216 return;
4218 do_vm_stop(reason);
4221 #endif
4224 #ifdef _WIN32
4225 static void host_main_loop_wait(int *timeout)
4227 int ret, ret2, i;
4228 PollingEntry *pe;
4231 /* XXX: need to suppress polling by better using win32 events */
4232 ret = 0;
4233 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4234 ret |= pe->func(pe->opaque);
4236 if (ret == 0) {
4237 int err;
4238 WaitObjects *w = &wait_objects;
4240 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4241 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4242 if (w->func[ret - WAIT_OBJECT_0])
4243 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4245 /* Check for additional signaled events */
4246 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4248 /* Check if event is signaled */
4249 ret2 = WaitForSingleObject(w->events[i], 0);
4250 if(ret2 == WAIT_OBJECT_0) {
4251 if (w->func[i])
4252 w->func[i](w->opaque[i]);
4253 } else if (ret2 == WAIT_TIMEOUT) {
4254 } else {
4255 err = GetLastError();
4256 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4259 } else if (ret == WAIT_TIMEOUT) {
4260 } else {
4261 err = GetLastError();
4262 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4266 *timeout = 0;
4268 #else
4269 static void host_main_loop_wait(int *timeout)
4272 #endif
4274 void main_loop_wait(int timeout)
4276 IOHandlerRecord *ioh;
4277 fd_set rfds, wfds, xfds;
4278 int ret, nfds;
4279 struct timeval tv;
4281 qemu_bh_update_timeout(&timeout);
4283 host_main_loop_wait(&timeout);
4285 /* poll any events */
4286 /* XXX: separate device handlers from system ones */
4287 nfds = -1;
4288 FD_ZERO(&rfds);
4289 FD_ZERO(&wfds);
4290 FD_ZERO(&xfds);
4291 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4292 if (ioh->deleted)
4293 continue;
4294 if (ioh->fd_read &&
4295 (!ioh->fd_read_poll ||
4296 ioh->fd_read_poll(ioh->opaque) != 0)) {
4297 FD_SET(ioh->fd, &rfds);
4298 if (ioh->fd > nfds)
4299 nfds = ioh->fd;
4301 if (ioh->fd_write) {
4302 FD_SET(ioh->fd, &wfds);
4303 if (ioh->fd > nfds)
4304 nfds = ioh->fd;
4308 tv.tv_sec = timeout / 1000;
4309 tv.tv_usec = (timeout % 1000) * 1000;
4311 #if defined(CONFIG_SLIRP)
4312 if (slirp_is_inited()) {
4313 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4315 #endif
4316 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4317 if (ret > 0) {
4318 IOHandlerRecord **pioh;
4320 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4321 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4322 ioh->fd_read(ioh->opaque);
4323 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4324 FD_CLR(ioh->fd, &rfds);
4326 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4327 ioh->fd_write(ioh->opaque);
4331 /* remove deleted IO handlers */
4332 pioh = &first_io_handler;
4333 while (*pioh) {
4334 ioh = *pioh;
4335 if (ioh->deleted) {
4336 *pioh = ioh->next;
4337 qemu_free(ioh);
4338 } else
4339 pioh = &ioh->next;
4342 #if defined(CONFIG_SLIRP)
4343 if (slirp_is_inited()) {
4344 if (ret < 0) {
4345 FD_ZERO(&rfds);
4346 FD_ZERO(&wfds);
4347 FD_ZERO(&xfds);
4349 slirp_select_poll(&rfds, &wfds, &xfds);
4351 #endif
4353 /* rearm timer, if not periodic */
4354 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4355 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4356 qemu_rearm_alarm_timer(alarm_timer);
4359 /* vm time timers */
4360 if (vm_running) {
4361 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4362 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4363 qemu_get_clock(vm_clock));
4366 /* real time timers */
4367 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4368 qemu_get_clock(rt_clock));
4370 /* Check bottom-halves last in case any of the earlier events triggered
4371 them. */
4372 qemu_bh_poll();
4376 static int qemu_cpu_exec(CPUState *env)
4378 int ret;
4379 #ifdef CONFIG_PROFILER
4380 int64_t ti;
4381 #endif
4383 #ifdef CONFIG_PROFILER
4384 ti = profile_getclock();
4385 #endif
4386 if (use_icount) {
4387 int64_t count;
4388 int decr;
4389 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4390 env->icount_decr.u16.low = 0;
4391 env->icount_extra = 0;
4392 count = qemu_next_deadline();
4393 count = (count + (1 << icount_time_shift) - 1)
4394 >> icount_time_shift;
4395 qemu_icount += count;
4396 decr = (count > 0xffff) ? 0xffff : count;
4397 count -= decr;
4398 env->icount_decr.u16.low = decr;
4399 env->icount_extra = count;
4401 ret = cpu_exec(env);
4402 #ifdef CONFIG_PROFILER
4403 qemu_time += profile_getclock() - ti;
4404 #endif
4405 if (use_icount) {
4406 /* Fold pending instructions back into the
4407 instruction counter, and clear the interrupt flag. */
4408 qemu_icount -= (env->icount_decr.u16.low
4409 + env->icount_extra);
4410 env->icount_decr.u32 = 0;
4411 env->icount_extra = 0;
4413 return ret;
4416 static void tcg_cpu_exec(void)
4418 int ret = 0;
4420 if (next_cpu == NULL)
4421 next_cpu = first_cpu;
4422 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4423 CPUState *env = cur_cpu = next_cpu;
4425 if (!vm_running)
4426 break;
4427 if (timer_alarm_pending) {
4428 timer_alarm_pending = 0;
4429 break;
4431 if (cpu_can_run(env))
4432 ret = qemu_cpu_exec(env);
4433 if (ret == EXCP_DEBUG) {
4434 gdb_set_stop_cpu(env);
4435 debug_requested = 1;
4436 break;
4441 static int cpu_has_work(CPUState *env)
4443 if (env->stop)
4444 return 1;
4445 if (env->stopped)
4446 return 0;
4447 if (!env->halted)
4448 return 1;
4449 if (qemu_cpu_has_work(env))
4450 return 1;
4451 return 0;
4454 static int tcg_has_work(void)
4456 CPUState *env;
4458 for (env = first_cpu; env != NULL; env = env->next_cpu)
4459 if (cpu_has_work(env))
4460 return 1;
4461 return 0;
4464 static int qemu_calculate_timeout(void)
4466 int timeout;
4468 if (!vm_running)
4469 timeout = 5000;
4470 else if (tcg_has_work())
4471 timeout = 0;
4472 else if (!use_icount)
4473 timeout = 5000;
4474 else {
4475 /* XXX: use timeout computed from timers */
4476 int64_t add;
4477 int64_t delta;
4478 /* Advance virtual time to the next event. */
4479 if (use_icount == 1) {
4480 /* When not using an adaptive execution frequency
4481 we tend to get badly out of sync with real time,
4482 so just delay for a reasonable amount of time. */
4483 delta = 0;
4484 } else {
4485 delta = cpu_get_icount() - cpu_get_clock();
4487 if (delta > 0) {
4488 /* If virtual time is ahead of real time then just
4489 wait for IO. */
4490 timeout = (delta / 1000000) + 1;
4491 } else {
4492 /* Wait for either IO to occur or the next
4493 timer event. */
4494 add = qemu_next_deadline();
4495 /* We advance the timer before checking for IO.
4496 Limit the amount we advance so that early IO
4497 activity won't get the guest too far ahead. */
4498 if (add > 10000000)
4499 add = 10000000;
4500 delta += add;
4501 add = (add + (1 << icount_time_shift) - 1)
4502 >> icount_time_shift;
4503 qemu_icount += add;
4504 timeout = delta / 1000000;
4505 if (timeout < 0)
4506 timeout = 0;
4510 return timeout;
4513 static int vm_can_run(void)
4515 if (powerdown_requested)
4516 return 0;
4517 if (reset_requested)
4518 return 0;
4519 if (shutdown_requested)
4520 return 0;
4521 if (debug_requested)
4522 return 0;
4523 return 1;
4526 static void main_loop(void)
4528 int r;
4530 if (kvm_enabled()) {
4531 kvm_main_loop();
4532 cpu_disable_ticks();
4533 return;
4536 #ifdef CONFIG_IOTHREAD
4537 qemu_system_ready = 1;
4538 qemu_cond_broadcast(&qemu_system_cond);
4539 #endif
4541 for (;;) {
4542 do {
4543 #ifdef CONFIG_PROFILER
4544 int64_t ti;
4545 #endif
4546 #ifndef CONFIG_IOTHREAD
4547 tcg_cpu_exec();
4548 #endif
4549 #ifdef CONFIG_PROFILER
4550 ti = profile_getclock();
4551 #endif
4552 #ifdef CONFIG_IOTHREAD
4553 main_loop_wait(1000);
4554 #else
4555 main_loop_wait(qemu_calculate_timeout());
4556 #endif
4557 #ifdef CONFIG_PROFILER
4558 dev_time += profile_getclock() - ti;
4559 #endif
4560 } while (vm_can_run());
4562 if (qemu_debug_requested())
4563 vm_stop(EXCP_DEBUG);
4564 if (qemu_shutdown_requested()) {
4565 if (no_shutdown) {
4566 vm_stop(0);
4567 no_shutdown = 0;
4568 } else
4569 break;
4571 if (qemu_reset_requested()) {
4572 pause_all_vcpus();
4573 qemu_system_reset();
4574 resume_all_vcpus();
4576 if (qemu_powerdown_requested())
4577 qemu_system_powerdown();
4578 if ((r = qemu_vmstop_requested()))
4579 vm_stop(r);
4581 pause_all_vcpus();
4584 static void version(void)
4586 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4589 static void help(int exitcode)
4591 version();
4592 printf("usage: %s [options] [disk_image]\n"
4593 "\n"
4594 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4595 "\n"
4596 #define DEF(option, opt_arg, opt_enum, opt_help) \
4597 opt_help
4598 #define DEFHEADING(text) stringify(text) "\n"
4599 #include "qemu-options.h"
4600 #undef DEF
4601 #undef DEFHEADING
4602 #undef GEN_DOCS
4603 "\n"
4604 "During emulation, the following keys are useful:\n"
4605 "ctrl-alt-f toggle full screen\n"
4606 "ctrl-alt-n switch to virtual console 'n'\n"
4607 "ctrl-alt toggle mouse and keyboard grab\n"
4608 "\n"
4609 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4611 "qemu",
4612 DEFAULT_RAM_SIZE,
4613 #ifndef _WIN32
4614 DEFAULT_NETWORK_SCRIPT,
4615 DEFAULT_NETWORK_DOWN_SCRIPT,
4616 #endif
4617 DEFAULT_GDBSTUB_PORT,
4618 "/tmp/qemu.log");
4619 exit(exitcode);
4622 #define HAS_ARG 0x0001
4624 enum {
4625 #define DEF(option, opt_arg, opt_enum, opt_help) \
4626 opt_enum,
4627 #define DEFHEADING(text)
4628 #include "qemu-options.h"
4629 #undef DEF
4630 #undef DEFHEADING
4631 #undef GEN_DOCS
4634 typedef struct QEMUOption {
4635 const char *name;
4636 int flags;
4637 int index;
4638 } QEMUOption;
4640 static const QEMUOption qemu_options[] = {
4641 { "h", 0, QEMU_OPTION_h },
4642 #define DEF(option, opt_arg, opt_enum, opt_help) \
4643 { option, opt_arg, opt_enum },
4644 #define DEFHEADING(text)
4645 #include "qemu-options.h"
4646 #undef DEF
4647 #undef DEFHEADING
4648 #undef GEN_DOCS
4649 { NULL },
4652 #ifdef HAS_AUDIO
4653 struct soundhw soundhw[] = {
4654 #ifdef HAS_AUDIO_CHOICE
4655 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4657 "pcspk",
4658 "PC speaker",
4661 { .init_isa = pcspk_audio_init }
4663 #endif
4665 #ifdef CONFIG_SB16
4667 "sb16",
4668 "Creative Sound Blaster 16",
4671 { .init_isa = SB16_init }
4673 #endif
4675 #ifdef CONFIG_CS4231A
4677 "cs4231a",
4678 "CS4231A",
4681 { .init_isa = cs4231a_init }
4683 #endif
4685 #ifdef CONFIG_ADLIB
4687 "adlib",
4688 #ifdef HAS_YMF262
4689 "Yamaha YMF262 (OPL3)",
4690 #else
4691 "Yamaha YM3812 (OPL2)",
4692 #endif
4695 { .init_isa = Adlib_init }
4697 #endif
4699 #ifdef CONFIG_GUS
4701 "gus",
4702 "Gravis Ultrasound GF1",
4705 { .init_isa = GUS_init }
4707 #endif
4709 #ifdef CONFIG_AC97
4711 "ac97",
4712 "Intel 82801AA AC97 Audio",
4715 { .init_pci = ac97_init }
4717 #endif
4719 #ifdef CONFIG_ES1370
4721 "es1370",
4722 "ENSONIQ AudioPCI ES1370",
4725 { .init_pci = es1370_init }
4727 #endif
4729 #endif /* HAS_AUDIO_CHOICE */
4731 { NULL, NULL, 0, 0, { NULL } }
4734 static void select_soundhw (const char *optarg)
4736 struct soundhw *c;
4738 if (*optarg == '?') {
4739 show_valid_cards:
4741 printf ("Valid sound card names (comma separated):\n");
4742 for (c = soundhw; c->name; ++c) {
4743 printf ("%-11s %s\n", c->name, c->descr);
4745 printf ("\n-soundhw all will enable all of the above\n");
4746 exit (*optarg != '?');
4748 else {
4749 size_t l;
4750 const char *p;
4751 char *e;
4752 int bad_card = 0;
4754 if (!strcmp (optarg, "all")) {
4755 for (c = soundhw; c->name; ++c) {
4756 c->enabled = 1;
4758 return;
4761 p = optarg;
4762 while (*p) {
4763 e = strchr (p, ',');
4764 l = !e ? strlen (p) : (size_t) (e - p);
4766 for (c = soundhw; c->name; ++c) {
4767 if (!strncmp (c->name, p, l)) {
4768 c->enabled = 1;
4769 break;
4773 if (!c->name) {
4774 if (l > 80) {
4775 fprintf (stderr,
4776 "Unknown sound card name (too big to show)\n");
4778 else {
4779 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4780 (int) l, p);
4782 bad_card = 1;
4784 p += l + (e != NULL);
4787 if (bad_card)
4788 goto show_valid_cards;
4791 #endif
4793 static void select_vgahw (const char *p)
4795 const char *opts;
4797 cirrus_vga_enabled = 0;
4798 std_vga_enabled = 0;
4799 vmsvga_enabled = 0;
4800 xenfb_enabled = 0;
4801 if (strstart(p, "std", &opts)) {
4802 std_vga_enabled = 1;
4803 } else if (strstart(p, "cirrus", &opts)) {
4804 cirrus_vga_enabled = 1;
4805 } else if (strstart(p, "vmware", &opts)) {
4806 vmsvga_enabled = 1;
4807 } else if (strstart(p, "xenfb", &opts)) {
4808 xenfb_enabled = 1;
4809 } else if (!strstart(p, "none", &opts)) {
4810 invalid_vga:
4811 fprintf(stderr, "Unknown vga type: %s\n", p);
4812 exit(1);
4814 while (*opts) {
4815 const char *nextopt;
4817 if (strstart(opts, ",retrace=", &nextopt)) {
4818 opts = nextopt;
4819 if (strstart(opts, "dumb", &nextopt))
4820 vga_retrace_method = VGA_RETRACE_DUMB;
4821 else if (strstart(opts, "precise", &nextopt))
4822 vga_retrace_method = VGA_RETRACE_PRECISE;
4823 else goto invalid_vga;
4824 } else goto invalid_vga;
4825 opts = nextopt;
4829 #ifdef _WIN32
4830 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4832 exit(STATUS_CONTROL_C_EXIT);
4833 return TRUE;
4835 #endif
4837 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4839 int ret;
4841 if(strlen(str) != 36)
4842 return -1;
4844 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4845 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4846 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4848 if(ret != 16)
4849 return -1;
4851 #ifdef TARGET_I386
4852 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4853 #endif
4855 return 0;
4858 #define MAX_NET_CLIENTS 32
4860 #ifdef USE_KVM
4862 #define HUGETLBFS_MAGIC 0x958458f6
4864 static long gethugepagesize(const char *path)
4866 struct statfs fs;
4867 int ret;
4869 do {
4870 ret = statfs(path, &fs);
4871 } while (ret != 0 && errno == EINTR);
4873 if (ret != 0) {
4874 perror("statfs");
4875 return 0;
4878 if (fs.f_type != HUGETLBFS_MAGIC)
4879 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4881 return fs.f_bsize;
4884 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4886 char *filename;
4887 void *area;
4888 int fd;
4889 #ifdef MAP_POPULATE
4890 int flags;
4891 #endif
4893 if (!kvm_has_sync_mmu()) {
4894 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4895 return NULL;
4898 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4899 return NULL;
4901 hpagesize = gethugepagesize(path);
4902 if (!hpagesize)
4903 return NULL;
4905 fd = mkstemp(filename);
4906 if (fd < 0) {
4907 perror("mkstemp");
4908 free(filename);
4909 return NULL;
4911 unlink(filename);
4912 free(filename);
4914 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4917 * ftruncate is not supported by hugetlbfs in older
4918 * hosts, so don't bother checking for errors.
4919 * If anything goes wrong with it under other filesystems,
4920 * mmap will fail.
4922 ftruncate(fd, memory);
4924 #ifdef MAP_POPULATE
4925 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4926 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4927 * to sidestep this quirk.
4929 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4930 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4931 #else
4932 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4933 #endif
4934 if (area == MAP_FAILED) {
4935 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4936 close(fd);
4937 return (NULL);
4939 *len = memory;
4940 return area;
4942 #endif
4944 #ifndef _WIN32
4946 static void termsig_handler(int signal)
4948 qemu_system_shutdown_request();
4951 static void termsig_setup(void)
4953 struct sigaction act;
4955 memset(&act, 0, sizeof(act));
4956 act.sa_handler = termsig_handler;
4957 sigaction(SIGINT, &act, NULL);
4958 sigaction(SIGHUP, &act, NULL);
4959 sigaction(SIGTERM, &act, NULL);
4962 #endif
4964 int main(int argc, char **argv, char **envp)
4966 const char *gdbstub_dev = NULL;
4967 uint32_t boot_devices_bitmap = 0;
4968 int i;
4969 int snapshot, linux_boot, net_boot;
4970 const char *initrd_filename;
4971 const char *kernel_filename, *kernel_cmdline;
4972 const char *boot_devices = "";
4973 DisplayState *ds;
4974 DisplayChangeListener *dcl;
4975 int cyls, heads, secs, translation;
4976 const char *net_clients[MAX_NET_CLIENTS];
4977 int nb_net_clients;
4978 const char *bt_opts[MAX_BT_CMDLINE];
4979 int nb_bt_opts;
4980 int hda_index;
4981 int optind;
4982 const char *r, *optarg;
4983 CharDriverState *monitor_hd = NULL;
4984 const char *monitor_device;
4985 const char *serial_devices[MAX_SERIAL_PORTS];
4986 int serial_device_index;
4987 const char *parallel_devices[MAX_PARALLEL_PORTS];
4988 int parallel_device_index;
4989 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4990 int virtio_console_index;
4991 const char *loadvm = NULL;
4992 QEMUMachine *machine;
4993 const char *cpu_model;
4994 const char *usb_devices[MAX_USB_CMDLINE];
4995 int usb_devices_index;
4996 #ifndef _WIN32
4997 int fds[2];
4998 #endif
4999 int tb_size;
5000 const char *pid_file = NULL;
5001 const char *incoming = NULL;
5002 #ifndef _WIN32
5003 int fd = 0;
5004 struct passwd *pwd = NULL;
5005 const char *chroot_dir = NULL;
5006 const char *run_as = NULL;
5007 #endif
5008 CPUState *env;
5010 qemu_cache_utils_init(envp);
5012 LIST_INIT (&vm_change_state_head);
5013 #ifndef _WIN32
5015 struct sigaction act;
5016 sigfillset(&act.sa_mask);
5017 act.sa_flags = 0;
5018 act.sa_handler = SIG_IGN;
5019 sigaction(SIGPIPE, &act, NULL);
5021 #else
5022 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5023 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5024 QEMU to run on a single CPU */
5026 HANDLE h;
5027 DWORD mask, smask;
5028 int i;
5029 h = GetCurrentProcess();
5030 if (GetProcessAffinityMask(h, &mask, &smask)) {
5031 for(i = 0; i < 32; i++) {
5032 if (mask & (1 << i))
5033 break;
5035 if (i != 32) {
5036 mask = 1 << i;
5037 SetProcessAffinityMask(h, mask);
5041 #endif
5043 module_call_init(MODULE_INIT_MACHINE);
5044 machine = first_machine;
5045 cpu_model = NULL;
5046 initrd_filename = NULL;
5047 ram_size = 0;
5048 snapshot = 0;
5049 nographic = 0;
5050 curses = 0;
5051 kernel_filename = NULL;
5052 kernel_cmdline = "";
5053 cyls = heads = secs = 0;
5054 translation = BIOS_ATA_TRANSLATION_AUTO;
5055 monitor_device = "vc:80Cx24C";
5057 serial_devices[0] = "vc:80Cx24C";
5058 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5059 serial_devices[i] = NULL;
5060 serial_device_index = 0;
5062 parallel_devices[0] = "vc:80Cx24C";
5063 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5064 parallel_devices[i] = NULL;
5065 parallel_device_index = 0;
5067 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5068 virtio_consoles[i] = NULL;
5069 virtio_console_index = 0;
5071 for (i = 0; i < MAX_NODES; i++) {
5072 node_mem[i] = 0;
5073 node_cpumask[i] = 0;
5076 usb_devices_index = 0;
5077 assigned_devices_index = 0;
5079 nb_net_clients = 0;
5080 nb_bt_opts = 0;
5081 nb_drives = 0;
5082 nb_drives_opt = 0;
5083 nb_numa_nodes = 0;
5084 hda_index = -1;
5086 nb_nics = 0;
5088 tb_size = 0;
5089 autostart= 1;
5091 register_watchdogs();
5093 optind = 1;
5094 for(;;) {
5095 if (optind >= argc)
5096 break;
5097 r = argv[optind];
5098 if (r[0] != '-') {
5099 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5100 } else {
5101 const QEMUOption *popt;
5103 optind++;
5104 /* Treat --foo the same as -foo. */
5105 if (r[1] == '-')
5106 r++;
5107 popt = qemu_options;
5108 for(;;) {
5109 if (!popt->name) {
5110 fprintf(stderr, "%s: invalid option -- '%s'\n",
5111 argv[0], r);
5112 exit(1);
5114 if (!strcmp(popt->name, r + 1))
5115 break;
5116 popt++;
5118 if (popt->flags & HAS_ARG) {
5119 if (optind >= argc) {
5120 fprintf(stderr, "%s: option '%s' requires an argument\n",
5121 argv[0], r);
5122 exit(1);
5124 optarg = argv[optind++];
5125 } else {
5126 optarg = NULL;
5129 switch(popt->index) {
5130 case QEMU_OPTION_M:
5131 machine = find_machine(optarg);
5132 if (!machine) {
5133 QEMUMachine *m;
5134 printf("Supported machines are:\n");
5135 for(m = first_machine; m != NULL; m = m->next) {
5136 printf("%-10s %s%s\n",
5137 m->name, m->desc,
5138 m == first_machine ? " (default)" : "");
5140 exit(*optarg != '?');
5142 break;
5143 case QEMU_OPTION_cpu:
5144 /* hw initialization will check this */
5145 if (*optarg == '?') {
5146 /* XXX: implement xxx_cpu_list for targets that still miss it */
5147 #if defined(cpu_list)
5148 cpu_list(stdout, &fprintf);
5149 #endif
5150 exit(0);
5151 } else {
5152 cpu_model = optarg;
5154 break;
5155 case QEMU_OPTION_initrd:
5156 initrd_filename = optarg;
5157 break;
5158 case QEMU_OPTION_hda:
5159 if (cyls == 0)
5160 hda_index = drive_add(optarg, HD_ALIAS, 0);
5161 else
5162 hda_index = drive_add(optarg, HD_ALIAS
5163 ",cyls=%d,heads=%d,secs=%d%s",
5164 0, cyls, heads, secs,
5165 translation == BIOS_ATA_TRANSLATION_LBA ?
5166 ",trans=lba" :
5167 translation == BIOS_ATA_TRANSLATION_NONE ?
5168 ",trans=none" : "");
5169 break;
5170 case QEMU_OPTION_hdb:
5171 case QEMU_OPTION_hdc:
5172 case QEMU_OPTION_hdd:
5173 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5174 break;
5175 case QEMU_OPTION_drive:
5176 drive_add(NULL, "%s", optarg);
5177 break;
5178 case QEMU_OPTION_mtdblock:
5179 drive_add(optarg, MTD_ALIAS);
5180 break;
5181 case QEMU_OPTION_sd:
5182 drive_add(optarg, SD_ALIAS);
5183 break;
5184 case QEMU_OPTION_pflash:
5185 drive_add(optarg, PFLASH_ALIAS);
5186 break;
5187 case QEMU_OPTION_snapshot:
5188 snapshot = 1;
5189 break;
5190 case QEMU_OPTION_hdachs:
5192 const char *p;
5193 p = optarg;
5194 cyls = strtol(p, (char **)&p, 0);
5195 if (cyls < 1 || cyls > 16383)
5196 goto chs_fail;
5197 if (*p != ',')
5198 goto chs_fail;
5199 p++;
5200 heads = strtol(p, (char **)&p, 0);
5201 if (heads < 1 || heads > 16)
5202 goto chs_fail;
5203 if (*p != ',')
5204 goto chs_fail;
5205 p++;
5206 secs = strtol(p, (char **)&p, 0);
5207 if (secs < 1 || secs > 63)
5208 goto chs_fail;
5209 if (*p == ',') {
5210 p++;
5211 if (!strcmp(p, "none"))
5212 translation = BIOS_ATA_TRANSLATION_NONE;
5213 else if (!strcmp(p, "lba"))
5214 translation = BIOS_ATA_TRANSLATION_LBA;
5215 else if (!strcmp(p, "auto"))
5216 translation = BIOS_ATA_TRANSLATION_AUTO;
5217 else
5218 goto chs_fail;
5219 } else if (*p != '\0') {
5220 chs_fail:
5221 fprintf(stderr, "qemu: invalid physical CHS format\n");
5222 exit(1);
5224 if (hda_index != -1)
5225 snprintf(drives_opt[hda_index].opt,
5226 sizeof(drives_opt[hda_index].opt),
5227 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5228 0, cyls, heads, secs,
5229 translation == BIOS_ATA_TRANSLATION_LBA ?
5230 ",trans=lba" :
5231 translation == BIOS_ATA_TRANSLATION_NONE ?
5232 ",trans=none" : "");
5234 break;
5235 case QEMU_OPTION_numa:
5236 if (nb_numa_nodes >= MAX_NODES) {
5237 fprintf(stderr, "qemu: too many NUMA nodes\n");
5238 exit(1);
5240 numa_add(optarg);
5241 break;
5242 case QEMU_OPTION_nographic:
5243 nographic = 1;
5244 break;
5245 #ifdef CONFIG_CURSES
5246 case QEMU_OPTION_curses:
5247 curses = 1;
5248 break;
5249 #endif
5250 case QEMU_OPTION_portrait:
5251 graphic_rotate = 1;
5252 break;
5253 case QEMU_OPTION_kernel:
5254 kernel_filename = optarg;
5255 break;
5256 case QEMU_OPTION_append:
5257 kernel_cmdline = optarg;
5258 break;
5259 case QEMU_OPTION_cdrom:
5260 drive_add(optarg, CDROM_ALIAS);
5261 break;
5262 case QEMU_OPTION_boot:
5263 boot_devices = optarg;
5264 /* We just do some generic consistency checks */
5266 /* Could easily be extended to 64 devices if needed */
5267 const char *p;
5269 boot_devices_bitmap = 0;
5270 for (p = boot_devices; *p != '\0'; p++) {
5271 /* Allowed boot devices are:
5272 * a b : floppy disk drives
5273 * c ... f : IDE disk drives
5274 * g ... m : machine implementation dependant drives
5275 * n ... p : network devices
5276 * It's up to each machine implementation to check
5277 * if the given boot devices match the actual hardware
5278 * implementation and firmware features.
5280 if (*p < 'a' || *p > 'q') {
5281 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5282 exit(1);
5284 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5285 fprintf(stderr,
5286 "Boot device '%c' was given twice\n",*p);
5287 exit(1);
5289 boot_devices_bitmap |= 1 << (*p - 'a');
5292 break;
5293 case QEMU_OPTION_fda:
5294 case QEMU_OPTION_fdb:
5295 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5296 break;
5297 #ifdef TARGET_I386
5298 case QEMU_OPTION_no_fd_bootchk:
5299 fd_bootchk = 0;
5300 break;
5301 #endif
5302 case QEMU_OPTION_net:
5303 if (nb_net_clients >= MAX_NET_CLIENTS) {
5304 fprintf(stderr, "qemu: too many network clients\n");
5305 exit(1);
5307 net_clients[nb_net_clients] = optarg;
5308 nb_net_clients++;
5309 break;
5310 #ifdef CONFIG_SLIRP
5311 case QEMU_OPTION_tftp:
5312 tftp_prefix = optarg;
5313 break;
5314 case QEMU_OPTION_bootp:
5315 bootp_filename = optarg;
5316 break;
5317 #ifndef _WIN32
5318 case QEMU_OPTION_smb:
5319 net_slirp_smb(optarg);
5320 break;
5321 #endif
5322 case QEMU_OPTION_redir:
5323 net_slirp_redir(NULL, optarg);
5324 break;
5325 #endif
5326 case QEMU_OPTION_bt:
5327 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5328 fprintf(stderr, "qemu: too many bluetooth options\n");
5329 exit(1);
5331 bt_opts[nb_bt_opts++] = optarg;
5332 break;
5333 #ifdef HAS_AUDIO
5334 case QEMU_OPTION_audio_help:
5335 AUD_help ();
5336 exit (0);
5337 break;
5338 case QEMU_OPTION_soundhw:
5339 select_soundhw (optarg);
5340 break;
5341 #endif
5342 case QEMU_OPTION_h:
5343 help(0);
5344 break;
5345 case QEMU_OPTION_version:
5346 version();
5347 exit(0);
5348 break;
5349 case QEMU_OPTION_m: {
5350 uint64_t value;
5351 char *ptr;
5353 value = strtoul(optarg, &ptr, 10);
5354 switch (*ptr) {
5355 case 0: case 'M': case 'm':
5356 value <<= 20;
5357 break;
5358 case 'G': case 'g':
5359 value <<= 30;
5360 break;
5361 default:
5362 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5363 exit(1);
5366 /* On 32-bit hosts, QEMU is limited by virtual address space */
5367 if (value > (2047 << 20)
5368 #ifndef CONFIG_KQEMU
5369 && HOST_LONG_BITS == 32
5370 #endif
5372 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5373 exit(1);
5375 if (value != (uint64_t)(ram_addr_t)value) {
5376 fprintf(stderr, "qemu: ram size too large\n");
5377 exit(1);
5379 ram_size = value;
5380 break;
5382 case QEMU_OPTION_d:
5384 int mask;
5385 const CPULogItem *item;
5387 mask = cpu_str_to_log_mask(optarg);
5388 if (!mask) {
5389 printf("Log items (comma separated):\n");
5390 for(item = cpu_log_items; item->mask != 0; item++) {
5391 printf("%-10s %s\n", item->name, item->help);
5393 exit(1);
5395 cpu_set_log(mask);
5397 break;
5398 case QEMU_OPTION_s:
5399 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5400 break;
5401 case QEMU_OPTION_gdb:
5402 gdbstub_dev = optarg;
5403 break;
5404 case QEMU_OPTION_L:
5405 bios_dir = optarg;
5406 break;
5407 case QEMU_OPTION_bios:
5408 bios_name = optarg;
5409 break;
5410 case QEMU_OPTION_singlestep:
5411 singlestep = 1;
5412 break;
5413 case QEMU_OPTION_S:
5414 autostart = 0;
5415 break;
5416 #ifndef _WIN32
5417 case QEMU_OPTION_k:
5418 keyboard_layout = optarg;
5419 break;
5420 #endif
5421 case QEMU_OPTION_localtime:
5422 rtc_utc = 0;
5423 break;
5424 case QEMU_OPTION_vga:
5425 select_vgahw (optarg);
5426 break;
5427 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5428 case QEMU_OPTION_g:
5430 const char *p;
5431 int w, h, depth;
5432 p = optarg;
5433 w = strtol(p, (char **)&p, 10);
5434 if (w <= 0) {
5435 graphic_error:
5436 fprintf(stderr, "qemu: invalid resolution or depth\n");
5437 exit(1);
5439 if (*p != 'x')
5440 goto graphic_error;
5441 p++;
5442 h = strtol(p, (char **)&p, 10);
5443 if (h <= 0)
5444 goto graphic_error;
5445 if (*p == 'x') {
5446 p++;
5447 depth = strtol(p, (char **)&p, 10);
5448 if (depth != 8 && depth != 15 && depth != 16 &&
5449 depth != 24 && depth != 32)
5450 goto graphic_error;
5451 } else if (*p == '\0') {
5452 depth = graphic_depth;
5453 } else {
5454 goto graphic_error;
5457 graphic_width = w;
5458 graphic_height = h;
5459 graphic_depth = depth;
5461 break;
5462 #endif
5463 case QEMU_OPTION_echr:
5465 char *r;
5466 term_escape_char = strtol(optarg, &r, 0);
5467 if (r == optarg)
5468 printf("Bad argument to echr\n");
5469 break;
5471 case QEMU_OPTION_monitor:
5472 monitor_device = optarg;
5473 break;
5474 case QEMU_OPTION_serial:
5475 if (serial_device_index >= MAX_SERIAL_PORTS) {
5476 fprintf(stderr, "qemu: too many serial ports\n");
5477 exit(1);
5479 serial_devices[serial_device_index] = optarg;
5480 serial_device_index++;
5481 break;
5482 case QEMU_OPTION_watchdog:
5483 i = select_watchdog(optarg);
5484 if (i > 0)
5485 exit (i == 1 ? 1 : 0);
5486 break;
5487 case QEMU_OPTION_watchdog_action:
5488 if (select_watchdog_action(optarg) == -1) {
5489 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5490 exit(1);
5492 break;
5493 case QEMU_OPTION_virtiocon:
5494 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5495 fprintf(stderr, "qemu: too many virtio consoles\n");
5496 exit(1);
5498 virtio_consoles[virtio_console_index] = optarg;
5499 virtio_console_index++;
5500 break;
5501 case QEMU_OPTION_parallel:
5502 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5503 fprintf(stderr, "qemu: too many parallel ports\n");
5504 exit(1);
5506 parallel_devices[parallel_device_index] = optarg;
5507 parallel_device_index++;
5508 break;
5509 case QEMU_OPTION_loadvm:
5510 loadvm = optarg;
5511 break;
5512 case QEMU_OPTION_full_screen:
5513 full_screen = 1;
5514 break;
5515 #ifdef CONFIG_SDL
5516 case QEMU_OPTION_no_frame:
5517 no_frame = 1;
5518 break;
5519 case QEMU_OPTION_alt_grab:
5520 alt_grab = 1;
5521 break;
5522 case QEMU_OPTION_no_quit:
5523 no_quit = 1;
5524 break;
5525 case QEMU_OPTION_sdl:
5526 sdl = 1;
5527 break;
5528 #endif
5529 case QEMU_OPTION_pidfile:
5530 pid_file = optarg;
5531 break;
5532 #ifdef TARGET_I386
5533 case QEMU_OPTION_win2k_hack:
5534 win2k_install_hack = 1;
5535 break;
5536 case QEMU_OPTION_rtc_td_hack:
5537 rtc_td_hack = 1;
5538 break;
5539 case QEMU_OPTION_acpitable:
5540 if(acpi_table_add(optarg) < 0) {
5541 fprintf(stderr, "Wrong acpi table provided\n");
5542 exit(1);
5544 break;
5545 case QEMU_OPTION_smbios:
5546 if(smbios_entry_add(optarg) < 0) {
5547 fprintf(stderr, "Wrong smbios provided\n");
5548 exit(1);
5550 break;
5551 #endif
5552 #ifdef CONFIG_KQEMU
5553 case QEMU_OPTION_no_kqemu:
5554 kqemu_allowed = 0;
5555 break;
5556 case QEMU_OPTION_kernel_kqemu:
5557 kqemu_allowed = 2;
5558 break;
5559 #endif
5560 #ifdef CONFIG_KVM
5561 case QEMU_OPTION_enable_kvm:
5562 kvm_allowed = 1;
5563 #ifdef CONFIG_KQEMU
5564 kqemu_allowed = 0;
5565 #endif
5566 break;
5567 #endif
5568 #ifdef USE_KVM
5569 case QEMU_OPTION_no_kvm:
5570 kvm_allowed = 0;
5571 break;
5572 case QEMU_OPTION_no_kvm_irqchip: {
5573 kvm_irqchip = 0;
5574 kvm_pit = 0;
5575 break;
5577 case QEMU_OPTION_no_kvm_pit: {
5578 kvm_pit = 0;
5579 break;
5581 case QEMU_OPTION_no_kvm_pit_reinjection: {
5582 kvm_pit_reinject = 0;
5583 break;
5585 case QEMU_OPTION_enable_nesting: {
5586 kvm_nested = 1;
5587 break;
5589 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5590 case QEMU_OPTION_pcidevice:
5591 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5592 fprintf(stderr, "Too many assigned devices\n");
5593 exit(1);
5595 assigned_devices[assigned_devices_index] = optarg;
5596 assigned_devices_index++;
5597 break;
5598 #endif
5599 #endif
5600 case QEMU_OPTION_usb:
5601 usb_enabled = 1;
5602 break;
5603 case QEMU_OPTION_usbdevice:
5604 usb_enabled = 1;
5605 if (usb_devices_index >= MAX_USB_CMDLINE) {
5606 fprintf(stderr, "Too many USB devices\n");
5607 exit(1);
5609 usb_devices[usb_devices_index] = optarg;
5610 usb_devices_index++;
5611 break;
5612 case QEMU_OPTION_smp:
5613 smp_cpus = atoi(optarg);
5614 if (smp_cpus < 1) {
5615 fprintf(stderr, "Invalid number of CPUs\n");
5616 exit(1);
5618 break;
5619 case QEMU_OPTION_vnc:
5620 vnc_display = optarg;
5621 break;
5622 #ifdef TARGET_I386
5623 case QEMU_OPTION_no_acpi:
5624 acpi_enabled = 0;
5625 break;
5626 case QEMU_OPTION_no_hpet:
5627 no_hpet = 1;
5628 break;
5629 #endif
5630 case QEMU_OPTION_no_reboot:
5631 no_reboot = 1;
5632 break;
5633 case QEMU_OPTION_no_shutdown:
5634 no_shutdown = 1;
5635 break;
5636 case QEMU_OPTION_show_cursor:
5637 cursor_hide = 0;
5638 break;
5639 case QEMU_OPTION_uuid:
5640 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5641 fprintf(stderr, "Fail to parse UUID string."
5642 " Wrong format.\n");
5643 exit(1);
5645 break;
5646 #ifndef _WIN32
5647 case QEMU_OPTION_daemonize:
5648 daemonize = 1;
5649 break;
5650 #endif
5651 case QEMU_OPTION_option_rom:
5652 if (nb_option_roms >= MAX_OPTION_ROMS) {
5653 fprintf(stderr, "Too many option ROMs\n");
5654 exit(1);
5656 option_rom[nb_option_roms] = optarg;
5657 nb_option_roms++;
5658 break;
5659 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5660 case QEMU_OPTION_semihosting:
5661 semihosting_enabled = 1;
5662 break;
5663 #endif
5664 case QEMU_OPTION_tdf:
5665 time_drift_fix = 1;
5666 break;
5667 case QEMU_OPTION_kvm_shadow_memory:
5668 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5669 break;
5670 case QEMU_OPTION_mempath:
5671 mem_path = optarg;
5672 break;
5673 #ifdef MAP_POPULATE
5674 case QEMU_OPTION_mem_prealloc:
5675 mem_prealloc = !mem_prealloc;
5676 break;
5677 #endif
5678 case QEMU_OPTION_name:
5679 qemu_name = optarg;
5680 break;
5681 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5682 case QEMU_OPTION_prom_env:
5683 if (nb_prom_envs >= MAX_PROM_ENVS) {
5684 fprintf(stderr, "Too many prom variables\n");
5685 exit(1);
5687 prom_envs[nb_prom_envs] = optarg;
5688 nb_prom_envs++;
5689 break;
5690 #endif
5691 #ifdef TARGET_ARM
5692 case QEMU_OPTION_old_param:
5693 old_param = 1;
5694 break;
5695 #endif
5696 case QEMU_OPTION_clock:
5697 configure_alarms(optarg);
5698 break;
5699 case QEMU_OPTION_startdate:
5701 struct tm tm;
5702 time_t rtc_start_date;
5703 if (!strcmp(optarg, "now")) {
5704 rtc_date_offset = -1;
5705 } else {
5706 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5707 &tm.tm_year,
5708 &tm.tm_mon,
5709 &tm.tm_mday,
5710 &tm.tm_hour,
5711 &tm.tm_min,
5712 &tm.tm_sec) == 6) {
5713 /* OK */
5714 } else if (sscanf(optarg, "%d-%d-%d",
5715 &tm.tm_year,
5716 &tm.tm_mon,
5717 &tm.tm_mday) == 3) {
5718 tm.tm_hour = 0;
5719 tm.tm_min = 0;
5720 tm.tm_sec = 0;
5721 } else {
5722 goto date_fail;
5724 tm.tm_year -= 1900;
5725 tm.tm_mon--;
5726 rtc_start_date = mktimegm(&tm);
5727 if (rtc_start_date == -1) {
5728 date_fail:
5729 fprintf(stderr, "Invalid date format. Valid format are:\n"
5730 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5731 exit(1);
5733 rtc_date_offset = time(NULL) - rtc_start_date;
5736 break;
5737 case QEMU_OPTION_tb_size:
5738 tb_size = strtol(optarg, NULL, 0);
5739 if (tb_size < 0)
5740 tb_size = 0;
5741 break;
5742 case QEMU_OPTION_icount:
5743 use_icount = 1;
5744 if (strcmp(optarg, "auto") == 0) {
5745 icount_time_shift = -1;
5746 } else {
5747 icount_time_shift = strtol(optarg, NULL, 0);
5749 break;
5750 case QEMU_OPTION_incoming:
5751 incoming = optarg;
5752 break;
5753 #ifndef _WIN32
5754 case QEMU_OPTION_chroot:
5755 chroot_dir = optarg;
5756 break;
5757 case QEMU_OPTION_runas:
5758 run_as = optarg;
5759 break;
5760 case QEMU_OPTION_nvram:
5761 nvram = optarg;
5762 break;
5763 #endif
5764 #ifdef CONFIG_XEN
5765 case QEMU_OPTION_xen_domid:
5766 xen_domid = atoi(optarg);
5767 break;
5768 case QEMU_OPTION_xen_create:
5769 xen_mode = XEN_CREATE;
5770 break;
5771 case QEMU_OPTION_xen_attach:
5772 xen_mode = XEN_ATTACH;
5773 break;
5774 #endif
5779 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5780 if (kvm_allowed && kqemu_allowed) {
5781 fprintf(stderr,
5782 "You can not enable both KVM and kqemu at the same time\n");
5783 exit(1);
5785 #endif
5787 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5788 if (smp_cpus > machine->max_cpus) {
5789 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5790 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5791 machine->max_cpus);
5792 exit(1);
5795 if (nographic) {
5796 if (serial_device_index == 0)
5797 serial_devices[0] = "stdio";
5798 if (parallel_device_index == 0)
5799 parallel_devices[0] = "null";
5800 if (strncmp(monitor_device, "vc", 2) == 0)
5801 monitor_device = "stdio";
5804 #ifndef _WIN32
5805 if (daemonize) {
5806 pid_t pid;
5808 if (pipe(fds) == -1)
5809 exit(1);
5811 pid = fork();
5812 if (pid > 0) {
5813 uint8_t status;
5814 ssize_t len;
5816 close(fds[1]);
5818 again:
5819 len = read(fds[0], &status, 1);
5820 if (len == -1 && (errno == EINTR))
5821 goto again;
5823 if (len != 1)
5824 exit(1);
5825 else if (status == 1) {
5826 fprintf(stderr, "Could not acquire pidfile\n");
5827 exit(1);
5828 } else
5829 exit(0);
5830 } else if (pid < 0)
5831 exit(1);
5833 setsid();
5835 pid = fork();
5836 if (pid > 0)
5837 exit(0);
5838 else if (pid < 0)
5839 exit(1);
5841 umask(027);
5843 signal(SIGTSTP, SIG_IGN);
5844 signal(SIGTTOU, SIG_IGN);
5845 signal(SIGTTIN, SIG_IGN);
5848 #ifdef USE_KVM
5849 if (kvm_enabled()) {
5850 if (kvm_qemu_init() < 0) {
5851 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5852 #ifdef NO_CPU_EMULATION
5853 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5854 exit(1);
5855 #endif
5856 kvm_allowed = 0;
5859 #endif
5861 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5862 if (daemonize) {
5863 uint8_t status = 1;
5864 write(fds[1], &status, 1);
5865 } else
5866 fprintf(stderr, "Could not acquire pid file\n");
5867 exit(1);
5869 #endif
5871 #ifdef CONFIG_KQEMU
5872 if (smp_cpus > 1)
5873 kqemu_allowed = 0;
5874 #endif
5875 if (qemu_init_main_loop()) {
5876 fprintf(stderr, "qemu_init_main_loop failed\n");
5877 exit(1);
5879 linux_boot = (kernel_filename != NULL);
5880 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5882 if (!linux_boot && *kernel_cmdline != '\0') {
5883 fprintf(stderr, "-append only allowed with -kernel option\n");
5884 exit(1);
5887 if (!linux_boot && initrd_filename != NULL) {
5888 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5889 exit(1);
5892 /* boot to floppy or the default cd if no hard disk defined yet */
5893 if (!boot_devices[0]) {
5894 boot_devices = "cad";
5896 setvbuf(stdout, NULL, _IOLBF, 0);
5898 init_timers();
5899 if (init_timer_alarm() < 0) {
5900 fprintf(stderr, "could not initialize alarm timer\n");
5901 exit(1);
5903 if (use_icount && icount_time_shift < 0) {
5904 use_icount = 2;
5905 /* 125MIPS seems a reasonable initial guess at the guest speed.
5906 It will be corrected fairly quickly anyway. */
5907 icount_time_shift = 3;
5908 init_icount_adjust();
5911 #ifdef _WIN32
5912 socket_init();
5913 #endif
5915 /* init network clients */
5916 if (nb_net_clients == 0) {
5917 /* if no clients, we use a default config */
5918 net_clients[nb_net_clients++] = "nic";
5919 #ifdef CONFIG_SLIRP
5920 net_clients[nb_net_clients++] = "user";
5921 #endif
5924 for(i = 0;i < nb_net_clients; i++) {
5925 if (net_client_parse(net_clients[i]) < 0)
5926 exit(1);
5928 net_client_check();
5930 #ifdef TARGET_I386
5931 /* XXX: this should be moved in the PC machine instantiation code */
5932 if (net_boot != 0) {
5933 int netroms = 0;
5934 for (i = 0; i < nb_nics && i < 4; i++) {
5935 const char *model = nd_table[i].model;
5936 char buf[1024];
5937 if (net_boot & (1 << i)) {
5938 if (model == NULL)
5939 model = "rtl8139";
5940 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5941 if (get_image_size(buf) > 0) {
5942 if (nb_option_roms >= MAX_OPTION_ROMS) {
5943 fprintf(stderr, "Too many option ROMs\n");
5944 exit(1);
5946 option_rom[nb_option_roms] = strdup(buf);
5947 nb_option_roms++;
5948 netroms++;
5952 if (netroms == 0) {
5953 fprintf(stderr, "No valid PXE rom found for network device\n");
5954 exit(1);
5957 #endif
5959 /* init the bluetooth world */
5960 for (i = 0; i < nb_bt_opts; i++)
5961 if (bt_parse(bt_opts[i]))
5962 exit(1);
5964 /* init the memory */
5965 if (ram_size == 0)
5966 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5968 if (kvm_enabled()) {
5969 if (kvm_qemu_create_context() < 0) {
5970 fprintf(stderr, "Could not create KVM context\n");
5971 exit(1);
5975 #ifdef CONFIG_KQEMU
5976 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5977 guest ram allocation. It needs to go away. */
5978 if (kqemu_allowed) {
5979 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5980 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5981 if (!kqemu_phys_ram_base) {
5982 fprintf(stderr, "Could not allocate physical memory\n");
5983 exit(1);
5986 #endif
5988 /* init the dynamic translator */
5989 cpu_exec_init_all(tb_size * 1024 * 1024);
5991 bdrv_init();
5992 dma_helper_init();
5994 /* we always create the cdrom drive, even if no disk is there */
5996 if (nb_drives_opt < MAX_DRIVES)
5997 drive_add(NULL, CDROM_ALIAS);
5999 /* we always create at least one floppy */
6001 if (nb_drives_opt < MAX_DRIVES)
6002 drive_add(NULL, FD_ALIAS, 0);
6004 /* we always create one sd slot, even if no card is in it */
6006 if (nb_drives_opt < MAX_DRIVES)
6007 drive_add(NULL, SD_ALIAS);
6009 /* open the virtual block devices
6010 * note that migration with device
6011 * hot add/remove is broken.
6013 for(i = 0; i < nb_drives_opt; i++)
6014 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6015 exit(1);
6017 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6018 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6020 #ifndef _WIN32
6021 /* must be after terminal init, SDL library changes signal handlers */
6022 termsig_setup();
6023 #endif
6025 /* Maintain compatibility with multiple stdio monitors */
6026 if (!strcmp(monitor_device,"stdio")) {
6027 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6028 const char *devname = serial_devices[i];
6029 if (devname && !strcmp(devname,"mon:stdio")) {
6030 monitor_device = NULL;
6031 break;
6032 } else if (devname && !strcmp(devname,"stdio")) {
6033 monitor_device = NULL;
6034 serial_devices[i] = "mon:stdio";
6035 break;
6040 if (nb_numa_nodes > 0) {
6041 int i;
6043 if (nb_numa_nodes > smp_cpus) {
6044 nb_numa_nodes = smp_cpus;
6047 /* If no memory size if given for any node, assume the default case
6048 * and distribute the available memory equally across all nodes
6050 for (i = 0; i < nb_numa_nodes; i++) {
6051 if (node_mem[i] != 0)
6052 break;
6054 if (i == nb_numa_nodes) {
6055 uint64_t usedmem = 0;
6057 /* On Linux, the each node's border has to be 8MB aligned,
6058 * the final node gets the rest.
6060 for (i = 0; i < nb_numa_nodes - 1; i++) {
6061 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6062 usedmem += node_mem[i];
6064 node_mem[i] = ram_size - usedmem;
6067 for (i = 0; i < nb_numa_nodes; i++) {
6068 if (node_cpumask[i] != 0)
6069 break;
6071 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6072 * must cope with this anyway, because there are BIOSes out there in
6073 * real machines which also use this scheme.
6075 if (i == nb_numa_nodes) {
6076 for (i = 0; i < smp_cpus; i++) {
6077 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6082 #ifdef KVM_UPSTREAM
6083 if (kvm_enabled()) {
6084 int ret;
6086 ret = kvm_init(smp_cpus);
6087 if (ret < 0) {
6088 fprintf(stderr, "failed to initialize KVM\n");
6089 exit(1);
6092 #endif
6094 if (monitor_device) {
6095 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6096 if (!monitor_hd) {
6097 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6098 exit(1);
6102 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6103 const char *devname = serial_devices[i];
6104 if (devname && strcmp(devname, "none")) {
6105 char label[32];
6106 snprintf(label, sizeof(label), "serial%d", i);
6107 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6108 if (!serial_hds[i]) {
6109 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6110 devname);
6111 exit(1);
6116 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6117 const char *devname = parallel_devices[i];
6118 if (devname && strcmp(devname, "none")) {
6119 char label[32];
6120 snprintf(label, sizeof(label), "parallel%d", i);
6121 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6122 if (!parallel_hds[i]) {
6123 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6124 devname);
6125 exit(1);
6130 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6131 const char *devname = virtio_consoles[i];
6132 if (devname && strcmp(devname, "none")) {
6133 char label[32];
6134 snprintf(label, sizeof(label), "virtcon%d", i);
6135 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6136 if (!virtcon_hds[i]) {
6137 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6138 devname);
6139 exit(1);
6144 module_call_init(MODULE_INIT_DEVICE);
6146 if (kvm_enabled())
6147 kvm_init_ap();
6149 machine->init(ram_size, boot_devices,
6150 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6153 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6154 for (i = 0; i < nb_numa_nodes; i++) {
6155 if (node_cpumask[i] & (1 << env->cpu_index)) {
6156 env->numa_node = i;
6161 current_machine = machine;
6163 /* Set KVM's vcpu state to qemu's initial CPUState. */
6164 if (kvm_enabled()) {
6165 int ret;
6167 ret = kvm_sync_vcpus();
6168 if (ret < 0) {
6169 fprintf(stderr, "failed to initialize vcpus\n");
6170 exit(1);
6174 /* init USB devices */
6175 if (usb_enabled) {
6176 for(i = 0; i < usb_devices_index; i++) {
6177 if (usb_device_add(usb_devices[i], 0) < 0) {
6178 fprintf(stderr, "Warning: could not add USB device %s\n",
6179 usb_devices[i]);
6184 if (!display_state)
6185 dumb_display_init();
6186 /* just use the first displaystate for the moment */
6187 ds = display_state;
6188 /* terminal init */
6189 if (nographic) {
6190 if (curses) {
6191 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
6192 exit(1);
6194 } else {
6195 #if defined(CONFIG_CURSES)
6196 if (curses) {
6197 /* At the moment curses cannot be used with other displays */
6198 curses_display_init(ds, full_screen);
6199 } else
6200 #endif
6201 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6202 if (sdl) {
6203 #if defined(CONFIG_SDL)
6204 sdl_display_init(ds, full_screen, no_frame);
6205 #elif defined(CONFIG_COCOA)
6206 cocoa_display_init(ds, full_screen);
6207 #endif
6208 } else
6209 #endif
6211 int print_port = 0;
6213 if (vnc_display == NULL) {
6214 vnc_display = "localhost:0,to=99";
6215 print_port = 1;
6218 vnc_display_init(ds);
6219 if (vnc_display_open(ds, vnc_display) < 0)
6220 exit(1);
6222 if (print_port) {
6223 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6227 dpy_resize(ds);
6229 dcl = ds->listeners;
6230 while (dcl != NULL) {
6231 if (dcl->dpy_refresh != NULL) {
6232 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6233 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6235 dcl = dcl->next;
6238 if (nographic || (vnc_display && !sdl)) {
6239 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6240 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6243 text_consoles_set_display(display_state);
6244 qemu_chr_initial_reset();
6246 if (monitor_device && monitor_hd)
6247 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6249 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6250 const char *devname = serial_devices[i];
6251 if (devname && strcmp(devname, "none")) {
6252 char label[32];
6253 snprintf(label, sizeof(label), "serial%d", i);
6254 if (strstart(devname, "vc", 0))
6255 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6259 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6260 const char *devname = parallel_devices[i];
6261 if (devname && strcmp(devname, "none")) {
6262 char label[32];
6263 snprintf(label, sizeof(label), "parallel%d", i);
6264 if (strstart(devname, "vc", 0))
6265 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6269 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6270 const char *devname = virtio_consoles[i];
6271 if (virtcon_hds[i] && devname) {
6272 char label[32];
6273 snprintf(label, sizeof(label), "virtcon%d", i);
6274 if (strstart(devname, "vc", 0))
6275 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6279 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6280 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6281 gdbstub_dev);
6282 exit(1);
6285 if (loadvm)
6286 do_loadvm(cur_mon, loadvm);
6288 if (incoming) {
6289 autostart = 0; /* fixme how to deal with -daemonize */
6290 qemu_start_incoming_migration(incoming);
6293 if (autostart)
6294 vm_start();
6296 #ifndef _WIN32
6297 if (daemonize) {
6298 uint8_t status = 0;
6299 ssize_t len;
6301 again1:
6302 len = write(fds[1], &status, 1);
6303 if (len == -1 && (errno == EINTR))
6304 goto again1;
6306 if (len != 1)
6307 exit(1);
6309 chdir("/");
6310 TFR(fd = open("/dev/null", O_RDWR));
6311 if (fd == -1)
6312 exit(1);
6315 if (run_as) {
6316 pwd = getpwnam(run_as);
6317 if (!pwd) {
6318 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6319 exit(1);
6323 if (chroot_dir) {
6324 if (chroot(chroot_dir) < 0) {
6325 fprintf(stderr, "chroot failed\n");
6326 exit(1);
6328 chdir("/");
6331 if (run_as) {
6332 if (setgid(pwd->pw_gid) < 0) {
6333 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6334 exit(1);
6336 if (setuid(pwd->pw_uid) < 0) {
6337 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6338 exit(1);
6340 if (setuid(0) != -1) {
6341 fprintf(stderr, "Dropping privileges failed\n");
6342 exit(1);
6346 if (daemonize) {
6347 dup2(fd, 0);
6348 dup2(fd, 1);
6349 dup2(fd, 2);
6351 close(fd);
6353 #endif
6355 main_loop();
6356 quit_timers();
6357 net_cleanup();
6359 return 0;