Increment version id for CPU save state
[qemu-kvm/fedora.git] / vl.c
blobfbc84a73a447a14c4f9683ab52dd2749baa6af64
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <pwd.h>
37 #include <sys/times.h>
38 #include <sys/wait.h>
39 #include <termios.h>
40 #include <sys/mman.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <sys/vfs.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef HOST_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
75 #include "hpet.h"
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
98 #if defined(__OpenBSD__)
99 #include <util.h>
100 #endif
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
104 #endif
106 #ifdef _WIN32
107 #include <windows.h>
108 #include <malloc.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
113 #endif
115 #ifdef CONFIG_SDL
116 #ifdef __APPLE__
117 #include <SDL/SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/smbios.h"
143 #include "hw/xen.h"
144 #include "bt-host.h"
145 #include "net.h"
146 #include "monitor.h"
147 #include "console.h"
148 #include "sysemu.h"
149 #include "gdbstub.h"
150 #include "qemu-timer.h"
151 #include "qemu-char.h"
152 #include "cache-utils.h"
153 #include "block.h"
154 #include "dma.h"
155 #include "audio/audio.h"
156 #include "migration.h"
157 #include "kvm.h"
158 #include "balloon.h"
159 #include "qemu-kvm.h"
160 #include "hw/device-assignment.h"
162 #include "disas.h"
164 #include "exec-all.h"
166 #include "qemu_socket.h"
168 #if defined(CONFIG_SLIRP)
169 #include "libslirp.h"
170 #endif
172 //#define DEBUG_UNUSED_IOPORT
173 //#define DEBUG_IOPORT
174 //#define DEBUG_NET
175 //#define DEBUG_SLIRP
178 #ifdef DEBUG_IOPORT
179 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
180 #else
181 # define LOG_IOPORT(...) do { } while (0)
182 #endif
184 #define DEFAULT_RAM_SIZE 128
186 /* Max number of USB devices that can be specified on the commandline. */
187 #define MAX_USB_CMDLINE 8
189 /* Max number of bluetooth switches on the commandline. */
190 #define MAX_BT_CMDLINE 10
192 /* XXX: use a two level table to limit memory usage */
193 #define MAX_IOPORTS 65536
195 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
196 const char *bios_name = NULL;
197 static void *ioport_opaque[MAX_IOPORTS];
198 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
199 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
200 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
201 to store the VM snapshots */
202 DriveInfo drives_table[MAX_DRIVES+1];
203 int nb_drives;
204 int extboot_drive = -1;
205 static int vga_ram_size;
206 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
207 static DisplayState *display_state;
208 int nographic;
209 static int curses;
210 static int sdl;
211 const char* keyboard_layout = NULL;
212 int64_t ticks_per_sec;
213 ram_addr_t ram_size;
214 int nb_nics;
215 NICInfo nd_table[MAX_NICS];
216 int vm_running;
217 static int autostart;
218 static int rtc_utc = 1;
219 static int rtc_date_offset = -1; /* -1 means no change */
220 int cirrus_vga_enabled = 1;
221 int std_vga_enabled = 0;
222 int vmsvga_enabled = 0;
223 int xenfb_enabled = 0;
224 #ifdef TARGET_SPARC
225 int graphic_width = 1024;
226 int graphic_height = 768;
227 int graphic_depth = 8;
228 #else
229 int graphic_width = 800;
230 int graphic_height = 600;
231 int graphic_depth = 15;
232 #endif
233 static int full_screen = 0;
234 #ifdef CONFIG_SDL
235 static int no_frame = 0;
236 #endif
237 int no_quit = 0;
238 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
239 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
240 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
241 #ifdef TARGET_I386
242 int win2k_install_hack = 0;
243 int rtc_td_hack = 0;
244 #endif
245 int usb_enabled = 0;
246 int singlestep = 0;
247 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
248 int assigned_devices_index;
249 int smp_cpus = 1;
250 const char *vnc_display;
251 int acpi_enabled = 1;
252 int no_hpet = 0;
253 int fd_bootchk = 1;
254 int no_reboot = 0;
255 int no_shutdown = 0;
256 int cursor_hide = 1;
257 int graphic_rotate = 0;
258 #ifndef _WIN32
259 int daemonize = 0;
260 #endif
261 const char *option_rom[MAX_OPTION_ROMS];
262 int nb_option_roms;
263 int semihosting_enabled = 0;
264 int time_drift_fix = 0;
265 unsigned int kvm_shadow_memory = 0;
266 const char *mem_path = NULL;
267 #ifdef MAP_POPULATE
268 int mem_prealloc = 1; /* force preallocation of physical target memory */
269 #endif
270 long hpagesize = 0;
271 const char *cpu_vendor_string;
272 #ifdef TARGET_ARM
273 int old_param = 0;
274 #endif
275 const char *qemu_name;
276 int alt_grab = 0;
277 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
278 unsigned int nb_prom_envs = 0;
279 const char *prom_envs[MAX_PROM_ENVS];
280 #endif
281 int nb_drives_opt;
282 const char *nvram = NULL;
283 struct drive_opt drives_opt[MAX_DRIVES];
285 int nb_numa_nodes;
286 uint64_t node_mem[MAX_NODES];
287 uint64_t node_cpumask[MAX_NODES];
289 static CPUState *cur_cpu;
290 static CPUState *next_cpu;
291 static int event_pending = 1;
292 /* Conversion factor from emulated instructions to virtual clock ticks. */
293 static int icount_time_shift;
294 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
295 #define MAX_ICOUNT_SHIFT 10
296 /* Compensate for varying guest execution speed. */
297 static int64_t qemu_icount_bias;
298 static QEMUTimer *icount_rt_timer;
299 static QEMUTimer *icount_vm_timer;
300 static QEMUTimer *nographic_timer;
302 uint8_t qemu_uuid[16];
304 /* KVM runs the main loop in a separate thread. If we update one of the lists
305 * that are polled before or after select(), we need to make sure to break out
306 * of the select() to ensure the new item is serviced.
308 static void main_loop_break(void)
310 if (kvm_enabled())
311 qemu_kvm_notify_work();
314 /***********************************************************/
315 /* x86 ISA bus support */
317 target_phys_addr_t isa_mem_base = 0;
318 PicState2 *isa_pic;
320 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
321 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
323 static uint32_t ioport_read(int index, uint32_t address)
325 static IOPortReadFunc *default_func[3] = {
326 default_ioport_readb,
327 default_ioport_readw,
328 default_ioport_readl
330 IOPortReadFunc *func = ioport_read_table[index][address];
331 if (!func)
332 func = default_func[index];
333 return func(ioport_opaque[address], address);
336 static void ioport_write(int index, uint32_t address, uint32_t data)
338 static IOPortWriteFunc *default_func[3] = {
339 default_ioport_writeb,
340 default_ioport_writew,
341 default_ioport_writel
343 IOPortWriteFunc *func = ioport_write_table[index][address];
344 if (!func)
345 func = default_func[index];
346 func(ioport_opaque[address], address, data);
349 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
351 #ifdef DEBUG_UNUSED_IOPORT
352 fprintf(stderr, "unused inb: port=0x%04x\n", address);
353 #endif
354 return 0xff;
357 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
359 #ifdef DEBUG_UNUSED_IOPORT
360 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
361 #endif
364 /* default is to make two byte accesses */
365 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
367 uint32_t data;
368 data = ioport_read(0, address);
369 address = (address + 1) & (MAX_IOPORTS - 1);
370 data |= ioport_read(0, address) << 8;
371 return data;
374 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
376 ioport_write(0, address, data & 0xff);
377 address = (address + 1) & (MAX_IOPORTS - 1);
378 ioport_write(0, address, (data >> 8) & 0xff);
381 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
383 #ifdef DEBUG_UNUSED_IOPORT
384 fprintf(stderr, "unused inl: port=0x%04x\n", address);
385 #endif
386 return 0xffffffff;
389 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
391 #ifdef DEBUG_UNUSED_IOPORT
392 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
393 #endif
396 /* size is the word size in byte */
397 int register_ioport_read(int start, int length, int size,
398 IOPortReadFunc *func, void *opaque)
400 int i, bsize;
402 if (size == 1) {
403 bsize = 0;
404 } else if (size == 2) {
405 bsize = 1;
406 } else if (size == 4) {
407 bsize = 2;
408 } else {
409 hw_error("register_ioport_read: invalid size");
410 return -1;
412 for(i = start; i < start + length; i += size) {
413 ioport_read_table[bsize][i] = func;
414 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
415 hw_error("register_ioport_read: invalid opaque");
416 ioport_opaque[i] = opaque;
418 return 0;
421 /* size is the word size in byte */
422 int register_ioport_write(int start, int length, int size,
423 IOPortWriteFunc *func, void *opaque)
425 int i, bsize;
427 if (size == 1) {
428 bsize = 0;
429 } else if (size == 2) {
430 bsize = 1;
431 } else if (size == 4) {
432 bsize = 2;
433 } else {
434 hw_error("register_ioport_write: invalid size");
435 return -1;
437 for(i = start; i < start + length; i += size) {
438 ioport_write_table[bsize][i] = func;
439 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
440 hw_error("register_ioport_write: invalid opaque");
441 ioport_opaque[i] = opaque;
443 return 0;
446 void isa_unassign_ioport(int start, int length)
448 int i;
450 for(i = start; i < start + length; i++) {
451 ioport_read_table[0][i] = default_ioport_readb;
452 ioport_read_table[1][i] = default_ioport_readw;
453 ioport_read_table[2][i] = default_ioport_readl;
455 ioport_write_table[0][i] = default_ioport_writeb;
456 ioport_write_table[1][i] = default_ioport_writew;
457 ioport_write_table[2][i] = default_ioport_writel;
459 ioport_opaque[i] = NULL;
463 /***********************************************************/
465 void cpu_outb(CPUState *env, int addr, int val)
467 LOG_IOPORT("outb: %04x %02x\n", addr, val);
468 ioport_write(0, addr, val);
469 #ifdef CONFIG_KQEMU
470 if (env)
471 env->last_io_time = cpu_get_time_fast();
472 #endif
475 void cpu_outw(CPUState *env, int addr, int val)
477 LOG_IOPORT("outw: %04x %04x\n", addr, val);
478 ioport_write(1, addr, val);
479 #ifdef CONFIG_KQEMU
480 if (env)
481 env->last_io_time = cpu_get_time_fast();
482 #endif
485 void cpu_outl(CPUState *env, int addr, int val)
487 LOG_IOPORT("outl: %04x %08x\n", addr, val);
488 ioport_write(2, addr, val);
489 #ifdef CONFIG_KQEMU
490 if (env)
491 env->last_io_time = cpu_get_time_fast();
492 #endif
495 int cpu_inb(CPUState *env, int addr)
497 int val;
498 val = ioport_read(0, addr);
499 LOG_IOPORT("inb : %04x %02x\n", addr, val);
500 #ifdef CONFIG_KQEMU
501 if (env)
502 env->last_io_time = cpu_get_time_fast();
503 #endif
504 return val;
507 int cpu_inw(CPUState *env, int addr)
509 int val;
510 val = ioport_read(1, addr);
511 LOG_IOPORT("inw : %04x %04x\n", addr, val);
512 #ifdef CONFIG_KQEMU
513 if (env)
514 env->last_io_time = cpu_get_time_fast();
515 #endif
516 return val;
519 int cpu_inl(CPUState *env, int addr)
521 int val;
522 val = ioport_read(2, addr);
523 LOG_IOPORT("inl : %04x %08x\n", addr, val);
524 #ifdef CONFIG_KQEMU
525 if (env)
526 env->last_io_time = cpu_get_time_fast();
527 #endif
528 return val;
531 /***********************************************************/
532 void hw_error(const char *fmt, ...)
534 va_list ap;
535 CPUState *env;
537 va_start(ap, fmt);
538 fprintf(stderr, "qemu: hardware error: ");
539 vfprintf(stderr, fmt, ap);
540 fprintf(stderr, "\n");
541 for(env = first_cpu; env != NULL; env = env->next_cpu) {
542 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
543 #ifdef TARGET_I386
544 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
545 #else
546 cpu_dump_state(env, stderr, fprintf, 0);
547 #endif
549 va_end(ap);
550 abort();
553 /***************/
554 /* ballooning */
556 static QEMUBalloonEvent *qemu_balloon_event;
557 void *qemu_balloon_event_opaque;
559 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
561 qemu_balloon_event = func;
562 qemu_balloon_event_opaque = opaque;
565 void qemu_balloon(ram_addr_t target)
567 if (qemu_balloon_event)
568 qemu_balloon_event(qemu_balloon_event_opaque, target);
571 ram_addr_t qemu_balloon_status(void)
573 if (qemu_balloon_event)
574 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
575 return 0;
578 /***********************************************************/
579 /* keyboard/mouse */
581 static QEMUPutKBDEvent *qemu_put_kbd_event;
582 static void *qemu_put_kbd_event_opaque;
583 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
584 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
586 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
588 qemu_put_kbd_event_opaque = opaque;
589 qemu_put_kbd_event = func;
592 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
593 void *opaque, int absolute,
594 const char *name)
596 QEMUPutMouseEntry *s, *cursor;
598 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
600 s->qemu_put_mouse_event = func;
601 s->qemu_put_mouse_event_opaque = opaque;
602 s->qemu_put_mouse_event_absolute = absolute;
603 s->qemu_put_mouse_event_name = qemu_strdup(name);
604 s->next = NULL;
606 if (!qemu_put_mouse_event_head) {
607 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
608 return s;
611 cursor = qemu_put_mouse_event_head;
612 while (cursor->next != NULL)
613 cursor = cursor->next;
615 cursor->next = s;
616 qemu_put_mouse_event_current = s;
618 return s;
621 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
623 QEMUPutMouseEntry *prev = NULL, *cursor;
625 if (!qemu_put_mouse_event_head || entry == NULL)
626 return;
628 cursor = qemu_put_mouse_event_head;
629 while (cursor != NULL && cursor != entry) {
630 prev = cursor;
631 cursor = cursor->next;
634 if (cursor == NULL) // does not exist or list empty
635 return;
636 else if (prev == NULL) { // entry is head
637 qemu_put_mouse_event_head = cursor->next;
638 if (qemu_put_mouse_event_current == entry)
639 qemu_put_mouse_event_current = cursor->next;
640 qemu_free(entry->qemu_put_mouse_event_name);
641 qemu_free(entry);
642 return;
645 prev->next = entry->next;
647 if (qemu_put_mouse_event_current == entry)
648 qemu_put_mouse_event_current = prev;
650 qemu_free(entry->qemu_put_mouse_event_name);
651 qemu_free(entry);
654 void kbd_put_keycode(int keycode)
656 if (qemu_put_kbd_event) {
657 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
661 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
663 QEMUPutMouseEvent *mouse_event;
664 void *mouse_event_opaque;
665 int width;
667 if (!qemu_put_mouse_event_current) {
668 return;
671 mouse_event =
672 qemu_put_mouse_event_current->qemu_put_mouse_event;
673 mouse_event_opaque =
674 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
676 if (mouse_event) {
677 if (graphic_rotate) {
678 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
679 width = 0x7fff;
680 else
681 width = graphic_width - 1;
682 mouse_event(mouse_event_opaque,
683 width - dy, dx, dz, buttons_state);
684 } else
685 mouse_event(mouse_event_opaque,
686 dx, dy, dz, buttons_state);
690 int kbd_mouse_is_absolute(void)
692 if (!qemu_put_mouse_event_current)
693 return 0;
695 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
698 void do_info_mice(Monitor *mon)
700 QEMUPutMouseEntry *cursor;
701 int index = 0;
703 if (!qemu_put_mouse_event_head) {
704 monitor_printf(mon, "No mouse devices connected\n");
705 return;
708 monitor_printf(mon, "Mouse devices available:\n");
709 cursor = qemu_put_mouse_event_head;
710 while (cursor != NULL) {
711 monitor_printf(mon, "%c Mouse #%d: %s\n",
712 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
713 index, cursor->qemu_put_mouse_event_name);
714 index++;
715 cursor = cursor->next;
719 void do_mouse_set(Monitor *mon, int index)
721 QEMUPutMouseEntry *cursor;
722 int i = 0;
724 if (!qemu_put_mouse_event_head) {
725 monitor_printf(mon, "No mouse devices connected\n");
726 return;
729 cursor = qemu_put_mouse_event_head;
730 while (cursor != NULL && index != i) {
731 i++;
732 cursor = cursor->next;
735 if (cursor != NULL)
736 qemu_put_mouse_event_current = cursor;
737 else
738 monitor_printf(mon, "Mouse at given index not found\n");
741 /* compute with 96 bit intermediate result: (a*b)/c */
742 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
744 union {
745 uint64_t ll;
746 struct {
747 #ifdef WORDS_BIGENDIAN
748 uint32_t high, low;
749 #else
750 uint32_t low, high;
751 #endif
752 } l;
753 } u, res;
754 uint64_t rl, rh;
756 u.ll = a;
757 rl = (uint64_t)u.l.low * (uint64_t)b;
758 rh = (uint64_t)u.l.high * (uint64_t)b;
759 rh += (rl >> 32);
760 res.l.high = rh / c;
761 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
762 return res.ll;
765 /***********************************************************/
766 /* real time host monotonic timer */
768 #define QEMU_TIMER_BASE 1000000000LL
770 #ifdef WIN32
772 static int64_t clock_freq;
774 static void init_get_clock(void)
776 LARGE_INTEGER freq;
777 int ret;
778 ret = QueryPerformanceFrequency(&freq);
779 if (ret == 0) {
780 fprintf(stderr, "Could not calibrate ticks\n");
781 exit(1);
783 clock_freq = freq.QuadPart;
786 static int64_t get_clock(void)
788 LARGE_INTEGER ti;
789 QueryPerformanceCounter(&ti);
790 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
793 #else
795 static int use_rt_clock;
797 static void init_get_clock(void)
799 use_rt_clock = 0;
800 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
801 || defined(__DragonFly__)
803 struct timespec ts;
804 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
805 use_rt_clock = 1;
808 #endif
811 static int64_t get_clock(void)
813 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
814 || defined(__DragonFly__)
815 if (use_rt_clock) {
816 struct timespec ts;
817 clock_gettime(CLOCK_MONOTONIC, &ts);
818 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
819 } else
820 #endif
822 /* XXX: using gettimeofday leads to problems if the date
823 changes, so it should be avoided. */
824 struct timeval tv;
825 gettimeofday(&tv, NULL);
826 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
829 #endif
831 /* Return the virtual CPU time, based on the instruction counter. */
832 static int64_t cpu_get_icount(void)
834 int64_t icount;
835 CPUState *env = cpu_single_env;;
836 icount = qemu_icount;
837 if (env) {
838 if (!can_do_io(env))
839 fprintf(stderr, "Bad clock read\n");
840 icount -= (env->icount_decr.u16.low + env->icount_extra);
842 return qemu_icount_bias + (icount << icount_time_shift);
845 /***********************************************************/
846 /* guest cycle counter */
848 static int64_t cpu_ticks_prev;
849 static int64_t cpu_ticks_offset;
850 static int64_t cpu_clock_offset;
851 static int cpu_ticks_enabled;
853 /* return the host CPU cycle counter and handle stop/restart */
854 int64_t cpu_get_ticks(void)
856 if (use_icount) {
857 return cpu_get_icount();
859 if (!cpu_ticks_enabled) {
860 return cpu_ticks_offset;
861 } else {
862 int64_t ticks;
863 ticks = cpu_get_real_ticks();
864 if (cpu_ticks_prev > ticks) {
865 /* Note: non increasing ticks may happen if the host uses
866 software suspend */
867 cpu_ticks_offset += cpu_ticks_prev - ticks;
869 cpu_ticks_prev = ticks;
870 return ticks + cpu_ticks_offset;
874 /* return the host CPU monotonic timer and handle stop/restart */
875 static int64_t cpu_get_clock(void)
877 int64_t ti;
878 if (!cpu_ticks_enabled) {
879 return cpu_clock_offset;
880 } else {
881 ti = get_clock();
882 return ti + cpu_clock_offset;
886 /* enable cpu_get_ticks() */
887 void cpu_enable_ticks(void)
889 if (!cpu_ticks_enabled) {
890 cpu_ticks_offset -= cpu_get_real_ticks();
891 cpu_clock_offset -= get_clock();
892 cpu_ticks_enabled = 1;
896 /* disable cpu_get_ticks() : the clock is stopped. You must not call
897 cpu_get_ticks() after that. */
898 void cpu_disable_ticks(void)
900 if (cpu_ticks_enabled) {
901 cpu_ticks_offset = cpu_get_ticks();
902 cpu_clock_offset = cpu_get_clock();
903 cpu_ticks_enabled = 0;
907 /***********************************************************/
908 /* timers */
910 #define QEMU_TIMER_REALTIME 0
911 #define QEMU_TIMER_VIRTUAL 1
913 struct QEMUClock {
914 int type;
915 /* XXX: add frequency */
918 struct QEMUTimer {
919 QEMUClock *clock;
920 int64_t expire_time;
921 QEMUTimerCB *cb;
922 void *opaque;
923 struct QEMUTimer *next;
926 struct qemu_alarm_timer {
927 char const *name;
928 unsigned int flags;
930 int (*start)(struct qemu_alarm_timer *t);
931 void (*stop)(struct qemu_alarm_timer *t);
932 void (*rearm)(struct qemu_alarm_timer *t);
933 void *priv;
936 #define ALARM_FLAG_DYNTICKS 0x1
937 #define ALARM_FLAG_EXPIRED 0x2
939 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
941 return t->flags & ALARM_FLAG_DYNTICKS;
944 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
946 if (!alarm_has_dynticks(t))
947 return;
949 t->rearm(t);
952 /* TODO: MIN_TIMER_REARM_US should be optimized */
953 #define MIN_TIMER_REARM_US 250
955 static struct qemu_alarm_timer *alarm_timer;
956 #ifndef _WIN32
957 static int alarm_timer_rfd, alarm_timer_wfd;
958 #endif
960 #ifdef _WIN32
962 struct qemu_alarm_win32 {
963 MMRESULT timerId;
964 HANDLE host_alarm;
965 unsigned int period;
966 } alarm_win32_data = {0, NULL, -1};
968 static int win32_start_timer(struct qemu_alarm_timer *t);
969 static void win32_stop_timer(struct qemu_alarm_timer *t);
970 static void win32_rearm_timer(struct qemu_alarm_timer *t);
972 #else
974 static int unix_start_timer(struct qemu_alarm_timer *t);
975 static void unix_stop_timer(struct qemu_alarm_timer *t);
977 #ifdef __linux__
979 static int dynticks_start_timer(struct qemu_alarm_timer *t);
980 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
981 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
983 static int hpet_start_timer(struct qemu_alarm_timer *t);
984 static void hpet_stop_timer(struct qemu_alarm_timer *t);
986 static int rtc_start_timer(struct qemu_alarm_timer *t);
987 static void rtc_stop_timer(struct qemu_alarm_timer *t);
989 #endif /* __linux__ */
991 #endif /* _WIN32 */
993 /* Correlation between real and virtual time is always going to be
994 fairly approximate, so ignore small variation.
995 When the guest is idle real and virtual time will be aligned in
996 the IO wait loop. */
997 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
999 static void icount_adjust(void)
1001 int64_t cur_time;
1002 int64_t cur_icount;
1003 int64_t delta;
1004 static int64_t last_delta;
1005 /* If the VM is not running, then do nothing. */
1006 if (!vm_running)
1007 return;
1009 cur_time = cpu_get_clock();
1010 cur_icount = qemu_get_clock(vm_clock);
1011 delta = cur_icount - cur_time;
1012 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1013 if (delta > 0
1014 && last_delta + ICOUNT_WOBBLE < delta * 2
1015 && icount_time_shift > 0) {
1016 /* The guest is getting too far ahead. Slow time down. */
1017 icount_time_shift--;
1019 if (delta < 0
1020 && last_delta - ICOUNT_WOBBLE > delta * 2
1021 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1022 /* The guest is getting too far behind. Speed time up. */
1023 icount_time_shift++;
1025 last_delta = delta;
1026 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1029 static void icount_adjust_rt(void * opaque)
1031 qemu_mod_timer(icount_rt_timer,
1032 qemu_get_clock(rt_clock) + 1000);
1033 icount_adjust();
1036 static void icount_adjust_vm(void * opaque)
1038 qemu_mod_timer(icount_vm_timer,
1039 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1040 icount_adjust();
1043 static void init_icount_adjust(void)
1045 /* Have both realtime and virtual time triggers for speed adjustment.
1046 The realtime trigger catches emulated time passing too slowly,
1047 the virtual time trigger catches emulated time passing too fast.
1048 Realtime triggers occur even when idle, so use them less frequently
1049 than VM triggers. */
1050 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1051 qemu_mod_timer(icount_rt_timer,
1052 qemu_get_clock(rt_clock) + 1000);
1053 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1054 qemu_mod_timer(icount_vm_timer,
1055 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1058 static struct qemu_alarm_timer alarm_timers[] = {
1059 #ifndef _WIN32
1060 #ifdef __linux__
1061 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1062 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1063 /* HPET - if available - is preferred */
1064 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1065 /* ...otherwise try RTC */
1066 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1067 #endif
1068 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1069 #else
1070 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1071 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1072 {"win32", 0, win32_start_timer,
1073 win32_stop_timer, NULL, &alarm_win32_data},
1074 #endif
1075 {NULL, }
1078 static void show_available_alarms(void)
1080 int i;
1082 printf("Available alarm timers, in order of precedence:\n");
1083 for (i = 0; alarm_timers[i].name; i++)
1084 printf("%s\n", alarm_timers[i].name);
1087 static void configure_alarms(char const *opt)
1089 int i;
1090 int cur = 0;
1091 int count = ARRAY_SIZE(alarm_timers) - 1;
1092 char *arg;
1093 char *name;
1094 struct qemu_alarm_timer tmp;
1096 if (!strcmp(opt, "?")) {
1097 show_available_alarms();
1098 exit(0);
1101 arg = strdup(opt);
1103 /* Reorder the array */
1104 name = strtok(arg, ",");
1105 while (name) {
1106 for (i = 0; i < count && alarm_timers[i].name; i++) {
1107 if (!strcmp(alarm_timers[i].name, name))
1108 break;
1111 if (i == count) {
1112 fprintf(stderr, "Unknown clock %s\n", name);
1113 goto next;
1116 if (i < cur)
1117 /* Ignore */
1118 goto next;
1120 /* Swap */
1121 tmp = alarm_timers[i];
1122 alarm_timers[i] = alarm_timers[cur];
1123 alarm_timers[cur] = tmp;
1125 cur++;
1126 next:
1127 name = strtok(NULL, ",");
1130 free(arg);
1132 if (cur) {
1133 /* Disable remaining timers */
1134 for (i = cur; i < count; i++)
1135 alarm_timers[i].name = NULL;
1136 } else {
1137 show_available_alarms();
1138 exit(1);
1142 QEMUClock *rt_clock;
1143 QEMUClock *vm_clock;
1145 static QEMUTimer *active_timers[2];
1147 static QEMUClock *qemu_new_clock(int type)
1149 QEMUClock *clock;
1150 clock = qemu_mallocz(sizeof(QEMUClock));
1151 clock->type = type;
1152 return clock;
1155 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1157 QEMUTimer *ts;
1159 ts = qemu_mallocz(sizeof(QEMUTimer));
1160 ts->clock = clock;
1161 ts->cb = cb;
1162 ts->opaque = opaque;
1163 return ts;
1166 void qemu_free_timer(QEMUTimer *ts)
1168 qemu_free(ts);
1171 /* stop a timer, but do not dealloc it */
1172 void qemu_del_timer(QEMUTimer *ts)
1174 QEMUTimer **pt, *t;
1176 /* NOTE: this code must be signal safe because
1177 qemu_timer_expired() can be called from a signal. */
1178 pt = &active_timers[ts->clock->type];
1179 for(;;) {
1180 t = *pt;
1181 if (!t)
1182 break;
1183 if (t == ts) {
1184 *pt = t->next;
1185 break;
1187 pt = &t->next;
1191 /* modify the current timer so that it will be fired when current_time
1192 >= expire_time. The corresponding callback will be called. */
1193 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1195 QEMUTimer **pt, *t;
1197 qemu_del_timer(ts);
1199 /* add the timer in the sorted list */
1200 /* NOTE: this code must be signal safe because
1201 qemu_timer_expired() can be called from a signal. */
1202 pt = &active_timers[ts->clock->type];
1203 for(;;) {
1204 t = *pt;
1205 if (!t)
1206 break;
1207 if (t->expire_time > expire_time)
1208 break;
1209 pt = &t->next;
1211 ts->expire_time = expire_time;
1212 ts->next = *pt;
1213 *pt = ts;
1215 /* Rearm if necessary */
1216 if (pt == &active_timers[ts->clock->type]) {
1217 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1218 qemu_rearm_alarm_timer(alarm_timer);
1220 /* Interrupt execution to force deadline recalculation. */
1221 if (use_icount && cpu_single_env) {
1222 cpu_exit(cpu_single_env);
1227 int qemu_timer_pending(QEMUTimer *ts)
1229 QEMUTimer *t;
1230 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1231 if (t == ts)
1232 return 1;
1234 return 0;
1237 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1239 if (!timer_head)
1240 return 0;
1241 return (timer_head->expire_time <= current_time);
1244 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1246 QEMUTimer *ts;
1248 for(;;) {
1249 ts = *ptimer_head;
1250 if (!ts || ts->expire_time > current_time)
1251 break;
1252 /* remove timer from the list before calling the callback */
1253 *ptimer_head = ts->next;
1254 ts->next = NULL;
1256 /* run the callback (the timer list can be modified) */
1257 ts->cb(ts->opaque);
1261 int64_t qemu_get_clock(QEMUClock *clock)
1263 switch(clock->type) {
1264 case QEMU_TIMER_REALTIME:
1265 return get_clock() / 1000000;
1266 default:
1267 case QEMU_TIMER_VIRTUAL:
1268 if (use_icount) {
1269 return cpu_get_icount();
1270 } else {
1271 return cpu_get_clock();
1276 static void init_timers(void)
1278 init_get_clock();
1279 ticks_per_sec = QEMU_TIMER_BASE;
1280 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1281 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1284 /* save a timer */
1285 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1287 uint64_t expire_time;
1289 if (qemu_timer_pending(ts)) {
1290 expire_time = ts->expire_time;
1291 } else {
1292 expire_time = -1;
1294 qemu_put_be64(f, expire_time);
1297 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1299 uint64_t expire_time;
1301 expire_time = qemu_get_be64(f);
1302 if (expire_time != -1) {
1303 qemu_mod_timer(ts, expire_time);
1304 } else {
1305 qemu_del_timer(ts);
1309 static void timer_save(QEMUFile *f, void *opaque)
1311 if (cpu_ticks_enabled) {
1312 hw_error("cannot save state if virtual timers are running");
1314 qemu_put_be64(f, cpu_ticks_offset);
1315 qemu_put_be64(f, ticks_per_sec);
1316 qemu_put_be64(f, cpu_clock_offset);
1319 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1321 if (version_id != 1 && version_id != 2)
1322 return -EINVAL;
1323 if (cpu_ticks_enabled) {
1324 return -EINVAL;
1326 cpu_ticks_offset=qemu_get_be64(f);
1327 ticks_per_sec=qemu_get_be64(f);
1328 if (version_id == 2) {
1329 cpu_clock_offset=qemu_get_be64(f);
1331 return 0;
1334 #ifdef _WIN32
1335 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1336 DWORD_PTR dwUser, DWORD_PTR dw1,
1337 DWORD_PTR dw2)
1338 #else
1339 static void host_alarm_handler(int host_signum)
1340 #endif
1342 #if 0
1343 #define DISP_FREQ 1000
1345 static int64_t delta_min = INT64_MAX;
1346 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1347 static int count;
1348 ti = qemu_get_clock(vm_clock);
1349 if (last_clock != 0) {
1350 delta = ti - last_clock;
1351 if (delta < delta_min)
1352 delta_min = delta;
1353 if (delta > delta_max)
1354 delta_max = delta;
1355 delta_cum += delta;
1356 if (++count == DISP_FREQ) {
1357 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1358 muldiv64(delta_min, 1000000, ticks_per_sec),
1359 muldiv64(delta_max, 1000000, ticks_per_sec),
1360 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1361 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1362 count = 0;
1363 delta_min = INT64_MAX;
1364 delta_max = 0;
1365 delta_cum = 0;
1368 last_clock = ti;
1370 #endif
1371 if (1 ||
1372 alarm_has_dynticks(alarm_timer) ||
1373 (!use_icount &&
1374 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1375 qemu_get_clock(vm_clock))) ||
1376 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1377 qemu_get_clock(rt_clock))) {
1378 CPUState *env = next_cpu;
1380 #ifdef _WIN32
1381 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1382 SetEvent(data->host_alarm);
1383 #else
1384 static const char byte = 0;
1385 write(alarm_timer_wfd, &byte, sizeof(byte));
1386 #endif
1387 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1389 if (env) {
1390 /* stop the currently executing cpu because a timer occured */
1391 cpu_exit(env);
1392 #ifdef CONFIG_KQEMU
1393 if (env->kqemu_enabled) {
1394 kqemu_cpu_interrupt(env);
1396 #endif
1398 event_pending = 1;
1402 static int64_t qemu_next_deadline(void)
1404 int64_t delta;
1406 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1407 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1408 qemu_get_clock(vm_clock);
1409 } else {
1410 /* To avoid problems with overflow limit this to 2^32. */
1411 delta = INT32_MAX;
1414 if (delta < 0)
1415 delta = 0;
1417 return delta;
1420 #if defined(__linux__) || defined(_WIN32)
1421 static uint64_t qemu_next_deadline_dyntick(void)
1423 int64_t delta;
1424 int64_t rtdelta;
1426 if (use_icount)
1427 delta = INT32_MAX;
1428 else
1429 delta = (qemu_next_deadline() + 999) / 1000;
1431 if (active_timers[QEMU_TIMER_REALTIME]) {
1432 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1433 qemu_get_clock(rt_clock))*1000;
1434 if (rtdelta < delta)
1435 delta = rtdelta;
1438 if (delta < MIN_TIMER_REARM_US)
1439 delta = MIN_TIMER_REARM_US;
1441 return delta;
1443 #endif
1445 #ifndef _WIN32
1447 /* Sets a specific flag */
1448 static int fcntl_setfl(int fd, int flag)
1450 int flags;
1452 flags = fcntl(fd, F_GETFL);
1453 if (flags == -1)
1454 return -errno;
1456 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1457 return -errno;
1459 return 0;
1462 #if defined(__linux__)
1464 #define RTC_FREQ 1024
1466 static void enable_sigio_timer(int fd)
1468 struct sigaction act;
1470 /* timer signal */
1471 sigfillset(&act.sa_mask);
1472 act.sa_flags = 0;
1473 act.sa_handler = host_alarm_handler;
1475 sigaction(SIGIO, &act, NULL);
1476 fcntl_setfl(fd, O_ASYNC);
1477 fcntl(fd, F_SETOWN, getpid());
1480 static int hpet_start_timer(struct qemu_alarm_timer *t)
1482 struct hpet_info info;
1483 int r, fd;
1485 fd = open("/dev/hpet", O_RDONLY);
1486 if (fd < 0)
1487 return -1;
1489 /* Set frequency */
1490 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1491 if (r < 0) {
1492 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1493 "error, but for better emulation accuracy type:\n"
1494 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1495 goto fail;
1498 /* Check capabilities */
1499 r = ioctl(fd, HPET_INFO, &info);
1500 if (r < 0)
1501 goto fail;
1503 /* Enable periodic mode */
1504 r = ioctl(fd, HPET_EPI, 0);
1505 if (info.hi_flags && (r < 0))
1506 goto fail;
1508 /* Enable interrupt */
1509 r = ioctl(fd, HPET_IE_ON, 0);
1510 if (r < 0)
1511 goto fail;
1513 enable_sigio_timer(fd);
1514 t->priv = (void *)(long)fd;
1516 return 0;
1517 fail:
1518 close(fd);
1519 return -1;
1522 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1524 int fd = (long)t->priv;
1526 close(fd);
1529 static int rtc_start_timer(struct qemu_alarm_timer *t)
1531 int rtc_fd;
1532 unsigned long current_rtc_freq = 0;
1534 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1535 if (rtc_fd < 0)
1536 return -1;
1537 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1538 if (current_rtc_freq != RTC_FREQ &&
1539 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1540 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1541 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1542 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1543 goto fail;
1545 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1546 fail:
1547 close(rtc_fd);
1548 return -1;
1551 enable_sigio_timer(rtc_fd);
1553 t->priv = (void *)(long)rtc_fd;
1555 return 0;
1558 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1560 int rtc_fd = (long)t->priv;
1562 close(rtc_fd);
1565 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1567 struct sigevent ev;
1568 timer_t host_timer;
1569 struct sigaction act;
1571 sigfillset(&act.sa_mask);
1572 act.sa_flags = 0;
1573 act.sa_handler = host_alarm_handler;
1575 sigaction(SIGALRM, &act, NULL);
1577 ev.sigev_value.sival_int = 0;
1578 ev.sigev_notify = SIGEV_SIGNAL;
1579 ev.sigev_signo = SIGALRM;
1581 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1582 perror("timer_create");
1584 /* disable dynticks */
1585 fprintf(stderr, "Dynamic Ticks disabled\n");
1587 return -1;
1590 t->priv = (void *)(long)host_timer;
1592 return 0;
1595 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1597 timer_t host_timer = (timer_t)(long)t->priv;
1599 timer_delete(host_timer);
1602 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1604 timer_t host_timer = (timer_t)(long)t->priv;
1605 struct itimerspec timeout;
1606 int64_t nearest_delta_us = INT64_MAX;
1607 int64_t current_us;
1609 if (!active_timers[QEMU_TIMER_REALTIME] &&
1610 !active_timers[QEMU_TIMER_VIRTUAL])
1611 return;
1613 nearest_delta_us = qemu_next_deadline_dyntick();
1615 /* check whether a timer is already running */
1616 if (timer_gettime(host_timer, &timeout)) {
1617 perror("gettime");
1618 fprintf(stderr, "Internal timer error: aborting\n");
1619 exit(1);
1621 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1622 if (current_us && current_us <= nearest_delta_us)
1623 return;
1625 timeout.it_interval.tv_sec = 0;
1626 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1627 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1628 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1629 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1630 perror("settime");
1631 fprintf(stderr, "Internal timer error: aborting\n");
1632 exit(1);
1636 #endif /* defined(__linux__) */
1638 static int unix_start_timer(struct qemu_alarm_timer *t)
1640 struct sigaction act;
1641 struct itimerval itv;
1642 int err;
1644 /* timer signal */
1645 sigfillset(&act.sa_mask);
1646 act.sa_flags = 0;
1647 act.sa_handler = host_alarm_handler;
1649 sigaction(SIGALRM, &act, NULL);
1651 itv.it_interval.tv_sec = 0;
1652 /* for i386 kernel 2.6 to get 1 ms */
1653 itv.it_interval.tv_usec = 999;
1654 itv.it_value.tv_sec = 0;
1655 itv.it_value.tv_usec = 10 * 1000;
1657 err = setitimer(ITIMER_REAL, &itv, NULL);
1658 if (err)
1659 return -1;
1661 return 0;
1664 static void unix_stop_timer(struct qemu_alarm_timer *t)
1666 struct itimerval itv;
1668 memset(&itv, 0, sizeof(itv));
1669 setitimer(ITIMER_REAL, &itv, NULL);
1672 #endif /* !defined(_WIN32) */
1674 static void try_to_rearm_timer(void *opaque)
1676 struct qemu_alarm_timer *t = opaque;
1677 #ifndef _WIN32
1678 ssize_t len;
1680 /* Drain the notify pipe */
1681 do {
1682 char buffer[512];
1683 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1684 } while ((len == -1 && errno == EINTR) || len > 0);
1685 #endif
1687 if (t->flags & ALARM_FLAG_EXPIRED) {
1688 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1689 qemu_rearm_alarm_timer(alarm_timer);
1693 #ifdef _WIN32
1695 static int win32_start_timer(struct qemu_alarm_timer *t)
1697 TIMECAPS tc;
1698 struct qemu_alarm_win32 *data = t->priv;
1699 UINT flags;
1701 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1702 if (!data->host_alarm) {
1703 perror("Failed CreateEvent");
1704 return -1;
1707 memset(&tc, 0, sizeof(tc));
1708 timeGetDevCaps(&tc, sizeof(tc));
1710 if (data->period < tc.wPeriodMin)
1711 data->period = tc.wPeriodMin;
1713 timeBeginPeriod(data->period);
1715 flags = TIME_CALLBACK_FUNCTION;
1716 if (alarm_has_dynticks(t))
1717 flags |= TIME_ONESHOT;
1718 else
1719 flags |= TIME_PERIODIC;
1721 data->timerId = timeSetEvent(1, // interval (ms)
1722 data->period, // resolution
1723 host_alarm_handler, // function
1724 (DWORD)t, // parameter
1725 flags);
1727 if (!data->timerId) {
1728 perror("Failed to initialize win32 alarm timer");
1730 timeEndPeriod(data->period);
1731 CloseHandle(data->host_alarm);
1732 return -1;
1735 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1737 return 0;
1740 static void win32_stop_timer(struct qemu_alarm_timer *t)
1742 struct qemu_alarm_win32 *data = t->priv;
1744 timeKillEvent(data->timerId);
1745 timeEndPeriod(data->period);
1747 CloseHandle(data->host_alarm);
1750 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1752 struct qemu_alarm_win32 *data = t->priv;
1753 uint64_t nearest_delta_us;
1755 if (!active_timers[QEMU_TIMER_REALTIME] &&
1756 !active_timers[QEMU_TIMER_VIRTUAL])
1757 return;
1759 nearest_delta_us = qemu_next_deadline_dyntick();
1760 nearest_delta_us /= 1000;
1762 timeKillEvent(data->timerId);
1764 data->timerId = timeSetEvent(1,
1765 data->period,
1766 host_alarm_handler,
1767 (DWORD)t,
1768 TIME_ONESHOT | TIME_PERIODIC);
1770 if (!data->timerId) {
1771 perror("Failed to re-arm win32 alarm timer");
1773 timeEndPeriod(data->period);
1774 CloseHandle(data->host_alarm);
1775 exit(1);
1779 #endif /* _WIN32 */
1781 static int init_timer_alarm(void)
1783 struct qemu_alarm_timer *t = NULL;
1784 int i, err = -1;
1786 #ifndef _WIN32
1787 int fds[2];
1789 err = pipe(fds);
1790 if (err == -1)
1791 return -errno;
1793 err = fcntl_setfl(fds[0], O_NONBLOCK);
1794 if (err < 0)
1795 goto fail;
1797 err = fcntl_setfl(fds[1], O_NONBLOCK);
1798 if (err < 0)
1799 goto fail;
1801 alarm_timer_rfd = fds[0];
1802 alarm_timer_wfd = fds[1];
1803 #endif
1805 for (i = 0; alarm_timers[i].name; i++) {
1806 t = &alarm_timers[i];
1808 err = t->start(t);
1809 if (!err)
1810 break;
1813 if (err) {
1814 err = -ENOENT;
1815 goto fail;
1818 #ifndef _WIN32
1819 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1820 try_to_rearm_timer, NULL, t);
1821 #endif
1823 alarm_timer = t;
1825 return 0;
1827 fail:
1828 #ifndef _WIN32
1829 close(fds[0]);
1830 close(fds[1]);
1831 #endif
1832 return err;
1835 static void quit_timers(void)
1837 alarm_timer->stop(alarm_timer);
1838 alarm_timer = NULL;
1841 /***********************************************************/
1842 /* host time/date access */
1843 void qemu_get_timedate(struct tm *tm, int offset)
1845 time_t ti;
1846 struct tm *ret;
1848 time(&ti);
1849 ti += offset;
1850 if (rtc_date_offset == -1) {
1851 if (rtc_utc)
1852 ret = gmtime(&ti);
1853 else
1854 ret = localtime(&ti);
1855 } else {
1856 ti -= rtc_date_offset;
1857 ret = gmtime(&ti);
1860 memcpy(tm, ret, sizeof(struct tm));
1863 int qemu_timedate_diff(struct tm *tm)
1865 time_t seconds;
1867 if (rtc_date_offset == -1)
1868 if (rtc_utc)
1869 seconds = mktimegm(tm);
1870 else
1871 seconds = mktime(tm);
1872 else
1873 seconds = mktimegm(tm) + rtc_date_offset;
1875 return seconds - time(NULL);
1878 #ifdef _WIN32
1879 static void socket_cleanup(void)
1881 WSACleanup();
1884 static int socket_init(void)
1886 WSADATA Data;
1887 int ret, err;
1889 ret = WSAStartup(MAKEWORD(2,2), &Data);
1890 if (ret != 0) {
1891 err = WSAGetLastError();
1892 fprintf(stderr, "WSAStartup: %d\n", err);
1893 return -1;
1895 atexit(socket_cleanup);
1896 return 0;
1898 #endif
1900 const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
1902 char *q;
1904 q = buf;
1905 while (*p != '\0' && *p != delim) {
1906 if (q && (q - buf) < buf_size - 1)
1907 *q++ = *p;
1908 p++;
1910 if (q)
1911 *q = '\0';
1913 return p;
1916 const char *get_opt_value(char *buf, int buf_size, const char *p)
1918 char *q;
1920 q = buf;
1921 while (*p != '\0') {
1922 if (*p == ',') {
1923 if (*(p + 1) != ',')
1924 break;
1925 p++;
1927 if (q && (q - buf) < buf_size - 1)
1928 *q++ = *p;
1929 p++;
1931 if (q)
1932 *q = '\0';
1934 return p;
1937 int get_param_value(char *buf, int buf_size,
1938 const char *tag, const char *str)
1940 const char *p;
1941 char option[128];
1943 p = str;
1944 for(;;) {
1945 p = get_opt_name(option, sizeof(option), p, '=');
1946 if (*p != '=')
1947 break;
1948 p++;
1949 if (!strcmp(tag, option)) {
1950 (void)get_opt_value(buf, buf_size, p);
1951 return strlen(buf);
1952 } else {
1953 p = get_opt_value(NULL, 0, p);
1955 if (*p != ',')
1956 break;
1957 p++;
1959 return 0;
1962 int check_params(char *buf, int buf_size,
1963 const char * const *params, const char *str)
1965 const char *p;
1966 int i;
1968 p = str;
1969 while (*p != '\0') {
1970 p = get_opt_name(buf, buf_size, p, '=');
1971 if (*p != '=')
1972 return -1;
1973 p++;
1974 for(i = 0; params[i] != NULL; i++)
1975 if (!strcmp(params[i], buf))
1976 break;
1977 if (params[i] == NULL)
1978 return -1;
1979 p = get_opt_value(NULL, 0, p);
1980 if (*p != ',')
1981 break;
1982 p++;
1984 return 0;
1987 /***********************************************************/
1988 /* Bluetooth support */
1989 static int nb_hcis;
1990 static int cur_hci;
1991 static struct HCIInfo *hci_table[MAX_NICS];
1993 static struct bt_vlan_s {
1994 struct bt_scatternet_s net;
1995 int id;
1996 struct bt_vlan_s *next;
1997 } *first_bt_vlan;
1999 /* find or alloc a new bluetooth "VLAN" */
2000 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
2002 struct bt_vlan_s **pvlan, *vlan;
2003 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
2004 if (vlan->id == id)
2005 return &vlan->net;
2007 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
2008 vlan->id = id;
2009 pvlan = &first_bt_vlan;
2010 while (*pvlan != NULL)
2011 pvlan = &(*pvlan)->next;
2012 *pvlan = vlan;
2013 return &vlan->net;
2016 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2020 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2022 return -ENOTSUP;
2025 static struct HCIInfo null_hci = {
2026 .cmd_send = null_hci_send,
2027 .sco_send = null_hci_send,
2028 .acl_send = null_hci_send,
2029 .bdaddr_set = null_hci_addr_set,
2032 struct HCIInfo *qemu_next_hci(void)
2034 if (cur_hci == nb_hcis)
2035 return &null_hci;
2037 return hci_table[cur_hci++];
2040 static struct HCIInfo *hci_init(const char *str)
2042 char *endp;
2043 struct bt_scatternet_s *vlan = 0;
2045 if (!strcmp(str, "null"))
2046 /* null */
2047 return &null_hci;
2048 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2049 /* host[:hciN] */
2050 return bt_host_hci(str[4] ? str + 5 : "hci0");
2051 else if (!strncmp(str, "hci", 3)) {
2052 /* hci[,vlan=n] */
2053 if (str[3]) {
2054 if (!strncmp(str + 3, ",vlan=", 6)) {
2055 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2056 if (*endp)
2057 vlan = 0;
2059 } else
2060 vlan = qemu_find_bt_vlan(0);
2061 if (vlan)
2062 return bt_new_hci(vlan);
2065 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2067 return 0;
2070 static int bt_hci_parse(const char *str)
2072 struct HCIInfo *hci;
2073 bdaddr_t bdaddr;
2075 if (nb_hcis >= MAX_NICS) {
2076 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2077 return -1;
2080 hci = hci_init(str);
2081 if (!hci)
2082 return -1;
2084 bdaddr.b[0] = 0x52;
2085 bdaddr.b[1] = 0x54;
2086 bdaddr.b[2] = 0x00;
2087 bdaddr.b[3] = 0x12;
2088 bdaddr.b[4] = 0x34;
2089 bdaddr.b[5] = 0x56 + nb_hcis;
2090 hci->bdaddr_set(hci, bdaddr.b);
2092 hci_table[nb_hcis++] = hci;
2094 return 0;
2097 static void bt_vhci_add(int vlan_id)
2099 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2101 if (!vlan->slave)
2102 fprintf(stderr, "qemu: warning: adding a VHCI to "
2103 "an empty scatternet %i\n", vlan_id);
2105 bt_vhci_init(bt_new_hci(vlan));
2108 static struct bt_device_s *bt_device_add(const char *opt)
2110 struct bt_scatternet_s *vlan;
2111 int vlan_id = 0;
2112 char *endp = strstr(opt, ",vlan=");
2113 int len = (endp ? endp - opt : strlen(opt)) + 1;
2114 char devname[10];
2116 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2118 if (endp) {
2119 vlan_id = strtol(endp + 6, &endp, 0);
2120 if (*endp) {
2121 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2122 return 0;
2126 vlan = qemu_find_bt_vlan(vlan_id);
2128 if (!vlan->slave)
2129 fprintf(stderr, "qemu: warning: adding a slave device to "
2130 "an empty scatternet %i\n", vlan_id);
2132 if (!strcmp(devname, "keyboard"))
2133 return bt_keyboard_init(vlan);
2135 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2136 return 0;
2139 static int bt_parse(const char *opt)
2141 const char *endp, *p;
2142 int vlan;
2144 if (strstart(opt, "hci", &endp)) {
2145 if (!*endp || *endp == ',') {
2146 if (*endp)
2147 if (!strstart(endp, ",vlan=", 0))
2148 opt = endp + 1;
2150 return bt_hci_parse(opt);
2152 } else if (strstart(opt, "vhci", &endp)) {
2153 if (!*endp || *endp == ',') {
2154 if (*endp) {
2155 if (strstart(endp, ",vlan=", &p)) {
2156 vlan = strtol(p, (char **) &endp, 0);
2157 if (*endp) {
2158 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2159 return 1;
2161 } else {
2162 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2163 return 1;
2165 } else
2166 vlan = 0;
2168 bt_vhci_add(vlan);
2169 return 0;
2171 } else if (strstart(opt, "device:", &endp))
2172 return !bt_device_add(endp);
2174 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2175 return 1;
2178 /***********************************************************/
2179 /* QEMU Block devices */
2181 #define HD_ALIAS "index=%d,media=disk"
2182 #define CDROM_ALIAS "index=2,media=cdrom"
2183 #define FD_ALIAS "index=%d,if=floppy"
2184 #define PFLASH_ALIAS "if=pflash"
2185 #define MTD_ALIAS "if=mtd"
2186 #define SD_ALIAS "index=0,if=sd"
2188 static int drive_opt_get_free_idx(void)
2190 int index;
2192 for (index = 0; index < MAX_DRIVES; index++)
2193 if (!drives_opt[index].used) {
2194 drives_opt[index].used = 1;
2195 return index;
2198 return -1;
2201 static int drive_get_free_idx(void)
2203 int index;
2205 for (index = 0; index < MAX_DRIVES; index++)
2206 if (!drives_table[index].used) {
2207 drives_table[index].used = 1;
2208 return index;
2211 return -1;
2214 int drive_add(const char *file, const char *fmt, ...)
2216 va_list ap;
2217 int index = drive_opt_get_free_idx();
2219 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2220 fprintf(stderr, "qemu: too many drives\n");
2221 return -1;
2224 drives_opt[index].file = file;
2225 va_start(ap, fmt);
2226 vsnprintf(drives_opt[index].opt,
2227 sizeof(drives_opt[0].opt), fmt, ap);
2228 va_end(ap);
2230 nb_drives_opt++;
2231 return index;
2234 void drive_remove(int index)
2236 drives_opt[index].used = 0;
2237 nb_drives_opt--;
2240 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2242 int index;
2244 /* seek interface, bus and unit */
2246 for (index = 0; index < MAX_DRIVES; index++)
2247 if (drives_table[index].type == type &&
2248 drives_table[index].bus == bus &&
2249 drives_table[index].unit == unit &&
2250 drives_table[index].used)
2251 return index;
2253 return -1;
2256 int drive_get_max_bus(BlockInterfaceType type)
2258 int max_bus;
2259 int index;
2261 max_bus = -1;
2262 for (index = 0; index < nb_drives; index++) {
2263 if(drives_table[index].type == type &&
2264 drives_table[index].bus > max_bus)
2265 max_bus = drives_table[index].bus;
2267 return max_bus;
2270 const char *drive_get_serial(BlockDriverState *bdrv)
2272 int index;
2274 for (index = 0; index < nb_drives; index++)
2275 if (drives_table[index].bdrv == bdrv)
2276 return drives_table[index].serial;
2278 return "\0";
2281 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2283 int index;
2285 for (index = 0; index < nb_drives; index++)
2286 if (drives_table[index].bdrv == bdrv)
2287 return drives_table[index].onerror;
2289 return BLOCK_ERR_STOP_ENOSPC;
2292 static void bdrv_format_print(void *opaque, const char *name)
2294 fprintf(stderr, " %s", name);
2297 void drive_uninit(BlockDriverState *bdrv)
2299 int i;
2301 for (i = 0; i < MAX_DRIVES; i++)
2302 if (drives_table[i].bdrv == bdrv) {
2303 drives_table[i].bdrv = NULL;
2304 drives_table[i].used = 0;
2305 drive_remove(drives_table[i].drive_opt_idx);
2306 nb_drives--;
2307 break;
2311 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2313 char buf[128];
2314 char file[1024];
2315 char devname[128];
2316 char serial[21];
2317 const char *mediastr = "";
2318 BlockInterfaceType type;
2319 enum { MEDIA_DISK, MEDIA_CDROM } media;
2320 int bus_id, unit_id;
2321 int cyls, heads, secs, translation;
2322 BlockDriverState *bdrv;
2323 BlockDriver *drv = NULL;
2324 QEMUMachine *machine = opaque;
2325 int max_devs;
2326 int index;
2327 int cache;
2328 int bdrv_flags, onerror;
2329 int drives_table_idx;
2330 char *str = arg->opt;
2331 static const char * const params[] = { "bus", "unit", "if", "index",
2332 "cyls", "heads", "secs", "trans",
2333 "media", "snapshot", "file",
2334 "cache", "format", "serial", "werror",
2335 "boot", NULL };
2337 if (check_params(buf, sizeof(buf), params, str) < 0) {
2338 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2339 buf, str);
2340 return -1;
2343 file[0] = 0;
2344 cyls = heads = secs = 0;
2345 bus_id = 0;
2346 unit_id = -1;
2347 translation = BIOS_ATA_TRANSLATION_AUTO;
2348 index = -1;
2349 cache = 3;
2351 if (machine->use_scsi) {
2352 type = IF_SCSI;
2353 max_devs = MAX_SCSI_DEVS;
2354 pstrcpy(devname, sizeof(devname), "scsi");
2355 } else {
2356 type = IF_IDE;
2357 max_devs = MAX_IDE_DEVS;
2358 pstrcpy(devname, sizeof(devname), "ide");
2360 media = MEDIA_DISK;
2362 /* extract parameters */
2364 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2365 bus_id = strtol(buf, NULL, 0);
2366 if (bus_id < 0) {
2367 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2368 return -1;
2372 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2373 unit_id = strtol(buf, NULL, 0);
2374 if (unit_id < 0) {
2375 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2376 return -1;
2380 if (get_param_value(buf, sizeof(buf), "if", str)) {
2381 pstrcpy(devname, sizeof(devname), buf);
2382 if (!strcmp(buf, "ide")) {
2383 type = IF_IDE;
2384 max_devs = MAX_IDE_DEVS;
2385 } else if (!strcmp(buf, "scsi")) {
2386 type = IF_SCSI;
2387 max_devs = MAX_SCSI_DEVS;
2388 } else if (!strcmp(buf, "floppy")) {
2389 type = IF_FLOPPY;
2390 max_devs = 0;
2391 } else if (!strcmp(buf, "pflash")) {
2392 type = IF_PFLASH;
2393 max_devs = 0;
2394 } else if (!strcmp(buf, "mtd")) {
2395 type = IF_MTD;
2396 max_devs = 0;
2397 } else if (!strcmp(buf, "sd")) {
2398 type = IF_SD;
2399 max_devs = 0;
2400 } else if (!strcmp(buf, "virtio")) {
2401 type = IF_VIRTIO;
2402 max_devs = 0;
2403 } else if (!strcmp(buf, "xen")) {
2404 type = IF_XEN;
2405 max_devs = 0;
2406 } else {
2407 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2408 return -1;
2412 if (get_param_value(buf, sizeof(buf), "index", str)) {
2413 index = strtol(buf, NULL, 0);
2414 if (index < 0) {
2415 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2416 return -1;
2420 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2421 cyls = strtol(buf, NULL, 0);
2424 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2425 heads = strtol(buf, NULL, 0);
2428 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2429 secs = strtol(buf, NULL, 0);
2432 if (cyls || heads || secs) {
2433 if (cyls < 1 || cyls > 16383) {
2434 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2435 return -1;
2437 if (heads < 1 || heads > 16) {
2438 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2439 return -1;
2441 if (secs < 1 || secs > 63) {
2442 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2443 return -1;
2447 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2448 if (!cyls) {
2449 fprintf(stderr,
2450 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2451 str);
2452 return -1;
2454 if (!strcmp(buf, "none"))
2455 translation = BIOS_ATA_TRANSLATION_NONE;
2456 else if (!strcmp(buf, "lba"))
2457 translation = BIOS_ATA_TRANSLATION_LBA;
2458 else if (!strcmp(buf, "auto"))
2459 translation = BIOS_ATA_TRANSLATION_AUTO;
2460 else {
2461 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2462 return -1;
2466 if (get_param_value(buf, sizeof(buf), "media", str)) {
2467 if (!strcmp(buf, "disk")) {
2468 media = MEDIA_DISK;
2469 } else if (!strcmp(buf, "cdrom")) {
2470 if (cyls || secs || heads) {
2471 fprintf(stderr,
2472 "qemu: '%s' invalid physical CHS format\n", str);
2473 return -1;
2475 media = MEDIA_CDROM;
2476 } else {
2477 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2478 return -1;
2482 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2483 if (!strcmp(buf, "on"))
2484 snapshot = 1;
2485 else if (!strcmp(buf, "off"))
2486 snapshot = 0;
2487 else {
2488 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2489 return -1;
2493 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2494 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2495 cache = 0;
2496 else if (!strcmp(buf, "writethrough"))
2497 cache = 1;
2498 else if (!strcmp(buf, "writeback"))
2499 cache = 2;
2500 else {
2501 fprintf(stderr, "qemu: invalid cache option\n");
2502 return -1;
2506 if (get_param_value(buf, sizeof(buf), "format", str)) {
2507 if (strcmp(buf, "?") == 0) {
2508 fprintf(stderr, "qemu: Supported formats:");
2509 bdrv_iterate_format(bdrv_format_print, NULL);
2510 fprintf(stderr, "\n");
2511 return -1;
2513 drv = bdrv_find_format(buf);
2514 if (!drv) {
2515 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2516 return -1;
2520 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2521 if (!strcmp(buf, "on")) {
2522 if (extboot_drive != -1) {
2523 fprintf(stderr, "qemu: two bootable drives specified\n");
2524 return -1;
2526 extboot_drive = nb_drives;
2527 } else if (strcmp(buf, "off")) {
2528 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2529 return -1;
2533 if (arg->file == NULL)
2534 get_param_value(file, sizeof(file), "file", str);
2535 else
2536 pstrcpy(file, sizeof(file), arg->file);
2538 if (!get_param_value(serial, sizeof(serial), "serial", str))
2539 memset(serial, 0, sizeof(serial));
2541 onerror = BLOCK_ERR_STOP_ENOSPC;
2542 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2543 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2544 fprintf(stderr, "werror is no supported by this format\n");
2545 return -1;
2547 if (!strcmp(buf, "ignore"))
2548 onerror = BLOCK_ERR_IGNORE;
2549 else if (!strcmp(buf, "enospc"))
2550 onerror = BLOCK_ERR_STOP_ENOSPC;
2551 else if (!strcmp(buf, "stop"))
2552 onerror = BLOCK_ERR_STOP_ANY;
2553 else if (!strcmp(buf, "report"))
2554 onerror = BLOCK_ERR_REPORT;
2555 else {
2556 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2557 return -1;
2561 /* compute bus and unit according index */
2563 if (index != -1) {
2564 if (bus_id != 0 || unit_id != -1) {
2565 fprintf(stderr,
2566 "qemu: '%s' index cannot be used with bus and unit\n", str);
2567 return -1;
2569 if (max_devs == 0)
2571 unit_id = index;
2572 bus_id = 0;
2573 } else {
2574 unit_id = index % max_devs;
2575 bus_id = index / max_devs;
2579 /* if user doesn't specify a unit_id,
2580 * try to find the first free
2583 if (unit_id == -1) {
2584 unit_id = 0;
2585 while (drive_get_index(type, bus_id, unit_id) != -1) {
2586 unit_id++;
2587 if (max_devs && unit_id >= max_devs) {
2588 unit_id -= max_devs;
2589 bus_id++;
2594 /* check unit id */
2596 if (max_devs && unit_id >= max_devs) {
2597 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2598 str, unit_id, max_devs - 1);
2599 return -1;
2603 * ignore multiple definitions
2606 if (drive_get_index(type, bus_id, unit_id) != -1)
2607 return -2;
2609 /* init */
2611 if (type == IF_IDE || type == IF_SCSI)
2612 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2613 if (max_devs)
2614 snprintf(buf, sizeof(buf), "%s%i%s%i",
2615 devname, bus_id, mediastr, unit_id);
2616 else
2617 snprintf(buf, sizeof(buf), "%s%s%i",
2618 devname, mediastr, unit_id);
2619 bdrv = bdrv_new(buf);
2620 drives_table_idx = drive_get_free_idx();
2621 drives_table[drives_table_idx].bdrv = bdrv;
2622 drives_table[drives_table_idx].type = type;
2623 drives_table[drives_table_idx].bus = bus_id;
2624 drives_table[drives_table_idx].unit = unit_id;
2625 drives_table[drives_table_idx].onerror = onerror;
2626 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2627 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2628 nb_drives++;
2630 switch(type) {
2631 case IF_IDE:
2632 case IF_SCSI:
2633 case IF_XEN:
2634 switch(media) {
2635 case MEDIA_DISK:
2636 if (cyls != 0) {
2637 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2638 bdrv_set_translation_hint(bdrv, translation);
2640 break;
2641 case MEDIA_CDROM:
2642 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2643 break;
2645 break;
2646 case IF_SD:
2647 /* FIXME: This isn't really a floppy, but it's a reasonable
2648 approximation. */
2649 case IF_FLOPPY:
2650 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2651 break;
2652 case IF_PFLASH:
2653 case IF_MTD:
2654 case IF_VIRTIO:
2655 break;
2657 if (!file[0])
2658 return -2;
2659 bdrv_flags = 0;
2660 if (snapshot) {
2661 bdrv_flags |= BDRV_O_SNAPSHOT;
2662 cache = 2; /* always use write-back with snapshot */
2664 if (cache == 0) /* no caching */
2665 bdrv_flags |= BDRV_O_NOCACHE;
2666 else if (cache == 2) /* write-back */
2667 bdrv_flags |= BDRV_O_CACHE_WB;
2668 else if (cache == 3) /* not specified */
2669 bdrv_flags |= BDRV_O_CACHE_DEF;
2670 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2671 fprintf(stderr, "qemu: could not open disk image %s\n",
2672 file);
2673 return -1;
2675 if (bdrv_key_required(bdrv))
2676 autostart = 0;
2677 return drives_table_idx;
2680 static void numa_add(const char *optarg)
2682 char option[128];
2683 char *endptr;
2684 unsigned long long value, endvalue;
2685 int nodenr;
2687 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2688 if (!strcmp(option, "node")) {
2689 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2690 nodenr = nb_numa_nodes;
2691 } else {
2692 nodenr = strtoull(option, NULL, 10);
2695 if (get_param_value(option, 128, "mem", optarg) == 0) {
2696 node_mem[nodenr] = 0;
2697 } else {
2698 value = strtoull(option, &endptr, 0);
2699 switch (*endptr) {
2700 case 0: case 'M': case 'm':
2701 value <<= 20;
2702 break;
2703 case 'G': case 'g':
2704 value <<= 30;
2705 break;
2707 node_mem[nodenr] = value;
2709 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2710 node_cpumask[nodenr] = 0;
2711 } else {
2712 value = strtoull(option, &endptr, 10);
2713 if (value >= 64) {
2714 value = 63;
2715 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2716 } else {
2717 if (*endptr == '-') {
2718 endvalue = strtoull(endptr+1, &endptr, 10);
2719 if (endvalue >= 63) {
2720 endvalue = 62;
2721 fprintf(stderr,
2722 "only 63 CPUs in NUMA mode supported.\n");
2724 value = (1 << (endvalue + 1)) - (1 << value);
2725 } else {
2726 value = 1 << value;
2729 node_cpumask[nodenr] = value;
2731 nb_numa_nodes++;
2733 return;
2736 /***********************************************************/
2737 /* USB devices */
2739 static USBPort *used_usb_ports;
2740 static USBPort *free_usb_ports;
2742 /* ??? Maybe change this to register a hub to keep track of the topology. */
2743 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2744 usb_attachfn attach)
2746 port->opaque = opaque;
2747 port->index = index;
2748 port->attach = attach;
2749 port->next = free_usb_ports;
2750 free_usb_ports = port;
2753 int usb_device_add_dev(USBDevice *dev)
2755 USBPort *port;
2757 /* Find a USB port to add the device to. */
2758 port = free_usb_ports;
2759 if (!port->next) {
2760 USBDevice *hub;
2762 /* Create a new hub and chain it on. */
2763 free_usb_ports = NULL;
2764 port->next = used_usb_ports;
2765 used_usb_ports = port;
2767 hub = usb_hub_init(VM_USB_HUB_SIZE);
2768 usb_attach(port, hub);
2769 port = free_usb_ports;
2772 free_usb_ports = port->next;
2773 port->next = used_usb_ports;
2774 used_usb_ports = port;
2775 usb_attach(port, dev);
2776 return 0;
2779 static void usb_msd_password_cb(void *opaque, int err)
2781 USBDevice *dev = opaque;
2783 if (!err)
2784 usb_device_add_dev(dev);
2785 else
2786 dev->handle_destroy(dev);
2789 static int usb_device_add(const char *devname, int is_hotplug)
2791 const char *p;
2792 USBDevice *dev;
2794 if (!free_usb_ports)
2795 return -1;
2797 if (strstart(devname, "host:", &p)) {
2798 dev = usb_host_device_open(p);
2799 } else if (!strcmp(devname, "mouse")) {
2800 dev = usb_mouse_init();
2801 } else if (!strcmp(devname, "tablet")) {
2802 dev = usb_tablet_init();
2803 } else if (!strcmp(devname, "keyboard")) {
2804 dev = usb_keyboard_init();
2805 } else if (strstart(devname, "disk:", &p)) {
2806 BlockDriverState *bs;
2808 dev = usb_msd_init(p);
2809 if (!dev)
2810 return -1;
2811 bs = usb_msd_get_bdrv(dev);
2812 if (bdrv_key_required(bs)) {
2813 autostart = 0;
2814 if (is_hotplug) {
2815 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2816 dev);
2817 return 0;
2820 } else if (!strcmp(devname, "wacom-tablet")) {
2821 dev = usb_wacom_init();
2822 } else if (strstart(devname, "serial:", &p)) {
2823 dev = usb_serial_init(p);
2824 #ifdef CONFIG_BRLAPI
2825 } else if (!strcmp(devname, "braille")) {
2826 dev = usb_baum_init();
2827 #endif
2828 } else if (strstart(devname, "net:", &p)) {
2829 int nic = nb_nics;
2831 if (net_client_init("nic", p) < 0)
2832 return -1;
2833 nd_table[nic].model = "usb";
2834 dev = usb_net_init(&nd_table[nic]);
2835 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2836 dev = usb_bt_init(devname[2] ? hci_init(p) :
2837 bt_new_hci(qemu_find_bt_vlan(0)));
2838 } else {
2839 return -1;
2841 if (!dev)
2842 return -1;
2844 return usb_device_add_dev(dev);
2847 int usb_device_del_addr(int bus_num, int addr)
2849 USBPort *port;
2850 USBPort **lastp;
2851 USBDevice *dev;
2853 if (!used_usb_ports)
2854 return -1;
2856 if (bus_num != 0)
2857 return -1;
2859 lastp = &used_usb_ports;
2860 port = used_usb_ports;
2861 while (port && port->dev->addr != addr) {
2862 lastp = &port->next;
2863 port = port->next;
2866 if (!port)
2867 return -1;
2869 dev = port->dev;
2870 *lastp = port->next;
2871 usb_attach(port, NULL);
2872 dev->handle_destroy(dev);
2873 port->next = free_usb_ports;
2874 free_usb_ports = port;
2875 return 0;
2878 static int usb_device_del(const char *devname)
2880 int bus_num, addr;
2881 const char *p;
2883 if (strstart(devname, "host:", &p))
2884 return usb_host_device_close(p);
2886 if (!used_usb_ports)
2887 return -1;
2889 p = strchr(devname, '.');
2890 if (!p)
2891 return -1;
2892 bus_num = strtoul(devname, NULL, 0);
2893 addr = strtoul(p + 1, NULL, 0);
2895 return usb_device_del_addr(bus_num, addr);
2898 void do_usb_add(Monitor *mon, const char *devname)
2900 usb_device_add(devname, 1);
2903 void do_usb_del(Monitor *mon, const char *devname)
2905 usb_device_del(devname);
2908 void usb_info(Monitor *mon)
2910 USBDevice *dev;
2911 USBPort *port;
2912 const char *speed_str;
2914 if (!usb_enabled) {
2915 monitor_printf(mon, "USB support not enabled\n");
2916 return;
2919 for (port = used_usb_ports; port; port = port->next) {
2920 dev = port->dev;
2921 if (!dev)
2922 continue;
2923 switch(dev->speed) {
2924 case USB_SPEED_LOW:
2925 speed_str = "1.5";
2926 break;
2927 case USB_SPEED_FULL:
2928 speed_str = "12";
2929 break;
2930 case USB_SPEED_HIGH:
2931 speed_str = "480";
2932 break;
2933 default:
2934 speed_str = "?";
2935 break;
2937 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2938 0, dev->addr, speed_str, dev->devname);
2942 /***********************************************************/
2943 /* PCMCIA/Cardbus */
2945 static struct pcmcia_socket_entry_s {
2946 struct pcmcia_socket_s *socket;
2947 struct pcmcia_socket_entry_s *next;
2948 } *pcmcia_sockets = 0;
2950 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2952 struct pcmcia_socket_entry_s *entry;
2954 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2955 entry->socket = socket;
2956 entry->next = pcmcia_sockets;
2957 pcmcia_sockets = entry;
2960 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2962 struct pcmcia_socket_entry_s *entry, **ptr;
2964 ptr = &pcmcia_sockets;
2965 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2966 if (entry->socket == socket) {
2967 *ptr = entry->next;
2968 qemu_free(entry);
2972 void pcmcia_info(Monitor *mon)
2974 struct pcmcia_socket_entry_s *iter;
2976 if (!pcmcia_sockets)
2977 monitor_printf(mon, "No PCMCIA sockets\n");
2979 for (iter = pcmcia_sockets; iter; iter = iter->next)
2980 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2981 iter->socket->attached ? iter->socket->card_string :
2982 "Empty");
2985 /***********************************************************/
2986 /* register display */
2988 struct DisplayAllocator default_allocator = {
2989 defaultallocator_create_displaysurface,
2990 defaultallocator_resize_displaysurface,
2991 defaultallocator_free_displaysurface
2994 void register_displaystate(DisplayState *ds)
2996 DisplayState **s;
2997 s = &display_state;
2998 while (*s != NULL)
2999 s = &(*s)->next;
3000 ds->next = NULL;
3001 *s = ds;
3004 DisplayState *get_displaystate(void)
3006 return display_state;
3009 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
3011 if(ds->allocator == &default_allocator) ds->allocator = da;
3012 return ds->allocator;
3015 /* dumb display */
3017 static void dumb_display_init(void)
3019 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
3020 ds->allocator = &default_allocator;
3021 ds->surface = qemu_create_displaysurface(ds, 640, 480);
3022 register_displaystate(ds);
3025 /***********************************************************/
3026 /* I/O handling */
3028 typedef struct IOHandlerRecord {
3029 int fd;
3030 IOCanRWHandler *fd_read_poll;
3031 IOHandler *fd_read;
3032 IOHandler *fd_write;
3033 int deleted;
3034 void *opaque;
3035 /* temporary data */
3036 struct pollfd *ufd;
3037 struct IOHandlerRecord *next;
3038 } IOHandlerRecord;
3040 static IOHandlerRecord *first_io_handler;
3042 /* XXX: fd_read_poll should be suppressed, but an API change is
3043 necessary in the character devices to suppress fd_can_read(). */
3044 int qemu_set_fd_handler2(int fd,
3045 IOCanRWHandler *fd_read_poll,
3046 IOHandler *fd_read,
3047 IOHandler *fd_write,
3048 void *opaque)
3050 IOHandlerRecord **pioh, *ioh;
3052 if (!fd_read && !fd_write) {
3053 pioh = &first_io_handler;
3054 for(;;) {
3055 ioh = *pioh;
3056 if (ioh == NULL)
3057 break;
3058 if (ioh->fd == fd) {
3059 ioh->deleted = 1;
3060 break;
3062 pioh = &ioh->next;
3064 } else {
3065 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3066 if (ioh->fd == fd)
3067 goto found;
3069 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3070 ioh->next = first_io_handler;
3071 first_io_handler = ioh;
3072 found:
3073 ioh->fd = fd;
3074 ioh->fd_read_poll = fd_read_poll;
3075 ioh->fd_read = fd_read;
3076 ioh->fd_write = fd_write;
3077 ioh->opaque = opaque;
3078 ioh->deleted = 0;
3080 main_loop_break();
3081 return 0;
3084 int qemu_set_fd_handler(int fd,
3085 IOHandler *fd_read,
3086 IOHandler *fd_write,
3087 void *opaque)
3089 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3092 #ifdef _WIN32
3093 /***********************************************************/
3094 /* Polling handling */
3096 typedef struct PollingEntry {
3097 PollingFunc *func;
3098 void *opaque;
3099 struct PollingEntry *next;
3100 } PollingEntry;
3102 static PollingEntry *first_polling_entry;
3104 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3106 PollingEntry **ppe, *pe;
3107 pe = qemu_mallocz(sizeof(PollingEntry));
3108 pe->func = func;
3109 pe->opaque = opaque;
3110 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3111 *ppe = pe;
3112 return 0;
3115 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3117 PollingEntry **ppe, *pe;
3118 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3119 pe = *ppe;
3120 if (pe->func == func && pe->opaque == opaque) {
3121 *ppe = pe->next;
3122 qemu_free(pe);
3123 break;
3128 /***********************************************************/
3129 /* Wait objects support */
3130 typedef struct WaitObjects {
3131 int num;
3132 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3133 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3134 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3135 } WaitObjects;
3137 static WaitObjects wait_objects = {0};
3139 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3141 WaitObjects *w = &wait_objects;
3143 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3144 return -1;
3145 w->events[w->num] = handle;
3146 w->func[w->num] = func;
3147 w->opaque[w->num] = opaque;
3148 w->num++;
3149 return 0;
3152 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3154 int i, found;
3155 WaitObjects *w = &wait_objects;
3157 found = 0;
3158 for (i = 0; i < w->num; i++) {
3159 if (w->events[i] == handle)
3160 found = 1;
3161 if (found) {
3162 w->events[i] = w->events[i + 1];
3163 w->func[i] = w->func[i + 1];
3164 w->opaque[i] = w->opaque[i + 1];
3167 if (found)
3168 w->num--;
3170 #endif
3172 /***********************************************************/
3173 /* ram save/restore */
3175 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3177 int v;
3179 v = qemu_get_byte(f);
3180 switch(v) {
3181 case 0:
3182 if (qemu_get_buffer(f, buf, len) != len)
3183 return -EIO;
3184 break;
3185 case 1:
3186 v = qemu_get_byte(f);
3187 memset(buf, v, len);
3188 break;
3189 default:
3190 return -EINVAL;
3193 if (qemu_file_has_error(f))
3194 return -EIO;
3196 return 0;
3199 static int ram_load_v1(QEMUFile *f, void *opaque)
3201 int ret;
3202 ram_addr_t i;
3204 if (qemu_get_be32(f) != last_ram_offset)
3205 return -EINVAL;
3206 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3207 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3208 continue;
3209 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3210 if (ret)
3211 return ret;
3213 return 0;
3216 #define BDRV_HASH_BLOCK_SIZE 1024
3217 #define IOBUF_SIZE 4096
3218 #define RAM_CBLOCK_MAGIC 0xfabe
3220 typedef struct RamDecompressState {
3221 z_stream zstream;
3222 QEMUFile *f;
3223 uint8_t buf[IOBUF_SIZE];
3224 } RamDecompressState;
3226 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3228 int ret;
3229 memset(s, 0, sizeof(*s));
3230 s->f = f;
3231 ret = inflateInit(&s->zstream);
3232 if (ret != Z_OK)
3233 return -1;
3234 return 0;
3237 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3239 int ret, clen;
3241 s->zstream.avail_out = len;
3242 s->zstream.next_out = buf;
3243 while (s->zstream.avail_out > 0) {
3244 if (s->zstream.avail_in == 0) {
3245 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3246 return -1;
3247 clen = qemu_get_be16(s->f);
3248 if (clen > IOBUF_SIZE)
3249 return -1;
3250 qemu_get_buffer(s->f, s->buf, clen);
3251 s->zstream.avail_in = clen;
3252 s->zstream.next_in = s->buf;
3254 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3255 if (ret != Z_OK && ret != Z_STREAM_END) {
3256 return -1;
3259 return 0;
3262 static void ram_decompress_close(RamDecompressState *s)
3264 inflateEnd(&s->zstream);
3267 #define RAM_SAVE_FLAG_FULL 0x01
3268 #define RAM_SAVE_FLAG_COMPRESS 0x02
3269 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3270 #define RAM_SAVE_FLAG_PAGE 0x08
3271 #define RAM_SAVE_FLAG_EOS 0x10
3273 static int is_dup_page(uint8_t *page, uint8_t ch)
3275 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3276 uint32_t *array = (uint32_t *)page;
3277 int i;
3279 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3280 if (array[i] != val)
3281 return 0;
3284 return 1;
3287 static int ram_save_block(QEMUFile *f)
3289 static ram_addr_t current_addr = 0;
3290 ram_addr_t saved_addr = current_addr;
3291 ram_addr_t addr = 0;
3292 int found = 0;
3294 while (addr < last_ram_offset) {
3295 if (kvm_enabled() && current_addr == 0) {
3296 int r;
3297 r = kvm_update_dirty_pages_log();
3298 if (r) {
3299 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3300 qemu_file_set_error(f);
3301 return 0;
3304 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3305 uint8_t *p;
3307 cpu_physical_memory_reset_dirty(current_addr,
3308 current_addr + TARGET_PAGE_SIZE,
3309 MIGRATION_DIRTY_FLAG);
3311 p = qemu_get_ram_ptr(current_addr);
3313 if (is_dup_page(p, *p)) {
3314 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3315 qemu_put_byte(f, *p);
3316 } else {
3317 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3318 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3321 found = 1;
3322 break;
3324 addr += TARGET_PAGE_SIZE;
3325 current_addr = (saved_addr + addr) % last_ram_offset;
3328 return found;
3331 static ram_addr_t ram_save_threshold = 10;
3333 static ram_addr_t ram_save_remaining(void)
3335 ram_addr_t addr;
3336 ram_addr_t count = 0;
3338 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3339 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3340 count++;
3343 return count;
3346 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3348 ram_addr_t addr;
3350 if (stage == 1) {
3351 /* Make sure all dirty bits are set */
3352 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3353 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3354 cpu_physical_memory_set_dirty(addr);
3357 /* Enable dirty memory tracking */
3358 cpu_physical_memory_set_dirty_tracking(1);
3360 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3363 while (!qemu_file_rate_limit(f)) {
3364 int ret;
3366 ret = ram_save_block(f);
3367 if (ret == 0) /* no more blocks */
3368 break;
3371 /* try transferring iterative blocks of memory */
3373 if (stage == 3) {
3375 /* flush all remaining blocks regardless of rate limiting */
3376 while (ram_save_block(f) != 0);
3377 cpu_physical_memory_set_dirty_tracking(0);
3380 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3382 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3385 static int ram_load_dead(QEMUFile *f, void *opaque)
3387 RamDecompressState s1, *s = &s1;
3388 uint8_t buf[10];
3389 ram_addr_t i;
3391 if (ram_decompress_open(s, f) < 0)
3392 return -EINVAL;
3393 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3394 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3395 continue;
3396 if (ram_decompress_buf(s, buf, 1) < 0) {
3397 fprintf(stderr, "Error while reading ram block header\n");
3398 goto error;
3400 if (buf[0] == 0) {
3401 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3402 BDRV_HASH_BLOCK_SIZE) < 0) {
3403 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3404 goto error;
3406 } else {
3407 error:
3408 printf("Error block header\n");
3409 return -EINVAL;
3412 ram_decompress_close(s);
3414 return 0;
3417 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3419 ram_addr_t addr;
3420 int flags;
3422 if (version_id == 1)
3423 return ram_load_v1(f, opaque);
3425 if (version_id == 2) {
3426 if (qemu_get_be32(f) != last_ram_offset)
3427 return -EINVAL;
3428 return ram_load_dead(f, opaque);
3431 if (version_id != 3)
3432 return -EINVAL;
3434 do {
3435 addr = qemu_get_be64(f);
3437 flags = addr & ~TARGET_PAGE_MASK;
3438 addr &= TARGET_PAGE_MASK;
3440 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3441 if (addr != last_ram_offset)
3442 return -EINVAL;
3445 if (flags & RAM_SAVE_FLAG_FULL) {
3446 if (ram_load_dead(f, opaque) < 0)
3447 return -EINVAL;
3450 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3451 uint8_t ch = qemu_get_byte(f);
3452 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3453 } else if (flags & RAM_SAVE_FLAG_PAGE)
3454 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3455 } while (!(flags & RAM_SAVE_FLAG_EOS));
3457 return 0;
3460 void qemu_service_io(void)
3462 CPUState *env = cpu_single_env;
3463 if (env) {
3464 cpu_exit(env);
3465 #ifdef CONFIG_KQEMU
3466 if (env->kqemu_enabled) {
3467 kqemu_cpu_interrupt(env);
3469 #endif
3473 /***********************************************************/
3474 /* bottom halves (can be seen as timers which expire ASAP) */
3476 struct QEMUBH {
3477 QEMUBHFunc *cb;
3478 void *opaque;
3479 int scheduled;
3480 int idle;
3481 int deleted;
3482 QEMUBH *next;
3485 static QEMUBH *first_bh = NULL;
3487 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3489 QEMUBH *bh;
3490 bh = qemu_mallocz(sizeof(QEMUBH));
3491 bh->cb = cb;
3492 bh->opaque = opaque;
3493 bh->next = first_bh;
3494 first_bh = bh;
3495 return bh;
3498 int qemu_bh_poll(void)
3500 QEMUBH *bh, **bhp;
3501 int ret;
3503 ret = 0;
3504 for (bh = first_bh; bh; bh = bh->next) {
3505 if (!bh->deleted && bh->scheduled) {
3506 bh->scheduled = 0;
3507 if (!bh->idle)
3508 ret = 1;
3509 bh->idle = 0;
3510 bh->cb(bh->opaque);
3514 /* remove deleted bhs */
3515 bhp = &first_bh;
3516 while (*bhp) {
3517 bh = *bhp;
3518 if (bh->deleted) {
3519 *bhp = bh->next;
3520 qemu_free(bh);
3521 } else
3522 bhp = &bh->next;
3525 return ret;
3528 void qemu_bh_schedule_idle(QEMUBH *bh)
3530 if (bh->scheduled)
3531 return;
3532 bh->scheduled = 1;
3533 bh->idle = 1;
3536 void qemu_bh_schedule(QEMUBH *bh)
3538 CPUState *env = cpu_single_env;
3539 if (bh->scheduled)
3540 return;
3541 bh->scheduled = 1;
3542 bh->idle = 0;
3543 /* stop the currently executing CPU to execute the BH ASAP */
3544 if (env) {
3545 cpu_exit(env);
3547 main_loop_break();
3550 void qemu_bh_cancel(QEMUBH *bh)
3552 bh->scheduled = 0;
3555 void qemu_bh_delete(QEMUBH *bh)
3557 bh->scheduled = 0;
3558 bh->deleted = 1;
3561 static void qemu_bh_update_timeout(int *timeout)
3563 QEMUBH *bh;
3565 for (bh = first_bh; bh; bh = bh->next) {
3566 if (!bh->deleted && bh->scheduled) {
3567 if (bh->idle) {
3568 /* idle bottom halves will be polled at least
3569 * every 10ms */
3570 *timeout = MIN(10, *timeout);
3571 } else {
3572 /* non-idle bottom halves will be executed
3573 * immediately */
3574 *timeout = 0;
3575 break;
3581 /***********************************************************/
3582 /* machine registration */
3584 static QEMUMachine *first_machine = NULL;
3585 QEMUMachine *current_machine = NULL;
3587 int qemu_register_machine(QEMUMachine *m)
3589 QEMUMachine **pm;
3590 pm = &first_machine;
3591 while (*pm != NULL)
3592 pm = &(*pm)->next;
3593 m->next = NULL;
3594 *pm = m;
3595 return 0;
3598 static QEMUMachine *find_machine(const char *name)
3600 QEMUMachine *m;
3602 for(m = first_machine; m != NULL; m = m->next) {
3603 if (!strcmp(m->name, name))
3604 return m;
3606 return NULL;
3609 /***********************************************************/
3610 /* main execution loop */
3612 static void gui_update(void *opaque)
3614 uint64_t interval = GUI_REFRESH_INTERVAL;
3615 DisplayState *ds = opaque;
3616 DisplayChangeListener *dcl = ds->listeners;
3618 dpy_refresh(ds);
3620 while (dcl != NULL) {
3621 if (dcl->gui_timer_interval &&
3622 dcl->gui_timer_interval < interval)
3623 interval = dcl->gui_timer_interval;
3624 dcl = dcl->next;
3626 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3629 static void nographic_update(void *opaque)
3631 uint64_t interval = GUI_REFRESH_INTERVAL;
3633 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3636 struct vm_change_state_entry {
3637 VMChangeStateHandler *cb;
3638 void *opaque;
3639 LIST_ENTRY (vm_change_state_entry) entries;
3642 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3644 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3645 void *opaque)
3647 VMChangeStateEntry *e;
3649 e = qemu_mallocz(sizeof (*e));
3651 e->cb = cb;
3652 e->opaque = opaque;
3653 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3654 return e;
3657 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3659 LIST_REMOVE (e, entries);
3660 qemu_free (e);
3663 static void vm_state_notify(int running, int reason)
3665 VMChangeStateEntry *e;
3667 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3668 e->cb(e->opaque, running, reason);
3672 void vm_start(void)
3674 if (!vm_running) {
3675 cpu_enable_ticks();
3676 vm_running = 1;
3677 vm_state_notify(1, 0);
3678 if (kvm_enabled())
3679 qemu_kvm_resume_all_threads();
3680 qemu_rearm_alarm_timer(alarm_timer);
3684 void vm_stop(int reason)
3686 if (vm_running) {
3687 cpu_disable_ticks();
3688 vm_running = 0;
3689 if (kvm_enabled())
3690 qemu_kvm_pause_all_threads();
3691 vm_state_notify(0, reason);
3695 /* reset/shutdown handler */
3697 typedef struct QEMUResetEntry {
3698 QEMUResetHandler *func;
3699 void *opaque;
3700 struct QEMUResetEntry *next;
3701 } QEMUResetEntry;
3703 static QEMUResetEntry *first_reset_entry;
3704 static int reset_requested;
3705 static int shutdown_requested;
3706 static int powerdown_requested;
3708 int qemu_shutdown_requested(void)
3710 int r = shutdown_requested;
3711 shutdown_requested = 0;
3712 return r;
3715 int qemu_reset_requested(void)
3717 int r = reset_requested;
3718 reset_requested = 0;
3719 return r;
3722 int qemu_powerdown_requested(void)
3724 int r = powerdown_requested;
3725 powerdown_requested = 0;
3726 return r;
3729 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3731 QEMUResetEntry **pre, *re;
3733 pre = &first_reset_entry;
3734 while (*pre != NULL)
3735 pre = &(*pre)->next;
3736 re = qemu_mallocz(sizeof(QEMUResetEntry));
3737 re->func = func;
3738 re->opaque = opaque;
3739 re->next = NULL;
3740 *pre = re;
3743 void qemu_system_reset(void)
3745 QEMUResetEntry *re;
3747 /* reset all devices */
3748 for(re = first_reset_entry; re != NULL; re = re->next) {
3749 re->func(re->opaque);
3751 if (kvm_enabled())
3752 kvm_sync_vcpus();
3755 void qemu_system_reset_request(void)
3757 if (no_reboot) {
3758 shutdown_requested = 1;
3759 } else {
3760 reset_requested = 1;
3762 if (cpu_single_env) {
3763 qemu_kvm_cpu_stop(cpu_single_env);
3764 cpu_exit(cpu_single_env);
3768 void qemu_system_shutdown_request(void)
3770 shutdown_requested = 1;
3771 if (cpu_single_env)
3772 cpu_exit(cpu_single_env);
3775 void qemu_system_powerdown_request(void)
3777 powerdown_requested = 1;
3778 if (cpu_single_env)
3779 cpu_exit(cpu_single_env);
3782 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3783 struct timeval *tv)
3785 int ret;
3787 /* KVM holds a mutex while QEMU code is running, we need hooks to
3788 release the mutex whenever QEMU code sleeps. */
3790 kvm_sleep_begin();
3792 ret = select(max_fd, rfds, wfds, xfds, tv);
3794 kvm_sleep_end();
3796 return ret;
3799 #ifdef _WIN32
3800 static void host_main_loop_wait(int *timeout)
3802 int ret, ret2, i;
3803 PollingEntry *pe;
3806 /* XXX: need to suppress polling by better using win32 events */
3807 ret = 0;
3808 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3809 ret |= pe->func(pe->opaque);
3811 if (ret == 0) {
3812 int err;
3813 WaitObjects *w = &wait_objects;
3815 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3816 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3817 if (w->func[ret - WAIT_OBJECT_0])
3818 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3820 /* Check for additional signaled events */
3821 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3823 /* Check if event is signaled */
3824 ret2 = WaitForSingleObject(w->events[i], 0);
3825 if(ret2 == WAIT_OBJECT_0) {
3826 if (w->func[i])
3827 w->func[i](w->opaque[i]);
3828 } else if (ret2 == WAIT_TIMEOUT) {
3829 } else {
3830 err = GetLastError();
3831 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3834 } else if (ret == WAIT_TIMEOUT) {
3835 } else {
3836 err = GetLastError();
3837 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3841 *timeout = 0;
3843 #else
3844 static void host_main_loop_wait(int *timeout)
3847 #endif
3849 void main_loop_wait(int timeout)
3851 IOHandlerRecord *ioh;
3852 fd_set rfds, wfds, xfds;
3853 int ret, nfds;
3854 struct timeval tv;
3856 qemu_bh_update_timeout(&timeout);
3858 host_main_loop_wait(&timeout);
3860 /* poll any events */
3861 /* XXX: separate device handlers from system ones */
3862 nfds = -1;
3863 FD_ZERO(&rfds);
3864 FD_ZERO(&wfds);
3865 FD_ZERO(&xfds);
3866 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3867 if (ioh->deleted)
3868 continue;
3869 if (ioh->fd_read &&
3870 (!ioh->fd_read_poll ||
3871 ioh->fd_read_poll(ioh->opaque) != 0)) {
3872 FD_SET(ioh->fd, &rfds);
3873 if (ioh->fd > nfds)
3874 nfds = ioh->fd;
3876 if (ioh->fd_write) {
3877 FD_SET(ioh->fd, &wfds);
3878 if (ioh->fd > nfds)
3879 nfds = ioh->fd;
3883 tv.tv_sec = timeout / 1000;
3884 tv.tv_usec = (timeout % 1000) * 1000;
3886 #if defined(CONFIG_SLIRP)
3887 if (slirp_is_inited()) {
3888 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3890 #endif
3891 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3892 if (ret > 0) {
3893 IOHandlerRecord **pioh;
3895 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3896 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3897 ioh->fd_read(ioh->opaque);
3898 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3899 FD_CLR(ioh->fd, &rfds);
3901 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3902 ioh->fd_write(ioh->opaque);
3906 /* remove deleted IO handlers */
3907 pioh = &first_io_handler;
3908 while (*pioh) {
3909 ioh = *pioh;
3910 if (ioh->deleted) {
3911 *pioh = ioh->next;
3912 qemu_free(ioh);
3913 } else
3914 pioh = &ioh->next;
3917 #if defined(CONFIG_SLIRP)
3918 if (slirp_is_inited()) {
3919 if (ret < 0) {
3920 FD_ZERO(&rfds);
3921 FD_ZERO(&wfds);
3922 FD_ZERO(&xfds);
3924 slirp_select_poll(&rfds, &wfds, &xfds);
3926 #endif
3928 /* vm time timers */
3929 if (vm_running && (!cur_cpu
3930 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3931 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3932 qemu_get_clock(vm_clock));
3934 /* real time timers */
3935 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3936 qemu_get_clock(rt_clock));
3938 /* Check bottom-halves last in case any of the earlier events triggered
3939 them. */
3940 qemu_bh_poll();
3944 static int main_loop(void)
3946 int ret, timeout;
3947 #ifdef CONFIG_PROFILER
3948 int64_t ti;
3949 #endif
3950 CPUState *env;
3953 if (kvm_enabled()) {
3954 kvm_main_loop();
3955 cpu_disable_ticks();
3956 return 0;
3959 cur_cpu = first_cpu;
3960 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3961 for(;;) {
3962 if (vm_running) {
3964 for(;;) {
3965 /* get next cpu */
3966 env = next_cpu;
3967 #ifdef CONFIG_PROFILER
3968 ti = profile_getclock();
3969 #endif
3970 if (use_icount) {
3971 int64_t count;
3972 int decr;
3973 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3974 env->icount_decr.u16.low = 0;
3975 env->icount_extra = 0;
3976 count = qemu_next_deadline();
3977 count = (count + (1 << icount_time_shift) - 1)
3978 >> icount_time_shift;
3979 qemu_icount += count;
3980 decr = (count > 0xffff) ? 0xffff : count;
3981 count -= decr;
3982 env->icount_decr.u16.low = decr;
3983 env->icount_extra = count;
3985 ret = cpu_exec(env);
3986 #ifdef CONFIG_PROFILER
3987 qemu_time += profile_getclock() - ti;
3988 #endif
3989 if (use_icount) {
3990 /* Fold pending instructions back into the
3991 instruction counter, and clear the interrupt flag. */
3992 qemu_icount -= (env->icount_decr.u16.low
3993 + env->icount_extra);
3994 env->icount_decr.u32 = 0;
3995 env->icount_extra = 0;
3997 next_cpu = env->next_cpu ?: first_cpu;
3998 if (event_pending && likely(ret != EXCP_DEBUG)) {
3999 ret = EXCP_INTERRUPT;
4000 event_pending = 0;
4001 break;
4003 if (ret == EXCP_HLT) {
4004 /* Give the next CPU a chance to run. */
4005 cur_cpu = env;
4006 continue;
4008 if (ret != EXCP_HALTED)
4009 break;
4010 /* all CPUs are halted ? */
4011 if (env == cur_cpu)
4012 break;
4014 cur_cpu = env;
4016 if (shutdown_requested) {
4017 ret = EXCP_INTERRUPT;
4018 if (no_shutdown) {
4019 vm_stop(0);
4020 no_shutdown = 0;
4022 else
4023 break;
4025 if (reset_requested) {
4026 reset_requested = 0;
4027 qemu_system_reset();
4028 ret = EXCP_INTERRUPT;
4030 if (powerdown_requested) {
4031 powerdown_requested = 0;
4032 qemu_system_powerdown();
4033 ret = EXCP_INTERRUPT;
4035 #ifdef CONFIG_GDBSTUB
4036 if (unlikely(ret == EXCP_DEBUG)) {
4037 gdb_set_stop_cpu(cur_cpu);
4038 vm_stop(EXCP_DEBUG);
4040 #endif
4041 /* If all cpus are halted then wait until the next IRQ */
4042 /* XXX: use timeout computed from timers */
4043 if (ret == EXCP_HALTED) {
4044 if (use_icount) {
4045 int64_t add;
4046 int64_t delta;
4047 /* Advance virtual time to the next event. */
4048 if (use_icount == 1) {
4049 /* When not using an adaptive execution frequency
4050 we tend to get badly out of sync with real time,
4051 so just delay for a reasonable amount of time. */
4052 delta = 0;
4053 } else {
4054 delta = cpu_get_icount() - cpu_get_clock();
4056 if (delta > 0) {
4057 /* If virtual time is ahead of real time then just
4058 wait for IO. */
4059 timeout = (delta / 1000000) + 1;
4060 } else {
4061 /* Wait for either IO to occur or the next
4062 timer event. */
4063 add = qemu_next_deadline();
4064 /* We advance the timer before checking for IO.
4065 Limit the amount we advance so that early IO
4066 activity won't get the guest too far ahead. */
4067 if (add > 10000000)
4068 add = 10000000;
4069 delta += add;
4070 add = (add + (1 << icount_time_shift) - 1)
4071 >> icount_time_shift;
4072 qemu_icount += add;
4073 timeout = delta / 1000000;
4074 if (timeout < 0)
4075 timeout = 0;
4077 } else {
4078 timeout = 5000;
4080 } else {
4081 timeout = 0;
4083 } else {
4084 if (shutdown_requested) {
4085 ret = EXCP_INTERRUPT;
4086 break;
4088 timeout = 5000;
4090 #ifdef CONFIG_PROFILER
4091 ti = profile_getclock();
4092 #endif
4093 main_loop_wait(timeout);
4094 #ifdef CONFIG_PROFILER
4095 dev_time += profile_getclock() - ti;
4096 #endif
4098 cpu_disable_ticks();
4099 return ret;
4102 static void version(void)
4104 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4107 static void help(int exitcode)
4109 version();
4110 printf("usage: %s [options] [disk_image]\n"
4111 "\n"
4112 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4113 "\n"
4114 #define DEF(option, opt_arg, opt_enum, opt_help) \
4115 opt_help
4116 #define DEFHEADING(text) stringify(text) "\n"
4117 #include "qemu-options.h"
4118 #undef DEF
4119 #undef DEFHEADING
4120 #undef GEN_DOCS
4121 "\n"
4122 "During emulation, the following keys are useful:\n"
4123 "ctrl-alt-f toggle full screen\n"
4124 "ctrl-alt-n switch to virtual console 'n'\n"
4125 "ctrl-alt toggle mouse and keyboard grab\n"
4126 "\n"
4127 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4129 "qemu",
4130 DEFAULT_RAM_SIZE,
4131 #ifndef _WIN32
4132 DEFAULT_NETWORK_SCRIPT,
4133 DEFAULT_NETWORK_DOWN_SCRIPT,
4134 #endif
4135 DEFAULT_GDBSTUB_PORT,
4136 "/tmp/qemu.log");
4137 exit(exitcode);
4140 #define HAS_ARG 0x0001
4142 enum {
4143 #define DEF(option, opt_arg, opt_enum, opt_help) \
4144 opt_enum,
4145 #define DEFHEADING(text)
4146 #include "qemu-options.h"
4147 #undef DEF
4148 #undef DEFHEADING
4149 #undef GEN_DOCS
4152 typedef struct QEMUOption {
4153 const char *name;
4154 int flags;
4155 int index;
4156 } QEMUOption;
4158 static const QEMUOption qemu_options[] = {
4159 { "h", 0, QEMU_OPTION_h },
4160 #define DEF(option, opt_arg, opt_enum, opt_help) \
4161 { option, opt_arg, opt_enum },
4162 #define DEFHEADING(text)
4163 #include "qemu-options.h"
4164 #undef DEF
4165 #undef DEFHEADING
4166 #undef GEN_DOCS
4167 { NULL },
4170 #ifdef HAS_AUDIO
4171 struct soundhw soundhw[] = {
4172 #ifdef HAS_AUDIO_CHOICE
4173 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4175 "pcspk",
4176 "PC speaker",
4179 { .init_isa = pcspk_audio_init }
4181 #endif
4183 #ifdef CONFIG_SB16
4185 "sb16",
4186 "Creative Sound Blaster 16",
4189 { .init_isa = SB16_init }
4191 #endif
4193 #ifdef CONFIG_CS4231A
4195 "cs4231a",
4196 "CS4231A",
4199 { .init_isa = cs4231a_init }
4201 #endif
4203 #ifdef CONFIG_ADLIB
4205 "adlib",
4206 #ifdef HAS_YMF262
4207 "Yamaha YMF262 (OPL3)",
4208 #else
4209 "Yamaha YM3812 (OPL2)",
4210 #endif
4213 { .init_isa = Adlib_init }
4215 #endif
4217 #ifdef CONFIG_GUS
4219 "gus",
4220 "Gravis Ultrasound GF1",
4223 { .init_isa = GUS_init }
4225 #endif
4227 #ifdef CONFIG_AC97
4229 "ac97",
4230 "Intel 82801AA AC97 Audio",
4233 { .init_pci = ac97_init }
4235 #endif
4237 #ifdef CONFIG_ES1370
4239 "es1370",
4240 "ENSONIQ AudioPCI ES1370",
4243 { .init_pci = es1370_init }
4245 #endif
4247 #endif /* HAS_AUDIO_CHOICE */
4249 { NULL, NULL, 0, 0, { NULL } }
4252 static void select_soundhw (const char *optarg)
4254 struct soundhw *c;
4256 if (*optarg == '?') {
4257 show_valid_cards:
4259 printf ("Valid sound card names (comma separated):\n");
4260 for (c = soundhw; c->name; ++c) {
4261 printf ("%-11s %s\n", c->name, c->descr);
4263 printf ("\n-soundhw all will enable all of the above\n");
4264 exit (*optarg != '?');
4266 else {
4267 size_t l;
4268 const char *p;
4269 char *e;
4270 int bad_card = 0;
4272 if (!strcmp (optarg, "all")) {
4273 for (c = soundhw; c->name; ++c) {
4274 c->enabled = 1;
4276 return;
4279 p = optarg;
4280 while (*p) {
4281 e = strchr (p, ',');
4282 l = !e ? strlen (p) : (size_t) (e - p);
4284 for (c = soundhw; c->name; ++c) {
4285 if (!strncmp (c->name, p, l)) {
4286 c->enabled = 1;
4287 break;
4291 if (!c->name) {
4292 if (l > 80) {
4293 fprintf (stderr,
4294 "Unknown sound card name (too big to show)\n");
4296 else {
4297 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4298 (int) l, p);
4300 bad_card = 1;
4302 p += l + (e != NULL);
4305 if (bad_card)
4306 goto show_valid_cards;
4309 #endif
4311 static void select_vgahw (const char *p)
4313 const char *opts;
4315 cirrus_vga_enabled = 0;
4316 std_vga_enabled = 0;
4317 vmsvga_enabled = 0;
4318 xenfb_enabled = 0;
4319 if (strstart(p, "std", &opts)) {
4320 std_vga_enabled = 1;
4321 } else if (strstart(p, "cirrus", &opts)) {
4322 cirrus_vga_enabled = 1;
4323 } else if (strstart(p, "vmware", &opts)) {
4324 vmsvga_enabled = 1;
4325 } else if (strstart(p, "xenfb", &opts)) {
4326 xenfb_enabled = 1;
4327 } else if (!strstart(p, "none", &opts)) {
4328 invalid_vga:
4329 fprintf(stderr, "Unknown vga type: %s\n", p);
4330 exit(1);
4332 while (*opts) {
4333 const char *nextopt;
4335 if (strstart(opts, ",retrace=", &nextopt)) {
4336 opts = nextopt;
4337 if (strstart(opts, "dumb", &nextopt))
4338 vga_retrace_method = VGA_RETRACE_DUMB;
4339 else if (strstart(opts, "precise", &nextopt))
4340 vga_retrace_method = VGA_RETRACE_PRECISE;
4341 else goto invalid_vga;
4342 } else goto invalid_vga;
4343 opts = nextopt;
4347 #ifdef _WIN32
4348 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4350 exit(STATUS_CONTROL_C_EXIT);
4351 return TRUE;
4353 #endif
4355 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4357 int ret;
4359 if(strlen(str) != 36)
4360 return -1;
4362 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4363 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4364 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4366 if(ret != 16)
4367 return -1;
4369 #ifdef TARGET_I386
4370 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4371 #endif
4373 return 0;
4376 #define MAX_NET_CLIENTS 32
4378 #ifdef USE_KVM
4380 #define HUGETLBFS_MAGIC 0x958458f6
4382 static long gethugepagesize(const char *path)
4384 struct statfs fs;
4385 int ret;
4387 do {
4388 ret = statfs(path, &fs);
4389 } while (ret != 0 && errno == EINTR);
4391 if (ret != 0) {
4392 perror("statfs");
4393 return 0;
4396 if (fs.f_type != HUGETLBFS_MAGIC)
4397 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4399 return fs.f_bsize;
4402 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4404 char *filename;
4405 void *area;
4406 int fd;
4407 #ifdef MAP_POPULATE
4408 int flags;
4409 #endif
4411 if (!kvm_has_sync_mmu()) {
4412 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4413 return NULL;
4416 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4417 return NULL;
4419 hpagesize = gethugepagesize(path);
4420 if (!hpagesize)
4421 return NULL;
4423 fd = mkstemp(filename);
4424 if (fd < 0) {
4425 perror("mkstemp");
4426 free(filename);
4427 return NULL;
4429 unlink(filename);
4430 free(filename);
4432 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4435 * ftruncate is not supported by hugetlbfs in older
4436 * hosts, so don't bother checking for errors.
4437 * If anything goes wrong with it under other filesystems,
4438 * mmap will fail.
4440 ftruncate(fd, memory);
4442 #ifdef MAP_POPULATE
4443 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4444 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4445 * to sidestep this quirk.
4447 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4448 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4449 #else
4450 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4451 #endif
4452 if (area == MAP_FAILED) {
4453 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4454 close(fd);
4455 return (NULL);
4457 *len = memory;
4458 return area;
4460 #endif
4462 static void *qemu_alloc_physram(unsigned long memory)
4464 void *area = NULL;
4465 #ifdef USE_KVM
4466 unsigned long map_len = memory;
4468 if (mem_path)
4469 area = alloc_mem_area(memory, &map_len, mem_path);
4470 #endif
4471 if (!area)
4472 area = qemu_vmalloc(memory);
4473 #ifdef USE_KVM
4474 if (kvm_setup_guest_memory(area, map_len))
4475 area = NULL;
4476 #endif
4477 return area;
4480 #ifndef _WIN32
4482 static void termsig_handler(int signal)
4484 qemu_system_shutdown_request();
4487 static void termsig_setup(void)
4489 struct sigaction act;
4491 memset(&act, 0, sizeof(act));
4492 act.sa_handler = termsig_handler;
4493 sigaction(SIGINT, &act, NULL);
4494 sigaction(SIGHUP, &act, NULL);
4495 sigaction(SIGTERM, &act, NULL);
4498 #endif
4500 int main(int argc, char **argv, char **envp)
4502 #ifdef CONFIG_GDBSTUB
4503 const char *gdbstub_dev = NULL;
4504 #endif
4505 uint32_t boot_devices_bitmap = 0;
4506 int i;
4507 int snapshot, linux_boot, net_boot;
4508 const char *initrd_filename;
4509 const char *kernel_filename, *kernel_cmdline;
4510 const char *boot_devices = "";
4511 DisplayState *ds;
4512 DisplayChangeListener *dcl;
4513 int cyls, heads, secs, translation;
4514 const char *net_clients[MAX_NET_CLIENTS];
4515 int nb_net_clients;
4516 const char *bt_opts[MAX_BT_CMDLINE];
4517 int nb_bt_opts;
4518 int hda_index;
4519 int optind;
4520 const char *r, *optarg;
4521 CharDriverState *monitor_hd = NULL;
4522 const char *monitor_device;
4523 const char *serial_devices[MAX_SERIAL_PORTS];
4524 int serial_device_index;
4525 const char *parallel_devices[MAX_PARALLEL_PORTS];
4526 int parallel_device_index;
4527 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4528 int virtio_console_index;
4529 const char *loadvm = NULL;
4530 QEMUMachine *machine;
4531 const char *cpu_model;
4532 const char *usb_devices[MAX_USB_CMDLINE];
4533 int usb_devices_index;
4534 #ifndef _WIN32
4535 int fds[2];
4536 #endif
4537 int tb_size;
4538 const char *pid_file = NULL;
4539 const char *incoming = NULL;
4540 #ifndef _WIN32
4541 int fd = 0;
4542 struct passwd *pwd = NULL;
4543 const char *chroot_dir = NULL;
4544 const char *run_as = NULL;
4545 #endif
4546 CPUState *env;
4548 qemu_cache_utils_init(envp);
4550 LIST_INIT (&vm_change_state_head);
4551 #ifndef _WIN32
4553 struct sigaction act;
4554 sigfillset(&act.sa_mask);
4555 act.sa_flags = 0;
4556 act.sa_handler = SIG_IGN;
4557 sigaction(SIGPIPE, &act, NULL);
4559 #else
4560 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4561 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4562 QEMU to run on a single CPU */
4564 HANDLE h;
4565 DWORD mask, smask;
4566 int i;
4567 h = GetCurrentProcess();
4568 if (GetProcessAffinityMask(h, &mask, &smask)) {
4569 for(i = 0; i < 32; i++) {
4570 if (mask & (1 << i))
4571 break;
4573 if (i != 32) {
4574 mask = 1 << i;
4575 SetProcessAffinityMask(h, mask);
4579 #endif
4581 register_machines();
4582 machine = first_machine;
4583 cpu_model = NULL;
4584 initrd_filename = NULL;
4585 ram_size = 0;
4586 vga_ram_size = VGA_RAM_SIZE;
4587 snapshot = 0;
4588 nographic = 0;
4589 curses = 0;
4590 kernel_filename = NULL;
4591 kernel_cmdline = "";
4592 cyls = heads = secs = 0;
4593 translation = BIOS_ATA_TRANSLATION_AUTO;
4594 monitor_device = "vc:80Cx24C";
4596 serial_devices[0] = "vc:80Cx24C";
4597 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4598 serial_devices[i] = NULL;
4599 serial_device_index = 0;
4601 parallel_devices[0] = "vc:80Cx24C";
4602 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4603 parallel_devices[i] = NULL;
4604 parallel_device_index = 0;
4606 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4607 virtio_consoles[i] = NULL;
4608 virtio_console_index = 0;
4610 for (i = 0; i < MAX_NODES; i++) {
4611 node_mem[i] = 0;
4612 node_cpumask[i] = 0;
4615 usb_devices_index = 0;
4616 assigned_devices_index = 0;
4618 nb_net_clients = 0;
4619 nb_bt_opts = 0;
4620 nb_drives = 0;
4621 nb_drives_opt = 0;
4622 nb_numa_nodes = 0;
4623 hda_index = -1;
4625 nb_nics = 0;
4627 tb_size = 0;
4628 autostart= 1;
4630 optind = 1;
4631 for(;;) {
4632 if (optind >= argc)
4633 break;
4634 r = argv[optind];
4635 if (r[0] != '-') {
4636 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4637 } else {
4638 const QEMUOption *popt;
4640 optind++;
4641 /* Treat --foo the same as -foo. */
4642 if (r[1] == '-')
4643 r++;
4644 popt = qemu_options;
4645 for(;;) {
4646 if (!popt->name) {
4647 fprintf(stderr, "%s: invalid option -- '%s'\n",
4648 argv[0], r);
4649 exit(1);
4651 if (!strcmp(popt->name, r + 1))
4652 break;
4653 popt++;
4655 if (popt->flags & HAS_ARG) {
4656 if (optind >= argc) {
4657 fprintf(stderr, "%s: option '%s' requires an argument\n",
4658 argv[0], r);
4659 exit(1);
4661 optarg = argv[optind++];
4662 } else {
4663 optarg = NULL;
4666 switch(popt->index) {
4667 case QEMU_OPTION_M:
4668 machine = find_machine(optarg);
4669 if (!machine) {
4670 QEMUMachine *m;
4671 printf("Supported machines are:\n");
4672 for(m = first_machine; m != NULL; m = m->next) {
4673 printf("%-10s %s%s\n",
4674 m->name, m->desc,
4675 m == first_machine ? " (default)" : "");
4677 exit(*optarg != '?');
4679 break;
4680 case QEMU_OPTION_cpu:
4681 /* hw initialization will check this */
4682 if (*optarg == '?') {
4683 /* XXX: implement xxx_cpu_list for targets that still miss it */
4684 #if defined(cpu_list)
4685 cpu_list(stdout, &fprintf);
4686 #endif
4687 exit(0);
4688 } else {
4689 cpu_model = optarg;
4691 break;
4692 case QEMU_OPTION_initrd:
4693 initrd_filename = optarg;
4694 break;
4695 case QEMU_OPTION_hda:
4696 if (cyls == 0)
4697 hda_index = drive_add(optarg, HD_ALIAS, 0);
4698 else
4699 hda_index = drive_add(optarg, HD_ALIAS
4700 ",cyls=%d,heads=%d,secs=%d%s",
4701 0, cyls, heads, secs,
4702 translation == BIOS_ATA_TRANSLATION_LBA ?
4703 ",trans=lba" :
4704 translation == BIOS_ATA_TRANSLATION_NONE ?
4705 ",trans=none" : "");
4706 break;
4707 case QEMU_OPTION_hdb:
4708 case QEMU_OPTION_hdc:
4709 case QEMU_OPTION_hdd:
4710 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4711 break;
4712 case QEMU_OPTION_drive:
4713 drive_add(NULL, "%s", optarg);
4714 break;
4715 case QEMU_OPTION_mtdblock:
4716 drive_add(optarg, MTD_ALIAS);
4717 break;
4718 case QEMU_OPTION_sd:
4719 drive_add(optarg, SD_ALIAS);
4720 break;
4721 case QEMU_OPTION_pflash:
4722 drive_add(optarg, PFLASH_ALIAS);
4723 break;
4724 case QEMU_OPTION_snapshot:
4725 snapshot = 1;
4726 break;
4727 case QEMU_OPTION_hdachs:
4729 const char *p;
4730 p = optarg;
4731 cyls = strtol(p, (char **)&p, 0);
4732 if (cyls < 1 || cyls > 16383)
4733 goto chs_fail;
4734 if (*p != ',')
4735 goto chs_fail;
4736 p++;
4737 heads = strtol(p, (char **)&p, 0);
4738 if (heads < 1 || heads > 16)
4739 goto chs_fail;
4740 if (*p != ',')
4741 goto chs_fail;
4742 p++;
4743 secs = strtol(p, (char **)&p, 0);
4744 if (secs < 1 || secs > 63)
4745 goto chs_fail;
4746 if (*p == ',') {
4747 p++;
4748 if (!strcmp(p, "none"))
4749 translation = BIOS_ATA_TRANSLATION_NONE;
4750 else if (!strcmp(p, "lba"))
4751 translation = BIOS_ATA_TRANSLATION_LBA;
4752 else if (!strcmp(p, "auto"))
4753 translation = BIOS_ATA_TRANSLATION_AUTO;
4754 else
4755 goto chs_fail;
4756 } else if (*p != '\0') {
4757 chs_fail:
4758 fprintf(stderr, "qemu: invalid physical CHS format\n");
4759 exit(1);
4761 if (hda_index != -1)
4762 snprintf(drives_opt[hda_index].opt,
4763 sizeof(drives_opt[hda_index].opt),
4764 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4765 0, cyls, heads, secs,
4766 translation == BIOS_ATA_TRANSLATION_LBA ?
4767 ",trans=lba" :
4768 translation == BIOS_ATA_TRANSLATION_NONE ?
4769 ",trans=none" : "");
4771 break;
4772 case QEMU_OPTION_numa:
4773 if (nb_numa_nodes >= MAX_NODES) {
4774 fprintf(stderr, "qemu: too many NUMA nodes\n");
4775 exit(1);
4777 numa_add(optarg);
4778 break;
4779 case QEMU_OPTION_nographic:
4780 nographic = 1;
4781 break;
4782 #ifdef CONFIG_CURSES
4783 case QEMU_OPTION_curses:
4784 curses = 1;
4785 break;
4786 #endif
4787 case QEMU_OPTION_portrait:
4788 graphic_rotate = 1;
4789 break;
4790 case QEMU_OPTION_kernel:
4791 kernel_filename = optarg;
4792 break;
4793 case QEMU_OPTION_append:
4794 kernel_cmdline = optarg;
4795 break;
4796 case QEMU_OPTION_cdrom:
4797 drive_add(optarg, CDROM_ALIAS);
4798 break;
4799 case QEMU_OPTION_boot:
4800 boot_devices = optarg;
4801 /* We just do some generic consistency checks */
4803 /* Could easily be extended to 64 devices if needed */
4804 const char *p;
4806 boot_devices_bitmap = 0;
4807 for (p = boot_devices; *p != '\0'; p++) {
4808 /* Allowed boot devices are:
4809 * a b : floppy disk drives
4810 * c ... f : IDE disk drives
4811 * g ... m : machine implementation dependant drives
4812 * n ... p : network devices
4813 * It's up to each machine implementation to check
4814 * if the given boot devices match the actual hardware
4815 * implementation and firmware features.
4817 if (*p < 'a' || *p > 'q') {
4818 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4819 exit(1);
4821 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4822 fprintf(stderr,
4823 "Boot device '%c' was given twice\n",*p);
4824 exit(1);
4826 boot_devices_bitmap |= 1 << (*p - 'a');
4829 break;
4830 case QEMU_OPTION_fda:
4831 case QEMU_OPTION_fdb:
4832 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4833 break;
4834 #ifdef TARGET_I386
4835 case QEMU_OPTION_no_fd_bootchk:
4836 fd_bootchk = 0;
4837 break;
4838 #endif
4839 case QEMU_OPTION_net:
4840 if (nb_net_clients >= MAX_NET_CLIENTS) {
4841 fprintf(stderr, "qemu: too many network clients\n");
4842 exit(1);
4844 net_clients[nb_net_clients] = optarg;
4845 nb_net_clients++;
4846 break;
4847 #ifdef CONFIG_SLIRP
4848 case QEMU_OPTION_tftp:
4849 tftp_prefix = optarg;
4850 break;
4851 case QEMU_OPTION_bootp:
4852 bootp_filename = optarg;
4853 break;
4854 #ifndef _WIN32
4855 case QEMU_OPTION_smb:
4856 net_slirp_smb(optarg);
4857 break;
4858 #endif
4859 case QEMU_OPTION_redir:
4860 net_slirp_redir(NULL, optarg);
4861 break;
4862 #endif
4863 case QEMU_OPTION_bt:
4864 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4865 fprintf(stderr, "qemu: too many bluetooth options\n");
4866 exit(1);
4868 bt_opts[nb_bt_opts++] = optarg;
4869 break;
4870 #ifdef HAS_AUDIO
4871 case QEMU_OPTION_audio_help:
4872 AUD_help ();
4873 exit (0);
4874 break;
4875 case QEMU_OPTION_soundhw:
4876 select_soundhw (optarg);
4877 break;
4878 #endif
4879 case QEMU_OPTION_h:
4880 help(0);
4881 break;
4882 case QEMU_OPTION_version:
4883 version();
4884 exit(0);
4885 break;
4886 case QEMU_OPTION_m: {
4887 uint64_t value;
4888 char *ptr;
4890 value = strtoul(optarg, &ptr, 10);
4891 switch (*ptr) {
4892 case 0: case 'M': case 'm':
4893 value <<= 20;
4894 break;
4895 case 'G': case 'g':
4896 value <<= 30;
4897 break;
4898 default:
4899 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4900 exit(1);
4903 /* On 32-bit hosts, QEMU is limited by virtual address space */
4904 if (value > (2047 << 20)
4905 #ifndef CONFIG_KQEMU
4906 && HOST_LONG_BITS == 32
4907 #endif
4909 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4910 exit(1);
4912 if (value != (uint64_t)(ram_addr_t)value) {
4913 fprintf(stderr, "qemu: ram size too large\n");
4914 exit(1);
4916 ram_size = value;
4917 break;
4919 case QEMU_OPTION_d:
4921 int mask;
4922 const CPULogItem *item;
4924 mask = cpu_str_to_log_mask(optarg);
4925 if (!mask) {
4926 printf("Log items (comma separated):\n");
4927 for(item = cpu_log_items; item->mask != 0; item++) {
4928 printf("%-10s %s\n", item->name, item->help);
4930 exit(1);
4932 cpu_set_log(mask);
4934 break;
4935 #ifdef CONFIG_GDBSTUB
4936 case QEMU_OPTION_s:
4937 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4938 break;
4939 case QEMU_OPTION_gdb:
4940 gdbstub_dev = optarg;
4941 break;
4942 #endif
4943 case QEMU_OPTION_L:
4944 bios_dir = optarg;
4945 break;
4946 case QEMU_OPTION_bios:
4947 bios_name = optarg;
4948 break;
4949 case QEMU_OPTION_singlestep:
4950 singlestep = 1;
4951 break;
4952 case QEMU_OPTION_S:
4953 autostart = 0;
4954 break;
4955 #ifndef _WIN32
4956 case QEMU_OPTION_k:
4957 keyboard_layout = optarg;
4958 break;
4959 #endif
4960 case QEMU_OPTION_localtime:
4961 rtc_utc = 0;
4962 break;
4963 case QEMU_OPTION_vga:
4964 select_vgahw (optarg);
4965 break;
4966 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4967 case QEMU_OPTION_g:
4969 const char *p;
4970 int w, h, depth;
4971 p = optarg;
4972 w = strtol(p, (char **)&p, 10);
4973 if (w <= 0) {
4974 graphic_error:
4975 fprintf(stderr, "qemu: invalid resolution or depth\n");
4976 exit(1);
4978 if (*p != 'x')
4979 goto graphic_error;
4980 p++;
4981 h = strtol(p, (char **)&p, 10);
4982 if (h <= 0)
4983 goto graphic_error;
4984 if (*p == 'x') {
4985 p++;
4986 depth = strtol(p, (char **)&p, 10);
4987 if (depth != 8 && depth != 15 && depth != 16 &&
4988 depth != 24 && depth != 32)
4989 goto graphic_error;
4990 } else if (*p == '\0') {
4991 depth = graphic_depth;
4992 } else {
4993 goto graphic_error;
4996 graphic_width = w;
4997 graphic_height = h;
4998 graphic_depth = depth;
5000 break;
5001 #endif
5002 case QEMU_OPTION_echr:
5004 char *r;
5005 term_escape_char = strtol(optarg, &r, 0);
5006 if (r == optarg)
5007 printf("Bad argument to echr\n");
5008 break;
5010 case QEMU_OPTION_monitor:
5011 monitor_device = optarg;
5012 break;
5013 case QEMU_OPTION_serial:
5014 if (serial_device_index >= MAX_SERIAL_PORTS) {
5015 fprintf(stderr, "qemu: too many serial ports\n");
5016 exit(1);
5018 serial_devices[serial_device_index] = optarg;
5019 serial_device_index++;
5020 break;
5021 case QEMU_OPTION_virtiocon:
5022 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5023 fprintf(stderr, "qemu: too many virtio consoles\n");
5024 exit(1);
5026 virtio_consoles[virtio_console_index] = optarg;
5027 virtio_console_index++;
5028 break;
5029 case QEMU_OPTION_parallel:
5030 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5031 fprintf(stderr, "qemu: too many parallel ports\n");
5032 exit(1);
5034 parallel_devices[parallel_device_index] = optarg;
5035 parallel_device_index++;
5036 break;
5037 case QEMU_OPTION_loadvm:
5038 loadvm = optarg;
5039 break;
5040 case QEMU_OPTION_full_screen:
5041 full_screen = 1;
5042 break;
5043 #ifdef CONFIG_SDL
5044 case QEMU_OPTION_no_frame:
5045 no_frame = 1;
5046 break;
5047 case QEMU_OPTION_alt_grab:
5048 alt_grab = 1;
5049 break;
5050 case QEMU_OPTION_no_quit:
5051 no_quit = 1;
5052 break;
5053 case QEMU_OPTION_sdl:
5054 sdl = 1;
5055 break;
5056 #endif
5057 case QEMU_OPTION_pidfile:
5058 pid_file = optarg;
5059 break;
5060 #ifdef TARGET_I386
5061 case QEMU_OPTION_win2k_hack:
5062 win2k_install_hack = 1;
5063 break;
5064 case QEMU_OPTION_rtc_td_hack:
5065 rtc_td_hack = 1;
5066 break;
5067 case QEMU_OPTION_acpitable:
5068 if(acpi_table_add(optarg) < 0) {
5069 fprintf(stderr, "Wrong acpi table provided\n");
5070 exit(1);
5072 break;
5073 case QEMU_OPTION_smbios:
5074 if(smbios_entry_add(optarg) < 0) {
5075 fprintf(stderr, "Wrong smbios provided\n");
5076 exit(1);
5078 break;
5079 #endif
5080 #ifdef CONFIG_KQEMU
5081 case QEMU_OPTION_no_kqemu:
5082 kqemu_allowed = 0;
5083 break;
5084 case QEMU_OPTION_kernel_kqemu:
5085 kqemu_allowed = 2;
5086 break;
5087 #endif
5088 #ifdef CONFIG_KVM
5089 case QEMU_OPTION_enable_kvm:
5090 kvm_allowed = 1;
5091 #ifdef CONFIG_KQEMU
5092 kqemu_allowed = 0;
5093 #endif
5094 break;
5095 #endif
5096 #ifdef USE_KVM
5097 case QEMU_OPTION_no_kvm:
5098 kvm_allowed = 0;
5099 break;
5100 case QEMU_OPTION_no_kvm_irqchip: {
5101 kvm_irqchip = 0;
5102 kvm_pit = 0;
5103 break;
5105 case QEMU_OPTION_no_kvm_pit: {
5106 kvm_pit = 0;
5107 break;
5109 case QEMU_OPTION_no_kvm_pit_reinjection: {
5110 kvm_pit_reinject = 0;
5111 break;
5113 case QEMU_OPTION_enable_nesting: {
5114 kvm_nested = 1;
5115 break;
5117 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5118 case QEMU_OPTION_pcidevice:
5119 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5120 fprintf(stderr, "Too many assigned devices\n");
5121 exit(1);
5123 assigned_devices[assigned_devices_index] = optarg;
5124 assigned_devices_index++;
5125 break;
5126 #endif
5127 #endif
5128 case QEMU_OPTION_usb:
5129 usb_enabled = 1;
5130 break;
5131 case QEMU_OPTION_usbdevice:
5132 usb_enabled = 1;
5133 if (usb_devices_index >= MAX_USB_CMDLINE) {
5134 fprintf(stderr, "Too many USB devices\n");
5135 exit(1);
5137 usb_devices[usb_devices_index] = optarg;
5138 usb_devices_index++;
5139 break;
5140 case QEMU_OPTION_smp:
5141 smp_cpus = atoi(optarg);
5142 if (smp_cpus < 1) {
5143 fprintf(stderr, "Invalid number of CPUs\n");
5144 exit(1);
5146 break;
5147 case QEMU_OPTION_vnc:
5148 vnc_display = optarg;
5149 break;
5150 #ifdef TARGET_I386
5151 case QEMU_OPTION_no_acpi:
5152 acpi_enabled = 0;
5153 break;
5154 case QEMU_OPTION_no_hpet:
5155 no_hpet = 1;
5156 break;
5157 #endif
5158 case QEMU_OPTION_no_reboot:
5159 no_reboot = 1;
5160 break;
5161 case QEMU_OPTION_no_shutdown:
5162 no_shutdown = 1;
5163 break;
5164 case QEMU_OPTION_show_cursor:
5165 cursor_hide = 0;
5166 break;
5167 case QEMU_OPTION_uuid:
5168 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5169 fprintf(stderr, "Fail to parse UUID string."
5170 " Wrong format.\n");
5171 exit(1);
5173 break;
5174 #ifndef _WIN32
5175 case QEMU_OPTION_daemonize:
5176 daemonize = 1;
5177 break;
5178 #endif
5179 case QEMU_OPTION_option_rom:
5180 if (nb_option_roms >= MAX_OPTION_ROMS) {
5181 fprintf(stderr, "Too many option ROMs\n");
5182 exit(1);
5184 option_rom[nb_option_roms] = optarg;
5185 nb_option_roms++;
5186 break;
5187 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5188 case QEMU_OPTION_semihosting:
5189 semihosting_enabled = 1;
5190 break;
5191 #endif
5192 case QEMU_OPTION_tdf:
5193 time_drift_fix = 1;
5194 break;
5195 case QEMU_OPTION_kvm_shadow_memory:
5196 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5197 break;
5198 case QEMU_OPTION_mempath:
5199 mem_path = optarg;
5200 break;
5201 #ifdef MAP_POPULATE
5202 case QEMU_OPTION_mem_prealloc:
5203 mem_prealloc = !mem_prealloc;
5204 break;
5205 #endif
5206 case QEMU_OPTION_name:
5207 qemu_name = optarg;
5208 break;
5209 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5210 case QEMU_OPTION_prom_env:
5211 if (nb_prom_envs >= MAX_PROM_ENVS) {
5212 fprintf(stderr, "Too many prom variables\n");
5213 exit(1);
5215 prom_envs[nb_prom_envs] = optarg;
5216 nb_prom_envs++;
5217 break;
5218 #endif
5219 case QEMU_OPTION_cpu_vendor:
5220 cpu_vendor_string = optarg;
5221 break;
5222 #ifdef TARGET_ARM
5223 case QEMU_OPTION_old_param:
5224 old_param = 1;
5225 break;
5226 #endif
5227 case QEMU_OPTION_clock:
5228 configure_alarms(optarg);
5229 break;
5230 case QEMU_OPTION_startdate:
5232 struct tm tm;
5233 time_t rtc_start_date;
5234 if (!strcmp(optarg, "now")) {
5235 rtc_date_offset = -1;
5236 } else {
5237 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5238 &tm.tm_year,
5239 &tm.tm_mon,
5240 &tm.tm_mday,
5241 &tm.tm_hour,
5242 &tm.tm_min,
5243 &tm.tm_sec) == 6) {
5244 /* OK */
5245 } else if (sscanf(optarg, "%d-%d-%d",
5246 &tm.tm_year,
5247 &tm.tm_mon,
5248 &tm.tm_mday) == 3) {
5249 tm.tm_hour = 0;
5250 tm.tm_min = 0;
5251 tm.tm_sec = 0;
5252 } else {
5253 goto date_fail;
5255 tm.tm_year -= 1900;
5256 tm.tm_mon--;
5257 rtc_start_date = mktimegm(&tm);
5258 if (rtc_start_date == -1) {
5259 date_fail:
5260 fprintf(stderr, "Invalid date format. Valid format are:\n"
5261 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5262 exit(1);
5264 rtc_date_offset = time(NULL) - rtc_start_date;
5267 break;
5268 case QEMU_OPTION_tb_size:
5269 tb_size = strtol(optarg, NULL, 0);
5270 if (tb_size < 0)
5271 tb_size = 0;
5272 break;
5273 case QEMU_OPTION_icount:
5274 use_icount = 1;
5275 if (strcmp(optarg, "auto") == 0) {
5276 icount_time_shift = -1;
5277 } else {
5278 icount_time_shift = strtol(optarg, NULL, 0);
5280 break;
5281 case QEMU_OPTION_incoming:
5282 incoming = optarg;
5283 break;
5284 #ifndef _WIN32
5285 case QEMU_OPTION_chroot:
5286 chroot_dir = optarg;
5287 break;
5288 case QEMU_OPTION_runas:
5289 run_as = optarg;
5290 break;
5291 case QEMU_OPTION_nvram:
5292 nvram = optarg;
5293 break;
5294 #endif
5295 #ifdef CONFIG_XEN
5296 case QEMU_OPTION_xen_domid:
5297 xen_domid = atoi(optarg);
5298 break;
5299 case QEMU_OPTION_xen_create:
5300 xen_mode = XEN_CREATE;
5301 break;
5302 case QEMU_OPTION_xen_attach:
5303 xen_mode = XEN_ATTACH;
5304 break;
5305 #endif
5310 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5311 if (kvm_allowed && kqemu_allowed) {
5312 fprintf(stderr,
5313 "You can not enable both KVM and kqemu at the same time\n");
5314 exit(1);
5316 #endif
5318 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5319 if (smp_cpus > machine->max_cpus) {
5320 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5321 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5322 machine->max_cpus);
5323 exit(1);
5326 if (nographic) {
5327 if (serial_device_index == 0)
5328 serial_devices[0] = "stdio";
5329 if (parallel_device_index == 0)
5330 parallel_devices[0] = "null";
5331 if (strncmp(monitor_device, "vc", 2) == 0)
5332 monitor_device = "stdio";
5335 #ifndef _WIN32
5336 if (daemonize) {
5337 pid_t pid;
5339 if (pipe(fds) == -1)
5340 exit(1);
5342 pid = fork();
5343 if (pid > 0) {
5344 uint8_t status;
5345 ssize_t len;
5347 close(fds[1]);
5349 again:
5350 len = read(fds[0], &status, 1);
5351 if (len == -1 && (errno == EINTR))
5352 goto again;
5354 if (len != 1)
5355 exit(1);
5356 else if (status == 1) {
5357 fprintf(stderr, "Could not acquire pidfile\n");
5358 exit(1);
5359 } else
5360 exit(0);
5361 } else if (pid < 0)
5362 exit(1);
5364 setsid();
5366 pid = fork();
5367 if (pid > 0)
5368 exit(0);
5369 else if (pid < 0)
5370 exit(1);
5372 umask(027);
5374 signal(SIGTSTP, SIG_IGN);
5375 signal(SIGTTOU, SIG_IGN);
5376 signal(SIGTTIN, SIG_IGN);
5379 #ifdef USE_KVM
5380 if (kvm_enabled()) {
5381 if (kvm_qemu_init() < 0) {
5382 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5383 #ifdef NO_CPU_EMULATION
5384 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5385 exit(1);
5386 #endif
5387 kvm_allowed = 0;
5390 #endif
5392 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5393 if (daemonize) {
5394 uint8_t status = 1;
5395 write(fds[1], &status, 1);
5396 } else
5397 fprintf(stderr, "Could not acquire pid file\n");
5398 exit(1);
5400 #endif
5402 #ifdef CONFIG_KQEMU
5403 if (smp_cpus > 1)
5404 kqemu_allowed = 0;
5405 #endif
5406 linux_boot = (kernel_filename != NULL);
5407 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5409 if (!linux_boot && *kernel_cmdline != '\0') {
5410 fprintf(stderr, "-append only allowed with -kernel option\n");
5411 exit(1);
5414 if (!linux_boot && initrd_filename != NULL) {
5415 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5416 exit(1);
5419 /* boot to floppy or the default cd if no hard disk defined yet */
5420 if (!boot_devices[0]) {
5421 boot_devices = "cad";
5423 setvbuf(stdout, NULL, _IOLBF, 0);
5425 init_timers();
5426 if (init_timer_alarm() < 0) {
5427 fprintf(stderr, "could not initialize alarm timer\n");
5428 exit(1);
5430 if (use_icount && icount_time_shift < 0) {
5431 use_icount = 2;
5432 /* 125MIPS seems a reasonable initial guess at the guest speed.
5433 It will be corrected fairly quickly anyway. */
5434 icount_time_shift = 3;
5435 init_icount_adjust();
5438 #ifdef _WIN32
5439 socket_init();
5440 #endif
5442 /* init network clients */
5443 if (nb_net_clients == 0) {
5444 /* if no clients, we use a default config */
5445 net_clients[nb_net_clients++] = "nic";
5446 #ifdef CONFIG_SLIRP
5447 net_clients[nb_net_clients++] = "user";
5448 #endif
5451 for(i = 0;i < nb_net_clients; i++) {
5452 if (net_client_parse(net_clients[i]) < 0)
5453 exit(1);
5455 net_client_check();
5457 #ifdef TARGET_I386
5458 /* XXX: this should be moved in the PC machine instantiation code */
5459 if (net_boot != 0) {
5460 int netroms = 0;
5461 for (i = 0; i < nb_nics && i < 4; i++) {
5462 const char *model = nd_table[i].model;
5463 char buf[1024];
5464 if (net_boot & (1 << i)) {
5465 if (model == NULL)
5466 model = "rtl8139";
5467 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5468 if (get_image_size(buf) > 0) {
5469 if (nb_option_roms >= MAX_OPTION_ROMS) {
5470 fprintf(stderr, "Too many option ROMs\n");
5471 exit(1);
5473 option_rom[nb_option_roms] = strdup(buf);
5474 nb_option_roms++;
5475 netroms++;
5479 if (netroms == 0) {
5480 fprintf(stderr, "No valid PXE rom found for network device\n");
5481 exit(1);
5484 #endif
5486 /* init the bluetooth world */
5487 for (i = 0; i < nb_bt_opts; i++)
5488 if (bt_parse(bt_opts[i]))
5489 exit(1);
5491 /* init the memory */
5492 if (ram_size == 0)
5493 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5495 if (kvm_enabled()) {
5496 if (kvm_qemu_create_context() < 0) {
5497 fprintf(stderr, "Could not create KVM context\n");
5498 exit(1);
5502 #ifdef CONFIG_KQEMU
5503 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5504 guest ram allocation. It needs to go away. */
5505 if (kqemu_allowed) {
5506 kqemu_phys_ram_size = ram_size + VGA_RAM_SIZE + 4 * 1024 * 1024;
5507 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5508 if (!kqemu_phys_ram_base) {
5509 fprintf(stderr, "Could not allocate physical memory\n");
5510 exit(1);
5513 #endif
5515 /* init the dynamic translator */
5516 cpu_exec_init_all(tb_size * 1024 * 1024);
5518 bdrv_init();
5519 dma_helper_init();
5521 /* we always create the cdrom drive, even if no disk is there */
5523 if (nb_drives_opt < MAX_DRIVES)
5524 drive_add(NULL, CDROM_ALIAS);
5526 /* we always create at least one floppy */
5528 if (nb_drives_opt < MAX_DRIVES)
5529 drive_add(NULL, FD_ALIAS, 0);
5531 /* we always create one sd slot, even if no card is in it */
5533 if (nb_drives_opt < MAX_DRIVES)
5534 drive_add(NULL, SD_ALIAS);
5536 /* open the virtual block devices
5537 * note that migration with device
5538 * hot add/remove is broken.
5540 for(i = 0; i < nb_drives_opt; i++)
5541 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5542 exit(1);
5544 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5545 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5547 #ifndef _WIN32
5548 /* must be after terminal init, SDL library changes signal handlers */
5549 termsig_setup();
5550 #endif
5552 /* Maintain compatibility with multiple stdio monitors */
5553 if (!strcmp(monitor_device,"stdio")) {
5554 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5555 const char *devname = serial_devices[i];
5556 if (devname && !strcmp(devname,"mon:stdio")) {
5557 monitor_device = NULL;
5558 break;
5559 } else if (devname && !strcmp(devname,"stdio")) {
5560 monitor_device = NULL;
5561 serial_devices[i] = "mon:stdio";
5562 break;
5567 if (nb_numa_nodes > 0) {
5568 int i;
5570 if (nb_numa_nodes > smp_cpus) {
5571 nb_numa_nodes = smp_cpus;
5574 /* If no memory size if given for any node, assume the default case
5575 * and distribute the available memory equally across all nodes
5577 for (i = 0; i < nb_numa_nodes; i++) {
5578 if (node_mem[i] != 0)
5579 break;
5581 if (i == nb_numa_nodes) {
5582 uint64_t usedmem = 0;
5584 /* On Linux, the each node's border has to be 8MB aligned,
5585 * the final node gets the rest.
5587 for (i = 0; i < nb_numa_nodes - 1; i++) {
5588 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5589 usedmem += node_mem[i];
5591 node_mem[i] = ram_size - usedmem;
5594 for (i = 0; i < nb_numa_nodes; i++) {
5595 if (node_cpumask[i] != 0)
5596 break;
5598 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5599 * must cope with this anyway, because there are BIOSes out there in
5600 * real machines which also use this scheme.
5602 if (i == nb_numa_nodes) {
5603 for (i = 0; i < smp_cpus; i++) {
5604 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5609 #ifdef KVM_UPSTREAM
5610 if (kvm_enabled()) {
5611 int ret;
5613 ret = kvm_init(smp_cpus);
5614 if (ret < 0) {
5615 fprintf(stderr, "failed to initialize KVM\n");
5616 exit(1);
5619 #endif
5621 if (monitor_device) {
5622 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5623 if (!monitor_hd) {
5624 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5625 exit(1);
5629 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5630 const char *devname = serial_devices[i];
5631 if (devname && strcmp(devname, "none")) {
5632 char label[32];
5633 snprintf(label, sizeof(label), "serial%d", i);
5634 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5635 if (!serial_hds[i]) {
5636 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5637 devname);
5638 exit(1);
5643 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5644 const char *devname = parallel_devices[i];
5645 if (devname && strcmp(devname, "none")) {
5646 char label[32];
5647 snprintf(label, sizeof(label), "parallel%d", i);
5648 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5649 if (!parallel_hds[i]) {
5650 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5651 devname);
5652 exit(1);
5657 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5658 const char *devname = virtio_consoles[i];
5659 if (devname && strcmp(devname, "none")) {
5660 char label[32];
5661 snprintf(label, sizeof(label), "virtcon%d", i);
5662 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5663 if (!virtcon_hds[i]) {
5664 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5665 devname);
5666 exit(1);
5671 if (kvm_enabled())
5672 kvm_init_ap();
5674 machine->init(ram_size, vga_ram_size, boot_devices,
5675 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5678 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5679 for (i = 0; i < nb_numa_nodes; i++) {
5680 if (node_cpumask[i] & (1 << env->cpu_index)) {
5681 env->numa_node = i;
5686 current_machine = machine;
5688 /* Set KVM's vcpu state to qemu's initial CPUState. */
5689 if (kvm_enabled()) {
5690 int ret;
5692 ret = kvm_sync_vcpus();
5693 if (ret < 0) {
5694 fprintf(stderr, "failed to initialize vcpus\n");
5695 exit(1);
5699 /* init USB devices */
5700 if (usb_enabled) {
5701 for(i = 0; i < usb_devices_index; i++) {
5702 if (usb_device_add(usb_devices[i], 0) < 0) {
5703 fprintf(stderr, "Warning: could not add USB device %s\n",
5704 usb_devices[i]);
5709 if (!display_state)
5710 dumb_display_init();
5711 /* just use the first displaystate for the moment */
5712 ds = display_state;
5713 /* terminal init */
5714 if (nographic) {
5715 if (curses) {
5716 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5717 exit(1);
5719 } else {
5720 #if defined(CONFIG_CURSES)
5721 if (curses) {
5722 /* At the moment curses cannot be used with other displays */
5723 curses_display_init(ds, full_screen);
5724 } else
5725 #endif
5727 if (vnc_display != NULL) {
5728 vnc_display_init(ds);
5729 if (vnc_display_open(ds, vnc_display) < 0)
5730 exit(1);
5732 #if defined(CONFIG_SDL)
5733 if (sdl || !vnc_display)
5734 sdl_display_init(ds, full_screen, no_frame);
5735 #elif defined(CONFIG_COCOA)
5736 if (sdl || !vnc_display)
5737 cocoa_display_init(ds, full_screen);
5738 #endif
5741 dpy_resize(ds);
5743 dcl = ds->listeners;
5744 while (dcl != NULL) {
5745 if (dcl->dpy_refresh != NULL) {
5746 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5747 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5749 dcl = dcl->next;
5752 if (nographic || (vnc_display && !sdl)) {
5753 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5754 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5757 text_consoles_set_display(display_state);
5758 qemu_chr_initial_reset();
5760 if (monitor_device && monitor_hd)
5761 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5763 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5764 const char *devname = serial_devices[i];
5765 if (devname && strcmp(devname, "none")) {
5766 char label[32];
5767 snprintf(label, sizeof(label), "serial%d", i);
5768 if (strstart(devname, "vc", 0))
5769 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5773 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5774 const char *devname = parallel_devices[i];
5775 if (devname && strcmp(devname, "none")) {
5776 char label[32];
5777 snprintf(label, sizeof(label), "parallel%d", i);
5778 if (strstart(devname, "vc", 0))
5779 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5783 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5784 const char *devname = virtio_consoles[i];
5785 if (virtcon_hds[i] && devname) {
5786 char label[32];
5787 snprintf(label, sizeof(label), "virtcon%d", i);
5788 if (strstart(devname, "vc", 0))
5789 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5793 #ifdef CONFIG_GDBSTUB
5794 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5795 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5796 gdbstub_dev);
5797 exit(1);
5799 #endif
5801 if (loadvm)
5802 do_loadvm(cur_mon, loadvm);
5804 if (incoming) {
5805 autostart = 0; /* fixme how to deal with -daemonize */
5806 qemu_start_incoming_migration(incoming);
5809 if (autostart)
5810 vm_start();
5812 #ifndef _WIN32
5813 if (daemonize) {
5814 uint8_t status = 0;
5815 ssize_t len;
5817 again1:
5818 len = write(fds[1], &status, 1);
5819 if (len == -1 && (errno == EINTR))
5820 goto again1;
5822 if (len != 1)
5823 exit(1);
5825 chdir("/");
5826 TFR(fd = open("/dev/null", O_RDWR));
5827 if (fd == -1)
5828 exit(1);
5831 if (run_as) {
5832 pwd = getpwnam(run_as);
5833 if (!pwd) {
5834 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5835 exit(1);
5839 if (chroot_dir) {
5840 if (chroot(chroot_dir) < 0) {
5841 fprintf(stderr, "chroot failed\n");
5842 exit(1);
5844 chdir("/");
5847 if (run_as) {
5848 if (setgid(pwd->pw_gid) < 0) {
5849 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5850 exit(1);
5852 if (setuid(pwd->pw_uid) < 0) {
5853 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5854 exit(1);
5856 if (setuid(0) != -1) {
5857 fprintf(stderr, "Dropping privileges failed\n");
5858 exit(1);
5862 if (daemonize) {
5863 dup2(fd, 0);
5864 dup2(fd, 1);
5865 dup2(fd, 2);
5867 close(fd);
5869 #endif
5871 main_loop();
5872 quit_timers();
5873 net_cleanup();
5875 return 0;