Fix non-x86 NMI hooks
[qemu-kvm/fedora.git] / vl.c
blob0eea3b327f7eb89374932ded7a8d55797c0633b4
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "block.h"
40 #include "audio/audio.h"
41 #include "hw/device-assignment.h"
42 #include "migration.h"
43 #include "kvm.h"
44 #include "balloon.h"
45 #include "qemu-kvm.h"
47 #include <unistd.h>
48 #include <fcntl.h>
49 #include <signal.h>
50 #include <time.h>
51 #include <errno.h>
52 #include <sys/time.h>
53 #include <zlib.h>
55 #ifndef _WIN32
56 #include <sys/times.h>
57 #include <sys/wait.h>
58 #include <termios.h>
59 #include <sys/mman.h>
60 #include <sys/ioctl.h>
61 #include <sys/resource.h>
62 #include <sys/socket.h>
63 #include <netinet/in.h>
64 #include <net/if.h>
65 #if defined(__NetBSD__)
66 #include <net/if_tap.h>
67 #endif
68 #ifdef __linux__
69 #include <linux/if_tun.h>
70 #endif
71 #include <arpa/inet.h>
72 #include <dirent.h>
73 #include <netdb.h>
74 #include <sys/select.h>
75 #ifdef _BSD
76 #include <sys/stat.h>
77 #ifdef __FreeBSD__
78 #include <libutil.h>
79 #else
80 #include <util.h>
81 #endif
82 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
83 #include <freebsd/stdlib.h>
84 #else
85 #ifdef __linux__
86 #include <pty.h>
87 #include <malloc.h>
88 #include <linux/rtc.h>
90 /* For the benefit of older linux systems which don't supply it,
91 we use a local copy of hpet.h. */
92 /* #include <linux/hpet.h> */
93 #include "hpet.h"
95 #include <linux/ppdev.h>
96 #include <linux/parport.h>
97 #endif
98 #ifdef __sun__
99 #include <sys/stat.h>
100 #include <sys/ethernet.h>
101 #include <sys/sockio.h>
102 #include <netinet/arp.h>
103 #include <netinet/in.h>
104 #include <netinet/in_systm.h>
105 #include <netinet/ip.h>
106 #include <netinet/ip_icmp.h> // must come after ip.h
107 #include <netinet/udp.h>
108 #include <netinet/tcp.h>
109 #include <net/if.h>
110 #include <syslog.h>
111 #include <stropts.h>
112 #endif
113 #endif
114 #endif
116 #include "qemu_socket.h"
118 #if defined(CONFIG_SLIRP)
119 #include "libslirp.h"
120 #endif
122 #if defined(__OpenBSD__)
123 #include <util.h>
124 #endif
126 #if defined(CONFIG_VDE)
127 #include <libvdeplug.h>
128 #endif
130 #ifdef _WIN32
131 #include <malloc.h>
132 #include <sys/timeb.h>
133 #include <mmsystem.h>
134 #define getopt_long_only getopt_long
135 #define memalign(align, size) malloc(size)
136 #endif
138 #ifdef CONFIG_SDL
139 #ifdef __APPLE__
140 #include <SDL/SDL.h>
141 #endif
142 #endif /* CONFIG_SDL */
144 #ifdef CONFIG_COCOA
145 #undef main
146 #define main qemu_main
147 #endif /* CONFIG_COCOA */
149 #include "disas.h"
151 #include "exec-all.h"
153 #include "qemu-kvm.h"
155 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
156 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
157 #ifdef __sun__
158 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
159 #else
160 #define SMBD_COMMAND "/usr/sbin/smbd"
161 #endif
163 //#define DEBUG_UNUSED_IOPORT
164 //#define DEBUG_IOPORT
165 //#define DEBUG_NET
166 //#define DEBUG_SLIRP
168 #ifdef TARGET_PPC
169 #define DEFAULT_RAM_SIZE 144
170 #else
171 #define DEFAULT_RAM_SIZE 128
172 #endif
174 /* Max number of USB devices that can be specified on the commandline. */
175 #define MAX_USB_CMDLINE 8
177 /* Max number of bluetooth switches on the commandline. */
178 #define MAX_BT_CMDLINE 10
180 /* XXX: use a two level table to limit memory usage */
181 #define MAX_IOPORTS 65536
183 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
184 const char *bios_name = NULL;
185 static void *ioport_opaque[MAX_IOPORTS];
186 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
187 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
188 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
189 to store the VM snapshots */
190 DriveInfo drives_table[MAX_DRIVES+1];
191 int nb_drives;
192 int extboot_drive = -1;
193 static int vga_ram_size;
194 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
195 DisplayState display_state;
196 int nographic;
197 static int curses;
198 const char* keyboard_layout = NULL;
199 int64_t ticks_per_sec;
200 ram_addr_t ram_size;
201 int nb_nics;
202 NICInfo nd_table[MAX_NICS];
203 int vm_running;
204 static int rtc_utc = 1;
205 static int rtc_date_offset = -1; /* -1 means no change */
206 int cirrus_vga_enabled = 1;
207 int vmsvga_enabled = 0;
208 #ifdef TARGET_SPARC
209 int graphic_width = 1024;
210 int graphic_height = 768;
211 int graphic_depth = 8;
212 #else
213 int graphic_width = 800;
214 int graphic_height = 600;
215 int graphic_depth = 15;
216 #endif
217 static int full_screen = 0;
218 #ifdef CONFIG_SDL
219 static int no_frame = 0;
220 #endif
221 int no_quit = 0;
222 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
223 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
224 #ifdef TARGET_I386
225 int win2k_install_hack = 0;
226 #endif
227 int usb_enabled = 0;
228 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
229 int assigned_devices_index;
230 int smp_cpus = 1;
231 const char *vnc_display;
232 int acpi_enabled = 1;
233 int fd_bootchk = 1;
234 int no_reboot = 0;
235 int no_shutdown = 0;
236 int cursor_hide = 1;
237 int graphic_rotate = 0;
238 int daemonize = 0;
239 const char *incoming;
240 const char *option_rom[MAX_OPTION_ROMS];
241 int nb_option_roms;
242 int semihosting_enabled = 0;
243 int time_drift_fix = 0;
244 unsigned int kvm_shadow_memory = 0;
245 const char *mem_path = NULL;
246 int hpagesize = 0;
247 const char *cpu_vendor_string;
248 #ifdef TARGET_ARM
249 int old_param = 0;
250 #endif
251 const char *qemu_name;
252 int alt_grab = 0;
253 #ifdef TARGET_SPARC
254 unsigned int nb_prom_envs = 0;
255 const char *prom_envs[MAX_PROM_ENVS];
256 #endif
257 int nb_drives_opt;
258 struct drive_opt drives_opt[MAX_DRIVES];
260 static CPUState *cur_cpu;
261 static CPUState *next_cpu;
262 static int event_pending = 1;
263 /* Conversion factor from emulated instructions to virtual clock ticks. */
264 static int icount_time_shift;
265 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
266 #define MAX_ICOUNT_SHIFT 10
267 /* Compensate for varying guest execution speed. */
268 static int64_t qemu_icount_bias;
269 static QEMUTimer *icount_rt_timer;
270 static QEMUTimer *icount_vm_timer;
272 uint8_t qemu_uuid[16];
274 /* KVM runs the main loop in a separate thread. If we update one of the lists
275 * that are polled before or after select(), we need to make sure to break out
276 * of the select() to ensure the new item is serviced.
278 static void main_loop_break(void)
280 if (kvm_enabled())
281 qemu_kvm_notify_work();
284 /***********************************************************/
285 /* x86 ISA bus support */
287 target_phys_addr_t isa_mem_base = 0;
288 PicState2 *isa_pic;
290 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
291 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
293 static uint32_t ioport_read(int index, uint32_t address)
295 static IOPortReadFunc *default_func[3] = {
296 default_ioport_readb,
297 default_ioport_readw,
298 default_ioport_readl
300 IOPortReadFunc *func = ioport_read_table[index][address];
301 if (!func)
302 func = default_func[index];
303 return func(ioport_opaque[address], address);
306 static void ioport_write(int index, uint32_t address, uint32_t data)
308 static IOPortWriteFunc *default_func[3] = {
309 default_ioport_writeb,
310 default_ioport_writew,
311 default_ioport_writel
313 IOPortWriteFunc *func = ioport_write_table[index][address];
314 if (!func)
315 func = default_func[index];
316 func(ioport_opaque[address], address, data);
319 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
321 #ifdef DEBUG_UNUSED_IOPORT
322 fprintf(stderr, "unused inb: port=0x%04x\n", address);
323 #endif
324 return 0xff;
327 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
329 #ifdef DEBUG_UNUSED_IOPORT
330 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
331 #endif
334 /* default is to make two byte accesses */
335 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
337 uint32_t data;
338 data = ioport_read(0, address);
339 address = (address + 1) & (MAX_IOPORTS - 1);
340 data |= ioport_read(0, address) << 8;
341 return data;
344 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
346 ioport_write(0, address, data & 0xff);
347 address = (address + 1) & (MAX_IOPORTS - 1);
348 ioport_write(0, address, (data >> 8) & 0xff);
351 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
353 #ifdef DEBUG_UNUSED_IOPORT
354 fprintf(stderr, "unused inl: port=0x%04x\n", address);
355 #endif
356 return 0xffffffff;
359 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
361 #ifdef DEBUG_UNUSED_IOPORT
362 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
363 #endif
366 /* size is the word size in byte */
367 int register_ioport_read(int start, int length, int size,
368 IOPortReadFunc *func, void *opaque)
370 int i, bsize;
372 if (size == 1) {
373 bsize = 0;
374 } else if (size == 2) {
375 bsize = 1;
376 } else if (size == 4) {
377 bsize = 2;
378 } else {
379 hw_error("register_ioport_read: invalid size");
380 return -1;
382 for(i = start; i < start + length; i += size) {
383 ioport_read_table[bsize][i] = func;
384 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
385 hw_error("register_ioport_read: invalid opaque");
386 ioport_opaque[i] = opaque;
388 return 0;
391 /* size is the word size in byte */
392 int register_ioport_write(int start, int length, int size,
393 IOPortWriteFunc *func, void *opaque)
395 int i, bsize;
397 if (size == 1) {
398 bsize = 0;
399 } else if (size == 2) {
400 bsize = 1;
401 } else if (size == 4) {
402 bsize = 2;
403 } else {
404 hw_error("register_ioport_write: invalid size");
405 return -1;
407 for(i = start; i < start + length; i += size) {
408 ioport_write_table[bsize][i] = func;
409 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
410 hw_error("register_ioport_write: invalid opaque");
411 ioport_opaque[i] = opaque;
413 return 0;
416 void isa_unassign_ioport(int start, int length)
418 int i;
420 for(i = start; i < start + length; i++) {
421 ioport_read_table[0][i] = default_ioport_readb;
422 ioport_read_table[1][i] = default_ioport_readw;
423 ioport_read_table[2][i] = default_ioport_readl;
425 ioport_write_table[0][i] = default_ioport_writeb;
426 ioport_write_table[1][i] = default_ioport_writew;
427 ioport_write_table[2][i] = default_ioport_writel;
429 ioport_opaque[i] = NULL;
433 /***********************************************************/
435 void cpu_outb(CPUState *env, int addr, int val)
437 #ifdef DEBUG_IOPORT
438 if (loglevel & CPU_LOG_IOPORT)
439 fprintf(logfile, "outb: %04x %02x\n", addr, val);
440 #endif
441 ioport_write(0, addr, val);
442 #ifdef USE_KQEMU
443 if (env)
444 env->last_io_time = cpu_get_time_fast();
445 #endif
448 void cpu_outw(CPUState *env, int addr, int val)
450 #ifdef DEBUG_IOPORT
451 if (loglevel & CPU_LOG_IOPORT)
452 fprintf(logfile, "outw: %04x %04x\n", addr, val);
453 #endif
454 ioport_write(1, addr, val);
455 #ifdef USE_KQEMU
456 if (env)
457 env->last_io_time = cpu_get_time_fast();
458 #endif
461 void cpu_outl(CPUState *env, int addr, int val)
463 #ifdef DEBUG_IOPORT
464 if (loglevel & CPU_LOG_IOPORT)
465 fprintf(logfile, "outl: %04x %08x\n", addr, val);
466 #endif
467 ioport_write(2, addr, val);
468 #ifdef USE_KQEMU
469 if (env)
470 env->last_io_time = cpu_get_time_fast();
471 #endif
474 int cpu_inb(CPUState *env, int addr)
476 int val;
477 val = ioport_read(0, addr);
478 #ifdef DEBUG_IOPORT
479 if (loglevel & CPU_LOG_IOPORT)
480 fprintf(logfile, "inb : %04x %02x\n", addr, val);
481 #endif
482 #ifdef USE_KQEMU
483 if (env)
484 env->last_io_time = cpu_get_time_fast();
485 #endif
486 return val;
489 int cpu_inw(CPUState *env, int addr)
491 int val;
492 val = ioport_read(1, addr);
493 #ifdef DEBUG_IOPORT
494 if (loglevel & CPU_LOG_IOPORT)
495 fprintf(logfile, "inw : %04x %04x\n", addr, val);
496 #endif
497 #ifdef USE_KQEMU
498 if (env)
499 env->last_io_time = cpu_get_time_fast();
500 #endif
501 return val;
504 int cpu_inl(CPUState *env, int addr)
506 int val;
507 val = ioport_read(2, addr);
508 #ifdef DEBUG_IOPORT
509 if (loglevel & CPU_LOG_IOPORT)
510 fprintf(logfile, "inl : %04x %08x\n", addr, val);
511 #endif
512 #ifdef USE_KQEMU
513 if (env)
514 env->last_io_time = cpu_get_time_fast();
515 #endif
516 return val;
519 /***********************************************************/
520 void hw_error(const char *fmt, ...)
522 va_list ap;
523 CPUState *env;
525 va_start(ap, fmt);
526 fprintf(stderr, "qemu: hardware error: ");
527 vfprintf(stderr, fmt, ap);
528 fprintf(stderr, "\n");
529 for(env = first_cpu; env != NULL; env = env->next_cpu) {
530 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
531 #ifdef TARGET_I386
532 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
533 #else
534 cpu_dump_state(env, stderr, fprintf, 0);
535 #endif
537 va_end(ap);
538 abort();
541 /***************/
542 /* ballooning */
544 static QEMUBalloonEvent *qemu_balloon_event;
545 void *qemu_balloon_event_opaque;
547 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
549 qemu_balloon_event = func;
550 qemu_balloon_event_opaque = opaque;
553 void qemu_balloon(ram_addr_t target)
555 if (qemu_balloon_event)
556 qemu_balloon_event(qemu_balloon_event_opaque, target);
559 ram_addr_t qemu_balloon_status(void)
561 if (qemu_balloon_event)
562 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
563 return 0;
566 /***********************************************************/
567 /* keyboard/mouse */
569 static QEMUPutKBDEvent *qemu_put_kbd_event;
570 static void *qemu_put_kbd_event_opaque;
571 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
572 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
574 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
576 qemu_put_kbd_event_opaque = opaque;
577 qemu_put_kbd_event = func;
580 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
581 void *opaque, int absolute,
582 const char *name)
584 QEMUPutMouseEntry *s, *cursor;
586 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
587 if (!s)
588 return NULL;
590 s->qemu_put_mouse_event = func;
591 s->qemu_put_mouse_event_opaque = opaque;
592 s->qemu_put_mouse_event_absolute = absolute;
593 s->qemu_put_mouse_event_name = qemu_strdup(name);
594 s->next = NULL;
596 if (!qemu_put_mouse_event_head) {
597 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
598 return s;
601 cursor = qemu_put_mouse_event_head;
602 while (cursor->next != NULL)
603 cursor = cursor->next;
605 cursor->next = s;
606 qemu_put_mouse_event_current = s;
608 return s;
611 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
613 QEMUPutMouseEntry *prev = NULL, *cursor;
615 if (!qemu_put_mouse_event_head || entry == NULL)
616 return;
618 cursor = qemu_put_mouse_event_head;
619 while (cursor != NULL && cursor != entry) {
620 prev = cursor;
621 cursor = cursor->next;
624 if (cursor == NULL) // does not exist or list empty
625 return;
626 else if (prev == NULL) { // entry is head
627 qemu_put_mouse_event_head = cursor->next;
628 if (qemu_put_mouse_event_current == entry)
629 qemu_put_mouse_event_current = cursor->next;
630 qemu_free(entry->qemu_put_mouse_event_name);
631 qemu_free(entry);
632 return;
635 prev->next = entry->next;
637 if (qemu_put_mouse_event_current == entry)
638 qemu_put_mouse_event_current = prev;
640 qemu_free(entry->qemu_put_mouse_event_name);
641 qemu_free(entry);
644 void kbd_put_keycode(int keycode)
646 if (qemu_put_kbd_event) {
647 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
651 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
653 QEMUPutMouseEvent *mouse_event;
654 void *mouse_event_opaque;
655 int width;
657 if (!qemu_put_mouse_event_current) {
658 return;
661 mouse_event =
662 qemu_put_mouse_event_current->qemu_put_mouse_event;
663 mouse_event_opaque =
664 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
666 if (mouse_event) {
667 if (graphic_rotate) {
668 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
669 width = 0x7fff;
670 else
671 width = graphic_width - 1;
672 mouse_event(mouse_event_opaque,
673 width - dy, dx, dz, buttons_state);
674 } else
675 mouse_event(mouse_event_opaque,
676 dx, dy, dz, buttons_state);
680 int kbd_mouse_is_absolute(void)
682 if (!qemu_put_mouse_event_current)
683 return 0;
685 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
688 void do_info_mice(void)
690 QEMUPutMouseEntry *cursor;
691 int index = 0;
693 if (!qemu_put_mouse_event_head) {
694 term_printf("No mouse devices connected\n");
695 return;
698 term_printf("Mouse devices available:\n");
699 cursor = qemu_put_mouse_event_head;
700 while (cursor != NULL) {
701 term_printf("%c Mouse #%d: %s\n",
702 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
703 index, cursor->qemu_put_mouse_event_name);
704 index++;
705 cursor = cursor->next;
709 void do_mouse_set(int index)
711 QEMUPutMouseEntry *cursor;
712 int i = 0;
714 if (!qemu_put_mouse_event_head) {
715 term_printf("No mouse devices connected\n");
716 return;
719 cursor = qemu_put_mouse_event_head;
720 while (cursor != NULL && index != i) {
721 i++;
722 cursor = cursor->next;
725 if (cursor != NULL)
726 qemu_put_mouse_event_current = cursor;
727 else
728 term_printf("Mouse at given index not found\n");
731 /* compute with 96 bit intermediate result: (a*b)/c */
732 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
734 union {
735 uint64_t ll;
736 struct {
737 #ifdef WORDS_BIGENDIAN
738 uint32_t high, low;
739 #else
740 uint32_t low, high;
741 #endif
742 } l;
743 } u, res;
744 uint64_t rl, rh;
746 u.ll = a;
747 rl = (uint64_t)u.l.low * (uint64_t)b;
748 rh = (uint64_t)u.l.high * (uint64_t)b;
749 rh += (rl >> 32);
750 res.l.high = rh / c;
751 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
752 return res.ll;
755 /***********************************************************/
756 /* real time host monotonic timer */
758 #define QEMU_TIMER_BASE 1000000000LL
760 #ifdef WIN32
762 static int64_t clock_freq;
764 static void init_get_clock(void)
766 LARGE_INTEGER freq;
767 int ret;
768 ret = QueryPerformanceFrequency(&freq);
769 if (ret == 0) {
770 fprintf(stderr, "Could not calibrate ticks\n");
771 exit(1);
773 clock_freq = freq.QuadPart;
776 static int64_t get_clock(void)
778 LARGE_INTEGER ti;
779 QueryPerformanceCounter(&ti);
780 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
783 #else
785 static int use_rt_clock;
787 static void init_get_clock(void)
789 use_rt_clock = 0;
790 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
792 struct timespec ts;
793 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
794 use_rt_clock = 1;
797 #endif
800 static int64_t get_clock(void)
802 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
803 if (use_rt_clock) {
804 struct timespec ts;
805 clock_gettime(CLOCK_MONOTONIC, &ts);
806 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
807 } else
808 #endif
810 /* XXX: using gettimeofday leads to problems if the date
811 changes, so it should be avoided. */
812 struct timeval tv;
813 gettimeofday(&tv, NULL);
814 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
817 #endif
819 /* Return the virtual CPU time, based on the instruction counter. */
820 static int64_t cpu_get_icount(void)
822 int64_t icount;
823 CPUState *env = cpu_single_env;;
824 icount = qemu_icount;
825 if (env) {
826 if (!can_do_io(env))
827 fprintf(stderr, "Bad clock read\n");
828 icount -= (env->icount_decr.u16.low + env->icount_extra);
830 return qemu_icount_bias + (icount << icount_time_shift);
833 /***********************************************************/
834 /* guest cycle counter */
836 static int64_t cpu_ticks_prev;
837 static int64_t cpu_ticks_offset;
838 static int64_t cpu_clock_offset;
839 static int cpu_ticks_enabled;
841 /* return the host CPU cycle counter and handle stop/restart */
842 int64_t cpu_get_ticks(void)
844 if (use_icount) {
845 return cpu_get_icount();
847 if (!cpu_ticks_enabled) {
848 return cpu_ticks_offset;
849 } else {
850 int64_t ticks;
851 ticks = cpu_get_real_ticks();
852 if (cpu_ticks_prev > ticks) {
853 /* Note: non increasing ticks may happen if the host uses
854 software suspend */
855 cpu_ticks_offset += cpu_ticks_prev - ticks;
857 cpu_ticks_prev = ticks;
858 return ticks + cpu_ticks_offset;
862 /* return the host CPU monotonic timer and handle stop/restart */
863 static int64_t cpu_get_clock(void)
865 int64_t ti;
866 if (!cpu_ticks_enabled) {
867 return cpu_clock_offset;
868 } else {
869 ti = get_clock();
870 return ti + cpu_clock_offset;
874 /* enable cpu_get_ticks() */
875 void cpu_enable_ticks(void)
877 if (!cpu_ticks_enabled) {
878 cpu_ticks_offset -= cpu_get_real_ticks();
879 cpu_clock_offset -= get_clock();
880 cpu_ticks_enabled = 1;
884 /* disable cpu_get_ticks() : the clock is stopped. You must not call
885 cpu_get_ticks() after that. */
886 void cpu_disable_ticks(void)
888 if (cpu_ticks_enabled) {
889 cpu_ticks_offset = cpu_get_ticks();
890 cpu_clock_offset = cpu_get_clock();
891 cpu_ticks_enabled = 0;
895 /***********************************************************/
896 /* timers */
898 #define QEMU_TIMER_REALTIME 0
899 #define QEMU_TIMER_VIRTUAL 1
901 struct QEMUClock {
902 int type;
903 /* XXX: add frequency */
906 struct QEMUTimer {
907 QEMUClock *clock;
908 int64_t expire_time;
909 QEMUTimerCB *cb;
910 void *opaque;
911 struct QEMUTimer *next;
914 struct qemu_alarm_timer {
915 char const *name;
916 unsigned int flags;
918 int (*start)(struct qemu_alarm_timer *t);
919 void (*stop)(struct qemu_alarm_timer *t);
920 void (*rearm)(struct qemu_alarm_timer *t);
921 void *priv;
924 #define ALARM_FLAG_DYNTICKS 0x1
925 #define ALARM_FLAG_EXPIRED 0x2
927 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
929 return t->flags & ALARM_FLAG_DYNTICKS;
932 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
934 if (!alarm_has_dynticks(t))
935 return;
937 t->rearm(t);
940 /* TODO: MIN_TIMER_REARM_US should be optimized */
941 #define MIN_TIMER_REARM_US 250
943 static struct qemu_alarm_timer *alarm_timer;
944 #ifndef _WIN32
945 static int alarm_timer_rfd, alarm_timer_wfd;
946 #endif
948 #ifdef _WIN32
950 struct qemu_alarm_win32 {
951 MMRESULT timerId;
952 HANDLE host_alarm;
953 unsigned int period;
954 } alarm_win32_data = {0, NULL, -1};
956 static int win32_start_timer(struct qemu_alarm_timer *t);
957 static void win32_stop_timer(struct qemu_alarm_timer *t);
958 static void win32_rearm_timer(struct qemu_alarm_timer *t);
960 #else
962 static int unix_start_timer(struct qemu_alarm_timer *t);
963 static void unix_stop_timer(struct qemu_alarm_timer *t);
965 #ifdef __linux__
967 static int dynticks_start_timer(struct qemu_alarm_timer *t);
968 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
969 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
971 static int hpet_start_timer(struct qemu_alarm_timer *t);
972 static void hpet_stop_timer(struct qemu_alarm_timer *t);
974 static int rtc_start_timer(struct qemu_alarm_timer *t);
975 static void rtc_stop_timer(struct qemu_alarm_timer *t);
977 #endif /* __linux__ */
979 #endif /* _WIN32 */
981 /* Correlation between real and virtual time is always going to be
982 fairly approximate, so ignore small variation.
983 When the guest is idle real and virtual time will be aligned in
984 the IO wait loop. */
985 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
987 static void icount_adjust(void)
989 int64_t cur_time;
990 int64_t cur_icount;
991 int64_t delta;
992 static int64_t last_delta;
993 /* If the VM is not running, then do nothing. */
994 if (!vm_running)
995 return;
997 cur_time = cpu_get_clock();
998 cur_icount = qemu_get_clock(vm_clock);
999 delta = cur_icount - cur_time;
1000 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1001 if (delta > 0
1002 && last_delta + ICOUNT_WOBBLE < delta * 2
1003 && icount_time_shift > 0) {
1004 /* The guest is getting too far ahead. Slow time down. */
1005 icount_time_shift--;
1007 if (delta < 0
1008 && last_delta - ICOUNT_WOBBLE > delta * 2
1009 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1010 /* The guest is getting too far behind. Speed time up. */
1011 icount_time_shift++;
1013 last_delta = delta;
1014 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1017 static void icount_adjust_rt(void * opaque)
1019 qemu_mod_timer(icount_rt_timer,
1020 qemu_get_clock(rt_clock) + 1000);
1021 icount_adjust();
1024 static void icount_adjust_vm(void * opaque)
1026 qemu_mod_timer(icount_vm_timer,
1027 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1028 icount_adjust();
1031 static void init_icount_adjust(void)
1033 /* Have both realtime and virtual time triggers for speed adjustment.
1034 The realtime trigger catches emulated time passing too slowly,
1035 the virtual time trigger catches emulated time passing too fast.
1036 Realtime triggers occur even when idle, so use them less frequently
1037 than VM triggers. */
1038 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1039 qemu_mod_timer(icount_rt_timer,
1040 qemu_get_clock(rt_clock) + 1000);
1041 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1042 qemu_mod_timer(icount_vm_timer,
1043 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1046 static struct qemu_alarm_timer alarm_timers[] = {
1047 #ifndef _WIN32
1048 #ifdef __linux__
1049 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1050 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1051 /* HPET - if available - is preferred */
1052 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1053 /* ...otherwise try RTC */
1054 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1055 #endif
1056 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1057 #else
1058 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1059 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1060 {"win32", 0, win32_start_timer,
1061 win32_stop_timer, NULL, &alarm_win32_data},
1062 #endif
1063 {NULL, }
1066 static void show_available_alarms(void)
1068 int i;
1070 printf("Available alarm timers, in order of precedence:\n");
1071 for (i = 0; alarm_timers[i].name; i++)
1072 printf("%s\n", alarm_timers[i].name);
1075 static void configure_alarms(char const *opt)
1077 int i;
1078 int cur = 0;
1079 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1080 char *arg;
1081 char *name;
1082 struct qemu_alarm_timer tmp;
1084 if (!strcmp(opt, "?")) {
1085 show_available_alarms();
1086 exit(0);
1089 arg = strdup(opt);
1091 /* Reorder the array */
1092 name = strtok(arg, ",");
1093 while (name) {
1094 for (i = 0; i < count && alarm_timers[i].name; i++) {
1095 if (!strcmp(alarm_timers[i].name, name))
1096 break;
1099 if (i == count) {
1100 fprintf(stderr, "Unknown clock %s\n", name);
1101 goto next;
1104 if (i < cur)
1105 /* Ignore */
1106 goto next;
1108 /* Swap */
1109 tmp = alarm_timers[i];
1110 alarm_timers[i] = alarm_timers[cur];
1111 alarm_timers[cur] = tmp;
1113 cur++;
1114 next:
1115 name = strtok(NULL, ",");
1118 free(arg);
1120 if (cur) {
1121 /* Disable remaining timers */
1122 for (i = cur; i < count; i++)
1123 alarm_timers[i].name = NULL;
1124 } else {
1125 show_available_alarms();
1126 exit(1);
1130 QEMUClock *rt_clock;
1131 QEMUClock *vm_clock;
1133 static QEMUTimer *active_timers[2];
1135 static QEMUClock *qemu_new_clock(int type)
1137 QEMUClock *clock;
1138 clock = qemu_mallocz(sizeof(QEMUClock));
1139 if (!clock)
1140 return NULL;
1141 clock->type = type;
1142 return clock;
1145 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1147 QEMUTimer *ts;
1149 ts = qemu_mallocz(sizeof(QEMUTimer));
1150 ts->clock = clock;
1151 ts->cb = cb;
1152 ts->opaque = opaque;
1153 return ts;
1156 void qemu_free_timer(QEMUTimer *ts)
1158 qemu_free(ts);
1161 /* stop a timer, but do not dealloc it */
1162 void qemu_del_timer(QEMUTimer *ts)
1164 QEMUTimer **pt, *t;
1166 /* NOTE: this code must be signal safe because
1167 qemu_timer_expired() can be called from a signal. */
1168 pt = &active_timers[ts->clock->type];
1169 for(;;) {
1170 t = *pt;
1171 if (!t)
1172 break;
1173 if (t == ts) {
1174 *pt = t->next;
1175 break;
1177 pt = &t->next;
1181 /* modify the current timer so that it will be fired when current_time
1182 >= expire_time. The corresponding callback will be called. */
1183 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1185 QEMUTimer **pt, *t;
1187 qemu_del_timer(ts);
1189 /* add the timer in the sorted list */
1190 /* NOTE: this code must be signal safe because
1191 qemu_timer_expired() can be called from a signal. */
1192 pt = &active_timers[ts->clock->type];
1193 for(;;) {
1194 t = *pt;
1195 if (!t)
1196 break;
1197 if (t->expire_time > expire_time)
1198 break;
1199 pt = &t->next;
1201 ts->expire_time = expire_time;
1202 ts->next = *pt;
1203 *pt = ts;
1205 /* Rearm if necessary */
1206 if (pt == &active_timers[ts->clock->type]) {
1207 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1208 qemu_rearm_alarm_timer(alarm_timer);
1210 /* Interrupt execution to force deadline recalculation. */
1211 if (use_icount && cpu_single_env) {
1212 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1217 int qemu_timer_pending(QEMUTimer *ts)
1219 QEMUTimer *t;
1220 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1221 if (t == ts)
1222 return 1;
1224 return 0;
1227 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1229 if (!timer_head)
1230 return 0;
1231 return (timer_head->expire_time <= current_time);
1234 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1236 QEMUTimer *ts;
1238 for(;;) {
1239 ts = *ptimer_head;
1240 if (!ts || ts->expire_time > current_time)
1241 break;
1242 /* remove timer from the list before calling the callback */
1243 *ptimer_head = ts->next;
1244 ts->next = NULL;
1246 /* run the callback (the timer list can be modified) */
1247 ts->cb(ts->opaque);
1251 int64_t qemu_get_clock(QEMUClock *clock)
1253 switch(clock->type) {
1254 case QEMU_TIMER_REALTIME:
1255 return get_clock() / 1000000;
1256 default:
1257 case QEMU_TIMER_VIRTUAL:
1258 if (use_icount) {
1259 return cpu_get_icount();
1260 } else {
1261 return cpu_get_clock();
1266 static void init_timers(void)
1268 init_get_clock();
1269 ticks_per_sec = QEMU_TIMER_BASE;
1270 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1271 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1274 /* save a timer */
1275 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1277 uint64_t expire_time;
1279 if (qemu_timer_pending(ts)) {
1280 expire_time = ts->expire_time;
1281 } else {
1282 expire_time = -1;
1284 qemu_put_be64(f, expire_time);
1287 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1289 uint64_t expire_time;
1291 expire_time = qemu_get_be64(f);
1292 if (expire_time != -1) {
1293 qemu_mod_timer(ts, expire_time);
1294 } else {
1295 qemu_del_timer(ts);
1299 static void timer_save(QEMUFile *f, void *opaque)
1301 if (cpu_ticks_enabled) {
1302 hw_error("cannot save state if virtual timers are running");
1304 qemu_put_be64(f, cpu_ticks_offset);
1305 qemu_put_be64(f, ticks_per_sec);
1306 qemu_put_be64(f, cpu_clock_offset);
1309 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1311 if (version_id != 1 && version_id != 2)
1312 return -EINVAL;
1313 if (cpu_ticks_enabled) {
1314 return -EINVAL;
1316 cpu_ticks_offset=qemu_get_be64(f);
1317 ticks_per_sec=qemu_get_be64(f);
1318 if (version_id == 2) {
1319 cpu_clock_offset=qemu_get_be64(f);
1321 return 0;
1324 #ifdef _WIN32
1325 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1326 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1327 #else
1328 static void host_alarm_handler(int host_signum)
1329 #endif
1331 #if 0
1332 #define DISP_FREQ 1000
1334 static int64_t delta_min = INT64_MAX;
1335 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1336 static int count;
1337 ti = qemu_get_clock(vm_clock);
1338 if (last_clock != 0) {
1339 delta = ti - last_clock;
1340 if (delta < delta_min)
1341 delta_min = delta;
1342 if (delta > delta_max)
1343 delta_max = delta;
1344 delta_cum += delta;
1345 if (++count == DISP_FREQ) {
1346 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1347 muldiv64(delta_min, 1000000, ticks_per_sec),
1348 muldiv64(delta_max, 1000000, ticks_per_sec),
1349 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1350 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1351 count = 0;
1352 delta_min = INT64_MAX;
1353 delta_max = 0;
1354 delta_cum = 0;
1357 last_clock = ti;
1359 #endif
1360 if (1 ||
1361 alarm_has_dynticks(alarm_timer) ||
1362 (!use_icount &&
1363 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1364 qemu_get_clock(vm_clock))) ||
1365 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1366 qemu_get_clock(rt_clock))) {
1367 CPUState *env = next_cpu;
1369 #ifdef _WIN32
1370 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1371 SetEvent(data->host_alarm);
1372 #else
1373 static const char byte = 0;
1374 write(alarm_timer_wfd, &byte, sizeof(byte));
1375 #endif
1376 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1378 if (env) {
1379 /* stop the currently executing cpu because a timer occured */
1380 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1381 #ifdef USE_KQEMU
1382 if (env->kqemu_enabled) {
1383 kqemu_cpu_interrupt(env);
1385 #endif
1387 event_pending = 1;
1391 static int64_t qemu_next_deadline(void)
1393 int64_t delta;
1395 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1396 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1397 qemu_get_clock(vm_clock);
1398 } else {
1399 /* To avoid problems with overflow limit this to 2^32. */
1400 delta = INT32_MAX;
1403 if (delta < 0)
1404 delta = 0;
1406 return delta;
1409 #if defined(__linux__) || defined(_WIN32)
1410 static uint64_t qemu_next_deadline_dyntick(void)
1412 int64_t delta;
1413 int64_t rtdelta;
1415 if (use_icount)
1416 delta = INT32_MAX;
1417 else
1418 delta = (qemu_next_deadline() + 999) / 1000;
1420 if (active_timers[QEMU_TIMER_REALTIME]) {
1421 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1422 qemu_get_clock(rt_clock))*1000;
1423 if (rtdelta < delta)
1424 delta = rtdelta;
1427 if (delta < MIN_TIMER_REARM_US)
1428 delta = MIN_TIMER_REARM_US;
1430 return delta;
1432 #endif
1434 #ifndef _WIN32
1436 /* Sets a specific flag */
1437 static int fcntl_setfl(int fd, int flag)
1439 int flags;
1441 flags = fcntl(fd, F_GETFL);
1442 if (flags == -1)
1443 return -errno;
1445 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1446 return -errno;
1448 return 0;
1451 #if defined(__linux__)
1453 #define RTC_FREQ 1024
1455 static void enable_sigio_timer(int fd)
1457 struct sigaction act;
1459 /* timer signal */
1460 sigfillset(&act.sa_mask);
1461 act.sa_flags = 0;
1462 act.sa_handler = host_alarm_handler;
1464 sigaction(SIGIO, &act, NULL);
1465 fcntl_setfl(fd, O_ASYNC);
1466 fcntl(fd, F_SETOWN, getpid());
1469 static int hpet_start_timer(struct qemu_alarm_timer *t)
1471 struct hpet_info info;
1472 int r, fd;
1474 fd = open("/dev/hpet", O_RDONLY);
1475 if (fd < 0)
1476 return -1;
1478 /* Set frequency */
1479 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1480 if (r < 0) {
1481 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1482 "error, but for better emulation accuracy type:\n"
1483 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1484 goto fail;
1487 /* Check capabilities */
1488 r = ioctl(fd, HPET_INFO, &info);
1489 if (r < 0)
1490 goto fail;
1492 /* Enable periodic mode */
1493 r = ioctl(fd, HPET_EPI, 0);
1494 if (info.hi_flags && (r < 0))
1495 goto fail;
1497 /* Enable interrupt */
1498 r = ioctl(fd, HPET_IE_ON, 0);
1499 if (r < 0)
1500 goto fail;
1502 enable_sigio_timer(fd);
1503 t->priv = (void *)(long)fd;
1505 return 0;
1506 fail:
1507 close(fd);
1508 return -1;
1511 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1513 int fd = (long)t->priv;
1515 close(fd);
1518 static int rtc_start_timer(struct qemu_alarm_timer *t)
1520 int rtc_fd;
1521 unsigned long current_rtc_freq = 0;
1523 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1524 if (rtc_fd < 0)
1525 return -1;
1526 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1527 if (current_rtc_freq != RTC_FREQ &&
1528 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1529 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1530 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1531 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1532 goto fail;
1534 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1535 fail:
1536 close(rtc_fd);
1537 return -1;
1540 enable_sigio_timer(rtc_fd);
1542 t->priv = (void *)(long)rtc_fd;
1544 return 0;
1547 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1549 int rtc_fd = (long)t->priv;
1551 close(rtc_fd);
1554 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1556 struct sigevent ev;
1557 timer_t host_timer;
1558 struct sigaction act;
1560 sigfillset(&act.sa_mask);
1561 act.sa_flags = 0;
1562 act.sa_handler = host_alarm_handler;
1564 sigaction(SIGALRM, &act, NULL);
1566 ev.sigev_value.sival_int = 0;
1567 ev.sigev_notify = SIGEV_SIGNAL;
1568 ev.sigev_signo = SIGALRM;
1570 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1571 perror("timer_create");
1573 /* disable dynticks */
1574 fprintf(stderr, "Dynamic Ticks disabled\n");
1576 return -1;
1579 t->priv = (void *)(long)host_timer;
1581 return 0;
1584 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1586 timer_t host_timer = (timer_t)(long)t->priv;
1588 timer_delete(host_timer);
1591 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1593 timer_t host_timer = (timer_t)(long)t->priv;
1594 struct itimerspec timeout;
1595 int64_t nearest_delta_us = INT64_MAX;
1596 int64_t current_us;
1598 if (!active_timers[QEMU_TIMER_REALTIME] &&
1599 !active_timers[QEMU_TIMER_VIRTUAL])
1600 return;
1602 nearest_delta_us = qemu_next_deadline_dyntick();
1604 /* check whether a timer is already running */
1605 if (timer_gettime(host_timer, &timeout)) {
1606 perror("gettime");
1607 fprintf(stderr, "Internal timer error: aborting\n");
1608 exit(1);
1610 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1611 if (current_us && current_us <= nearest_delta_us)
1612 return;
1614 timeout.it_interval.tv_sec = 0;
1615 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1616 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1617 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1618 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1619 perror("settime");
1620 fprintf(stderr, "Internal timer error: aborting\n");
1621 exit(1);
1625 #endif /* defined(__linux__) */
1627 static int unix_start_timer(struct qemu_alarm_timer *t)
1629 struct sigaction act;
1630 struct itimerval itv;
1631 int err;
1633 /* timer signal */
1634 sigfillset(&act.sa_mask);
1635 act.sa_flags = 0;
1636 act.sa_handler = host_alarm_handler;
1638 sigaction(SIGALRM, &act, NULL);
1640 itv.it_interval.tv_sec = 0;
1641 /* for i386 kernel 2.6 to get 1 ms */
1642 itv.it_interval.tv_usec = 999;
1643 itv.it_value.tv_sec = 0;
1644 itv.it_value.tv_usec = 10 * 1000;
1646 err = setitimer(ITIMER_REAL, &itv, NULL);
1647 if (err)
1648 return -1;
1650 return 0;
1653 static void unix_stop_timer(struct qemu_alarm_timer *t)
1655 struct itimerval itv;
1657 memset(&itv, 0, sizeof(itv));
1658 setitimer(ITIMER_REAL, &itv, NULL);
1661 #endif /* !defined(_WIN32) */
1663 static void try_to_rearm_timer(void *opaque)
1665 struct qemu_alarm_timer *t = opaque;
1666 #ifndef _WIN32
1667 ssize_t len;
1669 /* Drain the notify pipe */
1670 do {
1671 char buffer[512];
1672 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1673 } while ((len == -1 && errno == EINTR) || len > 0);
1674 #endif
1676 if (t->flags & ALARM_FLAG_EXPIRED) {
1677 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1678 qemu_rearm_alarm_timer(alarm_timer);
1682 #ifdef _WIN32
1684 static int win32_start_timer(struct qemu_alarm_timer *t)
1686 TIMECAPS tc;
1687 struct qemu_alarm_win32 *data = t->priv;
1688 UINT flags;
1690 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1691 if (!data->host_alarm) {
1692 perror("Failed CreateEvent");
1693 return -1;
1696 memset(&tc, 0, sizeof(tc));
1697 timeGetDevCaps(&tc, sizeof(tc));
1699 if (data->period < tc.wPeriodMin)
1700 data->period = tc.wPeriodMin;
1702 timeBeginPeriod(data->period);
1704 flags = TIME_CALLBACK_FUNCTION;
1705 if (alarm_has_dynticks(t))
1706 flags |= TIME_ONESHOT;
1707 else
1708 flags |= TIME_PERIODIC;
1710 data->timerId = timeSetEvent(1, // interval (ms)
1711 data->period, // resolution
1712 host_alarm_handler, // function
1713 (DWORD)t, // parameter
1714 flags);
1716 if (!data->timerId) {
1717 perror("Failed to initialize win32 alarm timer");
1719 timeEndPeriod(data->period);
1720 CloseHandle(data->host_alarm);
1721 return -1;
1724 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1726 return 0;
1729 static void win32_stop_timer(struct qemu_alarm_timer *t)
1731 struct qemu_alarm_win32 *data = t->priv;
1733 timeKillEvent(data->timerId);
1734 timeEndPeriod(data->period);
1736 CloseHandle(data->host_alarm);
1739 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1741 struct qemu_alarm_win32 *data = t->priv;
1742 uint64_t nearest_delta_us;
1744 if (!active_timers[QEMU_TIMER_REALTIME] &&
1745 !active_timers[QEMU_TIMER_VIRTUAL])
1746 return;
1748 nearest_delta_us = qemu_next_deadline_dyntick();
1749 nearest_delta_us /= 1000;
1751 timeKillEvent(data->timerId);
1753 data->timerId = timeSetEvent(1,
1754 data->period,
1755 host_alarm_handler,
1756 (DWORD)t,
1757 TIME_ONESHOT | TIME_PERIODIC);
1759 if (!data->timerId) {
1760 perror("Failed to re-arm win32 alarm timer");
1762 timeEndPeriod(data->period);
1763 CloseHandle(data->host_alarm);
1764 exit(1);
1768 #endif /* _WIN32 */
1770 static int init_timer_alarm(void)
1772 struct qemu_alarm_timer *t = NULL;
1773 int i, err = -1;
1775 #ifndef _WIN32
1776 int fds[2];
1778 err = pipe(fds);
1779 if (err == -1)
1780 return -errno;
1782 err = fcntl_setfl(fds[0], O_NONBLOCK);
1783 if (err < 0)
1784 goto fail;
1786 err = fcntl_setfl(fds[1], O_NONBLOCK);
1787 if (err < 0)
1788 goto fail;
1790 alarm_timer_rfd = fds[0];
1791 alarm_timer_wfd = fds[1];
1792 #endif
1794 for (i = 0; alarm_timers[i].name; i++) {
1795 t = &alarm_timers[i];
1797 err = t->start(t);
1798 if (!err)
1799 break;
1802 if (err) {
1803 err = -ENOENT;
1804 goto fail;
1807 #ifndef _WIN32
1808 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1809 try_to_rearm_timer, NULL, t);
1810 #endif
1812 alarm_timer = t;
1814 return 0;
1816 fail:
1817 #ifndef _WIN32
1818 close(fds[0]);
1819 close(fds[1]);
1820 #endif
1821 return err;
1824 static void quit_timers(void)
1826 alarm_timer->stop(alarm_timer);
1827 alarm_timer = NULL;
1830 /***********************************************************/
1831 /* host time/date access */
1832 void qemu_get_timedate(struct tm *tm, int offset)
1834 time_t ti;
1835 struct tm *ret;
1837 time(&ti);
1838 ti += offset;
1839 if (rtc_date_offset == -1) {
1840 if (rtc_utc)
1841 ret = gmtime(&ti);
1842 else
1843 ret = localtime(&ti);
1844 } else {
1845 ti -= rtc_date_offset;
1846 ret = gmtime(&ti);
1849 memcpy(tm, ret, sizeof(struct tm));
1852 int qemu_timedate_diff(struct tm *tm)
1854 time_t seconds;
1856 if (rtc_date_offset == -1)
1857 if (rtc_utc)
1858 seconds = mktimegm(tm);
1859 else
1860 seconds = mktime(tm);
1861 else
1862 seconds = mktimegm(tm) + rtc_date_offset;
1864 return seconds - time(NULL);
1867 #ifdef _WIN32
1868 static void socket_cleanup(void)
1870 WSACleanup();
1873 static int socket_init(void)
1875 WSADATA Data;
1876 int ret, err;
1878 ret = WSAStartup(MAKEWORD(2,2), &Data);
1879 if (ret != 0) {
1880 err = WSAGetLastError();
1881 fprintf(stderr, "WSAStartup: %d\n", err);
1882 return -1;
1884 atexit(socket_cleanup);
1885 return 0;
1887 #endif
1889 const char *get_opt_name(char *buf, int buf_size, const char *p)
1891 char *q;
1893 q = buf;
1894 while (*p != '\0' && *p != '=') {
1895 if (q && (q - buf) < buf_size - 1)
1896 *q++ = *p;
1897 p++;
1899 if (q)
1900 *q = '\0';
1902 return p;
1905 const char *get_opt_value(char *buf, int buf_size, const char *p)
1907 char *q;
1909 q = buf;
1910 while (*p != '\0') {
1911 if (*p == ',') {
1912 if (*(p + 1) != ',')
1913 break;
1914 p++;
1916 if (q && (q - buf) < buf_size - 1)
1917 *q++ = *p;
1918 p++;
1920 if (q)
1921 *q = '\0';
1923 return p;
1926 int get_param_value(char *buf, int buf_size,
1927 const char *tag, const char *str)
1929 const char *p;
1930 char option[128];
1932 p = str;
1933 for(;;) {
1934 p = get_opt_name(option, sizeof(option), p);
1935 if (*p != '=')
1936 break;
1937 p++;
1938 if (!strcmp(tag, option)) {
1939 (void)get_opt_value(buf, buf_size, p);
1940 return strlen(buf);
1941 } else {
1942 p = get_opt_value(NULL, 0, p);
1944 if (*p != ',')
1945 break;
1946 p++;
1948 return 0;
1951 int check_params(char *buf, int buf_size,
1952 const char * const *params, const char *str)
1954 const char *p;
1955 int i;
1957 p = str;
1958 for(;;) {
1959 p = get_opt_name(buf, buf_size, p);
1960 if (*p != '=')
1961 return -1;
1962 p++;
1963 for(i = 0; params[i] != NULL; i++)
1964 if (!strcmp(params[i], buf))
1965 break;
1966 if (params[i] == NULL)
1967 return -1;
1968 p = get_opt_value(NULL, 0, p);
1969 if (*p != ',')
1970 break;
1971 p++;
1973 return 0;
1976 /***********************************************************/
1977 /* Bluetooth support */
1978 static int nb_hcis;
1979 static int cur_hci;
1980 static struct HCIInfo *hci_table[MAX_NICS];
1982 static struct bt_vlan_s {
1983 struct bt_scatternet_s net;
1984 int id;
1985 struct bt_vlan_s *next;
1986 } *first_bt_vlan;
1988 /* find or alloc a new bluetooth "VLAN" */
1989 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1991 struct bt_vlan_s **pvlan, *vlan;
1992 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1993 if (vlan->id == id)
1994 return &vlan->net;
1996 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1997 vlan->id = id;
1998 pvlan = &first_bt_vlan;
1999 while (*pvlan != NULL)
2000 pvlan = &(*pvlan)->next;
2001 *pvlan = vlan;
2002 return &vlan->net;
2005 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2009 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2011 return -ENOTSUP;
2014 static struct HCIInfo null_hci = {
2015 .cmd_send = null_hci_send,
2016 .sco_send = null_hci_send,
2017 .acl_send = null_hci_send,
2018 .bdaddr_set = null_hci_addr_set,
2021 struct HCIInfo *qemu_next_hci(void)
2023 if (cur_hci == nb_hcis)
2024 return &null_hci;
2026 return hci_table[cur_hci++];
2029 static struct HCIInfo *hci_init(const char *str)
2031 char *endp;
2032 struct bt_scatternet_s *vlan = 0;
2034 if (!strcmp(str, "null"))
2035 /* null */
2036 return &null_hci;
2037 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2038 /* host[:hciN] */
2039 return bt_host_hci(str[4] ? str + 5 : "hci0");
2040 else if (!strncmp(str, "hci", 3)) {
2041 /* hci[,vlan=n] */
2042 if (str[3]) {
2043 if (!strncmp(str + 3, ",vlan=", 6)) {
2044 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2045 if (*endp)
2046 vlan = 0;
2048 } else
2049 vlan = qemu_find_bt_vlan(0);
2050 if (vlan)
2051 return bt_new_hci(vlan);
2054 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2056 return 0;
2059 static int bt_hci_parse(const char *str)
2061 struct HCIInfo *hci;
2062 bdaddr_t bdaddr;
2064 if (nb_hcis >= MAX_NICS) {
2065 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2066 return -1;
2069 hci = hci_init(str);
2070 if (!hci)
2071 return -1;
2073 bdaddr.b[0] = 0x52;
2074 bdaddr.b[1] = 0x54;
2075 bdaddr.b[2] = 0x00;
2076 bdaddr.b[3] = 0x12;
2077 bdaddr.b[4] = 0x34;
2078 bdaddr.b[5] = 0x56 + nb_hcis;
2079 hci->bdaddr_set(hci, bdaddr.b);
2081 hci_table[nb_hcis++] = hci;
2083 return 0;
2086 static void bt_vhci_add(int vlan_id)
2088 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2090 if (!vlan->slave)
2091 fprintf(stderr, "qemu: warning: adding a VHCI to "
2092 "an empty scatternet %i\n", vlan_id);
2094 bt_vhci_init(bt_new_hci(vlan));
2097 static struct bt_device_s *bt_device_add(const char *opt)
2099 struct bt_scatternet_s *vlan;
2100 int vlan_id = 0;
2101 char *endp = strstr(opt, ",vlan=");
2102 int len = (endp ? endp - opt : strlen(opt)) + 1;
2103 char devname[10];
2105 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2107 if (endp) {
2108 vlan_id = strtol(endp + 6, &endp, 0);
2109 if (*endp) {
2110 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2111 return 0;
2115 vlan = qemu_find_bt_vlan(vlan_id);
2117 if (!vlan->slave)
2118 fprintf(stderr, "qemu: warning: adding a slave device to "
2119 "an empty scatternet %i\n", vlan_id);
2121 if (!strcmp(devname, "keyboard"))
2122 return bt_keyboard_init(vlan);
2124 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2125 return 0;
2128 static int bt_parse(const char *opt)
2130 const char *endp, *p;
2131 int vlan;
2133 if (strstart(opt, "hci", &endp)) {
2134 if (!*endp || *endp == ',') {
2135 if (*endp)
2136 if (!strstart(endp, ",vlan=", 0))
2137 opt = endp + 1;
2139 return bt_hci_parse(opt);
2141 } else if (strstart(opt, "vhci", &endp)) {
2142 if (!*endp || *endp == ',') {
2143 if (*endp) {
2144 if (strstart(endp, ",vlan=", &p)) {
2145 vlan = strtol(p, (char **) &endp, 0);
2146 if (*endp) {
2147 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2148 return 1;
2150 } else {
2151 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2152 return 1;
2154 } else
2155 vlan = 0;
2157 bt_vhci_add(vlan);
2158 return 0;
2160 } else if (strstart(opt, "device:", &endp))
2161 return !bt_device_add(endp);
2163 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2164 return 1;
2167 /***********************************************************/
2168 /* QEMU Block devices */
2170 #define HD_ALIAS "index=%d,media=disk"
2171 #ifdef TARGET_PPC
2172 #define CDROM_ALIAS "index=1,media=cdrom"
2173 #else
2174 #define CDROM_ALIAS "index=2,media=cdrom"
2175 #endif
2176 #define FD_ALIAS "index=%d,if=floppy"
2177 #define PFLASH_ALIAS "if=pflash"
2178 #define MTD_ALIAS "if=mtd"
2179 #define SD_ALIAS "index=0,if=sd"
2181 static int drive_opt_get_free_idx(void)
2183 int index;
2185 for (index = 0; index < MAX_DRIVES; index++)
2186 if (!drives_opt[index].used) {
2187 drives_opt[index].used = 1;
2188 return index;
2191 return -1;
2194 static int drive_get_free_idx(void)
2196 int index;
2198 for (index = 0; index < MAX_DRIVES; index++)
2199 if (!drives_table[index].used) {
2200 drives_table[index].used = 1;
2201 return index;
2204 return -1;
2207 int drive_add(const char *file, const char *fmt, ...)
2209 va_list ap;
2210 int index = drive_opt_get_free_idx();
2212 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2213 fprintf(stderr, "qemu: too many drives\n");
2214 return -1;
2217 drives_opt[index].file = file;
2218 va_start(ap, fmt);
2219 vsnprintf(drives_opt[index].opt,
2220 sizeof(drives_opt[0].opt), fmt, ap);
2221 va_end(ap);
2223 nb_drives_opt++;
2224 return index;
2227 void drive_remove(int index)
2229 drives_opt[index].used = 0;
2230 nb_drives_opt--;
2233 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2235 int index;
2237 /* seek interface, bus and unit */
2239 for (index = 0; index < MAX_DRIVES; index++)
2240 if (drives_table[index].type == type &&
2241 drives_table[index].bus == bus &&
2242 drives_table[index].unit == unit &&
2243 drives_table[index].used)
2244 return index;
2246 return -1;
2249 int drive_get_max_bus(BlockInterfaceType type)
2251 int max_bus;
2252 int index;
2254 max_bus = -1;
2255 for (index = 0; index < nb_drives; index++) {
2256 if(drives_table[index].type == type &&
2257 drives_table[index].bus > max_bus)
2258 max_bus = drives_table[index].bus;
2260 return max_bus;
2263 static void bdrv_format_print(void *opaque, const char *name)
2265 fprintf(stderr, " %s", name);
2268 void drive_uninit(BlockDriverState *bdrv)
2270 int i;
2272 for (i = 0; i < MAX_DRIVES; i++)
2273 if (drives_table[i].bdrv == bdrv) {
2274 drives_table[i].bdrv = NULL;
2275 drives_table[i].used = 0;
2276 drive_remove(drives_table[i].drive_opt_idx);
2277 nb_drives--;
2278 break;
2282 int drive_init(struct drive_opt *arg, int snapshot,
2283 QEMUMachine *machine)
2285 char buf[128];
2286 char file[1024];
2287 char devname[128];
2288 const char *mediastr = "";
2289 BlockInterfaceType type;
2290 enum { MEDIA_DISK, MEDIA_CDROM } media;
2291 int bus_id, unit_id;
2292 int cyls, heads, secs, translation;
2293 BlockDriverState *bdrv;
2294 BlockDriver *drv = NULL;
2295 int max_devs;
2296 int index;
2297 int cache;
2298 int bdrv_flags;
2299 int drives_table_idx;
2300 char *str = arg->opt;
2301 static const char * const params[] = { "bus", "unit", "if", "index",
2302 "cyls", "heads", "secs", "trans",
2303 "media", "snapshot", "file",
2304 "cache", "format", "boot", NULL };
2306 if (check_params(buf, sizeof(buf), params, str) < 0) {
2307 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2308 buf, str);
2309 return -1;
2312 file[0] = 0;
2313 cyls = heads = secs = 0;
2314 bus_id = 0;
2315 unit_id = -1;
2316 translation = BIOS_ATA_TRANSLATION_AUTO;
2317 index = -1;
2318 cache = 1;
2320 if (machine->use_scsi) {
2321 type = IF_SCSI;
2322 max_devs = MAX_SCSI_DEVS;
2323 pstrcpy(devname, sizeof(devname), "scsi");
2324 } else {
2325 type = IF_IDE;
2326 max_devs = MAX_IDE_DEVS;
2327 pstrcpy(devname, sizeof(devname), "ide");
2329 media = MEDIA_DISK;
2331 /* extract parameters */
2333 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2334 bus_id = strtol(buf, NULL, 0);
2335 if (bus_id < 0) {
2336 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2337 return -1;
2341 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2342 unit_id = strtol(buf, NULL, 0);
2343 if (unit_id < 0) {
2344 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2345 return -1;
2349 if (get_param_value(buf, sizeof(buf), "if", str)) {
2350 pstrcpy(devname, sizeof(devname), buf);
2351 if (!strcmp(buf, "ide")) {
2352 type = IF_IDE;
2353 max_devs = MAX_IDE_DEVS;
2354 } else if (!strcmp(buf, "scsi")) {
2355 type = IF_SCSI;
2356 max_devs = MAX_SCSI_DEVS;
2357 } else if (!strcmp(buf, "floppy")) {
2358 type = IF_FLOPPY;
2359 max_devs = 0;
2360 } else if (!strcmp(buf, "pflash")) {
2361 type = IF_PFLASH;
2362 max_devs = 0;
2363 } else if (!strcmp(buf, "mtd")) {
2364 type = IF_MTD;
2365 max_devs = 0;
2366 } else if (!strcmp(buf, "sd")) {
2367 type = IF_SD;
2368 max_devs = 0;
2369 } else if (!strcmp(buf, "virtio")) {
2370 type = IF_VIRTIO;
2371 max_devs = 0;
2372 } else {
2373 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2374 return -1;
2378 if (get_param_value(buf, sizeof(buf), "index", str)) {
2379 index = strtol(buf, NULL, 0);
2380 if (index < 0) {
2381 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2382 return -1;
2386 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2387 cyls = strtol(buf, NULL, 0);
2390 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2391 heads = strtol(buf, NULL, 0);
2394 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2395 secs = strtol(buf, NULL, 0);
2398 if (cyls || heads || secs) {
2399 if (cyls < 1 || cyls > 16383) {
2400 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2401 return -1;
2403 if (heads < 1 || heads > 16) {
2404 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2405 return -1;
2407 if (secs < 1 || secs > 63) {
2408 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2409 return -1;
2413 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2414 if (!cyls) {
2415 fprintf(stderr,
2416 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2417 str);
2418 return -1;
2420 if (!strcmp(buf, "none"))
2421 translation = BIOS_ATA_TRANSLATION_NONE;
2422 else if (!strcmp(buf, "lba"))
2423 translation = BIOS_ATA_TRANSLATION_LBA;
2424 else if (!strcmp(buf, "auto"))
2425 translation = BIOS_ATA_TRANSLATION_AUTO;
2426 else {
2427 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2428 return -1;
2432 if (get_param_value(buf, sizeof(buf), "media", str)) {
2433 if (!strcmp(buf, "disk")) {
2434 media = MEDIA_DISK;
2435 } else if (!strcmp(buf, "cdrom")) {
2436 if (cyls || secs || heads) {
2437 fprintf(stderr,
2438 "qemu: '%s' invalid physical CHS format\n", str);
2439 return -1;
2441 media = MEDIA_CDROM;
2442 } else {
2443 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2444 return -1;
2448 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2449 if (!strcmp(buf, "on"))
2450 snapshot = 1;
2451 else if (!strcmp(buf, "off"))
2452 snapshot = 0;
2453 else {
2454 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2455 return -1;
2459 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2460 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2461 cache = 0;
2462 else if (!strcmp(buf, "writethrough"))
2463 cache = 1;
2464 else if (!strcmp(buf, "writeback"))
2465 cache = 2;
2466 else {
2467 fprintf(stderr, "qemu: invalid cache option\n");
2468 return -1;
2472 if (get_param_value(buf, sizeof(buf), "format", str)) {
2473 if (strcmp(buf, "?") == 0) {
2474 fprintf(stderr, "qemu: Supported formats:");
2475 bdrv_iterate_format(bdrv_format_print, NULL);
2476 fprintf(stderr, "\n");
2477 return -1;
2479 drv = bdrv_find_format(buf);
2480 if (!drv) {
2481 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2482 return -1;
2486 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2487 if (!strcmp(buf, "on")) {
2488 if (extboot_drive != -1) {
2489 fprintf(stderr, "qemu: two bootable drives specified\n");
2490 return -1;
2492 extboot_drive = nb_drives;
2493 } else if (strcmp(buf, "off")) {
2494 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2495 return -1;
2499 if (arg->file == NULL)
2500 get_param_value(file, sizeof(file), "file", str);
2501 else
2502 pstrcpy(file, sizeof(file), arg->file);
2504 /* compute bus and unit according index */
2506 if (index != -1) {
2507 if (bus_id != 0 || unit_id != -1) {
2508 fprintf(stderr,
2509 "qemu: '%s' index cannot be used with bus and unit\n", str);
2510 return -1;
2512 if (max_devs == 0)
2514 unit_id = index;
2515 bus_id = 0;
2516 } else {
2517 unit_id = index % max_devs;
2518 bus_id = index / max_devs;
2522 /* if user doesn't specify a unit_id,
2523 * try to find the first free
2526 if (unit_id == -1) {
2527 unit_id = 0;
2528 while (drive_get_index(type, bus_id, unit_id) != -1) {
2529 unit_id++;
2530 if (max_devs && unit_id >= max_devs) {
2531 unit_id -= max_devs;
2532 bus_id++;
2537 /* check unit id */
2539 if (max_devs && unit_id >= max_devs) {
2540 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2541 str, unit_id, max_devs - 1);
2542 return -1;
2546 * ignore multiple definitions
2549 if (drive_get_index(type, bus_id, unit_id) != -1)
2550 return -2;
2552 /* init */
2554 if (type == IF_IDE || type == IF_SCSI)
2555 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2556 if (max_devs)
2557 snprintf(buf, sizeof(buf), "%s%i%s%i",
2558 devname, bus_id, mediastr, unit_id);
2559 else
2560 snprintf(buf, sizeof(buf), "%s%s%i",
2561 devname, mediastr, unit_id);
2562 bdrv = bdrv_new(buf);
2563 drives_table_idx = drive_get_free_idx();
2564 drives_table[drives_table_idx].bdrv = bdrv;
2565 drives_table[drives_table_idx].type = type;
2566 drives_table[drives_table_idx].bus = bus_id;
2567 drives_table[drives_table_idx].unit = unit_id;
2568 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2569 nb_drives++;
2571 switch(type) {
2572 case IF_IDE:
2573 case IF_SCSI:
2574 switch(media) {
2575 case MEDIA_DISK:
2576 if (cyls != 0) {
2577 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2578 bdrv_set_translation_hint(bdrv, translation);
2580 break;
2581 case MEDIA_CDROM:
2582 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2583 break;
2585 break;
2586 case IF_SD:
2587 /* FIXME: This isn't really a floppy, but it's a reasonable
2588 approximation. */
2589 case IF_FLOPPY:
2590 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2591 break;
2592 case IF_PFLASH:
2593 case IF_MTD:
2594 case IF_VIRTIO:
2595 break;
2597 if (!file[0])
2598 return -2;
2599 bdrv_flags = 0;
2600 if (snapshot) {
2601 bdrv_flags |= BDRV_O_SNAPSHOT;
2602 cache = 2; /* always use write-back with snapshot */
2604 if (cache == 0) /* no caching */
2605 bdrv_flags |= BDRV_O_NOCACHE;
2606 else if (cache == 2) /* write-back */
2607 bdrv_flags |= BDRV_O_CACHE_WB;
2608 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2609 fprintf(stderr, "qemu: could not open disk image %s\n",
2610 file);
2611 return -1;
2613 return drives_table_idx;
2616 /***********************************************************/
2617 /* USB devices */
2619 static USBPort *used_usb_ports;
2620 static USBPort *free_usb_ports;
2622 /* ??? Maybe change this to register a hub to keep track of the topology. */
2623 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2624 usb_attachfn attach)
2626 port->opaque = opaque;
2627 port->index = index;
2628 port->attach = attach;
2629 port->next = free_usb_ports;
2630 free_usb_ports = port;
2633 int usb_device_add_dev(USBDevice *dev)
2635 USBPort *port;
2637 /* Find a USB port to add the device to. */
2638 port = free_usb_ports;
2639 if (!port->next) {
2640 USBDevice *hub;
2642 /* Create a new hub and chain it on. */
2643 free_usb_ports = NULL;
2644 port->next = used_usb_ports;
2645 used_usb_ports = port;
2647 hub = usb_hub_init(VM_USB_HUB_SIZE);
2648 usb_attach(port, hub);
2649 port = free_usb_ports;
2652 free_usb_ports = port->next;
2653 port->next = used_usb_ports;
2654 used_usb_ports = port;
2655 usb_attach(port, dev);
2656 return 0;
2659 static int usb_device_add(const char *devname)
2661 const char *p;
2662 USBDevice *dev;
2664 if (!free_usb_ports)
2665 return -1;
2667 if (strstart(devname, "host:", &p)) {
2668 dev = usb_host_device_open(p);
2669 } else if (!strcmp(devname, "mouse")) {
2670 dev = usb_mouse_init();
2671 } else if (!strcmp(devname, "tablet")) {
2672 dev = usb_tablet_init();
2673 } else if (!strcmp(devname, "keyboard")) {
2674 dev = usb_keyboard_init();
2675 } else if (strstart(devname, "disk:", &p)) {
2676 dev = usb_msd_init(p);
2677 } else if (!strcmp(devname, "wacom-tablet")) {
2678 dev = usb_wacom_init();
2679 } else if (strstart(devname, "serial:", &p)) {
2680 dev = usb_serial_init(p);
2681 #ifdef CONFIG_BRLAPI
2682 } else if (!strcmp(devname, "braille")) {
2683 dev = usb_baum_init();
2684 #endif
2685 } else if (strstart(devname, "net:", &p)) {
2686 int nic = nb_nics;
2688 if (net_client_init("nic", p) < 0)
2689 return -1;
2690 nd_table[nic].model = "usb";
2691 dev = usb_net_init(&nd_table[nic]);
2692 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2693 dev = usb_bt_init(devname[2] ? hci_init(p) :
2694 bt_new_hci(qemu_find_bt_vlan(0)));
2695 } else {
2696 return -1;
2698 if (!dev)
2699 return -1;
2701 return usb_device_add_dev(dev);
2704 int usb_device_del_addr(int bus_num, int addr)
2706 USBPort *port;
2707 USBPort **lastp;
2708 USBDevice *dev;
2710 if (!used_usb_ports)
2711 return -1;
2713 if (bus_num != 0)
2714 return -1;
2716 lastp = &used_usb_ports;
2717 port = used_usb_ports;
2718 while (port && port->dev->addr != addr) {
2719 lastp = &port->next;
2720 port = port->next;
2723 if (!port)
2724 return -1;
2726 dev = port->dev;
2727 *lastp = port->next;
2728 usb_attach(port, NULL);
2729 dev->handle_destroy(dev);
2730 port->next = free_usb_ports;
2731 free_usb_ports = port;
2732 return 0;
2735 static int usb_device_del(const char *devname)
2737 int bus_num, addr;
2738 const char *p;
2740 if (strstart(devname, "host:", &p))
2741 return usb_host_device_close(p);
2743 if (!used_usb_ports)
2744 return -1;
2746 p = strchr(devname, '.');
2747 if (!p)
2748 return -1;
2749 bus_num = strtoul(devname, NULL, 0);
2750 addr = strtoul(p + 1, NULL, 0);
2752 return usb_device_del_addr(bus_num, addr);
2755 void do_usb_add(const char *devname)
2757 usb_device_add(devname);
2760 void do_usb_del(const char *devname)
2762 usb_device_del(devname);
2765 void usb_info(void)
2767 USBDevice *dev;
2768 USBPort *port;
2769 const char *speed_str;
2771 if (!usb_enabled) {
2772 term_printf("USB support not enabled\n");
2773 return;
2776 for (port = used_usb_ports; port; port = port->next) {
2777 dev = port->dev;
2778 if (!dev)
2779 continue;
2780 switch(dev->speed) {
2781 case USB_SPEED_LOW:
2782 speed_str = "1.5";
2783 break;
2784 case USB_SPEED_FULL:
2785 speed_str = "12";
2786 break;
2787 case USB_SPEED_HIGH:
2788 speed_str = "480";
2789 break;
2790 default:
2791 speed_str = "?";
2792 break;
2794 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2795 0, dev->addr, speed_str, dev->devname);
2799 /***********************************************************/
2800 /* PCMCIA/Cardbus */
2802 static struct pcmcia_socket_entry_s {
2803 struct pcmcia_socket_s *socket;
2804 struct pcmcia_socket_entry_s *next;
2805 } *pcmcia_sockets = 0;
2807 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2809 struct pcmcia_socket_entry_s *entry;
2811 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2812 entry->socket = socket;
2813 entry->next = pcmcia_sockets;
2814 pcmcia_sockets = entry;
2817 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2819 struct pcmcia_socket_entry_s *entry, **ptr;
2821 ptr = &pcmcia_sockets;
2822 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2823 if (entry->socket == socket) {
2824 *ptr = entry->next;
2825 qemu_free(entry);
2829 void pcmcia_info(void)
2831 struct pcmcia_socket_entry_s *iter;
2832 if (!pcmcia_sockets)
2833 term_printf("No PCMCIA sockets\n");
2835 for (iter = pcmcia_sockets; iter; iter = iter->next)
2836 term_printf("%s: %s\n", iter->socket->slot_string,
2837 iter->socket->attached ? iter->socket->card_string :
2838 "Empty");
2841 /***********************************************************/
2842 /* dumb display */
2844 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2848 static void dumb_resize(DisplayState *ds, int w, int h)
2852 static void dumb_display_init(DisplayState *ds)
2854 ds->data = NULL;
2855 ds->linesize = 0;
2856 ds->depth = 0;
2857 ds->dpy_update = dumb_update;
2858 ds->dpy_resize = dumb_resize;
2859 ds->dpy_refresh = NULL;
2860 ds->gui_timer_interval = 0;
2861 ds->idle = 1;
2864 /***********************************************************/
2865 /* I/O handling */
2867 #define MAX_IO_HANDLERS 64
2869 typedef struct IOHandlerRecord {
2870 int fd;
2871 IOCanRWHandler *fd_read_poll;
2872 IOHandler *fd_read;
2873 IOHandler *fd_write;
2874 int deleted;
2875 void *opaque;
2876 /* temporary data */
2877 struct pollfd *ufd;
2878 struct IOHandlerRecord *next;
2879 } IOHandlerRecord;
2881 static IOHandlerRecord *first_io_handler;
2883 /* XXX: fd_read_poll should be suppressed, but an API change is
2884 necessary in the character devices to suppress fd_can_read(). */
2885 int qemu_set_fd_handler2(int fd,
2886 IOCanRWHandler *fd_read_poll,
2887 IOHandler *fd_read,
2888 IOHandler *fd_write,
2889 void *opaque)
2891 IOHandlerRecord **pioh, *ioh;
2893 if (!fd_read && !fd_write) {
2894 pioh = &first_io_handler;
2895 for(;;) {
2896 ioh = *pioh;
2897 if (ioh == NULL)
2898 break;
2899 if (ioh->fd == fd) {
2900 ioh->deleted = 1;
2901 break;
2903 pioh = &ioh->next;
2905 } else {
2906 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2907 if (ioh->fd == fd)
2908 goto found;
2910 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2911 if (!ioh)
2912 return -1;
2913 ioh->next = first_io_handler;
2914 first_io_handler = ioh;
2915 found:
2916 ioh->fd = fd;
2917 ioh->fd_read_poll = fd_read_poll;
2918 ioh->fd_read = fd_read;
2919 ioh->fd_write = fd_write;
2920 ioh->opaque = opaque;
2921 ioh->deleted = 0;
2923 main_loop_break();
2924 return 0;
2927 int qemu_set_fd_handler(int fd,
2928 IOHandler *fd_read,
2929 IOHandler *fd_write,
2930 void *opaque)
2932 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2935 #ifdef _WIN32
2936 /***********************************************************/
2937 /* Polling handling */
2939 typedef struct PollingEntry {
2940 PollingFunc *func;
2941 void *opaque;
2942 struct PollingEntry *next;
2943 } PollingEntry;
2945 static PollingEntry *first_polling_entry;
2947 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2949 PollingEntry **ppe, *pe;
2950 pe = qemu_mallocz(sizeof(PollingEntry));
2951 if (!pe)
2952 return -1;
2953 pe->func = func;
2954 pe->opaque = opaque;
2955 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2956 *ppe = pe;
2957 return 0;
2960 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2962 PollingEntry **ppe, *pe;
2963 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2964 pe = *ppe;
2965 if (pe->func == func && pe->opaque == opaque) {
2966 *ppe = pe->next;
2967 qemu_free(pe);
2968 break;
2973 /***********************************************************/
2974 /* Wait objects support */
2975 typedef struct WaitObjects {
2976 int num;
2977 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2978 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2979 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2980 } WaitObjects;
2982 static WaitObjects wait_objects = {0};
2984 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2986 WaitObjects *w = &wait_objects;
2988 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2989 return -1;
2990 w->events[w->num] = handle;
2991 w->func[w->num] = func;
2992 w->opaque[w->num] = opaque;
2993 w->num++;
2994 return 0;
2997 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2999 int i, found;
3000 WaitObjects *w = &wait_objects;
3002 found = 0;
3003 for (i = 0; i < w->num; i++) {
3004 if (w->events[i] == handle)
3005 found = 1;
3006 if (found) {
3007 w->events[i] = w->events[i + 1];
3008 w->func[i] = w->func[i + 1];
3009 w->opaque[i] = w->opaque[i + 1];
3012 if (found)
3013 w->num--;
3015 #endif
3017 /***********************************************************/
3018 /* ram save/restore */
3020 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3022 int v;
3024 v = qemu_get_byte(f);
3025 switch(v) {
3026 case 0:
3027 if (qemu_get_buffer(f, buf, len) != len)
3028 return -EIO;
3029 break;
3030 case 1:
3031 v = qemu_get_byte(f);
3032 memset(buf, v, len);
3033 break;
3034 default:
3035 return -EINVAL;
3038 if (qemu_file_has_error(f))
3039 return -EIO;
3041 return 0;
3044 static int ram_load_v1(QEMUFile *f, void *opaque)
3046 int ret;
3047 ram_addr_t i;
3049 if (qemu_get_be32(f) != phys_ram_size)
3050 return -EINVAL;
3051 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3052 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3053 continue;
3054 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3055 if (ret)
3056 return ret;
3058 return 0;
3061 #define BDRV_HASH_BLOCK_SIZE 1024
3062 #define IOBUF_SIZE 4096
3063 #define RAM_CBLOCK_MAGIC 0xfabe
3065 typedef struct RamDecompressState {
3066 z_stream zstream;
3067 QEMUFile *f;
3068 uint8_t buf[IOBUF_SIZE];
3069 } RamDecompressState;
3071 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3073 int ret;
3074 memset(s, 0, sizeof(*s));
3075 s->f = f;
3076 ret = inflateInit(&s->zstream);
3077 if (ret != Z_OK)
3078 return -1;
3079 return 0;
3082 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3084 int ret, clen;
3086 s->zstream.avail_out = len;
3087 s->zstream.next_out = buf;
3088 while (s->zstream.avail_out > 0) {
3089 if (s->zstream.avail_in == 0) {
3090 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3091 return -1;
3092 clen = qemu_get_be16(s->f);
3093 if (clen > IOBUF_SIZE)
3094 return -1;
3095 qemu_get_buffer(s->f, s->buf, clen);
3096 s->zstream.avail_in = clen;
3097 s->zstream.next_in = s->buf;
3099 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3100 if (ret != Z_OK && ret != Z_STREAM_END) {
3101 return -1;
3104 return 0;
3107 static void ram_decompress_close(RamDecompressState *s)
3109 inflateEnd(&s->zstream);
3112 #define RAM_SAVE_FLAG_FULL 0x01
3113 #define RAM_SAVE_FLAG_COMPRESS 0x02
3114 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3115 #define RAM_SAVE_FLAG_PAGE 0x08
3116 #define RAM_SAVE_FLAG_EOS 0x10
3118 static int is_dup_page(uint8_t *page, uint8_t ch)
3120 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3121 uint32_t *array = (uint32_t *)page;
3122 int i;
3124 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3125 if (array[i] != val)
3126 return 0;
3129 return 1;
3132 static int ram_save_block(QEMUFile *f)
3134 static ram_addr_t current_addr = 0;
3135 ram_addr_t saved_addr = current_addr;
3136 ram_addr_t addr = 0;
3137 int found = 0;
3139 while (addr < phys_ram_size) {
3140 if (kvm_enabled() && current_addr == 0)
3141 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3142 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3143 uint8_t ch;
3145 cpu_physical_memory_reset_dirty(current_addr,
3146 current_addr + TARGET_PAGE_SIZE,
3147 MIGRATION_DIRTY_FLAG);
3149 ch = *(phys_ram_base + current_addr);
3151 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3152 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3153 qemu_put_byte(f, ch);
3154 } else {
3155 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3156 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3159 found = 1;
3160 break;
3162 addr += TARGET_PAGE_SIZE;
3163 current_addr = (saved_addr + addr) % phys_ram_size;
3166 return found;
3169 static ram_addr_t ram_save_threshold = 10;
3171 static ram_addr_t ram_save_remaining(void)
3173 ram_addr_t addr;
3174 ram_addr_t count = 0;
3176 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3177 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3178 count++;
3181 return count;
3184 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3186 ram_addr_t addr;
3188 if (stage == 1) {
3189 /* Make sure all dirty bits are set */
3190 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3191 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3192 cpu_physical_memory_set_dirty(addr);
3195 /* Enable dirty memory tracking */
3196 cpu_physical_memory_set_dirty_tracking(1);
3198 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3201 while (!qemu_file_rate_limit(f)) {
3202 int ret;
3204 ret = ram_save_block(f);
3205 if (ret == 0) /* no more blocks */
3206 break;
3209 /* try transferring iterative blocks of memory */
3211 if (stage == 3) {
3212 cpu_physical_memory_set_dirty_tracking(0);
3214 /* flush all remaining blocks regardless of rate limiting */
3215 while (ram_save_block(f) != 0);
3218 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3220 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3223 static int ram_load_dead(QEMUFile *f, void *opaque)
3225 RamDecompressState s1, *s = &s1;
3226 uint8_t buf[10];
3227 ram_addr_t i;
3229 if (ram_decompress_open(s, f) < 0)
3230 return -EINVAL;
3231 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3232 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3233 continue;
3234 if (ram_decompress_buf(s, buf, 1) < 0) {
3235 fprintf(stderr, "Error while reading ram block header\n");
3236 goto error;
3238 if (buf[0] == 0) {
3239 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3240 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3241 goto error;
3243 } else {
3244 error:
3245 printf("Error block header\n");
3246 return -EINVAL;
3249 ram_decompress_close(s);
3251 return 0;
3254 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3256 ram_addr_t addr;
3257 int flags;
3259 if (version_id == 1)
3260 return ram_load_v1(f, opaque);
3262 if (version_id == 2) {
3263 if (qemu_get_be32(f) != phys_ram_size)
3264 return -EINVAL;
3265 return ram_load_dead(f, opaque);
3268 if (version_id != 3)
3269 return -EINVAL;
3271 do {
3272 addr = qemu_get_be64(f);
3274 flags = addr & ~TARGET_PAGE_MASK;
3275 addr &= TARGET_PAGE_MASK;
3277 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3278 if (addr != phys_ram_size)
3279 return -EINVAL;
3282 if (flags & RAM_SAVE_FLAG_FULL) {
3283 if (ram_load_dead(f, opaque) < 0)
3284 return -EINVAL;
3287 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3288 uint8_t ch = qemu_get_byte(f);
3289 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3290 } else if (flags & RAM_SAVE_FLAG_PAGE)
3291 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3292 } while (!(flags & RAM_SAVE_FLAG_EOS));
3294 return 0;
3297 /***********************************************************/
3298 /* bottom halves (can be seen as timers which expire ASAP) */
3300 struct QEMUBH {
3301 QEMUBHFunc *cb;
3302 void *opaque;
3303 int scheduled;
3304 int idle;
3305 int deleted;
3306 QEMUBH *next;
3309 static QEMUBH *first_bh = NULL;
3311 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3313 QEMUBH *bh;
3314 bh = qemu_mallocz(sizeof(QEMUBH));
3315 if (!bh)
3316 return NULL;
3317 bh->cb = cb;
3318 bh->opaque = opaque;
3319 bh->next = first_bh;
3320 first_bh = bh;
3321 return bh;
3324 int qemu_bh_poll(void)
3326 QEMUBH *bh, **bhp;
3327 int ret;
3329 ret = 0;
3330 for (bh = first_bh; bh; bh = bh->next) {
3331 if (!bh->deleted && bh->scheduled) {
3332 bh->scheduled = 0;
3333 if (!bh->idle)
3334 ret = 1;
3335 bh->idle = 0;
3336 bh->cb(bh->opaque);
3340 /* remove deleted bhs */
3341 bhp = &first_bh;
3342 while (*bhp) {
3343 bh = *bhp;
3344 if (bh->deleted) {
3345 *bhp = bh->next;
3346 qemu_free(bh);
3347 } else
3348 bhp = &bh->next;
3351 return ret;
3354 void qemu_bh_schedule_idle(QEMUBH *bh)
3356 if (bh->scheduled)
3357 return;
3358 bh->scheduled = 1;
3359 bh->idle = 1;
3362 void qemu_bh_schedule(QEMUBH *bh)
3364 CPUState *env = cpu_single_env;
3365 if (bh->scheduled)
3366 return;
3367 bh->scheduled = 1;
3368 bh->idle = 0;
3369 /* stop the currently executing CPU to execute the BH ASAP */
3370 if (env) {
3371 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3373 main_loop_break();
3376 void qemu_bh_cancel(QEMUBH *bh)
3378 bh->scheduled = 0;
3381 void qemu_bh_delete(QEMUBH *bh)
3383 bh->scheduled = 0;
3384 bh->deleted = 1;
3387 static void qemu_bh_update_timeout(int *timeout)
3389 QEMUBH *bh;
3391 for (bh = first_bh; bh; bh = bh->next) {
3392 if (!bh->deleted && bh->scheduled) {
3393 if (bh->idle) {
3394 /* idle bottom halves will be polled at least
3395 * every 10ms */
3396 *timeout = MIN(10, *timeout);
3397 } else {
3398 /* non-idle bottom halves will be executed
3399 * immediately */
3400 *timeout = 0;
3401 break;
3407 /***********************************************************/
3408 /* machine registration */
3410 static QEMUMachine *first_machine = NULL;
3411 QEMUMachine *current_machine = NULL;
3413 int qemu_register_machine(QEMUMachine *m)
3415 QEMUMachine **pm;
3416 pm = &first_machine;
3417 while (*pm != NULL)
3418 pm = &(*pm)->next;
3419 m->next = NULL;
3420 *pm = m;
3421 return 0;
3424 static QEMUMachine *find_machine(const char *name)
3426 QEMUMachine *m;
3428 for(m = first_machine; m != NULL; m = m->next) {
3429 if (!strcmp(m->name, name))
3430 return m;
3432 return NULL;
3435 /***********************************************************/
3436 /* main execution loop */
3438 static void gui_update(void *opaque)
3440 DisplayState *ds = opaque;
3441 ds->dpy_refresh(ds);
3442 qemu_mod_timer(ds->gui_timer,
3443 (ds->gui_timer_interval ?
3444 ds->gui_timer_interval :
3445 GUI_REFRESH_INTERVAL)
3446 + qemu_get_clock(rt_clock));
3449 struct vm_change_state_entry {
3450 VMChangeStateHandler *cb;
3451 void *opaque;
3452 LIST_ENTRY (vm_change_state_entry) entries;
3455 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3457 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3458 void *opaque)
3460 VMChangeStateEntry *e;
3462 e = qemu_mallocz(sizeof (*e));
3463 if (!e)
3464 return NULL;
3466 e->cb = cb;
3467 e->opaque = opaque;
3468 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3469 return e;
3472 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3474 LIST_REMOVE (e, entries);
3475 qemu_free (e);
3478 static void vm_state_notify(int running)
3480 VMChangeStateEntry *e;
3482 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3483 e->cb(e->opaque, running);
3487 /* XXX: support several handlers */
3488 static VMStopHandler *vm_stop_cb;
3489 static void *vm_stop_opaque;
3491 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3493 vm_stop_cb = cb;
3494 vm_stop_opaque = opaque;
3495 return 0;
3498 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3500 vm_stop_cb = NULL;
3503 void vm_start(void)
3505 if (!vm_running) {
3506 cpu_enable_ticks();
3507 vm_running = 1;
3508 vm_state_notify(1);
3509 qemu_rearm_alarm_timer(alarm_timer);
3513 void vm_stop(int reason)
3515 if (vm_running) {
3516 cpu_disable_ticks();
3517 vm_running = 0;
3518 if (reason != 0) {
3519 if (vm_stop_cb) {
3520 vm_stop_cb(vm_stop_opaque, reason);
3523 vm_state_notify(0);
3527 /* reset/shutdown handler */
3529 typedef struct QEMUResetEntry {
3530 QEMUResetHandler *func;
3531 void *opaque;
3532 struct QEMUResetEntry *next;
3533 } QEMUResetEntry;
3535 static QEMUResetEntry *first_reset_entry;
3536 static int reset_requested;
3537 static int shutdown_requested;
3538 static int powerdown_requested;
3540 int qemu_shutdown_requested(void)
3542 int r = shutdown_requested;
3543 shutdown_requested = 0;
3544 return r;
3547 int qemu_reset_requested(void)
3549 int r = reset_requested;
3550 reset_requested = 0;
3551 return r;
3554 int qemu_powerdown_requested(void)
3556 int r = powerdown_requested;
3557 powerdown_requested = 0;
3558 return r;
3561 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3563 QEMUResetEntry **pre, *re;
3565 pre = &first_reset_entry;
3566 while (*pre != NULL)
3567 pre = &(*pre)->next;
3568 re = qemu_mallocz(sizeof(QEMUResetEntry));
3569 re->func = func;
3570 re->opaque = opaque;
3571 re->next = NULL;
3572 *pre = re;
3575 void qemu_system_reset(void)
3577 QEMUResetEntry *re;
3579 /* reset all devices */
3580 for(re = first_reset_entry; re != NULL; re = re->next) {
3581 re->func(re->opaque);
3585 void qemu_system_reset_request(void)
3587 if (no_reboot) {
3588 shutdown_requested = 1;
3589 } else {
3590 reset_requested = 1;
3592 if (cpu_single_env)
3593 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3594 main_loop_break();
3597 void qemu_system_shutdown_request(void)
3599 shutdown_requested = 1;
3600 if (cpu_single_env)
3601 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3604 void qemu_system_powerdown_request(void)
3606 powerdown_requested = 1;
3607 if (cpu_single_env)
3608 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3611 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3612 struct timeval *tv)
3614 int ret;
3616 /* KVM holds a mutex while QEMU code is running, we need hooks to
3617 release the mutex whenever QEMU code sleeps. */
3619 kvm_sleep_begin();
3621 ret = select(max_fd, rfds, wfds, xfds, tv);
3623 kvm_sleep_end();
3625 return ret;
3628 #ifdef _WIN32
3629 void host_main_loop_wait(int *timeout)
3631 int ret, ret2, i;
3632 PollingEntry *pe;
3635 /* XXX: need to suppress polling by better using win32 events */
3636 ret = 0;
3637 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3638 ret |= pe->func(pe->opaque);
3640 if (ret == 0) {
3641 int err;
3642 WaitObjects *w = &wait_objects;
3644 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3645 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3646 if (w->func[ret - WAIT_OBJECT_0])
3647 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3649 /* Check for additional signaled events */
3650 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3652 /* Check if event is signaled */
3653 ret2 = WaitForSingleObject(w->events[i], 0);
3654 if(ret2 == WAIT_OBJECT_0) {
3655 if (w->func[i])
3656 w->func[i](w->opaque[i]);
3657 } else if (ret2 == WAIT_TIMEOUT) {
3658 } else {
3659 err = GetLastError();
3660 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3663 } else if (ret == WAIT_TIMEOUT) {
3664 } else {
3665 err = GetLastError();
3666 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3670 *timeout = 0;
3672 #else
3673 void host_main_loop_wait(int *timeout)
3676 #endif
3678 void main_loop_wait(int timeout)
3680 IOHandlerRecord *ioh;
3681 fd_set rfds, wfds, xfds;
3682 int ret, nfds;
3683 struct timeval tv;
3685 qemu_bh_update_timeout(&timeout);
3687 host_main_loop_wait(&timeout);
3689 /* poll any events */
3690 /* XXX: separate device handlers from system ones */
3691 nfds = -1;
3692 FD_ZERO(&rfds);
3693 FD_ZERO(&wfds);
3694 FD_ZERO(&xfds);
3695 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3696 if (ioh->deleted)
3697 continue;
3698 if (ioh->fd_read &&
3699 (!ioh->fd_read_poll ||
3700 ioh->fd_read_poll(ioh->opaque) != 0)) {
3701 FD_SET(ioh->fd, &rfds);
3702 if (ioh->fd > nfds)
3703 nfds = ioh->fd;
3705 if (ioh->fd_write) {
3706 FD_SET(ioh->fd, &wfds);
3707 if (ioh->fd > nfds)
3708 nfds = ioh->fd;
3712 tv.tv_sec = timeout / 1000;
3713 tv.tv_usec = (timeout % 1000) * 1000;
3715 #if defined(CONFIG_SLIRP)
3716 if (slirp_is_inited()) {
3717 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3719 #endif
3720 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3721 if (ret > 0) {
3722 IOHandlerRecord **pioh;
3724 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3725 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3726 ioh->fd_read(ioh->opaque);
3727 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3728 FD_CLR(ioh->fd, &rfds);
3730 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3731 ioh->fd_write(ioh->opaque);
3735 /* remove deleted IO handlers */
3736 pioh = &first_io_handler;
3737 while (*pioh) {
3738 ioh = *pioh;
3739 if (ioh->deleted) {
3740 *pioh = ioh->next;
3741 qemu_free(ioh);
3742 } else
3743 pioh = &ioh->next;
3746 #if defined(CONFIG_SLIRP)
3747 if (slirp_is_inited()) {
3748 if (ret < 0) {
3749 FD_ZERO(&rfds);
3750 FD_ZERO(&wfds);
3751 FD_ZERO(&xfds);
3753 slirp_select_poll(&rfds, &wfds, &xfds);
3755 #endif
3757 /* vm time timers */
3758 if (vm_running && (!cur_cpu
3759 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3760 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3761 qemu_get_clock(vm_clock));
3763 /* real time timers */
3764 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3765 qemu_get_clock(rt_clock));
3767 /* Check bottom-halves last in case any of the earlier events triggered
3768 them. */
3769 qemu_bh_poll();
3773 static int main_loop(void)
3775 int ret, timeout;
3776 #ifdef CONFIG_PROFILER
3777 int64_t ti;
3778 #endif
3779 CPUState *env;
3782 if (kvm_enabled()) {
3783 kvm_main_loop();
3784 cpu_disable_ticks();
3785 return 0;
3788 cur_cpu = first_cpu;
3789 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3790 for(;;) {
3791 if (vm_running) {
3793 for(;;) {
3794 /* get next cpu */
3795 env = next_cpu;
3796 #ifdef CONFIG_PROFILER
3797 ti = profile_getclock();
3798 #endif
3799 if (use_icount) {
3800 int64_t count;
3801 int decr;
3802 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3803 env->icount_decr.u16.low = 0;
3804 env->icount_extra = 0;
3805 count = qemu_next_deadline();
3806 count = (count + (1 << icount_time_shift) - 1)
3807 >> icount_time_shift;
3808 qemu_icount += count;
3809 decr = (count > 0xffff) ? 0xffff : count;
3810 count -= decr;
3811 env->icount_decr.u16.low = decr;
3812 env->icount_extra = count;
3814 ret = cpu_exec(env);
3815 #ifdef CONFIG_PROFILER
3816 qemu_time += profile_getclock() - ti;
3817 #endif
3818 if (use_icount) {
3819 /* Fold pending instructions back into the
3820 instruction counter, and clear the interrupt flag. */
3821 qemu_icount -= (env->icount_decr.u16.low
3822 + env->icount_extra);
3823 env->icount_decr.u32 = 0;
3824 env->icount_extra = 0;
3826 next_cpu = env->next_cpu ?: first_cpu;
3827 if (event_pending && likely(ret != EXCP_DEBUG)) {
3828 ret = EXCP_INTERRUPT;
3829 event_pending = 0;
3830 break;
3832 if (ret == EXCP_HLT) {
3833 /* Give the next CPU a chance to run. */
3834 cur_cpu = env;
3835 continue;
3837 if (ret != EXCP_HALTED)
3838 break;
3839 /* all CPUs are halted ? */
3840 if (env == cur_cpu)
3841 break;
3843 cur_cpu = env;
3845 if (shutdown_requested) {
3846 ret = EXCP_INTERRUPT;
3847 if (no_shutdown) {
3848 vm_stop(0);
3849 no_shutdown = 0;
3851 else
3852 break;
3854 if (reset_requested) {
3855 reset_requested = 0;
3856 qemu_system_reset();
3857 if (kvm_enabled())
3858 kvm_load_registers(env);
3859 ret = EXCP_INTERRUPT;
3861 if (powerdown_requested) {
3862 powerdown_requested = 0;
3863 qemu_system_powerdown();
3864 ret = EXCP_INTERRUPT;
3866 #ifdef CONFIG_GDBSTUB
3867 if (unlikely(ret == EXCP_DEBUG)) {
3868 gdb_set_stop_cpu(cur_cpu);
3869 vm_stop(EXCP_DEBUG);
3871 #endif
3872 /* If all cpus are halted then wait until the next IRQ */
3873 /* XXX: use timeout computed from timers */
3874 if (ret == EXCP_HALTED) {
3875 if (use_icount) {
3876 int64_t add;
3877 int64_t delta;
3878 /* Advance virtual time to the next event. */
3879 if (use_icount == 1) {
3880 /* When not using an adaptive execution frequency
3881 we tend to get badly out of sync with real time,
3882 so just delay for a reasonable amount of time. */
3883 delta = 0;
3884 } else {
3885 delta = cpu_get_icount() - cpu_get_clock();
3887 if (delta > 0) {
3888 /* If virtual time is ahead of real time then just
3889 wait for IO. */
3890 timeout = (delta / 1000000) + 1;
3891 } else {
3892 /* Wait for either IO to occur or the next
3893 timer event. */
3894 add = qemu_next_deadline();
3895 /* We advance the timer before checking for IO.
3896 Limit the amount we advance so that early IO
3897 activity won't get the guest too far ahead. */
3898 if (add > 10000000)
3899 add = 10000000;
3900 delta += add;
3901 add = (add + (1 << icount_time_shift) - 1)
3902 >> icount_time_shift;
3903 qemu_icount += add;
3904 timeout = delta / 1000000;
3905 if (timeout < 0)
3906 timeout = 0;
3908 } else {
3909 timeout = 5000;
3911 } else {
3912 timeout = 0;
3914 } else {
3915 if (shutdown_requested) {
3916 ret = EXCP_INTERRUPT;
3917 break;
3919 timeout = 5000;
3921 #ifdef CONFIG_PROFILER
3922 ti = profile_getclock();
3923 #endif
3924 main_loop_wait(timeout);
3925 #ifdef CONFIG_PROFILER
3926 dev_time += profile_getclock() - ti;
3927 #endif
3929 cpu_disable_ticks();
3930 return ret;
3933 static void help(int exitcode)
3935 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
3936 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3937 "usage: %s [options] [disk_image]\n"
3938 "\n"
3939 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3940 "\n"
3941 "Standard options:\n"
3942 "-M machine select emulated machine (-M ? for list)\n"
3943 "-cpu cpu select CPU (-cpu ? for list)\n"
3944 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3945 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3946 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3947 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3948 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3949 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3950 " [,cache=writethrough|writeback|none][,format=f]\n"
3951 " [,boot=on|off]\n"
3952 " use 'file' as a drive image\n"
3953 "-mtdblock file use 'file' as on-board Flash memory image\n"
3954 "-sd file use 'file' as SecureDigital card image\n"
3955 "-pflash file use 'file' as a parallel flash image\n"
3956 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3957 "-snapshot write to temporary files instead of disk image files\n"
3958 #ifdef CONFIG_SDL
3959 "-no-frame open SDL window without a frame and window decorations\n"
3960 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3961 "-no-quit disable SDL window close capability\n"
3962 #endif
3963 #ifdef TARGET_I386
3964 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3965 #endif
3966 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3967 "-smp n set the number of CPUs to 'n' [default=1]\n"
3968 "-nographic disable graphical output and redirect serial I/Os to console\n"
3969 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3970 #ifndef _WIN32
3971 "-k language use keyboard layout (for example \"fr\" for French)\n"
3972 #endif
3973 #ifdef HAS_AUDIO
3974 "-audio-help print list of audio drivers and their options\n"
3975 "-soundhw c1,... enable audio support\n"
3976 " and only specified sound cards (comma separated list)\n"
3977 " use -soundhw ? to get the list of supported cards\n"
3978 " use -soundhw all to enable all of them\n"
3979 #endif
3980 "-vga [std|cirrus|vmware]\n"
3981 " select video card type\n"
3982 "-localtime set the real time clock to local time [default=utc]\n"
3983 "-full-screen start in full screen\n"
3984 #ifdef TARGET_I386
3985 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3986 #endif
3987 "-usb enable the USB driver (will be the default soon)\n"
3988 "-usbdevice name add the host or guest USB device 'name'\n"
3989 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3990 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3991 #endif
3992 "-name string set the name of the guest\n"
3993 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
3994 "\n"
3995 "Network options:\n"
3996 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
3997 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3998 #ifdef CONFIG_SLIRP
3999 "-net user[,vlan=n][,hostname=host]\n"
4000 " connect the user mode network stack to VLAN 'n' and send\n"
4001 " hostname 'host' to DHCP clients\n"
4002 #endif
4003 #ifdef _WIN32
4004 "-net tap[,vlan=n],ifname=name\n"
4005 " connect the host TAP network interface to VLAN 'n'\n"
4006 #else
4007 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4008 " connect the host TAP network interface to VLAN 'n' and use the\n"
4009 " network scripts 'file' (default=%s)\n"
4010 " and 'dfile' (default=%s);\n"
4011 " use '[down]script=no' to disable script execution;\n"
4012 " use 'fd=h' to connect to an already opened TAP interface\n"
4013 #endif
4014 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4015 " connect the vlan 'n' to another VLAN using a socket connection\n"
4016 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4017 " connect the vlan 'n' to multicast maddr and port\n"
4018 #ifdef CONFIG_VDE
4019 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4020 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4021 " on host and listening for incoming connections on 'socketpath'.\n"
4022 " Use group 'groupname' and mode 'octalmode' to change default\n"
4023 " ownership and permissions for communication port.\n"
4024 #endif
4025 "-net none use it alone to have zero network devices; if no -net option\n"
4026 " is provided, the default is '-net nic -net user'\n"
4027 "\n"
4028 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
4029 "-bt hci,host[:id]\n"
4030 " Use host's HCI with the given name\n"
4031 "-bt hci[,vlan=n]\n"
4032 " Emulate a standard HCI in virtual scatternet 'n'\n"
4033 "-bt vhci[,vlan=n]\n"
4034 " Add host computer to virtual scatternet 'n' using VHCI\n"
4035 "-bt device:dev[,vlan=n]\n"
4036 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
4037 "\n"
4038 #ifdef CONFIG_SLIRP
4039 "-tftp dir allow tftp access to files in dir [-net user]\n"
4040 "-bootp file advertise file in BOOTP replies\n"
4041 #ifndef _WIN32
4042 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4043 #endif
4044 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4045 " redirect TCP or UDP connections from host to guest [-net user]\n"
4046 #endif
4047 "\n"
4048 "Linux boot specific:\n"
4049 "-kernel bzImage use 'bzImage' as kernel image\n"
4050 "-append cmdline use 'cmdline' as kernel command line\n"
4051 "-initrd file use 'file' as initial ram disk\n"
4052 "\n"
4053 "Debug/Expert options:\n"
4054 "-monitor dev redirect the monitor to char device 'dev'\n"
4055 "-serial dev redirect the serial port to char device 'dev'\n"
4056 "-parallel dev redirect the parallel port to char device 'dev'\n"
4057 "-pidfile file Write PID to 'file'\n"
4058 "-S freeze CPU at startup (use 'c' to start execution)\n"
4059 "-s wait gdb connection to port\n"
4060 "-p port set gdb connection port [default=%s]\n"
4061 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4062 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4063 " translation (t=none or lba) (usually qemu can guess them)\n"
4064 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4065 #ifdef USE_KQEMU
4066 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4067 "-no-kqemu disable KQEMU kernel module usage\n"
4068 #endif
4069 #ifdef CONFIG_KVM
4070 "-enable-kvm enable KVM full virtualization support\n"
4071 #endif
4072 #ifdef USE_KVM
4073 #ifndef NO_CPU_EMULATION
4074 "-no-kvm disable KVM hardware virtualization\n"
4075 #endif
4076 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4077 "-no-kvm-pit disable KVM kernel mode PIT\n"
4078 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4079 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4080 " expose a PCI device to the guest OS.\n"
4081 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4082 " 'string' is used in log output.\n"
4083 #endif
4084 #endif
4085 #ifdef TARGET_I386
4086 "-no-acpi disable ACPI\n"
4087 #endif
4088 #ifdef CONFIG_CURSES
4089 "-curses use a curses/ncurses interface instead of SDL\n"
4090 #endif
4091 "-no-reboot exit instead of rebooting\n"
4092 "-no-shutdown stop before shutdown\n"
4093 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
4094 "-vnc display start a VNC server on display\n"
4095 #ifndef _WIN32
4096 "-daemonize daemonize QEMU after initializing\n"
4097 #endif
4098 "-tdf inject timer interrupts that got lost\n"
4099 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4100 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
4101 "-option-rom rom load a file, rom, into the option ROM space\n"
4102 #ifdef TARGET_SPARC
4103 "-prom-env variable=value set OpenBIOS nvram variables\n"
4104 #endif
4105 "-clock force the use of the given methods for timer alarm.\n"
4106 " To see what timers are available use -clock ?\n"
4107 "-startdate select initial date of the clock\n"
4108 "-icount [N|auto]\n"
4109 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4110 "\n"
4111 "During emulation, the following keys are useful:\n"
4112 "ctrl-alt-f toggle full screen\n"
4113 "ctrl-alt-n switch to virtual console 'n'\n"
4114 "ctrl-alt toggle mouse and keyboard grab\n"
4115 "\n"
4116 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4118 "qemu",
4119 DEFAULT_RAM_SIZE,
4120 #ifndef _WIN32
4121 DEFAULT_NETWORK_SCRIPT,
4122 DEFAULT_NETWORK_DOWN_SCRIPT,
4123 #endif
4124 DEFAULT_GDBSTUB_PORT,
4125 "/tmp/qemu.log");
4126 exit(exitcode);
4129 #define HAS_ARG 0x0001
4131 enum {
4132 QEMU_OPTION_h,
4134 QEMU_OPTION_M,
4135 QEMU_OPTION_cpu,
4136 QEMU_OPTION_fda,
4137 QEMU_OPTION_fdb,
4138 QEMU_OPTION_hda,
4139 QEMU_OPTION_hdb,
4140 QEMU_OPTION_hdc,
4141 QEMU_OPTION_hdd,
4142 QEMU_OPTION_drive,
4143 QEMU_OPTION_cdrom,
4144 QEMU_OPTION_mtdblock,
4145 QEMU_OPTION_sd,
4146 QEMU_OPTION_pflash,
4147 QEMU_OPTION_boot,
4148 QEMU_OPTION_snapshot,
4149 #ifdef TARGET_I386
4150 QEMU_OPTION_no_fd_bootchk,
4151 #endif
4152 QEMU_OPTION_m,
4153 QEMU_OPTION_nographic,
4154 QEMU_OPTION_portrait,
4155 #ifdef HAS_AUDIO
4156 QEMU_OPTION_audio_help,
4157 QEMU_OPTION_soundhw,
4158 #endif
4160 QEMU_OPTION_net,
4161 QEMU_OPTION_tftp,
4162 QEMU_OPTION_bootp,
4163 QEMU_OPTION_smb,
4164 QEMU_OPTION_redir,
4165 QEMU_OPTION_bt,
4167 QEMU_OPTION_kernel,
4168 QEMU_OPTION_append,
4169 QEMU_OPTION_initrd,
4171 QEMU_OPTION_S,
4172 QEMU_OPTION_s,
4173 QEMU_OPTION_p,
4174 QEMU_OPTION_d,
4175 QEMU_OPTION_hdachs,
4176 QEMU_OPTION_L,
4177 QEMU_OPTION_bios,
4178 QEMU_OPTION_k,
4179 QEMU_OPTION_localtime,
4180 QEMU_OPTION_g,
4181 QEMU_OPTION_vga,
4182 QEMU_OPTION_echr,
4183 QEMU_OPTION_monitor,
4184 QEMU_OPTION_serial,
4185 QEMU_OPTION_parallel,
4186 QEMU_OPTION_loadvm,
4187 QEMU_OPTION_full_screen,
4188 QEMU_OPTION_no_frame,
4189 QEMU_OPTION_alt_grab,
4190 QEMU_OPTION_no_quit,
4191 QEMU_OPTION_pidfile,
4192 QEMU_OPTION_no_kqemu,
4193 QEMU_OPTION_kernel_kqemu,
4194 QEMU_OPTION_enable_kvm,
4195 QEMU_OPTION_win2k_hack,
4196 QEMU_OPTION_usb,
4197 QEMU_OPTION_usbdevice,
4198 QEMU_OPTION_smp,
4199 QEMU_OPTION_vnc,
4200 QEMU_OPTION_no_acpi,
4201 QEMU_OPTION_curses,
4202 QEMU_OPTION_no_kvm,
4203 QEMU_OPTION_no_kvm_irqchip,
4204 QEMU_OPTION_no_kvm_pit,
4205 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4206 QEMU_OPTION_pcidevice,
4207 #endif
4208 QEMU_OPTION_no_reboot,
4209 QEMU_OPTION_no_shutdown,
4210 QEMU_OPTION_show_cursor,
4211 QEMU_OPTION_daemonize,
4212 QEMU_OPTION_option_rom,
4213 QEMU_OPTION_semihosting,
4214 QEMU_OPTION_cpu_vendor,
4215 QEMU_OPTION_name,
4216 QEMU_OPTION_prom_env,
4217 QEMU_OPTION_old_param,
4218 QEMU_OPTION_clock,
4219 QEMU_OPTION_startdate,
4220 QEMU_OPTION_tb_size,
4221 QEMU_OPTION_icount,
4222 QEMU_OPTION_uuid,
4223 QEMU_OPTION_incoming,
4224 QEMU_OPTION_tdf,
4225 QEMU_OPTION_kvm_shadow_memory,
4226 QEMU_OPTION_mempath,
4229 typedef struct QEMUOption {
4230 const char *name;
4231 int flags;
4232 int index;
4233 } QEMUOption;
4235 static const QEMUOption qemu_options[] = {
4236 { "h", 0, QEMU_OPTION_h },
4237 { "help", 0, QEMU_OPTION_h },
4239 { "M", HAS_ARG, QEMU_OPTION_M },
4240 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4241 { "fda", HAS_ARG, QEMU_OPTION_fda },
4242 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4243 { "hda", HAS_ARG, QEMU_OPTION_hda },
4244 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4245 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4246 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4247 { "drive", HAS_ARG, QEMU_OPTION_drive },
4248 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4249 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4250 { "sd", HAS_ARG, QEMU_OPTION_sd },
4251 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4252 { "boot", HAS_ARG, QEMU_OPTION_boot },
4253 { "snapshot", 0, QEMU_OPTION_snapshot },
4254 #ifdef TARGET_I386
4255 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4256 #endif
4257 { "m", HAS_ARG, QEMU_OPTION_m },
4258 { "nographic", 0, QEMU_OPTION_nographic },
4259 { "portrait", 0, QEMU_OPTION_portrait },
4260 { "k", HAS_ARG, QEMU_OPTION_k },
4261 #ifdef HAS_AUDIO
4262 { "audio-help", 0, QEMU_OPTION_audio_help },
4263 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4264 #endif
4266 { "net", HAS_ARG, QEMU_OPTION_net},
4267 #ifdef CONFIG_SLIRP
4268 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4269 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4270 #ifndef _WIN32
4271 { "smb", HAS_ARG, QEMU_OPTION_smb },
4272 #endif
4273 { "redir", HAS_ARG, QEMU_OPTION_redir },
4274 #endif
4275 { "bt", HAS_ARG, QEMU_OPTION_bt },
4277 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4278 { "append", HAS_ARG, QEMU_OPTION_append },
4279 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4281 { "S", 0, QEMU_OPTION_S },
4282 { "s", 0, QEMU_OPTION_s },
4283 { "p", HAS_ARG, QEMU_OPTION_p },
4284 { "d", HAS_ARG, QEMU_OPTION_d },
4285 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4286 { "L", HAS_ARG, QEMU_OPTION_L },
4287 { "bios", HAS_ARG, QEMU_OPTION_bios },
4288 #ifdef USE_KQEMU
4289 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4290 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4291 #endif
4292 #ifdef CONFIG_KVM
4293 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4294 #endif
4295 #ifdef USE_KVM
4296 #ifndef NO_CPU_EMULATION
4297 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4298 #endif
4299 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4300 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4301 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4302 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4303 #endif
4304 #endif
4305 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4306 { "g", 1, QEMU_OPTION_g },
4307 #endif
4308 { "localtime", 0, QEMU_OPTION_localtime },
4309 { "vga", HAS_ARG, QEMU_OPTION_vga },
4310 { "echr", HAS_ARG, QEMU_OPTION_echr },
4311 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4312 { "serial", HAS_ARG, QEMU_OPTION_serial },
4313 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4314 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4315 { "incoming", 1, QEMU_OPTION_incoming },
4316 { "full-screen", 0, QEMU_OPTION_full_screen },
4317 #ifdef CONFIG_SDL
4318 { "no-frame", 0, QEMU_OPTION_no_frame },
4319 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4320 { "no-quit", 0, QEMU_OPTION_no_quit },
4321 #endif
4322 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4323 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4324 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4325 { "smp", HAS_ARG, QEMU_OPTION_smp },
4326 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4327 #ifdef CONFIG_CURSES
4328 { "curses", 0, QEMU_OPTION_curses },
4329 #endif
4330 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4332 /* temporary options */
4333 { "usb", 0, QEMU_OPTION_usb },
4334 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4335 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4336 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4337 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4338 { "daemonize", 0, QEMU_OPTION_daemonize },
4339 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4340 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4341 { "semihosting", 0, QEMU_OPTION_semihosting },
4342 #endif
4343 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4344 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4345 { "name", HAS_ARG, QEMU_OPTION_name },
4346 #if defined(TARGET_SPARC)
4347 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4348 #endif
4349 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4350 #if defined(TARGET_ARM)
4351 { "old-param", 0, QEMU_OPTION_old_param },
4352 #endif
4353 { "clock", HAS_ARG, QEMU_OPTION_clock },
4354 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4355 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4356 { "icount", HAS_ARG, QEMU_OPTION_icount },
4357 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4358 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4359 { NULL },
4362 /* password input */
4364 int qemu_key_check(BlockDriverState *bs, const char *name)
4366 char password[256];
4367 int i;
4369 if (!bdrv_is_encrypted(bs))
4370 return 0;
4372 term_printf("%s is encrypted.\n", name);
4373 for(i = 0; i < 3; i++) {
4374 monitor_readline("Password: ", 1, password, sizeof(password));
4375 if (bdrv_set_key(bs, password) == 0)
4376 return 0;
4377 term_printf("invalid password\n");
4379 return -EPERM;
4382 static BlockDriverState *get_bdrv(int index)
4384 if (index > nb_drives)
4385 return NULL;
4386 return drives_table[index].bdrv;
4389 static void read_passwords(void)
4391 BlockDriverState *bs;
4392 int i;
4394 for(i = 0; i < 6; i++) {
4395 bs = get_bdrv(i);
4396 if (bs)
4397 qemu_key_check(bs, bdrv_get_device_name(bs));
4401 #ifdef HAS_AUDIO
4402 struct soundhw soundhw[] = {
4403 #ifdef HAS_AUDIO_CHOICE
4404 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4406 "pcspk",
4407 "PC speaker",
4410 { .init_isa = pcspk_audio_init }
4412 #endif
4414 "sb16",
4415 "Creative Sound Blaster 16",
4418 { .init_isa = SB16_init }
4421 #ifdef CONFIG_CS4231A
4423 "cs4231a",
4424 "CS4231A",
4427 { .init_isa = cs4231a_init }
4429 #endif
4431 #ifdef CONFIG_ADLIB
4433 "adlib",
4434 #ifdef HAS_YMF262
4435 "Yamaha YMF262 (OPL3)",
4436 #else
4437 "Yamaha YM3812 (OPL2)",
4438 #endif
4441 { .init_isa = Adlib_init }
4443 #endif
4445 #ifdef CONFIG_GUS
4447 "gus",
4448 "Gravis Ultrasound GF1",
4451 { .init_isa = GUS_init }
4453 #endif
4455 #ifdef CONFIG_AC97
4457 "ac97",
4458 "Intel 82801AA AC97 Audio",
4461 { .init_pci = ac97_init }
4463 #endif
4466 "es1370",
4467 "ENSONIQ AudioPCI ES1370",
4470 { .init_pci = es1370_init }
4472 #endif
4474 { NULL, NULL, 0, 0, { NULL } }
4477 static void select_soundhw (const char *optarg)
4479 struct soundhw *c;
4481 if (*optarg == '?') {
4482 show_valid_cards:
4484 printf ("Valid sound card names (comma separated):\n");
4485 for (c = soundhw; c->name; ++c) {
4486 printf ("%-11s %s\n", c->name, c->descr);
4488 printf ("\n-soundhw all will enable all of the above\n");
4489 exit (*optarg != '?');
4491 else {
4492 size_t l;
4493 const char *p;
4494 char *e;
4495 int bad_card = 0;
4497 if (!strcmp (optarg, "all")) {
4498 for (c = soundhw; c->name; ++c) {
4499 c->enabled = 1;
4501 return;
4504 p = optarg;
4505 while (*p) {
4506 e = strchr (p, ',');
4507 l = !e ? strlen (p) : (size_t) (e - p);
4509 for (c = soundhw; c->name; ++c) {
4510 if (!strncmp (c->name, p, l)) {
4511 c->enabled = 1;
4512 break;
4516 if (!c->name) {
4517 if (l > 80) {
4518 fprintf (stderr,
4519 "Unknown sound card name (too big to show)\n");
4521 else {
4522 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4523 (int) l, p);
4525 bad_card = 1;
4527 p += l + (e != NULL);
4530 if (bad_card)
4531 goto show_valid_cards;
4534 #endif
4536 static void select_vgahw (const char *p)
4538 const char *opts;
4540 if (strstart(p, "std", &opts)) {
4541 cirrus_vga_enabled = 0;
4542 vmsvga_enabled = 0;
4543 } else if (strstart(p, "cirrus", &opts)) {
4544 cirrus_vga_enabled = 1;
4545 vmsvga_enabled = 0;
4546 } else if (strstart(p, "vmware", &opts)) {
4547 cirrus_vga_enabled = 0;
4548 vmsvga_enabled = 1;
4549 } else {
4550 invalid_vga:
4551 fprintf(stderr, "Unknown vga type: %s\n", p);
4552 exit(1);
4554 while (*opts) {
4555 const char *nextopt;
4557 if (strstart(opts, ",retrace=", &nextopt)) {
4558 opts = nextopt;
4559 if (strstart(opts, "dumb", &nextopt))
4560 vga_retrace_method = VGA_RETRACE_DUMB;
4561 else if (strstart(opts, "precise", &nextopt))
4562 vga_retrace_method = VGA_RETRACE_PRECISE;
4563 else goto invalid_vga;
4564 } else goto invalid_vga;
4565 opts = nextopt;
4569 #ifdef _WIN32
4570 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4572 exit(STATUS_CONTROL_C_EXIT);
4573 return TRUE;
4575 #endif
4577 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4579 int ret;
4581 if(strlen(str) != 36)
4582 return -1;
4584 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4585 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4586 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4588 if(ret != 16)
4589 return -1;
4591 return 0;
4594 #define MAX_NET_CLIENTS 32
4596 static int saved_argc;
4597 static char **saved_argv;
4599 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4601 *argc = saved_argc;
4602 *argv = saved_argv;
4603 *opt_daemonize = daemonize;
4604 *opt_incoming = incoming;
4608 static int gethugepagesize(void)
4610 int ret, fd;
4611 char buf[4096];
4612 char *needle = "Hugepagesize:";
4613 char *size;
4614 unsigned long hugepagesize;
4616 fd = open("/proc/meminfo", O_RDONLY);
4617 if (fd < 0) {
4618 perror("open");
4619 exit(0);
4622 ret = read(fd, buf, sizeof(buf));
4623 if (ret < 0) {
4624 perror("read");
4625 exit(0);
4628 size = strstr(buf, needle);
4629 if (!size)
4630 return 0;
4631 size += strlen(needle);
4632 hugepagesize = strtol(size, NULL, 0);
4633 return hugepagesize;
4636 void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4638 char *filename;
4639 void *area;
4640 int fd;
4642 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4643 return NULL;
4645 hpagesize = gethugepagesize() * 1024;
4646 if (!hpagesize)
4647 return NULL;
4649 fd = mkstemp(filename);
4650 if (fd < 0) {
4651 perror("mkstemp");
4652 free(filename);
4653 return NULL;
4655 unlink(filename);
4656 free(filename);
4658 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4661 * ftruncate is not supported by hugetlbfs in older
4662 * hosts, so don't bother checking for errors.
4663 * If anything goes wrong with it under other filesystems,
4664 * mmap will fail.
4666 ftruncate(fd, memory);
4668 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4669 if (area == MAP_FAILED) {
4670 perror("mmap");
4671 close(fd);
4672 return NULL;
4675 *len = memory;
4676 return area;
4679 void *qemu_alloc_physram(unsigned long memory)
4681 void *area = NULL;
4682 unsigned long map_len = memory;
4684 #ifdef USE_KVM
4685 if (mem_path)
4686 area = alloc_mem_area(memory, &map_len, mem_path);
4687 #endif
4688 if (!area)
4689 area = qemu_vmalloc(memory);
4690 #ifdef USE_KVM
4691 if (kvm_setup_guest_memory(area, map_len))
4692 area = NULL;
4693 #endif
4694 return area;
4697 #ifndef _WIN32
4699 static void termsig_handler(int signal)
4701 qemu_system_shutdown_request();
4704 static void termsig_setup(void)
4706 struct sigaction act;
4708 memset(&act, 0, sizeof(act));
4709 act.sa_handler = termsig_handler;
4710 sigaction(SIGINT, &act, NULL);
4711 sigaction(SIGHUP, &act, NULL);
4712 sigaction(SIGTERM, &act, NULL);
4715 #endif
4717 int main(int argc, char **argv)
4719 #ifdef CONFIG_GDBSTUB
4720 int use_gdbstub;
4721 const char *gdbstub_port;
4722 #endif
4723 uint32_t boot_devices_bitmap = 0;
4724 int i;
4725 int snapshot, linux_boot, net_boot;
4726 const char *initrd_filename;
4727 const char *kernel_filename, *kernel_cmdline;
4728 const char *boot_devices = "";
4729 DisplayState *ds = &display_state;
4730 int cyls, heads, secs, translation;
4731 const char *net_clients[MAX_NET_CLIENTS];
4732 int nb_net_clients;
4733 const char *bt_opts[MAX_BT_CMDLINE];
4734 int nb_bt_opts;
4735 int hda_index;
4736 int optind;
4737 const char *r, *optarg;
4738 CharDriverState *monitor_hd;
4739 const char *monitor_device;
4740 const char *serial_devices[MAX_SERIAL_PORTS];
4741 int serial_device_index;
4742 const char *parallel_devices[MAX_PARALLEL_PORTS];
4743 int parallel_device_index;
4744 const char *loadvm = NULL;
4745 QEMUMachine *machine;
4746 const char *cpu_model;
4747 const char *usb_devices[MAX_USB_CMDLINE];
4748 int usb_devices_index;
4749 int fds[2];
4750 int tb_size;
4751 const char *pid_file = NULL;
4752 int autostart;
4753 const char *incoming = NULL;
4755 LIST_INIT (&vm_change_state_head);
4756 #ifndef _WIN32
4758 struct sigaction act;
4759 sigfillset(&act.sa_mask);
4760 act.sa_flags = 0;
4761 act.sa_handler = SIG_IGN;
4762 sigaction(SIGPIPE, &act, NULL);
4764 #else
4765 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4766 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4767 QEMU to run on a single CPU */
4769 HANDLE h;
4770 DWORD mask, smask;
4771 int i;
4772 h = GetCurrentProcess();
4773 if (GetProcessAffinityMask(h, &mask, &smask)) {
4774 for(i = 0; i < 32; i++) {
4775 if (mask & (1 << i))
4776 break;
4778 if (i != 32) {
4779 mask = 1 << i;
4780 SetProcessAffinityMask(h, mask);
4784 #endif
4786 register_machines();
4787 machine = first_machine;
4788 cpu_model = NULL;
4789 initrd_filename = NULL;
4790 ram_size = 0;
4791 vga_ram_size = VGA_RAM_SIZE;
4792 #ifdef CONFIG_GDBSTUB
4793 use_gdbstub = 0;
4794 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4795 #endif
4796 snapshot = 0;
4797 nographic = 0;
4798 curses = 0;
4799 kernel_filename = NULL;
4800 kernel_cmdline = "";
4801 cyls = heads = secs = 0;
4802 translation = BIOS_ATA_TRANSLATION_AUTO;
4803 monitor_device = "vc";
4805 serial_devices[0] = "vc:80Cx24C";
4806 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4807 serial_devices[i] = NULL;
4808 serial_device_index = 0;
4810 parallel_devices[0] = "vc:640x480";
4811 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4812 parallel_devices[i] = NULL;
4813 parallel_device_index = 0;
4815 usb_devices_index = 0;
4816 assigned_devices_index = 0;
4818 nb_net_clients = 0;
4819 nb_bt_opts = 0;
4820 nb_drives = 0;
4821 nb_drives_opt = 0;
4822 hda_index = -1;
4824 nb_nics = 0;
4826 tb_size = 0;
4827 autostart= 1;
4829 optind = 1;
4830 for(;;) {
4831 if (optind >= argc)
4832 break;
4833 r = argv[optind];
4834 if (r[0] != '-') {
4835 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4836 } else {
4837 const QEMUOption *popt;
4839 optind++;
4840 /* Treat --foo the same as -foo. */
4841 if (r[1] == '-')
4842 r++;
4843 popt = qemu_options;
4844 for(;;) {
4845 if (!popt->name) {
4846 fprintf(stderr, "%s: invalid option -- '%s'\n",
4847 argv[0], r);
4848 exit(1);
4850 if (!strcmp(popt->name, r + 1))
4851 break;
4852 popt++;
4854 if (popt->flags & HAS_ARG) {
4855 if (optind >= argc) {
4856 fprintf(stderr, "%s: option '%s' requires an argument\n",
4857 argv[0], r);
4858 exit(1);
4860 optarg = argv[optind++];
4861 } else {
4862 optarg = NULL;
4865 switch(popt->index) {
4866 case QEMU_OPTION_M:
4867 machine = find_machine(optarg);
4868 if (!machine) {
4869 QEMUMachine *m;
4870 printf("Supported machines are:\n");
4871 for(m = first_machine; m != NULL; m = m->next) {
4872 printf("%-10s %s%s\n",
4873 m->name, m->desc,
4874 m == first_machine ? " (default)" : "");
4876 exit(*optarg != '?');
4878 break;
4879 case QEMU_OPTION_cpu:
4880 /* hw initialization will check this */
4881 if (*optarg == '?') {
4882 /* XXX: implement xxx_cpu_list for targets that still miss it */
4883 #if defined(cpu_list)
4884 cpu_list(stdout, &fprintf);
4885 #endif
4886 exit(0);
4887 } else {
4888 cpu_model = optarg;
4890 break;
4891 case QEMU_OPTION_initrd:
4892 initrd_filename = optarg;
4893 break;
4894 case QEMU_OPTION_hda:
4895 if (cyls == 0)
4896 hda_index = drive_add(optarg, HD_ALIAS, 0);
4897 else
4898 hda_index = drive_add(optarg, HD_ALIAS
4899 ",cyls=%d,heads=%d,secs=%d%s",
4900 0, cyls, heads, secs,
4901 translation == BIOS_ATA_TRANSLATION_LBA ?
4902 ",trans=lba" :
4903 translation == BIOS_ATA_TRANSLATION_NONE ?
4904 ",trans=none" : "");
4905 break;
4906 case QEMU_OPTION_hdb:
4907 case QEMU_OPTION_hdc:
4908 case QEMU_OPTION_hdd:
4909 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4910 break;
4911 case QEMU_OPTION_drive:
4912 drive_add(NULL, "%s", optarg);
4913 break;
4914 case QEMU_OPTION_mtdblock:
4915 drive_add(optarg, MTD_ALIAS);
4916 break;
4917 case QEMU_OPTION_sd:
4918 drive_add(optarg, SD_ALIAS);
4919 break;
4920 case QEMU_OPTION_pflash:
4921 drive_add(optarg, PFLASH_ALIAS);
4922 break;
4923 case QEMU_OPTION_snapshot:
4924 snapshot = 1;
4925 break;
4926 case QEMU_OPTION_hdachs:
4928 const char *p;
4929 p = optarg;
4930 cyls = strtol(p, (char **)&p, 0);
4931 if (cyls < 1 || cyls > 16383)
4932 goto chs_fail;
4933 if (*p != ',')
4934 goto chs_fail;
4935 p++;
4936 heads = strtol(p, (char **)&p, 0);
4937 if (heads < 1 || heads > 16)
4938 goto chs_fail;
4939 if (*p != ',')
4940 goto chs_fail;
4941 p++;
4942 secs = strtol(p, (char **)&p, 0);
4943 if (secs < 1 || secs > 63)
4944 goto chs_fail;
4945 if (*p == ',') {
4946 p++;
4947 if (!strcmp(p, "none"))
4948 translation = BIOS_ATA_TRANSLATION_NONE;
4949 else if (!strcmp(p, "lba"))
4950 translation = BIOS_ATA_TRANSLATION_LBA;
4951 else if (!strcmp(p, "auto"))
4952 translation = BIOS_ATA_TRANSLATION_AUTO;
4953 else
4954 goto chs_fail;
4955 } else if (*p != '\0') {
4956 chs_fail:
4957 fprintf(stderr, "qemu: invalid physical CHS format\n");
4958 exit(1);
4960 if (hda_index != -1)
4961 snprintf(drives_opt[hda_index].opt,
4962 sizeof(drives_opt[hda_index].opt),
4963 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4964 0, cyls, heads, secs,
4965 translation == BIOS_ATA_TRANSLATION_LBA ?
4966 ",trans=lba" :
4967 translation == BIOS_ATA_TRANSLATION_NONE ?
4968 ",trans=none" : "");
4970 break;
4971 case QEMU_OPTION_nographic:
4972 nographic = 1;
4973 break;
4974 #ifdef CONFIG_CURSES
4975 case QEMU_OPTION_curses:
4976 curses = 1;
4977 break;
4978 #endif
4979 case QEMU_OPTION_portrait:
4980 graphic_rotate = 1;
4981 break;
4982 case QEMU_OPTION_kernel:
4983 kernel_filename = optarg;
4984 break;
4985 case QEMU_OPTION_append:
4986 kernel_cmdline = optarg;
4987 break;
4988 case QEMU_OPTION_cdrom:
4989 drive_add(optarg, CDROM_ALIAS);
4990 break;
4991 case QEMU_OPTION_boot:
4992 boot_devices = optarg;
4993 /* We just do some generic consistency checks */
4995 /* Could easily be extended to 64 devices if needed */
4996 const char *p;
4998 boot_devices_bitmap = 0;
4999 for (p = boot_devices; *p != '\0'; p++) {
5000 /* Allowed boot devices are:
5001 * a b : floppy disk drives
5002 * c ... f : IDE disk drives
5003 * g ... m : machine implementation dependant drives
5004 * n ... p : network devices
5005 * It's up to each machine implementation to check
5006 * if the given boot devices match the actual hardware
5007 * implementation and firmware features.
5009 if (*p < 'a' || *p > 'q') {
5010 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5011 exit(1);
5013 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5014 fprintf(stderr,
5015 "Boot device '%c' was given twice\n",*p);
5016 exit(1);
5018 boot_devices_bitmap |= 1 << (*p - 'a');
5021 break;
5022 case QEMU_OPTION_fda:
5023 case QEMU_OPTION_fdb:
5024 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5025 break;
5026 #ifdef TARGET_I386
5027 case QEMU_OPTION_no_fd_bootchk:
5028 fd_bootchk = 0;
5029 break;
5030 #endif
5031 case QEMU_OPTION_net:
5032 if (nb_net_clients >= MAX_NET_CLIENTS) {
5033 fprintf(stderr, "qemu: too many network clients\n");
5034 exit(1);
5036 net_clients[nb_net_clients] = optarg;
5037 nb_net_clients++;
5038 break;
5039 #ifdef CONFIG_SLIRP
5040 case QEMU_OPTION_tftp:
5041 tftp_prefix = optarg;
5042 break;
5043 case QEMU_OPTION_bootp:
5044 bootp_filename = optarg;
5045 break;
5046 #ifndef _WIN32
5047 case QEMU_OPTION_smb:
5048 net_slirp_smb(optarg);
5049 break;
5050 #endif
5051 case QEMU_OPTION_redir:
5052 net_slirp_redir(optarg);
5053 break;
5054 #endif
5055 case QEMU_OPTION_bt:
5056 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5057 fprintf(stderr, "qemu: too many bluetooth options\n");
5058 exit(1);
5060 bt_opts[nb_bt_opts++] = optarg;
5061 break;
5062 #ifdef HAS_AUDIO
5063 case QEMU_OPTION_audio_help:
5064 AUD_help ();
5065 exit (0);
5066 break;
5067 case QEMU_OPTION_soundhw:
5068 select_soundhw (optarg);
5069 break;
5070 #endif
5071 case QEMU_OPTION_h:
5072 help(0);
5073 break;
5074 case QEMU_OPTION_m: {
5075 uint64_t value;
5076 char *ptr;
5078 value = strtoul(optarg, &ptr, 10);
5079 switch (*ptr) {
5080 case 0: case 'M': case 'm':
5081 value <<= 20;
5082 break;
5083 case 'G': case 'g':
5084 value <<= 30;
5085 break;
5086 default:
5087 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5088 exit(1);
5091 /* On 32-bit hosts, QEMU is limited by virtual address space */
5092 if (value > (2047 << 20)
5093 #ifndef USE_KQEMU
5094 && HOST_LONG_BITS == 32
5095 #endif
5097 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5098 exit(1);
5100 if (value != (uint64_t)(ram_addr_t)value) {
5101 fprintf(stderr, "qemu: ram size too large\n");
5102 exit(1);
5104 ram_size = value;
5105 break;
5107 case QEMU_OPTION_d:
5109 int mask;
5110 const CPULogItem *item;
5112 mask = cpu_str_to_log_mask(optarg);
5113 if (!mask) {
5114 printf("Log items (comma separated):\n");
5115 for(item = cpu_log_items; item->mask != 0; item++) {
5116 printf("%-10s %s\n", item->name, item->help);
5118 exit(1);
5120 cpu_set_log(mask);
5122 break;
5123 #ifdef CONFIG_GDBSTUB
5124 case QEMU_OPTION_s:
5125 use_gdbstub = 1;
5126 break;
5127 case QEMU_OPTION_p:
5128 gdbstub_port = optarg;
5129 break;
5130 #endif
5131 case QEMU_OPTION_L:
5132 bios_dir = optarg;
5133 break;
5134 case QEMU_OPTION_bios:
5135 bios_name = optarg;
5136 break;
5137 case QEMU_OPTION_S:
5138 autostart = 0;
5139 break;
5140 case QEMU_OPTION_k:
5141 keyboard_layout = optarg;
5142 break;
5143 case QEMU_OPTION_localtime:
5144 rtc_utc = 0;
5145 break;
5146 case QEMU_OPTION_vga:
5147 select_vgahw (optarg);
5148 break;
5149 case QEMU_OPTION_g:
5151 const char *p;
5152 int w, h, depth;
5153 p = optarg;
5154 w = strtol(p, (char **)&p, 10);
5155 if (w <= 0) {
5156 graphic_error:
5157 fprintf(stderr, "qemu: invalid resolution or depth\n");
5158 exit(1);
5160 if (*p != 'x')
5161 goto graphic_error;
5162 p++;
5163 h = strtol(p, (char **)&p, 10);
5164 if (h <= 0)
5165 goto graphic_error;
5166 if (*p == 'x') {
5167 p++;
5168 depth = strtol(p, (char **)&p, 10);
5169 if (depth != 8 && depth != 15 && depth != 16 &&
5170 depth != 24 && depth != 32)
5171 goto graphic_error;
5172 } else if (*p == '\0') {
5173 depth = graphic_depth;
5174 } else {
5175 goto graphic_error;
5178 graphic_width = w;
5179 graphic_height = h;
5180 graphic_depth = depth;
5182 break;
5183 case QEMU_OPTION_echr:
5185 char *r;
5186 term_escape_char = strtol(optarg, &r, 0);
5187 if (r == optarg)
5188 printf("Bad argument to echr\n");
5189 break;
5191 case QEMU_OPTION_monitor:
5192 monitor_device = optarg;
5193 break;
5194 case QEMU_OPTION_serial:
5195 if (serial_device_index >= MAX_SERIAL_PORTS) {
5196 fprintf(stderr, "qemu: too many serial ports\n");
5197 exit(1);
5199 serial_devices[serial_device_index] = optarg;
5200 serial_device_index++;
5201 break;
5202 case QEMU_OPTION_parallel:
5203 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5204 fprintf(stderr, "qemu: too many parallel ports\n");
5205 exit(1);
5207 parallel_devices[parallel_device_index] = optarg;
5208 parallel_device_index++;
5209 break;
5210 case QEMU_OPTION_loadvm:
5211 loadvm = optarg;
5212 break;
5213 case QEMU_OPTION_full_screen:
5214 full_screen = 1;
5215 break;
5216 #ifdef CONFIG_SDL
5217 case QEMU_OPTION_no_frame:
5218 no_frame = 1;
5219 break;
5220 case QEMU_OPTION_alt_grab:
5221 alt_grab = 1;
5222 break;
5223 case QEMU_OPTION_no_quit:
5224 no_quit = 1;
5225 break;
5226 #endif
5227 case QEMU_OPTION_pidfile:
5228 pid_file = optarg;
5229 break;
5230 #ifdef TARGET_I386
5231 case QEMU_OPTION_win2k_hack:
5232 win2k_install_hack = 1;
5233 break;
5234 #endif
5235 #ifdef USE_KQEMU
5236 case QEMU_OPTION_no_kqemu:
5237 kqemu_allowed = 0;
5238 break;
5239 case QEMU_OPTION_kernel_kqemu:
5240 kqemu_allowed = 2;
5241 break;
5242 #endif
5243 #ifdef CONFIG_KVM
5244 case QEMU_OPTION_enable_kvm:
5245 kvm_allowed = 1;
5246 #ifdef USE_KQEMU
5247 kqemu_allowed = 0;
5248 #endif
5249 break;
5250 #endif
5251 #ifdef USE_KVM
5252 case QEMU_OPTION_no_kvm:
5253 kvm_allowed = 0;
5254 break;
5255 case QEMU_OPTION_no_kvm_irqchip: {
5256 extern int kvm_irqchip, kvm_pit;
5257 kvm_irqchip = 0;
5258 kvm_pit = 0;
5259 break;
5261 case QEMU_OPTION_no_kvm_pit: {
5262 extern int kvm_pit;
5263 kvm_pit = 0;
5264 break;
5266 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5267 case QEMU_OPTION_pcidevice:
5268 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5269 fprintf(stderr, "Too many assigned devices\n");
5270 exit(1);
5272 assigned_devices[assigned_devices_index] = optarg;
5273 assigned_devices_index++;
5274 break;
5275 #endif
5276 #endif
5277 case QEMU_OPTION_usb:
5278 usb_enabled = 1;
5279 break;
5280 case QEMU_OPTION_usbdevice:
5281 usb_enabled = 1;
5282 if (usb_devices_index >= MAX_USB_CMDLINE) {
5283 fprintf(stderr, "Too many USB devices\n");
5284 exit(1);
5286 usb_devices[usb_devices_index] = optarg;
5287 usb_devices_index++;
5288 break;
5289 case QEMU_OPTION_smp:
5290 smp_cpus = atoi(optarg);
5291 if (smp_cpus < 1) {
5292 fprintf(stderr, "Invalid number of CPUs\n");
5293 exit(1);
5295 break;
5296 case QEMU_OPTION_vnc:
5297 vnc_display = optarg;
5298 break;
5299 case QEMU_OPTION_no_acpi:
5300 acpi_enabled = 0;
5301 break;
5302 case QEMU_OPTION_no_reboot:
5303 no_reboot = 1;
5304 break;
5305 case QEMU_OPTION_no_shutdown:
5306 no_shutdown = 1;
5307 break;
5308 case QEMU_OPTION_show_cursor:
5309 cursor_hide = 0;
5310 break;
5311 case QEMU_OPTION_uuid:
5312 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5313 fprintf(stderr, "Fail to parse UUID string."
5314 " Wrong format.\n");
5315 exit(1);
5317 break;
5318 case QEMU_OPTION_daemonize:
5319 daemonize = 1;
5320 break;
5321 case QEMU_OPTION_option_rom:
5322 if (nb_option_roms >= MAX_OPTION_ROMS) {
5323 fprintf(stderr, "Too many option ROMs\n");
5324 exit(1);
5326 option_rom[nb_option_roms] = optarg;
5327 nb_option_roms++;
5328 break;
5329 case QEMU_OPTION_semihosting:
5330 semihosting_enabled = 1;
5331 break;
5332 case QEMU_OPTION_tdf:
5333 time_drift_fix = 1;
5334 break;
5335 case QEMU_OPTION_kvm_shadow_memory:
5336 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5337 break;
5338 case QEMU_OPTION_mempath:
5339 mem_path = optarg;
5340 break;
5341 case QEMU_OPTION_name:
5342 qemu_name = optarg;
5343 break;
5344 #ifdef TARGET_SPARC
5345 case QEMU_OPTION_prom_env:
5346 if (nb_prom_envs >= MAX_PROM_ENVS) {
5347 fprintf(stderr, "Too many prom variables\n");
5348 exit(1);
5350 prom_envs[nb_prom_envs] = optarg;
5351 nb_prom_envs++;
5352 break;
5353 #endif
5354 case QEMU_OPTION_cpu_vendor:
5355 cpu_vendor_string = optarg;
5356 break;
5357 #ifdef TARGET_ARM
5358 case QEMU_OPTION_old_param:
5359 old_param = 1;
5360 break;
5361 #endif
5362 case QEMU_OPTION_clock:
5363 configure_alarms(optarg);
5364 break;
5365 case QEMU_OPTION_startdate:
5367 struct tm tm;
5368 time_t rtc_start_date;
5369 if (!strcmp(optarg, "now")) {
5370 rtc_date_offset = -1;
5371 } else {
5372 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5373 &tm.tm_year,
5374 &tm.tm_mon,
5375 &tm.tm_mday,
5376 &tm.tm_hour,
5377 &tm.tm_min,
5378 &tm.tm_sec) == 6) {
5379 /* OK */
5380 } else if (sscanf(optarg, "%d-%d-%d",
5381 &tm.tm_year,
5382 &tm.tm_mon,
5383 &tm.tm_mday) == 3) {
5384 tm.tm_hour = 0;
5385 tm.tm_min = 0;
5386 tm.tm_sec = 0;
5387 } else {
5388 goto date_fail;
5390 tm.tm_year -= 1900;
5391 tm.tm_mon--;
5392 rtc_start_date = mktimegm(&tm);
5393 if (rtc_start_date == -1) {
5394 date_fail:
5395 fprintf(stderr, "Invalid date format. Valid format are:\n"
5396 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5397 exit(1);
5399 rtc_date_offset = time(NULL) - rtc_start_date;
5402 break;
5403 case QEMU_OPTION_tb_size:
5404 tb_size = strtol(optarg, NULL, 0);
5405 if (tb_size < 0)
5406 tb_size = 0;
5407 break;
5408 case QEMU_OPTION_icount:
5409 use_icount = 1;
5410 if (strcmp(optarg, "auto") == 0) {
5411 icount_time_shift = -1;
5412 } else {
5413 icount_time_shift = strtol(optarg, NULL, 0);
5415 break;
5416 case QEMU_OPTION_incoming:
5417 incoming = optarg;
5418 break;
5423 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5424 if (kvm_allowed && kqemu_allowed) {
5425 fprintf(stderr,
5426 "You can not enable both KVM and kqemu at the same time\n");
5427 exit(1);
5429 #endif
5431 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5432 if (smp_cpus > machine->max_cpus) {
5433 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5434 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5435 machine->max_cpus);
5436 exit(1);
5439 if (nographic) {
5440 if (serial_device_index == 0)
5441 serial_devices[0] = "stdio";
5442 if (parallel_device_index == 0)
5443 parallel_devices[0] = "null";
5444 if (strncmp(monitor_device, "vc", 2) == 0)
5445 monitor_device = "stdio";
5448 #ifndef _WIN32
5449 if (daemonize) {
5450 pid_t pid;
5452 if (pipe(fds) == -1)
5453 exit(1);
5455 pid = fork();
5456 if (pid > 0) {
5457 uint8_t status;
5458 ssize_t len;
5460 close(fds[1]);
5462 again:
5463 len = read(fds[0], &status, 1);
5464 if (len == -1 && (errno == EINTR))
5465 goto again;
5467 if (len != 1)
5468 exit(1);
5469 else if (status == 1) {
5470 fprintf(stderr, "Could not acquire pidfile\n");
5471 exit(1);
5472 } else
5473 exit(0);
5474 } else if (pid < 0)
5475 exit(1);
5477 setsid();
5479 pid = fork();
5480 if (pid > 0)
5481 exit(0);
5482 else if (pid < 0)
5483 exit(1);
5485 umask(027);
5487 signal(SIGTSTP, SIG_IGN);
5488 signal(SIGTTOU, SIG_IGN);
5489 signal(SIGTTIN, SIG_IGN);
5491 #endif
5493 #if USE_KVM
5494 if (kvm_enabled()) {
5495 if (kvm_qemu_init() < 0) {
5496 extern int kvm_allowed;
5497 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5498 #ifdef NO_CPU_EMULATION
5499 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5500 exit(1);
5501 #endif
5502 kvm_allowed = 0;
5505 #endif
5507 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5508 if (daemonize) {
5509 uint8_t status = 1;
5510 write(fds[1], &status, 1);
5511 } else
5512 fprintf(stderr, "Could not acquire pid file\n");
5513 exit(1);
5516 #ifdef USE_KQEMU
5517 if (smp_cpus > 1)
5518 kqemu_allowed = 0;
5519 #endif
5520 linux_boot = (kernel_filename != NULL);
5521 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5523 if (!linux_boot && net_boot == 0 &&
5524 !machine->nodisk_ok && nb_drives_opt == 0)
5525 help(1);
5527 if (!linux_boot && *kernel_cmdline != '\0') {
5528 fprintf(stderr, "-append only allowed with -kernel option\n");
5529 exit(1);
5532 if (!linux_boot && initrd_filename != NULL) {
5533 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5534 exit(1);
5537 /* boot to floppy or the default cd if no hard disk defined yet */
5538 if (!boot_devices[0]) {
5539 boot_devices = "cad";
5541 setvbuf(stdout, NULL, _IOLBF, 0);
5543 init_timers();
5544 if (init_timer_alarm() < 0) {
5545 fprintf(stderr, "could not initialize alarm timer\n");
5546 exit(1);
5548 if (use_icount && icount_time_shift < 0) {
5549 use_icount = 2;
5550 /* 125MIPS seems a reasonable initial guess at the guest speed.
5551 It will be corrected fairly quickly anyway. */
5552 icount_time_shift = 3;
5553 init_icount_adjust();
5556 #ifdef _WIN32
5557 socket_init();
5558 #endif
5560 /* init network clients */
5561 if (nb_net_clients == 0) {
5562 /* if no clients, we use a default config */
5563 net_clients[nb_net_clients++] = "nic";
5564 #ifdef CONFIG_SLIRP
5565 net_clients[nb_net_clients++] = "user";
5566 #endif
5569 for(i = 0;i < nb_net_clients; i++) {
5570 if (net_client_parse(net_clients[i]) < 0)
5571 exit(1);
5573 net_client_check();
5575 #ifdef TARGET_I386
5576 /* XXX: this should be moved in the PC machine instantiation code */
5577 if (net_boot != 0) {
5578 int netroms = 0;
5579 for (i = 0; i < nb_nics && i < 4; i++) {
5580 const char *model = nd_table[i].model;
5581 char buf[1024];
5582 if (net_boot & (1 << i)) {
5583 if (model == NULL)
5584 model = "rtl8139";
5585 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5586 if (get_image_size(buf) > 0) {
5587 if (nb_option_roms >= MAX_OPTION_ROMS) {
5588 fprintf(stderr, "Too many option ROMs\n");
5589 exit(1);
5591 option_rom[nb_option_roms] = strdup(buf);
5592 nb_option_roms++;
5593 netroms++;
5597 if (netroms == 0) {
5598 fprintf(stderr, "No valid PXE rom found for network device\n");
5599 exit(1);
5602 #endif
5604 /* init the bluetooth world */
5605 for (i = 0; i < nb_bt_opts; i++)
5606 if (bt_parse(bt_opts[i]))
5607 exit(1);
5609 /* init the memory */
5610 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5612 if (machine->ram_require & RAMSIZE_FIXED) {
5613 if (ram_size > 0) {
5614 if (ram_size < phys_ram_size) {
5615 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5616 machine->name, (unsigned long long) phys_ram_size);
5617 exit(-1);
5620 phys_ram_size = ram_size;
5621 } else
5622 ram_size = phys_ram_size;
5623 } else {
5624 if (ram_size == 0)
5625 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5627 phys_ram_size += ram_size;
5630 /* Initialize kvm */
5631 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5632 #define KVM_EXTRA_PAGES 3
5633 #else
5634 #define KVM_EXTRA_PAGES 0
5635 #endif
5636 if (kvm_enabled()) {
5637 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5638 if (kvm_qemu_create_context() < 0) {
5639 fprintf(stderr, "Could not create KVM context\n");
5640 exit(1);
5644 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5645 if (!phys_ram_base) {
5646 fprintf(stderr, "Could not allocate physical memory\n");
5647 exit(1);
5650 /* init the dynamic translator */
5651 cpu_exec_init_all(tb_size * 1024 * 1024);
5653 bdrv_init();
5655 /* we always create the cdrom drive, even if no disk is there */
5657 if (nb_drives_opt < MAX_DRIVES)
5658 drive_add(NULL, CDROM_ALIAS);
5660 /* we always create at least one floppy */
5662 if (nb_drives_opt < MAX_DRIVES)
5663 drive_add(NULL, FD_ALIAS, 0);
5665 /* we always create one sd slot, even if no card is in it */
5667 if (nb_drives_opt < MAX_DRIVES)
5668 drive_add(NULL, SD_ALIAS);
5670 /* open the virtual block devices
5671 * note that migration with device
5672 * hot add/remove is broken.
5674 for(i = 0; i < nb_drives_opt; i++)
5675 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5676 exit(1);
5678 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5679 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5681 /* terminal init */
5682 memset(&display_state, 0, sizeof(display_state));
5683 if (nographic) {
5684 if (curses) {
5685 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5686 exit(1);
5688 /* nearly nothing to do */
5689 dumb_display_init(ds);
5690 } else if (vnc_display != NULL) {
5691 vnc_display_init(ds);
5692 if (vnc_display_open(ds, vnc_display) < 0)
5693 exit(1);
5694 } else
5695 #if defined(CONFIG_CURSES)
5696 if (curses) {
5697 curses_display_init(ds, full_screen);
5698 } else
5699 #endif
5701 #if defined(CONFIG_SDL)
5702 sdl_display_init(ds, full_screen, no_frame);
5703 #elif defined(CONFIG_COCOA)
5704 cocoa_display_init(ds, full_screen);
5705 #else
5706 dumb_display_init(ds);
5707 #endif
5710 #ifndef _WIN32
5711 /* must be after terminal init, SDL library changes signal handlers */
5712 termsig_setup();
5713 #endif
5715 /* Maintain compatibility with multiple stdio monitors */
5716 if (!strcmp(monitor_device,"stdio")) {
5717 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5718 const char *devname = serial_devices[i];
5719 if (devname && !strcmp(devname,"mon:stdio")) {
5720 monitor_device = NULL;
5721 break;
5722 } else if (devname && !strcmp(devname,"stdio")) {
5723 monitor_device = NULL;
5724 serial_devices[i] = "mon:stdio";
5725 break;
5729 if (monitor_device) {
5730 monitor_hd = qemu_chr_open("monitor", monitor_device);
5731 if (!monitor_hd) {
5732 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5733 exit(1);
5735 monitor_init(monitor_hd, !nographic);
5738 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5739 const char *devname = serial_devices[i];
5740 if (devname && strcmp(devname, "none")) {
5741 char label[32];
5742 snprintf(label, sizeof(label), "serial%d", i);
5743 serial_hds[i] = qemu_chr_open(label, devname);
5744 if (!serial_hds[i]) {
5745 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5746 devname);
5747 exit(1);
5749 if (strstart(devname, "vc", 0))
5750 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5754 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5755 const char *devname = parallel_devices[i];
5756 if (devname && strcmp(devname, "none")) {
5757 char label[32];
5758 snprintf(label, sizeof(label), "parallel%d", i);
5759 parallel_hds[i] = qemu_chr_open(label, devname);
5760 if (!parallel_hds[i]) {
5761 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5762 devname);
5763 exit(1);
5765 if (strstart(devname, "vc", 0))
5766 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5770 if (kvm_enabled())
5771 kvm_init_ap();
5773 #ifdef KVM_UPSTREAM
5774 if (kvm_enabled()) {
5775 int ret;
5777 ret = kvm_init(smp_cpus);
5778 if (ret < 0) {
5779 fprintf(stderr, "failed to initialize KVM\n");
5780 exit(1);
5783 #endif
5785 machine->init(ram_size, vga_ram_size, boot_devices, ds,
5786 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5788 current_machine = machine;
5790 /* init USB devices */
5791 if (usb_enabled) {
5792 for(i = 0; i < usb_devices_index; i++) {
5793 if (usb_device_add(usb_devices[i]) < 0) {
5794 fprintf(stderr, "Warning: could not add USB device %s\n",
5795 usb_devices[i]);
5800 if (display_state.dpy_refresh) {
5801 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5802 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5805 #ifdef CONFIG_GDBSTUB
5806 if (use_gdbstub) {
5807 /* XXX: use standard host:port notation and modify options
5808 accordingly. */
5809 if (gdbserver_start(gdbstub_port) < 0) {
5810 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5811 gdbstub_port);
5812 exit(1);
5815 #endif
5817 if (loadvm)
5818 do_loadvm(loadvm);
5820 if (incoming) {
5821 autostart = 0; /* fixme how to deal with -daemonize */
5822 qemu_start_incoming_migration(incoming);
5826 /* XXX: simplify init */
5827 read_passwords();
5828 if (autostart) {
5829 vm_start();
5833 if (daemonize) {
5834 uint8_t status = 0;
5835 ssize_t len;
5836 int fd;
5838 again1:
5839 len = write(fds[1], &status, 1);
5840 if (len == -1 && (errno == EINTR))
5841 goto again1;
5843 if (len != 1)
5844 exit(1);
5846 chdir("/");
5847 TFR(fd = open("/dev/null", O_RDWR));
5848 if (fd == -1)
5849 exit(1);
5851 dup2(fd, 0);
5852 dup2(fd, 1);
5853 dup2(fd, 2);
5855 close(fd);
5858 main_loop();
5859 quit_timers();
5860 net_cleanup();
5862 return 0;