kvm: bios: resolve memory device roll over reporting issues with >32G guests
[qemu-kvm/fedora.git] / vl.c
blob6614b1263dcd345ec17939061b036f1b69d88a1d
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 "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "block.h"
40 #include "audio/audio.h"
41 #include "hw/device-assignment.h"
42 #include "migration.h"
43 #include "kvm.h"
44 #include "balloon.h"
45 #include "qemu-kvm.h"
47 #include <unistd.h>
48 #include <fcntl.h>
49 #include <signal.h>
50 #include <time.h>
51 #include <errno.h>
52 #include <sys/time.h>
53 #include <zlib.h>
55 #ifndef _WIN32
56 #include <sys/times.h>
57 #include <sys/wait.h>
58 #include <termios.h>
59 #include <sys/mman.h>
60 #include <sys/ioctl.h>
61 #include <sys/resource.h>
62 #include <sys/socket.h>
63 #include <netinet/in.h>
64 #include <net/if.h>
65 #if defined(__NetBSD__)
66 #include <net/if_tap.h>
67 #endif
68 #ifdef __linux__
69 #include <linux/if_tun.h>
70 #endif
71 #include <arpa/inet.h>
72 #include <dirent.h>
73 #include <netdb.h>
74 #include <sys/select.h>
75 #ifdef _BSD
76 #include <sys/stat.h>
77 #ifdef __FreeBSD__
78 #include <libutil.h>
79 #else
80 #include <util.h>
81 #endif
82 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
83 #include <freebsd/stdlib.h>
84 #else
85 #ifdef __linux__
86 #include <pty.h>
87 #include <malloc.h>
88 #include <linux/rtc.h>
90 /* For the benefit of older linux systems which don't supply it,
91 we use a local copy of hpet.h. */
92 /* #include <linux/hpet.h> */
93 #include "hpet.h"
95 #include <linux/ppdev.h>
96 #include <linux/parport.h>
97 #endif
98 #ifdef __sun__
99 #include <sys/stat.h>
100 #include <sys/ethernet.h>
101 #include <sys/sockio.h>
102 #include <netinet/arp.h>
103 #include <netinet/in.h>
104 #include <netinet/in_systm.h>
105 #include <netinet/ip.h>
106 #include <netinet/ip_icmp.h> // must come after ip.h
107 #include <netinet/udp.h>
108 #include <netinet/tcp.h>
109 #include <net/if.h>
110 #include <syslog.h>
111 #include <stropts.h>
112 #endif
113 #endif
114 #endif
116 #include "qemu_socket.h"
118 #if defined(CONFIG_SLIRP)
119 #include "libslirp.h"
120 #endif
122 #if defined(__OpenBSD__)
123 #include <util.h>
124 #endif
126 #if defined(CONFIG_VDE)
127 #include <libvdeplug.h>
128 #endif
130 #ifdef _WIN32
131 #include <malloc.h>
132 #include <sys/timeb.h>
133 #include <mmsystem.h>
134 #define getopt_long_only getopt_long
135 #define memalign(align, size) malloc(size)
136 #endif
138 #ifdef CONFIG_SDL
139 #ifdef __APPLE__
140 #include <SDL/SDL.h>
141 #endif
142 #endif /* CONFIG_SDL */
144 #ifdef CONFIG_COCOA
145 #undef main
146 #define main qemu_main
147 #endif /* CONFIG_COCOA */
149 #include "disas.h"
151 #include "exec-all.h"
153 #include "qemu-kvm.h"
155 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
156 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
157 #ifdef __sun__
158 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
159 #else
160 #define SMBD_COMMAND "/usr/sbin/smbd"
161 #endif
163 //#define DEBUG_UNUSED_IOPORT
164 //#define DEBUG_IOPORT
165 //#define DEBUG_NET
166 //#define DEBUG_SLIRP
168 #ifdef TARGET_PPC
169 #define DEFAULT_RAM_SIZE 144
170 #else
171 #define DEFAULT_RAM_SIZE 128
172 #endif
174 /* Max number of USB devices that can be specified on the commandline. */
175 #define MAX_USB_CMDLINE 8
177 /* Max number of bluetooth switches on the commandline. */
178 #define MAX_BT_CMDLINE 10
180 /* XXX: use a two level table to limit memory usage */
181 #define MAX_IOPORTS 65536
183 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
184 const char *bios_name = NULL;
185 static void *ioport_opaque[MAX_IOPORTS];
186 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
187 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
188 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
189 to store the VM snapshots */
190 DriveInfo drives_table[MAX_DRIVES+1];
191 int nb_drives;
192 int extboot_drive = -1;
193 static int vga_ram_size;
194 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
195 DisplayState display_state;
196 int nographic;
197 static int curses;
198 const char* keyboard_layout = NULL;
199 int64_t ticks_per_sec;
200 ram_addr_t ram_size;
201 int nb_nics;
202 NICInfo nd_table[MAX_NICS];
203 int vm_running;
204 static int rtc_utc = 1;
205 static int rtc_date_offset = -1; /* -1 means no change */
206 int cirrus_vga_enabled = 1;
207 int vmsvga_enabled = 0;
208 #ifdef TARGET_SPARC
209 int graphic_width = 1024;
210 int graphic_height = 768;
211 int graphic_depth = 8;
212 #else
213 int graphic_width = 800;
214 int graphic_height = 600;
215 int graphic_depth = 15;
216 #endif
217 static int full_screen = 0;
218 static int no_frame = 0;
219 int no_quit = 0;
220 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
221 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
222 #ifdef TARGET_I386
223 int win2k_install_hack = 0;
224 #endif
225 int usb_enabled = 0;
226 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
227 int assigned_devices_index;
228 int smp_cpus = 1;
229 const char *vnc_display;
230 int acpi_enabled = 1;
231 int fd_bootchk = 1;
232 int no_reboot = 0;
233 int no_shutdown = 0;
234 int cursor_hide = 1;
235 int graphic_rotate = 0;
236 int daemonize = 0;
237 const char *incoming;
238 const char *option_rom[MAX_OPTION_ROMS];
239 int nb_option_roms;
240 int semihosting_enabled = 0;
241 int time_drift_fix = 0;
242 unsigned int kvm_shadow_memory = 0;
243 const char *mem_path = NULL;
244 int hpagesize = 0;
245 const char *cpu_vendor_string;
246 #ifdef TARGET_ARM
247 int old_param = 0;
248 #endif
249 const char *qemu_name;
250 int alt_grab = 0;
251 #ifdef TARGET_SPARC
252 unsigned int nb_prom_envs = 0;
253 const char *prom_envs[MAX_PROM_ENVS];
254 #endif
255 int nb_drives_opt;
256 struct drive_opt drives_opt[MAX_DRIVES];
258 static CPUState *cur_cpu;
259 static CPUState *next_cpu;
260 static int event_pending = 1;
261 /* Conversion factor from emulated instructions to virtual clock ticks. */
262 static int icount_time_shift;
263 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
264 #define MAX_ICOUNT_SHIFT 10
265 /* Compensate for varying guest execution speed. */
266 static int64_t qemu_icount_bias;
267 static QEMUTimer *icount_rt_timer;
268 static QEMUTimer *icount_vm_timer;
270 uint8_t qemu_uuid[16];
272 /* KVM runs the main loop in a separate thread. If we update one of the lists
273 * that are polled before or after select(), we need to make sure to break out
274 * of the select() to ensure the new item is serviced.
276 static void main_loop_break(void)
278 if (kvm_enabled())
279 qemu_kvm_notify_work();
282 /***********************************************************/
283 /* x86 ISA bus support */
285 target_phys_addr_t isa_mem_base = 0;
286 PicState2 *isa_pic;
288 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
289 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
291 static uint32_t ioport_read(int index, uint32_t address)
293 static IOPortReadFunc *default_func[3] = {
294 default_ioport_readb,
295 default_ioport_readw,
296 default_ioport_readl
298 IOPortReadFunc *func = ioport_read_table[index][address];
299 if (!func)
300 func = default_func[index];
301 return func(ioport_opaque[address], address);
304 static void ioport_write(int index, uint32_t address, uint32_t data)
306 static IOPortWriteFunc *default_func[3] = {
307 default_ioport_writeb,
308 default_ioport_writew,
309 default_ioport_writel
311 IOPortWriteFunc *func = ioport_write_table[index][address];
312 if (!func)
313 func = default_func[index];
314 func(ioport_opaque[address], address, data);
317 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
319 #ifdef DEBUG_UNUSED_IOPORT
320 fprintf(stderr, "unused inb: port=0x%04x\n", address);
321 #endif
322 return 0xff;
325 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
327 #ifdef DEBUG_UNUSED_IOPORT
328 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
329 #endif
332 /* default is to make two byte accesses */
333 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
335 uint32_t data;
336 data = ioport_read(0, address);
337 address = (address + 1) & (MAX_IOPORTS - 1);
338 data |= ioport_read(0, address) << 8;
339 return data;
342 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
344 ioport_write(0, address, data & 0xff);
345 address = (address + 1) & (MAX_IOPORTS - 1);
346 ioport_write(0, address, (data >> 8) & 0xff);
349 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
351 #ifdef DEBUG_UNUSED_IOPORT
352 fprintf(stderr, "unused inl: port=0x%04x\n", address);
353 #endif
354 return 0xffffffff;
357 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
359 #ifdef DEBUG_UNUSED_IOPORT
360 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
361 #endif
364 /* size is the word size in byte */
365 int register_ioport_read(int start, int length, int size,
366 IOPortReadFunc *func, void *opaque)
368 int i, bsize;
370 if (size == 1) {
371 bsize = 0;
372 } else if (size == 2) {
373 bsize = 1;
374 } else if (size == 4) {
375 bsize = 2;
376 } else {
377 hw_error("register_ioport_read: invalid size");
378 return -1;
380 for(i = start; i < start + length; i += size) {
381 ioport_read_table[bsize][i] = func;
382 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
383 hw_error("register_ioport_read: invalid opaque");
384 ioport_opaque[i] = opaque;
386 return 0;
389 /* size is the word size in byte */
390 int register_ioport_write(int start, int length, int size,
391 IOPortWriteFunc *func, void *opaque)
393 int i, bsize;
395 if (size == 1) {
396 bsize = 0;
397 } else if (size == 2) {
398 bsize = 1;
399 } else if (size == 4) {
400 bsize = 2;
401 } else {
402 hw_error("register_ioport_write: invalid size");
403 return -1;
405 for(i = start; i < start + length; i += size) {
406 ioport_write_table[bsize][i] = func;
407 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
408 hw_error("register_ioport_write: invalid opaque");
409 ioport_opaque[i] = opaque;
411 return 0;
414 void isa_unassign_ioport(int start, int length)
416 int i;
418 for(i = start; i < start + length; i++) {
419 ioport_read_table[0][i] = default_ioport_readb;
420 ioport_read_table[1][i] = default_ioport_readw;
421 ioport_read_table[2][i] = default_ioport_readl;
423 ioport_write_table[0][i] = default_ioport_writeb;
424 ioport_write_table[1][i] = default_ioport_writew;
425 ioport_write_table[2][i] = default_ioport_writel;
427 ioport_opaque[i] = NULL;
431 /***********************************************************/
433 void cpu_outb(CPUState *env, int addr, int val)
435 #ifdef DEBUG_IOPORT
436 if (loglevel & CPU_LOG_IOPORT)
437 fprintf(logfile, "outb: %04x %02x\n", addr, val);
438 #endif
439 ioport_write(0, addr, val);
440 #ifdef USE_KQEMU
441 if (env)
442 env->last_io_time = cpu_get_time_fast();
443 #endif
446 void cpu_outw(CPUState *env, int addr, int val)
448 #ifdef DEBUG_IOPORT
449 if (loglevel & CPU_LOG_IOPORT)
450 fprintf(logfile, "outw: %04x %04x\n", addr, val);
451 #endif
452 ioport_write(1, addr, val);
453 #ifdef USE_KQEMU
454 if (env)
455 env->last_io_time = cpu_get_time_fast();
456 #endif
459 void cpu_outl(CPUState *env, int addr, int val)
461 #ifdef DEBUG_IOPORT
462 if (loglevel & CPU_LOG_IOPORT)
463 fprintf(logfile, "outl: %04x %08x\n", addr, val);
464 #endif
465 ioport_write(2, addr, val);
466 #ifdef USE_KQEMU
467 if (env)
468 env->last_io_time = cpu_get_time_fast();
469 #endif
472 int cpu_inb(CPUState *env, int addr)
474 int val;
475 val = ioport_read(0, addr);
476 #ifdef DEBUG_IOPORT
477 if (loglevel & CPU_LOG_IOPORT)
478 fprintf(logfile, "inb : %04x %02x\n", addr, val);
479 #endif
480 #ifdef USE_KQEMU
481 if (env)
482 env->last_io_time = cpu_get_time_fast();
483 #endif
484 return val;
487 int cpu_inw(CPUState *env, int addr)
489 int val;
490 val = ioport_read(1, addr);
491 #ifdef DEBUG_IOPORT
492 if (loglevel & CPU_LOG_IOPORT)
493 fprintf(logfile, "inw : %04x %04x\n", addr, val);
494 #endif
495 #ifdef USE_KQEMU
496 if (env)
497 env->last_io_time = cpu_get_time_fast();
498 #endif
499 return val;
502 int cpu_inl(CPUState *env, int addr)
504 int val;
505 val = ioport_read(2, addr);
506 #ifdef DEBUG_IOPORT
507 if (loglevel & CPU_LOG_IOPORT)
508 fprintf(logfile, "inl : %04x %08x\n", addr, val);
509 #endif
510 #ifdef USE_KQEMU
511 if (env)
512 env->last_io_time = cpu_get_time_fast();
513 #endif
514 return val;
517 /***********************************************************/
518 void hw_error(const char *fmt, ...)
520 va_list ap;
521 CPUState *env;
523 va_start(ap, fmt);
524 fprintf(stderr, "qemu: hardware error: ");
525 vfprintf(stderr, fmt, ap);
526 fprintf(stderr, "\n");
527 for(env = first_cpu; env != NULL; env = env->next_cpu) {
528 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
529 #ifdef TARGET_I386
530 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
531 #else
532 cpu_dump_state(env, stderr, fprintf, 0);
533 #endif
535 va_end(ap);
536 abort();
539 /***************/
540 /* ballooning */
542 static QEMUBalloonEvent *qemu_balloon_event;
543 void *qemu_balloon_event_opaque;
545 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
547 qemu_balloon_event = func;
548 qemu_balloon_event_opaque = opaque;
551 void qemu_balloon(ram_addr_t target)
553 if (qemu_balloon_event)
554 qemu_balloon_event(qemu_balloon_event_opaque, target);
557 ram_addr_t qemu_balloon_status(void)
559 if (qemu_balloon_event)
560 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
561 return 0;
564 /***********************************************************/
565 /* keyboard/mouse */
567 static QEMUPutKBDEvent *qemu_put_kbd_event;
568 static void *qemu_put_kbd_event_opaque;
569 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
570 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
572 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
574 qemu_put_kbd_event_opaque = opaque;
575 qemu_put_kbd_event = func;
578 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
579 void *opaque, int absolute,
580 const char *name)
582 QEMUPutMouseEntry *s, *cursor;
584 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
585 if (!s)
586 return NULL;
588 s->qemu_put_mouse_event = func;
589 s->qemu_put_mouse_event_opaque = opaque;
590 s->qemu_put_mouse_event_absolute = absolute;
591 s->qemu_put_mouse_event_name = qemu_strdup(name);
592 s->next = NULL;
594 if (!qemu_put_mouse_event_head) {
595 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
596 return s;
599 cursor = qemu_put_mouse_event_head;
600 while (cursor->next != NULL)
601 cursor = cursor->next;
603 cursor->next = s;
604 qemu_put_mouse_event_current = s;
606 return s;
609 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
611 QEMUPutMouseEntry *prev = NULL, *cursor;
613 if (!qemu_put_mouse_event_head || entry == NULL)
614 return;
616 cursor = qemu_put_mouse_event_head;
617 while (cursor != NULL && cursor != entry) {
618 prev = cursor;
619 cursor = cursor->next;
622 if (cursor == NULL) // does not exist or list empty
623 return;
624 else if (prev == NULL) { // entry is head
625 qemu_put_mouse_event_head = cursor->next;
626 if (qemu_put_mouse_event_current == entry)
627 qemu_put_mouse_event_current = cursor->next;
628 qemu_free(entry->qemu_put_mouse_event_name);
629 qemu_free(entry);
630 return;
633 prev->next = entry->next;
635 if (qemu_put_mouse_event_current == entry)
636 qemu_put_mouse_event_current = prev;
638 qemu_free(entry->qemu_put_mouse_event_name);
639 qemu_free(entry);
642 void kbd_put_keycode(int keycode)
644 if (qemu_put_kbd_event) {
645 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
649 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
651 QEMUPutMouseEvent *mouse_event;
652 void *mouse_event_opaque;
653 int width;
655 if (!qemu_put_mouse_event_current) {
656 return;
659 mouse_event =
660 qemu_put_mouse_event_current->qemu_put_mouse_event;
661 mouse_event_opaque =
662 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
664 if (mouse_event) {
665 if (graphic_rotate) {
666 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
667 width = 0x7fff;
668 else
669 width = graphic_width - 1;
670 mouse_event(mouse_event_opaque,
671 width - dy, dx, dz, buttons_state);
672 } else
673 mouse_event(mouse_event_opaque,
674 dx, dy, dz, buttons_state);
678 int kbd_mouse_is_absolute(void)
680 if (!qemu_put_mouse_event_current)
681 return 0;
683 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
686 void do_info_mice(void)
688 QEMUPutMouseEntry *cursor;
689 int index = 0;
691 if (!qemu_put_mouse_event_head) {
692 term_printf("No mouse devices connected\n");
693 return;
696 term_printf("Mouse devices available:\n");
697 cursor = qemu_put_mouse_event_head;
698 while (cursor != NULL) {
699 term_printf("%c Mouse #%d: %s\n",
700 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
701 index, cursor->qemu_put_mouse_event_name);
702 index++;
703 cursor = cursor->next;
707 void do_mouse_set(int index)
709 QEMUPutMouseEntry *cursor;
710 int i = 0;
712 if (!qemu_put_mouse_event_head) {
713 term_printf("No mouse devices connected\n");
714 return;
717 cursor = qemu_put_mouse_event_head;
718 while (cursor != NULL && index != i) {
719 i++;
720 cursor = cursor->next;
723 if (cursor != NULL)
724 qemu_put_mouse_event_current = cursor;
725 else
726 term_printf("Mouse at given index not found\n");
729 /* compute with 96 bit intermediate result: (a*b)/c */
730 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
732 union {
733 uint64_t ll;
734 struct {
735 #ifdef WORDS_BIGENDIAN
736 uint32_t high, low;
737 #else
738 uint32_t low, high;
739 #endif
740 } l;
741 } u, res;
742 uint64_t rl, rh;
744 u.ll = a;
745 rl = (uint64_t)u.l.low * (uint64_t)b;
746 rh = (uint64_t)u.l.high * (uint64_t)b;
747 rh += (rl >> 32);
748 res.l.high = rh / c;
749 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
750 return res.ll;
753 /***********************************************************/
754 /* real time host monotonic timer */
756 #define QEMU_TIMER_BASE 1000000000LL
758 #ifdef WIN32
760 static int64_t clock_freq;
762 static void init_get_clock(void)
764 LARGE_INTEGER freq;
765 int ret;
766 ret = QueryPerformanceFrequency(&freq);
767 if (ret == 0) {
768 fprintf(stderr, "Could not calibrate ticks\n");
769 exit(1);
771 clock_freq = freq.QuadPart;
774 static int64_t get_clock(void)
776 LARGE_INTEGER ti;
777 QueryPerformanceCounter(&ti);
778 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
781 #else
783 static int use_rt_clock;
785 static void init_get_clock(void)
787 use_rt_clock = 0;
788 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
790 struct timespec ts;
791 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
792 use_rt_clock = 1;
795 #endif
798 static int64_t get_clock(void)
800 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
801 if (use_rt_clock) {
802 struct timespec ts;
803 clock_gettime(CLOCK_MONOTONIC, &ts);
804 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
805 } else
806 #endif
808 /* XXX: using gettimeofday leads to problems if the date
809 changes, so it should be avoided. */
810 struct timeval tv;
811 gettimeofday(&tv, NULL);
812 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
815 #endif
817 /* Return the virtual CPU time, based on the instruction counter. */
818 static int64_t cpu_get_icount(void)
820 int64_t icount;
821 CPUState *env = cpu_single_env;;
822 icount = qemu_icount;
823 if (env) {
824 if (!can_do_io(env))
825 fprintf(stderr, "Bad clock read\n");
826 icount -= (env->icount_decr.u16.low + env->icount_extra);
828 return qemu_icount_bias + (icount << icount_time_shift);
831 /***********************************************************/
832 /* guest cycle counter */
834 static int64_t cpu_ticks_prev;
835 static int64_t cpu_ticks_offset;
836 static int64_t cpu_clock_offset;
837 static int cpu_ticks_enabled;
839 /* return the host CPU cycle counter and handle stop/restart */
840 int64_t cpu_get_ticks(void)
842 if (use_icount) {
843 return cpu_get_icount();
845 if (!cpu_ticks_enabled) {
846 return cpu_ticks_offset;
847 } else {
848 int64_t ticks;
849 ticks = cpu_get_real_ticks();
850 if (cpu_ticks_prev > ticks) {
851 /* Note: non increasing ticks may happen if the host uses
852 software suspend */
853 cpu_ticks_offset += cpu_ticks_prev - ticks;
855 cpu_ticks_prev = ticks;
856 return ticks + cpu_ticks_offset;
860 /* return the host CPU monotonic timer and handle stop/restart */
861 static int64_t cpu_get_clock(void)
863 int64_t ti;
864 if (!cpu_ticks_enabled) {
865 return cpu_clock_offset;
866 } else {
867 ti = get_clock();
868 return ti + cpu_clock_offset;
872 /* enable cpu_get_ticks() */
873 void cpu_enable_ticks(void)
875 if (!cpu_ticks_enabled) {
876 cpu_ticks_offset -= cpu_get_real_ticks();
877 cpu_clock_offset -= get_clock();
878 cpu_ticks_enabled = 1;
882 /* disable cpu_get_ticks() : the clock is stopped. You must not call
883 cpu_get_ticks() after that. */
884 void cpu_disable_ticks(void)
886 if (cpu_ticks_enabled) {
887 cpu_ticks_offset = cpu_get_ticks();
888 cpu_clock_offset = cpu_get_clock();
889 cpu_ticks_enabled = 0;
893 /***********************************************************/
894 /* timers */
896 #define QEMU_TIMER_REALTIME 0
897 #define QEMU_TIMER_VIRTUAL 1
899 struct QEMUClock {
900 int type;
901 /* XXX: add frequency */
904 struct QEMUTimer {
905 QEMUClock *clock;
906 int64_t expire_time;
907 QEMUTimerCB *cb;
908 void *opaque;
909 struct QEMUTimer *next;
912 struct qemu_alarm_timer {
913 char const *name;
914 unsigned int flags;
916 int (*start)(struct qemu_alarm_timer *t);
917 void (*stop)(struct qemu_alarm_timer *t);
918 void (*rearm)(struct qemu_alarm_timer *t);
919 void *priv;
922 #define ALARM_FLAG_DYNTICKS 0x1
923 #define ALARM_FLAG_EXPIRED 0x2
925 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
927 return t->flags & ALARM_FLAG_DYNTICKS;
930 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
932 if (!alarm_has_dynticks(t))
933 return;
935 t->rearm(t);
938 /* TODO: MIN_TIMER_REARM_US should be optimized */
939 #define MIN_TIMER_REARM_US 250
941 static struct qemu_alarm_timer *alarm_timer;
942 #ifndef _WIN32
943 static int alarm_timer_rfd, alarm_timer_wfd;
944 #endif
946 #ifdef _WIN32
948 struct qemu_alarm_win32 {
949 MMRESULT timerId;
950 HANDLE host_alarm;
951 unsigned int period;
952 } alarm_win32_data = {0, NULL, -1};
954 static int win32_start_timer(struct qemu_alarm_timer *t);
955 static void win32_stop_timer(struct qemu_alarm_timer *t);
956 static void win32_rearm_timer(struct qemu_alarm_timer *t);
958 #else
960 static int unix_start_timer(struct qemu_alarm_timer *t);
961 static void unix_stop_timer(struct qemu_alarm_timer *t);
963 #ifdef __linux__
965 static int dynticks_start_timer(struct qemu_alarm_timer *t);
966 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
967 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
969 static int hpet_start_timer(struct qemu_alarm_timer *t);
970 static void hpet_stop_timer(struct qemu_alarm_timer *t);
972 static int rtc_start_timer(struct qemu_alarm_timer *t);
973 static void rtc_stop_timer(struct qemu_alarm_timer *t);
975 #endif /* __linux__ */
977 #endif /* _WIN32 */
979 /* Correlation between real and virtual time is always going to be
980 fairly approximate, so ignore small variation.
981 When the guest is idle real and virtual time will be aligned in
982 the IO wait loop. */
983 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
985 static void icount_adjust(void)
987 int64_t cur_time;
988 int64_t cur_icount;
989 int64_t delta;
990 static int64_t last_delta;
991 /* If the VM is not running, then do nothing. */
992 if (!vm_running)
993 return;
995 cur_time = cpu_get_clock();
996 cur_icount = qemu_get_clock(vm_clock);
997 delta = cur_icount - cur_time;
998 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
999 if (delta > 0
1000 && last_delta + ICOUNT_WOBBLE < delta * 2
1001 && icount_time_shift > 0) {
1002 /* The guest is getting too far ahead. Slow time down. */
1003 icount_time_shift--;
1005 if (delta < 0
1006 && last_delta - ICOUNT_WOBBLE > delta * 2
1007 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1008 /* The guest is getting too far behind. Speed time up. */
1009 icount_time_shift++;
1011 last_delta = delta;
1012 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1015 static void icount_adjust_rt(void * opaque)
1017 qemu_mod_timer(icount_rt_timer,
1018 qemu_get_clock(rt_clock) + 1000);
1019 icount_adjust();
1022 static void icount_adjust_vm(void * opaque)
1024 qemu_mod_timer(icount_vm_timer,
1025 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1026 icount_adjust();
1029 static void init_icount_adjust(void)
1031 /* Have both realtime and virtual time triggers for speed adjustment.
1032 The realtime trigger catches emulated time passing too slowly,
1033 the virtual time trigger catches emulated time passing too fast.
1034 Realtime triggers occur even when idle, so use them less frequently
1035 than VM triggers. */
1036 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1037 qemu_mod_timer(icount_rt_timer,
1038 qemu_get_clock(rt_clock) + 1000);
1039 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1040 qemu_mod_timer(icount_vm_timer,
1041 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1044 static struct qemu_alarm_timer alarm_timers[] = {
1045 #ifndef _WIN32
1046 #ifdef __linux__
1047 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1048 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1049 /* HPET - if available - is preferred */
1050 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1051 /* ...otherwise try RTC */
1052 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1053 #endif
1054 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1055 #else
1056 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1057 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1058 {"win32", 0, win32_start_timer,
1059 win32_stop_timer, NULL, &alarm_win32_data},
1060 #endif
1061 {NULL, }
1064 static void show_available_alarms(void)
1066 int i;
1068 printf("Available alarm timers, in order of precedence:\n");
1069 for (i = 0; alarm_timers[i].name; i++)
1070 printf("%s\n", alarm_timers[i].name);
1073 static void configure_alarms(char const *opt)
1075 int i;
1076 int cur = 0;
1077 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1078 char *arg;
1079 char *name;
1080 struct qemu_alarm_timer tmp;
1082 if (!strcmp(opt, "?")) {
1083 show_available_alarms();
1084 exit(0);
1087 arg = strdup(opt);
1089 /* Reorder the array */
1090 name = strtok(arg, ",");
1091 while (name) {
1092 for (i = 0; i < count && alarm_timers[i].name; i++) {
1093 if (!strcmp(alarm_timers[i].name, name))
1094 break;
1097 if (i == count) {
1098 fprintf(stderr, "Unknown clock %s\n", name);
1099 goto next;
1102 if (i < cur)
1103 /* Ignore */
1104 goto next;
1106 /* Swap */
1107 tmp = alarm_timers[i];
1108 alarm_timers[i] = alarm_timers[cur];
1109 alarm_timers[cur] = tmp;
1111 cur++;
1112 next:
1113 name = strtok(NULL, ",");
1116 free(arg);
1118 if (cur) {
1119 /* Disable remaining timers */
1120 for (i = cur; i < count; i++)
1121 alarm_timers[i].name = NULL;
1122 } else {
1123 show_available_alarms();
1124 exit(1);
1128 QEMUClock *rt_clock;
1129 QEMUClock *vm_clock;
1131 static QEMUTimer *active_timers[2];
1133 static QEMUClock *qemu_new_clock(int type)
1135 QEMUClock *clock;
1136 clock = qemu_mallocz(sizeof(QEMUClock));
1137 if (!clock)
1138 return NULL;
1139 clock->type = type;
1140 return clock;
1143 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1145 QEMUTimer *ts;
1147 ts = qemu_mallocz(sizeof(QEMUTimer));
1148 ts->clock = clock;
1149 ts->cb = cb;
1150 ts->opaque = opaque;
1151 return ts;
1154 void qemu_free_timer(QEMUTimer *ts)
1156 qemu_free(ts);
1159 /* stop a timer, but do not dealloc it */
1160 void qemu_del_timer(QEMUTimer *ts)
1162 QEMUTimer **pt, *t;
1164 /* NOTE: this code must be signal safe because
1165 qemu_timer_expired() can be called from a signal. */
1166 pt = &active_timers[ts->clock->type];
1167 for(;;) {
1168 t = *pt;
1169 if (!t)
1170 break;
1171 if (t == ts) {
1172 *pt = t->next;
1173 break;
1175 pt = &t->next;
1179 /* modify the current timer so that it will be fired when current_time
1180 >= expire_time. The corresponding callback will be called. */
1181 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1183 QEMUTimer **pt, *t;
1185 qemu_del_timer(ts);
1187 /* add the timer in the sorted list */
1188 /* NOTE: this code must be signal safe because
1189 qemu_timer_expired() can be called from a signal. */
1190 pt = &active_timers[ts->clock->type];
1191 for(;;) {
1192 t = *pt;
1193 if (!t)
1194 break;
1195 if (t->expire_time > expire_time)
1196 break;
1197 pt = &t->next;
1199 ts->expire_time = expire_time;
1200 ts->next = *pt;
1201 *pt = ts;
1203 /* Rearm if necessary */
1204 if (pt == &active_timers[ts->clock->type]) {
1205 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1206 qemu_rearm_alarm_timer(alarm_timer);
1208 /* Interrupt execution to force deadline recalculation. */
1209 if (use_icount && cpu_single_env) {
1210 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1215 int qemu_timer_pending(QEMUTimer *ts)
1217 QEMUTimer *t;
1218 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1219 if (t == ts)
1220 return 1;
1222 return 0;
1225 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1227 if (!timer_head)
1228 return 0;
1229 return (timer_head->expire_time <= current_time);
1232 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1234 QEMUTimer *ts;
1236 for(;;) {
1237 ts = *ptimer_head;
1238 if (!ts || ts->expire_time > current_time)
1239 break;
1240 /* remove timer from the list before calling the callback */
1241 *ptimer_head = ts->next;
1242 ts->next = NULL;
1244 /* run the callback (the timer list can be modified) */
1245 ts->cb(ts->opaque);
1249 int64_t qemu_get_clock(QEMUClock *clock)
1251 switch(clock->type) {
1252 case QEMU_TIMER_REALTIME:
1253 return get_clock() / 1000000;
1254 default:
1255 case QEMU_TIMER_VIRTUAL:
1256 if (use_icount) {
1257 return cpu_get_icount();
1258 } else {
1259 return cpu_get_clock();
1264 static void init_timers(void)
1266 init_get_clock();
1267 ticks_per_sec = QEMU_TIMER_BASE;
1268 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1269 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1272 /* save a timer */
1273 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1275 uint64_t expire_time;
1277 if (qemu_timer_pending(ts)) {
1278 expire_time = ts->expire_time;
1279 } else {
1280 expire_time = -1;
1282 qemu_put_be64(f, expire_time);
1285 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1287 uint64_t expire_time;
1289 expire_time = qemu_get_be64(f);
1290 if (expire_time != -1) {
1291 qemu_mod_timer(ts, expire_time);
1292 } else {
1293 qemu_del_timer(ts);
1297 static void timer_save(QEMUFile *f, void *opaque)
1299 if (cpu_ticks_enabled) {
1300 hw_error("cannot save state if virtual timers are running");
1302 qemu_put_be64(f, cpu_ticks_offset);
1303 qemu_put_be64(f, ticks_per_sec);
1304 qemu_put_be64(f, cpu_clock_offset);
1307 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1309 if (version_id != 1 && version_id != 2)
1310 return -EINVAL;
1311 if (cpu_ticks_enabled) {
1312 return -EINVAL;
1314 cpu_ticks_offset=qemu_get_be64(f);
1315 ticks_per_sec=qemu_get_be64(f);
1316 if (version_id == 2) {
1317 cpu_clock_offset=qemu_get_be64(f);
1319 return 0;
1322 #ifdef _WIN32
1323 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1324 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1325 #else
1326 static void host_alarm_handler(int host_signum)
1327 #endif
1329 #if 0
1330 #define DISP_FREQ 1000
1332 static int64_t delta_min = INT64_MAX;
1333 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1334 static int count;
1335 ti = qemu_get_clock(vm_clock);
1336 if (last_clock != 0) {
1337 delta = ti - last_clock;
1338 if (delta < delta_min)
1339 delta_min = delta;
1340 if (delta > delta_max)
1341 delta_max = delta;
1342 delta_cum += delta;
1343 if (++count == DISP_FREQ) {
1344 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1345 muldiv64(delta_min, 1000000, ticks_per_sec),
1346 muldiv64(delta_max, 1000000, ticks_per_sec),
1347 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1348 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1349 count = 0;
1350 delta_min = INT64_MAX;
1351 delta_max = 0;
1352 delta_cum = 0;
1355 last_clock = ti;
1357 #endif
1358 if (1 ||
1359 alarm_has_dynticks(alarm_timer) ||
1360 (!use_icount &&
1361 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1362 qemu_get_clock(vm_clock))) ||
1363 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1364 qemu_get_clock(rt_clock))) {
1365 CPUState *env = next_cpu;
1367 #ifdef _WIN32
1368 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1369 SetEvent(data->host_alarm);
1370 #else
1371 static const char byte = 0;
1372 write(alarm_timer_wfd, &byte, sizeof(byte));
1373 #endif
1374 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1376 if (env) {
1377 /* stop the currently executing cpu because a timer occured */
1378 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1379 #ifdef USE_KQEMU
1380 if (env->kqemu_enabled) {
1381 kqemu_cpu_interrupt(env);
1383 #endif
1385 event_pending = 1;
1389 static int64_t qemu_next_deadline(void)
1391 int64_t delta;
1393 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1394 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1395 qemu_get_clock(vm_clock);
1396 } else {
1397 /* To avoid problems with overflow limit this to 2^32. */
1398 delta = INT32_MAX;
1401 if (delta < 0)
1402 delta = 0;
1404 return delta;
1407 #if defined(__linux__) || defined(_WIN32)
1408 static uint64_t qemu_next_deadline_dyntick(void)
1410 int64_t delta;
1411 int64_t rtdelta;
1413 if (use_icount)
1414 delta = INT32_MAX;
1415 else
1416 delta = (qemu_next_deadline() + 999) / 1000;
1418 if (active_timers[QEMU_TIMER_REALTIME]) {
1419 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1420 qemu_get_clock(rt_clock))*1000;
1421 if (rtdelta < delta)
1422 delta = rtdelta;
1425 if (delta < MIN_TIMER_REARM_US)
1426 delta = MIN_TIMER_REARM_US;
1428 return delta;
1430 #endif
1432 #ifndef _WIN32
1434 /* Sets a specific flag */
1435 static int fcntl_setfl(int fd, int flag)
1437 int flags;
1439 flags = fcntl(fd, F_GETFL);
1440 if (flags == -1)
1441 return -errno;
1443 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1444 return -errno;
1446 return 0;
1449 #if defined(__linux__)
1451 #define RTC_FREQ 1024
1453 static void enable_sigio_timer(int fd)
1455 struct sigaction act;
1457 /* timer signal */
1458 sigfillset(&act.sa_mask);
1459 act.sa_flags = 0;
1460 act.sa_handler = host_alarm_handler;
1462 sigaction(SIGIO, &act, NULL);
1463 fcntl_setfl(fd, O_ASYNC);
1464 fcntl(fd, F_SETOWN, getpid());
1467 static int hpet_start_timer(struct qemu_alarm_timer *t)
1469 struct hpet_info info;
1470 int r, fd;
1472 fd = open("/dev/hpet", O_RDONLY);
1473 if (fd < 0)
1474 return -1;
1476 /* Set frequency */
1477 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1478 if (r < 0) {
1479 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1480 "error, but for better emulation accuracy type:\n"
1481 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1482 goto fail;
1485 /* Check capabilities */
1486 r = ioctl(fd, HPET_INFO, &info);
1487 if (r < 0)
1488 goto fail;
1490 /* Enable periodic mode */
1491 r = ioctl(fd, HPET_EPI, 0);
1492 if (info.hi_flags && (r < 0))
1493 goto fail;
1495 /* Enable interrupt */
1496 r = ioctl(fd, HPET_IE_ON, 0);
1497 if (r < 0)
1498 goto fail;
1500 enable_sigio_timer(fd);
1501 t->priv = (void *)(long)fd;
1503 return 0;
1504 fail:
1505 close(fd);
1506 return -1;
1509 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1511 int fd = (long)t->priv;
1513 close(fd);
1516 static int rtc_start_timer(struct qemu_alarm_timer *t)
1518 int rtc_fd;
1519 unsigned long current_rtc_freq = 0;
1521 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1522 if (rtc_fd < 0)
1523 return -1;
1524 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1525 if (current_rtc_freq != RTC_FREQ &&
1526 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1527 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1528 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1529 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1530 goto fail;
1532 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1533 fail:
1534 close(rtc_fd);
1535 return -1;
1538 enable_sigio_timer(rtc_fd);
1540 t->priv = (void *)(long)rtc_fd;
1542 return 0;
1545 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1547 int rtc_fd = (long)t->priv;
1549 close(rtc_fd);
1552 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1554 struct sigevent ev;
1555 timer_t host_timer;
1556 struct sigaction act;
1558 sigfillset(&act.sa_mask);
1559 act.sa_flags = 0;
1560 act.sa_handler = host_alarm_handler;
1562 sigaction(SIGALRM, &act, NULL);
1564 ev.sigev_value.sival_int = 0;
1565 ev.sigev_notify = SIGEV_SIGNAL;
1566 ev.sigev_signo = SIGALRM;
1568 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1569 perror("timer_create");
1571 /* disable dynticks */
1572 fprintf(stderr, "Dynamic Ticks disabled\n");
1574 return -1;
1577 t->priv = (void *)host_timer;
1579 return 0;
1582 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1584 timer_t host_timer = (timer_t)t->priv;
1586 timer_delete(host_timer);
1589 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1591 timer_t host_timer = (timer_t)t->priv;
1592 struct itimerspec timeout;
1593 int64_t nearest_delta_us = INT64_MAX;
1594 int64_t current_us;
1596 if (!active_timers[QEMU_TIMER_REALTIME] &&
1597 !active_timers[QEMU_TIMER_VIRTUAL])
1598 return;
1600 nearest_delta_us = qemu_next_deadline_dyntick();
1602 /* check whether a timer is already running */
1603 if (timer_gettime(host_timer, &timeout)) {
1604 perror("gettime");
1605 fprintf(stderr, "Internal timer error: aborting\n");
1606 exit(1);
1608 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1609 if (current_us && current_us <= nearest_delta_us)
1610 return;
1612 timeout.it_interval.tv_sec = 0;
1613 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1614 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1615 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1616 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1617 perror("settime");
1618 fprintf(stderr, "Internal timer error: aborting\n");
1619 exit(1);
1623 #endif /* defined(__linux__) */
1625 static int unix_start_timer(struct qemu_alarm_timer *t)
1627 struct sigaction act;
1628 struct itimerval itv;
1629 int err;
1631 /* timer signal */
1632 sigfillset(&act.sa_mask);
1633 act.sa_flags = 0;
1634 act.sa_handler = host_alarm_handler;
1636 sigaction(SIGALRM, &act, NULL);
1638 itv.it_interval.tv_sec = 0;
1639 /* for i386 kernel 2.6 to get 1 ms */
1640 itv.it_interval.tv_usec = 999;
1641 itv.it_value.tv_sec = 0;
1642 itv.it_value.tv_usec = 10 * 1000;
1644 err = setitimer(ITIMER_REAL, &itv, NULL);
1645 if (err)
1646 return -1;
1648 return 0;
1651 static void unix_stop_timer(struct qemu_alarm_timer *t)
1653 struct itimerval itv;
1655 memset(&itv, 0, sizeof(itv));
1656 setitimer(ITIMER_REAL, &itv, NULL);
1659 #endif /* !defined(_WIN32) */
1661 static void try_to_rearm_timer(void *opaque)
1663 struct qemu_alarm_timer *t = opaque;
1664 #ifndef _WIN32
1665 ssize_t len;
1667 /* Drain the notify pipe */
1668 do {
1669 char buffer[512];
1670 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1671 } while ((len == -1 && errno == EINTR) || len > 0);
1672 #endif
1674 /* vm time timers */
1675 if (vm_running && likely(!(cur_cpu && (cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
1676 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
1677 qemu_get_clock(vm_clock));
1679 /* real time timers */
1680 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
1681 qemu_get_clock(rt_clock));
1683 if (t->flags & ALARM_FLAG_EXPIRED) {
1684 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1685 qemu_rearm_alarm_timer(alarm_timer);
1689 #ifdef _WIN32
1691 static int win32_start_timer(struct qemu_alarm_timer *t)
1693 TIMECAPS tc;
1694 struct qemu_alarm_win32 *data = t->priv;
1695 UINT flags;
1697 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1698 if (!data->host_alarm) {
1699 perror("Failed CreateEvent");
1700 return -1;
1703 memset(&tc, 0, sizeof(tc));
1704 timeGetDevCaps(&tc, sizeof(tc));
1706 if (data->period < tc.wPeriodMin)
1707 data->period = tc.wPeriodMin;
1709 timeBeginPeriod(data->period);
1711 flags = TIME_CALLBACK_FUNCTION;
1712 if (alarm_has_dynticks(t))
1713 flags |= TIME_ONESHOT;
1714 else
1715 flags |= TIME_PERIODIC;
1717 data->timerId = timeSetEvent(1, // interval (ms)
1718 data->period, // resolution
1719 host_alarm_handler, // function
1720 (DWORD)t, // parameter
1721 flags);
1723 if (!data->timerId) {
1724 perror("Failed to initialize win32 alarm timer");
1726 timeEndPeriod(data->period);
1727 CloseHandle(data->host_alarm);
1728 return -1;
1731 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1733 return 0;
1736 static void win32_stop_timer(struct qemu_alarm_timer *t)
1738 struct qemu_alarm_win32 *data = t->priv;
1740 timeKillEvent(data->timerId);
1741 timeEndPeriod(data->period);
1743 CloseHandle(data->host_alarm);
1746 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1748 struct qemu_alarm_win32 *data = t->priv;
1749 uint64_t nearest_delta_us;
1751 if (!active_timers[QEMU_TIMER_REALTIME] &&
1752 !active_timers[QEMU_TIMER_VIRTUAL])
1753 return;
1755 nearest_delta_us = qemu_next_deadline_dyntick();
1756 nearest_delta_us /= 1000;
1758 timeKillEvent(data->timerId);
1760 data->timerId = timeSetEvent(1,
1761 data->period,
1762 host_alarm_handler,
1763 (DWORD)t,
1764 TIME_ONESHOT | TIME_PERIODIC);
1766 if (!data->timerId) {
1767 perror("Failed to re-arm win32 alarm timer");
1769 timeEndPeriod(data->period);
1770 CloseHandle(data->host_alarm);
1771 exit(1);
1775 #endif /* _WIN32 */
1777 static int init_timer_alarm(void)
1779 struct qemu_alarm_timer *t = NULL;
1780 int i, err = -1;
1782 #ifndef _WIN32
1783 int fds[2];
1785 err = pipe(fds);
1786 if (err == -1)
1787 return -errno;
1789 err = fcntl_setfl(fds[0], O_NONBLOCK);
1790 if (err < 0)
1791 goto fail;
1793 err = fcntl_setfl(fds[1], O_NONBLOCK);
1794 if (err < 0)
1795 goto fail;
1797 alarm_timer_rfd = fds[0];
1798 alarm_timer_wfd = fds[1];
1799 #endif
1801 for (i = 0; alarm_timers[i].name; i++) {
1802 t = &alarm_timers[i];
1804 err = t->start(t);
1805 if (!err)
1806 break;
1809 if (err) {
1810 err = -ENOENT;
1811 goto fail;
1814 #ifndef _WIN32
1815 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1816 try_to_rearm_timer, NULL, t);
1817 #endif
1819 alarm_timer = t;
1821 return 0;
1823 fail:
1824 #ifndef _WIN32
1825 close(fds[0]);
1826 close(fds[1]);
1827 #endif
1828 return err;
1831 static void quit_timers(void)
1833 alarm_timer->stop(alarm_timer);
1834 alarm_timer = NULL;
1837 /***********************************************************/
1838 /* host time/date access */
1839 void qemu_get_timedate(struct tm *tm, int offset)
1841 time_t ti;
1842 struct tm *ret;
1844 time(&ti);
1845 ti += offset;
1846 if (rtc_date_offset == -1) {
1847 if (rtc_utc)
1848 ret = gmtime(&ti);
1849 else
1850 ret = localtime(&ti);
1851 } else {
1852 ti -= rtc_date_offset;
1853 ret = gmtime(&ti);
1856 memcpy(tm, ret, sizeof(struct tm));
1859 int qemu_timedate_diff(struct tm *tm)
1861 time_t seconds;
1863 if (rtc_date_offset == -1)
1864 if (rtc_utc)
1865 seconds = mktimegm(tm);
1866 else
1867 seconds = mktime(tm);
1868 else
1869 seconds = mktimegm(tm) + rtc_date_offset;
1871 return seconds - time(NULL);
1874 #ifdef _WIN32
1875 static void socket_cleanup(void)
1877 WSACleanup();
1880 static int socket_init(void)
1882 WSADATA Data;
1883 int ret, err;
1885 ret = WSAStartup(MAKEWORD(2,2), &Data);
1886 if (ret != 0) {
1887 err = WSAGetLastError();
1888 fprintf(stderr, "WSAStartup: %d\n", err);
1889 return -1;
1891 atexit(socket_cleanup);
1892 return 0;
1894 #endif
1896 const char *get_opt_name(char *buf, int buf_size, const char *p)
1898 char *q;
1900 q = buf;
1901 while (*p != '\0' && *p != '=') {
1902 if (q && (q - buf) < buf_size - 1)
1903 *q++ = *p;
1904 p++;
1906 if (q)
1907 *q = '\0';
1909 return p;
1912 const char *get_opt_value(char *buf, int buf_size, const char *p)
1914 char *q;
1916 q = buf;
1917 while (*p != '\0') {
1918 if (*p == ',') {
1919 if (*(p + 1) != ',')
1920 break;
1921 p++;
1923 if (q && (q - buf) < buf_size - 1)
1924 *q++ = *p;
1925 p++;
1927 if (q)
1928 *q = '\0';
1930 return p;
1933 int get_param_value(char *buf, int buf_size,
1934 const char *tag, const char *str)
1936 const char *p;
1937 char option[128];
1939 p = str;
1940 for(;;) {
1941 p = get_opt_name(option, sizeof(option), p);
1942 if (*p != '=')
1943 break;
1944 p++;
1945 if (!strcmp(tag, option)) {
1946 (void)get_opt_value(buf, buf_size, p);
1947 return strlen(buf);
1948 } else {
1949 p = get_opt_value(NULL, 0, p);
1951 if (*p != ',')
1952 break;
1953 p++;
1955 return 0;
1958 int check_params(char *buf, int buf_size,
1959 const char * const *params, const char *str)
1961 const char *p;
1962 int i;
1964 p = str;
1965 for(;;) {
1966 p = get_opt_name(buf, buf_size, p);
1967 if (*p != '=')
1968 return -1;
1969 p++;
1970 for(i = 0; params[i] != NULL; i++)
1971 if (!strcmp(params[i], buf))
1972 break;
1973 if (params[i] == NULL)
1974 return -1;
1975 p = get_opt_value(NULL, 0, p);
1976 if (*p != ',')
1977 break;
1978 p++;
1980 return 0;
1983 /***********************************************************/
1984 /* Bluetooth support */
1985 static int nb_hcis;
1986 static int cur_hci;
1987 static struct HCIInfo *hci_table[MAX_NICS];
1989 static struct bt_vlan_s {
1990 struct bt_scatternet_s net;
1991 int id;
1992 struct bt_vlan_s *next;
1993 } *first_bt_vlan;
1995 /* find or alloc a new bluetooth "VLAN" */
1996 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1998 struct bt_vlan_s **pvlan, *vlan;
1999 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
2000 if (vlan->id == id)
2001 return &vlan->net;
2003 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
2004 vlan->id = id;
2005 pvlan = &first_bt_vlan;
2006 while (*pvlan != NULL)
2007 pvlan = &(*pvlan)->next;
2008 *pvlan = vlan;
2009 return &vlan->net;
2012 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2016 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2018 return -ENOTSUP;
2021 static struct HCIInfo null_hci = {
2022 .cmd_send = null_hci_send,
2023 .sco_send = null_hci_send,
2024 .acl_send = null_hci_send,
2025 .bdaddr_set = null_hci_addr_set,
2028 struct HCIInfo *qemu_next_hci(void)
2030 if (cur_hci == nb_hcis)
2031 return &null_hci;
2033 return hci_table[cur_hci++];
2036 static struct HCIInfo *hci_init(const char *str)
2038 char *endp;
2039 struct bt_scatternet_s *vlan = 0;
2041 if (!strcmp(str, "null"))
2042 /* null */
2043 return &null_hci;
2044 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2045 /* host[:hciN] */
2046 return bt_host_hci(str[4] ? str + 5 : "hci0");
2047 else if (!strncmp(str, "hci", 3)) {
2048 /* hci[,vlan=n] */
2049 if (str[3]) {
2050 if (!strncmp(str + 3, ",vlan=", 6)) {
2051 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2052 if (*endp)
2053 vlan = 0;
2055 } else
2056 vlan = qemu_find_bt_vlan(0);
2057 if (vlan)
2058 return bt_new_hci(vlan);
2061 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2063 return 0;
2066 static int bt_hci_parse(const char *str)
2068 struct HCIInfo *hci;
2069 bdaddr_t bdaddr;
2071 if (nb_hcis >= MAX_NICS) {
2072 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2073 return -1;
2076 hci = hci_init(str);
2077 if (!hci)
2078 return -1;
2080 bdaddr.b[0] = 0x52;
2081 bdaddr.b[1] = 0x54;
2082 bdaddr.b[2] = 0x00;
2083 bdaddr.b[3] = 0x12;
2084 bdaddr.b[4] = 0x34;
2085 bdaddr.b[5] = 0x56 + nb_hcis;
2086 hci->bdaddr_set(hci, bdaddr.b);
2088 hci_table[nb_hcis++] = hci;
2090 return 0;
2093 static void bt_vhci_add(int vlan_id)
2095 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2097 if (!vlan->slave)
2098 fprintf(stderr, "qemu: warning: adding a VHCI to "
2099 "an empty scatternet %i\n", vlan_id);
2101 bt_vhci_init(bt_new_hci(vlan));
2104 static struct bt_device_s *bt_device_add(const char *opt)
2106 struct bt_scatternet_s *vlan;
2107 int vlan_id = 0;
2108 char *endp = strstr(opt, ",vlan=");
2109 int len = (endp ? endp - opt : strlen(opt)) + 1;
2110 char devname[10];
2112 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2114 if (endp) {
2115 vlan_id = strtol(endp + 6, &endp, 0);
2116 if (*endp) {
2117 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2118 return 0;
2122 vlan = qemu_find_bt_vlan(vlan_id);
2124 if (!vlan->slave)
2125 fprintf(stderr, "qemu: warning: adding a slave device to "
2126 "an empty scatternet %i\n", vlan_id);
2128 if (!strcmp(devname, "keyboard"))
2129 return bt_keyboard_init(vlan);
2131 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2132 return 0;
2135 static int bt_parse(const char *opt)
2137 const char *endp, *p;
2138 int vlan;
2140 if (strstart(opt, "hci", &endp)) {
2141 if (!*endp || *endp == ',') {
2142 if (*endp)
2143 if (!strstart(endp, ",vlan=", 0))
2144 opt = endp + 1;
2146 return bt_hci_parse(opt);
2148 } else if (strstart(opt, "vhci", &endp)) {
2149 if (!*endp || *endp == ',') {
2150 if (*endp) {
2151 if (strstart(endp, ",vlan=", &p)) {
2152 vlan = strtol(p, (char **) &endp, 0);
2153 if (*endp) {
2154 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2155 return 1;
2157 } else {
2158 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2159 return 1;
2161 } else
2162 vlan = 0;
2164 bt_vhci_add(vlan);
2165 return 0;
2167 } else if (strstart(opt, "device:", &endp))
2168 return !bt_device_add(endp);
2170 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2171 return 1;
2174 /***********************************************************/
2175 /* QEMU Block devices */
2177 #define HD_ALIAS "index=%d,media=disk"
2178 #ifdef TARGET_PPC
2179 #define CDROM_ALIAS "index=1,media=cdrom"
2180 #else
2181 #define CDROM_ALIAS "index=2,media=cdrom"
2182 #endif
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 static void bdrv_format_print(void *opaque, const char *name)
2272 fprintf(stderr, " %s", name);
2275 void drive_uninit(BlockDriverState *bdrv)
2277 int i;
2279 for (i = 0; i < MAX_DRIVES; i++)
2280 if (drives_table[i].bdrv == bdrv) {
2281 drives_table[i].bdrv = NULL;
2282 drives_table[i].used = 0;
2283 drive_remove(drives_table[i].drive_opt_idx);
2284 nb_drives--;
2285 break;
2289 int drive_init(struct drive_opt *arg, int snapshot,
2290 QEMUMachine *machine)
2292 char buf[128];
2293 char file[1024];
2294 char devname[128];
2295 const char *mediastr = "";
2296 BlockInterfaceType type;
2297 enum { MEDIA_DISK, MEDIA_CDROM } media;
2298 int bus_id, unit_id;
2299 int cyls, heads, secs, translation;
2300 BlockDriverState *bdrv;
2301 BlockDriver *drv = NULL;
2302 int max_devs;
2303 int index;
2304 int cache;
2305 int bdrv_flags;
2306 int drives_table_idx;
2307 char *str = arg->opt;
2308 static const char * const params[] = { "bus", "unit", "if", "index",
2309 "cyls", "heads", "secs", "trans",
2310 "media", "snapshot", "file",
2311 "cache", "format", "boot", NULL };
2313 if (check_params(buf, sizeof(buf), params, str) < 0) {
2314 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2315 buf, str);
2316 return -1;
2319 file[0] = 0;
2320 cyls = heads = secs = 0;
2321 bus_id = 0;
2322 unit_id = -1;
2323 translation = BIOS_ATA_TRANSLATION_AUTO;
2324 index = -1;
2325 cache = 1;
2327 if (machine->use_scsi) {
2328 type = IF_SCSI;
2329 max_devs = MAX_SCSI_DEVS;
2330 pstrcpy(devname, sizeof(devname), "scsi");
2331 } else {
2332 type = IF_IDE;
2333 max_devs = MAX_IDE_DEVS;
2334 pstrcpy(devname, sizeof(devname), "ide");
2336 media = MEDIA_DISK;
2338 /* extract parameters */
2340 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2341 bus_id = strtol(buf, NULL, 0);
2342 if (bus_id < 0) {
2343 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2344 return -1;
2348 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2349 unit_id = strtol(buf, NULL, 0);
2350 if (unit_id < 0) {
2351 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2352 return -1;
2356 if (get_param_value(buf, sizeof(buf), "if", str)) {
2357 pstrcpy(devname, sizeof(devname), buf);
2358 if (!strcmp(buf, "ide")) {
2359 type = IF_IDE;
2360 max_devs = MAX_IDE_DEVS;
2361 } else if (!strcmp(buf, "scsi")) {
2362 type = IF_SCSI;
2363 max_devs = MAX_SCSI_DEVS;
2364 } else if (!strcmp(buf, "floppy")) {
2365 type = IF_FLOPPY;
2366 max_devs = 0;
2367 } else if (!strcmp(buf, "pflash")) {
2368 type = IF_PFLASH;
2369 max_devs = 0;
2370 } else if (!strcmp(buf, "mtd")) {
2371 type = IF_MTD;
2372 max_devs = 0;
2373 } else if (!strcmp(buf, "sd")) {
2374 type = IF_SD;
2375 max_devs = 0;
2376 } else if (!strcmp(buf, "virtio")) {
2377 type = IF_VIRTIO;
2378 max_devs = 0;
2379 } else {
2380 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2381 return -1;
2385 if (get_param_value(buf, sizeof(buf), "index", str)) {
2386 index = strtol(buf, NULL, 0);
2387 if (index < 0) {
2388 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2389 return -1;
2393 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2394 cyls = strtol(buf, NULL, 0);
2397 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2398 heads = strtol(buf, NULL, 0);
2401 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2402 secs = strtol(buf, NULL, 0);
2405 if (cyls || heads || secs) {
2406 if (cyls < 1 || cyls > 16383) {
2407 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2408 return -1;
2410 if (heads < 1 || heads > 16) {
2411 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2412 return -1;
2414 if (secs < 1 || secs > 63) {
2415 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2416 return -1;
2420 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2421 if (!cyls) {
2422 fprintf(stderr,
2423 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2424 str);
2425 return -1;
2427 if (!strcmp(buf, "none"))
2428 translation = BIOS_ATA_TRANSLATION_NONE;
2429 else if (!strcmp(buf, "lba"))
2430 translation = BIOS_ATA_TRANSLATION_LBA;
2431 else if (!strcmp(buf, "auto"))
2432 translation = BIOS_ATA_TRANSLATION_AUTO;
2433 else {
2434 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2435 return -1;
2439 if (get_param_value(buf, sizeof(buf), "media", str)) {
2440 if (!strcmp(buf, "disk")) {
2441 media = MEDIA_DISK;
2442 } else if (!strcmp(buf, "cdrom")) {
2443 if (cyls || secs || heads) {
2444 fprintf(stderr,
2445 "qemu: '%s' invalid physical CHS format\n", str);
2446 return -1;
2448 media = MEDIA_CDROM;
2449 } else {
2450 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2451 return -1;
2455 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2456 if (!strcmp(buf, "on"))
2457 snapshot = 1;
2458 else if (!strcmp(buf, "off"))
2459 snapshot = 0;
2460 else {
2461 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2462 return -1;
2466 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2467 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2468 cache = 0;
2469 else if (!strcmp(buf, "writethrough"))
2470 cache = 1;
2471 else if (!strcmp(buf, "writeback"))
2472 cache = 2;
2473 else {
2474 fprintf(stderr, "qemu: invalid cache option\n");
2475 return -1;
2479 if (get_param_value(buf, sizeof(buf), "format", str)) {
2480 if (strcmp(buf, "?") == 0) {
2481 fprintf(stderr, "qemu: Supported formats:");
2482 bdrv_iterate_format(bdrv_format_print, NULL);
2483 fprintf(stderr, "\n");
2484 return -1;
2486 drv = bdrv_find_format(buf);
2487 if (!drv) {
2488 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2489 return -1;
2493 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2494 if (!strcmp(buf, "on")) {
2495 if (extboot_drive != -1) {
2496 fprintf(stderr, "qemu: two bootable drives specified\n");
2497 return -1;
2499 extboot_drive = nb_drives;
2500 } else if (strcmp(buf, "off")) {
2501 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2502 return -1;
2506 if (arg->file == NULL)
2507 get_param_value(file, sizeof(file), "file", str);
2508 else
2509 pstrcpy(file, sizeof(file), arg->file);
2511 /* compute bus and unit according index */
2513 if (index != -1) {
2514 if (bus_id != 0 || unit_id != -1) {
2515 fprintf(stderr,
2516 "qemu: '%s' index cannot be used with bus and unit\n", str);
2517 return -1;
2519 if (max_devs == 0)
2521 unit_id = index;
2522 bus_id = 0;
2523 } else {
2524 unit_id = index % max_devs;
2525 bus_id = index / max_devs;
2529 /* if user doesn't specify a unit_id,
2530 * try to find the first free
2533 if (unit_id == -1) {
2534 unit_id = 0;
2535 while (drive_get_index(type, bus_id, unit_id) != -1) {
2536 unit_id++;
2537 if (max_devs && unit_id >= max_devs) {
2538 unit_id -= max_devs;
2539 bus_id++;
2544 /* check unit id */
2546 if (max_devs && unit_id >= max_devs) {
2547 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2548 str, unit_id, max_devs - 1);
2549 return -1;
2553 * ignore multiple definitions
2556 if (drive_get_index(type, bus_id, unit_id) != -1)
2557 return -2;
2559 /* init */
2561 if (type == IF_IDE || type == IF_SCSI)
2562 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2563 if (max_devs)
2564 snprintf(buf, sizeof(buf), "%s%i%s%i",
2565 devname, bus_id, mediastr, unit_id);
2566 else
2567 snprintf(buf, sizeof(buf), "%s%s%i",
2568 devname, mediastr, unit_id);
2569 bdrv = bdrv_new(buf);
2570 drives_table_idx = drive_get_free_idx();
2571 drives_table[drives_table_idx].bdrv = bdrv;
2572 drives_table[drives_table_idx].type = type;
2573 drives_table[drives_table_idx].bus = bus_id;
2574 drives_table[drives_table_idx].unit = unit_id;
2575 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2576 nb_drives++;
2578 switch(type) {
2579 case IF_IDE:
2580 case IF_SCSI:
2581 switch(media) {
2582 case MEDIA_DISK:
2583 if (cyls != 0) {
2584 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2585 bdrv_set_translation_hint(bdrv, translation);
2587 break;
2588 case MEDIA_CDROM:
2589 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2590 break;
2592 break;
2593 case IF_SD:
2594 /* FIXME: This isn't really a floppy, but it's a reasonable
2595 approximation. */
2596 case IF_FLOPPY:
2597 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2598 break;
2599 case IF_PFLASH:
2600 case IF_MTD:
2601 case IF_VIRTIO:
2602 break;
2604 if (!file[0])
2605 return -2;
2606 bdrv_flags = 0;
2607 if (snapshot) {
2608 bdrv_flags |= BDRV_O_SNAPSHOT;
2609 cache = 2; /* always use write-back with snapshot */
2611 if (cache == 0) /* no caching */
2612 bdrv_flags |= BDRV_O_NOCACHE;
2613 else if (cache == 2) /* write-back */
2614 bdrv_flags |= BDRV_O_CACHE_WB;
2615 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2616 fprintf(stderr, "qemu: could not open disk image %s\n",
2617 file);
2618 return -1;
2620 return drives_table_idx;
2623 /***********************************************************/
2624 /* USB devices */
2626 static USBPort *used_usb_ports;
2627 static USBPort *free_usb_ports;
2629 /* ??? Maybe change this to register a hub to keep track of the topology. */
2630 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2631 usb_attachfn attach)
2633 port->opaque = opaque;
2634 port->index = index;
2635 port->attach = attach;
2636 port->next = free_usb_ports;
2637 free_usb_ports = port;
2640 int usb_device_add_dev(USBDevice *dev)
2642 USBPort *port;
2644 /* Find a USB port to add the device to. */
2645 port = free_usb_ports;
2646 if (!port->next) {
2647 USBDevice *hub;
2649 /* Create a new hub and chain it on. */
2650 free_usb_ports = NULL;
2651 port->next = used_usb_ports;
2652 used_usb_ports = port;
2654 hub = usb_hub_init(VM_USB_HUB_SIZE);
2655 usb_attach(port, hub);
2656 port = free_usb_ports;
2659 free_usb_ports = port->next;
2660 port->next = used_usb_ports;
2661 used_usb_ports = port;
2662 usb_attach(port, dev);
2663 return 0;
2666 static int usb_device_add(const char *devname)
2668 const char *p;
2669 USBDevice *dev;
2671 if (!free_usb_ports)
2672 return -1;
2674 if (strstart(devname, "host:", &p)) {
2675 dev = usb_host_device_open(p);
2676 } else if (!strcmp(devname, "mouse")) {
2677 dev = usb_mouse_init();
2678 } else if (!strcmp(devname, "tablet")) {
2679 dev = usb_tablet_init();
2680 } else if (!strcmp(devname, "keyboard")) {
2681 dev = usb_keyboard_init();
2682 } else if (strstart(devname, "disk:", &p)) {
2683 dev = usb_msd_init(p);
2684 } else if (!strcmp(devname, "wacom-tablet")) {
2685 dev = usb_wacom_init();
2686 } else if (strstart(devname, "serial:", &p)) {
2687 dev = usb_serial_init(p);
2688 #ifdef CONFIG_BRLAPI
2689 } else if (!strcmp(devname, "braille")) {
2690 dev = usb_baum_init();
2691 #endif
2692 } else if (strstart(devname, "net:", &p)) {
2693 int nic = nb_nics;
2695 if (net_client_init("nic", p) < 0)
2696 return -1;
2697 nd_table[nic].model = "usb";
2698 dev = usb_net_init(&nd_table[nic]);
2699 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2700 dev = usb_bt_init(devname[2] ? hci_init(p) :
2701 bt_new_hci(qemu_find_bt_vlan(0)));
2702 } else {
2703 return -1;
2705 if (!dev)
2706 return -1;
2708 return usb_device_add_dev(dev);
2711 int usb_device_del_addr(int bus_num, int addr)
2713 USBPort *port;
2714 USBPort **lastp;
2715 USBDevice *dev;
2717 if (!used_usb_ports)
2718 return -1;
2720 if (bus_num != 0)
2721 return -1;
2723 lastp = &used_usb_ports;
2724 port = used_usb_ports;
2725 while (port && port->dev->addr != addr) {
2726 lastp = &port->next;
2727 port = port->next;
2730 if (!port)
2731 return -1;
2733 dev = port->dev;
2734 *lastp = port->next;
2735 usb_attach(port, NULL);
2736 dev->handle_destroy(dev);
2737 port->next = free_usb_ports;
2738 free_usb_ports = port;
2739 return 0;
2742 static int usb_device_del(const char *devname)
2744 int bus_num, addr;
2745 const char *p;
2747 if (strstart(devname, "host:", &p))
2748 return usb_host_device_close(p);
2750 if (!used_usb_ports)
2751 return -1;
2753 p = strchr(devname, '.');
2754 if (!p)
2755 return -1;
2756 bus_num = strtoul(devname, NULL, 0);
2757 addr = strtoul(p + 1, NULL, 0);
2759 return usb_device_del_addr(bus_num, addr);
2762 void do_usb_add(const char *devname)
2764 usb_device_add(devname);
2767 void do_usb_del(const char *devname)
2769 usb_device_del(devname);
2772 void usb_info(void)
2774 USBDevice *dev;
2775 USBPort *port;
2776 const char *speed_str;
2778 if (!usb_enabled) {
2779 term_printf("USB support not enabled\n");
2780 return;
2783 for (port = used_usb_ports; port; port = port->next) {
2784 dev = port->dev;
2785 if (!dev)
2786 continue;
2787 switch(dev->speed) {
2788 case USB_SPEED_LOW:
2789 speed_str = "1.5";
2790 break;
2791 case USB_SPEED_FULL:
2792 speed_str = "12";
2793 break;
2794 case USB_SPEED_HIGH:
2795 speed_str = "480";
2796 break;
2797 default:
2798 speed_str = "?";
2799 break;
2801 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2802 0, dev->addr, speed_str, dev->devname);
2806 /***********************************************************/
2807 /* PCMCIA/Cardbus */
2809 static struct pcmcia_socket_entry_s {
2810 struct pcmcia_socket_s *socket;
2811 struct pcmcia_socket_entry_s *next;
2812 } *pcmcia_sockets = 0;
2814 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2816 struct pcmcia_socket_entry_s *entry;
2818 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2819 entry->socket = socket;
2820 entry->next = pcmcia_sockets;
2821 pcmcia_sockets = entry;
2824 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2826 struct pcmcia_socket_entry_s *entry, **ptr;
2828 ptr = &pcmcia_sockets;
2829 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2830 if (entry->socket == socket) {
2831 *ptr = entry->next;
2832 qemu_free(entry);
2836 void pcmcia_info(void)
2838 struct pcmcia_socket_entry_s *iter;
2839 if (!pcmcia_sockets)
2840 term_printf("No PCMCIA sockets\n");
2842 for (iter = pcmcia_sockets; iter; iter = iter->next)
2843 term_printf("%s: %s\n", iter->socket->slot_string,
2844 iter->socket->attached ? iter->socket->card_string :
2845 "Empty");
2848 /***********************************************************/
2849 /* dumb display */
2851 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2855 static void dumb_resize(DisplayState *ds, int w, int h)
2859 static void dumb_display_init(DisplayState *ds)
2861 ds->data = NULL;
2862 ds->linesize = 0;
2863 ds->depth = 0;
2864 ds->dpy_update = dumb_update;
2865 ds->dpy_resize = dumb_resize;
2866 ds->dpy_refresh = NULL;
2867 ds->gui_timer_interval = 0;
2868 ds->idle = 1;
2871 /***********************************************************/
2872 /* I/O handling */
2874 #define MAX_IO_HANDLERS 64
2876 typedef struct IOHandlerRecord {
2877 int fd;
2878 IOCanRWHandler *fd_read_poll;
2879 IOHandler *fd_read;
2880 IOHandler *fd_write;
2881 int deleted;
2882 void *opaque;
2883 /* temporary data */
2884 struct pollfd *ufd;
2885 struct IOHandlerRecord *next;
2886 } IOHandlerRecord;
2888 static IOHandlerRecord *first_io_handler;
2890 /* XXX: fd_read_poll should be suppressed, but an API change is
2891 necessary in the character devices to suppress fd_can_read(). */
2892 int qemu_set_fd_handler2(int fd,
2893 IOCanRWHandler *fd_read_poll,
2894 IOHandler *fd_read,
2895 IOHandler *fd_write,
2896 void *opaque)
2898 IOHandlerRecord **pioh, *ioh;
2900 if (!fd_read && !fd_write) {
2901 pioh = &first_io_handler;
2902 for(;;) {
2903 ioh = *pioh;
2904 if (ioh == NULL)
2905 break;
2906 if (ioh->fd == fd) {
2907 ioh->deleted = 1;
2908 break;
2910 pioh = &ioh->next;
2912 } else {
2913 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2914 if (ioh->fd == fd)
2915 goto found;
2917 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2918 if (!ioh)
2919 return -1;
2920 ioh->next = first_io_handler;
2921 first_io_handler = ioh;
2922 found:
2923 ioh->fd = fd;
2924 ioh->fd_read_poll = fd_read_poll;
2925 ioh->fd_read = fd_read;
2926 ioh->fd_write = fd_write;
2927 ioh->opaque = opaque;
2928 ioh->deleted = 0;
2930 main_loop_break();
2931 return 0;
2934 int qemu_set_fd_handler(int fd,
2935 IOHandler *fd_read,
2936 IOHandler *fd_write,
2937 void *opaque)
2939 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2942 #ifdef _WIN32
2943 /***********************************************************/
2944 /* Polling handling */
2946 typedef struct PollingEntry {
2947 PollingFunc *func;
2948 void *opaque;
2949 struct PollingEntry *next;
2950 } PollingEntry;
2952 static PollingEntry *first_polling_entry;
2954 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2956 PollingEntry **ppe, *pe;
2957 pe = qemu_mallocz(sizeof(PollingEntry));
2958 if (!pe)
2959 return -1;
2960 pe->func = func;
2961 pe->opaque = opaque;
2962 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2963 *ppe = pe;
2964 return 0;
2967 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2969 PollingEntry **ppe, *pe;
2970 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2971 pe = *ppe;
2972 if (pe->func == func && pe->opaque == opaque) {
2973 *ppe = pe->next;
2974 qemu_free(pe);
2975 break;
2980 /***********************************************************/
2981 /* Wait objects support */
2982 typedef struct WaitObjects {
2983 int num;
2984 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2985 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2986 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2987 } WaitObjects;
2989 static WaitObjects wait_objects = {0};
2991 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2993 WaitObjects *w = &wait_objects;
2995 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2996 return -1;
2997 w->events[w->num] = handle;
2998 w->func[w->num] = func;
2999 w->opaque[w->num] = opaque;
3000 w->num++;
3001 return 0;
3004 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3006 int i, found;
3007 WaitObjects *w = &wait_objects;
3009 found = 0;
3010 for (i = 0; i < w->num; i++) {
3011 if (w->events[i] == handle)
3012 found = 1;
3013 if (found) {
3014 w->events[i] = w->events[i + 1];
3015 w->func[i] = w->func[i + 1];
3016 w->opaque[i] = w->opaque[i + 1];
3019 if (found)
3020 w->num--;
3022 #endif
3024 /***********************************************************/
3025 /* ram save/restore */
3027 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3029 int v;
3031 v = qemu_get_byte(f);
3032 switch(v) {
3033 case 0:
3034 if (qemu_get_buffer(f, buf, len) != len)
3035 return -EIO;
3036 break;
3037 case 1:
3038 v = qemu_get_byte(f);
3039 memset(buf, v, len);
3040 break;
3041 default:
3042 return -EINVAL;
3045 if (qemu_file_has_error(f))
3046 return -EIO;
3048 return 0;
3051 static int ram_load_v1(QEMUFile *f, void *opaque)
3053 int ret;
3054 ram_addr_t i;
3056 if (qemu_get_be32(f) != phys_ram_size)
3057 return -EINVAL;
3058 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3059 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3060 continue;
3061 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3062 if (ret)
3063 return ret;
3065 return 0;
3068 #define BDRV_HASH_BLOCK_SIZE 1024
3069 #define IOBUF_SIZE 4096
3070 #define RAM_CBLOCK_MAGIC 0xfabe
3072 typedef struct RamDecompressState {
3073 z_stream zstream;
3074 QEMUFile *f;
3075 uint8_t buf[IOBUF_SIZE];
3076 } RamDecompressState;
3078 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3080 int ret;
3081 memset(s, 0, sizeof(*s));
3082 s->f = f;
3083 ret = inflateInit(&s->zstream);
3084 if (ret != Z_OK)
3085 return -1;
3086 return 0;
3089 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3091 int ret, clen;
3093 s->zstream.avail_out = len;
3094 s->zstream.next_out = buf;
3095 while (s->zstream.avail_out > 0) {
3096 if (s->zstream.avail_in == 0) {
3097 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3098 return -1;
3099 clen = qemu_get_be16(s->f);
3100 if (clen > IOBUF_SIZE)
3101 return -1;
3102 qemu_get_buffer(s->f, s->buf, clen);
3103 s->zstream.avail_in = clen;
3104 s->zstream.next_in = s->buf;
3106 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3107 if (ret != Z_OK && ret != Z_STREAM_END) {
3108 return -1;
3111 return 0;
3114 static void ram_decompress_close(RamDecompressState *s)
3116 inflateEnd(&s->zstream);
3119 #define RAM_SAVE_FLAG_FULL 0x01
3120 #define RAM_SAVE_FLAG_COMPRESS 0x02
3121 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3122 #define RAM_SAVE_FLAG_PAGE 0x08
3123 #define RAM_SAVE_FLAG_EOS 0x10
3125 static int is_dup_page(uint8_t *page, uint8_t ch)
3127 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3128 uint32_t *array = (uint32_t *)page;
3129 int i;
3131 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3132 if (array[i] != val)
3133 return 0;
3136 return 1;
3139 static int ram_save_block(QEMUFile *f)
3141 static ram_addr_t current_addr = 0;
3142 ram_addr_t saved_addr = current_addr;
3143 ram_addr_t addr = 0;
3144 int found = 0;
3146 while (addr < phys_ram_size) {
3147 if (kvm_enabled() && current_addr == 0)
3148 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3149 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3150 uint8_t ch;
3152 cpu_physical_memory_reset_dirty(current_addr,
3153 current_addr + TARGET_PAGE_SIZE,
3154 MIGRATION_DIRTY_FLAG);
3156 ch = *(phys_ram_base + current_addr);
3158 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3159 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3160 qemu_put_byte(f, ch);
3161 } else {
3162 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3163 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3166 found = 1;
3167 break;
3169 addr += TARGET_PAGE_SIZE;
3170 current_addr = (saved_addr + addr) % phys_ram_size;
3173 return found;
3176 static ram_addr_t ram_save_threshold = 10;
3178 static ram_addr_t ram_save_remaining(void)
3180 ram_addr_t addr;
3181 ram_addr_t count = 0;
3183 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3184 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3185 count++;
3188 return count;
3191 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3193 ram_addr_t addr;
3195 if (stage == 1) {
3196 /* Make sure all dirty bits are set */
3197 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3198 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3199 cpu_physical_memory_set_dirty(addr);
3202 /* Enable dirty memory tracking */
3203 cpu_physical_memory_set_dirty_tracking(1);
3205 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3208 while (!qemu_file_rate_limit(f)) {
3209 int ret;
3211 ret = ram_save_block(f);
3212 if (ret == 0) /* no more blocks */
3213 break;
3216 /* try transferring iterative blocks of memory */
3218 if (stage == 3) {
3219 cpu_physical_memory_set_dirty_tracking(0);
3221 /* flush all remaining blocks regardless of rate limiting */
3222 while (ram_save_block(f) != 0);
3225 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3227 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3230 static int ram_load_dead(QEMUFile *f, void *opaque)
3232 RamDecompressState s1, *s = &s1;
3233 uint8_t buf[10];
3234 ram_addr_t i;
3236 if (ram_decompress_open(s, f) < 0)
3237 return -EINVAL;
3238 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3239 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3240 continue;
3241 if (ram_decompress_buf(s, buf, 1) < 0) {
3242 fprintf(stderr, "Error while reading ram block header\n");
3243 goto error;
3245 if (buf[0] == 0) {
3246 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3247 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3248 goto error;
3250 } else {
3251 error:
3252 printf("Error block header\n");
3253 return -EINVAL;
3256 ram_decompress_close(s);
3258 return 0;
3261 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3263 ram_addr_t addr;
3264 int flags;
3266 if (version_id == 1)
3267 return ram_load_v1(f, opaque);
3269 if (version_id == 2) {
3270 if (qemu_get_be32(f) != phys_ram_size)
3271 return -EINVAL;
3272 return ram_load_dead(f, opaque);
3275 if (version_id != 3)
3276 return -EINVAL;
3278 do {
3279 addr = qemu_get_be64(f);
3281 flags = addr & ~TARGET_PAGE_MASK;
3282 addr &= TARGET_PAGE_MASK;
3284 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3285 if (addr != phys_ram_size)
3286 return -EINVAL;
3289 if (flags & RAM_SAVE_FLAG_FULL) {
3290 if (ram_load_dead(f, opaque) < 0)
3291 return -EINVAL;
3294 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3295 uint8_t ch = qemu_get_byte(f);
3296 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3297 } else if (flags & RAM_SAVE_FLAG_PAGE)
3298 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3299 } while (!(flags & RAM_SAVE_FLAG_EOS));
3301 return 0;
3304 /***********************************************************/
3305 /* bottom halves (can be seen as timers which expire ASAP) */
3307 struct QEMUBH {
3308 QEMUBHFunc *cb;
3309 void *opaque;
3310 int scheduled;
3311 int idle;
3312 int deleted;
3313 QEMUBH *next;
3316 static QEMUBH *first_bh = NULL;
3318 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3320 QEMUBH *bh;
3321 bh = qemu_mallocz(sizeof(QEMUBH));
3322 if (!bh)
3323 return NULL;
3324 bh->cb = cb;
3325 bh->opaque = opaque;
3326 bh->next = first_bh;
3327 first_bh = bh;
3328 return bh;
3331 int qemu_bh_poll(void)
3333 QEMUBH *bh, **bhp;
3334 int ret;
3336 ret = 0;
3337 for (bh = first_bh; bh; bh = bh->next) {
3338 if (!bh->deleted && bh->scheduled) {
3339 bh->scheduled = 0;
3340 if (!bh->idle)
3341 ret = 1;
3342 bh->idle = 0;
3343 bh->cb(bh->opaque);
3347 /* remove deleted bhs */
3348 bhp = &first_bh;
3349 while (*bhp) {
3350 bh = *bhp;
3351 if (bh->deleted) {
3352 *bhp = bh->next;
3353 qemu_free(bh);
3354 } else
3355 bhp = &bh->next;
3358 return ret;
3361 void qemu_bh_schedule_idle(QEMUBH *bh)
3363 if (bh->scheduled)
3364 return;
3365 bh->scheduled = 1;
3366 bh->idle = 1;
3369 void qemu_bh_schedule(QEMUBH *bh)
3371 CPUState *env = cpu_single_env;
3372 if (bh->scheduled)
3373 return;
3374 bh->scheduled = 1;
3375 bh->idle = 0;
3376 /* stop the currently executing CPU to execute the BH ASAP */
3377 if (env) {
3378 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3380 main_loop_break();
3383 void qemu_bh_cancel(QEMUBH *bh)
3385 bh->scheduled = 0;
3388 void qemu_bh_delete(QEMUBH *bh)
3390 bh->scheduled = 0;
3391 bh->deleted = 1;
3394 static void qemu_bh_update_timeout(int *timeout)
3396 QEMUBH *bh;
3398 for (bh = first_bh; bh; bh = bh->next) {
3399 if (!bh->deleted && bh->scheduled) {
3400 if (bh->idle) {
3401 /* idle bottom halves will be polled at least
3402 * every 10ms */
3403 *timeout = MIN(10, *timeout);
3404 } else {
3405 /* non-idle bottom halves will be executed
3406 * immediately */
3407 *timeout = 0;
3408 break;
3414 /***********************************************************/
3415 /* machine registration */
3417 static QEMUMachine *first_machine = NULL;
3418 QEMUMachine *current_machine = NULL;
3420 int qemu_register_machine(QEMUMachine *m)
3422 QEMUMachine **pm;
3423 pm = &first_machine;
3424 while (*pm != NULL)
3425 pm = &(*pm)->next;
3426 m->next = NULL;
3427 *pm = m;
3428 return 0;
3431 static QEMUMachine *find_machine(const char *name)
3433 QEMUMachine *m;
3435 for(m = first_machine; m != NULL; m = m->next) {
3436 if (!strcmp(m->name, name))
3437 return m;
3439 return NULL;
3442 /***********************************************************/
3443 /* main execution loop */
3445 static void gui_update(void *opaque)
3447 DisplayState *ds = opaque;
3448 ds->dpy_refresh(ds);
3449 qemu_mod_timer(ds->gui_timer,
3450 (ds->gui_timer_interval ?
3451 ds->gui_timer_interval :
3452 GUI_REFRESH_INTERVAL)
3453 + qemu_get_clock(rt_clock));
3456 struct vm_change_state_entry {
3457 VMChangeStateHandler *cb;
3458 void *opaque;
3459 LIST_ENTRY (vm_change_state_entry) entries;
3462 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3464 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3465 void *opaque)
3467 VMChangeStateEntry *e;
3469 e = qemu_mallocz(sizeof (*e));
3470 if (!e)
3471 return NULL;
3473 e->cb = cb;
3474 e->opaque = opaque;
3475 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3476 return e;
3479 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3481 LIST_REMOVE (e, entries);
3482 qemu_free (e);
3485 static void vm_state_notify(int running)
3487 VMChangeStateEntry *e;
3489 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3490 e->cb(e->opaque, running);
3494 /* XXX: support several handlers */
3495 static VMStopHandler *vm_stop_cb;
3496 static void *vm_stop_opaque;
3498 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3500 vm_stop_cb = cb;
3501 vm_stop_opaque = opaque;
3502 return 0;
3505 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3507 vm_stop_cb = NULL;
3510 void vm_start(void)
3512 if (!vm_running) {
3513 cpu_enable_ticks();
3514 vm_running = 1;
3515 vm_state_notify(1);
3516 qemu_rearm_alarm_timer(alarm_timer);
3520 void vm_stop(int reason)
3522 if (vm_running) {
3523 cpu_disable_ticks();
3524 vm_running = 0;
3525 if (reason != 0) {
3526 if (vm_stop_cb) {
3527 vm_stop_cb(vm_stop_opaque, reason);
3530 vm_state_notify(0);
3534 /* reset/shutdown handler */
3536 typedef struct QEMUResetEntry {
3537 QEMUResetHandler *func;
3538 void *opaque;
3539 struct QEMUResetEntry *next;
3540 } QEMUResetEntry;
3542 static QEMUResetEntry *first_reset_entry;
3543 static int reset_requested;
3544 static int shutdown_requested;
3545 static int powerdown_requested;
3547 int qemu_shutdown_requested(void)
3549 int r = shutdown_requested;
3550 shutdown_requested = 0;
3551 return r;
3554 int qemu_reset_requested(void)
3556 int r = reset_requested;
3557 reset_requested = 0;
3558 return r;
3561 int qemu_powerdown_requested(void)
3563 int r = powerdown_requested;
3564 powerdown_requested = 0;
3565 return r;
3568 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3570 QEMUResetEntry **pre, *re;
3572 pre = &first_reset_entry;
3573 while (*pre != NULL)
3574 pre = &(*pre)->next;
3575 re = qemu_mallocz(sizeof(QEMUResetEntry));
3576 re->func = func;
3577 re->opaque = opaque;
3578 re->next = NULL;
3579 *pre = re;
3582 void qemu_system_reset(void)
3584 QEMUResetEntry *re;
3586 /* reset all devices */
3587 for(re = first_reset_entry; re != NULL; re = re->next) {
3588 re->func(re->opaque);
3592 void qemu_system_reset_request(void)
3594 if (no_reboot) {
3595 shutdown_requested = 1;
3596 } else {
3597 reset_requested = 1;
3599 if (cpu_single_env)
3600 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3601 main_loop_break();
3604 void qemu_system_shutdown_request(void)
3606 shutdown_requested = 1;
3607 if (cpu_single_env)
3608 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3611 void qemu_system_powerdown_request(void)
3613 powerdown_requested = 1;
3614 if (cpu_single_env)
3615 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3618 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3619 struct timeval *tv)
3621 int ret;
3623 /* KVM holds a mutex while QEMU code is running, we need hooks to
3624 release the mutex whenever QEMU code sleeps. */
3626 kvm_sleep_begin();
3628 ret = select(max_fd, rfds, wfds, xfds, tv);
3630 kvm_sleep_end();
3632 return ret;
3635 #ifdef _WIN32
3636 void host_main_loop_wait(int *timeout)
3638 int ret, ret2, i;
3639 PollingEntry *pe;
3642 /* XXX: need to suppress polling by better using win32 events */
3643 ret = 0;
3644 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3645 ret |= pe->func(pe->opaque);
3647 if (ret == 0) {
3648 int err;
3649 WaitObjects *w = &wait_objects;
3651 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3652 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3653 if (w->func[ret - WAIT_OBJECT_0])
3654 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3656 /* Check for additional signaled events */
3657 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3659 /* Check if event is signaled */
3660 ret2 = WaitForSingleObject(w->events[i], 0);
3661 if(ret2 == WAIT_OBJECT_0) {
3662 if (w->func[i])
3663 w->func[i](w->opaque[i]);
3664 } else if (ret2 == WAIT_TIMEOUT) {
3665 } else {
3666 err = GetLastError();
3667 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3670 } else if (ret == WAIT_TIMEOUT) {
3671 } else {
3672 err = GetLastError();
3673 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3677 *timeout = 0;
3679 #else
3680 void host_main_loop_wait(int *timeout)
3683 #endif
3685 void main_loop_wait(int timeout)
3687 IOHandlerRecord *ioh;
3688 fd_set rfds, wfds, xfds;
3689 int ret, nfds;
3690 struct timeval tv;
3692 qemu_bh_update_timeout(&timeout);
3694 host_main_loop_wait(&timeout);
3696 /* poll any events */
3697 /* XXX: separate device handlers from system ones */
3698 nfds = -1;
3699 FD_ZERO(&rfds);
3700 FD_ZERO(&wfds);
3701 FD_ZERO(&xfds);
3702 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3703 if (ioh->deleted)
3704 continue;
3705 if (ioh->fd_read &&
3706 (!ioh->fd_read_poll ||
3707 ioh->fd_read_poll(ioh->opaque) != 0)) {
3708 FD_SET(ioh->fd, &rfds);
3709 if (ioh->fd > nfds)
3710 nfds = ioh->fd;
3712 if (ioh->fd_write) {
3713 FD_SET(ioh->fd, &wfds);
3714 if (ioh->fd > nfds)
3715 nfds = ioh->fd;
3719 tv.tv_sec = timeout / 1000;
3720 tv.tv_usec = (timeout % 1000) * 1000;
3722 #if defined(CONFIG_SLIRP)
3723 if (slirp_is_inited()) {
3724 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3726 #endif
3727 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3728 if (ret > 0) {
3729 IOHandlerRecord **pioh;
3731 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3732 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3733 ioh->fd_read(ioh->opaque);
3734 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3735 FD_CLR(ioh->fd, &rfds);
3737 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3738 ioh->fd_write(ioh->opaque);
3742 /* remove deleted IO handlers */
3743 pioh = &first_io_handler;
3744 while (*pioh) {
3745 ioh = *pioh;
3746 if (ioh->deleted) {
3747 *pioh = ioh->next;
3748 qemu_free(ioh);
3749 } else
3750 pioh = &ioh->next;
3753 #if defined(CONFIG_SLIRP)
3754 if (slirp_is_inited()) {
3755 if (ret < 0) {
3756 FD_ZERO(&rfds);
3757 FD_ZERO(&wfds);
3758 FD_ZERO(&xfds);
3760 slirp_select_poll(&rfds, &wfds, &xfds);
3762 #endif
3764 /* Check bottom-halves last in case any of the earlier events triggered
3765 them. */
3766 qemu_bh_poll();
3770 static int main_loop(void)
3772 int ret, timeout;
3773 #ifdef CONFIG_PROFILER
3774 int64_t ti;
3775 #endif
3776 CPUState *env;
3779 if (kvm_enabled()) {
3780 kvm_main_loop();
3781 cpu_disable_ticks();
3782 return 0;
3785 cur_cpu = first_cpu;
3786 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3787 for(;;) {
3788 if (vm_running) {
3790 for(;;) {
3791 /* get next cpu */
3792 env = next_cpu;
3793 #ifdef CONFIG_PROFILER
3794 ti = profile_getclock();
3795 #endif
3796 if (use_icount) {
3797 int64_t count;
3798 int decr;
3799 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3800 env->icount_decr.u16.low = 0;
3801 env->icount_extra = 0;
3802 count = qemu_next_deadline();
3803 count = (count + (1 << icount_time_shift) - 1)
3804 >> icount_time_shift;
3805 qemu_icount += count;
3806 decr = (count > 0xffff) ? 0xffff : count;
3807 count -= decr;
3808 env->icount_decr.u16.low = decr;
3809 env->icount_extra = count;
3811 ret = cpu_exec(env);
3812 #ifdef CONFIG_PROFILER
3813 qemu_time += profile_getclock() - ti;
3814 #endif
3815 if (use_icount) {
3816 /* Fold pending instructions back into the
3817 instruction counter, and clear the interrupt flag. */
3818 qemu_icount -= (env->icount_decr.u16.low
3819 + env->icount_extra);
3820 env->icount_decr.u32 = 0;
3821 env->icount_extra = 0;
3823 next_cpu = env->next_cpu ?: first_cpu;
3824 if (event_pending && likely(ret != EXCP_DEBUG)) {
3825 ret = EXCP_INTERRUPT;
3826 event_pending = 0;
3827 break;
3829 if (ret == EXCP_HLT) {
3830 /* Give the next CPU a chance to run. */
3831 cur_cpu = env;
3832 continue;
3834 if (ret != EXCP_HALTED)
3835 break;
3836 /* all CPUs are halted ? */
3837 if (env == cur_cpu)
3838 break;
3840 cur_cpu = env;
3842 if (shutdown_requested) {
3843 ret = EXCP_INTERRUPT;
3844 if (no_shutdown) {
3845 vm_stop(0);
3846 no_shutdown = 0;
3848 else
3849 break;
3851 if (reset_requested) {
3852 reset_requested = 0;
3853 qemu_system_reset();
3854 if (kvm_enabled())
3855 kvm_load_registers(env);
3856 ret = EXCP_INTERRUPT;
3858 if (powerdown_requested) {
3859 powerdown_requested = 0;
3860 qemu_system_powerdown();
3861 ret = EXCP_INTERRUPT;
3863 if (unlikely(ret == EXCP_DEBUG)) {
3864 vm_stop(EXCP_DEBUG);
3866 /* If all cpus are halted then wait until the next IRQ */
3867 /* XXX: use timeout computed from timers */
3868 if (ret == EXCP_HALTED) {
3869 if (use_icount) {
3870 int64_t add;
3871 int64_t delta;
3872 /* Advance virtual time to the next event. */
3873 if (use_icount == 1) {
3874 /* When not using an adaptive execution frequency
3875 we tend to get badly out of sync with real time,
3876 so just delay for a reasonable amount of time. */
3877 delta = 0;
3878 } else {
3879 delta = cpu_get_icount() - cpu_get_clock();
3881 if (delta > 0) {
3882 /* If virtual time is ahead of real time then just
3883 wait for IO. */
3884 timeout = (delta / 1000000) + 1;
3885 } else {
3886 /* Wait for either IO to occur or the next
3887 timer event. */
3888 add = qemu_next_deadline();
3889 /* We advance the timer before checking for IO.
3890 Limit the amount we advance so that early IO
3891 activity won't get the guest too far ahead. */
3892 if (add > 10000000)
3893 add = 10000000;
3894 delta += add;
3895 add = (add + (1 << icount_time_shift) - 1)
3896 >> icount_time_shift;
3897 qemu_icount += add;
3898 timeout = delta / 1000000;
3899 if (timeout < 0)
3900 timeout = 0;
3902 } else {
3903 timeout = 5000;
3905 } else {
3906 timeout = 0;
3908 } else {
3909 if (shutdown_requested) {
3910 ret = EXCP_INTERRUPT;
3911 break;
3913 timeout = 5000;
3915 #ifdef CONFIG_PROFILER
3916 ti = profile_getclock();
3917 #endif
3918 main_loop_wait(timeout);
3919 #ifdef CONFIG_PROFILER
3920 dev_time += profile_getclock() - ti;
3921 #endif
3923 cpu_disable_ticks();
3924 return ret;
3927 static void help(int exitcode)
3929 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
3930 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3931 "usage: %s [options] [disk_image]\n"
3932 "\n"
3933 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3934 "\n"
3935 "Standard options:\n"
3936 "-M machine select emulated machine (-M ? for list)\n"
3937 "-cpu cpu select CPU (-cpu ? for list)\n"
3938 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3939 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3940 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3941 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3942 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3943 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3944 " [,cache=writethrough|writeback|none][,format=f]\n"
3945 " [,boot=on|off]\n"
3946 " use 'file' as a drive image\n"
3947 "-mtdblock file use 'file' as on-board Flash memory image\n"
3948 "-sd file use 'file' as SecureDigital card image\n"
3949 "-pflash file use 'file' as a parallel flash image\n"
3950 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3951 "-snapshot write to temporary files instead of disk image files\n"
3952 #ifdef CONFIG_SDL
3953 "-no-frame open SDL window without a frame and window decorations\n"
3954 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3955 "-no-quit disable SDL window close capability\n"
3956 #endif
3957 #ifdef TARGET_I386
3958 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3959 #endif
3960 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3961 "-smp n set the number of CPUs to 'n' [default=1]\n"
3962 "-nographic disable graphical output and redirect serial I/Os to console\n"
3963 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3964 #ifndef _WIN32
3965 "-k language use keyboard layout (for example \"fr\" for French)\n"
3966 #endif
3967 #ifdef HAS_AUDIO
3968 "-audio-help print list of audio drivers and their options\n"
3969 "-soundhw c1,... enable audio support\n"
3970 " and only specified sound cards (comma separated list)\n"
3971 " use -soundhw ? to get the list of supported cards\n"
3972 " use -soundhw all to enable all of them\n"
3973 #endif
3974 "-vga [std|cirrus|vmware]\n"
3975 " select video card type\n"
3976 "-localtime set the real time clock to local time [default=utc]\n"
3977 "-full-screen start in full screen\n"
3978 #ifdef TARGET_I386
3979 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3980 #endif
3981 "-usb enable the USB driver (will be the default soon)\n"
3982 "-usbdevice name add the host or guest USB device 'name'\n"
3983 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3984 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3985 #endif
3986 "-name string set the name of the guest\n"
3987 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
3988 "\n"
3989 "Network options:\n"
3990 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
3991 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3992 #ifdef CONFIG_SLIRP
3993 "-net user[,vlan=n][,hostname=host]\n"
3994 " connect the user mode network stack to VLAN 'n' and send\n"
3995 " hostname 'host' to DHCP clients\n"
3996 #endif
3997 #ifdef _WIN32
3998 "-net tap[,vlan=n],ifname=name\n"
3999 " connect the host TAP network interface to VLAN 'n'\n"
4000 #else
4001 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4002 " connect the host TAP network interface to VLAN 'n' and use the\n"
4003 " network scripts 'file' (default=%s)\n"
4004 " and 'dfile' (default=%s);\n"
4005 " use '[down]script=no' to disable script execution;\n"
4006 " use 'fd=h' to connect to an already opened TAP interface\n"
4007 #endif
4008 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4009 " connect the vlan 'n' to another VLAN using a socket connection\n"
4010 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4011 " connect the vlan 'n' to multicast maddr and port\n"
4012 #ifdef CONFIG_VDE
4013 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4014 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4015 " on host and listening for incoming connections on 'socketpath'.\n"
4016 " Use group 'groupname' and mode 'octalmode' to change default\n"
4017 " ownership and permissions for communication port.\n"
4018 #endif
4019 "-net none use it alone to have zero network devices; if no -net option\n"
4020 " is provided, the default is '-net nic -net user'\n"
4021 "\n"
4022 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
4023 "-bt hci,host[:id]\n"
4024 " Use host's HCI with the given name\n"
4025 "-bt hci[,vlan=n]\n"
4026 " Emulate a standard HCI in virtual scatternet 'n'\n"
4027 "-bt vhci[,vlan=n]\n"
4028 " Add host computer to virtual scatternet 'n' using VHCI\n"
4029 "-bt device:dev[,vlan=n]\n"
4030 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
4031 "\n"
4032 #ifdef CONFIG_SLIRP
4033 "-tftp dir allow tftp access to files in dir [-net user]\n"
4034 "-bootp file advertise file in BOOTP replies\n"
4035 #ifndef _WIN32
4036 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4037 #endif
4038 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4039 " redirect TCP or UDP connections from host to guest [-net user]\n"
4040 #endif
4041 "\n"
4042 "Linux boot specific:\n"
4043 "-kernel bzImage use 'bzImage' as kernel image\n"
4044 "-append cmdline use 'cmdline' as kernel command line\n"
4045 "-initrd file use 'file' as initial ram disk\n"
4046 "\n"
4047 "Debug/Expert options:\n"
4048 "-monitor dev redirect the monitor to char device 'dev'\n"
4049 "-serial dev redirect the serial port to char device 'dev'\n"
4050 "-parallel dev redirect the parallel port to char device 'dev'\n"
4051 "-pidfile file Write PID to 'file'\n"
4052 "-S freeze CPU at startup (use 'c' to start execution)\n"
4053 "-s wait gdb connection to port\n"
4054 "-p port set gdb connection port [default=%s]\n"
4055 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4056 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4057 " translation (t=none or lba) (usually qemu can guess them)\n"
4058 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4059 #ifdef USE_KQEMU
4060 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4061 "-no-kqemu disable KQEMU kernel module usage\n"
4062 #endif
4063 #ifdef CONFIG_KVM
4064 "-enable-kvm enable KVM full virtualization support\n"
4065 #endif
4066 #ifdef USE_KVM
4067 #ifndef NO_CPU_EMULATION
4068 "-no-kvm disable KVM hardware virtualization\n"
4069 #endif
4070 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4071 "-no-kvm-pit disable KVM kernel mode PIT\n"
4072 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4073 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4074 " expose a PCI device to the guest OS.\n"
4075 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4076 " 'string' is used in log output.\n"
4077 #endif
4078 #endif
4079 #ifdef TARGET_I386
4080 "-no-acpi disable ACPI\n"
4081 #endif
4082 #ifdef CONFIG_CURSES
4083 "-curses use a curses/ncurses interface instead of SDL\n"
4084 #endif
4085 "-no-reboot exit instead of rebooting\n"
4086 "-no-shutdown stop before shutdown\n"
4087 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
4088 "-vnc display start a VNC server on display\n"
4089 #ifndef _WIN32
4090 "-daemonize daemonize QEMU after initializing\n"
4091 #endif
4092 "-tdf inject timer interrupts that got lost\n"
4093 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4094 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
4095 "-option-rom rom load a file, rom, into the option ROM space\n"
4096 #ifdef TARGET_SPARC
4097 "-prom-env variable=value set OpenBIOS nvram variables\n"
4098 #endif
4099 "-clock force the use of the given methods for timer alarm.\n"
4100 " To see what timers are available use -clock ?\n"
4101 "-startdate select initial date of the clock\n"
4102 "-icount [N|auto]\n"
4103 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4104 "\n"
4105 "During emulation, the following keys are useful:\n"
4106 "ctrl-alt-f toggle full screen\n"
4107 "ctrl-alt-n switch to virtual console 'n'\n"
4108 "ctrl-alt toggle mouse and keyboard grab\n"
4109 "\n"
4110 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4112 "qemu",
4113 DEFAULT_RAM_SIZE,
4114 #ifndef _WIN32
4115 DEFAULT_NETWORK_SCRIPT,
4116 DEFAULT_NETWORK_DOWN_SCRIPT,
4117 #endif
4118 DEFAULT_GDBSTUB_PORT,
4119 "/tmp/qemu.log");
4120 exit(exitcode);
4123 #define HAS_ARG 0x0001
4125 enum {
4126 QEMU_OPTION_h,
4128 QEMU_OPTION_M,
4129 QEMU_OPTION_cpu,
4130 QEMU_OPTION_fda,
4131 QEMU_OPTION_fdb,
4132 QEMU_OPTION_hda,
4133 QEMU_OPTION_hdb,
4134 QEMU_OPTION_hdc,
4135 QEMU_OPTION_hdd,
4136 QEMU_OPTION_drive,
4137 QEMU_OPTION_cdrom,
4138 QEMU_OPTION_mtdblock,
4139 QEMU_OPTION_sd,
4140 QEMU_OPTION_pflash,
4141 QEMU_OPTION_boot,
4142 QEMU_OPTION_snapshot,
4143 #ifdef TARGET_I386
4144 QEMU_OPTION_no_fd_bootchk,
4145 #endif
4146 QEMU_OPTION_m,
4147 QEMU_OPTION_nographic,
4148 QEMU_OPTION_portrait,
4149 #ifdef HAS_AUDIO
4150 QEMU_OPTION_audio_help,
4151 QEMU_OPTION_soundhw,
4152 #endif
4154 QEMU_OPTION_net,
4155 QEMU_OPTION_tftp,
4156 QEMU_OPTION_bootp,
4157 QEMU_OPTION_smb,
4158 QEMU_OPTION_redir,
4159 QEMU_OPTION_bt,
4161 QEMU_OPTION_kernel,
4162 QEMU_OPTION_append,
4163 QEMU_OPTION_initrd,
4165 QEMU_OPTION_S,
4166 QEMU_OPTION_s,
4167 QEMU_OPTION_p,
4168 QEMU_OPTION_d,
4169 QEMU_OPTION_hdachs,
4170 QEMU_OPTION_L,
4171 QEMU_OPTION_bios,
4172 QEMU_OPTION_k,
4173 QEMU_OPTION_localtime,
4174 QEMU_OPTION_g,
4175 QEMU_OPTION_vga,
4176 QEMU_OPTION_echr,
4177 QEMU_OPTION_monitor,
4178 QEMU_OPTION_serial,
4179 QEMU_OPTION_parallel,
4180 QEMU_OPTION_loadvm,
4181 QEMU_OPTION_full_screen,
4182 QEMU_OPTION_no_frame,
4183 QEMU_OPTION_alt_grab,
4184 QEMU_OPTION_no_quit,
4185 QEMU_OPTION_pidfile,
4186 QEMU_OPTION_no_kqemu,
4187 QEMU_OPTION_kernel_kqemu,
4188 QEMU_OPTION_enable_kvm,
4189 QEMU_OPTION_win2k_hack,
4190 QEMU_OPTION_usb,
4191 QEMU_OPTION_usbdevice,
4192 QEMU_OPTION_smp,
4193 QEMU_OPTION_vnc,
4194 QEMU_OPTION_no_acpi,
4195 QEMU_OPTION_curses,
4196 QEMU_OPTION_no_kvm,
4197 QEMU_OPTION_no_kvm_irqchip,
4198 QEMU_OPTION_no_kvm_pit,
4199 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4200 QEMU_OPTION_pcidevice,
4201 #endif
4202 QEMU_OPTION_no_reboot,
4203 QEMU_OPTION_no_shutdown,
4204 QEMU_OPTION_show_cursor,
4205 QEMU_OPTION_daemonize,
4206 QEMU_OPTION_option_rom,
4207 QEMU_OPTION_semihosting,
4208 QEMU_OPTION_cpu_vendor,
4209 QEMU_OPTION_name,
4210 QEMU_OPTION_prom_env,
4211 QEMU_OPTION_old_param,
4212 QEMU_OPTION_clock,
4213 QEMU_OPTION_startdate,
4214 QEMU_OPTION_tb_size,
4215 QEMU_OPTION_icount,
4216 QEMU_OPTION_uuid,
4217 QEMU_OPTION_incoming,
4218 QEMU_OPTION_tdf,
4219 QEMU_OPTION_kvm_shadow_memory,
4220 QEMU_OPTION_mempath,
4223 typedef struct QEMUOption {
4224 const char *name;
4225 int flags;
4226 int index;
4227 } QEMUOption;
4229 static const QEMUOption qemu_options[] = {
4230 { "h", 0, QEMU_OPTION_h },
4231 { "help", 0, QEMU_OPTION_h },
4233 { "M", HAS_ARG, QEMU_OPTION_M },
4234 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4235 { "fda", HAS_ARG, QEMU_OPTION_fda },
4236 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4237 { "hda", HAS_ARG, QEMU_OPTION_hda },
4238 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4239 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4240 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4241 { "drive", HAS_ARG, QEMU_OPTION_drive },
4242 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4243 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4244 { "sd", HAS_ARG, QEMU_OPTION_sd },
4245 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4246 { "boot", HAS_ARG, QEMU_OPTION_boot },
4247 { "snapshot", 0, QEMU_OPTION_snapshot },
4248 #ifdef TARGET_I386
4249 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4250 #endif
4251 { "m", HAS_ARG, QEMU_OPTION_m },
4252 { "nographic", 0, QEMU_OPTION_nographic },
4253 { "portrait", 0, QEMU_OPTION_portrait },
4254 { "k", HAS_ARG, QEMU_OPTION_k },
4255 #ifdef HAS_AUDIO
4256 { "audio-help", 0, QEMU_OPTION_audio_help },
4257 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4258 #endif
4260 { "net", HAS_ARG, QEMU_OPTION_net},
4261 #ifdef CONFIG_SLIRP
4262 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4263 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4264 #ifndef _WIN32
4265 { "smb", HAS_ARG, QEMU_OPTION_smb },
4266 #endif
4267 { "redir", HAS_ARG, QEMU_OPTION_redir },
4268 #endif
4269 { "bt", HAS_ARG, QEMU_OPTION_bt },
4271 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4272 { "append", HAS_ARG, QEMU_OPTION_append },
4273 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4275 { "S", 0, QEMU_OPTION_S },
4276 { "s", 0, QEMU_OPTION_s },
4277 { "p", HAS_ARG, QEMU_OPTION_p },
4278 { "d", HAS_ARG, QEMU_OPTION_d },
4279 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4280 { "L", HAS_ARG, QEMU_OPTION_L },
4281 { "bios", HAS_ARG, QEMU_OPTION_bios },
4282 #ifdef USE_KQEMU
4283 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4284 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4285 #endif
4286 #ifdef CONFIG_KVM
4287 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4288 #endif
4289 #ifdef USE_KVM
4290 #ifndef NO_CPU_EMULATION
4291 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4292 #endif
4293 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4294 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4295 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4296 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4297 #endif
4298 #endif
4299 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4300 { "g", 1, QEMU_OPTION_g },
4301 #endif
4302 { "localtime", 0, QEMU_OPTION_localtime },
4303 { "vga", HAS_ARG, QEMU_OPTION_vga },
4304 { "echr", HAS_ARG, QEMU_OPTION_echr },
4305 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4306 { "serial", HAS_ARG, QEMU_OPTION_serial },
4307 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4308 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4309 { "incoming", 1, QEMU_OPTION_incoming },
4310 { "full-screen", 0, QEMU_OPTION_full_screen },
4311 #ifdef CONFIG_SDL
4312 { "no-frame", 0, QEMU_OPTION_no_frame },
4313 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4314 { "no-quit", 0, QEMU_OPTION_no_quit },
4315 #endif
4316 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4317 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4318 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4319 { "smp", HAS_ARG, QEMU_OPTION_smp },
4320 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4321 #ifdef CONFIG_CURSES
4322 { "curses", 0, QEMU_OPTION_curses },
4323 #endif
4324 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4326 /* temporary options */
4327 { "usb", 0, QEMU_OPTION_usb },
4328 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4329 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4330 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4331 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4332 { "daemonize", 0, QEMU_OPTION_daemonize },
4333 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4334 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4335 { "semihosting", 0, QEMU_OPTION_semihosting },
4336 #endif
4337 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4338 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4339 { "name", HAS_ARG, QEMU_OPTION_name },
4340 #if defined(TARGET_SPARC)
4341 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4342 #endif
4343 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4344 #if defined(TARGET_ARM)
4345 { "old-param", 0, QEMU_OPTION_old_param },
4346 #endif
4347 { "clock", HAS_ARG, QEMU_OPTION_clock },
4348 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4349 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4350 { "icount", HAS_ARG, QEMU_OPTION_icount },
4351 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4352 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4353 { NULL },
4356 /* password input */
4358 int qemu_key_check(BlockDriverState *bs, const char *name)
4360 char password[256];
4361 int i;
4363 if (!bdrv_is_encrypted(bs))
4364 return 0;
4366 term_printf("%s is encrypted.\n", name);
4367 for(i = 0; i < 3; i++) {
4368 monitor_readline("Password: ", 1, password, sizeof(password));
4369 if (bdrv_set_key(bs, password) == 0)
4370 return 0;
4371 term_printf("invalid password\n");
4373 return -EPERM;
4376 static BlockDriverState *get_bdrv(int index)
4378 if (index > nb_drives)
4379 return NULL;
4380 return drives_table[index].bdrv;
4383 static void read_passwords(void)
4385 BlockDriverState *bs;
4386 int i;
4388 for(i = 0; i < 6; i++) {
4389 bs = get_bdrv(i);
4390 if (bs)
4391 qemu_key_check(bs, bdrv_get_device_name(bs));
4395 #ifdef HAS_AUDIO
4396 struct soundhw soundhw[] = {
4397 #ifdef HAS_AUDIO_CHOICE
4398 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4400 "pcspk",
4401 "PC speaker",
4404 { .init_isa = pcspk_audio_init }
4406 #endif
4408 "sb16",
4409 "Creative Sound Blaster 16",
4412 { .init_isa = SB16_init }
4415 #ifdef CONFIG_CS4231A
4417 "cs4231a",
4418 "CS4231A",
4421 { .init_isa = cs4231a_init }
4423 #endif
4425 #ifdef CONFIG_ADLIB
4427 "adlib",
4428 #ifdef HAS_YMF262
4429 "Yamaha YMF262 (OPL3)",
4430 #else
4431 "Yamaha YM3812 (OPL2)",
4432 #endif
4435 { .init_isa = Adlib_init }
4437 #endif
4439 #ifdef CONFIG_GUS
4441 "gus",
4442 "Gravis Ultrasound GF1",
4445 { .init_isa = GUS_init }
4447 #endif
4449 #ifdef CONFIG_AC97
4451 "ac97",
4452 "Intel 82801AA AC97 Audio",
4455 { .init_pci = ac97_init }
4457 #endif
4460 "es1370",
4461 "ENSONIQ AudioPCI ES1370",
4464 { .init_pci = es1370_init }
4466 #endif
4468 { NULL, NULL, 0, 0, { NULL } }
4471 static void select_soundhw (const char *optarg)
4473 struct soundhw *c;
4475 if (*optarg == '?') {
4476 show_valid_cards:
4478 printf ("Valid sound card names (comma separated):\n");
4479 for (c = soundhw; c->name; ++c) {
4480 printf ("%-11s %s\n", c->name, c->descr);
4482 printf ("\n-soundhw all will enable all of the above\n");
4483 exit (*optarg != '?');
4485 else {
4486 size_t l;
4487 const char *p;
4488 char *e;
4489 int bad_card = 0;
4491 if (!strcmp (optarg, "all")) {
4492 for (c = soundhw; c->name; ++c) {
4493 c->enabled = 1;
4495 return;
4498 p = optarg;
4499 while (*p) {
4500 e = strchr (p, ',');
4501 l = !e ? strlen (p) : (size_t) (e - p);
4503 for (c = soundhw; c->name; ++c) {
4504 if (!strncmp (c->name, p, l)) {
4505 c->enabled = 1;
4506 break;
4510 if (!c->name) {
4511 if (l > 80) {
4512 fprintf (stderr,
4513 "Unknown sound card name (too big to show)\n");
4515 else {
4516 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4517 (int) l, p);
4519 bad_card = 1;
4521 p += l + (e != NULL);
4524 if (bad_card)
4525 goto show_valid_cards;
4528 #endif
4530 static void select_vgahw (const char *p)
4532 const char *opts;
4534 if (strstart(p, "std", &opts)) {
4535 cirrus_vga_enabled = 0;
4536 vmsvga_enabled = 0;
4537 } else if (strstart(p, "cirrus", &opts)) {
4538 cirrus_vga_enabled = 1;
4539 vmsvga_enabled = 0;
4540 } else if (strstart(p, "vmware", &opts)) {
4541 cirrus_vga_enabled = 0;
4542 vmsvga_enabled = 1;
4543 } else {
4544 invalid_vga:
4545 fprintf(stderr, "Unknown vga type: %s\n", p);
4546 exit(1);
4548 while (*opts) {
4549 const char *nextopt;
4551 if (strstart(opts, ",retrace=", &nextopt)) {
4552 opts = nextopt;
4553 if (strstart(opts, "dumb", &nextopt))
4554 vga_retrace_method = VGA_RETRACE_DUMB;
4555 else if (strstart(opts, "precise", &nextopt))
4556 vga_retrace_method = VGA_RETRACE_PRECISE;
4557 else goto invalid_vga;
4558 } else goto invalid_vga;
4559 opts = nextopt;
4563 #ifdef _WIN32
4564 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4566 exit(STATUS_CONTROL_C_EXIT);
4567 return TRUE;
4569 #endif
4571 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4573 int ret;
4575 if(strlen(str) != 36)
4576 return -1;
4578 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4579 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4580 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4582 if(ret != 16)
4583 return -1;
4585 return 0;
4588 #define MAX_NET_CLIENTS 32
4590 static int saved_argc;
4591 static char **saved_argv;
4593 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4595 *argc = saved_argc;
4596 *argv = saved_argv;
4597 *opt_daemonize = daemonize;
4598 *opt_incoming = incoming;
4602 static int gethugepagesize(void)
4604 int ret, fd;
4605 char buf[4096];
4606 char *needle = "Hugepagesize:";
4607 char *size;
4608 unsigned long hugepagesize;
4610 fd = open("/proc/meminfo", O_RDONLY);
4611 if (fd < 0) {
4612 perror("open");
4613 exit(0);
4616 ret = read(fd, buf, sizeof(buf));
4617 if (ret < 0) {
4618 perror("read");
4619 exit(0);
4622 size = strstr(buf, needle);
4623 if (!size)
4624 return 0;
4625 size += strlen(needle);
4626 hugepagesize = strtol(size, NULL, 0);
4627 return hugepagesize;
4630 void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4632 char *filename;
4633 void *area;
4634 int fd;
4636 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4637 return NULL;
4639 hpagesize = gethugepagesize() * 1024;
4640 if (!hpagesize)
4641 return NULL;
4643 fd = mkstemp(filename);
4644 if (fd < 0) {
4645 perror("mkstemp");
4646 free(filename);
4647 return NULL;
4649 unlink(filename);
4650 free(filename);
4652 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4655 * ftruncate is not supported by hugetlbfs in older
4656 * hosts, so don't bother checking for errors.
4657 * If anything goes wrong with it under other filesystems,
4658 * mmap will fail.
4660 ftruncate(fd, memory);
4662 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4663 if (area == MAP_FAILED) {
4664 perror("mmap");
4665 close(fd);
4666 return NULL;
4669 *len = memory;
4670 return area;
4673 void *qemu_alloc_physram(unsigned long memory)
4675 void *area = NULL;
4676 unsigned long map_len = memory;
4678 #ifdef USE_KVM
4679 if (mem_path)
4680 area = alloc_mem_area(memory, &map_len, mem_path);
4681 #endif
4682 if (!area)
4683 area = qemu_vmalloc(memory);
4684 #ifdef USE_KVM
4685 if (kvm_setup_guest_memory(area, map_len))
4686 area = NULL;
4687 #endif
4688 return area;
4691 #ifndef _WIN32
4693 static void termsig_handler(int signal)
4695 qemu_system_shutdown_request();
4698 static void termsig_setup(void)
4700 struct sigaction act;
4702 memset(&act, 0, sizeof(act));
4703 act.sa_handler = termsig_handler;
4704 sigaction(SIGINT, &act, NULL);
4705 sigaction(SIGHUP, &act, NULL);
4706 sigaction(SIGTERM, &act, NULL);
4709 #endif
4711 int main(int argc, char **argv)
4713 #ifdef CONFIG_GDBSTUB
4714 int use_gdbstub;
4715 const char *gdbstub_port;
4716 #endif
4717 uint32_t boot_devices_bitmap = 0;
4718 int i;
4719 int snapshot, linux_boot, net_boot;
4720 const char *initrd_filename;
4721 const char *kernel_filename, *kernel_cmdline;
4722 const char *boot_devices = "";
4723 DisplayState *ds = &display_state;
4724 int cyls, heads, secs, translation;
4725 const char *net_clients[MAX_NET_CLIENTS];
4726 int nb_net_clients;
4727 const char *bt_opts[MAX_BT_CMDLINE];
4728 int nb_bt_opts;
4729 int hda_index;
4730 int optind;
4731 const char *r, *optarg;
4732 CharDriverState *monitor_hd;
4733 const char *monitor_device;
4734 const char *serial_devices[MAX_SERIAL_PORTS];
4735 int serial_device_index;
4736 const char *parallel_devices[MAX_PARALLEL_PORTS];
4737 int parallel_device_index;
4738 const char *loadvm = NULL;
4739 QEMUMachine *machine;
4740 const char *cpu_model;
4741 const char *usb_devices[MAX_USB_CMDLINE];
4742 int usb_devices_index;
4743 int fds[2];
4744 int tb_size;
4745 const char *pid_file = NULL;
4746 int autostart;
4747 const char *incoming = NULL;
4749 LIST_INIT (&vm_change_state_head);
4750 #ifndef _WIN32
4752 struct sigaction act;
4753 sigfillset(&act.sa_mask);
4754 act.sa_flags = 0;
4755 act.sa_handler = SIG_IGN;
4756 sigaction(SIGPIPE, &act, NULL);
4758 #else
4759 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4760 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4761 QEMU to run on a single CPU */
4763 HANDLE h;
4764 DWORD mask, smask;
4765 int i;
4766 h = GetCurrentProcess();
4767 if (GetProcessAffinityMask(h, &mask, &smask)) {
4768 for(i = 0; i < 32; i++) {
4769 if (mask & (1 << i))
4770 break;
4772 if (i != 32) {
4773 mask = 1 << i;
4774 SetProcessAffinityMask(h, mask);
4778 #endif
4780 register_machines();
4781 machine = first_machine;
4782 cpu_model = NULL;
4783 initrd_filename = NULL;
4784 ram_size = 0;
4785 vga_ram_size = VGA_RAM_SIZE;
4786 #ifdef CONFIG_GDBSTUB
4787 use_gdbstub = 0;
4788 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4789 #endif
4790 snapshot = 0;
4791 nographic = 0;
4792 curses = 0;
4793 kernel_filename = NULL;
4794 kernel_cmdline = "";
4795 cyls = heads = secs = 0;
4796 translation = BIOS_ATA_TRANSLATION_AUTO;
4797 monitor_device = "vc";
4799 serial_devices[0] = "vc:80Cx24C";
4800 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4801 serial_devices[i] = NULL;
4802 serial_device_index = 0;
4804 parallel_devices[0] = "vc:640x480";
4805 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4806 parallel_devices[i] = NULL;
4807 parallel_device_index = 0;
4809 usb_devices_index = 0;
4810 assigned_devices_index = 0;
4812 nb_net_clients = 0;
4813 nb_bt_opts = 0;
4814 nb_drives = 0;
4815 nb_drives_opt = 0;
4816 hda_index = -1;
4818 nb_nics = 0;
4820 tb_size = 0;
4821 autostart= 1;
4823 optind = 1;
4824 for(;;) {
4825 if (optind >= argc)
4826 break;
4827 r = argv[optind];
4828 if (r[0] != '-') {
4829 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4830 } else {
4831 const QEMUOption *popt;
4833 optind++;
4834 /* Treat --foo the same as -foo. */
4835 if (r[1] == '-')
4836 r++;
4837 popt = qemu_options;
4838 for(;;) {
4839 if (!popt->name) {
4840 fprintf(stderr, "%s: invalid option -- '%s'\n",
4841 argv[0], r);
4842 exit(1);
4844 if (!strcmp(popt->name, r + 1))
4845 break;
4846 popt++;
4848 if (popt->flags & HAS_ARG) {
4849 if (optind >= argc) {
4850 fprintf(stderr, "%s: option '%s' requires an argument\n",
4851 argv[0], r);
4852 exit(1);
4854 optarg = argv[optind++];
4855 } else {
4856 optarg = NULL;
4859 switch(popt->index) {
4860 case QEMU_OPTION_M:
4861 machine = find_machine(optarg);
4862 if (!machine) {
4863 QEMUMachine *m;
4864 printf("Supported machines are:\n");
4865 for(m = first_machine; m != NULL; m = m->next) {
4866 printf("%-10s %s%s\n",
4867 m->name, m->desc,
4868 m == first_machine ? " (default)" : "");
4870 exit(*optarg != '?');
4872 break;
4873 case QEMU_OPTION_cpu:
4874 /* hw initialization will check this */
4875 if (*optarg == '?') {
4876 /* XXX: implement xxx_cpu_list for targets that still miss it */
4877 #if defined(cpu_list)
4878 cpu_list(stdout, &fprintf);
4879 #endif
4880 exit(0);
4881 } else {
4882 cpu_model = optarg;
4884 break;
4885 case QEMU_OPTION_initrd:
4886 initrd_filename = optarg;
4887 break;
4888 case QEMU_OPTION_hda:
4889 if (cyls == 0)
4890 hda_index = drive_add(optarg, HD_ALIAS, 0);
4891 else
4892 hda_index = drive_add(optarg, HD_ALIAS
4893 ",cyls=%d,heads=%d,secs=%d%s",
4894 0, cyls, heads, secs,
4895 translation == BIOS_ATA_TRANSLATION_LBA ?
4896 ",trans=lba" :
4897 translation == BIOS_ATA_TRANSLATION_NONE ?
4898 ",trans=none" : "");
4899 break;
4900 case QEMU_OPTION_hdb:
4901 case QEMU_OPTION_hdc:
4902 case QEMU_OPTION_hdd:
4903 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4904 break;
4905 case QEMU_OPTION_drive:
4906 drive_add(NULL, "%s", optarg);
4907 break;
4908 case QEMU_OPTION_mtdblock:
4909 drive_add(optarg, MTD_ALIAS);
4910 break;
4911 case QEMU_OPTION_sd:
4912 drive_add(optarg, SD_ALIAS);
4913 break;
4914 case QEMU_OPTION_pflash:
4915 drive_add(optarg, PFLASH_ALIAS);
4916 break;
4917 case QEMU_OPTION_snapshot:
4918 snapshot = 1;
4919 break;
4920 case QEMU_OPTION_hdachs:
4922 const char *p;
4923 p = optarg;
4924 cyls = strtol(p, (char **)&p, 0);
4925 if (cyls < 1 || cyls > 16383)
4926 goto chs_fail;
4927 if (*p != ',')
4928 goto chs_fail;
4929 p++;
4930 heads = strtol(p, (char **)&p, 0);
4931 if (heads < 1 || heads > 16)
4932 goto chs_fail;
4933 if (*p != ',')
4934 goto chs_fail;
4935 p++;
4936 secs = strtol(p, (char **)&p, 0);
4937 if (secs < 1 || secs > 63)
4938 goto chs_fail;
4939 if (*p == ',') {
4940 p++;
4941 if (!strcmp(p, "none"))
4942 translation = BIOS_ATA_TRANSLATION_NONE;
4943 else if (!strcmp(p, "lba"))
4944 translation = BIOS_ATA_TRANSLATION_LBA;
4945 else if (!strcmp(p, "auto"))
4946 translation = BIOS_ATA_TRANSLATION_AUTO;
4947 else
4948 goto chs_fail;
4949 } else if (*p != '\0') {
4950 chs_fail:
4951 fprintf(stderr, "qemu: invalid physical CHS format\n");
4952 exit(1);
4954 if (hda_index != -1)
4955 snprintf(drives_opt[hda_index].opt,
4956 sizeof(drives_opt[hda_index].opt),
4957 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4958 0, cyls, heads, secs,
4959 translation == BIOS_ATA_TRANSLATION_LBA ?
4960 ",trans=lba" :
4961 translation == BIOS_ATA_TRANSLATION_NONE ?
4962 ",trans=none" : "");
4964 break;
4965 case QEMU_OPTION_nographic:
4966 nographic = 1;
4967 break;
4968 #ifdef CONFIG_CURSES
4969 case QEMU_OPTION_curses:
4970 curses = 1;
4971 break;
4972 #endif
4973 case QEMU_OPTION_portrait:
4974 graphic_rotate = 1;
4975 break;
4976 case QEMU_OPTION_kernel:
4977 kernel_filename = optarg;
4978 break;
4979 case QEMU_OPTION_append:
4980 kernel_cmdline = optarg;
4981 break;
4982 case QEMU_OPTION_cdrom:
4983 drive_add(optarg, CDROM_ALIAS);
4984 break;
4985 case QEMU_OPTION_boot:
4986 boot_devices = optarg;
4987 /* We just do some generic consistency checks */
4989 /* Could easily be extended to 64 devices if needed */
4990 const char *p;
4992 boot_devices_bitmap = 0;
4993 for (p = boot_devices; *p != '\0'; p++) {
4994 /* Allowed boot devices are:
4995 * a b : floppy disk drives
4996 * c ... f : IDE disk drives
4997 * g ... m : machine implementation dependant drives
4998 * n ... p : network devices
4999 * It's up to each machine implementation to check
5000 * if the given boot devices match the actual hardware
5001 * implementation and firmware features.
5003 if (*p < 'a' || *p > 'q') {
5004 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5005 exit(1);
5007 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5008 fprintf(stderr,
5009 "Boot device '%c' was given twice\n",*p);
5010 exit(1);
5012 boot_devices_bitmap |= 1 << (*p - 'a');
5015 break;
5016 case QEMU_OPTION_fda:
5017 case QEMU_OPTION_fdb:
5018 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5019 break;
5020 #ifdef TARGET_I386
5021 case QEMU_OPTION_no_fd_bootchk:
5022 fd_bootchk = 0;
5023 break;
5024 #endif
5025 case QEMU_OPTION_net:
5026 if (nb_net_clients >= MAX_NET_CLIENTS) {
5027 fprintf(stderr, "qemu: too many network clients\n");
5028 exit(1);
5030 net_clients[nb_net_clients] = optarg;
5031 nb_net_clients++;
5032 break;
5033 #ifdef CONFIG_SLIRP
5034 case QEMU_OPTION_tftp:
5035 tftp_prefix = optarg;
5036 break;
5037 case QEMU_OPTION_bootp:
5038 bootp_filename = optarg;
5039 break;
5040 #ifndef _WIN32
5041 case QEMU_OPTION_smb:
5042 net_slirp_smb(optarg);
5043 break;
5044 #endif
5045 case QEMU_OPTION_redir:
5046 net_slirp_redir(optarg);
5047 break;
5048 #endif
5049 case QEMU_OPTION_bt:
5050 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5051 fprintf(stderr, "qemu: too many bluetooth options\n");
5052 exit(1);
5054 bt_opts[nb_bt_opts++] = optarg;
5055 break;
5056 #ifdef HAS_AUDIO
5057 case QEMU_OPTION_audio_help:
5058 AUD_help ();
5059 exit (0);
5060 break;
5061 case QEMU_OPTION_soundhw:
5062 select_soundhw (optarg);
5063 break;
5064 #endif
5065 case QEMU_OPTION_h:
5066 help(0);
5067 break;
5068 case QEMU_OPTION_m: {
5069 uint64_t value;
5070 char *ptr;
5072 value = strtoul(optarg, &ptr, 10);
5073 switch (*ptr) {
5074 case 0: case 'M': case 'm':
5075 value <<= 20;
5076 break;
5077 case 'G': case 'g':
5078 value <<= 30;
5079 break;
5080 default:
5081 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5082 exit(1);
5085 /* On 32-bit hosts, QEMU is limited by virtual address space */
5086 if (value > (2047 << 20)
5087 #ifndef USE_KQEMU
5088 && HOST_LONG_BITS == 32
5089 #endif
5091 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5092 exit(1);
5094 if (value != (uint64_t)(ram_addr_t)value) {
5095 fprintf(stderr, "qemu: ram size too large\n");
5096 exit(1);
5098 ram_size = value;
5099 break;
5101 case QEMU_OPTION_d:
5103 int mask;
5104 const CPULogItem *item;
5106 mask = cpu_str_to_log_mask(optarg);
5107 if (!mask) {
5108 printf("Log items (comma separated):\n");
5109 for(item = cpu_log_items; item->mask != 0; item++) {
5110 printf("%-10s %s\n", item->name, item->help);
5112 exit(1);
5114 cpu_set_log(mask);
5116 break;
5117 #ifdef CONFIG_GDBSTUB
5118 case QEMU_OPTION_s:
5119 use_gdbstub = 1;
5120 break;
5121 case QEMU_OPTION_p:
5122 gdbstub_port = optarg;
5123 break;
5124 #endif
5125 case QEMU_OPTION_L:
5126 bios_dir = optarg;
5127 break;
5128 case QEMU_OPTION_bios:
5129 bios_name = optarg;
5130 break;
5131 case QEMU_OPTION_S:
5132 autostart = 0;
5133 break;
5134 case QEMU_OPTION_k:
5135 keyboard_layout = optarg;
5136 break;
5137 case QEMU_OPTION_localtime:
5138 rtc_utc = 0;
5139 break;
5140 case QEMU_OPTION_vga:
5141 select_vgahw (optarg);
5142 break;
5143 case QEMU_OPTION_g:
5145 const char *p;
5146 int w, h, depth;
5147 p = optarg;
5148 w = strtol(p, (char **)&p, 10);
5149 if (w <= 0) {
5150 graphic_error:
5151 fprintf(stderr, "qemu: invalid resolution or depth\n");
5152 exit(1);
5154 if (*p != 'x')
5155 goto graphic_error;
5156 p++;
5157 h = strtol(p, (char **)&p, 10);
5158 if (h <= 0)
5159 goto graphic_error;
5160 if (*p == 'x') {
5161 p++;
5162 depth = strtol(p, (char **)&p, 10);
5163 if (depth != 8 && depth != 15 && depth != 16 &&
5164 depth != 24 && depth != 32)
5165 goto graphic_error;
5166 } else if (*p == '\0') {
5167 depth = graphic_depth;
5168 } else {
5169 goto graphic_error;
5172 graphic_width = w;
5173 graphic_height = h;
5174 graphic_depth = depth;
5176 break;
5177 case QEMU_OPTION_echr:
5179 char *r;
5180 term_escape_char = strtol(optarg, &r, 0);
5181 if (r == optarg)
5182 printf("Bad argument to echr\n");
5183 break;
5185 case QEMU_OPTION_monitor:
5186 monitor_device = optarg;
5187 break;
5188 case QEMU_OPTION_serial:
5189 if (serial_device_index >= MAX_SERIAL_PORTS) {
5190 fprintf(stderr, "qemu: too many serial ports\n");
5191 exit(1);
5193 serial_devices[serial_device_index] = optarg;
5194 serial_device_index++;
5195 break;
5196 case QEMU_OPTION_parallel:
5197 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5198 fprintf(stderr, "qemu: too many parallel ports\n");
5199 exit(1);
5201 parallel_devices[parallel_device_index] = optarg;
5202 parallel_device_index++;
5203 break;
5204 case QEMU_OPTION_loadvm:
5205 loadvm = optarg;
5206 break;
5207 case QEMU_OPTION_full_screen:
5208 full_screen = 1;
5209 break;
5210 #ifdef CONFIG_SDL
5211 case QEMU_OPTION_no_frame:
5212 no_frame = 1;
5213 break;
5214 case QEMU_OPTION_alt_grab:
5215 alt_grab = 1;
5216 break;
5217 case QEMU_OPTION_no_quit:
5218 no_quit = 1;
5219 break;
5220 #endif
5221 case QEMU_OPTION_pidfile:
5222 pid_file = optarg;
5223 break;
5224 #ifdef TARGET_I386
5225 case QEMU_OPTION_win2k_hack:
5226 win2k_install_hack = 1;
5227 break;
5228 #endif
5229 #ifdef USE_KQEMU
5230 case QEMU_OPTION_no_kqemu:
5231 kqemu_allowed = 0;
5232 break;
5233 case QEMU_OPTION_kernel_kqemu:
5234 kqemu_allowed = 2;
5235 break;
5236 #endif
5237 #ifdef CONFIG_KVM
5238 case QEMU_OPTION_enable_kvm:
5239 kvm_allowed = 1;
5240 #ifdef USE_KQEMU
5241 kqemu_allowed = 0;
5242 #endif
5243 break;
5244 #endif
5245 #ifdef USE_KVM
5246 case QEMU_OPTION_no_kvm:
5247 kvm_allowed = 0;
5248 break;
5249 case QEMU_OPTION_no_kvm_irqchip: {
5250 extern int kvm_irqchip, kvm_pit;
5251 kvm_irqchip = 0;
5252 kvm_pit = 0;
5253 break;
5255 case QEMU_OPTION_no_kvm_pit: {
5256 extern int kvm_pit;
5257 kvm_pit = 0;
5258 break;
5260 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5261 case QEMU_OPTION_pcidevice:
5262 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5263 fprintf(stderr, "Too many assigned devices\n");
5264 exit(1);
5266 assigned_devices[assigned_devices_index] = optarg;
5267 assigned_devices_index++;
5268 break;
5269 #endif
5270 #endif
5271 case QEMU_OPTION_usb:
5272 usb_enabled = 1;
5273 break;
5274 case QEMU_OPTION_usbdevice:
5275 usb_enabled = 1;
5276 if (usb_devices_index >= MAX_USB_CMDLINE) {
5277 fprintf(stderr, "Too many USB devices\n");
5278 exit(1);
5280 usb_devices[usb_devices_index] = optarg;
5281 usb_devices_index++;
5282 break;
5283 case QEMU_OPTION_smp:
5284 smp_cpus = atoi(optarg);
5285 if (smp_cpus < 1) {
5286 fprintf(stderr, "Invalid number of CPUs\n");
5287 exit(1);
5289 break;
5290 case QEMU_OPTION_vnc:
5291 vnc_display = optarg;
5292 break;
5293 case QEMU_OPTION_no_acpi:
5294 acpi_enabled = 0;
5295 break;
5296 case QEMU_OPTION_no_reboot:
5297 no_reboot = 1;
5298 break;
5299 case QEMU_OPTION_no_shutdown:
5300 no_shutdown = 1;
5301 break;
5302 case QEMU_OPTION_show_cursor:
5303 cursor_hide = 0;
5304 break;
5305 case QEMU_OPTION_uuid:
5306 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5307 fprintf(stderr, "Fail to parse UUID string."
5308 " Wrong format.\n");
5309 exit(1);
5311 break;
5312 case QEMU_OPTION_daemonize:
5313 daemonize = 1;
5314 break;
5315 case QEMU_OPTION_option_rom:
5316 if (nb_option_roms >= MAX_OPTION_ROMS) {
5317 fprintf(stderr, "Too many option ROMs\n");
5318 exit(1);
5320 option_rom[nb_option_roms] = optarg;
5321 nb_option_roms++;
5322 break;
5323 case QEMU_OPTION_semihosting:
5324 semihosting_enabled = 1;
5325 break;
5326 case QEMU_OPTION_tdf:
5327 time_drift_fix = 1;
5328 break;
5329 case QEMU_OPTION_kvm_shadow_memory:
5330 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5331 break;
5332 case QEMU_OPTION_mempath:
5333 mem_path = optarg;
5334 break;
5335 case QEMU_OPTION_name:
5336 qemu_name = optarg;
5337 break;
5338 #ifdef TARGET_SPARC
5339 case QEMU_OPTION_prom_env:
5340 if (nb_prom_envs >= MAX_PROM_ENVS) {
5341 fprintf(stderr, "Too many prom variables\n");
5342 exit(1);
5344 prom_envs[nb_prom_envs] = optarg;
5345 nb_prom_envs++;
5346 break;
5347 #endif
5348 case QEMU_OPTION_cpu_vendor:
5349 cpu_vendor_string = optarg;
5350 break;
5351 #ifdef TARGET_ARM
5352 case QEMU_OPTION_old_param:
5353 old_param = 1;
5354 break;
5355 #endif
5356 case QEMU_OPTION_clock:
5357 configure_alarms(optarg);
5358 break;
5359 case QEMU_OPTION_startdate:
5361 struct tm tm;
5362 time_t rtc_start_date;
5363 if (!strcmp(optarg, "now")) {
5364 rtc_date_offset = -1;
5365 } else {
5366 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5367 &tm.tm_year,
5368 &tm.tm_mon,
5369 &tm.tm_mday,
5370 &tm.tm_hour,
5371 &tm.tm_min,
5372 &tm.tm_sec) == 6) {
5373 /* OK */
5374 } else if (sscanf(optarg, "%d-%d-%d",
5375 &tm.tm_year,
5376 &tm.tm_mon,
5377 &tm.tm_mday) == 3) {
5378 tm.tm_hour = 0;
5379 tm.tm_min = 0;
5380 tm.tm_sec = 0;
5381 } else {
5382 goto date_fail;
5384 tm.tm_year -= 1900;
5385 tm.tm_mon--;
5386 rtc_start_date = mktimegm(&tm);
5387 if (rtc_start_date == -1) {
5388 date_fail:
5389 fprintf(stderr, "Invalid date format. Valid format are:\n"
5390 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5391 exit(1);
5393 rtc_date_offset = time(NULL) - rtc_start_date;
5396 break;
5397 case QEMU_OPTION_tb_size:
5398 tb_size = strtol(optarg, NULL, 0);
5399 if (tb_size < 0)
5400 tb_size = 0;
5401 break;
5402 case QEMU_OPTION_icount:
5403 use_icount = 1;
5404 if (strcmp(optarg, "auto") == 0) {
5405 icount_time_shift = -1;
5406 } else {
5407 icount_time_shift = strtol(optarg, NULL, 0);
5409 break;
5410 case QEMU_OPTION_incoming:
5411 incoming = optarg;
5412 break;
5417 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5418 if (kvm_allowed && kqemu_allowed) {
5419 fprintf(stderr,
5420 "You can not enable both KVM and kqemu at the same time\n");
5421 exit(1);
5423 #endif
5425 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5426 if (smp_cpus > machine->max_cpus) {
5427 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5428 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5429 machine->max_cpus);
5430 exit(1);
5433 if (nographic) {
5434 if (serial_device_index == 0)
5435 serial_devices[0] = "stdio";
5436 if (parallel_device_index == 0)
5437 parallel_devices[0] = "null";
5438 if (strncmp(monitor_device, "vc", 2) == 0)
5439 monitor_device = "stdio";
5442 #ifndef _WIN32
5443 if (daemonize) {
5444 pid_t pid;
5446 if (pipe(fds) == -1)
5447 exit(1);
5449 pid = fork();
5450 if (pid > 0) {
5451 uint8_t status;
5452 ssize_t len;
5454 close(fds[1]);
5456 again:
5457 len = read(fds[0], &status, 1);
5458 if (len == -1 && (errno == EINTR))
5459 goto again;
5461 if (len != 1)
5462 exit(1);
5463 else if (status == 1) {
5464 fprintf(stderr, "Could not acquire pidfile\n");
5465 exit(1);
5466 } else
5467 exit(0);
5468 } else if (pid < 0)
5469 exit(1);
5471 setsid();
5473 pid = fork();
5474 if (pid > 0)
5475 exit(0);
5476 else if (pid < 0)
5477 exit(1);
5479 umask(027);
5481 signal(SIGTSTP, SIG_IGN);
5482 signal(SIGTTOU, SIG_IGN);
5483 signal(SIGTTIN, SIG_IGN);
5485 #endif
5487 #if USE_KVM
5488 if (kvm_enabled()) {
5489 if (kvm_qemu_init() < 0) {
5490 extern int kvm_allowed;
5491 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5492 #ifdef NO_CPU_EMULATION
5493 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5494 exit(1);
5495 #endif
5496 kvm_allowed = 0;
5499 #endif
5501 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5502 if (daemonize) {
5503 uint8_t status = 1;
5504 write(fds[1], &status, 1);
5505 } else
5506 fprintf(stderr, "Could not acquire pid file\n");
5507 exit(1);
5510 #ifdef USE_KQEMU
5511 if (smp_cpus > 1)
5512 kqemu_allowed = 0;
5513 #endif
5514 linux_boot = (kernel_filename != NULL);
5515 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5517 if (!linux_boot && net_boot == 0 &&
5518 !machine->nodisk_ok && nb_drives_opt == 0)
5519 help(1);
5521 if (!linux_boot && *kernel_cmdline != '\0') {
5522 fprintf(stderr, "-append only allowed with -kernel option\n");
5523 exit(1);
5526 if (!linux_boot && initrd_filename != NULL) {
5527 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5528 exit(1);
5531 /* boot to floppy or the default cd if no hard disk defined yet */
5532 if (!boot_devices[0]) {
5533 boot_devices = "cad";
5535 setvbuf(stdout, NULL, _IOLBF, 0);
5537 init_timers();
5538 if (init_timer_alarm() < 0) {
5539 fprintf(stderr, "could not initialize alarm timer\n");
5540 exit(1);
5542 if (use_icount && icount_time_shift < 0) {
5543 use_icount = 2;
5544 /* 125MIPS seems a reasonable initial guess at the guest speed.
5545 It will be corrected fairly quickly anyway. */
5546 icount_time_shift = 3;
5547 init_icount_adjust();
5550 #ifdef _WIN32
5551 socket_init();
5552 #endif
5554 /* init network clients */
5555 if (nb_net_clients == 0) {
5556 /* if no clients, we use a default config */
5557 net_clients[nb_net_clients++] = "nic";
5558 #ifdef CONFIG_SLIRP
5559 net_clients[nb_net_clients++] = "user";
5560 #endif
5563 for(i = 0;i < nb_net_clients; i++) {
5564 if (net_client_parse(net_clients[i]) < 0)
5565 exit(1);
5567 net_client_check();
5569 #ifdef TARGET_I386
5570 /* XXX: this should be moved in the PC machine instantiation code */
5571 if (net_boot != 0) {
5572 int netroms = 0;
5573 for (i = 0; i < nb_nics && i < 4; i++) {
5574 const char *model = nd_table[i].model;
5575 char buf[1024];
5576 if (net_boot & (1 << i)) {
5577 if (model == NULL)
5578 model = "rtl8139";
5579 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5580 if (get_image_size(buf) > 0) {
5581 if (nb_option_roms >= MAX_OPTION_ROMS) {
5582 fprintf(stderr, "Too many option ROMs\n");
5583 exit(1);
5585 option_rom[nb_option_roms] = strdup(buf);
5586 nb_option_roms++;
5587 netroms++;
5591 if (netroms == 0) {
5592 fprintf(stderr, "No valid PXE rom found for network device\n");
5593 exit(1);
5596 #endif
5598 /* init the bluetooth world */
5599 for (i = 0; i < nb_bt_opts; i++)
5600 if (bt_parse(bt_opts[i]))
5601 exit(1);
5603 /* init the memory */
5604 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5606 if (machine->ram_require & RAMSIZE_FIXED) {
5607 if (ram_size > 0) {
5608 if (ram_size < phys_ram_size) {
5609 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5610 machine->name, (unsigned long long) phys_ram_size);
5611 exit(-1);
5614 phys_ram_size = ram_size;
5615 } else
5616 ram_size = phys_ram_size;
5617 } else {
5618 if (ram_size == 0)
5619 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5621 phys_ram_size += ram_size;
5624 /* Initialize kvm */
5625 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5626 #define KVM_EXTRA_PAGES 3
5627 #else
5628 #define KVM_EXTRA_PAGES 0
5629 #endif
5630 if (kvm_enabled()) {
5631 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5632 if (kvm_qemu_create_context() < 0) {
5633 fprintf(stderr, "Could not create KVM context\n");
5634 exit(1);
5638 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5639 if (!phys_ram_base) {
5640 fprintf(stderr, "Could not allocate physical memory\n");
5641 exit(1);
5644 /* init the dynamic translator */
5645 cpu_exec_init_all(tb_size * 1024 * 1024);
5647 bdrv_init();
5649 /* we always create the cdrom drive, even if no disk is there */
5651 if (nb_drives_opt < MAX_DRIVES)
5652 drive_add(NULL, CDROM_ALIAS);
5654 /* we always create at least one floppy */
5656 if (nb_drives_opt < MAX_DRIVES)
5657 drive_add(NULL, FD_ALIAS, 0);
5659 /* we always create one sd slot, even if no card is in it */
5661 if (nb_drives_opt < MAX_DRIVES)
5662 drive_add(NULL, SD_ALIAS);
5664 /* open the virtual block devices
5665 * note that migration with device
5666 * hot add/remove is broken.
5668 for(i = 0; i < nb_drives_opt; i++)
5669 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5670 exit(1);
5672 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5673 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5675 /* terminal init */
5676 memset(&display_state, 0, sizeof(display_state));
5677 if (nographic) {
5678 if (curses) {
5679 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5680 exit(1);
5682 /* nearly nothing to do */
5683 dumb_display_init(ds);
5684 } else if (vnc_display != NULL) {
5685 vnc_display_init(ds);
5686 if (vnc_display_open(ds, vnc_display) < 0)
5687 exit(1);
5688 } else
5689 #if defined(CONFIG_CURSES)
5690 if (curses) {
5691 curses_display_init(ds, full_screen);
5692 } else
5693 #endif
5695 #if defined(CONFIG_SDL)
5696 sdl_display_init(ds, full_screen, no_frame);
5697 #elif defined(CONFIG_COCOA)
5698 cocoa_display_init(ds, full_screen);
5699 #else
5700 dumb_display_init(ds);
5701 #endif
5704 #ifndef _WIN32
5705 /* must be after terminal init, SDL library changes signal handlers */
5706 termsig_setup();
5707 #endif
5709 /* Maintain compatibility with multiple stdio monitors */
5710 if (!strcmp(monitor_device,"stdio")) {
5711 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5712 const char *devname = serial_devices[i];
5713 if (devname && !strcmp(devname,"mon:stdio")) {
5714 monitor_device = NULL;
5715 break;
5716 } else if (devname && !strcmp(devname,"stdio")) {
5717 monitor_device = NULL;
5718 serial_devices[i] = "mon:stdio";
5719 break;
5723 if (monitor_device) {
5724 monitor_hd = qemu_chr_open("monitor", monitor_device);
5725 if (!monitor_hd) {
5726 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5727 exit(1);
5729 monitor_init(monitor_hd, !nographic);
5732 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5733 const char *devname = serial_devices[i];
5734 if (devname && strcmp(devname, "none")) {
5735 char label[32];
5736 snprintf(label, sizeof(label), "serial%d", i);
5737 serial_hds[i] = qemu_chr_open(label, devname);
5738 if (!serial_hds[i]) {
5739 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5740 devname);
5741 exit(1);
5743 if (strstart(devname, "vc", 0))
5744 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5748 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5749 const char *devname = parallel_devices[i];
5750 if (devname && strcmp(devname, "none")) {
5751 char label[32];
5752 snprintf(label, sizeof(label), "parallel%d", i);
5753 parallel_hds[i] = qemu_chr_open(label, devname);
5754 if (!parallel_hds[i]) {
5755 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5756 devname);
5757 exit(1);
5759 if (strstart(devname, "vc", 0))
5760 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5764 if (kvm_enabled())
5765 kvm_init_ap();
5767 #ifdef KVM_UPSTREAM
5768 if (kvm_enabled()) {
5769 int ret;
5771 ret = kvm_init(smp_cpus);
5772 if (ret < 0) {
5773 fprintf(stderr, "failed to initialize KVM\n");
5774 exit(1);
5777 #endif
5779 machine->init(ram_size, vga_ram_size, boot_devices, ds,
5780 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5782 current_machine = machine;
5784 /* init USB devices */
5785 if (usb_enabled) {
5786 for(i = 0; i < usb_devices_index; i++) {
5787 if (usb_device_add(usb_devices[i]) < 0) {
5788 fprintf(stderr, "Warning: could not add USB device %s\n",
5789 usb_devices[i]);
5794 if (display_state.dpy_refresh) {
5795 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5796 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5799 #ifdef CONFIG_GDBSTUB
5800 if (use_gdbstub) {
5801 /* XXX: use standard host:port notation and modify options
5802 accordingly. */
5803 if (gdbserver_start(gdbstub_port) < 0) {
5804 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5805 gdbstub_port);
5806 exit(1);
5809 #endif
5811 if (loadvm)
5812 do_loadvm(loadvm);
5814 if (incoming) {
5815 autostart = 0; /* fixme how to deal with -daemonize */
5816 qemu_start_incoming_migration(incoming);
5820 /* XXX: simplify init */
5821 read_passwords();
5822 if (autostart) {
5823 vm_start();
5827 if (daemonize) {
5828 uint8_t status = 0;
5829 ssize_t len;
5830 int fd;
5832 again1:
5833 len = write(fds[1], &status, 1);
5834 if (len == -1 && (errno == EINTR))
5835 goto again1;
5837 if (len != 1)
5838 exit(1);
5840 chdir("/");
5841 TFR(fd = open("/dev/null", O_RDWR));
5842 if (fd == -1)
5843 exit(1);
5845 dup2(fd, 0);
5846 dup2(fd, 1);
5847 dup2(fd, 2);
5849 close(fd);
5852 main_loop();
5853 quit_timers();
5854 net_cleanup();
5856 return 0;