qemu: add pci_unregister_device (Marcelo Tosatti)
[qemu/mini2440/sniper_sniper_test.git] / vl.c
blobba1e643573149065cab260638bcd5eb323472be5
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "migration.h"
43 #include "kvm.h"
44 #include "balloon.h"
46 #include <unistd.h>
47 #include <fcntl.h>
48 #include <signal.h>
49 #include <time.h>
50 #include <errno.h>
51 #include <sys/time.h>
52 #include <zlib.h>
54 #ifndef _WIN32
55 #include <sys/times.h>
56 #include <sys/wait.h>
57 #include <termios.h>
58 #include <sys/mman.h>
59 #include <sys/ioctl.h>
60 #include <sys/resource.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <net/if.h>
64 #if defined(__NetBSD__)
65 #include <net/if_tap.h>
66 #endif
67 #ifdef __linux__
68 #include <linux/if_tun.h>
69 #endif
70 #include <arpa/inet.h>
71 #include <dirent.h>
72 #include <netdb.h>
73 #include <sys/select.h>
74 #ifdef _BSD
75 #include <sys/stat.h>
76 #ifdef __FreeBSD__
77 #include <libutil.h>
78 #else
79 #include <util.h>
80 #endif
81 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
82 #include <freebsd/stdlib.h>
83 #else
84 #ifdef __linux__
85 #include <pty.h>
86 #include <malloc.h>
87 #include <linux/rtc.h>
89 /* For the benefit of older linux systems which don't supply it,
90 we use a local copy of hpet.h. */
91 /* #include <linux/hpet.h> */
92 #include "hpet.h"
94 #include <linux/ppdev.h>
95 #include <linux/parport.h>
96 #endif
97 #ifdef __sun__
98 #include <sys/stat.h>
99 #include <sys/ethernet.h>
100 #include <sys/sockio.h>
101 #include <netinet/arp.h>
102 #include <netinet/in.h>
103 #include <netinet/in_systm.h>
104 #include <netinet/ip.h>
105 #include <netinet/ip_icmp.h> // must come after ip.h
106 #include <netinet/udp.h>
107 #include <netinet/tcp.h>
108 #include <net/if.h>
109 #include <syslog.h>
110 #include <stropts.h>
111 #endif
112 #endif
113 #endif
115 #include "qemu_socket.h"
117 #if defined(CONFIG_SLIRP)
118 #include "libslirp.h"
119 #endif
121 #if defined(__OpenBSD__)
122 #include <util.h>
123 #endif
125 #if defined(CONFIG_VDE)
126 #include <libvdeplug.h>
127 #endif
129 #ifdef _WIN32
130 #include <malloc.h>
131 #include <sys/timeb.h>
132 #include <mmsystem.h>
133 #define getopt_long_only getopt_long
134 #define memalign(align, size) malloc(size)
135 #endif
137 #ifdef CONFIG_SDL
138 #ifdef __APPLE__
139 #include <SDL/SDL.h>
140 #endif
141 #endif /* CONFIG_SDL */
143 #ifdef CONFIG_COCOA
144 #undef main
145 #define main qemu_main
146 #endif /* CONFIG_COCOA */
148 #include "disas.h"
150 #include "exec-all.h"
152 //#define DEBUG_UNUSED_IOPORT
153 //#define DEBUG_IOPORT
154 //#define DEBUG_NET
155 //#define DEBUG_SLIRP
158 #ifdef DEBUG_IOPORT
159 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
160 #else
161 # define LOG_IOPORT(...) do { } while (0)
162 #endif
164 #define DEFAULT_RAM_SIZE 128
166 /* Max number of USB devices that can be specified on the commandline. */
167 #define MAX_USB_CMDLINE 8
169 /* Max number of bluetooth switches on the commandline. */
170 #define MAX_BT_CMDLINE 10
172 /* XXX: use a two level table to limit memory usage */
173 #define MAX_IOPORTS 65536
175 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
176 const char *bios_name = NULL;
177 static void *ioport_opaque[MAX_IOPORTS];
178 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
179 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 DriveInfo drives_table[MAX_DRIVES+1];
183 int nb_drives;
184 static int vga_ram_size;
185 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186 static DisplayState *display_state;
187 int nographic;
188 static int curses;
189 static int sdl;
190 const char* keyboard_layout = NULL;
191 int64_t ticks_per_sec;
192 ram_addr_t ram_size;
193 int nb_nics;
194 NICInfo nd_table[MAX_NICS];
195 int vm_running;
196 static int rtc_utc = 1;
197 static int rtc_date_offset = -1; /* -1 means no change */
198 int cirrus_vga_enabled = 1;
199 int std_vga_enabled = 0;
200 int vmsvga_enabled = 0;
201 #ifdef TARGET_SPARC
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
205 #else
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
209 #endif
210 static int full_screen = 0;
211 #ifdef CONFIG_SDL
212 static int no_frame = 0;
213 #endif
214 int no_quit = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
218 #ifdef TARGET_I386
219 int win2k_install_hack = 0;
220 int rtc_td_hack = 0;
221 #endif
222 int usb_enabled = 0;
223 int smp_cpus = 1;
224 const char *vnc_display;
225 int acpi_enabled = 1;
226 int no_hpet = 0;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 int daemonize = 0;
233 const char *option_rom[MAX_OPTION_ROMS];
234 int nb_option_roms;
235 int semihosting_enabled = 0;
236 #ifdef TARGET_ARM
237 int old_param = 0;
238 #endif
239 const char *qemu_name;
240 int alt_grab = 0;
241 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
242 unsigned int nb_prom_envs = 0;
243 const char *prom_envs[MAX_PROM_ENVS];
244 #endif
245 int nb_drives_opt;
246 struct drive_opt drives_opt[MAX_DRIVES];
248 static CPUState *cur_cpu;
249 static CPUState *next_cpu;
250 static int event_pending = 1;
251 /* Conversion factor from emulated instructions to virtual clock ticks. */
252 static int icount_time_shift;
253 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
254 #define MAX_ICOUNT_SHIFT 10
255 /* Compensate for varying guest execution speed. */
256 static int64_t qemu_icount_bias;
257 static QEMUTimer *icount_rt_timer;
258 static QEMUTimer *icount_vm_timer;
259 static QEMUTimer *nographic_timer;
261 uint8_t qemu_uuid[16];
263 /***********************************************************/
264 /* x86 ISA bus support */
266 target_phys_addr_t isa_mem_base = 0;
267 PicState2 *isa_pic;
269 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
270 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
272 static uint32_t ioport_read(int index, uint32_t address)
274 static IOPortReadFunc *default_func[3] = {
275 default_ioport_readb,
276 default_ioport_readw,
277 default_ioport_readl
279 IOPortReadFunc *func = ioport_read_table[index][address];
280 if (!func)
281 func = default_func[index];
282 return func(ioport_opaque[address], address);
285 static void ioport_write(int index, uint32_t address, uint32_t data)
287 static IOPortWriteFunc *default_func[3] = {
288 default_ioport_writeb,
289 default_ioport_writew,
290 default_ioport_writel
292 IOPortWriteFunc *func = ioport_write_table[index][address];
293 if (!func)
294 func = default_func[index];
295 func(ioport_opaque[address], address, data);
298 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
300 #ifdef DEBUG_UNUSED_IOPORT
301 fprintf(stderr, "unused inb: port=0x%04x\n", address);
302 #endif
303 return 0xff;
306 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
308 #ifdef DEBUG_UNUSED_IOPORT
309 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
310 #endif
313 /* default is to make two byte accesses */
314 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
316 uint32_t data;
317 data = ioport_read(0, address);
318 address = (address + 1) & (MAX_IOPORTS - 1);
319 data |= ioport_read(0, address) << 8;
320 return data;
323 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
325 ioport_write(0, address, data & 0xff);
326 address = (address + 1) & (MAX_IOPORTS - 1);
327 ioport_write(0, address, (data >> 8) & 0xff);
330 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
332 #ifdef DEBUG_UNUSED_IOPORT
333 fprintf(stderr, "unused inl: port=0x%04x\n", address);
334 #endif
335 return 0xffffffff;
338 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
340 #ifdef DEBUG_UNUSED_IOPORT
341 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
342 #endif
345 /* size is the word size in byte */
346 int register_ioport_read(int start, int length, int size,
347 IOPortReadFunc *func, void *opaque)
349 int i, bsize;
351 if (size == 1) {
352 bsize = 0;
353 } else if (size == 2) {
354 bsize = 1;
355 } else if (size == 4) {
356 bsize = 2;
357 } else {
358 hw_error("register_ioport_read: invalid size");
359 return -1;
361 for(i = start; i < start + length; i += size) {
362 ioport_read_table[bsize][i] = func;
363 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
364 hw_error("register_ioport_read: invalid opaque");
365 ioport_opaque[i] = opaque;
367 return 0;
370 /* size is the word size in byte */
371 int register_ioport_write(int start, int length, int size,
372 IOPortWriteFunc *func, void *opaque)
374 int i, bsize;
376 if (size == 1) {
377 bsize = 0;
378 } else if (size == 2) {
379 bsize = 1;
380 } else if (size == 4) {
381 bsize = 2;
382 } else {
383 hw_error("register_ioport_write: invalid size");
384 return -1;
386 for(i = start; i < start + length; i += size) {
387 ioport_write_table[bsize][i] = func;
388 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
389 hw_error("register_ioport_write: invalid opaque");
390 ioport_opaque[i] = opaque;
392 return 0;
395 void isa_unassign_ioport(int start, int length)
397 int i;
399 for(i = start; i < start + length; i++) {
400 ioport_read_table[0][i] = default_ioport_readb;
401 ioport_read_table[1][i] = default_ioport_readw;
402 ioport_read_table[2][i] = default_ioport_readl;
404 ioport_write_table[0][i] = default_ioport_writeb;
405 ioport_write_table[1][i] = default_ioport_writew;
406 ioport_write_table[2][i] = default_ioport_writel;
410 /***********************************************************/
412 void cpu_outb(CPUState *env, int addr, int val)
414 LOG_IOPORT("outb: %04x %02x\n", addr, val);
415 ioport_write(0, addr, val);
416 #ifdef USE_KQEMU
417 if (env)
418 env->last_io_time = cpu_get_time_fast();
419 #endif
422 void cpu_outw(CPUState *env, int addr, int val)
424 LOG_IOPORT("outw: %04x %04x\n", addr, val);
425 ioport_write(1, addr, val);
426 #ifdef USE_KQEMU
427 if (env)
428 env->last_io_time = cpu_get_time_fast();
429 #endif
432 void cpu_outl(CPUState *env, int addr, int val)
434 LOG_IOPORT("outl: %04x %08x\n", addr, val);
435 ioport_write(2, addr, val);
436 #ifdef USE_KQEMU
437 if (env)
438 env->last_io_time = cpu_get_time_fast();
439 #endif
442 int cpu_inb(CPUState *env, int addr)
444 int val;
445 val = ioport_read(0, addr);
446 LOG_IOPORT("inb : %04x %02x\n", addr, val);
447 #ifdef USE_KQEMU
448 if (env)
449 env->last_io_time = cpu_get_time_fast();
450 #endif
451 return val;
454 int cpu_inw(CPUState *env, int addr)
456 int val;
457 val = ioport_read(1, addr);
458 LOG_IOPORT("inw : %04x %04x\n", addr, val);
459 #ifdef USE_KQEMU
460 if (env)
461 env->last_io_time = cpu_get_time_fast();
462 #endif
463 return val;
466 int cpu_inl(CPUState *env, int addr)
468 int val;
469 val = ioport_read(2, addr);
470 LOG_IOPORT("inl : %04x %08x\n", addr, val);
471 #ifdef USE_KQEMU
472 if (env)
473 env->last_io_time = cpu_get_time_fast();
474 #endif
475 return val;
478 /***********************************************************/
479 void hw_error(const char *fmt, ...)
481 va_list ap;
482 CPUState *env;
484 va_start(ap, fmt);
485 fprintf(stderr, "qemu: hardware error: ");
486 vfprintf(stderr, fmt, ap);
487 fprintf(stderr, "\n");
488 for(env = first_cpu; env != NULL; env = env->next_cpu) {
489 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
490 #ifdef TARGET_I386
491 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
492 #else
493 cpu_dump_state(env, stderr, fprintf, 0);
494 #endif
496 va_end(ap);
497 abort();
500 /***************/
501 /* ballooning */
503 static QEMUBalloonEvent *qemu_balloon_event;
504 void *qemu_balloon_event_opaque;
506 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
508 qemu_balloon_event = func;
509 qemu_balloon_event_opaque = opaque;
512 void qemu_balloon(ram_addr_t target)
514 if (qemu_balloon_event)
515 qemu_balloon_event(qemu_balloon_event_opaque, target);
518 ram_addr_t qemu_balloon_status(void)
520 if (qemu_balloon_event)
521 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
522 return 0;
525 /***********************************************************/
526 /* keyboard/mouse */
528 static QEMUPutKBDEvent *qemu_put_kbd_event;
529 static void *qemu_put_kbd_event_opaque;
530 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
531 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
533 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
535 qemu_put_kbd_event_opaque = opaque;
536 qemu_put_kbd_event = func;
539 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
540 void *opaque, int absolute,
541 const char *name)
543 QEMUPutMouseEntry *s, *cursor;
545 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
547 s->qemu_put_mouse_event = func;
548 s->qemu_put_mouse_event_opaque = opaque;
549 s->qemu_put_mouse_event_absolute = absolute;
550 s->qemu_put_mouse_event_name = qemu_strdup(name);
551 s->next = NULL;
553 if (!qemu_put_mouse_event_head) {
554 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
555 return s;
558 cursor = qemu_put_mouse_event_head;
559 while (cursor->next != NULL)
560 cursor = cursor->next;
562 cursor->next = s;
563 qemu_put_mouse_event_current = s;
565 return s;
568 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
570 QEMUPutMouseEntry *prev = NULL, *cursor;
572 if (!qemu_put_mouse_event_head || entry == NULL)
573 return;
575 cursor = qemu_put_mouse_event_head;
576 while (cursor != NULL && cursor != entry) {
577 prev = cursor;
578 cursor = cursor->next;
581 if (cursor == NULL) // does not exist or list empty
582 return;
583 else if (prev == NULL) { // entry is head
584 qemu_put_mouse_event_head = cursor->next;
585 if (qemu_put_mouse_event_current == entry)
586 qemu_put_mouse_event_current = cursor->next;
587 qemu_free(entry->qemu_put_mouse_event_name);
588 qemu_free(entry);
589 return;
592 prev->next = entry->next;
594 if (qemu_put_mouse_event_current == entry)
595 qemu_put_mouse_event_current = prev;
597 qemu_free(entry->qemu_put_mouse_event_name);
598 qemu_free(entry);
601 void kbd_put_keycode(int keycode)
603 if (qemu_put_kbd_event) {
604 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
608 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
610 QEMUPutMouseEvent *mouse_event;
611 void *mouse_event_opaque;
612 int width;
614 if (!qemu_put_mouse_event_current) {
615 return;
618 mouse_event =
619 qemu_put_mouse_event_current->qemu_put_mouse_event;
620 mouse_event_opaque =
621 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
623 if (mouse_event) {
624 if (graphic_rotate) {
625 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
626 width = 0x7fff;
627 else
628 width = graphic_width - 1;
629 mouse_event(mouse_event_opaque,
630 width - dy, dx, dz, buttons_state);
631 } else
632 mouse_event(mouse_event_opaque,
633 dx, dy, dz, buttons_state);
637 int kbd_mouse_is_absolute(void)
639 if (!qemu_put_mouse_event_current)
640 return 0;
642 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
645 void do_info_mice(void)
647 QEMUPutMouseEntry *cursor;
648 int index = 0;
650 if (!qemu_put_mouse_event_head) {
651 term_printf("No mouse devices connected\n");
652 return;
655 term_printf("Mouse devices available:\n");
656 cursor = qemu_put_mouse_event_head;
657 while (cursor != NULL) {
658 term_printf("%c Mouse #%d: %s\n",
659 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
660 index, cursor->qemu_put_mouse_event_name);
661 index++;
662 cursor = cursor->next;
666 void do_mouse_set(int index)
668 QEMUPutMouseEntry *cursor;
669 int i = 0;
671 if (!qemu_put_mouse_event_head) {
672 term_printf("No mouse devices connected\n");
673 return;
676 cursor = qemu_put_mouse_event_head;
677 while (cursor != NULL && index != i) {
678 i++;
679 cursor = cursor->next;
682 if (cursor != NULL)
683 qemu_put_mouse_event_current = cursor;
684 else
685 term_printf("Mouse at given index not found\n");
688 /* compute with 96 bit intermediate result: (a*b)/c */
689 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
691 union {
692 uint64_t ll;
693 struct {
694 #ifdef WORDS_BIGENDIAN
695 uint32_t high, low;
696 #else
697 uint32_t low, high;
698 #endif
699 } l;
700 } u, res;
701 uint64_t rl, rh;
703 u.ll = a;
704 rl = (uint64_t)u.l.low * (uint64_t)b;
705 rh = (uint64_t)u.l.high * (uint64_t)b;
706 rh += (rl >> 32);
707 res.l.high = rh / c;
708 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
709 return res.ll;
712 /***********************************************************/
713 /* real time host monotonic timer */
715 #define QEMU_TIMER_BASE 1000000000LL
717 #ifdef WIN32
719 static int64_t clock_freq;
721 static void init_get_clock(void)
723 LARGE_INTEGER freq;
724 int ret;
725 ret = QueryPerformanceFrequency(&freq);
726 if (ret == 0) {
727 fprintf(stderr, "Could not calibrate ticks\n");
728 exit(1);
730 clock_freq = freq.QuadPart;
733 static int64_t get_clock(void)
735 LARGE_INTEGER ti;
736 QueryPerformanceCounter(&ti);
737 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
740 #else
742 static int use_rt_clock;
744 static void init_get_clock(void)
746 use_rt_clock = 0;
747 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
749 struct timespec ts;
750 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
751 use_rt_clock = 1;
754 #endif
757 static int64_t get_clock(void)
759 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
760 if (use_rt_clock) {
761 struct timespec ts;
762 clock_gettime(CLOCK_MONOTONIC, &ts);
763 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
764 } else
765 #endif
767 /* XXX: using gettimeofday leads to problems if the date
768 changes, so it should be avoided. */
769 struct timeval tv;
770 gettimeofday(&tv, NULL);
771 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
774 #endif
776 /* Return the virtual CPU time, based on the instruction counter. */
777 static int64_t cpu_get_icount(void)
779 int64_t icount;
780 CPUState *env = cpu_single_env;;
781 icount = qemu_icount;
782 if (env) {
783 if (!can_do_io(env))
784 fprintf(stderr, "Bad clock read\n");
785 icount -= (env->icount_decr.u16.low + env->icount_extra);
787 return qemu_icount_bias + (icount << icount_time_shift);
790 /***********************************************************/
791 /* guest cycle counter */
793 static int64_t cpu_ticks_prev;
794 static int64_t cpu_ticks_offset;
795 static int64_t cpu_clock_offset;
796 static int cpu_ticks_enabled;
798 /* return the host CPU cycle counter and handle stop/restart */
799 int64_t cpu_get_ticks(void)
801 if (use_icount) {
802 return cpu_get_icount();
804 if (!cpu_ticks_enabled) {
805 return cpu_ticks_offset;
806 } else {
807 int64_t ticks;
808 ticks = cpu_get_real_ticks();
809 if (cpu_ticks_prev > ticks) {
810 /* Note: non increasing ticks may happen if the host uses
811 software suspend */
812 cpu_ticks_offset += cpu_ticks_prev - ticks;
814 cpu_ticks_prev = ticks;
815 return ticks + cpu_ticks_offset;
819 /* return the host CPU monotonic timer and handle stop/restart */
820 static int64_t cpu_get_clock(void)
822 int64_t ti;
823 if (!cpu_ticks_enabled) {
824 return cpu_clock_offset;
825 } else {
826 ti = get_clock();
827 return ti + cpu_clock_offset;
831 /* enable cpu_get_ticks() */
832 void cpu_enable_ticks(void)
834 if (!cpu_ticks_enabled) {
835 cpu_ticks_offset -= cpu_get_real_ticks();
836 cpu_clock_offset -= get_clock();
837 cpu_ticks_enabled = 1;
841 /* disable cpu_get_ticks() : the clock is stopped. You must not call
842 cpu_get_ticks() after that. */
843 void cpu_disable_ticks(void)
845 if (cpu_ticks_enabled) {
846 cpu_ticks_offset = cpu_get_ticks();
847 cpu_clock_offset = cpu_get_clock();
848 cpu_ticks_enabled = 0;
852 /***********************************************************/
853 /* timers */
855 #define QEMU_TIMER_REALTIME 0
856 #define QEMU_TIMER_VIRTUAL 1
858 struct QEMUClock {
859 int type;
860 /* XXX: add frequency */
863 struct QEMUTimer {
864 QEMUClock *clock;
865 int64_t expire_time;
866 QEMUTimerCB *cb;
867 void *opaque;
868 struct QEMUTimer *next;
871 struct qemu_alarm_timer {
872 char const *name;
873 unsigned int flags;
875 int (*start)(struct qemu_alarm_timer *t);
876 void (*stop)(struct qemu_alarm_timer *t);
877 void (*rearm)(struct qemu_alarm_timer *t);
878 void *priv;
881 #define ALARM_FLAG_DYNTICKS 0x1
882 #define ALARM_FLAG_EXPIRED 0x2
884 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
886 return t->flags & ALARM_FLAG_DYNTICKS;
889 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
891 if (!alarm_has_dynticks(t))
892 return;
894 t->rearm(t);
897 /* TODO: MIN_TIMER_REARM_US should be optimized */
898 #define MIN_TIMER_REARM_US 250
900 static struct qemu_alarm_timer *alarm_timer;
901 #ifndef _WIN32
902 static int alarm_timer_rfd, alarm_timer_wfd;
903 #endif
905 #ifdef _WIN32
907 struct qemu_alarm_win32 {
908 MMRESULT timerId;
909 HANDLE host_alarm;
910 unsigned int period;
911 } alarm_win32_data = {0, NULL, -1};
913 static int win32_start_timer(struct qemu_alarm_timer *t);
914 static void win32_stop_timer(struct qemu_alarm_timer *t);
915 static void win32_rearm_timer(struct qemu_alarm_timer *t);
917 #else
919 static int unix_start_timer(struct qemu_alarm_timer *t);
920 static void unix_stop_timer(struct qemu_alarm_timer *t);
922 #ifdef __linux__
924 static int dynticks_start_timer(struct qemu_alarm_timer *t);
925 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
926 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
928 static int hpet_start_timer(struct qemu_alarm_timer *t);
929 static void hpet_stop_timer(struct qemu_alarm_timer *t);
931 static int rtc_start_timer(struct qemu_alarm_timer *t);
932 static void rtc_stop_timer(struct qemu_alarm_timer *t);
934 #endif /* __linux__ */
936 #endif /* _WIN32 */
938 /* Correlation between real and virtual time is always going to be
939 fairly approximate, so ignore small variation.
940 When the guest is idle real and virtual time will be aligned in
941 the IO wait loop. */
942 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
944 static void icount_adjust(void)
946 int64_t cur_time;
947 int64_t cur_icount;
948 int64_t delta;
949 static int64_t last_delta;
950 /* If the VM is not running, then do nothing. */
951 if (!vm_running)
952 return;
954 cur_time = cpu_get_clock();
955 cur_icount = qemu_get_clock(vm_clock);
956 delta = cur_icount - cur_time;
957 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
958 if (delta > 0
959 && last_delta + ICOUNT_WOBBLE < delta * 2
960 && icount_time_shift > 0) {
961 /* The guest is getting too far ahead. Slow time down. */
962 icount_time_shift--;
964 if (delta < 0
965 && last_delta - ICOUNT_WOBBLE > delta * 2
966 && icount_time_shift < MAX_ICOUNT_SHIFT) {
967 /* The guest is getting too far behind. Speed time up. */
968 icount_time_shift++;
970 last_delta = delta;
971 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
974 static void icount_adjust_rt(void * opaque)
976 qemu_mod_timer(icount_rt_timer,
977 qemu_get_clock(rt_clock) + 1000);
978 icount_adjust();
981 static void icount_adjust_vm(void * opaque)
983 qemu_mod_timer(icount_vm_timer,
984 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
985 icount_adjust();
988 static void init_icount_adjust(void)
990 /* Have both realtime and virtual time triggers for speed adjustment.
991 The realtime trigger catches emulated time passing too slowly,
992 the virtual time trigger catches emulated time passing too fast.
993 Realtime triggers occur even when idle, so use them less frequently
994 than VM triggers. */
995 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
996 qemu_mod_timer(icount_rt_timer,
997 qemu_get_clock(rt_clock) + 1000);
998 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
999 qemu_mod_timer(icount_vm_timer,
1000 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1003 static struct qemu_alarm_timer alarm_timers[] = {
1004 #ifndef _WIN32
1005 #ifdef __linux__
1006 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1007 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1008 /* HPET - if available - is preferred */
1009 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1010 /* ...otherwise try RTC */
1011 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1012 #endif
1013 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1014 #else
1015 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1016 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1017 {"win32", 0, win32_start_timer,
1018 win32_stop_timer, NULL, &alarm_win32_data},
1019 #endif
1020 {NULL, }
1023 static void show_available_alarms(void)
1025 int i;
1027 printf("Available alarm timers, in order of precedence:\n");
1028 for (i = 0; alarm_timers[i].name; i++)
1029 printf("%s\n", alarm_timers[i].name);
1032 static void configure_alarms(char const *opt)
1034 int i;
1035 int cur = 0;
1036 int count = ARRAY_SIZE(alarm_timers) - 1;
1037 char *arg;
1038 char *name;
1039 struct qemu_alarm_timer tmp;
1041 if (!strcmp(opt, "?")) {
1042 show_available_alarms();
1043 exit(0);
1046 arg = strdup(opt);
1048 /* Reorder the array */
1049 name = strtok(arg, ",");
1050 while (name) {
1051 for (i = 0; i < count && alarm_timers[i].name; i++) {
1052 if (!strcmp(alarm_timers[i].name, name))
1053 break;
1056 if (i == count) {
1057 fprintf(stderr, "Unknown clock %s\n", name);
1058 goto next;
1061 if (i < cur)
1062 /* Ignore */
1063 goto next;
1065 /* Swap */
1066 tmp = alarm_timers[i];
1067 alarm_timers[i] = alarm_timers[cur];
1068 alarm_timers[cur] = tmp;
1070 cur++;
1071 next:
1072 name = strtok(NULL, ",");
1075 free(arg);
1077 if (cur) {
1078 /* Disable remaining timers */
1079 for (i = cur; i < count; i++)
1080 alarm_timers[i].name = NULL;
1081 } else {
1082 show_available_alarms();
1083 exit(1);
1087 QEMUClock *rt_clock;
1088 QEMUClock *vm_clock;
1090 static QEMUTimer *active_timers[2];
1092 static QEMUClock *qemu_new_clock(int type)
1094 QEMUClock *clock;
1095 clock = qemu_mallocz(sizeof(QEMUClock));
1096 clock->type = type;
1097 return clock;
1100 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1102 QEMUTimer *ts;
1104 ts = qemu_mallocz(sizeof(QEMUTimer));
1105 ts->clock = clock;
1106 ts->cb = cb;
1107 ts->opaque = opaque;
1108 return ts;
1111 void qemu_free_timer(QEMUTimer *ts)
1113 qemu_free(ts);
1116 /* stop a timer, but do not dealloc it */
1117 void qemu_del_timer(QEMUTimer *ts)
1119 QEMUTimer **pt, *t;
1121 /* NOTE: this code must be signal safe because
1122 qemu_timer_expired() can be called from a signal. */
1123 pt = &active_timers[ts->clock->type];
1124 for(;;) {
1125 t = *pt;
1126 if (!t)
1127 break;
1128 if (t == ts) {
1129 *pt = t->next;
1130 break;
1132 pt = &t->next;
1136 /* modify the current timer so that it will be fired when current_time
1137 >= expire_time. The corresponding callback will be called. */
1138 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1140 QEMUTimer **pt, *t;
1142 qemu_del_timer(ts);
1144 /* add the timer in the sorted list */
1145 /* NOTE: this code must be signal safe because
1146 qemu_timer_expired() can be called from a signal. */
1147 pt = &active_timers[ts->clock->type];
1148 for(;;) {
1149 t = *pt;
1150 if (!t)
1151 break;
1152 if (t->expire_time > expire_time)
1153 break;
1154 pt = &t->next;
1156 ts->expire_time = expire_time;
1157 ts->next = *pt;
1158 *pt = ts;
1160 /* Rearm if necessary */
1161 if (pt == &active_timers[ts->clock->type]) {
1162 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1163 qemu_rearm_alarm_timer(alarm_timer);
1165 /* Interrupt execution to force deadline recalculation. */
1166 if (use_icount && cpu_single_env) {
1167 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1172 int qemu_timer_pending(QEMUTimer *ts)
1174 QEMUTimer *t;
1175 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1176 if (t == ts)
1177 return 1;
1179 return 0;
1182 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1184 if (!timer_head)
1185 return 0;
1186 return (timer_head->expire_time <= current_time);
1189 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1191 QEMUTimer *ts;
1193 for(;;) {
1194 ts = *ptimer_head;
1195 if (!ts || ts->expire_time > current_time)
1196 break;
1197 /* remove timer from the list before calling the callback */
1198 *ptimer_head = ts->next;
1199 ts->next = NULL;
1201 /* run the callback (the timer list can be modified) */
1202 ts->cb(ts->opaque);
1206 int64_t qemu_get_clock(QEMUClock *clock)
1208 switch(clock->type) {
1209 case QEMU_TIMER_REALTIME:
1210 return get_clock() / 1000000;
1211 default:
1212 case QEMU_TIMER_VIRTUAL:
1213 if (use_icount) {
1214 return cpu_get_icount();
1215 } else {
1216 return cpu_get_clock();
1221 static void init_timers(void)
1223 init_get_clock();
1224 ticks_per_sec = QEMU_TIMER_BASE;
1225 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1226 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1229 /* save a timer */
1230 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1232 uint64_t expire_time;
1234 if (qemu_timer_pending(ts)) {
1235 expire_time = ts->expire_time;
1236 } else {
1237 expire_time = -1;
1239 qemu_put_be64(f, expire_time);
1242 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1244 uint64_t expire_time;
1246 expire_time = qemu_get_be64(f);
1247 if (expire_time != -1) {
1248 qemu_mod_timer(ts, expire_time);
1249 } else {
1250 qemu_del_timer(ts);
1254 static void timer_save(QEMUFile *f, void *opaque)
1256 if (cpu_ticks_enabled) {
1257 hw_error("cannot save state if virtual timers are running");
1259 qemu_put_be64(f, cpu_ticks_offset);
1260 qemu_put_be64(f, ticks_per_sec);
1261 qemu_put_be64(f, cpu_clock_offset);
1264 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1266 if (version_id != 1 && version_id != 2)
1267 return -EINVAL;
1268 if (cpu_ticks_enabled) {
1269 return -EINVAL;
1271 cpu_ticks_offset=qemu_get_be64(f);
1272 ticks_per_sec=qemu_get_be64(f);
1273 if (version_id == 2) {
1274 cpu_clock_offset=qemu_get_be64(f);
1276 return 0;
1279 #ifdef _WIN32
1280 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1281 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1282 #else
1283 static void host_alarm_handler(int host_signum)
1284 #endif
1286 #if 0
1287 #define DISP_FREQ 1000
1289 static int64_t delta_min = INT64_MAX;
1290 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1291 static int count;
1292 ti = qemu_get_clock(vm_clock);
1293 if (last_clock != 0) {
1294 delta = ti - last_clock;
1295 if (delta < delta_min)
1296 delta_min = delta;
1297 if (delta > delta_max)
1298 delta_max = delta;
1299 delta_cum += delta;
1300 if (++count == DISP_FREQ) {
1301 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1302 muldiv64(delta_min, 1000000, ticks_per_sec),
1303 muldiv64(delta_max, 1000000, ticks_per_sec),
1304 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1305 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1306 count = 0;
1307 delta_min = INT64_MAX;
1308 delta_max = 0;
1309 delta_cum = 0;
1312 last_clock = ti;
1314 #endif
1315 if (alarm_has_dynticks(alarm_timer) ||
1316 (!use_icount &&
1317 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1318 qemu_get_clock(vm_clock))) ||
1319 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1320 qemu_get_clock(rt_clock))) {
1321 CPUState *env = next_cpu;
1323 #ifdef _WIN32
1324 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1325 SetEvent(data->host_alarm);
1326 #else
1327 static const char byte = 0;
1328 write(alarm_timer_wfd, &byte, sizeof(byte));
1329 #endif
1330 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1332 if (env) {
1333 /* stop the currently executing cpu because a timer occured */
1334 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1335 #ifdef USE_KQEMU
1336 if (env->kqemu_enabled) {
1337 kqemu_cpu_interrupt(env);
1339 #endif
1341 event_pending = 1;
1345 static int64_t qemu_next_deadline(void)
1347 int64_t delta;
1349 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1350 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1351 qemu_get_clock(vm_clock);
1352 } else {
1353 /* To avoid problems with overflow limit this to 2^32. */
1354 delta = INT32_MAX;
1357 if (delta < 0)
1358 delta = 0;
1360 return delta;
1363 #if defined(__linux__) || defined(_WIN32)
1364 static uint64_t qemu_next_deadline_dyntick(void)
1366 int64_t delta;
1367 int64_t rtdelta;
1369 if (use_icount)
1370 delta = INT32_MAX;
1371 else
1372 delta = (qemu_next_deadline() + 999) / 1000;
1374 if (active_timers[QEMU_TIMER_REALTIME]) {
1375 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1376 qemu_get_clock(rt_clock))*1000;
1377 if (rtdelta < delta)
1378 delta = rtdelta;
1381 if (delta < MIN_TIMER_REARM_US)
1382 delta = MIN_TIMER_REARM_US;
1384 return delta;
1386 #endif
1388 #ifndef _WIN32
1390 /* Sets a specific flag */
1391 static int fcntl_setfl(int fd, int flag)
1393 int flags;
1395 flags = fcntl(fd, F_GETFL);
1396 if (flags == -1)
1397 return -errno;
1399 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1400 return -errno;
1402 return 0;
1405 #if defined(__linux__)
1407 #define RTC_FREQ 1024
1409 static void enable_sigio_timer(int fd)
1411 struct sigaction act;
1413 /* timer signal */
1414 sigfillset(&act.sa_mask);
1415 act.sa_flags = 0;
1416 act.sa_handler = host_alarm_handler;
1418 sigaction(SIGIO, &act, NULL);
1419 fcntl_setfl(fd, O_ASYNC);
1420 fcntl(fd, F_SETOWN, getpid());
1423 static int hpet_start_timer(struct qemu_alarm_timer *t)
1425 struct hpet_info info;
1426 int r, fd;
1428 fd = open("/dev/hpet", O_RDONLY);
1429 if (fd < 0)
1430 return -1;
1432 /* Set frequency */
1433 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1434 if (r < 0) {
1435 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1436 "error, but for better emulation accuracy type:\n"
1437 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1438 goto fail;
1441 /* Check capabilities */
1442 r = ioctl(fd, HPET_INFO, &info);
1443 if (r < 0)
1444 goto fail;
1446 /* Enable periodic mode */
1447 r = ioctl(fd, HPET_EPI, 0);
1448 if (info.hi_flags && (r < 0))
1449 goto fail;
1451 /* Enable interrupt */
1452 r = ioctl(fd, HPET_IE_ON, 0);
1453 if (r < 0)
1454 goto fail;
1456 enable_sigio_timer(fd);
1457 t->priv = (void *)(long)fd;
1459 return 0;
1460 fail:
1461 close(fd);
1462 return -1;
1465 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1467 int fd = (long)t->priv;
1469 close(fd);
1472 static int rtc_start_timer(struct qemu_alarm_timer *t)
1474 int rtc_fd;
1475 unsigned long current_rtc_freq = 0;
1477 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1478 if (rtc_fd < 0)
1479 return -1;
1480 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1481 if (current_rtc_freq != RTC_FREQ &&
1482 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1483 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1484 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1485 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1486 goto fail;
1488 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1489 fail:
1490 close(rtc_fd);
1491 return -1;
1494 enable_sigio_timer(rtc_fd);
1496 t->priv = (void *)(long)rtc_fd;
1498 return 0;
1501 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1503 int rtc_fd = (long)t->priv;
1505 close(rtc_fd);
1508 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1510 struct sigevent ev;
1511 timer_t host_timer;
1512 struct sigaction act;
1514 sigfillset(&act.sa_mask);
1515 act.sa_flags = 0;
1516 act.sa_handler = host_alarm_handler;
1518 sigaction(SIGALRM, &act, NULL);
1520 ev.sigev_value.sival_int = 0;
1521 ev.sigev_notify = SIGEV_SIGNAL;
1522 ev.sigev_signo = SIGALRM;
1524 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1525 perror("timer_create");
1527 /* disable dynticks */
1528 fprintf(stderr, "Dynamic Ticks disabled\n");
1530 return -1;
1533 t->priv = (void *)(long)host_timer;
1535 return 0;
1538 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1540 timer_t host_timer = (timer_t)(long)t->priv;
1542 timer_delete(host_timer);
1545 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1547 timer_t host_timer = (timer_t)(long)t->priv;
1548 struct itimerspec timeout;
1549 int64_t nearest_delta_us = INT64_MAX;
1550 int64_t current_us;
1552 if (!active_timers[QEMU_TIMER_REALTIME] &&
1553 !active_timers[QEMU_TIMER_VIRTUAL])
1554 return;
1556 nearest_delta_us = qemu_next_deadline_dyntick();
1558 /* check whether a timer is already running */
1559 if (timer_gettime(host_timer, &timeout)) {
1560 perror("gettime");
1561 fprintf(stderr, "Internal timer error: aborting\n");
1562 exit(1);
1564 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1565 if (current_us && current_us <= nearest_delta_us)
1566 return;
1568 timeout.it_interval.tv_sec = 0;
1569 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1570 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1571 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1572 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1573 perror("settime");
1574 fprintf(stderr, "Internal timer error: aborting\n");
1575 exit(1);
1579 #endif /* defined(__linux__) */
1581 static int unix_start_timer(struct qemu_alarm_timer *t)
1583 struct sigaction act;
1584 struct itimerval itv;
1585 int err;
1587 /* timer signal */
1588 sigfillset(&act.sa_mask);
1589 act.sa_flags = 0;
1590 act.sa_handler = host_alarm_handler;
1592 sigaction(SIGALRM, &act, NULL);
1594 itv.it_interval.tv_sec = 0;
1595 /* for i386 kernel 2.6 to get 1 ms */
1596 itv.it_interval.tv_usec = 999;
1597 itv.it_value.tv_sec = 0;
1598 itv.it_value.tv_usec = 10 * 1000;
1600 err = setitimer(ITIMER_REAL, &itv, NULL);
1601 if (err)
1602 return -1;
1604 return 0;
1607 static void unix_stop_timer(struct qemu_alarm_timer *t)
1609 struct itimerval itv;
1611 memset(&itv, 0, sizeof(itv));
1612 setitimer(ITIMER_REAL, &itv, NULL);
1615 #endif /* !defined(_WIN32) */
1617 static void try_to_rearm_timer(void *opaque)
1619 struct qemu_alarm_timer *t = opaque;
1620 #ifndef _WIN32
1621 ssize_t len;
1623 /* Drain the notify pipe */
1624 do {
1625 char buffer[512];
1626 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1627 } while ((len == -1 && errno == EINTR) || len > 0);
1628 #endif
1630 if (t->flags & ALARM_FLAG_EXPIRED) {
1631 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1632 qemu_rearm_alarm_timer(alarm_timer);
1636 #ifdef _WIN32
1638 static int win32_start_timer(struct qemu_alarm_timer *t)
1640 TIMECAPS tc;
1641 struct qemu_alarm_win32 *data = t->priv;
1642 UINT flags;
1644 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1645 if (!data->host_alarm) {
1646 perror("Failed CreateEvent");
1647 return -1;
1650 memset(&tc, 0, sizeof(tc));
1651 timeGetDevCaps(&tc, sizeof(tc));
1653 if (data->period < tc.wPeriodMin)
1654 data->period = tc.wPeriodMin;
1656 timeBeginPeriod(data->period);
1658 flags = TIME_CALLBACK_FUNCTION;
1659 if (alarm_has_dynticks(t))
1660 flags |= TIME_ONESHOT;
1661 else
1662 flags |= TIME_PERIODIC;
1664 data->timerId = timeSetEvent(1, // interval (ms)
1665 data->period, // resolution
1666 host_alarm_handler, // function
1667 (DWORD)t, // parameter
1668 flags);
1670 if (!data->timerId) {
1671 perror("Failed to initialize win32 alarm timer");
1673 timeEndPeriod(data->period);
1674 CloseHandle(data->host_alarm);
1675 return -1;
1678 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1680 return 0;
1683 static void win32_stop_timer(struct qemu_alarm_timer *t)
1685 struct qemu_alarm_win32 *data = t->priv;
1687 timeKillEvent(data->timerId);
1688 timeEndPeriod(data->period);
1690 CloseHandle(data->host_alarm);
1693 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1695 struct qemu_alarm_win32 *data = t->priv;
1696 uint64_t nearest_delta_us;
1698 if (!active_timers[QEMU_TIMER_REALTIME] &&
1699 !active_timers[QEMU_TIMER_VIRTUAL])
1700 return;
1702 nearest_delta_us = qemu_next_deadline_dyntick();
1703 nearest_delta_us /= 1000;
1705 timeKillEvent(data->timerId);
1707 data->timerId = timeSetEvent(1,
1708 data->period,
1709 host_alarm_handler,
1710 (DWORD)t,
1711 TIME_ONESHOT | TIME_PERIODIC);
1713 if (!data->timerId) {
1714 perror("Failed to re-arm win32 alarm timer");
1716 timeEndPeriod(data->period);
1717 CloseHandle(data->host_alarm);
1718 exit(1);
1722 #endif /* _WIN32 */
1724 static int init_timer_alarm(void)
1726 struct qemu_alarm_timer *t = NULL;
1727 int i, err = -1;
1729 #ifndef _WIN32
1730 int fds[2];
1732 err = pipe(fds);
1733 if (err == -1)
1734 return -errno;
1736 err = fcntl_setfl(fds[0], O_NONBLOCK);
1737 if (err < 0)
1738 goto fail;
1740 err = fcntl_setfl(fds[1], O_NONBLOCK);
1741 if (err < 0)
1742 goto fail;
1744 alarm_timer_rfd = fds[0];
1745 alarm_timer_wfd = fds[1];
1746 #endif
1748 for (i = 0; alarm_timers[i].name; i++) {
1749 t = &alarm_timers[i];
1751 err = t->start(t);
1752 if (!err)
1753 break;
1756 if (err) {
1757 err = -ENOENT;
1758 goto fail;
1761 #ifndef _WIN32
1762 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1763 try_to_rearm_timer, NULL, t);
1764 #endif
1766 alarm_timer = t;
1768 return 0;
1770 fail:
1771 #ifndef _WIN32
1772 close(fds[0]);
1773 close(fds[1]);
1774 #endif
1775 return err;
1778 static void quit_timers(void)
1780 alarm_timer->stop(alarm_timer);
1781 alarm_timer = NULL;
1784 /***********************************************************/
1785 /* host time/date access */
1786 void qemu_get_timedate(struct tm *tm, int offset)
1788 time_t ti;
1789 struct tm *ret;
1791 time(&ti);
1792 ti += offset;
1793 if (rtc_date_offset == -1) {
1794 if (rtc_utc)
1795 ret = gmtime(&ti);
1796 else
1797 ret = localtime(&ti);
1798 } else {
1799 ti -= rtc_date_offset;
1800 ret = gmtime(&ti);
1803 memcpy(tm, ret, sizeof(struct tm));
1806 int qemu_timedate_diff(struct tm *tm)
1808 time_t seconds;
1810 if (rtc_date_offset == -1)
1811 if (rtc_utc)
1812 seconds = mktimegm(tm);
1813 else
1814 seconds = mktime(tm);
1815 else
1816 seconds = mktimegm(tm) + rtc_date_offset;
1818 return seconds - time(NULL);
1821 #ifdef _WIN32
1822 static void socket_cleanup(void)
1824 WSACleanup();
1827 static int socket_init(void)
1829 WSADATA Data;
1830 int ret, err;
1832 ret = WSAStartup(MAKEWORD(2,2), &Data);
1833 if (ret != 0) {
1834 err = WSAGetLastError();
1835 fprintf(stderr, "WSAStartup: %d\n", err);
1836 return -1;
1838 atexit(socket_cleanup);
1839 return 0;
1841 #endif
1843 const char *get_opt_name(char *buf, int buf_size, const char *p)
1845 char *q;
1847 q = buf;
1848 while (*p != '\0' && *p != '=') {
1849 if (q && (q - buf) < buf_size - 1)
1850 *q++ = *p;
1851 p++;
1853 if (q)
1854 *q = '\0';
1856 return p;
1859 const char *get_opt_value(char *buf, int buf_size, const char *p)
1861 char *q;
1863 q = buf;
1864 while (*p != '\0') {
1865 if (*p == ',') {
1866 if (*(p + 1) != ',')
1867 break;
1868 p++;
1870 if (q && (q - buf) < buf_size - 1)
1871 *q++ = *p;
1872 p++;
1874 if (q)
1875 *q = '\0';
1877 return p;
1880 int get_param_value(char *buf, int buf_size,
1881 const char *tag, const char *str)
1883 const char *p;
1884 char option[128];
1886 p = str;
1887 for(;;) {
1888 p = get_opt_name(option, sizeof(option), p);
1889 if (*p != '=')
1890 break;
1891 p++;
1892 if (!strcmp(tag, option)) {
1893 (void)get_opt_value(buf, buf_size, p);
1894 return strlen(buf);
1895 } else {
1896 p = get_opt_value(NULL, 0, p);
1898 if (*p != ',')
1899 break;
1900 p++;
1902 return 0;
1905 int check_params(char *buf, int buf_size,
1906 const char * const *params, const char *str)
1908 const char *p;
1909 int i;
1911 p = str;
1912 for(;;) {
1913 p = get_opt_name(buf, buf_size, p);
1914 if (*p != '=')
1915 return -1;
1916 p++;
1917 for(i = 0; params[i] != NULL; i++)
1918 if (!strcmp(params[i], buf))
1919 break;
1920 if (params[i] == NULL)
1921 return -1;
1922 p = get_opt_value(NULL, 0, p);
1923 if (*p != ',')
1924 break;
1925 p++;
1927 return 0;
1930 /***********************************************************/
1931 /* Bluetooth support */
1932 static int nb_hcis;
1933 static int cur_hci;
1934 static struct HCIInfo *hci_table[MAX_NICS];
1936 static struct bt_vlan_s {
1937 struct bt_scatternet_s net;
1938 int id;
1939 struct bt_vlan_s *next;
1940 } *first_bt_vlan;
1942 /* find or alloc a new bluetooth "VLAN" */
1943 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1945 struct bt_vlan_s **pvlan, *vlan;
1946 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1947 if (vlan->id == id)
1948 return &vlan->net;
1950 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1951 vlan->id = id;
1952 pvlan = &first_bt_vlan;
1953 while (*pvlan != NULL)
1954 pvlan = &(*pvlan)->next;
1955 *pvlan = vlan;
1956 return &vlan->net;
1959 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1963 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1965 return -ENOTSUP;
1968 static struct HCIInfo null_hci = {
1969 .cmd_send = null_hci_send,
1970 .sco_send = null_hci_send,
1971 .acl_send = null_hci_send,
1972 .bdaddr_set = null_hci_addr_set,
1975 struct HCIInfo *qemu_next_hci(void)
1977 if (cur_hci == nb_hcis)
1978 return &null_hci;
1980 return hci_table[cur_hci++];
1983 static struct HCIInfo *hci_init(const char *str)
1985 char *endp;
1986 struct bt_scatternet_s *vlan = 0;
1988 if (!strcmp(str, "null"))
1989 /* null */
1990 return &null_hci;
1991 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1992 /* host[:hciN] */
1993 return bt_host_hci(str[4] ? str + 5 : "hci0");
1994 else if (!strncmp(str, "hci", 3)) {
1995 /* hci[,vlan=n] */
1996 if (str[3]) {
1997 if (!strncmp(str + 3, ",vlan=", 6)) {
1998 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1999 if (*endp)
2000 vlan = 0;
2002 } else
2003 vlan = qemu_find_bt_vlan(0);
2004 if (vlan)
2005 return bt_new_hci(vlan);
2008 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2010 return 0;
2013 static int bt_hci_parse(const char *str)
2015 struct HCIInfo *hci;
2016 bdaddr_t bdaddr;
2018 if (nb_hcis >= MAX_NICS) {
2019 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2020 return -1;
2023 hci = hci_init(str);
2024 if (!hci)
2025 return -1;
2027 bdaddr.b[0] = 0x52;
2028 bdaddr.b[1] = 0x54;
2029 bdaddr.b[2] = 0x00;
2030 bdaddr.b[3] = 0x12;
2031 bdaddr.b[4] = 0x34;
2032 bdaddr.b[5] = 0x56 + nb_hcis;
2033 hci->bdaddr_set(hci, bdaddr.b);
2035 hci_table[nb_hcis++] = hci;
2037 return 0;
2040 static void bt_vhci_add(int vlan_id)
2042 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2044 if (!vlan->slave)
2045 fprintf(stderr, "qemu: warning: adding a VHCI to "
2046 "an empty scatternet %i\n", vlan_id);
2048 bt_vhci_init(bt_new_hci(vlan));
2051 static struct bt_device_s *bt_device_add(const char *opt)
2053 struct bt_scatternet_s *vlan;
2054 int vlan_id = 0;
2055 char *endp = strstr(opt, ",vlan=");
2056 int len = (endp ? endp - opt : strlen(opt)) + 1;
2057 char devname[10];
2059 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2061 if (endp) {
2062 vlan_id = strtol(endp + 6, &endp, 0);
2063 if (*endp) {
2064 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2065 return 0;
2069 vlan = qemu_find_bt_vlan(vlan_id);
2071 if (!vlan->slave)
2072 fprintf(stderr, "qemu: warning: adding a slave device to "
2073 "an empty scatternet %i\n", vlan_id);
2075 if (!strcmp(devname, "keyboard"))
2076 return bt_keyboard_init(vlan);
2078 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2079 return 0;
2082 static int bt_parse(const char *opt)
2084 const char *endp, *p;
2085 int vlan;
2087 if (strstart(opt, "hci", &endp)) {
2088 if (!*endp || *endp == ',') {
2089 if (*endp)
2090 if (!strstart(endp, ",vlan=", 0))
2091 opt = endp + 1;
2093 return bt_hci_parse(opt);
2095 } else if (strstart(opt, "vhci", &endp)) {
2096 if (!*endp || *endp == ',') {
2097 if (*endp) {
2098 if (strstart(endp, ",vlan=", &p)) {
2099 vlan = strtol(p, (char **) &endp, 0);
2100 if (*endp) {
2101 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2102 return 1;
2104 } else {
2105 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2106 return 1;
2108 } else
2109 vlan = 0;
2111 bt_vhci_add(vlan);
2112 return 0;
2114 } else if (strstart(opt, "device:", &endp))
2115 return !bt_device_add(endp);
2117 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2118 return 1;
2121 /***********************************************************/
2122 /* QEMU Block devices */
2124 #define HD_ALIAS "index=%d,media=disk"
2125 #ifdef TARGET_PPC
2126 #define CDROM_ALIAS "index=1,media=cdrom"
2127 #else
2128 #define CDROM_ALIAS "index=2,media=cdrom"
2129 #endif
2130 #define FD_ALIAS "index=%d,if=floppy"
2131 #define PFLASH_ALIAS "if=pflash"
2132 #define MTD_ALIAS "if=mtd"
2133 #define SD_ALIAS "index=0,if=sd"
2135 static int drive_opt_get_free_idx(void)
2137 int index;
2139 for (index = 0; index < MAX_DRIVES; index++)
2140 if (!drives_opt[index].used) {
2141 drives_opt[index].used = 1;
2142 return index;
2145 return -1;
2148 static int drive_get_free_idx(void)
2150 int index;
2152 for (index = 0; index < MAX_DRIVES; index++)
2153 if (!drives_table[index].used) {
2154 drives_table[index].used = 1;
2155 return index;
2158 return -1;
2161 int drive_add(const char *file, const char *fmt, ...)
2163 va_list ap;
2164 int index = drive_opt_get_free_idx();
2166 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2167 fprintf(stderr, "qemu: too many drives\n");
2168 return -1;
2171 drives_opt[index].file = file;
2172 va_start(ap, fmt);
2173 vsnprintf(drives_opt[index].opt,
2174 sizeof(drives_opt[0].opt), fmt, ap);
2175 va_end(ap);
2177 nb_drives_opt++;
2178 return index;
2181 void drive_remove(int index)
2183 drives_opt[index].used = 0;
2184 nb_drives_opt--;
2187 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2189 int index;
2191 /* seek interface, bus and unit */
2193 for (index = 0; index < MAX_DRIVES; index++)
2194 if (drives_table[index].type == type &&
2195 drives_table[index].bus == bus &&
2196 drives_table[index].unit == unit &&
2197 drives_table[index].used)
2198 return index;
2200 return -1;
2203 int drive_get_max_bus(BlockInterfaceType type)
2205 int max_bus;
2206 int index;
2208 max_bus = -1;
2209 for (index = 0; index < nb_drives; index++) {
2210 if(drives_table[index].type == type &&
2211 drives_table[index].bus > max_bus)
2212 max_bus = drives_table[index].bus;
2214 return max_bus;
2217 const char *drive_get_serial(BlockDriverState *bdrv)
2219 int index;
2221 for (index = 0; index < nb_drives; index++)
2222 if (drives_table[index].bdrv == bdrv)
2223 return drives_table[index].serial;
2225 return "\0";
2228 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2230 int index;
2232 for (index = 0; index < nb_drives; index++)
2233 if (drives_table[index].bdrv == bdrv)
2234 return drives_table[index].onerror;
2236 return BLOCK_ERR_REPORT;
2239 static void bdrv_format_print(void *opaque, const char *name)
2241 fprintf(stderr, " %s", name);
2244 void drive_uninit(BlockDriverState *bdrv)
2246 int i;
2248 for (i = 0; i < MAX_DRIVES; i++)
2249 if (drives_table[i].bdrv == bdrv) {
2250 drives_table[i].bdrv = NULL;
2251 drives_table[i].used = 0;
2252 drive_remove(drives_table[i].drive_opt_idx);
2253 nb_drives--;
2254 break;
2258 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2260 char buf[128];
2261 char file[1024];
2262 char devname[128];
2263 char serial[21];
2264 const char *mediastr = "";
2265 BlockInterfaceType type;
2266 enum { MEDIA_DISK, MEDIA_CDROM } media;
2267 int bus_id, unit_id;
2268 int cyls, heads, secs, translation;
2269 BlockDriverState *bdrv;
2270 BlockDriver *drv = NULL;
2271 QEMUMachine *machine = opaque;
2272 int max_devs;
2273 int index;
2274 int cache;
2275 int bdrv_flags, onerror;
2276 int drives_table_idx;
2277 char *str = arg->opt;
2278 static const char * const params[] = { "bus", "unit", "if", "index",
2279 "cyls", "heads", "secs", "trans",
2280 "media", "snapshot", "file",
2281 "cache", "format", "serial", "werror",
2282 NULL };
2284 if (check_params(buf, sizeof(buf), params, str) < 0) {
2285 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2286 buf, str);
2287 return -1;
2290 file[0] = 0;
2291 cyls = heads = secs = 0;
2292 bus_id = 0;
2293 unit_id = -1;
2294 translation = BIOS_ATA_TRANSLATION_AUTO;
2295 index = -1;
2296 cache = 3;
2298 if (machine->use_scsi) {
2299 type = IF_SCSI;
2300 max_devs = MAX_SCSI_DEVS;
2301 pstrcpy(devname, sizeof(devname), "scsi");
2302 } else {
2303 type = IF_IDE;
2304 max_devs = MAX_IDE_DEVS;
2305 pstrcpy(devname, sizeof(devname), "ide");
2307 media = MEDIA_DISK;
2309 /* extract parameters */
2311 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2312 bus_id = strtol(buf, NULL, 0);
2313 if (bus_id < 0) {
2314 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2315 return -1;
2319 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2320 unit_id = strtol(buf, NULL, 0);
2321 if (unit_id < 0) {
2322 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2323 return -1;
2327 if (get_param_value(buf, sizeof(buf), "if", str)) {
2328 pstrcpy(devname, sizeof(devname), buf);
2329 if (!strcmp(buf, "ide")) {
2330 type = IF_IDE;
2331 max_devs = MAX_IDE_DEVS;
2332 } else if (!strcmp(buf, "scsi")) {
2333 type = IF_SCSI;
2334 max_devs = MAX_SCSI_DEVS;
2335 } else if (!strcmp(buf, "floppy")) {
2336 type = IF_FLOPPY;
2337 max_devs = 0;
2338 } else if (!strcmp(buf, "pflash")) {
2339 type = IF_PFLASH;
2340 max_devs = 0;
2341 } else if (!strcmp(buf, "mtd")) {
2342 type = IF_MTD;
2343 max_devs = 0;
2344 } else if (!strcmp(buf, "sd")) {
2345 type = IF_SD;
2346 max_devs = 0;
2347 } else if (!strcmp(buf, "virtio")) {
2348 type = IF_VIRTIO;
2349 max_devs = 0;
2350 } else {
2351 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2352 return -1;
2356 if (get_param_value(buf, sizeof(buf), "index", str)) {
2357 index = strtol(buf, NULL, 0);
2358 if (index < 0) {
2359 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2360 return -1;
2364 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2365 cyls = strtol(buf, NULL, 0);
2368 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2369 heads = strtol(buf, NULL, 0);
2372 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2373 secs = strtol(buf, NULL, 0);
2376 if (cyls || heads || secs) {
2377 if (cyls < 1 || cyls > 16383) {
2378 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2379 return -1;
2381 if (heads < 1 || heads > 16) {
2382 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2383 return -1;
2385 if (secs < 1 || secs > 63) {
2386 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2387 return -1;
2391 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2392 if (!cyls) {
2393 fprintf(stderr,
2394 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2395 str);
2396 return -1;
2398 if (!strcmp(buf, "none"))
2399 translation = BIOS_ATA_TRANSLATION_NONE;
2400 else if (!strcmp(buf, "lba"))
2401 translation = BIOS_ATA_TRANSLATION_LBA;
2402 else if (!strcmp(buf, "auto"))
2403 translation = BIOS_ATA_TRANSLATION_AUTO;
2404 else {
2405 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2406 return -1;
2410 if (get_param_value(buf, sizeof(buf), "media", str)) {
2411 if (!strcmp(buf, "disk")) {
2412 media = MEDIA_DISK;
2413 } else if (!strcmp(buf, "cdrom")) {
2414 if (cyls || secs || heads) {
2415 fprintf(stderr,
2416 "qemu: '%s' invalid physical CHS format\n", str);
2417 return -1;
2419 media = MEDIA_CDROM;
2420 } else {
2421 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2422 return -1;
2426 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2427 if (!strcmp(buf, "on"))
2428 snapshot = 1;
2429 else if (!strcmp(buf, "off"))
2430 snapshot = 0;
2431 else {
2432 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2433 return -1;
2437 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2438 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2439 cache = 0;
2440 else if (!strcmp(buf, "writethrough"))
2441 cache = 1;
2442 else if (!strcmp(buf, "writeback"))
2443 cache = 2;
2444 else {
2445 fprintf(stderr, "qemu: invalid cache option\n");
2446 return -1;
2450 if (get_param_value(buf, sizeof(buf), "format", str)) {
2451 if (strcmp(buf, "?") == 0) {
2452 fprintf(stderr, "qemu: Supported formats:");
2453 bdrv_iterate_format(bdrv_format_print, NULL);
2454 fprintf(stderr, "\n");
2455 return -1;
2457 drv = bdrv_find_format(buf);
2458 if (!drv) {
2459 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2460 return -1;
2464 if (arg->file == NULL)
2465 get_param_value(file, sizeof(file), "file", str);
2466 else
2467 pstrcpy(file, sizeof(file), arg->file);
2469 if (!get_param_value(serial, sizeof(serial), "serial", str))
2470 memset(serial, 0, sizeof(serial));
2472 onerror = BLOCK_ERR_REPORT;
2473 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2474 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2475 fprintf(stderr, "werror is no supported by this format\n");
2476 return -1;
2478 if (!strcmp(buf, "ignore"))
2479 onerror = BLOCK_ERR_IGNORE;
2480 else if (!strcmp(buf, "enospc"))
2481 onerror = BLOCK_ERR_STOP_ENOSPC;
2482 else if (!strcmp(buf, "stop"))
2483 onerror = BLOCK_ERR_STOP_ANY;
2484 else if (!strcmp(buf, "report"))
2485 onerror = BLOCK_ERR_REPORT;
2486 else {
2487 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2488 return -1;
2492 /* compute bus and unit according index */
2494 if (index != -1) {
2495 if (bus_id != 0 || unit_id != -1) {
2496 fprintf(stderr,
2497 "qemu: '%s' index cannot be used with bus and unit\n", str);
2498 return -1;
2500 if (max_devs == 0)
2502 unit_id = index;
2503 bus_id = 0;
2504 } else {
2505 unit_id = index % max_devs;
2506 bus_id = index / max_devs;
2510 /* if user doesn't specify a unit_id,
2511 * try to find the first free
2514 if (unit_id == -1) {
2515 unit_id = 0;
2516 while (drive_get_index(type, bus_id, unit_id) != -1) {
2517 unit_id++;
2518 if (max_devs && unit_id >= max_devs) {
2519 unit_id -= max_devs;
2520 bus_id++;
2525 /* check unit id */
2527 if (max_devs && unit_id >= max_devs) {
2528 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2529 str, unit_id, max_devs - 1);
2530 return -1;
2534 * ignore multiple definitions
2537 if (drive_get_index(type, bus_id, unit_id) != -1)
2538 return -2;
2540 /* init */
2542 if (type == IF_IDE || type == IF_SCSI)
2543 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2544 if (max_devs)
2545 snprintf(buf, sizeof(buf), "%s%i%s%i",
2546 devname, bus_id, mediastr, unit_id);
2547 else
2548 snprintf(buf, sizeof(buf), "%s%s%i",
2549 devname, mediastr, unit_id);
2550 bdrv = bdrv_new(buf);
2551 drives_table_idx = drive_get_free_idx();
2552 drives_table[drives_table_idx].bdrv = bdrv;
2553 drives_table[drives_table_idx].type = type;
2554 drives_table[drives_table_idx].bus = bus_id;
2555 drives_table[drives_table_idx].unit = unit_id;
2556 drives_table[drives_table_idx].onerror = onerror;
2557 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2558 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2559 nb_drives++;
2561 switch(type) {
2562 case IF_IDE:
2563 case IF_SCSI:
2564 switch(media) {
2565 case MEDIA_DISK:
2566 if (cyls != 0) {
2567 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2568 bdrv_set_translation_hint(bdrv, translation);
2570 break;
2571 case MEDIA_CDROM:
2572 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2573 break;
2575 break;
2576 case IF_SD:
2577 /* FIXME: This isn't really a floppy, but it's a reasonable
2578 approximation. */
2579 case IF_FLOPPY:
2580 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2581 break;
2582 case IF_PFLASH:
2583 case IF_MTD:
2584 case IF_VIRTIO:
2585 break;
2587 if (!file[0])
2588 return -2;
2589 bdrv_flags = 0;
2590 if (snapshot) {
2591 bdrv_flags |= BDRV_O_SNAPSHOT;
2592 cache = 2; /* always use write-back with snapshot */
2594 if (cache == 0) /* no caching */
2595 bdrv_flags |= BDRV_O_NOCACHE;
2596 else if (cache == 2) /* write-back */
2597 bdrv_flags |= BDRV_O_CACHE_WB;
2598 else if (cache == 3) /* not specified */
2599 bdrv_flags |= BDRV_O_CACHE_DEF;
2600 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2601 fprintf(stderr, "qemu: could not open disk image %s\n",
2602 file);
2603 return -1;
2605 return drives_table_idx;
2608 /***********************************************************/
2609 /* USB devices */
2611 static USBPort *used_usb_ports;
2612 static USBPort *free_usb_ports;
2614 /* ??? Maybe change this to register a hub to keep track of the topology. */
2615 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2616 usb_attachfn attach)
2618 port->opaque = opaque;
2619 port->index = index;
2620 port->attach = attach;
2621 port->next = free_usb_ports;
2622 free_usb_ports = port;
2625 int usb_device_add_dev(USBDevice *dev)
2627 USBPort *port;
2629 /* Find a USB port to add the device to. */
2630 port = free_usb_ports;
2631 if (!port->next) {
2632 USBDevice *hub;
2634 /* Create a new hub and chain it on. */
2635 free_usb_ports = NULL;
2636 port->next = used_usb_ports;
2637 used_usb_ports = port;
2639 hub = usb_hub_init(VM_USB_HUB_SIZE);
2640 usb_attach(port, hub);
2641 port = free_usb_ports;
2644 free_usb_ports = port->next;
2645 port->next = used_usb_ports;
2646 used_usb_ports = port;
2647 usb_attach(port, dev);
2648 return 0;
2651 static int usb_device_add(const char *devname)
2653 const char *p;
2654 USBDevice *dev;
2656 if (!free_usb_ports)
2657 return -1;
2659 if (strstart(devname, "host:", &p)) {
2660 dev = usb_host_device_open(p);
2661 } else if (!strcmp(devname, "mouse")) {
2662 dev = usb_mouse_init();
2663 } else if (!strcmp(devname, "tablet")) {
2664 dev = usb_tablet_init();
2665 } else if (!strcmp(devname, "keyboard")) {
2666 dev = usb_keyboard_init();
2667 } else if (strstart(devname, "disk:", &p)) {
2668 dev = usb_msd_init(p);
2669 } else if (!strcmp(devname, "wacom-tablet")) {
2670 dev = usb_wacom_init();
2671 } else if (strstart(devname, "serial:", &p)) {
2672 dev = usb_serial_init(p);
2673 #ifdef CONFIG_BRLAPI
2674 } else if (!strcmp(devname, "braille")) {
2675 dev = usb_baum_init();
2676 #endif
2677 } else if (strstart(devname, "net:", &p)) {
2678 int nic = nb_nics;
2680 if (net_client_init("nic", p) < 0)
2681 return -1;
2682 nd_table[nic].model = "usb";
2683 dev = usb_net_init(&nd_table[nic]);
2684 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2685 dev = usb_bt_init(devname[2] ? hci_init(p) :
2686 bt_new_hci(qemu_find_bt_vlan(0)));
2687 } else {
2688 return -1;
2690 if (!dev)
2691 return -1;
2693 return usb_device_add_dev(dev);
2696 int usb_device_del_addr(int bus_num, int addr)
2698 USBPort *port;
2699 USBPort **lastp;
2700 USBDevice *dev;
2702 if (!used_usb_ports)
2703 return -1;
2705 if (bus_num != 0)
2706 return -1;
2708 lastp = &used_usb_ports;
2709 port = used_usb_ports;
2710 while (port && port->dev->addr != addr) {
2711 lastp = &port->next;
2712 port = port->next;
2715 if (!port)
2716 return -1;
2718 dev = port->dev;
2719 *lastp = port->next;
2720 usb_attach(port, NULL);
2721 dev->handle_destroy(dev);
2722 port->next = free_usb_ports;
2723 free_usb_ports = port;
2724 return 0;
2727 static int usb_device_del(const char *devname)
2729 int bus_num, addr;
2730 const char *p;
2732 if (strstart(devname, "host:", &p))
2733 return usb_host_device_close(p);
2735 if (!used_usb_ports)
2736 return -1;
2738 p = strchr(devname, '.');
2739 if (!p)
2740 return -1;
2741 bus_num = strtoul(devname, NULL, 0);
2742 addr = strtoul(p + 1, NULL, 0);
2744 return usb_device_del_addr(bus_num, addr);
2747 void do_usb_add(const char *devname)
2749 usb_device_add(devname);
2752 void do_usb_del(const char *devname)
2754 usb_device_del(devname);
2757 void usb_info(void)
2759 USBDevice *dev;
2760 USBPort *port;
2761 const char *speed_str;
2763 if (!usb_enabled) {
2764 term_printf("USB support not enabled\n");
2765 return;
2768 for (port = used_usb_ports; port; port = port->next) {
2769 dev = port->dev;
2770 if (!dev)
2771 continue;
2772 switch(dev->speed) {
2773 case USB_SPEED_LOW:
2774 speed_str = "1.5";
2775 break;
2776 case USB_SPEED_FULL:
2777 speed_str = "12";
2778 break;
2779 case USB_SPEED_HIGH:
2780 speed_str = "480";
2781 break;
2782 default:
2783 speed_str = "?";
2784 break;
2786 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2787 0, dev->addr, speed_str, dev->devname);
2791 /***********************************************************/
2792 /* PCMCIA/Cardbus */
2794 static struct pcmcia_socket_entry_s {
2795 struct pcmcia_socket_s *socket;
2796 struct pcmcia_socket_entry_s *next;
2797 } *pcmcia_sockets = 0;
2799 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2801 struct pcmcia_socket_entry_s *entry;
2803 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2804 entry->socket = socket;
2805 entry->next = pcmcia_sockets;
2806 pcmcia_sockets = entry;
2809 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2811 struct pcmcia_socket_entry_s *entry, **ptr;
2813 ptr = &pcmcia_sockets;
2814 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2815 if (entry->socket == socket) {
2816 *ptr = entry->next;
2817 qemu_free(entry);
2821 void pcmcia_info(void)
2823 struct pcmcia_socket_entry_s *iter;
2824 if (!pcmcia_sockets)
2825 term_printf("No PCMCIA sockets\n");
2827 for (iter = pcmcia_sockets; iter; iter = iter->next)
2828 term_printf("%s: %s\n", iter->socket->slot_string,
2829 iter->socket->attached ? iter->socket->card_string :
2830 "Empty");
2833 /***********************************************************/
2834 /* register display */
2836 void register_displaystate(DisplayState *ds)
2838 DisplayState **s;
2839 s = &display_state;
2840 while (*s != NULL)
2841 s = &(*s)->next;
2842 ds->next = NULL;
2843 *s = ds;
2846 DisplayState *get_displaystate(void)
2848 return display_state;
2851 /* dumb display */
2853 static void dumb_display_init(void)
2855 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2856 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2857 register_displaystate(ds);
2860 /***********************************************************/
2861 /* I/O handling */
2863 #define MAX_IO_HANDLERS 64
2865 typedef struct IOHandlerRecord {
2866 int fd;
2867 IOCanRWHandler *fd_read_poll;
2868 IOHandler *fd_read;
2869 IOHandler *fd_write;
2870 int deleted;
2871 void *opaque;
2872 /* temporary data */
2873 struct pollfd *ufd;
2874 struct IOHandlerRecord *next;
2875 } IOHandlerRecord;
2877 static IOHandlerRecord *first_io_handler;
2879 /* XXX: fd_read_poll should be suppressed, but an API change is
2880 necessary in the character devices to suppress fd_can_read(). */
2881 int qemu_set_fd_handler2(int fd,
2882 IOCanRWHandler *fd_read_poll,
2883 IOHandler *fd_read,
2884 IOHandler *fd_write,
2885 void *opaque)
2887 IOHandlerRecord **pioh, *ioh;
2889 if (!fd_read && !fd_write) {
2890 pioh = &first_io_handler;
2891 for(;;) {
2892 ioh = *pioh;
2893 if (ioh == NULL)
2894 break;
2895 if (ioh->fd == fd) {
2896 ioh->deleted = 1;
2897 break;
2899 pioh = &ioh->next;
2901 } else {
2902 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2903 if (ioh->fd == fd)
2904 goto found;
2906 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2907 ioh->next = first_io_handler;
2908 first_io_handler = ioh;
2909 found:
2910 ioh->fd = fd;
2911 ioh->fd_read_poll = fd_read_poll;
2912 ioh->fd_read = fd_read;
2913 ioh->fd_write = fd_write;
2914 ioh->opaque = opaque;
2915 ioh->deleted = 0;
2917 return 0;
2920 int qemu_set_fd_handler(int fd,
2921 IOHandler *fd_read,
2922 IOHandler *fd_write,
2923 void *opaque)
2925 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2928 #ifdef _WIN32
2929 /***********************************************************/
2930 /* Polling handling */
2932 typedef struct PollingEntry {
2933 PollingFunc *func;
2934 void *opaque;
2935 struct PollingEntry *next;
2936 } PollingEntry;
2938 static PollingEntry *first_polling_entry;
2940 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2942 PollingEntry **ppe, *pe;
2943 pe = qemu_mallocz(sizeof(PollingEntry));
2944 pe->func = func;
2945 pe->opaque = opaque;
2946 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2947 *ppe = pe;
2948 return 0;
2951 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2953 PollingEntry **ppe, *pe;
2954 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2955 pe = *ppe;
2956 if (pe->func == func && pe->opaque == opaque) {
2957 *ppe = pe->next;
2958 qemu_free(pe);
2959 break;
2964 /***********************************************************/
2965 /* Wait objects support */
2966 typedef struct WaitObjects {
2967 int num;
2968 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2969 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2970 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2971 } WaitObjects;
2973 static WaitObjects wait_objects = {0};
2975 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2977 WaitObjects *w = &wait_objects;
2979 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2980 return -1;
2981 w->events[w->num] = handle;
2982 w->func[w->num] = func;
2983 w->opaque[w->num] = opaque;
2984 w->num++;
2985 return 0;
2988 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2990 int i, found;
2991 WaitObjects *w = &wait_objects;
2993 found = 0;
2994 for (i = 0; i < w->num; i++) {
2995 if (w->events[i] == handle)
2996 found = 1;
2997 if (found) {
2998 w->events[i] = w->events[i + 1];
2999 w->func[i] = w->func[i + 1];
3000 w->opaque[i] = w->opaque[i + 1];
3003 if (found)
3004 w->num--;
3006 #endif
3008 /***********************************************************/
3009 /* ram save/restore */
3011 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3013 int v;
3015 v = qemu_get_byte(f);
3016 switch(v) {
3017 case 0:
3018 if (qemu_get_buffer(f, buf, len) != len)
3019 return -EIO;
3020 break;
3021 case 1:
3022 v = qemu_get_byte(f);
3023 memset(buf, v, len);
3024 break;
3025 default:
3026 return -EINVAL;
3029 if (qemu_file_has_error(f))
3030 return -EIO;
3032 return 0;
3035 static int ram_load_v1(QEMUFile *f, void *opaque)
3037 int ret;
3038 ram_addr_t i;
3040 if (qemu_get_be32(f) != phys_ram_size)
3041 return -EINVAL;
3042 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3043 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3044 if (ret)
3045 return ret;
3047 return 0;
3050 #define BDRV_HASH_BLOCK_SIZE 1024
3051 #define IOBUF_SIZE 4096
3052 #define RAM_CBLOCK_MAGIC 0xfabe
3054 typedef struct RamDecompressState {
3055 z_stream zstream;
3056 QEMUFile *f;
3057 uint8_t buf[IOBUF_SIZE];
3058 } RamDecompressState;
3060 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3062 int ret;
3063 memset(s, 0, sizeof(*s));
3064 s->f = f;
3065 ret = inflateInit(&s->zstream);
3066 if (ret != Z_OK)
3067 return -1;
3068 return 0;
3071 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3073 int ret, clen;
3075 s->zstream.avail_out = len;
3076 s->zstream.next_out = buf;
3077 while (s->zstream.avail_out > 0) {
3078 if (s->zstream.avail_in == 0) {
3079 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3080 return -1;
3081 clen = qemu_get_be16(s->f);
3082 if (clen > IOBUF_SIZE)
3083 return -1;
3084 qemu_get_buffer(s->f, s->buf, clen);
3085 s->zstream.avail_in = clen;
3086 s->zstream.next_in = s->buf;
3088 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3089 if (ret != Z_OK && ret != Z_STREAM_END) {
3090 return -1;
3093 return 0;
3096 static void ram_decompress_close(RamDecompressState *s)
3098 inflateEnd(&s->zstream);
3101 #define RAM_SAVE_FLAG_FULL 0x01
3102 #define RAM_SAVE_FLAG_COMPRESS 0x02
3103 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3104 #define RAM_SAVE_FLAG_PAGE 0x08
3105 #define RAM_SAVE_FLAG_EOS 0x10
3107 static int is_dup_page(uint8_t *page, uint8_t ch)
3109 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3110 uint32_t *array = (uint32_t *)page;
3111 int i;
3113 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3114 if (array[i] != val)
3115 return 0;
3118 return 1;
3121 static int ram_save_block(QEMUFile *f)
3123 static ram_addr_t current_addr = 0;
3124 ram_addr_t saved_addr = current_addr;
3125 ram_addr_t addr = 0;
3126 int found = 0;
3128 while (addr < phys_ram_size) {
3129 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3130 uint8_t ch;
3132 cpu_physical_memory_reset_dirty(current_addr,
3133 current_addr + TARGET_PAGE_SIZE,
3134 MIGRATION_DIRTY_FLAG);
3136 ch = *(phys_ram_base + current_addr);
3138 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3139 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3140 qemu_put_byte(f, ch);
3141 } else {
3142 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3143 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3146 found = 1;
3147 break;
3149 addr += TARGET_PAGE_SIZE;
3150 current_addr = (saved_addr + addr) % phys_ram_size;
3153 return found;
3156 static ram_addr_t ram_save_threshold = 10;
3158 static ram_addr_t ram_save_remaining(void)
3160 ram_addr_t addr;
3161 ram_addr_t count = 0;
3163 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3164 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3165 count++;
3168 return count;
3171 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3173 ram_addr_t addr;
3175 if (stage == 1) {
3176 /* Make sure all dirty bits are set */
3177 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3178 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3179 cpu_physical_memory_set_dirty(addr);
3182 /* Enable dirty memory tracking */
3183 cpu_physical_memory_set_dirty_tracking(1);
3185 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3188 while (!qemu_file_rate_limit(f)) {
3189 int ret;
3191 ret = ram_save_block(f);
3192 if (ret == 0) /* no more blocks */
3193 break;
3196 /* try transferring iterative blocks of memory */
3198 if (stage == 3) {
3199 cpu_physical_memory_set_dirty_tracking(0);
3201 /* flush all remaining blocks regardless of rate limiting */
3202 while (ram_save_block(f) != 0);
3205 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3207 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3210 static int ram_load_dead(QEMUFile *f, void *opaque)
3212 RamDecompressState s1, *s = &s1;
3213 uint8_t buf[10];
3214 ram_addr_t i;
3216 if (ram_decompress_open(s, f) < 0)
3217 return -EINVAL;
3218 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3219 if (ram_decompress_buf(s, buf, 1) < 0) {
3220 fprintf(stderr, "Error while reading ram block header\n");
3221 goto error;
3223 if (buf[0] == 0) {
3224 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3225 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3226 goto error;
3228 } else {
3229 error:
3230 printf("Error block header\n");
3231 return -EINVAL;
3234 ram_decompress_close(s);
3236 return 0;
3239 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3241 ram_addr_t addr;
3242 int flags;
3244 if (version_id == 1)
3245 return ram_load_v1(f, opaque);
3247 if (version_id == 2) {
3248 if (qemu_get_be32(f) != phys_ram_size)
3249 return -EINVAL;
3250 return ram_load_dead(f, opaque);
3253 if (version_id != 3)
3254 return -EINVAL;
3256 do {
3257 addr = qemu_get_be64(f);
3259 flags = addr & ~TARGET_PAGE_MASK;
3260 addr &= TARGET_PAGE_MASK;
3262 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3263 if (addr != phys_ram_size)
3264 return -EINVAL;
3267 if (flags & RAM_SAVE_FLAG_FULL) {
3268 if (ram_load_dead(f, opaque) < 0)
3269 return -EINVAL;
3272 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3273 uint8_t ch = qemu_get_byte(f);
3274 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3275 } else if (flags & RAM_SAVE_FLAG_PAGE)
3276 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3277 } while (!(flags & RAM_SAVE_FLAG_EOS));
3279 return 0;
3282 void qemu_service_io(void)
3284 CPUState *env = cpu_single_env;
3285 if (env) {
3286 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3287 #ifdef USE_KQEMU
3288 if (env->kqemu_enabled) {
3289 kqemu_cpu_interrupt(env);
3291 #endif
3295 /***********************************************************/
3296 /* bottom halves (can be seen as timers which expire ASAP) */
3298 struct QEMUBH {
3299 QEMUBHFunc *cb;
3300 void *opaque;
3301 int scheduled;
3302 int idle;
3303 int deleted;
3304 QEMUBH *next;
3307 static QEMUBH *first_bh = NULL;
3309 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3311 QEMUBH *bh;
3312 bh = qemu_mallocz(sizeof(QEMUBH));
3313 bh->cb = cb;
3314 bh->opaque = opaque;
3315 bh->next = first_bh;
3316 first_bh = bh;
3317 return bh;
3320 int qemu_bh_poll(void)
3322 QEMUBH *bh, **bhp;
3323 int ret;
3325 ret = 0;
3326 for (bh = first_bh; bh; bh = bh->next) {
3327 if (!bh->deleted && bh->scheduled) {
3328 bh->scheduled = 0;
3329 if (!bh->idle)
3330 ret = 1;
3331 bh->idle = 0;
3332 bh->cb(bh->opaque);
3336 /* remove deleted bhs */
3337 bhp = &first_bh;
3338 while (*bhp) {
3339 bh = *bhp;
3340 if (bh->deleted) {
3341 *bhp = bh->next;
3342 qemu_free(bh);
3343 } else
3344 bhp = &bh->next;
3347 return ret;
3350 void qemu_bh_schedule_idle(QEMUBH *bh)
3352 if (bh->scheduled)
3353 return;
3354 bh->scheduled = 1;
3355 bh->idle = 1;
3358 void qemu_bh_schedule(QEMUBH *bh)
3360 CPUState *env = cpu_single_env;
3361 if (bh->scheduled)
3362 return;
3363 bh->scheduled = 1;
3364 bh->idle = 0;
3365 /* stop the currently executing CPU to execute the BH ASAP */
3366 if (env) {
3367 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3371 void qemu_bh_cancel(QEMUBH *bh)
3373 bh->scheduled = 0;
3376 void qemu_bh_delete(QEMUBH *bh)
3378 bh->scheduled = 0;
3379 bh->deleted = 1;
3382 static void qemu_bh_update_timeout(int *timeout)
3384 QEMUBH *bh;
3386 for (bh = first_bh; bh; bh = bh->next) {
3387 if (!bh->deleted && bh->scheduled) {
3388 if (bh->idle) {
3389 /* idle bottom halves will be polled at least
3390 * every 10ms */
3391 *timeout = MIN(10, *timeout);
3392 } else {
3393 /* non-idle bottom halves will be executed
3394 * immediately */
3395 *timeout = 0;
3396 break;
3402 /***********************************************************/
3403 /* machine registration */
3405 static QEMUMachine *first_machine = NULL;
3407 int qemu_register_machine(QEMUMachine *m)
3409 QEMUMachine **pm;
3410 pm = &first_machine;
3411 while (*pm != NULL)
3412 pm = &(*pm)->next;
3413 m->next = NULL;
3414 *pm = m;
3415 return 0;
3418 static QEMUMachine *find_machine(const char *name)
3420 QEMUMachine *m;
3422 for(m = first_machine; m != NULL; m = m->next) {
3423 if (!strcmp(m->name, name))
3424 return m;
3426 return NULL;
3429 /***********************************************************/
3430 /* main execution loop */
3432 static void gui_update(void *opaque)
3434 uint64_t interval = GUI_REFRESH_INTERVAL;
3435 DisplayState *ds = opaque;
3436 DisplayChangeListener *dcl = ds->listeners;
3438 dpy_refresh(ds);
3440 while (dcl != NULL) {
3441 if (dcl->gui_timer_interval &&
3442 dcl->gui_timer_interval < interval)
3443 interval = dcl->gui_timer_interval;
3444 dcl = dcl->next;
3446 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3449 static void nographic_update(void *opaque)
3451 uint64_t interval = GUI_REFRESH_INTERVAL;
3453 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3456 struct vm_change_state_entry {
3457 VMChangeStateHandler *cb;
3458 void *opaque;
3459 LIST_ENTRY (vm_change_state_entry) entries;
3462 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3464 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3465 void *opaque)
3467 VMChangeStateEntry *e;
3469 e = qemu_mallocz(sizeof (*e));
3471 e->cb = cb;
3472 e->opaque = opaque;
3473 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3474 return e;
3477 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3479 LIST_REMOVE (e, entries);
3480 qemu_free (e);
3483 static void vm_state_notify(int running, int reason)
3485 VMChangeStateEntry *e;
3487 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3488 e->cb(e->opaque, running, reason);
3492 void vm_start(void)
3494 if (!vm_running) {
3495 cpu_enable_ticks();
3496 vm_running = 1;
3497 vm_state_notify(1, 0);
3498 qemu_rearm_alarm_timer(alarm_timer);
3502 void vm_stop(int reason)
3504 if (vm_running) {
3505 cpu_disable_ticks();
3506 vm_running = 0;
3507 vm_state_notify(0, reason);
3511 /* reset/shutdown handler */
3513 typedef struct QEMUResetEntry {
3514 QEMUResetHandler *func;
3515 void *opaque;
3516 struct QEMUResetEntry *next;
3517 } QEMUResetEntry;
3519 static QEMUResetEntry *first_reset_entry;
3520 static int reset_requested;
3521 static int shutdown_requested;
3522 static int powerdown_requested;
3524 int qemu_shutdown_requested(void)
3526 int r = shutdown_requested;
3527 shutdown_requested = 0;
3528 return r;
3531 int qemu_reset_requested(void)
3533 int r = reset_requested;
3534 reset_requested = 0;
3535 return r;
3538 int qemu_powerdown_requested(void)
3540 int r = powerdown_requested;
3541 powerdown_requested = 0;
3542 return r;
3545 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3547 QEMUResetEntry **pre, *re;
3549 pre = &first_reset_entry;
3550 while (*pre != NULL)
3551 pre = &(*pre)->next;
3552 re = qemu_mallocz(sizeof(QEMUResetEntry));
3553 re->func = func;
3554 re->opaque = opaque;
3555 re->next = NULL;
3556 *pre = re;
3559 void qemu_system_reset(void)
3561 QEMUResetEntry *re;
3563 /* reset all devices */
3564 for(re = first_reset_entry; re != NULL; re = re->next) {
3565 re->func(re->opaque);
3569 void qemu_system_reset_request(void)
3571 if (no_reboot) {
3572 shutdown_requested = 1;
3573 } else {
3574 reset_requested = 1;
3576 if (cpu_single_env)
3577 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3580 void qemu_system_shutdown_request(void)
3582 shutdown_requested = 1;
3583 if (cpu_single_env)
3584 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3587 void qemu_system_powerdown_request(void)
3589 powerdown_requested = 1;
3590 if (cpu_single_env)
3591 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3594 #ifdef _WIN32
3595 static void host_main_loop_wait(int *timeout)
3597 int ret, ret2, i;
3598 PollingEntry *pe;
3601 /* XXX: need to suppress polling by better using win32 events */
3602 ret = 0;
3603 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3604 ret |= pe->func(pe->opaque);
3606 if (ret == 0) {
3607 int err;
3608 WaitObjects *w = &wait_objects;
3610 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3611 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3612 if (w->func[ret - WAIT_OBJECT_0])
3613 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3615 /* Check for additional signaled events */
3616 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3618 /* Check if event is signaled */
3619 ret2 = WaitForSingleObject(w->events[i], 0);
3620 if(ret2 == WAIT_OBJECT_0) {
3621 if (w->func[i])
3622 w->func[i](w->opaque[i]);
3623 } else if (ret2 == WAIT_TIMEOUT) {
3624 } else {
3625 err = GetLastError();
3626 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3629 } else if (ret == WAIT_TIMEOUT) {
3630 } else {
3631 err = GetLastError();
3632 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3636 *timeout = 0;
3638 #else
3639 static void host_main_loop_wait(int *timeout)
3642 #endif
3644 void main_loop_wait(int timeout)
3646 IOHandlerRecord *ioh;
3647 fd_set rfds, wfds, xfds;
3648 int ret, nfds;
3649 struct timeval tv;
3651 qemu_bh_update_timeout(&timeout);
3653 host_main_loop_wait(&timeout);
3655 /* poll any events */
3656 /* XXX: separate device handlers from system ones */
3657 nfds = -1;
3658 FD_ZERO(&rfds);
3659 FD_ZERO(&wfds);
3660 FD_ZERO(&xfds);
3661 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3662 if (ioh->deleted)
3663 continue;
3664 if (ioh->fd_read &&
3665 (!ioh->fd_read_poll ||
3666 ioh->fd_read_poll(ioh->opaque) != 0)) {
3667 FD_SET(ioh->fd, &rfds);
3668 if (ioh->fd > nfds)
3669 nfds = ioh->fd;
3671 if (ioh->fd_write) {
3672 FD_SET(ioh->fd, &wfds);
3673 if (ioh->fd > nfds)
3674 nfds = ioh->fd;
3678 tv.tv_sec = timeout / 1000;
3679 tv.tv_usec = (timeout % 1000) * 1000;
3681 #if defined(CONFIG_SLIRP)
3682 if (slirp_is_inited()) {
3683 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3685 #endif
3686 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3687 if (ret > 0) {
3688 IOHandlerRecord **pioh;
3690 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3691 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3692 ioh->fd_read(ioh->opaque);
3694 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3695 ioh->fd_write(ioh->opaque);
3699 /* remove deleted IO handlers */
3700 pioh = &first_io_handler;
3701 while (*pioh) {
3702 ioh = *pioh;
3703 if (ioh->deleted) {
3704 *pioh = ioh->next;
3705 qemu_free(ioh);
3706 } else
3707 pioh = &ioh->next;
3710 #if defined(CONFIG_SLIRP)
3711 if (slirp_is_inited()) {
3712 if (ret < 0) {
3713 FD_ZERO(&rfds);
3714 FD_ZERO(&wfds);
3715 FD_ZERO(&xfds);
3717 slirp_select_poll(&rfds, &wfds, &xfds);
3719 #endif
3721 /* vm time timers */
3722 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3723 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3724 qemu_get_clock(vm_clock));
3726 /* real time timers */
3727 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3728 qemu_get_clock(rt_clock));
3730 /* Check bottom-halves last in case any of the earlier events triggered
3731 them. */
3732 qemu_bh_poll();
3736 static int main_loop(void)
3738 int ret, timeout;
3739 #ifdef CONFIG_PROFILER
3740 int64_t ti;
3741 #endif
3742 CPUState *env;
3744 cur_cpu = first_cpu;
3745 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3746 for(;;) {
3747 if (vm_running) {
3749 for(;;) {
3750 /* get next cpu */
3751 env = next_cpu;
3752 #ifdef CONFIG_PROFILER
3753 ti = profile_getclock();
3754 #endif
3755 if (use_icount) {
3756 int64_t count;
3757 int decr;
3758 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3759 env->icount_decr.u16.low = 0;
3760 env->icount_extra = 0;
3761 count = qemu_next_deadline();
3762 count = (count + (1 << icount_time_shift) - 1)
3763 >> icount_time_shift;
3764 qemu_icount += count;
3765 decr = (count > 0xffff) ? 0xffff : count;
3766 count -= decr;
3767 env->icount_decr.u16.low = decr;
3768 env->icount_extra = count;
3770 ret = cpu_exec(env);
3771 #ifdef CONFIG_PROFILER
3772 qemu_time += profile_getclock() - ti;
3773 #endif
3774 if (use_icount) {
3775 /* Fold pending instructions back into the
3776 instruction counter, and clear the interrupt flag. */
3777 qemu_icount -= (env->icount_decr.u16.low
3778 + env->icount_extra);
3779 env->icount_decr.u32 = 0;
3780 env->icount_extra = 0;
3782 next_cpu = env->next_cpu ?: first_cpu;
3783 if (event_pending && likely(ret != EXCP_DEBUG)) {
3784 ret = EXCP_INTERRUPT;
3785 event_pending = 0;
3786 break;
3788 if (ret == EXCP_HLT) {
3789 /* Give the next CPU a chance to run. */
3790 cur_cpu = env;
3791 continue;
3793 if (ret != EXCP_HALTED)
3794 break;
3795 /* all CPUs are halted ? */
3796 if (env == cur_cpu)
3797 break;
3799 cur_cpu = env;
3801 if (shutdown_requested) {
3802 ret = EXCP_INTERRUPT;
3803 if (no_shutdown) {
3804 vm_stop(0);
3805 no_shutdown = 0;
3807 else
3808 break;
3810 if (reset_requested) {
3811 reset_requested = 0;
3812 qemu_system_reset();
3813 ret = EXCP_INTERRUPT;
3815 if (powerdown_requested) {
3816 powerdown_requested = 0;
3817 qemu_system_powerdown();
3818 ret = EXCP_INTERRUPT;
3820 if (unlikely(ret == EXCP_DEBUG)) {
3821 gdb_set_stop_cpu(cur_cpu);
3822 vm_stop(EXCP_DEBUG);
3824 /* If all cpus are halted then wait until the next IRQ */
3825 /* XXX: use timeout computed from timers */
3826 if (ret == EXCP_HALTED) {
3827 if (use_icount) {
3828 int64_t add;
3829 int64_t delta;
3830 /* Advance virtual time to the next event. */
3831 if (use_icount == 1) {
3832 /* When not using an adaptive execution frequency
3833 we tend to get badly out of sync with real time,
3834 so just delay for a reasonable amount of time. */
3835 delta = 0;
3836 } else {
3837 delta = cpu_get_icount() - cpu_get_clock();
3839 if (delta > 0) {
3840 /* If virtual time is ahead of real time then just
3841 wait for IO. */
3842 timeout = (delta / 1000000) + 1;
3843 } else {
3844 /* Wait for either IO to occur or the next
3845 timer event. */
3846 add = qemu_next_deadline();
3847 /* We advance the timer before checking for IO.
3848 Limit the amount we advance so that early IO
3849 activity won't get the guest too far ahead. */
3850 if (add > 10000000)
3851 add = 10000000;
3852 delta += add;
3853 add = (add + (1 << icount_time_shift) - 1)
3854 >> icount_time_shift;
3855 qemu_icount += add;
3856 timeout = delta / 1000000;
3857 if (timeout < 0)
3858 timeout = 0;
3860 } else {
3861 timeout = 5000;
3863 } else {
3864 timeout = 0;
3866 } else {
3867 if (shutdown_requested) {
3868 ret = EXCP_INTERRUPT;
3869 break;
3871 timeout = 5000;
3873 #ifdef CONFIG_PROFILER
3874 ti = profile_getclock();
3875 #endif
3876 main_loop_wait(timeout);
3877 #ifdef CONFIG_PROFILER
3878 dev_time += profile_getclock() - ti;
3879 #endif
3881 cpu_disable_ticks();
3882 return ret;
3885 static void help(int exitcode)
3887 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3888 and qemu-doc.texi */
3889 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3890 "usage: %s [options] [disk_image]\n"
3891 "\n"
3892 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3893 "\n"
3894 "Standard options:\n"
3895 "-h or -help display this help and exit\n"
3896 "-M machine select emulated machine (-M ? for list)\n"
3897 "-cpu cpu select CPU (-cpu ? for list)\n"
3898 "-smp n set the number of CPUs to 'n' [default=1]\n"
3899 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3900 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3901 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3902 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3903 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3904 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3905 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3906 " use 'file' as a drive image\n"
3907 "-mtdblock file use 'file' as on-board Flash memory image\n"
3908 "-sd file use 'file' as SecureDigital card image\n"
3909 "-pflash file use 'file' as a parallel flash image\n"
3910 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3911 "-snapshot write to temporary files instead of disk image files\n"
3912 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3913 #ifndef _WIN32
3914 "-k language use keyboard layout (for example \"fr\" for French)\n"
3915 #endif
3916 #ifdef HAS_AUDIO
3917 "-audio-help print list of audio drivers and their options\n"
3918 "-soundhw c1,... enable audio support\n"
3919 " and only specified sound cards (comma separated list)\n"
3920 " use -soundhw ? to get the list of supported cards\n"
3921 " use -soundhw all to enable all of them\n"
3922 #endif
3923 "-usb enable the USB driver (will be the default soon)\n"
3924 "-usbdevice name add the host or guest USB device 'name'\n"
3925 "-name string set the name of the guest\n"
3926 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3927 " specify machine UUID\n"
3928 "\n"
3929 "Display options:\n"
3930 "-nographic disable graphical output and redirect serial I/Os to console\n"
3931 #ifdef CONFIG_CURSES
3932 "-curses use a curses/ncurses interface instead of SDL\n"
3933 #endif
3934 #ifdef CONFIG_SDL
3935 "-no-frame open SDL window without a frame and window decorations\n"
3936 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3937 "-no-quit disable SDL window close capability\n"
3938 "-sdl enable SDL\n"
3939 #endif
3940 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3941 "-vga [std|cirrus|vmware|none]\n"
3942 " select video card type\n"
3943 "-full-screen start in full screen\n"
3944 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3945 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3946 #endif
3947 "-vnc display start a VNC server on display\n"
3948 "\n"
3949 "Network options:\n"
3950 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3951 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3952 #ifdef CONFIG_SLIRP
3953 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3954 " connect the user mode network stack to VLAN 'n' and send\n"
3955 " hostname 'host' to DHCP clients\n"
3956 #endif
3957 #ifdef _WIN32
3958 "-net tap[,vlan=n][,name=str],ifname=name\n"
3959 " connect the host TAP network interface to VLAN 'n'\n"
3960 #else
3961 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3962 " connect the host TAP network interface to VLAN 'n' and use the\n"
3963 " network scripts 'file' (default=%s)\n"
3964 " and 'dfile' (default=%s);\n"
3965 " use '[down]script=no' to disable script execution;\n"
3966 " use 'fd=h' to connect to an already opened TAP interface\n"
3967 #endif
3968 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3969 " connect the vlan 'n' to another VLAN using a socket connection\n"
3970 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
3971 " connect the vlan 'n' to multicast maddr and port\n"
3972 #ifdef CONFIG_VDE
3973 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3974 " connect the vlan 'n' to port 'n' of a vde switch running\n"
3975 " on host and listening for incoming connections on 'socketpath'.\n"
3976 " Use group 'groupname' and mode 'octalmode' to change default\n"
3977 " ownership and permissions for communication port.\n"
3978 #endif
3979 "-net none use it alone to have zero network devices; if no -net option\n"
3980 " is provided, the default is '-net nic -net user'\n"
3981 #ifdef CONFIG_SLIRP
3982 "-tftp dir allow tftp access to files in dir [-net user]\n"
3983 "-bootp file advertise file in BOOTP replies\n"
3984 #ifndef _WIN32
3985 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3986 #endif
3987 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3988 " redirect TCP or UDP connections from host to guest [-net user]\n"
3989 #endif
3990 "\n"
3991 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
3992 "-bt hci,host[:id]\n"
3993 " use host's HCI with the given name\n"
3994 "-bt hci[,vlan=n]\n"
3995 " emulate a standard HCI in virtual scatternet 'n'\n"
3996 "-bt vhci[,vlan=n]\n"
3997 " add host computer to virtual scatternet 'n' using VHCI\n"
3998 "-bt device:dev[,vlan=n]\n"
3999 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4000 "\n"
4001 #ifdef TARGET_I386
4002 "\n"
4003 "i386 target only:\n"
4004 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4005 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4006 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4007 "-no-acpi disable ACPI\n"
4008 "-no-hpet disable HPET\n"
4009 #endif
4010 "Linux boot specific:\n"
4011 "-kernel bzImage use 'bzImage' as kernel image\n"
4012 "-append cmdline use 'cmdline' as kernel command line\n"
4013 "-initrd file use 'file' as initial ram disk\n"
4014 "\n"
4015 "Debug/Expert options:\n"
4016 "-serial dev redirect the serial port to char device 'dev'\n"
4017 "-parallel dev redirect the parallel port to char device 'dev'\n"
4018 "-monitor dev redirect the monitor to char device 'dev'\n"
4019 "-pidfile file write PID to 'file'\n"
4020 "-S freeze CPU at startup (use 'c' to start execution)\n"
4021 "-s wait gdb connection to port\n"
4022 "-p port set gdb connection port [default=%s]\n"
4023 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4024 "-hdachs c,h,s[,t]\n"
4025 " force hard disk 0 physical geometry and the optional BIOS\n"
4026 " translation (t=none or lba) (usually qemu can guess them)\n"
4027 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4028 "-bios file set the filename for the BIOS\n"
4029 #ifdef USE_KQEMU
4030 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4031 "-no-kqemu disable KQEMU kernel module usage\n"
4032 #endif
4033 #ifdef CONFIG_KVM
4034 "-enable-kvm enable KVM full virtualization support\n"
4035 #endif
4036 "-no-reboot exit instead of rebooting\n"
4037 "-no-shutdown stop before shutdown\n"
4038 "-loadvm [tag|id]\n"
4039 " start right away with a saved state (loadvm in monitor)\n"
4040 #ifndef _WIN32
4041 "-daemonize daemonize QEMU after initializing\n"
4042 #endif
4043 "-option-rom rom load a file, rom, into the option ROM space\n"
4044 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4045 "-prom-env variable=value\n"
4046 " set OpenBIOS nvram variables\n"
4047 #endif
4048 "-clock force the use of the given methods for timer alarm.\n"
4049 " To see what timers are available use -clock ?\n"
4050 "-localtime set the real time clock to local time [default=utc]\n"
4051 "-startdate select initial date of the clock\n"
4052 "-icount [N|auto]\n"
4053 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4054 "-echr chr set terminal escape character instead of ctrl-a\n"
4055 "-virtioconsole c\n"
4056 " set virtio console\n"
4057 "-show-cursor show cursor\n"
4058 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4059 "-semihosting semihosting mode\n"
4060 #endif
4061 #if defined(TARGET_ARM)
4062 "-old-param old param mode\n"
4063 #endif
4064 "-tb-size n set TB size\n"
4065 "-incoming p prepare for incoming migration, listen on port p\n"
4066 "\n"
4067 "During emulation, the following keys are useful:\n"
4068 "ctrl-alt-f toggle full screen\n"
4069 "ctrl-alt-n switch to virtual console 'n'\n"
4070 "ctrl-alt toggle mouse and keyboard grab\n"
4071 "\n"
4072 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4074 "qemu",
4075 DEFAULT_RAM_SIZE,
4076 #ifndef _WIN32
4077 DEFAULT_NETWORK_SCRIPT,
4078 DEFAULT_NETWORK_DOWN_SCRIPT,
4079 #endif
4080 DEFAULT_GDBSTUB_PORT,
4081 "/tmp/qemu.log");
4082 exit(exitcode);
4085 #define HAS_ARG 0x0001
4087 enum {
4088 /* Please keep in synch with help, qemu_options[] and
4089 qemu-doc.texi */
4090 /* Standard options: */
4091 QEMU_OPTION_h,
4092 QEMU_OPTION_M,
4093 QEMU_OPTION_cpu,
4094 QEMU_OPTION_smp,
4095 QEMU_OPTION_fda,
4096 QEMU_OPTION_fdb,
4097 QEMU_OPTION_hda,
4098 QEMU_OPTION_hdb,
4099 QEMU_OPTION_hdc,
4100 QEMU_OPTION_hdd,
4101 QEMU_OPTION_cdrom,
4102 QEMU_OPTION_drive,
4103 QEMU_OPTION_mtdblock,
4104 QEMU_OPTION_sd,
4105 QEMU_OPTION_pflash,
4106 QEMU_OPTION_boot,
4107 QEMU_OPTION_snapshot,
4108 QEMU_OPTION_m,
4109 QEMU_OPTION_k,
4110 QEMU_OPTION_audio_help,
4111 QEMU_OPTION_soundhw,
4112 QEMU_OPTION_usb,
4113 QEMU_OPTION_usbdevice,
4114 QEMU_OPTION_name,
4115 QEMU_OPTION_uuid,
4117 /* Display options: */
4118 QEMU_OPTION_nographic,
4119 QEMU_OPTION_curses,
4120 QEMU_OPTION_no_frame,
4121 QEMU_OPTION_alt_grab,
4122 QEMU_OPTION_no_quit,
4123 QEMU_OPTION_sdl,
4124 QEMU_OPTION_portrait,
4125 QEMU_OPTION_vga,
4126 QEMU_OPTION_full_screen,
4127 QEMU_OPTION_g,
4128 QEMU_OPTION_vnc,
4130 /* Network options: */
4131 QEMU_OPTION_net,
4132 QEMU_OPTION_tftp,
4133 QEMU_OPTION_bootp,
4134 QEMU_OPTION_smb,
4135 QEMU_OPTION_redir,
4136 QEMU_OPTION_bt,
4138 /* i386 target only: */
4139 QEMU_OPTION_win2k_hack,
4140 QEMU_OPTION_rtc_td_hack,
4141 QEMU_OPTION_no_fd_bootchk,
4142 QEMU_OPTION_no_acpi,
4143 QEMU_OPTION_no_hpet,
4145 /* Linux boot specific: */
4146 QEMU_OPTION_kernel,
4147 QEMU_OPTION_append,
4148 QEMU_OPTION_initrd,
4150 /* Debug/Expert options: */
4151 QEMU_OPTION_serial,
4152 QEMU_OPTION_parallel,
4153 QEMU_OPTION_monitor,
4154 QEMU_OPTION_pidfile,
4155 QEMU_OPTION_S,
4156 QEMU_OPTION_s,
4157 QEMU_OPTION_p,
4158 QEMU_OPTION_d,
4159 QEMU_OPTION_hdachs,
4160 QEMU_OPTION_L,
4161 QEMU_OPTION_bios,
4162 QEMU_OPTION_kernel_kqemu,
4163 QEMU_OPTION_no_kqemu,
4164 QEMU_OPTION_enable_kvm,
4165 QEMU_OPTION_no_reboot,
4166 QEMU_OPTION_no_shutdown,
4167 QEMU_OPTION_loadvm,
4168 QEMU_OPTION_daemonize,
4169 QEMU_OPTION_option_rom,
4170 QEMU_OPTION_prom_env,
4171 QEMU_OPTION_clock,
4172 QEMU_OPTION_localtime,
4173 QEMU_OPTION_startdate,
4174 QEMU_OPTION_icount,
4175 QEMU_OPTION_echr,
4176 QEMU_OPTION_virtiocon,
4177 QEMU_OPTION_show_cursor,
4178 QEMU_OPTION_semihosting,
4179 QEMU_OPTION_old_param,
4180 QEMU_OPTION_tb_size,
4181 QEMU_OPTION_incoming,
4184 typedef struct QEMUOption {
4185 const char *name;
4186 int flags;
4187 int index;
4188 } QEMUOption;
4190 static const QEMUOption qemu_options[] = {
4191 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4192 qemu-doc.texi */
4193 /* Standard options: */
4194 { "h", 0, QEMU_OPTION_h },
4195 { "help", 0, QEMU_OPTION_h },
4196 { "M", HAS_ARG, QEMU_OPTION_M },
4197 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4198 { "smp", HAS_ARG, QEMU_OPTION_smp },
4199 { "fda", HAS_ARG, QEMU_OPTION_fda },
4200 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4201 { "hda", HAS_ARG, QEMU_OPTION_hda },
4202 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4203 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4204 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4205 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4206 { "drive", HAS_ARG, QEMU_OPTION_drive },
4207 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4208 { "sd", HAS_ARG, QEMU_OPTION_sd },
4209 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4210 { "boot", HAS_ARG, QEMU_OPTION_boot },
4211 { "snapshot", 0, QEMU_OPTION_snapshot },
4212 { "m", HAS_ARG, QEMU_OPTION_m },
4213 #ifndef _WIN32
4214 { "k", HAS_ARG, QEMU_OPTION_k },
4215 #endif
4216 #ifdef HAS_AUDIO
4217 { "audio-help", 0, QEMU_OPTION_audio_help },
4218 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4219 #endif
4220 { "usb", 0, QEMU_OPTION_usb },
4221 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4222 { "name", HAS_ARG, QEMU_OPTION_name },
4223 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4225 /* Display options: */
4226 { "nographic", 0, QEMU_OPTION_nographic },
4227 #ifdef CONFIG_CURSES
4228 { "curses", 0, QEMU_OPTION_curses },
4229 #endif
4230 #ifdef CONFIG_SDL
4231 { "no-frame", 0, QEMU_OPTION_no_frame },
4232 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4233 { "no-quit", 0, QEMU_OPTION_no_quit },
4234 { "sdl", 0, QEMU_OPTION_sdl },
4235 #endif
4236 { "portrait", 0, QEMU_OPTION_portrait },
4237 { "vga", HAS_ARG, QEMU_OPTION_vga },
4238 { "full-screen", 0, QEMU_OPTION_full_screen },
4239 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4240 { "g", 1, QEMU_OPTION_g },
4241 #endif
4242 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4244 /* Network options: */
4245 { "net", HAS_ARG, QEMU_OPTION_net},
4246 #ifdef CONFIG_SLIRP
4247 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4248 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4249 #ifndef _WIN32
4250 { "smb", HAS_ARG, QEMU_OPTION_smb },
4251 #endif
4252 { "redir", HAS_ARG, QEMU_OPTION_redir },
4253 #endif
4254 { "bt", HAS_ARG, QEMU_OPTION_bt },
4255 #ifdef TARGET_I386
4256 /* i386 target only: */
4257 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4258 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4259 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4260 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4261 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4262 #endif
4264 /* Linux boot specific: */
4265 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4266 { "append", HAS_ARG, QEMU_OPTION_append },
4267 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4269 /* Debug/Expert options: */
4270 { "serial", HAS_ARG, QEMU_OPTION_serial },
4271 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4272 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4273 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4274 { "S", 0, QEMU_OPTION_S },
4275 { "s", 0, QEMU_OPTION_s },
4276 { "p", HAS_ARG, QEMU_OPTION_p },
4277 { "d", HAS_ARG, QEMU_OPTION_d },
4278 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4279 { "L", HAS_ARG, QEMU_OPTION_L },
4280 { "bios", HAS_ARG, QEMU_OPTION_bios },
4281 #ifdef USE_KQEMU
4282 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4283 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4284 #endif
4285 #ifdef CONFIG_KVM
4286 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4287 #endif
4288 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4289 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4290 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4291 { "daemonize", 0, QEMU_OPTION_daemonize },
4292 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4293 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4294 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4295 #endif
4296 { "clock", HAS_ARG, QEMU_OPTION_clock },
4297 { "localtime", 0, QEMU_OPTION_localtime },
4298 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4299 { "icount", HAS_ARG, QEMU_OPTION_icount },
4300 { "echr", HAS_ARG, QEMU_OPTION_echr },
4301 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4302 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4303 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4304 { "semihosting", 0, QEMU_OPTION_semihosting },
4305 #endif
4306 #if defined(TARGET_ARM)
4307 { "old-param", 0, QEMU_OPTION_old_param },
4308 #endif
4309 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4310 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4311 { NULL },
4314 /* password input */
4316 int qemu_key_check(BlockDriverState *bs, const char *name)
4318 char password[256];
4319 int i;
4321 if (!bdrv_is_encrypted(bs))
4322 return 0;
4324 term_printf("%s is encrypted.\n", name);
4325 for(i = 0; i < 3; i++) {
4326 monitor_readline("Password: ", 1, password, sizeof(password));
4327 if (bdrv_set_key(bs, password) == 0)
4328 return 0;
4329 term_printf("invalid password\n");
4331 return -EPERM;
4334 static BlockDriverState *get_bdrv(int index)
4336 if (index > nb_drives)
4337 return NULL;
4338 return drives_table[index].bdrv;
4341 static void read_passwords(void)
4343 BlockDriverState *bs;
4344 int i;
4346 for(i = 0; i < 6; i++) {
4347 bs = get_bdrv(i);
4348 if (bs)
4349 qemu_key_check(bs, bdrv_get_device_name(bs));
4353 #ifdef HAS_AUDIO
4354 struct soundhw soundhw[] = {
4355 #ifdef HAS_AUDIO_CHOICE
4356 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4358 "pcspk",
4359 "PC speaker",
4362 { .init_isa = pcspk_audio_init }
4364 #endif
4366 #ifdef CONFIG_SB16
4368 "sb16",
4369 "Creative Sound Blaster 16",
4372 { .init_isa = SB16_init }
4374 #endif
4376 #ifdef CONFIG_CS4231A
4378 "cs4231a",
4379 "CS4231A",
4382 { .init_isa = cs4231a_init }
4384 #endif
4386 #ifdef CONFIG_ADLIB
4388 "adlib",
4389 #ifdef HAS_YMF262
4390 "Yamaha YMF262 (OPL3)",
4391 #else
4392 "Yamaha YM3812 (OPL2)",
4393 #endif
4396 { .init_isa = Adlib_init }
4398 #endif
4400 #ifdef CONFIG_GUS
4402 "gus",
4403 "Gravis Ultrasound GF1",
4406 { .init_isa = GUS_init }
4408 #endif
4410 #ifdef CONFIG_AC97
4412 "ac97",
4413 "Intel 82801AA AC97 Audio",
4416 { .init_pci = ac97_init }
4418 #endif
4420 #ifdef CONFIG_ES1370
4422 "es1370",
4423 "ENSONIQ AudioPCI ES1370",
4426 { .init_pci = es1370_init }
4428 #endif
4430 #endif /* HAS_AUDIO_CHOICE */
4432 { NULL, NULL, 0, 0, { NULL } }
4435 static void select_soundhw (const char *optarg)
4437 struct soundhw *c;
4439 if (*optarg == '?') {
4440 show_valid_cards:
4442 printf ("Valid sound card names (comma separated):\n");
4443 for (c = soundhw; c->name; ++c) {
4444 printf ("%-11s %s\n", c->name, c->descr);
4446 printf ("\n-soundhw all will enable all of the above\n");
4447 exit (*optarg != '?');
4449 else {
4450 size_t l;
4451 const char *p;
4452 char *e;
4453 int bad_card = 0;
4455 if (!strcmp (optarg, "all")) {
4456 for (c = soundhw; c->name; ++c) {
4457 c->enabled = 1;
4459 return;
4462 p = optarg;
4463 while (*p) {
4464 e = strchr (p, ',');
4465 l = !e ? strlen (p) : (size_t) (e - p);
4467 for (c = soundhw; c->name; ++c) {
4468 if (!strncmp (c->name, p, l)) {
4469 c->enabled = 1;
4470 break;
4474 if (!c->name) {
4475 if (l > 80) {
4476 fprintf (stderr,
4477 "Unknown sound card name (too big to show)\n");
4479 else {
4480 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4481 (int) l, p);
4483 bad_card = 1;
4485 p += l + (e != NULL);
4488 if (bad_card)
4489 goto show_valid_cards;
4492 #endif
4494 static void select_vgahw (const char *p)
4496 const char *opts;
4498 if (strstart(p, "std", &opts)) {
4499 std_vga_enabled = 1;
4500 cirrus_vga_enabled = 0;
4501 vmsvga_enabled = 0;
4502 } else if (strstart(p, "cirrus", &opts)) {
4503 cirrus_vga_enabled = 1;
4504 std_vga_enabled = 0;
4505 vmsvga_enabled = 0;
4506 } else if (strstart(p, "vmware", &opts)) {
4507 cirrus_vga_enabled = 0;
4508 std_vga_enabled = 0;
4509 vmsvga_enabled = 1;
4510 } else if (strstart(p, "none", &opts)) {
4511 cirrus_vga_enabled = 0;
4512 std_vga_enabled = 0;
4513 vmsvga_enabled = 0;
4514 } else {
4515 invalid_vga:
4516 fprintf(stderr, "Unknown vga type: %s\n", p);
4517 exit(1);
4519 while (*opts) {
4520 const char *nextopt;
4522 if (strstart(opts, ",retrace=", &nextopt)) {
4523 opts = nextopt;
4524 if (strstart(opts, "dumb", &nextopt))
4525 vga_retrace_method = VGA_RETRACE_DUMB;
4526 else if (strstart(opts, "precise", &nextopt))
4527 vga_retrace_method = VGA_RETRACE_PRECISE;
4528 else goto invalid_vga;
4529 } else goto invalid_vga;
4530 opts = nextopt;
4534 #ifdef _WIN32
4535 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4537 exit(STATUS_CONTROL_C_EXIT);
4538 return TRUE;
4540 #endif
4542 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4544 int ret;
4546 if(strlen(str) != 36)
4547 return -1;
4549 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4550 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4551 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4553 if(ret != 16)
4554 return -1;
4556 return 0;
4559 #define MAX_NET_CLIENTS 32
4561 #ifndef _WIN32
4563 static void termsig_handler(int signal)
4565 qemu_system_shutdown_request();
4568 static void termsig_setup(void)
4570 struct sigaction act;
4572 memset(&act, 0, sizeof(act));
4573 act.sa_handler = termsig_handler;
4574 sigaction(SIGINT, &act, NULL);
4575 sigaction(SIGHUP, &act, NULL);
4576 sigaction(SIGTERM, &act, NULL);
4579 #endif
4581 int main(int argc, char **argv, char **envp)
4583 #ifdef CONFIG_GDBSTUB
4584 int use_gdbstub;
4585 const char *gdbstub_port;
4586 #endif
4587 uint32_t boot_devices_bitmap = 0;
4588 int i;
4589 int snapshot, linux_boot, net_boot;
4590 const char *initrd_filename;
4591 const char *kernel_filename, *kernel_cmdline;
4592 const char *boot_devices = "";
4593 DisplayState *ds;
4594 DisplayChangeListener *dcl;
4595 int cyls, heads, secs, translation;
4596 const char *net_clients[MAX_NET_CLIENTS];
4597 int nb_net_clients;
4598 const char *bt_opts[MAX_BT_CMDLINE];
4599 int nb_bt_opts;
4600 int hda_index;
4601 int optind;
4602 const char *r, *optarg;
4603 CharDriverState *monitor_hd = NULL;
4604 const char *monitor_device;
4605 const char *serial_devices[MAX_SERIAL_PORTS];
4606 int serial_device_index;
4607 const char *parallel_devices[MAX_PARALLEL_PORTS];
4608 int parallel_device_index;
4609 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4610 int virtio_console_index;
4611 const char *loadvm = NULL;
4612 QEMUMachine *machine;
4613 const char *cpu_model;
4614 const char *usb_devices[MAX_USB_CMDLINE];
4615 int usb_devices_index;
4616 int fds[2];
4617 int tb_size;
4618 const char *pid_file = NULL;
4619 int autostart;
4620 const char *incoming = NULL;
4622 qemu_cache_utils_init(envp);
4624 LIST_INIT (&vm_change_state_head);
4625 #ifndef _WIN32
4627 struct sigaction act;
4628 sigfillset(&act.sa_mask);
4629 act.sa_flags = 0;
4630 act.sa_handler = SIG_IGN;
4631 sigaction(SIGPIPE, &act, NULL);
4633 #else
4634 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4635 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4636 QEMU to run on a single CPU */
4638 HANDLE h;
4639 DWORD mask, smask;
4640 int i;
4641 h = GetCurrentProcess();
4642 if (GetProcessAffinityMask(h, &mask, &smask)) {
4643 for(i = 0; i < 32; i++) {
4644 if (mask & (1 << i))
4645 break;
4647 if (i != 32) {
4648 mask = 1 << i;
4649 SetProcessAffinityMask(h, mask);
4653 #endif
4655 register_machines();
4656 machine = first_machine;
4657 cpu_model = NULL;
4658 initrd_filename = NULL;
4659 ram_size = 0;
4660 vga_ram_size = VGA_RAM_SIZE;
4661 #ifdef CONFIG_GDBSTUB
4662 use_gdbstub = 0;
4663 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4664 #endif
4665 snapshot = 0;
4666 nographic = 0;
4667 curses = 0;
4668 kernel_filename = NULL;
4669 kernel_cmdline = "";
4670 cyls = heads = secs = 0;
4671 translation = BIOS_ATA_TRANSLATION_AUTO;
4672 monitor_device = "vc";
4674 serial_devices[0] = "vc:80Cx24C";
4675 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4676 serial_devices[i] = NULL;
4677 serial_device_index = 0;
4679 parallel_devices[0] = "vc:640x480";
4680 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4681 parallel_devices[i] = NULL;
4682 parallel_device_index = 0;
4684 virtio_consoles[0] = "vc:80Cx24C";
4685 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4686 virtio_consoles[i] = NULL;
4687 virtio_console_index = 0;
4689 usb_devices_index = 0;
4691 nb_net_clients = 0;
4692 nb_bt_opts = 0;
4693 nb_drives = 0;
4694 nb_drives_opt = 0;
4695 hda_index = -1;
4697 nb_nics = 0;
4699 tb_size = 0;
4700 autostart= 1;
4702 optind = 1;
4703 for(;;) {
4704 if (optind >= argc)
4705 break;
4706 r = argv[optind];
4707 if (r[0] != '-') {
4708 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4709 } else {
4710 const QEMUOption *popt;
4712 optind++;
4713 /* Treat --foo the same as -foo. */
4714 if (r[1] == '-')
4715 r++;
4716 popt = qemu_options;
4717 for(;;) {
4718 if (!popt->name) {
4719 fprintf(stderr, "%s: invalid option -- '%s'\n",
4720 argv[0], r);
4721 exit(1);
4723 if (!strcmp(popt->name, r + 1))
4724 break;
4725 popt++;
4727 if (popt->flags & HAS_ARG) {
4728 if (optind >= argc) {
4729 fprintf(stderr, "%s: option '%s' requires an argument\n",
4730 argv[0], r);
4731 exit(1);
4733 optarg = argv[optind++];
4734 } else {
4735 optarg = NULL;
4738 switch(popt->index) {
4739 case QEMU_OPTION_M:
4740 machine = find_machine(optarg);
4741 if (!machine) {
4742 QEMUMachine *m;
4743 printf("Supported machines are:\n");
4744 for(m = first_machine; m != NULL; m = m->next) {
4745 printf("%-10s %s%s\n",
4746 m->name, m->desc,
4747 m == first_machine ? " (default)" : "");
4749 exit(*optarg != '?');
4751 break;
4752 case QEMU_OPTION_cpu:
4753 /* hw initialization will check this */
4754 if (*optarg == '?') {
4755 /* XXX: implement xxx_cpu_list for targets that still miss it */
4756 #if defined(cpu_list)
4757 cpu_list(stdout, &fprintf);
4758 #endif
4759 exit(0);
4760 } else {
4761 cpu_model = optarg;
4763 break;
4764 case QEMU_OPTION_initrd:
4765 initrd_filename = optarg;
4766 break;
4767 case QEMU_OPTION_hda:
4768 if (cyls == 0)
4769 hda_index = drive_add(optarg, HD_ALIAS, 0);
4770 else
4771 hda_index = drive_add(optarg, HD_ALIAS
4772 ",cyls=%d,heads=%d,secs=%d%s",
4773 0, cyls, heads, secs,
4774 translation == BIOS_ATA_TRANSLATION_LBA ?
4775 ",trans=lba" :
4776 translation == BIOS_ATA_TRANSLATION_NONE ?
4777 ",trans=none" : "");
4778 break;
4779 case QEMU_OPTION_hdb:
4780 case QEMU_OPTION_hdc:
4781 case QEMU_OPTION_hdd:
4782 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4783 break;
4784 case QEMU_OPTION_drive:
4785 drive_add(NULL, "%s", optarg);
4786 break;
4787 case QEMU_OPTION_mtdblock:
4788 drive_add(optarg, MTD_ALIAS);
4789 break;
4790 case QEMU_OPTION_sd:
4791 drive_add(optarg, SD_ALIAS);
4792 break;
4793 case QEMU_OPTION_pflash:
4794 drive_add(optarg, PFLASH_ALIAS);
4795 break;
4796 case QEMU_OPTION_snapshot:
4797 snapshot = 1;
4798 break;
4799 case QEMU_OPTION_hdachs:
4801 const char *p;
4802 p = optarg;
4803 cyls = strtol(p, (char **)&p, 0);
4804 if (cyls < 1 || cyls > 16383)
4805 goto chs_fail;
4806 if (*p != ',')
4807 goto chs_fail;
4808 p++;
4809 heads = strtol(p, (char **)&p, 0);
4810 if (heads < 1 || heads > 16)
4811 goto chs_fail;
4812 if (*p != ',')
4813 goto chs_fail;
4814 p++;
4815 secs = strtol(p, (char **)&p, 0);
4816 if (secs < 1 || secs > 63)
4817 goto chs_fail;
4818 if (*p == ',') {
4819 p++;
4820 if (!strcmp(p, "none"))
4821 translation = BIOS_ATA_TRANSLATION_NONE;
4822 else if (!strcmp(p, "lba"))
4823 translation = BIOS_ATA_TRANSLATION_LBA;
4824 else if (!strcmp(p, "auto"))
4825 translation = BIOS_ATA_TRANSLATION_AUTO;
4826 else
4827 goto chs_fail;
4828 } else if (*p != '\0') {
4829 chs_fail:
4830 fprintf(stderr, "qemu: invalid physical CHS format\n");
4831 exit(1);
4833 if (hda_index != -1)
4834 snprintf(drives_opt[hda_index].opt,
4835 sizeof(drives_opt[hda_index].opt),
4836 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4837 0, cyls, heads, secs,
4838 translation == BIOS_ATA_TRANSLATION_LBA ?
4839 ",trans=lba" :
4840 translation == BIOS_ATA_TRANSLATION_NONE ?
4841 ",trans=none" : "");
4843 break;
4844 case QEMU_OPTION_nographic:
4845 nographic = 1;
4846 break;
4847 #ifdef CONFIG_CURSES
4848 case QEMU_OPTION_curses:
4849 curses = 1;
4850 break;
4851 #endif
4852 case QEMU_OPTION_portrait:
4853 graphic_rotate = 1;
4854 break;
4855 case QEMU_OPTION_kernel:
4856 kernel_filename = optarg;
4857 break;
4858 case QEMU_OPTION_append:
4859 kernel_cmdline = optarg;
4860 break;
4861 case QEMU_OPTION_cdrom:
4862 drive_add(optarg, CDROM_ALIAS);
4863 break;
4864 case QEMU_OPTION_boot:
4865 boot_devices = optarg;
4866 /* We just do some generic consistency checks */
4868 /* Could easily be extended to 64 devices if needed */
4869 const char *p;
4871 boot_devices_bitmap = 0;
4872 for (p = boot_devices; *p != '\0'; p++) {
4873 /* Allowed boot devices are:
4874 * a b : floppy disk drives
4875 * c ... f : IDE disk drives
4876 * g ... m : machine implementation dependant drives
4877 * n ... p : network devices
4878 * It's up to each machine implementation to check
4879 * if the given boot devices match the actual hardware
4880 * implementation and firmware features.
4882 if (*p < 'a' || *p > 'q') {
4883 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4884 exit(1);
4886 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4887 fprintf(stderr,
4888 "Boot device '%c' was given twice\n",*p);
4889 exit(1);
4891 boot_devices_bitmap |= 1 << (*p - 'a');
4894 break;
4895 case QEMU_OPTION_fda:
4896 case QEMU_OPTION_fdb:
4897 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4898 break;
4899 #ifdef TARGET_I386
4900 case QEMU_OPTION_no_fd_bootchk:
4901 fd_bootchk = 0;
4902 break;
4903 #endif
4904 case QEMU_OPTION_net:
4905 if (nb_net_clients >= MAX_NET_CLIENTS) {
4906 fprintf(stderr, "qemu: too many network clients\n");
4907 exit(1);
4909 net_clients[nb_net_clients] = optarg;
4910 nb_net_clients++;
4911 break;
4912 #ifdef CONFIG_SLIRP
4913 case QEMU_OPTION_tftp:
4914 tftp_prefix = optarg;
4915 break;
4916 case QEMU_OPTION_bootp:
4917 bootp_filename = optarg;
4918 break;
4919 #ifndef _WIN32
4920 case QEMU_OPTION_smb:
4921 net_slirp_smb(optarg);
4922 break;
4923 #endif
4924 case QEMU_OPTION_redir:
4925 net_slirp_redir(optarg);
4926 break;
4927 #endif
4928 case QEMU_OPTION_bt:
4929 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4930 fprintf(stderr, "qemu: too many bluetooth options\n");
4931 exit(1);
4933 bt_opts[nb_bt_opts++] = optarg;
4934 break;
4935 #ifdef HAS_AUDIO
4936 case QEMU_OPTION_audio_help:
4937 AUD_help ();
4938 exit (0);
4939 break;
4940 case QEMU_OPTION_soundhw:
4941 select_soundhw (optarg);
4942 break;
4943 #endif
4944 case QEMU_OPTION_h:
4945 help(0);
4946 break;
4947 case QEMU_OPTION_m: {
4948 uint64_t value;
4949 char *ptr;
4951 value = strtoul(optarg, &ptr, 10);
4952 switch (*ptr) {
4953 case 0: case 'M': case 'm':
4954 value <<= 20;
4955 break;
4956 case 'G': case 'g':
4957 value <<= 30;
4958 break;
4959 default:
4960 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4961 exit(1);
4964 /* On 32-bit hosts, QEMU is limited by virtual address space */
4965 if (value > (2047 << 20)
4966 #ifndef USE_KQEMU
4967 && HOST_LONG_BITS == 32
4968 #endif
4970 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4971 exit(1);
4973 if (value != (uint64_t)(ram_addr_t)value) {
4974 fprintf(stderr, "qemu: ram size too large\n");
4975 exit(1);
4977 ram_size = value;
4978 break;
4980 case QEMU_OPTION_d:
4982 int mask;
4983 const CPULogItem *item;
4985 mask = cpu_str_to_log_mask(optarg);
4986 if (!mask) {
4987 printf("Log items (comma separated):\n");
4988 for(item = cpu_log_items; item->mask != 0; item++) {
4989 printf("%-10s %s\n", item->name, item->help);
4991 exit(1);
4993 cpu_set_log(mask);
4995 break;
4996 #ifdef CONFIG_GDBSTUB
4997 case QEMU_OPTION_s:
4998 use_gdbstub = 1;
4999 break;
5000 case QEMU_OPTION_p:
5001 gdbstub_port = optarg;
5002 break;
5003 #endif
5004 case QEMU_OPTION_L:
5005 bios_dir = optarg;
5006 break;
5007 case QEMU_OPTION_bios:
5008 bios_name = optarg;
5009 break;
5010 case QEMU_OPTION_S:
5011 autostart = 0;
5012 break;
5013 case QEMU_OPTION_k:
5014 keyboard_layout = optarg;
5015 break;
5016 case QEMU_OPTION_localtime:
5017 rtc_utc = 0;
5018 break;
5019 case QEMU_OPTION_vga:
5020 select_vgahw (optarg);
5021 break;
5022 case QEMU_OPTION_g:
5024 const char *p;
5025 int w, h, depth;
5026 p = optarg;
5027 w = strtol(p, (char **)&p, 10);
5028 if (w <= 0) {
5029 graphic_error:
5030 fprintf(stderr, "qemu: invalid resolution or depth\n");
5031 exit(1);
5033 if (*p != 'x')
5034 goto graphic_error;
5035 p++;
5036 h = strtol(p, (char **)&p, 10);
5037 if (h <= 0)
5038 goto graphic_error;
5039 if (*p == 'x') {
5040 p++;
5041 depth = strtol(p, (char **)&p, 10);
5042 if (depth != 8 && depth != 15 && depth != 16 &&
5043 depth != 24 && depth != 32)
5044 goto graphic_error;
5045 } else if (*p == '\0') {
5046 depth = graphic_depth;
5047 } else {
5048 goto graphic_error;
5051 graphic_width = w;
5052 graphic_height = h;
5053 graphic_depth = depth;
5055 break;
5056 case QEMU_OPTION_echr:
5058 char *r;
5059 term_escape_char = strtol(optarg, &r, 0);
5060 if (r == optarg)
5061 printf("Bad argument to echr\n");
5062 break;
5064 case QEMU_OPTION_monitor:
5065 monitor_device = optarg;
5066 break;
5067 case QEMU_OPTION_serial:
5068 if (serial_device_index >= MAX_SERIAL_PORTS) {
5069 fprintf(stderr, "qemu: too many serial ports\n");
5070 exit(1);
5072 serial_devices[serial_device_index] = optarg;
5073 serial_device_index++;
5074 break;
5075 case QEMU_OPTION_virtiocon:
5076 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5077 fprintf(stderr, "qemu: too many virtio consoles\n");
5078 exit(1);
5080 virtio_consoles[virtio_console_index] = optarg;
5081 virtio_console_index++;
5082 break;
5083 case QEMU_OPTION_parallel:
5084 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5085 fprintf(stderr, "qemu: too many parallel ports\n");
5086 exit(1);
5088 parallel_devices[parallel_device_index] = optarg;
5089 parallel_device_index++;
5090 break;
5091 case QEMU_OPTION_loadvm:
5092 loadvm = optarg;
5093 break;
5094 case QEMU_OPTION_full_screen:
5095 full_screen = 1;
5096 break;
5097 #ifdef CONFIG_SDL
5098 case QEMU_OPTION_no_frame:
5099 no_frame = 1;
5100 break;
5101 case QEMU_OPTION_alt_grab:
5102 alt_grab = 1;
5103 break;
5104 case QEMU_OPTION_no_quit:
5105 no_quit = 1;
5106 break;
5107 case QEMU_OPTION_sdl:
5108 sdl = 1;
5109 break;
5110 #endif
5111 case QEMU_OPTION_pidfile:
5112 pid_file = optarg;
5113 break;
5114 #ifdef TARGET_I386
5115 case QEMU_OPTION_win2k_hack:
5116 win2k_install_hack = 1;
5117 break;
5118 case QEMU_OPTION_rtc_td_hack:
5119 rtc_td_hack = 1;
5120 break;
5121 #endif
5122 #ifdef USE_KQEMU
5123 case QEMU_OPTION_no_kqemu:
5124 kqemu_allowed = 0;
5125 break;
5126 case QEMU_OPTION_kernel_kqemu:
5127 kqemu_allowed = 2;
5128 break;
5129 #endif
5130 #ifdef CONFIG_KVM
5131 case QEMU_OPTION_enable_kvm:
5132 kvm_allowed = 1;
5133 #ifdef USE_KQEMU
5134 kqemu_allowed = 0;
5135 #endif
5136 break;
5137 #endif
5138 case QEMU_OPTION_usb:
5139 usb_enabled = 1;
5140 break;
5141 case QEMU_OPTION_usbdevice:
5142 usb_enabled = 1;
5143 if (usb_devices_index >= MAX_USB_CMDLINE) {
5144 fprintf(stderr, "Too many USB devices\n");
5145 exit(1);
5147 usb_devices[usb_devices_index] = optarg;
5148 usb_devices_index++;
5149 break;
5150 case QEMU_OPTION_smp:
5151 smp_cpus = atoi(optarg);
5152 if (smp_cpus < 1) {
5153 fprintf(stderr, "Invalid number of CPUs\n");
5154 exit(1);
5156 break;
5157 case QEMU_OPTION_vnc:
5158 vnc_display = optarg;
5159 break;
5160 case QEMU_OPTION_no_acpi:
5161 acpi_enabled = 0;
5162 break;
5163 case QEMU_OPTION_no_hpet:
5164 no_hpet = 1;
5165 break;
5166 case QEMU_OPTION_no_reboot:
5167 no_reboot = 1;
5168 break;
5169 case QEMU_OPTION_no_shutdown:
5170 no_shutdown = 1;
5171 break;
5172 case QEMU_OPTION_show_cursor:
5173 cursor_hide = 0;
5174 break;
5175 case QEMU_OPTION_uuid:
5176 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5177 fprintf(stderr, "Fail to parse UUID string."
5178 " Wrong format.\n");
5179 exit(1);
5181 break;
5182 case QEMU_OPTION_daemonize:
5183 daemonize = 1;
5184 break;
5185 case QEMU_OPTION_option_rom:
5186 if (nb_option_roms >= MAX_OPTION_ROMS) {
5187 fprintf(stderr, "Too many option ROMs\n");
5188 exit(1);
5190 option_rom[nb_option_roms] = optarg;
5191 nb_option_roms++;
5192 break;
5193 case QEMU_OPTION_semihosting:
5194 semihosting_enabled = 1;
5195 break;
5196 case QEMU_OPTION_name:
5197 qemu_name = optarg;
5198 break;
5199 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5200 case QEMU_OPTION_prom_env:
5201 if (nb_prom_envs >= MAX_PROM_ENVS) {
5202 fprintf(stderr, "Too many prom variables\n");
5203 exit(1);
5205 prom_envs[nb_prom_envs] = optarg;
5206 nb_prom_envs++;
5207 break;
5208 #endif
5209 #ifdef TARGET_ARM
5210 case QEMU_OPTION_old_param:
5211 old_param = 1;
5212 break;
5213 #endif
5214 case QEMU_OPTION_clock:
5215 configure_alarms(optarg);
5216 break;
5217 case QEMU_OPTION_startdate:
5219 struct tm tm;
5220 time_t rtc_start_date;
5221 if (!strcmp(optarg, "now")) {
5222 rtc_date_offset = -1;
5223 } else {
5224 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5225 &tm.tm_year,
5226 &tm.tm_mon,
5227 &tm.tm_mday,
5228 &tm.tm_hour,
5229 &tm.tm_min,
5230 &tm.tm_sec) == 6) {
5231 /* OK */
5232 } else if (sscanf(optarg, "%d-%d-%d",
5233 &tm.tm_year,
5234 &tm.tm_mon,
5235 &tm.tm_mday) == 3) {
5236 tm.tm_hour = 0;
5237 tm.tm_min = 0;
5238 tm.tm_sec = 0;
5239 } else {
5240 goto date_fail;
5242 tm.tm_year -= 1900;
5243 tm.tm_mon--;
5244 rtc_start_date = mktimegm(&tm);
5245 if (rtc_start_date == -1) {
5246 date_fail:
5247 fprintf(stderr, "Invalid date format. Valid format are:\n"
5248 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5249 exit(1);
5251 rtc_date_offset = time(NULL) - rtc_start_date;
5254 break;
5255 case QEMU_OPTION_tb_size:
5256 tb_size = strtol(optarg, NULL, 0);
5257 if (tb_size < 0)
5258 tb_size = 0;
5259 break;
5260 case QEMU_OPTION_icount:
5261 use_icount = 1;
5262 if (strcmp(optarg, "auto") == 0) {
5263 icount_time_shift = -1;
5264 } else {
5265 icount_time_shift = strtol(optarg, NULL, 0);
5267 break;
5268 case QEMU_OPTION_incoming:
5269 incoming = optarg;
5270 break;
5275 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5276 if (kvm_allowed && kqemu_allowed) {
5277 fprintf(stderr,
5278 "You can not enable both KVM and kqemu at the same time\n");
5279 exit(1);
5281 #endif
5283 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5284 if (smp_cpus > machine->max_cpus) {
5285 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5286 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5287 machine->max_cpus);
5288 exit(1);
5291 if (nographic) {
5292 if (serial_device_index == 0)
5293 serial_devices[0] = "stdio";
5294 if (parallel_device_index == 0)
5295 parallel_devices[0] = "null";
5296 if (strncmp(monitor_device, "vc", 2) == 0)
5297 monitor_device = "stdio";
5298 if (virtio_console_index == 0)
5299 virtio_consoles[0] = "null";
5302 #ifndef _WIN32
5303 if (daemonize) {
5304 pid_t pid;
5306 if (pipe(fds) == -1)
5307 exit(1);
5309 pid = fork();
5310 if (pid > 0) {
5311 uint8_t status;
5312 ssize_t len;
5314 close(fds[1]);
5316 again:
5317 len = read(fds[0], &status, 1);
5318 if (len == -1 && (errno == EINTR))
5319 goto again;
5321 if (len != 1)
5322 exit(1);
5323 else if (status == 1) {
5324 fprintf(stderr, "Could not acquire pidfile\n");
5325 exit(1);
5326 } else
5327 exit(0);
5328 } else if (pid < 0)
5329 exit(1);
5331 setsid();
5333 pid = fork();
5334 if (pid > 0)
5335 exit(0);
5336 else if (pid < 0)
5337 exit(1);
5339 umask(027);
5341 signal(SIGTSTP, SIG_IGN);
5342 signal(SIGTTOU, SIG_IGN);
5343 signal(SIGTTIN, SIG_IGN);
5345 #endif
5347 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5348 if (daemonize) {
5349 uint8_t status = 1;
5350 write(fds[1], &status, 1);
5351 } else
5352 fprintf(stderr, "Could not acquire pid file\n");
5353 exit(1);
5356 #ifdef USE_KQEMU
5357 if (smp_cpus > 1)
5358 kqemu_allowed = 0;
5359 #endif
5360 linux_boot = (kernel_filename != NULL);
5361 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5363 if (!linux_boot && net_boot == 0 &&
5364 !machine->nodisk_ok && nb_drives_opt == 0)
5365 help(1);
5367 if (!linux_boot && *kernel_cmdline != '\0') {
5368 fprintf(stderr, "-append only allowed with -kernel option\n");
5369 exit(1);
5372 if (!linux_boot && initrd_filename != NULL) {
5373 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5374 exit(1);
5377 /* boot to floppy or the default cd if no hard disk defined yet */
5378 if (!boot_devices[0]) {
5379 boot_devices = "cad";
5381 setvbuf(stdout, NULL, _IOLBF, 0);
5383 init_timers();
5384 if (init_timer_alarm() < 0) {
5385 fprintf(stderr, "could not initialize alarm timer\n");
5386 exit(1);
5388 if (use_icount && icount_time_shift < 0) {
5389 use_icount = 2;
5390 /* 125MIPS seems a reasonable initial guess at the guest speed.
5391 It will be corrected fairly quickly anyway. */
5392 icount_time_shift = 3;
5393 init_icount_adjust();
5396 #ifdef _WIN32
5397 socket_init();
5398 #endif
5400 /* init network clients */
5401 if (nb_net_clients == 0) {
5402 /* if no clients, we use a default config */
5403 net_clients[nb_net_clients++] = "nic";
5404 #ifdef CONFIG_SLIRP
5405 net_clients[nb_net_clients++] = "user";
5406 #endif
5409 for(i = 0;i < nb_net_clients; i++) {
5410 if (net_client_parse(net_clients[i]) < 0)
5411 exit(1);
5413 net_client_check();
5415 #ifdef TARGET_I386
5416 /* XXX: this should be moved in the PC machine instantiation code */
5417 if (net_boot != 0) {
5418 int netroms = 0;
5419 for (i = 0; i < nb_nics && i < 4; i++) {
5420 const char *model = nd_table[i].model;
5421 char buf[1024];
5422 if (net_boot & (1 << i)) {
5423 if (model == NULL)
5424 model = "ne2k_pci";
5425 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5426 if (get_image_size(buf) > 0) {
5427 if (nb_option_roms >= MAX_OPTION_ROMS) {
5428 fprintf(stderr, "Too many option ROMs\n");
5429 exit(1);
5431 option_rom[nb_option_roms] = strdup(buf);
5432 nb_option_roms++;
5433 netroms++;
5437 if (netroms == 0) {
5438 fprintf(stderr, "No valid PXE rom found for network device\n");
5439 exit(1);
5442 #endif
5444 /* init the bluetooth world */
5445 for (i = 0; i < nb_bt_opts; i++)
5446 if (bt_parse(bt_opts[i]))
5447 exit(1);
5449 /* init the memory */
5450 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5452 if (machine->ram_require & RAMSIZE_FIXED) {
5453 if (ram_size > 0) {
5454 if (ram_size < phys_ram_size) {
5455 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5456 machine->name, (unsigned long long) phys_ram_size);
5457 exit(-1);
5460 phys_ram_size = ram_size;
5461 } else
5462 ram_size = phys_ram_size;
5463 } else {
5464 if (ram_size == 0)
5465 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5467 phys_ram_size += ram_size;
5470 phys_ram_base = qemu_vmalloc(phys_ram_size);
5471 if (!phys_ram_base) {
5472 fprintf(stderr, "Could not allocate physical memory\n");
5473 exit(1);
5476 /* init the dynamic translator */
5477 cpu_exec_init_all(tb_size * 1024 * 1024);
5479 bdrv_init();
5481 /* we always create the cdrom drive, even if no disk is there */
5483 if (nb_drives_opt < MAX_DRIVES)
5484 drive_add(NULL, CDROM_ALIAS);
5486 /* we always create at least one floppy */
5488 if (nb_drives_opt < MAX_DRIVES)
5489 drive_add(NULL, FD_ALIAS, 0);
5491 /* we always create one sd slot, even if no card is in it */
5493 if (nb_drives_opt < MAX_DRIVES)
5494 drive_add(NULL, SD_ALIAS);
5496 /* open the virtual block devices */
5498 for(i = 0; i < nb_drives_opt; i++)
5499 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5500 exit(1);
5502 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5503 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5505 #ifndef _WIN32
5506 /* must be after terminal init, SDL library changes signal handlers */
5507 termsig_setup();
5508 #endif
5510 /* Maintain compatibility with multiple stdio monitors */
5511 if (!strcmp(monitor_device,"stdio")) {
5512 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5513 const char *devname = serial_devices[i];
5514 if (devname && !strcmp(devname,"mon:stdio")) {
5515 monitor_device = NULL;
5516 break;
5517 } else if (devname && !strcmp(devname,"stdio")) {
5518 monitor_device = NULL;
5519 serial_devices[i] = "mon:stdio";
5520 break;
5525 if (kvm_enabled()) {
5526 int ret;
5528 ret = kvm_init(smp_cpus);
5529 if (ret < 0) {
5530 fprintf(stderr, "failed to initialize KVM\n");
5531 exit(1);
5535 if (monitor_device) {
5536 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5537 if (!monitor_hd) {
5538 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5539 exit(1);
5543 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5544 const char *devname = serial_devices[i];
5545 if (devname && strcmp(devname, "none")) {
5546 char label[32];
5547 snprintf(label, sizeof(label), "serial%d", i);
5548 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5549 if (!serial_hds[i]) {
5550 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5551 devname);
5552 exit(1);
5557 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5558 const char *devname = parallel_devices[i];
5559 if (devname && strcmp(devname, "none")) {
5560 char label[32];
5561 snprintf(label, sizeof(label), "parallel%d", i);
5562 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5563 if (!parallel_hds[i]) {
5564 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5565 devname);
5566 exit(1);
5571 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5572 const char *devname = virtio_consoles[i];
5573 if (devname && strcmp(devname, "none")) {
5574 char label[32];
5575 snprintf(label, sizeof(label), "virtcon%d", i);
5576 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5577 if (!virtcon_hds[i]) {
5578 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5579 devname);
5580 exit(1);
5585 machine->init(ram_size, vga_ram_size, boot_devices,
5586 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5588 /* Set KVM's vcpu state to qemu's initial CPUState. */
5589 if (kvm_enabled()) {
5590 int ret;
5592 ret = kvm_sync_vcpus();
5593 if (ret < 0) {
5594 fprintf(stderr, "failed to initialize vcpus\n");
5595 exit(1);
5599 /* init USB devices */
5600 if (usb_enabled) {
5601 for(i = 0; i < usb_devices_index; i++) {
5602 if (usb_device_add(usb_devices[i]) < 0) {
5603 fprintf(stderr, "Warning: could not add USB device %s\n",
5604 usb_devices[i]);
5609 if (!display_state)
5610 dumb_display_init();
5611 /* just use the first displaystate for the moment */
5612 ds = display_state;
5613 /* terminal init */
5614 if (nographic) {
5615 if (curses) {
5616 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5617 exit(1);
5619 } else {
5620 #if defined(CONFIG_CURSES)
5621 if (curses) {
5622 /* At the moment curses cannot be used with other displays */
5623 curses_display_init(ds, full_screen);
5624 } else
5625 #endif
5627 if (vnc_display != NULL) {
5628 vnc_display_init(ds);
5629 if (vnc_display_open(ds, vnc_display) < 0)
5630 exit(1);
5632 #if defined(CONFIG_SDL)
5633 if (sdl || !vnc_display)
5634 sdl_display_init(ds, full_screen, no_frame);
5635 #elif defined(CONFIG_COCOA)
5636 if (sdl || !vnc_display)
5637 cocoa_display_init(ds, full_screen);
5638 #endif
5641 dpy_resize(ds);
5643 dcl = ds->listeners;
5644 while (dcl != NULL) {
5645 if (dcl->dpy_refresh != NULL) {
5646 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5647 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5649 dcl = dcl->next;
5652 if (nographic || (vnc_display && !sdl)) {
5653 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5654 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5657 text_consoles_set_display(display_state);
5659 if (monitor_device && monitor_hd)
5660 monitor_init(monitor_hd, !nographic);
5662 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5663 const char *devname = serial_devices[i];
5664 if (devname && strcmp(devname, "none")) {
5665 char label[32];
5666 snprintf(label, sizeof(label), "serial%d", i);
5667 if (strstart(devname, "vc", 0))
5668 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5672 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5673 const char *devname = parallel_devices[i];
5674 if (devname && strcmp(devname, "none")) {
5675 char label[32];
5676 snprintf(label, sizeof(label), "parallel%d", i);
5677 if (strstart(devname, "vc", 0))
5678 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5682 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5683 const char *devname = virtio_consoles[i];
5684 if (virtcon_hds[i] && devname) {
5685 char label[32];
5686 snprintf(label, sizeof(label), "virtcon%d", i);
5687 if (strstart(devname, "vc", 0))
5688 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5692 #ifdef CONFIG_GDBSTUB
5693 if (use_gdbstub) {
5694 /* XXX: use standard host:port notation and modify options
5695 accordingly. */
5696 if (gdbserver_start(gdbstub_port) < 0) {
5697 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5698 gdbstub_port);
5699 exit(1);
5702 #endif
5704 if (loadvm)
5705 do_loadvm(loadvm);
5707 if (incoming) {
5708 autostart = 0; /* fixme how to deal with -daemonize */
5709 qemu_start_incoming_migration(incoming);
5713 /* XXX: simplify init */
5714 read_passwords();
5715 if (autostart) {
5716 vm_start();
5720 if (daemonize) {
5721 uint8_t status = 0;
5722 ssize_t len;
5723 int fd;
5725 again1:
5726 len = write(fds[1], &status, 1);
5727 if (len == -1 && (errno == EINTR))
5728 goto again1;
5730 if (len != 1)
5731 exit(1);
5733 chdir("/");
5734 TFR(fd = open("/dev/null", O_RDWR));
5735 if (fd == -1)
5736 exit(1);
5738 dup2(fd, 0);
5739 dup2(fd, 1);
5740 dup2(fd, 2);
5742 close(fd);
5745 main_loop();
5746 quit_timers();
5747 net_cleanup();
5749 return 0;