target-ppc: Remove a few TCG temp variable leaks
[qemu/qemu-JZ.git] / vl.c
blob7bcffd334ab77c36737b8530696842f4a61b7996
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "block.h"
40 #include "audio/audio.h"
41 #include "migration.h"
42 #include "kvm.h"
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <time.h>
48 #include <errno.h>
49 #include <sys/time.h>
50 #include <zlib.h>
52 #ifndef _WIN32
53 #include <sys/times.h>
54 #include <sys/wait.h>
55 #include <termios.h>
56 #include <sys/mman.h>
57 #include <sys/ioctl.h>
58 #include <sys/resource.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <net/if.h>
62 #if defined(__NetBSD__)
63 #include <net/if_tap.h>
64 #endif
65 #ifdef __linux__
66 #include <linux/if_tun.h>
67 #endif
68 #include <arpa/inet.h>
69 #include <dirent.h>
70 #include <netdb.h>
71 #include <sys/select.h>
72 #ifdef _BSD
73 #include <sys/stat.h>
74 #ifdef __FreeBSD__
75 #include <libutil.h>
76 #else
77 #include <util.h>
78 #endif
79 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
80 #include <freebsd/stdlib.h>
81 #else
82 #ifdef __linux__
83 #include <pty.h>
84 #include <malloc.h>
85 #include <linux/rtc.h>
87 /* For the benefit of older linux systems which don't supply it,
88 we use a local copy of hpet.h. */
89 /* #include <linux/hpet.h> */
90 #include "hpet.h"
92 #include <linux/ppdev.h>
93 #include <linux/parport.h>
94 #endif
95 #ifdef __sun__
96 #include <sys/stat.h>
97 #include <sys/ethernet.h>
98 #include <sys/sockio.h>
99 #include <netinet/arp.h>
100 #include <netinet/in.h>
101 #include <netinet/in_systm.h>
102 #include <netinet/ip.h>
103 #include <netinet/ip_icmp.h> // must come after ip.h
104 #include <netinet/udp.h>
105 #include <netinet/tcp.h>
106 #include <net/if.h>
107 #include <syslog.h>
108 #include <stropts.h>
109 #endif
110 #endif
111 #endif
113 #include "qemu_socket.h"
115 #if defined(CONFIG_SLIRP)
116 #include "libslirp.h"
117 #endif
119 #if defined(__OpenBSD__)
120 #include <util.h>
121 #endif
123 #if defined(CONFIG_VDE)
124 #include <libvdeplug.h>
125 #endif
127 #ifdef _WIN32
128 #include <malloc.h>
129 #include <sys/timeb.h>
130 #include <mmsystem.h>
131 #define getopt_long_only getopt_long
132 #define memalign(align, size) malloc(size)
133 #endif
135 #ifdef CONFIG_SDL
136 #ifdef __APPLE__
137 #include <SDL/SDL.h>
138 #endif
139 #endif /* CONFIG_SDL */
141 #ifdef CONFIG_COCOA
142 #undef main
143 #define main qemu_main
144 #endif /* CONFIG_COCOA */
146 #include "disas.h"
148 #include "exec-all.h"
150 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
151 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
152 #ifdef __sun__
153 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
154 #else
155 #define SMBD_COMMAND "/usr/sbin/smbd"
156 #endif
158 //#define DEBUG_UNUSED_IOPORT
159 //#define DEBUG_IOPORT
160 //#define DEBUG_NET
161 //#define DEBUG_SLIRP
163 #ifdef TARGET_PPC
164 #define DEFAULT_RAM_SIZE 144
165 #else
166 #define DEFAULT_RAM_SIZE 128
167 #endif
169 /* Max number of USB devices that can be specified on the commandline. */
170 #define MAX_USB_CMDLINE 8
172 /* Max number of bluetooth switches on the commandline. */
173 #define MAX_BT_CMDLINE 10
175 /* XXX: use a two level table to limit memory usage */
176 #define MAX_IOPORTS 65536
178 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
179 const char *bios_name = NULL;
180 static void *ioport_opaque[MAX_IOPORTS];
181 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
182 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
183 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
184 to store the VM snapshots */
185 DriveInfo drives_table[MAX_DRIVES+1];
186 int nb_drives;
187 /* point to the block driver where the snapshots are managed */
188 static BlockDriverState *bs_snapshots;
189 static int vga_ram_size;
190 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
191 DisplayState display_state;
192 int nographic;
193 static int curses;
194 const char* keyboard_layout = NULL;
195 int64_t ticks_per_sec;
196 ram_addr_t ram_size;
197 int nb_nics;
198 NICInfo nd_table[MAX_NICS];
199 int vm_running;
200 static int rtc_utc = 1;
201 static int rtc_date_offset = -1; /* -1 means no change */
202 int cirrus_vga_enabled = 1;
203 int vmsvga_enabled = 0;
204 #ifdef TARGET_SPARC
205 int graphic_width = 1024;
206 int graphic_height = 768;
207 int graphic_depth = 8;
208 #else
209 int graphic_width = 800;
210 int graphic_height = 600;
211 int graphic_depth = 15;
212 #endif
213 static int full_screen = 0;
214 static int no_frame = 0;
215 int no_quit = 0;
216 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
217 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
218 #ifdef TARGET_I386
219 int win2k_install_hack = 0;
220 #endif
221 int usb_enabled = 0;
222 int smp_cpus = 1;
223 const char *vnc_display;
224 int acpi_enabled = 1;
225 int fd_bootchk = 1;
226 int no_reboot = 0;
227 int no_shutdown = 0;
228 int cursor_hide = 1;
229 int graphic_rotate = 0;
230 int daemonize = 0;
231 const char *option_rom[MAX_OPTION_ROMS];
232 int nb_option_roms;
233 int semihosting_enabled = 0;
234 #ifdef TARGET_ARM
235 int old_param = 0;
236 #endif
237 const char *qemu_name;
238 int alt_grab = 0;
239 #ifdef TARGET_SPARC
240 unsigned int nb_prom_envs = 0;
241 const char *prom_envs[MAX_PROM_ENVS];
242 #endif
243 static int nb_drives_opt;
244 static struct drive_opt {
245 const char *file;
246 char opt[1024];
247 } drives_opt[MAX_DRIVES];
249 static CPUState *cur_cpu;
250 static CPUState *next_cpu;
251 static int event_pending = 1;
252 /* Conversion factor from emulated instructions to virtual clock ticks. */
253 static int icount_time_shift;
254 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
255 #define MAX_ICOUNT_SHIFT 10
256 /* Compensate for varying guest execution speed. */
257 static int64_t qemu_icount_bias;
258 static QEMUTimer *icount_rt_timer;
259 static QEMUTimer *icount_vm_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 #ifdef DEBUG_IOPORT
415 if (loglevel & CPU_LOG_IOPORT)
416 fprintf(logfile, "outb: %04x %02x\n", addr, val);
417 #endif
418 ioport_write(0, addr, val);
419 #ifdef USE_KQEMU
420 if (env)
421 env->last_io_time = cpu_get_time_fast();
422 #endif
425 void cpu_outw(CPUState *env, int addr, int val)
427 #ifdef DEBUG_IOPORT
428 if (loglevel & CPU_LOG_IOPORT)
429 fprintf(logfile, "outw: %04x %04x\n", addr, val);
430 #endif
431 ioport_write(1, addr, val);
432 #ifdef USE_KQEMU
433 if (env)
434 env->last_io_time = cpu_get_time_fast();
435 #endif
438 void cpu_outl(CPUState *env, int addr, int val)
440 #ifdef DEBUG_IOPORT
441 if (loglevel & CPU_LOG_IOPORT)
442 fprintf(logfile, "outl: %04x %08x\n", addr, val);
443 #endif
444 ioport_write(2, addr, val);
445 #ifdef USE_KQEMU
446 if (env)
447 env->last_io_time = cpu_get_time_fast();
448 #endif
451 int cpu_inb(CPUState *env, int addr)
453 int val;
454 val = ioport_read(0, addr);
455 #ifdef DEBUG_IOPORT
456 if (loglevel & CPU_LOG_IOPORT)
457 fprintf(logfile, "inb : %04x %02x\n", addr, val);
458 #endif
459 #ifdef USE_KQEMU
460 if (env)
461 env->last_io_time = cpu_get_time_fast();
462 #endif
463 return val;
466 int cpu_inw(CPUState *env, int addr)
468 int val;
469 val = ioport_read(1, addr);
470 #ifdef DEBUG_IOPORT
471 if (loglevel & CPU_LOG_IOPORT)
472 fprintf(logfile, "inw : %04x %04x\n", addr, val);
473 #endif
474 #ifdef USE_KQEMU
475 if (env)
476 env->last_io_time = cpu_get_time_fast();
477 #endif
478 return val;
481 int cpu_inl(CPUState *env, int addr)
483 int val;
484 val = ioport_read(2, addr);
485 #ifdef DEBUG_IOPORT
486 if (loglevel & CPU_LOG_IOPORT)
487 fprintf(logfile, "inl : %04x %08x\n", addr, val);
488 #endif
489 #ifdef USE_KQEMU
490 if (env)
491 env->last_io_time = cpu_get_time_fast();
492 #endif
493 return val;
496 /***********************************************************/
497 void hw_error(const char *fmt, ...)
499 va_list ap;
500 CPUState *env;
502 va_start(ap, fmt);
503 fprintf(stderr, "qemu: hardware error: ");
504 vfprintf(stderr, fmt, ap);
505 fprintf(stderr, "\n");
506 for(env = first_cpu; env != NULL; env = env->next_cpu) {
507 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
508 #ifdef TARGET_I386
509 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
510 #else
511 cpu_dump_state(env, stderr, fprintf, 0);
512 #endif
514 va_end(ap);
515 abort();
518 /***********************************************************/
519 /* keyboard/mouse */
521 static QEMUPutKBDEvent *qemu_put_kbd_event;
522 static void *qemu_put_kbd_event_opaque;
523 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
524 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
526 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
528 qemu_put_kbd_event_opaque = opaque;
529 qemu_put_kbd_event = func;
532 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
533 void *opaque, int absolute,
534 const char *name)
536 QEMUPutMouseEntry *s, *cursor;
538 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
539 if (!s)
540 return NULL;
542 s->qemu_put_mouse_event = func;
543 s->qemu_put_mouse_event_opaque = opaque;
544 s->qemu_put_mouse_event_absolute = absolute;
545 s->qemu_put_mouse_event_name = qemu_strdup(name);
546 s->next = NULL;
548 if (!qemu_put_mouse_event_head) {
549 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
550 return s;
553 cursor = qemu_put_mouse_event_head;
554 while (cursor->next != NULL)
555 cursor = cursor->next;
557 cursor->next = s;
558 qemu_put_mouse_event_current = s;
560 return s;
563 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
565 QEMUPutMouseEntry *prev = NULL, *cursor;
567 if (!qemu_put_mouse_event_head || entry == NULL)
568 return;
570 cursor = qemu_put_mouse_event_head;
571 while (cursor != NULL && cursor != entry) {
572 prev = cursor;
573 cursor = cursor->next;
576 if (cursor == NULL) // does not exist or list empty
577 return;
578 else if (prev == NULL) { // entry is head
579 qemu_put_mouse_event_head = cursor->next;
580 if (qemu_put_mouse_event_current == entry)
581 qemu_put_mouse_event_current = cursor->next;
582 qemu_free(entry->qemu_put_mouse_event_name);
583 qemu_free(entry);
584 return;
587 prev->next = entry->next;
589 if (qemu_put_mouse_event_current == entry)
590 qemu_put_mouse_event_current = prev;
592 qemu_free(entry->qemu_put_mouse_event_name);
593 qemu_free(entry);
596 void kbd_put_keycode(int keycode)
598 if (qemu_put_kbd_event) {
599 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
603 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
605 QEMUPutMouseEvent *mouse_event;
606 void *mouse_event_opaque;
607 int width;
609 if (!qemu_put_mouse_event_current) {
610 return;
613 mouse_event =
614 qemu_put_mouse_event_current->qemu_put_mouse_event;
615 mouse_event_opaque =
616 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
618 if (mouse_event) {
619 if (graphic_rotate) {
620 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
621 width = 0x7fff;
622 else
623 width = graphic_width - 1;
624 mouse_event(mouse_event_opaque,
625 width - dy, dx, dz, buttons_state);
626 } else
627 mouse_event(mouse_event_opaque,
628 dx, dy, dz, buttons_state);
632 int kbd_mouse_is_absolute(void)
634 if (!qemu_put_mouse_event_current)
635 return 0;
637 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
640 void do_info_mice(void)
642 QEMUPutMouseEntry *cursor;
643 int index = 0;
645 if (!qemu_put_mouse_event_head) {
646 term_printf("No mouse devices connected\n");
647 return;
650 term_printf("Mouse devices available:\n");
651 cursor = qemu_put_mouse_event_head;
652 while (cursor != NULL) {
653 term_printf("%c Mouse #%d: %s\n",
654 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
655 index, cursor->qemu_put_mouse_event_name);
656 index++;
657 cursor = cursor->next;
661 void do_mouse_set(int index)
663 QEMUPutMouseEntry *cursor;
664 int i = 0;
666 if (!qemu_put_mouse_event_head) {
667 term_printf("No mouse devices connected\n");
668 return;
671 cursor = qemu_put_mouse_event_head;
672 while (cursor != NULL && index != i) {
673 i++;
674 cursor = cursor->next;
677 if (cursor != NULL)
678 qemu_put_mouse_event_current = cursor;
679 else
680 term_printf("Mouse at given index not found\n");
683 /* compute with 96 bit intermediate result: (a*b)/c */
684 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
686 union {
687 uint64_t ll;
688 struct {
689 #ifdef WORDS_BIGENDIAN
690 uint32_t high, low;
691 #else
692 uint32_t low, high;
693 #endif
694 } l;
695 } u, res;
696 uint64_t rl, rh;
698 u.ll = a;
699 rl = (uint64_t)u.l.low * (uint64_t)b;
700 rh = (uint64_t)u.l.high * (uint64_t)b;
701 rh += (rl >> 32);
702 res.l.high = rh / c;
703 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
704 return res.ll;
707 /***********************************************************/
708 /* real time host monotonic timer */
710 #define QEMU_TIMER_BASE 1000000000LL
712 #ifdef WIN32
714 static int64_t clock_freq;
716 static void init_get_clock(void)
718 LARGE_INTEGER freq;
719 int ret;
720 ret = QueryPerformanceFrequency(&freq);
721 if (ret == 0) {
722 fprintf(stderr, "Could not calibrate ticks\n");
723 exit(1);
725 clock_freq = freq.QuadPart;
728 static int64_t get_clock(void)
730 LARGE_INTEGER ti;
731 QueryPerformanceCounter(&ti);
732 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
735 #else
737 static int use_rt_clock;
739 static void init_get_clock(void)
741 use_rt_clock = 0;
742 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
744 struct timespec ts;
745 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
746 use_rt_clock = 1;
749 #endif
752 static int64_t get_clock(void)
754 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
755 if (use_rt_clock) {
756 struct timespec ts;
757 clock_gettime(CLOCK_MONOTONIC, &ts);
758 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
759 } else
760 #endif
762 /* XXX: using gettimeofday leads to problems if the date
763 changes, so it should be avoided. */
764 struct timeval tv;
765 gettimeofday(&tv, NULL);
766 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
769 #endif
771 /* Return the virtual CPU time, based on the instruction counter. */
772 static int64_t cpu_get_icount(void)
774 int64_t icount;
775 CPUState *env = cpu_single_env;;
776 icount = qemu_icount;
777 if (env) {
778 if (!can_do_io(env))
779 fprintf(stderr, "Bad clock read\n");
780 icount -= (env->icount_decr.u16.low + env->icount_extra);
782 return qemu_icount_bias + (icount << icount_time_shift);
785 /***********************************************************/
786 /* guest cycle counter */
788 static int64_t cpu_ticks_prev;
789 static int64_t cpu_ticks_offset;
790 static int64_t cpu_clock_offset;
791 static int cpu_ticks_enabled;
793 /* return the host CPU cycle counter and handle stop/restart */
794 int64_t cpu_get_ticks(void)
796 if (use_icount) {
797 return cpu_get_icount();
799 if (!cpu_ticks_enabled) {
800 return cpu_ticks_offset;
801 } else {
802 int64_t ticks;
803 ticks = cpu_get_real_ticks();
804 if (cpu_ticks_prev > ticks) {
805 /* Note: non increasing ticks may happen if the host uses
806 software suspend */
807 cpu_ticks_offset += cpu_ticks_prev - ticks;
809 cpu_ticks_prev = ticks;
810 return ticks + cpu_ticks_offset;
814 /* return the host CPU monotonic timer and handle stop/restart */
815 static int64_t cpu_get_clock(void)
817 int64_t ti;
818 if (!cpu_ticks_enabled) {
819 return cpu_clock_offset;
820 } else {
821 ti = get_clock();
822 return ti + cpu_clock_offset;
826 /* enable cpu_get_ticks() */
827 void cpu_enable_ticks(void)
829 if (!cpu_ticks_enabled) {
830 cpu_ticks_offset -= cpu_get_real_ticks();
831 cpu_clock_offset -= get_clock();
832 cpu_ticks_enabled = 1;
836 /* disable cpu_get_ticks() : the clock is stopped. You must not call
837 cpu_get_ticks() after that. */
838 void cpu_disable_ticks(void)
840 if (cpu_ticks_enabled) {
841 cpu_ticks_offset = cpu_get_ticks();
842 cpu_clock_offset = cpu_get_clock();
843 cpu_ticks_enabled = 0;
847 /***********************************************************/
848 /* timers */
850 #define QEMU_TIMER_REALTIME 0
851 #define QEMU_TIMER_VIRTUAL 1
853 struct QEMUClock {
854 int type;
855 /* XXX: add frequency */
858 struct QEMUTimer {
859 QEMUClock *clock;
860 int64_t expire_time;
861 QEMUTimerCB *cb;
862 void *opaque;
863 struct QEMUTimer *next;
866 struct qemu_alarm_timer {
867 char const *name;
868 unsigned int flags;
870 int (*start)(struct qemu_alarm_timer *t);
871 void (*stop)(struct qemu_alarm_timer *t);
872 void (*rearm)(struct qemu_alarm_timer *t);
873 void *priv;
876 #define ALARM_FLAG_DYNTICKS 0x1
877 #define ALARM_FLAG_EXPIRED 0x2
879 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
881 return t->flags & ALARM_FLAG_DYNTICKS;
884 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
886 if (!alarm_has_dynticks(t))
887 return;
889 t->rearm(t);
892 /* TODO: MIN_TIMER_REARM_US should be optimized */
893 #define MIN_TIMER_REARM_US 250
895 static struct qemu_alarm_timer *alarm_timer;
896 #ifndef _WIN32
897 static int alarm_timer_rfd, alarm_timer_wfd;
898 #endif
900 #ifdef _WIN32
902 struct qemu_alarm_win32 {
903 MMRESULT timerId;
904 HANDLE host_alarm;
905 unsigned int period;
906 } alarm_win32_data = {0, NULL, -1};
908 static int win32_start_timer(struct qemu_alarm_timer *t);
909 static void win32_stop_timer(struct qemu_alarm_timer *t);
910 static void win32_rearm_timer(struct qemu_alarm_timer *t);
912 #else
914 static int unix_start_timer(struct qemu_alarm_timer *t);
915 static void unix_stop_timer(struct qemu_alarm_timer *t);
917 #ifdef __linux__
919 static int dynticks_start_timer(struct qemu_alarm_timer *t);
920 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
921 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
923 static int hpet_start_timer(struct qemu_alarm_timer *t);
924 static void hpet_stop_timer(struct qemu_alarm_timer *t);
926 static int rtc_start_timer(struct qemu_alarm_timer *t);
927 static void rtc_stop_timer(struct qemu_alarm_timer *t);
929 #endif /* __linux__ */
931 #endif /* _WIN32 */
933 /* Correlation between real and virtual time is always going to be
934 fairly approximate, so ignore small variation.
935 When the guest is idle real and virtual time will be aligned in
936 the IO wait loop. */
937 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
939 static void icount_adjust(void)
941 int64_t cur_time;
942 int64_t cur_icount;
943 int64_t delta;
944 static int64_t last_delta;
945 /* If the VM is not running, then do nothing. */
946 if (!vm_running)
947 return;
949 cur_time = cpu_get_clock();
950 cur_icount = qemu_get_clock(vm_clock);
951 delta = cur_icount - cur_time;
952 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
953 if (delta > 0
954 && last_delta + ICOUNT_WOBBLE < delta * 2
955 && icount_time_shift > 0) {
956 /* The guest is getting too far ahead. Slow time down. */
957 icount_time_shift--;
959 if (delta < 0
960 && last_delta - ICOUNT_WOBBLE > delta * 2
961 && icount_time_shift < MAX_ICOUNT_SHIFT) {
962 /* The guest is getting too far behind. Speed time up. */
963 icount_time_shift++;
965 last_delta = delta;
966 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
969 static void icount_adjust_rt(void * opaque)
971 qemu_mod_timer(icount_rt_timer,
972 qemu_get_clock(rt_clock) + 1000);
973 icount_adjust();
976 static void icount_adjust_vm(void * opaque)
978 qemu_mod_timer(icount_vm_timer,
979 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
980 icount_adjust();
983 static void init_icount_adjust(void)
985 /* Have both realtime and virtual time triggers for speed adjustment.
986 The realtime trigger catches emulated time passing too slowly,
987 the virtual time trigger catches emulated time passing too fast.
988 Realtime triggers occur even when idle, so use them less frequently
989 than VM triggers. */
990 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
991 qemu_mod_timer(icount_rt_timer,
992 qemu_get_clock(rt_clock) + 1000);
993 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
994 qemu_mod_timer(icount_vm_timer,
995 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
998 static struct qemu_alarm_timer alarm_timers[] = {
999 #ifndef _WIN32
1000 #ifdef __linux__
1001 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1002 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1003 /* HPET - if available - is preferred */
1004 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1005 /* ...otherwise try RTC */
1006 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1007 #endif
1008 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1009 #else
1010 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1011 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1012 {"win32", 0, win32_start_timer,
1013 win32_stop_timer, NULL, &alarm_win32_data},
1014 #endif
1015 {NULL, }
1018 static void show_available_alarms(void)
1020 int i;
1022 printf("Available alarm timers, in order of precedence:\n");
1023 for (i = 0; alarm_timers[i].name; i++)
1024 printf("%s\n", alarm_timers[i].name);
1027 static void configure_alarms(char const *opt)
1029 int i;
1030 int cur = 0;
1031 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1032 char *arg;
1033 char *name;
1034 struct qemu_alarm_timer tmp;
1036 if (!strcmp(opt, "?")) {
1037 show_available_alarms();
1038 exit(0);
1041 arg = strdup(opt);
1043 /* Reorder the array */
1044 name = strtok(arg, ",");
1045 while (name) {
1046 for (i = 0; i < count && alarm_timers[i].name; i++) {
1047 if (!strcmp(alarm_timers[i].name, name))
1048 break;
1051 if (i == count) {
1052 fprintf(stderr, "Unknown clock %s\n", name);
1053 goto next;
1056 if (i < cur)
1057 /* Ignore */
1058 goto next;
1060 /* Swap */
1061 tmp = alarm_timers[i];
1062 alarm_timers[i] = alarm_timers[cur];
1063 alarm_timers[cur] = tmp;
1065 cur++;
1066 next:
1067 name = strtok(NULL, ",");
1070 free(arg);
1072 if (cur) {
1073 /* Disable remaining timers */
1074 for (i = cur; i < count; i++)
1075 alarm_timers[i].name = NULL;
1076 } else {
1077 show_available_alarms();
1078 exit(1);
1082 QEMUClock *rt_clock;
1083 QEMUClock *vm_clock;
1085 static QEMUTimer *active_timers[2];
1087 static QEMUClock *qemu_new_clock(int type)
1089 QEMUClock *clock;
1090 clock = qemu_mallocz(sizeof(QEMUClock));
1091 if (!clock)
1092 return NULL;
1093 clock->type = type;
1094 return clock;
1097 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1099 QEMUTimer *ts;
1101 ts = qemu_mallocz(sizeof(QEMUTimer));
1102 ts->clock = clock;
1103 ts->cb = cb;
1104 ts->opaque = opaque;
1105 return ts;
1108 void qemu_free_timer(QEMUTimer *ts)
1110 qemu_free(ts);
1113 /* stop a timer, but do not dealloc it */
1114 void qemu_del_timer(QEMUTimer *ts)
1116 QEMUTimer **pt, *t;
1118 /* NOTE: this code must be signal safe because
1119 qemu_timer_expired() can be called from a signal. */
1120 pt = &active_timers[ts->clock->type];
1121 for(;;) {
1122 t = *pt;
1123 if (!t)
1124 break;
1125 if (t == ts) {
1126 *pt = t->next;
1127 break;
1129 pt = &t->next;
1133 /* modify the current timer so that it will be fired when current_time
1134 >= expire_time. The corresponding callback will be called. */
1135 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1137 QEMUTimer **pt, *t;
1139 qemu_del_timer(ts);
1141 /* add the timer in the sorted list */
1142 /* NOTE: this code must be signal safe because
1143 qemu_timer_expired() can be called from a signal. */
1144 pt = &active_timers[ts->clock->type];
1145 for(;;) {
1146 t = *pt;
1147 if (!t)
1148 break;
1149 if (t->expire_time > expire_time)
1150 break;
1151 pt = &t->next;
1153 ts->expire_time = expire_time;
1154 ts->next = *pt;
1155 *pt = ts;
1157 /* Rearm if necessary */
1158 if (pt == &active_timers[ts->clock->type]) {
1159 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1160 qemu_rearm_alarm_timer(alarm_timer);
1162 /* Interrupt execution to force deadline recalculation. */
1163 if (use_icount && cpu_single_env) {
1164 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1169 int qemu_timer_pending(QEMUTimer *ts)
1171 QEMUTimer *t;
1172 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1173 if (t == ts)
1174 return 1;
1176 return 0;
1179 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1181 if (!timer_head)
1182 return 0;
1183 return (timer_head->expire_time <= current_time);
1186 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1188 QEMUTimer *ts;
1190 for(;;) {
1191 ts = *ptimer_head;
1192 if (!ts || ts->expire_time > current_time)
1193 break;
1194 /* remove timer from the list before calling the callback */
1195 *ptimer_head = ts->next;
1196 ts->next = NULL;
1198 /* run the callback (the timer list can be modified) */
1199 ts->cb(ts->opaque);
1203 int64_t qemu_get_clock(QEMUClock *clock)
1205 switch(clock->type) {
1206 case QEMU_TIMER_REALTIME:
1207 return get_clock() / 1000000;
1208 default:
1209 case QEMU_TIMER_VIRTUAL:
1210 if (use_icount) {
1211 return cpu_get_icount();
1212 } else {
1213 return cpu_get_clock();
1218 static void init_timers(void)
1220 init_get_clock();
1221 ticks_per_sec = QEMU_TIMER_BASE;
1222 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1223 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1226 /* save a timer */
1227 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1229 uint64_t expire_time;
1231 if (qemu_timer_pending(ts)) {
1232 expire_time = ts->expire_time;
1233 } else {
1234 expire_time = -1;
1236 qemu_put_be64(f, expire_time);
1239 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1241 uint64_t expire_time;
1243 expire_time = qemu_get_be64(f);
1244 if (expire_time != -1) {
1245 qemu_mod_timer(ts, expire_time);
1246 } else {
1247 qemu_del_timer(ts);
1251 static void timer_save(QEMUFile *f, void *opaque)
1253 if (cpu_ticks_enabled) {
1254 hw_error("cannot save state if virtual timers are running");
1256 qemu_put_be64(f, cpu_ticks_offset);
1257 qemu_put_be64(f, ticks_per_sec);
1258 qemu_put_be64(f, cpu_clock_offset);
1261 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1263 if (version_id != 1 && version_id != 2)
1264 return -EINVAL;
1265 if (cpu_ticks_enabled) {
1266 return -EINVAL;
1268 cpu_ticks_offset=qemu_get_be64(f);
1269 ticks_per_sec=qemu_get_be64(f);
1270 if (version_id == 2) {
1271 cpu_clock_offset=qemu_get_be64(f);
1273 return 0;
1276 #ifdef _WIN32
1277 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1278 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1279 #else
1280 static void host_alarm_handler(int host_signum)
1281 #endif
1283 #if 0
1284 #define DISP_FREQ 1000
1286 static int64_t delta_min = INT64_MAX;
1287 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1288 static int count;
1289 ti = qemu_get_clock(vm_clock);
1290 if (last_clock != 0) {
1291 delta = ti - last_clock;
1292 if (delta < delta_min)
1293 delta_min = delta;
1294 if (delta > delta_max)
1295 delta_max = delta;
1296 delta_cum += delta;
1297 if (++count == DISP_FREQ) {
1298 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1299 muldiv64(delta_min, 1000000, ticks_per_sec),
1300 muldiv64(delta_max, 1000000, ticks_per_sec),
1301 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1302 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1303 count = 0;
1304 delta_min = INT64_MAX;
1305 delta_max = 0;
1306 delta_cum = 0;
1309 last_clock = ti;
1311 #endif
1312 if (alarm_has_dynticks(alarm_timer) ||
1313 (!use_icount &&
1314 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1315 qemu_get_clock(vm_clock))) ||
1316 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1317 qemu_get_clock(rt_clock))) {
1318 CPUState *env = next_cpu;
1320 #ifdef _WIN32
1321 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1322 SetEvent(data->host_alarm);
1323 #else
1324 static const char byte = 0;
1325 write(alarm_timer_wfd, &byte, sizeof(byte));
1326 #endif
1327 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1329 if (env) {
1330 /* stop the currently executing cpu because a timer occured */
1331 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1332 #ifdef USE_KQEMU
1333 if (env->kqemu_enabled) {
1334 kqemu_cpu_interrupt(env);
1336 #endif
1338 event_pending = 1;
1342 static int64_t qemu_next_deadline(void)
1344 int64_t delta;
1346 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1347 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1348 qemu_get_clock(vm_clock);
1349 } else {
1350 /* To avoid problems with overflow limit this to 2^32. */
1351 delta = INT32_MAX;
1354 if (delta < 0)
1355 delta = 0;
1357 return delta;
1360 #if defined(__linux__) || defined(_WIN32)
1361 static uint64_t qemu_next_deadline_dyntick(void)
1363 int64_t delta;
1364 int64_t rtdelta;
1366 if (use_icount)
1367 delta = INT32_MAX;
1368 else
1369 delta = (qemu_next_deadline() + 999) / 1000;
1371 if (active_timers[QEMU_TIMER_REALTIME]) {
1372 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1373 qemu_get_clock(rt_clock))*1000;
1374 if (rtdelta < delta)
1375 delta = rtdelta;
1378 if (delta < MIN_TIMER_REARM_US)
1379 delta = MIN_TIMER_REARM_US;
1381 return delta;
1383 #endif
1385 #ifndef _WIN32
1387 /* Sets a specific flag */
1388 static int fcntl_setfl(int fd, int flag)
1390 int flags;
1392 flags = fcntl(fd, F_GETFL);
1393 if (flags == -1)
1394 return -errno;
1396 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1397 return -errno;
1399 return 0;
1402 #if defined(__linux__)
1404 #define RTC_FREQ 1024
1406 static void enable_sigio_timer(int fd)
1408 struct sigaction act;
1410 /* timer signal */
1411 sigfillset(&act.sa_mask);
1412 act.sa_flags = 0;
1413 act.sa_handler = host_alarm_handler;
1415 sigaction(SIGIO, &act, NULL);
1416 fcntl_setfl(fd, O_ASYNC);
1417 fcntl(fd, F_SETOWN, getpid());
1420 static int hpet_start_timer(struct qemu_alarm_timer *t)
1422 struct hpet_info info;
1423 int r, fd;
1425 fd = open("/dev/hpet", O_RDONLY);
1426 if (fd < 0)
1427 return -1;
1429 /* Set frequency */
1430 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1431 if (r < 0) {
1432 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1433 "error, but for better emulation accuracy type:\n"
1434 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1435 goto fail;
1438 /* Check capabilities */
1439 r = ioctl(fd, HPET_INFO, &info);
1440 if (r < 0)
1441 goto fail;
1443 /* Enable periodic mode */
1444 r = ioctl(fd, HPET_EPI, 0);
1445 if (info.hi_flags && (r < 0))
1446 goto fail;
1448 /* Enable interrupt */
1449 r = ioctl(fd, HPET_IE_ON, 0);
1450 if (r < 0)
1451 goto fail;
1453 enable_sigio_timer(fd);
1454 t->priv = (void *)(long)fd;
1456 return 0;
1457 fail:
1458 close(fd);
1459 return -1;
1462 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1464 int fd = (long)t->priv;
1466 close(fd);
1469 static int rtc_start_timer(struct qemu_alarm_timer *t)
1471 int rtc_fd;
1472 unsigned long current_rtc_freq = 0;
1474 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1475 if (rtc_fd < 0)
1476 return -1;
1477 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1478 if (current_rtc_freq != RTC_FREQ &&
1479 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1480 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1481 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1482 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1483 goto fail;
1485 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1486 fail:
1487 close(rtc_fd);
1488 return -1;
1491 enable_sigio_timer(rtc_fd);
1493 t->priv = (void *)(long)rtc_fd;
1495 return 0;
1498 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1500 int rtc_fd = (long)t->priv;
1502 close(rtc_fd);
1505 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1507 struct sigevent ev;
1508 timer_t host_timer;
1509 struct sigaction act;
1511 sigfillset(&act.sa_mask);
1512 act.sa_flags = 0;
1513 act.sa_handler = host_alarm_handler;
1515 sigaction(SIGALRM, &act, NULL);
1517 ev.sigev_value.sival_int = 0;
1518 ev.sigev_notify = SIGEV_SIGNAL;
1519 ev.sigev_signo = SIGALRM;
1521 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1522 perror("timer_create");
1524 /* disable dynticks */
1525 fprintf(stderr, "Dynamic Ticks disabled\n");
1527 return -1;
1530 t->priv = (void *)host_timer;
1532 return 0;
1535 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1537 timer_t host_timer = (timer_t)t->priv;
1539 timer_delete(host_timer);
1542 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1544 timer_t host_timer = (timer_t)t->priv;
1545 struct itimerspec timeout;
1546 int64_t nearest_delta_us = INT64_MAX;
1547 int64_t current_us;
1549 if (!active_timers[QEMU_TIMER_REALTIME] &&
1550 !active_timers[QEMU_TIMER_VIRTUAL])
1551 return;
1553 nearest_delta_us = qemu_next_deadline_dyntick();
1555 /* check whether a timer is already running */
1556 if (timer_gettime(host_timer, &timeout)) {
1557 perror("gettime");
1558 fprintf(stderr, "Internal timer error: aborting\n");
1559 exit(1);
1561 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1562 if (current_us && current_us <= nearest_delta_us)
1563 return;
1565 timeout.it_interval.tv_sec = 0;
1566 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1567 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1568 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1569 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1570 perror("settime");
1571 fprintf(stderr, "Internal timer error: aborting\n");
1572 exit(1);
1576 #endif /* defined(__linux__) */
1578 static int unix_start_timer(struct qemu_alarm_timer *t)
1580 struct sigaction act;
1581 struct itimerval itv;
1582 int err;
1584 /* timer signal */
1585 sigfillset(&act.sa_mask);
1586 act.sa_flags = 0;
1587 act.sa_handler = host_alarm_handler;
1589 sigaction(SIGALRM, &act, NULL);
1591 itv.it_interval.tv_sec = 0;
1592 /* for i386 kernel 2.6 to get 1 ms */
1593 itv.it_interval.tv_usec = 999;
1594 itv.it_value.tv_sec = 0;
1595 itv.it_value.tv_usec = 10 * 1000;
1597 err = setitimer(ITIMER_REAL, &itv, NULL);
1598 if (err)
1599 return -1;
1601 return 0;
1604 static void unix_stop_timer(struct qemu_alarm_timer *t)
1606 struct itimerval itv;
1608 memset(&itv, 0, sizeof(itv));
1609 setitimer(ITIMER_REAL, &itv, NULL);
1612 #endif /* !defined(_WIN32) */
1614 static void try_to_rearm_timer(void *opaque)
1616 struct qemu_alarm_timer *t = opaque;
1617 #ifndef _WIN32
1618 ssize_t len;
1620 /* Drain the notify pipe */
1621 do {
1622 char buffer[512];
1623 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1624 } while ((len == -1 && errno == EINTR) || len > 0);
1625 #endif
1627 /* vm time timers */
1628 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
1629 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
1630 qemu_get_clock(vm_clock));
1632 /* real time timers */
1633 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
1634 qemu_get_clock(rt_clock));
1636 if (t->flags & ALARM_FLAG_EXPIRED) {
1637 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1638 qemu_rearm_alarm_timer(alarm_timer);
1642 #ifdef _WIN32
1644 static int win32_start_timer(struct qemu_alarm_timer *t)
1646 TIMECAPS tc;
1647 struct qemu_alarm_win32 *data = t->priv;
1648 UINT flags;
1650 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1651 if (!data->host_alarm) {
1652 perror("Failed CreateEvent");
1653 return -1;
1656 memset(&tc, 0, sizeof(tc));
1657 timeGetDevCaps(&tc, sizeof(tc));
1659 if (data->period < tc.wPeriodMin)
1660 data->period = tc.wPeriodMin;
1662 timeBeginPeriod(data->period);
1664 flags = TIME_CALLBACK_FUNCTION;
1665 if (alarm_has_dynticks(t))
1666 flags |= TIME_ONESHOT;
1667 else
1668 flags |= TIME_PERIODIC;
1670 data->timerId = timeSetEvent(1, // interval (ms)
1671 data->period, // resolution
1672 host_alarm_handler, // function
1673 (DWORD)t, // parameter
1674 flags);
1676 if (!data->timerId) {
1677 perror("Failed to initialize win32 alarm timer");
1679 timeEndPeriod(data->period);
1680 CloseHandle(data->host_alarm);
1681 return -1;
1684 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1686 return 0;
1689 static void win32_stop_timer(struct qemu_alarm_timer *t)
1691 struct qemu_alarm_win32 *data = t->priv;
1693 timeKillEvent(data->timerId);
1694 timeEndPeriod(data->period);
1696 CloseHandle(data->host_alarm);
1699 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1701 struct qemu_alarm_win32 *data = t->priv;
1702 uint64_t nearest_delta_us;
1704 if (!active_timers[QEMU_TIMER_REALTIME] &&
1705 !active_timers[QEMU_TIMER_VIRTUAL])
1706 return;
1708 nearest_delta_us = qemu_next_deadline_dyntick();
1709 nearest_delta_us /= 1000;
1711 timeKillEvent(data->timerId);
1713 data->timerId = timeSetEvent(1,
1714 data->period,
1715 host_alarm_handler,
1716 (DWORD)t,
1717 TIME_ONESHOT | TIME_PERIODIC);
1719 if (!data->timerId) {
1720 perror("Failed to re-arm win32 alarm timer");
1722 timeEndPeriod(data->period);
1723 CloseHandle(data->host_alarm);
1724 exit(1);
1728 #endif /* _WIN32 */
1730 static int init_timer_alarm(void)
1732 struct qemu_alarm_timer *t = NULL;
1733 int i, err = -1;
1735 #ifndef _WIN32
1736 int fds[2];
1738 err = pipe(fds);
1739 if (err == -1)
1740 return -errno;
1742 err = fcntl_setfl(fds[0], O_NONBLOCK);
1743 if (err < 0)
1744 goto fail;
1746 err = fcntl_setfl(fds[1], O_NONBLOCK);
1747 if (err < 0)
1748 goto fail;
1750 alarm_timer_rfd = fds[0];
1751 alarm_timer_wfd = fds[1];
1752 #endif
1754 for (i = 0; alarm_timers[i].name; i++) {
1755 t = &alarm_timers[i];
1757 err = t->start(t);
1758 if (!err)
1759 break;
1762 if (err) {
1763 err = -ENOENT;
1764 goto fail;
1767 #ifndef _WIN32
1768 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1769 try_to_rearm_timer, NULL, t);
1770 #endif
1772 alarm_timer = t;
1774 return 0;
1776 fail:
1777 #ifndef _WIN32
1778 close(fds[0]);
1779 close(fds[1]);
1780 #endif
1781 return err;
1784 static void quit_timers(void)
1786 alarm_timer->stop(alarm_timer);
1787 alarm_timer = NULL;
1790 /***********************************************************/
1791 /* host time/date access */
1792 void qemu_get_timedate(struct tm *tm, int offset)
1794 time_t ti;
1795 struct tm *ret;
1797 time(&ti);
1798 ti += offset;
1799 if (rtc_date_offset == -1) {
1800 if (rtc_utc)
1801 ret = gmtime(&ti);
1802 else
1803 ret = localtime(&ti);
1804 } else {
1805 ti -= rtc_date_offset;
1806 ret = gmtime(&ti);
1809 memcpy(tm, ret, sizeof(struct tm));
1812 int qemu_timedate_diff(struct tm *tm)
1814 time_t seconds;
1816 if (rtc_date_offset == -1)
1817 if (rtc_utc)
1818 seconds = mktimegm(tm);
1819 else
1820 seconds = mktime(tm);
1821 else
1822 seconds = mktimegm(tm) + rtc_date_offset;
1824 return seconds - time(NULL);
1827 #ifdef _WIN32
1828 static void socket_cleanup(void)
1830 WSACleanup();
1833 static int socket_init(void)
1835 WSADATA Data;
1836 int ret, err;
1838 ret = WSAStartup(MAKEWORD(2,2), &Data);
1839 if (ret != 0) {
1840 err = WSAGetLastError();
1841 fprintf(stderr, "WSAStartup: %d\n", err);
1842 return -1;
1844 atexit(socket_cleanup);
1845 return 0;
1847 #endif
1849 const char *get_opt_name(char *buf, int buf_size, const char *p)
1851 char *q;
1853 q = buf;
1854 while (*p != '\0' && *p != '=') {
1855 if (q && (q - buf) < buf_size - 1)
1856 *q++ = *p;
1857 p++;
1859 if (q)
1860 *q = '\0';
1862 return p;
1865 const char *get_opt_value(char *buf, int buf_size, const char *p)
1867 char *q;
1869 q = buf;
1870 while (*p != '\0') {
1871 if (*p == ',') {
1872 if (*(p + 1) != ',')
1873 break;
1874 p++;
1876 if (q && (q - buf) < buf_size - 1)
1877 *q++ = *p;
1878 p++;
1880 if (q)
1881 *q = '\0';
1883 return p;
1886 int get_param_value(char *buf, int buf_size,
1887 const char *tag, const char *str)
1889 const char *p;
1890 char option[128];
1892 p = str;
1893 for(;;) {
1894 p = get_opt_name(option, sizeof(option), p);
1895 if (*p != '=')
1896 break;
1897 p++;
1898 if (!strcmp(tag, option)) {
1899 (void)get_opt_value(buf, buf_size, p);
1900 return strlen(buf);
1901 } else {
1902 p = get_opt_value(NULL, 0, p);
1904 if (*p != ',')
1905 break;
1906 p++;
1908 return 0;
1911 int check_params(char *buf, int buf_size,
1912 const char * const *params, const char *str)
1914 const char *p;
1915 int i;
1917 p = str;
1918 for(;;) {
1919 p = get_opt_name(buf, buf_size, p);
1920 if (*p != '=')
1921 return -1;
1922 p++;
1923 for(i = 0; params[i] != NULL; i++)
1924 if (!strcmp(params[i], buf))
1925 break;
1926 if (params[i] == NULL)
1927 return -1;
1928 p = get_opt_value(NULL, 0, p);
1929 if (*p != ',')
1930 break;
1931 p++;
1933 return 0;
1936 /***********************************************************/
1937 /* Bluetooth support */
1938 static int nb_hcis;
1939 static int cur_hci;
1940 static struct HCIInfo *hci_table[MAX_NICS];
1942 static struct bt_vlan_s {
1943 struct bt_scatternet_s net;
1944 int id;
1945 struct bt_vlan_s *next;
1946 } *first_bt_vlan;
1948 /* find or alloc a new bluetooth "VLAN" */
1949 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1951 struct bt_vlan_s **pvlan, *vlan;
1952 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1953 if (vlan->id == id)
1954 return &vlan->net;
1956 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1957 vlan->id = id;
1958 pvlan = &first_bt_vlan;
1959 while (*pvlan != NULL)
1960 pvlan = &(*pvlan)->next;
1961 *pvlan = vlan;
1962 return &vlan->net;
1965 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1969 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1971 return -ENOTSUP;
1974 static struct HCIInfo null_hci = {
1975 .cmd_send = null_hci_send,
1976 .sco_send = null_hci_send,
1977 .acl_send = null_hci_send,
1978 .bdaddr_set = null_hci_addr_set,
1981 struct HCIInfo *qemu_next_hci(void)
1983 if (cur_hci == nb_hcis)
1984 return &null_hci;
1986 return hci_table[cur_hci++];
1989 static struct HCIInfo *hci_init(const char *str)
1991 char *endp;
1992 struct bt_scatternet_s *vlan = 0;
1994 if (!strcmp(str, "null"))
1995 /* null */
1996 return &null_hci;
1997 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1998 /* host[:hciN] */
1999 return bt_host_hci(str[4] ? str + 5 : "hci0");
2000 else if (!strncmp(str, "hci", 3)) {
2001 /* hci[,vlan=n] */
2002 if (str[3]) {
2003 if (!strncmp(str + 3, ",vlan=", 6)) {
2004 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2005 if (*endp)
2006 vlan = 0;
2008 } else
2009 vlan = qemu_find_bt_vlan(0);
2010 if (vlan)
2011 return bt_new_hci(vlan);
2014 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2016 return 0;
2019 static int bt_hci_parse(const char *str)
2021 struct HCIInfo *hci;
2022 bdaddr_t bdaddr;
2024 if (nb_hcis >= MAX_NICS) {
2025 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2026 return -1;
2029 hci = hci_init(str);
2030 if (!hci)
2031 return -1;
2033 bdaddr.b[0] = 0x52;
2034 bdaddr.b[1] = 0x54;
2035 bdaddr.b[2] = 0x00;
2036 bdaddr.b[3] = 0x12;
2037 bdaddr.b[4] = 0x34;
2038 bdaddr.b[5] = 0x56 + nb_hcis;
2039 hci->bdaddr_set(hci, bdaddr.b);
2041 hci_table[nb_hcis++] = hci;
2043 return 0;
2046 static void bt_vhci_add(int vlan_id)
2048 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2050 if (!vlan->slave)
2051 fprintf(stderr, "qemu: warning: adding a VHCI to "
2052 "an empty scatternet %i\n", vlan_id);
2054 bt_vhci_init(bt_new_hci(vlan));
2057 static struct bt_device_s *bt_device_add(const char *opt)
2059 struct bt_scatternet_s *vlan;
2060 int vlan_id = 0;
2061 char *endp = strstr(opt, ",vlan=");
2062 int len = (endp ? endp - opt : strlen(opt)) + 1;
2063 char devname[10];
2065 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2067 if (endp) {
2068 vlan_id = strtol(endp + 6, &endp, 0);
2069 if (*endp) {
2070 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2071 return 0;
2075 vlan = qemu_find_bt_vlan(vlan_id);
2077 if (!vlan->slave)
2078 fprintf(stderr, "qemu: warning: adding a slave device to "
2079 "an empty scatternet %i\n", vlan_id);
2081 if (!strcmp(devname, "keyboard"))
2082 return bt_keyboard_init(vlan);
2084 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2085 return 0;
2088 static int bt_parse(const char *opt)
2090 const char *endp, *p;
2091 int vlan;
2093 if (strstart(opt, "hci", &endp)) {
2094 if (!*endp || *endp == ',') {
2095 if (*endp)
2096 if (!strstart(endp, ",vlan=", 0))
2097 opt = endp + 1;
2099 return bt_hci_parse(opt);
2101 } else if (strstart(opt, "vhci", &endp)) {
2102 if (!*endp || *endp == ',') {
2103 if (*endp) {
2104 if (strstart(endp, ",vlan=", &p)) {
2105 vlan = strtol(p, (char **) &endp, 0);
2106 if (*endp) {
2107 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2108 return 1;
2110 } else {
2111 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2112 return 1;
2114 } else
2115 vlan = 0;
2117 bt_vhci_add(vlan);
2118 return 0;
2120 } else if (strstart(opt, "device:", &endp))
2121 return !bt_device_add(endp);
2123 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2124 return 1;
2127 /***********************************************************/
2128 /* QEMU Block devices */
2130 #define HD_ALIAS "index=%d,media=disk"
2131 #ifdef TARGET_PPC
2132 #define CDROM_ALIAS "index=1,media=cdrom"
2133 #else
2134 #define CDROM_ALIAS "index=2,media=cdrom"
2135 #endif
2136 #define FD_ALIAS "index=%d,if=floppy"
2137 #define PFLASH_ALIAS "if=pflash"
2138 #define MTD_ALIAS "if=mtd"
2139 #define SD_ALIAS "index=0,if=sd"
2141 static int drive_add(const char *file, const char *fmt, ...)
2143 va_list ap;
2145 if (nb_drives_opt >= MAX_DRIVES) {
2146 fprintf(stderr, "qemu: too many drives\n");
2147 exit(1);
2150 drives_opt[nb_drives_opt].file = file;
2151 va_start(ap, fmt);
2152 vsnprintf(drives_opt[nb_drives_opt].opt,
2153 sizeof(drives_opt[0].opt), fmt, ap);
2154 va_end(ap);
2156 return nb_drives_opt++;
2159 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2161 int index;
2163 /* seek interface, bus and unit */
2165 for (index = 0; index < nb_drives; index++)
2166 if (drives_table[index].type == type &&
2167 drives_table[index].bus == bus &&
2168 drives_table[index].unit == unit)
2169 return index;
2171 return -1;
2174 int drive_get_max_bus(BlockInterfaceType type)
2176 int max_bus;
2177 int index;
2179 max_bus = -1;
2180 for (index = 0; index < nb_drives; index++) {
2181 if(drives_table[index].type == type &&
2182 drives_table[index].bus > max_bus)
2183 max_bus = drives_table[index].bus;
2185 return max_bus;
2188 static void bdrv_format_print(void *opaque, const char *name)
2190 fprintf(stderr, " %s", name);
2193 static int drive_init(struct drive_opt *arg, int snapshot,
2194 QEMUMachine *machine)
2196 char buf[128];
2197 char file[1024];
2198 char devname[128];
2199 const char *mediastr = "";
2200 BlockInterfaceType type;
2201 enum { MEDIA_DISK, MEDIA_CDROM } media;
2202 int bus_id, unit_id;
2203 int cyls, heads, secs, translation;
2204 BlockDriverState *bdrv;
2205 BlockDriver *drv = NULL;
2206 int max_devs;
2207 int index;
2208 int cache;
2209 int bdrv_flags;
2210 char *str = arg->opt;
2211 static const char * const params[] = { "bus", "unit", "if", "index",
2212 "cyls", "heads", "secs", "trans",
2213 "media", "snapshot", "file",
2214 "cache", "format", NULL };
2216 if (check_params(buf, sizeof(buf), params, str) < 0) {
2217 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2218 buf, str);
2219 return -1;
2222 file[0] = 0;
2223 cyls = heads = secs = 0;
2224 bus_id = 0;
2225 unit_id = -1;
2226 translation = BIOS_ATA_TRANSLATION_AUTO;
2227 index = -1;
2228 cache = 1;
2230 if (machine->use_scsi) {
2231 type = IF_SCSI;
2232 max_devs = MAX_SCSI_DEVS;
2233 pstrcpy(devname, sizeof(devname), "scsi");
2234 } else {
2235 type = IF_IDE;
2236 max_devs = MAX_IDE_DEVS;
2237 pstrcpy(devname, sizeof(devname), "ide");
2239 media = MEDIA_DISK;
2241 /* extract parameters */
2243 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2244 bus_id = strtol(buf, NULL, 0);
2245 if (bus_id < 0) {
2246 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2247 return -1;
2251 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2252 unit_id = strtol(buf, NULL, 0);
2253 if (unit_id < 0) {
2254 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2255 return -1;
2259 if (get_param_value(buf, sizeof(buf), "if", str)) {
2260 pstrcpy(devname, sizeof(devname), buf);
2261 if (!strcmp(buf, "ide")) {
2262 type = IF_IDE;
2263 max_devs = MAX_IDE_DEVS;
2264 } else if (!strcmp(buf, "scsi")) {
2265 type = IF_SCSI;
2266 max_devs = MAX_SCSI_DEVS;
2267 } else if (!strcmp(buf, "floppy")) {
2268 type = IF_FLOPPY;
2269 max_devs = 0;
2270 } else if (!strcmp(buf, "pflash")) {
2271 type = IF_PFLASH;
2272 max_devs = 0;
2273 } else if (!strcmp(buf, "mtd")) {
2274 type = IF_MTD;
2275 max_devs = 0;
2276 } else if (!strcmp(buf, "sd")) {
2277 type = IF_SD;
2278 max_devs = 0;
2279 } else {
2280 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2281 return -1;
2285 if (get_param_value(buf, sizeof(buf), "index", str)) {
2286 index = strtol(buf, NULL, 0);
2287 if (index < 0) {
2288 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2289 return -1;
2293 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2294 cyls = strtol(buf, NULL, 0);
2297 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2298 heads = strtol(buf, NULL, 0);
2301 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2302 secs = strtol(buf, NULL, 0);
2305 if (cyls || heads || secs) {
2306 if (cyls < 1 || cyls > 16383) {
2307 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2308 return -1;
2310 if (heads < 1 || heads > 16) {
2311 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2312 return -1;
2314 if (secs < 1 || secs > 63) {
2315 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2316 return -1;
2320 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2321 if (!cyls) {
2322 fprintf(stderr,
2323 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2324 str);
2325 return -1;
2327 if (!strcmp(buf, "none"))
2328 translation = BIOS_ATA_TRANSLATION_NONE;
2329 else if (!strcmp(buf, "lba"))
2330 translation = BIOS_ATA_TRANSLATION_LBA;
2331 else if (!strcmp(buf, "auto"))
2332 translation = BIOS_ATA_TRANSLATION_AUTO;
2333 else {
2334 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2335 return -1;
2339 if (get_param_value(buf, sizeof(buf), "media", str)) {
2340 if (!strcmp(buf, "disk")) {
2341 media = MEDIA_DISK;
2342 } else if (!strcmp(buf, "cdrom")) {
2343 if (cyls || secs || heads) {
2344 fprintf(stderr,
2345 "qemu: '%s' invalid physical CHS format\n", str);
2346 return -1;
2348 media = MEDIA_CDROM;
2349 } else {
2350 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2351 return -1;
2355 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2356 if (!strcmp(buf, "on"))
2357 snapshot = 1;
2358 else if (!strcmp(buf, "off"))
2359 snapshot = 0;
2360 else {
2361 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2362 return -1;
2366 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2367 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2368 cache = 0;
2369 else if (!strcmp(buf, "writethrough"))
2370 cache = 1;
2371 else if (!strcmp(buf, "writeback"))
2372 cache = 2;
2373 else {
2374 fprintf(stderr, "qemu: invalid cache option\n");
2375 return -1;
2379 if (get_param_value(buf, sizeof(buf), "format", str)) {
2380 if (strcmp(buf, "?") == 0) {
2381 fprintf(stderr, "qemu: Supported formats:");
2382 bdrv_iterate_format(bdrv_format_print, NULL);
2383 fprintf(stderr, "\n");
2384 return -1;
2386 drv = bdrv_find_format(buf);
2387 if (!drv) {
2388 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2389 return -1;
2393 if (arg->file == NULL)
2394 get_param_value(file, sizeof(file), "file", str);
2395 else
2396 pstrcpy(file, sizeof(file), arg->file);
2398 /* compute bus and unit according index */
2400 if (index != -1) {
2401 if (bus_id != 0 || unit_id != -1) {
2402 fprintf(stderr,
2403 "qemu: '%s' index cannot be used with bus and unit\n", str);
2404 return -1;
2406 if (max_devs == 0)
2408 unit_id = index;
2409 bus_id = 0;
2410 } else {
2411 unit_id = index % max_devs;
2412 bus_id = index / max_devs;
2416 /* if user doesn't specify a unit_id,
2417 * try to find the first free
2420 if (unit_id == -1) {
2421 unit_id = 0;
2422 while (drive_get_index(type, bus_id, unit_id) != -1) {
2423 unit_id++;
2424 if (max_devs && unit_id >= max_devs) {
2425 unit_id -= max_devs;
2426 bus_id++;
2431 /* check unit id */
2433 if (max_devs && unit_id >= max_devs) {
2434 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2435 str, unit_id, max_devs - 1);
2436 return -1;
2440 * ignore multiple definitions
2443 if (drive_get_index(type, bus_id, unit_id) != -1)
2444 return 0;
2446 /* init */
2448 if (type == IF_IDE || type == IF_SCSI)
2449 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2450 if (max_devs)
2451 snprintf(buf, sizeof(buf), "%s%i%s%i",
2452 devname, bus_id, mediastr, unit_id);
2453 else
2454 snprintf(buf, sizeof(buf), "%s%s%i",
2455 devname, mediastr, unit_id);
2456 bdrv = bdrv_new(buf);
2457 drives_table[nb_drives].bdrv = bdrv;
2458 drives_table[nb_drives].type = type;
2459 drives_table[nb_drives].bus = bus_id;
2460 drives_table[nb_drives].unit = unit_id;
2461 nb_drives++;
2463 switch(type) {
2464 case IF_IDE:
2465 case IF_SCSI:
2466 switch(media) {
2467 case MEDIA_DISK:
2468 if (cyls != 0) {
2469 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2470 bdrv_set_translation_hint(bdrv, translation);
2472 break;
2473 case MEDIA_CDROM:
2474 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2475 break;
2477 break;
2478 case IF_SD:
2479 /* FIXME: This isn't really a floppy, but it's a reasonable
2480 approximation. */
2481 case IF_FLOPPY:
2482 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2483 break;
2484 case IF_PFLASH:
2485 case IF_MTD:
2486 break;
2488 if (!file[0])
2489 return 0;
2490 bdrv_flags = 0;
2491 if (snapshot) {
2492 bdrv_flags |= BDRV_O_SNAPSHOT;
2493 cache = 2; /* always use write-back with snapshot */
2495 if (cache == 0) /* no caching */
2496 bdrv_flags |= BDRV_O_NOCACHE;
2497 else if (cache == 2) /* write-back */
2498 bdrv_flags |= BDRV_O_CACHE_WB;
2499 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2500 fprintf(stderr, "qemu: could not open disk image %s\n",
2501 file);
2502 return -1;
2504 return 0;
2507 /***********************************************************/
2508 /* USB devices */
2510 static USBPort *used_usb_ports;
2511 static USBPort *free_usb_ports;
2513 /* ??? Maybe change this to register a hub to keep track of the topology. */
2514 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2515 usb_attachfn attach)
2517 port->opaque = opaque;
2518 port->index = index;
2519 port->attach = attach;
2520 port->next = free_usb_ports;
2521 free_usb_ports = port;
2524 int usb_device_add_dev(USBDevice *dev)
2526 USBPort *port;
2528 /* Find a USB port to add the device to. */
2529 port = free_usb_ports;
2530 if (!port->next) {
2531 USBDevice *hub;
2533 /* Create a new hub and chain it on. */
2534 free_usb_ports = NULL;
2535 port->next = used_usb_ports;
2536 used_usb_ports = port;
2538 hub = usb_hub_init(VM_USB_HUB_SIZE);
2539 usb_attach(port, hub);
2540 port = free_usb_ports;
2543 free_usb_ports = port->next;
2544 port->next = used_usb_ports;
2545 used_usb_ports = port;
2546 usb_attach(port, dev);
2547 return 0;
2550 static int usb_device_add(const char *devname)
2552 const char *p;
2553 USBDevice *dev;
2555 if (!free_usb_ports)
2556 return -1;
2558 if (strstart(devname, "host:", &p)) {
2559 dev = usb_host_device_open(p);
2560 } else if (!strcmp(devname, "mouse")) {
2561 dev = usb_mouse_init();
2562 } else if (!strcmp(devname, "tablet")) {
2563 dev = usb_tablet_init();
2564 } else if (!strcmp(devname, "keyboard")) {
2565 dev = usb_keyboard_init();
2566 } else if (strstart(devname, "disk:", &p)) {
2567 dev = usb_msd_init(p);
2568 } else if (!strcmp(devname, "wacom-tablet")) {
2569 dev = usb_wacom_init();
2570 } else if (strstart(devname, "serial:", &p)) {
2571 dev = usb_serial_init(p);
2572 #ifdef CONFIG_BRLAPI
2573 } else if (!strcmp(devname, "braille")) {
2574 dev = usb_baum_init();
2575 #endif
2576 } else if (strstart(devname, "net:", &p)) {
2577 int nic = nb_nics;
2579 if (net_client_init("nic", p) < 0)
2580 return -1;
2581 nd_table[nic].model = "usb";
2582 dev = usb_net_init(&nd_table[nic]);
2583 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2584 dev = usb_bt_init(devname[2] ? hci_init(p) :
2585 bt_new_hci(qemu_find_bt_vlan(0)));
2586 } else {
2587 return -1;
2589 if (!dev)
2590 return -1;
2592 return usb_device_add_dev(dev);
2595 int usb_device_del_addr(int bus_num, int addr)
2597 USBPort *port;
2598 USBPort **lastp;
2599 USBDevice *dev;
2601 if (!used_usb_ports)
2602 return -1;
2604 if (bus_num != 0)
2605 return -1;
2607 lastp = &used_usb_ports;
2608 port = used_usb_ports;
2609 while (port && port->dev->addr != addr) {
2610 lastp = &port->next;
2611 port = port->next;
2614 if (!port)
2615 return -1;
2617 dev = port->dev;
2618 *lastp = port->next;
2619 usb_attach(port, NULL);
2620 dev->handle_destroy(dev);
2621 port->next = free_usb_ports;
2622 free_usb_ports = port;
2623 return 0;
2626 static int usb_device_del(const char *devname)
2628 int bus_num, addr;
2629 const char *p;
2631 if (strstart(devname, "host:", &p))
2632 return usb_host_device_close(p);
2634 if (!used_usb_ports)
2635 return -1;
2637 p = strchr(devname, '.');
2638 if (!p)
2639 return -1;
2640 bus_num = strtoul(devname, NULL, 0);
2641 addr = strtoul(p + 1, NULL, 0);
2643 return usb_device_del_addr(bus_num, addr);
2646 void do_usb_add(const char *devname)
2648 usb_device_add(devname);
2651 void do_usb_del(const char *devname)
2653 usb_device_del(devname);
2656 void usb_info(void)
2658 USBDevice *dev;
2659 USBPort *port;
2660 const char *speed_str;
2662 if (!usb_enabled) {
2663 term_printf("USB support not enabled\n");
2664 return;
2667 for (port = used_usb_ports; port; port = port->next) {
2668 dev = port->dev;
2669 if (!dev)
2670 continue;
2671 switch(dev->speed) {
2672 case USB_SPEED_LOW:
2673 speed_str = "1.5";
2674 break;
2675 case USB_SPEED_FULL:
2676 speed_str = "12";
2677 break;
2678 case USB_SPEED_HIGH:
2679 speed_str = "480";
2680 break;
2681 default:
2682 speed_str = "?";
2683 break;
2685 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2686 0, dev->addr, speed_str, dev->devname);
2690 /***********************************************************/
2691 /* PCMCIA/Cardbus */
2693 static struct pcmcia_socket_entry_s {
2694 struct pcmcia_socket_s *socket;
2695 struct pcmcia_socket_entry_s *next;
2696 } *pcmcia_sockets = 0;
2698 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2700 struct pcmcia_socket_entry_s *entry;
2702 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2703 entry->socket = socket;
2704 entry->next = pcmcia_sockets;
2705 pcmcia_sockets = entry;
2708 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2710 struct pcmcia_socket_entry_s *entry, **ptr;
2712 ptr = &pcmcia_sockets;
2713 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2714 if (entry->socket == socket) {
2715 *ptr = entry->next;
2716 qemu_free(entry);
2720 void pcmcia_info(void)
2722 struct pcmcia_socket_entry_s *iter;
2723 if (!pcmcia_sockets)
2724 term_printf("No PCMCIA sockets\n");
2726 for (iter = pcmcia_sockets; iter; iter = iter->next)
2727 term_printf("%s: %s\n", iter->socket->slot_string,
2728 iter->socket->attached ? iter->socket->card_string :
2729 "Empty");
2732 /***********************************************************/
2733 /* dumb display */
2735 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2739 static void dumb_resize(DisplayState *ds, int w, int h)
2743 static void dumb_display_init(DisplayState *ds)
2745 ds->data = NULL;
2746 ds->linesize = 0;
2747 ds->depth = 0;
2748 ds->dpy_update = dumb_update;
2749 ds->dpy_resize = dumb_resize;
2750 ds->dpy_refresh = NULL;
2751 ds->gui_timer_interval = 0;
2752 ds->idle = 1;
2755 /***********************************************************/
2756 /* I/O handling */
2758 #define MAX_IO_HANDLERS 64
2760 typedef struct IOHandlerRecord {
2761 int fd;
2762 IOCanRWHandler *fd_read_poll;
2763 IOHandler *fd_read;
2764 IOHandler *fd_write;
2765 int deleted;
2766 void *opaque;
2767 /* temporary data */
2768 struct pollfd *ufd;
2769 struct IOHandlerRecord *next;
2770 } IOHandlerRecord;
2772 static IOHandlerRecord *first_io_handler;
2774 /* XXX: fd_read_poll should be suppressed, but an API change is
2775 necessary in the character devices to suppress fd_can_read(). */
2776 int qemu_set_fd_handler2(int fd,
2777 IOCanRWHandler *fd_read_poll,
2778 IOHandler *fd_read,
2779 IOHandler *fd_write,
2780 void *opaque)
2782 IOHandlerRecord **pioh, *ioh;
2784 if (!fd_read && !fd_write) {
2785 pioh = &first_io_handler;
2786 for(;;) {
2787 ioh = *pioh;
2788 if (ioh == NULL)
2789 break;
2790 if (ioh->fd == fd) {
2791 ioh->deleted = 1;
2792 break;
2794 pioh = &ioh->next;
2796 } else {
2797 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2798 if (ioh->fd == fd)
2799 goto found;
2801 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2802 if (!ioh)
2803 return -1;
2804 ioh->next = first_io_handler;
2805 first_io_handler = ioh;
2806 found:
2807 ioh->fd = fd;
2808 ioh->fd_read_poll = fd_read_poll;
2809 ioh->fd_read = fd_read;
2810 ioh->fd_write = fd_write;
2811 ioh->opaque = opaque;
2812 ioh->deleted = 0;
2814 return 0;
2817 int qemu_set_fd_handler(int fd,
2818 IOHandler *fd_read,
2819 IOHandler *fd_write,
2820 void *opaque)
2822 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2825 #ifdef _WIN32
2826 /***********************************************************/
2827 /* Polling handling */
2829 typedef struct PollingEntry {
2830 PollingFunc *func;
2831 void *opaque;
2832 struct PollingEntry *next;
2833 } PollingEntry;
2835 static PollingEntry *first_polling_entry;
2837 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2839 PollingEntry **ppe, *pe;
2840 pe = qemu_mallocz(sizeof(PollingEntry));
2841 if (!pe)
2842 return -1;
2843 pe->func = func;
2844 pe->opaque = opaque;
2845 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2846 *ppe = pe;
2847 return 0;
2850 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2852 PollingEntry **ppe, *pe;
2853 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2854 pe = *ppe;
2855 if (pe->func == func && pe->opaque == opaque) {
2856 *ppe = pe->next;
2857 qemu_free(pe);
2858 break;
2863 /***********************************************************/
2864 /* Wait objects support */
2865 typedef struct WaitObjects {
2866 int num;
2867 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2868 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2869 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2870 } WaitObjects;
2872 static WaitObjects wait_objects = {0};
2874 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2876 WaitObjects *w = &wait_objects;
2878 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2879 return -1;
2880 w->events[w->num] = handle;
2881 w->func[w->num] = func;
2882 w->opaque[w->num] = opaque;
2883 w->num++;
2884 return 0;
2887 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2889 int i, found;
2890 WaitObjects *w = &wait_objects;
2892 found = 0;
2893 for (i = 0; i < w->num; i++) {
2894 if (w->events[i] == handle)
2895 found = 1;
2896 if (found) {
2897 w->events[i] = w->events[i + 1];
2898 w->func[i] = w->func[i + 1];
2899 w->opaque[i] = w->opaque[i + 1];
2902 if (found)
2903 w->num--;
2905 #endif
2907 #define SELF_ANNOUNCE_ROUNDS 5
2908 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
2909 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
2910 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
2912 static int announce_self_create(uint8_t *buf,
2913 uint8_t *mac_addr)
2915 uint32_t magic = EXPERIMENTAL_MAGIC;
2916 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
2918 /* FIXME: should we send a different packet (arp/rarp/ping)? */
2920 memset(buf, 0xff, 6); /* h_dst */
2921 memcpy(buf + 6, mac_addr, 6); /* h_src */
2922 memcpy(buf + 12, &proto, 2); /* h_proto */
2923 memcpy(buf + 14, &magic, 4); /* magic */
2925 return 18; /* len */
2928 void qemu_announce_self(void)
2930 int i, j, len;
2931 VLANState *vlan;
2932 VLANClientState *vc;
2933 uint8_t buf[256];
2935 for (i = 0; i < nb_nics; i++) {
2936 len = announce_self_create(buf, nd_table[i].macaddr);
2937 vlan = nd_table[i].vlan;
2938 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2939 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
2940 vc->fd_read(vc->opaque, buf, len);
2945 /***********************************************************/
2946 /* savevm/loadvm support */
2948 #define IO_BUF_SIZE 32768
2950 struct QEMUFile {
2951 QEMUFilePutBufferFunc *put_buffer;
2952 QEMUFileGetBufferFunc *get_buffer;
2953 QEMUFileCloseFunc *close;
2954 QEMUFileRateLimit *rate_limit;
2955 void *opaque;
2956 int is_write;
2958 int64_t buf_offset; /* start of buffer when writing, end of buffer
2959 when reading */
2960 int buf_index;
2961 int buf_size; /* 0 when writing */
2962 uint8_t buf[IO_BUF_SIZE];
2964 int has_error;
2967 typedef struct QEMUFileSocket
2969 int fd;
2970 QEMUFile *file;
2971 } QEMUFileSocket;
2973 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2975 QEMUFileSocket *s = opaque;
2976 ssize_t len;
2978 do {
2979 len = recv(s->fd, buf, size, 0);
2980 } while (len == -1 && socket_error() == EINTR);
2982 if (len == -1)
2983 len = -socket_error();
2985 return len;
2988 static int socket_close(void *opaque)
2990 QEMUFileSocket *s = opaque;
2991 qemu_free(s);
2992 return 0;
2995 QEMUFile *qemu_fopen_socket(int fd)
2997 QEMUFileSocket *s = qemu_mallocz(sizeof(QEMUFileSocket));
2999 if (s == NULL)
3000 return NULL;
3002 s->fd = fd;
3003 s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, socket_close, NULL);
3004 return s->file;
3007 typedef struct QEMUFileStdio
3009 FILE *outfile;
3010 } QEMUFileStdio;
3012 static int file_put_buffer(void *opaque, const uint8_t *buf,
3013 int64_t pos, int size)
3015 QEMUFileStdio *s = opaque;
3016 fseek(s->outfile, pos, SEEK_SET);
3017 fwrite(buf, 1, size, s->outfile);
3018 return size;
3021 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
3023 QEMUFileStdio *s = opaque;
3024 fseek(s->outfile, pos, SEEK_SET);
3025 return fread(buf, 1, size, s->outfile);
3028 static int file_close(void *opaque)
3030 QEMUFileStdio *s = opaque;
3031 fclose(s->outfile);
3032 qemu_free(s);
3033 return 0;
3036 QEMUFile *qemu_fopen(const char *filename, const char *mode)
3038 QEMUFileStdio *s;
3040 s = qemu_mallocz(sizeof(QEMUFileStdio));
3041 if (!s)
3042 return NULL;
3044 s->outfile = fopen(filename, mode);
3045 if (!s->outfile)
3046 goto fail;
3048 if (!strcmp(mode, "wb"))
3049 return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
3050 else if (!strcmp(mode, "rb"))
3051 return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
3053 fail:
3054 if (s->outfile)
3055 fclose(s->outfile);
3056 qemu_free(s);
3057 return NULL;
3060 typedef struct QEMUFileBdrv
3062 BlockDriverState *bs;
3063 int64_t base_offset;
3064 } QEMUFileBdrv;
3066 static int bdrv_put_buffer(void *opaque, const uint8_t *buf,
3067 int64_t pos, int size)
3069 QEMUFileBdrv *s = opaque;
3070 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
3071 return size;
3074 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
3076 QEMUFileBdrv *s = opaque;
3077 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
3080 static int bdrv_fclose(void *opaque)
3082 QEMUFileBdrv *s = opaque;
3083 qemu_free(s);
3084 return 0;
3087 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
3089 QEMUFileBdrv *s;
3091 s = qemu_mallocz(sizeof(QEMUFileBdrv));
3092 if (!s)
3093 return NULL;
3095 s->bs = bs;
3096 s->base_offset = offset;
3098 if (is_writable)
3099 return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
3101 return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
3104 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
3105 QEMUFileGetBufferFunc *get_buffer,
3106 QEMUFileCloseFunc *close,
3107 QEMUFileRateLimit *rate_limit)
3109 QEMUFile *f;
3111 f = qemu_mallocz(sizeof(QEMUFile));
3112 if (!f)
3113 return NULL;
3115 f->opaque = opaque;
3116 f->put_buffer = put_buffer;
3117 f->get_buffer = get_buffer;
3118 f->close = close;
3119 f->rate_limit = rate_limit;
3120 f->is_write = 0;
3122 return f;
3125 int qemu_file_has_error(QEMUFile *f)
3127 return f->has_error;
3130 void qemu_fflush(QEMUFile *f)
3132 if (!f->put_buffer)
3133 return;
3135 if (f->is_write && f->buf_index > 0) {
3136 int len;
3138 len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
3139 if (len > 0)
3140 f->buf_offset += f->buf_index;
3141 else
3142 f->has_error = 1;
3143 f->buf_index = 0;
3147 static void qemu_fill_buffer(QEMUFile *f)
3149 int len;
3151 if (!f->get_buffer)
3152 return;
3154 if (f->is_write)
3155 abort();
3157 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
3158 if (len > 0) {
3159 f->buf_index = 0;
3160 f->buf_size = len;
3161 f->buf_offset += len;
3162 } else if (len != -EAGAIN)
3163 f->has_error = 1;
3166 int qemu_fclose(QEMUFile *f)
3168 int ret = 0;
3169 qemu_fflush(f);
3170 if (f->close)
3171 ret = f->close(f->opaque);
3172 qemu_free(f);
3173 return ret;
3176 void qemu_file_put_notify(QEMUFile *f)
3178 f->put_buffer(f->opaque, NULL, 0, 0);
3181 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3183 int l;
3185 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3186 fprintf(stderr,
3187 "Attempted to write to buffer while read buffer is not empty\n");
3188 abort();
3191 while (!f->has_error && size > 0) {
3192 l = IO_BUF_SIZE - f->buf_index;
3193 if (l > size)
3194 l = size;
3195 memcpy(f->buf + f->buf_index, buf, l);
3196 f->is_write = 1;
3197 f->buf_index += l;
3198 buf += l;
3199 size -= l;
3200 if (f->buf_index >= IO_BUF_SIZE)
3201 qemu_fflush(f);
3205 void qemu_put_byte(QEMUFile *f, int v)
3207 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3208 fprintf(stderr,
3209 "Attempted to write to buffer while read buffer is not empty\n");
3210 abort();
3213 f->buf[f->buf_index++] = v;
3214 f->is_write = 1;
3215 if (f->buf_index >= IO_BUF_SIZE)
3216 qemu_fflush(f);
3219 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
3221 int size, l;
3223 if (f->is_write)
3224 abort();
3226 size = size1;
3227 while (size > 0) {
3228 l = f->buf_size - f->buf_index;
3229 if (l == 0) {
3230 qemu_fill_buffer(f);
3231 l = f->buf_size - f->buf_index;
3232 if (l == 0)
3233 break;
3235 if (l > size)
3236 l = size;
3237 memcpy(buf, f->buf + f->buf_index, l);
3238 f->buf_index += l;
3239 buf += l;
3240 size -= l;
3242 return size1 - size;
3245 int qemu_get_byte(QEMUFile *f)
3247 if (f->is_write)
3248 abort();
3250 if (f->buf_index >= f->buf_size) {
3251 qemu_fill_buffer(f);
3252 if (f->buf_index >= f->buf_size)
3253 return 0;
3255 return f->buf[f->buf_index++];
3258 int64_t qemu_ftell(QEMUFile *f)
3260 return f->buf_offset - f->buf_size + f->buf_index;
3263 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3265 if (whence == SEEK_SET) {
3266 /* nothing to do */
3267 } else if (whence == SEEK_CUR) {
3268 pos += qemu_ftell(f);
3269 } else {
3270 /* SEEK_END not supported */
3271 return -1;
3273 if (f->put_buffer) {
3274 qemu_fflush(f);
3275 f->buf_offset = pos;
3276 } else {
3277 f->buf_offset = pos;
3278 f->buf_index = 0;
3279 f->buf_size = 0;
3281 return pos;
3284 int qemu_file_rate_limit(QEMUFile *f)
3286 if (f->rate_limit)
3287 return f->rate_limit(f->opaque);
3289 return 0;
3292 void qemu_put_be16(QEMUFile *f, unsigned int v)
3294 qemu_put_byte(f, v >> 8);
3295 qemu_put_byte(f, v);
3298 void qemu_put_be32(QEMUFile *f, unsigned int v)
3300 qemu_put_byte(f, v >> 24);
3301 qemu_put_byte(f, v >> 16);
3302 qemu_put_byte(f, v >> 8);
3303 qemu_put_byte(f, v);
3306 void qemu_put_be64(QEMUFile *f, uint64_t v)
3308 qemu_put_be32(f, v >> 32);
3309 qemu_put_be32(f, v);
3312 unsigned int qemu_get_be16(QEMUFile *f)
3314 unsigned int v;
3315 v = qemu_get_byte(f) << 8;
3316 v |= qemu_get_byte(f);
3317 return v;
3320 unsigned int qemu_get_be32(QEMUFile *f)
3322 unsigned int v;
3323 v = qemu_get_byte(f) << 24;
3324 v |= qemu_get_byte(f) << 16;
3325 v |= qemu_get_byte(f) << 8;
3326 v |= qemu_get_byte(f);
3327 return v;
3330 uint64_t qemu_get_be64(QEMUFile *f)
3332 uint64_t v;
3333 v = (uint64_t)qemu_get_be32(f) << 32;
3334 v |= qemu_get_be32(f);
3335 return v;
3338 typedef struct SaveStateEntry {
3339 char idstr[256];
3340 int instance_id;
3341 int version_id;
3342 int section_id;
3343 SaveLiveStateHandler *save_live_state;
3344 SaveStateHandler *save_state;
3345 LoadStateHandler *load_state;
3346 void *opaque;
3347 struct SaveStateEntry *next;
3348 } SaveStateEntry;
3350 static SaveStateEntry *first_se;
3352 /* TODO: Individual devices generally have very little idea about the rest
3353 of the system, so instance_id should be removed/replaced.
3354 Meanwhile pass -1 as instance_id if you do not already have a clearly
3355 distinguishing id for all instances of your device class. */
3356 int register_savevm_live(const char *idstr,
3357 int instance_id,
3358 int version_id,
3359 SaveLiveStateHandler *save_live_state,
3360 SaveStateHandler *save_state,
3361 LoadStateHandler *load_state,
3362 void *opaque)
3364 SaveStateEntry *se, **pse;
3365 static int global_section_id;
3367 se = qemu_malloc(sizeof(SaveStateEntry));
3368 if (!se)
3369 return -1;
3370 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3371 se->instance_id = (instance_id == -1) ? 0 : instance_id;
3372 se->version_id = version_id;
3373 se->section_id = global_section_id++;
3374 se->save_live_state = save_live_state;
3375 se->save_state = save_state;
3376 se->load_state = load_state;
3377 se->opaque = opaque;
3378 se->next = NULL;
3380 /* add at the end of list */
3381 pse = &first_se;
3382 while (*pse != NULL) {
3383 if (instance_id == -1
3384 && strcmp(se->idstr, (*pse)->idstr) == 0
3385 && se->instance_id <= (*pse)->instance_id)
3386 se->instance_id = (*pse)->instance_id + 1;
3387 pse = &(*pse)->next;
3389 *pse = se;
3390 return 0;
3393 int register_savevm(const char *idstr,
3394 int instance_id,
3395 int version_id,
3396 SaveStateHandler *save_state,
3397 LoadStateHandler *load_state,
3398 void *opaque)
3400 return register_savevm_live(idstr, instance_id, version_id,
3401 NULL, save_state, load_state, opaque);
3404 #define QEMU_VM_FILE_MAGIC 0x5145564d
3405 #define QEMU_VM_FILE_VERSION_COMPAT 0x00000002
3406 #define QEMU_VM_FILE_VERSION 0x00000003
3408 #define QEMU_VM_EOF 0x00
3409 #define QEMU_VM_SECTION_START 0x01
3410 #define QEMU_VM_SECTION_PART 0x02
3411 #define QEMU_VM_SECTION_END 0x03
3412 #define QEMU_VM_SECTION_FULL 0x04
3414 int qemu_savevm_state_begin(QEMUFile *f)
3416 SaveStateEntry *se;
3418 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3419 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3421 for (se = first_se; se != NULL; se = se->next) {
3422 int len;
3424 if (se->save_live_state == NULL)
3425 continue;
3427 /* Section type */
3428 qemu_put_byte(f, QEMU_VM_SECTION_START);
3429 qemu_put_be32(f, se->section_id);
3431 /* ID string */
3432 len = strlen(se->idstr);
3433 qemu_put_byte(f, len);
3434 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3436 qemu_put_be32(f, se->instance_id);
3437 qemu_put_be32(f, se->version_id);
3439 se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
3442 if (qemu_file_has_error(f))
3443 return -EIO;
3445 return 0;
3448 int qemu_savevm_state_iterate(QEMUFile *f)
3450 SaveStateEntry *se;
3451 int ret = 1;
3453 for (se = first_se; se != NULL; se = se->next) {
3454 if (se->save_live_state == NULL)
3455 continue;
3457 /* Section type */
3458 qemu_put_byte(f, QEMU_VM_SECTION_PART);
3459 qemu_put_be32(f, se->section_id);
3461 ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
3464 if (ret)
3465 return 1;
3467 if (qemu_file_has_error(f))
3468 return -EIO;
3470 return 0;
3473 int qemu_savevm_state_complete(QEMUFile *f)
3475 SaveStateEntry *se;
3477 for (se = first_se; se != NULL; se = se->next) {
3478 if (se->save_live_state == NULL)
3479 continue;
3481 /* Section type */
3482 qemu_put_byte(f, QEMU_VM_SECTION_END);
3483 qemu_put_be32(f, se->section_id);
3485 se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
3488 for(se = first_se; se != NULL; se = se->next) {
3489 int len;
3491 if (se->save_state == NULL)
3492 continue;
3494 /* Section type */
3495 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
3496 qemu_put_be32(f, se->section_id);
3498 /* ID string */
3499 len = strlen(se->idstr);
3500 qemu_put_byte(f, len);
3501 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3503 qemu_put_be32(f, se->instance_id);
3504 qemu_put_be32(f, se->version_id);
3506 se->save_state(f, se->opaque);
3509 qemu_put_byte(f, QEMU_VM_EOF);
3511 if (qemu_file_has_error(f))
3512 return -EIO;
3514 return 0;
3517 int qemu_savevm_state(QEMUFile *f)
3519 int saved_vm_running;
3520 int ret;
3522 saved_vm_running = vm_running;
3523 vm_stop(0);
3525 bdrv_flush_all();
3527 ret = qemu_savevm_state_begin(f);
3528 if (ret < 0)
3529 goto out;
3531 do {
3532 ret = qemu_savevm_state_iterate(f);
3533 if (ret < 0)
3534 goto out;
3535 } while (ret == 0);
3537 ret = qemu_savevm_state_complete(f);
3539 out:
3540 if (qemu_file_has_error(f))
3541 ret = -EIO;
3543 if (!ret && saved_vm_running)
3544 vm_start();
3546 return ret;
3549 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3551 SaveStateEntry *se;
3553 for(se = first_se; se != NULL; se = se->next) {
3554 if (!strcmp(se->idstr, idstr) &&
3555 instance_id == se->instance_id)
3556 return se;
3558 return NULL;
3561 typedef struct LoadStateEntry {
3562 SaveStateEntry *se;
3563 int section_id;
3564 int version_id;
3565 struct LoadStateEntry *next;
3566 } LoadStateEntry;
3568 static int qemu_loadvm_state_v2(QEMUFile *f)
3570 SaveStateEntry *se;
3571 int len, ret, instance_id, record_len, version_id;
3572 int64_t total_len, end_pos, cur_pos;
3573 char idstr[256];
3575 total_len = qemu_get_be64(f);
3576 end_pos = total_len + qemu_ftell(f);
3577 for(;;) {
3578 if (qemu_ftell(f) >= end_pos)
3579 break;
3580 len = qemu_get_byte(f);
3581 qemu_get_buffer(f, (uint8_t *)idstr, len);
3582 idstr[len] = '\0';
3583 instance_id = qemu_get_be32(f);
3584 version_id = qemu_get_be32(f);
3585 record_len = qemu_get_be32(f);
3586 cur_pos = qemu_ftell(f);
3587 se = find_se(idstr, instance_id);
3588 if (!se) {
3589 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3590 instance_id, idstr);
3591 } else {
3592 ret = se->load_state(f, se->opaque, version_id);
3593 if (ret < 0) {
3594 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3595 instance_id, idstr);
3598 /* always seek to exact end of record */
3599 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3602 if (qemu_file_has_error(f))
3603 return -EIO;
3605 return 0;
3608 int qemu_loadvm_state(QEMUFile *f)
3610 LoadStateEntry *first_le = NULL;
3611 uint8_t section_type;
3612 unsigned int v;
3613 int ret;
3615 v = qemu_get_be32(f);
3616 if (v != QEMU_VM_FILE_MAGIC)
3617 return -EINVAL;
3619 v = qemu_get_be32(f);
3620 if (v == QEMU_VM_FILE_VERSION_COMPAT)
3621 return qemu_loadvm_state_v2(f);
3622 if (v != QEMU_VM_FILE_VERSION)
3623 return -ENOTSUP;
3625 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
3626 uint32_t instance_id, version_id, section_id;
3627 LoadStateEntry *le;
3628 SaveStateEntry *se;
3629 char idstr[257];
3630 int len;
3632 switch (section_type) {
3633 case QEMU_VM_SECTION_START:
3634 case QEMU_VM_SECTION_FULL:
3635 /* Read section start */
3636 section_id = qemu_get_be32(f);
3637 len = qemu_get_byte(f);
3638 qemu_get_buffer(f, (uint8_t *)idstr, len);
3639 idstr[len] = 0;
3640 instance_id = qemu_get_be32(f);
3641 version_id = qemu_get_be32(f);
3643 /* Find savevm section */
3644 se = find_se(idstr, instance_id);
3645 if (se == NULL) {
3646 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
3647 ret = -EINVAL;
3648 goto out;
3651 /* Validate version */
3652 if (version_id > se->version_id) {
3653 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
3654 version_id, idstr, se->version_id);
3655 ret = -EINVAL;
3656 goto out;
3659 /* Add entry */
3660 le = qemu_mallocz(sizeof(*le));
3661 if (le == NULL) {
3662 ret = -ENOMEM;
3663 goto out;
3666 le->se = se;
3667 le->section_id = section_id;
3668 le->version_id = version_id;
3669 le->next = first_le;
3670 first_le = le;
3672 le->se->load_state(f, le->se->opaque, le->version_id);
3673 break;
3674 case QEMU_VM_SECTION_PART:
3675 case QEMU_VM_SECTION_END:
3676 section_id = qemu_get_be32(f);
3678 for (le = first_le; le && le->section_id != section_id; le = le->next);
3679 if (le == NULL) {
3680 fprintf(stderr, "Unknown savevm section %d\n", section_id);
3681 ret = -EINVAL;
3682 goto out;
3685 le->se->load_state(f, le->se->opaque, le->version_id);
3686 break;
3687 default:
3688 fprintf(stderr, "Unknown savevm section type %d\n", section_type);
3689 ret = -EINVAL;
3690 goto out;
3694 ret = 0;
3696 out:
3697 while (first_le) {
3698 LoadStateEntry *le = first_le;
3699 first_le = first_le->next;
3700 qemu_free(le);
3703 if (qemu_file_has_error(f))
3704 ret = -EIO;
3706 return ret;
3709 /* device can contain snapshots */
3710 static int bdrv_can_snapshot(BlockDriverState *bs)
3712 return (bs &&
3713 !bdrv_is_removable(bs) &&
3714 !bdrv_is_read_only(bs));
3717 /* device must be snapshots in order to have a reliable snapshot */
3718 static int bdrv_has_snapshot(BlockDriverState *bs)
3720 return (bs &&
3721 !bdrv_is_removable(bs) &&
3722 !bdrv_is_read_only(bs));
3725 static BlockDriverState *get_bs_snapshots(void)
3727 BlockDriverState *bs;
3728 int i;
3730 if (bs_snapshots)
3731 return bs_snapshots;
3732 for(i = 0; i <= nb_drives; i++) {
3733 bs = drives_table[i].bdrv;
3734 if (bdrv_can_snapshot(bs))
3735 goto ok;
3737 return NULL;
3739 bs_snapshots = bs;
3740 return bs;
3743 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
3744 const char *name)
3746 QEMUSnapshotInfo *sn_tab, *sn;
3747 int nb_sns, i, ret;
3749 ret = -ENOENT;
3750 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3751 if (nb_sns < 0)
3752 return ret;
3753 for(i = 0; i < nb_sns; i++) {
3754 sn = &sn_tab[i];
3755 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
3756 *sn_info = *sn;
3757 ret = 0;
3758 break;
3761 qemu_free(sn_tab);
3762 return ret;
3765 void do_savevm(const char *name)
3767 BlockDriverState *bs, *bs1;
3768 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
3769 int must_delete, ret, i;
3770 BlockDriverInfo bdi1, *bdi = &bdi1;
3771 QEMUFile *f;
3772 int saved_vm_running;
3773 #ifdef _WIN32
3774 struct _timeb tb;
3775 #else
3776 struct timeval tv;
3777 #endif
3779 bs = get_bs_snapshots();
3780 if (!bs) {
3781 term_printf("No block device can accept snapshots\n");
3782 return;
3785 /* ??? Should this occur after vm_stop? */
3786 qemu_aio_flush();
3788 saved_vm_running = vm_running;
3789 vm_stop(0);
3791 must_delete = 0;
3792 if (name) {
3793 ret = bdrv_snapshot_find(bs, old_sn, name);
3794 if (ret >= 0) {
3795 must_delete = 1;
3798 memset(sn, 0, sizeof(*sn));
3799 if (must_delete) {
3800 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
3801 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
3802 } else {
3803 if (name)
3804 pstrcpy(sn->name, sizeof(sn->name), name);
3807 /* fill auxiliary fields */
3808 #ifdef _WIN32
3809 _ftime(&tb);
3810 sn->date_sec = tb.time;
3811 sn->date_nsec = tb.millitm * 1000000;
3812 #else
3813 gettimeofday(&tv, NULL);
3814 sn->date_sec = tv.tv_sec;
3815 sn->date_nsec = tv.tv_usec * 1000;
3816 #endif
3817 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
3819 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3820 term_printf("Device %s does not support VM state snapshots\n",
3821 bdrv_get_device_name(bs));
3822 goto the_end;
3825 /* save the VM state */
3826 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
3827 if (!f) {
3828 term_printf("Could not open VM state file\n");
3829 goto the_end;
3831 ret = qemu_savevm_state(f);
3832 sn->vm_state_size = qemu_ftell(f);
3833 qemu_fclose(f);
3834 if (ret < 0) {
3835 term_printf("Error %d while writing VM\n", ret);
3836 goto the_end;
3839 /* create the snapshots */
3841 for(i = 0; i < nb_drives; i++) {
3842 bs1 = drives_table[i].bdrv;
3843 if (bdrv_has_snapshot(bs1)) {
3844 if (must_delete) {
3845 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
3846 if (ret < 0) {
3847 term_printf("Error while deleting snapshot on '%s'\n",
3848 bdrv_get_device_name(bs1));
3851 ret = bdrv_snapshot_create(bs1, sn);
3852 if (ret < 0) {
3853 term_printf("Error while creating snapshot on '%s'\n",
3854 bdrv_get_device_name(bs1));
3859 the_end:
3860 if (saved_vm_running)
3861 vm_start();
3864 void do_loadvm(const char *name)
3866 BlockDriverState *bs, *bs1;
3867 BlockDriverInfo bdi1, *bdi = &bdi1;
3868 QEMUFile *f;
3869 int i, ret;
3870 int saved_vm_running;
3872 bs = get_bs_snapshots();
3873 if (!bs) {
3874 term_printf("No block device supports snapshots\n");
3875 return;
3878 /* Flush all IO requests so they don't interfere with the new state. */
3879 qemu_aio_flush();
3881 saved_vm_running = vm_running;
3882 vm_stop(0);
3884 for(i = 0; i <= nb_drives; i++) {
3885 bs1 = drives_table[i].bdrv;
3886 if (bdrv_has_snapshot(bs1)) {
3887 ret = bdrv_snapshot_goto(bs1, name);
3888 if (ret < 0) {
3889 if (bs != bs1)
3890 term_printf("Warning: ");
3891 switch(ret) {
3892 case -ENOTSUP:
3893 term_printf("Snapshots not supported on device '%s'\n",
3894 bdrv_get_device_name(bs1));
3895 break;
3896 case -ENOENT:
3897 term_printf("Could not find snapshot '%s' on device '%s'\n",
3898 name, bdrv_get_device_name(bs1));
3899 break;
3900 default:
3901 term_printf("Error %d while activating snapshot on '%s'\n",
3902 ret, bdrv_get_device_name(bs1));
3903 break;
3905 /* fatal on snapshot block device */
3906 if (bs == bs1)
3907 goto the_end;
3912 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3913 term_printf("Device %s does not support VM state snapshots\n",
3914 bdrv_get_device_name(bs));
3915 return;
3918 /* restore the VM state */
3919 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
3920 if (!f) {
3921 term_printf("Could not open VM state file\n");
3922 goto the_end;
3924 ret = qemu_loadvm_state(f);
3925 qemu_fclose(f);
3926 if (ret < 0) {
3927 term_printf("Error %d while loading VM state\n", ret);
3929 the_end:
3930 if (saved_vm_running)
3931 vm_start();
3934 void do_delvm(const char *name)
3936 BlockDriverState *bs, *bs1;
3937 int i, ret;
3939 bs = get_bs_snapshots();
3940 if (!bs) {
3941 term_printf("No block device supports snapshots\n");
3942 return;
3945 for(i = 0; i <= nb_drives; i++) {
3946 bs1 = drives_table[i].bdrv;
3947 if (bdrv_has_snapshot(bs1)) {
3948 ret = bdrv_snapshot_delete(bs1, name);
3949 if (ret < 0) {
3950 if (ret == -ENOTSUP)
3951 term_printf("Snapshots not supported on device '%s'\n",
3952 bdrv_get_device_name(bs1));
3953 else
3954 term_printf("Error %d while deleting snapshot on '%s'\n",
3955 ret, bdrv_get_device_name(bs1));
3961 void do_info_snapshots(void)
3963 BlockDriverState *bs, *bs1;
3964 QEMUSnapshotInfo *sn_tab, *sn;
3965 int nb_sns, i;
3966 char buf[256];
3968 bs = get_bs_snapshots();
3969 if (!bs) {
3970 term_printf("No available block device supports snapshots\n");
3971 return;
3973 term_printf("Snapshot devices:");
3974 for(i = 0; i <= nb_drives; i++) {
3975 bs1 = drives_table[i].bdrv;
3976 if (bdrv_has_snapshot(bs1)) {
3977 if (bs == bs1)
3978 term_printf(" %s", bdrv_get_device_name(bs1));
3981 term_printf("\n");
3983 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3984 if (nb_sns < 0) {
3985 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
3986 return;
3988 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
3989 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
3990 for(i = 0; i < nb_sns; i++) {
3991 sn = &sn_tab[i];
3992 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
3994 qemu_free(sn_tab);
3997 /***********************************************************/
3998 /* ram save/restore */
4000 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4002 int v;
4004 v = qemu_get_byte(f);
4005 switch(v) {
4006 case 0:
4007 if (qemu_get_buffer(f, buf, len) != len)
4008 return -EIO;
4009 break;
4010 case 1:
4011 v = qemu_get_byte(f);
4012 memset(buf, v, len);
4013 break;
4014 default:
4015 return -EINVAL;
4018 if (qemu_file_has_error(f))
4019 return -EIO;
4021 return 0;
4024 static int ram_load_v1(QEMUFile *f, void *opaque)
4026 int ret;
4027 ram_addr_t i;
4029 if (qemu_get_be32(f) != phys_ram_size)
4030 return -EINVAL;
4031 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4032 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4033 if (ret)
4034 return ret;
4036 return 0;
4039 #define BDRV_HASH_BLOCK_SIZE 1024
4040 #define IOBUF_SIZE 4096
4041 #define RAM_CBLOCK_MAGIC 0xfabe
4043 typedef struct RamDecompressState {
4044 z_stream zstream;
4045 QEMUFile *f;
4046 uint8_t buf[IOBUF_SIZE];
4047 } RamDecompressState;
4049 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
4051 int ret;
4052 memset(s, 0, sizeof(*s));
4053 s->f = f;
4054 ret = inflateInit(&s->zstream);
4055 if (ret != Z_OK)
4056 return -1;
4057 return 0;
4060 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
4062 int ret, clen;
4064 s->zstream.avail_out = len;
4065 s->zstream.next_out = buf;
4066 while (s->zstream.avail_out > 0) {
4067 if (s->zstream.avail_in == 0) {
4068 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
4069 return -1;
4070 clen = qemu_get_be16(s->f);
4071 if (clen > IOBUF_SIZE)
4072 return -1;
4073 qemu_get_buffer(s->f, s->buf, clen);
4074 s->zstream.avail_in = clen;
4075 s->zstream.next_in = s->buf;
4077 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
4078 if (ret != Z_OK && ret != Z_STREAM_END) {
4079 return -1;
4082 return 0;
4085 static void ram_decompress_close(RamDecompressState *s)
4087 inflateEnd(&s->zstream);
4090 #define RAM_SAVE_FLAG_FULL 0x01
4091 #define RAM_SAVE_FLAG_COMPRESS 0x02
4092 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
4093 #define RAM_SAVE_FLAG_PAGE 0x08
4094 #define RAM_SAVE_FLAG_EOS 0x10
4096 static int is_dup_page(uint8_t *page, uint8_t ch)
4098 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
4099 uint32_t *array = (uint32_t *)page;
4100 int i;
4102 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
4103 if (array[i] != val)
4104 return 0;
4107 return 1;
4110 static int ram_save_block(QEMUFile *f)
4112 static ram_addr_t current_addr = 0;
4113 ram_addr_t saved_addr = current_addr;
4114 ram_addr_t addr = 0;
4115 int found = 0;
4117 while (addr < phys_ram_size) {
4118 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
4119 uint8_t ch;
4121 cpu_physical_memory_reset_dirty(current_addr,
4122 current_addr + TARGET_PAGE_SIZE,
4123 MIGRATION_DIRTY_FLAG);
4125 ch = *(phys_ram_base + current_addr);
4127 if (is_dup_page(phys_ram_base + current_addr, ch)) {
4128 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
4129 qemu_put_byte(f, ch);
4130 } else {
4131 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
4132 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
4135 found = 1;
4136 break;
4138 addr += TARGET_PAGE_SIZE;
4139 current_addr = (saved_addr + addr) % phys_ram_size;
4142 return found;
4145 static ram_addr_t ram_save_threshold = 10;
4147 static ram_addr_t ram_save_remaining(void)
4149 ram_addr_t addr;
4150 ram_addr_t count = 0;
4152 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4153 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4154 count++;
4157 return count;
4160 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
4162 ram_addr_t addr;
4164 if (stage == 1) {
4165 /* Make sure all dirty bits are set */
4166 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4167 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4168 cpu_physical_memory_set_dirty(addr);
4171 /* Enable dirty memory tracking */
4172 cpu_physical_memory_set_dirty_tracking(1);
4174 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
4177 while (!qemu_file_rate_limit(f)) {
4178 int ret;
4180 ret = ram_save_block(f);
4181 if (ret == 0) /* no more blocks */
4182 break;
4185 /* try transferring iterative blocks of memory */
4187 if (stage == 3) {
4188 cpu_physical_memory_set_dirty_tracking(0);
4190 /* flush all remaining blocks regardless of rate limiting */
4191 while (ram_save_block(f) != 0);
4194 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
4196 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
4199 static int ram_load_dead(QEMUFile *f, void *opaque)
4201 RamDecompressState s1, *s = &s1;
4202 uint8_t buf[10];
4203 ram_addr_t i;
4205 if (ram_decompress_open(s, f) < 0)
4206 return -EINVAL;
4207 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
4208 if (ram_decompress_buf(s, buf, 1) < 0) {
4209 fprintf(stderr, "Error while reading ram block header\n");
4210 goto error;
4212 if (buf[0] == 0) {
4213 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
4214 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
4215 goto error;
4217 } else {
4218 error:
4219 printf("Error block header\n");
4220 return -EINVAL;
4223 ram_decompress_close(s);
4225 return 0;
4228 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4230 ram_addr_t addr;
4231 int flags;
4233 if (version_id == 1)
4234 return ram_load_v1(f, opaque);
4236 if (version_id == 2) {
4237 if (qemu_get_be32(f) != phys_ram_size)
4238 return -EINVAL;
4239 return ram_load_dead(f, opaque);
4242 if (version_id != 3)
4243 return -EINVAL;
4245 do {
4246 addr = qemu_get_be64(f);
4248 flags = addr & ~TARGET_PAGE_MASK;
4249 addr &= TARGET_PAGE_MASK;
4251 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
4252 if (addr != phys_ram_size)
4253 return -EINVAL;
4256 if (flags & RAM_SAVE_FLAG_FULL) {
4257 if (ram_load_dead(f, opaque) < 0)
4258 return -EINVAL;
4261 if (flags & RAM_SAVE_FLAG_COMPRESS) {
4262 uint8_t ch = qemu_get_byte(f);
4263 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
4264 } else if (flags & RAM_SAVE_FLAG_PAGE)
4265 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
4266 } while (!(flags & RAM_SAVE_FLAG_EOS));
4268 return 0;
4271 void qemu_service_io(void)
4273 CPUState *env = cpu_single_env;
4274 if (env) {
4275 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4276 #ifdef USE_KQEMU
4277 if (env->kqemu_enabled) {
4278 kqemu_cpu_interrupt(env);
4280 #endif
4284 /***********************************************************/
4285 /* bottom halves (can be seen as timers which expire ASAP) */
4287 struct QEMUBH {
4288 QEMUBHFunc *cb;
4289 void *opaque;
4290 int scheduled;
4291 int idle;
4292 int deleted;
4293 QEMUBH *next;
4296 static QEMUBH *first_bh = NULL;
4298 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
4300 QEMUBH *bh;
4301 bh = qemu_mallocz(sizeof(QEMUBH));
4302 if (!bh)
4303 return NULL;
4304 bh->cb = cb;
4305 bh->opaque = opaque;
4306 bh->next = first_bh;
4307 first_bh = bh;
4308 return bh;
4311 int qemu_bh_poll(void)
4313 QEMUBH *bh, **bhp;
4314 int ret;
4316 ret = 0;
4317 for (bh = first_bh; bh; bh = bh->next) {
4318 if (!bh->deleted && bh->scheduled) {
4319 bh->scheduled = 0;
4320 if (!bh->idle)
4321 ret = 1;
4322 bh->idle = 0;
4323 bh->cb(bh->opaque);
4327 /* remove deleted bhs */
4328 bhp = &first_bh;
4329 while (*bhp) {
4330 bh = *bhp;
4331 if (bh->deleted) {
4332 *bhp = bh->next;
4333 qemu_free(bh);
4334 } else
4335 bhp = &bh->next;
4338 return ret;
4341 void qemu_bh_schedule_idle(QEMUBH *bh)
4343 if (bh->scheduled)
4344 return;
4345 bh->scheduled = 1;
4346 bh->idle = 1;
4349 void qemu_bh_schedule(QEMUBH *bh)
4351 CPUState *env = cpu_single_env;
4352 if (bh->scheduled)
4353 return;
4354 bh->scheduled = 1;
4355 bh->idle = 0;
4356 /* stop the currently executing CPU to execute the BH ASAP */
4357 if (env) {
4358 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4362 void qemu_bh_cancel(QEMUBH *bh)
4364 bh->scheduled = 0;
4367 void qemu_bh_delete(QEMUBH *bh)
4369 bh->scheduled = 0;
4370 bh->deleted = 1;
4373 static void qemu_bh_update_timeout(int *timeout)
4375 QEMUBH *bh;
4377 for (bh = first_bh; bh; bh = bh->next) {
4378 if (!bh->deleted && bh->scheduled) {
4379 if (bh->idle) {
4380 /* idle bottom halves will be polled at least
4381 * every 10ms */
4382 *timeout = MIN(10, *timeout);
4383 } else {
4384 /* non-idle bottom halves will be executed
4385 * immediately */
4386 *timeout = 0;
4387 break;
4393 /***********************************************************/
4394 /* machine registration */
4396 static QEMUMachine *first_machine = NULL;
4398 int qemu_register_machine(QEMUMachine *m)
4400 QEMUMachine **pm;
4401 pm = &first_machine;
4402 while (*pm != NULL)
4403 pm = &(*pm)->next;
4404 m->next = NULL;
4405 *pm = m;
4406 return 0;
4409 static QEMUMachine *find_machine(const char *name)
4411 QEMUMachine *m;
4413 for(m = first_machine; m != NULL; m = m->next) {
4414 if (!strcmp(m->name, name))
4415 return m;
4417 return NULL;
4420 /***********************************************************/
4421 /* main execution loop */
4423 static void gui_update(void *opaque)
4425 DisplayState *ds = opaque;
4426 ds->dpy_refresh(ds);
4427 qemu_mod_timer(ds->gui_timer,
4428 (ds->gui_timer_interval ?
4429 ds->gui_timer_interval :
4430 GUI_REFRESH_INTERVAL)
4431 + qemu_get_clock(rt_clock));
4434 struct vm_change_state_entry {
4435 VMChangeStateHandler *cb;
4436 void *opaque;
4437 LIST_ENTRY (vm_change_state_entry) entries;
4440 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4442 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4443 void *opaque)
4445 VMChangeStateEntry *e;
4447 e = qemu_mallocz(sizeof (*e));
4448 if (!e)
4449 return NULL;
4451 e->cb = cb;
4452 e->opaque = opaque;
4453 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4454 return e;
4457 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4459 LIST_REMOVE (e, entries);
4460 qemu_free (e);
4463 static void vm_state_notify(int running)
4465 VMChangeStateEntry *e;
4467 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4468 e->cb(e->opaque, running);
4472 /* XXX: support several handlers */
4473 static VMStopHandler *vm_stop_cb;
4474 static void *vm_stop_opaque;
4476 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4478 vm_stop_cb = cb;
4479 vm_stop_opaque = opaque;
4480 return 0;
4483 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4485 vm_stop_cb = NULL;
4488 void vm_start(void)
4490 if (!vm_running) {
4491 cpu_enable_ticks();
4492 vm_running = 1;
4493 vm_state_notify(1);
4494 qemu_rearm_alarm_timer(alarm_timer);
4498 void vm_stop(int reason)
4500 if (vm_running) {
4501 cpu_disable_ticks();
4502 vm_running = 0;
4503 if (reason != 0) {
4504 if (vm_stop_cb) {
4505 vm_stop_cb(vm_stop_opaque, reason);
4508 vm_state_notify(0);
4512 /* reset/shutdown handler */
4514 typedef struct QEMUResetEntry {
4515 QEMUResetHandler *func;
4516 void *opaque;
4517 struct QEMUResetEntry *next;
4518 } QEMUResetEntry;
4520 static QEMUResetEntry *first_reset_entry;
4521 static int reset_requested;
4522 static int shutdown_requested;
4523 static int powerdown_requested;
4525 int qemu_shutdown_requested(void)
4527 int r = shutdown_requested;
4528 shutdown_requested = 0;
4529 return r;
4532 int qemu_reset_requested(void)
4534 int r = reset_requested;
4535 reset_requested = 0;
4536 return r;
4539 int qemu_powerdown_requested(void)
4541 int r = powerdown_requested;
4542 powerdown_requested = 0;
4543 return r;
4546 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4548 QEMUResetEntry **pre, *re;
4550 pre = &first_reset_entry;
4551 while (*pre != NULL)
4552 pre = &(*pre)->next;
4553 re = qemu_mallocz(sizeof(QEMUResetEntry));
4554 re->func = func;
4555 re->opaque = opaque;
4556 re->next = NULL;
4557 *pre = re;
4560 void qemu_system_reset(void)
4562 QEMUResetEntry *re;
4564 /* reset all devices */
4565 for(re = first_reset_entry; re != NULL; re = re->next) {
4566 re->func(re->opaque);
4570 void qemu_system_reset_request(void)
4572 if (no_reboot) {
4573 shutdown_requested = 1;
4574 } else {
4575 reset_requested = 1;
4577 if (cpu_single_env)
4578 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4581 void qemu_system_shutdown_request(void)
4583 shutdown_requested = 1;
4584 if (cpu_single_env)
4585 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4588 void qemu_system_powerdown_request(void)
4590 powerdown_requested = 1;
4591 if (cpu_single_env)
4592 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4595 #ifdef _WIN32
4596 void host_main_loop_wait(int *timeout)
4598 int ret, ret2, i;
4599 PollingEntry *pe;
4602 /* XXX: need to suppress polling by better using win32 events */
4603 ret = 0;
4604 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4605 ret |= pe->func(pe->opaque);
4607 if (ret == 0) {
4608 int err;
4609 WaitObjects *w = &wait_objects;
4611 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4612 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4613 if (w->func[ret - WAIT_OBJECT_0])
4614 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4616 /* Check for additional signaled events */
4617 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4619 /* Check if event is signaled */
4620 ret2 = WaitForSingleObject(w->events[i], 0);
4621 if(ret2 == WAIT_OBJECT_0) {
4622 if (w->func[i])
4623 w->func[i](w->opaque[i]);
4624 } else if (ret2 == WAIT_TIMEOUT) {
4625 } else {
4626 err = GetLastError();
4627 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4630 } else if (ret == WAIT_TIMEOUT) {
4631 } else {
4632 err = GetLastError();
4633 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4637 *timeout = 0;
4639 #else
4640 void host_main_loop_wait(int *timeout)
4643 #endif
4645 void main_loop_wait(int timeout)
4647 IOHandlerRecord *ioh;
4648 fd_set rfds, wfds, xfds;
4649 int ret, nfds;
4650 struct timeval tv;
4652 qemu_bh_update_timeout(&timeout);
4654 host_main_loop_wait(&timeout);
4656 /* poll any events */
4657 /* XXX: separate device handlers from system ones */
4658 nfds = -1;
4659 FD_ZERO(&rfds);
4660 FD_ZERO(&wfds);
4661 FD_ZERO(&xfds);
4662 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4663 if (ioh->deleted)
4664 continue;
4665 if (ioh->fd_read &&
4666 (!ioh->fd_read_poll ||
4667 ioh->fd_read_poll(ioh->opaque) != 0)) {
4668 FD_SET(ioh->fd, &rfds);
4669 if (ioh->fd > nfds)
4670 nfds = ioh->fd;
4672 if (ioh->fd_write) {
4673 FD_SET(ioh->fd, &wfds);
4674 if (ioh->fd > nfds)
4675 nfds = ioh->fd;
4679 tv.tv_sec = timeout / 1000;
4680 tv.tv_usec = (timeout % 1000) * 1000;
4682 #if defined(CONFIG_SLIRP)
4683 if (slirp_is_inited()) {
4684 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4686 #endif
4687 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4688 if (ret > 0) {
4689 IOHandlerRecord **pioh;
4691 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4692 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4693 ioh->fd_read(ioh->opaque);
4695 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4696 ioh->fd_write(ioh->opaque);
4700 /* remove deleted IO handlers */
4701 pioh = &first_io_handler;
4702 while (*pioh) {
4703 ioh = *pioh;
4704 if (ioh->deleted) {
4705 *pioh = ioh->next;
4706 qemu_free(ioh);
4707 } else
4708 pioh = &ioh->next;
4711 #if defined(CONFIG_SLIRP)
4712 if (slirp_is_inited()) {
4713 if (ret < 0) {
4714 FD_ZERO(&rfds);
4715 FD_ZERO(&wfds);
4716 FD_ZERO(&xfds);
4718 slirp_select_poll(&rfds, &wfds, &xfds);
4720 #endif
4722 /* Check bottom-halves last in case any of the earlier events triggered
4723 them. */
4724 qemu_bh_poll();
4728 static int main_loop(void)
4730 int ret, timeout;
4731 #ifdef CONFIG_PROFILER
4732 int64_t ti;
4733 #endif
4734 CPUState *env;
4736 cur_cpu = first_cpu;
4737 next_cpu = cur_cpu->next_cpu ?: first_cpu;
4738 for(;;) {
4739 if (vm_running) {
4741 for(;;) {
4742 /* get next cpu */
4743 env = next_cpu;
4744 #ifdef CONFIG_PROFILER
4745 ti = profile_getclock();
4746 #endif
4747 if (use_icount) {
4748 int64_t count;
4749 int decr;
4750 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4751 env->icount_decr.u16.low = 0;
4752 env->icount_extra = 0;
4753 count = qemu_next_deadline();
4754 count = (count + (1 << icount_time_shift) - 1)
4755 >> icount_time_shift;
4756 qemu_icount += count;
4757 decr = (count > 0xffff) ? 0xffff : count;
4758 count -= decr;
4759 env->icount_decr.u16.low = decr;
4760 env->icount_extra = count;
4762 ret = cpu_exec(env);
4763 #ifdef CONFIG_PROFILER
4764 qemu_time += profile_getclock() - ti;
4765 #endif
4766 if (use_icount) {
4767 /* Fold pending instructions back into the
4768 instruction counter, and clear the interrupt flag. */
4769 qemu_icount -= (env->icount_decr.u16.low
4770 + env->icount_extra);
4771 env->icount_decr.u32 = 0;
4772 env->icount_extra = 0;
4774 next_cpu = env->next_cpu ?: first_cpu;
4775 if (event_pending && likely(ret != EXCP_DEBUG)) {
4776 ret = EXCP_INTERRUPT;
4777 event_pending = 0;
4778 break;
4780 if (ret == EXCP_HLT) {
4781 /* Give the next CPU a chance to run. */
4782 cur_cpu = env;
4783 continue;
4785 if (ret != EXCP_HALTED)
4786 break;
4787 /* all CPUs are halted ? */
4788 if (env == cur_cpu)
4789 break;
4791 cur_cpu = env;
4793 if (shutdown_requested) {
4794 ret = EXCP_INTERRUPT;
4795 if (no_shutdown) {
4796 vm_stop(0);
4797 no_shutdown = 0;
4799 else
4800 break;
4802 if (reset_requested) {
4803 reset_requested = 0;
4804 qemu_system_reset();
4805 ret = EXCP_INTERRUPT;
4807 if (powerdown_requested) {
4808 powerdown_requested = 0;
4809 qemu_system_powerdown();
4810 ret = EXCP_INTERRUPT;
4812 if (unlikely(ret == EXCP_DEBUG)) {
4813 vm_stop(EXCP_DEBUG);
4815 /* If all cpus are halted then wait until the next IRQ */
4816 /* XXX: use timeout computed from timers */
4817 if (ret == EXCP_HALTED) {
4818 if (use_icount) {
4819 int64_t add;
4820 int64_t delta;
4821 /* Advance virtual time to the next event. */
4822 if (use_icount == 1) {
4823 /* When not using an adaptive execution frequency
4824 we tend to get badly out of sync with real time,
4825 so just delay for a reasonable amount of time. */
4826 delta = 0;
4827 } else {
4828 delta = cpu_get_icount() - cpu_get_clock();
4830 if (delta > 0) {
4831 /* If virtual time is ahead of real time then just
4832 wait for IO. */
4833 timeout = (delta / 1000000) + 1;
4834 } else {
4835 /* Wait for either IO to occur or the next
4836 timer event. */
4837 add = qemu_next_deadline();
4838 /* We advance the timer before checking for IO.
4839 Limit the amount we advance so that early IO
4840 activity won't get the guest too far ahead. */
4841 if (add > 10000000)
4842 add = 10000000;
4843 delta += add;
4844 add = (add + (1 << icount_time_shift) - 1)
4845 >> icount_time_shift;
4846 qemu_icount += add;
4847 timeout = delta / 1000000;
4848 if (timeout < 0)
4849 timeout = 0;
4851 } else {
4852 timeout = 5000;
4854 } else {
4855 timeout = 0;
4857 } else {
4858 if (shutdown_requested) {
4859 ret = EXCP_INTERRUPT;
4860 break;
4862 timeout = 5000;
4864 #ifdef CONFIG_PROFILER
4865 ti = profile_getclock();
4866 #endif
4867 main_loop_wait(timeout);
4868 #ifdef CONFIG_PROFILER
4869 dev_time += profile_getclock() - ti;
4870 #endif
4872 cpu_disable_ticks();
4873 return ret;
4876 static void help(int exitcode)
4878 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4879 "usage: %s [options] [disk_image]\n"
4880 "\n"
4881 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4882 "\n"
4883 "Standard options:\n"
4884 "-M machine select emulated machine (-M ? for list)\n"
4885 "-cpu cpu select CPU (-cpu ? for list)\n"
4886 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4887 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4888 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4889 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4890 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
4891 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
4892 " [,cache=writethrough|writeback|none][,format=f]\n"
4893 " use 'file' as a drive image\n"
4894 "-mtdblock file use 'file' as on-board Flash memory image\n"
4895 "-sd file use 'file' as SecureDigital card image\n"
4896 "-pflash file use 'file' as a parallel flash image\n"
4897 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4898 "-snapshot write to temporary files instead of disk image files\n"
4899 #ifdef CONFIG_SDL
4900 "-no-frame open SDL window without a frame and window decorations\n"
4901 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4902 "-no-quit disable SDL window close capability\n"
4903 #endif
4904 #ifdef TARGET_I386
4905 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4906 #endif
4907 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4908 "-smp n set the number of CPUs to 'n' [default=1]\n"
4909 "-nographic disable graphical output and redirect serial I/Os to console\n"
4910 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4911 #ifndef _WIN32
4912 "-k language use keyboard layout (for example \"fr\" for French)\n"
4913 #endif
4914 #ifdef HAS_AUDIO
4915 "-audio-help print list of audio drivers and their options\n"
4916 "-soundhw c1,... enable audio support\n"
4917 " and only specified sound cards (comma separated list)\n"
4918 " use -soundhw ? to get the list of supported cards\n"
4919 " use -soundhw all to enable all of them\n"
4920 #endif
4921 "-vga [std|cirrus|vmware]\n"
4922 " select video card type\n"
4923 "-localtime set the real time clock to local time [default=utc]\n"
4924 "-full-screen start in full screen\n"
4925 #ifdef TARGET_I386
4926 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4927 #endif
4928 "-usb enable the USB driver (will be the default soon)\n"
4929 "-usbdevice name add the host or guest USB device 'name'\n"
4930 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4931 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4932 #endif
4933 "-name string set the name of the guest\n"
4934 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4935 "\n"
4936 "Network options:\n"
4937 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4938 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4939 #ifdef CONFIG_SLIRP
4940 "-net user[,vlan=n][,hostname=host]\n"
4941 " connect the user mode network stack to VLAN 'n' and send\n"
4942 " hostname 'host' to DHCP clients\n"
4943 #endif
4944 #ifdef _WIN32
4945 "-net tap[,vlan=n],ifname=name\n"
4946 " connect the host TAP network interface to VLAN 'n'\n"
4947 #else
4948 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4949 " connect the host TAP network interface to VLAN 'n' and use the\n"
4950 " network scripts 'file' (default=%s)\n"
4951 " and 'dfile' (default=%s);\n"
4952 " use '[down]script=no' to disable script execution;\n"
4953 " use 'fd=h' to connect to an already opened TAP interface\n"
4954 #endif
4955 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4956 " connect the vlan 'n' to another VLAN using a socket connection\n"
4957 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4958 " connect the vlan 'n' to multicast maddr and port\n"
4959 #ifdef CONFIG_VDE
4960 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4961 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4962 " on host and listening for incoming connections on 'socketpath'.\n"
4963 " Use group 'groupname' and mode 'octalmode' to change default\n"
4964 " ownership and permissions for communication port.\n"
4965 #endif
4966 "-net none use it alone to have zero network devices; if no -net option\n"
4967 " is provided, the default is '-net nic -net user'\n"
4968 "\n"
4969 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
4970 "-bt hci,host[:id]\n"
4971 " Use host's HCI with the given name\n"
4972 "-bt hci[,vlan=n]\n"
4973 " Emulate a standard HCI in virtual scatternet 'n'\n"
4974 "-bt vhci[,vlan=n]\n"
4975 " Add host computer to virtual scatternet 'n' using VHCI\n"
4976 "-bt device:dev[,vlan=n]\n"
4977 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
4978 "\n"
4979 #ifdef CONFIG_SLIRP
4980 "-tftp dir allow tftp access to files in dir [-net user]\n"
4981 "-bootp file advertise file in BOOTP replies\n"
4982 #ifndef _WIN32
4983 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4984 #endif
4985 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4986 " redirect TCP or UDP connections from host to guest [-net user]\n"
4987 #endif
4988 "\n"
4989 "Linux boot specific:\n"
4990 "-kernel bzImage use 'bzImage' as kernel image\n"
4991 "-append cmdline use 'cmdline' as kernel command line\n"
4992 "-initrd file use 'file' as initial ram disk\n"
4993 "\n"
4994 "Debug/Expert options:\n"
4995 "-monitor dev redirect the monitor to char device 'dev'\n"
4996 "-serial dev redirect the serial port to char device 'dev'\n"
4997 "-parallel dev redirect the parallel port to char device 'dev'\n"
4998 "-pidfile file Write PID to 'file'\n"
4999 "-S freeze CPU at startup (use 'c' to start execution)\n"
5000 "-s wait gdb connection to port\n"
5001 "-p port set gdb connection port [default=%s]\n"
5002 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5003 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5004 " translation (t=none or lba) (usually qemu can guess them)\n"
5005 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
5006 #ifdef USE_KQEMU
5007 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5008 "-no-kqemu disable KQEMU kernel module usage\n"
5009 #endif
5010 #ifdef CONFIG_KVM
5011 "-enable-kvm enable KVM full virtualization support\n"
5012 #endif
5013 #ifdef TARGET_I386
5014 "-no-acpi disable ACPI\n"
5015 #endif
5016 #ifdef CONFIG_CURSES
5017 "-curses use a curses/ncurses interface instead of SDL\n"
5018 #endif
5019 "-no-reboot exit instead of rebooting\n"
5020 "-no-shutdown stop before shutdown\n"
5021 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
5022 "-vnc display start a VNC server on display\n"
5023 #ifndef _WIN32
5024 "-daemonize daemonize QEMU after initializing\n"
5025 #endif
5026 "-option-rom rom load a file, rom, into the option ROM space\n"
5027 #ifdef TARGET_SPARC
5028 "-prom-env variable=value set OpenBIOS nvram variables\n"
5029 #endif
5030 "-clock force the use of the given methods for timer alarm.\n"
5031 " To see what timers are available use -clock ?\n"
5032 "-startdate select initial date of the clock\n"
5033 "-icount [N|auto]\n"
5034 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
5035 "\n"
5036 "During emulation, the following keys are useful:\n"
5037 "ctrl-alt-f toggle full screen\n"
5038 "ctrl-alt-n switch to virtual console 'n'\n"
5039 "ctrl-alt toggle mouse and keyboard grab\n"
5040 "\n"
5041 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5043 "qemu",
5044 DEFAULT_RAM_SIZE,
5045 #ifndef _WIN32
5046 DEFAULT_NETWORK_SCRIPT,
5047 DEFAULT_NETWORK_DOWN_SCRIPT,
5048 #endif
5049 DEFAULT_GDBSTUB_PORT,
5050 "/tmp/qemu.log");
5051 exit(exitcode);
5054 #define HAS_ARG 0x0001
5056 enum {
5057 QEMU_OPTION_h,
5059 QEMU_OPTION_M,
5060 QEMU_OPTION_cpu,
5061 QEMU_OPTION_fda,
5062 QEMU_OPTION_fdb,
5063 QEMU_OPTION_hda,
5064 QEMU_OPTION_hdb,
5065 QEMU_OPTION_hdc,
5066 QEMU_OPTION_hdd,
5067 QEMU_OPTION_drive,
5068 QEMU_OPTION_cdrom,
5069 QEMU_OPTION_mtdblock,
5070 QEMU_OPTION_sd,
5071 QEMU_OPTION_pflash,
5072 QEMU_OPTION_boot,
5073 QEMU_OPTION_snapshot,
5074 #ifdef TARGET_I386
5075 QEMU_OPTION_no_fd_bootchk,
5076 #endif
5077 QEMU_OPTION_m,
5078 QEMU_OPTION_nographic,
5079 QEMU_OPTION_portrait,
5080 #ifdef HAS_AUDIO
5081 QEMU_OPTION_audio_help,
5082 QEMU_OPTION_soundhw,
5083 #endif
5085 QEMU_OPTION_net,
5086 QEMU_OPTION_tftp,
5087 QEMU_OPTION_bootp,
5088 QEMU_OPTION_smb,
5089 QEMU_OPTION_redir,
5090 QEMU_OPTION_bt,
5092 QEMU_OPTION_kernel,
5093 QEMU_OPTION_append,
5094 QEMU_OPTION_initrd,
5096 QEMU_OPTION_S,
5097 QEMU_OPTION_s,
5098 QEMU_OPTION_p,
5099 QEMU_OPTION_d,
5100 QEMU_OPTION_hdachs,
5101 QEMU_OPTION_L,
5102 QEMU_OPTION_bios,
5103 QEMU_OPTION_k,
5104 QEMU_OPTION_localtime,
5105 QEMU_OPTION_g,
5106 QEMU_OPTION_vga,
5107 QEMU_OPTION_echr,
5108 QEMU_OPTION_monitor,
5109 QEMU_OPTION_serial,
5110 QEMU_OPTION_parallel,
5111 QEMU_OPTION_loadvm,
5112 QEMU_OPTION_full_screen,
5113 QEMU_OPTION_no_frame,
5114 QEMU_OPTION_alt_grab,
5115 QEMU_OPTION_no_quit,
5116 QEMU_OPTION_pidfile,
5117 QEMU_OPTION_no_kqemu,
5118 QEMU_OPTION_kernel_kqemu,
5119 QEMU_OPTION_enable_kvm,
5120 QEMU_OPTION_win2k_hack,
5121 QEMU_OPTION_usb,
5122 QEMU_OPTION_usbdevice,
5123 QEMU_OPTION_smp,
5124 QEMU_OPTION_vnc,
5125 QEMU_OPTION_no_acpi,
5126 QEMU_OPTION_curses,
5127 QEMU_OPTION_no_reboot,
5128 QEMU_OPTION_no_shutdown,
5129 QEMU_OPTION_show_cursor,
5130 QEMU_OPTION_daemonize,
5131 QEMU_OPTION_option_rom,
5132 QEMU_OPTION_semihosting,
5133 QEMU_OPTION_name,
5134 QEMU_OPTION_prom_env,
5135 QEMU_OPTION_old_param,
5136 QEMU_OPTION_clock,
5137 QEMU_OPTION_startdate,
5138 QEMU_OPTION_tb_size,
5139 QEMU_OPTION_icount,
5140 QEMU_OPTION_uuid,
5141 QEMU_OPTION_incoming,
5144 typedef struct QEMUOption {
5145 const char *name;
5146 int flags;
5147 int index;
5148 } QEMUOption;
5150 static const QEMUOption qemu_options[] = {
5151 { "h", 0, QEMU_OPTION_h },
5152 { "help", 0, QEMU_OPTION_h },
5154 { "M", HAS_ARG, QEMU_OPTION_M },
5155 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
5156 { "fda", HAS_ARG, QEMU_OPTION_fda },
5157 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5158 { "hda", HAS_ARG, QEMU_OPTION_hda },
5159 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5160 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5161 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5162 { "drive", HAS_ARG, QEMU_OPTION_drive },
5163 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5164 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
5165 { "sd", HAS_ARG, QEMU_OPTION_sd },
5166 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
5167 { "boot", HAS_ARG, QEMU_OPTION_boot },
5168 { "snapshot", 0, QEMU_OPTION_snapshot },
5169 #ifdef TARGET_I386
5170 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5171 #endif
5172 { "m", HAS_ARG, QEMU_OPTION_m },
5173 { "nographic", 0, QEMU_OPTION_nographic },
5174 { "portrait", 0, QEMU_OPTION_portrait },
5175 { "k", HAS_ARG, QEMU_OPTION_k },
5176 #ifdef HAS_AUDIO
5177 { "audio-help", 0, QEMU_OPTION_audio_help },
5178 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5179 #endif
5181 { "net", HAS_ARG, QEMU_OPTION_net},
5182 #ifdef CONFIG_SLIRP
5183 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5184 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
5185 #ifndef _WIN32
5186 { "smb", HAS_ARG, QEMU_OPTION_smb },
5187 #endif
5188 { "redir", HAS_ARG, QEMU_OPTION_redir },
5189 #endif
5190 { "bt", HAS_ARG, QEMU_OPTION_bt },
5192 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5193 { "append", HAS_ARG, QEMU_OPTION_append },
5194 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5196 { "S", 0, QEMU_OPTION_S },
5197 { "s", 0, QEMU_OPTION_s },
5198 { "p", HAS_ARG, QEMU_OPTION_p },
5199 { "d", HAS_ARG, QEMU_OPTION_d },
5200 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5201 { "L", HAS_ARG, QEMU_OPTION_L },
5202 { "bios", HAS_ARG, QEMU_OPTION_bios },
5203 #ifdef USE_KQEMU
5204 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5205 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5206 #endif
5207 #ifdef CONFIG_KVM
5208 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
5209 #endif
5210 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5211 { "g", 1, QEMU_OPTION_g },
5212 #endif
5213 { "localtime", 0, QEMU_OPTION_localtime },
5214 { "vga", HAS_ARG, QEMU_OPTION_vga },
5215 { "echr", HAS_ARG, QEMU_OPTION_echr },
5216 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
5217 { "serial", HAS_ARG, QEMU_OPTION_serial },
5218 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
5219 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5220 { "full-screen", 0, QEMU_OPTION_full_screen },
5221 #ifdef CONFIG_SDL
5222 { "no-frame", 0, QEMU_OPTION_no_frame },
5223 { "alt-grab", 0, QEMU_OPTION_alt_grab },
5224 { "no-quit", 0, QEMU_OPTION_no_quit },
5225 #endif
5226 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5227 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5228 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5229 { "smp", HAS_ARG, QEMU_OPTION_smp },
5230 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5231 #ifdef CONFIG_CURSES
5232 { "curses", 0, QEMU_OPTION_curses },
5233 #endif
5234 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
5236 /* temporary options */
5237 { "usb", 0, QEMU_OPTION_usb },
5238 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5239 { "no-reboot", 0, QEMU_OPTION_no_reboot },
5240 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
5241 { "show-cursor", 0, QEMU_OPTION_show_cursor },
5242 { "daemonize", 0, QEMU_OPTION_daemonize },
5243 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
5244 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5245 { "semihosting", 0, QEMU_OPTION_semihosting },
5246 #endif
5247 { "name", HAS_ARG, QEMU_OPTION_name },
5248 #if defined(TARGET_SPARC)
5249 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
5250 #endif
5251 #if defined(TARGET_ARM)
5252 { "old-param", 0, QEMU_OPTION_old_param },
5253 #endif
5254 { "clock", HAS_ARG, QEMU_OPTION_clock },
5255 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
5256 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
5257 { "icount", HAS_ARG, QEMU_OPTION_icount },
5258 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
5259 { NULL },
5262 /* password input */
5264 int qemu_key_check(BlockDriverState *bs, const char *name)
5266 char password[256];
5267 int i;
5269 if (!bdrv_is_encrypted(bs))
5270 return 0;
5272 term_printf("%s is encrypted.\n", name);
5273 for(i = 0; i < 3; i++) {
5274 monitor_readline("Password: ", 1, password, sizeof(password));
5275 if (bdrv_set_key(bs, password) == 0)
5276 return 0;
5277 term_printf("invalid password\n");
5279 return -EPERM;
5282 static BlockDriverState *get_bdrv(int index)
5284 if (index > nb_drives)
5285 return NULL;
5286 return drives_table[index].bdrv;
5289 static void read_passwords(void)
5291 BlockDriverState *bs;
5292 int i;
5294 for(i = 0; i < 6; i++) {
5295 bs = get_bdrv(i);
5296 if (bs)
5297 qemu_key_check(bs, bdrv_get_device_name(bs));
5301 #ifdef HAS_AUDIO
5302 struct soundhw soundhw[] = {
5303 #ifdef HAS_AUDIO_CHOICE
5304 #if defined(TARGET_I386) || defined(TARGET_MIPS)
5306 "pcspk",
5307 "PC speaker",
5310 { .init_isa = pcspk_audio_init }
5312 #endif
5314 "sb16",
5315 "Creative Sound Blaster 16",
5318 { .init_isa = SB16_init }
5321 #ifdef CONFIG_CS4231A
5323 "cs4231a",
5324 "CS4231A",
5327 { .init_isa = cs4231a_init }
5329 #endif
5331 #ifdef CONFIG_ADLIB
5333 "adlib",
5334 #ifdef HAS_YMF262
5335 "Yamaha YMF262 (OPL3)",
5336 #else
5337 "Yamaha YM3812 (OPL2)",
5338 #endif
5341 { .init_isa = Adlib_init }
5343 #endif
5345 #ifdef CONFIG_GUS
5347 "gus",
5348 "Gravis Ultrasound GF1",
5351 { .init_isa = GUS_init }
5353 #endif
5355 #ifdef CONFIG_AC97
5357 "ac97",
5358 "Intel 82801AA AC97 Audio",
5361 { .init_pci = ac97_init }
5363 #endif
5366 "es1370",
5367 "ENSONIQ AudioPCI ES1370",
5370 { .init_pci = es1370_init }
5372 #endif
5374 { NULL, NULL, 0, 0, { NULL } }
5377 static void select_soundhw (const char *optarg)
5379 struct soundhw *c;
5381 if (*optarg == '?') {
5382 show_valid_cards:
5384 printf ("Valid sound card names (comma separated):\n");
5385 for (c = soundhw; c->name; ++c) {
5386 printf ("%-11s %s\n", c->name, c->descr);
5388 printf ("\n-soundhw all will enable all of the above\n");
5389 exit (*optarg != '?');
5391 else {
5392 size_t l;
5393 const char *p;
5394 char *e;
5395 int bad_card = 0;
5397 if (!strcmp (optarg, "all")) {
5398 for (c = soundhw; c->name; ++c) {
5399 c->enabled = 1;
5401 return;
5404 p = optarg;
5405 while (*p) {
5406 e = strchr (p, ',');
5407 l = !e ? strlen (p) : (size_t) (e - p);
5409 for (c = soundhw; c->name; ++c) {
5410 if (!strncmp (c->name, p, l)) {
5411 c->enabled = 1;
5412 break;
5416 if (!c->name) {
5417 if (l > 80) {
5418 fprintf (stderr,
5419 "Unknown sound card name (too big to show)\n");
5421 else {
5422 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5423 (int) l, p);
5425 bad_card = 1;
5427 p += l + (e != NULL);
5430 if (bad_card)
5431 goto show_valid_cards;
5434 #endif
5436 static void select_vgahw (const char *p)
5438 const char *opts;
5440 if (strstart(p, "std", &opts)) {
5441 cirrus_vga_enabled = 0;
5442 vmsvga_enabled = 0;
5443 } else if (strstart(p, "cirrus", &opts)) {
5444 cirrus_vga_enabled = 1;
5445 vmsvga_enabled = 0;
5446 } else if (strstart(p, "vmware", &opts)) {
5447 cirrus_vga_enabled = 0;
5448 vmsvga_enabled = 1;
5449 } else {
5450 invalid_vga:
5451 fprintf(stderr, "Unknown vga type: %s\n", p);
5452 exit(1);
5454 while (*opts) {
5455 const char *nextopt;
5457 if (strstart(opts, ",retrace=", &nextopt)) {
5458 opts = nextopt;
5459 if (strstart(opts, "dumb", &nextopt))
5460 vga_retrace_method = VGA_RETRACE_DUMB;
5461 else if (strstart(opts, "precise", &nextopt))
5462 vga_retrace_method = VGA_RETRACE_PRECISE;
5463 else goto invalid_vga;
5464 } else goto invalid_vga;
5465 opts = nextopt;
5469 #ifdef _WIN32
5470 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5472 exit(STATUS_CONTROL_C_EXIT);
5473 return TRUE;
5475 #endif
5477 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
5479 int ret;
5481 if(strlen(str) != 36)
5482 return -1;
5484 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
5485 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
5486 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
5488 if(ret != 16)
5489 return -1;
5491 return 0;
5494 #define MAX_NET_CLIENTS 32
5496 #ifndef _WIN32
5498 static void termsig_handler(int signal)
5500 qemu_system_shutdown_request();
5503 static void termsig_setup(void)
5505 struct sigaction act;
5507 memset(&act, 0, sizeof(act));
5508 act.sa_handler = termsig_handler;
5509 sigaction(SIGINT, &act, NULL);
5510 sigaction(SIGHUP, &act, NULL);
5511 sigaction(SIGTERM, &act, NULL);
5514 #endif
5516 int main(int argc, char **argv)
5518 #ifdef CONFIG_GDBSTUB
5519 int use_gdbstub;
5520 const char *gdbstub_port;
5521 #endif
5522 uint32_t boot_devices_bitmap = 0;
5523 int i;
5524 int snapshot, linux_boot, net_boot;
5525 const char *initrd_filename;
5526 const char *kernel_filename, *kernel_cmdline;
5527 const char *boot_devices = "";
5528 DisplayState *ds = &display_state;
5529 int cyls, heads, secs, translation;
5530 const char *net_clients[MAX_NET_CLIENTS];
5531 int nb_net_clients;
5532 const char *bt_opts[MAX_BT_CMDLINE];
5533 int nb_bt_opts;
5534 int hda_index;
5535 int optind;
5536 const char *r, *optarg;
5537 CharDriverState *monitor_hd;
5538 const char *monitor_device;
5539 const char *serial_devices[MAX_SERIAL_PORTS];
5540 int serial_device_index;
5541 const char *parallel_devices[MAX_PARALLEL_PORTS];
5542 int parallel_device_index;
5543 const char *loadvm = NULL;
5544 QEMUMachine *machine;
5545 const char *cpu_model;
5546 const char *usb_devices[MAX_USB_CMDLINE];
5547 int usb_devices_index;
5548 int fds[2];
5549 int tb_size;
5550 const char *pid_file = NULL;
5551 int autostart;
5552 const char *incoming = NULL;
5554 LIST_INIT (&vm_change_state_head);
5555 #ifndef _WIN32
5557 struct sigaction act;
5558 sigfillset(&act.sa_mask);
5559 act.sa_flags = 0;
5560 act.sa_handler = SIG_IGN;
5561 sigaction(SIGPIPE, &act, NULL);
5563 #else
5564 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5565 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5566 QEMU to run on a single CPU */
5568 HANDLE h;
5569 DWORD mask, smask;
5570 int i;
5571 h = GetCurrentProcess();
5572 if (GetProcessAffinityMask(h, &mask, &smask)) {
5573 for(i = 0; i < 32; i++) {
5574 if (mask & (1 << i))
5575 break;
5577 if (i != 32) {
5578 mask = 1 << i;
5579 SetProcessAffinityMask(h, mask);
5583 #endif
5585 register_machines();
5586 machine = first_machine;
5587 cpu_model = NULL;
5588 initrd_filename = NULL;
5589 ram_size = 0;
5590 vga_ram_size = VGA_RAM_SIZE;
5591 #ifdef CONFIG_GDBSTUB
5592 use_gdbstub = 0;
5593 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5594 #endif
5595 snapshot = 0;
5596 nographic = 0;
5597 curses = 0;
5598 kernel_filename = NULL;
5599 kernel_cmdline = "";
5600 cyls = heads = secs = 0;
5601 translation = BIOS_ATA_TRANSLATION_AUTO;
5602 monitor_device = "vc";
5604 serial_devices[0] = "vc:80Cx24C";
5605 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5606 serial_devices[i] = NULL;
5607 serial_device_index = 0;
5609 parallel_devices[0] = "vc:640x480";
5610 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5611 parallel_devices[i] = NULL;
5612 parallel_device_index = 0;
5614 usb_devices_index = 0;
5616 nb_net_clients = 0;
5617 nb_bt_opts = 0;
5618 nb_drives = 0;
5619 nb_drives_opt = 0;
5620 hda_index = -1;
5622 nb_nics = 0;
5624 tb_size = 0;
5625 autostart= 1;
5627 optind = 1;
5628 for(;;) {
5629 if (optind >= argc)
5630 break;
5631 r = argv[optind];
5632 if (r[0] != '-') {
5633 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5634 } else {
5635 const QEMUOption *popt;
5637 optind++;
5638 /* Treat --foo the same as -foo. */
5639 if (r[1] == '-')
5640 r++;
5641 popt = qemu_options;
5642 for(;;) {
5643 if (!popt->name) {
5644 fprintf(stderr, "%s: invalid option -- '%s'\n",
5645 argv[0], r);
5646 exit(1);
5648 if (!strcmp(popt->name, r + 1))
5649 break;
5650 popt++;
5652 if (popt->flags & HAS_ARG) {
5653 if (optind >= argc) {
5654 fprintf(stderr, "%s: option '%s' requires an argument\n",
5655 argv[0], r);
5656 exit(1);
5658 optarg = argv[optind++];
5659 } else {
5660 optarg = NULL;
5663 switch(popt->index) {
5664 case QEMU_OPTION_M:
5665 machine = find_machine(optarg);
5666 if (!machine) {
5667 QEMUMachine *m;
5668 printf("Supported machines are:\n");
5669 for(m = first_machine; m != NULL; m = m->next) {
5670 printf("%-10s %s%s\n",
5671 m->name, m->desc,
5672 m == first_machine ? " (default)" : "");
5674 exit(*optarg != '?');
5676 break;
5677 case QEMU_OPTION_cpu:
5678 /* hw initialization will check this */
5679 if (*optarg == '?') {
5680 /* XXX: implement xxx_cpu_list for targets that still miss it */
5681 #if defined(cpu_list)
5682 cpu_list(stdout, &fprintf);
5683 #endif
5684 exit(0);
5685 } else {
5686 cpu_model = optarg;
5688 break;
5689 case QEMU_OPTION_initrd:
5690 initrd_filename = optarg;
5691 break;
5692 case QEMU_OPTION_hda:
5693 if (cyls == 0)
5694 hda_index = drive_add(optarg, HD_ALIAS, 0);
5695 else
5696 hda_index = drive_add(optarg, HD_ALIAS
5697 ",cyls=%d,heads=%d,secs=%d%s",
5698 0, cyls, heads, secs,
5699 translation == BIOS_ATA_TRANSLATION_LBA ?
5700 ",trans=lba" :
5701 translation == BIOS_ATA_TRANSLATION_NONE ?
5702 ",trans=none" : "");
5703 break;
5704 case QEMU_OPTION_hdb:
5705 case QEMU_OPTION_hdc:
5706 case QEMU_OPTION_hdd:
5707 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5708 break;
5709 case QEMU_OPTION_drive:
5710 drive_add(NULL, "%s", optarg);
5711 break;
5712 case QEMU_OPTION_mtdblock:
5713 drive_add(optarg, MTD_ALIAS);
5714 break;
5715 case QEMU_OPTION_sd:
5716 drive_add(optarg, SD_ALIAS);
5717 break;
5718 case QEMU_OPTION_pflash:
5719 drive_add(optarg, PFLASH_ALIAS);
5720 break;
5721 case QEMU_OPTION_snapshot:
5722 snapshot = 1;
5723 break;
5724 case QEMU_OPTION_hdachs:
5726 const char *p;
5727 p = optarg;
5728 cyls = strtol(p, (char **)&p, 0);
5729 if (cyls < 1 || cyls > 16383)
5730 goto chs_fail;
5731 if (*p != ',')
5732 goto chs_fail;
5733 p++;
5734 heads = strtol(p, (char **)&p, 0);
5735 if (heads < 1 || heads > 16)
5736 goto chs_fail;
5737 if (*p != ',')
5738 goto chs_fail;
5739 p++;
5740 secs = strtol(p, (char **)&p, 0);
5741 if (secs < 1 || secs > 63)
5742 goto chs_fail;
5743 if (*p == ',') {
5744 p++;
5745 if (!strcmp(p, "none"))
5746 translation = BIOS_ATA_TRANSLATION_NONE;
5747 else if (!strcmp(p, "lba"))
5748 translation = BIOS_ATA_TRANSLATION_LBA;
5749 else if (!strcmp(p, "auto"))
5750 translation = BIOS_ATA_TRANSLATION_AUTO;
5751 else
5752 goto chs_fail;
5753 } else if (*p != '\0') {
5754 chs_fail:
5755 fprintf(stderr, "qemu: invalid physical CHS format\n");
5756 exit(1);
5758 if (hda_index != -1)
5759 snprintf(drives_opt[hda_index].opt,
5760 sizeof(drives_opt[hda_index].opt),
5761 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5762 0, cyls, heads, secs,
5763 translation == BIOS_ATA_TRANSLATION_LBA ?
5764 ",trans=lba" :
5765 translation == BIOS_ATA_TRANSLATION_NONE ?
5766 ",trans=none" : "");
5768 break;
5769 case QEMU_OPTION_nographic:
5770 nographic = 1;
5771 break;
5772 #ifdef CONFIG_CURSES
5773 case QEMU_OPTION_curses:
5774 curses = 1;
5775 break;
5776 #endif
5777 case QEMU_OPTION_portrait:
5778 graphic_rotate = 1;
5779 break;
5780 case QEMU_OPTION_kernel:
5781 kernel_filename = optarg;
5782 break;
5783 case QEMU_OPTION_append:
5784 kernel_cmdline = optarg;
5785 break;
5786 case QEMU_OPTION_cdrom:
5787 drive_add(optarg, CDROM_ALIAS);
5788 break;
5789 case QEMU_OPTION_boot:
5790 boot_devices = optarg;
5791 /* We just do some generic consistency checks */
5793 /* Could easily be extended to 64 devices if needed */
5794 const char *p;
5796 boot_devices_bitmap = 0;
5797 for (p = boot_devices; *p != '\0'; p++) {
5798 /* Allowed boot devices are:
5799 * a b : floppy disk drives
5800 * c ... f : IDE disk drives
5801 * g ... m : machine implementation dependant drives
5802 * n ... p : network devices
5803 * It's up to each machine implementation to check
5804 * if the given boot devices match the actual hardware
5805 * implementation and firmware features.
5807 if (*p < 'a' || *p > 'q') {
5808 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5809 exit(1);
5811 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5812 fprintf(stderr,
5813 "Boot device '%c' was given twice\n",*p);
5814 exit(1);
5816 boot_devices_bitmap |= 1 << (*p - 'a');
5819 break;
5820 case QEMU_OPTION_fda:
5821 case QEMU_OPTION_fdb:
5822 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5823 break;
5824 #ifdef TARGET_I386
5825 case QEMU_OPTION_no_fd_bootchk:
5826 fd_bootchk = 0;
5827 break;
5828 #endif
5829 case QEMU_OPTION_net:
5830 if (nb_net_clients >= MAX_NET_CLIENTS) {
5831 fprintf(stderr, "qemu: too many network clients\n");
5832 exit(1);
5834 net_clients[nb_net_clients] = optarg;
5835 nb_net_clients++;
5836 break;
5837 #ifdef CONFIG_SLIRP
5838 case QEMU_OPTION_tftp:
5839 tftp_prefix = optarg;
5840 break;
5841 case QEMU_OPTION_bootp:
5842 bootp_filename = optarg;
5843 break;
5844 #ifndef _WIN32
5845 case QEMU_OPTION_smb:
5846 net_slirp_smb(optarg);
5847 break;
5848 #endif
5849 case QEMU_OPTION_redir:
5850 net_slirp_redir(optarg);
5851 break;
5852 #endif
5853 case QEMU_OPTION_bt:
5854 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5855 fprintf(stderr, "qemu: too many bluetooth options\n");
5856 exit(1);
5858 bt_opts[nb_bt_opts++] = optarg;
5859 break;
5860 #ifdef HAS_AUDIO
5861 case QEMU_OPTION_audio_help:
5862 AUD_help ();
5863 exit (0);
5864 break;
5865 case QEMU_OPTION_soundhw:
5866 select_soundhw (optarg);
5867 break;
5868 #endif
5869 case QEMU_OPTION_h:
5870 help(0);
5871 break;
5872 case QEMU_OPTION_m: {
5873 uint64_t value;
5874 char *ptr;
5876 value = strtoul(optarg, &ptr, 10);
5877 switch (*ptr) {
5878 case 0: case 'M': case 'm':
5879 value <<= 20;
5880 break;
5881 case 'G': case 'g':
5882 value <<= 30;
5883 break;
5884 default:
5885 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5886 exit(1);
5889 /* On 32-bit hosts, QEMU is limited by virtual address space */
5890 if (value > (2047 << 20)
5891 #ifndef USE_KQEMU
5892 && HOST_LONG_BITS == 32
5893 #endif
5895 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5896 exit(1);
5898 if (value != (uint64_t)(ram_addr_t)value) {
5899 fprintf(stderr, "qemu: ram size too large\n");
5900 exit(1);
5902 ram_size = value;
5903 break;
5905 case QEMU_OPTION_d:
5907 int mask;
5908 const CPULogItem *item;
5910 mask = cpu_str_to_log_mask(optarg);
5911 if (!mask) {
5912 printf("Log items (comma separated):\n");
5913 for(item = cpu_log_items; item->mask != 0; item++) {
5914 printf("%-10s %s\n", item->name, item->help);
5916 exit(1);
5918 cpu_set_log(mask);
5920 break;
5921 #ifdef CONFIG_GDBSTUB
5922 case QEMU_OPTION_s:
5923 use_gdbstub = 1;
5924 break;
5925 case QEMU_OPTION_p:
5926 gdbstub_port = optarg;
5927 break;
5928 #endif
5929 case QEMU_OPTION_L:
5930 bios_dir = optarg;
5931 break;
5932 case QEMU_OPTION_bios:
5933 bios_name = optarg;
5934 break;
5935 case QEMU_OPTION_S:
5936 autostart = 0;
5937 break;
5938 case QEMU_OPTION_k:
5939 keyboard_layout = optarg;
5940 break;
5941 case QEMU_OPTION_localtime:
5942 rtc_utc = 0;
5943 break;
5944 case QEMU_OPTION_vga:
5945 select_vgahw (optarg);
5946 break;
5947 case QEMU_OPTION_g:
5949 const char *p;
5950 int w, h, depth;
5951 p = optarg;
5952 w = strtol(p, (char **)&p, 10);
5953 if (w <= 0) {
5954 graphic_error:
5955 fprintf(stderr, "qemu: invalid resolution or depth\n");
5956 exit(1);
5958 if (*p != 'x')
5959 goto graphic_error;
5960 p++;
5961 h = strtol(p, (char **)&p, 10);
5962 if (h <= 0)
5963 goto graphic_error;
5964 if (*p == 'x') {
5965 p++;
5966 depth = strtol(p, (char **)&p, 10);
5967 if (depth != 8 && depth != 15 && depth != 16 &&
5968 depth != 24 && depth != 32)
5969 goto graphic_error;
5970 } else if (*p == '\0') {
5971 depth = graphic_depth;
5972 } else {
5973 goto graphic_error;
5976 graphic_width = w;
5977 graphic_height = h;
5978 graphic_depth = depth;
5980 break;
5981 case QEMU_OPTION_echr:
5983 char *r;
5984 term_escape_char = strtol(optarg, &r, 0);
5985 if (r == optarg)
5986 printf("Bad argument to echr\n");
5987 break;
5989 case QEMU_OPTION_monitor:
5990 monitor_device = optarg;
5991 break;
5992 case QEMU_OPTION_serial:
5993 if (serial_device_index >= MAX_SERIAL_PORTS) {
5994 fprintf(stderr, "qemu: too many serial ports\n");
5995 exit(1);
5997 serial_devices[serial_device_index] = optarg;
5998 serial_device_index++;
5999 break;
6000 case QEMU_OPTION_parallel:
6001 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6002 fprintf(stderr, "qemu: too many parallel ports\n");
6003 exit(1);
6005 parallel_devices[parallel_device_index] = optarg;
6006 parallel_device_index++;
6007 break;
6008 case QEMU_OPTION_loadvm:
6009 loadvm = optarg;
6010 break;
6011 case QEMU_OPTION_full_screen:
6012 full_screen = 1;
6013 break;
6014 #ifdef CONFIG_SDL
6015 case QEMU_OPTION_no_frame:
6016 no_frame = 1;
6017 break;
6018 case QEMU_OPTION_alt_grab:
6019 alt_grab = 1;
6020 break;
6021 case QEMU_OPTION_no_quit:
6022 no_quit = 1;
6023 break;
6024 #endif
6025 case QEMU_OPTION_pidfile:
6026 pid_file = optarg;
6027 break;
6028 #ifdef TARGET_I386
6029 case QEMU_OPTION_win2k_hack:
6030 win2k_install_hack = 1;
6031 break;
6032 #endif
6033 #ifdef USE_KQEMU
6034 case QEMU_OPTION_no_kqemu:
6035 kqemu_allowed = 0;
6036 break;
6037 case QEMU_OPTION_kernel_kqemu:
6038 kqemu_allowed = 2;
6039 break;
6040 #endif
6041 #ifdef CONFIG_KVM
6042 case QEMU_OPTION_enable_kvm:
6043 kvm_allowed = 1;
6044 #ifdef USE_KQEMU
6045 kqemu_allowed = 0;
6046 #endif
6047 break;
6048 #endif
6049 case QEMU_OPTION_usb:
6050 usb_enabled = 1;
6051 break;
6052 case QEMU_OPTION_usbdevice:
6053 usb_enabled = 1;
6054 if (usb_devices_index >= MAX_USB_CMDLINE) {
6055 fprintf(stderr, "Too many USB devices\n");
6056 exit(1);
6058 usb_devices[usb_devices_index] = optarg;
6059 usb_devices_index++;
6060 break;
6061 case QEMU_OPTION_smp:
6062 smp_cpus = atoi(optarg);
6063 if (smp_cpus < 1) {
6064 fprintf(stderr, "Invalid number of CPUs\n");
6065 exit(1);
6067 break;
6068 case QEMU_OPTION_vnc:
6069 vnc_display = optarg;
6070 break;
6071 case QEMU_OPTION_no_acpi:
6072 acpi_enabled = 0;
6073 break;
6074 case QEMU_OPTION_no_reboot:
6075 no_reboot = 1;
6076 break;
6077 case QEMU_OPTION_no_shutdown:
6078 no_shutdown = 1;
6079 break;
6080 case QEMU_OPTION_show_cursor:
6081 cursor_hide = 0;
6082 break;
6083 case QEMU_OPTION_uuid:
6084 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
6085 fprintf(stderr, "Fail to parse UUID string."
6086 " Wrong format.\n");
6087 exit(1);
6089 break;
6090 case QEMU_OPTION_daemonize:
6091 daemonize = 1;
6092 break;
6093 case QEMU_OPTION_option_rom:
6094 if (nb_option_roms >= MAX_OPTION_ROMS) {
6095 fprintf(stderr, "Too many option ROMs\n");
6096 exit(1);
6098 option_rom[nb_option_roms] = optarg;
6099 nb_option_roms++;
6100 break;
6101 case QEMU_OPTION_semihosting:
6102 semihosting_enabled = 1;
6103 break;
6104 case QEMU_OPTION_name:
6105 qemu_name = optarg;
6106 break;
6107 #ifdef TARGET_SPARC
6108 case QEMU_OPTION_prom_env:
6109 if (nb_prom_envs >= MAX_PROM_ENVS) {
6110 fprintf(stderr, "Too many prom variables\n");
6111 exit(1);
6113 prom_envs[nb_prom_envs] = optarg;
6114 nb_prom_envs++;
6115 break;
6116 #endif
6117 #ifdef TARGET_ARM
6118 case QEMU_OPTION_old_param:
6119 old_param = 1;
6120 break;
6121 #endif
6122 case QEMU_OPTION_clock:
6123 configure_alarms(optarg);
6124 break;
6125 case QEMU_OPTION_startdate:
6127 struct tm tm;
6128 time_t rtc_start_date;
6129 if (!strcmp(optarg, "now")) {
6130 rtc_date_offset = -1;
6131 } else {
6132 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
6133 &tm.tm_year,
6134 &tm.tm_mon,
6135 &tm.tm_mday,
6136 &tm.tm_hour,
6137 &tm.tm_min,
6138 &tm.tm_sec) == 6) {
6139 /* OK */
6140 } else if (sscanf(optarg, "%d-%d-%d",
6141 &tm.tm_year,
6142 &tm.tm_mon,
6143 &tm.tm_mday) == 3) {
6144 tm.tm_hour = 0;
6145 tm.tm_min = 0;
6146 tm.tm_sec = 0;
6147 } else {
6148 goto date_fail;
6150 tm.tm_year -= 1900;
6151 tm.tm_mon--;
6152 rtc_start_date = mktimegm(&tm);
6153 if (rtc_start_date == -1) {
6154 date_fail:
6155 fprintf(stderr, "Invalid date format. Valid format are:\n"
6156 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
6157 exit(1);
6159 rtc_date_offset = time(NULL) - rtc_start_date;
6162 break;
6163 case QEMU_OPTION_tb_size:
6164 tb_size = strtol(optarg, NULL, 0);
6165 if (tb_size < 0)
6166 tb_size = 0;
6167 break;
6168 case QEMU_OPTION_icount:
6169 use_icount = 1;
6170 if (strcmp(optarg, "auto") == 0) {
6171 icount_time_shift = -1;
6172 } else {
6173 icount_time_shift = strtol(optarg, NULL, 0);
6175 break;
6176 case QEMU_OPTION_incoming:
6177 incoming = optarg;
6178 break;
6183 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
6184 if (kvm_allowed && kqemu_allowed) {
6185 fprintf(stderr,
6186 "You can not enable both KVM and kqemu at the same time\n");
6187 exit(1);
6189 #endif
6191 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
6192 if (smp_cpus > machine->max_cpus) {
6193 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
6194 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
6195 machine->max_cpus);
6196 exit(1);
6199 if (nographic) {
6200 if (serial_device_index == 0)
6201 serial_devices[0] = "stdio";
6202 if (parallel_device_index == 0)
6203 parallel_devices[0] = "null";
6204 if (strncmp(monitor_device, "vc", 2) == 0)
6205 monitor_device = "stdio";
6208 #ifndef _WIN32
6209 if (daemonize) {
6210 pid_t pid;
6212 if (pipe(fds) == -1)
6213 exit(1);
6215 pid = fork();
6216 if (pid > 0) {
6217 uint8_t status;
6218 ssize_t len;
6220 close(fds[1]);
6222 again:
6223 len = read(fds[0], &status, 1);
6224 if (len == -1 && (errno == EINTR))
6225 goto again;
6227 if (len != 1)
6228 exit(1);
6229 else if (status == 1) {
6230 fprintf(stderr, "Could not acquire pidfile\n");
6231 exit(1);
6232 } else
6233 exit(0);
6234 } else if (pid < 0)
6235 exit(1);
6237 setsid();
6239 pid = fork();
6240 if (pid > 0)
6241 exit(0);
6242 else if (pid < 0)
6243 exit(1);
6245 umask(027);
6247 signal(SIGTSTP, SIG_IGN);
6248 signal(SIGTTOU, SIG_IGN);
6249 signal(SIGTTIN, SIG_IGN);
6251 #endif
6253 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
6254 if (daemonize) {
6255 uint8_t status = 1;
6256 write(fds[1], &status, 1);
6257 } else
6258 fprintf(stderr, "Could not acquire pid file\n");
6259 exit(1);
6262 #ifdef USE_KQEMU
6263 if (smp_cpus > 1)
6264 kqemu_allowed = 0;
6265 #endif
6266 linux_boot = (kernel_filename != NULL);
6267 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6269 if (!linux_boot && net_boot == 0 &&
6270 !machine->nodisk_ok && nb_drives_opt == 0)
6271 help(1);
6273 if (!linux_boot && *kernel_cmdline != '\0') {
6274 fprintf(stderr, "-append only allowed with -kernel option\n");
6275 exit(1);
6278 if (!linux_boot && initrd_filename != NULL) {
6279 fprintf(stderr, "-initrd only allowed with -kernel option\n");
6280 exit(1);
6283 /* boot to floppy or the default cd if no hard disk defined yet */
6284 if (!boot_devices[0]) {
6285 boot_devices = "cad";
6287 setvbuf(stdout, NULL, _IOLBF, 0);
6289 init_timers();
6290 if (init_timer_alarm() < 0) {
6291 fprintf(stderr, "could not initialize alarm timer\n");
6292 exit(1);
6294 if (use_icount && icount_time_shift < 0) {
6295 use_icount = 2;
6296 /* 125MIPS seems a reasonable initial guess at the guest speed.
6297 It will be corrected fairly quickly anyway. */
6298 icount_time_shift = 3;
6299 init_icount_adjust();
6302 #ifdef _WIN32
6303 socket_init();
6304 #endif
6306 /* init network clients */
6307 if (nb_net_clients == 0) {
6308 /* if no clients, we use a default config */
6309 net_clients[nb_net_clients++] = "nic";
6310 #ifdef CONFIG_SLIRP
6311 net_clients[nb_net_clients++] = "user";
6312 #endif
6315 for(i = 0;i < nb_net_clients; i++) {
6316 if (net_client_parse(net_clients[i]) < 0)
6317 exit(1);
6319 net_client_check();
6321 #ifdef TARGET_I386
6322 /* XXX: this should be moved in the PC machine instantiation code */
6323 if (net_boot != 0) {
6324 int netroms = 0;
6325 for (i = 0; i < nb_nics && i < 4; i++) {
6326 const char *model = nd_table[i].model;
6327 char buf[1024];
6328 if (net_boot & (1 << i)) {
6329 if (model == NULL)
6330 model = "ne2k_pci";
6331 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
6332 if (get_image_size(buf) > 0) {
6333 if (nb_option_roms >= MAX_OPTION_ROMS) {
6334 fprintf(stderr, "Too many option ROMs\n");
6335 exit(1);
6337 option_rom[nb_option_roms] = strdup(buf);
6338 nb_option_roms++;
6339 netroms++;
6343 if (netroms == 0) {
6344 fprintf(stderr, "No valid PXE rom found for network device\n");
6345 exit(1);
6348 #endif
6350 /* init the bluetooth world */
6351 for (i = 0; i < nb_bt_opts; i++)
6352 if (bt_parse(bt_opts[i]))
6353 exit(1);
6355 /* init the memory */
6356 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
6358 if (machine->ram_require & RAMSIZE_FIXED) {
6359 if (ram_size > 0) {
6360 if (ram_size < phys_ram_size) {
6361 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
6362 machine->name, (unsigned long long) phys_ram_size);
6363 exit(-1);
6366 phys_ram_size = ram_size;
6367 } else
6368 ram_size = phys_ram_size;
6369 } else {
6370 if (ram_size == 0)
6371 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6373 phys_ram_size += ram_size;
6376 phys_ram_base = qemu_vmalloc(phys_ram_size);
6377 if (!phys_ram_base) {
6378 fprintf(stderr, "Could not allocate physical memory\n");
6379 exit(1);
6382 /* init the dynamic translator */
6383 cpu_exec_init_all(tb_size * 1024 * 1024);
6385 bdrv_init();
6387 /* we always create the cdrom drive, even if no disk is there */
6389 if (nb_drives_opt < MAX_DRIVES)
6390 drive_add(NULL, CDROM_ALIAS);
6392 /* we always create at least one floppy */
6394 if (nb_drives_opt < MAX_DRIVES)
6395 drive_add(NULL, FD_ALIAS, 0);
6397 /* we always create one sd slot, even if no card is in it */
6399 if (nb_drives_opt < MAX_DRIVES)
6400 drive_add(NULL, SD_ALIAS);
6402 /* open the virtual block devices */
6404 for(i = 0; i < nb_drives_opt; i++)
6405 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6406 exit(1);
6408 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6409 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6411 /* terminal init */
6412 memset(&display_state, 0, sizeof(display_state));
6413 if (nographic) {
6414 if (curses) {
6415 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
6416 exit(1);
6418 /* nearly nothing to do */
6419 dumb_display_init(ds);
6420 } else if (vnc_display != NULL) {
6421 vnc_display_init(ds);
6422 if (vnc_display_open(ds, vnc_display) < 0)
6423 exit(1);
6424 } else
6425 #if defined(CONFIG_CURSES)
6426 if (curses) {
6427 curses_display_init(ds, full_screen);
6428 } else
6429 #endif
6431 #if defined(CONFIG_SDL)
6432 sdl_display_init(ds, full_screen, no_frame);
6433 #elif defined(CONFIG_COCOA)
6434 cocoa_display_init(ds, full_screen);
6435 #else
6436 dumb_display_init(ds);
6437 #endif
6440 #ifndef _WIN32
6441 /* must be after terminal init, SDL library changes signal handlers */
6442 termsig_setup();
6443 #endif
6445 /* Maintain compatibility with multiple stdio monitors */
6446 if (!strcmp(monitor_device,"stdio")) {
6447 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6448 const char *devname = serial_devices[i];
6449 if (devname && !strcmp(devname,"mon:stdio")) {
6450 monitor_device = NULL;
6451 break;
6452 } else if (devname && !strcmp(devname,"stdio")) {
6453 monitor_device = NULL;
6454 serial_devices[i] = "mon:stdio";
6455 break;
6459 if (monitor_device) {
6460 monitor_hd = qemu_chr_open("monitor", monitor_device);
6461 if (!monitor_hd) {
6462 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6463 exit(1);
6465 monitor_init(monitor_hd, !nographic);
6468 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6469 const char *devname = serial_devices[i];
6470 if (devname && strcmp(devname, "none")) {
6471 char label[32];
6472 snprintf(label, sizeof(label), "serial%d", i);
6473 serial_hds[i] = qemu_chr_open(label, devname);
6474 if (!serial_hds[i]) {
6475 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6476 devname);
6477 exit(1);
6479 if (strstart(devname, "vc", 0))
6480 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6484 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6485 const char *devname = parallel_devices[i];
6486 if (devname && strcmp(devname, "none")) {
6487 char label[32];
6488 snprintf(label, sizeof(label), "parallel%d", i);
6489 parallel_hds[i] = qemu_chr_open(label, devname);
6490 if (!parallel_hds[i]) {
6491 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6492 devname);
6493 exit(1);
6495 if (strstart(devname, "vc", 0))
6496 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6500 if (kvm_enabled()) {
6501 int ret;
6503 ret = kvm_init(smp_cpus);
6504 if (ret < 0) {
6505 fprintf(stderr, "failed to initialize KVM\n");
6506 exit(1);
6510 machine->init(ram_size, vga_ram_size, boot_devices, ds,
6511 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6513 /* init USB devices */
6514 if (usb_enabled) {
6515 for(i = 0; i < usb_devices_index; i++) {
6516 if (usb_device_add(usb_devices[i]) < 0) {
6517 fprintf(stderr, "Warning: could not add USB device %s\n",
6518 usb_devices[i]);
6523 if (display_state.dpy_refresh) {
6524 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
6525 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
6528 #ifdef CONFIG_GDBSTUB
6529 if (use_gdbstub) {
6530 /* XXX: use standard host:port notation and modify options
6531 accordingly. */
6532 if (gdbserver_start(gdbstub_port) < 0) {
6533 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6534 gdbstub_port);
6535 exit(1);
6538 #endif
6540 if (loadvm)
6541 do_loadvm(loadvm);
6543 if (incoming) {
6544 autostart = 0; /* fixme how to deal with -daemonize */
6545 qemu_start_incoming_migration(incoming);
6549 /* XXX: simplify init */
6550 read_passwords();
6551 if (autostart) {
6552 vm_start();
6556 if (daemonize) {
6557 uint8_t status = 0;
6558 ssize_t len;
6559 int fd;
6561 again1:
6562 len = write(fds[1], &status, 1);
6563 if (len == -1 && (errno == EINTR))
6564 goto again1;
6566 if (len != 1)
6567 exit(1);
6569 chdir("/");
6570 TFR(fd = open("/dev/null", O_RDWR));
6571 if (fd == -1)
6572 exit(1);
6574 dup2(fd, 0);
6575 dup2(fd, 1);
6576 dup2(fd, 2);
6578 close(fd);
6581 main_loop();
6582 quit_timers();
6583 net_cleanup();
6585 return 0;