Merge branch 'master' of git://git.sv.gnu.org/qemu into master
[qemu-kvm/fedora.git] / vl.c
blob9ff4a5a89c8931c155c4d7dd89a645e9b7550bac
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.
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <time.h>
29 #include <errno.h>
30 #include <sys/time.h>
31 #include <zlib.h>
33 /* Needed early for HOST_BSD etc. */
34 #include "config-host.h"
36 #ifndef _WIN32
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <sys/vfs.h>
46 #include <netinet/in.h>
47 #include <net/if.h>
48 #if defined(__NetBSD__)
49 #include <net/if_tap.h>
50 #endif
51 #ifdef __linux__
52 #include <linux/if_tun.h>
53 #endif
54 #include <arpa/inet.h>
55 #include <dirent.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef HOST_BSD
59 #include <sys/stat.h>
60 #if defined(__FreeBSD__) || defined(__DragonFly__)
61 #include <libutil.h>
62 #else
63 #include <util.h>
64 #endif
65 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
66 #include <freebsd/stdlib.h>
67 #else
68 #ifdef __linux__
69 #include <pty.h>
70 #include <malloc.h>
71 #include <linux/rtc.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
76 #include "hpet.h"
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
80 #endif
81 #ifdef __sun__
82 #include <sys/stat.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
92 #include <net/if.h>
93 #include <syslog.h>
94 #include <stropts.h>
95 #endif
96 #endif
97 #endif
99 #if defined(__OpenBSD__)
100 #include <util.h>
101 #endif
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
105 #endif
107 #ifdef _WIN32
108 #include <windows.h>
109 #include <malloc.h>
110 #include <sys/timeb.h>
111 #include <mmsystem.h>
112 #define getopt_long_only getopt_long
113 #define memalign(align, size) malloc(size)
114 #endif
116 #ifdef CONFIG_SDL
117 #ifdef __APPLE__
118 #include <SDL/SDL.h>
119 int qemu_main(int argc, char **argv, char **envp);
120 int main(int argc, char **argv)
122 qemu_main(argc, argv, NULL);
124 #undef main
125 #define main qemu_main
126 #endif
127 #endif /* CONFIG_SDL */
129 #ifdef CONFIG_COCOA
130 #undef main
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
134 #include "hw/hw.h"
135 #include "hw/boards.h"
136 #include "hw/usb.h"
137 #include "hw/pcmcia.h"
138 #include "hw/pc.h"
139 #include "hw/audiodev.h"
140 #include "hw/isa.h"
141 #include "hw/baum.h"
142 #include "hw/bt.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 static int vga_ram_size;
207 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
208 static DisplayState *display_state;
209 int nographic;
210 static int curses;
211 static int sdl;
212 const char* keyboard_layout = NULL;
213 int64_t ticks_per_sec;
214 ram_addr_t ram_size;
215 int nb_nics;
216 NICInfo nd_table[MAX_NICS];
217 int vm_running;
218 static int autostart;
219 static int rtc_utc = 1;
220 static int rtc_date_offset = -1; /* -1 means no change */
221 int cirrus_vga_enabled = 1;
222 int std_vga_enabled = 0;
223 int vmsvga_enabled = 0;
224 int xenfb_enabled = 0;
225 #ifdef TARGET_SPARC
226 int graphic_width = 1024;
227 int graphic_height = 768;
228 int graphic_depth = 8;
229 #else
230 int graphic_width = 800;
231 int graphic_height = 600;
232 int graphic_depth = 15;
233 #endif
234 static int full_screen = 0;
235 #ifdef CONFIG_SDL
236 static int no_frame = 0;
237 #endif
238 int no_quit = 0;
239 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
240 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
241 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
242 #ifdef TARGET_I386
243 int win2k_install_hack = 0;
244 int rtc_td_hack = 0;
245 #endif
246 int usb_enabled = 0;
247 int singlestep = 0;
248 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
249 int assigned_devices_index;
250 int smp_cpus = 1;
251 const char *vnc_display;
252 int acpi_enabled = 1;
253 int no_hpet = 0;
254 int fd_bootchk = 1;
255 int no_reboot = 0;
256 int no_shutdown = 0;
257 int cursor_hide = 1;
258 int graphic_rotate = 0;
259 #ifndef _WIN32
260 int daemonize = 0;
261 #endif
262 const char *option_rom[MAX_OPTION_ROMS];
263 int nb_option_roms;
264 int semihosting_enabled = 0;
265 int time_drift_fix = 0;
266 unsigned int kvm_shadow_memory = 0;
267 const char *mem_path = NULL;
268 #ifdef MAP_POPULATE
269 int mem_prealloc = 1; /* force preallocation of physical target memory */
270 #endif
271 long hpagesize = 0;
272 const char *cpu_vendor_string;
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 event_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 /* KVM runs the main loop in a separate thread. If we update one of the lists
306 * that are polled before or after select(), we need to make sure to break out
307 * of the select() to ensure the new item is serviced.
309 static void main_loop_break(void)
311 if (kvm_enabled())
312 qemu_kvm_notify_work();
315 /***********************************************************/
316 /* x86 ISA bus support */
318 target_phys_addr_t isa_mem_base = 0;
319 PicState2 *isa_pic;
321 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
322 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
324 static uint32_t ioport_read(int index, uint32_t address)
326 static IOPortReadFunc *default_func[3] = {
327 default_ioport_readb,
328 default_ioport_readw,
329 default_ioport_readl
331 IOPortReadFunc *func = ioport_read_table[index][address];
332 if (!func)
333 func = default_func[index];
334 return func(ioport_opaque[address], address);
337 static void ioport_write(int index, uint32_t address, uint32_t data)
339 static IOPortWriteFunc *default_func[3] = {
340 default_ioport_writeb,
341 default_ioport_writew,
342 default_ioport_writel
344 IOPortWriteFunc *func = ioport_write_table[index][address];
345 if (!func)
346 func = default_func[index];
347 func(ioport_opaque[address], address, data);
350 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
352 #ifdef DEBUG_UNUSED_IOPORT
353 fprintf(stderr, "unused inb: port=0x%04x\n", address);
354 #endif
355 return 0xff;
358 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
360 #ifdef DEBUG_UNUSED_IOPORT
361 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
362 #endif
365 /* default is to make two byte accesses */
366 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
368 uint32_t data;
369 data = ioport_read(0, address);
370 address = (address + 1) & (MAX_IOPORTS - 1);
371 data |= ioport_read(0, address) << 8;
372 return data;
375 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
377 ioport_write(0, address, data & 0xff);
378 address = (address + 1) & (MAX_IOPORTS - 1);
379 ioport_write(0, address, (data >> 8) & 0xff);
382 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
384 #ifdef DEBUG_UNUSED_IOPORT
385 fprintf(stderr, "unused inl: port=0x%04x\n", address);
386 #endif
387 return 0xffffffff;
390 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
392 #ifdef DEBUG_UNUSED_IOPORT
393 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
394 #endif
397 /* size is the word size in byte */
398 int register_ioport_read(int start, int length, int size,
399 IOPortReadFunc *func, void *opaque)
401 int i, bsize;
403 if (size == 1) {
404 bsize = 0;
405 } else if (size == 2) {
406 bsize = 1;
407 } else if (size == 4) {
408 bsize = 2;
409 } else {
410 hw_error("register_ioport_read: invalid size");
411 return -1;
413 for(i = start; i < start + length; i += size) {
414 ioport_read_table[bsize][i] = func;
415 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
416 hw_error("register_ioport_read: invalid opaque");
417 ioport_opaque[i] = opaque;
419 return 0;
422 /* size is the word size in byte */
423 int register_ioport_write(int start, int length, int size,
424 IOPortWriteFunc *func, void *opaque)
426 int i, bsize;
428 if (size == 1) {
429 bsize = 0;
430 } else if (size == 2) {
431 bsize = 1;
432 } else if (size == 4) {
433 bsize = 2;
434 } else {
435 hw_error("register_ioport_write: invalid size");
436 return -1;
438 for(i = start; i < start + length; i += size) {
439 ioport_write_table[bsize][i] = func;
440 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
441 hw_error("register_ioport_write: invalid opaque");
442 ioport_opaque[i] = opaque;
444 return 0;
447 void isa_unassign_ioport(int start, int length)
449 int i;
451 for(i = start; i < start + length; i++) {
452 ioport_read_table[0][i] = default_ioport_readb;
453 ioport_read_table[1][i] = default_ioport_readw;
454 ioport_read_table[2][i] = default_ioport_readl;
456 ioport_write_table[0][i] = default_ioport_writeb;
457 ioport_write_table[1][i] = default_ioport_writew;
458 ioport_write_table[2][i] = default_ioport_writel;
460 ioport_opaque[i] = NULL;
464 /***********************************************************/
466 void cpu_outb(CPUState *env, int addr, int val)
468 LOG_IOPORT("outb: %04x %02x\n", addr, val);
469 ioport_write(0, addr, val);
470 #ifdef CONFIG_KQEMU
471 if (env)
472 env->last_io_time = cpu_get_time_fast();
473 #endif
476 void cpu_outw(CPUState *env, int addr, int val)
478 LOG_IOPORT("outw: %04x %04x\n", addr, val);
479 ioport_write(1, addr, val);
480 #ifdef CONFIG_KQEMU
481 if (env)
482 env->last_io_time = cpu_get_time_fast();
483 #endif
486 void cpu_outl(CPUState *env, int addr, int val)
488 LOG_IOPORT("outl: %04x %08x\n", addr, val);
489 ioport_write(2, addr, val);
490 #ifdef CONFIG_KQEMU
491 if (env)
492 env->last_io_time = cpu_get_time_fast();
493 #endif
496 int cpu_inb(CPUState *env, int addr)
498 int val;
499 val = ioport_read(0, addr);
500 LOG_IOPORT("inb : %04x %02x\n", addr, val);
501 #ifdef CONFIG_KQEMU
502 if (env)
503 env->last_io_time = cpu_get_time_fast();
504 #endif
505 return val;
508 int cpu_inw(CPUState *env, int addr)
510 int val;
511 val = ioport_read(1, addr);
512 LOG_IOPORT("inw : %04x %04x\n", addr, val);
513 #ifdef CONFIG_KQEMU
514 if (env)
515 env->last_io_time = cpu_get_time_fast();
516 #endif
517 return val;
520 int cpu_inl(CPUState *env, int addr)
522 int val;
523 val = ioport_read(2, addr);
524 LOG_IOPORT("inl : %04x %08x\n", addr, val);
525 #ifdef CONFIG_KQEMU
526 if (env)
527 env->last_io_time = cpu_get_time_fast();
528 #endif
529 return val;
532 /***********************************************************/
533 void hw_error(const char *fmt, ...)
535 va_list ap;
536 CPUState *env;
538 va_start(ap, fmt);
539 fprintf(stderr, "qemu: hardware error: ");
540 vfprintf(stderr, fmt, ap);
541 fprintf(stderr, "\n");
542 for(env = first_cpu; env != NULL; env = env->next_cpu) {
543 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
544 #ifdef TARGET_I386
545 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
546 #else
547 cpu_dump_state(env, stderr, fprintf, 0);
548 #endif
550 va_end(ap);
551 abort();
554 /***************/
555 /* ballooning */
557 static QEMUBalloonEvent *qemu_balloon_event;
558 void *qemu_balloon_event_opaque;
560 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
562 qemu_balloon_event = func;
563 qemu_balloon_event_opaque = opaque;
566 void qemu_balloon(ram_addr_t target)
568 if (qemu_balloon_event)
569 qemu_balloon_event(qemu_balloon_event_opaque, target);
572 ram_addr_t qemu_balloon_status(void)
574 if (qemu_balloon_event)
575 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
576 return 0;
579 /***********************************************************/
580 /* keyboard/mouse */
582 static QEMUPutKBDEvent *qemu_put_kbd_event;
583 static void *qemu_put_kbd_event_opaque;
584 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
585 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
587 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
589 qemu_put_kbd_event_opaque = opaque;
590 qemu_put_kbd_event = func;
593 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
594 void *opaque, int absolute,
595 const char *name)
597 QEMUPutMouseEntry *s, *cursor;
599 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
601 s->qemu_put_mouse_event = func;
602 s->qemu_put_mouse_event_opaque = opaque;
603 s->qemu_put_mouse_event_absolute = absolute;
604 s->qemu_put_mouse_event_name = qemu_strdup(name);
605 s->next = NULL;
607 if (!qemu_put_mouse_event_head) {
608 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
609 return s;
612 cursor = qemu_put_mouse_event_head;
613 while (cursor->next != NULL)
614 cursor = cursor->next;
616 cursor->next = s;
617 qemu_put_mouse_event_current = s;
619 return s;
622 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
624 QEMUPutMouseEntry *prev = NULL, *cursor;
626 if (!qemu_put_mouse_event_head || entry == NULL)
627 return;
629 cursor = qemu_put_mouse_event_head;
630 while (cursor != NULL && cursor != entry) {
631 prev = cursor;
632 cursor = cursor->next;
635 if (cursor == NULL) // does not exist or list empty
636 return;
637 else if (prev == NULL) { // entry is head
638 qemu_put_mouse_event_head = cursor->next;
639 if (qemu_put_mouse_event_current == entry)
640 qemu_put_mouse_event_current = cursor->next;
641 qemu_free(entry->qemu_put_mouse_event_name);
642 qemu_free(entry);
643 return;
646 prev->next = entry->next;
648 if (qemu_put_mouse_event_current == entry)
649 qemu_put_mouse_event_current = prev;
651 qemu_free(entry->qemu_put_mouse_event_name);
652 qemu_free(entry);
655 void kbd_put_keycode(int keycode)
657 if (qemu_put_kbd_event) {
658 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
662 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
664 QEMUPutMouseEvent *mouse_event;
665 void *mouse_event_opaque;
666 int width;
668 if (!qemu_put_mouse_event_current) {
669 return;
672 mouse_event =
673 qemu_put_mouse_event_current->qemu_put_mouse_event;
674 mouse_event_opaque =
675 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
677 if (mouse_event) {
678 if (graphic_rotate) {
679 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
680 width = 0x7fff;
681 else
682 width = graphic_width - 1;
683 mouse_event(mouse_event_opaque,
684 width - dy, dx, dz, buttons_state);
685 } else
686 mouse_event(mouse_event_opaque,
687 dx, dy, dz, buttons_state);
691 int kbd_mouse_is_absolute(void)
693 if (!qemu_put_mouse_event_current)
694 return 0;
696 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
699 void do_info_mice(Monitor *mon)
701 QEMUPutMouseEntry *cursor;
702 int index = 0;
704 if (!qemu_put_mouse_event_head) {
705 monitor_printf(mon, "No mouse devices connected\n");
706 return;
709 monitor_printf(mon, "Mouse devices available:\n");
710 cursor = qemu_put_mouse_event_head;
711 while (cursor != NULL) {
712 monitor_printf(mon, "%c Mouse #%d: %s\n",
713 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
714 index, cursor->qemu_put_mouse_event_name);
715 index++;
716 cursor = cursor->next;
720 void do_mouse_set(Monitor *mon, int index)
722 QEMUPutMouseEntry *cursor;
723 int i = 0;
725 if (!qemu_put_mouse_event_head) {
726 monitor_printf(mon, "No mouse devices connected\n");
727 return;
730 cursor = qemu_put_mouse_event_head;
731 while (cursor != NULL && index != i) {
732 i++;
733 cursor = cursor->next;
736 if (cursor != NULL)
737 qemu_put_mouse_event_current = cursor;
738 else
739 monitor_printf(mon, "Mouse at given index not found\n");
742 /* compute with 96 bit intermediate result: (a*b)/c */
743 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
745 union {
746 uint64_t ll;
747 struct {
748 #ifdef WORDS_BIGENDIAN
749 uint32_t high, low;
750 #else
751 uint32_t low, high;
752 #endif
753 } l;
754 } u, res;
755 uint64_t rl, rh;
757 u.ll = a;
758 rl = (uint64_t)u.l.low * (uint64_t)b;
759 rh = (uint64_t)u.l.high * (uint64_t)b;
760 rh += (rl >> 32);
761 res.l.high = rh / c;
762 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
763 return res.ll;
766 /***********************************************************/
767 /* real time host monotonic timer */
769 #define QEMU_TIMER_BASE 1000000000LL
771 #ifdef WIN32
773 static int64_t clock_freq;
775 static void init_get_clock(void)
777 LARGE_INTEGER freq;
778 int ret;
779 ret = QueryPerformanceFrequency(&freq);
780 if (ret == 0) {
781 fprintf(stderr, "Could not calibrate ticks\n");
782 exit(1);
784 clock_freq = freq.QuadPart;
787 static int64_t get_clock(void)
789 LARGE_INTEGER ti;
790 QueryPerformanceCounter(&ti);
791 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
794 #else
796 static int use_rt_clock;
798 static void init_get_clock(void)
800 use_rt_clock = 0;
801 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
802 || defined(__DragonFly__)
804 struct timespec ts;
805 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
806 use_rt_clock = 1;
809 #endif
812 static int64_t get_clock(void)
814 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
815 || defined(__DragonFly__)
816 if (use_rt_clock) {
817 struct timespec ts;
818 clock_gettime(CLOCK_MONOTONIC, &ts);
819 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
820 } else
821 #endif
823 /* XXX: using gettimeofday leads to problems if the date
824 changes, so it should be avoided. */
825 struct timeval tv;
826 gettimeofday(&tv, NULL);
827 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
830 #endif
832 /* Return the virtual CPU time, based on the instruction counter. */
833 static int64_t cpu_get_icount(void)
835 int64_t icount;
836 CPUState *env = cpu_single_env;;
837 icount = qemu_icount;
838 if (env) {
839 if (!can_do_io(env))
840 fprintf(stderr, "Bad clock read\n");
841 icount -= (env->icount_decr.u16.low + env->icount_extra);
843 return qemu_icount_bias + (icount << icount_time_shift);
846 /***********************************************************/
847 /* guest cycle counter */
849 static int64_t cpu_ticks_prev;
850 static int64_t cpu_ticks_offset;
851 static int64_t cpu_clock_offset;
852 static int cpu_ticks_enabled;
854 /* return the host CPU cycle counter and handle stop/restart */
855 int64_t cpu_get_ticks(void)
857 if (use_icount) {
858 return cpu_get_icount();
860 if (!cpu_ticks_enabled) {
861 return cpu_ticks_offset;
862 } else {
863 int64_t ticks;
864 ticks = cpu_get_real_ticks();
865 if (cpu_ticks_prev > ticks) {
866 /* Note: non increasing ticks may happen if the host uses
867 software suspend */
868 cpu_ticks_offset += cpu_ticks_prev - ticks;
870 cpu_ticks_prev = ticks;
871 return ticks + cpu_ticks_offset;
875 /* return the host CPU monotonic timer and handle stop/restart */
876 static int64_t cpu_get_clock(void)
878 int64_t ti;
879 if (!cpu_ticks_enabled) {
880 return cpu_clock_offset;
881 } else {
882 ti = get_clock();
883 return ti + cpu_clock_offset;
887 /* enable cpu_get_ticks() */
888 void cpu_enable_ticks(void)
890 if (!cpu_ticks_enabled) {
891 cpu_ticks_offset -= cpu_get_real_ticks();
892 cpu_clock_offset -= get_clock();
893 cpu_ticks_enabled = 1;
897 /* disable cpu_get_ticks() : the clock is stopped. You must not call
898 cpu_get_ticks() after that. */
899 void cpu_disable_ticks(void)
901 if (cpu_ticks_enabled) {
902 cpu_ticks_offset = cpu_get_ticks();
903 cpu_clock_offset = cpu_get_clock();
904 cpu_ticks_enabled = 0;
908 /***********************************************************/
909 /* timers */
911 #define QEMU_TIMER_REALTIME 0
912 #define QEMU_TIMER_VIRTUAL 1
914 struct QEMUClock {
915 int type;
916 /* XXX: add frequency */
919 struct QEMUTimer {
920 QEMUClock *clock;
921 int64_t expire_time;
922 QEMUTimerCB *cb;
923 void *opaque;
924 struct QEMUTimer *next;
927 struct qemu_alarm_timer {
928 char const *name;
929 unsigned int flags;
931 int (*start)(struct qemu_alarm_timer *t);
932 void (*stop)(struct qemu_alarm_timer *t);
933 void (*rearm)(struct qemu_alarm_timer *t);
934 void *priv;
937 #define ALARM_FLAG_DYNTICKS 0x1
938 #define ALARM_FLAG_EXPIRED 0x2
940 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
942 return t->flags & ALARM_FLAG_DYNTICKS;
945 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
947 if (!alarm_has_dynticks(t))
948 return;
950 t->rearm(t);
953 /* TODO: MIN_TIMER_REARM_US should be optimized */
954 #define MIN_TIMER_REARM_US 250
956 static struct qemu_alarm_timer *alarm_timer;
957 #ifndef _WIN32
958 static int alarm_timer_rfd, alarm_timer_wfd;
959 #endif
961 #ifdef _WIN32
963 struct qemu_alarm_win32 {
964 MMRESULT timerId;
965 HANDLE host_alarm;
966 unsigned int period;
967 } alarm_win32_data = {0, NULL, -1};
969 static int win32_start_timer(struct qemu_alarm_timer *t);
970 static void win32_stop_timer(struct qemu_alarm_timer *t);
971 static void win32_rearm_timer(struct qemu_alarm_timer *t);
973 #else
975 static int unix_start_timer(struct qemu_alarm_timer *t);
976 static void unix_stop_timer(struct qemu_alarm_timer *t);
978 #ifdef __linux__
980 static int dynticks_start_timer(struct qemu_alarm_timer *t);
981 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
982 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
984 static int hpet_start_timer(struct qemu_alarm_timer *t);
985 static void hpet_stop_timer(struct qemu_alarm_timer *t);
987 static int rtc_start_timer(struct qemu_alarm_timer *t);
988 static void rtc_stop_timer(struct qemu_alarm_timer *t);
990 #endif /* __linux__ */
992 #endif /* _WIN32 */
994 /* Correlation between real and virtual time is always going to be
995 fairly approximate, so ignore small variation.
996 When the guest is idle real and virtual time will be aligned in
997 the IO wait loop. */
998 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1000 static void icount_adjust(void)
1002 int64_t cur_time;
1003 int64_t cur_icount;
1004 int64_t delta;
1005 static int64_t last_delta;
1006 /* If the VM is not running, then do nothing. */
1007 if (!vm_running)
1008 return;
1010 cur_time = cpu_get_clock();
1011 cur_icount = qemu_get_clock(vm_clock);
1012 delta = cur_icount - cur_time;
1013 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1014 if (delta > 0
1015 && last_delta + ICOUNT_WOBBLE < delta * 2
1016 && icount_time_shift > 0) {
1017 /* The guest is getting too far ahead. Slow time down. */
1018 icount_time_shift--;
1020 if (delta < 0
1021 && last_delta - ICOUNT_WOBBLE > delta * 2
1022 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1023 /* The guest is getting too far behind. Speed time up. */
1024 icount_time_shift++;
1026 last_delta = delta;
1027 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1030 static void icount_adjust_rt(void * opaque)
1032 qemu_mod_timer(icount_rt_timer,
1033 qemu_get_clock(rt_clock) + 1000);
1034 icount_adjust();
1037 static void icount_adjust_vm(void * opaque)
1039 qemu_mod_timer(icount_vm_timer,
1040 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1041 icount_adjust();
1044 static void init_icount_adjust(void)
1046 /* Have both realtime and virtual time triggers for speed adjustment.
1047 The realtime trigger catches emulated time passing too slowly,
1048 the virtual time trigger catches emulated time passing too fast.
1049 Realtime triggers occur even when idle, so use them less frequently
1050 than VM triggers. */
1051 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1052 qemu_mod_timer(icount_rt_timer,
1053 qemu_get_clock(rt_clock) + 1000);
1054 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1055 qemu_mod_timer(icount_vm_timer,
1056 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1059 static struct qemu_alarm_timer alarm_timers[] = {
1060 #ifndef _WIN32
1061 #ifdef __linux__
1062 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1063 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1064 /* HPET - if available - is preferred */
1065 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1066 /* ...otherwise try RTC */
1067 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1068 #endif
1069 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1070 #else
1071 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1072 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1073 {"win32", 0, win32_start_timer,
1074 win32_stop_timer, NULL, &alarm_win32_data},
1075 #endif
1076 {NULL, }
1079 static void show_available_alarms(void)
1081 int i;
1083 printf("Available alarm timers, in order of precedence:\n");
1084 for (i = 0; alarm_timers[i].name; i++)
1085 printf("%s\n", alarm_timers[i].name);
1088 static void configure_alarms(char const *opt)
1090 int i;
1091 int cur = 0;
1092 int count = ARRAY_SIZE(alarm_timers) - 1;
1093 char *arg;
1094 char *name;
1095 struct qemu_alarm_timer tmp;
1097 if (!strcmp(opt, "?")) {
1098 show_available_alarms();
1099 exit(0);
1102 arg = strdup(opt);
1104 /* Reorder the array */
1105 name = strtok(arg, ",");
1106 while (name) {
1107 for (i = 0; i < count && alarm_timers[i].name; i++) {
1108 if (!strcmp(alarm_timers[i].name, name))
1109 break;
1112 if (i == count) {
1113 fprintf(stderr, "Unknown clock %s\n", name);
1114 goto next;
1117 if (i < cur)
1118 /* Ignore */
1119 goto next;
1121 /* Swap */
1122 tmp = alarm_timers[i];
1123 alarm_timers[i] = alarm_timers[cur];
1124 alarm_timers[cur] = tmp;
1126 cur++;
1127 next:
1128 name = strtok(NULL, ",");
1131 free(arg);
1133 if (cur) {
1134 /* Disable remaining timers */
1135 for (i = cur; i < count; i++)
1136 alarm_timers[i].name = NULL;
1137 } else {
1138 show_available_alarms();
1139 exit(1);
1143 QEMUClock *rt_clock;
1144 QEMUClock *vm_clock;
1146 static QEMUTimer *active_timers[2];
1148 static QEMUClock *qemu_new_clock(int type)
1150 QEMUClock *clock;
1151 clock = qemu_mallocz(sizeof(QEMUClock));
1152 clock->type = type;
1153 return clock;
1156 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1158 QEMUTimer *ts;
1160 ts = qemu_mallocz(sizeof(QEMUTimer));
1161 ts->clock = clock;
1162 ts->cb = cb;
1163 ts->opaque = opaque;
1164 return ts;
1167 void qemu_free_timer(QEMUTimer *ts)
1169 qemu_free(ts);
1172 /* stop a timer, but do not dealloc it */
1173 void qemu_del_timer(QEMUTimer *ts)
1175 QEMUTimer **pt, *t;
1177 /* NOTE: this code must be signal safe because
1178 qemu_timer_expired() can be called from a signal. */
1179 pt = &active_timers[ts->clock->type];
1180 for(;;) {
1181 t = *pt;
1182 if (!t)
1183 break;
1184 if (t == ts) {
1185 *pt = t->next;
1186 break;
1188 pt = &t->next;
1192 /* modify the current timer so that it will be fired when current_time
1193 >= expire_time. The corresponding callback will be called. */
1194 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1196 QEMUTimer **pt, *t;
1198 qemu_del_timer(ts);
1200 /* add the timer in the sorted list */
1201 /* NOTE: this code must be signal safe because
1202 qemu_timer_expired() can be called from a signal. */
1203 pt = &active_timers[ts->clock->type];
1204 for(;;) {
1205 t = *pt;
1206 if (!t)
1207 break;
1208 if (t->expire_time > expire_time)
1209 break;
1210 pt = &t->next;
1212 ts->expire_time = expire_time;
1213 ts->next = *pt;
1214 *pt = ts;
1216 /* Rearm if necessary */
1217 if (pt == &active_timers[ts->clock->type]) {
1218 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1219 qemu_rearm_alarm_timer(alarm_timer);
1221 /* Interrupt execution to force deadline recalculation. */
1222 if (use_icount && cpu_single_env) {
1223 cpu_exit(cpu_single_env);
1228 int qemu_timer_pending(QEMUTimer *ts)
1230 QEMUTimer *t;
1231 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1232 if (t == ts)
1233 return 1;
1235 return 0;
1238 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1240 if (!timer_head)
1241 return 0;
1242 return (timer_head->expire_time <= current_time);
1245 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1247 QEMUTimer *ts;
1249 for(;;) {
1250 ts = *ptimer_head;
1251 if (!ts || ts->expire_time > current_time)
1252 break;
1253 /* remove timer from the list before calling the callback */
1254 *ptimer_head = ts->next;
1255 ts->next = NULL;
1257 /* run the callback (the timer list can be modified) */
1258 ts->cb(ts->opaque);
1262 int64_t qemu_get_clock(QEMUClock *clock)
1264 switch(clock->type) {
1265 case QEMU_TIMER_REALTIME:
1266 return get_clock() / 1000000;
1267 default:
1268 case QEMU_TIMER_VIRTUAL:
1269 if (use_icount) {
1270 return cpu_get_icount();
1271 } else {
1272 return cpu_get_clock();
1277 static void init_timers(void)
1279 init_get_clock();
1280 ticks_per_sec = QEMU_TIMER_BASE;
1281 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1282 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1285 /* save a timer */
1286 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1288 uint64_t expire_time;
1290 if (qemu_timer_pending(ts)) {
1291 expire_time = ts->expire_time;
1292 } else {
1293 expire_time = -1;
1295 qemu_put_be64(f, expire_time);
1298 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1300 uint64_t expire_time;
1302 expire_time = qemu_get_be64(f);
1303 if (expire_time != -1) {
1304 qemu_mod_timer(ts, expire_time);
1305 } else {
1306 qemu_del_timer(ts);
1310 static void timer_save(QEMUFile *f, void *opaque)
1312 if (cpu_ticks_enabled) {
1313 hw_error("cannot save state if virtual timers are running");
1315 qemu_put_be64(f, cpu_ticks_offset);
1316 qemu_put_be64(f, ticks_per_sec);
1317 qemu_put_be64(f, cpu_clock_offset);
1320 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1322 if (version_id != 1 && version_id != 2)
1323 return -EINVAL;
1324 if (cpu_ticks_enabled) {
1325 return -EINVAL;
1327 cpu_ticks_offset=qemu_get_be64(f);
1328 ticks_per_sec=qemu_get_be64(f);
1329 if (version_id == 2) {
1330 cpu_clock_offset=qemu_get_be64(f);
1332 return 0;
1335 #ifdef _WIN32
1336 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1337 DWORD_PTR dwUser, DWORD_PTR dw1,
1338 DWORD_PTR dw2)
1339 #else
1340 static void host_alarm_handler(int host_signum)
1341 #endif
1343 #if 0
1344 #define DISP_FREQ 1000
1346 static int64_t delta_min = INT64_MAX;
1347 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1348 static int count;
1349 ti = qemu_get_clock(vm_clock);
1350 if (last_clock != 0) {
1351 delta = ti - last_clock;
1352 if (delta < delta_min)
1353 delta_min = delta;
1354 if (delta > delta_max)
1355 delta_max = delta;
1356 delta_cum += delta;
1357 if (++count == DISP_FREQ) {
1358 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1359 muldiv64(delta_min, 1000000, ticks_per_sec),
1360 muldiv64(delta_max, 1000000, ticks_per_sec),
1361 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1362 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1363 count = 0;
1364 delta_min = INT64_MAX;
1365 delta_max = 0;
1366 delta_cum = 0;
1369 last_clock = ti;
1371 #endif
1372 if (1 ||
1373 alarm_has_dynticks(alarm_timer) ||
1374 (!use_icount &&
1375 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1376 qemu_get_clock(vm_clock))) ||
1377 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1378 qemu_get_clock(rt_clock))) {
1379 CPUState *env = next_cpu;
1381 #ifdef _WIN32
1382 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1383 SetEvent(data->host_alarm);
1384 #else
1385 static const char byte = 0;
1386 write(alarm_timer_wfd, &byte, sizeof(byte));
1387 #endif
1388 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1390 if (env) {
1391 /* stop the currently executing cpu because a timer occured */
1392 cpu_exit(env);
1393 #ifdef CONFIG_KQEMU
1394 if (env->kqemu_enabled) {
1395 kqemu_cpu_interrupt(env);
1397 #endif
1399 event_pending = 1;
1403 static int64_t qemu_next_deadline(void)
1405 int64_t delta;
1407 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1408 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1409 qemu_get_clock(vm_clock);
1410 } else {
1411 /* To avoid problems with overflow limit this to 2^32. */
1412 delta = INT32_MAX;
1415 if (delta < 0)
1416 delta = 0;
1418 return delta;
1421 #if defined(__linux__) || defined(_WIN32)
1422 static uint64_t qemu_next_deadline_dyntick(void)
1424 int64_t delta;
1425 int64_t rtdelta;
1427 if (use_icount)
1428 delta = INT32_MAX;
1429 else
1430 delta = (qemu_next_deadline() + 999) / 1000;
1432 if (active_timers[QEMU_TIMER_REALTIME]) {
1433 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1434 qemu_get_clock(rt_clock))*1000;
1435 if (rtdelta < delta)
1436 delta = rtdelta;
1439 if (delta < MIN_TIMER_REARM_US)
1440 delta = MIN_TIMER_REARM_US;
1442 return delta;
1444 #endif
1446 #ifndef _WIN32
1448 /* Sets a specific flag */
1449 static int fcntl_setfl(int fd, int flag)
1451 int flags;
1453 flags = fcntl(fd, F_GETFL);
1454 if (flags == -1)
1455 return -errno;
1457 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1458 return -errno;
1460 return 0;
1463 #if defined(__linux__)
1465 #define RTC_FREQ 1024
1467 static void enable_sigio_timer(int fd)
1469 struct sigaction act;
1471 /* timer signal */
1472 sigfillset(&act.sa_mask);
1473 act.sa_flags = 0;
1474 act.sa_handler = host_alarm_handler;
1476 sigaction(SIGIO, &act, NULL);
1477 fcntl_setfl(fd, O_ASYNC);
1478 fcntl(fd, F_SETOWN, getpid());
1481 static int hpet_start_timer(struct qemu_alarm_timer *t)
1483 struct hpet_info info;
1484 int r, fd;
1486 fd = open("/dev/hpet", O_RDONLY);
1487 if (fd < 0)
1488 return -1;
1490 /* Set frequency */
1491 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1492 if (r < 0) {
1493 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1494 "error, but for better emulation accuracy type:\n"
1495 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1496 goto fail;
1499 /* Check capabilities */
1500 r = ioctl(fd, HPET_INFO, &info);
1501 if (r < 0)
1502 goto fail;
1504 /* Enable periodic mode */
1505 r = ioctl(fd, HPET_EPI, 0);
1506 if (info.hi_flags && (r < 0))
1507 goto fail;
1509 /* Enable interrupt */
1510 r = ioctl(fd, HPET_IE_ON, 0);
1511 if (r < 0)
1512 goto fail;
1514 enable_sigio_timer(fd);
1515 t->priv = (void *)(long)fd;
1517 return 0;
1518 fail:
1519 close(fd);
1520 return -1;
1523 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1525 int fd = (long)t->priv;
1527 close(fd);
1530 static int rtc_start_timer(struct qemu_alarm_timer *t)
1532 int rtc_fd;
1533 unsigned long current_rtc_freq = 0;
1535 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1536 if (rtc_fd < 0)
1537 return -1;
1538 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1539 if (current_rtc_freq != RTC_FREQ &&
1540 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1541 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1542 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1543 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1544 goto fail;
1546 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1547 fail:
1548 close(rtc_fd);
1549 return -1;
1552 enable_sigio_timer(rtc_fd);
1554 t->priv = (void *)(long)rtc_fd;
1556 return 0;
1559 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1561 int rtc_fd = (long)t->priv;
1563 close(rtc_fd);
1566 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1568 struct sigevent ev;
1569 timer_t host_timer;
1570 struct sigaction act;
1572 sigfillset(&act.sa_mask);
1573 act.sa_flags = 0;
1574 act.sa_handler = host_alarm_handler;
1576 sigaction(SIGALRM, &act, NULL);
1578 ev.sigev_value.sival_int = 0;
1579 ev.sigev_notify = SIGEV_SIGNAL;
1580 ev.sigev_signo = SIGALRM;
1582 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1583 perror("timer_create");
1585 /* disable dynticks */
1586 fprintf(stderr, "Dynamic Ticks disabled\n");
1588 return -1;
1591 t->priv = (void *)(long)host_timer;
1593 return 0;
1596 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1598 timer_t host_timer = (timer_t)(long)t->priv;
1600 timer_delete(host_timer);
1603 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1605 timer_t host_timer = (timer_t)(long)t->priv;
1606 struct itimerspec timeout;
1607 int64_t nearest_delta_us = INT64_MAX;
1608 int64_t current_us;
1610 if (!active_timers[QEMU_TIMER_REALTIME] &&
1611 !active_timers[QEMU_TIMER_VIRTUAL])
1612 return;
1614 nearest_delta_us = qemu_next_deadline_dyntick();
1616 /* check whether a timer is already running */
1617 if (timer_gettime(host_timer, &timeout)) {
1618 perror("gettime");
1619 fprintf(stderr, "Internal timer error: aborting\n");
1620 exit(1);
1622 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1623 if (current_us && current_us <= nearest_delta_us)
1624 return;
1626 timeout.it_interval.tv_sec = 0;
1627 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1628 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1629 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1630 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1631 perror("settime");
1632 fprintf(stderr, "Internal timer error: aborting\n");
1633 exit(1);
1637 #endif /* defined(__linux__) */
1639 static int unix_start_timer(struct qemu_alarm_timer *t)
1641 struct sigaction act;
1642 struct itimerval itv;
1643 int err;
1645 /* timer signal */
1646 sigfillset(&act.sa_mask);
1647 act.sa_flags = 0;
1648 act.sa_handler = host_alarm_handler;
1650 sigaction(SIGALRM, &act, NULL);
1652 itv.it_interval.tv_sec = 0;
1653 /* for i386 kernel 2.6 to get 1 ms */
1654 itv.it_interval.tv_usec = 999;
1655 itv.it_value.tv_sec = 0;
1656 itv.it_value.tv_usec = 10 * 1000;
1658 err = setitimer(ITIMER_REAL, &itv, NULL);
1659 if (err)
1660 return -1;
1662 return 0;
1665 static void unix_stop_timer(struct qemu_alarm_timer *t)
1667 struct itimerval itv;
1669 memset(&itv, 0, sizeof(itv));
1670 setitimer(ITIMER_REAL, &itv, NULL);
1673 #endif /* !defined(_WIN32) */
1675 static void try_to_rearm_timer(void *opaque)
1677 struct qemu_alarm_timer *t = opaque;
1678 #ifndef _WIN32
1679 ssize_t len;
1681 /* Drain the notify pipe */
1682 do {
1683 char buffer[512];
1684 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1685 } while ((len == -1 && errno == EINTR) || len > 0);
1686 #endif
1688 if (t->flags & ALARM_FLAG_EXPIRED) {
1689 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1690 qemu_rearm_alarm_timer(alarm_timer);
1694 #ifdef _WIN32
1696 static int win32_start_timer(struct qemu_alarm_timer *t)
1698 TIMECAPS tc;
1699 struct qemu_alarm_win32 *data = t->priv;
1700 UINT flags;
1702 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1703 if (!data->host_alarm) {
1704 perror("Failed CreateEvent");
1705 return -1;
1708 memset(&tc, 0, sizeof(tc));
1709 timeGetDevCaps(&tc, sizeof(tc));
1711 if (data->period < tc.wPeriodMin)
1712 data->period = tc.wPeriodMin;
1714 timeBeginPeriod(data->period);
1716 flags = TIME_CALLBACK_FUNCTION;
1717 if (alarm_has_dynticks(t))
1718 flags |= TIME_ONESHOT;
1719 else
1720 flags |= TIME_PERIODIC;
1722 data->timerId = timeSetEvent(1, // interval (ms)
1723 data->period, // resolution
1724 host_alarm_handler, // function
1725 (DWORD)t, // parameter
1726 flags);
1728 if (!data->timerId) {
1729 perror("Failed to initialize win32 alarm timer");
1731 timeEndPeriod(data->period);
1732 CloseHandle(data->host_alarm);
1733 return -1;
1736 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1738 return 0;
1741 static void win32_stop_timer(struct qemu_alarm_timer *t)
1743 struct qemu_alarm_win32 *data = t->priv;
1745 timeKillEvent(data->timerId);
1746 timeEndPeriod(data->period);
1748 CloseHandle(data->host_alarm);
1751 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1753 struct qemu_alarm_win32 *data = t->priv;
1754 uint64_t nearest_delta_us;
1756 if (!active_timers[QEMU_TIMER_REALTIME] &&
1757 !active_timers[QEMU_TIMER_VIRTUAL])
1758 return;
1760 nearest_delta_us = qemu_next_deadline_dyntick();
1761 nearest_delta_us /= 1000;
1763 timeKillEvent(data->timerId);
1765 data->timerId = timeSetEvent(1,
1766 data->period,
1767 host_alarm_handler,
1768 (DWORD)t,
1769 TIME_ONESHOT | TIME_PERIODIC);
1771 if (!data->timerId) {
1772 perror("Failed to re-arm win32 alarm timer");
1774 timeEndPeriod(data->period);
1775 CloseHandle(data->host_alarm);
1776 exit(1);
1780 #endif /* _WIN32 */
1782 static int init_timer_alarm(void)
1784 struct qemu_alarm_timer *t = NULL;
1785 int i, err = -1;
1787 #ifndef _WIN32
1788 int fds[2];
1790 err = pipe(fds);
1791 if (err == -1)
1792 return -errno;
1794 err = fcntl_setfl(fds[0], O_NONBLOCK);
1795 if (err < 0)
1796 goto fail;
1798 err = fcntl_setfl(fds[1], O_NONBLOCK);
1799 if (err < 0)
1800 goto fail;
1802 alarm_timer_rfd = fds[0];
1803 alarm_timer_wfd = fds[1];
1804 #endif
1806 for (i = 0; alarm_timers[i].name; i++) {
1807 t = &alarm_timers[i];
1809 err = t->start(t);
1810 if (!err)
1811 break;
1814 if (err) {
1815 err = -ENOENT;
1816 goto fail;
1819 #ifndef _WIN32
1820 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1821 try_to_rearm_timer, NULL, t);
1822 #endif
1824 alarm_timer = t;
1826 return 0;
1828 fail:
1829 #ifndef _WIN32
1830 close(fds[0]);
1831 close(fds[1]);
1832 #endif
1833 return err;
1836 static void quit_timers(void)
1838 alarm_timer->stop(alarm_timer);
1839 alarm_timer = NULL;
1842 /***********************************************************/
1843 /* host time/date access */
1844 void qemu_get_timedate(struct tm *tm, int offset)
1846 time_t ti;
1847 struct tm *ret;
1849 time(&ti);
1850 ti += offset;
1851 if (rtc_date_offset == -1) {
1852 if (rtc_utc)
1853 ret = gmtime(&ti);
1854 else
1855 ret = localtime(&ti);
1856 } else {
1857 ti -= rtc_date_offset;
1858 ret = gmtime(&ti);
1861 memcpy(tm, ret, sizeof(struct tm));
1864 int qemu_timedate_diff(struct tm *tm)
1866 time_t seconds;
1868 if (rtc_date_offset == -1)
1869 if (rtc_utc)
1870 seconds = mktimegm(tm);
1871 else
1872 seconds = mktime(tm);
1873 else
1874 seconds = mktimegm(tm) + rtc_date_offset;
1876 return seconds - time(NULL);
1879 #ifdef _WIN32
1880 static void socket_cleanup(void)
1882 WSACleanup();
1885 static int socket_init(void)
1887 WSADATA Data;
1888 int ret, err;
1890 ret = WSAStartup(MAKEWORD(2,2), &Data);
1891 if (ret != 0) {
1892 err = WSAGetLastError();
1893 fprintf(stderr, "WSAStartup: %d\n", err);
1894 return -1;
1896 atexit(socket_cleanup);
1897 return 0;
1899 #endif
1901 const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
1903 char *q;
1905 q = buf;
1906 while (*p != '\0' && *p != delim) {
1907 if (q && (q - buf) < buf_size - 1)
1908 *q++ = *p;
1909 p++;
1911 if (q)
1912 *q = '\0';
1914 return p;
1917 const char *get_opt_value(char *buf, int buf_size, const char *p)
1919 char *q;
1921 q = buf;
1922 while (*p != '\0') {
1923 if (*p == ',') {
1924 if (*(p + 1) != ',')
1925 break;
1926 p++;
1928 if (q && (q - buf) < buf_size - 1)
1929 *q++ = *p;
1930 p++;
1932 if (q)
1933 *q = '\0';
1935 return p;
1938 int get_param_value(char *buf, int buf_size,
1939 const char *tag, const char *str)
1941 const char *p;
1942 char option[128];
1944 p = str;
1945 for(;;) {
1946 p = get_opt_name(option, sizeof(option), p, '=');
1947 if (*p != '=')
1948 break;
1949 p++;
1950 if (!strcmp(tag, option)) {
1951 (void)get_opt_value(buf, buf_size, p);
1952 return strlen(buf);
1953 } else {
1954 p = get_opt_value(NULL, 0, p);
1956 if (*p != ',')
1957 break;
1958 p++;
1960 return 0;
1963 int check_params(char *buf, int buf_size,
1964 const char * const *params, const char *str)
1966 const char *p;
1967 int i;
1969 p = str;
1970 while (*p != '\0') {
1971 p = get_opt_name(buf, buf_size, p, '=');
1972 if (*p != '=')
1973 return -1;
1974 p++;
1975 for(i = 0; params[i] != NULL; i++)
1976 if (!strcmp(params[i], buf))
1977 break;
1978 if (params[i] == NULL)
1979 return -1;
1980 p = get_opt_value(NULL, 0, p);
1981 if (*p != ',')
1982 break;
1983 p++;
1985 return 0;
1988 /***********************************************************/
1989 /* Bluetooth support */
1990 static int nb_hcis;
1991 static int cur_hci;
1992 static struct HCIInfo *hci_table[MAX_NICS];
1994 static struct bt_vlan_s {
1995 struct bt_scatternet_s net;
1996 int id;
1997 struct bt_vlan_s *next;
1998 } *first_bt_vlan;
2000 /* find or alloc a new bluetooth "VLAN" */
2001 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
2003 struct bt_vlan_s **pvlan, *vlan;
2004 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
2005 if (vlan->id == id)
2006 return &vlan->net;
2008 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
2009 vlan->id = id;
2010 pvlan = &first_bt_vlan;
2011 while (*pvlan != NULL)
2012 pvlan = &(*pvlan)->next;
2013 *pvlan = vlan;
2014 return &vlan->net;
2017 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2021 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2023 return -ENOTSUP;
2026 static struct HCIInfo null_hci = {
2027 .cmd_send = null_hci_send,
2028 .sco_send = null_hci_send,
2029 .acl_send = null_hci_send,
2030 .bdaddr_set = null_hci_addr_set,
2033 struct HCIInfo *qemu_next_hci(void)
2035 if (cur_hci == nb_hcis)
2036 return &null_hci;
2038 return hci_table[cur_hci++];
2041 static struct HCIInfo *hci_init(const char *str)
2043 char *endp;
2044 struct bt_scatternet_s *vlan = 0;
2046 if (!strcmp(str, "null"))
2047 /* null */
2048 return &null_hci;
2049 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2050 /* host[:hciN] */
2051 return bt_host_hci(str[4] ? str + 5 : "hci0");
2052 else if (!strncmp(str, "hci", 3)) {
2053 /* hci[,vlan=n] */
2054 if (str[3]) {
2055 if (!strncmp(str + 3, ",vlan=", 6)) {
2056 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2057 if (*endp)
2058 vlan = 0;
2060 } else
2061 vlan = qemu_find_bt_vlan(0);
2062 if (vlan)
2063 return bt_new_hci(vlan);
2066 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2068 return 0;
2071 static int bt_hci_parse(const char *str)
2073 struct HCIInfo *hci;
2074 bdaddr_t bdaddr;
2076 if (nb_hcis >= MAX_NICS) {
2077 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2078 return -1;
2081 hci = hci_init(str);
2082 if (!hci)
2083 return -1;
2085 bdaddr.b[0] = 0x52;
2086 bdaddr.b[1] = 0x54;
2087 bdaddr.b[2] = 0x00;
2088 bdaddr.b[3] = 0x12;
2089 bdaddr.b[4] = 0x34;
2090 bdaddr.b[5] = 0x56 + nb_hcis;
2091 hci->bdaddr_set(hci, bdaddr.b);
2093 hci_table[nb_hcis++] = hci;
2095 return 0;
2098 static void bt_vhci_add(int vlan_id)
2100 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2102 if (!vlan->slave)
2103 fprintf(stderr, "qemu: warning: adding a VHCI to "
2104 "an empty scatternet %i\n", vlan_id);
2106 bt_vhci_init(bt_new_hci(vlan));
2109 static struct bt_device_s *bt_device_add(const char *opt)
2111 struct bt_scatternet_s *vlan;
2112 int vlan_id = 0;
2113 char *endp = strstr(opt, ",vlan=");
2114 int len = (endp ? endp - opt : strlen(opt)) + 1;
2115 char devname[10];
2117 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2119 if (endp) {
2120 vlan_id = strtol(endp + 6, &endp, 0);
2121 if (*endp) {
2122 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2123 return 0;
2127 vlan = qemu_find_bt_vlan(vlan_id);
2129 if (!vlan->slave)
2130 fprintf(stderr, "qemu: warning: adding a slave device to "
2131 "an empty scatternet %i\n", vlan_id);
2133 if (!strcmp(devname, "keyboard"))
2134 return bt_keyboard_init(vlan);
2136 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2137 return 0;
2140 static int bt_parse(const char *opt)
2142 const char *endp, *p;
2143 int vlan;
2145 if (strstart(opt, "hci", &endp)) {
2146 if (!*endp || *endp == ',') {
2147 if (*endp)
2148 if (!strstart(endp, ",vlan=", 0))
2149 opt = endp + 1;
2151 return bt_hci_parse(opt);
2153 } else if (strstart(opt, "vhci", &endp)) {
2154 if (!*endp || *endp == ',') {
2155 if (*endp) {
2156 if (strstart(endp, ",vlan=", &p)) {
2157 vlan = strtol(p, (char **) &endp, 0);
2158 if (*endp) {
2159 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2160 return 1;
2162 } else {
2163 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2164 return 1;
2166 } else
2167 vlan = 0;
2169 bt_vhci_add(vlan);
2170 return 0;
2172 } else if (strstart(opt, "device:", &endp))
2173 return !bt_device_add(endp);
2175 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2176 return 1;
2179 /***********************************************************/
2180 /* QEMU Block devices */
2182 #define HD_ALIAS "index=%d,media=disk"
2183 #define CDROM_ALIAS "index=2,media=cdrom"
2184 #define FD_ALIAS "index=%d,if=floppy"
2185 #define PFLASH_ALIAS "if=pflash"
2186 #define MTD_ALIAS "if=mtd"
2187 #define SD_ALIAS "index=0,if=sd"
2189 static int drive_opt_get_free_idx(void)
2191 int index;
2193 for (index = 0; index < MAX_DRIVES; index++)
2194 if (!drives_opt[index].used) {
2195 drives_opt[index].used = 1;
2196 return index;
2199 return -1;
2202 static int drive_get_free_idx(void)
2204 int index;
2206 for (index = 0; index < MAX_DRIVES; index++)
2207 if (!drives_table[index].used) {
2208 drives_table[index].used = 1;
2209 return index;
2212 return -1;
2215 int drive_add(const char *file, const char *fmt, ...)
2217 va_list ap;
2218 int index = drive_opt_get_free_idx();
2220 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2221 fprintf(stderr, "qemu: too many drives\n");
2222 return -1;
2225 drives_opt[index].file = file;
2226 va_start(ap, fmt);
2227 vsnprintf(drives_opt[index].opt,
2228 sizeof(drives_opt[0].opt), fmt, ap);
2229 va_end(ap);
2231 nb_drives_opt++;
2232 return index;
2235 void drive_remove(int index)
2237 drives_opt[index].used = 0;
2238 nb_drives_opt--;
2241 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2243 int index;
2245 /* seek interface, bus and unit */
2247 for (index = 0; index < MAX_DRIVES; index++)
2248 if (drives_table[index].type == type &&
2249 drives_table[index].bus == bus &&
2250 drives_table[index].unit == unit &&
2251 drives_table[index].used)
2252 return index;
2254 return -1;
2257 int drive_get_max_bus(BlockInterfaceType type)
2259 int max_bus;
2260 int index;
2262 max_bus = -1;
2263 for (index = 0; index < nb_drives; index++) {
2264 if(drives_table[index].type == type &&
2265 drives_table[index].bus > max_bus)
2266 max_bus = drives_table[index].bus;
2268 return max_bus;
2271 const char *drive_get_serial(BlockDriverState *bdrv)
2273 int index;
2275 for (index = 0; index < nb_drives; index++)
2276 if (drives_table[index].bdrv == bdrv)
2277 return drives_table[index].serial;
2279 return "\0";
2282 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2284 int index;
2286 for (index = 0; index < nb_drives; index++)
2287 if (drives_table[index].bdrv == bdrv)
2288 return drives_table[index].onerror;
2290 return BLOCK_ERR_STOP_ENOSPC;
2293 static void bdrv_format_print(void *opaque, const char *name)
2295 fprintf(stderr, " %s", name);
2298 void drive_uninit(BlockDriverState *bdrv)
2300 int i;
2302 for (i = 0; i < MAX_DRIVES; i++)
2303 if (drives_table[i].bdrv == bdrv) {
2304 drives_table[i].bdrv = NULL;
2305 drives_table[i].used = 0;
2306 drive_remove(drives_table[i].drive_opt_idx);
2307 nb_drives--;
2308 break;
2312 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2314 char buf[128];
2315 char file[1024];
2316 char devname[128];
2317 char serial[21];
2318 const char *mediastr = "";
2319 BlockInterfaceType type;
2320 enum { MEDIA_DISK, MEDIA_CDROM } media;
2321 int bus_id, unit_id;
2322 int cyls, heads, secs, translation;
2323 BlockDriverState *bdrv;
2324 BlockDriver *drv = NULL;
2325 QEMUMachine *machine = opaque;
2326 int max_devs;
2327 int index;
2328 int cache;
2329 int bdrv_flags, onerror;
2330 int drives_table_idx;
2331 char *str = arg->opt;
2332 static const char * const params[] = { "bus", "unit", "if", "index",
2333 "cyls", "heads", "secs", "trans",
2334 "media", "snapshot", "file",
2335 "cache", "format", "serial", "werror",
2336 "boot", NULL };
2338 if (check_params(buf, sizeof(buf), params, str) < 0) {
2339 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2340 buf, str);
2341 return -1;
2344 file[0] = 0;
2345 cyls = heads = secs = 0;
2346 bus_id = 0;
2347 unit_id = -1;
2348 translation = BIOS_ATA_TRANSLATION_AUTO;
2349 index = -1;
2350 cache = 3;
2352 if (machine->use_scsi) {
2353 type = IF_SCSI;
2354 max_devs = MAX_SCSI_DEVS;
2355 pstrcpy(devname, sizeof(devname), "scsi");
2356 } else {
2357 type = IF_IDE;
2358 max_devs = MAX_IDE_DEVS;
2359 pstrcpy(devname, sizeof(devname), "ide");
2361 media = MEDIA_DISK;
2363 /* extract parameters */
2365 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2366 bus_id = strtol(buf, NULL, 0);
2367 if (bus_id < 0) {
2368 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2369 return -1;
2373 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2374 unit_id = strtol(buf, NULL, 0);
2375 if (unit_id < 0) {
2376 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2377 return -1;
2381 if (get_param_value(buf, sizeof(buf), "if", str)) {
2382 pstrcpy(devname, sizeof(devname), buf);
2383 if (!strcmp(buf, "ide")) {
2384 type = IF_IDE;
2385 max_devs = MAX_IDE_DEVS;
2386 } else if (!strcmp(buf, "scsi")) {
2387 type = IF_SCSI;
2388 max_devs = MAX_SCSI_DEVS;
2389 } else if (!strcmp(buf, "floppy")) {
2390 type = IF_FLOPPY;
2391 max_devs = 0;
2392 } else if (!strcmp(buf, "pflash")) {
2393 type = IF_PFLASH;
2394 max_devs = 0;
2395 } else if (!strcmp(buf, "mtd")) {
2396 type = IF_MTD;
2397 max_devs = 0;
2398 } else if (!strcmp(buf, "sd")) {
2399 type = IF_SD;
2400 max_devs = 0;
2401 } else if (!strcmp(buf, "virtio")) {
2402 type = IF_VIRTIO;
2403 max_devs = 0;
2404 } else if (!strcmp(buf, "xen")) {
2405 type = IF_XEN;
2406 max_devs = 0;
2407 } else {
2408 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2409 return -1;
2413 if (get_param_value(buf, sizeof(buf), "index", str)) {
2414 index = strtol(buf, NULL, 0);
2415 if (index < 0) {
2416 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2417 return -1;
2421 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2422 cyls = strtol(buf, NULL, 0);
2425 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2426 heads = strtol(buf, NULL, 0);
2429 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2430 secs = strtol(buf, NULL, 0);
2433 if (cyls || heads || secs) {
2434 if (cyls < 1 || cyls > 16383) {
2435 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2436 return -1;
2438 if (heads < 1 || heads > 16) {
2439 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2440 return -1;
2442 if (secs < 1 || secs > 63) {
2443 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2444 return -1;
2448 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2449 if (!cyls) {
2450 fprintf(stderr,
2451 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2452 str);
2453 return -1;
2455 if (!strcmp(buf, "none"))
2456 translation = BIOS_ATA_TRANSLATION_NONE;
2457 else if (!strcmp(buf, "lba"))
2458 translation = BIOS_ATA_TRANSLATION_LBA;
2459 else if (!strcmp(buf, "auto"))
2460 translation = BIOS_ATA_TRANSLATION_AUTO;
2461 else {
2462 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2463 return -1;
2467 if (get_param_value(buf, sizeof(buf), "media", str)) {
2468 if (!strcmp(buf, "disk")) {
2469 media = MEDIA_DISK;
2470 } else if (!strcmp(buf, "cdrom")) {
2471 if (cyls || secs || heads) {
2472 fprintf(stderr,
2473 "qemu: '%s' invalid physical CHS format\n", str);
2474 return -1;
2476 media = MEDIA_CDROM;
2477 } else {
2478 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2479 return -1;
2483 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2484 if (!strcmp(buf, "on"))
2485 snapshot = 1;
2486 else if (!strcmp(buf, "off"))
2487 snapshot = 0;
2488 else {
2489 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2490 return -1;
2494 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2495 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2496 cache = 0;
2497 else if (!strcmp(buf, "writethrough"))
2498 cache = 1;
2499 else if (!strcmp(buf, "writeback"))
2500 cache = 2;
2501 else {
2502 fprintf(stderr, "qemu: invalid cache option\n");
2503 return -1;
2507 if (get_param_value(buf, sizeof(buf), "format", str)) {
2508 if (strcmp(buf, "?") == 0) {
2509 fprintf(stderr, "qemu: Supported formats:");
2510 bdrv_iterate_format(bdrv_format_print, NULL);
2511 fprintf(stderr, "\n");
2512 return -1;
2514 drv = bdrv_find_format(buf);
2515 if (!drv) {
2516 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2517 return -1;
2521 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2522 if (!strcmp(buf, "on")) {
2523 if (extboot_drive != -1) {
2524 fprintf(stderr, "qemu: two bootable drives specified\n");
2525 return -1;
2527 extboot_drive = nb_drives;
2528 } else if (strcmp(buf, "off")) {
2529 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2530 return -1;
2534 if (arg->file == NULL)
2535 get_param_value(file, sizeof(file), "file", str);
2536 else
2537 pstrcpy(file, sizeof(file), arg->file);
2539 if (!get_param_value(serial, sizeof(serial), "serial", str))
2540 memset(serial, 0, sizeof(serial));
2542 onerror = BLOCK_ERR_STOP_ENOSPC;
2543 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2544 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2545 fprintf(stderr, "werror is no supported by this format\n");
2546 return -1;
2548 if (!strcmp(buf, "ignore"))
2549 onerror = BLOCK_ERR_IGNORE;
2550 else if (!strcmp(buf, "enospc"))
2551 onerror = BLOCK_ERR_STOP_ENOSPC;
2552 else if (!strcmp(buf, "stop"))
2553 onerror = BLOCK_ERR_STOP_ANY;
2554 else if (!strcmp(buf, "report"))
2555 onerror = BLOCK_ERR_REPORT;
2556 else {
2557 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2558 return -1;
2562 /* compute bus and unit according index */
2564 if (index != -1) {
2565 if (bus_id != 0 || unit_id != -1) {
2566 fprintf(stderr,
2567 "qemu: '%s' index cannot be used with bus and unit\n", str);
2568 return -1;
2570 if (max_devs == 0)
2572 unit_id = index;
2573 bus_id = 0;
2574 } else {
2575 unit_id = index % max_devs;
2576 bus_id = index / max_devs;
2580 /* if user doesn't specify a unit_id,
2581 * try to find the first free
2584 if (unit_id == -1) {
2585 unit_id = 0;
2586 while (drive_get_index(type, bus_id, unit_id) != -1) {
2587 unit_id++;
2588 if (max_devs && unit_id >= max_devs) {
2589 unit_id -= max_devs;
2590 bus_id++;
2595 /* check unit id */
2597 if (max_devs && unit_id >= max_devs) {
2598 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2599 str, unit_id, max_devs - 1);
2600 return -1;
2604 * ignore multiple definitions
2607 if (drive_get_index(type, bus_id, unit_id) != -1)
2608 return -2;
2610 /* init */
2612 if (type == IF_IDE || type == IF_SCSI)
2613 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2614 if (max_devs)
2615 snprintf(buf, sizeof(buf), "%s%i%s%i",
2616 devname, bus_id, mediastr, unit_id);
2617 else
2618 snprintf(buf, sizeof(buf), "%s%s%i",
2619 devname, mediastr, unit_id);
2620 bdrv = bdrv_new(buf);
2621 drives_table_idx = drive_get_free_idx();
2622 drives_table[drives_table_idx].bdrv = bdrv;
2623 drives_table[drives_table_idx].type = type;
2624 drives_table[drives_table_idx].bus = bus_id;
2625 drives_table[drives_table_idx].unit = unit_id;
2626 drives_table[drives_table_idx].onerror = onerror;
2627 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2628 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2629 nb_drives++;
2631 switch(type) {
2632 case IF_IDE:
2633 case IF_SCSI:
2634 case IF_XEN:
2635 switch(media) {
2636 case MEDIA_DISK:
2637 if (cyls != 0) {
2638 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2639 bdrv_set_translation_hint(bdrv, translation);
2641 break;
2642 case MEDIA_CDROM:
2643 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2644 break;
2646 break;
2647 case IF_SD:
2648 /* FIXME: This isn't really a floppy, but it's a reasonable
2649 approximation. */
2650 case IF_FLOPPY:
2651 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2652 break;
2653 case IF_PFLASH:
2654 case IF_MTD:
2655 case IF_VIRTIO:
2656 break;
2658 if (!file[0])
2659 return -2;
2660 bdrv_flags = 0;
2661 if (snapshot) {
2662 bdrv_flags |= BDRV_O_SNAPSHOT;
2663 cache = 2; /* always use write-back with snapshot */
2665 if (cache == 0) /* no caching */
2666 bdrv_flags |= BDRV_O_NOCACHE;
2667 else if (cache == 2) /* write-back */
2668 bdrv_flags |= BDRV_O_CACHE_WB;
2669 else if (cache == 3) /* not specified */
2670 bdrv_flags |= BDRV_O_CACHE_DEF;
2671 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2672 fprintf(stderr, "qemu: could not open disk image %s\n",
2673 file);
2674 return -1;
2676 if (bdrv_key_required(bdrv))
2677 autostart = 0;
2678 return drives_table_idx;
2681 static void numa_add(const char *optarg)
2683 char option[128];
2684 char *endptr;
2685 unsigned long long value, endvalue;
2686 int nodenr;
2688 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2689 if (!strcmp(option, "node")) {
2690 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2691 nodenr = nb_numa_nodes;
2692 } else {
2693 nodenr = strtoull(option, NULL, 10);
2696 if (get_param_value(option, 128, "mem", optarg) == 0) {
2697 node_mem[nodenr] = 0;
2698 } else {
2699 value = strtoull(option, &endptr, 0);
2700 switch (*endptr) {
2701 case 0: case 'M': case 'm':
2702 value <<= 20;
2703 break;
2704 case 'G': case 'g':
2705 value <<= 30;
2706 break;
2708 node_mem[nodenr] = value;
2710 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2711 node_cpumask[nodenr] = 0;
2712 } else {
2713 value = strtoull(option, &endptr, 10);
2714 if (value >= 64) {
2715 value = 63;
2716 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2717 } else {
2718 if (*endptr == '-') {
2719 endvalue = strtoull(endptr+1, &endptr, 10);
2720 if (endvalue >= 63) {
2721 endvalue = 62;
2722 fprintf(stderr,
2723 "only 63 CPUs in NUMA mode supported.\n");
2725 value = (1 << (endvalue + 1)) - (1 << value);
2726 } else {
2727 value = 1 << value;
2730 node_cpumask[nodenr] = value;
2732 nb_numa_nodes++;
2734 return;
2737 /***********************************************************/
2738 /* USB devices */
2740 static USBPort *used_usb_ports;
2741 static USBPort *free_usb_ports;
2743 /* ??? Maybe change this to register a hub to keep track of the topology. */
2744 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2745 usb_attachfn attach)
2747 port->opaque = opaque;
2748 port->index = index;
2749 port->attach = attach;
2750 port->next = free_usb_ports;
2751 free_usb_ports = port;
2754 int usb_device_add_dev(USBDevice *dev)
2756 USBPort *port;
2758 /* Find a USB port to add the device to. */
2759 port = free_usb_ports;
2760 if (!port->next) {
2761 USBDevice *hub;
2763 /* Create a new hub and chain it on. */
2764 free_usb_ports = NULL;
2765 port->next = used_usb_ports;
2766 used_usb_ports = port;
2768 hub = usb_hub_init(VM_USB_HUB_SIZE);
2769 usb_attach(port, hub);
2770 port = free_usb_ports;
2773 free_usb_ports = port->next;
2774 port->next = used_usb_ports;
2775 used_usb_ports = port;
2776 usb_attach(port, dev);
2777 return 0;
2780 static void usb_msd_password_cb(void *opaque, int err)
2782 USBDevice *dev = opaque;
2784 if (!err)
2785 usb_device_add_dev(dev);
2786 else
2787 dev->handle_destroy(dev);
2790 static int usb_device_add(const char *devname, int is_hotplug)
2792 const char *p;
2793 USBDevice *dev;
2795 if (!free_usb_ports)
2796 return -1;
2798 if (strstart(devname, "host:", &p)) {
2799 dev = usb_host_device_open(p);
2800 } else if (!strcmp(devname, "mouse")) {
2801 dev = usb_mouse_init();
2802 } else if (!strcmp(devname, "tablet")) {
2803 dev = usb_tablet_init();
2804 } else if (!strcmp(devname, "keyboard")) {
2805 dev = usb_keyboard_init();
2806 } else if (strstart(devname, "disk:", &p)) {
2807 BlockDriverState *bs;
2809 dev = usb_msd_init(p);
2810 if (!dev)
2811 return -1;
2812 bs = usb_msd_get_bdrv(dev);
2813 if (bdrv_key_required(bs)) {
2814 autostart = 0;
2815 if (is_hotplug) {
2816 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2817 dev);
2818 return 0;
2821 } else if (!strcmp(devname, "wacom-tablet")) {
2822 dev = usb_wacom_init();
2823 } else if (strstart(devname, "serial:", &p)) {
2824 dev = usb_serial_init(p);
2825 #ifdef CONFIG_BRLAPI
2826 } else if (!strcmp(devname, "braille")) {
2827 dev = usb_baum_init();
2828 #endif
2829 } else if (strstart(devname, "net:", &p)) {
2830 int nic = nb_nics;
2832 if (net_client_init("nic", p) < 0)
2833 return -1;
2834 nd_table[nic].model = "usb";
2835 dev = usb_net_init(&nd_table[nic]);
2836 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2837 dev = usb_bt_init(devname[2] ? hci_init(p) :
2838 bt_new_hci(qemu_find_bt_vlan(0)));
2839 } else {
2840 return -1;
2842 if (!dev)
2843 return -1;
2845 return usb_device_add_dev(dev);
2848 int usb_device_del_addr(int bus_num, int addr)
2850 USBPort *port;
2851 USBPort **lastp;
2852 USBDevice *dev;
2854 if (!used_usb_ports)
2855 return -1;
2857 if (bus_num != 0)
2858 return -1;
2860 lastp = &used_usb_ports;
2861 port = used_usb_ports;
2862 while (port && port->dev->addr != addr) {
2863 lastp = &port->next;
2864 port = port->next;
2867 if (!port)
2868 return -1;
2870 dev = port->dev;
2871 *lastp = port->next;
2872 usb_attach(port, NULL);
2873 dev->handle_destroy(dev);
2874 port->next = free_usb_ports;
2875 free_usb_ports = port;
2876 return 0;
2879 static int usb_device_del(const char *devname)
2881 int bus_num, addr;
2882 const char *p;
2884 if (strstart(devname, "host:", &p))
2885 return usb_host_device_close(p);
2887 if (!used_usb_ports)
2888 return -1;
2890 p = strchr(devname, '.');
2891 if (!p)
2892 return -1;
2893 bus_num = strtoul(devname, NULL, 0);
2894 addr = strtoul(p + 1, NULL, 0);
2896 return usb_device_del_addr(bus_num, addr);
2899 void do_usb_add(Monitor *mon, const char *devname)
2901 usb_device_add(devname, 1);
2904 void do_usb_del(Monitor *mon, const char *devname)
2906 usb_device_del(devname);
2909 void usb_info(Monitor *mon)
2911 USBDevice *dev;
2912 USBPort *port;
2913 const char *speed_str;
2915 if (!usb_enabled) {
2916 monitor_printf(mon, "USB support not enabled\n");
2917 return;
2920 for (port = used_usb_ports; port; port = port->next) {
2921 dev = port->dev;
2922 if (!dev)
2923 continue;
2924 switch(dev->speed) {
2925 case USB_SPEED_LOW:
2926 speed_str = "1.5";
2927 break;
2928 case USB_SPEED_FULL:
2929 speed_str = "12";
2930 break;
2931 case USB_SPEED_HIGH:
2932 speed_str = "480";
2933 break;
2934 default:
2935 speed_str = "?";
2936 break;
2938 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2939 0, dev->addr, speed_str, dev->devname);
2943 /***********************************************************/
2944 /* PCMCIA/Cardbus */
2946 static struct pcmcia_socket_entry_s {
2947 struct pcmcia_socket_s *socket;
2948 struct pcmcia_socket_entry_s *next;
2949 } *pcmcia_sockets = 0;
2951 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2953 struct pcmcia_socket_entry_s *entry;
2955 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2956 entry->socket = socket;
2957 entry->next = pcmcia_sockets;
2958 pcmcia_sockets = entry;
2961 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2963 struct pcmcia_socket_entry_s *entry, **ptr;
2965 ptr = &pcmcia_sockets;
2966 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2967 if (entry->socket == socket) {
2968 *ptr = entry->next;
2969 qemu_free(entry);
2973 void pcmcia_info(Monitor *mon)
2975 struct pcmcia_socket_entry_s *iter;
2977 if (!pcmcia_sockets)
2978 monitor_printf(mon, "No PCMCIA sockets\n");
2980 for (iter = pcmcia_sockets; iter; iter = iter->next)
2981 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2982 iter->socket->attached ? iter->socket->card_string :
2983 "Empty");
2986 /***********************************************************/
2987 /* register display */
2989 struct DisplayAllocator default_allocator = {
2990 defaultallocator_create_displaysurface,
2991 defaultallocator_resize_displaysurface,
2992 defaultallocator_free_displaysurface
2995 void register_displaystate(DisplayState *ds)
2997 DisplayState **s;
2998 s = &display_state;
2999 while (*s != NULL)
3000 s = &(*s)->next;
3001 ds->next = NULL;
3002 *s = ds;
3005 DisplayState *get_displaystate(void)
3007 return display_state;
3010 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
3012 if(ds->allocator == &default_allocator) ds->allocator = da;
3013 return ds->allocator;
3016 /* dumb display */
3018 static void dumb_display_init(void)
3020 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
3021 ds->allocator = &default_allocator;
3022 ds->surface = qemu_create_displaysurface(ds, 640, 480);
3023 register_displaystate(ds);
3026 /***********************************************************/
3027 /* I/O handling */
3029 typedef struct IOHandlerRecord {
3030 int fd;
3031 IOCanRWHandler *fd_read_poll;
3032 IOHandler *fd_read;
3033 IOHandler *fd_write;
3034 int deleted;
3035 void *opaque;
3036 /* temporary data */
3037 struct pollfd *ufd;
3038 struct IOHandlerRecord *next;
3039 } IOHandlerRecord;
3041 static IOHandlerRecord *first_io_handler;
3043 /* XXX: fd_read_poll should be suppressed, but an API change is
3044 necessary in the character devices to suppress fd_can_read(). */
3045 int qemu_set_fd_handler2(int fd,
3046 IOCanRWHandler *fd_read_poll,
3047 IOHandler *fd_read,
3048 IOHandler *fd_write,
3049 void *opaque)
3051 IOHandlerRecord **pioh, *ioh;
3053 if (!fd_read && !fd_write) {
3054 pioh = &first_io_handler;
3055 for(;;) {
3056 ioh = *pioh;
3057 if (ioh == NULL)
3058 break;
3059 if (ioh->fd == fd) {
3060 ioh->deleted = 1;
3061 break;
3063 pioh = &ioh->next;
3065 } else {
3066 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3067 if (ioh->fd == fd)
3068 goto found;
3070 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3071 ioh->next = first_io_handler;
3072 first_io_handler = ioh;
3073 found:
3074 ioh->fd = fd;
3075 ioh->fd_read_poll = fd_read_poll;
3076 ioh->fd_read = fd_read;
3077 ioh->fd_write = fd_write;
3078 ioh->opaque = opaque;
3079 ioh->deleted = 0;
3081 main_loop_break();
3082 return 0;
3085 int qemu_set_fd_handler(int fd,
3086 IOHandler *fd_read,
3087 IOHandler *fd_write,
3088 void *opaque)
3090 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3093 #ifdef _WIN32
3094 /***********************************************************/
3095 /* Polling handling */
3097 typedef struct PollingEntry {
3098 PollingFunc *func;
3099 void *opaque;
3100 struct PollingEntry *next;
3101 } PollingEntry;
3103 static PollingEntry *first_polling_entry;
3105 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3107 PollingEntry **ppe, *pe;
3108 pe = qemu_mallocz(sizeof(PollingEntry));
3109 pe->func = func;
3110 pe->opaque = opaque;
3111 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3112 *ppe = pe;
3113 return 0;
3116 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3118 PollingEntry **ppe, *pe;
3119 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3120 pe = *ppe;
3121 if (pe->func == func && pe->opaque == opaque) {
3122 *ppe = pe->next;
3123 qemu_free(pe);
3124 break;
3129 /***********************************************************/
3130 /* Wait objects support */
3131 typedef struct WaitObjects {
3132 int num;
3133 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3134 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3135 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3136 } WaitObjects;
3138 static WaitObjects wait_objects = {0};
3140 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3142 WaitObjects *w = &wait_objects;
3144 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3145 return -1;
3146 w->events[w->num] = handle;
3147 w->func[w->num] = func;
3148 w->opaque[w->num] = opaque;
3149 w->num++;
3150 return 0;
3153 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3155 int i, found;
3156 WaitObjects *w = &wait_objects;
3158 found = 0;
3159 for (i = 0; i < w->num; i++) {
3160 if (w->events[i] == handle)
3161 found = 1;
3162 if (found) {
3163 w->events[i] = w->events[i + 1];
3164 w->func[i] = w->func[i + 1];
3165 w->opaque[i] = w->opaque[i + 1];
3168 if (found)
3169 w->num--;
3171 #endif
3173 /***********************************************************/
3174 /* ram save/restore */
3176 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3178 int v;
3180 v = qemu_get_byte(f);
3181 switch(v) {
3182 case 0:
3183 if (qemu_get_buffer(f, buf, len) != len)
3184 return -EIO;
3185 break;
3186 case 1:
3187 v = qemu_get_byte(f);
3188 memset(buf, v, len);
3189 break;
3190 default:
3191 return -EINVAL;
3194 if (qemu_file_has_error(f))
3195 return -EIO;
3197 return 0;
3200 static int ram_load_v1(QEMUFile *f, void *opaque)
3202 int ret;
3203 ram_addr_t i;
3205 if (qemu_get_be32(f) != last_ram_offset)
3206 return -EINVAL;
3207 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3208 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3209 continue;
3210 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3211 if (ret)
3212 return ret;
3214 return 0;
3217 #define BDRV_HASH_BLOCK_SIZE 1024
3218 #define IOBUF_SIZE 4096
3219 #define RAM_CBLOCK_MAGIC 0xfabe
3221 typedef struct RamDecompressState {
3222 z_stream zstream;
3223 QEMUFile *f;
3224 uint8_t buf[IOBUF_SIZE];
3225 } RamDecompressState;
3227 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3229 int ret;
3230 memset(s, 0, sizeof(*s));
3231 s->f = f;
3232 ret = inflateInit(&s->zstream);
3233 if (ret != Z_OK)
3234 return -1;
3235 return 0;
3238 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3240 int ret, clen;
3242 s->zstream.avail_out = len;
3243 s->zstream.next_out = buf;
3244 while (s->zstream.avail_out > 0) {
3245 if (s->zstream.avail_in == 0) {
3246 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3247 return -1;
3248 clen = qemu_get_be16(s->f);
3249 if (clen > IOBUF_SIZE)
3250 return -1;
3251 qemu_get_buffer(s->f, s->buf, clen);
3252 s->zstream.avail_in = clen;
3253 s->zstream.next_in = s->buf;
3255 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3256 if (ret != Z_OK && ret != Z_STREAM_END) {
3257 return -1;
3260 return 0;
3263 static void ram_decompress_close(RamDecompressState *s)
3265 inflateEnd(&s->zstream);
3268 #define RAM_SAVE_FLAG_FULL 0x01
3269 #define RAM_SAVE_FLAG_COMPRESS 0x02
3270 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3271 #define RAM_SAVE_FLAG_PAGE 0x08
3272 #define RAM_SAVE_FLAG_EOS 0x10
3274 static int is_dup_page(uint8_t *page, uint8_t ch)
3276 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3277 uint32_t *array = (uint32_t *)page;
3278 int i;
3280 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3281 if (array[i] != val)
3282 return 0;
3285 return 1;
3288 static int ram_save_block(QEMUFile *f)
3290 static ram_addr_t current_addr = 0;
3291 ram_addr_t saved_addr = current_addr;
3292 ram_addr_t addr = 0;
3293 int found = 0;
3295 while (addr < last_ram_offset) {
3296 if (kvm_enabled() && current_addr == 0) {
3297 int r;
3298 r = kvm_update_dirty_pages_log();
3299 if (r) {
3300 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3301 qemu_file_set_error(f);
3302 return 0;
3305 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3306 uint8_t *p;
3308 cpu_physical_memory_reset_dirty(current_addr,
3309 current_addr + TARGET_PAGE_SIZE,
3310 MIGRATION_DIRTY_FLAG);
3312 p = qemu_get_ram_ptr(current_addr);
3314 if (is_dup_page(p, *p)) {
3315 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3316 qemu_put_byte(f, *p);
3317 } else {
3318 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3319 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3322 found = 1;
3323 break;
3325 addr += TARGET_PAGE_SIZE;
3326 current_addr = (saved_addr + addr) % last_ram_offset;
3329 return found;
3332 static ram_addr_t ram_save_threshold = 10;
3334 static ram_addr_t ram_save_remaining(void)
3336 ram_addr_t addr;
3337 ram_addr_t count = 0;
3339 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3340 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3341 count++;
3344 return count;
3347 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3349 ram_addr_t addr;
3351 if (stage == 1) {
3352 /* Make sure all dirty bits are set */
3353 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3354 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3355 cpu_physical_memory_set_dirty(addr);
3358 /* Enable dirty memory tracking */
3359 cpu_physical_memory_set_dirty_tracking(1);
3361 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3364 while (!qemu_file_rate_limit(f)) {
3365 int ret;
3367 ret = ram_save_block(f);
3368 if (ret == 0) /* no more blocks */
3369 break;
3372 /* try transferring iterative blocks of memory */
3374 if (stage == 3) {
3376 /* flush all remaining blocks regardless of rate limiting */
3377 while (ram_save_block(f) != 0);
3378 cpu_physical_memory_set_dirty_tracking(0);
3381 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3383 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3386 static int ram_load_dead(QEMUFile *f, void *opaque)
3388 RamDecompressState s1, *s = &s1;
3389 uint8_t buf[10];
3390 ram_addr_t i;
3392 if (ram_decompress_open(s, f) < 0)
3393 return -EINVAL;
3394 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3395 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3396 continue;
3397 if (ram_decompress_buf(s, buf, 1) < 0) {
3398 fprintf(stderr, "Error while reading ram block header\n");
3399 goto error;
3401 if (buf[0] == 0) {
3402 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3403 BDRV_HASH_BLOCK_SIZE) < 0) {
3404 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3405 goto error;
3407 } else {
3408 error:
3409 printf("Error block header\n");
3410 return -EINVAL;
3413 ram_decompress_close(s);
3415 return 0;
3418 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3420 ram_addr_t addr;
3421 int flags;
3423 if (version_id == 1)
3424 return ram_load_v1(f, opaque);
3426 if (version_id == 2) {
3427 if (qemu_get_be32(f) != last_ram_offset)
3428 return -EINVAL;
3429 return ram_load_dead(f, opaque);
3432 if (version_id != 3)
3433 return -EINVAL;
3435 do {
3436 addr = qemu_get_be64(f);
3438 flags = addr & ~TARGET_PAGE_MASK;
3439 addr &= TARGET_PAGE_MASK;
3441 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3442 if (addr != last_ram_offset)
3443 return -EINVAL;
3446 if (flags & RAM_SAVE_FLAG_FULL) {
3447 if (ram_load_dead(f, opaque) < 0)
3448 return -EINVAL;
3451 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3452 uint8_t ch = qemu_get_byte(f);
3453 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3454 } else if (flags & RAM_SAVE_FLAG_PAGE)
3455 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3456 } while (!(flags & RAM_SAVE_FLAG_EOS));
3458 return 0;
3461 void qemu_service_io(void)
3463 CPUState *env = cpu_single_env;
3464 if (env) {
3465 cpu_exit(env);
3466 #ifdef CONFIG_KQEMU
3467 if (env->kqemu_enabled) {
3468 kqemu_cpu_interrupt(env);
3470 #endif
3474 /***********************************************************/
3475 /* bottom halves (can be seen as timers which expire ASAP) */
3477 struct QEMUBH {
3478 QEMUBHFunc *cb;
3479 void *opaque;
3480 int scheduled;
3481 int idle;
3482 int deleted;
3483 QEMUBH *next;
3486 static QEMUBH *first_bh = NULL;
3488 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3490 QEMUBH *bh;
3491 bh = qemu_mallocz(sizeof(QEMUBH));
3492 bh->cb = cb;
3493 bh->opaque = opaque;
3494 bh->next = first_bh;
3495 first_bh = bh;
3496 return bh;
3499 int qemu_bh_poll(void)
3501 QEMUBH *bh, **bhp;
3502 int ret;
3504 ret = 0;
3505 for (bh = first_bh; bh; bh = bh->next) {
3506 if (!bh->deleted && bh->scheduled) {
3507 bh->scheduled = 0;
3508 if (!bh->idle)
3509 ret = 1;
3510 bh->idle = 0;
3511 bh->cb(bh->opaque);
3515 /* remove deleted bhs */
3516 bhp = &first_bh;
3517 while (*bhp) {
3518 bh = *bhp;
3519 if (bh->deleted) {
3520 *bhp = bh->next;
3521 qemu_free(bh);
3522 } else
3523 bhp = &bh->next;
3526 return ret;
3529 void qemu_bh_schedule_idle(QEMUBH *bh)
3531 if (bh->scheduled)
3532 return;
3533 bh->scheduled = 1;
3534 bh->idle = 1;
3537 void qemu_bh_schedule(QEMUBH *bh)
3539 CPUState *env = cpu_single_env;
3540 if (bh->scheduled)
3541 return;
3542 bh->scheduled = 1;
3543 bh->idle = 0;
3544 /* stop the currently executing CPU to execute the BH ASAP */
3545 if (env) {
3546 cpu_exit(env);
3548 main_loop_break();
3551 void qemu_bh_cancel(QEMUBH *bh)
3553 bh->scheduled = 0;
3556 void qemu_bh_delete(QEMUBH *bh)
3558 bh->scheduled = 0;
3559 bh->deleted = 1;
3562 static void qemu_bh_update_timeout(int *timeout)
3564 QEMUBH *bh;
3566 for (bh = first_bh; bh; bh = bh->next) {
3567 if (!bh->deleted && bh->scheduled) {
3568 if (bh->idle) {
3569 /* idle bottom halves will be polled at least
3570 * every 10ms */
3571 *timeout = MIN(10, *timeout);
3572 } else {
3573 /* non-idle bottom halves will be executed
3574 * immediately */
3575 *timeout = 0;
3576 break;
3582 /***********************************************************/
3583 /* machine registration */
3585 static QEMUMachine *first_machine = NULL;
3586 QEMUMachine *current_machine = NULL;
3588 int qemu_register_machine(QEMUMachine *m)
3590 QEMUMachine **pm;
3591 pm = &first_machine;
3592 while (*pm != NULL)
3593 pm = &(*pm)->next;
3594 m->next = NULL;
3595 *pm = m;
3596 return 0;
3599 static QEMUMachine *find_machine(const char *name)
3601 QEMUMachine *m;
3603 for(m = first_machine; m != NULL; m = m->next) {
3604 if (!strcmp(m->name, name))
3605 return m;
3607 return NULL;
3610 /***********************************************************/
3611 /* main execution loop */
3613 static void gui_update(void *opaque)
3615 uint64_t interval = GUI_REFRESH_INTERVAL;
3616 DisplayState *ds = opaque;
3617 DisplayChangeListener *dcl = ds->listeners;
3619 dpy_refresh(ds);
3621 while (dcl != NULL) {
3622 if (dcl->gui_timer_interval &&
3623 dcl->gui_timer_interval < interval)
3624 interval = dcl->gui_timer_interval;
3625 dcl = dcl->next;
3627 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3630 static void nographic_update(void *opaque)
3632 uint64_t interval = GUI_REFRESH_INTERVAL;
3634 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3637 struct vm_change_state_entry {
3638 VMChangeStateHandler *cb;
3639 void *opaque;
3640 LIST_ENTRY (vm_change_state_entry) entries;
3643 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3645 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3646 void *opaque)
3648 VMChangeStateEntry *e;
3650 e = qemu_mallocz(sizeof (*e));
3652 e->cb = cb;
3653 e->opaque = opaque;
3654 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3655 return e;
3658 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3660 LIST_REMOVE (e, entries);
3661 qemu_free (e);
3664 static void vm_state_notify(int running, int reason)
3666 VMChangeStateEntry *e;
3668 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3669 e->cb(e->opaque, running, reason);
3673 void vm_start(void)
3675 if (!vm_running) {
3676 cpu_enable_ticks();
3677 vm_running = 1;
3678 vm_state_notify(1, 0);
3679 if (kvm_enabled())
3680 qemu_kvm_resume_all_threads();
3681 qemu_rearm_alarm_timer(alarm_timer);
3685 void vm_stop(int reason)
3687 if (vm_running) {
3688 cpu_disable_ticks();
3689 vm_running = 0;
3690 if (kvm_enabled())
3691 qemu_kvm_pause_all_threads();
3692 vm_state_notify(0, reason);
3696 /* reset/shutdown handler */
3698 typedef struct QEMUResetEntry {
3699 QEMUResetHandler *func;
3700 void *opaque;
3701 struct QEMUResetEntry *next;
3702 } QEMUResetEntry;
3704 static QEMUResetEntry *first_reset_entry;
3705 static int reset_requested;
3706 static int shutdown_requested;
3707 static int powerdown_requested;
3709 int qemu_shutdown_requested(void)
3711 int r = shutdown_requested;
3712 shutdown_requested = 0;
3713 return r;
3716 int qemu_reset_requested(void)
3718 int r = reset_requested;
3719 reset_requested = 0;
3720 return r;
3723 int qemu_powerdown_requested(void)
3725 int r = powerdown_requested;
3726 powerdown_requested = 0;
3727 return r;
3730 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3732 QEMUResetEntry **pre, *re;
3734 pre = &first_reset_entry;
3735 while (*pre != NULL)
3736 pre = &(*pre)->next;
3737 re = qemu_mallocz(sizeof(QEMUResetEntry));
3738 re->func = func;
3739 re->opaque = opaque;
3740 re->next = NULL;
3741 *pre = re;
3744 void qemu_system_reset(void)
3746 QEMUResetEntry *re;
3748 /* reset all devices */
3749 for(re = first_reset_entry; re != NULL; re = re->next) {
3750 re->func(re->opaque);
3752 if (kvm_enabled())
3753 kvm_sync_vcpus();
3756 void qemu_system_reset_request(void)
3758 if (no_reboot) {
3759 shutdown_requested = 1;
3760 } else {
3761 reset_requested = 1;
3763 if (cpu_single_env) {
3764 qemu_kvm_cpu_stop(cpu_single_env);
3765 cpu_exit(cpu_single_env);
3769 void qemu_system_shutdown_request(void)
3771 shutdown_requested = 1;
3772 if (cpu_single_env)
3773 cpu_exit(cpu_single_env);
3776 void qemu_system_powerdown_request(void)
3778 powerdown_requested = 1;
3779 if (cpu_single_env)
3780 cpu_exit(cpu_single_env);
3783 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3784 struct timeval *tv)
3786 int ret;
3788 /* KVM holds a mutex while QEMU code is running, we need hooks to
3789 release the mutex whenever QEMU code sleeps. */
3791 kvm_sleep_begin();
3793 ret = select(max_fd, rfds, wfds, xfds, tv);
3795 kvm_sleep_end();
3797 return ret;
3800 #ifdef _WIN32
3801 static void host_main_loop_wait(int *timeout)
3803 int ret, ret2, i;
3804 PollingEntry *pe;
3807 /* XXX: need to suppress polling by better using win32 events */
3808 ret = 0;
3809 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3810 ret |= pe->func(pe->opaque);
3812 if (ret == 0) {
3813 int err;
3814 WaitObjects *w = &wait_objects;
3816 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3817 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3818 if (w->func[ret - WAIT_OBJECT_0])
3819 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3821 /* Check for additional signaled events */
3822 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3824 /* Check if event is signaled */
3825 ret2 = WaitForSingleObject(w->events[i], 0);
3826 if(ret2 == WAIT_OBJECT_0) {
3827 if (w->func[i])
3828 w->func[i](w->opaque[i]);
3829 } else if (ret2 == WAIT_TIMEOUT) {
3830 } else {
3831 err = GetLastError();
3832 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3835 } else if (ret == WAIT_TIMEOUT) {
3836 } else {
3837 err = GetLastError();
3838 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3842 *timeout = 0;
3844 #else
3845 static void host_main_loop_wait(int *timeout)
3848 #endif
3850 void main_loop_wait(int timeout)
3852 IOHandlerRecord *ioh;
3853 fd_set rfds, wfds, xfds;
3854 int ret, nfds;
3855 struct timeval tv;
3857 qemu_bh_update_timeout(&timeout);
3859 host_main_loop_wait(&timeout);
3861 /* poll any events */
3862 /* XXX: separate device handlers from system ones */
3863 nfds = -1;
3864 FD_ZERO(&rfds);
3865 FD_ZERO(&wfds);
3866 FD_ZERO(&xfds);
3867 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3868 if (ioh->deleted)
3869 continue;
3870 if (ioh->fd_read &&
3871 (!ioh->fd_read_poll ||
3872 ioh->fd_read_poll(ioh->opaque) != 0)) {
3873 FD_SET(ioh->fd, &rfds);
3874 if (ioh->fd > nfds)
3875 nfds = ioh->fd;
3877 if (ioh->fd_write) {
3878 FD_SET(ioh->fd, &wfds);
3879 if (ioh->fd > nfds)
3880 nfds = ioh->fd;
3884 tv.tv_sec = timeout / 1000;
3885 tv.tv_usec = (timeout % 1000) * 1000;
3887 #if defined(CONFIG_SLIRP)
3888 if (slirp_is_inited()) {
3889 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3891 #endif
3892 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3893 if (ret > 0) {
3894 IOHandlerRecord **pioh;
3896 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3897 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3898 ioh->fd_read(ioh->opaque);
3899 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3900 FD_CLR(ioh->fd, &rfds);
3902 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3903 ioh->fd_write(ioh->opaque);
3907 /* remove deleted IO handlers */
3908 pioh = &first_io_handler;
3909 while (*pioh) {
3910 ioh = *pioh;
3911 if (ioh->deleted) {
3912 *pioh = ioh->next;
3913 qemu_free(ioh);
3914 } else
3915 pioh = &ioh->next;
3918 #if defined(CONFIG_SLIRP)
3919 if (slirp_is_inited()) {
3920 if (ret < 0) {
3921 FD_ZERO(&rfds);
3922 FD_ZERO(&wfds);
3923 FD_ZERO(&xfds);
3925 slirp_select_poll(&rfds, &wfds, &xfds);
3927 #endif
3929 /* vm time timers */
3930 if (vm_running && (!cur_cpu
3931 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3932 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3933 qemu_get_clock(vm_clock));
3935 /* real time timers */
3936 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3937 qemu_get_clock(rt_clock));
3939 /* Check bottom-halves last in case any of the earlier events triggered
3940 them. */
3941 qemu_bh_poll();
3945 static int main_loop(void)
3947 int ret, timeout;
3948 #ifdef CONFIG_PROFILER
3949 int64_t ti;
3950 #endif
3951 CPUState *env;
3954 if (kvm_enabled()) {
3955 kvm_main_loop();
3956 cpu_disable_ticks();
3957 return 0;
3960 cur_cpu = first_cpu;
3961 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3962 for(;;) {
3963 if (vm_running) {
3965 for(;;) {
3966 /* get next cpu */
3967 env = next_cpu;
3968 #ifdef CONFIG_PROFILER
3969 ti = profile_getclock();
3970 #endif
3971 if (use_icount) {
3972 int64_t count;
3973 int decr;
3974 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3975 env->icount_decr.u16.low = 0;
3976 env->icount_extra = 0;
3977 count = qemu_next_deadline();
3978 count = (count + (1 << icount_time_shift) - 1)
3979 >> icount_time_shift;
3980 qemu_icount += count;
3981 decr = (count > 0xffff) ? 0xffff : count;
3982 count -= decr;
3983 env->icount_decr.u16.low = decr;
3984 env->icount_extra = count;
3986 ret = cpu_exec(env);
3987 #ifdef CONFIG_PROFILER
3988 qemu_time += profile_getclock() - ti;
3989 #endif
3990 if (use_icount) {
3991 /* Fold pending instructions back into the
3992 instruction counter, and clear the interrupt flag. */
3993 qemu_icount -= (env->icount_decr.u16.low
3994 + env->icount_extra);
3995 env->icount_decr.u32 = 0;
3996 env->icount_extra = 0;
3998 next_cpu = env->next_cpu ?: first_cpu;
3999 if (event_pending && likely(ret != EXCP_DEBUG)) {
4000 ret = EXCP_INTERRUPT;
4001 event_pending = 0;
4002 break;
4004 if (ret == EXCP_HLT) {
4005 /* Give the next CPU a chance to run. */
4006 cur_cpu = env;
4007 continue;
4009 if (ret != EXCP_HALTED)
4010 break;
4011 /* all CPUs are halted ? */
4012 if (env == cur_cpu)
4013 break;
4015 cur_cpu = env;
4017 if (shutdown_requested) {
4018 ret = EXCP_INTERRUPT;
4019 if (no_shutdown) {
4020 vm_stop(0);
4021 no_shutdown = 0;
4023 else
4024 break;
4026 if (reset_requested) {
4027 reset_requested = 0;
4028 qemu_system_reset();
4029 ret = EXCP_INTERRUPT;
4031 if (powerdown_requested) {
4032 powerdown_requested = 0;
4033 qemu_system_powerdown();
4034 ret = EXCP_INTERRUPT;
4036 #ifdef CONFIG_GDBSTUB
4037 if (unlikely(ret == EXCP_DEBUG)) {
4038 gdb_set_stop_cpu(cur_cpu);
4039 vm_stop(EXCP_DEBUG);
4041 #endif
4042 /* If all cpus are halted then wait until the next IRQ */
4043 /* XXX: use timeout computed from timers */
4044 if (ret == EXCP_HALTED) {
4045 if (use_icount) {
4046 int64_t add;
4047 int64_t delta;
4048 /* Advance virtual time to the next event. */
4049 if (use_icount == 1) {
4050 /* When not using an adaptive execution frequency
4051 we tend to get badly out of sync with real time,
4052 so just delay for a reasonable amount of time. */
4053 delta = 0;
4054 } else {
4055 delta = cpu_get_icount() - cpu_get_clock();
4057 if (delta > 0) {
4058 /* If virtual time is ahead of real time then just
4059 wait for IO. */
4060 timeout = (delta / 1000000) + 1;
4061 } else {
4062 /* Wait for either IO to occur or the next
4063 timer event. */
4064 add = qemu_next_deadline();
4065 /* We advance the timer before checking for IO.
4066 Limit the amount we advance so that early IO
4067 activity won't get the guest too far ahead. */
4068 if (add > 10000000)
4069 add = 10000000;
4070 delta += add;
4071 add = (add + (1 << icount_time_shift) - 1)
4072 >> icount_time_shift;
4073 qemu_icount += add;
4074 timeout = delta / 1000000;
4075 if (timeout < 0)
4076 timeout = 0;
4078 } else {
4079 timeout = 5000;
4081 } else {
4082 timeout = 0;
4084 } else {
4085 if (shutdown_requested) {
4086 ret = EXCP_INTERRUPT;
4087 break;
4089 timeout = 5000;
4091 #ifdef CONFIG_PROFILER
4092 ti = profile_getclock();
4093 #endif
4094 main_loop_wait(timeout);
4095 #ifdef CONFIG_PROFILER
4096 dev_time += profile_getclock() - ti;
4097 #endif
4099 cpu_disable_ticks();
4100 return ret;
4103 static void version(void)
4105 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")" QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4108 static void help(int exitcode)
4110 version();
4111 printf("usage: %s [options] [disk_image]\n"
4112 "\n"
4113 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4114 "\n"
4115 #define DEF(option, opt_arg, opt_enum, opt_help) \
4116 opt_help
4117 #define DEFHEADING(text) stringify(text) "\n"
4118 #include "qemu-options.h"
4119 #undef DEF
4120 #undef DEFHEADING
4121 #undef GEN_DOCS
4122 "\n"
4123 "During emulation, the following keys are useful:\n"
4124 "ctrl-alt-f toggle full screen\n"
4125 "ctrl-alt-n switch to virtual console 'n'\n"
4126 "ctrl-alt toggle mouse and keyboard grab\n"
4127 "\n"
4128 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4130 "qemu",
4131 DEFAULT_RAM_SIZE,
4132 #ifndef _WIN32
4133 DEFAULT_NETWORK_SCRIPT,
4134 DEFAULT_NETWORK_DOWN_SCRIPT,
4135 #endif
4136 DEFAULT_GDBSTUB_PORT,
4137 "/tmp/qemu.log");
4138 exit(exitcode);
4141 #define HAS_ARG 0x0001
4143 enum {
4144 #define DEF(option, opt_arg, opt_enum, opt_help) \
4145 opt_enum,
4146 #define DEFHEADING(text)
4147 #include "qemu-options.h"
4148 #undef DEF
4149 #undef DEFHEADING
4150 #undef GEN_DOCS
4153 typedef struct QEMUOption {
4154 const char *name;
4155 int flags;
4156 int index;
4157 } QEMUOption;
4159 static const QEMUOption qemu_options[] = {
4160 { "h", 0, QEMU_OPTION_h },
4161 #define DEF(option, opt_arg, opt_enum, opt_help) \
4162 { option, opt_arg, opt_enum },
4163 #define DEFHEADING(text)
4164 #include "qemu-options.h"
4165 #undef DEF
4166 #undef DEFHEADING
4167 #undef GEN_DOCS
4168 { NULL },
4171 #ifdef HAS_AUDIO
4172 struct soundhw soundhw[] = {
4173 #ifdef HAS_AUDIO_CHOICE
4174 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4176 "pcspk",
4177 "PC speaker",
4180 { .init_isa = pcspk_audio_init }
4182 #endif
4184 #ifdef CONFIG_SB16
4186 "sb16",
4187 "Creative Sound Blaster 16",
4190 { .init_isa = SB16_init }
4192 #endif
4194 #ifdef CONFIG_CS4231A
4196 "cs4231a",
4197 "CS4231A",
4200 { .init_isa = cs4231a_init }
4202 #endif
4204 #ifdef CONFIG_ADLIB
4206 "adlib",
4207 #ifdef HAS_YMF262
4208 "Yamaha YMF262 (OPL3)",
4209 #else
4210 "Yamaha YM3812 (OPL2)",
4211 #endif
4214 { .init_isa = Adlib_init }
4216 #endif
4218 #ifdef CONFIG_GUS
4220 "gus",
4221 "Gravis Ultrasound GF1",
4224 { .init_isa = GUS_init }
4226 #endif
4228 #ifdef CONFIG_AC97
4230 "ac97",
4231 "Intel 82801AA AC97 Audio",
4234 { .init_pci = ac97_init }
4236 #endif
4238 #ifdef CONFIG_ES1370
4240 "es1370",
4241 "ENSONIQ AudioPCI ES1370",
4244 { .init_pci = es1370_init }
4246 #endif
4248 #endif /* HAS_AUDIO_CHOICE */
4250 { NULL, NULL, 0, 0, { NULL } }
4253 static void select_soundhw (const char *optarg)
4255 struct soundhw *c;
4257 if (*optarg == '?') {
4258 show_valid_cards:
4260 printf ("Valid sound card names (comma separated):\n");
4261 for (c = soundhw; c->name; ++c) {
4262 printf ("%-11s %s\n", c->name, c->descr);
4264 printf ("\n-soundhw all will enable all of the above\n");
4265 exit (*optarg != '?');
4267 else {
4268 size_t l;
4269 const char *p;
4270 char *e;
4271 int bad_card = 0;
4273 if (!strcmp (optarg, "all")) {
4274 for (c = soundhw; c->name; ++c) {
4275 c->enabled = 1;
4277 return;
4280 p = optarg;
4281 while (*p) {
4282 e = strchr (p, ',');
4283 l = !e ? strlen (p) : (size_t) (e - p);
4285 for (c = soundhw; c->name; ++c) {
4286 if (!strncmp (c->name, p, l)) {
4287 c->enabled = 1;
4288 break;
4292 if (!c->name) {
4293 if (l > 80) {
4294 fprintf (stderr,
4295 "Unknown sound card name (too big to show)\n");
4297 else {
4298 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4299 (int) l, p);
4301 bad_card = 1;
4303 p += l + (e != NULL);
4306 if (bad_card)
4307 goto show_valid_cards;
4310 #endif
4312 static void select_vgahw (const char *p)
4314 const char *opts;
4316 cirrus_vga_enabled = 0;
4317 std_vga_enabled = 0;
4318 vmsvga_enabled = 0;
4319 xenfb_enabled = 0;
4320 if (strstart(p, "std", &opts)) {
4321 std_vga_enabled = 1;
4322 } else if (strstart(p, "cirrus", &opts)) {
4323 cirrus_vga_enabled = 1;
4324 } else if (strstart(p, "vmware", &opts)) {
4325 vmsvga_enabled = 1;
4326 } else if (strstart(p, "xenfb", &opts)) {
4327 xenfb_enabled = 1;
4328 } else if (!strstart(p, "none", &opts)) {
4329 invalid_vga:
4330 fprintf(stderr, "Unknown vga type: %s\n", p);
4331 exit(1);
4333 while (*opts) {
4334 const char *nextopt;
4336 if (strstart(opts, ",retrace=", &nextopt)) {
4337 opts = nextopt;
4338 if (strstart(opts, "dumb", &nextopt))
4339 vga_retrace_method = VGA_RETRACE_DUMB;
4340 else if (strstart(opts, "precise", &nextopt))
4341 vga_retrace_method = VGA_RETRACE_PRECISE;
4342 else goto invalid_vga;
4343 } else goto invalid_vga;
4344 opts = nextopt;
4348 #ifdef _WIN32
4349 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4351 exit(STATUS_CONTROL_C_EXIT);
4352 return TRUE;
4354 #endif
4356 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4358 int ret;
4360 if(strlen(str) != 36)
4361 return -1;
4363 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4364 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4365 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4367 if(ret != 16)
4368 return -1;
4370 #ifdef TARGET_I386
4371 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4372 #endif
4374 return 0;
4377 #define MAX_NET_CLIENTS 32
4379 static int saved_argc;
4380 static char **saved_argv;
4381 static const char *saved_incoming;
4383 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4385 *argc = saved_argc;
4386 *argv = saved_argv;
4387 *opt_daemonize = daemonize;
4388 *opt_incoming = saved_incoming;
4391 #ifdef USE_KVM
4393 #define HUGETLBFS_MAGIC 0x958458f6
4395 static long gethugepagesize(const char *path)
4397 struct statfs fs;
4398 int ret;
4400 do {
4401 ret = statfs(path, &fs);
4402 } while (ret != 0 && errno == EINTR);
4404 if (ret != 0) {
4405 perror("statfs");
4406 return 0;
4409 if (fs.f_type != HUGETLBFS_MAGIC)
4410 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4412 return fs.f_bsize;
4415 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4417 char *filename;
4418 void *area;
4419 int fd;
4420 #ifdef MAP_POPULATE
4421 int flags;
4422 #endif
4424 if (!kvm_has_sync_mmu()) {
4425 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4426 return NULL;
4429 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4430 return NULL;
4432 hpagesize = gethugepagesize(path);
4433 if (!hpagesize)
4434 return NULL;
4436 fd = mkstemp(filename);
4437 if (fd < 0) {
4438 perror("mkstemp");
4439 free(filename);
4440 return NULL;
4442 unlink(filename);
4443 free(filename);
4445 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4448 * ftruncate is not supported by hugetlbfs in older
4449 * hosts, so don't bother checking for errors.
4450 * If anything goes wrong with it under other filesystems,
4451 * mmap will fail.
4453 ftruncate(fd, memory);
4455 #ifdef MAP_POPULATE
4456 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4457 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4458 * to sidestep this quirk.
4460 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4461 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4462 #else
4463 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4464 #endif
4465 if (area == MAP_FAILED) {
4466 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4467 close(fd);
4468 return (NULL);
4470 *len = memory;
4471 return area;
4473 #endif
4475 static void *qemu_alloc_physram(unsigned long memory)
4477 void *area = NULL;
4478 #ifdef USE_KVM
4479 unsigned long map_len = memory;
4481 if (mem_path)
4482 area = alloc_mem_area(memory, &map_len, mem_path);
4483 #endif
4484 if (!area)
4485 area = qemu_vmalloc(memory);
4486 #ifdef USE_KVM
4487 if (kvm_setup_guest_memory(area, map_len))
4488 area = NULL;
4489 #endif
4490 return area;
4493 #ifndef _WIN32
4495 static void termsig_handler(int signal)
4497 qemu_system_shutdown_request();
4500 static void termsig_setup(void)
4502 struct sigaction act;
4504 memset(&act, 0, sizeof(act));
4505 act.sa_handler = termsig_handler;
4506 sigaction(SIGINT, &act, NULL);
4507 sigaction(SIGHUP, &act, NULL);
4508 sigaction(SIGTERM, &act, NULL);
4511 #endif
4513 int main(int argc, char **argv, char **envp)
4515 #ifdef CONFIG_GDBSTUB
4516 const char *gdbstub_dev = NULL;
4517 #endif
4518 uint32_t boot_devices_bitmap = 0;
4519 int i;
4520 int snapshot, linux_boot, net_boot;
4521 const char *initrd_filename;
4522 const char *kernel_filename, *kernel_cmdline;
4523 const char *boot_devices = "";
4524 DisplayState *ds;
4525 DisplayChangeListener *dcl;
4526 int cyls, heads, secs, translation;
4527 const char *net_clients[MAX_NET_CLIENTS];
4528 int nb_net_clients;
4529 const char *bt_opts[MAX_BT_CMDLINE];
4530 int nb_bt_opts;
4531 int hda_index;
4532 int optind;
4533 const char *r, *optarg;
4534 CharDriverState *monitor_hd = NULL;
4535 const char *monitor_device;
4536 const char *serial_devices[MAX_SERIAL_PORTS];
4537 int serial_device_index;
4538 const char *parallel_devices[MAX_PARALLEL_PORTS];
4539 int parallel_device_index;
4540 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4541 int virtio_console_index;
4542 const char *loadvm = NULL;
4543 QEMUMachine *machine;
4544 const char *cpu_model;
4545 const char *usb_devices[MAX_USB_CMDLINE];
4546 int usb_devices_index;
4547 #ifndef _WIN32
4548 int fds[2];
4549 #endif
4550 int tb_size;
4551 const char *pid_file = NULL;
4552 const char *incoming = NULL;
4553 #ifndef _WIN32
4554 int fd = 0;
4555 struct passwd *pwd = NULL;
4556 const char *chroot_dir = NULL;
4557 const char *run_as = NULL;
4558 #endif
4559 CPUState *env;
4561 qemu_cache_utils_init(envp);
4563 LIST_INIT (&vm_change_state_head);
4564 #ifndef _WIN32
4566 struct sigaction act;
4567 sigfillset(&act.sa_mask);
4568 act.sa_flags = 0;
4569 act.sa_handler = SIG_IGN;
4570 sigaction(SIGPIPE, &act, NULL);
4572 #else
4573 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4574 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4575 QEMU to run on a single CPU */
4577 HANDLE h;
4578 DWORD mask, smask;
4579 int i;
4580 h = GetCurrentProcess();
4581 if (GetProcessAffinityMask(h, &mask, &smask)) {
4582 for(i = 0; i < 32; i++) {
4583 if (mask & (1 << i))
4584 break;
4586 if (i != 32) {
4587 mask = 1 << i;
4588 SetProcessAffinityMask(h, mask);
4592 #endif
4594 register_machines();
4595 machine = first_machine;
4596 cpu_model = NULL;
4597 initrd_filename = NULL;
4598 ram_size = 0;
4599 vga_ram_size = VGA_RAM_SIZE;
4600 snapshot = 0;
4601 nographic = 0;
4602 curses = 0;
4603 kernel_filename = NULL;
4604 kernel_cmdline = "";
4605 cyls = heads = secs = 0;
4606 translation = BIOS_ATA_TRANSLATION_AUTO;
4607 monitor_device = "vc:80Cx24C";
4609 serial_devices[0] = "vc:80Cx24C";
4610 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4611 serial_devices[i] = NULL;
4612 serial_device_index = 0;
4614 parallel_devices[0] = "vc:80Cx24C";
4615 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4616 parallel_devices[i] = NULL;
4617 parallel_device_index = 0;
4619 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4620 virtio_consoles[i] = NULL;
4621 virtio_console_index = 0;
4623 for (i = 0; i < MAX_NODES; i++) {
4624 node_mem[i] = 0;
4625 node_cpumask[i] = 0;
4628 usb_devices_index = 0;
4629 assigned_devices_index = 0;
4631 nb_net_clients = 0;
4632 nb_bt_opts = 0;
4633 nb_drives = 0;
4634 nb_drives_opt = 0;
4635 nb_numa_nodes = 0;
4636 hda_index = -1;
4638 nb_nics = 0;
4640 tb_size = 0;
4641 autostart= 1;
4643 optind = 1;
4644 for(;;) {
4645 if (optind >= argc)
4646 break;
4647 r = argv[optind];
4648 if (r[0] != '-') {
4649 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4650 } else {
4651 const QEMUOption *popt;
4653 optind++;
4654 /* Treat --foo the same as -foo. */
4655 if (r[1] == '-')
4656 r++;
4657 popt = qemu_options;
4658 for(;;) {
4659 if (!popt->name) {
4660 fprintf(stderr, "%s: invalid option -- '%s'\n",
4661 argv[0], r);
4662 exit(1);
4664 if (!strcmp(popt->name, r + 1))
4665 break;
4666 popt++;
4668 if (popt->flags & HAS_ARG) {
4669 if (optind >= argc) {
4670 fprintf(stderr, "%s: option '%s' requires an argument\n",
4671 argv[0], r);
4672 exit(1);
4674 optarg = argv[optind++];
4675 } else {
4676 optarg = NULL;
4679 switch(popt->index) {
4680 case QEMU_OPTION_M:
4681 machine = find_machine(optarg);
4682 if (!machine) {
4683 QEMUMachine *m;
4684 printf("Supported machines are:\n");
4685 for(m = first_machine; m != NULL; m = m->next) {
4686 printf("%-10s %s%s\n",
4687 m->name, m->desc,
4688 m == first_machine ? " (default)" : "");
4690 exit(*optarg != '?');
4692 break;
4693 case QEMU_OPTION_cpu:
4694 /* hw initialization will check this */
4695 if (*optarg == '?') {
4696 /* XXX: implement xxx_cpu_list for targets that still miss it */
4697 #if defined(cpu_list)
4698 cpu_list(stdout, &fprintf);
4699 #endif
4700 exit(0);
4701 } else {
4702 cpu_model = optarg;
4704 break;
4705 case QEMU_OPTION_initrd:
4706 initrd_filename = optarg;
4707 break;
4708 case QEMU_OPTION_hda:
4709 if (cyls == 0)
4710 hda_index = drive_add(optarg, HD_ALIAS, 0);
4711 else
4712 hda_index = drive_add(optarg, HD_ALIAS
4713 ",cyls=%d,heads=%d,secs=%d%s",
4714 0, cyls, heads, secs,
4715 translation == BIOS_ATA_TRANSLATION_LBA ?
4716 ",trans=lba" :
4717 translation == BIOS_ATA_TRANSLATION_NONE ?
4718 ",trans=none" : "");
4719 break;
4720 case QEMU_OPTION_hdb:
4721 case QEMU_OPTION_hdc:
4722 case QEMU_OPTION_hdd:
4723 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4724 break;
4725 case QEMU_OPTION_drive:
4726 drive_add(NULL, "%s", optarg);
4727 break;
4728 case QEMU_OPTION_mtdblock:
4729 drive_add(optarg, MTD_ALIAS);
4730 break;
4731 case QEMU_OPTION_sd:
4732 drive_add(optarg, SD_ALIAS);
4733 break;
4734 case QEMU_OPTION_pflash:
4735 drive_add(optarg, PFLASH_ALIAS);
4736 break;
4737 case QEMU_OPTION_snapshot:
4738 snapshot = 1;
4739 break;
4740 case QEMU_OPTION_hdachs:
4742 const char *p;
4743 p = optarg;
4744 cyls = strtol(p, (char **)&p, 0);
4745 if (cyls < 1 || cyls > 16383)
4746 goto chs_fail;
4747 if (*p != ',')
4748 goto chs_fail;
4749 p++;
4750 heads = strtol(p, (char **)&p, 0);
4751 if (heads < 1 || heads > 16)
4752 goto chs_fail;
4753 if (*p != ',')
4754 goto chs_fail;
4755 p++;
4756 secs = strtol(p, (char **)&p, 0);
4757 if (secs < 1 || secs > 63)
4758 goto chs_fail;
4759 if (*p == ',') {
4760 p++;
4761 if (!strcmp(p, "none"))
4762 translation = BIOS_ATA_TRANSLATION_NONE;
4763 else if (!strcmp(p, "lba"))
4764 translation = BIOS_ATA_TRANSLATION_LBA;
4765 else if (!strcmp(p, "auto"))
4766 translation = BIOS_ATA_TRANSLATION_AUTO;
4767 else
4768 goto chs_fail;
4769 } else if (*p != '\0') {
4770 chs_fail:
4771 fprintf(stderr, "qemu: invalid physical CHS format\n");
4772 exit(1);
4774 if (hda_index != -1)
4775 snprintf(drives_opt[hda_index].opt,
4776 sizeof(drives_opt[hda_index].opt),
4777 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4778 0, cyls, heads, secs,
4779 translation == BIOS_ATA_TRANSLATION_LBA ?
4780 ",trans=lba" :
4781 translation == BIOS_ATA_TRANSLATION_NONE ?
4782 ",trans=none" : "");
4784 break;
4785 case QEMU_OPTION_numa:
4786 if (nb_numa_nodes >= MAX_NODES) {
4787 fprintf(stderr, "qemu: too many NUMA nodes\n");
4788 exit(1);
4790 numa_add(optarg);
4791 break;
4792 case QEMU_OPTION_nographic:
4793 nographic = 1;
4794 break;
4795 #ifdef CONFIG_CURSES
4796 case QEMU_OPTION_curses:
4797 curses = 1;
4798 break;
4799 #endif
4800 case QEMU_OPTION_portrait:
4801 graphic_rotate = 1;
4802 break;
4803 case QEMU_OPTION_kernel:
4804 kernel_filename = optarg;
4805 break;
4806 case QEMU_OPTION_append:
4807 kernel_cmdline = optarg;
4808 break;
4809 case QEMU_OPTION_cdrom:
4810 drive_add(optarg, CDROM_ALIAS);
4811 break;
4812 case QEMU_OPTION_boot:
4813 boot_devices = optarg;
4814 /* We just do some generic consistency checks */
4816 /* Could easily be extended to 64 devices if needed */
4817 const char *p;
4819 boot_devices_bitmap = 0;
4820 for (p = boot_devices; *p != '\0'; p++) {
4821 /* Allowed boot devices are:
4822 * a b : floppy disk drives
4823 * c ... f : IDE disk drives
4824 * g ... m : machine implementation dependant drives
4825 * n ... p : network devices
4826 * It's up to each machine implementation to check
4827 * if the given boot devices match the actual hardware
4828 * implementation and firmware features.
4830 if (*p < 'a' || *p > 'q') {
4831 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4832 exit(1);
4834 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4835 fprintf(stderr,
4836 "Boot device '%c' was given twice\n",*p);
4837 exit(1);
4839 boot_devices_bitmap |= 1 << (*p - 'a');
4842 break;
4843 case QEMU_OPTION_fda:
4844 case QEMU_OPTION_fdb:
4845 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4846 break;
4847 #ifdef TARGET_I386
4848 case QEMU_OPTION_no_fd_bootchk:
4849 fd_bootchk = 0;
4850 break;
4851 #endif
4852 case QEMU_OPTION_net:
4853 if (nb_net_clients >= MAX_NET_CLIENTS) {
4854 fprintf(stderr, "qemu: too many network clients\n");
4855 exit(1);
4857 net_clients[nb_net_clients] = optarg;
4858 nb_net_clients++;
4859 break;
4860 #ifdef CONFIG_SLIRP
4861 case QEMU_OPTION_tftp:
4862 tftp_prefix = optarg;
4863 break;
4864 case QEMU_OPTION_bootp:
4865 bootp_filename = optarg;
4866 break;
4867 #ifndef _WIN32
4868 case QEMU_OPTION_smb:
4869 net_slirp_smb(optarg);
4870 break;
4871 #endif
4872 case QEMU_OPTION_redir:
4873 net_slirp_redir(NULL, optarg);
4874 break;
4875 #endif
4876 case QEMU_OPTION_bt:
4877 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4878 fprintf(stderr, "qemu: too many bluetooth options\n");
4879 exit(1);
4881 bt_opts[nb_bt_opts++] = optarg;
4882 break;
4883 #ifdef HAS_AUDIO
4884 case QEMU_OPTION_audio_help:
4885 AUD_help ();
4886 exit (0);
4887 break;
4888 case QEMU_OPTION_soundhw:
4889 select_soundhw (optarg);
4890 break;
4891 #endif
4892 case QEMU_OPTION_h:
4893 help(0);
4894 break;
4895 case QEMU_OPTION_version:
4896 version();
4897 exit(0);
4898 break;
4899 case QEMU_OPTION_m: {
4900 uint64_t value;
4901 char *ptr;
4903 value = strtoul(optarg, &ptr, 10);
4904 switch (*ptr) {
4905 case 0: case 'M': case 'm':
4906 value <<= 20;
4907 break;
4908 case 'G': case 'g':
4909 value <<= 30;
4910 break;
4911 default:
4912 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4913 exit(1);
4916 /* On 32-bit hosts, QEMU is limited by virtual address space */
4917 if (value > (2047 << 20)
4918 #ifndef CONFIG_KQEMU
4919 && HOST_LONG_BITS == 32
4920 #endif
4922 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4923 exit(1);
4925 if (value != (uint64_t)(ram_addr_t)value) {
4926 fprintf(stderr, "qemu: ram size too large\n");
4927 exit(1);
4929 ram_size = value;
4930 break;
4932 case QEMU_OPTION_d:
4934 int mask;
4935 const CPULogItem *item;
4937 mask = cpu_str_to_log_mask(optarg);
4938 if (!mask) {
4939 printf("Log items (comma separated):\n");
4940 for(item = cpu_log_items; item->mask != 0; item++) {
4941 printf("%-10s %s\n", item->name, item->help);
4943 exit(1);
4945 cpu_set_log(mask);
4947 break;
4948 #ifdef CONFIG_GDBSTUB
4949 case QEMU_OPTION_s:
4950 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4951 break;
4952 case QEMU_OPTION_gdb:
4953 gdbstub_dev = optarg;
4954 break;
4955 #endif
4956 case QEMU_OPTION_L:
4957 bios_dir = optarg;
4958 break;
4959 case QEMU_OPTION_bios:
4960 bios_name = optarg;
4961 break;
4962 case QEMU_OPTION_singlestep:
4963 singlestep = 1;
4964 break;
4965 case QEMU_OPTION_S:
4966 autostart = 0;
4967 break;
4968 #ifndef _WIN32
4969 case QEMU_OPTION_k:
4970 keyboard_layout = optarg;
4971 break;
4972 #endif
4973 case QEMU_OPTION_localtime:
4974 rtc_utc = 0;
4975 break;
4976 case QEMU_OPTION_vga:
4977 select_vgahw (optarg);
4978 break;
4979 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4980 case QEMU_OPTION_g:
4982 const char *p;
4983 int w, h, depth;
4984 p = optarg;
4985 w = strtol(p, (char **)&p, 10);
4986 if (w <= 0) {
4987 graphic_error:
4988 fprintf(stderr, "qemu: invalid resolution or depth\n");
4989 exit(1);
4991 if (*p != 'x')
4992 goto graphic_error;
4993 p++;
4994 h = strtol(p, (char **)&p, 10);
4995 if (h <= 0)
4996 goto graphic_error;
4997 if (*p == 'x') {
4998 p++;
4999 depth = strtol(p, (char **)&p, 10);
5000 if (depth != 8 && depth != 15 && depth != 16 &&
5001 depth != 24 && depth != 32)
5002 goto graphic_error;
5003 } else if (*p == '\0') {
5004 depth = graphic_depth;
5005 } else {
5006 goto graphic_error;
5009 graphic_width = w;
5010 graphic_height = h;
5011 graphic_depth = depth;
5013 break;
5014 #endif
5015 case QEMU_OPTION_echr:
5017 char *r;
5018 term_escape_char = strtol(optarg, &r, 0);
5019 if (r == optarg)
5020 printf("Bad argument to echr\n");
5021 break;
5023 case QEMU_OPTION_monitor:
5024 monitor_device = optarg;
5025 break;
5026 case QEMU_OPTION_serial:
5027 if (serial_device_index >= MAX_SERIAL_PORTS) {
5028 fprintf(stderr, "qemu: too many serial ports\n");
5029 exit(1);
5031 serial_devices[serial_device_index] = optarg;
5032 serial_device_index++;
5033 break;
5034 case QEMU_OPTION_virtiocon:
5035 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5036 fprintf(stderr, "qemu: too many virtio consoles\n");
5037 exit(1);
5039 virtio_consoles[virtio_console_index] = optarg;
5040 virtio_console_index++;
5041 break;
5042 case QEMU_OPTION_parallel:
5043 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5044 fprintf(stderr, "qemu: too many parallel ports\n");
5045 exit(1);
5047 parallel_devices[parallel_device_index] = optarg;
5048 parallel_device_index++;
5049 break;
5050 case QEMU_OPTION_loadvm:
5051 loadvm = optarg;
5052 break;
5053 case QEMU_OPTION_full_screen:
5054 full_screen = 1;
5055 break;
5056 #ifdef CONFIG_SDL
5057 case QEMU_OPTION_no_frame:
5058 no_frame = 1;
5059 break;
5060 case QEMU_OPTION_alt_grab:
5061 alt_grab = 1;
5062 break;
5063 case QEMU_OPTION_no_quit:
5064 no_quit = 1;
5065 break;
5066 case QEMU_OPTION_sdl:
5067 sdl = 1;
5068 break;
5069 #endif
5070 case QEMU_OPTION_pidfile:
5071 pid_file = optarg;
5072 break;
5073 #ifdef TARGET_I386
5074 case QEMU_OPTION_win2k_hack:
5075 win2k_install_hack = 1;
5076 break;
5077 case QEMU_OPTION_rtc_td_hack:
5078 rtc_td_hack = 1;
5079 break;
5080 case QEMU_OPTION_acpitable:
5081 if(acpi_table_add(optarg) < 0) {
5082 fprintf(stderr, "Wrong acpi table provided\n");
5083 exit(1);
5085 break;
5086 case QEMU_OPTION_smbios:
5087 if(smbios_entry_add(optarg) < 0) {
5088 fprintf(stderr, "Wrong smbios provided\n");
5089 exit(1);
5091 break;
5092 #endif
5093 #ifdef CONFIG_KQEMU
5094 case QEMU_OPTION_no_kqemu:
5095 kqemu_allowed = 0;
5096 break;
5097 case QEMU_OPTION_kernel_kqemu:
5098 kqemu_allowed = 2;
5099 break;
5100 #endif
5101 #ifdef CONFIG_KVM
5102 case QEMU_OPTION_enable_kvm:
5103 kvm_allowed = 1;
5104 #ifdef CONFIG_KQEMU
5105 kqemu_allowed = 0;
5106 #endif
5107 break;
5108 #endif
5109 #ifdef USE_KVM
5110 case QEMU_OPTION_no_kvm:
5111 kvm_allowed = 0;
5112 break;
5113 case QEMU_OPTION_no_kvm_irqchip: {
5114 kvm_irqchip = 0;
5115 kvm_pit = 0;
5116 break;
5118 case QEMU_OPTION_no_kvm_pit: {
5119 kvm_pit = 0;
5120 break;
5122 case QEMU_OPTION_no_kvm_pit_reinjection: {
5123 kvm_pit_reinject = 0;
5124 break;
5126 case QEMU_OPTION_enable_nesting: {
5127 kvm_nested = 1;
5128 break;
5130 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5131 case QEMU_OPTION_pcidevice:
5132 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5133 fprintf(stderr, "Too many assigned devices\n");
5134 exit(1);
5136 assigned_devices[assigned_devices_index] = optarg;
5137 assigned_devices_index++;
5138 break;
5139 #endif
5140 #endif
5141 case QEMU_OPTION_usb:
5142 usb_enabled = 1;
5143 break;
5144 case QEMU_OPTION_usbdevice:
5145 usb_enabled = 1;
5146 if (usb_devices_index >= MAX_USB_CMDLINE) {
5147 fprintf(stderr, "Too many USB devices\n");
5148 exit(1);
5150 usb_devices[usb_devices_index] = optarg;
5151 usb_devices_index++;
5152 break;
5153 case QEMU_OPTION_smp:
5154 smp_cpus = atoi(optarg);
5155 if (smp_cpus < 1) {
5156 fprintf(stderr, "Invalid number of CPUs\n");
5157 exit(1);
5159 break;
5160 case QEMU_OPTION_vnc:
5161 vnc_display = optarg;
5162 break;
5163 #ifdef TARGET_I386
5164 case QEMU_OPTION_no_acpi:
5165 acpi_enabled = 0;
5166 break;
5167 case QEMU_OPTION_no_hpet:
5168 no_hpet = 1;
5169 break;
5170 #endif
5171 case QEMU_OPTION_no_reboot:
5172 no_reboot = 1;
5173 break;
5174 case QEMU_OPTION_no_shutdown:
5175 no_shutdown = 1;
5176 break;
5177 case QEMU_OPTION_show_cursor:
5178 cursor_hide = 0;
5179 break;
5180 case QEMU_OPTION_uuid:
5181 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5182 fprintf(stderr, "Fail to parse UUID string."
5183 " Wrong format.\n");
5184 exit(1);
5186 break;
5187 #ifndef _WIN32
5188 case QEMU_OPTION_daemonize:
5189 daemonize = 1;
5190 break;
5191 #endif
5192 case QEMU_OPTION_option_rom:
5193 if (nb_option_roms >= MAX_OPTION_ROMS) {
5194 fprintf(stderr, "Too many option ROMs\n");
5195 exit(1);
5197 option_rom[nb_option_roms] = optarg;
5198 nb_option_roms++;
5199 break;
5200 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5201 case QEMU_OPTION_semihosting:
5202 semihosting_enabled = 1;
5203 break;
5204 #endif
5205 case QEMU_OPTION_tdf:
5206 time_drift_fix = 1;
5207 break;
5208 case QEMU_OPTION_kvm_shadow_memory:
5209 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5210 break;
5211 case QEMU_OPTION_mempath:
5212 mem_path = optarg;
5213 break;
5214 #ifdef MAP_POPULATE
5215 case QEMU_OPTION_mem_prealloc:
5216 mem_prealloc = !mem_prealloc;
5217 break;
5218 #endif
5219 case QEMU_OPTION_name:
5220 qemu_name = optarg;
5221 break;
5222 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5223 case QEMU_OPTION_prom_env:
5224 if (nb_prom_envs >= MAX_PROM_ENVS) {
5225 fprintf(stderr, "Too many prom variables\n");
5226 exit(1);
5228 prom_envs[nb_prom_envs] = optarg;
5229 nb_prom_envs++;
5230 break;
5231 #endif
5232 case QEMU_OPTION_cpu_vendor:
5233 cpu_vendor_string = optarg;
5234 break;
5235 #ifdef TARGET_ARM
5236 case QEMU_OPTION_old_param:
5237 old_param = 1;
5238 break;
5239 #endif
5240 case QEMU_OPTION_clock:
5241 configure_alarms(optarg);
5242 break;
5243 case QEMU_OPTION_startdate:
5245 struct tm tm;
5246 time_t rtc_start_date;
5247 if (!strcmp(optarg, "now")) {
5248 rtc_date_offset = -1;
5249 } else {
5250 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5251 &tm.tm_year,
5252 &tm.tm_mon,
5253 &tm.tm_mday,
5254 &tm.tm_hour,
5255 &tm.tm_min,
5256 &tm.tm_sec) == 6) {
5257 /* OK */
5258 } else if (sscanf(optarg, "%d-%d-%d",
5259 &tm.tm_year,
5260 &tm.tm_mon,
5261 &tm.tm_mday) == 3) {
5262 tm.tm_hour = 0;
5263 tm.tm_min = 0;
5264 tm.tm_sec = 0;
5265 } else {
5266 goto date_fail;
5268 tm.tm_year -= 1900;
5269 tm.tm_mon--;
5270 rtc_start_date = mktimegm(&tm);
5271 if (rtc_start_date == -1) {
5272 date_fail:
5273 fprintf(stderr, "Invalid date format. Valid format are:\n"
5274 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5275 exit(1);
5277 rtc_date_offset = time(NULL) - rtc_start_date;
5280 break;
5281 case QEMU_OPTION_tb_size:
5282 tb_size = strtol(optarg, NULL, 0);
5283 if (tb_size < 0)
5284 tb_size = 0;
5285 break;
5286 case QEMU_OPTION_icount:
5287 use_icount = 1;
5288 if (strcmp(optarg, "auto") == 0) {
5289 icount_time_shift = -1;
5290 } else {
5291 icount_time_shift = strtol(optarg, NULL, 0);
5293 break;
5294 case QEMU_OPTION_incoming:
5295 incoming = optarg;
5296 saved_incoming = incoming;
5297 break;
5298 #ifndef _WIN32
5299 case QEMU_OPTION_chroot:
5300 chroot_dir = optarg;
5301 break;
5302 case QEMU_OPTION_runas:
5303 run_as = optarg;
5304 break;
5305 case QEMU_OPTION_nvram:
5306 nvram = optarg;
5307 break;
5308 #endif
5309 #ifdef CONFIG_XEN
5310 case QEMU_OPTION_xen_domid:
5311 xen_domid = atoi(optarg);
5312 break;
5313 case QEMU_OPTION_xen_create:
5314 xen_mode = XEN_CREATE;
5315 break;
5316 case QEMU_OPTION_xen_attach:
5317 xen_mode = XEN_ATTACH;
5318 break;
5319 #endif
5324 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5325 if (kvm_allowed && kqemu_allowed) {
5326 fprintf(stderr,
5327 "You can not enable both KVM and kqemu at the same time\n");
5328 exit(1);
5330 #endif
5332 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5333 if (smp_cpus > machine->max_cpus) {
5334 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5335 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5336 machine->max_cpus);
5337 exit(1);
5340 if (nographic) {
5341 if (serial_device_index == 0)
5342 serial_devices[0] = "stdio";
5343 if (parallel_device_index == 0)
5344 parallel_devices[0] = "null";
5345 if (strncmp(monitor_device, "vc", 2) == 0)
5346 monitor_device = "stdio";
5349 #ifndef _WIN32
5350 if (daemonize) {
5351 pid_t pid;
5353 if (pipe(fds) == -1)
5354 exit(1);
5356 pid = fork();
5357 if (pid > 0) {
5358 uint8_t status;
5359 ssize_t len;
5361 close(fds[1]);
5363 again:
5364 len = read(fds[0], &status, 1);
5365 if (len == -1 && (errno == EINTR))
5366 goto again;
5368 if (len != 1)
5369 exit(1);
5370 else if (status == 1) {
5371 fprintf(stderr, "Could not acquire pidfile\n");
5372 exit(1);
5373 } else
5374 exit(0);
5375 } else if (pid < 0)
5376 exit(1);
5378 setsid();
5380 pid = fork();
5381 if (pid > 0)
5382 exit(0);
5383 else if (pid < 0)
5384 exit(1);
5386 umask(027);
5388 signal(SIGTSTP, SIG_IGN);
5389 signal(SIGTTOU, SIG_IGN);
5390 signal(SIGTTIN, SIG_IGN);
5393 #ifdef USE_KVM
5394 if (kvm_enabled()) {
5395 if (kvm_qemu_init() < 0) {
5396 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5397 #ifdef NO_CPU_EMULATION
5398 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5399 exit(1);
5400 #endif
5401 kvm_allowed = 0;
5404 #endif
5406 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5407 if (daemonize) {
5408 uint8_t status = 1;
5409 write(fds[1], &status, 1);
5410 } else
5411 fprintf(stderr, "Could not acquire pid file\n");
5412 exit(1);
5414 #endif
5416 #ifdef CONFIG_KQEMU
5417 if (smp_cpus > 1)
5418 kqemu_allowed = 0;
5419 #endif
5420 linux_boot = (kernel_filename != NULL);
5421 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5423 if (!linux_boot && *kernel_cmdline != '\0') {
5424 fprintf(stderr, "-append only allowed with -kernel option\n");
5425 exit(1);
5428 if (!linux_boot && initrd_filename != NULL) {
5429 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5430 exit(1);
5433 /* boot to floppy or the default cd if no hard disk defined yet */
5434 if (!boot_devices[0]) {
5435 boot_devices = "cad";
5437 setvbuf(stdout, NULL, _IOLBF, 0);
5439 init_timers();
5440 if (init_timer_alarm() < 0) {
5441 fprintf(stderr, "could not initialize alarm timer\n");
5442 exit(1);
5444 if (use_icount && icount_time_shift < 0) {
5445 use_icount = 2;
5446 /* 125MIPS seems a reasonable initial guess at the guest speed.
5447 It will be corrected fairly quickly anyway. */
5448 icount_time_shift = 3;
5449 init_icount_adjust();
5452 #ifdef _WIN32
5453 socket_init();
5454 #endif
5456 /* init network clients */
5457 if (nb_net_clients == 0) {
5458 /* if no clients, we use a default config */
5459 net_clients[nb_net_clients++] = "nic";
5460 #ifdef CONFIG_SLIRP
5461 net_clients[nb_net_clients++] = "user";
5462 #endif
5465 for(i = 0;i < nb_net_clients; i++) {
5466 if (net_client_parse(net_clients[i]) < 0)
5467 exit(1);
5469 net_client_check();
5471 #ifdef TARGET_I386
5472 /* XXX: this should be moved in the PC machine instantiation code */
5473 if (net_boot != 0) {
5474 int netroms = 0;
5475 for (i = 0; i < nb_nics && i < 4; i++) {
5476 const char *model = nd_table[i].model;
5477 char buf[1024];
5478 if (net_boot & (1 << i)) {
5479 if (model == NULL)
5480 model = "rtl8139";
5481 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5482 if (get_image_size(buf) > 0) {
5483 if (nb_option_roms >= MAX_OPTION_ROMS) {
5484 fprintf(stderr, "Too many option ROMs\n");
5485 exit(1);
5487 option_rom[nb_option_roms] = strdup(buf);
5488 nb_option_roms++;
5489 netroms++;
5493 if (netroms == 0) {
5494 fprintf(stderr, "No valid PXE rom found for network device\n");
5495 exit(1);
5498 #endif
5500 /* init the bluetooth world */
5501 for (i = 0; i < nb_bt_opts; i++)
5502 if (bt_parse(bt_opts[i]))
5503 exit(1);
5505 if (ram_size == 0)
5506 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5508 /* init the memory */
5509 if (kvm_enabled()) {
5510 if (kvm_qemu_create_context() < 0) {
5511 fprintf(stderr, "Could not create KVM context\n");
5512 exit(1);
5516 #ifdef CONFIG_KQEMU
5517 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5518 guest ram allocation. It needs to go away. */
5519 if (kqemu_allowed) {
5520 kqemu_phys_ram_size = ram_size + VGA_RAM_SIZE + 4 * 1024 * 1024;
5521 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5522 if (!kqemu_phys_ram_base) {
5523 fprintf(stderr, "Could not allocate physical memory\n");
5524 exit(1);
5527 #endif
5529 /* init the dynamic translator */
5530 cpu_exec_init_all(tb_size * 1024 * 1024);
5532 bdrv_init();
5533 dma_helper_init();
5535 /* we always create the cdrom drive, even if no disk is there */
5537 if (nb_drives_opt < MAX_DRIVES)
5538 drive_add(NULL, CDROM_ALIAS);
5540 /* we always create at least one floppy */
5542 if (nb_drives_opt < MAX_DRIVES)
5543 drive_add(NULL, FD_ALIAS, 0);
5545 /* we always create one sd slot, even if no card is in it */
5547 if (nb_drives_opt < MAX_DRIVES)
5548 drive_add(NULL, SD_ALIAS);
5550 /* open the virtual block devices
5551 * note that migration with device
5552 * hot add/remove is broken.
5554 for(i = 0; i < nb_drives_opt; i++)
5555 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5556 exit(1);
5558 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5559 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5561 #ifndef _WIN32
5562 /* must be after terminal init, SDL library changes signal handlers */
5563 termsig_setup();
5564 #endif
5566 /* Maintain compatibility with multiple stdio monitors */
5567 if (!strcmp(monitor_device,"stdio")) {
5568 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5569 const char *devname = serial_devices[i];
5570 if (devname && !strcmp(devname,"mon:stdio")) {
5571 monitor_device = NULL;
5572 break;
5573 } else if (devname && !strcmp(devname,"stdio")) {
5574 monitor_device = NULL;
5575 serial_devices[i] = "mon:stdio";
5576 break;
5581 if (nb_numa_nodes > 0) {
5582 int i;
5584 if (nb_numa_nodes > smp_cpus) {
5585 nb_numa_nodes = smp_cpus;
5588 /* If no memory size if given for any node, assume the default case
5589 * and distribute the available memory equally across all nodes
5591 for (i = 0; i < nb_numa_nodes; i++) {
5592 if (node_mem[i] != 0)
5593 break;
5595 if (i == nb_numa_nodes) {
5596 uint64_t usedmem = 0;
5598 /* On Linux, the each node's border has to be 8MB aligned,
5599 * the final node gets the rest.
5601 for (i = 0; i < nb_numa_nodes - 1; i++) {
5602 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5603 usedmem += node_mem[i];
5605 node_mem[i] = ram_size - usedmem;
5608 for (i = 0; i < nb_numa_nodes; i++) {
5609 if (node_cpumask[i] != 0)
5610 break;
5612 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5613 * must cope with this anyway, because there are BIOSes out there in
5614 * real machines which also use this scheme.
5616 if (i == nb_numa_nodes) {
5617 for (i = 0; i < smp_cpus; i++) {
5618 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5623 #ifdef KVM_UPSTREAM
5624 if (kvm_enabled()) {
5625 int ret;
5627 ret = kvm_init(smp_cpus);
5628 if (ret < 0) {
5629 fprintf(stderr, "failed to initialize KVM\n");
5630 exit(1);
5633 #endif
5635 if (monitor_device) {
5636 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5637 if (!monitor_hd) {
5638 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5639 exit(1);
5643 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5644 const char *devname = serial_devices[i];
5645 if (devname && strcmp(devname, "none")) {
5646 char label[32];
5647 snprintf(label, sizeof(label), "serial%d", i);
5648 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5649 if (!serial_hds[i]) {
5650 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5651 devname);
5652 exit(1);
5657 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5658 const char *devname = parallel_devices[i];
5659 if (devname && strcmp(devname, "none")) {
5660 char label[32];
5661 snprintf(label, sizeof(label), "parallel%d", i);
5662 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5663 if (!parallel_hds[i]) {
5664 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5665 devname);
5666 exit(1);
5671 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5672 const char *devname = virtio_consoles[i];
5673 if (devname && strcmp(devname, "none")) {
5674 char label[32];
5675 snprintf(label, sizeof(label), "virtcon%d", i);
5676 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5677 if (!virtcon_hds[i]) {
5678 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5679 devname);
5680 exit(1);
5685 if (kvm_enabled())
5686 kvm_init_ap();
5688 machine->init(ram_size, vga_ram_size, boot_devices,
5689 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5692 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5693 for (i = 0; i < nb_numa_nodes; i++) {
5694 if (node_cpumask[i] & (1 << env->cpu_index)) {
5695 env->numa_node = i;
5700 current_machine = machine;
5702 /* Set KVM's vcpu state to qemu's initial CPUState. */
5703 if (kvm_enabled()) {
5704 int ret;
5706 ret = kvm_sync_vcpus();
5707 if (ret < 0) {
5708 fprintf(stderr, "failed to initialize vcpus\n");
5709 exit(1);
5713 /* init USB devices */
5714 if (usb_enabled) {
5715 for(i = 0; i < usb_devices_index; i++) {
5716 if (usb_device_add(usb_devices[i], 0) < 0) {
5717 fprintf(stderr, "Warning: could not add USB device %s\n",
5718 usb_devices[i]);
5723 if (!display_state)
5724 dumb_display_init();
5725 /* just use the first displaystate for the moment */
5726 ds = display_state;
5727 /* terminal init */
5728 if (nographic) {
5729 if (curses) {
5730 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5731 exit(1);
5733 } else {
5734 #if defined(CONFIG_CURSES)
5735 if (curses) {
5736 /* At the moment curses cannot be used with other displays */
5737 curses_display_init(ds, full_screen);
5738 } else
5739 #endif
5741 if (vnc_display != NULL) {
5742 vnc_display_init(ds);
5743 if (vnc_display_open(ds, vnc_display) < 0)
5744 exit(1);
5746 #if defined(CONFIG_SDL)
5747 if (sdl || !vnc_display)
5748 sdl_display_init(ds, full_screen, no_frame);
5749 #elif defined(CONFIG_COCOA)
5750 if (sdl || !vnc_display)
5751 cocoa_display_init(ds, full_screen);
5752 #endif
5755 dpy_resize(ds);
5757 dcl = ds->listeners;
5758 while (dcl != NULL) {
5759 if (dcl->dpy_refresh != NULL) {
5760 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5761 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5763 dcl = dcl->next;
5766 if (nographic || (vnc_display && !sdl)) {
5767 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5768 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5771 text_consoles_set_display(display_state);
5772 qemu_chr_initial_reset();
5774 if (monitor_device && monitor_hd)
5775 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5777 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5778 const char *devname = serial_devices[i];
5779 if (devname && strcmp(devname, "none")) {
5780 char label[32];
5781 snprintf(label, sizeof(label), "serial%d", i);
5782 if (strstart(devname, "vc", 0))
5783 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5787 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5788 const char *devname = parallel_devices[i];
5789 if (devname && strcmp(devname, "none")) {
5790 char label[32];
5791 snprintf(label, sizeof(label), "parallel%d", i);
5792 if (strstart(devname, "vc", 0))
5793 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5797 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5798 const char *devname = virtio_consoles[i];
5799 if (virtcon_hds[i] && devname) {
5800 char label[32];
5801 snprintf(label, sizeof(label), "virtcon%d", i);
5802 if (strstart(devname, "vc", 0))
5803 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5807 #ifdef CONFIG_GDBSTUB
5808 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5809 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5810 gdbstub_dev);
5811 exit(1);
5813 #endif
5815 if (loadvm)
5816 do_loadvm(cur_mon, loadvm);
5818 if (incoming) {
5819 autostart = 0; /* fixme how to deal with -daemonize */
5820 qemu_start_incoming_migration(incoming);
5823 if (autostart)
5824 vm_start();
5826 #ifndef _WIN32
5827 if (daemonize) {
5828 uint8_t status = 0;
5829 ssize_t len;
5831 again1:
5832 len = write(fds[1], &status, 1);
5833 if (len == -1 && (errno == EINTR))
5834 goto again1;
5836 if (len != 1)
5837 exit(1);
5839 chdir("/");
5840 TFR(fd = open("/dev/null", O_RDWR));
5841 if (fd == -1)
5842 exit(1);
5845 if (run_as) {
5846 pwd = getpwnam(run_as);
5847 if (!pwd) {
5848 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5849 exit(1);
5853 if (chroot_dir) {
5854 if (chroot(chroot_dir) < 0) {
5855 fprintf(stderr, "chroot failed\n");
5856 exit(1);
5858 chdir("/");
5861 if (run_as) {
5862 if (setgid(pwd->pw_gid) < 0) {
5863 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5864 exit(1);
5866 if (setuid(pwd->pw_uid) < 0) {
5867 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5868 exit(1);
5870 if (setuid(0) != -1) {
5871 fprintf(stderr, "Dropping privileges failed\n");
5872 exit(1);
5876 if (daemonize) {
5877 dup2(fd, 0);
5878 dup2(fd, 1);
5879 dup2(fd, 2);
5881 close(fd);
5883 #endif
5885 main_loop();
5886 quit_timers();
5887 net_cleanup();
5889 return 0;