kvm: qemu: provide an option to disable in-kernel PIT int reinjection
[kvm-userspace.git] / qemu / vl.c
blob0d761acfe1446ef366ead3c9280029d417a6b156
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 #ifdef TARGET_SPARC
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 static void bdrv_format_print(void *opaque, const char *name)
2259 fprintf(stderr, " %s", name);
2262 void drive_uninit(BlockDriverState *bdrv)
2264 int i;
2266 for (i = 0; i < MAX_DRIVES; i++)
2267 if (drives_table[i].bdrv == bdrv) {
2268 drives_table[i].bdrv = NULL;
2269 drives_table[i].used = 0;
2270 drive_remove(drives_table[i].drive_opt_idx);
2271 nb_drives--;
2272 break;
2276 int drive_init(struct drive_opt *arg, int snapshot,
2277 QEMUMachine *machine)
2279 char buf[128];
2280 char file[1024];
2281 char devname[128];
2282 const char *mediastr = "";
2283 BlockInterfaceType type;
2284 enum { MEDIA_DISK, MEDIA_CDROM } media;
2285 int bus_id, unit_id;
2286 int cyls, heads, secs, translation;
2287 BlockDriverState *bdrv;
2288 BlockDriver *drv = NULL;
2289 int max_devs;
2290 int index;
2291 int cache;
2292 int bdrv_flags;
2293 int drives_table_idx;
2294 char *str = arg->opt;
2295 static const char * const params[] = { "bus", "unit", "if", "index",
2296 "cyls", "heads", "secs", "trans",
2297 "media", "snapshot", "file",
2298 "cache", "format", "boot", NULL };
2300 if (check_params(buf, sizeof(buf), params, str) < 0) {
2301 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2302 buf, str);
2303 return -1;
2306 file[0] = 0;
2307 cyls = heads = secs = 0;
2308 bus_id = 0;
2309 unit_id = -1;
2310 translation = BIOS_ATA_TRANSLATION_AUTO;
2311 index = -1;
2312 cache = 3;
2314 if (machine->use_scsi) {
2315 type = IF_SCSI;
2316 max_devs = MAX_SCSI_DEVS;
2317 pstrcpy(devname, sizeof(devname), "scsi");
2318 } else {
2319 type = IF_IDE;
2320 max_devs = MAX_IDE_DEVS;
2321 pstrcpy(devname, sizeof(devname), "ide");
2323 media = MEDIA_DISK;
2325 /* extract parameters */
2327 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2328 bus_id = strtol(buf, NULL, 0);
2329 if (bus_id < 0) {
2330 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2331 return -1;
2335 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2336 unit_id = strtol(buf, NULL, 0);
2337 if (unit_id < 0) {
2338 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2339 return -1;
2343 if (get_param_value(buf, sizeof(buf), "if", str)) {
2344 pstrcpy(devname, sizeof(devname), buf);
2345 if (!strcmp(buf, "ide")) {
2346 type = IF_IDE;
2347 max_devs = MAX_IDE_DEVS;
2348 } else if (!strcmp(buf, "scsi")) {
2349 type = IF_SCSI;
2350 max_devs = MAX_SCSI_DEVS;
2351 } else if (!strcmp(buf, "floppy")) {
2352 type = IF_FLOPPY;
2353 max_devs = 0;
2354 } else if (!strcmp(buf, "pflash")) {
2355 type = IF_PFLASH;
2356 max_devs = 0;
2357 } else if (!strcmp(buf, "mtd")) {
2358 type = IF_MTD;
2359 max_devs = 0;
2360 } else if (!strcmp(buf, "sd")) {
2361 type = IF_SD;
2362 max_devs = 0;
2363 } else if (!strcmp(buf, "virtio")) {
2364 type = IF_VIRTIO;
2365 max_devs = 0;
2366 } else {
2367 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2368 return -1;
2372 if (get_param_value(buf, sizeof(buf), "index", str)) {
2373 index = strtol(buf, NULL, 0);
2374 if (index < 0) {
2375 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2376 return -1;
2380 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2381 cyls = strtol(buf, NULL, 0);
2384 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2385 heads = strtol(buf, NULL, 0);
2388 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2389 secs = strtol(buf, NULL, 0);
2392 if (cyls || heads || secs) {
2393 if (cyls < 1 || cyls > 16383) {
2394 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2395 return -1;
2397 if (heads < 1 || heads > 16) {
2398 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2399 return -1;
2401 if (secs < 1 || secs > 63) {
2402 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2403 return -1;
2407 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2408 if (!cyls) {
2409 fprintf(stderr,
2410 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2411 str);
2412 return -1;
2414 if (!strcmp(buf, "none"))
2415 translation = BIOS_ATA_TRANSLATION_NONE;
2416 else if (!strcmp(buf, "lba"))
2417 translation = BIOS_ATA_TRANSLATION_LBA;
2418 else if (!strcmp(buf, "auto"))
2419 translation = BIOS_ATA_TRANSLATION_AUTO;
2420 else {
2421 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2422 return -1;
2426 if (get_param_value(buf, sizeof(buf), "media", str)) {
2427 if (!strcmp(buf, "disk")) {
2428 media = MEDIA_DISK;
2429 } else if (!strcmp(buf, "cdrom")) {
2430 if (cyls || secs || heads) {
2431 fprintf(stderr,
2432 "qemu: '%s' invalid physical CHS format\n", str);
2433 return -1;
2435 media = MEDIA_CDROM;
2436 } else {
2437 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2438 return -1;
2442 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2443 if (!strcmp(buf, "on"))
2444 snapshot = 1;
2445 else if (!strcmp(buf, "off"))
2446 snapshot = 0;
2447 else {
2448 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2449 return -1;
2453 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2454 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2455 cache = 0;
2456 else if (!strcmp(buf, "writethrough"))
2457 cache = 1;
2458 else if (!strcmp(buf, "writeback"))
2459 cache = 2;
2460 else {
2461 fprintf(stderr, "qemu: invalid cache option\n");
2462 return -1;
2466 if (get_param_value(buf, sizeof(buf), "format", str)) {
2467 if (strcmp(buf, "?") == 0) {
2468 fprintf(stderr, "qemu: Supported formats:");
2469 bdrv_iterate_format(bdrv_format_print, NULL);
2470 fprintf(stderr, "\n");
2471 return -1;
2473 drv = bdrv_find_format(buf);
2474 if (!drv) {
2475 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2476 return -1;
2480 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2481 if (!strcmp(buf, "on")) {
2482 if (extboot_drive != -1) {
2483 fprintf(stderr, "qemu: two bootable drives specified\n");
2484 return -1;
2486 extboot_drive = nb_drives;
2487 } else if (strcmp(buf, "off")) {
2488 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2489 return -1;
2493 if (arg->file == NULL)
2494 get_param_value(file, sizeof(file), "file", str);
2495 else
2496 pstrcpy(file, sizeof(file), arg->file);
2498 /* compute bus and unit according index */
2500 if (index != -1) {
2501 if (bus_id != 0 || unit_id != -1) {
2502 fprintf(stderr,
2503 "qemu: '%s' index cannot be used with bus and unit\n", str);
2504 return -1;
2506 if (max_devs == 0)
2508 unit_id = index;
2509 bus_id = 0;
2510 } else {
2511 unit_id = index % max_devs;
2512 bus_id = index / max_devs;
2516 /* if user doesn't specify a unit_id,
2517 * try to find the first free
2520 if (unit_id == -1) {
2521 unit_id = 0;
2522 while (drive_get_index(type, bus_id, unit_id) != -1) {
2523 unit_id++;
2524 if (max_devs && unit_id >= max_devs) {
2525 unit_id -= max_devs;
2526 bus_id++;
2531 /* check unit id */
2533 if (max_devs && unit_id >= max_devs) {
2534 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2535 str, unit_id, max_devs - 1);
2536 return -1;
2540 * ignore multiple definitions
2543 if (drive_get_index(type, bus_id, unit_id) != -1)
2544 return -2;
2546 /* init */
2548 if (type == IF_IDE || type == IF_SCSI)
2549 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2550 if (max_devs)
2551 snprintf(buf, sizeof(buf), "%s%i%s%i",
2552 devname, bus_id, mediastr, unit_id);
2553 else
2554 snprintf(buf, sizeof(buf), "%s%s%i",
2555 devname, mediastr, unit_id);
2556 bdrv = bdrv_new(buf);
2557 drives_table_idx = drive_get_free_idx();
2558 drives_table[drives_table_idx].bdrv = bdrv;
2559 drives_table[drives_table_idx].type = type;
2560 drives_table[drives_table_idx].bus = bus_id;
2561 drives_table[drives_table_idx].unit = unit_id;
2562 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2563 nb_drives++;
2565 switch(type) {
2566 case IF_IDE:
2567 case IF_SCSI:
2568 switch(media) {
2569 case MEDIA_DISK:
2570 if (cyls != 0) {
2571 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2572 bdrv_set_translation_hint(bdrv, translation);
2574 break;
2575 case MEDIA_CDROM:
2576 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2577 break;
2579 break;
2580 case IF_SD:
2581 /* FIXME: This isn't really a floppy, but it's a reasonable
2582 approximation. */
2583 case IF_FLOPPY:
2584 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2585 break;
2586 case IF_PFLASH:
2587 case IF_MTD:
2588 case IF_VIRTIO:
2589 break;
2591 if (!file[0])
2592 return -2;
2593 bdrv_flags = 0;
2594 if (snapshot) {
2595 bdrv_flags |= BDRV_O_SNAPSHOT;
2596 cache = 2; /* always use write-back with snapshot */
2598 if (cache == 0) /* no caching */
2599 bdrv_flags |= BDRV_O_NOCACHE;
2600 else if (cache == 2) /* write-back */
2601 bdrv_flags |= BDRV_O_CACHE_WB;
2602 else if (cache == 3) /* not specified */
2603 bdrv_flags |= BDRV_O_CACHE_DEF;
2604 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2605 fprintf(stderr, "qemu: could not open disk image %s\n",
2606 file);
2607 return -1;
2609 return drives_table_idx;
2612 /***********************************************************/
2613 /* USB devices */
2615 static USBPort *used_usb_ports;
2616 static USBPort *free_usb_ports;
2618 /* ??? Maybe change this to register a hub to keep track of the topology. */
2619 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2620 usb_attachfn attach)
2622 port->opaque = opaque;
2623 port->index = index;
2624 port->attach = attach;
2625 port->next = free_usb_ports;
2626 free_usb_ports = port;
2629 int usb_device_add_dev(USBDevice *dev)
2631 USBPort *port;
2633 /* Find a USB port to add the device to. */
2634 port = free_usb_ports;
2635 if (!port->next) {
2636 USBDevice *hub;
2638 /* Create a new hub and chain it on. */
2639 free_usb_ports = NULL;
2640 port->next = used_usb_ports;
2641 used_usb_ports = port;
2643 hub = usb_hub_init(VM_USB_HUB_SIZE);
2644 usb_attach(port, hub);
2645 port = free_usb_ports;
2648 free_usb_ports = port->next;
2649 port->next = used_usb_ports;
2650 used_usb_ports = port;
2651 usb_attach(port, dev);
2652 return 0;
2655 static int usb_device_add(const char *devname)
2657 const char *p;
2658 USBDevice *dev;
2660 if (!free_usb_ports)
2661 return -1;
2663 if (strstart(devname, "host:", &p)) {
2664 dev = usb_host_device_open(p);
2665 } else if (!strcmp(devname, "mouse")) {
2666 dev = usb_mouse_init();
2667 } else if (!strcmp(devname, "tablet")) {
2668 dev = usb_tablet_init();
2669 } else if (!strcmp(devname, "keyboard")) {
2670 dev = usb_keyboard_init();
2671 } else if (strstart(devname, "disk:", &p)) {
2672 dev = usb_msd_init(p);
2673 } else if (!strcmp(devname, "wacom-tablet")) {
2674 dev = usb_wacom_init();
2675 } else if (strstart(devname, "serial:", &p)) {
2676 dev = usb_serial_init(p);
2677 #ifdef CONFIG_BRLAPI
2678 } else if (!strcmp(devname, "braille")) {
2679 dev = usb_baum_init();
2680 #endif
2681 } else if (strstart(devname, "net:", &p)) {
2682 int nic = nb_nics;
2684 if (net_client_init("nic", p) < 0)
2685 return -1;
2686 nd_table[nic].model = "usb";
2687 dev = usb_net_init(&nd_table[nic]);
2688 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2689 dev = usb_bt_init(devname[2] ? hci_init(p) :
2690 bt_new_hci(qemu_find_bt_vlan(0)));
2691 } else {
2692 return -1;
2694 if (!dev)
2695 return -1;
2697 return usb_device_add_dev(dev);
2700 int usb_device_del_addr(int bus_num, int addr)
2702 USBPort *port;
2703 USBPort **lastp;
2704 USBDevice *dev;
2706 if (!used_usb_ports)
2707 return -1;
2709 if (bus_num != 0)
2710 return -1;
2712 lastp = &used_usb_ports;
2713 port = used_usb_ports;
2714 while (port && port->dev->addr != addr) {
2715 lastp = &port->next;
2716 port = port->next;
2719 if (!port)
2720 return -1;
2722 dev = port->dev;
2723 *lastp = port->next;
2724 usb_attach(port, NULL);
2725 dev->handle_destroy(dev);
2726 port->next = free_usb_ports;
2727 free_usb_ports = port;
2728 return 0;
2731 static int usb_device_del(const char *devname)
2733 int bus_num, addr;
2734 const char *p;
2736 if (strstart(devname, "host:", &p))
2737 return usb_host_device_close(p);
2739 if (!used_usb_ports)
2740 return -1;
2742 p = strchr(devname, '.');
2743 if (!p)
2744 return -1;
2745 bus_num = strtoul(devname, NULL, 0);
2746 addr = strtoul(p + 1, NULL, 0);
2748 return usb_device_del_addr(bus_num, addr);
2751 void do_usb_add(const char *devname)
2753 usb_device_add(devname);
2756 void do_usb_del(const char *devname)
2758 usb_device_del(devname);
2761 void usb_info(void)
2763 USBDevice *dev;
2764 USBPort *port;
2765 const char *speed_str;
2767 if (!usb_enabled) {
2768 term_printf("USB support not enabled\n");
2769 return;
2772 for (port = used_usb_ports; port; port = port->next) {
2773 dev = port->dev;
2774 if (!dev)
2775 continue;
2776 switch(dev->speed) {
2777 case USB_SPEED_LOW:
2778 speed_str = "1.5";
2779 break;
2780 case USB_SPEED_FULL:
2781 speed_str = "12";
2782 break;
2783 case USB_SPEED_HIGH:
2784 speed_str = "480";
2785 break;
2786 default:
2787 speed_str = "?";
2788 break;
2790 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2791 0, dev->addr, speed_str, dev->devname);
2795 /***********************************************************/
2796 /* PCMCIA/Cardbus */
2798 static struct pcmcia_socket_entry_s {
2799 struct pcmcia_socket_s *socket;
2800 struct pcmcia_socket_entry_s *next;
2801 } *pcmcia_sockets = 0;
2803 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2805 struct pcmcia_socket_entry_s *entry;
2807 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2808 entry->socket = socket;
2809 entry->next = pcmcia_sockets;
2810 pcmcia_sockets = entry;
2813 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2815 struct pcmcia_socket_entry_s *entry, **ptr;
2817 ptr = &pcmcia_sockets;
2818 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2819 if (entry->socket == socket) {
2820 *ptr = entry->next;
2821 qemu_free(entry);
2825 void pcmcia_info(void)
2827 struct pcmcia_socket_entry_s *iter;
2828 if (!pcmcia_sockets)
2829 term_printf("No PCMCIA sockets\n");
2831 for (iter = pcmcia_sockets; iter; iter = iter->next)
2832 term_printf("%s: %s\n", iter->socket->slot_string,
2833 iter->socket->attached ? iter->socket->card_string :
2834 "Empty");
2837 /***********************************************************/
2838 /* dumb display */
2840 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2844 static void dumb_resize(DisplayState *ds, int w, int h)
2848 static void dumb_display_init(DisplayState *ds)
2850 ds->data = NULL;
2851 ds->linesize = 0;
2852 ds->depth = 0;
2853 ds->dpy_update = dumb_update;
2854 ds->dpy_resize = dumb_resize;
2855 ds->dpy_refresh = NULL;
2856 ds->gui_timer_interval = 0;
2857 ds->idle = 1;
2860 /***********************************************************/
2861 /* I/O handling */
2863 #define MAX_IO_HANDLERS 64
2865 typedef struct IOHandlerRecord {
2866 int fd;
2867 IOCanRWHandler *fd_read_poll;
2868 IOHandler *fd_read;
2869 IOHandler *fd_write;
2870 int deleted;
2871 void *opaque;
2872 /* temporary data */
2873 struct pollfd *ufd;
2874 struct IOHandlerRecord *next;
2875 } IOHandlerRecord;
2877 static IOHandlerRecord *first_io_handler;
2879 /* XXX: fd_read_poll should be suppressed, but an API change is
2880 necessary in the character devices to suppress fd_can_read(). */
2881 int qemu_set_fd_handler2(int fd,
2882 IOCanRWHandler *fd_read_poll,
2883 IOHandler *fd_read,
2884 IOHandler *fd_write,
2885 void *opaque)
2887 IOHandlerRecord **pioh, *ioh;
2889 if (!fd_read && !fd_write) {
2890 pioh = &first_io_handler;
2891 for(;;) {
2892 ioh = *pioh;
2893 if (ioh == NULL)
2894 break;
2895 if (ioh->fd == fd) {
2896 ioh->deleted = 1;
2897 break;
2899 pioh = &ioh->next;
2901 } else {
2902 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2903 if (ioh->fd == fd)
2904 goto found;
2906 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2907 if (!ioh)
2908 return -1;
2909 ioh->next = first_io_handler;
2910 first_io_handler = ioh;
2911 found:
2912 ioh->fd = fd;
2913 ioh->fd_read_poll = fd_read_poll;
2914 ioh->fd_read = fd_read;
2915 ioh->fd_write = fd_write;
2916 ioh->opaque = opaque;
2917 ioh->deleted = 0;
2919 main_loop_break();
2920 return 0;
2923 int qemu_set_fd_handler(int fd,
2924 IOHandler *fd_read,
2925 IOHandler *fd_write,
2926 void *opaque)
2928 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2931 #ifdef _WIN32
2932 /***********************************************************/
2933 /* Polling handling */
2935 typedef struct PollingEntry {
2936 PollingFunc *func;
2937 void *opaque;
2938 struct PollingEntry *next;
2939 } PollingEntry;
2941 static PollingEntry *first_polling_entry;
2943 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2945 PollingEntry **ppe, *pe;
2946 pe = qemu_mallocz(sizeof(PollingEntry));
2947 if (!pe)
2948 return -1;
2949 pe->func = func;
2950 pe->opaque = opaque;
2951 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2952 *ppe = pe;
2953 return 0;
2956 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2958 PollingEntry **ppe, *pe;
2959 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2960 pe = *ppe;
2961 if (pe->func == func && pe->opaque == opaque) {
2962 *ppe = pe->next;
2963 qemu_free(pe);
2964 break;
2969 /***********************************************************/
2970 /* Wait objects support */
2971 typedef struct WaitObjects {
2972 int num;
2973 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2974 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2975 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2976 } WaitObjects;
2978 static WaitObjects wait_objects = {0};
2980 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2982 WaitObjects *w = &wait_objects;
2984 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2985 return -1;
2986 w->events[w->num] = handle;
2987 w->func[w->num] = func;
2988 w->opaque[w->num] = opaque;
2989 w->num++;
2990 return 0;
2993 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2995 int i, found;
2996 WaitObjects *w = &wait_objects;
2998 found = 0;
2999 for (i = 0; i < w->num; i++) {
3000 if (w->events[i] == handle)
3001 found = 1;
3002 if (found) {
3003 w->events[i] = w->events[i + 1];
3004 w->func[i] = w->func[i + 1];
3005 w->opaque[i] = w->opaque[i + 1];
3008 if (found)
3009 w->num--;
3011 #endif
3013 /***********************************************************/
3014 /* ram save/restore */
3016 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3018 int v;
3020 v = qemu_get_byte(f);
3021 switch(v) {
3022 case 0:
3023 if (qemu_get_buffer(f, buf, len) != len)
3024 return -EIO;
3025 break;
3026 case 1:
3027 v = qemu_get_byte(f);
3028 memset(buf, v, len);
3029 break;
3030 default:
3031 return -EINVAL;
3034 if (qemu_file_has_error(f))
3035 return -EIO;
3037 return 0;
3040 static int ram_load_v1(QEMUFile *f, void *opaque)
3042 int ret;
3043 ram_addr_t i;
3045 if (qemu_get_be32(f) != phys_ram_size)
3046 return -EINVAL;
3047 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3048 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3049 continue;
3050 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3051 if (ret)
3052 return ret;
3054 return 0;
3057 #define BDRV_HASH_BLOCK_SIZE 1024
3058 #define IOBUF_SIZE 4096
3059 #define RAM_CBLOCK_MAGIC 0xfabe
3061 typedef struct RamDecompressState {
3062 z_stream zstream;
3063 QEMUFile *f;
3064 uint8_t buf[IOBUF_SIZE];
3065 } RamDecompressState;
3067 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3069 int ret;
3070 memset(s, 0, sizeof(*s));
3071 s->f = f;
3072 ret = inflateInit(&s->zstream);
3073 if (ret != Z_OK)
3074 return -1;
3075 return 0;
3078 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3080 int ret, clen;
3082 s->zstream.avail_out = len;
3083 s->zstream.next_out = buf;
3084 while (s->zstream.avail_out > 0) {
3085 if (s->zstream.avail_in == 0) {
3086 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3087 return -1;
3088 clen = qemu_get_be16(s->f);
3089 if (clen > IOBUF_SIZE)
3090 return -1;
3091 qemu_get_buffer(s->f, s->buf, clen);
3092 s->zstream.avail_in = clen;
3093 s->zstream.next_in = s->buf;
3095 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3096 if (ret != Z_OK && ret != Z_STREAM_END) {
3097 return -1;
3100 return 0;
3103 static void ram_decompress_close(RamDecompressState *s)
3105 inflateEnd(&s->zstream);
3108 #define RAM_SAVE_FLAG_FULL 0x01
3109 #define RAM_SAVE_FLAG_COMPRESS 0x02
3110 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3111 #define RAM_SAVE_FLAG_PAGE 0x08
3112 #define RAM_SAVE_FLAG_EOS 0x10
3114 static int is_dup_page(uint8_t *page, uint8_t ch)
3116 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3117 uint32_t *array = (uint32_t *)page;
3118 int i;
3120 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3121 if (array[i] != val)
3122 return 0;
3125 return 1;
3128 static int ram_save_block(QEMUFile *f)
3130 static ram_addr_t current_addr = 0;
3131 ram_addr_t saved_addr = current_addr;
3132 ram_addr_t addr = 0;
3133 int found = 0;
3135 while (addr < phys_ram_size) {
3136 if (kvm_enabled() && current_addr == 0)
3137 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3138 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3139 uint8_t ch;
3141 cpu_physical_memory_reset_dirty(current_addr,
3142 current_addr + TARGET_PAGE_SIZE,
3143 MIGRATION_DIRTY_FLAG);
3145 ch = *(phys_ram_base + current_addr);
3147 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3148 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3149 qemu_put_byte(f, ch);
3150 } else {
3151 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3152 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3155 found = 1;
3156 break;
3158 addr += TARGET_PAGE_SIZE;
3159 current_addr = (saved_addr + addr) % phys_ram_size;
3162 return found;
3165 static ram_addr_t ram_save_threshold = 10;
3167 static ram_addr_t ram_save_remaining(void)
3169 ram_addr_t addr;
3170 ram_addr_t count = 0;
3172 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3173 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3174 count++;
3177 return count;
3180 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3182 ram_addr_t addr;
3184 if (stage == 1) {
3185 /* Make sure all dirty bits are set */
3186 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3187 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3188 cpu_physical_memory_set_dirty(addr);
3191 /* Enable dirty memory tracking */
3192 cpu_physical_memory_set_dirty_tracking(1);
3194 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3197 while (!qemu_file_rate_limit(f)) {
3198 int ret;
3200 ret = ram_save_block(f);
3201 if (ret == 0) /* no more blocks */
3202 break;
3205 /* try transferring iterative blocks of memory */
3207 if (stage == 3) {
3208 cpu_physical_memory_set_dirty_tracking(0);
3210 /* flush all remaining blocks regardless of rate limiting */
3211 while (ram_save_block(f) != 0);
3214 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3216 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3219 static int ram_load_dead(QEMUFile *f, void *opaque)
3221 RamDecompressState s1, *s = &s1;
3222 uint8_t buf[10];
3223 ram_addr_t i;
3225 if (ram_decompress_open(s, f) < 0)
3226 return -EINVAL;
3227 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3228 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3229 continue;
3230 if (ram_decompress_buf(s, buf, 1) < 0) {
3231 fprintf(stderr, "Error while reading ram block header\n");
3232 goto error;
3234 if (buf[0] == 0) {
3235 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3236 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3237 goto error;
3239 } else {
3240 error:
3241 printf("Error block header\n");
3242 return -EINVAL;
3245 ram_decompress_close(s);
3247 return 0;
3250 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3252 ram_addr_t addr;
3253 int flags;
3255 if (version_id == 1)
3256 return ram_load_v1(f, opaque);
3258 if (version_id == 2) {
3259 if (qemu_get_be32(f) != phys_ram_size)
3260 return -EINVAL;
3261 return ram_load_dead(f, opaque);
3264 if (version_id != 3)
3265 return -EINVAL;
3267 do {
3268 addr = qemu_get_be64(f);
3270 flags = addr & ~TARGET_PAGE_MASK;
3271 addr &= TARGET_PAGE_MASK;
3273 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3274 if (addr != phys_ram_size)
3275 return -EINVAL;
3278 if (flags & RAM_SAVE_FLAG_FULL) {
3279 if (ram_load_dead(f, opaque) < 0)
3280 return -EINVAL;
3283 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3284 uint8_t ch = qemu_get_byte(f);
3285 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3286 } else if (flags & RAM_SAVE_FLAG_PAGE)
3287 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3288 } while (!(flags & RAM_SAVE_FLAG_EOS));
3290 return 0;
3293 /***********************************************************/
3294 /* bottom halves (can be seen as timers which expire ASAP) */
3296 struct QEMUBH {
3297 QEMUBHFunc *cb;
3298 void *opaque;
3299 int scheduled;
3300 int idle;
3301 int deleted;
3302 QEMUBH *next;
3305 static QEMUBH *first_bh = NULL;
3307 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3309 QEMUBH *bh;
3310 bh = qemu_mallocz(sizeof(QEMUBH));
3311 if (!bh)
3312 return NULL;
3313 bh->cb = cb;
3314 bh->opaque = opaque;
3315 bh->next = first_bh;
3316 first_bh = bh;
3317 return bh;
3320 int qemu_bh_poll(void)
3322 QEMUBH *bh, **bhp;
3323 int ret;
3325 ret = 0;
3326 for (bh = first_bh; bh; bh = bh->next) {
3327 if (!bh->deleted && bh->scheduled) {
3328 bh->scheduled = 0;
3329 if (!bh->idle)
3330 ret = 1;
3331 bh->idle = 0;
3332 bh->cb(bh->opaque);
3336 /* remove deleted bhs */
3337 bhp = &first_bh;
3338 while (*bhp) {
3339 bh = *bhp;
3340 if (bh->deleted) {
3341 *bhp = bh->next;
3342 qemu_free(bh);
3343 } else
3344 bhp = &bh->next;
3347 return ret;
3350 void qemu_bh_schedule_idle(QEMUBH *bh)
3352 if (bh->scheduled)
3353 return;
3354 bh->scheduled = 1;
3355 bh->idle = 1;
3358 void qemu_bh_schedule(QEMUBH *bh)
3360 CPUState *env = cpu_single_env;
3361 if (bh->scheduled)
3362 return;
3363 bh->scheduled = 1;
3364 bh->idle = 0;
3365 /* stop the currently executing CPU to execute the BH ASAP */
3366 if (env) {
3367 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3369 main_loop_break();
3372 void qemu_bh_cancel(QEMUBH *bh)
3374 bh->scheduled = 0;
3377 void qemu_bh_delete(QEMUBH *bh)
3379 bh->scheduled = 0;
3380 bh->deleted = 1;
3383 static void qemu_bh_update_timeout(int *timeout)
3385 QEMUBH *bh;
3387 for (bh = first_bh; bh; bh = bh->next) {
3388 if (!bh->deleted && bh->scheduled) {
3389 if (bh->idle) {
3390 /* idle bottom halves will be polled at least
3391 * every 10ms */
3392 *timeout = MIN(10, *timeout);
3393 } else {
3394 /* non-idle bottom halves will be executed
3395 * immediately */
3396 *timeout = 0;
3397 break;
3403 /***********************************************************/
3404 /* machine registration */
3406 static QEMUMachine *first_machine = NULL;
3407 QEMUMachine *current_machine = NULL;
3409 int qemu_register_machine(QEMUMachine *m)
3411 QEMUMachine **pm;
3412 pm = &first_machine;
3413 while (*pm != NULL)
3414 pm = &(*pm)->next;
3415 m->next = NULL;
3416 *pm = m;
3417 return 0;
3420 static QEMUMachine *find_machine(const char *name)
3422 QEMUMachine *m;
3424 for(m = first_machine; m != NULL; m = m->next) {
3425 if (!strcmp(m->name, name))
3426 return m;
3428 return NULL;
3431 /***********************************************************/
3432 /* main execution loop */
3434 static void gui_update(void *opaque)
3436 DisplayState *ds = opaque;
3437 ds->dpy_refresh(ds);
3438 qemu_mod_timer(ds->gui_timer,
3439 (ds->gui_timer_interval ?
3440 ds->gui_timer_interval :
3441 GUI_REFRESH_INTERVAL)
3442 + qemu_get_clock(rt_clock));
3445 struct vm_change_state_entry {
3446 VMChangeStateHandler *cb;
3447 void *opaque;
3448 LIST_ENTRY (vm_change_state_entry) entries;
3451 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3453 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3454 void *opaque)
3456 VMChangeStateEntry *e;
3458 e = qemu_mallocz(sizeof (*e));
3459 if (!e)
3460 return NULL;
3462 e->cb = cb;
3463 e->opaque = opaque;
3464 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3465 return e;
3468 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3470 LIST_REMOVE (e, entries);
3471 qemu_free (e);
3474 static void vm_state_notify(int running)
3476 VMChangeStateEntry *e;
3478 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3479 e->cb(e->opaque, running);
3483 /* XXX: support several handlers */
3484 static VMStopHandler *vm_stop_cb;
3485 static void *vm_stop_opaque;
3487 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3489 vm_stop_cb = cb;
3490 vm_stop_opaque = opaque;
3491 return 0;
3494 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3496 vm_stop_cb = NULL;
3499 void vm_start(void)
3501 if (!vm_running) {
3502 cpu_enable_ticks();
3503 vm_running = 1;
3504 vm_state_notify(1);
3505 qemu_rearm_alarm_timer(alarm_timer);
3509 void vm_stop(int reason)
3511 if (vm_running) {
3512 cpu_disable_ticks();
3513 vm_running = 0;
3514 if (reason != 0) {
3515 if (vm_stop_cb) {
3516 vm_stop_cb(vm_stop_opaque, reason);
3519 vm_state_notify(0);
3523 /* reset/shutdown handler */
3525 typedef struct QEMUResetEntry {
3526 QEMUResetHandler *func;
3527 void *opaque;
3528 struct QEMUResetEntry *next;
3529 } QEMUResetEntry;
3531 static QEMUResetEntry *first_reset_entry;
3532 static int reset_requested;
3533 static int shutdown_requested;
3534 static int powerdown_requested;
3536 int qemu_shutdown_requested(void)
3538 int r = shutdown_requested;
3539 shutdown_requested = 0;
3540 return r;
3543 int qemu_reset_requested(void)
3545 int r = reset_requested;
3546 reset_requested = 0;
3547 return r;
3550 int qemu_powerdown_requested(void)
3552 int r = powerdown_requested;
3553 powerdown_requested = 0;
3554 return r;
3557 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3559 QEMUResetEntry **pre, *re;
3561 pre = &first_reset_entry;
3562 while (*pre != NULL)
3563 pre = &(*pre)->next;
3564 re = qemu_mallocz(sizeof(QEMUResetEntry));
3565 re->func = func;
3566 re->opaque = opaque;
3567 re->next = NULL;
3568 *pre = re;
3571 void qemu_system_reset(void)
3573 QEMUResetEntry *re;
3575 /* reset all devices */
3576 for(re = first_reset_entry; re != NULL; re = re->next) {
3577 re->func(re->opaque);
3581 void qemu_system_reset_request(void)
3583 if (no_reboot) {
3584 shutdown_requested = 1;
3585 } else {
3586 reset_requested = 1;
3589 if (cpu_single_env) {
3590 qemu_kvm_cpu_stop(cpu_single_env);
3591 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3593 main_loop_break();
3596 void qemu_system_shutdown_request(void)
3598 shutdown_requested = 1;
3599 if (cpu_single_env)
3600 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3603 void qemu_system_powerdown_request(void)
3605 powerdown_requested = 1;
3606 if (cpu_single_env)
3607 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3610 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3611 struct timeval *tv)
3613 int ret;
3615 /* KVM holds a mutex while QEMU code is running, we need hooks to
3616 release the mutex whenever QEMU code sleeps. */
3618 kvm_sleep_begin();
3620 ret = select(max_fd, rfds, wfds, xfds, tv);
3622 kvm_sleep_end();
3624 return ret;
3627 #ifdef _WIN32
3628 static void host_main_loop_wait(int *timeout)
3630 int ret, ret2, i;
3631 PollingEntry *pe;
3634 /* XXX: need to suppress polling by better using win32 events */
3635 ret = 0;
3636 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3637 ret |= pe->func(pe->opaque);
3639 if (ret == 0) {
3640 int err;
3641 WaitObjects *w = &wait_objects;
3643 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3644 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3645 if (w->func[ret - WAIT_OBJECT_0])
3646 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3648 /* Check for additional signaled events */
3649 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3651 /* Check if event is signaled */
3652 ret2 = WaitForSingleObject(w->events[i], 0);
3653 if(ret2 == WAIT_OBJECT_0) {
3654 if (w->func[i])
3655 w->func[i](w->opaque[i]);
3656 } else if (ret2 == WAIT_TIMEOUT) {
3657 } else {
3658 err = GetLastError();
3659 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3662 } else if (ret == WAIT_TIMEOUT) {
3663 } else {
3664 err = GetLastError();
3665 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3669 *timeout = 0;
3671 #else
3672 static void host_main_loop_wait(int *timeout)
3675 #endif
3677 void main_loop_wait(int timeout)
3679 IOHandlerRecord *ioh;
3680 fd_set rfds, wfds, xfds;
3681 int ret, nfds;
3682 struct timeval tv;
3684 qemu_bh_update_timeout(&timeout);
3686 host_main_loop_wait(&timeout);
3688 /* poll any events */
3689 /* XXX: separate device handlers from system ones */
3690 nfds = -1;
3691 FD_ZERO(&rfds);
3692 FD_ZERO(&wfds);
3693 FD_ZERO(&xfds);
3694 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3695 if (ioh->deleted)
3696 continue;
3697 if (ioh->fd_read &&
3698 (!ioh->fd_read_poll ||
3699 ioh->fd_read_poll(ioh->opaque) != 0)) {
3700 FD_SET(ioh->fd, &rfds);
3701 if (ioh->fd > nfds)
3702 nfds = ioh->fd;
3704 if (ioh->fd_write) {
3705 FD_SET(ioh->fd, &wfds);
3706 if (ioh->fd > nfds)
3707 nfds = ioh->fd;
3711 tv.tv_sec = timeout / 1000;
3712 tv.tv_usec = (timeout % 1000) * 1000;
3714 #if defined(CONFIG_SLIRP)
3715 if (slirp_is_inited()) {
3716 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3718 #endif
3719 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3720 if (ret > 0) {
3721 IOHandlerRecord **pioh;
3723 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3724 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3725 ioh->fd_read(ioh->opaque);
3726 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3727 FD_CLR(ioh->fd, &rfds);
3729 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3730 ioh->fd_write(ioh->opaque);
3734 /* remove deleted IO handlers */
3735 pioh = &first_io_handler;
3736 while (*pioh) {
3737 ioh = *pioh;
3738 if (ioh->deleted) {
3739 *pioh = ioh->next;
3740 qemu_free(ioh);
3741 } else
3742 pioh = &ioh->next;
3745 #if defined(CONFIG_SLIRP)
3746 if (slirp_is_inited()) {
3747 if (ret < 0) {
3748 FD_ZERO(&rfds);
3749 FD_ZERO(&wfds);
3750 FD_ZERO(&xfds);
3752 slirp_select_poll(&rfds, &wfds, &xfds);
3754 #endif
3756 /* vm time timers */
3757 if (vm_running && (!cur_cpu
3758 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3759 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3760 qemu_get_clock(vm_clock));
3762 /* real time timers */
3763 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3764 qemu_get_clock(rt_clock));
3766 /* Check bottom-halves last in case any of the earlier events triggered
3767 them. */
3768 qemu_bh_poll();
3772 static int main_loop(void)
3774 int ret, timeout;
3775 #ifdef CONFIG_PROFILER
3776 int64_t ti;
3777 #endif
3778 CPUState *env;
3781 if (kvm_enabled()) {
3782 kvm_main_loop();
3783 cpu_disable_ticks();
3784 return 0;
3787 cur_cpu = first_cpu;
3788 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3789 for(;;) {
3790 if (vm_running) {
3792 for(;;) {
3793 /* get next cpu */
3794 env = next_cpu;
3795 #ifdef CONFIG_PROFILER
3796 ti = profile_getclock();
3797 #endif
3798 if (use_icount) {
3799 int64_t count;
3800 int decr;
3801 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3802 env->icount_decr.u16.low = 0;
3803 env->icount_extra = 0;
3804 count = qemu_next_deadline();
3805 count = (count + (1 << icount_time_shift) - 1)
3806 >> icount_time_shift;
3807 qemu_icount += count;
3808 decr = (count > 0xffff) ? 0xffff : count;
3809 count -= decr;
3810 env->icount_decr.u16.low = decr;
3811 env->icount_extra = count;
3813 ret = cpu_exec(env);
3814 #ifdef CONFIG_PROFILER
3815 qemu_time += profile_getclock() - ti;
3816 #endif
3817 if (use_icount) {
3818 /* Fold pending instructions back into the
3819 instruction counter, and clear the interrupt flag. */
3820 qemu_icount -= (env->icount_decr.u16.low
3821 + env->icount_extra);
3822 env->icount_decr.u32 = 0;
3823 env->icount_extra = 0;
3825 next_cpu = env->next_cpu ?: first_cpu;
3826 if (event_pending && likely(ret != EXCP_DEBUG)) {
3827 ret = EXCP_INTERRUPT;
3828 event_pending = 0;
3829 break;
3831 if (ret == EXCP_HLT) {
3832 /* Give the next CPU a chance to run. */
3833 cur_cpu = env;
3834 continue;
3836 if (ret != EXCP_HALTED)
3837 break;
3838 /* all CPUs are halted ? */
3839 if (env == cur_cpu)
3840 break;
3842 cur_cpu = env;
3844 if (shutdown_requested) {
3845 ret = EXCP_INTERRUPT;
3846 if (no_shutdown) {
3847 vm_stop(0);
3848 no_shutdown = 0;
3850 else
3851 break;
3853 if (reset_requested) {
3854 reset_requested = 0;
3855 qemu_system_reset();
3856 if (kvm_enabled())
3857 kvm_load_registers(env);
3858 ret = EXCP_INTERRUPT;
3860 if (powerdown_requested) {
3861 powerdown_requested = 0;
3862 qemu_system_powerdown();
3863 ret = EXCP_INTERRUPT;
3865 #ifdef CONFIG_GDBSTUB
3866 if (unlikely(ret == EXCP_DEBUG)) {
3867 gdb_set_stop_cpu(cur_cpu);
3868 vm_stop(EXCP_DEBUG);
3870 #endif
3871 /* If all cpus are halted then wait until the next IRQ */
3872 /* XXX: use timeout computed from timers */
3873 if (ret == EXCP_HALTED) {
3874 if (use_icount) {
3875 int64_t add;
3876 int64_t delta;
3877 /* Advance virtual time to the next event. */
3878 if (use_icount == 1) {
3879 /* When not using an adaptive execution frequency
3880 we tend to get badly out of sync with real time,
3881 so just delay for a reasonable amount of time. */
3882 delta = 0;
3883 } else {
3884 delta = cpu_get_icount() - cpu_get_clock();
3886 if (delta > 0) {
3887 /* If virtual time is ahead of real time then just
3888 wait for IO. */
3889 timeout = (delta / 1000000) + 1;
3890 } else {
3891 /* Wait for either IO to occur or the next
3892 timer event. */
3893 add = qemu_next_deadline();
3894 /* We advance the timer before checking for IO.
3895 Limit the amount we advance so that early IO
3896 activity won't get the guest too far ahead. */
3897 if (add > 10000000)
3898 add = 10000000;
3899 delta += add;
3900 add = (add + (1 << icount_time_shift) - 1)
3901 >> icount_time_shift;
3902 qemu_icount += add;
3903 timeout = delta / 1000000;
3904 if (timeout < 0)
3905 timeout = 0;
3907 } else {
3908 timeout = 5000;
3910 } else {
3911 timeout = 0;
3913 } else {
3914 if (shutdown_requested) {
3915 ret = EXCP_INTERRUPT;
3916 break;
3918 timeout = 5000;
3920 #ifdef CONFIG_PROFILER
3921 ti = profile_getclock();
3922 #endif
3923 main_loop_wait(timeout);
3924 #ifdef CONFIG_PROFILER
3925 dev_time += profile_getclock() - ti;
3926 #endif
3928 cpu_disable_ticks();
3929 return ret;
3932 static void help(int exitcode)
3934 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
3935 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3936 "usage: %s [options] [disk_image]\n"
3937 "\n"
3938 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3939 "\n"
3940 "Standard options:\n"
3941 "-M machine select emulated machine (-M ? for list)\n"
3942 "-cpu cpu select CPU (-cpu ? for list)\n"
3943 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3944 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3945 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3946 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3947 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3948 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3949 " [,cache=writethrough|writeback|none][,format=f]\n"
3950 " [,boot=on|off]\n"
3951 " use 'file' as a drive image\n"
3952 "-mtdblock file use 'file' as on-board Flash memory image\n"
3953 "-sd file use 'file' as SecureDigital card image\n"
3954 "-pflash file use 'file' as a parallel flash image\n"
3955 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3956 "-snapshot write to temporary files instead of disk image files\n"
3957 #ifdef CONFIG_SDL
3958 "-no-frame open SDL window without a frame and window decorations\n"
3959 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3960 "-no-quit disable SDL window close capability\n"
3961 #endif
3962 #ifdef TARGET_I386
3963 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3964 #endif
3965 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3966 "-smp n set the number of CPUs to 'n' [default=1]\n"
3967 "-nographic disable graphical output and redirect serial I/Os to console\n"
3968 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3969 #ifndef _WIN32
3970 "-k language use keyboard layout (for example \"fr\" for French)\n"
3971 #endif
3972 #ifdef HAS_AUDIO
3973 "-audio-help print list of audio drivers and their options\n"
3974 "-soundhw c1,... enable audio support\n"
3975 " and only specified sound cards (comma separated list)\n"
3976 " use -soundhw ? to get the list of supported cards\n"
3977 " use -soundhw all to enable all of them\n"
3978 #endif
3979 "-vga [std|cirrus|vmware]\n"
3980 " select video card type\n"
3981 "-localtime set the real time clock to local time [default=utc]\n"
3982 "-full-screen start in full screen\n"
3983 #ifdef TARGET_I386
3984 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3985 #endif
3986 "-usb enable the USB driver (will be the default soon)\n"
3987 "-usbdevice name add the host or guest USB device 'name'\n"
3988 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3989 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3990 #endif
3991 "-name string set the name of the guest\n"
3992 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
3993 "\n"
3994 "Network options:\n"
3995 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
3996 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3997 #ifdef CONFIG_SLIRP
3998 "-net user[,vlan=n][,hostname=host]\n"
3999 " connect the user mode network stack to VLAN 'n' and send\n"
4000 " hostname 'host' to DHCP clients\n"
4001 #endif
4002 #ifdef _WIN32
4003 "-net tap[,vlan=n],ifname=name\n"
4004 " connect the host TAP network interface to VLAN 'n'\n"
4005 #else
4006 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4007 " connect the host TAP network interface to VLAN 'n' and use the\n"
4008 " network scripts 'file' (default=%s)\n"
4009 " and 'dfile' (default=%s);\n"
4010 " use '[down]script=no' to disable script execution;\n"
4011 " use 'fd=h' to connect to an already opened TAP interface\n"
4012 #endif
4013 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4014 " connect the vlan 'n' to another VLAN using a socket connection\n"
4015 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4016 " connect the vlan 'n' to multicast maddr and port\n"
4017 #ifdef CONFIG_VDE
4018 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4019 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4020 " on host and listening for incoming connections on 'socketpath'.\n"
4021 " Use group 'groupname' and mode 'octalmode' to change default\n"
4022 " ownership and permissions for communication port.\n"
4023 #endif
4024 "-net none use it alone to have zero network devices; if no -net option\n"
4025 " is provided, the default is '-net nic -net user'\n"
4026 "\n"
4027 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
4028 "-bt hci,host[:id]\n"
4029 " Use host's HCI with the given name\n"
4030 "-bt hci[,vlan=n]\n"
4031 " Emulate a standard HCI in virtual scatternet 'n'\n"
4032 "-bt vhci[,vlan=n]\n"
4033 " Add host computer to virtual scatternet 'n' using VHCI\n"
4034 "-bt device:dev[,vlan=n]\n"
4035 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
4036 "\n"
4037 #ifdef CONFIG_SLIRP
4038 "-tftp dir allow tftp access to files in dir [-net user]\n"
4039 "-bootp file advertise file in BOOTP replies\n"
4040 #ifndef _WIN32
4041 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4042 #endif
4043 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4044 " redirect TCP or UDP connections from host to guest [-net user]\n"
4045 #endif
4046 "\n"
4047 "Linux boot specific:\n"
4048 "-kernel bzImage use 'bzImage' as kernel image\n"
4049 "-append cmdline use 'cmdline' as kernel command line\n"
4050 "-initrd file use 'file' as initial ram disk\n"
4051 "\n"
4052 "Debug/Expert options:\n"
4053 "-monitor dev redirect the monitor to char device 'dev'\n"
4054 "-serial dev redirect the serial port to char device 'dev'\n"
4055 "-parallel dev redirect the parallel port to char device 'dev'\n"
4056 "-pidfile file Write PID to 'file'\n"
4057 "-S freeze CPU at startup (use 'c' to start execution)\n"
4058 "-s wait gdb connection to port\n"
4059 "-p port set gdb connection port [default=%s]\n"
4060 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4061 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4062 " translation (t=none or lba) (usually qemu can guess them)\n"
4063 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4064 #ifdef USE_KQEMU
4065 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4066 "-no-kqemu disable KQEMU kernel module usage\n"
4067 #endif
4068 #ifdef CONFIG_KVM
4069 "-enable-kvm enable KVM full virtualization support\n"
4070 #endif
4071 #ifdef USE_KVM
4072 #ifndef NO_CPU_EMULATION
4073 "-no-kvm disable KVM hardware virtualization\n"
4074 #endif
4075 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4076 "-no-kvm-pit disable KVM kernel mode PIT\n"
4077 "-no-kvm-pit-reinjection disable KVM kernel mode PIT interrupt reinjection\n"
4078 "-enable-nesting enable support for running a VM inside the VM (AMD only)\n"
4079 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4080 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4081 " expose a PCI device to the guest OS.\n"
4082 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4083 " 'string' is used in log output.\n"
4084 #endif
4085 #endif
4086 #ifdef TARGET_I386
4087 "-no-acpi disable ACPI\n"
4088 "-no-hpet disable HPET\n"
4089 #endif
4090 #ifdef CONFIG_CURSES
4091 "-curses use a curses/ncurses interface instead of SDL\n"
4092 #endif
4093 "-no-reboot exit instead of rebooting\n"
4094 "-no-shutdown stop before shutdown\n"
4095 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
4096 "-vnc display start a VNC server on display\n"
4097 #ifndef _WIN32
4098 "-daemonize daemonize QEMU after initializing\n"
4099 #endif
4100 "-tdf inject timer interrupts that got lost\n"
4101 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4102 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
4103 "-option-rom rom load a file, rom, into the option ROM space\n"
4104 #ifdef TARGET_SPARC
4105 "-prom-env variable=value set OpenBIOS nvram variables\n"
4106 #endif
4107 "-clock force the use of the given methods for timer alarm.\n"
4108 " To see what timers are available use -clock ?\n"
4109 "-startdate select initial date of the clock\n"
4110 "-icount [N|auto]\n"
4111 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4112 "\n"
4113 "During emulation, the following keys are useful:\n"
4114 "ctrl-alt-f toggle full screen\n"
4115 "ctrl-alt-n switch to virtual console 'n'\n"
4116 "ctrl-alt toggle mouse and keyboard grab\n"
4117 "\n"
4118 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4120 "qemu",
4121 DEFAULT_RAM_SIZE,
4122 #ifndef _WIN32
4123 DEFAULT_NETWORK_SCRIPT,
4124 DEFAULT_NETWORK_DOWN_SCRIPT,
4125 #endif
4126 DEFAULT_GDBSTUB_PORT,
4127 "/tmp/qemu.log");
4128 exit(exitcode);
4131 #define HAS_ARG 0x0001
4133 enum {
4134 QEMU_OPTION_h,
4136 QEMU_OPTION_M,
4137 QEMU_OPTION_cpu,
4138 QEMU_OPTION_fda,
4139 QEMU_OPTION_fdb,
4140 QEMU_OPTION_hda,
4141 QEMU_OPTION_hdb,
4142 QEMU_OPTION_hdc,
4143 QEMU_OPTION_hdd,
4144 QEMU_OPTION_drive,
4145 QEMU_OPTION_cdrom,
4146 QEMU_OPTION_mtdblock,
4147 QEMU_OPTION_sd,
4148 QEMU_OPTION_pflash,
4149 QEMU_OPTION_boot,
4150 QEMU_OPTION_snapshot,
4151 #ifdef TARGET_I386
4152 QEMU_OPTION_no_fd_bootchk,
4153 #endif
4154 QEMU_OPTION_m,
4155 QEMU_OPTION_nographic,
4156 QEMU_OPTION_portrait,
4157 #ifdef HAS_AUDIO
4158 QEMU_OPTION_audio_help,
4159 QEMU_OPTION_soundhw,
4160 #endif
4162 QEMU_OPTION_net,
4163 QEMU_OPTION_tftp,
4164 QEMU_OPTION_bootp,
4165 QEMU_OPTION_smb,
4166 QEMU_OPTION_redir,
4167 QEMU_OPTION_bt,
4169 QEMU_OPTION_kernel,
4170 QEMU_OPTION_append,
4171 QEMU_OPTION_initrd,
4173 QEMU_OPTION_S,
4174 QEMU_OPTION_s,
4175 QEMU_OPTION_p,
4176 QEMU_OPTION_d,
4177 QEMU_OPTION_hdachs,
4178 QEMU_OPTION_L,
4179 QEMU_OPTION_bios,
4180 QEMU_OPTION_k,
4181 QEMU_OPTION_localtime,
4182 QEMU_OPTION_g,
4183 QEMU_OPTION_vga,
4184 QEMU_OPTION_echr,
4185 QEMU_OPTION_monitor,
4186 QEMU_OPTION_serial,
4187 QEMU_OPTION_parallel,
4188 QEMU_OPTION_loadvm,
4189 QEMU_OPTION_full_screen,
4190 QEMU_OPTION_no_frame,
4191 QEMU_OPTION_alt_grab,
4192 QEMU_OPTION_no_quit,
4193 QEMU_OPTION_pidfile,
4194 QEMU_OPTION_no_kqemu,
4195 QEMU_OPTION_kernel_kqemu,
4196 QEMU_OPTION_enable_kvm,
4197 QEMU_OPTION_enable_nesting,
4198 QEMU_OPTION_win2k_hack,
4199 QEMU_OPTION_usb,
4200 QEMU_OPTION_usbdevice,
4201 QEMU_OPTION_smp,
4202 QEMU_OPTION_vnc,
4203 QEMU_OPTION_no_acpi,
4204 QEMU_OPTION_no_hpet,
4205 QEMU_OPTION_curses,
4206 QEMU_OPTION_no_kvm,
4207 QEMU_OPTION_no_kvm_irqchip,
4208 QEMU_OPTION_no_kvm_pit,
4209 QEMU_OPTION_no_kvm_pit_reinjection,
4210 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4211 QEMU_OPTION_pcidevice,
4212 #endif
4213 QEMU_OPTION_no_reboot,
4214 QEMU_OPTION_no_shutdown,
4215 QEMU_OPTION_show_cursor,
4216 QEMU_OPTION_daemonize,
4217 QEMU_OPTION_option_rom,
4218 QEMU_OPTION_semihosting,
4219 QEMU_OPTION_cpu_vendor,
4220 QEMU_OPTION_name,
4221 QEMU_OPTION_prom_env,
4222 QEMU_OPTION_old_param,
4223 QEMU_OPTION_clock,
4224 QEMU_OPTION_startdate,
4225 QEMU_OPTION_tb_size,
4226 QEMU_OPTION_icount,
4227 QEMU_OPTION_uuid,
4228 QEMU_OPTION_incoming,
4229 QEMU_OPTION_tdf,
4230 QEMU_OPTION_kvm_shadow_memory,
4231 QEMU_OPTION_mempath,
4234 typedef struct QEMUOption {
4235 const char *name;
4236 int flags;
4237 int index;
4238 } QEMUOption;
4240 static const QEMUOption qemu_options[] = {
4241 { "h", 0, QEMU_OPTION_h },
4242 { "help", 0, QEMU_OPTION_h },
4244 { "M", HAS_ARG, QEMU_OPTION_M },
4245 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4246 { "fda", HAS_ARG, QEMU_OPTION_fda },
4247 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4248 { "hda", HAS_ARG, QEMU_OPTION_hda },
4249 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4250 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4251 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4252 { "drive", HAS_ARG, QEMU_OPTION_drive },
4253 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4254 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4255 { "sd", HAS_ARG, QEMU_OPTION_sd },
4256 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4257 { "boot", HAS_ARG, QEMU_OPTION_boot },
4258 { "snapshot", 0, QEMU_OPTION_snapshot },
4259 #ifdef TARGET_I386
4260 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4261 #endif
4262 { "m", HAS_ARG, QEMU_OPTION_m },
4263 { "nographic", 0, QEMU_OPTION_nographic },
4264 { "portrait", 0, QEMU_OPTION_portrait },
4265 { "k", HAS_ARG, QEMU_OPTION_k },
4266 #ifdef HAS_AUDIO
4267 { "audio-help", 0, QEMU_OPTION_audio_help },
4268 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4269 #endif
4271 { "net", HAS_ARG, QEMU_OPTION_net},
4272 #ifdef CONFIG_SLIRP
4273 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4274 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4275 #ifndef _WIN32
4276 { "smb", HAS_ARG, QEMU_OPTION_smb },
4277 #endif
4278 { "redir", HAS_ARG, QEMU_OPTION_redir },
4279 #endif
4280 { "bt", HAS_ARG, QEMU_OPTION_bt },
4282 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4283 { "append", HAS_ARG, QEMU_OPTION_append },
4284 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4286 { "S", 0, QEMU_OPTION_S },
4287 { "s", 0, QEMU_OPTION_s },
4288 { "p", HAS_ARG, QEMU_OPTION_p },
4289 { "d", HAS_ARG, QEMU_OPTION_d },
4290 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4291 { "L", HAS_ARG, QEMU_OPTION_L },
4292 { "bios", HAS_ARG, QEMU_OPTION_bios },
4293 #ifdef USE_KQEMU
4294 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4295 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4296 #endif
4297 #ifdef CONFIG_KVM
4298 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4299 #endif
4300 #ifdef USE_KVM
4301 #ifndef NO_CPU_EMULATION
4302 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4303 #endif
4304 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4305 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4306 { "no-kvm-pit-reinjection", 0, QEMU_OPTION_no_kvm_pit_reinjection },
4307 { "enable-nesting", 0, QEMU_OPTION_enable_nesting },
4308 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4309 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4310 #endif
4311 #endif
4312 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4313 { "g", 1, QEMU_OPTION_g },
4314 #endif
4315 { "localtime", 0, QEMU_OPTION_localtime },
4316 { "vga", HAS_ARG, QEMU_OPTION_vga },
4317 { "echr", HAS_ARG, QEMU_OPTION_echr },
4318 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4319 { "serial", HAS_ARG, QEMU_OPTION_serial },
4320 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4321 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4322 { "incoming", 1, QEMU_OPTION_incoming },
4323 { "full-screen", 0, QEMU_OPTION_full_screen },
4324 #ifdef CONFIG_SDL
4325 { "no-frame", 0, QEMU_OPTION_no_frame },
4326 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4327 { "no-quit", 0, QEMU_OPTION_no_quit },
4328 #endif
4329 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4330 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4331 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4332 { "smp", HAS_ARG, QEMU_OPTION_smp },
4333 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4334 #ifdef CONFIG_CURSES
4335 { "curses", 0, QEMU_OPTION_curses },
4336 #endif
4337 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4339 /* temporary options */
4340 { "usb", 0, QEMU_OPTION_usb },
4341 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4342 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4343 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4344 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4345 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4346 { "daemonize", 0, QEMU_OPTION_daemonize },
4347 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4348 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4349 { "semihosting", 0, QEMU_OPTION_semihosting },
4350 #endif
4351 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4352 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4353 { "name", HAS_ARG, QEMU_OPTION_name },
4354 #if defined(TARGET_SPARC)
4355 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4356 #endif
4357 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4358 #if defined(TARGET_ARM)
4359 { "old-param", 0, QEMU_OPTION_old_param },
4360 #endif
4361 { "clock", HAS_ARG, QEMU_OPTION_clock },
4362 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4363 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4364 { "icount", HAS_ARG, QEMU_OPTION_icount },
4365 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4366 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4367 { NULL },
4370 /* password input */
4372 int qemu_key_check(BlockDriverState *bs, const char *name)
4374 char password[256];
4375 int i;
4377 if (!bdrv_is_encrypted(bs))
4378 return 0;
4380 term_printf("%s is encrypted.\n", name);
4381 for(i = 0; i < 3; i++) {
4382 monitor_readline("Password: ", 1, password, sizeof(password));
4383 if (bdrv_set_key(bs, password) == 0)
4384 return 0;
4385 term_printf("invalid password\n");
4387 return -EPERM;
4390 static BlockDriverState *get_bdrv(int index)
4392 if (index > nb_drives)
4393 return NULL;
4394 return drives_table[index].bdrv;
4397 static void read_passwords(void)
4399 BlockDriverState *bs;
4400 int i;
4402 for(i = 0; i < 6; i++) {
4403 bs = get_bdrv(i);
4404 if (bs)
4405 qemu_key_check(bs, bdrv_get_device_name(bs));
4409 #ifdef HAS_AUDIO
4410 struct soundhw soundhw[] = {
4411 #ifdef HAS_AUDIO_CHOICE
4412 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4414 "pcspk",
4415 "PC speaker",
4418 { .init_isa = pcspk_audio_init }
4420 #endif
4422 "sb16",
4423 "Creative Sound Blaster 16",
4426 { .init_isa = SB16_init }
4429 #ifdef CONFIG_CS4231A
4431 "cs4231a",
4432 "CS4231A",
4435 { .init_isa = cs4231a_init }
4437 #endif
4439 #ifdef CONFIG_ADLIB
4441 "adlib",
4442 #ifdef HAS_YMF262
4443 "Yamaha YMF262 (OPL3)",
4444 #else
4445 "Yamaha YM3812 (OPL2)",
4446 #endif
4449 { .init_isa = Adlib_init }
4451 #endif
4453 #ifdef CONFIG_GUS
4455 "gus",
4456 "Gravis Ultrasound GF1",
4459 { .init_isa = GUS_init }
4461 #endif
4463 #ifdef CONFIG_AC97
4465 "ac97",
4466 "Intel 82801AA AC97 Audio",
4469 { .init_pci = ac97_init }
4471 #endif
4474 "es1370",
4475 "ENSONIQ AudioPCI ES1370",
4478 { .init_pci = es1370_init }
4480 #endif
4482 { NULL, NULL, 0, 0, { NULL } }
4485 static void select_soundhw (const char *optarg)
4487 struct soundhw *c;
4489 if (*optarg == '?') {
4490 show_valid_cards:
4492 printf ("Valid sound card names (comma separated):\n");
4493 for (c = soundhw; c->name; ++c) {
4494 printf ("%-11s %s\n", c->name, c->descr);
4496 printf ("\n-soundhw all will enable all of the above\n");
4497 exit (*optarg != '?');
4499 else {
4500 size_t l;
4501 const char *p;
4502 char *e;
4503 int bad_card = 0;
4505 if (!strcmp (optarg, "all")) {
4506 for (c = soundhw; c->name; ++c) {
4507 c->enabled = 1;
4509 return;
4512 p = optarg;
4513 while (*p) {
4514 e = strchr (p, ',');
4515 l = !e ? strlen (p) : (size_t) (e - p);
4517 for (c = soundhw; c->name; ++c) {
4518 if (!strncmp (c->name, p, l)) {
4519 c->enabled = 1;
4520 break;
4524 if (!c->name) {
4525 if (l > 80) {
4526 fprintf (stderr,
4527 "Unknown sound card name (too big to show)\n");
4529 else {
4530 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4531 (int) l, p);
4533 bad_card = 1;
4535 p += l + (e != NULL);
4538 if (bad_card)
4539 goto show_valid_cards;
4542 #endif
4544 static void select_vgahw (const char *p)
4546 const char *opts;
4548 if (strstart(p, "std", &opts)) {
4549 cirrus_vga_enabled = 0;
4550 vmsvga_enabled = 0;
4551 } else if (strstart(p, "cirrus", &opts)) {
4552 cirrus_vga_enabled = 1;
4553 vmsvga_enabled = 0;
4554 } else if (strstart(p, "vmware", &opts)) {
4555 cirrus_vga_enabled = 0;
4556 vmsvga_enabled = 1;
4557 } else {
4558 invalid_vga:
4559 fprintf(stderr, "Unknown vga type: %s\n", p);
4560 exit(1);
4562 while (*opts) {
4563 const char *nextopt;
4565 if (strstart(opts, ",retrace=", &nextopt)) {
4566 opts = nextopt;
4567 if (strstart(opts, "dumb", &nextopt))
4568 vga_retrace_method = VGA_RETRACE_DUMB;
4569 else if (strstart(opts, "precise", &nextopt))
4570 vga_retrace_method = VGA_RETRACE_PRECISE;
4571 else goto invalid_vga;
4572 } else goto invalid_vga;
4573 opts = nextopt;
4577 #ifdef _WIN32
4578 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4580 exit(STATUS_CONTROL_C_EXIT);
4581 return TRUE;
4583 #endif
4585 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4587 int ret;
4589 if(strlen(str) != 36)
4590 return -1;
4592 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4593 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4594 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4596 if(ret != 16)
4597 return -1;
4599 return 0;
4602 #define MAX_NET_CLIENTS 32
4604 static int saved_argc;
4605 static char **saved_argv;
4607 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4609 *argc = saved_argc;
4610 *argv = saved_argv;
4611 *opt_daemonize = daemonize;
4612 *opt_incoming = incoming;
4616 static int gethugepagesize(void)
4618 int ret, fd;
4619 char buf[4096];
4620 const char *needle = "Hugepagesize:";
4621 char *size;
4622 unsigned long hugepagesize;
4624 fd = open("/proc/meminfo", O_RDONLY);
4625 if (fd < 0) {
4626 perror("open");
4627 exit(0);
4630 ret = read(fd, buf, sizeof(buf));
4631 if (ret < 0) {
4632 perror("read");
4633 exit(0);
4636 size = strstr(buf, needle);
4637 if (!size)
4638 return 0;
4639 size += strlen(needle);
4640 hugepagesize = strtol(size, NULL, 0);
4641 return hugepagesize;
4644 void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4646 char *filename;
4647 void *area;
4648 int fd;
4650 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4651 return NULL;
4653 hpagesize = gethugepagesize() * 1024;
4654 if (!hpagesize)
4655 return NULL;
4657 fd = mkstemp(filename);
4658 if (fd < 0) {
4659 perror("mkstemp");
4660 free(filename);
4661 return NULL;
4663 unlink(filename);
4664 free(filename);
4666 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4669 * ftruncate is not supported by hugetlbfs in older
4670 * hosts, so don't bother checking for errors.
4671 * If anything goes wrong with it under other filesystems,
4672 * mmap will fail.
4674 ftruncate(fd, memory);
4676 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4677 if (area == MAP_FAILED) {
4678 perror("mmap");
4679 close(fd);
4680 return NULL;
4683 *len = memory;
4684 return area;
4687 void *qemu_alloc_physram(unsigned long memory)
4689 void *area = NULL;
4690 unsigned long map_len = memory;
4692 #ifdef USE_KVM
4693 if (mem_path)
4694 area = alloc_mem_area(memory, &map_len, mem_path);
4695 #endif
4696 if (!area)
4697 area = qemu_vmalloc(memory);
4698 #ifdef USE_KVM
4699 if (kvm_setup_guest_memory(area, map_len))
4700 area = NULL;
4701 #endif
4702 return area;
4705 #ifndef _WIN32
4707 static void termsig_handler(int signal)
4709 qemu_system_shutdown_request();
4712 static void termsig_setup(void)
4714 struct sigaction act;
4716 memset(&act, 0, sizeof(act));
4717 act.sa_handler = termsig_handler;
4718 sigaction(SIGINT, &act, NULL);
4719 sigaction(SIGHUP, &act, NULL);
4720 sigaction(SIGTERM, &act, NULL);
4723 #endif
4725 int main(int argc, char **argv, char **envp)
4727 #ifdef CONFIG_GDBSTUB
4728 int use_gdbstub;
4729 const char *gdbstub_port;
4730 #endif
4731 uint32_t boot_devices_bitmap = 0;
4732 int i;
4733 int snapshot, linux_boot, net_boot;
4734 const char *initrd_filename;
4735 const char *kernel_filename, *kernel_cmdline;
4736 const char *boot_devices = "";
4737 DisplayState *ds = &display_state;
4738 int cyls, heads, secs, translation;
4739 const char *net_clients[MAX_NET_CLIENTS];
4740 int nb_net_clients;
4741 const char *bt_opts[MAX_BT_CMDLINE];
4742 int nb_bt_opts;
4743 int hda_index;
4744 int optind;
4745 const char *r, *optarg;
4746 CharDriverState *monitor_hd;
4747 const char *monitor_device;
4748 const char *serial_devices[MAX_SERIAL_PORTS];
4749 int serial_device_index;
4750 const char *parallel_devices[MAX_PARALLEL_PORTS];
4751 int parallel_device_index;
4752 const char *loadvm = NULL;
4753 QEMUMachine *machine;
4754 const char *cpu_model;
4755 const char *usb_devices[MAX_USB_CMDLINE];
4756 int usb_devices_index;
4757 int fds[2];
4758 int tb_size;
4759 const char *pid_file = NULL;
4760 int autostart;
4761 const char *incoming = NULL;
4763 qemu_cache_utils_init(envp);
4765 LIST_INIT (&vm_change_state_head);
4766 #ifndef _WIN32
4768 struct sigaction act;
4769 sigfillset(&act.sa_mask);
4770 act.sa_flags = 0;
4771 act.sa_handler = SIG_IGN;
4772 sigaction(SIGPIPE, &act, NULL);
4774 #else
4775 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4776 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4777 QEMU to run on a single CPU */
4779 HANDLE h;
4780 DWORD mask, smask;
4781 int i;
4782 h = GetCurrentProcess();
4783 if (GetProcessAffinityMask(h, &mask, &smask)) {
4784 for(i = 0; i < 32; i++) {
4785 if (mask & (1 << i))
4786 break;
4788 if (i != 32) {
4789 mask = 1 << i;
4790 SetProcessAffinityMask(h, mask);
4794 #endif
4796 register_machines();
4797 machine = first_machine;
4798 cpu_model = NULL;
4799 initrd_filename = NULL;
4800 ram_size = 0;
4801 vga_ram_size = VGA_RAM_SIZE;
4802 #ifdef CONFIG_GDBSTUB
4803 use_gdbstub = 0;
4804 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4805 #endif
4806 snapshot = 0;
4807 nographic = 0;
4808 curses = 0;
4809 kernel_filename = NULL;
4810 kernel_cmdline = "";
4811 cyls = heads = secs = 0;
4812 translation = BIOS_ATA_TRANSLATION_AUTO;
4813 monitor_device = "vc";
4815 serial_devices[0] = "vc:80Cx24C";
4816 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4817 serial_devices[i] = NULL;
4818 serial_device_index = 0;
4820 parallel_devices[0] = "vc:640x480";
4821 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4822 parallel_devices[i] = NULL;
4823 parallel_device_index = 0;
4825 usb_devices_index = 0;
4826 assigned_devices_index = 0;
4828 nb_net_clients = 0;
4829 nb_bt_opts = 0;
4830 nb_drives = 0;
4831 nb_drives_opt = 0;
4832 hda_index = -1;
4834 nb_nics = 0;
4836 tb_size = 0;
4837 autostart= 1;
4839 optind = 1;
4840 for(;;) {
4841 if (optind >= argc)
4842 break;
4843 r = argv[optind];
4844 if (r[0] != '-') {
4845 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4846 } else {
4847 const QEMUOption *popt;
4849 optind++;
4850 /* Treat --foo the same as -foo. */
4851 if (r[1] == '-')
4852 r++;
4853 popt = qemu_options;
4854 for(;;) {
4855 if (!popt->name) {
4856 fprintf(stderr, "%s: invalid option -- '%s'\n",
4857 argv[0], r);
4858 exit(1);
4860 if (!strcmp(popt->name, r + 1))
4861 break;
4862 popt++;
4864 if (popt->flags & HAS_ARG) {
4865 if (optind >= argc) {
4866 fprintf(stderr, "%s: option '%s' requires an argument\n",
4867 argv[0], r);
4868 exit(1);
4870 optarg = argv[optind++];
4871 } else {
4872 optarg = NULL;
4875 switch(popt->index) {
4876 case QEMU_OPTION_M:
4877 machine = find_machine(optarg);
4878 if (!machine) {
4879 QEMUMachine *m;
4880 printf("Supported machines are:\n");
4881 for(m = first_machine; m != NULL; m = m->next) {
4882 printf("%-10s %s%s\n",
4883 m->name, m->desc,
4884 m == first_machine ? " (default)" : "");
4886 exit(*optarg != '?');
4888 break;
4889 case QEMU_OPTION_cpu:
4890 /* hw initialization will check this */
4891 if (*optarg == '?') {
4892 /* XXX: implement xxx_cpu_list for targets that still miss it */
4893 #if defined(cpu_list)
4894 cpu_list(stdout, &fprintf);
4895 #endif
4896 exit(0);
4897 } else {
4898 cpu_model = optarg;
4900 break;
4901 case QEMU_OPTION_initrd:
4902 initrd_filename = optarg;
4903 break;
4904 case QEMU_OPTION_hda:
4905 if (cyls == 0)
4906 hda_index = drive_add(optarg, HD_ALIAS, 0);
4907 else
4908 hda_index = drive_add(optarg, HD_ALIAS
4909 ",cyls=%d,heads=%d,secs=%d%s",
4910 0, cyls, heads, secs,
4911 translation == BIOS_ATA_TRANSLATION_LBA ?
4912 ",trans=lba" :
4913 translation == BIOS_ATA_TRANSLATION_NONE ?
4914 ",trans=none" : "");
4915 break;
4916 case QEMU_OPTION_hdb:
4917 case QEMU_OPTION_hdc:
4918 case QEMU_OPTION_hdd:
4919 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4920 break;
4921 case QEMU_OPTION_drive:
4922 drive_add(NULL, "%s", optarg);
4923 break;
4924 case QEMU_OPTION_mtdblock:
4925 drive_add(optarg, MTD_ALIAS);
4926 break;
4927 case QEMU_OPTION_sd:
4928 drive_add(optarg, SD_ALIAS);
4929 break;
4930 case QEMU_OPTION_pflash:
4931 drive_add(optarg, PFLASH_ALIAS);
4932 break;
4933 case QEMU_OPTION_snapshot:
4934 snapshot = 1;
4935 break;
4936 case QEMU_OPTION_hdachs:
4938 const char *p;
4939 p = optarg;
4940 cyls = strtol(p, (char **)&p, 0);
4941 if (cyls < 1 || cyls > 16383)
4942 goto chs_fail;
4943 if (*p != ',')
4944 goto chs_fail;
4945 p++;
4946 heads = strtol(p, (char **)&p, 0);
4947 if (heads < 1 || heads > 16)
4948 goto chs_fail;
4949 if (*p != ',')
4950 goto chs_fail;
4951 p++;
4952 secs = strtol(p, (char **)&p, 0);
4953 if (secs < 1 || secs > 63)
4954 goto chs_fail;
4955 if (*p == ',') {
4956 p++;
4957 if (!strcmp(p, "none"))
4958 translation = BIOS_ATA_TRANSLATION_NONE;
4959 else if (!strcmp(p, "lba"))
4960 translation = BIOS_ATA_TRANSLATION_LBA;
4961 else if (!strcmp(p, "auto"))
4962 translation = BIOS_ATA_TRANSLATION_AUTO;
4963 else
4964 goto chs_fail;
4965 } else if (*p != '\0') {
4966 chs_fail:
4967 fprintf(stderr, "qemu: invalid physical CHS format\n");
4968 exit(1);
4970 if (hda_index != -1)
4971 snprintf(drives_opt[hda_index].opt,
4972 sizeof(drives_opt[hda_index].opt),
4973 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4974 0, cyls, heads, secs,
4975 translation == BIOS_ATA_TRANSLATION_LBA ?
4976 ",trans=lba" :
4977 translation == BIOS_ATA_TRANSLATION_NONE ?
4978 ",trans=none" : "");
4980 break;
4981 case QEMU_OPTION_nographic:
4982 nographic = 1;
4983 break;
4984 #ifdef CONFIG_CURSES
4985 case QEMU_OPTION_curses:
4986 curses = 1;
4987 break;
4988 #endif
4989 case QEMU_OPTION_portrait:
4990 graphic_rotate = 1;
4991 break;
4992 case QEMU_OPTION_kernel:
4993 kernel_filename = optarg;
4994 break;
4995 case QEMU_OPTION_append:
4996 kernel_cmdline = optarg;
4997 break;
4998 case QEMU_OPTION_cdrom:
4999 drive_add(optarg, CDROM_ALIAS);
5000 break;
5001 case QEMU_OPTION_boot:
5002 boot_devices = optarg;
5003 /* We just do some generic consistency checks */
5005 /* Could easily be extended to 64 devices if needed */
5006 const char *p;
5008 boot_devices_bitmap = 0;
5009 for (p = boot_devices; *p != '\0'; p++) {
5010 /* Allowed boot devices are:
5011 * a b : floppy disk drives
5012 * c ... f : IDE disk drives
5013 * g ... m : machine implementation dependant drives
5014 * n ... p : network devices
5015 * It's up to each machine implementation to check
5016 * if the given boot devices match the actual hardware
5017 * implementation and firmware features.
5019 if (*p < 'a' || *p > 'q') {
5020 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5021 exit(1);
5023 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5024 fprintf(stderr,
5025 "Boot device '%c' was given twice\n",*p);
5026 exit(1);
5028 boot_devices_bitmap |= 1 << (*p - 'a');
5031 break;
5032 case QEMU_OPTION_fda:
5033 case QEMU_OPTION_fdb:
5034 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5035 break;
5036 #ifdef TARGET_I386
5037 case QEMU_OPTION_no_fd_bootchk:
5038 fd_bootchk = 0;
5039 break;
5040 #endif
5041 case QEMU_OPTION_net:
5042 if (nb_net_clients >= MAX_NET_CLIENTS) {
5043 fprintf(stderr, "qemu: too many network clients\n");
5044 exit(1);
5046 net_clients[nb_net_clients] = optarg;
5047 nb_net_clients++;
5048 break;
5049 #ifdef CONFIG_SLIRP
5050 case QEMU_OPTION_tftp:
5051 tftp_prefix = optarg;
5052 break;
5053 case QEMU_OPTION_bootp:
5054 bootp_filename = optarg;
5055 break;
5056 #ifndef _WIN32
5057 case QEMU_OPTION_smb:
5058 net_slirp_smb(optarg);
5059 break;
5060 #endif
5061 case QEMU_OPTION_redir:
5062 net_slirp_redir(optarg);
5063 break;
5064 #endif
5065 case QEMU_OPTION_bt:
5066 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5067 fprintf(stderr, "qemu: too many bluetooth options\n");
5068 exit(1);
5070 bt_opts[nb_bt_opts++] = optarg;
5071 break;
5072 #ifdef HAS_AUDIO
5073 case QEMU_OPTION_audio_help:
5074 AUD_help ();
5075 exit (0);
5076 break;
5077 case QEMU_OPTION_soundhw:
5078 select_soundhw (optarg);
5079 break;
5080 #endif
5081 case QEMU_OPTION_h:
5082 help(0);
5083 break;
5084 case QEMU_OPTION_m: {
5085 uint64_t value;
5086 char *ptr;
5088 value = strtoul(optarg, &ptr, 10);
5089 switch (*ptr) {
5090 case 0: case 'M': case 'm':
5091 value <<= 20;
5092 break;
5093 case 'G': case 'g':
5094 value <<= 30;
5095 break;
5096 default:
5097 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5098 exit(1);
5101 /* On 32-bit hosts, QEMU is limited by virtual address space */
5102 if (value > (2047 << 20)
5103 #ifndef USE_KQEMU
5104 && HOST_LONG_BITS == 32
5105 #endif
5107 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5108 exit(1);
5110 if (value != (uint64_t)(ram_addr_t)value) {
5111 fprintf(stderr, "qemu: ram size too large\n");
5112 exit(1);
5114 ram_size = value;
5115 break;
5117 case QEMU_OPTION_d:
5119 int mask;
5120 const CPULogItem *item;
5122 mask = cpu_str_to_log_mask(optarg);
5123 if (!mask) {
5124 printf("Log items (comma separated):\n");
5125 for(item = cpu_log_items; item->mask != 0; item++) {
5126 printf("%-10s %s\n", item->name, item->help);
5128 exit(1);
5130 cpu_set_log(mask);
5132 break;
5133 #ifdef CONFIG_GDBSTUB
5134 case QEMU_OPTION_s:
5135 use_gdbstub = 1;
5136 break;
5137 case QEMU_OPTION_p:
5138 gdbstub_port = optarg;
5139 break;
5140 #endif
5141 case QEMU_OPTION_L:
5142 bios_dir = optarg;
5143 break;
5144 case QEMU_OPTION_bios:
5145 bios_name = optarg;
5146 break;
5147 case QEMU_OPTION_S:
5148 autostart = 0;
5149 break;
5150 case QEMU_OPTION_k:
5151 keyboard_layout = optarg;
5152 break;
5153 case QEMU_OPTION_localtime:
5154 rtc_utc = 0;
5155 break;
5156 case QEMU_OPTION_vga:
5157 select_vgahw (optarg);
5158 break;
5159 case QEMU_OPTION_g:
5161 const char *p;
5162 int w, h, depth;
5163 p = optarg;
5164 w = strtol(p, (char **)&p, 10);
5165 if (w <= 0) {
5166 graphic_error:
5167 fprintf(stderr, "qemu: invalid resolution or depth\n");
5168 exit(1);
5170 if (*p != 'x')
5171 goto graphic_error;
5172 p++;
5173 h = strtol(p, (char **)&p, 10);
5174 if (h <= 0)
5175 goto graphic_error;
5176 if (*p == 'x') {
5177 p++;
5178 depth = strtol(p, (char **)&p, 10);
5179 if (depth != 8 && depth != 15 && depth != 16 &&
5180 depth != 24 && depth != 32)
5181 goto graphic_error;
5182 } else if (*p == '\0') {
5183 depth = graphic_depth;
5184 } else {
5185 goto graphic_error;
5188 graphic_width = w;
5189 graphic_height = h;
5190 graphic_depth = depth;
5192 break;
5193 case QEMU_OPTION_echr:
5195 char *r;
5196 term_escape_char = strtol(optarg, &r, 0);
5197 if (r == optarg)
5198 printf("Bad argument to echr\n");
5199 break;
5201 case QEMU_OPTION_monitor:
5202 monitor_device = optarg;
5203 break;
5204 case QEMU_OPTION_serial:
5205 if (serial_device_index >= MAX_SERIAL_PORTS) {
5206 fprintf(stderr, "qemu: too many serial ports\n");
5207 exit(1);
5209 serial_devices[serial_device_index] = optarg;
5210 serial_device_index++;
5211 break;
5212 case QEMU_OPTION_parallel:
5213 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5214 fprintf(stderr, "qemu: too many parallel ports\n");
5215 exit(1);
5217 parallel_devices[parallel_device_index] = optarg;
5218 parallel_device_index++;
5219 break;
5220 case QEMU_OPTION_loadvm:
5221 loadvm = optarg;
5222 break;
5223 case QEMU_OPTION_full_screen:
5224 full_screen = 1;
5225 break;
5226 #ifdef CONFIG_SDL
5227 case QEMU_OPTION_no_frame:
5228 no_frame = 1;
5229 break;
5230 case QEMU_OPTION_alt_grab:
5231 alt_grab = 1;
5232 break;
5233 case QEMU_OPTION_no_quit:
5234 no_quit = 1;
5235 break;
5236 #endif
5237 case QEMU_OPTION_pidfile:
5238 pid_file = optarg;
5239 break;
5240 #ifdef TARGET_I386
5241 case QEMU_OPTION_win2k_hack:
5242 win2k_install_hack = 1;
5243 break;
5244 #endif
5245 #ifdef USE_KQEMU
5246 case QEMU_OPTION_no_kqemu:
5247 kqemu_allowed = 0;
5248 break;
5249 case QEMU_OPTION_kernel_kqemu:
5250 kqemu_allowed = 2;
5251 break;
5252 #endif
5253 #ifdef CONFIG_KVM
5254 case QEMU_OPTION_enable_kvm:
5255 kvm_allowed = 1;
5256 #ifdef USE_KQEMU
5257 kqemu_allowed = 0;
5258 #endif
5259 break;
5260 #endif
5261 #ifdef USE_KVM
5262 case QEMU_OPTION_no_kvm:
5263 kvm_allowed = 0;
5264 break;
5265 case QEMU_OPTION_no_kvm_irqchip: {
5266 extern int kvm_irqchip, kvm_pit;
5267 kvm_irqchip = 0;
5268 kvm_pit = 0;
5269 break;
5271 case QEMU_OPTION_no_kvm_pit: {
5272 extern int kvm_pit;
5273 kvm_pit = 0;
5274 break;
5276 case QEMU_OPTION_no_kvm_pit_reinjection: {
5277 extern int kvm_pit_reinject;
5278 kvm_pit_reinject = 0;
5279 break;
5281 case QEMU_OPTION_enable_nesting: {
5282 kvm_nested = 1;
5283 break;
5285 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5286 case QEMU_OPTION_pcidevice:
5287 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5288 fprintf(stderr, "Too many assigned devices\n");
5289 exit(1);
5291 assigned_devices[assigned_devices_index] = optarg;
5292 assigned_devices_index++;
5293 break;
5294 #endif
5295 #endif
5296 case QEMU_OPTION_usb:
5297 usb_enabled = 1;
5298 break;
5299 case QEMU_OPTION_usbdevice:
5300 usb_enabled = 1;
5301 if (usb_devices_index >= MAX_USB_CMDLINE) {
5302 fprintf(stderr, "Too many USB devices\n");
5303 exit(1);
5305 usb_devices[usb_devices_index] = optarg;
5306 usb_devices_index++;
5307 break;
5308 case QEMU_OPTION_smp:
5309 smp_cpus = atoi(optarg);
5310 if (smp_cpus < 1) {
5311 fprintf(stderr, "Invalid number of CPUs\n");
5312 exit(1);
5314 break;
5315 case QEMU_OPTION_vnc:
5316 vnc_display = optarg;
5317 break;
5318 case QEMU_OPTION_no_acpi:
5319 acpi_enabled = 0;
5320 break;
5321 case QEMU_OPTION_no_hpet:
5322 no_hpet = 1;
5323 break;
5324 case QEMU_OPTION_no_reboot:
5325 no_reboot = 1;
5326 break;
5327 case QEMU_OPTION_no_shutdown:
5328 no_shutdown = 1;
5329 break;
5330 case QEMU_OPTION_show_cursor:
5331 cursor_hide = 0;
5332 break;
5333 case QEMU_OPTION_uuid:
5334 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5335 fprintf(stderr, "Fail to parse UUID string."
5336 " Wrong format.\n");
5337 exit(1);
5339 break;
5340 case QEMU_OPTION_daemonize:
5341 daemonize = 1;
5342 break;
5343 case QEMU_OPTION_option_rom:
5344 if (nb_option_roms >= MAX_OPTION_ROMS) {
5345 fprintf(stderr, "Too many option ROMs\n");
5346 exit(1);
5348 option_rom[nb_option_roms] = optarg;
5349 nb_option_roms++;
5350 break;
5351 case QEMU_OPTION_semihosting:
5352 semihosting_enabled = 1;
5353 break;
5354 case QEMU_OPTION_tdf:
5355 time_drift_fix = 1;
5356 break;
5357 case QEMU_OPTION_kvm_shadow_memory:
5358 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5359 break;
5360 case QEMU_OPTION_mempath:
5361 mem_path = optarg;
5362 break;
5363 case QEMU_OPTION_name:
5364 qemu_name = optarg;
5365 break;
5366 #ifdef TARGET_SPARC
5367 case QEMU_OPTION_prom_env:
5368 if (nb_prom_envs >= MAX_PROM_ENVS) {
5369 fprintf(stderr, "Too many prom variables\n");
5370 exit(1);
5372 prom_envs[nb_prom_envs] = optarg;
5373 nb_prom_envs++;
5374 break;
5375 #endif
5376 case QEMU_OPTION_cpu_vendor:
5377 cpu_vendor_string = optarg;
5378 break;
5379 #ifdef TARGET_ARM
5380 case QEMU_OPTION_old_param:
5381 old_param = 1;
5382 break;
5383 #endif
5384 case QEMU_OPTION_clock:
5385 configure_alarms(optarg);
5386 break;
5387 case QEMU_OPTION_startdate:
5389 struct tm tm;
5390 time_t rtc_start_date;
5391 if (!strcmp(optarg, "now")) {
5392 rtc_date_offset = -1;
5393 } else {
5394 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5395 &tm.tm_year,
5396 &tm.tm_mon,
5397 &tm.tm_mday,
5398 &tm.tm_hour,
5399 &tm.tm_min,
5400 &tm.tm_sec) == 6) {
5401 /* OK */
5402 } else if (sscanf(optarg, "%d-%d-%d",
5403 &tm.tm_year,
5404 &tm.tm_mon,
5405 &tm.tm_mday) == 3) {
5406 tm.tm_hour = 0;
5407 tm.tm_min = 0;
5408 tm.tm_sec = 0;
5409 } else {
5410 goto date_fail;
5412 tm.tm_year -= 1900;
5413 tm.tm_mon--;
5414 rtc_start_date = mktimegm(&tm);
5415 if (rtc_start_date == -1) {
5416 date_fail:
5417 fprintf(stderr, "Invalid date format. Valid format are:\n"
5418 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5419 exit(1);
5421 rtc_date_offset = time(NULL) - rtc_start_date;
5424 break;
5425 case QEMU_OPTION_tb_size:
5426 tb_size = strtol(optarg, NULL, 0);
5427 if (tb_size < 0)
5428 tb_size = 0;
5429 break;
5430 case QEMU_OPTION_icount:
5431 use_icount = 1;
5432 if (strcmp(optarg, "auto") == 0) {
5433 icount_time_shift = -1;
5434 } else {
5435 icount_time_shift = strtol(optarg, NULL, 0);
5437 break;
5438 case QEMU_OPTION_incoming:
5439 incoming = optarg;
5440 break;
5445 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5446 if (kvm_allowed && kqemu_allowed) {
5447 fprintf(stderr,
5448 "You can not enable both KVM and kqemu at the same time\n");
5449 exit(1);
5451 #endif
5453 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5454 if (smp_cpus > machine->max_cpus) {
5455 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5456 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5457 machine->max_cpus);
5458 exit(1);
5461 if (nographic) {
5462 if (serial_device_index == 0)
5463 serial_devices[0] = "stdio";
5464 if (parallel_device_index == 0)
5465 parallel_devices[0] = "null";
5466 if (strncmp(monitor_device, "vc", 2) == 0)
5467 monitor_device = "stdio";
5470 #ifndef _WIN32
5471 if (daemonize) {
5472 pid_t pid;
5474 if (pipe(fds) == -1)
5475 exit(1);
5477 pid = fork();
5478 if (pid > 0) {
5479 uint8_t status;
5480 ssize_t len;
5482 close(fds[1]);
5484 again:
5485 len = read(fds[0], &status, 1);
5486 if (len == -1 && (errno == EINTR))
5487 goto again;
5489 if (len != 1)
5490 exit(1);
5491 else if (status == 1) {
5492 fprintf(stderr, "Could not acquire pidfile\n");
5493 exit(1);
5494 } else
5495 exit(0);
5496 } else if (pid < 0)
5497 exit(1);
5499 setsid();
5501 pid = fork();
5502 if (pid > 0)
5503 exit(0);
5504 else if (pid < 0)
5505 exit(1);
5507 umask(027);
5509 signal(SIGTSTP, SIG_IGN);
5510 signal(SIGTTOU, SIG_IGN);
5511 signal(SIGTTIN, SIG_IGN);
5513 #endif
5515 #if USE_KVM
5516 if (kvm_enabled()) {
5517 if (kvm_qemu_init() < 0) {
5518 extern int kvm_allowed;
5519 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5520 #ifdef NO_CPU_EMULATION
5521 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5522 exit(1);
5523 #endif
5524 kvm_allowed = 0;
5527 #endif
5529 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5530 if (daemonize) {
5531 uint8_t status = 1;
5532 write(fds[1], &status, 1);
5533 } else
5534 fprintf(stderr, "Could not acquire pid file\n");
5535 exit(1);
5538 #ifdef USE_KQEMU
5539 if (smp_cpus > 1)
5540 kqemu_allowed = 0;
5541 #endif
5542 linux_boot = (kernel_filename != NULL);
5543 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5545 if (!linux_boot && net_boot == 0 &&
5546 !machine->nodisk_ok && nb_drives_opt == 0)
5547 help(1);
5549 if (!linux_boot && *kernel_cmdline != '\0') {
5550 fprintf(stderr, "-append only allowed with -kernel option\n");
5551 exit(1);
5554 if (!linux_boot && initrd_filename != NULL) {
5555 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5556 exit(1);
5559 /* boot to floppy or the default cd if no hard disk defined yet */
5560 if (!boot_devices[0]) {
5561 boot_devices = "cad";
5563 setvbuf(stdout, NULL, _IOLBF, 0);
5565 init_timers();
5566 if (init_timer_alarm() < 0) {
5567 fprintf(stderr, "could not initialize alarm timer\n");
5568 exit(1);
5570 if (use_icount && icount_time_shift < 0) {
5571 use_icount = 2;
5572 /* 125MIPS seems a reasonable initial guess at the guest speed.
5573 It will be corrected fairly quickly anyway. */
5574 icount_time_shift = 3;
5575 init_icount_adjust();
5578 #ifdef _WIN32
5579 socket_init();
5580 #endif
5582 /* init network clients */
5583 if (nb_net_clients == 0) {
5584 /* if no clients, we use a default config */
5585 net_clients[nb_net_clients++] = "nic";
5586 #ifdef CONFIG_SLIRP
5587 net_clients[nb_net_clients++] = "user";
5588 #endif
5591 for(i = 0;i < nb_net_clients; i++) {
5592 if (net_client_parse(net_clients[i]) < 0)
5593 exit(1);
5595 net_client_check();
5597 #ifdef TARGET_I386
5598 /* XXX: this should be moved in the PC machine instantiation code */
5599 if (net_boot != 0) {
5600 int netroms = 0;
5601 for (i = 0; i < nb_nics && i < 4; i++) {
5602 const char *model = nd_table[i].model;
5603 char buf[1024];
5604 if (net_boot & (1 << i)) {
5605 if (model == NULL)
5606 model = "rtl8139";
5607 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5608 if (get_image_size(buf) > 0) {
5609 if (nb_option_roms >= MAX_OPTION_ROMS) {
5610 fprintf(stderr, "Too many option ROMs\n");
5611 exit(1);
5613 option_rom[nb_option_roms] = strdup(buf);
5614 nb_option_roms++;
5615 netroms++;
5619 if (netroms == 0) {
5620 fprintf(stderr, "No valid PXE rom found for network device\n");
5621 exit(1);
5624 #endif
5626 /* init the bluetooth world */
5627 for (i = 0; i < nb_bt_opts; i++)
5628 if (bt_parse(bt_opts[i]))
5629 exit(1);
5631 /* init the memory */
5632 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5634 if (machine->ram_require & RAMSIZE_FIXED) {
5635 if (ram_size > 0) {
5636 if (ram_size < phys_ram_size) {
5637 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5638 machine->name, (unsigned long long) phys_ram_size);
5639 exit(-1);
5642 phys_ram_size = ram_size;
5643 } else
5644 ram_size = phys_ram_size;
5645 } else {
5646 if (ram_size == 0)
5647 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5649 phys_ram_size += ram_size;
5652 /* Initialize kvm */
5653 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5654 #define KVM_EXTRA_PAGES 3
5655 #else
5656 #define KVM_EXTRA_PAGES 0
5657 #endif
5658 if (kvm_enabled()) {
5659 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5660 if (kvm_qemu_create_context() < 0) {
5661 fprintf(stderr, "Could not create KVM context\n");
5662 exit(1);
5666 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5667 if (!phys_ram_base) {
5668 fprintf(stderr, "Could not allocate physical memory\n");
5669 exit(1);
5672 /* init the dynamic translator */
5673 cpu_exec_init_all(tb_size * 1024 * 1024);
5675 bdrv_init();
5677 /* we always create the cdrom drive, even if no disk is there */
5679 if (nb_drives_opt < MAX_DRIVES)
5680 drive_add(NULL, CDROM_ALIAS);
5682 /* we always create at least one floppy */
5684 if (nb_drives_opt < MAX_DRIVES)
5685 drive_add(NULL, FD_ALIAS, 0);
5687 /* we always create one sd slot, even if no card is in it */
5689 if (nb_drives_opt < MAX_DRIVES)
5690 drive_add(NULL, SD_ALIAS);
5692 /* open the virtual block devices
5693 * note that migration with device
5694 * hot add/remove is broken.
5696 for(i = 0; i < nb_drives_opt; i++)
5697 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5698 exit(1);
5700 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5701 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5703 /* terminal init */
5704 memset(&display_state, 0, sizeof(display_state));
5705 if (nographic) {
5706 if (curses) {
5707 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5708 exit(1);
5710 /* nearly nothing to do */
5711 dumb_display_init(ds);
5712 } else if (vnc_display != NULL) {
5713 vnc_display_init(ds);
5714 if (vnc_display_open(ds, vnc_display) < 0)
5715 exit(1);
5716 } else
5717 #if defined(CONFIG_CURSES)
5718 if (curses) {
5719 curses_display_init(ds, full_screen);
5720 } else
5721 #endif
5723 #if defined(CONFIG_SDL)
5724 sdl_display_init(ds, full_screen, no_frame);
5725 #elif defined(CONFIG_COCOA)
5726 cocoa_display_init(ds, full_screen);
5727 #else
5728 dumb_display_init(ds);
5729 #endif
5732 #ifndef _WIN32
5733 /* must be after terminal init, SDL library changes signal handlers */
5734 termsig_setup();
5735 #endif
5737 /* Maintain compatibility with multiple stdio monitors */
5738 if (!strcmp(monitor_device,"stdio")) {
5739 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5740 const char *devname = serial_devices[i];
5741 if (devname && !strcmp(devname,"mon:stdio")) {
5742 monitor_device = NULL;
5743 break;
5744 } else if (devname && !strcmp(devname,"stdio")) {
5745 monitor_device = NULL;
5746 serial_devices[i] = "mon:stdio";
5747 break;
5751 if (monitor_device) {
5752 monitor_hd = qemu_chr_open("monitor", monitor_device);
5753 if (!monitor_hd) {
5754 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5755 exit(1);
5757 monitor_init(monitor_hd, !nographic);
5760 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5761 const char *devname = serial_devices[i];
5762 if (devname && strcmp(devname, "none")) {
5763 char label[32];
5764 snprintf(label, sizeof(label), "serial%d", i);
5765 serial_hds[i] = qemu_chr_open(label, devname);
5766 if (!serial_hds[i]) {
5767 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5768 devname);
5769 exit(1);
5771 if (strstart(devname, "vc", 0))
5772 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5776 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5777 const char *devname = parallel_devices[i];
5778 if (devname && strcmp(devname, "none")) {
5779 char label[32];
5780 snprintf(label, sizeof(label), "parallel%d", i);
5781 parallel_hds[i] = qemu_chr_open(label, devname);
5782 if (!parallel_hds[i]) {
5783 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5784 devname);
5785 exit(1);
5787 if (strstart(devname, "vc", 0))
5788 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5792 if (kvm_enabled())
5793 kvm_init_ap();
5795 #ifdef KVM_UPSTREAM
5796 if (kvm_enabled()) {
5797 int ret;
5799 ret = kvm_init(smp_cpus);
5800 if (ret < 0) {
5801 fprintf(stderr, "failed to initialize KVM\n");
5802 exit(1);
5805 #endif
5807 machine->init(ram_size, vga_ram_size, boot_devices, ds,
5808 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5810 current_machine = machine;
5812 /* Set KVM's vcpu state to qemu's initial CPUState. */
5813 if (kvm_enabled()) {
5814 int ret;
5816 ret = kvm_sync_vcpus();
5817 if (ret < 0) {
5818 fprintf(stderr, "failed to initialize vcpus\n");
5819 exit(1);
5823 /* init USB devices */
5824 if (usb_enabled) {
5825 for(i = 0; i < usb_devices_index; i++) {
5826 if (usb_device_add(usb_devices[i]) < 0) {
5827 fprintf(stderr, "Warning: could not add USB device %s\n",
5828 usb_devices[i]);
5833 if (display_state.dpy_refresh) {
5834 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5835 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5838 #ifdef CONFIG_GDBSTUB
5839 if (use_gdbstub) {
5840 /* XXX: use standard host:port notation and modify options
5841 accordingly. */
5842 if (gdbserver_start(gdbstub_port) < 0) {
5843 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5844 gdbstub_port);
5845 exit(1);
5848 #endif
5850 if (loadvm)
5851 do_loadvm(loadvm);
5853 if (incoming) {
5854 autostart = 0; /* fixme how to deal with -daemonize */
5855 qemu_start_incoming_migration(incoming);
5859 /* XXX: simplify init */
5860 read_passwords();
5861 if (autostart) {
5862 vm_start();
5866 if (daemonize) {
5867 uint8_t status = 0;
5868 ssize_t len;
5869 int fd;
5871 again1:
5872 len = write(fds[1], &status, 1);
5873 if (len == -1 && (errno == EINTR))
5874 goto again1;
5876 if (len != 1)
5877 exit(1);
5879 chdir("/");
5880 TFR(fd = open("/dev/null", O_RDWR));
5881 if (fd == -1)
5882 exit(1);
5884 dup2(fd, 0);
5885 dup2(fd, 1);
5886 dup2(fd, 2);
5888 close(fd);
5891 main_loop();
5892 quit_timers();
5893 net_cleanup();
5895 return 0;