Build fix for !CONFIG_GDBSTUB case
[qemu-kvm/fedora.git] / vl.c
blob46733e9041752ccc864c6bb0168825db6e494382
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 /* vm time timers */
1677 if (vm_running && likely(!(cur_cpu && (cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
1678 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
1679 qemu_get_clock(vm_clock));
1681 /* real time timers */
1682 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
1683 qemu_get_clock(rt_clock));
1685 if (t->flags & ALARM_FLAG_EXPIRED) {
1686 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1687 qemu_rearm_alarm_timer(alarm_timer);
1691 #ifdef _WIN32
1693 static int win32_start_timer(struct qemu_alarm_timer *t)
1695 TIMECAPS tc;
1696 struct qemu_alarm_win32 *data = t->priv;
1697 UINT flags;
1699 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1700 if (!data->host_alarm) {
1701 perror("Failed CreateEvent");
1702 return -1;
1705 memset(&tc, 0, sizeof(tc));
1706 timeGetDevCaps(&tc, sizeof(tc));
1708 if (data->period < tc.wPeriodMin)
1709 data->period = tc.wPeriodMin;
1711 timeBeginPeriod(data->period);
1713 flags = TIME_CALLBACK_FUNCTION;
1714 if (alarm_has_dynticks(t))
1715 flags |= TIME_ONESHOT;
1716 else
1717 flags |= TIME_PERIODIC;
1719 data->timerId = timeSetEvent(1, // interval (ms)
1720 data->period, // resolution
1721 host_alarm_handler, // function
1722 (DWORD)t, // parameter
1723 flags);
1725 if (!data->timerId) {
1726 perror("Failed to initialize win32 alarm timer");
1728 timeEndPeriod(data->period);
1729 CloseHandle(data->host_alarm);
1730 return -1;
1733 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1735 return 0;
1738 static void win32_stop_timer(struct qemu_alarm_timer *t)
1740 struct qemu_alarm_win32 *data = t->priv;
1742 timeKillEvent(data->timerId);
1743 timeEndPeriod(data->period);
1745 CloseHandle(data->host_alarm);
1748 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1750 struct qemu_alarm_win32 *data = t->priv;
1751 uint64_t nearest_delta_us;
1753 if (!active_timers[QEMU_TIMER_REALTIME] &&
1754 !active_timers[QEMU_TIMER_VIRTUAL])
1755 return;
1757 nearest_delta_us = qemu_next_deadline_dyntick();
1758 nearest_delta_us /= 1000;
1760 timeKillEvent(data->timerId);
1762 data->timerId = timeSetEvent(1,
1763 data->period,
1764 host_alarm_handler,
1765 (DWORD)t,
1766 TIME_ONESHOT | TIME_PERIODIC);
1768 if (!data->timerId) {
1769 perror("Failed to re-arm win32 alarm timer");
1771 timeEndPeriod(data->period);
1772 CloseHandle(data->host_alarm);
1773 exit(1);
1777 #endif /* _WIN32 */
1779 static int init_timer_alarm(void)
1781 struct qemu_alarm_timer *t = NULL;
1782 int i, err = -1;
1784 #ifndef _WIN32
1785 int fds[2];
1787 err = pipe(fds);
1788 if (err == -1)
1789 return -errno;
1791 err = fcntl_setfl(fds[0], O_NONBLOCK);
1792 if (err < 0)
1793 goto fail;
1795 err = fcntl_setfl(fds[1], O_NONBLOCK);
1796 if (err < 0)
1797 goto fail;
1799 alarm_timer_rfd = fds[0];
1800 alarm_timer_wfd = fds[1];
1801 #endif
1803 for (i = 0; alarm_timers[i].name; i++) {
1804 t = &alarm_timers[i];
1806 err = t->start(t);
1807 if (!err)
1808 break;
1811 if (err) {
1812 err = -ENOENT;
1813 goto fail;
1816 #ifndef _WIN32
1817 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1818 try_to_rearm_timer, NULL, t);
1819 #endif
1821 alarm_timer = t;
1823 return 0;
1825 fail:
1826 #ifndef _WIN32
1827 close(fds[0]);
1828 close(fds[1]);
1829 #endif
1830 return err;
1833 static void quit_timers(void)
1835 alarm_timer->stop(alarm_timer);
1836 alarm_timer = NULL;
1839 /***********************************************************/
1840 /* host time/date access */
1841 void qemu_get_timedate(struct tm *tm, int offset)
1843 time_t ti;
1844 struct tm *ret;
1846 time(&ti);
1847 ti += offset;
1848 if (rtc_date_offset == -1) {
1849 if (rtc_utc)
1850 ret = gmtime(&ti);
1851 else
1852 ret = localtime(&ti);
1853 } else {
1854 ti -= rtc_date_offset;
1855 ret = gmtime(&ti);
1858 memcpy(tm, ret, sizeof(struct tm));
1861 int qemu_timedate_diff(struct tm *tm)
1863 time_t seconds;
1865 if (rtc_date_offset == -1)
1866 if (rtc_utc)
1867 seconds = mktimegm(tm);
1868 else
1869 seconds = mktime(tm);
1870 else
1871 seconds = mktimegm(tm) + rtc_date_offset;
1873 return seconds - time(NULL);
1876 #ifdef _WIN32
1877 static void socket_cleanup(void)
1879 WSACleanup();
1882 static int socket_init(void)
1884 WSADATA Data;
1885 int ret, err;
1887 ret = WSAStartup(MAKEWORD(2,2), &Data);
1888 if (ret != 0) {
1889 err = WSAGetLastError();
1890 fprintf(stderr, "WSAStartup: %d\n", err);
1891 return -1;
1893 atexit(socket_cleanup);
1894 return 0;
1896 #endif
1898 const char *get_opt_name(char *buf, int buf_size, const char *p)
1900 char *q;
1902 q = buf;
1903 while (*p != '\0' && *p != '=') {
1904 if (q && (q - buf) < buf_size - 1)
1905 *q++ = *p;
1906 p++;
1908 if (q)
1909 *q = '\0';
1911 return p;
1914 const char *get_opt_value(char *buf, int buf_size, const char *p)
1916 char *q;
1918 q = buf;
1919 while (*p != '\0') {
1920 if (*p == ',') {
1921 if (*(p + 1) != ',')
1922 break;
1923 p++;
1925 if (q && (q - buf) < buf_size - 1)
1926 *q++ = *p;
1927 p++;
1929 if (q)
1930 *q = '\0';
1932 return p;
1935 int get_param_value(char *buf, int buf_size,
1936 const char *tag, const char *str)
1938 const char *p;
1939 char option[128];
1941 p = str;
1942 for(;;) {
1943 p = get_opt_name(option, sizeof(option), p);
1944 if (*p != '=')
1945 break;
1946 p++;
1947 if (!strcmp(tag, option)) {
1948 (void)get_opt_value(buf, buf_size, p);
1949 return strlen(buf);
1950 } else {
1951 p = get_opt_value(NULL, 0, p);
1953 if (*p != ',')
1954 break;
1955 p++;
1957 return 0;
1960 int check_params(char *buf, int buf_size,
1961 const char * const *params, const char *str)
1963 const char *p;
1964 int i;
1966 p = str;
1967 for(;;) {
1968 p = get_opt_name(buf, buf_size, p);
1969 if (*p != '=')
1970 return -1;
1971 p++;
1972 for(i = 0; params[i] != NULL; i++)
1973 if (!strcmp(params[i], buf))
1974 break;
1975 if (params[i] == NULL)
1976 return -1;
1977 p = get_opt_value(NULL, 0, p);
1978 if (*p != ',')
1979 break;
1980 p++;
1982 return 0;
1985 /***********************************************************/
1986 /* Bluetooth support */
1987 static int nb_hcis;
1988 static int cur_hci;
1989 static struct HCIInfo *hci_table[MAX_NICS];
1991 static struct bt_vlan_s {
1992 struct bt_scatternet_s net;
1993 int id;
1994 struct bt_vlan_s *next;
1995 } *first_bt_vlan;
1997 /* find or alloc a new bluetooth "VLAN" */
1998 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
2000 struct bt_vlan_s **pvlan, *vlan;
2001 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
2002 if (vlan->id == id)
2003 return &vlan->net;
2005 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
2006 vlan->id = id;
2007 pvlan = &first_bt_vlan;
2008 while (*pvlan != NULL)
2009 pvlan = &(*pvlan)->next;
2010 *pvlan = vlan;
2011 return &vlan->net;
2014 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2018 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2020 return -ENOTSUP;
2023 static struct HCIInfo null_hci = {
2024 .cmd_send = null_hci_send,
2025 .sco_send = null_hci_send,
2026 .acl_send = null_hci_send,
2027 .bdaddr_set = null_hci_addr_set,
2030 struct HCIInfo *qemu_next_hci(void)
2032 if (cur_hci == nb_hcis)
2033 return &null_hci;
2035 return hci_table[cur_hci++];
2038 static struct HCIInfo *hci_init(const char *str)
2040 char *endp;
2041 struct bt_scatternet_s *vlan = 0;
2043 if (!strcmp(str, "null"))
2044 /* null */
2045 return &null_hci;
2046 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2047 /* host[:hciN] */
2048 return bt_host_hci(str[4] ? str + 5 : "hci0");
2049 else if (!strncmp(str, "hci", 3)) {
2050 /* hci[,vlan=n] */
2051 if (str[3]) {
2052 if (!strncmp(str + 3, ",vlan=", 6)) {
2053 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2054 if (*endp)
2055 vlan = 0;
2057 } else
2058 vlan = qemu_find_bt_vlan(0);
2059 if (vlan)
2060 return bt_new_hci(vlan);
2063 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2065 return 0;
2068 static int bt_hci_parse(const char *str)
2070 struct HCIInfo *hci;
2071 bdaddr_t bdaddr;
2073 if (nb_hcis >= MAX_NICS) {
2074 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2075 return -1;
2078 hci = hci_init(str);
2079 if (!hci)
2080 return -1;
2082 bdaddr.b[0] = 0x52;
2083 bdaddr.b[1] = 0x54;
2084 bdaddr.b[2] = 0x00;
2085 bdaddr.b[3] = 0x12;
2086 bdaddr.b[4] = 0x34;
2087 bdaddr.b[5] = 0x56 + nb_hcis;
2088 hci->bdaddr_set(hci, bdaddr.b);
2090 hci_table[nb_hcis++] = hci;
2092 return 0;
2095 static void bt_vhci_add(int vlan_id)
2097 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2099 if (!vlan->slave)
2100 fprintf(stderr, "qemu: warning: adding a VHCI to "
2101 "an empty scatternet %i\n", vlan_id);
2103 bt_vhci_init(bt_new_hci(vlan));
2106 static struct bt_device_s *bt_device_add(const char *opt)
2108 struct bt_scatternet_s *vlan;
2109 int vlan_id = 0;
2110 char *endp = strstr(opt, ",vlan=");
2111 int len = (endp ? endp - opt : strlen(opt)) + 1;
2112 char devname[10];
2114 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2116 if (endp) {
2117 vlan_id = strtol(endp + 6, &endp, 0);
2118 if (*endp) {
2119 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2120 return 0;
2124 vlan = qemu_find_bt_vlan(vlan_id);
2126 if (!vlan->slave)
2127 fprintf(stderr, "qemu: warning: adding a slave device to "
2128 "an empty scatternet %i\n", vlan_id);
2130 if (!strcmp(devname, "keyboard"))
2131 return bt_keyboard_init(vlan);
2133 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2134 return 0;
2137 static int bt_parse(const char *opt)
2139 const char *endp, *p;
2140 int vlan;
2142 if (strstart(opt, "hci", &endp)) {
2143 if (!*endp || *endp == ',') {
2144 if (*endp)
2145 if (!strstart(endp, ",vlan=", 0))
2146 opt = endp + 1;
2148 return bt_hci_parse(opt);
2150 } else if (strstart(opt, "vhci", &endp)) {
2151 if (!*endp || *endp == ',') {
2152 if (*endp) {
2153 if (strstart(endp, ",vlan=", &p)) {
2154 vlan = strtol(p, (char **) &endp, 0);
2155 if (*endp) {
2156 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2157 return 1;
2159 } else {
2160 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2161 return 1;
2163 } else
2164 vlan = 0;
2166 bt_vhci_add(vlan);
2167 return 0;
2169 } else if (strstart(opt, "device:", &endp))
2170 return !bt_device_add(endp);
2172 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2173 return 1;
2176 /***********************************************************/
2177 /* QEMU Block devices */
2179 #define HD_ALIAS "index=%d,media=disk"
2180 #ifdef TARGET_PPC
2181 #define CDROM_ALIAS "index=1,media=cdrom"
2182 #else
2183 #define CDROM_ALIAS "index=2,media=cdrom"
2184 #endif
2185 #define FD_ALIAS "index=%d,if=floppy"
2186 #define PFLASH_ALIAS "if=pflash"
2187 #define MTD_ALIAS "if=mtd"
2188 #define SD_ALIAS "index=0,if=sd"
2190 static int drive_opt_get_free_idx(void)
2192 int index;
2194 for (index = 0; index < MAX_DRIVES; index++)
2195 if (!drives_opt[index].used) {
2196 drives_opt[index].used = 1;
2197 return index;
2200 return -1;
2203 static int drive_get_free_idx(void)
2205 int index;
2207 for (index = 0; index < MAX_DRIVES; index++)
2208 if (!drives_table[index].used) {
2209 drives_table[index].used = 1;
2210 return index;
2213 return -1;
2216 int drive_add(const char *file, const char *fmt, ...)
2218 va_list ap;
2219 int index = drive_opt_get_free_idx();
2221 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2222 fprintf(stderr, "qemu: too many drives\n");
2223 return -1;
2226 drives_opt[index].file = file;
2227 va_start(ap, fmt);
2228 vsnprintf(drives_opt[index].opt,
2229 sizeof(drives_opt[0].opt), fmt, ap);
2230 va_end(ap);
2232 nb_drives_opt++;
2233 return index;
2236 void drive_remove(int index)
2238 drives_opt[index].used = 0;
2239 nb_drives_opt--;
2242 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2244 int index;
2246 /* seek interface, bus and unit */
2248 for (index = 0; index < MAX_DRIVES; index++)
2249 if (drives_table[index].type == type &&
2250 drives_table[index].bus == bus &&
2251 drives_table[index].unit == unit &&
2252 drives_table[index].used)
2253 return index;
2255 return -1;
2258 int drive_get_max_bus(BlockInterfaceType type)
2260 int max_bus;
2261 int index;
2263 max_bus = -1;
2264 for (index = 0; index < nb_drives; index++) {
2265 if(drives_table[index].type == type &&
2266 drives_table[index].bus > max_bus)
2267 max_bus = drives_table[index].bus;
2269 return max_bus;
2272 static void bdrv_format_print(void *opaque, const char *name)
2274 fprintf(stderr, " %s", name);
2277 void drive_uninit(BlockDriverState *bdrv)
2279 int i;
2281 for (i = 0; i < MAX_DRIVES; i++)
2282 if (drives_table[i].bdrv == bdrv) {
2283 drives_table[i].bdrv = NULL;
2284 drives_table[i].used = 0;
2285 drive_remove(drives_table[i].drive_opt_idx);
2286 nb_drives--;
2287 break;
2291 int drive_init(struct drive_opt *arg, int snapshot,
2292 QEMUMachine *machine)
2294 char buf[128];
2295 char file[1024];
2296 char devname[128];
2297 const char *mediastr = "";
2298 BlockInterfaceType type;
2299 enum { MEDIA_DISK, MEDIA_CDROM } media;
2300 int bus_id, unit_id;
2301 int cyls, heads, secs, translation;
2302 BlockDriverState *bdrv;
2303 BlockDriver *drv = NULL;
2304 int max_devs;
2305 int index;
2306 int cache;
2307 int bdrv_flags;
2308 int drives_table_idx;
2309 char *str = arg->opt;
2310 static const char * const params[] = { "bus", "unit", "if", "index",
2311 "cyls", "heads", "secs", "trans",
2312 "media", "snapshot", "file",
2313 "cache", "format", "boot", NULL };
2315 if (check_params(buf, sizeof(buf), params, str) < 0) {
2316 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2317 buf, str);
2318 return -1;
2321 file[0] = 0;
2322 cyls = heads = secs = 0;
2323 bus_id = 0;
2324 unit_id = -1;
2325 translation = BIOS_ATA_TRANSLATION_AUTO;
2326 index = -1;
2327 cache = 1;
2329 if (machine->use_scsi) {
2330 type = IF_SCSI;
2331 max_devs = MAX_SCSI_DEVS;
2332 pstrcpy(devname, sizeof(devname), "scsi");
2333 } else {
2334 type = IF_IDE;
2335 max_devs = MAX_IDE_DEVS;
2336 pstrcpy(devname, sizeof(devname), "ide");
2338 media = MEDIA_DISK;
2340 /* extract parameters */
2342 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2343 bus_id = strtol(buf, NULL, 0);
2344 if (bus_id < 0) {
2345 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2346 return -1;
2350 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2351 unit_id = strtol(buf, NULL, 0);
2352 if (unit_id < 0) {
2353 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2354 return -1;
2358 if (get_param_value(buf, sizeof(buf), "if", str)) {
2359 pstrcpy(devname, sizeof(devname), buf);
2360 if (!strcmp(buf, "ide")) {
2361 type = IF_IDE;
2362 max_devs = MAX_IDE_DEVS;
2363 } else if (!strcmp(buf, "scsi")) {
2364 type = IF_SCSI;
2365 max_devs = MAX_SCSI_DEVS;
2366 } else if (!strcmp(buf, "floppy")) {
2367 type = IF_FLOPPY;
2368 max_devs = 0;
2369 } else if (!strcmp(buf, "pflash")) {
2370 type = IF_PFLASH;
2371 max_devs = 0;
2372 } else if (!strcmp(buf, "mtd")) {
2373 type = IF_MTD;
2374 max_devs = 0;
2375 } else if (!strcmp(buf, "sd")) {
2376 type = IF_SD;
2377 max_devs = 0;
2378 } else if (!strcmp(buf, "virtio")) {
2379 type = IF_VIRTIO;
2380 max_devs = 0;
2381 } else {
2382 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2383 return -1;
2387 if (get_param_value(buf, sizeof(buf), "index", str)) {
2388 index = strtol(buf, NULL, 0);
2389 if (index < 0) {
2390 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2391 return -1;
2395 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2396 cyls = strtol(buf, NULL, 0);
2399 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2400 heads = strtol(buf, NULL, 0);
2403 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2404 secs = strtol(buf, NULL, 0);
2407 if (cyls || heads || secs) {
2408 if (cyls < 1 || cyls > 16383) {
2409 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2410 return -1;
2412 if (heads < 1 || heads > 16) {
2413 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2414 return -1;
2416 if (secs < 1 || secs > 63) {
2417 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2418 return -1;
2422 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2423 if (!cyls) {
2424 fprintf(stderr,
2425 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2426 str);
2427 return -1;
2429 if (!strcmp(buf, "none"))
2430 translation = BIOS_ATA_TRANSLATION_NONE;
2431 else if (!strcmp(buf, "lba"))
2432 translation = BIOS_ATA_TRANSLATION_LBA;
2433 else if (!strcmp(buf, "auto"))
2434 translation = BIOS_ATA_TRANSLATION_AUTO;
2435 else {
2436 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2437 return -1;
2441 if (get_param_value(buf, sizeof(buf), "media", str)) {
2442 if (!strcmp(buf, "disk")) {
2443 media = MEDIA_DISK;
2444 } else if (!strcmp(buf, "cdrom")) {
2445 if (cyls || secs || heads) {
2446 fprintf(stderr,
2447 "qemu: '%s' invalid physical CHS format\n", str);
2448 return -1;
2450 media = MEDIA_CDROM;
2451 } else {
2452 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2453 return -1;
2457 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2458 if (!strcmp(buf, "on"))
2459 snapshot = 1;
2460 else if (!strcmp(buf, "off"))
2461 snapshot = 0;
2462 else {
2463 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2464 return -1;
2468 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2469 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2470 cache = 0;
2471 else if (!strcmp(buf, "writethrough"))
2472 cache = 1;
2473 else if (!strcmp(buf, "writeback"))
2474 cache = 2;
2475 else {
2476 fprintf(stderr, "qemu: invalid cache option\n");
2477 return -1;
2481 if (get_param_value(buf, sizeof(buf), "format", str)) {
2482 if (strcmp(buf, "?") == 0) {
2483 fprintf(stderr, "qemu: Supported formats:");
2484 bdrv_iterate_format(bdrv_format_print, NULL);
2485 fprintf(stderr, "\n");
2486 return -1;
2488 drv = bdrv_find_format(buf);
2489 if (!drv) {
2490 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2491 return -1;
2495 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2496 if (!strcmp(buf, "on")) {
2497 if (extboot_drive != -1) {
2498 fprintf(stderr, "qemu: two bootable drives specified\n");
2499 return -1;
2501 extboot_drive = nb_drives;
2502 } else if (strcmp(buf, "off")) {
2503 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2504 return -1;
2508 if (arg->file == NULL)
2509 get_param_value(file, sizeof(file), "file", str);
2510 else
2511 pstrcpy(file, sizeof(file), arg->file);
2513 /* compute bus and unit according index */
2515 if (index != -1) {
2516 if (bus_id != 0 || unit_id != -1) {
2517 fprintf(stderr,
2518 "qemu: '%s' index cannot be used with bus and unit\n", str);
2519 return -1;
2521 if (max_devs == 0)
2523 unit_id = index;
2524 bus_id = 0;
2525 } else {
2526 unit_id = index % max_devs;
2527 bus_id = index / max_devs;
2531 /* if user doesn't specify a unit_id,
2532 * try to find the first free
2535 if (unit_id == -1) {
2536 unit_id = 0;
2537 while (drive_get_index(type, bus_id, unit_id) != -1) {
2538 unit_id++;
2539 if (max_devs && unit_id >= max_devs) {
2540 unit_id -= max_devs;
2541 bus_id++;
2546 /* check unit id */
2548 if (max_devs && unit_id >= max_devs) {
2549 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2550 str, unit_id, max_devs - 1);
2551 return -1;
2555 * ignore multiple definitions
2558 if (drive_get_index(type, bus_id, unit_id) != -1)
2559 return -2;
2561 /* init */
2563 if (type == IF_IDE || type == IF_SCSI)
2564 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2565 if (max_devs)
2566 snprintf(buf, sizeof(buf), "%s%i%s%i",
2567 devname, bus_id, mediastr, unit_id);
2568 else
2569 snprintf(buf, sizeof(buf), "%s%s%i",
2570 devname, mediastr, unit_id);
2571 bdrv = bdrv_new(buf);
2572 drives_table_idx = drive_get_free_idx();
2573 drives_table[drives_table_idx].bdrv = bdrv;
2574 drives_table[drives_table_idx].type = type;
2575 drives_table[drives_table_idx].bus = bus_id;
2576 drives_table[drives_table_idx].unit = unit_id;
2577 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2578 nb_drives++;
2580 switch(type) {
2581 case IF_IDE:
2582 case IF_SCSI:
2583 switch(media) {
2584 case MEDIA_DISK:
2585 if (cyls != 0) {
2586 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2587 bdrv_set_translation_hint(bdrv, translation);
2589 break;
2590 case MEDIA_CDROM:
2591 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2592 break;
2594 break;
2595 case IF_SD:
2596 /* FIXME: This isn't really a floppy, but it's a reasonable
2597 approximation. */
2598 case IF_FLOPPY:
2599 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2600 break;
2601 case IF_PFLASH:
2602 case IF_MTD:
2603 case IF_VIRTIO:
2604 break;
2606 if (!file[0])
2607 return -2;
2608 bdrv_flags = 0;
2609 if (snapshot) {
2610 bdrv_flags |= BDRV_O_SNAPSHOT;
2611 cache = 2; /* always use write-back with snapshot */
2613 if (cache == 0) /* no caching */
2614 bdrv_flags |= BDRV_O_NOCACHE;
2615 else if (cache == 2) /* write-back */
2616 bdrv_flags |= BDRV_O_CACHE_WB;
2617 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2618 fprintf(stderr, "qemu: could not open disk image %s\n",
2619 file);
2620 return -1;
2622 return drives_table_idx;
2625 /***********************************************************/
2626 /* USB devices */
2628 static USBPort *used_usb_ports;
2629 static USBPort *free_usb_ports;
2631 /* ??? Maybe change this to register a hub to keep track of the topology. */
2632 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2633 usb_attachfn attach)
2635 port->opaque = opaque;
2636 port->index = index;
2637 port->attach = attach;
2638 port->next = free_usb_ports;
2639 free_usb_ports = port;
2642 int usb_device_add_dev(USBDevice *dev)
2644 USBPort *port;
2646 /* Find a USB port to add the device to. */
2647 port = free_usb_ports;
2648 if (!port->next) {
2649 USBDevice *hub;
2651 /* Create a new hub and chain it on. */
2652 free_usb_ports = NULL;
2653 port->next = used_usb_ports;
2654 used_usb_ports = port;
2656 hub = usb_hub_init(VM_USB_HUB_SIZE);
2657 usb_attach(port, hub);
2658 port = free_usb_ports;
2661 free_usb_ports = port->next;
2662 port->next = used_usb_ports;
2663 used_usb_ports = port;
2664 usb_attach(port, dev);
2665 return 0;
2668 static int usb_device_add(const char *devname)
2670 const char *p;
2671 USBDevice *dev;
2673 if (!free_usb_ports)
2674 return -1;
2676 if (strstart(devname, "host:", &p)) {
2677 dev = usb_host_device_open(p);
2678 } else if (!strcmp(devname, "mouse")) {
2679 dev = usb_mouse_init();
2680 } else if (!strcmp(devname, "tablet")) {
2681 dev = usb_tablet_init();
2682 } else if (!strcmp(devname, "keyboard")) {
2683 dev = usb_keyboard_init();
2684 } else if (strstart(devname, "disk:", &p)) {
2685 dev = usb_msd_init(p);
2686 } else if (!strcmp(devname, "wacom-tablet")) {
2687 dev = usb_wacom_init();
2688 } else if (strstart(devname, "serial:", &p)) {
2689 dev = usb_serial_init(p);
2690 #ifdef CONFIG_BRLAPI
2691 } else if (!strcmp(devname, "braille")) {
2692 dev = usb_baum_init();
2693 #endif
2694 } else if (strstart(devname, "net:", &p)) {
2695 int nic = nb_nics;
2697 if (net_client_init("nic", p) < 0)
2698 return -1;
2699 nd_table[nic].model = "usb";
2700 dev = usb_net_init(&nd_table[nic]);
2701 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2702 dev = usb_bt_init(devname[2] ? hci_init(p) :
2703 bt_new_hci(qemu_find_bt_vlan(0)));
2704 } else {
2705 return -1;
2707 if (!dev)
2708 return -1;
2710 return usb_device_add_dev(dev);
2713 int usb_device_del_addr(int bus_num, int addr)
2715 USBPort *port;
2716 USBPort **lastp;
2717 USBDevice *dev;
2719 if (!used_usb_ports)
2720 return -1;
2722 if (bus_num != 0)
2723 return -1;
2725 lastp = &used_usb_ports;
2726 port = used_usb_ports;
2727 while (port && port->dev->addr != addr) {
2728 lastp = &port->next;
2729 port = port->next;
2732 if (!port)
2733 return -1;
2735 dev = port->dev;
2736 *lastp = port->next;
2737 usb_attach(port, NULL);
2738 dev->handle_destroy(dev);
2739 port->next = free_usb_ports;
2740 free_usb_ports = port;
2741 return 0;
2744 static int usb_device_del(const char *devname)
2746 int bus_num, addr;
2747 const char *p;
2749 if (strstart(devname, "host:", &p))
2750 return usb_host_device_close(p);
2752 if (!used_usb_ports)
2753 return -1;
2755 p = strchr(devname, '.');
2756 if (!p)
2757 return -1;
2758 bus_num = strtoul(devname, NULL, 0);
2759 addr = strtoul(p + 1, NULL, 0);
2761 return usb_device_del_addr(bus_num, addr);
2764 void do_usb_add(const char *devname)
2766 usb_device_add(devname);
2769 void do_usb_del(const char *devname)
2771 usb_device_del(devname);
2774 void usb_info(void)
2776 USBDevice *dev;
2777 USBPort *port;
2778 const char *speed_str;
2780 if (!usb_enabled) {
2781 term_printf("USB support not enabled\n");
2782 return;
2785 for (port = used_usb_ports; port; port = port->next) {
2786 dev = port->dev;
2787 if (!dev)
2788 continue;
2789 switch(dev->speed) {
2790 case USB_SPEED_LOW:
2791 speed_str = "1.5";
2792 break;
2793 case USB_SPEED_FULL:
2794 speed_str = "12";
2795 break;
2796 case USB_SPEED_HIGH:
2797 speed_str = "480";
2798 break;
2799 default:
2800 speed_str = "?";
2801 break;
2803 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2804 0, dev->addr, speed_str, dev->devname);
2808 /***********************************************************/
2809 /* PCMCIA/Cardbus */
2811 static struct pcmcia_socket_entry_s {
2812 struct pcmcia_socket_s *socket;
2813 struct pcmcia_socket_entry_s *next;
2814 } *pcmcia_sockets = 0;
2816 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2818 struct pcmcia_socket_entry_s *entry;
2820 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2821 entry->socket = socket;
2822 entry->next = pcmcia_sockets;
2823 pcmcia_sockets = entry;
2826 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2828 struct pcmcia_socket_entry_s *entry, **ptr;
2830 ptr = &pcmcia_sockets;
2831 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2832 if (entry->socket == socket) {
2833 *ptr = entry->next;
2834 qemu_free(entry);
2838 void pcmcia_info(void)
2840 struct pcmcia_socket_entry_s *iter;
2841 if (!pcmcia_sockets)
2842 term_printf("No PCMCIA sockets\n");
2844 for (iter = pcmcia_sockets; iter; iter = iter->next)
2845 term_printf("%s: %s\n", iter->socket->slot_string,
2846 iter->socket->attached ? iter->socket->card_string :
2847 "Empty");
2850 /***********************************************************/
2851 /* dumb display */
2853 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2857 static void dumb_resize(DisplayState *ds, int w, int h)
2861 static void dumb_display_init(DisplayState *ds)
2863 ds->data = NULL;
2864 ds->linesize = 0;
2865 ds->depth = 0;
2866 ds->dpy_update = dumb_update;
2867 ds->dpy_resize = dumb_resize;
2868 ds->dpy_refresh = NULL;
2869 ds->gui_timer_interval = 0;
2870 ds->idle = 1;
2873 /***********************************************************/
2874 /* I/O handling */
2876 #define MAX_IO_HANDLERS 64
2878 typedef struct IOHandlerRecord {
2879 int fd;
2880 IOCanRWHandler *fd_read_poll;
2881 IOHandler *fd_read;
2882 IOHandler *fd_write;
2883 int deleted;
2884 void *opaque;
2885 /* temporary data */
2886 struct pollfd *ufd;
2887 struct IOHandlerRecord *next;
2888 } IOHandlerRecord;
2890 static IOHandlerRecord *first_io_handler;
2892 /* XXX: fd_read_poll should be suppressed, but an API change is
2893 necessary in the character devices to suppress fd_can_read(). */
2894 int qemu_set_fd_handler2(int fd,
2895 IOCanRWHandler *fd_read_poll,
2896 IOHandler *fd_read,
2897 IOHandler *fd_write,
2898 void *opaque)
2900 IOHandlerRecord **pioh, *ioh;
2902 if (!fd_read && !fd_write) {
2903 pioh = &first_io_handler;
2904 for(;;) {
2905 ioh = *pioh;
2906 if (ioh == NULL)
2907 break;
2908 if (ioh->fd == fd) {
2909 ioh->deleted = 1;
2910 break;
2912 pioh = &ioh->next;
2914 } else {
2915 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2916 if (ioh->fd == fd)
2917 goto found;
2919 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2920 if (!ioh)
2921 return -1;
2922 ioh->next = first_io_handler;
2923 first_io_handler = ioh;
2924 found:
2925 ioh->fd = fd;
2926 ioh->fd_read_poll = fd_read_poll;
2927 ioh->fd_read = fd_read;
2928 ioh->fd_write = fd_write;
2929 ioh->opaque = opaque;
2930 ioh->deleted = 0;
2932 main_loop_break();
2933 return 0;
2936 int qemu_set_fd_handler(int fd,
2937 IOHandler *fd_read,
2938 IOHandler *fd_write,
2939 void *opaque)
2941 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2944 #ifdef _WIN32
2945 /***********************************************************/
2946 /* Polling handling */
2948 typedef struct PollingEntry {
2949 PollingFunc *func;
2950 void *opaque;
2951 struct PollingEntry *next;
2952 } PollingEntry;
2954 static PollingEntry *first_polling_entry;
2956 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2958 PollingEntry **ppe, *pe;
2959 pe = qemu_mallocz(sizeof(PollingEntry));
2960 if (!pe)
2961 return -1;
2962 pe->func = func;
2963 pe->opaque = opaque;
2964 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2965 *ppe = pe;
2966 return 0;
2969 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2971 PollingEntry **ppe, *pe;
2972 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2973 pe = *ppe;
2974 if (pe->func == func && pe->opaque == opaque) {
2975 *ppe = pe->next;
2976 qemu_free(pe);
2977 break;
2982 /***********************************************************/
2983 /* Wait objects support */
2984 typedef struct WaitObjects {
2985 int num;
2986 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2987 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2988 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2989 } WaitObjects;
2991 static WaitObjects wait_objects = {0};
2993 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2995 WaitObjects *w = &wait_objects;
2997 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2998 return -1;
2999 w->events[w->num] = handle;
3000 w->func[w->num] = func;
3001 w->opaque[w->num] = opaque;
3002 w->num++;
3003 return 0;
3006 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3008 int i, found;
3009 WaitObjects *w = &wait_objects;
3011 found = 0;
3012 for (i = 0; i < w->num; i++) {
3013 if (w->events[i] == handle)
3014 found = 1;
3015 if (found) {
3016 w->events[i] = w->events[i + 1];
3017 w->func[i] = w->func[i + 1];
3018 w->opaque[i] = w->opaque[i + 1];
3021 if (found)
3022 w->num--;
3024 #endif
3026 /***********************************************************/
3027 /* ram save/restore */
3029 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3031 int v;
3033 v = qemu_get_byte(f);
3034 switch(v) {
3035 case 0:
3036 if (qemu_get_buffer(f, buf, len) != len)
3037 return -EIO;
3038 break;
3039 case 1:
3040 v = qemu_get_byte(f);
3041 memset(buf, v, len);
3042 break;
3043 default:
3044 return -EINVAL;
3047 if (qemu_file_has_error(f))
3048 return -EIO;
3050 return 0;
3053 static int ram_load_v1(QEMUFile *f, void *opaque)
3055 int ret;
3056 ram_addr_t i;
3058 if (qemu_get_be32(f) != phys_ram_size)
3059 return -EINVAL;
3060 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3061 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3062 continue;
3063 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3064 if (ret)
3065 return ret;
3067 return 0;
3070 #define BDRV_HASH_BLOCK_SIZE 1024
3071 #define IOBUF_SIZE 4096
3072 #define RAM_CBLOCK_MAGIC 0xfabe
3074 typedef struct RamDecompressState {
3075 z_stream zstream;
3076 QEMUFile *f;
3077 uint8_t buf[IOBUF_SIZE];
3078 } RamDecompressState;
3080 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3082 int ret;
3083 memset(s, 0, sizeof(*s));
3084 s->f = f;
3085 ret = inflateInit(&s->zstream);
3086 if (ret != Z_OK)
3087 return -1;
3088 return 0;
3091 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3093 int ret, clen;
3095 s->zstream.avail_out = len;
3096 s->zstream.next_out = buf;
3097 while (s->zstream.avail_out > 0) {
3098 if (s->zstream.avail_in == 0) {
3099 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3100 return -1;
3101 clen = qemu_get_be16(s->f);
3102 if (clen > IOBUF_SIZE)
3103 return -1;
3104 qemu_get_buffer(s->f, s->buf, clen);
3105 s->zstream.avail_in = clen;
3106 s->zstream.next_in = s->buf;
3108 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3109 if (ret != Z_OK && ret != Z_STREAM_END) {
3110 return -1;
3113 return 0;
3116 static void ram_decompress_close(RamDecompressState *s)
3118 inflateEnd(&s->zstream);
3121 #define RAM_SAVE_FLAG_FULL 0x01
3122 #define RAM_SAVE_FLAG_COMPRESS 0x02
3123 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3124 #define RAM_SAVE_FLAG_PAGE 0x08
3125 #define RAM_SAVE_FLAG_EOS 0x10
3127 static int is_dup_page(uint8_t *page, uint8_t ch)
3129 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3130 uint32_t *array = (uint32_t *)page;
3131 int i;
3133 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3134 if (array[i] != val)
3135 return 0;
3138 return 1;
3141 static int ram_save_block(QEMUFile *f)
3143 static ram_addr_t current_addr = 0;
3144 ram_addr_t saved_addr = current_addr;
3145 ram_addr_t addr = 0;
3146 int found = 0;
3148 while (addr < phys_ram_size) {
3149 if (kvm_enabled() && current_addr == 0)
3150 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3151 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3152 uint8_t ch;
3154 cpu_physical_memory_reset_dirty(current_addr,
3155 current_addr + TARGET_PAGE_SIZE,
3156 MIGRATION_DIRTY_FLAG);
3158 ch = *(phys_ram_base + current_addr);
3160 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3161 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3162 qemu_put_byte(f, ch);
3163 } else {
3164 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3165 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3168 found = 1;
3169 break;
3171 addr += TARGET_PAGE_SIZE;
3172 current_addr = (saved_addr + addr) % phys_ram_size;
3175 return found;
3178 static ram_addr_t ram_save_threshold = 10;
3180 static ram_addr_t ram_save_remaining(void)
3182 ram_addr_t addr;
3183 ram_addr_t count = 0;
3185 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3186 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3187 count++;
3190 return count;
3193 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3195 ram_addr_t addr;
3197 if (stage == 1) {
3198 /* Make sure all dirty bits are set */
3199 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3200 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3201 cpu_physical_memory_set_dirty(addr);
3204 /* Enable dirty memory tracking */
3205 cpu_physical_memory_set_dirty_tracking(1);
3207 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3210 while (!qemu_file_rate_limit(f)) {
3211 int ret;
3213 ret = ram_save_block(f);
3214 if (ret == 0) /* no more blocks */
3215 break;
3218 /* try transferring iterative blocks of memory */
3220 if (stage == 3) {
3221 cpu_physical_memory_set_dirty_tracking(0);
3223 /* flush all remaining blocks regardless of rate limiting */
3224 while (ram_save_block(f) != 0);
3227 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3229 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3232 static int ram_load_dead(QEMUFile *f, void *opaque)
3234 RamDecompressState s1, *s = &s1;
3235 uint8_t buf[10];
3236 ram_addr_t i;
3238 if (ram_decompress_open(s, f) < 0)
3239 return -EINVAL;
3240 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3241 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3242 continue;
3243 if (ram_decompress_buf(s, buf, 1) < 0) {
3244 fprintf(stderr, "Error while reading ram block header\n");
3245 goto error;
3247 if (buf[0] == 0) {
3248 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3249 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3250 goto error;
3252 } else {
3253 error:
3254 printf("Error block header\n");
3255 return -EINVAL;
3258 ram_decompress_close(s);
3260 return 0;
3263 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3265 ram_addr_t addr;
3266 int flags;
3268 if (version_id == 1)
3269 return ram_load_v1(f, opaque);
3271 if (version_id == 2) {
3272 if (qemu_get_be32(f) != phys_ram_size)
3273 return -EINVAL;
3274 return ram_load_dead(f, opaque);
3277 if (version_id != 3)
3278 return -EINVAL;
3280 do {
3281 addr = qemu_get_be64(f);
3283 flags = addr & ~TARGET_PAGE_MASK;
3284 addr &= TARGET_PAGE_MASK;
3286 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3287 if (addr != phys_ram_size)
3288 return -EINVAL;
3291 if (flags & RAM_SAVE_FLAG_FULL) {
3292 if (ram_load_dead(f, opaque) < 0)
3293 return -EINVAL;
3296 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3297 uint8_t ch = qemu_get_byte(f);
3298 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3299 } else if (flags & RAM_SAVE_FLAG_PAGE)
3300 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3301 } while (!(flags & RAM_SAVE_FLAG_EOS));
3303 return 0;
3306 /***********************************************************/
3307 /* bottom halves (can be seen as timers which expire ASAP) */
3309 struct QEMUBH {
3310 QEMUBHFunc *cb;
3311 void *opaque;
3312 int scheduled;
3313 int idle;
3314 int deleted;
3315 QEMUBH *next;
3318 static QEMUBH *first_bh = NULL;
3320 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3322 QEMUBH *bh;
3323 bh = qemu_mallocz(sizeof(QEMUBH));
3324 if (!bh)
3325 return NULL;
3326 bh->cb = cb;
3327 bh->opaque = opaque;
3328 bh->next = first_bh;
3329 first_bh = bh;
3330 return bh;
3333 int qemu_bh_poll(void)
3335 QEMUBH *bh, **bhp;
3336 int ret;
3338 ret = 0;
3339 for (bh = first_bh; bh; bh = bh->next) {
3340 if (!bh->deleted && bh->scheduled) {
3341 bh->scheduled = 0;
3342 if (!bh->idle)
3343 ret = 1;
3344 bh->idle = 0;
3345 bh->cb(bh->opaque);
3349 /* remove deleted bhs */
3350 bhp = &first_bh;
3351 while (*bhp) {
3352 bh = *bhp;
3353 if (bh->deleted) {
3354 *bhp = bh->next;
3355 qemu_free(bh);
3356 } else
3357 bhp = &bh->next;
3360 return ret;
3363 void qemu_bh_schedule_idle(QEMUBH *bh)
3365 if (bh->scheduled)
3366 return;
3367 bh->scheduled = 1;
3368 bh->idle = 1;
3371 void qemu_bh_schedule(QEMUBH *bh)
3373 CPUState *env = cpu_single_env;
3374 if (bh->scheduled)
3375 return;
3376 bh->scheduled = 1;
3377 bh->idle = 0;
3378 /* stop the currently executing CPU to execute the BH ASAP */
3379 if (env) {
3380 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3382 main_loop_break();
3385 void qemu_bh_cancel(QEMUBH *bh)
3387 bh->scheduled = 0;
3390 void qemu_bh_delete(QEMUBH *bh)
3392 bh->scheduled = 0;
3393 bh->deleted = 1;
3396 static void qemu_bh_update_timeout(int *timeout)
3398 QEMUBH *bh;
3400 for (bh = first_bh; bh; bh = bh->next) {
3401 if (!bh->deleted && bh->scheduled) {
3402 if (bh->idle) {
3403 /* idle bottom halves will be polled at least
3404 * every 10ms */
3405 *timeout = MIN(10, *timeout);
3406 } else {
3407 /* non-idle bottom halves will be executed
3408 * immediately */
3409 *timeout = 0;
3410 break;
3416 /***********************************************************/
3417 /* machine registration */
3419 static QEMUMachine *first_machine = NULL;
3420 QEMUMachine *current_machine = NULL;
3422 int qemu_register_machine(QEMUMachine *m)
3424 QEMUMachine **pm;
3425 pm = &first_machine;
3426 while (*pm != NULL)
3427 pm = &(*pm)->next;
3428 m->next = NULL;
3429 *pm = m;
3430 return 0;
3433 static QEMUMachine *find_machine(const char *name)
3435 QEMUMachine *m;
3437 for(m = first_machine; m != NULL; m = m->next) {
3438 if (!strcmp(m->name, name))
3439 return m;
3441 return NULL;
3444 /***********************************************************/
3445 /* main execution loop */
3447 static void gui_update(void *opaque)
3449 DisplayState *ds = opaque;
3450 ds->dpy_refresh(ds);
3451 qemu_mod_timer(ds->gui_timer,
3452 (ds->gui_timer_interval ?
3453 ds->gui_timer_interval :
3454 GUI_REFRESH_INTERVAL)
3455 + qemu_get_clock(rt_clock));
3458 struct vm_change_state_entry {
3459 VMChangeStateHandler *cb;
3460 void *opaque;
3461 LIST_ENTRY (vm_change_state_entry) entries;
3464 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3466 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3467 void *opaque)
3469 VMChangeStateEntry *e;
3471 e = qemu_mallocz(sizeof (*e));
3472 if (!e)
3473 return NULL;
3475 e->cb = cb;
3476 e->opaque = opaque;
3477 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3478 return e;
3481 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3483 LIST_REMOVE (e, entries);
3484 qemu_free (e);
3487 static void vm_state_notify(int running)
3489 VMChangeStateEntry *e;
3491 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3492 e->cb(e->opaque, running);
3496 /* XXX: support several handlers */
3497 static VMStopHandler *vm_stop_cb;
3498 static void *vm_stop_opaque;
3500 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3502 vm_stop_cb = cb;
3503 vm_stop_opaque = opaque;
3504 return 0;
3507 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3509 vm_stop_cb = NULL;
3512 void vm_start(void)
3514 if (!vm_running) {
3515 cpu_enable_ticks();
3516 vm_running = 1;
3517 vm_state_notify(1);
3518 qemu_rearm_alarm_timer(alarm_timer);
3522 void vm_stop(int reason)
3524 if (vm_running) {
3525 cpu_disable_ticks();
3526 vm_running = 0;
3527 if (reason != 0) {
3528 if (vm_stop_cb) {
3529 vm_stop_cb(vm_stop_opaque, reason);
3532 vm_state_notify(0);
3536 /* reset/shutdown handler */
3538 typedef struct QEMUResetEntry {
3539 QEMUResetHandler *func;
3540 void *opaque;
3541 struct QEMUResetEntry *next;
3542 } QEMUResetEntry;
3544 static QEMUResetEntry *first_reset_entry;
3545 static int reset_requested;
3546 static int shutdown_requested;
3547 static int powerdown_requested;
3549 int qemu_shutdown_requested(void)
3551 int r = shutdown_requested;
3552 shutdown_requested = 0;
3553 return r;
3556 int qemu_reset_requested(void)
3558 int r = reset_requested;
3559 reset_requested = 0;
3560 return r;
3563 int qemu_powerdown_requested(void)
3565 int r = powerdown_requested;
3566 powerdown_requested = 0;
3567 return r;
3570 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3572 QEMUResetEntry **pre, *re;
3574 pre = &first_reset_entry;
3575 while (*pre != NULL)
3576 pre = &(*pre)->next;
3577 re = qemu_mallocz(sizeof(QEMUResetEntry));
3578 re->func = func;
3579 re->opaque = opaque;
3580 re->next = NULL;
3581 *pre = re;
3584 void qemu_system_reset(void)
3586 QEMUResetEntry *re;
3588 /* reset all devices */
3589 for(re = first_reset_entry; re != NULL; re = re->next) {
3590 re->func(re->opaque);
3594 void qemu_system_reset_request(void)
3596 if (no_reboot) {
3597 shutdown_requested = 1;
3598 } else {
3599 reset_requested = 1;
3601 if (cpu_single_env)
3602 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3603 main_loop_break();
3606 void qemu_system_shutdown_request(void)
3608 shutdown_requested = 1;
3609 if (cpu_single_env)
3610 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3613 void qemu_system_powerdown_request(void)
3615 powerdown_requested = 1;
3616 if (cpu_single_env)
3617 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3620 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3621 struct timeval *tv)
3623 int ret;
3625 /* KVM holds a mutex while QEMU code is running, we need hooks to
3626 release the mutex whenever QEMU code sleeps. */
3628 kvm_sleep_begin();
3630 ret = select(max_fd, rfds, wfds, xfds, tv);
3632 kvm_sleep_end();
3634 return ret;
3637 #ifdef _WIN32
3638 void host_main_loop_wait(int *timeout)
3640 int ret, ret2, i;
3641 PollingEntry *pe;
3644 /* XXX: need to suppress polling by better using win32 events */
3645 ret = 0;
3646 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3647 ret |= pe->func(pe->opaque);
3649 if (ret == 0) {
3650 int err;
3651 WaitObjects *w = &wait_objects;
3653 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3654 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3655 if (w->func[ret - WAIT_OBJECT_0])
3656 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3658 /* Check for additional signaled events */
3659 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3661 /* Check if event is signaled */
3662 ret2 = WaitForSingleObject(w->events[i], 0);
3663 if(ret2 == WAIT_OBJECT_0) {
3664 if (w->func[i])
3665 w->func[i](w->opaque[i]);
3666 } else if (ret2 == WAIT_TIMEOUT) {
3667 } else {
3668 err = GetLastError();
3669 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3672 } else if (ret == WAIT_TIMEOUT) {
3673 } else {
3674 err = GetLastError();
3675 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3679 *timeout = 0;
3681 #else
3682 void host_main_loop_wait(int *timeout)
3685 #endif
3687 void main_loop_wait(int timeout)
3689 IOHandlerRecord *ioh;
3690 fd_set rfds, wfds, xfds;
3691 int ret, nfds;
3692 struct timeval tv;
3694 qemu_bh_update_timeout(&timeout);
3696 host_main_loop_wait(&timeout);
3698 /* poll any events */
3699 /* XXX: separate device handlers from system ones */
3700 nfds = -1;
3701 FD_ZERO(&rfds);
3702 FD_ZERO(&wfds);
3703 FD_ZERO(&xfds);
3704 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3705 if (ioh->deleted)
3706 continue;
3707 if (ioh->fd_read &&
3708 (!ioh->fd_read_poll ||
3709 ioh->fd_read_poll(ioh->opaque) != 0)) {
3710 FD_SET(ioh->fd, &rfds);
3711 if (ioh->fd > nfds)
3712 nfds = ioh->fd;
3714 if (ioh->fd_write) {
3715 FD_SET(ioh->fd, &wfds);
3716 if (ioh->fd > nfds)
3717 nfds = ioh->fd;
3721 tv.tv_sec = timeout / 1000;
3722 tv.tv_usec = (timeout % 1000) * 1000;
3724 #if defined(CONFIG_SLIRP)
3725 if (slirp_is_inited()) {
3726 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3728 #endif
3729 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3730 if (ret > 0) {
3731 IOHandlerRecord **pioh;
3733 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3734 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3735 ioh->fd_read(ioh->opaque);
3736 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3737 FD_CLR(ioh->fd, &rfds);
3739 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3740 ioh->fd_write(ioh->opaque);
3744 /* remove deleted IO handlers */
3745 pioh = &first_io_handler;
3746 while (*pioh) {
3747 ioh = *pioh;
3748 if (ioh->deleted) {
3749 *pioh = ioh->next;
3750 qemu_free(ioh);
3751 } else
3752 pioh = &ioh->next;
3755 #if defined(CONFIG_SLIRP)
3756 if (slirp_is_inited()) {
3757 if (ret < 0) {
3758 FD_ZERO(&rfds);
3759 FD_ZERO(&wfds);
3760 FD_ZERO(&xfds);
3762 slirp_select_poll(&rfds, &wfds, &xfds);
3764 #endif
3766 /* Check bottom-halves last in case any of the earlier events triggered
3767 them. */
3768 qemu_bh_poll();
3772 static int main_loop(void)
3774 int ret, timeout;
3775 #ifdef CONFIG_PROFILER
3776 int64_t ti;
3777 #endif
3778 CPUState *env;
3781 if (kvm_enabled()) {
3782 kvm_main_loop();
3783 cpu_disable_ticks();
3784 return 0;
3787 cur_cpu = first_cpu;
3788 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3789 for(;;) {
3790 if (vm_running) {
3792 for(;;) {
3793 /* get next cpu */
3794 env = next_cpu;
3795 #ifdef CONFIG_PROFILER
3796 ti = profile_getclock();
3797 #endif
3798 if (use_icount) {
3799 int64_t count;
3800 int decr;
3801 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3802 env->icount_decr.u16.low = 0;
3803 env->icount_extra = 0;
3804 count = qemu_next_deadline();
3805 count = (count + (1 << icount_time_shift) - 1)
3806 >> icount_time_shift;
3807 qemu_icount += count;
3808 decr = (count > 0xffff) ? 0xffff : count;
3809 count -= decr;
3810 env->icount_decr.u16.low = decr;
3811 env->icount_extra = count;
3813 ret = cpu_exec(env);
3814 #ifdef CONFIG_PROFILER
3815 qemu_time += profile_getclock() - ti;
3816 #endif
3817 if (use_icount) {
3818 /* Fold pending instructions back into the
3819 instruction counter, and clear the interrupt flag. */
3820 qemu_icount -= (env->icount_decr.u16.low
3821 + env->icount_extra);
3822 env->icount_decr.u32 = 0;
3823 env->icount_extra = 0;
3825 next_cpu = env->next_cpu ?: first_cpu;
3826 if (event_pending && likely(ret != EXCP_DEBUG)) {
3827 ret = EXCP_INTERRUPT;
3828 event_pending = 0;
3829 break;
3831 if (ret == EXCP_HLT) {
3832 /* Give the next CPU a chance to run. */
3833 cur_cpu = env;
3834 continue;
3836 if (ret != EXCP_HALTED)
3837 break;
3838 /* all CPUs are halted ? */
3839 if (env == cur_cpu)
3840 break;
3842 cur_cpu = env;
3844 if (shutdown_requested) {
3845 ret = EXCP_INTERRUPT;
3846 if (no_shutdown) {
3847 vm_stop(0);
3848 no_shutdown = 0;
3850 else
3851 break;
3853 if (reset_requested) {
3854 reset_requested = 0;
3855 qemu_system_reset();
3856 if (kvm_enabled())
3857 kvm_load_registers(env);
3858 ret = EXCP_INTERRUPT;
3860 if (powerdown_requested) {
3861 powerdown_requested = 0;
3862 qemu_system_powerdown();
3863 ret = EXCP_INTERRUPT;
3865 #ifdef CONFIG_GDBSTUB
3866 if (unlikely(ret == EXCP_DEBUG)) {
3867 gdb_set_stop_cpu(cur_cpu);
3868 vm_stop(EXCP_DEBUG);
3870 #endif
3871 /* If all cpus are halted then wait until the next IRQ */
3872 /* XXX: use timeout computed from timers */
3873 if (ret == EXCP_HALTED) {
3874 if (use_icount) {
3875 int64_t add;
3876 int64_t delta;
3877 /* Advance virtual time to the next event. */
3878 if (use_icount == 1) {
3879 /* When not using an adaptive execution frequency
3880 we tend to get badly out of sync with real time,
3881 so just delay for a reasonable amount of time. */
3882 delta = 0;
3883 } else {
3884 delta = cpu_get_icount() - cpu_get_clock();
3886 if (delta > 0) {
3887 /* If virtual time is ahead of real time then just
3888 wait for IO. */
3889 timeout = (delta / 1000000) + 1;
3890 } else {
3891 /* Wait for either IO to occur or the next
3892 timer event. */
3893 add = qemu_next_deadline();
3894 /* We advance the timer before checking for IO.
3895 Limit the amount we advance so that early IO
3896 activity won't get the guest too far ahead. */
3897 if (add > 10000000)
3898 add = 10000000;
3899 delta += add;
3900 add = (add + (1 << icount_time_shift) - 1)
3901 >> icount_time_shift;
3902 qemu_icount += add;
3903 timeout = delta / 1000000;
3904 if (timeout < 0)
3905 timeout = 0;
3907 } else {
3908 timeout = 5000;
3910 } else {
3911 timeout = 0;
3913 } else {
3914 if (shutdown_requested) {
3915 ret = EXCP_INTERRUPT;
3916 break;
3918 timeout = 5000;
3920 #ifdef CONFIG_PROFILER
3921 ti = profile_getclock();
3922 #endif
3923 main_loop_wait(timeout);
3924 #ifdef CONFIG_PROFILER
3925 dev_time += profile_getclock() - ti;
3926 #endif
3928 cpu_disable_ticks();
3929 return ret;
3932 static void help(int exitcode)
3934 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
3935 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3936 "usage: %s [options] [disk_image]\n"
3937 "\n"
3938 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3939 "\n"
3940 "Standard options:\n"
3941 "-M machine select emulated machine (-M ? for list)\n"
3942 "-cpu cpu select CPU (-cpu ? for list)\n"
3943 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3944 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3945 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3946 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3947 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3948 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3949 " [,cache=writethrough|writeback|none][,format=f]\n"
3950 " [,boot=on|off]\n"
3951 " use 'file' as a drive image\n"
3952 "-mtdblock file use 'file' as on-board Flash memory image\n"
3953 "-sd file use 'file' as SecureDigital card image\n"
3954 "-pflash file use 'file' as a parallel flash image\n"
3955 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3956 "-snapshot write to temporary files instead of disk image files\n"
3957 #ifdef CONFIG_SDL
3958 "-no-frame open SDL window without a frame and window decorations\n"
3959 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3960 "-no-quit disable SDL window close capability\n"
3961 #endif
3962 #ifdef TARGET_I386
3963 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3964 #endif
3965 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3966 "-smp n set the number of CPUs to 'n' [default=1]\n"
3967 "-nographic disable graphical output and redirect serial I/Os to console\n"
3968 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3969 #ifndef _WIN32
3970 "-k language use keyboard layout (for example \"fr\" for French)\n"
3971 #endif
3972 #ifdef HAS_AUDIO
3973 "-audio-help print list of audio drivers and their options\n"
3974 "-soundhw c1,... enable audio support\n"
3975 " and only specified sound cards (comma separated list)\n"
3976 " use -soundhw ? to get the list of supported cards\n"
3977 " use -soundhw all to enable all of them\n"
3978 #endif
3979 "-vga [std|cirrus|vmware]\n"
3980 " select video card type\n"
3981 "-localtime set the real time clock to local time [default=utc]\n"
3982 "-full-screen start in full screen\n"
3983 #ifdef TARGET_I386
3984 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3985 #endif
3986 "-usb enable the USB driver (will be the default soon)\n"
3987 "-usbdevice name add the host or guest USB device 'name'\n"
3988 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3989 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3990 #endif
3991 "-name string set the name of the guest\n"
3992 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
3993 "\n"
3994 "Network options:\n"
3995 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
3996 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3997 #ifdef CONFIG_SLIRP
3998 "-net user[,vlan=n][,hostname=host]\n"
3999 " connect the user mode network stack to VLAN 'n' and send\n"
4000 " hostname 'host' to DHCP clients\n"
4001 #endif
4002 #ifdef _WIN32
4003 "-net tap[,vlan=n],ifname=name\n"
4004 " connect the host TAP network interface to VLAN 'n'\n"
4005 #else
4006 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4007 " connect the host TAP network interface to VLAN 'n' and use the\n"
4008 " network scripts 'file' (default=%s)\n"
4009 " and 'dfile' (default=%s);\n"
4010 " use '[down]script=no' to disable script execution;\n"
4011 " use 'fd=h' to connect to an already opened TAP interface\n"
4012 #endif
4013 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4014 " connect the vlan 'n' to another VLAN using a socket connection\n"
4015 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4016 " connect the vlan 'n' to multicast maddr and port\n"
4017 #ifdef CONFIG_VDE
4018 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4019 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4020 " on host and listening for incoming connections on 'socketpath'.\n"
4021 " Use group 'groupname' and mode 'octalmode' to change default\n"
4022 " ownership and permissions for communication port.\n"
4023 #endif
4024 "-net none use it alone to have zero network devices; if no -net option\n"
4025 " is provided, the default is '-net nic -net user'\n"
4026 "\n"
4027 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
4028 "-bt hci,host[:id]\n"
4029 " Use host's HCI with the given name\n"
4030 "-bt hci[,vlan=n]\n"
4031 " Emulate a standard HCI in virtual scatternet 'n'\n"
4032 "-bt vhci[,vlan=n]\n"
4033 " Add host computer to virtual scatternet 'n' using VHCI\n"
4034 "-bt device:dev[,vlan=n]\n"
4035 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
4036 "\n"
4037 #ifdef CONFIG_SLIRP
4038 "-tftp dir allow tftp access to files in dir [-net user]\n"
4039 "-bootp file advertise file in BOOTP replies\n"
4040 #ifndef _WIN32
4041 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4042 #endif
4043 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4044 " redirect TCP or UDP connections from host to guest [-net user]\n"
4045 #endif
4046 "\n"
4047 "Linux boot specific:\n"
4048 "-kernel bzImage use 'bzImage' as kernel image\n"
4049 "-append cmdline use 'cmdline' as kernel command line\n"
4050 "-initrd file use 'file' as initial ram disk\n"
4051 "\n"
4052 "Debug/Expert options:\n"
4053 "-monitor dev redirect the monitor to char device 'dev'\n"
4054 "-serial dev redirect the serial port to char device 'dev'\n"
4055 "-parallel dev redirect the parallel port to char device 'dev'\n"
4056 "-pidfile file Write PID to 'file'\n"
4057 "-S freeze CPU at startup (use 'c' to start execution)\n"
4058 "-s wait gdb connection to port\n"
4059 "-p port set gdb connection port [default=%s]\n"
4060 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4061 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4062 " translation (t=none or lba) (usually qemu can guess them)\n"
4063 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4064 #ifdef USE_KQEMU
4065 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4066 "-no-kqemu disable KQEMU kernel module usage\n"
4067 #endif
4068 #ifdef CONFIG_KVM
4069 "-enable-kvm enable KVM full virtualization support\n"
4070 #endif
4071 #ifdef USE_KVM
4072 #ifndef NO_CPU_EMULATION
4073 "-no-kvm disable KVM hardware virtualization\n"
4074 #endif
4075 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4076 "-no-kvm-pit disable KVM kernel mode PIT\n"
4077 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4078 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4079 " expose a PCI device to the guest OS.\n"
4080 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4081 " 'string' is used in log output.\n"
4082 #endif
4083 #endif
4084 #ifdef TARGET_I386
4085 "-no-acpi disable ACPI\n"
4086 #endif
4087 #ifdef CONFIG_CURSES
4088 "-curses use a curses/ncurses interface instead of SDL\n"
4089 #endif
4090 "-no-reboot exit instead of rebooting\n"
4091 "-no-shutdown stop before shutdown\n"
4092 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
4093 "-vnc display start a VNC server on display\n"
4094 #ifndef _WIN32
4095 "-daemonize daemonize QEMU after initializing\n"
4096 #endif
4097 "-tdf inject timer interrupts that got lost\n"
4098 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4099 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
4100 "-option-rom rom load a file, rom, into the option ROM space\n"
4101 #ifdef TARGET_SPARC
4102 "-prom-env variable=value set OpenBIOS nvram variables\n"
4103 #endif
4104 "-clock force the use of the given methods for timer alarm.\n"
4105 " To see what timers are available use -clock ?\n"
4106 "-startdate select initial date of the clock\n"
4107 "-icount [N|auto]\n"
4108 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4109 "\n"
4110 "During emulation, the following keys are useful:\n"
4111 "ctrl-alt-f toggle full screen\n"
4112 "ctrl-alt-n switch to virtual console 'n'\n"
4113 "ctrl-alt toggle mouse and keyboard grab\n"
4114 "\n"
4115 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4117 "qemu",
4118 DEFAULT_RAM_SIZE,
4119 #ifndef _WIN32
4120 DEFAULT_NETWORK_SCRIPT,
4121 DEFAULT_NETWORK_DOWN_SCRIPT,
4122 #endif
4123 DEFAULT_GDBSTUB_PORT,
4124 "/tmp/qemu.log");
4125 exit(exitcode);
4128 #define HAS_ARG 0x0001
4130 enum {
4131 QEMU_OPTION_h,
4133 QEMU_OPTION_M,
4134 QEMU_OPTION_cpu,
4135 QEMU_OPTION_fda,
4136 QEMU_OPTION_fdb,
4137 QEMU_OPTION_hda,
4138 QEMU_OPTION_hdb,
4139 QEMU_OPTION_hdc,
4140 QEMU_OPTION_hdd,
4141 QEMU_OPTION_drive,
4142 QEMU_OPTION_cdrom,
4143 QEMU_OPTION_mtdblock,
4144 QEMU_OPTION_sd,
4145 QEMU_OPTION_pflash,
4146 QEMU_OPTION_boot,
4147 QEMU_OPTION_snapshot,
4148 #ifdef TARGET_I386
4149 QEMU_OPTION_no_fd_bootchk,
4150 #endif
4151 QEMU_OPTION_m,
4152 QEMU_OPTION_nographic,
4153 QEMU_OPTION_portrait,
4154 #ifdef HAS_AUDIO
4155 QEMU_OPTION_audio_help,
4156 QEMU_OPTION_soundhw,
4157 #endif
4159 QEMU_OPTION_net,
4160 QEMU_OPTION_tftp,
4161 QEMU_OPTION_bootp,
4162 QEMU_OPTION_smb,
4163 QEMU_OPTION_redir,
4164 QEMU_OPTION_bt,
4166 QEMU_OPTION_kernel,
4167 QEMU_OPTION_append,
4168 QEMU_OPTION_initrd,
4170 QEMU_OPTION_S,
4171 QEMU_OPTION_s,
4172 QEMU_OPTION_p,
4173 QEMU_OPTION_d,
4174 QEMU_OPTION_hdachs,
4175 QEMU_OPTION_L,
4176 QEMU_OPTION_bios,
4177 QEMU_OPTION_k,
4178 QEMU_OPTION_localtime,
4179 QEMU_OPTION_g,
4180 QEMU_OPTION_vga,
4181 QEMU_OPTION_echr,
4182 QEMU_OPTION_monitor,
4183 QEMU_OPTION_serial,
4184 QEMU_OPTION_parallel,
4185 QEMU_OPTION_loadvm,
4186 QEMU_OPTION_full_screen,
4187 QEMU_OPTION_no_frame,
4188 QEMU_OPTION_alt_grab,
4189 QEMU_OPTION_no_quit,
4190 QEMU_OPTION_pidfile,
4191 QEMU_OPTION_no_kqemu,
4192 QEMU_OPTION_kernel_kqemu,
4193 QEMU_OPTION_enable_kvm,
4194 QEMU_OPTION_win2k_hack,
4195 QEMU_OPTION_usb,
4196 QEMU_OPTION_usbdevice,
4197 QEMU_OPTION_smp,
4198 QEMU_OPTION_vnc,
4199 QEMU_OPTION_no_acpi,
4200 QEMU_OPTION_curses,
4201 QEMU_OPTION_no_kvm,
4202 QEMU_OPTION_no_kvm_irqchip,
4203 QEMU_OPTION_no_kvm_pit,
4204 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4205 QEMU_OPTION_pcidevice,
4206 #endif
4207 QEMU_OPTION_no_reboot,
4208 QEMU_OPTION_no_shutdown,
4209 QEMU_OPTION_show_cursor,
4210 QEMU_OPTION_daemonize,
4211 QEMU_OPTION_option_rom,
4212 QEMU_OPTION_semihosting,
4213 QEMU_OPTION_cpu_vendor,
4214 QEMU_OPTION_name,
4215 QEMU_OPTION_prom_env,
4216 QEMU_OPTION_old_param,
4217 QEMU_OPTION_clock,
4218 QEMU_OPTION_startdate,
4219 QEMU_OPTION_tb_size,
4220 QEMU_OPTION_icount,
4221 QEMU_OPTION_uuid,
4222 QEMU_OPTION_incoming,
4223 QEMU_OPTION_tdf,
4224 QEMU_OPTION_kvm_shadow_memory,
4225 QEMU_OPTION_mempath,
4228 typedef struct QEMUOption {
4229 const char *name;
4230 int flags;
4231 int index;
4232 } QEMUOption;
4234 static const QEMUOption qemu_options[] = {
4235 { "h", 0, QEMU_OPTION_h },
4236 { "help", 0, QEMU_OPTION_h },
4238 { "M", HAS_ARG, QEMU_OPTION_M },
4239 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4240 { "fda", HAS_ARG, QEMU_OPTION_fda },
4241 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4242 { "hda", HAS_ARG, QEMU_OPTION_hda },
4243 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4244 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4245 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4246 { "drive", HAS_ARG, QEMU_OPTION_drive },
4247 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4248 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4249 { "sd", HAS_ARG, QEMU_OPTION_sd },
4250 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4251 { "boot", HAS_ARG, QEMU_OPTION_boot },
4252 { "snapshot", 0, QEMU_OPTION_snapshot },
4253 #ifdef TARGET_I386
4254 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4255 #endif
4256 { "m", HAS_ARG, QEMU_OPTION_m },
4257 { "nographic", 0, QEMU_OPTION_nographic },
4258 { "portrait", 0, QEMU_OPTION_portrait },
4259 { "k", HAS_ARG, QEMU_OPTION_k },
4260 #ifdef HAS_AUDIO
4261 { "audio-help", 0, QEMU_OPTION_audio_help },
4262 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4263 #endif
4265 { "net", HAS_ARG, QEMU_OPTION_net},
4266 #ifdef CONFIG_SLIRP
4267 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4268 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4269 #ifndef _WIN32
4270 { "smb", HAS_ARG, QEMU_OPTION_smb },
4271 #endif
4272 { "redir", HAS_ARG, QEMU_OPTION_redir },
4273 #endif
4274 { "bt", HAS_ARG, QEMU_OPTION_bt },
4276 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4277 { "append", HAS_ARG, QEMU_OPTION_append },
4278 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4280 { "S", 0, QEMU_OPTION_S },
4281 { "s", 0, QEMU_OPTION_s },
4282 { "p", HAS_ARG, QEMU_OPTION_p },
4283 { "d", HAS_ARG, QEMU_OPTION_d },
4284 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4285 { "L", HAS_ARG, QEMU_OPTION_L },
4286 { "bios", HAS_ARG, QEMU_OPTION_bios },
4287 #ifdef USE_KQEMU
4288 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4289 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4290 #endif
4291 #ifdef CONFIG_KVM
4292 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4293 #endif
4294 #ifdef USE_KVM
4295 #ifndef NO_CPU_EMULATION
4296 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4297 #endif
4298 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4299 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4300 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4301 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4302 #endif
4303 #endif
4304 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4305 { "g", 1, QEMU_OPTION_g },
4306 #endif
4307 { "localtime", 0, QEMU_OPTION_localtime },
4308 { "vga", HAS_ARG, QEMU_OPTION_vga },
4309 { "echr", HAS_ARG, QEMU_OPTION_echr },
4310 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4311 { "serial", HAS_ARG, QEMU_OPTION_serial },
4312 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4313 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4314 { "incoming", 1, QEMU_OPTION_incoming },
4315 { "full-screen", 0, QEMU_OPTION_full_screen },
4316 #ifdef CONFIG_SDL
4317 { "no-frame", 0, QEMU_OPTION_no_frame },
4318 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4319 { "no-quit", 0, QEMU_OPTION_no_quit },
4320 #endif
4321 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4322 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4323 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4324 { "smp", HAS_ARG, QEMU_OPTION_smp },
4325 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4326 #ifdef CONFIG_CURSES
4327 { "curses", 0, QEMU_OPTION_curses },
4328 #endif
4329 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4331 /* temporary options */
4332 { "usb", 0, QEMU_OPTION_usb },
4333 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4334 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4335 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4336 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4337 { "daemonize", 0, QEMU_OPTION_daemonize },
4338 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4339 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4340 { "semihosting", 0, QEMU_OPTION_semihosting },
4341 #endif
4342 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4343 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4344 { "name", HAS_ARG, QEMU_OPTION_name },
4345 #if defined(TARGET_SPARC)
4346 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4347 #endif
4348 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4349 #if defined(TARGET_ARM)
4350 { "old-param", 0, QEMU_OPTION_old_param },
4351 #endif
4352 { "clock", HAS_ARG, QEMU_OPTION_clock },
4353 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4354 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4355 { "icount", HAS_ARG, QEMU_OPTION_icount },
4356 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4357 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4358 { NULL },
4361 /* password input */
4363 int qemu_key_check(BlockDriverState *bs, const char *name)
4365 char password[256];
4366 int i;
4368 if (!bdrv_is_encrypted(bs))
4369 return 0;
4371 term_printf("%s is encrypted.\n", name);
4372 for(i = 0; i < 3; i++) {
4373 monitor_readline("Password: ", 1, password, sizeof(password));
4374 if (bdrv_set_key(bs, password) == 0)
4375 return 0;
4376 term_printf("invalid password\n");
4378 return -EPERM;
4381 static BlockDriverState *get_bdrv(int index)
4383 if (index > nb_drives)
4384 return NULL;
4385 return drives_table[index].bdrv;
4388 static void read_passwords(void)
4390 BlockDriverState *bs;
4391 int i;
4393 for(i = 0; i < 6; i++) {
4394 bs = get_bdrv(i);
4395 if (bs)
4396 qemu_key_check(bs, bdrv_get_device_name(bs));
4400 #ifdef HAS_AUDIO
4401 struct soundhw soundhw[] = {
4402 #ifdef HAS_AUDIO_CHOICE
4403 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4405 "pcspk",
4406 "PC speaker",
4409 { .init_isa = pcspk_audio_init }
4411 #endif
4413 "sb16",
4414 "Creative Sound Blaster 16",
4417 { .init_isa = SB16_init }
4420 #ifdef CONFIG_CS4231A
4422 "cs4231a",
4423 "CS4231A",
4426 { .init_isa = cs4231a_init }
4428 #endif
4430 #ifdef CONFIG_ADLIB
4432 "adlib",
4433 #ifdef HAS_YMF262
4434 "Yamaha YMF262 (OPL3)",
4435 #else
4436 "Yamaha YM3812 (OPL2)",
4437 #endif
4440 { .init_isa = Adlib_init }
4442 #endif
4444 #ifdef CONFIG_GUS
4446 "gus",
4447 "Gravis Ultrasound GF1",
4450 { .init_isa = GUS_init }
4452 #endif
4454 #ifdef CONFIG_AC97
4456 "ac97",
4457 "Intel 82801AA AC97 Audio",
4460 { .init_pci = ac97_init }
4462 #endif
4465 "es1370",
4466 "ENSONIQ AudioPCI ES1370",
4469 { .init_pci = es1370_init }
4471 #endif
4473 { NULL, NULL, 0, 0, { NULL } }
4476 static void select_soundhw (const char *optarg)
4478 struct soundhw *c;
4480 if (*optarg == '?') {
4481 show_valid_cards:
4483 printf ("Valid sound card names (comma separated):\n");
4484 for (c = soundhw; c->name; ++c) {
4485 printf ("%-11s %s\n", c->name, c->descr);
4487 printf ("\n-soundhw all will enable all of the above\n");
4488 exit (*optarg != '?');
4490 else {
4491 size_t l;
4492 const char *p;
4493 char *e;
4494 int bad_card = 0;
4496 if (!strcmp (optarg, "all")) {
4497 for (c = soundhw; c->name; ++c) {
4498 c->enabled = 1;
4500 return;
4503 p = optarg;
4504 while (*p) {
4505 e = strchr (p, ',');
4506 l = !e ? strlen (p) : (size_t) (e - p);
4508 for (c = soundhw; c->name; ++c) {
4509 if (!strncmp (c->name, p, l)) {
4510 c->enabled = 1;
4511 break;
4515 if (!c->name) {
4516 if (l > 80) {
4517 fprintf (stderr,
4518 "Unknown sound card name (too big to show)\n");
4520 else {
4521 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4522 (int) l, p);
4524 bad_card = 1;
4526 p += l + (e != NULL);
4529 if (bad_card)
4530 goto show_valid_cards;
4533 #endif
4535 static void select_vgahw (const char *p)
4537 const char *opts;
4539 if (strstart(p, "std", &opts)) {
4540 cirrus_vga_enabled = 0;
4541 vmsvga_enabled = 0;
4542 } else if (strstart(p, "cirrus", &opts)) {
4543 cirrus_vga_enabled = 1;
4544 vmsvga_enabled = 0;
4545 } else if (strstart(p, "vmware", &opts)) {
4546 cirrus_vga_enabled = 0;
4547 vmsvga_enabled = 1;
4548 } else {
4549 invalid_vga:
4550 fprintf(stderr, "Unknown vga type: %s\n", p);
4551 exit(1);
4553 while (*opts) {
4554 const char *nextopt;
4556 if (strstart(opts, ",retrace=", &nextopt)) {
4557 opts = nextopt;
4558 if (strstart(opts, "dumb", &nextopt))
4559 vga_retrace_method = VGA_RETRACE_DUMB;
4560 else if (strstart(opts, "precise", &nextopt))
4561 vga_retrace_method = VGA_RETRACE_PRECISE;
4562 else goto invalid_vga;
4563 } else goto invalid_vga;
4564 opts = nextopt;
4568 #ifdef _WIN32
4569 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4571 exit(STATUS_CONTROL_C_EXIT);
4572 return TRUE;
4574 #endif
4576 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4578 int ret;
4580 if(strlen(str) != 36)
4581 return -1;
4583 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4584 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4585 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4587 if(ret != 16)
4588 return -1;
4590 return 0;
4593 #define MAX_NET_CLIENTS 32
4595 static int saved_argc;
4596 static char **saved_argv;
4598 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4600 *argc = saved_argc;
4601 *argv = saved_argv;
4602 *opt_daemonize = daemonize;
4603 *opt_incoming = incoming;
4607 static int gethugepagesize(void)
4609 int ret, fd;
4610 char buf[4096];
4611 char *needle = "Hugepagesize:";
4612 char *size;
4613 unsigned long hugepagesize;
4615 fd = open("/proc/meminfo", O_RDONLY);
4616 if (fd < 0) {
4617 perror("open");
4618 exit(0);
4621 ret = read(fd, buf, sizeof(buf));
4622 if (ret < 0) {
4623 perror("read");
4624 exit(0);
4627 size = strstr(buf, needle);
4628 if (!size)
4629 return 0;
4630 size += strlen(needle);
4631 hugepagesize = strtol(size, NULL, 0);
4632 return hugepagesize;
4635 void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4637 char *filename;
4638 void *area;
4639 int fd;
4641 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4642 return NULL;
4644 hpagesize = gethugepagesize() * 1024;
4645 if (!hpagesize)
4646 return NULL;
4648 fd = mkstemp(filename);
4649 if (fd < 0) {
4650 perror("mkstemp");
4651 free(filename);
4652 return NULL;
4654 unlink(filename);
4655 free(filename);
4657 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4660 * ftruncate is not supported by hugetlbfs in older
4661 * hosts, so don't bother checking for errors.
4662 * If anything goes wrong with it under other filesystems,
4663 * mmap will fail.
4665 ftruncate(fd, memory);
4667 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4668 if (area == MAP_FAILED) {
4669 perror("mmap");
4670 close(fd);
4671 return NULL;
4674 *len = memory;
4675 return area;
4678 void *qemu_alloc_physram(unsigned long memory)
4680 void *area = NULL;
4681 unsigned long map_len = memory;
4683 #ifdef USE_KVM
4684 if (mem_path)
4685 area = alloc_mem_area(memory, &map_len, mem_path);
4686 #endif
4687 if (!area)
4688 area = qemu_vmalloc(memory);
4689 #ifdef USE_KVM
4690 if (kvm_setup_guest_memory(area, map_len))
4691 area = NULL;
4692 #endif
4693 return area;
4696 #ifndef _WIN32
4698 static void termsig_handler(int signal)
4700 qemu_system_shutdown_request();
4703 static void termsig_setup(void)
4705 struct sigaction act;
4707 memset(&act, 0, sizeof(act));
4708 act.sa_handler = termsig_handler;
4709 sigaction(SIGINT, &act, NULL);
4710 sigaction(SIGHUP, &act, NULL);
4711 sigaction(SIGTERM, &act, NULL);
4714 #endif
4716 int main(int argc, char **argv)
4718 #ifdef CONFIG_GDBSTUB
4719 int use_gdbstub;
4720 const char *gdbstub_port;
4721 #endif
4722 uint32_t boot_devices_bitmap = 0;
4723 int i;
4724 int snapshot, linux_boot, net_boot;
4725 const char *initrd_filename;
4726 const char *kernel_filename, *kernel_cmdline;
4727 const char *boot_devices = "";
4728 DisplayState *ds = &display_state;
4729 int cyls, heads, secs, translation;
4730 const char *net_clients[MAX_NET_CLIENTS];
4731 int nb_net_clients;
4732 const char *bt_opts[MAX_BT_CMDLINE];
4733 int nb_bt_opts;
4734 int hda_index;
4735 int optind;
4736 const char *r, *optarg;
4737 CharDriverState *monitor_hd;
4738 const char *monitor_device;
4739 const char *serial_devices[MAX_SERIAL_PORTS];
4740 int serial_device_index;
4741 const char *parallel_devices[MAX_PARALLEL_PORTS];
4742 int parallel_device_index;
4743 const char *loadvm = NULL;
4744 QEMUMachine *machine;
4745 const char *cpu_model;
4746 const char *usb_devices[MAX_USB_CMDLINE];
4747 int usb_devices_index;
4748 int fds[2];
4749 int tb_size;
4750 const char *pid_file = NULL;
4751 int autostart;
4752 const char *incoming = NULL;
4754 LIST_INIT (&vm_change_state_head);
4755 #ifndef _WIN32
4757 struct sigaction act;
4758 sigfillset(&act.sa_mask);
4759 act.sa_flags = 0;
4760 act.sa_handler = SIG_IGN;
4761 sigaction(SIGPIPE, &act, NULL);
4763 #else
4764 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4765 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4766 QEMU to run on a single CPU */
4768 HANDLE h;
4769 DWORD mask, smask;
4770 int i;
4771 h = GetCurrentProcess();
4772 if (GetProcessAffinityMask(h, &mask, &smask)) {
4773 for(i = 0; i < 32; i++) {
4774 if (mask & (1 << i))
4775 break;
4777 if (i != 32) {
4778 mask = 1 << i;
4779 SetProcessAffinityMask(h, mask);
4783 #endif
4785 register_machines();
4786 machine = first_machine;
4787 cpu_model = NULL;
4788 initrd_filename = NULL;
4789 ram_size = 0;
4790 vga_ram_size = VGA_RAM_SIZE;
4791 #ifdef CONFIG_GDBSTUB
4792 use_gdbstub = 0;
4793 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4794 #endif
4795 snapshot = 0;
4796 nographic = 0;
4797 curses = 0;
4798 kernel_filename = NULL;
4799 kernel_cmdline = "";
4800 cyls = heads = secs = 0;
4801 translation = BIOS_ATA_TRANSLATION_AUTO;
4802 monitor_device = "vc";
4804 serial_devices[0] = "vc:80Cx24C";
4805 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4806 serial_devices[i] = NULL;
4807 serial_device_index = 0;
4809 parallel_devices[0] = "vc:640x480";
4810 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4811 parallel_devices[i] = NULL;
4812 parallel_device_index = 0;
4814 usb_devices_index = 0;
4815 assigned_devices_index = 0;
4817 nb_net_clients = 0;
4818 nb_bt_opts = 0;
4819 nb_drives = 0;
4820 nb_drives_opt = 0;
4821 hda_index = -1;
4823 nb_nics = 0;
4825 tb_size = 0;
4826 autostart= 1;
4828 optind = 1;
4829 for(;;) {
4830 if (optind >= argc)
4831 break;
4832 r = argv[optind];
4833 if (r[0] != '-') {
4834 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4835 } else {
4836 const QEMUOption *popt;
4838 optind++;
4839 /* Treat --foo the same as -foo. */
4840 if (r[1] == '-')
4841 r++;
4842 popt = qemu_options;
4843 for(;;) {
4844 if (!popt->name) {
4845 fprintf(stderr, "%s: invalid option -- '%s'\n",
4846 argv[0], r);
4847 exit(1);
4849 if (!strcmp(popt->name, r + 1))
4850 break;
4851 popt++;
4853 if (popt->flags & HAS_ARG) {
4854 if (optind >= argc) {
4855 fprintf(stderr, "%s: option '%s' requires an argument\n",
4856 argv[0], r);
4857 exit(1);
4859 optarg = argv[optind++];
4860 } else {
4861 optarg = NULL;
4864 switch(popt->index) {
4865 case QEMU_OPTION_M:
4866 machine = find_machine(optarg);
4867 if (!machine) {
4868 QEMUMachine *m;
4869 printf("Supported machines are:\n");
4870 for(m = first_machine; m != NULL; m = m->next) {
4871 printf("%-10s %s%s\n",
4872 m->name, m->desc,
4873 m == first_machine ? " (default)" : "");
4875 exit(*optarg != '?');
4877 break;
4878 case QEMU_OPTION_cpu:
4879 /* hw initialization will check this */
4880 if (*optarg == '?') {
4881 /* XXX: implement xxx_cpu_list for targets that still miss it */
4882 #if defined(cpu_list)
4883 cpu_list(stdout, &fprintf);
4884 #endif
4885 exit(0);
4886 } else {
4887 cpu_model = optarg;
4889 break;
4890 case QEMU_OPTION_initrd:
4891 initrd_filename = optarg;
4892 break;
4893 case QEMU_OPTION_hda:
4894 if (cyls == 0)
4895 hda_index = drive_add(optarg, HD_ALIAS, 0);
4896 else
4897 hda_index = drive_add(optarg, HD_ALIAS
4898 ",cyls=%d,heads=%d,secs=%d%s",
4899 0, cyls, heads, secs,
4900 translation == BIOS_ATA_TRANSLATION_LBA ?
4901 ",trans=lba" :
4902 translation == BIOS_ATA_TRANSLATION_NONE ?
4903 ",trans=none" : "");
4904 break;
4905 case QEMU_OPTION_hdb:
4906 case QEMU_OPTION_hdc:
4907 case QEMU_OPTION_hdd:
4908 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4909 break;
4910 case QEMU_OPTION_drive:
4911 drive_add(NULL, "%s", optarg);
4912 break;
4913 case QEMU_OPTION_mtdblock:
4914 drive_add(optarg, MTD_ALIAS);
4915 break;
4916 case QEMU_OPTION_sd:
4917 drive_add(optarg, SD_ALIAS);
4918 break;
4919 case QEMU_OPTION_pflash:
4920 drive_add(optarg, PFLASH_ALIAS);
4921 break;
4922 case QEMU_OPTION_snapshot:
4923 snapshot = 1;
4924 break;
4925 case QEMU_OPTION_hdachs:
4927 const char *p;
4928 p = optarg;
4929 cyls = strtol(p, (char **)&p, 0);
4930 if (cyls < 1 || cyls > 16383)
4931 goto chs_fail;
4932 if (*p != ',')
4933 goto chs_fail;
4934 p++;
4935 heads = strtol(p, (char **)&p, 0);
4936 if (heads < 1 || heads > 16)
4937 goto chs_fail;
4938 if (*p != ',')
4939 goto chs_fail;
4940 p++;
4941 secs = strtol(p, (char **)&p, 0);
4942 if (secs < 1 || secs > 63)
4943 goto chs_fail;
4944 if (*p == ',') {
4945 p++;
4946 if (!strcmp(p, "none"))
4947 translation = BIOS_ATA_TRANSLATION_NONE;
4948 else if (!strcmp(p, "lba"))
4949 translation = BIOS_ATA_TRANSLATION_LBA;
4950 else if (!strcmp(p, "auto"))
4951 translation = BIOS_ATA_TRANSLATION_AUTO;
4952 else
4953 goto chs_fail;
4954 } else if (*p != '\0') {
4955 chs_fail:
4956 fprintf(stderr, "qemu: invalid physical CHS format\n");
4957 exit(1);
4959 if (hda_index != -1)
4960 snprintf(drives_opt[hda_index].opt,
4961 sizeof(drives_opt[hda_index].opt),
4962 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4963 0, cyls, heads, secs,
4964 translation == BIOS_ATA_TRANSLATION_LBA ?
4965 ",trans=lba" :
4966 translation == BIOS_ATA_TRANSLATION_NONE ?
4967 ",trans=none" : "");
4969 break;
4970 case QEMU_OPTION_nographic:
4971 nographic = 1;
4972 break;
4973 #ifdef CONFIG_CURSES
4974 case QEMU_OPTION_curses:
4975 curses = 1;
4976 break;
4977 #endif
4978 case QEMU_OPTION_portrait:
4979 graphic_rotate = 1;
4980 break;
4981 case QEMU_OPTION_kernel:
4982 kernel_filename = optarg;
4983 break;
4984 case QEMU_OPTION_append:
4985 kernel_cmdline = optarg;
4986 break;
4987 case QEMU_OPTION_cdrom:
4988 drive_add(optarg, CDROM_ALIAS);
4989 break;
4990 case QEMU_OPTION_boot:
4991 boot_devices = optarg;
4992 /* We just do some generic consistency checks */
4994 /* Could easily be extended to 64 devices if needed */
4995 const char *p;
4997 boot_devices_bitmap = 0;
4998 for (p = boot_devices; *p != '\0'; p++) {
4999 /* Allowed boot devices are:
5000 * a b : floppy disk drives
5001 * c ... f : IDE disk drives
5002 * g ... m : machine implementation dependant drives
5003 * n ... p : network devices
5004 * It's up to each machine implementation to check
5005 * if the given boot devices match the actual hardware
5006 * implementation and firmware features.
5008 if (*p < 'a' || *p > 'q') {
5009 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5010 exit(1);
5012 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5013 fprintf(stderr,
5014 "Boot device '%c' was given twice\n",*p);
5015 exit(1);
5017 boot_devices_bitmap |= 1 << (*p - 'a');
5020 break;
5021 case QEMU_OPTION_fda:
5022 case QEMU_OPTION_fdb:
5023 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5024 break;
5025 #ifdef TARGET_I386
5026 case QEMU_OPTION_no_fd_bootchk:
5027 fd_bootchk = 0;
5028 break;
5029 #endif
5030 case QEMU_OPTION_net:
5031 if (nb_net_clients >= MAX_NET_CLIENTS) {
5032 fprintf(stderr, "qemu: too many network clients\n");
5033 exit(1);
5035 net_clients[nb_net_clients] = optarg;
5036 nb_net_clients++;
5037 break;
5038 #ifdef CONFIG_SLIRP
5039 case QEMU_OPTION_tftp:
5040 tftp_prefix = optarg;
5041 break;
5042 case QEMU_OPTION_bootp:
5043 bootp_filename = optarg;
5044 break;
5045 #ifndef _WIN32
5046 case QEMU_OPTION_smb:
5047 net_slirp_smb(optarg);
5048 break;
5049 #endif
5050 case QEMU_OPTION_redir:
5051 net_slirp_redir(optarg);
5052 break;
5053 #endif
5054 case QEMU_OPTION_bt:
5055 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5056 fprintf(stderr, "qemu: too many bluetooth options\n");
5057 exit(1);
5059 bt_opts[nb_bt_opts++] = optarg;
5060 break;
5061 #ifdef HAS_AUDIO
5062 case QEMU_OPTION_audio_help:
5063 AUD_help ();
5064 exit (0);
5065 break;
5066 case QEMU_OPTION_soundhw:
5067 select_soundhw (optarg);
5068 break;
5069 #endif
5070 case QEMU_OPTION_h:
5071 help(0);
5072 break;
5073 case QEMU_OPTION_m: {
5074 uint64_t value;
5075 char *ptr;
5077 value = strtoul(optarg, &ptr, 10);
5078 switch (*ptr) {
5079 case 0: case 'M': case 'm':
5080 value <<= 20;
5081 break;
5082 case 'G': case 'g':
5083 value <<= 30;
5084 break;
5085 default:
5086 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5087 exit(1);
5090 /* On 32-bit hosts, QEMU is limited by virtual address space */
5091 if (value > (2047 << 20)
5092 #ifndef USE_KQEMU
5093 && HOST_LONG_BITS == 32
5094 #endif
5096 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5097 exit(1);
5099 if (value != (uint64_t)(ram_addr_t)value) {
5100 fprintf(stderr, "qemu: ram size too large\n");
5101 exit(1);
5103 ram_size = value;
5104 break;
5106 case QEMU_OPTION_d:
5108 int mask;
5109 const CPULogItem *item;
5111 mask = cpu_str_to_log_mask(optarg);
5112 if (!mask) {
5113 printf("Log items (comma separated):\n");
5114 for(item = cpu_log_items; item->mask != 0; item++) {
5115 printf("%-10s %s\n", item->name, item->help);
5117 exit(1);
5119 cpu_set_log(mask);
5121 break;
5122 #ifdef CONFIG_GDBSTUB
5123 case QEMU_OPTION_s:
5124 use_gdbstub = 1;
5125 break;
5126 case QEMU_OPTION_p:
5127 gdbstub_port = optarg;
5128 break;
5129 #endif
5130 case QEMU_OPTION_L:
5131 bios_dir = optarg;
5132 break;
5133 case QEMU_OPTION_bios:
5134 bios_name = optarg;
5135 break;
5136 case QEMU_OPTION_S:
5137 autostart = 0;
5138 break;
5139 case QEMU_OPTION_k:
5140 keyboard_layout = optarg;
5141 break;
5142 case QEMU_OPTION_localtime:
5143 rtc_utc = 0;
5144 break;
5145 case QEMU_OPTION_vga:
5146 select_vgahw (optarg);
5147 break;
5148 case QEMU_OPTION_g:
5150 const char *p;
5151 int w, h, depth;
5152 p = optarg;
5153 w = strtol(p, (char **)&p, 10);
5154 if (w <= 0) {
5155 graphic_error:
5156 fprintf(stderr, "qemu: invalid resolution or depth\n");
5157 exit(1);
5159 if (*p != 'x')
5160 goto graphic_error;
5161 p++;
5162 h = strtol(p, (char **)&p, 10);
5163 if (h <= 0)
5164 goto graphic_error;
5165 if (*p == 'x') {
5166 p++;
5167 depth = strtol(p, (char **)&p, 10);
5168 if (depth != 8 && depth != 15 && depth != 16 &&
5169 depth != 24 && depth != 32)
5170 goto graphic_error;
5171 } else if (*p == '\0') {
5172 depth = graphic_depth;
5173 } else {
5174 goto graphic_error;
5177 graphic_width = w;
5178 graphic_height = h;
5179 graphic_depth = depth;
5181 break;
5182 case QEMU_OPTION_echr:
5184 char *r;
5185 term_escape_char = strtol(optarg, &r, 0);
5186 if (r == optarg)
5187 printf("Bad argument to echr\n");
5188 break;
5190 case QEMU_OPTION_monitor:
5191 monitor_device = optarg;
5192 break;
5193 case QEMU_OPTION_serial:
5194 if (serial_device_index >= MAX_SERIAL_PORTS) {
5195 fprintf(stderr, "qemu: too many serial ports\n");
5196 exit(1);
5198 serial_devices[serial_device_index] = optarg;
5199 serial_device_index++;
5200 break;
5201 case QEMU_OPTION_parallel:
5202 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5203 fprintf(stderr, "qemu: too many parallel ports\n");
5204 exit(1);
5206 parallel_devices[parallel_device_index] = optarg;
5207 parallel_device_index++;
5208 break;
5209 case QEMU_OPTION_loadvm:
5210 loadvm = optarg;
5211 break;
5212 case QEMU_OPTION_full_screen:
5213 full_screen = 1;
5214 break;
5215 #ifdef CONFIG_SDL
5216 case QEMU_OPTION_no_frame:
5217 no_frame = 1;
5218 break;
5219 case QEMU_OPTION_alt_grab:
5220 alt_grab = 1;
5221 break;
5222 case QEMU_OPTION_no_quit:
5223 no_quit = 1;
5224 break;
5225 #endif
5226 case QEMU_OPTION_pidfile:
5227 pid_file = optarg;
5228 break;
5229 #ifdef TARGET_I386
5230 case QEMU_OPTION_win2k_hack:
5231 win2k_install_hack = 1;
5232 break;
5233 #endif
5234 #ifdef USE_KQEMU
5235 case QEMU_OPTION_no_kqemu:
5236 kqemu_allowed = 0;
5237 break;
5238 case QEMU_OPTION_kernel_kqemu:
5239 kqemu_allowed = 2;
5240 break;
5241 #endif
5242 #ifdef CONFIG_KVM
5243 case QEMU_OPTION_enable_kvm:
5244 kvm_allowed = 1;
5245 #ifdef USE_KQEMU
5246 kqemu_allowed = 0;
5247 #endif
5248 break;
5249 #endif
5250 #ifdef USE_KVM
5251 case QEMU_OPTION_no_kvm:
5252 kvm_allowed = 0;
5253 break;
5254 case QEMU_OPTION_no_kvm_irqchip: {
5255 extern int kvm_irqchip, kvm_pit;
5256 kvm_irqchip = 0;
5257 kvm_pit = 0;
5258 break;
5260 case QEMU_OPTION_no_kvm_pit: {
5261 extern int kvm_pit;
5262 kvm_pit = 0;
5263 break;
5265 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5266 case QEMU_OPTION_pcidevice:
5267 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5268 fprintf(stderr, "Too many assigned devices\n");
5269 exit(1);
5271 assigned_devices[assigned_devices_index] = optarg;
5272 assigned_devices_index++;
5273 break;
5274 #endif
5275 #endif
5276 case QEMU_OPTION_usb:
5277 usb_enabled = 1;
5278 break;
5279 case QEMU_OPTION_usbdevice:
5280 usb_enabled = 1;
5281 if (usb_devices_index >= MAX_USB_CMDLINE) {
5282 fprintf(stderr, "Too many USB devices\n");
5283 exit(1);
5285 usb_devices[usb_devices_index] = optarg;
5286 usb_devices_index++;
5287 break;
5288 case QEMU_OPTION_smp:
5289 smp_cpus = atoi(optarg);
5290 if (smp_cpus < 1) {
5291 fprintf(stderr, "Invalid number of CPUs\n");
5292 exit(1);
5294 break;
5295 case QEMU_OPTION_vnc:
5296 vnc_display = optarg;
5297 break;
5298 case QEMU_OPTION_no_acpi:
5299 acpi_enabled = 0;
5300 break;
5301 case QEMU_OPTION_no_reboot:
5302 no_reboot = 1;
5303 break;
5304 case QEMU_OPTION_no_shutdown:
5305 no_shutdown = 1;
5306 break;
5307 case QEMU_OPTION_show_cursor:
5308 cursor_hide = 0;
5309 break;
5310 case QEMU_OPTION_uuid:
5311 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5312 fprintf(stderr, "Fail to parse UUID string."
5313 " Wrong format.\n");
5314 exit(1);
5316 break;
5317 case QEMU_OPTION_daemonize:
5318 daemonize = 1;
5319 break;
5320 case QEMU_OPTION_option_rom:
5321 if (nb_option_roms >= MAX_OPTION_ROMS) {
5322 fprintf(stderr, "Too many option ROMs\n");
5323 exit(1);
5325 option_rom[nb_option_roms] = optarg;
5326 nb_option_roms++;
5327 break;
5328 case QEMU_OPTION_semihosting:
5329 semihosting_enabled = 1;
5330 break;
5331 case QEMU_OPTION_tdf:
5332 time_drift_fix = 1;
5333 break;
5334 case QEMU_OPTION_kvm_shadow_memory:
5335 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5336 break;
5337 case QEMU_OPTION_mempath:
5338 mem_path = optarg;
5339 break;
5340 case QEMU_OPTION_name:
5341 qemu_name = optarg;
5342 break;
5343 #ifdef TARGET_SPARC
5344 case QEMU_OPTION_prom_env:
5345 if (nb_prom_envs >= MAX_PROM_ENVS) {
5346 fprintf(stderr, "Too many prom variables\n");
5347 exit(1);
5349 prom_envs[nb_prom_envs] = optarg;
5350 nb_prom_envs++;
5351 break;
5352 #endif
5353 case QEMU_OPTION_cpu_vendor:
5354 cpu_vendor_string = optarg;
5355 break;
5356 #ifdef TARGET_ARM
5357 case QEMU_OPTION_old_param:
5358 old_param = 1;
5359 break;
5360 #endif
5361 case QEMU_OPTION_clock:
5362 configure_alarms(optarg);
5363 break;
5364 case QEMU_OPTION_startdate:
5366 struct tm tm;
5367 time_t rtc_start_date;
5368 if (!strcmp(optarg, "now")) {
5369 rtc_date_offset = -1;
5370 } else {
5371 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5372 &tm.tm_year,
5373 &tm.tm_mon,
5374 &tm.tm_mday,
5375 &tm.tm_hour,
5376 &tm.tm_min,
5377 &tm.tm_sec) == 6) {
5378 /* OK */
5379 } else if (sscanf(optarg, "%d-%d-%d",
5380 &tm.tm_year,
5381 &tm.tm_mon,
5382 &tm.tm_mday) == 3) {
5383 tm.tm_hour = 0;
5384 tm.tm_min = 0;
5385 tm.tm_sec = 0;
5386 } else {
5387 goto date_fail;
5389 tm.tm_year -= 1900;
5390 tm.tm_mon--;
5391 rtc_start_date = mktimegm(&tm);
5392 if (rtc_start_date == -1) {
5393 date_fail:
5394 fprintf(stderr, "Invalid date format. Valid format are:\n"
5395 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5396 exit(1);
5398 rtc_date_offset = time(NULL) - rtc_start_date;
5401 break;
5402 case QEMU_OPTION_tb_size:
5403 tb_size = strtol(optarg, NULL, 0);
5404 if (tb_size < 0)
5405 tb_size = 0;
5406 break;
5407 case QEMU_OPTION_icount:
5408 use_icount = 1;
5409 if (strcmp(optarg, "auto") == 0) {
5410 icount_time_shift = -1;
5411 } else {
5412 icount_time_shift = strtol(optarg, NULL, 0);
5414 break;
5415 case QEMU_OPTION_incoming:
5416 incoming = optarg;
5417 break;
5422 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5423 if (kvm_allowed && kqemu_allowed) {
5424 fprintf(stderr,
5425 "You can not enable both KVM and kqemu at the same time\n");
5426 exit(1);
5428 #endif
5430 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5431 if (smp_cpus > machine->max_cpus) {
5432 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5433 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5434 machine->max_cpus);
5435 exit(1);
5438 if (nographic) {
5439 if (serial_device_index == 0)
5440 serial_devices[0] = "stdio";
5441 if (parallel_device_index == 0)
5442 parallel_devices[0] = "null";
5443 if (strncmp(monitor_device, "vc", 2) == 0)
5444 monitor_device = "stdio";
5447 #ifndef _WIN32
5448 if (daemonize) {
5449 pid_t pid;
5451 if (pipe(fds) == -1)
5452 exit(1);
5454 pid = fork();
5455 if (pid > 0) {
5456 uint8_t status;
5457 ssize_t len;
5459 close(fds[1]);
5461 again:
5462 len = read(fds[0], &status, 1);
5463 if (len == -1 && (errno == EINTR))
5464 goto again;
5466 if (len != 1)
5467 exit(1);
5468 else if (status == 1) {
5469 fprintf(stderr, "Could not acquire pidfile\n");
5470 exit(1);
5471 } else
5472 exit(0);
5473 } else if (pid < 0)
5474 exit(1);
5476 setsid();
5478 pid = fork();
5479 if (pid > 0)
5480 exit(0);
5481 else if (pid < 0)
5482 exit(1);
5484 umask(027);
5486 signal(SIGTSTP, SIG_IGN);
5487 signal(SIGTTOU, SIG_IGN);
5488 signal(SIGTTIN, SIG_IGN);
5490 #endif
5492 #if USE_KVM
5493 if (kvm_enabled()) {
5494 if (kvm_qemu_init() < 0) {
5495 extern int kvm_allowed;
5496 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5497 #ifdef NO_CPU_EMULATION
5498 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5499 exit(1);
5500 #endif
5501 kvm_allowed = 0;
5504 #endif
5506 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5507 if (daemonize) {
5508 uint8_t status = 1;
5509 write(fds[1], &status, 1);
5510 } else
5511 fprintf(stderr, "Could not acquire pid file\n");
5512 exit(1);
5515 #ifdef USE_KQEMU
5516 if (smp_cpus > 1)
5517 kqemu_allowed = 0;
5518 #endif
5519 linux_boot = (kernel_filename != NULL);
5520 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5522 if (!linux_boot && net_boot == 0 &&
5523 !machine->nodisk_ok && nb_drives_opt == 0)
5524 help(1);
5526 if (!linux_boot && *kernel_cmdline != '\0') {
5527 fprintf(stderr, "-append only allowed with -kernel option\n");
5528 exit(1);
5531 if (!linux_boot && initrd_filename != NULL) {
5532 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5533 exit(1);
5536 /* boot to floppy or the default cd if no hard disk defined yet */
5537 if (!boot_devices[0]) {
5538 boot_devices = "cad";
5540 setvbuf(stdout, NULL, _IOLBF, 0);
5542 init_timers();
5543 if (init_timer_alarm() < 0) {
5544 fprintf(stderr, "could not initialize alarm timer\n");
5545 exit(1);
5547 if (use_icount && icount_time_shift < 0) {
5548 use_icount = 2;
5549 /* 125MIPS seems a reasonable initial guess at the guest speed.
5550 It will be corrected fairly quickly anyway. */
5551 icount_time_shift = 3;
5552 init_icount_adjust();
5555 #ifdef _WIN32
5556 socket_init();
5557 #endif
5559 /* init network clients */
5560 if (nb_net_clients == 0) {
5561 /* if no clients, we use a default config */
5562 net_clients[nb_net_clients++] = "nic";
5563 #ifdef CONFIG_SLIRP
5564 net_clients[nb_net_clients++] = "user";
5565 #endif
5568 for(i = 0;i < nb_net_clients; i++) {
5569 if (net_client_parse(net_clients[i]) < 0)
5570 exit(1);
5572 net_client_check();
5574 #ifdef TARGET_I386
5575 /* XXX: this should be moved in the PC machine instantiation code */
5576 if (net_boot != 0) {
5577 int netroms = 0;
5578 for (i = 0; i < nb_nics && i < 4; i++) {
5579 const char *model = nd_table[i].model;
5580 char buf[1024];
5581 if (net_boot & (1 << i)) {
5582 if (model == NULL)
5583 model = "rtl8139";
5584 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5585 if (get_image_size(buf) > 0) {
5586 if (nb_option_roms >= MAX_OPTION_ROMS) {
5587 fprintf(stderr, "Too many option ROMs\n");
5588 exit(1);
5590 option_rom[nb_option_roms] = strdup(buf);
5591 nb_option_roms++;
5592 netroms++;
5596 if (netroms == 0) {
5597 fprintf(stderr, "No valid PXE rom found for network device\n");
5598 exit(1);
5601 #endif
5603 /* init the bluetooth world */
5604 for (i = 0; i < nb_bt_opts; i++)
5605 if (bt_parse(bt_opts[i]))
5606 exit(1);
5608 /* init the memory */
5609 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5611 if (machine->ram_require & RAMSIZE_FIXED) {
5612 if (ram_size > 0) {
5613 if (ram_size < phys_ram_size) {
5614 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5615 machine->name, (unsigned long long) phys_ram_size);
5616 exit(-1);
5619 phys_ram_size = ram_size;
5620 } else
5621 ram_size = phys_ram_size;
5622 } else {
5623 if (ram_size == 0)
5624 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5626 phys_ram_size += ram_size;
5629 /* Initialize kvm */
5630 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5631 #define KVM_EXTRA_PAGES 3
5632 #else
5633 #define KVM_EXTRA_PAGES 0
5634 #endif
5635 if (kvm_enabled()) {
5636 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5637 if (kvm_qemu_create_context() < 0) {
5638 fprintf(stderr, "Could not create KVM context\n");
5639 exit(1);
5643 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5644 if (!phys_ram_base) {
5645 fprintf(stderr, "Could not allocate physical memory\n");
5646 exit(1);
5649 /* init the dynamic translator */
5650 cpu_exec_init_all(tb_size * 1024 * 1024);
5652 bdrv_init();
5654 /* we always create the cdrom drive, even if no disk is there */
5656 if (nb_drives_opt < MAX_DRIVES)
5657 drive_add(NULL, CDROM_ALIAS);
5659 /* we always create at least one floppy */
5661 if (nb_drives_opt < MAX_DRIVES)
5662 drive_add(NULL, FD_ALIAS, 0);
5664 /* we always create one sd slot, even if no card is in it */
5666 if (nb_drives_opt < MAX_DRIVES)
5667 drive_add(NULL, SD_ALIAS);
5669 /* open the virtual block devices
5670 * note that migration with device
5671 * hot add/remove is broken.
5673 for(i = 0; i < nb_drives_opt; i++)
5674 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5675 exit(1);
5677 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5678 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5680 /* terminal init */
5681 memset(&display_state, 0, sizeof(display_state));
5682 if (nographic) {
5683 if (curses) {
5684 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5685 exit(1);
5687 /* nearly nothing to do */
5688 dumb_display_init(ds);
5689 } else if (vnc_display != NULL) {
5690 vnc_display_init(ds);
5691 if (vnc_display_open(ds, vnc_display) < 0)
5692 exit(1);
5693 } else
5694 #if defined(CONFIG_CURSES)
5695 if (curses) {
5696 curses_display_init(ds, full_screen);
5697 } else
5698 #endif
5700 #if defined(CONFIG_SDL)
5701 sdl_display_init(ds, full_screen, no_frame);
5702 #elif defined(CONFIG_COCOA)
5703 cocoa_display_init(ds, full_screen);
5704 #else
5705 dumb_display_init(ds);
5706 #endif
5709 #ifndef _WIN32
5710 /* must be after terminal init, SDL library changes signal handlers */
5711 termsig_setup();
5712 #endif
5714 /* Maintain compatibility with multiple stdio monitors */
5715 if (!strcmp(monitor_device,"stdio")) {
5716 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5717 const char *devname = serial_devices[i];
5718 if (devname && !strcmp(devname,"mon:stdio")) {
5719 monitor_device = NULL;
5720 break;
5721 } else if (devname && !strcmp(devname,"stdio")) {
5722 monitor_device = NULL;
5723 serial_devices[i] = "mon:stdio";
5724 break;
5728 if (monitor_device) {
5729 monitor_hd = qemu_chr_open("monitor", monitor_device);
5730 if (!monitor_hd) {
5731 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5732 exit(1);
5734 monitor_init(monitor_hd, !nographic);
5737 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5738 const char *devname = serial_devices[i];
5739 if (devname && strcmp(devname, "none")) {
5740 char label[32];
5741 snprintf(label, sizeof(label), "serial%d", i);
5742 serial_hds[i] = qemu_chr_open(label, devname);
5743 if (!serial_hds[i]) {
5744 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5745 devname);
5746 exit(1);
5748 if (strstart(devname, "vc", 0))
5749 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5753 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5754 const char *devname = parallel_devices[i];
5755 if (devname && strcmp(devname, "none")) {
5756 char label[32];
5757 snprintf(label, sizeof(label), "parallel%d", i);
5758 parallel_hds[i] = qemu_chr_open(label, devname);
5759 if (!parallel_hds[i]) {
5760 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5761 devname);
5762 exit(1);
5764 if (strstart(devname, "vc", 0))
5765 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5769 if (kvm_enabled())
5770 kvm_init_ap();
5772 #ifdef KVM_UPSTREAM
5773 if (kvm_enabled()) {
5774 int ret;
5776 ret = kvm_init(smp_cpus);
5777 if (ret < 0) {
5778 fprintf(stderr, "failed to initialize KVM\n");
5779 exit(1);
5782 #endif
5784 machine->init(ram_size, vga_ram_size, boot_devices, ds,
5785 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5787 current_machine = machine;
5789 /* init USB devices */
5790 if (usb_enabled) {
5791 for(i = 0; i < usb_devices_index; i++) {
5792 if (usb_device_add(usb_devices[i]) < 0) {
5793 fprintf(stderr, "Warning: could not add USB device %s\n",
5794 usb_devices[i]);
5799 if (display_state.dpy_refresh) {
5800 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5801 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5804 #ifdef CONFIG_GDBSTUB
5805 if (use_gdbstub) {
5806 /* XXX: use standard host:port notation and modify options
5807 accordingly. */
5808 if (gdbserver_start(gdbstub_port) < 0) {
5809 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5810 gdbstub_port);
5811 exit(1);
5814 #endif
5816 if (loadvm)
5817 do_loadvm(loadvm);
5819 if (incoming) {
5820 autostart = 0; /* fixme how to deal with -daemonize */
5821 qemu_start_incoming_migration(incoming);
5825 /* XXX: simplify init */
5826 read_passwords();
5827 if (autostart) {
5828 vm_start();
5832 if (daemonize) {
5833 uint8_t status = 0;
5834 ssize_t len;
5835 int fd;
5837 again1:
5838 len = write(fds[1], &status, 1);
5839 if (len == -1 && (errno == EINTR))
5840 goto again1;
5842 if (len != 1)
5843 exit(1);
5845 chdir("/");
5846 TFR(fd = open("/dev/null", O_RDWR));
5847 if (fd == -1)
5848 exit(1);
5850 dup2(fd, 0);
5851 dup2(fd, 1);
5852 dup2(fd, 2);
5854 close(fd);
5857 main_loop();
5858 quit_timers();
5859 net_cleanup();
5861 return 0;