kvm: libkvm: don't install anything
[qemu-kvm/fedora.git] / vl.c
blobd0660aba16cdd2df518d76d14454b8f5ee696103
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 "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "hw/device-assignment.h"
43 #include "migration.h"
44 #include "kvm.h"
45 #include "balloon.h"
46 #include "qemu-kvm.h"
48 #include <unistd.h>
49 #include <fcntl.h>
50 #include <signal.h>
51 #include <time.h>
52 #include <errno.h>
53 #include <sys/time.h>
54 #include <zlib.h>
56 #ifndef _WIN32
57 #include <sys/times.h>
58 #include <sys/wait.h>
59 #include <termios.h>
60 #include <sys/mman.h>
61 #include <sys/ioctl.h>
62 #include <sys/resource.h>
63 #include <sys/socket.h>
64 #include <netinet/in.h>
65 #include <net/if.h>
66 #if defined(__NetBSD__)
67 #include <net/if_tap.h>
68 #endif
69 #ifdef __linux__
70 #include <linux/if_tun.h>
71 #endif
72 #include <arpa/inet.h>
73 #include <dirent.h>
74 #include <netdb.h>
75 #include <sys/select.h>
76 #ifdef _BSD
77 #include <sys/stat.h>
78 #ifdef __FreeBSD__
79 #include <libutil.h>
80 #else
81 #include <util.h>
82 #endif
83 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
84 #include <freebsd/stdlib.h>
85 #else
86 #ifdef __linux__
87 #include <pty.h>
88 #include <malloc.h>
89 #include <linux/rtc.h>
91 /* For the benefit of older linux systems which don't supply it,
92 we use a local copy of hpet.h. */
93 /* #include <linux/hpet.h> */
94 #include "hpet.h"
96 #include <linux/ppdev.h>
97 #include <linux/parport.h>
98 #endif
99 #ifdef __sun__
100 #include <sys/stat.h>
101 #include <sys/ethernet.h>
102 #include <sys/sockio.h>
103 #include <netinet/arp.h>
104 #include <netinet/in.h>
105 #include <netinet/in_systm.h>
106 #include <netinet/ip.h>
107 #include <netinet/ip_icmp.h> // must come after ip.h
108 #include <netinet/udp.h>
109 #include <netinet/tcp.h>
110 #include <net/if.h>
111 #include <syslog.h>
112 #include <stropts.h>
113 #endif
114 #endif
115 #endif
117 #include "qemu_socket.h"
119 #if defined(CONFIG_SLIRP)
120 #include "libslirp.h"
121 #endif
123 #if defined(__OpenBSD__)
124 #include <util.h>
125 #endif
127 #if defined(CONFIG_VDE)
128 #include <libvdeplug.h>
129 #endif
131 #ifdef _WIN32
132 #include <malloc.h>
133 #include <sys/timeb.h>
134 #include <mmsystem.h>
135 #define getopt_long_only getopt_long
136 #define memalign(align, size) malloc(size)
137 #endif
139 #ifdef CONFIG_SDL
140 #ifdef __APPLE__
141 #include <SDL/SDL.h>
142 #endif
143 #endif /* CONFIG_SDL */
145 #ifdef CONFIG_COCOA
146 #undef main
147 #define main qemu_main
148 #endif /* CONFIG_COCOA */
150 #include "disas.h"
152 #include "exec-all.h"
154 #include "qemu-kvm.h"
156 //#define DEBUG_UNUSED_IOPORT
157 //#define DEBUG_IOPORT
158 //#define DEBUG_NET
159 //#define DEBUG_SLIRP
161 #ifdef TARGET_PPC
162 #define DEFAULT_RAM_SIZE 144
163 #else
164 #define DEFAULT_RAM_SIZE 128
165 #endif
167 /* Max number of USB devices that can be specified on the commandline. */
168 #define MAX_USB_CMDLINE 8
170 /* Max number of bluetooth switches on the commandline. */
171 #define MAX_BT_CMDLINE 10
173 /* XXX: use a two level table to limit memory usage */
174 #define MAX_IOPORTS 65536
176 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
177 const char *bios_name = NULL;
178 static void *ioport_opaque[MAX_IOPORTS];
179 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
180 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
181 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
182 to store the VM snapshots */
183 DriveInfo drives_table[MAX_DRIVES+1];
184 int nb_drives;
185 int extboot_drive = -1;
186 static int vga_ram_size;
187 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
188 DisplayState display_state;
189 int nographic;
190 static int curses;
191 const char* keyboard_layout = NULL;
192 int64_t ticks_per_sec;
193 ram_addr_t ram_size;
194 int nb_nics;
195 NICInfo nd_table[MAX_NICS];
196 int vm_running;
197 static int rtc_utc = 1;
198 static int rtc_date_offset = -1; /* -1 means no change */
199 int cirrus_vga_enabled = 1;
200 int vmsvga_enabled = 0;
201 #ifdef TARGET_SPARC
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
205 #else
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
209 #endif
210 static int full_screen = 0;
211 #ifdef CONFIG_SDL
212 static int no_frame = 0;
213 #endif
214 int no_quit = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 #ifdef TARGET_I386
218 int win2k_install_hack = 0;
219 #endif
220 int usb_enabled = 0;
221 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
222 int assigned_devices_index;
223 int smp_cpus = 1;
224 const char *vnc_display;
225 int acpi_enabled = 1;
226 int no_hpet = 0;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 int daemonize = 0;
233 const char *incoming;
234 const char *option_rom[MAX_OPTION_ROMS];
235 int nb_option_roms;
236 int semihosting_enabled = 0;
237 int time_drift_fix = 0;
238 unsigned int kvm_shadow_memory = 0;
239 const char *mem_path = NULL;
240 int hpagesize = 0;
241 const char *cpu_vendor_string;
242 #ifdef TARGET_ARM
243 int old_param = 0;
244 #endif
245 const char *qemu_name;
246 int alt_grab = 0;
247 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
248 unsigned int nb_prom_envs = 0;
249 const char *prom_envs[MAX_PROM_ENVS];
250 #endif
251 int nb_drives_opt;
252 struct drive_opt drives_opt[MAX_DRIVES];
254 static CPUState *cur_cpu;
255 static CPUState *next_cpu;
256 static int event_pending = 1;
257 /* Conversion factor from emulated instructions to virtual clock ticks. */
258 static int icount_time_shift;
259 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
260 #define MAX_ICOUNT_SHIFT 10
261 /* Compensate for varying guest execution speed. */
262 static int64_t qemu_icount_bias;
263 static QEMUTimer *icount_rt_timer;
264 static QEMUTimer *icount_vm_timer;
266 uint8_t qemu_uuid[16];
268 /* KVM runs the main loop in a separate thread. If we update one of the lists
269 * that are polled before or after select(), we need to make sure to break out
270 * of the select() to ensure the new item is serviced.
272 static void main_loop_break(void)
274 if (kvm_enabled())
275 qemu_kvm_notify_work();
278 /***********************************************************/
279 /* x86 ISA bus support */
281 target_phys_addr_t isa_mem_base = 0;
282 PicState2 *isa_pic;
284 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
285 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
287 static uint32_t ioport_read(int index, uint32_t address)
289 static IOPortReadFunc *default_func[3] = {
290 default_ioport_readb,
291 default_ioport_readw,
292 default_ioport_readl
294 IOPortReadFunc *func = ioport_read_table[index][address];
295 if (!func)
296 func = default_func[index];
297 return func(ioport_opaque[address], address);
300 static void ioport_write(int index, uint32_t address, uint32_t data)
302 static IOPortWriteFunc *default_func[3] = {
303 default_ioport_writeb,
304 default_ioport_writew,
305 default_ioport_writel
307 IOPortWriteFunc *func = ioport_write_table[index][address];
308 if (!func)
309 func = default_func[index];
310 func(ioport_opaque[address], address, data);
313 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
315 #ifdef DEBUG_UNUSED_IOPORT
316 fprintf(stderr, "unused inb: port=0x%04x\n", address);
317 #endif
318 return 0xff;
321 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
323 #ifdef DEBUG_UNUSED_IOPORT
324 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
325 #endif
328 /* default is to make two byte accesses */
329 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
331 uint32_t data;
332 data = ioport_read(0, address);
333 address = (address + 1) & (MAX_IOPORTS - 1);
334 data |= ioport_read(0, address) << 8;
335 return data;
338 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
340 ioport_write(0, address, data & 0xff);
341 address = (address + 1) & (MAX_IOPORTS - 1);
342 ioport_write(0, address, (data >> 8) & 0xff);
345 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
347 #ifdef DEBUG_UNUSED_IOPORT
348 fprintf(stderr, "unused inl: port=0x%04x\n", address);
349 #endif
350 return 0xffffffff;
353 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
355 #ifdef DEBUG_UNUSED_IOPORT
356 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
357 #endif
360 /* size is the word size in byte */
361 int register_ioport_read(int start, int length, int size,
362 IOPortReadFunc *func, void *opaque)
364 int i, bsize;
366 if (size == 1) {
367 bsize = 0;
368 } else if (size == 2) {
369 bsize = 1;
370 } else if (size == 4) {
371 bsize = 2;
372 } else {
373 hw_error("register_ioport_read: invalid size");
374 return -1;
376 for(i = start; i < start + length; i += size) {
377 ioport_read_table[bsize][i] = func;
378 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
379 hw_error("register_ioport_read: invalid opaque");
380 ioport_opaque[i] = opaque;
382 return 0;
385 /* size is the word size in byte */
386 int register_ioport_write(int start, int length, int size,
387 IOPortWriteFunc *func, void *opaque)
389 int i, bsize;
391 if (size == 1) {
392 bsize = 0;
393 } else if (size == 2) {
394 bsize = 1;
395 } else if (size == 4) {
396 bsize = 2;
397 } else {
398 hw_error("register_ioport_write: invalid size");
399 return -1;
401 for(i = start; i < start + length; i += size) {
402 ioport_write_table[bsize][i] = func;
403 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
404 hw_error("register_ioport_write: invalid opaque");
405 ioport_opaque[i] = opaque;
407 return 0;
410 void isa_unassign_ioport(int start, int length)
412 int i;
414 for(i = start; i < start + length; i++) {
415 ioport_read_table[0][i] = default_ioport_readb;
416 ioport_read_table[1][i] = default_ioport_readw;
417 ioport_read_table[2][i] = default_ioport_readl;
419 ioport_write_table[0][i] = default_ioport_writeb;
420 ioport_write_table[1][i] = default_ioport_writew;
421 ioport_write_table[2][i] = default_ioport_writel;
423 ioport_opaque[i] = NULL;
427 /***********************************************************/
429 void cpu_outb(CPUState *env, int addr, int val)
431 #ifdef DEBUG_IOPORT
432 if (loglevel & CPU_LOG_IOPORT)
433 fprintf(logfile, "outb: %04x %02x\n", addr, val);
434 #endif
435 ioport_write(0, addr, val);
436 #ifdef USE_KQEMU
437 if (env)
438 env->last_io_time = cpu_get_time_fast();
439 #endif
442 void cpu_outw(CPUState *env, int addr, int val)
444 #ifdef DEBUG_IOPORT
445 if (loglevel & CPU_LOG_IOPORT)
446 fprintf(logfile, "outw: %04x %04x\n", addr, val);
447 #endif
448 ioport_write(1, addr, val);
449 #ifdef USE_KQEMU
450 if (env)
451 env->last_io_time = cpu_get_time_fast();
452 #endif
455 void cpu_outl(CPUState *env, int addr, int val)
457 #ifdef DEBUG_IOPORT
458 if (loglevel & CPU_LOG_IOPORT)
459 fprintf(logfile, "outl: %04x %08x\n", addr, val);
460 #endif
461 ioport_write(2, addr, val);
462 #ifdef USE_KQEMU
463 if (env)
464 env->last_io_time = cpu_get_time_fast();
465 #endif
468 int cpu_inb(CPUState *env, int addr)
470 int val;
471 val = ioport_read(0, addr);
472 #ifdef DEBUG_IOPORT
473 if (loglevel & CPU_LOG_IOPORT)
474 fprintf(logfile, "inb : %04x %02x\n", addr, val);
475 #endif
476 #ifdef USE_KQEMU
477 if (env)
478 env->last_io_time = cpu_get_time_fast();
479 #endif
480 return val;
483 int cpu_inw(CPUState *env, int addr)
485 int val;
486 val = ioport_read(1, addr);
487 #ifdef DEBUG_IOPORT
488 if (loglevel & CPU_LOG_IOPORT)
489 fprintf(logfile, "inw : %04x %04x\n", addr, val);
490 #endif
491 #ifdef USE_KQEMU
492 if (env)
493 env->last_io_time = cpu_get_time_fast();
494 #endif
495 return val;
498 int cpu_inl(CPUState *env, int addr)
500 int val;
501 val = ioport_read(2, addr);
502 #ifdef DEBUG_IOPORT
503 if (loglevel & CPU_LOG_IOPORT)
504 fprintf(logfile, "inl : %04x %08x\n", addr, val);
505 #endif
506 #ifdef USE_KQEMU
507 if (env)
508 env->last_io_time = cpu_get_time_fast();
509 #endif
510 return val;
513 /***********************************************************/
514 void hw_error(const char *fmt, ...)
516 va_list ap;
517 CPUState *env;
519 va_start(ap, fmt);
520 fprintf(stderr, "qemu: hardware error: ");
521 vfprintf(stderr, fmt, ap);
522 fprintf(stderr, "\n");
523 for(env = first_cpu; env != NULL; env = env->next_cpu) {
524 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
525 #ifdef TARGET_I386
526 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
527 #else
528 cpu_dump_state(env, stderr, fprintf, 0);
529 #endif
531 va_end(ap);
532 abort();
535 /***************/
536 /* ballooning */
538 static QEMUBalloonEvent *qemu_balloon_event;
539 void *qemu_balloon_event_opaque;
541 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
543 qemu_balloon_event = func;
544 qemu_balloon_event_opaque = opaque;
547 void qemu_balloon(ram_addr_t target)
549 if (qemu_balloon_event)
550 qemu_balloon_event(qemu_balloon_event_opaque, target);
553 ram_addr_t qemu_balloon_status(void)
555 if (qemu_balloon_event)
556 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
557 return 0;
560 /***********************************************************/
561 /* keyboard/mouse */
563 static QEMUPutKBDEvent *qemu_put_kbd_event;
564 static void *qemu_put_kbd_event_opaque;
565 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
566 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
568 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
570 qemu_put_kbd_event_opaque = opaque;
571 qemu_put_kbd_event = func;
574 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
575 void *opaque, int absolute,
576 const char *name)
578 QEMUPutMouseEntry *s, *cursor;
580 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
581 if (!s)
582 return NULL;
584 s->qemu_put_mouse_event = func;
585 s->qemu_put_mouse_event_opaque = opaque;
586 s->qemu_put_mouse_event_absolute = absolute;
587 s->qemu_put_mouse_event_name = qemu_strdup(name);
588 s->next = NULL;
590 if (!qemu_put_mouse_event_head) {
591 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
592 return s;
595 cursor = qemu_put_mouse_event_head;
596 while (cursor->next != NULL)
597 cursor = cursor->next;
599 cursor->next = s;
600 qemu_put_mouse_event_current = s;
602 return s;
605 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
607 QEMUPutMouseEntry *prev = NULL, *cursor;
609 if (!qemu_put_mouse_event_head || entry == NULL)
610 return;
612 cursor = qemu_put_mouse_event_head;
613 while (cursor != NULL && cursor != entry) {
614 prev = cursor;
615 cursor = cursor->next;
618 if (cursor == NULL) // does not exist or list empty
619 return;
620 else if (prev == NULL) { // entry is head
621 qemu_put_mouse_event_head = cursor->next;
622 if (qemu_put_mouse_event_current == entry)
623 qemu_put_mouse_event_current = cursor->next;
624 qemu_free(entry->qemu_put_mouse_event_name);
625 qemu_free(entry);
626 return;
629 prev->next = entry->next;
631 if (qemu_put_mouse_event_current == entry)
632 qemu_put_mouse_event_current = prev;
634 qemu_free(entry->qemu_put_mouse_event_name);
635 qemu_free(entry);
638 void kbd_put_keycode(int keycode)
640 if (qemu_put_kbd_event) {
641 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
645 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
647 QEMUPutMouseEvent *mouse_event;
648 void *mouse_event_opaque;
649 int width;
651 if (!qemu_put_mouse_event_current) {
652 return;
655 mouse_event =
656 qemu_put_mouse_event_current->qemu_put_mouse_event;
657 mouse_event_opaque =
658 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
660 if (mouse_event) {
661 if (graphic_rotate) {
662 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
663 width = 0x7fff;
664 else
665 width = graphic_width - 1;
666 mouse_event(mouse_event_opaque,
667 width - dy, dx, dz, buttons_state);
668 } else
669 mouse_event(mouse_event_opaque,
670 dx, dy, dz, buttons_state);
674 int kbd_mouse_is_absolute(void)
676 if (!qemu_put_mouse_event_current)
677 return 0;
679 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
682 void do_info_mice(void)
684 QEMUPutMouseEntry *cursor;
685 int index = 0;
687 if (!qemu_put_mouse_event_head) {
688 term_printf("No mouse devices connected\n");
689 return;
692 term_printf("Mouse devices available:\n");
693 cursor = qemu_put_mouse_event_head;
694 while (cursor != NULL) {
695 term_printf("%c Mouse #%d: %s\n",
696 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
697 index, cursor->qemu_put_mouse_event_name);
698 index++;
699 cursor = cursor->next;
703 void do_mouse_set(int index)
705 QEMUPutMouseEntry *cursor;
706 int i = 0;
708 if (!qemu_put_mouse_event_head) {
709 term_printf("No mouse devices connected\n");
710 return;
713 cursor = qemu_put_mouse_event_head;
714 while (cursor != NULL && index != i) {
715 i++;
716 cursor = cursor->next;
719 if (cursor != NULL)
720 qemu_put_mouse_event_current = cursor;
721 else
722 term_printf("Mouse at given index not found\n");
725 /* compute with 96 bit intermediate result: (a*b)/c */
726 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
728 union {
729 uint64_t ll;
730 struct {
731 #ifdef WORDS_BIGENDIAN
732 uint32_t high, low;
733 #else
734 uint32_t low, high;
735 #endif
736 } l;
737 } u, res;
738 uint64_t rl, rh;
740 u.ll = a;
741 rl = (uint64_t)u.l.low * (uint64_t)b;
742 rh = (uint64_t)u.l.high * (uint64_t)b;
743 rh += (rl >> 32);
744 res.l.high = rh / c;
745 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
746 return res.ll;
749 /***********************************************************/
750 /* real time host monotonic timer */
752 #define QEMU_TIMER_BASE 1000000000LL
754 #ifdef WIN32
756 static int64_t clock_freq;
758 static void init_get_clock(void)
760 LARGE_INTEGER freq;
761 int ret;
762 ret = QueryPerformanceFrequency(&freq);
763 if (ret == 0) {
764 fprintf(stderr, "Could not calibrate ticks\n");
765 exit(1);
767 clock_freq = freq.QuadPart;
770 static int64_t get_clock(void)
772 LARGE_INTEGER ti;
773 QueryPerformanceCounter(&ti);
774 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
777 #else
779 static int use_rt_clock;
781 static void init_get_clock(void)
783 use_rt_clock = 0;
784 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
786 struct timespec ts;
787 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
788 use_rt_clock = 1;
791 #endif
794 static int64_t get_clock(void)
796 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
797 if (use_rt_clock) {
798 struct timespec ts;
799 clock_gettime(CLOCK_MONOTONIC, &ts);
800 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
801 } else
802 #endif
804 /* XXX: using gettimeofday leads to problems if the date
805 changes, so it should be avoided. */
806 struct timeval tv;
807 gettimeofday(&tv, NULL);
808 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
811 #endif
813 /* Return the virtual CPU time, based on the instruction counter. */
814 static int64_t cpu_get_icount(void)
816 int64_t icount;
817 CPUState *env = cpu_single_env;;
818 icount = qemu_icount;
819 if (env) {
820 if (!can_do_io(env))
821 fprintf(stderr, "Bad clock read\n");
822 icount -= (env->icount_decr.u16.low + env->icount_extra);
824 return qemu_icount_bias + (icount << icount_time_shift);
827 /***********************************************************/
828 /* guest cycle counter */
830 static int64_t cpu_ticks_prev;
831 static int64_t cpu_ticks_offset;
832 static int64_t cpu_clock_offset;
833 static int cpu_ticks_enabled;
835 /* return the host CPU cycle counter and handle stop/restart */
836 int64_t cpu_get_ticks(void)
838 if (use_icount) {
839 return cpu_get_icount();
841 if (!cpu_ticks_enabled) {
842 return cpu_ticks_offset;
843 } else {
844 int64_t ticks;
845 ticks = cpu_get_real_ticks();
846 if (cpu_ticks_prev > ticks) {
847 /* Note: non increasing ticks may happen if the host uses
848 software suspend */
849 cpu_ticks_offset += cpu_ticks_prev - ticks;
851 cpu_ticks_prev = ticks;
852 return ticks + cpu_ticks_offset;
856 /* return the host CPU monotonic timer and handle stop/restart */
857 static int64_t cpu_get_clock(void)
859 int64_t ti;
860 if (!cpu_ticks_enabled) {
861 return cpu_clock_offset;
862 } else {
863 ti = get_clock();
864 return ti + cpu_clock_offset;
868 /* enable cpu_get_ticks() */
869 void cpu_enable_ticks(void)
871 if (!cpu_ticks_enabled) {
872 cpu_ticks_offset -= cpu_get_real_ticks();
873 cpu_clock_offset -= get_clock();
874 cpu_ticks_enabled = 1;
878 /* disable cpu_get_ticks() : the clock is stopped. You must not call
879 cpu_get_ticks() after that. */
880 void cpu_disable_ticks(void)
882 if (cpu_ticks_enabled) {
883 cpu_ticks_offset = cpu_get_ticks();
884 cpu_clock_offset = cpu_get_clock();
885 cpu_ticks_enabled = 0;
889 /***********************************************************/
890 /* timers */
892 #define QEMU_TIMER_REALTIME 0
893 #define QEMU_TIMER_VIRTUAL 1
895 struct QEMUClock {
896 int type;
897 /* XXX: add frequency */
900 struct QEMUTimer {
901 QEMUClock *clock;
902 int64_t expire_time;
903 QEMUTimerCB *cb;
904 void *opaque;
905 struct QEMUTimer *next;
908 struct qemu_alarm_timer {
909 char const *name;
910 unsigned int flags;
912 int (*start)(struct qemu_alarm_timer *t);
913 void (*stop)(struct qemu_alarm_timer *t);
914 void (*rearm)(struct qemu_alarm_timer *t);
915 void *priv;
918 #define ALARM_FLAG_DYNTICKS 0x1
919 #define ALARM_FLAG_EXPIRED 0x2
921 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
923 return t->flags & ALARM_FLAG_DYNTICKS;
926 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
928 if (!alarm_has_dynticks(t))
929 return;
931 t->rearm(t);
934 /* TODO: MIN_TIMER_REARM_US should be optimized */
935 #define MIN_TIMER_REARM_US 250
937 static struct qemu_alarm_timer *alarm_timer;
938 #ifndef _WIN32
939 static int alarm_timer_rfd, alarm_timer_wfd;
940 #endif
942 #ifdef _WIN32
944 struct qemu_alarm_win32 {
945 MMRESULT timerId;
946 HANDLE host_alarm;
947 unsigned int period;
948 } alarm_win32_data = {0, NULL, -1};
950 static int win32_start_timer(struct qemu_alarm_timer *t);
951 static void win32_stop_timer(struct qemu_alarm_timer *t);
952 static void win32_rearm_timer(struct qemu_alarm_timer *t);
954 #else
956 static int unix_start_timer(struct qemu_alarm_timer *t);
957 static void unix_stop_timer(struct qemu_alarm_timer *t);
959 #ifdef __linux__
961 static int dynticks_start_timer(struct qemu_alarm_timer *t);
962 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
963 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
965 static int hpet_start_timer(struct qemu_alarm_timer *t);
966 static void hpet_stop_timer(struct qemu_alarm_timer *t);
968 static int rtc_start_timer(struct qemu_alarm_timer *t);
969 static void rtc_stop_timer(struct qemu_alarm_timer *t);
971 #endif /* __linux__ */
973 #endif /* _WIN32 */
975 /* Correlation between real and virtual time is always going to be
976 fairly approximate, so ignore small variation.
977 When the guest is idle real and virtual time will be aligned in
978 the IO wait loop. */
979 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
981 static void icount_adjust(void)
983 int64_t cur_time;
984 int64_t cur_icount;
985 int64_t delta;
986 static int64_t last_delta;
987 /* If the VM is not running, then do nothing. */
988 if (!vm_running)
989 return;
991 cur_time = cpu_get_clock();
992 cur_icount = qemu_get_clock(vm_clock);
993 delta = cur_icount - cur_time;
994 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
995 if (delta > 0
996 && last_delta + ICOUNT_WOBBLE < delta * 2
997 && icount_time_shift > 0) {
998 /* The guest is getting too far ahead. Slow time down. */
999 icount_time_shift--;
1001 if (delta < 0
1002 && last_delta - ICOUNT_WOBBLE > delta * 2
1003 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1004 /* The guest is getting too far behind. Speed time up. */
1005 icount_time_shift++;
1007 last_delta = delta;
1008 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1011 static void icount_adjust_rt(void * opaque)
1013 qemu_mod_timer(icount_rt_timer,
1014 qemu_get_clock(rt_clock) + 1000);
1015 icount_adjust();
1018 static void icount_adjust_vm(void * opaque)
1020 qemu_mod_timer(icount_vm_timer,
1021 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1022 icount_adjust();
1025 static void init_icount_adjust(void)
1027 /* Have both realtime and virtual time triggers for speed adjustment.
1028 The realtime trigger catches emulated time passing too slowly,
1029 the virtual time trigger catches emulated time passing too fast.
1030 Realtime triggers occur even when idle, so use them less frequently
1031 than VM triggers. */
1032 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1033 qemu_mod_timer(icount_rt_timer,
1034 qemu_get_clock(rt_clock) + 1000);
1035 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1036 qemu_mod_timer(icount_vm_timer,
1037 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1040 static struct qemu_alarm_timer alarm_timers[] = {
1041 #ifndef _WIN32
1042 #ifdef __linux__
1043 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1044 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1045 /* HPET - if available - is preferred */
1046 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1047 /* ...otherwise try RTC */
1048 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1049 #endif
1050 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1051 #else
1052 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1053 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1054 {"win32", 0, win32_start_timer,
1055 win32_stop_timer, NULL, &alarm_win32_data},
1056 #endif
1057 {NULL, }
1060 static void show_available_alarms(void)
1062 int i;
1064 printf("Available alarm timers, in order of precedence:\n");
1065 for (i = 0; alarm_timers[i].name; i++)
1066 printf("%s\n", alarm_timers[i].name);
1069 static void configure_alarms(char const *opt)
1071 int i;
1072 int cur = 0;
1073 int count = ARRAY_SIZE(alarm_timers) - 1;
1074 char *arg;
1075 char *name;
1076 struct qemu_alarm_timer tmp;
1078 if (!strcmp(opt, "?")) {
1079 show_available_alarms();
1080 exit(0);
1083 arg = strdup(opt);
1085 /* Reorder the array */
1086 name = strtok(arg, ",");
1087 while (name) {
1088 for (i = 0; i < count && alarm_timers[i].name; i++) {
1089 if (!strcmp(alarm_timers[i].name, name))
1090 break;
1093 if (i == count) {
1094 fprintf(stderr, "Unknown clock %s\n", name);
1095 goto next;
1098 if (i < cur)
1099 /* Ignore */
1100 goto next;
1102 /* Swap */
1103 tmp = alarm_timers[i];
1104 alarm_timers[i] = alarm_timers[cur];
1105 alarm_timers[cur] = tmp;
1107 cur++;
1108 next:
1109 name = strtok(NULL, ",");
1112 free(arg);
1114 if (cur) {
1115 /* Disable remaining timers */
1116 for (i = cur; i < count; i++)
1117 alarm_timers[i].name = NULL;
1118 } else {
1119 show_available_alarms();
1120 exit(1);
1124 QEMUClock *rt_clock;
1125 QEMUClock *vm_clock;
1127 static QEMUTimer *active_timers[2];
1129 static QEMUClock *qemu_new_clock(int type)
1131 QEMUClock *clock;
1132 clock = qemu_mallocz(sizeof(QEMUClock));
1133 if (!clock)
1134 return NULL;
1135 clock->type = type;
1136 return clock;
1139 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1141 QEMUTimer *ts;
1143 ts = qemu_mallocz(sizeof(QEMUTimer));
1144 ts->clock = clock;
1145 ts->cb = cb;
1146 ts->opaque = opaque;
1147 return ts;
1150 void qemu_free_timer(QEMUTimer *ts)
1152 qemu_free(ts);
1155 /* stop a timer, but do not dealloc it */
1156 void qemu_del_timer(QEMUTimer *ts)
1158 QEMUTimer **pt, *t;
1160 /* NOTE: this code must be signal safe because
1161 qemu_timer_expired() can be called from a signal. */
1162 pt = &active_timers[ts->clock->type];
1163 for(;;) {
1164 t = *pt;
1165 if (!t)
1166 break;
1167 if (t == ts) {
1168 *pt = t->next;
1169 break;
1171 pt = &t->next;
1175 /* modify the current timer so that it will be fired when current_time
1176 >= expire_time. The corresponding callback will be called. */
1177 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1179 QEMUTimer **pt, *t;
1181 qemu_del_timer(ts);
1183 /* add the timer in the sorted list */
1184 /* NOTE: this code must be signal safe because
1185 qemu_timer_expired() can be called from a signal. */
1186 pt = &active_timers[ts->clock->type];
1187 for(;;) {
1188 t = *pt;
1189 if (!t)
1190 break;
1191 if (t->expire_time > expire_time)
1192 break;
1193 pt = &t->next;
1195 ts->expire_time = expire_time;
1196 ts->next = *pt;
1197 *pt = ts;
1199 /* Rearm if necessary */
1200 if (pt == &active_timers[ts->clock->type]) {
1201 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1202 qemu_rearm_alarm_timer(alarm_timer);
1204 /* Interrupt execution to force deadline recalculation. */
1205 if (use_icount && cpu_single_env) {
1206 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1211 int qemu_timer_pending(QEMUTimer *ts)
1213 QEMUTimer *t;
1214 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1215 if (t == ts)
1216 return 1;
1218 return 0;
1221 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1223 if (!timer_head)
1224 return 0;
1225 return (timer_head->expire_time <= current_time);
1228 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1230 QEMUTimer *ts;
1232 for(;;) {
1233 ts = *ptimer_head;
1234 if (!ts || ts->expire_time > current_time)
1235 break;
1236 /* remove timer from the list before calling the callback */
1237 *ptimer_head = ts->next;
1238 ts->next = NULL;
1240 /* run the callback (the timer list can be modified) */
1241 ts->cb(ts->opaque);
1245 int64_t qemu_get_clock(QEMUClock *clock)
1247 switch(clock->type) {
1248 case QEMU_TIMER_REALTIME:
1249 return get_clock() / 1000000;
1250 default:
1251 case QEMU_TIMER_VIRTUAL:
1252 if (use_icount) {
1253 return cpu_get_icount();
1254 } else {
1255 return cpu_get_clock();
1260 static void init_timers(void)
1262 init_get_clock();
1263 ticks_per_sec = QEMU_TIMER_BASE;
1264 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1265 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1268 /* save a timer */
1269 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1271 uint64_t expire_time;
1273 if (qemu_timer_pending(ts)) {
1274 expire_time = ts->expire_time;
1275 } else {
1276 expire_time = -1;
1278 qemu_put_be64(f, expire_time);
1281 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1283 uint64_t expire_time;
1285 expire_time = qemu_get_be64(f);
1286 if (expire_time != -1) {
1287 qemu_mod_timer(ts, expire_time);
1288 } else {
1289 qemu_del_timer(ts);
1293 static void timer_save(QEMUFile *f, void *opaque)
1295 if (cpu_ticks_enabled) {
1296 hw_error("cannot save state if virtual timers are running");
1298 qemu_put_be64(f, cpu_ticks_offset);
1299 qemu_put_be64(f, ticks_per_sec);
1300 qemu_put_be64(f, cpu_clock_offset);
1303 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1305 if (version_id != 1 && version_id != 2)
1306 return -EINVAL;
1307 if (cpu_ticks_enabled) {
1308 return -EINVAL;
1310 cpu_ticks_offset=qemu_get_be64(f);
1311 ticks_per_sec=qemu_get_be64(f);
1312 if (version_id == 2) {
1313 cpu_clock_offset=qemu_get_be64(f);
1315 return 0;
1318 #ifdef _WIN32
1319 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1320 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1321 #else
1322 static void host_alarm_handler(int host_signum)
1323 #endif
1325 #if 0
1326 #define DISP_FREQ 1000
1328 static int64_t delta_min = INT64_MAX;
1329 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1330 static int count;
1331 ti = qemu_get_clock(vm_clock);
1332 if (last_clock != 0) {
1333 delta = ti - last_clock;
1334 if (delta < delta_min)
1335 delta_min = delta;
1336 if (delta > delta_max)
1337 delta_max = delta;
1338 delta_cum += delta;
1339 if (++count == DISP_FREQ) {
1340 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1341 muldiv64(delta_min, 1000000, ticks_per_sec),
1342 muldiv64(delta_max, 1000000, ticks_per_sec),
1343 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1344 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1345 count = 0;
1346 delta_min = INT64_MAX;
1347 delta_max = 0;
1348 delta_cum = 0;
1351 last_clock = ti;
1353 #endif
1354 if (1 ||
1355 alarm_has_dynticks(alarm_timer) ||
1356 (!use_icount &&
1357 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1358 qemu_get_clock(vm_clock))) ||
1359 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1360 qemu_get_clock(rt_clock))) {
1361 CPUState *env = next_cpu;
1363 #ifdef _WIN32
1364 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1365 SetEvent(data->host_alarm);
1366 #else
1367 static const char byte = 0;
1368 write(alarm_timer_wfd, &byte, sizeof(byte));
1369 #endif
1370 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1372 if (env) {
1373 /* stop the currently executing cpu because a timer occured */
1374 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1375 #ifdef USE_KQEMU
1376 if (env->kqemu_enabled) {
1377 kqemu_cpu_interrupt(env);
1379 #endif
1381 event_pending = 1;
1385 static int64_t qemu_next_deadline(void)
1387 int64_t delta;
1389 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1390 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1391 qemu_get_clock(vm_clock);
1392 } else {
1393 /* To avoid problems with overflow limit this to 2^32. */
1394 delta = INT32_MAX;
1397 if (delta < 0)
1398 delta = 0;
1400 return delta;
1403 #if defined(__linux__) || defined(_WIN32)
1404 static uint64_t qemu_next_deadline_dyntick(void)
1406 int64_t delta;
1407 int64_t rtdelta;
1409 if (use_icount)
1410 delta = INT32_MAX;
1411 else
1412 delta = (qemu_next_deadline() + 999) / 1000;
1414 if (active_timers[QEMU_TIMER_REALTIME]) {
1415 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1416 qemu_get_clock(rt_clock))*1000;
1417 if (rtdelta < delta)
1418 delta = rtdelta;
1421 if (delta < MIN_TIMER_REARM_US)
1422 delta = MIN_TIMER_REARM_US;
1424 return delta;
1426 #endif
1428 #ifndef _WIN32
1430 /* Sets a specific flag */
1431 static int fcntl_setfl(int fd, int flag)
1433 int flags;
1435 flags = fcntl(fd, F_GETFL);
1436 if (flags == -1)
1437 return -errno;
1439 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1440 return -errno;
1442 return 0;
1445 #if defined(__linux__)
1447 #define RTC_FREQ 1024
1449 static void enable_sigio_timer(int fd)
1451 struct sigaction act;
1453 /* timer signal */
1454 sigfillset(&act.sa_mask);
1455 act.sa_flags = 0;
1456 act.sa_handler = host_alarm_handler;
1458 sigaction(SIGIO, &act, NULL);
1459 fcntl_setfl(fd, O_ASYNC);
1460 fcntl(fd, F_SETOWN, getpid());
1463 static int hpet_start_timer(struct qemu_alarm_timer *t)
1465 struct hpet_info info;
1466 int r, fd;
1468 fd = open("/dev/hpet", O_RDONLY);
1469 if (fd < 0)
1470 return -1;
1472 /* Set frequency */
1473 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1474 if (r < 0) {
1475 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1476 "error, but for better emulation accuracy type:\n"
1477 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1478 goto fail;
1481 /* Check capabilities */
1482 r = ioctl(fd, HPET_INFO, &info);
1483 if (r < 0)
1484 goto fail;
1486 /* Enable periodic mode */
1487 r = ioctl(fd, HPET_EPI, 0);
1488 if (info.hi_flags && (r < 0))
1489 goto fail;
1491 /* Enable interrupt */
1492 r = ioctl(fd, HPET_IE_ON, 0);
1493 if (r < 0)
1494 goto fail;
1496 enable_sigio_timer(fd);
1497 t->priv = (void *)(long)fd;
1499 return 0;
1500 fail:
1501 close(fd);
1502 return -1;
1505 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1507 int fd = (long)t->priv;
1509 close(fd);
1512 static int rtc_start_timer(struct qemu_alarm_timer *t)
1514 int rtc_fd;
1515 unsigned long current_rtc_freq = 0;
1517 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1518 if (rtc_fd < 0)
1519 return -1;
1520 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1521 if (current_rtc_freq != RTC_FREQ &&
1522 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1523 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1524 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1525 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1526 goto fail;
1528 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1529 fail:
1530 close(rtc_fd);
1531 return -1;
1534 enable_sigio_timer(rtc_fd);
1536 t->priv = (void *)(long)rtc_fd;
1538 return 0;
1541 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1543 int rtc_fd = (long)t->priv;
1545 close(rtc_fd);
1548 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1550 struct sigevent ev;
1551 timer_t host_timer;
1552 struct sigaction act;
1554 sigfillset(&act.sa_mask);
1555 act.sa_flags = 0;
1556 act.sa_handler = host_alarm_handler;
1558 sigaction(SIGALRM, &act, NULL);
1560 ev.sigev_value.sival_int = 0;
1561 ev.sigev_notify = SIGEV_SIGNAL;
1562 ev.sigev_signo = SIGALRM;
1564 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1565 perror("timer_create");
1567 /* disable dynticks */
1568 fprintf(stderr, "Dynamic Ticks disabled\n");
1570 return -1;
1573 t->priv = (void *)(long)host_timer;
1575 return 0;
1578 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1580 timer_t host_timer = (timer_t)(long)t->priv;
1582 timer_delete(host_timer);
1585 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1587 timer_t host_timer = (timer_t)(long)t->priv;
1588 struct itimerspec timeout;
1589 int64_t nearest_delta_us = INT64_MAX;
1590 int64_t current_us;
1592 if (!active_timers[QEMU_TIMER_REALTIME] &&
1593 !active_timers[QEMU_TIMER_VIRTUAL])
1594 return;
1596 nearest_delta_us = qemu_next_deadline_dyntick();
1598 /* check whether a timer is already running */
1599 if (timer_gettime(host_timer, &timeout)) {
1600 perror("gettime");
1601 fprintf(stderr, "Internal timer error: aborting\n");
1602 exit(1);
1604 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1605 if (current_us && current_us <= nearest_delta_us)
1606 return;
1608 timeout.it_interval.tv_sec = 0;
1609 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1610 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1611 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1612 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1613 perror("settime");
1614 fprintf(stderr, "Internal timer error: aborting\n");
1615 exit(1);
1619 #endif /* defined(__linux__) */
1621 static int unix_start_timer(struct qemu_alarm_timer *t)
1623 struct sigaction act;
1624 struct itimerval itv;
1625 int err;
1627 /* timer signal */
1628 sigfillset(&act.sa_mask);
1629 act.sa_flags = 0;
1630 act.sa_handler = host_alarm_handler;
1632 sigaction(SIGALRM, &act, NULL);
1634 itv.it_interval.tv_sec = 0;
1635 /* for i386 kernel 2.6 to get 1 ms */
1636 itv.it_interval.tv_usec = 999;
1637 itv.it_value.tv_sec = 0;
1638 itv.it_value.tv_usec = 10 * 1000;
1640 err = setitimer(ITIMER_REAL, &itv, NULL);
1641 if (err)
1642 return -1;
1644 return 0;
1647 static void unix_stop_timer(struct qemu_alarm_timer *t)
1649 struct itimerval itv;
1651 memset(&itv, 0, sizeof(itv));
1652 setitimer(ITIMER_REAL, &itv, NULL);
1655 #endif /* !defined(_WIN32) */
1657 static void try_to_rearm_timer(void *opaque)
1659 struct qemu_alarm_timer *t = opaque;
1660 #ifndef _WIN32
1661 ssize_t len;
1663 /* Drain the notify pipe */
1664 do {
1665 char buffer[512];
1666 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1667 } while ((len == -1 && errno == EINTR) || len > 0);
1668 #endif
1670 if (t->flags & ALARM_FLAG_EXPIRED) {
1671 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1672 qemu_rearm_alarm_timer(alarm_timer);
1676 #ifdef _WIN32
1678 static int win32_start_timer(struct qemu_alarm_timer *t)
1680 TIMECAPS tc;
1681 struct qemu_alarm_win32 *data = t->priv;
1682 UINT flags;
1684 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1685 if (!data->host_alarm) {
1686 perror("Failed CreateEvent");
1687 return -1;
1690 memset(&tc, 0, sizeof(tc));
1691 timeGetDevCaps(&tc, sizeof(tc));
1693 if (data->period < tc.wPeriodMin)
1694 data->period = tc.wPeriodMin;
1696 timeBeginPeriod(data->period);
1698 flags = TIME_CALLBACK_FUNCTION;
1699 if (alarm_has_dynticks(t))
1700 flags |= TIME_ONESHOT;
1701 else
1702 flags |= TIME_PERIODIC;
1704 data->timerId = timeSetEvent(1, // interval (ms)
1705 data->period, // resolution
1706 host_alarm_handler, // function
1707 (DWORD)t, // parameter
1708 flags);
1710 if (!data->timerId) {
1711 perror("Failed to initialize win32 alarm timer");
1713 timeEndPeriod(data->period);
1714 CloseHandle(data->host_alarm);
1715 return -1;
1718 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1720 return 0;
1723 static void win32_stop_timer(struct qemu_alarm_timer *t)
1725 struct qemu_alarm_win32 *data = t->priv;
1727 timeKillEvent(data->timerId);
1728 timeEndPeriod(data->period);
1730 CloseHandle(data->host_alarm);
1733 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1735 struct qemu_alarm_win32 *data = t->priv;
1736 uint64_t nearest_delta_us;
1738 if (!active_timers[QEMU_TIMER_REALTIME] &&
1739 !active_timers[QEMU_TIMER_VIRTUAL])
1740 return;
1742 nearest_delta_us = qemu_next_deadline_dyntick();
1743 nearest_delta_us /= 1000;
1745 timeKillEvent(data->timerId);
1747 data->timerId = timeSetEvent(1,
1748 data->period,
1749 host_alarm_handler,
1750 (DWORD)t,
1751 TIME_ONESHOT | TIME_PERIODIC);
1753 if (!data->timerId) {
1754 perror("Failed to re-arm win32 alarm timer");
1756 timeEndPeriod(data->period);
1757 CloseHandle(data->host_alarm);
1758 exit(1);
1762 #endif /* _WIN32 */
1764 static int init_timer_alarm(void)
1766 struct qemu_alarm_timer *t = NULL;
1767 int i, err = -1;
1769 #ifndef _WIN32
1770 int fds[2];
1772 err = pipe(fds);
1773 if (err == -1)
1774 return -errno;
1776 err = fcntl_setfl(fds[0], O_NONBLOCK);
1777 if (err < 0)
1778 goto fail;
1780 err = fcntl_setfl(fds[1], O_NONBLOCK);
1781 if (err < 0)
1782 goto fail;
1784 alarm_timer_rfd = fds[0];
1785 alarm_timer_wfd = fds[1];
1786 #endif
1788 for (i = 0; alarm_timers[i].name; i++) {
1789 t = &alarm_timers[i];
1791 err = t->start(t);
1792 if (!err)
1793 break;
1796 if (err) {
1797 err = -ENOENT;
1798 goto fail;
1801 #ifndef _WIN32
1802 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1803 try_to_rearm_timer, NULL, t);
1804 #endif
1806 alarm_timer = t;
1808 return 0;
1810 fail:
1811 #ifndef _WIN32
1812 close(fds[0]);
1813 close(fds[1]);
1814 #endif
1815 return err;
1818 static void quit_timers(void)
1820 alarm_timer->stop(alarm_timer);
1821 alarm_timer = NULL;
1824 /***********************************************************/
1825 /* host time/date access */
1826 void qemu_get_timedate(struct tm *tm, int offset)
1828 time_t ti;
1829 struct tm *ret;
1831 time(&ti);
1832 ti += offset;
1833 if (rtc_date_offset == -1) {
1834 if (rtc_utc)
1835 ret = gmtime(&ti);
1836 else
1837 ret = localtime(&ti);
1838 } else {
1839 ti -= rtc_date_offset;
1840 ret = gmtime(&ti);
1843 memcpy(tm, ret, sizeof(struct tm));
1846 int qemu_timedate_diff(struct tm *tm)
1848 time_t seconds;
1850 if (rtc_date_offset == -1)
1851 if (rtc_utc)
1852 seconds = mktimegm(tm);
1853 else
1854 seconds = mktime(tm);
1855 else
1856 seconds = mktimegm(tm) + rtc_date_offset;
1858 return seconds - time(NULL);
1861 #ifdef _WIN32
1862 static void socket_cleanup(void)
1864 WSACleanup();
1867 static int socket_init(void)
1869 WSADATA Data;
1870 int ret, err;
1872 ret = WSAStartup(MAKEWORD(2,2), &Data);
1873 if (ret != 0) {
1874 err = WSAGetLastError();
1875 fprintf(stderr, "WSAStartup: %d\n", err);
1876 return -1;
1878 atexit(socket_cleanup);
1879 return 0;
1881 #endif
1883 const char *get_opt_name(char *buf, int buf_size, const char *p)
1885 char *q;
1887 q = buf;
1888 while (*p != '\0' && *p != '=') {
1889 if (q && (q - buf) < buf_size - 1)
1890 *q++ = *p;
1891 p++;
1893 if (q)
1894 *q = '\0';
1896 return p;
1899 const char *get_opt_value(char *buf, int buf_size, const char *p)
1901 char *q;
1903 q = buf;
1904 while (*p != '\0') {
1905 if (*p == ',') {
1906 if (*(p + 1) != ',')
1907 break;
1908 p++;
1910 if (q && (q - buf) < buf_size - 1)
1911 *q++ = *p;
1912 p++;
1914 if (q)
1915 *q = '\0';
1917 return p;
1920 int get_param_value(char *buf, int buf_size,
1921 const char *tag, const char *str)
1923 const char *p;
1924 char option[128];
1926 p = str;
1927 for(;;) {
1928 p = get_opt_name(option, sizeof(option), p);
1929 if (*p != '=')
1930 break;
1931 p++;
1932 if (!strcmp(tag, option)) {
1933 (void)get_opt_value(buf, buf_size, p);
1934 return strlen(buf);
1935 } else {
1936 p = get_opt_value(NULL, 0, p);
1938 if (*p != ',')
1939 break;
1940 p++;
1942 return 0;
1945 int check_params(char *buf, int buf_size,
1946 const char * const *params, const char *str)
1948 const char *p;
1949 int i;
1951 p = str;
1952 for(;;) {
1953 p = get_opt_name(buf, buf_size, p);
1954 if (*p != '=')
1955 return -1;
1956 p++;
1957 for(i = 0; params[i] != NULL; i++)
1958 if (!strcmp(params[i], buf))
1959 break;
1960 if (params[i] == NULL)
1961 return -1;
1962 p = get_opt_value(NULL, 0, p);
1963 if (*p != ',')
1964 break;
1965 p++;
1967 return 0;
1970 /***********************************************************/
1971 /* Bluetooth support */
1972 static int nb_hcis;
1973 static int cur_hci;
1974 static struct HCIInfo *hci_table[MAX_NICS];
1976 static struct bt_vlan_s {
1977 struct bt_scatternet_s net;
1978 int id;
1979 struct bt_vlan_s *next;
1980 } *first_bt_vlan;
1982 /* find or alloc a new bluetooth "VLAN" */
1983 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1985 struct bt_vlan_s **pvlan, *vlan;
1986 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1987 if (vlan->id == id)
1988 return &vlan->net;
1990 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1991 vlan->id = id;
1992 pvlan = &first_bt_vlan;
1993 while (*pvlan != NULL)
1994 pvlan = &(*pvlan)->next;
1995 *pvlan = vlan;
1996 return &vlan->net;
1999 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2003 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2005 return -ENOTSUP;
2008 static struct HCIInfo null_hci = {
2009 .cmd_send = null_hci_send,
2010 .sco_send = null_hci_send,
2011 .acl_send = null_hci_send,
2012 .bdaddr_set = null_hci_addr_set,
2015 struct HCIInfo *qemu_next_hci(void)
2017 if (cur_hci == nb_hcis)
2018 return &null_hci;
2020 return hci_table[cur_hci++];
2023 static struct HCIInfo *hci_init(const char *str)
2025 char *endp;
2026 struct bt_scatternet_s *vlan = 0;
2028 if (!strcmp(str, "null"))
2029 /* null */
2030 return &null_hci;
2031 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2032 /* host[:hciN] */
2033 return bt_host_hci(str[4] ? str + 5 : "hci0");
2034 else if (!strncmp(str, "hci", 3)) {
2035 /* hci[,vlan=n] */
2036 if (str[3]) {
2037 if (!strncmp(str + 3, ",vlan=", 6)) {
2038 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2039 if (*endp)
2040 vlan = 0;
2042 } else
2043 vlan = qemu_find_bt_vlan(0);
2044 if (vlan)
2045 return bt_new_hci(vlan);
2048 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2050 return 0;
2053 static int bt_hci_parse(const char *str)
2055 struct HCIInfo *hci;
2056 bdaddr_t bdaddr;
2058 if (nb_hcis >= MAX_NICS) {
2059 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2060 return -1;
2063 hci = hci_init(str);
2064 if (!hci)
2065 return -1;
2067 bdaddr.b[0] = 0x52;
2068 bdaddr.b[1] = 0x54;
2069 bdaddr.b[2] = 0x00;
2070 bdaddr.b[3] = 0x12;
2071 bdaddr.b[4] = 0x34;
2072 bdaddr.b[5] = 0x56 + nb_hcis;
2073 hci->bdaddr_set(hci, bdaddr.b);
2075 hci_table[nb_hcis++] = hci;
2077 return 0;
2080 static void bt_vhci_add(int vlan_id)
2082 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2084 if (!vlan->slave)
2085 fprintf(stderr, "qemu: warning: adding a VHCI to "
2086 "an empty scatternet %i\n", vlan_id);
2088 bt_vhci_init(bt_new_hci(vlan));
2091 static struct bt_device_s *bt_device_add(const char *opt)
2093 struct bt_scatternet_s *vlan;
2094 int vlan_id = 0;
2095 char *endp = strstr(opt, ",vlan=");
2096 int len = (endp ? endp - opt : strlen(opt)) + 1;
2097 char devname[10];
2099 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2101 if (endp) {
2102 vlan_id = strtol(endp + 6, &endp, 0);
2103 if (*endp) {
2104 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2105 return 0;
2109 vlan = qemu_find_bt_vlan(vlan_id);
2111 if (!vlan->slave)
2112 fprintf(stderr, "qemu: warning: adding a slave device to "
2113 "an empty scatternet %i\n", vlan_id);
2115 if (!strcmp(devname, "keyboard"))
2116 return bt_keyboard_init(vlan);
2118 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2119 return 0;
2122 static int bt_parse(const char *opt)
2124 const char *endp, *p;
2125 int vlan;
2127 if (strstart(opt, "hci", &endp)) {
2128 if (!*endp || *endp == ',') {
2129 if (*endp)
2130 if (!strstart(endp, ",vlan=", 0))
2131 opt = endp + 1;
2133 return bt_hci_parse(opt);
2135 } else if (strstart(opt, "vhci", &endp)) {
2136 if (!*endp || *endp == ',') {
2137 if (*endp) {
2138 if (strstart(endp, ",vlan=", &p)) {
2139 vlan = strtol(p, (char **) &endp, 0);
2140 if (*endp) {
2141 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2142 return 1;
2144 } else {
2145 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2146 return 1;
2148 } else
2149 vlan = 0;
2151 bt_vhci_add(vlan);
2152 return 0;
2154 } else if (strstart(opt, "device:", &endp))
2155 return !bt_device_add(endp);
2157 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2158 return 1;
2161 /***********************************************************/
2162 /* QEMU Block devices */
2164 #define HD_ALIAS "index=%d,media=disk"
2165 #ifdef TARGET_PPC
2166 #define CDROM_ALIAS "index=1,media=cdrom"
2167 #else
2168 #define CDROM_ALIAS "index=2,media=cdrom"
2169 #endif
2170 #define FD_ALIAS "index=%d,if=floppy"
2171 #define PFLASH_ALIAS "if=pflash"
2172 #define MTD_ALIAS "if=mtd"
2173 #define SD_ALIAS "index=0,if=sd"
2175 static int drive_opt_get_free_idx(void)
2177 int index;
2179 for (index = 0; index < MAX_DRIVES; index++)
2180 if (!drives_opt[index].used) {
2181 drives_opt[index].used = 1;
2182 return index;
2185 return -1;
2188 static int drive_get_free_idx(void)
2190 int index;
2192 for (index = 0; index < MAX_DRIVES; index++)
2193 if (!drives_table[index].used) {
2194 drives_table[index].used = 1;
2195 return index;
2198 return -1;
2201 int drive_add(const char *file, const char *fmt, ...)
2203 va_list ap;
2204 int index = drive_opt_get_free_idx();
2206 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2207 fprintf(stderr, "qemu: too many drives\n");
2208 return -1;
2211 drives_opt[index].file = file;
2212 va_start(ap, fmt);
2213 vsnprintf(drives_opt[index].opt,
2214 sizeof(drives_opt[0].opt), fmt, ap);
2215 va_end(ap);
2217 nb_drives_opt++;
2218 return index;
2221 void drive_remove(int index)
2223 drives_opt[index].used = 0;
2224 nb_drives_opt--;
2227 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2229 int index;
2231 /* seek interface, bus and unit */
2233 for (index = 0; index < MAX_DRIVES; index++)
2234 if (drives_table[index].type == type &&
2235 drives_table[index].bus == bus &&
2236 drives_table[index].unit == unit &&
2237 drives_table[index].used)
2238 return index;
2240 return -1;
2243 int drive_get_max_bus(BlockInterfaceType type)
2245 int max_bus;
2246 int index;
2248 max_bus = -1;
2249 for (index = 0; index < nb_drives; index++) {
2250 if(drives_table[index].type == type &&
2251 drives_table[index].bus > max_bus)
2252 max_bus = drives_table[index].bus;
2254 return max_bus;
2257 const char *drive_get_serial(BlockDriverState *bdrv)
2259 int index;
2261 for (index = 0; index < nb_drives; index++)
2262 if (drives_table[index].bdrv == bdrv)
2263 return drives_table[index].serial;
2265 return "\0";
2268 static void bdrv_format_print(void *opaque, const char *name)
2270 fprintf(stderr, " %s", name);
2273 void drive_uninit(BlockDriverState *bdrv)
2275 int i;
2277 for (i = 0; i < MAX_DRIVES; i++)
2278 if (drives_table[i].bdrv == bdrv) {
2279 drives_table[i].bdrv = NULL;
2280 drives_table[i].used = 0;
2281 drive_remove(drives_table[i].drive_opt_idx);
2282 nb_drives--;
2283 break;
2287 int drive_init(struct drive_opt *arg, int snapshot,
2288 QEMUMachine *machine)
2290 char buf[128];
2291 char file[1024];
2292 char devname[128];
2293 char serial[21];
2294 const char *mediastr = "";
2295 BlockInterfaceType type;
2296 enum { MEDIA_DISK, MEDIA_CDROM } media;
2297 int bus_id, unit_id;
2298 int cyls, heads, secs, translation;
2299 BlockDriverState *bdrv;
2300 BlockDriver *drv = NULL;
2301 int max_devs;
2302 int index;
2303 int cache;
2304 int bdrv_flags;
2305 int drives_table_idx;
2306 char *str = arg->opt;
2307 static const char * const params[] = { "bus", "unit", "if", "index",
2308 "cyls", "heads", "secs", "trans",
2309 "media", "snapshot", "file",
2310 "cache", "format", "serial",
2311 "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 = 3;
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 if (!get_param_value(serial, sizeof(serial), "serial", str))
2512 memset(serial, 0, sizeof(serial));
2514 /* compute bus and unit according index */
2516 if (index != -1) {
2517 if (bus_id != 0 || unit_id != -1) {
2518 fprintf(stderr,
2519 "qemu: '%s' index cannot be used with bus and unit\n", str);
2520 return -1;
2522 if (max_devs == 0)
2524 unit_id = index;
2525 bus_id = 0;
2526 } else {
2527 unit_id = index % max_devs;
2528 bus_id = index / max_devs;
2532 /* if user doesn't specify a unit_id,
2533 * try to find the first free
2536 if (unit_id == -1) {
2537 unit_id = 0;
2538 while (drive_get_index(type, bus_id, unit_id) != -1) {
2539 unit_id++;
2540 if (max_devs && unit_id >= max_devs) {
2541 unit_id -= max_devs;
2542 bus_id++;
2547 /* check unit id */
2549 if (max_devs && unit_id >= max_devs) {
2550 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2551 str, unit_id, max_devs - 1);
2552 return -1;
2556 * ignore multiple definitions
2559 if (drive_get_index(type, bus_id, unit_id) != -1)
2560 return -2;
2562 /* init */
2564 if (type == IF_IDE || type == IF_SCSI)
2565 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2566 if (max_devs)
2567 snprintf(buf, sizeof(buf), "%s%i%s%i",
2568 devname, bus_id, mediastr, unit_id);
2569 else
2570 snprintf(buf, sizeof(buf), "%s%s%i",
2571 devname, mediastr, unit_id);
2572 bdrv = bdrv_new(buf);
2573 drives_table_idx = drive_get_free_idx();
2574 drives_table[drives_table_idx].bdrv = bdrv;
2575 drives_table[drives_table_idx].type = type;
2576 drives_table[drives_table_idx].bus = bus_id;
2577 drives_table[drives_table_idx].unit = unit_id;
2578 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2579 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2580 nb_drives++;
2582 switch(type) {
2583 case IF_IDE:
2584 case IF_SCSI:
2585 switch(media) {
2586 case MEDIA_DISK:
2587 if (cyls != 0) {
2588 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2589 bdrv_set_translation_hint(bdrv, translation);
2591 break;
2592 case MEDIA_CDROM:
2593 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2594 break;
2596 break;
2597 case IF_SD:
2598 /* FIXME: This isn't really a floppy, but it's a reasonable
2599 approximation. */
2600 case IF_FLOPPY:
2601 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2602 break;
2603 case IF_PFLASH:
2604 case IF_MTD:
2605 case IF_VIRTIO:
2606 break;
2608 if (!file[0])
2609 return -2;
2610 bdrv_flags = 0;
2611 if (snapshot) {
2612 bdrv_flags |= BDRV_O_SNAPSHOT;
2613 cache = 2; /* always use write-back with snapshot */
2615 if (cache == 0) /* no caching */
2616 bdrv_flags |= BDRV_O_NOCACHE;
2617 else if (cache == 2) /* write-back */
2618 bdrv_flags |= BDRV_O_CACHE_WB;
2619 else if (cache == 3) /* not specified */
2620 bdrv_flags |= BDRV_O_CACHE_DEF;
2621 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2622 fprintf(stderr, "qemu: could not open disk image %s\n",
2623 file);
2624 return -1;
2626 return drives_table_idx;
2629 /***********************************************************/
2630 /* USB devices */
2632 static USBPort *used_usb_ports;
2633 static USBPort *free_usb_ports;
2635 /* ??? Maybe change this to register a hub to keep track of the topology. */
2636 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2637 usb_attachfn attach)
2639 port->opaque = opaque;
2640 port->index = index;
2641 port->attach = attach;
2642 port->next = free_usb_ports;
2643 free_usb_ports = port;
2646 int usb_device_add_dev(USBDevice *dev)
2648 USBPort *port;
2650 /* Find a USB port to add the device to. */
2651 port = free_usb_ports;
2652 if (!port->next) {
2653 USBDevice *hub;
2655 /* Create a new hub and chain it on. */
2656 free_usb_ports = NULL;
2657 port->next = used_usb_ports;
2658 used_usb_ports = port;
2660 hub = usb_hub_init(VM_USB_HUB_SIZE);
2661 usb_attach(port, hub);
2662 port = free_usb_ports;
2665 free_usb_ports = port->next;
2666 port->next = used_usb_ports;
2667 used_usb_ports = port;
2668 usb_attach(port, dev);
2669 return 0;
2672 static int usb_device_add(const char *devname)
2674 const char *p;
2675 USBDevice *dev;
2677 if (!free_usb_ports)
2678 return -1;
2680 if (strstart(devname, "host:", &p)) {
2681 dev = usb_host_device_open(p);
2682 } else if (!strcmp(devname, "mouse")) {
2683 dev = usb_mouse_init();
2684 } else if (!strcmp(devname, "tablet")) {
2685 dev = usb_tablet_init();
2686 } else if (!strcmp(devname, "keyboard")) {
2687 dev = usb_keyboard_init();
2688 } else if (strstart(devname, "disk:", &p)) {
2689 dev = usb_msd_init(p);
2690 } else if (!strcmp(devname, "wacom-tablet")) {
2691 dev = usb_wacom_init();
2692 } else if (strstart(devname, "serial:", &p)) {
2693 dev = usb_serial_init(p);
2694 #ifdef CONFIG_BRLAPI
2695 } else if (!strcmp(devname, "braille")) {
2696 dev = usb_baum_init();
2697 #endif
2698 } else if (strstart(devname, "net:", &p)) {
2699 int nic = nb_nics;
2701 if (net_client_init("nic", p) < 0)
2702 return -1;
2703 nd_table[nic].model = "usb";
2704 dev = usb_net_init(&nd_table[nic]);
2705 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2706 dev = usb_bt_init(devname[2] ? hci_init(p) :
2707 bt_new_hci(qemu_find_bt_vlan(0)));
2708 } else {
2709 return -1;
2711 if (!dev)
2712 return -1;
2714 return usb_device_add_dev(dev);
2717 int usb_device_del_addr(int bus_num, int addr)
2719 USBPort *port;
2720 USBPort **lastp;
2721 USBDevice *dev;
2723 if (!used_usb_ports)
2724 return -1;
2726 if (bus_num != 0)
2727 return -1;
2729 lastp = &used_usb_ports;
2730 port = used_usb_ports;
2731 while (port && port->dev->addr != addr) {
2732 lastp = &port->next;
2733 port = port->next;
2736 if (!port)
2737 return -1;
2739 dev = port->dev;
2740 *lastp = port->next;
2741 usb_attach(port, NULL);
2742 dev->handle_destroy(dev);
2743 port->next = free_usb_ports;
2744 free_usb_ports = port;
2745 return 0;
2748 static int usb_device_del(const char *devname)
2750 int bus_num, addr;
2751 const char *p;
2753 if (strstart(devname, "host:", &p))
2754 return usb_host_device_close(p);
2756 if (!used_usb_ports)
2757 return -1;
2759 p = strchr(devname, '.');
2760 if (!p)
2761 return -1;
2762 bus_num = strtoul(devname, NULL, 0);
2763 addr = strtoul(p + 1, NULL, 0);
2765 return usb_device_del_addr(bus_num, addr);
2768 void do_usb_add(const char *devname)
2770 usb_device_add(devname);
2773 void do_usb_del(const char *devname)
2775 usb_device_del(devname);
2778 void usb_info(void)
2780 USBDevice *dev;
2781 USBPort *port;
2782 const char *speed_str;
2784 if (!usb_enabled) {
2785 term_printf("USB support not enabled\n");
2786 return;
2789 for (port = used_usb_ports; port; port = port->next) {
2790 dev = port->dev;
2791 if (!dev)
2792 continue;
2793 switch(dev->speed) {
2794 case USB_SPEED_LOW:
2795 speed_str = "1.5";
2796 break;
2797 case USB_SPEED_FULL:
2798 speed_str = "12";
2799 break;
2800 case USB_SPEED_HIGH:
2801 speed_str = "480";
2802 break;
2803 default:
2804 speed_str = "?";
2805 break;
2807 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2808 0, dev->addr, speed_str, dev->devname);
2812 /***********************************************************/
2813 /* PCMCIA/Cardbus */
2815 static struct pcmcia_socket_entry_s {
2816 struct pcmcia_socket_s *socket;
2817 struct pcmcia_socket_entry_s *next;
2818 } *pcmcia_sockets = 0;
2820 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2822 struct pcmcia_socket_entry_s *entry;
2824 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2825 entry->socket = socket;
2826 entry->next = pcmcia_sockets;
2827 pcmcia_sockets = entry;
2830 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2832 struct pcmcia_socket_entry_s *entry, **ptr;
2834 ptr = &pcmcia_sockets;
2835 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2836 if (entry->socket == socket) {
2837 *ptr = entry->next;
2838 qemu_free(entry);
2842 void pcmcia_info(void)
2844 struct pcmcia_socket_entry_s *iter;
2845 if (!pcmcia_sockets)
2846 term_printf("No PCMCIA sockets\n");
2848 for (iter = pcmcia_sockets; iter; iter = iter->next)
2849 term_printf("%s: %s\n", iter->socket->slot_string,
2850 iter->socket->attached ? iter->socket->card_string :
2851 "Empty");
2854 /***********************************************************/
2855 /* dumb display */
2857 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2861 static void dumb_resize(DisplayState *ds, int w, int h)
2865 static void dumb_display_init(DisplayState *ds)
2867 ds->data = NULL;
2868 ds->linesize = 0;
2869 ds->depth = 0;
2870 ds->dpy_update = dumb_update;
2871 ds->dpy_resize = dumb_resize;
2872 ds->dpy_refresh = NULL;
2873 ds->gui_timer_interval = 0;
2874 ds->idle = 1;
2877 /***********************************************************/
2878 /* I/O handling */
2880 #define MAX_IO_HANDLERS 64
2882 typedef struct IOHandlerRecord {
2883 int fd;
2884 IOCanRWHandler *fd_read_poll;
2885 IOHandler *fd_read;
2886 IOHandler *fd_write;
2887 int deleted;
2888 void *opaque;
2889 /* temporary data */
2890 struct pollfd *ufd;
2891 struct IOHandlerRecord *next;
2892 } IOHandlerRecord;
2894 static IOHandlerRecord *first_io_handler;
2896 /* XXX: fd_read_poll should be suppressed, but an API change is
2897 necessary in the character devices to suppress fd_can_read(). */
2898 int qemu_set_fd_handler2(int fd,
2899 IOCanRWHandler *fd_read_poll,
2900 IOHandler *fd_read,
2901 IOHandler *fd_write,
2902 void *opaque)
2904 IOHandlerRecord **pioh, *ioh;
2906 if (!fd_read && !fd_write) {
2907 pioh = &first_io_handler;
2908 for(;;) {
2909 ioh = *pioh;
2910 if (ioh == NULL)
2911 break;
2912 if (ioh->fd == fd) {
2913 ioh->deleted = 1;
2914 break;
2916 pioh = &ioh->next;
2918 } else {
2919 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2920 if (ioh->fd == fd)
2921 goto found;
2923 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2924 if (!ioh)
2925 return -1;
2926 ioh->next = first_io_handler;
2927 first_io_handler = ioh;
2928 found:
2929 ioh->fd = fd;
2930 ioh->fd_read_poll = fd_read_poll;
2931 ioh->fd_read = fd_read;
2932 ioh->fd_write = fd_write;
2933 ioh->opaque = opaque;
2934 ioh->deleted = 0;
2936 main_loop_break();
2937 return 0;
2940 int qemu_set_fd_handler(int fd,
2941 IOHandler *fd_read,
2942 IOHandler *fd_write,
2943 void *opaque)
2945 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2948 #ifdef _WIN32
2949 /***********************************************************/
2950 /* Polling handling */
2952 typedef struct PollingEntry {
2953 PollingFunc *func;
2954 void *opaque;
2955 struct PollingEntry *next;
2956 } PollingEntry;
2958 static PollingEntry *first_polling_entry;
2960 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2962 PollingEntry **ppe, *pe;
2963 pe = qemu_mallocz(sizeof(PollingEntry));
2964 if (!pe)
2965 return -1;
2966 pe->func = func;
2967 pe->opaque = opaque;
2968 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2969 *ppe = pe;
2970 return 0;
2973 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2975 PollingEntry **ppe, *pe;
2976 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2977 pe = *ppe;
2978 if (pe->func == func && pe->opaque == opaque) {
2979 *ppe = pe->next;
2980 qemu_free(pe);
2981 break;
2986 /***********************************************************/
2987 /* Wait objects support */
2988 typedef struct WaitObjects {
2989 int num;
2990 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2991 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2992 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2993 } WaitObjects;
2995 static WaitObjects wait_objects = {0};
2997 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2999 WaitObjects *w = &wait_objects;
3001 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3002 return -1;
3003 w->events[w->num] = handle;
3004 w->func[w->num] = func;
3005 w->opaque[w->num] = opaque;
3006 w->num++;
3007 return 0;
3010 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3012 int i, found;
3013 WaitObjects *w = &wait_objects;
3015 found = 0;
3016 for (i = 0; i < w->num; i++) {
3017 if (w->events[i] == handle)
3018 found = 1;
3019 if (found) {
3020 w->events[i] = w->events[i + 1];
3021 w->func[i] = w->func[i + 1];
3022 w->opaque[i] = w->opaque[i + 1];
3025 if (found)
3026 w->num--;
3028 #endif
3030 /***********************************************************/
3031 /* ram save/restore */
3033 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3035 int v;
3037 v = qemu_get_byte(f);
3038 switch(v) {
3039 case 0:
3040 if (qemu_get_buffer(f, buf, len) != len)
3041 return -EIO;
3042 break;
3043 case 1:
3044 v = qemu_get_byte(f);
3045 memset(buf, v, len);
3046 break;
3047 default:
3048 return -EINVAL;
3051 if (qemu_file_has_error(f))
3052 return -EIO;
3054 return 0;
3057 static int ram_load_v1(QEMUFile *f, void *opaque)
3059 int ret;
3060 ram_addr_t i;
3062 if (qemu_get_be32(f) != phys_ram_size)
3063 return -EINVAL;
3064 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3065 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3066 continue;
3067 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3068 if (ret)
3069 return ret;
3071 return 0;
3074 #define BDRV_HASH_BLOCK_SIZE 1024
3075 #define IOBUF_SIZE 4096
3076 #define RAM_CBLOCK_MAGIC 0xfabe
3078 typedef struct RamDecompressState {
3079 z_stream zstream;
3080 QEMUFile *f;
3081 uint8_t buf[IOBUF_SIZE];
3082 } RamDecompressState;
3084 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3086 int ret;
3087 memset(s, 0, sizeof(*s));
3088 s->f = f;
3089 ret = inflateInit(&s->zstream);
3090 if (ret != Z_OK)
3091 return -1;
3092 return 0;
3095 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3097 int ret, clen;
3099 s->zstream.avail_out = len;
3100 s->zstream.next_out = buf;
3101 while (s->zstream.avail_out > 0) {
3102 if (s->zstream.avail_in == 0) {
3103 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3104 return -1;
3105 clen = qemu_get_be16(s->f);
3106 if (clen > IOBUF_SIZE)
3107 return -1;
3108 qemu_get_buffer(s->f, s->buf, clen);
3109 s->zstream.avail_in = clen;
3110 s->zstream.next_in = s->buf;
3112 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3113 if (ret != Z_OK && ret != Z_STREAM_END) {
3114 return -1;
3117 return 0;
3120 static void ram_decompress_close(RamDecompressState *s)
3122 inflateEnd(&s->zstream);
3125 #define RAM_SAVE_FLAG_FULL 0x01
3126 #define RAM_SAVE_FLAG_COMPRESS 0x02
3127 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3128 #define RAM_SAVE_FLAG_PAGE 0x08
3129 #define RAM_SAVE_FLAG_EOS 0x10
3131 static int is_dup_page(uint8_t *page, uint8_t ch)
3133 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3134 uint32_t *array = (uint32_t *)page;
3135 int i;
3137 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3138 if (array[i] != val)
3139 return 0;
3142 return 1;
3145 static int ram_save_block(QEMUFile *f)
3147 static ram_addr_t current_addr = 0;
3148 ram_addr_t saved_addr = current_addr;
3149 ram_addr_t addr = 0;
3150 int found = 0;
3152 while (addr < phys_ram_size) {
3153 if (kvm_enabled() && current_addr == 0)
3154 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3155 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3156 uint8_t ch;
3158 cpu_physical_memory_reset_dirty(current_addr,
3159 current_addr + TARGET_PAGE_SIZE,
3160 MIGRATION_DIRTY_FLAG);
3162 ch = *(phys_ram_base + current_addr);
3164 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3165 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3166 qemu_put_byte(f, ch);
3167 } else {
3168 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3169 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3172 found = 1;
3173 break;
3175 addr += TARGET_PAGE_SIZE;
3176 current_addr = (saved_addr + addr) % phys_ram_size;
3179 return found;
3182 static ram_addr_t ram_save_threshold = 10;
3184 static ram_addr_t ram_save_remaining(void)
3186 ram_addr_t addr;
3187 ram_addr_t count = 0;
3189 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3190 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3191 count++;
3194 return count;
3197 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3199 ram_addr_t addr;
3201 if (stage == 1) {
3202 /* Make sure all dirty bits are set */
3203 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3204 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3205 cpu_physical_memory_set_dirty(addr);
3208 /* Enable dirty memory tracking */
3209 cpu_physical_memory_set_dirty_tracking(1);
3211 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3214 while (!qemu_file_rate_limit(f)) {
3215 int ret;
3217 ret = ram_save_block(f);
3218 if (ret == 0) /* no more blocks */
3219 break;
3222 /* try transferring iterative blocks of memory */
3224 if (stage == 3) {
3225 cpu_physical_memory_set_dirty_tracking(0);
3227 /* flush all remaining blocks regardless of rate limiting */
3228 while (ram_save_block(f) != 0);
3231 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3233 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3236 static int ram_load_dead(QEMUFile *f, void *opaque)
3238 RamDecompressState s1, *s = &s1;
3239 uint8_t buf[10];
3240 ram_addr_t i;
3242 if (ram_decompress_open(s, f) < 0)
3243 return -EINVAL;
3244 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3245 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3246 continue;
3247 if (ram_decompress_buf(s, buf, 1) < 0) {
3248 fprintf(stderr, "Error while reading ram block header\n");
3249 goto error;
3251 if (buf[0] == 0) {
3252 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3253 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3254 goto error;
3256 } else {
3257 error:
3258 printf("Error block header\n");
3259 return -EINVAL;
3262 ram_decompress_close(s);
3264 return 0;
3267 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3269 ram_addr_t addr;
3270 int flags;
3272 if (version_id == 1)
3273 return ram_load_v1(f, opaque);
3275 if (version_id == 2) {
3276 if (qemu_get_be32(f) != phys_ram_size)
3277 return -EINVAL;
3278 return ram_load_dead(f, opaque);
3281 if (version_id != 3)
3282 return -EINVAL;
3284 do {
3285 addr = qemu_get_be64(f);
3287 flags = addr & ~TARGET_PAGE_MASK;
3288 addr &= TARGET_PAGE_MASK;
3290 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3291 if (addr != phys_ram_size)
3292 return -EINVAL;
3295 if (flags & RAM_SAVE_FLAG_FULL) {
3296 if (ram_load_dead(f, opaque) < 0)
3297 return -EINVAL;
3300 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3301 uint8_t ch = qemu_get_byte(f);
3302 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3303 } else if (flags & RAM_SAVE_FLAG_PAGE)
3304 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3305 } while (!(flags & RAM_SAVE_FLAG_EOS));
3307 return 0;
3310 /***********************************************************/
3311 /* bottom halves (can be seen as timers which expire ASAP) */
3313 struct QEMUBH {
3314 QEMUBHFunc *cb;
3315 void *opaque;
3316 int scheduled;
3317 int idle;
3318 int deleted;
3319 QEMUBH *next;
3322 static QEMUBH *first_bh = NULL;
3324 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3326 QEMUBH *bh;
3327 bh = qemu_mallocz(sizeof(QEMUBH));
3328 if (!bh)
3329 return NULL;
3330 bh->cb = cb;
3331 bh->opaque = opaque;
3332 bh->next = first_bh;
3333 first_bh = bh;
3334 return bh;
3337 int qemu_bh_poll(void)
3339 QEMUBH *bh, **bhp;
3340 int ret;
3342 ret = 0;
3343 for (bh = first_bh; bh; bh = bh->next) {
3344 if (!bh->deleted && bh->scheduled) {
3345 bh->scheduled = 0;
3346 if (!bh->idle)
3347 ret = 1;
3348 bh->idle = 0;
3349 bh->cb(bh->opaque);
3353 /* remove deleted bhs */
3354 bhp = &first_bh;
3355 while (*bhp) {
3356 bh = *bhp;
3357 if (bh->deleted) {
3358 *bhp = bh->next;
3359 qemu_free(bh);
3360 } else
3361 bhp = &bh->next;
3364 return ret;
3367 void qemu_bh_schedule_idle(QEMUBH *bh)
3369 if (bh->scheduled)
3370 return;
3371 bh->scheduled = 1;
3372 bh->idle = 1;
3375 void qemu_bh_schedule(QEMUBH *bh)
3377 CPUState *env = cpu_single_env;
3378 if (bh->scheduled)
3379 return;
3380 bh->scheduled = 1;
3381 bh->idle = 0;
3382 /* stop the currently executing CPU to execute the BH ASAP */
3383 if (env) {
3384 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3386 main_loop_break();
3389 void qemu_bh_cancel(QEMUBH *bh)
3391 bh->scheduled = 0;
3394 void qemu_bh_delete(QEMUBH *bh)
3396 bh->scheduled = 0;
3397 bh->deleted = 1;
3400 static void qemu_bh_update_timeout(int *timeout)
3402 QEMUBH *bh;
3404 for (bh = first_bh; bh; bh = bh->next) {
3405 if (!bh->deleted && bh->scheduled) {
3406 if (bh->idle) {
3407 /* idle bottom halves will be polled at least
3408 * every 10ms */
3409 *timeout = MIN(10, *timeout);
3410 } else {
3411 /* non-idle bottom halves will be executed
3412 * immediately */
3413 *timeout = 0;
3414 break;
3420 /***********************************************************/
3421 /* machine registration */
3423 static QEMUMachine *first_machine = NULL;
3424 QEMUMachine *current_machine = NULL;
3426 int qemu_register_machine(QEMUMachine *m)
3428 QEMUMachine **pm;
3429 pm = &first_machine;
3430 while (*pm != NULL)
3431 pm = &(*pm)->next;
3432 m->next = NULL;
3433 *pm = m;
3434 return 0;
3437 static QEMUMachine *find_machine(const char *name)
3439 QEMUMachine *m;
3441 for(m = first_machine; m != NULL; m = m->next) {
3442 if (!strcmp(m->name, name))
3443 return m;
3445 return NULL;
3448 /***********************************************************/
3449 /* main execution loop */
3451 static void gui_update(void *opaque)
3453 DisplayState *ds = opaque;
3454 ds->dpy_refresh(ds);
3455 qemu_mod_timer(ds->gui_timer,
3456 (ds->gui_timer_interval ?
3457 ds->gui_timer_interval :
3458 GUI_REFRESH_INTERVAL)
3459 + qemu_get_clock(rt_clock));
3462 struct vm_change_state_entry {
3463 VMChangeStateHandler *cb;
3464 void *opaque;
3465 LIST_ENTRY (vm_change_state_entry) entries;
3468 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3470 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3471 void *opaque)
3473 VMChangeStateEntry *e;
3475 e = qemu_mallocz(sizeof (*e));
3476 if (!e)
3477 return NULL;
3479 e->cb = cb;
3480 e->opaque = opaque;
3481 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3482 return e;
3485 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3487 LIST_REMOVE (e, entries);
3488 qemu_free (e);
3491 static void vm_state_notify(int running)
3493 VMChangeStateEntry *e;
3495 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3496 e->cb(e->opaque, running);
3500 /* XXX: support several handlers */
3501 static VMStopHandler *vm_stop_cb;
3502 static void *vm_stop_opaque;
3504 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3506 vm_stop_cb = cb;
3507 vm_stop_opaque = opaque;
3508 return 0;
3511 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3513 vm_stop_cb = NULL;
3516 void vm_start(void)
3518 if (!vm_running) {
3519 cpu_enable_ticks();
3520 vm_running = 1;
3521 vm_state_notify(1);
3522 qemu_rearm_alarm_timer(alarm_timer);
3526 void vm_stop(int reason)
3528 if (vm_running) {
3529 cpu_disable_ticks();
3530 vm_running = 0;
3531 if (reason != 0) {
3532 if (vm_stop_cb) {
3533 vm_stop_cb(vm_stop_opaque, reason);
3536 vm_state_notify(0);
3540 /* reset/shutdown handler */
3542 typedef struct QEMUResetEntry {
3543 QEMUResetHandler *func;
3544 void *opaque;
3545 struct QEMUResetEntry *next;
3546 } QEMUResetEntry;
3548 static QEMUResetEntry *first_reset_entry;
3549 static int reset_requested;
3550 static int shutdown_requested;
3551 static int powerdown_requested;
3553 int qemu_shutdown_requested(void)
3555 int r = shutdown_requested;
3556 shutdown_requested = 0;
3557 return r;
3560 int qemu_reset_requested(void)
3562 int r = reset_requested;
3563 reset_requested = 0;
3564 return r;
3567 int qemu_powerdown_requested(void)
3569 int r = powerdown_requested;
3570 powerdown_requested = 0;
3571 return r;
3574 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3576 QEMUResetEntry **pre, *re;
3578 pre = &first_reset_entry;
3579 while (*pre != NULL)
3580 pre = &(*pre)->next;
3581 re = qemu_mallocz(sizeof(QEMUResetEntry));
3582 re->func = func;
3583 re->opaque = opaque;
3584 re->next = NULL;
3585 *pre = re;
3588 void qemu_system_reset(void)
3590 QEMUResetEntry *re;
3592 /* reset all devices */
3593 for(re = first_reset_entry; re != NULL; re = re->next) {
3594 re->func(re->opaque);
3598 void qemu_system_reset_request(void)
3600 if (no_reboot) {
3601 shutdown_requested = 1;
3602 } else {
3603 reset_requested = 1;
3606 if (cpu_single_env) {
3607 qemu_kvm_cpu_stop(cpu_single_env);
3608 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3610 main_loop_break();
3613 void qemu_system_shutdown_request(void)
3615 shutdown_requested = 1;
3616 if (cpu_single_env)
3617 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3620 void qemu_system_powerdown_request(void)
3622 powerdown_requested = 1;
3623 if (cpu_single_env)
3624 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3627 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3628 struct timeval *tv)
3630 int ret;
3632 /* KVM holds a mutex while QEMU code is running, we need hooks to
3633 release the mutex whenever QEMU code sleeps. */
3635 kvm_sleep_begin();
3637 ret = select(max_fd, rfds, wfds, xfds, tv);
3639 kvm_sleep_end();
3641 return ret;
3644 #ifdef _WIN32
3645 static void host_main_loop_wait(int *timeout)
3647 int ret, ret2, i;
3648 PollingEntry *pe;
3651 /* XXX: need to suppress polling by better using win32 events */
3652 ret = 0;
3653 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3654 ret |= pe->func(pe->opaque);
3656 if (ret == 0) {
3657 int err;
3658 WaitObjects *w = &wait_objects;
3660 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3661 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3662 if (w->func[ret - WAIT_OBJECT_0])
3663 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3665 /* Check for additional signaled events */
3666 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3668 /* Check if event is signaled */
3669 ret2 = WaitForSingleObject(w->events[i], 0);
3670 if(ret2 == WAIT_OBJECT_0) {
3671 if (w->func[i])
3672 w->func[i](w->opaque[i]);
3673 } else if (ret2 == WAIT_TIMEOUT) {
3674 } else {
3675 err = GetLastError();
3676 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3679 } else if (ret == WAIT_TIMEOUT) {
3680 } else {
3681 err = GetLastError();
3682 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3686 *timeout = 0;
3688 #else
3689 static void host_main_loop_wait(int *timeout)
3692 #endif
3694 void main_loop_wait(int timeout)
3696 IOHandlerRecord *ioh;
3697 fd_set rfds, wfds, xfds;
3698 int ret, nfds;
3699 struct timeval tv;
3701 qemu_bh_update_timeout(&timeout);
3703 host_main_loop_wait(&timeout);
3705 /* poll any events */
3706 /* XXX: separate device handlers from system ones */
3707 nfds = -1;
3708 FD_ZERO(&rfds);
3709 FD_ZERO(&wfds);
3710 FD_ZERO(&xfds);
3711 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3712 if (ioh->deleted)
3713 continue;
3714 if (ioh->fd_read &&
3715 (!ioh->fd_read_poll ||
3716 ioh->fd_read_poll(ioh->opaque) != 0)) {
3717 FD_SET(ioh->fd, &rfds);
3718 if (ioh->fd > nfds)
3719 nfds = ioh->fd;
3721 if (ioh->fd_write) {
3722 FD_SET(ioh->fd, &wfds);
3723 if (ioh->fd > nfds)
3724 nfds = ioh->fd;
3728 tv.tv_sec = timeout / 1000;
3729 tv.tv_usec = (timeout % 1000) * 1000;
3731 #if defined(CONFIG_SLIRP)
3732 if (slirp_is_inited()) {
3733 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3735 #endif
3736 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3737 if (ret > 0) {
3738 IOHandlerRecord **pioh;
3740 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3741 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3742 ioh->fd_read(ioh->opaque);
3743 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3744 FD_CLR(ioh->fd, &rfds);
3746 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3747 ioh->fd_write(ioh->opaque);
3751 /* remove deleted IO handlers */
3752 pioh = &first_io_handler;
3753 while (*pioh) {
3754 ioh = *pioh;
3755 if (ioh->deleted) {
3756 *pioh = ioh->next;
3757 qemu_free(ioh);
3758 } else
3759 pioh = &ioh->next;
3762 #if defined(CONFIG_SLIRP)
3763 if (slirp_is_inited()) {
3764 if (ret < 0) {
3765 FD_ZERO(&rfds);
3766 FD_ZERO(&wfds);
3767 FD_ZERO(&xfds);
3769 slirp_select_poll(&rfds, &wfds, &xfds);
3771 #endif
3773 /* vm time timers */
3774 if (vm_running && (!cur_cpu
3775 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3776 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3777 qemu_get_clock(vm_clock));
3779 /* real time timers */
3780 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3781 qemu_get_clock(rt_clock));
3783 /* Check bottom-halves last in case any of the earlier events triggered
3784 them. */
3785 qemu_bh_poll();
3789 static int main_loop(void)
3791 int ret, timeout;
3792 #ifdef CONFIG_PROFILER
3793 int64_t ti;
3794 #endif
3795 CPUState *env;
3798 if (kvm_enabled()) {
3799 kvm_main_loop();
3800 cpu_disable_ticks();
3801 return 0;
3804 cur_cpu = first_cpu;
3805 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3806 for(;;) {
3807 if (vm_running) {
3809 for(;;) {
3810 /* get next cpu */
3811 env = next_cpu;
3812 #ifdef CONFIG_PROFILER
3813 ti = profile_getclock();
3814 #endif
3815 if (use_icount) {
3816 int64_t count;
3817 int decr;
3818 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3819 env->icount_decr.u16.low = 0;
3820 env->icount_extra = 0;
3821 count = qemu_next_deadline();
3822 count = (count + (1 << icount_time_shift) - 1)
3823 >> icount_time_shift;
3824 qemu_icount += count;
3825 decr = (count > 0xffff) ? 0xffff : count;
3826 count -= decr;
3827 env->icount_decr.u16.low = decr;
3828 env->icount_extra = count;
3830 ret = cpu_exec(env);
3831 #ifdef CONFIG_PROFILER
3832 qemu_time += profile_getclock() - ti;
3833 #endif
3834 if (use_icount) {
3835 /* Fold pending instructions back into the
3836 instruction counter, and clear the interrupt flag. */
3837 qemu_icount -= (env->icount_decr.u16.low
3838 + env->icount_extra);
3839 env->icount_decr.u32 = 0;
3840 env->icount_extra = 0;
3842 next_cpu = env->next_cpu ?: first_cpu;
3843 if (event_pending && likely(ret != EXCP_DEBUG)) {
3844 ret = EXCP_INTERRUPT;
3845 event_pending = 0;
3846 break;
3848 if (ret == EXCP_HLT) {
3849 /* Give the next CPU a chance to run. */
3850 cur_cpu = env;
3851 continue;
3853 if (ret != EXCP_HALTED)
3854 break;
3855 /* all CPUs are halted ? */
3856 if (env == cur_cpu)
3857 break;
3859 cur_cpu = env;
3861 if (shutdown_requested) {
3862 ret = EXCP_INTERRUPT;
3863 if (no_shutdown) {
3864 vm_stop(0);
3865 no_shutdown = 0;
3867 else
3868 break;
3870 if (reset_requested) {
3871 reset_requested = 0;
3872 qemu_system_reset();
3873 if (kvm_enabled())
3874 kvm_load_registers(env);
3875 ret = EXCP_INTERRUPT;
3877 if (powerdown_requested) {
3878 powerdown_requested = 0;
3879 qemu_system_powerdown();
3880 ret = EXCP_INTERRUPT;
3882 #ifdef CONFIG_GDBSTUB
3883 if (unlikely(ret == EXCP_DEBUG)) {
3884 gdb_set_stop_cpu(cur_cpu);
3885 vm_stop(EXCP_DEBUG);
3887 #endif
3888 /* If all cpus are halted then wait until the next IRQ */
3889 /* XXX: use timeout computed from timers */
3890 if (ret == EXCP_HALTED) {
3891 if (use_icount) {
3892 int64_t add;
3893 int64_t delta;
3894 /* Advance virtual time to the next event. */
3895 if (use_icount == 1) {
3896 /* When not using an adaptive execution frequency
3897 we tend to get badly out of sync with real time,
3898 so just delay for a reasonable amount of time. */
3899 delta = 0;
3900 } else {
3901 delta = cpu_get_icount() - cpu_get_clock();
3903 if (delta > 0) {
3904 /* If virtual time is ahead of real time then just
3905 wait for IO. */
3906 timeout = (delta / 1000000) + 1;
3907 } else {
3908 /* Wait for either IO to occur or the next
3909 timer event. */
3910 add = qemu_next_deadline();
3911 /* We advance the timer before checking for IO.
3912 Limit the amount we advance so that early IO
3913 activity won't get the guest too far ahead. */
3914 if (add > 10000000)
3915 add = 10000000;
3916 delta += add;
3917 add = (add + (1 << icount_time_shift) - 1)
3918 >> icount_time_shift;
3919 qemu_icount += add;
3920 timeout = delta / 1000000;
3921 if (timeout < 0)
3922 timeout = 0;
3924 } else {
3925 timeout = 5000;
3927 } else {
3928 timeout = 0;
3930 } else {
3931 if (shutdown_requested) {
3932 ret = EXCP_INTERRUPT;
3933 break;
3935 timeout = 5000;
3937 #ifdef CONFIG_PROFILER
3938 ti = profile_getclock();
3939 #endif
3940 main_loop_wait(timeout);
3941 #ifdef CONFIG_PROFILER
3942 dev_time += profile_getclock() - ti;
3943 #endif
3945 cpu_disable_ticks();
3946 return ret;
3949 static void help(int exitcode)
3951 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
3952 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3953 "usage: %s [options] [disk_image]\n"
3954 "\n"
3955 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3956 "\n"
3957 "Standard options:\n"
3958 "-M machine select emulated machine (-M ? for list)\n"
3959 "-cpu cpu select CPU (-cpu ? for list)\n"
3960 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3961 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3962 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3963 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3964 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3965 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3966 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3967 " [,boot=on|off]\n"
3968 " use 'file' as a drive image\n"
3969 "-mtdblock file use 'file' as on-board Flash memory image\n"
3970 "-sd file use 'file' as SecureDigital card image\n"
3971 "-pflash file use 'file' as a parallel flash image\n"
3972 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3973 "-snapshot write to temporary files instead of disk image files\n"
3974 #ifdef CONFIG_SDL
3975 "-no-frame open SDL window without a frame and window decorations\n"
3976 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3977 "-no-quit disable SDL window close capability\n"
3978 #endif
3979 #ifdef TARGET_I386
3980 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3981 #endif
3982 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3983 "-smp n set the number of CPUs to 'n' [default=1]\n"
3984 "-nographic disable graphical output and redirect serial I/Os to console\n"
3985 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3986 #ifndef _WIN32
3987 "-k language use keyboard layout (for example \"fr\" for French)\n"
3988 #endif
3989 #ifdef HAS_AUDIO
3990 "-audio-help print list of audio drivers and their options\n"
3991 "-soundhw c1,... enable audio support\n"
3992 " and only specified sound cards (comma separated list)\n"
3993 " use -soundhw ? to get the list of supported cards\n"
3994 " use -soundhw all to enable all of them\n"
3995 #endif
3996 "-vga [std|cirrus|vmware]\n"
3997 " select video card type\n"
3998 "-localtime set the real time clock to local time [default=utc]\n"
3999 "-full-screen start in full screen\n"
4000 #ifdef TARGET_I386
4001 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4002 #endif
4003 "-usb enable the USB driver (will be the default soon)\n"
4004 "-usbdevice name add the host or guest USB device 'name'\n"
4005 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4006 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4007 #endif
4008 "-name string set the name of the guest\n"
4009 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4010 "\n"
4011 "Network options:\n"
4012 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
4013 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4014 #ifdef CONFIG_SLIRP
4015 "-net user[,vlan=n][,name=str][,hostname=host]\n"
4016 " connect the user mode network stack to VLAN 'n' and send\n"
4017 " hostname 'host' to DHCP clients\n"
4018 #endif
4019 #ifdef _WIN32
4020 "-net tap[,vlan=n][,name=str],ifname=name\n"
4021 " connect the host TAP network interface to VLAN 'n'\n"
4022 #else
4023 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4024 " connect the host TAP network interface to VLAN 'n' and use the\n"
4025 " network scripts 'file' (default=%s)\n"
4026 " and 'dfile' (default=%s);\n"
4027 " use '[down]script=no' to disable script execution;\n"
4028 " use 'fd=h' to connect to an already opened TAP interface\n"
4029 #endif
4030 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4031 " connect the vlan 'n' to another VLAN using a socket connection\n"
4032 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4033 " connect the vlan 'n' to multicast maddr and port\n"
4034 #ifdef CONFIG_VDE
4035 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4036 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4037 " on host and listening for incoming connections on 'socketpath'.\n"
4038 " Use group 'groupname' and mode 'octalmode' to change default\n"
4039 " ownership and permissions for communication port.\n"
4040 #endif
4041 "-net none use it alone to have zero network devices; if no -net option\n"
4042 " is provided, the default is '-net nic -net user'\n"
4043 "\n"
4044 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
4045 "-bt hci,host[:id]\n"
4046 " Use host's HCI with the given name\n"
4047 "-bt hci[,vlan=n]\n"
4048 " Emulate a standard HCI in virtual scatternet 'n'\n"
4049 "-bt vhci[,vlan=n]\n"
4050 " Add host computer to virtual scatternet 'n' using VHCI\n"
4051 "-bt device:dev[,vlan=n]\n"
4052 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
4053 "\n"
4054 #ifdef CONFIG_SLIRP
4055 "-tftp dir allow tftp access to files in dir [-net user]\n"
4056 "-bootp file advertise file in BOOTP replies\n"
4057 #ifndef _WIN32
4058 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4059 #endif
4060 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4061 " redirect TCP or UDP connections from host to guest [-net user]\n"
4062 #endif
4063 "\n"
4064 "Linux boot specific:\n"
4065 "-kernel bzImage use 'bzImage' as kernel image\n"
4066 "-append cmdline use 'cmdline' as kernel command line\n"
4067 "-initrd file use 'file' as initial ram disk\n"
4068 "\n"
4069 "Debug/Expert options:\n"
4070 "-monitor dev redirect the monitor to char device 'dev'\n"
4071 "-serial dev redirect the serial port to char device 'dev'\n"
4072 "-parallel dev redirect the parallel port to char device 'dev'\n"
4073 "-pidfile file Write PID to 'file'\n"
4074 "-S freeze CPU at startup (use 'c' to start execution)\n"
4075 "-s wait gdb connection to port\n"
4076 "-p port set gdb connection port [default=%s]\n"
4077 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4078 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4079 " translation (t=none or lba) (usually qemu can guess them)\n"
4080 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4081 #ifdef USE_KQEMU
4082 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4083 "-no-kqemu disable KQEMU kernel module usage\n"
4084 #endif
4085 #ifdef CONFIG_KVM
4086 "-enable-kvm enable KVM full virtualization support\n"
4087 #endif
4088 #ifdef USE_KVM
4089 #ifndef NO_CPU_EMULATION
4090 "-no-kvm disable KVM hardware virtualization\n"
4091 #endif
4092 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4093 "-no-kvm-pit disable KVM kernel mode PIT\n"
4094 "-no-kvm-pit-reinjection disable KVM kernel mode PIT interrupt reinjection\n"
4095 "-enable-nesting enable support for running a VM inside the VM (AMD only)\n"
4096 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4097 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4098 " expose a PCI device to the guest OS.\n"
4099 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4100 " 'string' is used in log output.\n"
4101 #endif
4102 #endif
4103 #ifdef TARGET_I386
4104 "-no-acpi disable ACPI\n"
4105 "-no-hpet disable HPET\n"
4106 #endif
4107 #ifdef CONFIG_CURSES
4108 "-curses use a curses/ncurses interface instead of SDL\n"
4109 #endif
4110 "-no-reboot exit instead of rebooting\n"
4111 "-no-shutdown stop before shutdown\n"
4112 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
4113 "-vnc display start a VNC server on display\n"
4114 #ifndef _WIN32
4115 "-daemonize daemonize QEMU after initializing\n"
4116 #endif
4117 "-tdf inject timer interrupts that got lost\n"
4118 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4119 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
4120 "-option-rom rom load a file, rom, into the option ROM space\n"
4121 #ifdef TARGET_SPARC
4122 "-prom-env variable=value set OpenBIOS nvram variables\n"
4123 #endif
4124 "-clock force the use of the given methods for timer alarm.\n"
4125 " To see what timers are available use -clock ?\n"
4126 "-startdate select initial date of the clock\n"
4127 "-icount [N|auto]\n"
4128 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4129 "\n"
4130 "During emulation, the following keys are useful:\n"
4131 "ctrl-alt-f toggle full screen\n"
4132 "ctrl-alt-n switch to virtual console 'n'\n"
4133 "ctrl-alt toggle mouse and keyboard grab\n"
4134 "\n"
4135 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4137 "qemu",
4138 DEFAULT_RAM_SIZE,
4139 #ifndef _WIN32
4140 DEFAULT_NETWORK_SCRIPT,
4141 DEFAULT_NETWORK_DOWN_SCRIPT,
4142 #endif
4143 DEFAULT_GDBSTUB_PORT,
4144 "/tmp/qemu.log");
4145 exit(exitcode);
4148 #define HAS_ARG 0x0001
4150 enum {
4151 QEMU_OPTION_h,
4153 QEMU_OPTION_M,
4154 QEMU_OPTION_cpu,
4155 QEMU_OPTION_fda,
4156 QEMU_OPTION_fdb,
4157 QEMU_OPTION_hda,
4158 QEMU_OPTION_hdb,
4159 QEMU_OPTION_hdc,
4160 QEMU_OPTION_hdd,
4161 QEMU_OPTION_drive,
4162 QEMU_OPTION_cdrom,
4163 QEMU_OPTION_mtdblock,
4164 QEMU_OPTION_sd,
4165 QEMU_OPTION_pflash,
4166 QEMU_OPTION_boot,
4167 QEMU_OPTION_snapshot,
4168 #ifdef TARGET_I386
4169 QEMU_OPTION_no_fd_bootchk,
4170 #endif
4171 QEMU_OPTION_m,
4172 QEMU_OPTION_nographic,
4173 QEMU_OPTION_portrait,
4174 #ifdef HAS_AUDIO
4175 QEMU_OPTION_audio_help,
4176 QEMU_OPTION_soundhw,
4177 #endif
4179 QEMU_OPTION_net,
4180 QEMU_OPTION_tftp,
4181 QEMU_OPTION_bootp,
4182 QEMU_OPTION_smb,
4183 QEMU_OPTION_redir,
4184 QEMU_OPTION_bt,
4186 QEMU_OPTION_kernel,
4187 QEMU_OPTION_append,
4188 QEMU_OPTION_initrd,
4190 QEMU_OPTION_S,
4191 QEMU_OPTION_s,
4192 QEMU_OPTION_p,
4193 QEMU_OPTION_d,
4194 QEMU_OPTION_hdachs,
4195 QEMU_OPTION_L,
4196 QEMU_OPTION_bios,
4197 QEMU_OPTION_k,
4198 QEMU_OPTION_localtime,
4199 QEMU_OPTION_g,
4200 QEMU_OPTION_vga,
4201 QEMU_OPTION_echr,
4202 QEMU_OPTION_monitor,
4203 QEMU_OPTION_serial,
4204 QEMU_OPTION_parallel,
4205 QEMU_OPTION_loadvm,
4206 QEMU_OPTION_full_screen,
4207 QEMU_OPTION_no_frame,
4208 QEMU_OPTION_alt_grab,
4209 QEMU_OPTION_no_quit,
4210 QEMU_OPTION_pidfile,
4211 QEMU_OPTION_no_kqemu,
4212 QEMU_OPTION_kernel_kqemu,
4213 QEMU_OPTION_enable_kvm,
4214 QEMU_OPTION_enable_nesting,
4215 QEMU_OPTION_win2k_hack,
4216 QEMU_OPTION_usb,
4217 QEMU_OPTION_usbdevice,
4218 QEMU_OPTION_smp,
4219 QEMU_OPTION_vnc,
4220 QEMU_OPTION_no_acpi,
4221 QEMU_OPTION_no_hpet,
4222 QEMU_OPTION_curses,
4223 QEMU_OPTION_no_kvm,
4224 QEMU_OPTION_no_kvm_irqchip,
4225 QEMU_OPTION_no_kvm_pit,
4226 QEMU_OPTION_no_kvm_pit_reinjection,
4227 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4228 QEMU_OPTION_pcidevice,
4229 #endif
4230 QEMU_OPTION_no_reboot,
4231 QEMU_OPTION_no_shutdown,
4232 QEMU_OPTION_show_cursor,
4233 QEMU_OPTION_daemonize,
4234 QEMU_OPTION_option_rom,
4235 QEMU_OPTION_semihosting,
4236 QEMU_OPTION_cpu_vendor,
4237 QEMU_OPTION_name,
4238 QEMU_OPTION_prom_env,
4239 QEMU_OPTION_old_param,
4240 QEMU_OPTION_clock,
4241 QEMU_OPTION_startdate,
4242 QEMU_OPTION_tb_size,
4243 QEMU_OPTION_icount,
4244 QEMU_OPTION_uuid,
4245 QEMU_OPTION_incoming,
4246 QEMU_OPTION_tdf,
4247 QEMU_OPTION_kvm_shadow_memory,
4248 QEMU_OPTION_mempath,
4251 typedef struct QEMUOption {
4252 const char *name;
4253 int flags;
4254 int index;
4255 } QEMUOption;
4257 static const QEMUOption qemu_options[] = {
4258 { "h", 0, QEMU_OPTION_h },
4259 { "help", 0, QEMU_OPTION_h },
4261 { "M", HAS_ARG, QEMU_OPTION_M },
4262 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4263 { "fda", HAS_ARG, QEMU_OPTION_fda },
4264 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4265 { "hda", HAS_ARG, QEMU_OPTION_hda },
4266 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4267 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4268 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4269 { "drive", HAS_ARG, QEMU_OPTION_drive },
4270 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4271 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4272 { "sd", HAS_ARG, QEMU_OPTION_sd },
4273 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4274 { "boot", HAS_ARG, QEMU_OPTION_boot },
4275 { "snapshot", 0, QEMU_OPTION_snapshot },
4276 #ifdef TARGET_I386
4277 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4278 #endif
4279 { "m", HAS_ARG, QEMU_OPTION_m },
4280 { "nographic", 0, QEMU_OPTION_nographic },
4281 { "portrait", 0, QEMU_OPTION_portrait },
4282 { "k", HAS_ARG, QEMU_OPTION_k },
4283 #ifdef HAS_AUDIO
4284 { "audio-help", 0, QEMU_OPTION_audio_help },
4285 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4286 #endif
4288 { "net", HAS_ARG, QEMU_OPTION_net},
4289 #ifdef CONFIG_SLIRP
4290 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4291 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4292 #ifndef _WIN32
4293 { "smb", HAS_ARG, QEMU_OPTION_smb },
4294 #endif
4295 { "redir", HAS_ARG, QEMU_OPTION_redir },
4296 #endif
4297 { "bt", HAS_ARG, QEMU_OPTION_bt },
4299 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4300 { "append", HAS_ARG, QEMU_OPTION_append },
4301 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4303 { "S", 0, QEMU_OPTION_S },
4304 { "s", 0, QEMU_OPTION_s },
4305 { "p", HAS_ARG, QEMU_OPTION_p },
4306 { "d", HAS_ARG, QEMU_OPTION_d },
4307 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4308 { "L", HAS_ARG, QEMU_OPTION_L },
4309 { "bios", HAS_ARG, QEMU_OPTION_bios },
4310 #ifdef USE_KQEMU
4311 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4312 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4313 #endif
4314 #ifdef CONFIG_KVM
4315 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4316 #endif
4317 #ifdef USE_KVM
4318 #ifndef NO_CPU_EMULATION
4319 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4320 #endif
4321 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4322 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4323 { "no-kvm-pit-reinjection", 0, QEMU_OPTION_no_kvm_pit_reinjection },
4324 { "enable-nesting", 0, QEMU_OPTION_enable_nesting },
4325 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4326 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4327 #endif
4328 #endif
4329 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4330 { "g", 1, QEMU_OPTION_g },
4331 #endif
4332 { "localtime", 0, QEMU_OPTION_localtime },
4333 { "vga", HAS_ARG, QEMU_OPTION_vga },
4334 { "echr", HAS_ARG, QEMU_OPTION_echr },
4335 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4336 { "serial", HAS_ARG, QEMU_OPTION_serial },
4337 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4338 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4339 { "incoming", 1, QEMU_OPTION_incoming },
4340 { "full-screen", 0, QEMU_OPTION_full_screen },
4341 #ifdef CONFIG_SDL
4342 { "no-frame", 0, QEMU_OPTION_no_frame },
4343 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4344 { "no-quit", 0, QEMU_OPTION_no_quit },
4345 #endif
4346 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4347 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4348 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4349 { "smp", HAS_ARG, QEMU_OPTION_smp },
4350 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4351 #ifdef CONFIG_CURSES
4352 { "curses", 0, QEMU_OPTION_curses },
4353 #endif
4354 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4356 /* temporary options */
4357 { "usb", 0, QEMU_OPTION_usb },
4358 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4359 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4360 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4361 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4362 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4363 { "daemonize", 0, QEMU_OPTION_daemonize },
4364 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4365 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4366 { "semihosting", 0, QEMU_OPTION_semihosting },
4367 #endif
4368 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4369 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4370 { "name", HAS_ARG, QEMU_OPTION_name },
4371 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4372 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4373 #endif
4374 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4375 #if defined(TARGET_ARM)
4376 { "old-param", 0, QEMU_OPTION_old_param },
4377 #endif
4378 { "clock", HAS_ARG, QEMU_OPTION_clock },
4379 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4380 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4381 { "icount", HAS_ARG, QEMU_OPTION_icount },
4382 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4383 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4384 { NULL },
4387 /* password input */
4389 int qemu_key_check(BlockDriverState *bs, const char *name)
4391 char password[256];
4392 int i;
4394 if (!bdrv_is_encrypted(bs))
4395 return 0;
4397 term_printf("%s is encrypted.\n", name);
4398 for(i = 0; i < 3; i++) {
4399 monitor_readline("Password: ", 1, password, sizeof(password));
4400 if (bdrv_set_key(bs, password) == 0)
4401 return 0;
4402 term_printf("invalid password\n");
4404 return -EPERM;
4407 static BlockDriverState *get_bdrv(int index)
4409 if (index > nb_drives)
4410 return NULL;
4411 return drives_table[index].bdrv;
4414 static void read_passwords(void)
4416 BlockDriverState *bs;
4417 int i;
4419 for(i = 0; i < 6; i++) {
4420 bs = get_bdrv(i);
4421 if (bs)
4422 qemu_key_check(bs, bdrv_get_device_name(bs));
4426 #ifdef HAS_AUDIO
4427 struct soundhw soundhw[] = {
4428 #ifdef HAS_AUDIO_CHOICE
4429 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4431 "pcspk",
4432 "PC speaker",
4435 { .init_isa = pcspk_audio_init }
4437 #endif
4439 "sb16",
4440 "Creative Sound Blaster 16",
4443 { .init_isa = SB16_init }
4446 #ifdef CONFIG_CS4231A
4448 "cs4231a",
4449 "CS4231A",
4452 { .init_isa = cs4231a_init }
4454 #endif
4456 #ifdef CONFIG_ADLIB
4458 "adlib",
4459 #ifdef HAS_YMF262
4460 "Yamaha YMF262 (OPL3)",
4461 #else
4462 "Yamaha YM3812 (OPL2)",
4463 #endif
4466 { .init_isa = Adlib_init }
4468 #endif
4470 #ifdef CONFIG_GUS
4472 "gus",
4473 "Gravis Ultrasound GF1",
4476 { .init_isa = GUS_init }
4478 #endif
4480 #ifdef CONFIG_AC97
4482 "ac97",
4483 "Intel 82801AA AC97 Audio",
4486 { .init_pci = ac97_init }
4488 #endif
4491 "es1370",
4492 "ENSONIQ AudioPCI ES1370",
4495 { .init_pci = es1370_init }
4497 #endif
4499 { NULL, NULL, 0, 0, { NULL } }
4502 static void select_soundhw (const char *optarg)
4504 struct soundhw *c;
4506 if (*optarg == '?') {
4507 show_valid_cards:
4509 printf ("Valid sound card names (comma separated):\n");
4510 for (c = soundhw; c->name; ++c) {
4511 printf ("%-11s %s\n", c->name, c->descr);
4513 printf ("\n-soundhw all will enable all of the above\n");
4514 exit (*optarg != '?');
4516 else {
4517 size_t l;
4518 const char *p;
4519 char *e;
4520 int bad_card = 0;
4522 if (!strcmp (optarg, "all")) {
4523 for (c = soundhw; c->name; ++c) {
4524 c->enabled = 1;
4526 return;
4529 p = optarg;
4530 while (*p) {
4531 e = strchr (p, ',');
4532 l = !e ? strlen (p) : (size_t) (e - p);
4534 for (c = soundhw; c->name; ++c) {
4535 if (!strncmp (c->name, p, l)) {
4536 c->enabled = 1;
4537 break;
4541 if (!c->name) {
4542 if (l > 80) {
4543 fprintf (stderr,
4544 "Unknown sound card name (too big to show)\n");
4546 else {
4547 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4548 (int) l, p);
4550 bad_card = 1;
4552 p += l + (e != NULL);
4555 if (bad_card)
4556 goto show_valid_cards;
4559 #endif
4561 static void select_vgahw (const char *p)
4563 const char *opts;
4565 if (strstart(p, "std", &opts)) {
4566 cirrus_vga_enabled = 0;
4567 vmsvga_enabled = 0;
4568 } else if (strstart(p, "cirrus", &opts)) {
4569 cirrus_vga_enabled = 1;
4570 vmsvga_enabled = 0;
4571 } else if (strstart(p, "vmware", &opts)) {
4572 cirrus_vga_enabled = 0;
4573 vmsvga_enabled = 1;
4574 } else {
4575 invalid_vga:
4576 fprintf(stderr, "Unknown vga type: %s\n", p);
4577 exit(1);
4579 while (*opts) {
4580 const char *nextopt;
4582 if (strstart(opts, ",retrace=", &nextopt)) {
4583 opts = nextopt;
4584 if (strstart(opts, "dumb", &nextopt))
4585 vga_retrace_method = VGA_RETRACE_DUMB;
4586 else if (strstart(opts, "precise", &nextopt))
4587 vga_retrace_method = VGA_RETRACE_PRECISE;
4588 else goto invalid_vga;
4589 } else goto invalid_vga;
4590 opts = nextopt;
4594 #ifdef _WIN32
4595 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4597 exit(STATUS_CONTROL_C_EXIT);
4598 return TRUE;
4600 #endif
4602 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4604 int ret;
4606 if(strlen(str) != 36)
4607 return -1;
4609 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4610 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4611 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4613 if(ret != 16)
4614 return -1;
4616 return 0;
4619 #define MAX_NET_CLIENTS 32
4621 static int saved_argc;
4622 static char **saved_argv;
4624 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4626 *argc = saved_argc;
4627 *argv = saved_argv;
4628 *opt_daemonize = daemonize;
4629 *opt_incoming = incoming;
4633 static int gethugepagesize(void)
4635 int ret, fd;
4636 char buf[4096];
4637 const char *needle = "Hugepagesize:";
4638 char *size;
4639 unsigned long hugepagesize;
4641 fd = open("/proc/meminfo", O_RDONLY);
4642 if (fd < 0) {
4643 perror("open");
4644 exit(0);
4647 ret = read(fd, buf, sizeof(buf));
4648 if (ret < 0) {
4649 perror("read");
4650 exit(0);
4653 size = strstr(buf, needle);
4654 if (!size)
4655 return 0;
4656 size += strlen(needle);
4657 hugepagesize = strtol(size, NULL, 0);
4658 return hugepagesize;
4661 void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4663 char *filename;
4664 void *area;
4665 int fd;
4667 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4668 return NULL;
4670 hpagesize = gethugepagesize() * 1024;
4671 if (!hpagesize)
4672 return NULL;
4674 fd = mkstemp(filename);
4675 if (fd < 0) {
4676 perror("mkstemp");
4677 free(filename);
4678 return NULL;
4680 unlink(filename);
4681 free(filename);
4683 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4686 * ftruncate is not supported by hugetlbfs in older
4687 * hosts, so don't bother checking for errors.
4688 * If anything goes wrong with it under other filesystems,
4689 * mmap will fail.
4691 ftruncate(fd, memory);
4693 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4694 if (area == MAP_FAILED) {
4695 perror("mmap");
4696 close(fd);
4697 return NULL;
4700 *len = memory;
4701 return area;
4704 void *qemu_alloc_physram(unsigned long memory)
4706 void *area = NULL;
4707 unsigned long map_len = memory;
4709 #ifdef USE_KVM
4710 if (mem_path)
4711 area = alloc_mem_area(memory, &map_len, mem_path);
4712 #endif
4713 if (!area)
4714 area = qemu_vmalloc(memory);
4715 #ifdef USE_KVM
4716 if (kvm_setup_guest_memory(area, map_len))
4717 area = NULL;
4718 #endif
4719 return area;
4722 #ifndef _WIN32
4724 static void termsig_handler(int signal)
4726 qemu_system_shutdown_request();
4729 static void termsig_setup(void)
4731 struct sigaction act;
4733 memset(&act, 0, sizeof(act));
4734 act.sa_handler = termsig_handler;
4735 sigaction(SIGINT, &act, NULL);
4736 sigaction(SIGHUP, &act, NULL);
4737 sigaction(SIGTERM, &act, NULL);
4740 #endif
4742 int main(int argc, char **argv, char **envp)
4744 #ifdef CONFIG_GDBSTUB
4745 int use_gdbstub;
4746 const char *gdbstub_port;
4747 #endif
4748 uint32_t boot_devices_bitmap = 0;
4749 int i;
4750 int snapshot, linux_boot, net_boot;
4751 const char *initrd_filename;
4752 const char *kernel_filename, *kernel_cmdline;
4753 const char *boot_devices = "";
4754 DisplayState *ds = &display_state;
4755 int cyls, heads, secs, translation;
4756 const char *net_clients[MAX_NET_CLIENTS];
4757 int nb_net_clients;
4758 const char *bt_opts[MAX_BT_CMDLINE];
4759 int nb_bt_opts;
4760 int hda_index;
4761 int optind;
4762 const char *r, *optarg;
4763 CharDriverState *monitor_hd;
4764 const char *monitor_device;
4765 const char *serial_devices[MAX_SERIAL_PORTS];
4766 int serial_device_index;
4767 const char *parallel_devices[MAX_PARALLEL_PORTS];
4768 int parallel_device_index;
4769 const char *loadvm = NULL;
4770 QEMUMachine *machine;
4771 const char *cpu_model;
4772 const char *usb_devices[MAX_USB_CMDLINE];
4773 int usb_devices_index;
4774 int fds[2];
4775 int tb_size;
4776 const char *pid_file = NULL;
4777 int autostart;
4778 const char *incoming = NULL;
4780 qemu_cache_utils_init(envp);
4782 LIST_INIT (&vm_change_state_head);
4783 #ifndef _WIN32
4785 struct sigaction act;
4786 sigfillset(&act.sa_mask);
4787 act.sa_flags = 0;
4788 act.sa_handler = SIG_IGN;
4789 sigaction(SIGPIPE, &act, NULL);
4791 #else
4792 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4793 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4794 QEMU to run on a single CPU */
4796 HANDLE h;
4797 DWORD mask, smask;
4798 int i;
4799 h = GetCurrentProcess();
4800 if (GetProcessAffinityMask(h, &mask, &smask)) {
4801 for(i = 0; i < 32; i++) {
4802 if (mask & (1 << i))
4803 break;
4805 if (i != 32) {
4806 mask = 1 << i;
4807 SetProcessAffinityMask(h, mask);
4811 #endif
4813 register_machines();
4814 machine = first_machine;
4815 cpu_model = NULL;
4816 initrd_filename = NULL;
4817 ram_size = 0;
4818 vga_ram_size = VGA_RAM_SIZE;
4819 #ifdef CONFIG_GDBSTUB
4820 use_gdbstub = 0;
4821 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4822 #endif
4823 snapshot = 0;
4824 nographic = 0;
4825 curses = 0;
4826 kernel_filename = NULL;
4827 kernel_cmdline = "";
4828 cyls = heads = secs = 0;
4829 translation = BIOS_ATA_TRANSLATION_AUTO;
4830 monitor_device = "vc";
4832 serial_devices[0] = "vc:80Cx24C";
4833 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4834 serial_devices[i] = NULL;
4835 serial_device_index = 0;
4837 parallel_devices[0] = "vc:640x480";
4838 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4839 parallel_devices[i] = NULL;
4840 parallel_device_index = 0;
4842 usb_devices_index = 0;
4843 assigned_devices_index = 0;
4845 nb_net_clients = 0;
4846 nb_bt_opts = 0;
4847 nb_drives = 0;
4848 nb_drives_opt = 0;
4849 hda_index = -1;
4851 nb_nics = 0;
4853 tb_size = 0;
4854 autostart= 1;
4856 optind = 1;
4857 for(;;) {
4858 if (optind >= argc)
4859 break;
4860 r = argv[optind];
4861 if (r[0] != '-') {
4862 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4863 } else {
4864 const QEMUOption *popt;
4866 optind++;
4867 /* Treat --foo the same as -foo. */
4868 if (r[1] == '-')
4869 r++;
4870 popt = qemu_options;
4871 for(;;) {
4872 if (!popt->name) {
4873 fprintf(stderr, "%s: invalid option -- '%s'\n",
4874 argv[0], r);
4875 exit(1);
4877 if (!strcmp(popt->name, r + 1))
4878 break;
4879 popt++;
4881 if (popt->flags & HAS_ARG) {
4882 if (optind >= argc) {
4883 fprintf(stderr, "%s: option '%s' requires an argument\n",
4884 argv[0], r);
4885 exit(1);
4887 optarg = argv[optind++];
4888 } else {
4889 optarg = NULL;
4892 switch(popt->index) {
4893 case QEMU_OPTION_M:
4894 machine = find_machine(optarg);
4895 if (!machine) {
4896 QEMUMachine *m;
4897 printf("Supported machines are:\n");
4898 for(m = first_machine; m != NULL; m = m->next) {
4899 printf("%-10s %s%s\n",
4900 m->name, m->desc,
4901 m == first_machine ? " (default)" : "");
4903 exit(*optarg != '?');
4905 break;
4906 case QEMU_OPTION_cpu:
4907 /* hw initialization will check this */
4908 if (*optarg == '?') {
4909 /* XXX: implement xxx_cpu_list for targets that still miss it */
4910 #if defined(cpu_list)
4911 cpu_list(stdout, &fprintf);
4912 #endif
4913 exit(0);
4914 } else {
4915 cpu_model = optarg;
4917 break;
4918 case QEMU_OPTION_initrd:
4919 initrd_filename = optarg;
4920 break;
4921 case QEMU_OPTION_hda:
4922 if (cyls == 0)
4923 hda_index = drive_add(optarg, HD_ALIAS, 0);
4924 else
4925 hda_index = drive_add(optarg, HD_ALIAS
4926 ",cyls=%d,heads=%d,secs=%d%s",
4927 0, cyls, heads, secs,
4928 translation == BIOS_ATA_TRANSLATION_LBA ?
4929 ",trans=lba" :
4930 translation == BIOS_ATA_TRANSLATION_NONE ?
4931 ",trans=none" : "");
4932 break;
4933 case QEMU_OPTION_hdb:
4934 case QEMU_OPTION_hdc:
4935 case QEMU_OPTION_hdd:
4936 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4937 break;
4938 case QEMU_OPTION_drive:
4939 drive_add(NULL, "%s", optarg);
4940 break;
4941 case QEMU_OPTION_mtdblock:
4942 drive_add(optarg, MTD_ALIAS);
4943 break;
4944 case QEMU_OPTION_sd:
4945 drive_add(optarg, SD_ALIAS);
4946 break;
4947 case QEMU_OPTION_pflash:
4948 drive_add(optarg, PFLASH_ALIAS);
4949 break;
4950 case QEMU_OPTION_snapshot:
4951 snapshot = 1;
4952 break;
4953 case QEMU_OPTION_hdachs:
4955 const char *p;
4956 p = optarg;
4957 cyls = strtol(p, (char **)&p, 0);
4958 if (cyls < 1 || cyls > 16383)
4959 goto chs_fail;
4960 if (*p != ',')
4961 goto chs_fail;
4962 p++;
4963 heads = strtol(p, (char **)&p, 0);
4964 if (heads < 1 || heads > 16)
4965 goto chs_fail;
4966 if (*p != ',')
4967 goto chs_fail;
4968 p++;
4969 secs = strtol(p, (char **)&p, 0);
4970 if (secs < 1 || secs > 63)
4971 goto chs_fail;
4972 if (*p == ',') {
4973 p++;
4974 if (!strcmp(p, "none"))
4975 translation = BIOS_ATA_TRANSLATION_NONE;
4976 else if (!strcmp(p, "lba"))
4977 translation = BIOS_ATA_TRANSLATION_LBA;
4978 else if (!strcmp(p, "auto"))
4979 translation = BIOS_ATA_TRANSLATION_AUTO;
4980 else
4981 goto chs_fail;
4982 } else if (*p != '\0') {
4983 chs_fail:
4984 fprintf(stderr, "qemu: invalid physical CHS format\n");
4985 exit(1);
4987 if (hda_index != -1)
4988 snprintf(drives_opt[hda_index].opt,
4989 sizeof(drives_opt[hda_index].opt),
4990 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4991 0, cyls, heads, secs,
4992 translation == BIOS_ATA_TRANSLATION_LBA ?
4993 ",trans=lba" :
4994 translation == BIOS_ATA_TRANSLATION_NONE ?
4995 ",trans=none" : "");
4997 break;
4998 case QEMU_OPTION_nographic:
4999 nographic = 1;
5000 break;
5001 #ifdef CONFIG_CURSES
5002 case QEMU_OPTION_curses:
5003 curses = 1;
5004 break;
5005 #endif
5006 case QEMU_OPTION_portrait:
5007 graphic_rotate = 1;
5008 break;
5009 case QEMU_OPTION_kernel:
5010 kernel_filename = optarg;
5011 break;
5012 case QEMU_OPTION_append:
5013 kernel_cmdline = optarg;
5014 break;
5015 case QEMU_OPTION_cdrom:
5016 drive_add(optarg, CDROM_ALIAS);
5017 break;
5018 case QEMU_OPTION_boot:
5019 boot_devices = optarg;
5020 /* We just do some generic consistency checks */
5022 /* Could easily be extended to 64 devices if needed */
5023 const char *p;
5025 boot_devices_bitmap = 0;
5026 for (p = boot_devices; *p != '\0'; p++) {
5027 /* Allowed boot devices are:
5028 * a b : floppy disk drives
5029 * c ... f : IDE disk drives
5030 * g ... m : machine implementation dependant drives
5031 * n ... p : network devices
5032 * It's up to each machine implementation to check
5033 * if the given boot devices match the actual hardware
5034 * implementation and firmware features.
5036 if (*p < 'a' || *p > 'q') {
5037 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5038 exit(1);
5040 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5041 fprintf(stderr,
5042 "Boot device '%c' was given twice\n",*p);
5043 exit(1);
5045 boot_devices_bitmap |= 1 << (*p - 'a');
5048 break;
5049 case QEMU_OPTION_fda:
5050 case QEMU_OPTION_fdb:
5051 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5052 break;
5053 #ifdef TARGET_I386
5054 case QEMU_OPTION_no_fd_bootchk:
5055 fd_bootchk = 0;
5056 break;
5057 #endif
5058 case QEMU_OPTION_net:
5059 if (nb_net_clients >= MAX_NET_CLIENTS) {
5060 fprintf(stderr, "qemu: too many network clients\n");
5061 exit(1);
5063 net_clients[nb_net_clients] = optarg;
5064 nb_net_clients++;
5065 break;
5066 #ifdef CONFIG_SLIRP
5067 case QEMU_OPTION_tftp:
5068 tftp_prefix = optarg;
5069 break;
5070 case QEMU_OPTION_bootp:
5071 bootp_filename = optarg;
5072 break;
5073 #ifndef _WIN32
5074 case QEMU_OPTION_smb:
5075 net_slirp_smb(optarg);
5076 break;
5077 #endif
5078 case QEMU_OPTION_redir:
5079 net_slirp_redir(optarg);
5080 break;
5081 #endif
5082 case QEMU_OPTION_bt:
5083 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5084 fprintf(stderr, "qemu: too many bluetooth options\n");
5085 exit(1);
5087 bt_opts[nb_bt_opts++] = optarg;
5088 break;
5089 #ifdef HAS_AUDIO
5090 case QEMU_OPTION_audio_help:
5091 AUD_help ();
5092 exit (0);
5093 break;
5094 case QEMU_OPTION_soundhw:
5095 select_soundhw (optarg);
5096 break;
5097 #endif
5098 case QEMU_OPTION_h:
5099 help(0);
5100 break;
5101 case QEMU_OPTION_m: {
5102 uint64_t value;
5103 char *ptr;
5105 value = strtoul(optarg, &ptr, 10);
5106 switch (*ptr) {
5107 case 0: case 'M': case 'm':
5108 value <<= 20;
5109 break;
5110 case 'G': case 'g':
5111 value <<= 30;
5112 break;
5113 default:
5114 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5115 exit(1);
5118 /* On 32-bit hosts, QEMU is limited by virtual address space */
5119 if (value > (2047 << 20)
5120 #ifndef USE_KQEMU
5121 && HOST_LONG_BITS == 32
5122 #endif
5124 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5125 exit(1);
5127 if (value != (uint64_t)(ram_addr_t)value) {
5128 fprintf(stderr, "qemu: ram size too large\n");
5129 exit(1);
5131 ram_size = value;
5132 break;
5134 case QEMU_OPTION_d:
5136 int mask;
5137 const CPULogItem *item;
5139 mask = cpu_str_to_log_mask(optarg);
5140 if (!mask) {
5141 printf("Log items (comma separated):\n");
5142 for(item = cpu_log_items; item->mask != 0; item++) {
5143 printf("%-10s %s\n", item->name, item->help);
5145 exit(1);
5147 cpu_set_log(mask);
5149 break;
5150 #ifdef CONFIG_GDBSTUB
5151 case QEMU_OPTION_s:
5152 use_gdbstub = 1;
5153 break;
5154 case QEMU_OPTION_p:
5155 gdbstub_port = optarg;
5156 break;
5157 #endif
5158 case QEMU_OPTION_L:
5159 bios_dir = optarg;
5160 break;
5161 case QEMU_OPTION_bios:
5162 bios_name = optarg;
5163 break;
5164 case QEMU_OPTION_S:
5165 autostart = 0;
5166 break;
5167 case QEMU_OPTION_k:
5168 keyboard_layout = optarg;
5169 break;
5170 case QEMU_OPTION_localtime:
5171 rtc_utc = 0;
5172 break;
5173 case QEMU_OPTION_vga:
5174 select_vgahw (optarg);
5175 break;
5176 case QEMU_OPTION_g:
5178 const char *p;
5179 int w, h, depth;
5180 p = optarg;
5181 w = strtol(p, (char **)&p, 10);
5182 if (w <= 0) {
5183 graphic_error:
5184 fprintf(stderr, "qemu: invalid resolution or depth\n");
5185 exit(1);
5187 if (*p != 'x')
5188 goto graphic_error;
5189 p++;
5190 h = strtol(p, (char **)&p, 10);
5191 if (h <= 0)
5192 goto graphic_error;
5193 if (*p == 'x') {
5194 p++;
5195 depth = strtol(p, (char **)&p, 10);
5196 if (depth != 8 && depth != 15 && depth != 16 &&
5197 depth != 24 && depth != 32)
5198 goto graphic_error;
5199 } else if (*p == '\0') {
5200 depth = graphic_depth;
5201 } else {
5202 goto graphic_error;
5205 graphic_width = w;
5206 graphic_height = h;
5207 graphic_depth = depth;
5209 break;
5210 case QEMU_OPTION_echr:
5212 char *r;
5213 term_escape_char = strtol(optarg, &r, 0);
5214 if (r == optarg)
5215 printf("Bad argument to echr\n");
5216 break;
5218 case QEMU_OPTION_monitor:
5219 monitor_device = optarg;
5220 break;
5221 case QEMU_OPTION_serial:
5222 if (serial_device_index >= MAX_SERIAL_PORTS) {
5223 fprintf(stderr, "qemu: too many serial ports\n");
5224 exit(1);
5226 serial_devices[serial_device_index] = optarg;
5227 serial_device_index++;
5228 break;
5229 case QEMU_OPTION_parallel:
5230 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5231 fprintf(stderr, "qemu: too many parallel ports\n");
5232 exit(1);
5234 parallel_devices[parallel_device_index] = optarg;
5235 parallel_device_index++;
5236 break;
5237 case QEMU_OPTION_loadvm:
5238 loadvm = optarg;
5239 break;
5240 case QEMU_OPTION_full_screen:
5241 full_screen = 1;
5242 break;
5243 #ifdef CONFIG_SDL
5244 case QEMU_OPTION_no_frame:
5245 no_frame = 1;
5246 break;
5247 case QEMU_OPTION_alt_grab:
5248 alt_grab = 1;
5249 break;
5250 case QEMU_OPTION_no_quit:
5251 no_quit = 1;
5252 break;
5253 #endif
5254 case QEMU_OPTION_pidfile:
5255 pid_file = optarg;
5256 break;
5257 #ifdef TARGET_I386
5258 case QEMU_OPTION_win2k_hack:
5259 win2k_install_hack = 1;
5260 break;
5261 #endif
5262 #ifdef USE_KQEMU
5263 case QEMU_OPTION_no_kqemu:
5264 kqemu_allowed = 0;
5265 break;
5266 case QEMU_OPTION_kernel_kqemu:
5267 kqemu_allowed = 2;
5268 break;
5269 #endif
5270 #ifdef CONFIG_KVM
5271 case QEMU_OPTION_enable_kvm:
5272 kvm_allowed = 1;
5273 #ifdef USE_KQEMU
5274 kqemu_allowed = 0;
5275 #endif
5276 break;
5277 #endif
5278 #ifdef USE_KVM
5279 case QEMU_OPTION_no_kvm:
5280 kvm_allowed = 0;
5281 break;
5282 case QEMU_OPTION_no_kvm_irqchip: {
5283 extern int kvm_irqchip, kvm_pit;
5284 kvm_irqchip = 0;
5285 kvm_pit = 0;
5286 break;
5288 case QEMU_OPTION_no_kvm_pit: {
5289 extern int kvm_pit;
5290 kvm_pit = 0;
5291 break;
5293 case QEMU_OPTION_no_kvm_pit_reinjection: {
5294 extern int kvm_pit_reinject;
5295 kvm_pit_reinject = 0;
5296 break;
5298 case QEMU_OPTION_enable_nesting: {
5299 kvm_nested = 1;
5300 break;
5302 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5303 case QEMU_OPTION_pcidevice:
5304 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5305 fprintf(stderr, "Too many assigned devices\n");
5306 exit(1);
5308 assigned_devices[assigned_devices_index] = optarg;
5309 assigned_devices_index++;
5310 break;
5311 #endif
5312 #endif
5313 case QEMU_OPTION_usb:
5314 usb_enabled = 1;
5315 break;
5316 case QEMU_OPTION_usbdevice:
5317 usb_enabled = 1;
5318 if (usb_devices_index >= MAX_USB_CMDLINE) {
5319 fprintf(stderr, "Too many USB devices\n");
5320 exit(1);
5322 usb_devices[usb_devices_index] = optarg;
5323 usb_devices_index++;
5324 break;
5325 case QEMU_OPTION_smp:
5326 smp_cpus = atoi(optarg);
5327 if (smp_cpus < 1) {
5328 fprintf(stderr, "Invalid number of CPUs\n");
5329 exit(1);
5331 break;
5332 case QEMU_OPTION_vnc:
5333 vnc_display = optarg;
5334 break;
5335 case QEMU_OPTION_no_acpi:
5336 acpi_enabled = 0;
5337 break;
5338 case QEMU_OPTION_no_hpet:
5339 no_hpet = 1;
5340 break;
5341 case QEMU_OPTION_no_reboot:
5342 no_reboot = 1;
5343 break;
5344 case QEMU_OPTION_no_shutdown:
5345 no_shutdown = 1;
5346 break;
5347 case QEMU_OPTION_show_cursor:
5348 cursor_hide = 0;
5349 break;
5350 case QEMU_OPTION_uuid:
5351 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5352 fprintf(stderr, "Fail to parse UUID string."
5353 " Wrong format.\n");
5354 exit(1);
5356 break;
5357 case QEMU_OPTION_daemonize:
5358 daemonize = 1;
5359 break;
5360 case QEMU_OPTION_option_rom:
5361 if (nb_option_roms >= MAX_OPTION_ROMS) {
5362 fprintf(stderr, "Too many option ROMs\n");
5363 exit(1);
5365 option_rom[nb_option_roms] = optarg;
5366 nb_option_roms++;
5367 break;
5368 case QEMU_OPTION_semihosting:
5369 semihosting_enabled = 1;
5370 break;
5371 case QEMU_OPTION_tdf:
5372 time_drift_fix = 1;
5373 break;
5374 case QEMU_OPTION_kvm_shadow_memory:
5375 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5376 break;
5377 case QEMU_OPTION_mempath:
5378 mem_path = optarg;
5379 break;
5380 case QEMU_OPTION_name:
5381 qemu_name = optarg;
5382 break;
5383 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5384 case QEMU_OPTION_prom_env:
5385 if (nb_prom_envs >= MAX_PROM_ENVS) {
5386 fprintf(stderr, "Too many prom variables\n");
5387 exit(1);
5389 prom_envs[nb_prom_envs] = optarg;
5390 nb_prom_envs++;
5391 break;
5392 #endif
5393 case QEMU_OPTION_cpu_vendor:
5394 cpu_vendor_string = optarg;
5395 break;
5396 #ifdef TARGET_ARM
5397 case QEMU_OPTION_old_param:
5398 old_param = 1;
5399 break;
5400 #endif
5401 case QEMU_OPTION_clock:
5402 configure_alarms(optarg);
5403 break;
5404 case QEMU_OPTION_startdate:
5406 struct tm tm;
5407 time_t rtc_start_date;
5408 if (!strcmp(optarg, "now")) {
5409 rtc_date_offset = -1;
5410 } else {
5411 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5412 &tm.tm_year,
5413 &tm.tm_mon,
5414 &tm.tm_mday,
5415 &tm.tm_hour,
5416 &tm.tm_min,
5417 &tm.tm_sec) == 6) {
5418 /* OK */
5419 } else if (sscanf(optarg, "%d-%d-%d",
5420 &tm.tm_year,
5421 &tm.tm_mon,
5422 &tm.tm_mday) == 3) {
5423 tm.tm_hour = 0;
5424 tm.tm_min = 0;
5425 tm.tm_sec = 0;
5426 } else {
5427 goto date_fail;
5429 tm.tm_year -= 1900;
5430 tm.tm_mon--;
5431 rtc_start_date = mktimegm(&tm);
5432 if (rtc_start_date == -1) {
5433 date_fail:
5434 fprintf(stderr, "Invalid date format. Valid format are:\n"
5435 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5436 exit(1);
5438 rtc_date_offset = time(NULL) - rtc_start_date;
5441 break;
5442 case QEMU_OPTION_tb_size:
5443 tb_size = strtol(optarg, NULL, 0);
5444 if (tb_size < 0)
5445 tb_size = 0;
5446 break;
5447 case QEMU_OPTION_icount:
5448 use_icount = 1;
5449 if (strcmp(optarg, "auto") == 0) {
5450 icount_time_shift = -1;
5451 } else {
5452 icount_time_shift = strtol(optarg, NULL, 0);
5454 break;
5455 case QEMU_OPTION_incoming:
5456 incoming = optarg;
5457 break;
5462 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5463 if (kvm_allowed && kqemu_allowed) {
5464 fprintf(stderr,
5465 "You can not enable both KVM and kqemu at the same time\n");
5466 exit(1);
5468 #endif
5470 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5471 if (smp_cpus > machine->max_cpus) {
5472 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5473 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5474 machine->max_cpus);
5475 exit(1);
5478 if (nographic) {
5479 if (serial_device_index == 0)
5480 serial_devices[0] = "stdio";
5481 if (parallel_device_index == 0)
5482 parallel_devices[0] = "null";
5483 if (strncmp(monitor_device, "vc", 2) == 0)
5484 monitor_device = "stdio";
5487 #ifndef _WIN32
5488 if (daemonize) {
5489 pid_t pid;
5491 if (pipe(fds) == -1)
5492 exit(1);
5494 pid = fork();
5495 if (pid > 0) {
5496 uint8_t status;
5497 ssize_t len;
5499 close(fds[1]);
5501 again:
5502 len = read(fds[0], &status, 1);
5503 if (len == -1 && (errno == EINTR))
5504 goto again;
5506 if (len != 1)
5507 exit(1);
5508 else if (status == 1) {
5509 fprintf(stderr, "Could not acquire pidfile\n");
5510 exit(1);
5511 } else
5512 exit(0);
5513 } else if (pid < 0)
5514 exit(1);
5516 setsid();
5518 pid = fork();
5519 if (pid > 0)
5520 exit(0);
5521 else if (pid < 0)
5522 exit(1);
5524 umask(027);
5526 signal(SIGTSTP, SIG_IGN);
5527 signal(SIGTTOU, SIG_IGN);
5528 signal(SIGTTIN, SIG_IGN);
5530 #endif
5532 #if USE_KVM
5533 if (kvm_enabled()) {
5534 if (kvm_qemu_init() < 0) {
5535 extern int kvm_allowed;
5536 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5537 #ifdef NO_CPU_EMULATION
5538 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5539 exit(1);
5540 #endif
5541 kvm_allowed = 0;
5544 #endif
5546 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5547 if (daemonize) {
5548 uint8_t status = 1;
5549 write(fds[1], &status, 1);
5550 } else
5551 fprintf(stderr, "Could not acquire pid file\n");
5552 exit(1);
5555 #ifdef USE_KQEMU
5556 if (smp_cpus > 1)
5557 kqemu_allowed = 0;
5558 #endif
5559 linux_boot = (kernel_filename != NULL);
5560 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5562 if (!linux_boot && net_boot == 0 &&
5563 !machine->nodisk_ok && nb_drives_opt == 0)
5564 help(1);
5566 if (!linux_boot && *kernel_cmdline != '\0') {
5567 fprintf(stderr, "-append only allowed with -kernel option\n");
5568 exit(1);
5571 if (!linux_boot && initrd_filename != NULL) {
5572 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5573 exit(1);
5576 /* boot to floppy or the default cd if no hard disk defined yet */
5577 if (!boot_devices[0]) {
5578 boot_devices = "cad";
5580 setvbuf(stdout, NULL, _IOLBF, 0);
5582 init_timers();
5583 if (init_timer_alarm() < 0) {
5584 fprintf(stderr, "could not initialize alarm timer\n");
5585 exit(1);
5587 if (use_icount && icount_time_shift < 0) {
5588 use_icount = 2;
5589 /* 125MIPS seems a reasonable initial guess at the guest speed.
5590 It will be corrected fairly quickly anyway. */
5591 icount_time_shift = 3;
5592 init_icount_adjust();
5595 #ifdef _WIN32
5596 socket_init();
5597 #endif
5599 /* init network clients */
5600 if (nb_net_clients == 0) {
5601 /* if no clients, we use a default config */
5602 net_clients[nb_net_clients++] = "nic";
5603 #ifdef CONFIG_SLIRP
5604 net_clients[nb_net_clients++] = "user";
5605 #endif
5608 for(i = 0;i < nb_net_clients; i++) {
5609 if (net_client_parse(net_clients[i]) < 0)
5610 exit(1);
5612 net_client_check();
5614 #ifdef TARGET_I386
5615 /* XXX: this should be moved in the PC machine instantiation code */
5616 if (net_boot != 0) {
5617 int netroms = 0;
5618 for (i = 0; i < nb_nics && i < 4; i++) {
5619 const char *model = nd_table[i].model;
5620 char buf[1024];
5621 if (net_boot & (1 << i)) {
5622 if (model == NULL)
5623 model = "rtl8139";
5624 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5625 if (get_image_size(buf) > 0) {
5626 if (nb_option_roms >= MAX_OPTION_ROMS) {
5627 fprintf(stderr, "Too many option ROMs\n");
5628 exit(1);
5630 option_rom[nb_option_roms] = strdup(buf);
5631 nb_option_roms++;
5632 netroms++;
5636 if (netroms == 0) {
5637 fprintf(stderr, "No valid PXE rom found for network device\n");
5638 exit(1);
5641 #endif
5643 /* init the bluetooth world */
5644 for (i = 0; i < nb_bt_opts; i++)
5645 if (bt_parse(bt_opts[i]))
5646 exit(1);
5648 /* init the memory */
5649 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5651 if (machine->ram_require & RAMSIZE_FIXED) {
5652 if (ram_size > 0) {
5653 if (ram_size < phys_ram_size) {
5654 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5655 machine->name, (unsigned long long) phys_ram_size);
5656 exit(-1);
5659 phys_ram_size = ram_size;
5660 } else
5661 ram_size = phys_ram_size;
5662 } else {
5663 if (ram_size == 0)
5664 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5666 phys_ram_size += ram_size;
5669 /* Initialize kvm */
5670 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5671 #define KVM_EXTRA_PAGES 3
5672 #else
5673 #define KVM_EXTRA_PAGES 0
5674 #endif
5675 if (kvm_enabled()) {
5676 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5677 if (kvm_qemu_create_context() < 0) {
5678 fprintf(stderr, "Could not create KVM context\n");
5679 exit(1);
5683 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5684 if (!phys_ram_base) {
5685 fprintf(stderr, "Could not allocate physical memory\n");
5686 exit(1);
5689 /* init the dynamic translator */
5690 cpu_exec_init_all(tb_size * 1024 * 1024);
5692 bdrv_init();
5694 /* we always create the cdrom drive, even if no disk is there */
5696 if (nb_drives_opt < MAX_DRIVES)
5697 drive_add(NULL, CDROM_ALIAS);
5699 /* we always create at least one floppy */
5701 if (nb_drives_opt < MAX_DRIVES)
5702 drive_add(NULL, FD_ALIAS, 0);
5704 /* we always create one sd slot, even if no card is in it */
5706 if (nb_drives_opt < MAX_DRIVES)
5707 drive_add(NULL, SD_ALIAS);
5709 /* open the virtual block devices
5710 * note that migration with device
5711 * hot add/remove is broken.
5713 for(i = 0; i < nb_drives_opt; i++)
5714 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5715 exit(1);
5717 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5718 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5720 /* terminal init */
5721 memset(&display_state, 0, sizeof(display_state));
5722 if (nographic) {
5723 if (curses) {
5724 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5725 exit(1);
5727 /* nearly nothing to do */
5728 dumb_display_init(ds);
5729 } else if (vnc_display != NULL) {
5730 vnc_display_init(ds);
5731 if (vnc_display_open(ds, vnc_display) < 0)
5732 exit(1);
5733 } else
5734 #if defined(CONFIG_CURSES)
5735 if (curses) {
5736 curses_display_init(ds, full_screen);
5737 } else
5738 #endif
5740 #if defined(CONFIG_SDL)
5741 sdl_display_init(ds, full_screen, no_frame);
5742 #elif defined(CONFIG_COCOA)
5743 cocoa_display_init(ds, full_screen);
5744 #else
5745 dumb_display_init(ds);
5746 #endif
5749 #ifndef _WIN32
5750 /* must be after terminal init, SDL library changes signal handlers */
5751 termsig_setup();
5752 #endif
5754 /* Maintain compatibility with multiple stdio monitors */
5755 if (!strcmp(monitor_device,"stdio")) {
5756 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5757 const char *devname = serial_devices[i];
5758 if (devname && !strcmp(devname,"mon:stdio")) {
5759 monitor_device = NULL;
5760 break;
5761 } else if (devname && !strcmp(devname,"stdio")) {
5762 monitor_device = NULL;
5763 serial_devices[i] = "mon:stdio";
5764 break;
5768 if (monitor_device) {
5769 monitor_hd = qemu_chr_open("monitor", monitor_device);
5770 if (!monitor_hd) {
5771 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5772 exit(1);
5774 monitor_init(monitor_hd, !nographic);
5777 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5778 const char *devname = serial_devices[i];
5779 if (devname && strcmp(devname, "none")) {
5780 char label[32];
5781 snprintf(label, sizeof(label), "serial%d", i);
5782 serial_hds[i] = qemu_chr_open(label, devname);
5783 if (!serial_hds[i]) {
5784 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5785 devname);
5786 exit(1);
5788 if (strstart(devname, "vc", 0))
5789 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5793 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5794 const char *devname = parallel_devices[i];
5795 if (devname && strcmp(devname, "none")) {
5796 char label[32];
5797 snprintf(label, sizeof(label), "parallel%d", i);
5798 parallel_hds[i] = qemu_chr_open(label, devname);
5799 if (!parallel_hds[i]) {
5800 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5801 devname);
5802 exit(1);
5804 if (strstart(devname, "vc", 0))
5805 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5809 if (kvm_enabled())
5810 kvm_init_ap();
5812 #ifdef KVM_UPSTREAM
5813 if (kvm_enabled()) {
5814 int ret;
5816 ret = kvm_init(smp_cpus);
5817 if (ret < 0) {
5818 fprintf(stderr, "failed to initialize KVM\n");
5819 exit(1);
5822 #endif
5824 machine->init(ram_size, vga_ram_size, boot_devices, ds,
5825 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5827 current_machine = machine;
5829 /* Set KVM's vcpu state to qemu's initial CPUState. */
5830 if (kvm_enabled()) {
5831 int ret;
5833 ret = kvm_sync_vcpus();
5834 if (ret < 0) {
5835 fprintf(stderr, "failed to initialize vcpus\n");
5836 exit(1);
5840 /* init USB devices */
5841 if (usb_enabled) {
5842 for(i = 0; i < usb_devices_index; i++) {
5843 if (usb_device_add(usb_devices[i]) < 0) {
5844 fprintf(stderr, "Warning: could not add USB device %s\n",
5845 usb_devices[i]);
5850 if (display_state.dpy_refresh) {
5851 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5852 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5855 #ifdef CONFIG_GDBSTUB
5856 if (use_gdbstub) {
5857 /* XXX: use standard host:port notation and modify options
5858 accordingly. */
5859 if (gdbserver_start(gdbstub_port) < 0) {
5860 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5861 gdbstub_port);
5862 exit(1);
5865 #endif
5867 if (loadvm)
5868 do_loadvm(loadvm);
5870 if (incoming) {
5871 autostart = 0; /* fixme how to deal with -daemonize */
5872 qemu_start_incoming_migration(incoming);
5876 /* XXX: simplify init */
5877 read_passwords();
5878 if (autostart) {
5879 vm_start();
5883 if (daemonize) {
5884 uint8_t status = 0;
5885 ssize_t len;
5886 int fd;
5888 again1:
5889 len = write(fds[1], &status, 1);
5890 if (len == -1 && (errno == EINTR))
5891 goto again1;
5893 if (len != 1)
5894 exit(1);
5896 chdir("/");
5897 TFR(fd = open("/dev/null", O_RDWR));
5898 if (fd == -1)
5899 exit(1);
5901 dup2(fd, 0);
5902 dup2(fd, 1);
5903 dup2(fd, 2);
5905 close(fd);
5908 main_loop();
5909 quit_timers();
5910 net_cleanup();
5912 return 0;