Set default audio timer period to a sane value (otherwise qemu becomes unusable if...
[qemu/mini2440.git] / vl.c
blobee93c73087641d61525b763eade5de9a931f2b24
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"
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <time.h>
47 #include <errno.h>
48 #include <sys/time.h>
49 #include <zlib.h>
51 #ifndef _WIN32
52 #include <sys/times.h>
53 #include <sys/wait.h>
54 #include <termios.h>
55 #include <sys/mman.h>
56 #include <sys/ioctl.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <dirent.h>
60 #include <netdb.h>
61 #include <sys/select.h>
62 #include <arpa/inet.h>
63 #ifdef _BSD
64 #include <sys/stat.h>
65 #if !defined(__APPLE__) && !defined(__OpenBSD__)
66 #include <libutil.h>
67 #endif
68 #ifdef __OpenBSD__
69 #include <net/if.h>
70 #endif
71 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
72 #include <freebsd/stdlib.h>
73 #else
74 #ifdef __linux__
75 #include <linux/if.h>
76 #include <linux/if_tun.h>
77 #include <pty.h>
78 #include <malloc.h>
79 #include <linux/rtc.h>
81 /* For the benefit of older linux systems which don't supply it,
82 we use a local copy of hpet.h. */
83 /* #include <linux/hpet.h> */
84 #include "hpet.h"
86 #include <linux/ppdev.h>
87 #include <linux/parport.h>
88 #endif
89 #ifdef __sun__
90 #include <sys/stat.h>
91 #include <sys/ethernet.h>
92 #include <sys/sockio.h>
93 #include <netinet/arp.h>
94 #include <netinet/in.h>
95 #include <netinet/in_systm.h>
96 #include <netinet/ip.h>
97 #include <netinet/ip_icmp.h> // must come after ip.h
98 #include <netinet/udp.h>
99 #include <netinet/tcp.h>
100 #include <net/if.h>
101 #include <syslog.h>
102 #include <stropts.h>
103 #endif
104 #endif
105 #endif
107 #include "qemu_socket.h"
109 #if defined(CONFIG_SLIRP)
110 #include "libslirp.h"
111 #endif
113 #if defined(__OpenBSD__)
114 #include <util.h>
115 #endif
117 #if defined(CONFIG_VDE)
118 #include <libvdeplug.h>
119 #endif
121 #ifdef _WIN32
122 #include <malloc.h>
123 #include <sys/timeb.h>
124 #include <mmsystem.h>
125 #define getopt_long_only getopt_long
126 #define memalign(align, size) malloc(size)
127 #endif
129 #ifdef CONFIG_SDL
130 #ifdef __APPLE__
131 #include <SDL/SDL.h>
132 #endif
133 #endif /* CONFIG_SDL */
135 #ifdef CONFIG_COCOA
136 #undef main
137 #define main qemu_main
138 #endif /* CONFIG_COCOA */
140 #include "disas.h"
142 #include "exec-all.h"
144 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
145 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
146 #ifdef __sun__
147 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
148 #else
149 #define SMBD_COMMAND "/usr/sbin/smbd"
150 #endif
152 //#define DEBUG_UNUSED_IOPORT
153 //#define DEBUG_IOPORT
154 //#define DEBUG_NET
155 //#define DEBUG_SLIRP
157 #ifdef TARGET_PPC
158 #define DEFAULT_RAM_SIZE 144
159 #else
160 #define DEFAULT_RAM_SIZE 128
161 #endif
163 /* Max number of USB devices that can be specified on the commandline. */
164 #define MAX_USB_CMDLINE 8
166 /* XXX: use a two level table to limit memory usage */
167 #define MAX_IOPORTS 65536
169 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
170 const char *bios_name = NULL;
171 static void *ioport_opaque[MAX_IOPORTS];
172 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
173 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
174 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
175 to store the VM snapshots */
176 DriveInfo drives_table[MAX_DRIVES+1];
177 int nb_drives;
178 /* point to the block driver where the snapshots are managed */
179 static BlockDriverState *bs_snapshots;
180 static int vga_ram_size;
181 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
182 DisplayState display_state;
183 int nographic;
184 static int curses;
185 const char* keyboard_layout = NULL;
186 int64_t ticks_per_sec;
187 ram_addr_t ram_size;
188 int nb_nics;
189 NICInfo nd_table[MAX_NICS];
190 int vm_running;
191 static int rtc_utc = 1;
192 static int rtc_date_offset = -1; /* -1 means no change */
193 int cirrus_vga_enabled = 1;
194 int vmsvga_enabled = 0;
195 #ifdef TARGET_SPARC
196 int graphic_width = 1024;
197 int graphic_height = 768;
198 int graphic_depth = 8;
199 #else
200 int graphic_width = 800;
201 int graphic_height = 600;
202 int graphic_depth = 15;
203 #endif
204 static int full_screen = 0;
205 static int no_frame = 0;
206 int no_quit = 0;
207 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
208 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
209 #ifdef TARGET_I386
210 int win2k_install_hack = 0;
211 #endif
212 int usb_enabled = 0;
213 int smp_cpus = 1;
214 const char *vnc_display;
215 int acpi_enabled = 1;
216 int fd_bootchk = 1;
217 int no_reboot = 0;
218 int no_shutdown = 0;
219 int cursor_hide = 1;
220 int graphic_rotate = 0;
221 int daemonize = 0;
222 const char *option_rom[MAX_OPTION_ROMS];
223 int nb_option_roms;
224 int semihosting_enabled = 0;
225 #ifdef TARGET_ARM
226 int old_param = 0;
227 #endif
228 const char *qemu_name;
229 int alt_grab = 0;
230 #ifdef TARGET_SPARC
231 unsigned int nb_prom_envs = 0;
232 const char *prom_envs[MAX_PROM_ENVS];
233 #endif
234 static int nb_drives_opt;
235 static struct drive_opt {
236 const char *file;
237 char opt[1024];
238 } drives_opt[MAX_DRIVES];
240 static CPUState *cur_cpu;
241 static CPUState *next_cpu;
242 static int event_pending = 1;
243 /* Conversion factor from emulated instructions to virtual clock ticks. */
244 static int icount_time_shift;
245 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
246 #define MAX_ICOUNT_SHIFT 10
247 /* Compensate for varying guest execution speed. */
248 static int64_t qemu_icount_bias;
249 static QEMUTimer *icount_rt_timer;
250 static QEMUTimer *icount_vm_timer;
252 uint8_t qemu_uuid[16];
254 /***********************************************************/
255 /* x86 ISA bus support */
257 target_phys_addr_t isa_mem_base = 0;
258 PicState2 *isa_pic;
260 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
261 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
263 static uint32_t ioport_read(int index, uint32_t address)
265 static IOPortReadFunc *default_func[3] = {
266 default_ioport_readb,
267 default_ioport_readw,
268 default_ioport_readl
270 IOPortReadFunc *func = ioport_read_table[index][address];
271 if (!func)
272 func = default_func[index];
273 return func(ioport_opaque[address], address);
276 static void ioport_write(int index, uint32_t address, uint32_t data)
278 static IOPortWriteFunc *default_func[3] = {
279 default_ioport_writeb,
280 default_ioport_writew,
281 default_ioport_writel
283 IOPortWriteFunc *func = ioport_write_table[index][address];
284 if (!func)
285 func = default_func[index];
286 func(ioport_opaque[address], address, data);
289 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
291 #ifdef DEBUG_UNUSED_IOPORT
292 fprintf(stderr, "unused inb: port=0x%04x\n", address);
293 #endif
294 return 0xff;
297 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
299 #ifdef DEBUG_UNUSED_IOPORT
300 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
301 #endif
304 /* default is to make two byte accesses */
305 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
307 uint32_t data;
308 data = ioport_read(0, address);
309 address = (address + 1) & (MAX_IOPORTS - 1);
310 data |= ioport_read(0, address) << 8;
311 return data;
314 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
316 ioport_write(0, address, data & 0xff);
317 address = (address + 1) & (MAX_IOPORTS - 1);
318 ioport_write(0, address, (data >> 8) & 0xff);
321 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
323 #ifdef DEBUG_UNUSED_IOPORT
324 fprintf(stderr, "unused inl: port=0x%04x\n", address);
325 #endif
326 return 0xffffffff;
329 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
331 #ifdef DEBUG_UNUSED_IOPORT
332 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
333 #endif
336 /* size is the word size in byte */
337 int register_ioport_read(int start, int length, int size,
338 IOPortReadFunc *func, void *opaque)
340 int i, bsize;
342 if (size == 1) {
343 bsize = 0;
344 } else if (size == 2) {
345 bsize = 1;
346 } else if (size == 4) {
347 bsize = 2;
348 } else {
349 hw_error("register_ioport_read: invalid size");
350 return -1;
352 for(i = start; i < start + length; i += size) {
353 ioport_read_table[bsize][i] = func;
354 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
355 hw_error("register_ioport_read: invalid opaque");
356 ioport_opaque[i] = opaque;
358 return 0;
361 /* size is the word size in byte */
362 int register_ioport_write(int start, int length, int size,
363 IOPortWriteFunc *func, void *opaque)
365 int i, bsize;
367 if (size == 1) {
368 bsize = 0;
369 } else if (size == 2) {
370 bsize = 1;
371 } else if (size == 4) {
372 bsize = 2;
373 } else {
374 hw_error("register_ioport_write: invalid size");
375 return -1;
377 for(i = start; i < start + length; i += size) {
378 ioport_write_table[bsize][i] = func;
379 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
380 hw_error("register_ioport_write: invalid opaque");
381 ioport_opaque[i] = opaque;
383 return 0;
386 void isa_unassign_ioport(int start, int length)
388 int i;
390 for(i = start; i < start + length; i++) {
391 ioport_read_table[0][i] = default_ioport_readb;
392 ioport_read_table[1][i] = default_ioport_readw;
393 ioport_read_table[2][i] = default_ioport_readl;
395 ioport_write_table[0][i] = default_ioport_writeb;
396 ioport_write_table[1][i] = default_ioport_writew;
397 ioport_write_table[2][i] = default_ioport_writel;
401 /***********************************************************/
403 void cpu_outb(CPUState *env, int addr, int val)
405 #ifdef DEBUG_IOPORT
406 if (loglevel & CPU_LOG_IOPORT)
407 fprintf(logfile, "outb: %04x %02x\n", addr, val);
408 #endif
409 ioport_write(0, addr, val);
410 #ifdef USE_KQEMU
411 if (env)
412 env->last_io_time = cpu_get_time_fast();
413 #endif
416 void cpu_outw(CPUState *env, int addr, int val)
418 #ifdef DEBUG_IOPORT
419 if (loglevel & CPU_LOG_IOPORT)
420 fprintf(logfile, "outw: %04x %04x\n", addr, val);
421 #endif
422 ioport_write(1, addr, val);
423 #ifdef USE_KQEMU
424 if (env)
425 env->last_io_time = cpu_get_time_fast();
426 #endif
429 void cpu_outl(CPUState *env, int addr, int val)
431 #ifdef DEBUG_IOPORT
432 if (loglevel & CPU_LOG_IOPORT)
433 fprintf(logfile, "outl: %04x %08x\n", addr, val);
434 #endif
435 ioport_write(2, addr, val);
436 #ifdef USE_KQEMU
437 if (env)
438 env->last_io_time = cpu_get_time_fast();
439 #endif
442 int cpu_inb(CPUState *env, int addr)
444 int val;
445 val = ioport_read(0, addr);
446 #ifdef DEBUG_IOPORT
447 if (loglevel & CPU_LOG_IOPORT)
448 fprintf(logfile, "inb : %04x %02x\n", addr, val);
449 #endif
450 #ifdef USE_KQEMU
451 if (env)
452 env->last_io_time = cpu_get_time_fast();
453 #endif
454 return val;
457 int cpu_inw(CPUState *env, int addr)
459 int val;
460 val = ioport_read(1, addr);
461 #ifdef DEBUG_IOPORT
462 if (loglevel & CPU_LOG_IOPORT)
463 fprintf(logfile, "inw : %04x %04x\n", addr, val);
464 #endif
465 #ifdef USE_KQEMU
466 if (env)
467 env->last_io_time = cpu_get_time_fast();
468 #endif
469 return val;
472 int cpu_inl(CPUState *env, int addr)
474 int val;
475 val = ioport_read(2, addr);
476 #ifdef DEBUG_IOPORT
477 if (loglevel & CPU_LOG_IOPORT)
478 fprintf(logfile, "inl : %04x %08x\n", addr, val);
479 #endif
480 #ifdef USE_KQEMU
481 if (env)
482 env->last_io_time = cpu_get_time_fast();
483 #endif
484 return val;
487 /***********************************************************/
488 void hw_error(const char *fmt, ...)
490 va_list ap;
491 CPUState *env;
493 va_start(ap, fmt);
494 fprintf(stderr, "qemu: hardware error: ");
495 vfprintf(stderr, fmt, ap);
496 fprintf(stderr, "\n");
497 for(env = first_cpu; env != NULL; env = env->next_cpu) {
498 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
499 #ifdef TARGET_I386
500 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
501 #else
502 cpu_dump_state(env, stderr, fprintf, 0);
503 #endif
505 va_end(ap);
506 abort();
509 /***********************************************************/
510 /* keyboard/mouse */
512 static QEMUPutKBDEvent *qemu_put_kbd_event;
513 static void *qemu_put_kbd_event_opaque;
514 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
515 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
517 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
519 qemu_put_kbd_event_opaque = opaque;
520 qemu_put_kbd_event = func;
523 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
524 void *opaque, int absolute,
525 const char *name)
527 QEMUPutMouseEntry *s, *cursor;
529 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
530 if (!s)
531 return NULL;
533 s->qemu_put_mouse_event = func;
534 s->qemu_put_mouse_event_opaque = opaque;
535 s->qemu_put_mouse_event_absolute = absolute;
536 s->qemu_put_mouse_event_name = qemu_strdup(name);
537 s->next = NULL;
539 if (!qemu_put_mouse_event_head) {
540 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
541 return s;
544 cursor = qemu_put_mouse_event_head;
545 while (cursor->next != NULL)
546 cursor = cursor->next;
548 cursor->next = s;
549 qemu_put_mouse_event_current = s;
551 return s;
554 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
556 QEMUPutMouseEntry *prev = NULL, *cursor;
558 if (!qemu_put_mouse_event_head || entry == NULL)
559 return;
561 cursor = qemu_put_mouse_event_head;
562 while (cursor != NULL && cursor != entry) {
563 prev = cursor;
564 cursor = cursor->next;
567 if (cursor == NULL) // does not exist or list empty
568 return;
569 else if (prev == NULL) { // entry is head
570 qemu_put_mouse_event_head = cursor->next;
571 if (qemu_put_mouse_event_current == entry)
572 qemu_put_mouse_event_current = cursor->next;
573 qemu_free(entry->qemu_put_mouse_event_name);
574 qemu_free(entry);
575 return;
578 prev->next = entry->next;
580 if (qemu_put_mouse_event_current == entry)
581 qemu_put_mouse_event_current = prev;
583 qemu_free(entry->qemu_put_mouse_event_name);
584 qemu_free(entry);
587 void kbd_put_keycode(int keycode)
589 if (qemu_put_kbd_event) {
590 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
594 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
596 QEMUPutMouseEvent *mouse_event;
597 void *mouse_event_opaque;
598 int width;
600 if (!qemu_put_mouse_event_current) {
601 return;
604 mouse_event =
605 qemu_put_mouse_event_current->qemu_put_mouse_event;
606 mouse_event_opaque =
607 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
609 if (mouse_event) {
610 if (graphic_rotate) {
611 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
612 width = 0x7fff;
613 else
614 width = graphic_width - 1;
615 mouse_event(mouse_event_opaque,
616 width - dy, dx, dz, buttons_state);
617 } else
618 mouse_event(mouse_event_opaque,
619 dx, dy, dz, buttons_state);
623 int kbd_mouse_is_absolute(void)
625 if (!qemu_put_mouse_event_current)
626 return 0;
628 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
631 void do_info_mice(void)
633 QEMUPutMouseEntry *cursor;
634 int index = 0;
636 if (!qemu_put_mouse_event_head) {
637 term_printf("No mouse devices connected\n");
638 return;
641 term_printf("Mouse devices available:\n");
642 cursor = qemu_put_mouse_event_head;
643 while (cursor != NULL) {
644 term_printf("%c Mouse #%d: %s\n",
645 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
646 index, cursor->qemu_put_mouse_event_name);
647 index++;
648 cursor = cursor->next;
652 void do_mouse_set(int index)
654 QEMUPutMouseEntry *cursor;
655 int i = 0;
657 if (!qemu_put_mouse_event_head) {
658 term_printf("No mouse devices connected\n");
659 return;
662 cursor = qemu_put_mouse_event_head;
663 while (cursor != NULL && index != i) {
664 i++;
665 cursor = cursor->next;
668 if (cursor != NULL)
669 qemu_put_mouse_event_current = cursor;
670 else
671 term_printf("Mouse at given index not found\n");
674 /* compute with 96 bit intermediate result: (a*b)/c */
675 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
677 union {
678 uint64_t ll;
679 struct {
680 #ifdef WORDS_BIGENDIAN
681 uint32_t high, low;
682 #else
683 uint32_t low, high;
684 #endif
685 } l;
686 } u, res;
687 uint64_t rl, rh;
689 u.ll = a;
690 rl = (uint64_t)u.l.low * (uint64_t)b;
691 rh = (uint64_t)u.l.high * (uint64_t)b;
692 rh += (rl >> 32);
693 res.l.high = rh / c;
694 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
695 return res.ll;
698 /***********************************************************/
699 /* real time host monotonic timer */
701 #define QEMU_TIMER_BASE 1000000000LL
703 #ifdef WIN32
705 static int64_t clock_freq;
707 static void init_get_clock(void)
709 LARGE_INTEGER freq;
710 int ret;
711 ret = QueryPerformanceFrequency(&freq);
712 if (ret == 0) {
713 fprintf(stderr, "Could not calibrate ticks\n");
714 exit(1);
716 clock_freq = freq.QuadPart;
719 static int64_t get_clock(void)
721 LARGE_INTEGER ti;
722 QueryPerformanceCounter(&ti);
723 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
726 #else
728 static int use_rt_clock;
730 static void init_get_clock(void)
732 use_rt_clock = 0;
733 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
735 struct timespec ts;
736 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
737 use_rt_clock = 1;
740 #endif
743 static int64_t get_clock(void)
745 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
746 if (use_rt_clock) {
747 struct timespec ts;
748 clock_gettime(CLOCK_MONOTONIC, &ts);
749 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
750 } else
751 #endif
753 /* XXX: using gettimeofday leads to problems if the date
754 changes, so it should be avoided. */
755 struct timeval tv;
756 gettimeofday(&tv, NULL);
757 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
760 #endif
762 /* Return the virtual CPU time, based on the instruction counter. */
763 static int64_t cpu_get_icount(void)
765 int64_t icount;
766 CPUState *env = cpu_single_env;;
767 icount = qemu_icount;
768 if (env) {
769 if (!can_do_io(env))
770 fprintf(stderr, "Bad clock read\n");
771 icount -= (env->icount_decr.u16.low + env->icount_extra);
773 return qemu_icount_bias + (icount << icount_time_shift);
776 /***********************************************************/
777 /* guest cycle counter */
779 static int64_t cpu_ticks_prev;
780 static int64_t cpu_ticks_offset;
781 static int64_t cpu_clock_offset;
782 static int cpu_ticks_enabled;
784 /* return the host CPU cycle counter and handle stop/restart */
785 int64_t cpu_get_ticks(void)
787 if (use_icount) {
788 return cpu_get_icount();
790 if (!cpu_ticks_enabled) {
791 return cpu_ticks_offset;
792 } else {
793 int64_t ticks;
794 ticks = cpu_get_real_ticks();
795 if (cpu_ticks_prev > ticks) {
796 /* Note: non increasing ticks may happen if the host uses
797 software suspend */
798 cpu_ticks_offset += cpu_ticks_prev - ticks;
800 cpu_ticks_prev = ticks;
801 return ticks + cpu_ticks_offset;
805 /* return the host CPU monotonic timer and handle stop/restart */
806 static int64_t cpu_get_clock(void)
808 int64_t ti;
809 if (!cpu_ticks_enabled) {
810 return cpu_clock_offset;
811 } else {
812 ti = get_clock();
813 return ti + cpu_clock_offset;
817 /* enable cpu_get_ticks() */
818 void cpu_enable_ticks(void)
820 if (!cpu_ticks_enabled) {
821 cpu_ticks_offset -= cpu_get_real_ticks();
822 cpu_clock_offset -= get_clock();
823 cpu_ticks_enabled = 1;
827 /* disable cpu_get_ticks() : the clock is stopped. You must not call
828 cpu_get_ticks() after that. */
829 void cpu_disable_ticks(void)
831 if (cpu_ticks_enabled) {
832 cpu_ticks_offset = cpu_get_ticks();
833 cpu_clock_offset = cpu_get_clock();
834 cpu_ticks_enabled = 0;
838 /***********************************************************/
839 /* timers */
841 #define QEMU_TIMER_REALTIME 0
842 #define QEMU_TIMER_VIRTUAL 1
844 struct QEMUClock {
845 int type;
846 /* XXX: add frequency */
849 struct QEMUTimer {
850 QEMUClock *clock;
851 int64_t expire_time;
852 QEMUTimerCB *cb;
853 void *opaque;
854 struct QEMUTimer *next;
857 struct qemu_alarm_timer {
858 char const *name;
859 unsigned int flags;
861 int (*start)(struct qemu_alarm_timer *t);
862 void (*stop)(struct qemu_alarm_timer *t);
863 void (*rearm)(struct qemu_alarm_timer *t);
864 void *priv;
867 #define ALARM_FLAG_DYNTICKS 0x1
868 #define ALARM_FLAG_EXPIRED 0x2
870 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
872 return t->flags & ALARM_FLAG_DYNTICKS;
875 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
877 if (!alarm_has_dynticks(t))
878 return;
880 t->rearm(t);
883 /* TODO: MIN_TIMER_REARM_US should be optimized */
884 #define MIN_TIMER_REARM_US 250
886 static struct qemu_alarm_timer *alarm_timer;
888 #ifdef _WIN32
890 struct qemu_alarm_win32 {
891 MMRESULT timerId;
892 HANDLE host_alarm;
893 unsigned int period;
894 } alarm_win32_data = {0, NULL, -1};
896 static int win32_start_timer(struct qemu_alarm_timer *t);
897 static void win32_stop_timer(struct qemu_alarm_timer *t);
898 static void win32_rearm_timer(struct qemu_alarm_timer *t);
900 #else
902 static int unix_start_timer(struct qemu_alarm_timer *t);
903 static void unix_stop_timer(struct qemu_alarm_timer *t);
905 #ifdef __linux__
907 static int dynticks_start_timer(struct qemu_alarm_timer *t);
908 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
909 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
911 static int hpet_start_timer(struct qemu_alarm_timer *t);
912 static void hpet_stop_timer(struct qemu_alarm_timer *t);
914 static int rtc_start_timer(struct qemu_alarm_timer *t);
915 static void rtc_stop_timer(struct qemu_alarm_timer *t);
917 #endif /* __linux__ */
919 #endif /* _WIN32 */
921 /* Correlation between real and virtual time is always going to be
922 fairly approximate, so ignore small variation.
923 When the guest is idle real and virtual time will be aligned in
924 the IO wait loop. */
925 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
927 static void icount_adjust(void)
929 int64_t cur_time;
930 int64_t cur_icount;
931 int64_t delta;
932 static int64_t last_delta;
933 /* If the VM is not running, then do nothing. */
934 if (!vm_running)
935 return;
937 cur_time = cpu_get_clock();
938 cur_icount = qemu_get_clock(vm_clock);
939 delta = cur_icount - cur_time;
940 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
941 if (delta > 0
942 && last_delta + ICOUNT_WOBBLE < delta * 2
943 && icount_time_shift > 0) {
944 /* The guest is getting too far ahead. Slow time down. */
945 icount_time_shift--;
947 if (delta < 0
948 && last_delta - ICOUNT_WOBBLE > delta * 2
949 && icount_time_shift < MAX_ICOUNT_SHIFT) {
950 /* The guest is getting too far behind. Speed time up. */
951 icount_time_shift++;
953 last_delta = delta;
954 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
957 static void icount_adjust_rt(void * opaque)
959 qemu_mod_timer(icount_rt_timer,
960 qemu_get_clock(rt_clock) + 1000);
961 icount_adjust();
964 static void icount_adjust_vm(void * opaque)
966 qemu_mod_timer(icount_vm_timer,
967 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
968 icount_adjust();
971 static void init_icount_adjust(void)
973 /* Have both realtime and virtual time triggers for speed adjustment.
974 The realtime trigger catches emulated time passing too slowly,
975 the virtual time trigger catches emulated time passing too fast.
976 Realtime triggers occur even when idle, so use them less frequently
977 than VM triggers. */
978 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
979 qemu_mod_timer(icount_rt_timer,
980 qemu_get_clock(rt_clock) + 1000);
981 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
982 qemu_mod_timer(icount_vm_timer,
983 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
986 static struct qemu_alarm_timer alarm_timers[] = {
987 #ifndef _WIN32
988 #ifdef __linux__
989 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
990 dynticks_stop_timer, dynticks_rearm_timer, NULL},
991 /* HPET - if available - is preferred */
992 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
993 /* ...otherwise try RTC */
994 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
995 #endif
996 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
997 #else
998 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
999 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1000 {"win32", 0, win32_start_timer,
1001 win32_stop_timer, NULL, &alarm_win32_data},
1002 #endif
1003 {NULL, }
1006 static void show_available_alarms(void)
1008 int i;
1010 printf("Available alarm timers, in order of precedence:\n");
1011 for (i = 0; alarm_timers[i].name; i++)
1012 printf("%s\n", alarm_timers[i].name);
1015 static void configure_alarms(char const *opt)
1017 int i;
1018 int cur = 0;
1019 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1020 char *arg;
1021 char *name;
1022 struct qemu_alarm_timer tmp;
1024 if (!strcmp(opt, "?")) {
1025 show_available_alarms();
1026 exit(0);
1029 arg = strdup(opt);
1031 /* Reorder the array */
1032 name = strtok(arg, ",");
1033 while (name) {
1034 for (i = 0; i < count && alarm_timers[i].name; i++) {
1035 if (!strcmp(alarm_timers[i].name, name))
1036 break;
1039 if (i == count) {
1040 fprintf(stderr, "Unknown clock %s\n", name);
1041 goto next;
1044 if (i < cur)
1045 /* Ignore */
1046 goto next;
1048 /* Swap */
1049 tmp = alarm_timers[i];
1050 alarm_timers[i] = alarm_timers[cur];
1051 alarm_timers[cur] = tmp;
1053 cur++;
1054 next:
1055 name = strtok(NULL, ",");
1058 free(arg);
1060 if (cur) {
1061 /* Disable remaining timers */
1062 for (i = cur; i < count; i++)
1063 alarm_timers[i].name = NULL;
1064 } else {
1065 show_available_alarms();
1066 exit(1);
1070 QEMUClock *rt_clock;
1071 QEMUClock *vm_clock;
1073 static QEMUTimer *active_timers[2];
1075 static QEMUClock *qemu_new_clock(int type)
1077 QEMUClock *clock;
1078 clock = qemu_mallocz(sizeof(QEMUClock));
1079 if (!clock)
1080 return NULL;
1081 clock->type = type;
1082 return clock;
1085 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1087 QEMUTimer *ts;
1089 ts = qemu_mallocz(sizeof(QEMUTimer));
1090 ts->clock = clock;
1091 ts->cb = cb;
1092 ts->opaque = opaque;
1093 return ts;
1096 void qemu_free_timer(QEMUTimer *ts)
1098 qemu_free(ts);
1101 /* stop a timer, but do not dealloc it */
1102 void qemu_del_timer(QEMUTimer *ts)
1104 QEMUTimer **pt, *t;
1106 /* NOTE: this code must be signal safe because
1107 qemu_timer_expired() can be called from a signal. */
1108 pt = &active_timers[ts->clock->type];
1109 for(;;) {
1110 t = *pt;
1111 if (!t)
1112 break;
1113 if (t == ts) {
1114 *pt = t->next;
1115 break;
1117 pt = &t->next;
1121 /* modify the current timer so that it will be fired when current_time
1122 >= expire_time. The corresponding callback will be called. */
1123 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1125 QEMUTimer **pt, *t;
1127 qemu_del_timer(ts);
1129 /* add the timer in the sorted list */
1130 /* NOTE: this code must be signal safe because
1131 qemu_timer_expired() can be called from a signal. */
1132 pt = &active_timers[ts->clock->type];
1133 for(;;) {
1134 t = *pt;
1135 if (!t)
1136 break;
1137 if (t->expire_time > expire_time)
1138 break;
1139 pt = &t->next;
1141 ts->expire_time = expire_time;
1142 ts->next = *pt;
1143 *pt = ts;
1145 /* Rearm if necessary */
1146 if (pt == &active_timers[ts->clock->type]) {
1147 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1148 qemu_rearm_alarm_timer(alarm_timer);
1150 /* Interrupt execution to force deadline recalculation. */
1151 if (use_icount && cpu_single_env) {
1152 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1157 int qemu_timer_pending(QEMUTimer *ts)
1159 QEMUTimer *t;
1160 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1161 if (t == ts)
1162 return 1;
1164 return 0;
1167 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1169 if (!timer_head)
1170 return 0;
1171 return (timer_head->expire_time <= current_time);
1174 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1176 QEMUTimer *ts;
1178 for(;;) {
1179 ts = *ptimer_head;
1180 if (!ts || ts->expire_time > current_time)
1181 break;
1182 /* remove timer from the list before calling the callback */
1183 *ptimer_head = ts->next;
1184 ts->next = NULL;
1186 /* run the callback (the timer list can be modified) */
1187 ts->cb(ts->opaque);
1191 int64_t qemu_get_clock(QEMUClock *clock)
1193 switch(clock->type) {
1194 case QEMU_TIMER_REALTIME:
1195 return get_clock() / 1000000;
1196 default:
1197 case QEMU_TIMER_VIRTUAL:
1198 if (use_icount) {
1199 return cpu_get_icount();
1200 } else {
1201 return cpu_get_clock();
1206 static void init_timers(void)
1208 init_get_clock();
1209 ticks_per_sec = QEMU_TIMER_BASE;
1210 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1211 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1214 /* save a timer */
1215 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1217 uint64_t expire_time;
1219 if (qemu_timer_pending(ts)) {
1220 expire_time = ts->expire_time;
1221 } else {
1222 expire_time = -1;
1224 qemu_put_be64(f, expire_time);
1227 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1229 uint64_t expire_time;
1231 expire_time = qemu_get_be64(f);
1232 if (expire_time != -1) {
1233 qemu_mod_timer(ts, expire_time);
1234 } else {
1235 qemu_del_timer(ts);
1239 static void timer_save(QEMUFile *f, void *opaque)
1241 if (cpu_ticks_enabled) {
1242 hw_error("cannot save state if virtual timers are running");
1244 qemu_put_be64(f, cpu_ticks_offset);
1245 qemu_put_be64(f, ticks_per_sec);
1246 qemu_put_be64(f, cpu_clock_offset);
1249 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1251 if (version_id != 1 && version_id != 2)
1252 return -EINVAL;
1253 if (cpu_ticks_enabled) {
1254 return -EINVAL;
1256 cpu_ticks_offset=qemu_get_be64(f);
1257 ticks_per_sec=qemu_get_be64(f);
1258 if (version_id == 2) {
1259 cpu_clock_offset=qemu_get_be64(f);
1261 return 0;
1264 #ifdef _WIN32
1265 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1266 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1267 #else
1268 static void host_alarm_handler(int host_signum)
1269 #endif
1271 #if 0
1272 #define DISP_FREQ 1000
1274 static int64_t delta_min = INT64_MAX;
1275 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1276 static int count;
1277 ti = qemu_get_clock(vm_clock);
1278 if (last_clock != 0) {
1279 delta = ti - last_clock;
1280 if (delta < delta_min)
1281 delta_min = delta;
1282 if (delta > delta_max)
1283 delta_max = delta;
1284 delta_cum += delta;
1285 if (++count == DISP_FREQ) {
1286 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1287 muldiv64(delta_min, 1000000, ticks_per_sec),
1288 muldiv64(delta_max, 1000000, ticks_per_sec),
1289 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1290 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1291 count = 0;
1292 delta_min = INT64_MAX;
1293 delta_max = 0;
1294 delta_cum = 0;
1297 last_clock = ti;
1299 #endif
1300 if (alarm_has_dynticks(alarm_timer) ||
1301 (!use_icount &&
1302 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1303 qemu_get_clock(vm_clock))) ||
1304 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1305 qemu_get_clock(rt_clock))) {
1306 #ifdef _WIN32
1307 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1308 SetEvent(data->host_alarm);
1309 #endif
1310 CPUState *env = next_cpu;
1312 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1314 if (env) {
1315 /* stop the currently executing cpu because a timer occured */
1316 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1317 #ifdef USE_KQEMU
1318 if (env->kqemu_enabled) {
1319 kqemu_cpu_interrupt(env);
1321 #endif
1323 event_pending = 1;
1327 static int64_t qemu_next_deadline(void)
1329 int64_t delta;
1331 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1332 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1333 qemu_get_clock(vm_clock);
1334 } else {
1335 /* To avoid problems with overflow limit this to 2^32. */
1336 delta = INT32_MAX;
1339 if (delta < 0)
1340 delta = 0;
1342 return delta;
1345 #if defined(__linux__) || defined(_WIN32)
1346 static uint64_t qemu_next_deadline_dyntick(void)
1348 int64_t delta;
1349 int64_t rtdelta;
1351 if (use_icount)
1352 delta = INT32_MAX;
1353 else
1354 delta = (qemu_next_deadline() + 999) / 1000;
1356 if (active_timers[QEMU_TIMER_REALTIME]) {
1357 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1358 qemu_get_clock(rt_clock))*1000;
1359 if (rtdelta < delta)
1360 delta = rtdelta;
1363 if (delta < MIN_TIMER_REARM_US)
1364 delta = MIN_TIMER_REARM_US;
1366 return delta;
1368 #endif
1370 #ifndef _WIN32
1372 #if defined(__linux__)
1374 #define RTC_FREQ 1024
1376 static void enable_sigio_timer(int fd)
1378 struct sigaction act;
1380 /* timer signal */
1381 sigfillset(&act.sa_mask);
1382 act.sa_flags = 0;
1383 act.sa_handler = host_alarm_handler;
1385 sigaction(SIGIO, &act, NULL);
1386 fcntl(fd, F_SETFL, O_ASYNC);
1387 fcntl(fd, F_SETOWN, getpid());
1390 static int hpet_start_timer(struct qemu_alarm_timer *t)
1392 struct hpet_info info;
1393 int r, fd;
1395 fd = open("/dev/hpet", O_RDONLY);
1396 if (fd < 0)
1397 return -1;
1399 /* Set frequency */
1400 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1401 if (r < 0) {
1402 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1403 "error, but for better emulation accuracy type:\n"
1404 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1405 goto fail;
1408 /* Check capabilities */
1409 r = ioctl(fd, HPET_INFO, &info);
1410 if (r < 0)
1411 goto fail;
1413 /* Enable periodic mode */
1414 r = ioctl(fd, HPET_EPI, 0);
1415 if (info.hi_flags && (r < 0))
1416 goto fail;
1418 /* Enable interrupt */
1419 r = ioctl(fd, HPET_IE_ON, 0);
1420 if (r < 0)
1421 goto fail;
1423 enable_sigio_timer(fd);
1424 t->priv = (void *)(long)fd;
1426 return 0;
1427 fail:
1428 close(fd);
1429 return -1;
1432 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1434 int fd = (long)t->priv;
1436 close(fd);
1439 static int rtc_start_timer(struct qemu_alarm_timer *t)
1441 int rtc_fd;
1442 unsigned long current_rtc_freq = 0;
1444 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1445 if (rtc_fd < 0)
1446 return -1;
1447 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1448 if (current_rtc_freq != RTC_FREQ &&
1449 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1450 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1451 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1452 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1453 goto fail;
1455 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1456 fail:
1457 close(rtc_fd);
1458 return -1;
1461 enable_sigio_timer(rtc_fd);
1463 t->priv = (void *)(long)rtc_fd;
1465 return 0;
1468 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1470 int rtc_fd = (long)t->priv;
1472 close(rtc_fd);
1475 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1477 struct sigevent ev;
1478 timer_t host_timer;
1479 struct sigaction act;
1481 sigfillset(&act.sa_mask);
1482 act.sa_flags = 0;
1483 act.sa_handler = host_alarm_handler;
1485 sigaction(SIGALRM, &act, NULL);
1487 ev.sigev_value.sival_int = 0;
1488 ev.sigev_notify = SIGEV_SIGNAL;
1489 ev.sigev_signo = SIGALRM;
1491 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1492 perror("timer_create");
1494 /* disable dynticks */
1495 fprintf(stderr, "Dynamic Ticks disabled\n");
1497 return -1;
1500 t->priv = (void *)host_timer;
1502 return 0;
1505 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1507 timer_t host_timer = (timer_t)t->priv;
1509 timer_delete(host_timer);
1512 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1514 timer_t host_timer = (timer_t)t->priv;
1515 struct itimerspec timeout;
1516 int64_t nearest_delta_us = INT64_MAX;
1517 int64_t current_us;
1519 if (!active_timers[QEMU_TIMER_REALTIME] &&
1520 !active_timers[QEMU_TIMER_VIRTUAL])
1521 return;
1523 nearest_delta_us = qemu_next_deadline_dyntick();
1525 /* check whether a timer is already running */
1526 if (timer_gettime(host_timer, &timeout)) {
1527 perror("gettime");
1528 fprintf(stderr, "Internal timer error: aborting\n");
1529 exit(1);
1531 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1532 if (current_us && current_us <= nearest_delta_us)
1533 return;
1535 timeout.it_interval.tv_sec = 0;
1536 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1537 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1538 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1539 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1540 perror("settime");
1541 fprintf(stderr, "Internal timer error: aborting\n");
1542 exit(1);
1546 #endif /* defined(__linux__) */
1548 static int unix_start_timer(struct qemu_alarm_timer *t)
1550 struct sigaction act;
1551 struct itimerval itv;
1552 int err;
1554 /* timer signal */
1555 sigfillset(&act.sa_mask);
1556 act.sa_flags = 0;
1557 act.sa_handler = host_alarm_handler;
1559 sigaction(SIGALRM, &act, NULL);
1561 itv.it_interval.tv_sec = 0;
1562 /* for i386 kernel 2.6 to get 1 ms */
1563 itv.it_interval.tv_usec = 999;
1564 itv.it_value.tv_sec = 0;
1565 itv.it_value.tv_usec = 10 * 1000;
1567 err = setitimer(ITIMER_REAL, &itv, NULL);
1568 if (err)
1569 return -1;
1571 return 0;
1574 static void unix_stop_timer(struct qemu_alarm_timer *t)
1576 struct itimerval itv;
1578 memset(&itv, 0, sizeof(itv));
1579 setitimer(ITIMER_REAL, &itv, NULL);
1582 #endif /* !defined(_WIN32) */
1584 #ifdef _WIN32
1586 static int win32_start_timer(struct qemu_alarm_timer *t)
1588 TIMECAPS tc;
1589 struct qemu_alarm_win32 *data = t->priv;
1590 UINT flags;
1592 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1593 if (!data->host_alarm) {
1594 perror("Failed CreateEvent");
1595 return -1;
1598 memset(&tc, 0, sizeof(tc));
1599 timeGetDevCaps(&tc, sizeof(tc));
1601 if (data->period < tc.wPeriodMin)
1602 data->period = tc.wPeriodMin;
1604 timeBeginPeriod(data->period);
1606 flags = TIME_CALLBACK_FUNCTION;
1607 if (alarm_has_dynticks(t))
1608 flags |= TIME_ONESHOT;
1609 else
1610 flags |= TIME_PERIODIC;
1612 data->timerId = timeSetEvent(1, // interval (ms)
1613 data->period, // resolution
1614 host_alarm_handler, // function
1615 (DWORD)t, // parameter
1616 flags);
1618 if (!data->timerId) {
1619 perror("Failed to initialize win32 alarm timer");
1621 timeEndPeriod(data->period);
1622 CloseHandle(data->host_alarm);
1623 return -1;
1626 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1628 return 0;
1631 static void win32_stop_timer(struct qemu_alarm_timer *t)
1633 struct qemu_alarm_win32 *data = t->priv;
1635 timeKillEvent(data->timerId);
1636 timeEndPeriod(data->period);
1638 CloseHandle(data->host_alarm);
1641 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1643 struct qemu_alarm_win32 *data = t->priv;
1644 uint64_t nearest_delta_us;
1646 if (!active_timers[QEMU_TIMER_REALTIME] &&
1647 !active_timers[QEMU_TIMER_VIRTUAL])
1648 return;
1650 nearest_delta_us = qemu_next_deadline_dyntick();
1651 nearest_delta_us /= 1000;
1653 timeKillEvent(data->timerId);
1655 data->timerId = timeSetEvent(1,
1656 data->period,
1657 host_alarm_handler,
1658 (DWORD)t,
1659 TIME_ONESHOT | TIME_PERIODIC);
1661 if (!data->timerId) {
1662 perror("Failed to re-arm win32 alarm timer");
1664 timeEndPeriod(data->period);
1665 CloseHandle(data->host_alarm);
1666 exit(1);
1670 #endif /* _WIN32 */
1672 static void init_timer_alarm(void)
1674 struct qemu_alarm_timer *t = NULL;
1675 int i, err = -1;
1677 for (i = 0; alarm_timers[i].name; i++) {
1678 t = &alarm_timers[i];
1680 err = t->start(t);
1681 if (!err)
1682 break;
1685 if (err) {
1686 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1687 fprintf(stderr, "Terminating\n");
1688 exit(1);
1691 alarm_timer = t;
1694 static void quit_timers(void)
1696 alarm_timer->stop(alarm_timer);
1697 alarm_timer = NULL;
1700 /***********************************************************/
1701 /* host time/date access */
1702 void qemu_get_timedate(struct tm *tm, int offset)
1704 time_t ti;
1705 struct tm *ret;
1707 time(&ti);
1708 ti += offset;
1709 if (rtc_date_offset == -1) {
1710 if (rtc_utc)
1711 ret = gmtime(&ti);
1712 else
1713 ret = localtime(&ti);
1714 } else {
1715 ti -= rtc_date_offset;
1716 ret = gmtime(&ti);
1719 memcpy(tm, ret, sizeof(struct tm));
1722 int qemu_timedate_diff(struct tm *tm)
1724 time_t seconds;
1726 if (rtc_date_offset == -1)
1727 if (rtc_utc)
1728 seconds = mktimegm(tm);
1729 else
1730 seconds = mktime(tm);
1731 else
1732 seconds = mktimegm(tm) + rtc_date_offset;
1734 return seconds - time(NULL);
1737 #ifdef _WIN32
1738 static void socket_cleanup(void)
1740 WSACleanup();
1743 static int socket_init(void)
1745 WSADATA Data;
1746 int ret, err;
1748 ret = WSAStartup(MAKEWORD(2,2), &Data);
1749 if (ret != 0) {
1750 err = WSAGetLastError();
1751 fprintf(stderr, "WSAStartup: %d\n", err);
1752 return -1;
1754 atexit(socket_cleanup);
1755 return 0;
1757 #endif
1759 const char *get_opt_name(char *buf, int buf_size, const char *p)
1761 char *q;
1763 q = buf;
1764 while (*p != '\0' && *p != '=') {
1765 if (q && (q - buf) < buf_size - 1)
1766 *q++ = *p;
1767 p++;
1769 if (q)
1770 *q = '\0';
1772 return p;
1775 const char *get_opt_value(char *buf, int buf_size, const char *p)
1777 char *q;
1779 q = buf;
1780 while (*p != '\0') {
1781 if (*p == ',') {
1782 if (*(p + 1) != ',')
1783 break;
1784 p++;
1786 if (q && (q - buf) < buf_size - 1)
1787 *q++ = *p;
1788 p++;
1790 if (q)
1791 *q = '\0';
1793 return p;
1796 int get_param_value(char *buf, int buf_size,
1797 const char *tag, const char *str)
1799 const char *p;
1800 char option[128];
1802 p = str;
1803 for(;;) {
1804 p = get_opt_name(option, sizeof(option), p);
1805 if (*p != '=')
1806 break;
1807 p++;
1808 if (!strcmp(tag, option)) {
1809 (void)get_opt_value(buf, buf_size, p);
1810 return strlen(buf);
1811 } else {
1812 p = get_opt_value(NULL, 0, p);
1814 if (*p != ',')
1815 break;
1816 p++;
1818 return 0;
1821 int check_params(char *buf, int buf_size,
1822 const char * const *params, const char *str)
1824 const char *p;
1825 int i;
1827 p = str;
1828 for(;;) {
1829 p = get_opt_name(buf, buf_size, p);
1830 if (*p != '=')
1831 return -1;
1832 p++;
1833 for(i = 0; params[i] != NULL; i++)
1834 if (!strcmp(params[i], buf))
1835 break;
1836 if (params[i] == NULL)
1837 return -1;
1838 p = get_opt_value(NULL, 0, p);
1839 if (*p != ',')
1840 break;
1841 p++;
1843 return 0;
1846 /***********************************************************/
1847 /* Bluetooth support */
1848 static int nb_hcis;
1849 static int cur_hci;
1850 static struct HCIInfo *hci_table[MAX_NICS];
1851 #if 0
1852 static struct bt_vlan_s {
1853 struct bt_scatternet_s net;
1854 int id;
1855 struct bt_vlan_s *next;
1856 } *first_bt_vlan;
1858 /* find or alloc a new bluetooth "VLAN" */
1859 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1861 struct bt_vlan_s **pvlan, *vlan;
1862 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1863 if (vlan->id == id)
1864 return &vlan->net;
1866 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1867 vlan->id = id;
1868 pvlan = &first_bt_vlan;
1869 while (*pvlan != NULL)
1870 pvlan = &(*pvlan)->next;
1871 *pvlan = vlan;
1872 return &vlan->net;
1874 #endif
1876 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1880 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1882 return -ENOTSUP;
1885 static struct HCIInfo null_hci = {
1886 .cmd_send = null_hci_send,
1887 .sco_send = null_hci_send,
1888 .acl_send = null_hci_send,
1889 .bdaddr_set = null_hci_addr_set,
1892 struct HCIInfo *qemu_next_hci(void)
1894 if (cur_hci == nb_hcis)
1895 return &null_hci;
1897 return hci_table[cur_hci++];
1900 /***********************************************************/
1901 /* QEMU Block devices */
1903 #define HD_ALIAS "index=%d,media=disk"
1904 #ifdef TARGET_PPC
1905 #define CDROM_ALIAS "index=1,media=cdrom"
1906 #else
1907 #define CDROM_ALIAS "index=2,media=cdrom"
1908 #endif
1909 #define FD_ALIAS "index=%d,if=floppy"
1910 #define PFLASH_ALIAS "if=pflash"
1911 #define MTD_ALIAS "if=mtd"
1912 #define SD_ALIAS "index=0,if=sd"
1914 static int drive_add(const char *file, const char *fmt, ...)
1916 va_list ap;
1918 if (nb_drives_opt >= MAX_DRIVES) {
1919 fprintf(stderr, "qemu: too many drives\n");
1920 exit(1);
1923 drives_opt[nb_drives_opt].file = file;
1924 va_start(ap, fmt);
1925 vsnprintf(drives_opt[nb_drives_opt].opt,
1926 sizeof(drives_opt[0].opt), fmt, ap);
1927 va_end(ap);
1929 return nb_drives_opt++;
1932 int drive_get_index(BlockInterfaceType type, int bus, int unit)
1934 int index;
1936 /* seek interface, bus and unit */
1938 for (index = 0; index < nb_drives; index++)
1939 if (drives_table[index].type == type &&
1940 drives_table[index].bus == bus &&
1941 drives_table[index].unit == unit)
1942 return index;
1944 return -1;
1947 int drive_get_max_bus(BlockInterfaceType type)
1949 int max_bus;
1950 int index;
1952 max_bus = -1;
1953 for (index = 0; index < nb_drives; index++) {
1954 if(drives_table[index].type == type &&
1955 drives_table[index].bus > max_bus)
1956 max_bus = drives_table[index].bus;
1958 return max_bus;
1961 static void bdrv_format_print(void *opaque, const char *name)
1963 fprintf(stderr, " %s", name);
1966 static int drive_init(struct drive_opt *arg, int snapshot,
1967 QEMUMachine *machine)
1969 char buf[128];
1970 char file[1024];
1971 char devname[128];
1972 const char *mediastr = "";
1973 BlockInterfaceType type;
1974 enum { MEDIA_DISK, MEDIA_CDROM } media;
1975 int bus_id, unit_id;
1976 int cyls, heads, secs, translation;
1977 BlockDriverState *bdrv;
1978 BlockDriver *drv = NULL;
1979 int max_devs;
1980 int index;
1981 int cache;
1982 int bdrv_flags;
1983 char *str = arg->opt;
1984 static const char * const params[] = { "bus", "unit", "if", "index",
1985 "cyls", "heads", "secs", "trans",
1986 "media", "snapshot", "file",
1987 "cache", "format", NULL };
1989 if (check_params(buf, sizeof(buf), params, str) < 0) {
1990 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
1991 buf, str);
1992 return -1;
1995 file[0] = 0;
1996 cyls = heads = secs = 0;
1997 bus_id = 0;
1998 unit_id = -1;
1999 translation = BIOS_ATA_TRANSLATION_AUTO;
2000 index = -1;
2001 cache = 1;
2003 if (machine->use_scsi) {
2004 type = IF_SCSI;
2005 max_devs = MAX_SCSI_DEVS;
2006 pstrcpy(devname, sizeof(devname), "scsi");
2007 } else {
2008 type = IF_IDE;
2009 max_devs = MAX_IDE_DEVS;
2010 pstrcpy(devname, sizeof(devname), "ide");
2012 media = MEDIA_DISK;
2014 /* extract parameters */
2016 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2017 bus_id = strtol(buf, NULL, 0);
2018 if (bus_id < 0) {
2019 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2020 return -1;
2024 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2025 unit_id = strtol(buf, NULL, 0);
2026 if (unit_id < 0) {
2027 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2028 return -1;
2032 if (get_param_value(buf, sizeof(buf), "if", str)) {
2033 pstrcpy(devname, sizeof(devname), buf);
2034 if (!strcmp(buf, "ide")) {
2035 type = IF_IDE;
2036 max_devs = MAX_IDE_DEVS;
2037 } else if (!strcmp(buf, "scsi")) {
2038 type = IF_SCSI;
2039 max_devs = MAX_SCSI_DEVS;
2040 } else if (!strcmp(buf, "floppy")) {
2041 type = IF_FLOPPY;
2042 max_devs = 0;
2043 } else if (!strcmp(buf, "pflash")) {
2044 type = IF_PFLASH;
2045 max_devs = 0;
2046 } else if (!strcmp(buf, "mtd")) {
2047 type = IF_MTD;
2048 max_devs = 0;
2049 } else if (!strcmp(buf, "sd")) {
2050 type = IF_SD;
2051 max_devs = 0;
2052 } else {
2053 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2054 return -1;
2058 if (get_param_value(buf, sizeof(buf), "index", str)) {
2059 index = strtol(buf, NULL, 0);
2060 if (index < 0) {
2061 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2062 return -1;
2066 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2067 cyls = strtol(buf, NULL, 0);
2070 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2071 heads = strtol(buf, NULL, 0);
2074 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2075 secs = strtol(buf, NULL, 0);
2078 if (cyls || heads || secs) {
2079 if (cyls < 1 || cyls > 16383) {
2080 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2081 return -1;
2083 if (heads < 1 || heads > 16) {
2084 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2085 return -1;
2087 if (secs < 1 || secs > 63) {
2088 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2089 return -1;
2093 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2094 if (!cyls) {
2095 fprintf(stderr,
2096 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2097 str);
2098 return -1;
2100 if (!strcmp(buf, "none"))
2101 translation = BIOS_ATA_TRANSLATION_NONE;
2102 else if (!strcmp(buf, "lba"))
2103 translation = BIOS_ATA_TRANSLATION_LBA;
2104 else if (!strcmp(buf, "auto"))
2105 translation = BIOS_ATA_TRANSLATION_AUTO;
2106 else {
2107 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2108 return -1;
2112 if (get_param_value(buf, sizeof(buf), "media", str)) {
2113 if (!strcmp(buf, "disk")) {
2114 media = MEDIA_DISK;
2115 } else if (!strcmp(buf, "cdrom")) {
2116 if (cyls || secs || heads) {
2117 fprintf(stderr,
2118 "qemu: '%s' invalid physical CHS format\n", str);
2119 return -1;
2121 media = MEDIA_CDROM;
2122 } else {
2123 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2124 return -1;
2128 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2129 if (!strcmp(buf, "on"))
2130 snapshot = 1;
2131 else if (!strcmp(buf, "off"))
2132 snapshot = 0;
2133 else {
2134 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2135 return -1;
2139 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2140 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2141 cache = 0;
2142 else if (!strcmp(buf, "writethrough"))
2143 cache = 1;
2144 else if (!strcmp(buf, "writeback"))
2145 cache = 2;
2146 else {
2147 fprintf(stderr, "qemu: invalid cache option\n");
2148 return -1;
2152 if (get_param_value(buf, sizeof(buf), "format", str)) {
2153 if (strcmp(buf, "?") == 0) {
2154 fprintf(stderr, "qemu: Supported formats:");
2155 bdrv_iterate_format(bdrv_format_print, NULL);
2156 fprintf(stderr, "\n");
2157 return -1;
2159 drv = bdrv_find_format(buf);
2160 if (!drv) {
2161 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2162 return -1;
2166 if (arg->file == NULL)
2167 get_param_value(file, sizeof(file), "file", str);
2168 else
2169 pstrcpy(file, sizeof(file), arg->file);
2171 /* compute bus and unit according index */
2173 if (index != -1) {
2174 if (bus_id != 0 || unit_id != -1) {
2175 fprintf(stderr,
2176 "qemu: '%s' index cannot be used with bus and unit\n", str);
2177 return -1;
2179 if (max_devs == 0)
2181 unit_id = index;
2182 bus_id = 0;
2183 } else {
2184 unit_id = index % max_devs;
2185 bus_id = index / max_devs;
2189 /* if user doesn't specify a unit_id,
2190 * try to find the first free
2193 if (unit_id == -1) {
2194 unit_id = 0;
2195 while (drive_get_index(type, bus_id, unit_id) != -1) {
2196 unit_id++;
2197 if (max_devs && unit_id >= max_devs) {
2198 unit_id -= max_devs;
2199 bus_id++;
2204 /* check unit id */
2206 if (max_devs && unit_id >= max_devs) {
2207 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2208 str, unit_id, max_devs - 1);
2209 return -1;
2213 * ignore multiple definitions
2216 if (drive_get_index(type, bus_id, unit_id) != -1)
2217 return 0;
2219 /* init */
2221 if (type == IF_IDE || type == IF_SCSI)
2222 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2223 if (max_devs)
2224 snprintf(buf, sizeof(buf), "%s%i%s%i",
2225 devname, bus_id, mediastr, unit_id);
2226 else
2227 snprintf(buf, sizeof(buf), "%s%s%i",
2228 devname, mediastr, unit_id);
2229 bdrv = bdrv_new(buf);
2230 drives_table[nb_drives].bdrv = bdrv;
2231 drives_table[nb_drives].type = type;
2232 drives_table[nb_drives].bus = bus_id;
2233 drives_table[nb_drives].unit = unit_id;
2234 nb_drives++;
2236 switch(type) {
2237 case IF_IDE:
2238 case IF_SCSI:
2239 switch(media) {
2240 case MEDIA_DISK:
2241 if (cyls != 0) {
2242 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2243 bdrv_set_translation_hint(bdrv, translation);
2245 break;
2246 case MEDIA_CDROM:
2247 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2248 break;
2250 break;
2251 case IF_SD:
2252 /* FIXME: This isn't really a floppy, but it's a reasonable
2253 approximation. */
2254 case IF_FLOPPY:
2255 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2256 break;
2257 case IF_PFLASH:
2258 case IF_MTD:
2259 break;
2261 if (!file[0])
2262 return 0;
2263 bdrv_flags = 0;
2264 if (snapshot) {
2265 bdrv_flags |= BDRV_O_SNAPSHOT;
2266 cache = 2; /* always use write-back with snapshot */
2268 if (cache == 0) /* no caching */
2269 bdrv_flags |= BDRV_O_NOCACHE;
2270 else if (cache == 2) /* write-back */
2271 bdrv_flags |= BDRV_O_CACHE_WB;
2272 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2273 fprintf(stderr, "qemu: could not open disk image %s\n",
2274 file);
2275 return -1;
2277 return 0;
2280 /***********************************************************/
2281 /* USB devices */
2283 static USBPort *used_usb_ports;
2284 static USBPort *free_usb_ports;
2286 /* ??? Maybe change this to register a hub to keep track of the topology. */
2287 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2288 usb_attachfn attach)
2290 port->opaque = opaque;
2291 port->index = index;
2292 port->attach = attach;
2293 port->next = free_usb_ports;
2294 free_usb_ports = port;
2297 int usb_device_add_dev(USBDevice *dev)
2299 USBPort *port;
2301 /* Find a USB port to add the device to. */
2302 port = free_usb_ports;
2303 if (!port->next) {
2304 USBDevice *hub;
2306 /* Create a new hub and chain it on. */
2307 free_usb_ports = NULL;
2308 port->next = used_usb_ports;
2309 used_usb_ports = port;
2311 hub = usb_hub_init(VM_USB_HUB_SIZE);
2312 usb_attach(port, hub);
2313 port = free_usb_ports;
2316 free_usb_ports = port->next;
2317 port->next = used_usb_ports;
2318 used_usb_ports = port;
2319 usb_attach(port, dev);
2320 return 0;
2323 static int usb_device_add(const char *devname)
2325 const char *p;
2326 USBDevice *dev;
2328 if (!free_usb_ports)
2329 return -1;
2331 if (strstart(devname, "host:", &p)) {
2332 dev = usb_host_device_open(p);
2333 } else if (!strcmp(devname, "mouse")) {
2334 dev = usb_mouse_init();
2335 } else if (!strcmp(devname, "tablet")) {
2336 dev = usb_tablet_init();
2337 } else if (!strcmp(devname, "keyboard")) {
2338 dev = usb_keyboard_init();
2339 } else if (strstart(devname, "disk:", &p)) {
2340 dev = usb_msd_init(p);
2341 } else if (!strcmp(devname, "wacom-tablet")) {
2342 dev = usb_wacom_init();
2343 } else if (strstart(devname, "serial:", &p)) {
2344 dev = usb_serial_init(p);
2345 #ifdef CONFIG_BRLAPI
2346 } else if (!strcmp(devname, "braille")) {
2347 dev = usb_baum_init();
2348 #endif
2349 } else if (strstart(devname, "net:", &p)) {
2350 int nic = nb_nics;
2352 if (net_client_init("nic", p) < 0)
2353 return -1;
2354 nd_table[nic].model = "usb";
2355 dev = usb_net_init(&nd_table[nic]);
2356 } else {
2357 return -1;
2359 if (!dev)
2360 return -1;
2362 return usb_device_add_dev(dev);
2365 int usb_device_del_addr(int bus_num, int addr)
2367 USBPort *port;
2368 USBPort **lastp;
2369 USBDevice *dev;
2371 if (!used_usb_ports)
2372 return -1;
2374 if (bus_num != 0)
2375 return -1;
2377 lastp = &used_usb_ports;
2378 port = used_usb_ports;
2379 while (port && port->dev->addr != addr) {
2380 lastp = &port->next;
2381 port = port->next;
2384 if (!port)
2385 return -1;
2387 dev = port->dev;
2388 *lastp = port->next;
2389 usb_attach(port, NULL);
2390 dev->handle_destroy(dev);
2391 port->next = free_usb_ports;
2392 free_usb_ports = port;
2393 return 0;
2396 static int usb_device_del(const char *devname)
2398 int bus_num, addr;
2399 const char *p;
2401 if (strstart(devname, "host:", &p))
2402 return usb_host_device_close(p);
2404 if (!used_usb_ports)
2405 return -1;
2407 p = strchr(devname, '.');
2408 if (!p)
2409 return -1;
2410 bus_num = strtoul(devname, NULL, 0);
2411 addr = strtoul(p + 1, NULL, 0);
2413 return usb_device_del_addr(bus_num, addr);
2416 void do_usb_add(const char *devname)
2418 usb_device_add(devname);
2421 void do_usb_del(const char *devname)
2423 usb_device_del(devname);
2426 void usb_info(void)
2428 USBDevice *dev;
2429 USBPort *port;
2430 const char *speed_str;
2432 if (!usb_enabled) {
2433 term_printf("USB support not enabled\n");
2434 return;
2437 for (port = used_usb_ports; port; port = port->next) {
2438 dev = port->dev;
2439 if (!dev)
2440 continue;
2441 switch(dev->speed) {
2442 case USB_SPEED_LOW:
2443 speed_str = "1.5";
2444 break;
2445 case USB_SPEED_FULL:
2446 speed_str = "12";
2447 break;
2448 case USB_SPEED_HIGH:
2449 speed_str = "480";
2450 break;
2451 default:
2452 speed_str = "?";
2453 break;
2455 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2456 0, dev->addr, speed_str, dev->devname);
2460 /***********************************************************/
2461 /* PCMCIA/Cardbus */
2463 static struct pcmcia_socket_entry_s {
2464 struct pcmcia_socket_s *socket;
2465 struct pcmcia_socket_entry_s *next;
2466 } *pcmcia_sockets = 0;
2468 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2470 struct pcmcia_socket_entry_s *entry;
2472 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2473 entry->socket = socket;
2474 entry->next = pcmcia_sockets;
2475 pcmcia_sockets = entry;
2478 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2480 struct pcmcia_socket_entry_s *entry, **ptr;
2482 ptr = &pcmcia_sockets;
2483 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2484 if (entry->socket == socket) {
2485 *ptr = entry->next;
2486 qemu_free(entry);
2490 void pcmcia_info(void)
2492 struct pcmcia_socket_entry_s *iter;
2493 if (!pcmcia_sockets)
2494 term_printf("No PCMCIA sockets\n");
2496 for (iter = pcmcia_sockets; iter; iter = iter->next)
2497 term_printf("%s: %s\n", iter->socket->slot_string,
2498 iter->socket->attached ? iter->socket->card_string :
2499 "Empty");
2502 /***********************************************************/
2503 /* dumb display */
2505 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2509 static void dumb_resize(DisplayState *ds, int w, int h)
2513 static void dumb_display_init(DisplayState *ds)
2515 ds->data = NULL;
2516 ds->linesize = 0;
2517 ds->depth = 0;
2518 ds->dpy_update = dumb_update;
2519 ds->dpy_resize = dumb_resize;
2520 ds->dpy_refresh = NULL;
2521 ds->gui_timer_interval = 0;
2522 ds->idle = 1;
2525 /***********************************************************/
2526 /* I/O handling */
2528 #define MAX_IO_HANDLERS 64
2530 typedef struct IOHandlerRecord {
2531 int fd;
2532 IOCanRWHandler *fd_read_poll;
2533 IOHandler *fd_read;
2534 IOHandler *fd_write;
2535 int deleted;
2536 void *opaque;
2537 /* temporary data */
2538 struct pollfd *ufd;
2539 struct IOHandlerRecord *next;
2540 } IOHandlerRecord;
2542 static IOHandlerRecord *first_io_handler;
2544 /* XXX: fd_read_poll should be suppressed, but an API change is
2545 necessary in the character devices to suppress fd_can_read(). */
2546 int qemu_set_fd_handler2(int fd,
2547 IOCanRWHandler *fd_read_poll,
2548 IOHandler *fd_read,
2549 IOHandler *fd_write,
2550 void *opaque)
2552 IOHandlerRecord **pioh, *ioh;
2554 if (!fd_read && !fd_write) {
2555 pioh = &first_io_handler;
2556 for(;;) {
2557 ioh = *pioh;
2558 if (ioh == NULL)
2559 break;
2560 if (ioh->fd == fd) {
2561 ioh->deleted = 1;
2562 break;
2564 pioh = &ioh->next;
2566 } else {
2567 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2568 if (ioh->fd == fd)
2569 goto found;
2571 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2572 if (!ioh)
2573 return -1;
2574 ioh->next = first_io_handler;
2575 first_io_handler = ioh;
2576 found:
2577 ioh->fd = fd;
2578 ioh->fd_read_poll = fd_read_poll;
2579 ioh->fd_read = fd_read;
2580 ioh->fd_write = fd_write;
2581 ioh->opaque = opaque;
2582 ioh->deleted = 0;
2584 return 0;
2587 int qemu_set_fd_handler(int fd,
2588 IOHandler *fd_read,
2589 IOHandler *fd_write,
2590 void *opaque)
2592 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2595 #ifdef _WIN32
2596 /***********************************************************/
2597 /* Polling handling */
2599 typedef struct PollingEntry {
2600 PollingFunc *func;
2601 void *opaque;
2602 struct PollingEntry *next;
2603 } PollingEntry;
2605 static PollingEntry *first_polling_entry;
2607 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2609 PollingEntry **ppe, *pe;
2610 pe = qemu_mallocz(sizeof(PollingEntry));
2611 if (!pe)
2612 return -1;
2613 pe->func = func;
2614 pe->opaque = opaque;
2615 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2616 *ppe = pe;
2617 return 0;
2620 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2622 PollingEntry **ppe, *pe;
2623 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2624 pe = *ppe;
2625 if (pe->func == func && pe->opaque == opaque) {
2626 *ppe = pe->next;
2627 qemu_free(pe);
2628 break;
2633 /***********************************************************/
2634 /* Wait objects support */
2635 typedef struct WaitObjects {
2636 int num;
2637 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2638 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2639 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2640 } WaitObjects;
2642 static WaitObjects wait_objects = {0};
2644 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2646 WaitObjects *w = &wait_objects;
2648 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2649 return -1;
2650 w->events[w->num] = handle;
2651 w->func[w->num] = func;
2652 w->opaque[w->num] = opaque;
2653 w->num++;
2654 return 0;
2657 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2659 int i, found;
2660 WaitObjects *w = &wait_objects;
2662 found = 0;
2663 for (i = 0; i < w->num; i++) {
2664 if (w->events[i] == handle)
2665 found = 1;
2666 if (found) {
2667 w->events[i] = w->events[i + 1];
2668 w->func[i] = w->func[i + 1];
2669 w->opaque[i] = w->opaque[i + 1];
2672 if (found)
2673 w->num--;
2675 #endif
2677 #define SELF_ANNOUNCE_ROUNDS 5
2678 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
2679 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
2680 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
2682 static int announce_self_create(uint8_t *buf,
2683 uint8_t *mac_addr)
2685 uint32_t magic = EXPERIMENTAL_MAGIC;
2686 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
2688 /* FIXME: should we send a different packet (arp/rarp/ping)? */
2690 memset(buf, 0xff, 6); /* h_dst */
2691 memcpy(buf + 6, mac_addr, 6); /* h_src */
2692 memcpy(buf + 12, &proto, 2); /* h_proto */
2693 memcpy(buf + 14, &magic, 4); /* magic */
2695 return 18; /* len */
2698 void qemu_announce_self(void)
2700 int i, j, len;
2701 VLANState *vlan;
2702 VLANClientState *vc;
2703 uint8_t buf[256];
2705 for (i = 0; i < nb_nics; i++) {
2706 len = announce_self_create(buf, nd_table[i].macaddr);
2707 vlan = nd_table[i].vlan;
2708 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2709 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
2710 vc->fd_read(vc->opaque, buf, len);
2715 /***********************************************************/
2716 /* savevm/loadvm support */
2718 #define IO_BUF_SIZE 32768
2720 struct QEMUFile {
2721 QEMUFilePutBufferFunc *put_buffer;
2722 QEMUFileGetBufferFunc *get_buffer;
2723 QEMUFileCloseFunc *close;
2724 QEMUFileRateLimit *rate_limit;
2725 void *opaque;
2726 int is_write;
2728 int64_t buf_offset; /* start of buffer when writing, end of buffer
2729 when reading */
2730 int buf_index;
2731 int buf_size; /* 0 when writing */
2732 uint8_t buf[IO_BUF_SIZE];
2734 int has_error;
2737 typedef struct QEMUFileSocket
2739 int fd;
2740 QEMUFile *file;
2741 } QEMUFileSocket;
2743 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2745 QEMUFileSocket *s = opaque;
2746 ssize_t len;
2748 do {
2749 len = recv(s->fd, buf, size, 0);
2750 } while (len == -1 && socket_error() == EINTR);
2752 if (len == -1)
2753 len = -socket_error();
2755 return len;
2758 static int socket_close(void *opaque)
2760 QEMUFileSocket *s = opaque;
2761 qemu_free(s);
2762 return 0;
2765 QEMUFile *qemu_fopen_socket(int fd)
2767 QEMUFileSocket *s = qemu_mallocz(sizeof(QEMUFileSocket));
2769 if (s == NULL)
2770 return NULL;
2772 s->fd = fd;
2773 s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, socket_close, NULL);
2774 return s->file;
2777 typedef struct QEMUFileStdio
2779 FILE *outfile;
2780 } QEMUFileStdio;
2782 static int file_put_buffer(void *opaque, const uint8_t *buf,
2783 int64_t pos, int size)
2785 QEMUFileStdio *s = opaque;
2786 fseek(s->outfile, pos, SEEK_SET);
2787 fwrite(buf, 1, size, s->outfile);
2788 return size;
2791 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2793 QEMUFileStdio *s = opaque;
2794 fseek(s->outfile, pos, SEEK_SET);
2795 return fread(buf, 1, size, s->outfile);
2798 static int file_close(void *opaque)
2800 QEMUFileStdio *s = opaque;
2801 fclose(s->outfile);
2802 qemu_free(s);
2803 return 0;
2806 QEMUFile *qemu_fopen(const char *filename, const char *mode)
2808 QEMUFileStdio *s;
2810 s = qemu_mallocz(sizeof(QEMUFileStdio));
2811 if (!s)
2812 return NULL;
2814 s->outfile = fopen(filename, mode);
2815 if (!s->outfile)
2816 goto fail;
2818 if (!strcmp(mode, "wb"))
2819 return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
2820 else if (!strcmp(mode, "rb"))
2821 return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
2823 fail:
2824 if (s->outfile)
2825 fclose(s->outfile);
2826 qemu_free(s);
2827 return NULL;
2830 typedef struct QEMUFileBdrv
2832 BlockDriverState *bs;
2833 int64_t base_offset;
2834 } QEMUFileBdrv;
2836 static int bdrv_put_buffer(void *opaque, const uint8_t *buf,
2837 int64_t pos, int size)
2839 QEMUFileBdrv *s = opaque;
2840 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
2841 return size;
2844 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2846 QEMUFileBdrv *s = opaque;
2847 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
2850 static int bdrv_fclose(void *opaque)
2852 QEMUFileBdrv *s = opaque;
2853 qemu_free(s);
2854 return 0;
2857 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
2859 QEMUFileBdrv *s;
2861 s = qemu_mallocz(sizeof(QEMUFileBdrv));
2862 if (!s)
2863 return NULL;
2865 s->bs = bs;
2866 s->base_offset = offset;
2868 if (is_writable)
2869 return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
2871 return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
2874 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
2875 QEMUFileGetBufferFunc *get_buffer,
2876 QEMUFileCloseFunc *close,
2877 QEMUFileRateLimit *rate_limit)
2879 QEMUFile *f;
2881 f = qemu_mallocz(sizeof(QEMUFile));
2882 if (!f)
2883 return NULL;
2885 f->opaque = opaque;
2886 f->put_buffer = put_buffer;
2887 f->get_buffer = get_buffer;
2888 f->close = close;
2889 f->rate_limit = rate_limit;
2890 f->is_write = 0;
2892 return f;
2895 int qemu_file_has_error(QEMUFile *f)
2897 return f->has_error;
2900 void qemu_fflush(QEMUFile *f)
2902 if (!f->put_buffer)
2903 return;
2905 if (f->is_write && f->buf_index > 0) {
2906 int len;
2908 len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
2909 if (len > 0)
2910 f->buf_offset += f->buf_index;
2911 else
2912 f->has_error = 1;
2913 f->buf_index = 0;
2917 static void qemu_fill_buffer(QEMUFile *f)
2919 int len;
2921 if (!f->get_buffer)
2922 return;
2924 if (f->is_write)
2925 abort();
2927 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
2928 if (len > 0) {
2929 f->buf_index = 0;
2930 f->buf_size = len;
2931 f->buf_offset += len;
2932 } else if (len != -EAGAIN)
2933 f->has_error = 1;
2936 int qemu_fclose(QEMUFile *f)
2938 int ret = 0;
2939 qemu_fflush(f);
2940 if (f->close)
2941 ret = f->close(f->opaque);
2942 qemu_free(f);
2943 return ret;
2946 void qemu_file_put_notify(QEMUFile *f)
2948 f->put_buffer(f->opaque, NULL, 0, 0);
2951 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
2953 int l;
2955 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
2956 fprintf(stderr,
2957 "Attempted to write to buffer while read buffer is not empty\n");
2958 abort();
2961 while (!f->has_error && size > 0) {
2962 l = IO_BUF_SIZE - f->buf_index;
2963 if (l > size)
2964 l = size;
2965 memcpy(f->buf + f->buf_index, buf, l);
2966 f->is_write = 1;
2967 f->buf_index += l;
2968 buf += l;
2969 size -= l;
2970 if (f->buf_index >= IO_BUF_SIZE)
2971 qemu_fflush(f);
2975 void qemu_put_byte(QEMUFile *f, int v)
2977 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
2978 fprintf(stderr,
2979 "Attempted to write to buffer while read buffer is not empty\n");
2980 abort();
2983 f->buf[f->buf_index++] = v;
2984 f->is_write = 1;
2985 if (f->buf_index >= IO_BUF_SIZE)
2986 qemu_fflush(f);
2989 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
2991 int size, l;
2993 if (f->is_write)
2994 abort();
2996 size = size1;
2997 while (size > 0) {
2998 l = f->buf_size - f->buf_index;
2999 if (l == 0) {
3000 qemu_fill_buffer(f);
3001 l = f->buf_size - f->buf_index;
3002 if (l == 0)
3003 break;
3005 if (l > size)
3006 l = size;
3007 memcpy(buf, f->buf + f->buf_index, l);
3008 f->buf_index += l;
3009 buf += l;
3010 size -= l;
3012 return size1 - size;
3015 int qemu_get_byte(QEMUFile *f)
3017 if (f->is_write)
3018 abort();
3020 if (f->buf_index >= f->buf_size) {
3021 qemu_fill_buffer(f);
3022 if (f->buf_index >= f->buf_size)
3023 return 0;
3025 return f->buf[f->buf_index++];
3028 int64_t qemu_ftell(QEMUFile *f)
3030 return f->buf_offset - f->buf_size + f->buf_index;
3033 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3035 if (whence == SEEK_SET) {
3036 /* nothing to do */
3037 } else if (whence == SEEK_CUR) {
3038 pos += qemu_ftell(f);
3039 } else {
3040 /* SEEK_END not supported */
3041 return -1;
3043 if (f->put_buffer) {
3044 qemu_fflush(f);
3045 f->buf_offset = pos;
3046 } else {
3047 f->buf_offset = pos;
3048 f->buf_index = 0;
3049 f->buf_size = 0;
3051 return pos;
3054 int qemu_file_rate_limit(QEMUFile *f)
3056 if (f->rate_limit)
3057 return f->rate_limit(f->opaque);
3059 return 0;
3062 void qemu_put_be16(QEMUFile *f, unsigned int v)
3064 qemu_put_byte(f, v >> 8);
3065 qemu_put_byte(f, v);
3068 void qemu_put_be32(QEMUFile *f, unsigned int v)
3070 qemu_put_byte(f, v >> 24);
3071 qemu_put_byte(f, v >> 16);
3072 qemu_put_byte(f, v >> 8);
3073 qemu_put_byte(f, v);
3076 void qemu_put_be64(QEMUFile *f, uint64_t v)
3078 qemu_put_be32(f, v >> 32);
3079 qemu_put_be32(f, v);
3082 unsigned int qemu_get_be16(QEMUFile *f)
3084 unsigned int v;
3085 v = qemu_get_byte(f) << 8;
3086 v |= qemu_get_byte(f);
3087 return v;
3090 unsigned int qemu_get_be32(QEMUFile *f)
3092 unsigned int v;
3093 v = qemu_get_byte(f) << 24;
3094 v |= qemu_get_byte(f) << 16;
3095 v |= qemu_get_byte(f) << 8;
3096 v |= qemu_get_byte(f);
3097 return v;
3100 uint64_t qemu_get_be64(QEMUFile *f)
3102 uint64_t v;
3103 v = (uint64_t)qemu_get_be32(f) << 32;
3104 v |= qemu_get_be32(f);
3105 return v;
3108 typedef struct SaveStateEntry {
3109 char idstr[256];
3110 int instance_id;
3111 int version_id;
3112 int section_id;
3113 SaveLiveStateHandler *save_live_state;
3114 SaveStateHandler *save_state;
3115 LoadStateHandler *load_state;
3116 void *opaque;
3117 struct SaveStateEntry *next;
3118 } SaveStateEntry;
3120 static SaveStateEntry *first_se;
3122 /* TODO: Individual devices generally have very little idea about the rest
3123 of the system, so instance_id should be removed/replaced.
3124 Meanwhile pass -1 as instance_id if you do not already have a clearly
3125 distinguishing id for all instances of your device class. */
3126 int register_savevm_live(const char *idstr,
3127 int instance_id,
3128 int version_id,
3129 SaveLiveStateHandler *save_live_state,
3130 SaveStateHandler *save_state,
3131 LoadStateHandler *load_state,
3132 void *opaque)
3134 SaveStateEntry *se, **pse;
3135 static int global_section_id;
3137 se = qemu_malloc(sizeof(SaveStateEntry));
3138 if (!se)
3139 return -1;
3140 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3141 se->instance_id = (instance_id == -1) ? 0 : instance_id;
3142 se->version_id = version_id;
3143 se->section_id = global_section_id++;
3144 se->save_live_state = save_live_state;
3145 se->save_state = save_state;
3146 se->load_state = load_state;
3147 se->opaque = opaque;
3148 se->next = NULL;
3150 /* add at the end of list */
3151 pse = &first_se;
3152 while (*pse != NULL) {
3153 if (instance_id == -1
3154 && strcmp(se->idstr, (*pse)->idstr) == 0
3155 && se->instance_id <= (*pse)->instance_id)
3156 se->instance_id = (*pse)->instance_id + 1;
3157 pse = &(*pse)->next;
3159 *pse = se;
3160 return 0;
3163 int register_savevm(const char *idstr,
3164 int instance_id,
3165 int version_id,
3166 SaveStateHandler *save_state,
3167 LoadStateHandler *load_state,
3168 void *opaque)
3170 return register_savevm_live(idstr, instance_id, version_id,
3171 NULL, save_state, load_state, opaque);
3174 #define QEMU_VM_FILE_MAGIC 0x5145564d
3175 #define QEMU_VM_FILE_VERSION_COMPAT 0x00000002
3176 #define QEMU_VM_FILE_VERSION 0x00000003
3178 #define QEMU_VM_EOF 0x00
3179 #define QEMU_VM_SECTION_START 0x01
3180 #define QEMU_VM_SECTION_PART 0x02
3181 #define QEMU_VM_SECTION_END 0x03
3182 #define QEMU_VM_SECTION_FULL 0x04
3184 int qemu_savevm_state_begin(QEMUFile *f)
3186 SaveStateEntry *se;
3188 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3189 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3191 for (se = first_se; se != NULL; se = se->next) {
3192 int len;
3194 if (se->save_live_state == NULL)
3195 continue;
3197 /* Section type */
3198 qemu_put_byte(f, QEMU_VM_SECTION_START);
3199 qemu_put_be32(f, se->section_id);
3201 /* ID string */
3202 len = strlen(se->idstr);
3203 qemu_put_byte(f, len);
3204 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3206 qemu_put_be32(f, se->instance_id);
3207 qemu_put_be32(f, se->version_id);
3209 se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
3212 if (qemu_file_has_error(f))
3213 return -EIO;
3215 return 0;
3218 int qemu_savevm_state_iterate(QEMUFile *f)
3220 SaveStateEntry *se;
3221 int ret = 1;
3223 for (se = first_se; se != NULL; se = se->next) {
3224 if (se->save_live_state == NULL)
3225 continue;
3227 /* Section type */
3228 qemu_put_byte(f, QEMU_VM_SECTION_PART);
3229 qemu_put_be32(f, se->section_id);
3231 ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
3234 if (ret)
3235 return 1;
3237 if (qemu_file_has_error(f))
3238 return -EIO;
3240 return 0;
3243 int qemu_savevm_state_complete(QEMUFile *f)
3245 SaveStateEntry *se;
3247 for (se = first_se; se != NULL; se = se->next) {
3248 if (se->save_live_state == NULL)
3249 continue;
3251 /* Section type */
3252 qemu_put_byte(f, QEMU_VM_SECTION_END);
3253 qemu_put_be32(f, se->section_id);
3255 se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
3258 for(se = first_se; se != NULL; se = se->next) {
3259 int len;
3261 if (se->save_state == NULL)
3262 continue;
3264 /* Section type */
3265 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
3266 qemu_put_be32(f, se->section_id);
3268 /* ID string */
3269 len = strlen(se->idstr);
3270 qemu_put_byte(f, len);
3271 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3273 qemu_put_be32(f, se->instance_id);
3274 qemu_put_be32(f, se->version_id);
3276 se->save_state(f, se->opaque);
3279 qemu_put_byte(f, QEMU_VM_EOF);
3281 if (qemu_file_has_error(f))
3282 return -EIO;
3284 return 0;
3287 int qemu_savevm_state(QEMUFile *f)
3289 int saved_vm_running;
3290 int ret;
3292 saved_vm_running = vm_running;
3293 vm_stop(0);
3295 bdrv_flush_all();
3297 ret = qemu_savevm_state_begin(f);
3298 if (ret < 0)
3299 goto out;
3301 do {
3302 ret = qemu_savevm_state_iterate(f);
3303 if (ret < 0)
3304 goto out;
3305 } while (ret == 0);
3307 ret = qemu_savevm_state_complete(f);
3309 out:
3310 if (qemu_file_has_error(f))
3311 ret = -EIO;
3313 if (!ret && saved_vm_running)
3314 vm_start();
3316 return ret;
3319 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3321 SaveStateEntry *se;
3323 for(se = first_se; se != NULL; se = se->next) {
3324 if (!strcmp(se->idstr, idstr) &&
3325 instance_id == se->instance_id)
3326 return se;
3328 return NULL;
3331 typedef struct LoadStateEntry {
3332 SaveStateEntry *se;
3333 int section_id;
3334 int version_id;
3335 struct LoadStateEntry *next;
3336 } LoadStateEntry;
3338 static int qemu_loadvm_state_v2(QEMUFile *f)
3340 SaveStateEntry *se;
3341 int len, ret, instance_id, record_len, version_id;
3342 int64_t total_len, end_pos, cur_pos;
3343 char idstr[256];
3345 total_len = qemu_get_be64(f);
3346 end_pos = total_len + qemu_ftell(f);
3347 for(;;) {
3348 if (qemu_ftell(f) >= end_pos)
3349 break;
3350 len = qemu_get_byte(f);
3351 qemu_get_buffer(f, (uint8_t *)idstr, len);
3352 idstr[len] = '\0';
3353 instance_id = qemu_get_be32(f);
3354 version_id = qemu_get_be32(f);
3355 record_len = qemu_get_be32(f);
3356 cur_pos = qemu_ftell(f);
3357 se = find_se(idstr, instance_id);
3358 if (!se) {
3359 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3360 instance_id, idstr);
3361 } else {
3362 ret = se->load_state(f, se->opaque, version_id);
3363 if (ret < 0) {
3364 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3365 instance_id, idstr);
3368 /* always seek to exact end of record */
3369 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3372 if (qemu_file_has_error(f))
3373 return -EIO;
3375 return 0;
3378 int qemu_loadvm_state(QEMUFile *f)
3380 LoadStateEntry *first_le = NULL;
3381 uint8_t section_type;
3382 unsigned int v;
3383 int ret;
3385 v = qemu_get_be32(f);
3386 if (v != QEMU_VM_FILE_MAGIC)
3387 return -EINVAL;
3389 v = qemu_get_be32(f);
3390 if (v == QEMU_VM_FILE_VERSION_COMPAT)
3391 return qemu_loadvm_state_v2(f);
3392 if (v != QEMU_VM_FILE_VERSION)
3393 return -ENOTSUP;
3395 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
3396 uint32_t instance_id, version_id, section_id;
3397 LoadStateEntry *le;
3398 SaveStateEntry *se;
3399 char idstr[257];
3400 int len;
3402 switch (section_type) {
3403 case QEMU_VM_SECTION_START:
3404 case QEMU_VM_SECTION_FULL:
3405 /* Read section start */
3406 section_id = qemu_get_be32(f);
3407 len = qemu_get_byte(f);
3408 qemu_get_buffer(f, (uint8_t *)idstr, len);
3409 idstr[len] = 0;
3410 instance_id = qemu_get_be32(f);
3411 version_id = qemu_get_be32(f);
3413 /* Find savevm section */
3414 se = find_se(idstr, instance_id);
3415 if (se == NULL) {
3416 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
3417 ret = -EINVAL;
3418 goto out;
3421 /* Validate version */
3422 if (version_id > se->version_id) {
3423 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
3424 version_id, idstr, se->version_id);
3425 ret = -EINVAL;
3426 goto out;
3429 /* Add entry */
3430 le = qemu_mallocz(sizeof(*le));
3431 if (le == NULL) {
3432 ret = -ENOMEM;
3433 goto out;
3436 le->se = se;
3437 le->section_id = section_id;
3438 le->version_id = version_id;
3439 le->next = first_le;
3440 first_le = le;
3442 le->se->load_state(f, le->se->opaque, le->version_id);
3443 break;
3444 case QEMU_VM_SECTION_PART:
3445 case QEMU_VM_SECTION_END:
3446 section_id = qemu_get_be32(f);
3448 for (le = first_le; le && le->section_id != section_id; le = le->next);
3449 if (le == NULL) {
3450 fprintf(stderr, "Unknown savevm section %d\n", section_id);
3451 ret = -EINVAL;
3452 goto out;
3455 le->se->load_state(f, le->se->opaque, le->version_id);
3456 break;
3457 default:
3458 fprintf(stderr, "Unknown savevm section type %d\n", section_type);
3459 ret = -EINVAL;
3460 goto out;
3464 ret = 0;
3466 out:
3467 while (first_le) {
3468 LoadStateEntry *le = first_le;
3469 first_le = first_le->next;
3470 qemu_free(le);
3473 if (qemu_file_has_error(f))
3474 ret = -EIO;
3476 return ret;
3479 /* device can contain snapshots */
3480 static int bdrv_can_snapshot(BlockDriverState *bs)
3482 return (bs &&
3483 !bdrv_is_removable(bs) &&
3484 !bdrv_is_read_only(bs));
3487 /* device must be snapshots in order to have a reliable snapshot */
3488 static int bdrv_has_snapshot(BlockDriverState *bs)
3490 return (bs &&
3491 !bdrv_is_removable(bs) &&
3492 !bdrv_is_read_only(bs));
3495 static BlockDriverState *get_bs_snapshots(void)
3497 BlockDriverState *bs;
3498 int i;
3500 if (bs_snapshots)
3501 return bs_snapshots;
3502 for(i = 0; i <= nb_drives; i++) {
3503 bs = drives_table[i].bdrv;
3504 if (bdrv_can_snapshot(bs))
3505 goto ok;
3507 return NULL;
3509 bs_snapshots = bs;
3510 return bs;
3513 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
3514 const char *name)
3516 QEMUSnapshotInfo *sn_tab, *sn;
3517 int nb_sns, i, ret;
3519 ret = -ENOENT;
3520 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3521 if (nb_sns < 0)
3522 return ret;
3523 for(i = 0; i < nb_sns; i++) {
3524 sn = &sn_tab[i];
3525 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
3526 *sn_info = *sn;
3527 ret = 0;
3528 break;
3531 qemu_free(sn_tab);
3532 return ret;
3535 void do_savevm(const char *name)
3537 BlockDriverState *bs, *bs1;
3538 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
3539 int must_delete, ret, i;
3540 BlockDriverInfo bdi1, *bdi = &bdi1;
3541 QEMUFile *f;
3542 int saved_vm_running;
3543 #ifdef _WIN32
3544 struct _timeb tb;
3545 #else
3546 struct timeval tv;
3547 #endif
3549 bs = get_bs_snapshots();
3550 if (!bs) {
3551 term_printf("No block device can accept snapshots\n");
3552 return;
3555 /* ??? Should this occur after vm_stop? */
3556 qemu_aio_flush();
3558 saved_vm_running = vm_running;
3559 vm_stop(0);
3561 must_delete = 0;
3562 if (name) {
3563 ret = bdrv_snapshot_find(bs, old_sn, name);
3564 if (ret >= 0) {
3565 must_delete = 1;
3568 memset(sn, 0, sizeof(*sn));
3569 if (must_delete) {
3570 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
3571 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
3572 } else {
3573 if (name)
3574 pstrcpy(sn->name, sizeof(sn->name), name);
3577 /* fill auxiliary fields */
3578 #ifdef _WIN32
3579 _ftime(&tb);
3580 sn->date_sec = tb.time;
3581 sn->date_nsec = tb.millitm * 1000000;
3582 #else
3583 gettimeofday(&tv, NULL);
3584 sn->date_sec = tv.tv_sec;
3585 sn->date_nsec = tv.tv_usec * 1000;
3586 #endif
3587 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
3589 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3590 term_printf("Device %s does not support VM state snapshots\n",
3591 bdrv_get_device_name(bs));
3592 goto the_end;
3595 /* save the VM state */
3596 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
3597 if (!f) {
3598 term_printf("Could not open VM state file\n");
3599 goto the_end;
3601 ret = qemu_savevm_state(f);
3602 sn->vm_state_size = qemu_ftell(f);
3603 qemu_fclose(f);
3604 if (ret < 0) {
3605 term_printf("Error %d while writing VM\n", ret);
3606 goto the_end;
3609 /* create the snapshots */
3611 for(i = 0; i < nb_drives; i++) {
3612 bs1 = drives_table[i].bdrv;
3613 if (bdrv_has_snapshot(bs1)) {
3614 if (must_delete) {
3615 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
3616 if (ret < 0) {
3617 term_printf("Error while deleting snapshot on '%s'\n",
3618 bdrv_get_device_name(bs1));
3621 ret = bdrv_snapshot_create(bs1, sn);
3622 if (ret < 0) {
3623 term_printf("Error while creating snapshot on '%s'\n",
3624 bdrv_get_device_name(bs1));
3629 the_end:
3630 if (saved_vm_running)
3631 vm_start();
3634 void do_loadvm(const char *name)
3636 BlockDriverState *bs, *bs1;
3637 BlockDriverInfo bdi1, *bdi = &bdi1;
3638 QEMUFile *f;
3639 int i, ret;
3640 int saved_vm_running;
3642 bs = get_bs_snapshots();
3643 if (!bs) {
3644 term_printf("No block device supports snapshots\n");
3645 return;
3648 /* Flush all IO requests so they don't interfere with the new state. */
3649 qemu_aio_flush();
3651 saved_vm_running = vm_running;
3652 vm_stop(0);
3654 for(i = 0; i <= nb_drives; i++) {
3655 bs1 = drives_table[i].bdrv;
3656 if (bdrv_has_snapshot(bs1)) {
3657 ret = bdrv_snapshot_goto(bs1, name);
3658 if (ret < 0) {
3659 if (bs != bs1)
3660 term_printf("Warning: ");
3661 switch(ret) {
3662 case -ENOTSUP:
3663 term_printf("Snapshots not supported on device '%s'\n",
3664 bdrv_get_device_name(bs1));
3665 break;
3666 case -ENOENT:
3667 term_printf("Could not find snapshot '%s' on device '%s'\n",
3668 name, bdrv_get_device_name(bs1));
3669 break;
3670 default:
3671 term_printf("Error %d while activating snapshot on '%s'\n",
3672 ret, bdrv_get_device_name(bs1));
3673 break;
3675 /* fatal on snapshot block device */
3676 if (bs == bs1)
3677 goto the_end;
3682 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3683 term_printf("Device %s does not support VM state snapshots\n",
3684 bdrv_get_device_name(bs));
3685 return;
3688 /* restore the VM state */
3689 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
3690 if (!f) {
3691 term_printf("Could not open VM state file\n");
3692 goto the_end;
3694 ret = qemu_loadvm_state(f);
3695 qemu_fclose(f);
3696 if (ret < 0) {
3697 term_printf("Error %d while loading VM state\n", ret);
3699 the_end:
3700 if (saved_vm_running)
3701 vm_start();
3704 void do_delvm(const char *name)
3706 BlockDriverState *bs, *bs1;
3707 int i, ret;
3709 bs = get_bs_snapshots();
3710 if (!bs) {
3711 term_printf("No block device supports snapshots\n");
3712 return;
3715 for(i = 0; i <= nb_drives; i++) {
3716 bs1 = drives_table[i].bdrv;
3717 if (bdrv_has_snapshot(bs1)) {
3718 ret = bdrv_snapshot_delete(bs1, name);
3719 if (ret < 0) {
3720 if (ret == -ENOTSUP)
3721 term_printf("Snapshots not supported on device '%s'\n",
3722 bdrv_get_device_name(bs1));
3723 else
3724 term_printf("Error %d while deleting snapshot on '%s'\n",
3725 ret, bdrv_get_device_name(bs1));
3731 void do_info_snapshots(void)
3733 BlockDriverState *bs, *bs1;
3734 QEMUSnapshotInfo *sn_tab, *sn;
3735 int nb_sns, i;
3736 char buf[256];
3738 bs = get_bs_snapshots();
3739 if (!bs) {
3740 term_printf("No available block device supports snapshots\n");
3741 return;
3743 term_printf("Snapshot devices:");
3744 for(i = 0; i <= nb_drives; i++) {
3745 bs1 = drives_table[i].bdrv;
3746 if (bdrv_has_snapshot(bs1)) {
3747 if (bs == bs1)
3748 term_printf(" %s", bdrv_get_device_name(bs1));
3751 term_printf("\n");
3753 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3754 if (nb_sns < 0) {
3755 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
3756 return;
3758 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
3759 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
3760 for(i = 0; i < nb_sns; i++) {
3761 sn = &sn_tab[i];
3762 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
3764 qemu_free(sn_tab);
3767 /***********************************************************/
3768 /* ram save/restore */
3770 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3772 int v;
3774 v = qemu_get_byte(f);
3775 switch(v) {
3776 case 0:
3777 if (qemu_get_buffer(f, buf, len) != len)
3778 return -EIO;
3779 break;
3780 case 1:
3781 v = qemu_get_byte(f);
3782 memset(buf, v, len);
3783 break;
3784 default:
3785 return -EINVAL;
3788 if (qemu_file_has_error(f))
3789 return -EIO;
3791 return 0;
3794 static int ram_load_v1(QEMUFile *f, void *opaque)
3796 int ret;
3797 ram_addr_t i;
3799 if (qemu_get_be32(f) != phys_ram_size)
3800 return -EINVAL;
3801 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3802 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3803 if (ret)
3804 return ret;
3806 return 0;
3809 #define BDRV_HASH_BLOCK_SIZE 1024
3810 #define IOBUF_SIZE 4096
3811 #define RAM_CBLOCK_MAGIC 0xfabe
3813 typedef struct RamDecompressState {
3814 z_stream zstream;
3815 QEMUFile *f;
3816 uint8_t buf[IOBUF_SIZE];
3817 } RamDecompressState;
3819 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3821 int ret;
3822 memset(s, 0, sizeof(*s));
3823 s->f = f;
3824 ret = inflateInit(&s->zstream);
3825 if (ret != Z_OK)
3826 return -1;
3827 return 0;
3830 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3832 int ret, clen;
3834 s->zstream.avail_out = len;
3835 s->zstream.next_out = buf;
3836 while (s->zstream.avail_out > 0) {
3837 if (s->zstream.avail_in == 0) {
3838 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3839 return -1;
3840 clen = qemu_get_be16(s->f);
3841 if (clen > IOBUF_SIZE)
3842 return -1;
3843 qemu_get_buffer(s->f, s->buf, clen);
3844 s->zstream.avail_in = clen;
3845 s->zstream.next_in = s->buf;
3847 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3848 if (ret != Z_OK && ret != Z_STREAM_END) {
3849 return -1;
3852 return 0;
3855 static void ram_decompress_close(RamDecompressState *s)
3857 inflateEnd(&s->zstream);
3860 #define RAM_SAVE_FLAG_FULL 0x01
3861 #define RAM_SAVE_FLAG_COMPRESS 0x02
3862 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3863 #define RAM_SAVE_FLAG_PAGE 0x08
3864 #define RAM_SAVE_FLAG_EOS 0x10
3866 static int is_dup_page(uint8_t *page, uint8_t ch)
3868 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3869 uint32_t *array = (uint32_t *)page;
3870 int i;
3872 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3873 if (array[i] != val)
3874 return 0;
3877 return 1;
3880 static int ram_save_block(QEMUFile *f)
3882 static ram_addr_t current_addr = 0;
3883 ram_addr_t saved_addr = current_addr;
3884 ram_addr_t addr = 0;
3885 int found = 0;
3887 while (addr < phys_ram_size) {
3888 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3889 uint8_t ch;
3891 cpu_physical_memory_reset_dirty(current_addr,
3892 current_addr + TARGET_PAGE_SIZE,
3893 MIGRATION_DIRTY_FLAG);
3895 ch = *(phys_ram_base + current_addr);
3897 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3898 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3899 qemu_put_byte(f, ch);
3900 } else {
3901 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3902 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3905 found = 1;
3906 break;
3908 addr += TARGET_PAGE_SIZE;
3909 current_addr = (saved_addr + addr) % phys_ram_size;
3912 return found;
3915 static ram_addr_t ram_save_threshold = 10;
3917 static ram_addr_t ram_save_remaining(void)
3919 ram_addr_t addr;
3920 ram_addr_t count = 0;
3922 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3923 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3924 count++;
3927 return count;
3930 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3932 ram_addr_t addr;
3934 if (stage == 1) {
3935 /* Make sure all dirty bits are set */
3936 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3937 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3938 cpu_physical_memory_set_dirty(addr);
3941 /* Enable dirty memory tracking */
3942 cpu_physical_memory_set_dirty_tracking(1);
3944 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3947 while (!qemu_file_rate_limit(f)) {
3948 int ret;
3950 ret = ram_save_block(f);
3951 if (ret == 0) /* no more blocks */
3952 break;
3955 /* try transferring iterative blocks of memory */
3957 if (stage == 3) {
3958 cpu_physical_memory_set_dirty_tracking(0);
3960 /* flush all remaining blocks regardless of rate limiting */
3961 while (ram_save_block(f) != 0);
3964 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3966 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3969 static int ram_load_dead(QEMUFile *f, void *opaque)
3971 RamDecompressState s1, *s = &s1;
3972 uint8_t buf[10];
3973 ram_addr_t i;
3975 if (ram_decompress_open(s, f) < 0)
3976 return -EINVAL;
3977 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3978 if (ram_decompress_buf(s, buf, 1) < 0) {
3979 fprintf(stderr, "Error while reading ram block header\n");
3980 goto error;
3982 if (buf[0] == 0) {
3983 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3984 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3985 goto error;
3987 } else {
3988 error:
3989 printf("Error block header\n");
3990 return -EINVAL;
3993 ram_decompress_close(s);
3995 return 0;
3998 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4000 ram_addr_t addr;
4001 int flags;
4003 if (version_id == 1)
4004 return ram_load_v1(f, opaque);
4006 if (version_id == 2) {
4007 if (qemu_get_be32(f) != phys_ram_size)
4008 return -EINVAL;
4009 return ram_load_dead(f, opaque);
4012 if (version_id != 3)
4013 return -EINVAL;
4015 do {
4016 addr = qemu_get_be64(f);
4018 flags = addr & ~TARGET_PAGE_MASK;
4019 addr &= TARGET_PAGE_MASK;
4021 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
4022 if (addr != phys_ram_size)
4023 return -EINVAL;
4026 if (flags & RAM_SAVE_FLAG_FULL) {
4027 if (ram_load_dead(f, opaque) < 0)
4028 return -EINVAL;
4031 if (flags & RAM_SAVE_FLAG_COMPRESS) {
4032 uint8_t ch = qemu_get_byte(f);
4033 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
4034 } else if (flags & RAM_SAVE_FLAG_PAGE)
4035 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
4036 } while (!(flags & RAM_SAVE_FLAG_EOS));
4038 return 0;
4041 void qemu_service_io(void)
4043 CPUState *env = cpu_single_env;
4044 if (env) {
4045 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4046 #ifdef USE_KQEMU
4047 if (env->kqemu_enabled) {
4048 kqemu_cpu_interrupt(env);
4050 #endif
4054 /***********************************************************/
4055 /* bottom halves (can be seen as timers which expire ASAP) */
4057 struct QEMUBH {
4058 QEMUBHFunc *cb;
4059 void *opaque;
4060 int scheduled;
4061 int idle;
4062 int deleted;
4063 QEMUBH *next;
4066 static QEMUBH *first_bh = NULL;
4068 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
4070 QEMUBH *bh;
4071 bh = qemu_mallocz(sizeof(QEMUBH));
4072 if (!bh)
4073 return NULL;
4074 bh->cb = cb;
4075 bh->opaque = opaque;
4076 bh->next = first_bh;
4077 first_bh = bh;
4078 return bh;
4081 int qemu_bh_poll(void)
4083 QEMUBH *bh, **bhp;
4084 int ret;
4086 ret = 0;
4087 for (bh = first_bh; bh; bh = bh->next) {
4088 if (!bh->deleted && bh->scheduled) {
4089 bh->scheduled = 0;
4090 if (!bh->idle)
4091 ret = 1;
4092 bh->idle = 0;
4093 bh->cb(bh->opaque);
4097 /* remove deleted bhs */
4098 bhp = &first_bh;
4099 while (*bhp) {
4100 bh = *bhp;
4101 if (bh->deleted) {
4102 *bhp = bh->next;
4103 qemu_free(bh);
4104 } else
4105 bhp = &bh->next;
4108 return ret;
4111 void qemu_bh_schedule_idle(QEMUBH *bh)
4113 if (bh->scheduled)
4114 return;
4115 bh->scheduled = 1;
4116 bh->idle = 1;
4119 void qemu_bh_schedule(QEMUBH *bh)
4121 CPUState *env = cpu_single_env;
4122 if (bh->scheduled)
4123 return;
4124 bh->scheduled = 1;
4125 bh->idle = 0;
4126 /* stop the currently executing CPU to execute the BH ASAP */
4127 if (env) {
4128 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4132 void qemu_bh_cancel(QEMUBH *bh)
4134 bh->scheduled = 0;
4137 void qemu_bh_delete(QEMUBH *bh)
4139 bh->scheduled = 0;
4140 bh->deleted = 1;
4143 static void qemu_bh_update_timeout(int *timeout)
4145 QEMUBH *bh;
4147 for (bh = first_bh; bh; bh = bh->next) {
4148 if (!bh->deleted && bh->scheduled) {
4149 if (bh->idle) {
4150 /* idle bottom halves will be polled at least
4151 * every 10ms */
4152 *timeout = MIN(10, *timeout);
4153 } else {
4154 /* non-idle bottom halves will be executed
4155 * immediately */
4156 *timeout = 0;
4157 break;
4163 /***********************************************************/
4164 /* machine registration */
4166 static QEMUMachine *first_machine = NULL;
4168 int qemu_register_machine(QEMUMachine *m)
4170 QEMUMachine **pm;
4171 pm = &first_machine;
4172 while (*pm != NULL)
4173 pm = &(*pm)->next;
4174 m->next = NULL;
4175 *pm = m;
4176 return 0;
4179 static QEMUMachine *find_machine(const char *name)
4181 QEMUMachine *m;
4183 for(m = first_machine; m != NULL; m = m->next) {
4184 if (!strcmp(m->name, name))
4185 return m;
4187 return NULL;
4190 /***********************************************************/
4191 /* main execution loop */
4193 static void gui_update(void *opaque)
4195 DisplayState *ds = opaque;
4196 ds->dpy_refresh(ds);
4197 qemu_mod_timer(ds->gui_timer,
4198 (ds->gui_timer_interval ?
4199 ds->gui_timer_interval :
4200 GUI_REFRESH_INTERVAL)
4201 + qemu_get_clock(rt_clock));
4204 struct vm_change_state_entry {
4205 VMChangeStateHandler *cb;
4206 void *opaque;
4207 LIST_ENTRY (vm_change_state_entry) entries;
4210 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4212 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4213 void *opaque)
4215 VMChangeStateEntry *e;
4217 e = qemu_mallocz(sizeof (*e));
4218 if (!e)
4219 return NULL;
4221 e->cb = cb;
4222 e->opaque = opaque;
4223 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4224 return e;
4227 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4229 LIST_REMOVE (e, entries);
4230 qemu_free (e);
4233 static void vm_state_notify(int running)
4235 VMChangeStateEntry *e;
4237 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4238 e->cb(e->opaque, running);
4242 /* XXX: support several handlers */
4243 static VMStopHandler *vm_stop_cb;
4244 static void *vm_stop_opaque;
4246 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4248 vm_stop_cb = cb;
4249 vm_stop_opaque = opaque;
4250 return 0;
4253 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4255 vm_stop_cb = NULL;
4258 void vm_start(void)
4260 if (!vm_running) {
4261 cpu_enable_ticks();
4262 vm_running = 1;
4263 vm_state_notify(1);
4264 qemu_rearm_alarm_timer(alarm_timer);
4268 void vm_stop(int reason)
4270 if (vm_running) {
4271 cpu_disable_ticks();
4272 vm_running = 0;
4273 if (reason != 0) {
4274 if (vm_stop_cb) {
4275 vm_stop_cb(vm_stop_opaque, reason);
4278 vm_state_notify(0);
4282 /* reset/shutdown handler */
4284 typedef struct QEMUResetEntry {
4285 QEMUResetHandler *func;
4286 void *opaque;
4287 struct QEMUResetEntry *next;
4288 } QEMUResetEntry;
4290 static QEMUResetEntry *first_reset_entry;
4291 static int reset_requested;
4292 static int shutdown_requested;
4293 static int powerdown_requested;
4295 int qemu_shutdown_requested(void)
4297 int r = shutdown_requested;
4298 shutdown_requested = 0;
4299 return r;
4302 int qemu_reset_requested(void)
4304 int r = reset_requested;
4305 reset_requested = 0;
4306 return r;
4309 int qemu_powerdown_requested(void)
4311 int r = powerdown_requested;
4312 powerdown_requested = 0;
4313 return r;
4316 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4318 QEMUResetEntry **pre, *re;
4320 pre = &first_reset_entry;
4321 while (*pre != NULL)
4322 pre = &(*pre)->next;
4323 re = qemu_mallocz(sizeof(QEMUResetEntry));
4324 re->func = func;
4325 re->opaque = opaque;
4326 re->next = NULL;
4327 *pre = re;
4330 void qemu_system_reset(void)
4332 QEMUResetEntry *re;
4334 /* reset all devices */
4335 for(re = first_reset_entry; re != NULL; re = re->next) {
4336 re->func(re->opaque);
4340 void qemu_system_reset_request(void)
4342 if (no_reboot) {
4343 shutdown_requested = 1;
4344 } else {
4345 reset_requested = 1;
4347 if (cpu_single_env)
4348 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4351 void qemu_system_shutdown_request(void)
4353 shutdown_requested = 1;
4354 if (cpu_single_env)
4355 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4358 void qemu_system_powerdown_request(void)
4360 powerdown_requested = 1;
4361 if (cpu_single_env)
4362 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4365 #ifdef _WIN32
4366 void host_main_loop_wait(int *timeout)
4368 int ret, ret2, i;
4369 PollingEntry *pe;
4372 /* XXX: need to suppress polling by better using win32 events */
4373 ret = 0;
4374 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4375 ret |= pe->func(pe->opaque);
4377 if (ret == 0) {
4378 int err;
4379 WaitObjects *w = &wait_objects;
4381 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4382 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4383 if (w->func[ret - WAIT_OBJECT_0])
4384 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4386 /* Check for additional signaled events */
4387 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4389 /* Check if event is signaled */
4390 ret2 = WaitForSingleObject(w->events[i], 0);
4391 if(ret2 == WAIT_OBJECT_0) {
4392 if (w->func[i])
4393 w->func[i](w->opaque[i]);
4394 } else if (ret2 == WAIT_TIMEOUT) {
4395 } else {
4396 err = GetLastError();
4397 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4400 } else if (ret == WAIT_TIMEOUT) {
4401 } else {
4402 err = GetLastError();
4403 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4407 *timeout = 0;
4409 #else
4410 void host_main_loop_wait(int *timeout)
4413 #endif
4415 void main_loop_wait(int timeout)
4417 IOHandlerRecord *ioh;
4418 fd_set rfds, wfds, xfds;
4419 int ret, nfds;
4420 struct timeval tv;
4422 qemu_bh_update_timeout(&timeout);
4424 host_main_loop_wait(&timeout);
4426 /* poll any events */
4427 /* XXX: separate device handlers from system ones */
4428 nfds = -1;
4429 FD_ZERO(&rfds);
4430 FD_ZERO(&wfds);
4431 FD_ZERO(&xfds);
4432 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4433 if (ioh->deleted)
4434 continue;
4435 if (ioh->fd_read &&
4436 (!ioh->fd_read_poll ||
4437 ioh->fd_read_poll(ioh->opaque) != 0)) {
4438 FD_SET(ioh->fd, &rfds);
4439 if (ioh->fd > nfds)
4440 nfds = ioh->fd;
4442 if (ioh->fd_write) {
4443 FD_SET(ioh->fd, &wfds);
4444 if (ioh->fd > nfds)
4445 nfds = ioh->fd;
4449 tv.tv_sec = timeout / 1000;
4450 tv.tv_usec = (timeout % 1000) * 1000;
4452 #if defined(CONFIG_SLIRP)
4453 if (slirp_is_inited()) {
4454 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4456 #endif
4457 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4458 if (ret > 0) {
4459 IOHandlerRecord **pioh;
4461 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4462 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4463 ioh->fd_read(ioh->opaque);
4465 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4466 ioh->fd_write(ioh->opaque);
4470 /* remove deleted IO handlers */
4471 pioh = &first_io_handler;
4472 while (*pioh) {
4473 ioh = *pioh;
4474 if (ioh->deleted) {
4475 *pioh = ioh->next;
4476 qemu_free(ioh);
4477 } else
4478 pioh = &ioh->next;
4481 #if defined(CONFIG_SLIRP)
4482 if (slirp_is_inited()) {
4483 if (ret < 0) {
4484 FD_ZERO(&rfds);
4485 FD_ZERO(&wfds);
4486 FD_ZERO(&xfds);
4488 slirp_select_poll(&rfds, &wfds, &xfds);
4490 #endif
4492 if (vm_running) {
4493 if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4494 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4495 qemu_get_clock(vm_clock));
4498 /* real time timers */
4499 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4500 qemu_get_clock(rt_clock));
4502 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4503 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
4504 qemu_rearm_alarm_timer(alarm_timer);
4507 /* Check bottom-halves last in case any of the earlier events triggered
4508 them. */
4509 qemu_bh_poll();
4513 static int main_loop(void)
4515 int ret, timeout;
4516 #ifdef CONFIG_PROFILER
4517 int64_t ti;
4518 #endif
4519 CPUState *env;
4521 cur_cpu = first_cpu;
4522 next_cpu = cur_cpu->next_cpu ?: first_cpu;
4523 for(;;) {
4524 if (vm_running) {
4526 for(;;) {
4527 /* get next cpu */
4528 env = next_cpu;
4529 #ifdef CONFIG_PROFILER
4530 ti = profile_getclock();
4531 #endif
4532 if (use_icount) {
4533 int64_t count;
4534 int decr;
4535 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4536 env->icount_decr.u16.low = 0;
4537 env->icount_extra = 0;
4538 count = qemu_next_deadline();
4539 count = (count + (1 << icount_time_shift) - 1)
4540 >> icount_time_shift;
4541 qemu_icount += count;
4542 decr = (count > 0xffff) ? 0xffff : count;
4543 count -= decr;
4544 env->icount_decr.u16.low = decr;
4545 env->icount_extra = count;
4547 ret = cpu_exec(env);
4548 #ifdef CONFIG_PROFILER
4549 qemu_time += profile_getclock() - ti;
4550 #endif
4551 if (use_icount) {
4552 /* Fold pending instructions back into the
4553 instruction counter, and clear the interrupt flag. */
4554 qemu_icount -= (env->icount_decr.u16.low
4555 + env->icount_extra);
4556 env->icount_decr.u32 = 0;
4557 env->icount_extra = 0;
4559 next_cpu = env->next_cpu ?: first_cpu;
4560 if (event_pending && likely(ret != EXCP_DEBUG)) {
4561 ret = EXCP_INTERRUPT;
4562 event_pending = 0;
4563 break;
4565 if (ret == EXCP_HLT) {
4566 /* Give the next CPU a chance to run. */
4567 cur_cpu = env;
4568 continue;
4570 if (ret != EXCP_HALTED)
4571 break;
4572 /* all CPUs are halted ? */
4573 if (env == cur_cpu)
4574 break;
4576 cur_cpu = env;
4578 if (shutdown_requested) {
4579 ret = EXCP_INTERRUPT;
4580 if (no_shutdown) {
4581 vm_stop(0);
4582 no_shutdown = 0;
4584 else
4585 break;
4587 if (reset_requested) {
4588 reset_requested = 0;
4589 qemu_system_reset();
4590 ret = EXCP_INTERRUPT;
4592 if (powerdown_requested) {
4593 powerdown_requested = 0;
4594 qemu_system_powerdown();
4595 ret = EXCP_INTERRUPT;
4597 if (unlikely(ret == EXCP_DEBUG)) {
4598 vm_stop(EXCP_DEBUG);
4600 /* If all cpus are halted then wait until the next IRQ */
4601 /* XXX: use timeout computed from timers */
4602 if (ret == EXCP_HALTED) {
4603 if (use_icount) {
4604 int64_t add;
4605 int64_t delta;
4606 /* Advance virtual time to the next event. */
4607 if (use_icount == 1) {
4608 /* When not using an adaptive execution frequency
4609 we tend to get badly out of sync with real time,
4610 so just delay for a reasonable amount of time. */
4611 delta = 0;
4612 } else {
4613 delta = cpu_get_icount() - cpu_get_clock();
4615 if (delta > 0) {
4616 /* If virtual time is ahead of real time then just
4617 wait for IO. */
4618 timeout = (delta / 1000000) + 1;
4619 } else {
4620 /* Wait for either IO to occur or the next
4621 timer event. */
4622 add = qemu_next_deadline();
4623 /* We advance the timer before checking for IO.
4624 Limit the amount we advance so that early IO
4625 activity won't get the guest too far ahead. */
4626 if (add > 10000000)
4627 add = 10000000;
4628 delta += add;
4629 add = (add + (1 << icount_time_shift) - 1)
4630 >> icount_time_shift;
4631 qemu_icount += add;
4632 timeout = delta / 1000000;
4633 if (timeout < 0)
4634 timeout = 0;
4636 } else {
4637 timeout = 5000;
4639 } else {
4640 timeout = 0;
4642 } else {
4643 if (shutdown_requested) {
4644 ret = EXCP_INTERRUPT;
4645 break;
4647 timeout = 5000;
4649 #ifdef CONFIG_PROFILER
4650 ti = profile_getclock();
4651 #endif
4652 main_loop_wait(timeout);
4653 #ifdef CONFIG_PROFILER
4654 dev_time += profile_getclock() - ti;
4655 #endif
4657 cpu_disable_ticks();
4658 return ret;
4661 static void help(int exitcode)
4663 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4664 "usage: %s [options] [disk_image]\n"
4665 "\n"
4666 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4667 "\n"
4668 "Standard options:\n"
4669 "-M machine select emulated machine (-M ? for list)\n"
4670 "-cpu cpu select CPU (-cpu ? for list)\n"
4671 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4672 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4673 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4674 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4675 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
4676 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
4677 " [,cache=writethrough|writeback|none][,format=f]\n"
4678 " use 'file' as a drive image\n"
4679 "-mtdblock file use 'file' as on-board Flash memory image\n"
4680 "-sd file use 'file' as SecureDigital card image\n"
4681 "-pflash file use 'file' as a parallel flash image\n"
4682 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4683 "-snapshot write to temporary files instead of disk image files\n"
4684 #ifdef CONFIG_SDL
4685 "-no-frame open SDL window without a frame and window decorations\n"
4686 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4687 "-no-quit disable SDL window close capability\n"
4688 #endif
4689 #ifdef TARGET_I386
4690 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4691 #endif
4692 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4693 "-smp n set the number of CPUs to 'n' [default=1]\n"
4694 "-nographic disable graphical output and redirect serial I/Os to console\n"
4695 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4696 #ifndef _WIN32
4697 "-k language use keyboard layout (for example \"fr\" for French)\n"
4698 #endif
4699 #ifdef HAS_AUDIO
4700 "-audio-help print list of audio drivers and their options\n"
4701 "-soundhw c1,... enable audio support\n"
4702 " and only specified sound cards (comma separated list)\n"
4703 " use -soundhw ? to get the list of supported cards\n"
4704 " use -soundhw all to enable all of them\n"
4705 #endif
4706 "-vga [std|cirrus|vmware]\n"
4707 " select video card type\n"
4708 "-localtime set the real time clock to local time [default=utc]\n"
4709 "-full-screen start in full screen\n"
4710 #ifdef TARGET_I386
4711 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4712 #endif
4713 "-usb enable the USB driver (will be the default soon)\n"
4714 "-usbdevice name add the host or guest USB device 'name'\n"
4715 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4716 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4717 #endif
4718 "-name string set the name of the guest\n"
4719 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4720 "\n"
4721 "Network options:\n"
4722 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4723 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4724 #ifdef CONFIG_SLIRP
4725 "-net user[,vlan=n][,hostname=host]\n"
4726 " connect the user mode network stack to VLAN 'n' and send\n"
4727 " hostname 'host' to DHCP clients\n"
4728 #endif
4729 #ifdef _WIN32
4730 "-net tap[,vlan=n],ifname=name\n"
4731 " connect the host TAP network interface to VLAN 'n'\n"
4732 #else
4733 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4734 " connect the host TAP network interface to VLAN 'n' and use the\n"
4735 " network scripts 'file' (default=%s)\n"
4736 " and 'dfile' (default=%s);\n"
4737 " use '[down]script=no' to disable script execution;\n"
4738 " use 'fd=h' to connect to an already opened TAP interface\n"
4739 #endif
4740 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4741 " connect the vlan 'n' to another VLAN using a socket connection\n"
4742 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4743 " connect the vlan 'n' to multicast maddr and port\n"
4744 #ifdef CONFIG_VDE
4745 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4746 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4747 " on host and listening for incoming connections on 'socketpath'.\n"
4748 " Use group 'groupname' and mode 'octalmode' to change default\n"
4749 " ownership and permissions for communication port.\n"
4750 #endif
4751 "-net none use it alone to have zero network devices; if no -net option\n"
4752 " is provided, the default is '-net nic -net user'\n"
4753 "\n"
4754 #ifdef CONFIG_SLIRP
4755 "-tftp dir allow tftp access to files in dir [-net user]\n"
4756 "-bootp file advertise file in BOOTP replies\n"
4757 #ifndef _WIN32
4758 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4759 #endif
4760 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4761 " redirect TCP or UDP connections from host to guest [-net user]\n"
4762 #endif
4763 "\n"
4764 "Linux boot specific:\n"
4765 "-kernel bzImage use 'bzImage' as kernel image\n"
4766 "-append cmdline use 'cmdline' as kernel command line\n"
4767 "-initrd file use 'file' as initial ram disk\n"
4768 "\n"
4769 "Debug/Expert options:\n"
4770 "-monitor dev redirect the monitor to char device 'dev'\n"
4771 "-serial dev redirect the serial port to char device 'dev'\n"
4772 "-parallel dev redirect the parallel port to char device 'dev'\n"
4773 "-pidfile file Write PID to 'file'\n"
4774 "-S freeze CPU at startup (use 'c' to start execution)\n"
4775 "-s wait gdb connection to port\n"
4776 "-p port set gdb connection port [default=%s]\n"
4777 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4778 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4779 " translation (t=none or lba) (usually qemu can guess them)\n"
4780 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4781 #ifdef USE_KQEMU
4782 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4783 "-no-kqemu disable KQEMU kernel module usage\n"
4784 #endif
4785 #ifdef TARGET_I386
4786 "-no-acpi disable ACPI\n"
4787 #endif
4788 #ifdef CONFIG_CURSES
4789 "-curses use a curses/ncurses interface instead of SDL\n"
4790 #endif
4791 "-no-reboot exit instead of rebooting\n"
4792 "-no-shutdown stop before shutdown\n"
4793 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
4794 "-vnc display start a VNC server on display\n"
4795 #ifndef _WIN32
4796 "-daemonize daemonize QEMU after initializing\n"
4797 #endif
4798 "-option-rom rom load a file, rom, into the option ROM space\n"
4799 #ifdef TARGET_SPARC
4800 "-prom-env variable=value set OpenBIOS nvram variables\n"
4801 #endif
4802 "-clock force the use of the given methods for timer alarm.\n"
4803 " To see what timers are available use -clock ?\n"
4804 "-startdate select initial date of the clock\n"
4805 "-icount [N|auto]\n"
4806 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4807 "\n"
4808 "During emulation, the following keys are useful:\n"
4809 "ctrl-alt-f toggle full screen\n"
4810 "ctrl-alt-n switch to virtual console 'n'\n"
4811 "ctrl-alt toggle mouse and keyboard grab\n"
4812 "\n"
4813 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4815 "qemu",
4816 DEFAULT_RAM_SIZE,
4817 #ifndef _WIN32
4818 DEFAULT_NETWORK_SCRIPT,
4819 DEFAULT_NETWORK_DOWN_SCRIPT,
4820 #endif
4821 DEFAULT_GDBSTUB_PORT,
4822 "/tmp/qemu.log");
4823 exit(exitcode);
4826 #define HAS_ARG 0x0001
4828 enum {
4829 QEMU_OPTION_h,
4831 QEMU_OPTION_M,
4832 QEMU_OPTION_cpu,
4833 QEMU_OPTION_fda,
4834 QEMU_OPTION_fdb,
4835 QEMU_OPTION_hda,
4836 QEMU_OPTION_hdb,
4837 QEMU_OPTION_hdc,
4838 QEMU_OPTION_hdd,
4839 QEMU_OPTION_drive,
4840 QEMU_OPTION_cdrom,
4841 QEMU_OPTION_mtdblock,
4842 QEMU_OPTION_sd,
4843 QEMU_OPTION_pflash,
4844 QEMU_OPTION_boot,
4845 QEMU_OPTION_snapshot,
4846 #ifdef TARGET_I386
4847 QEMU_OPTION_no_fd_bootchk,
4848 #endif
4849 QEMU_OPTION_m,
4850 QEMU_OPTION_nographic,
4851 QEMU_OPTION_portrait,
4852 #ifdef HAS_AUDIO
4853 QEMU_OPTION_audio_help,
4854 QEMU_OPTION_soundhw,
4855 #endif
4857 QEMU_OPTION_net,
4858 QEMU_OPTION_tftp,
4859 QEMU_OPTION_bootp,
4860 QEMU_OPTION_smb,
4861 QEMU_OPTION_redir,
4863 QEMU_OPTION_kernel,
4864 QEMU_OPTION_append,
4865 QEMU_OPTION_initrd,
4867 QEMU_OPTION_S,
4868 QEMU_OPTION_s,
4869 QEMU_OPTION_p,
4870 QEMU_OPTION_d,
4871 QEMU_OPTION_hdachs,
4872 QEMU_OPTION_L,
4873 QEMU_OPTION_bios,
4874 QEMU_OPTION_k,
4875 QEMU_OPTION_localtime,
4876 QEMU_OPTION_g,
4877 QEMU_OPTION_vga,
4878 QEMU_OPTION_echr,
4879 QEMU_OPTION_monitor,
4880 QEMU_OPTION_serial,
4881 QEMU_OPTION_parallel,
4882 QEMU_OPTION_loadvm,
4883 QEMU_OPTION_full_screen,
4884 QEMU_OPTION_no_frame,
4885 QEMU_OPTION_alt_grab,
4886 QEMU_OPTION_no_quit,
4887 QEMU_OPTION_pidfile,
4888 QEMU_OPTION_no_kqemu,
4889 QEMU_OPTION_kernel_kqemu,
4890 QEMU_OPTION_win2k_hack,
4891 QEMU_OPTION_usb,
4892 QEMU_OPTION_usbdevice,
4893 QEMU_OPTION_smp,
4894 QEMU_OPTION_vnc,
4895 QEMU_OPTION_no_acpi,
4896 QEMU_OPTION_curses,
4897 QEMU_OPTION_no_reboot,
4898 QEMU_OPTION_no_shutdown,
4899 QEMU_OPTION_show_cursor,
4900 QEMU_OPTION_daemonize,
4901 QEMU_OPTION_option_rom,
4902 QEMU_OPTION_semihosting,
4903 QEMU_OPTION_name,
4904 QEMU_OPTION_prom_env,
4905 QEMU_OPTION_old_param,
4906 QEMU_OPTION_clock,
4907 QEMU_OPTION_startdate,
4908 QEMU_OPTION_tb_size,
4909 QEMU_OPTION_icount,
4910 QEMU_OPTION_uuid,
4911 QEMU_OPTION_incoming,
4914 typedef struct QEMUOption {
4915 const char *name;
4916 int flags;
4917 int index;
4918 } QEMUOption;
4920 static const QEMUOption qemu_options[] = {
4921 { "h", 0, QEMU_OPTION_h },
4922 { "help", 0, QEMU_OPTION_h },
4924 { "M", HAS_ARG, QEMU_OPTION_M },
4925 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4926 { "fda", HAS_ARG, QEMU_OPTION_fda },
4927 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4928 { "hda", HAS_ARG, QEMU_OPTION_hda },
4929 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4930 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4931 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4932 { "drive", HAS_ARG, QEMU_OPTION_drive },
4933 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4934 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4935 { "sd", HAS_ARG, QEMU_OPTION_sd },
4936 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4937 { "boot", HAS_ARG, QEMU_OPTION_boot },
4938 { "snapshot", 0, QEMU_OPTION_snapshot },
4939 #ifdef TARGET_I386
4940 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4941 #endif
4942 { "m", HAS_ARG, QEMU_OPTION_m },
4943 { "nographic", 0, QEMU_OPTION_nographic },
4944 { "portrait", 0, QEMU_OPTION_portrait },
4945 { "k", HAS_ARG, QEMU_OPTION_k },
4946 #ifdef HAS_AUDIO
4947 { "audio-help", 0, QEMU_OPTION_audio_help },
4948 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4949 #endif
4951 { "net", HAS_ARG, QEMU_OPTION_net},
4952 #ifdef CONFIG_SLIRP
4953 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4954 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4955 #ifndef _WIN32
4956 { "smb", HAS_ARG, QEMU_OPTION_smb },
4957 #endif
4958 { "redir", HAS_ARG, QEMU_OPTION_redir },
4959 #endif
4961 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4962 { "append", HAS_ARG, QEMU_OPTION_append },
4963 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4965 { "S", 0, QEMU_OPTION_S },
4966 { "s", 0, QEMU_OPTION_s },
4967 { "p", HAS_ARG, QEMU_OPTION_p },
4968 { "d", HAS_ARG, QEMU_OPTION_d },
4969 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4970 { "L", HAS_ARG, QEMU_OPTION_L },
4971 { "bios", HAS_ARG, QEMU_OPTION_bios },
4972 #ifdef USE_KQEMU
4973 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4974 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4975 #endif
4976 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4977 { "g", 1, QEMU_OPTION_g },
4978 #endif
4979 { "localtime", 0, QEMU_OPTION_localtime },
4980 { "vga", HAS_ARG, QEMU_OPTION_vga },
4981 { "echr", HAS_ARG, QEMU_OPTION_echr },
4982 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4983 { "serial", HAS_ARG, QEMU_OPTION_serial },
4984 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4985 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4986 { "full-screen", 0, QEMU_OPTION_full_screen },
4987 #ifdef CONFIG_SDL
4988 { "no-frame", 0, QEMU_OPTION_no_frame },
4989 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4990 { "no-quit", 0, QEMU_OPTION_no_quit },
4991 #endif
4992 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4993 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4994 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4995 { "smp", HAS_ARG, QEMU_OPTION_smp },
4996 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4997 #ifdef CONFIG_CURSES
4998 { "curses", 0, QEMU_OPTION_curses },
4999 #endif
5000 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
5002 /* temporary options */
5003 { "usb", 0, QEMU_OPTION_usb },
5004 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5005 { "no-reboot", 0, QEMU_OPTION_no_reboot },
5006 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
5007 { "show-cursor", 0, QEMU_OPTION_show_cursor },
5008 { "daemonize", 0, QEMU_OPTION_daemonize },
5009 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
5010 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5011 { "semihosting", 0, QEMU_OPTION_semihosting },
5012 #endif
5013 { "name", HAS_ARG, QEMU_OPTION_name },
5014 #if defined(TARGET_SPARC)
5015 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
5016 #endif
5017 #if defined(TARGET_ARM)
5018 { "old-param", 0, QEMU_OPTION_old_param },
5019 #endif
5020 { "clock", HAS_ARG, QEMU_OPTION_clock },
5021 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
5022 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
5023 { "icount", HAS_ARG, QEMU_OPTION_icount },
5024 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
5025 { NULL },
5028 /* password input */
5030 int qemu_key_check(BlockDriverState *bs, const char *name)
5032 char password[256];
5033 int i;
5035 if (!bdrv_is_encrypted(bs))
5036 return 0;
5038 term_printf("%s is encrypted.\n", name);
5039 for(i = 0; i < 3; i++) {
5040 monitor_readline("Password: ", 1, password, sizeof(password));
5041 if (bdrv_set_key(bs, password) == 0)
5042 return 0;
5043 term_printf("invalid password\n");
5045 return -EPERM;
5048 static BlockDriverState *get_bdrv(int index)
5050 if (index > nb_drives)
5051 return NULL;
5052 return drives_table[index].bdrv;
5055 static void read_passwords(void)
5057 BlockDriverState *bs;
5058 int i;
5060 for(i = 0; i < 6; i++) {
5061 bs = get_bdrv(i);
5062 if (bs)
5063 qemu_key_check(bs, bdrv_get_device_name(bs));
5067 #ifdef HAS_AUDIO
5068 struct soundhw soundhw[] = {
5069 #ifdef HAS_AUDIO_CHOICE
5070 #if defined(TARGET_I386) || defined(TARGET_MIPS)
5072 "pcspk",
5073 "PC speaker",
5076 { .init_isa = pcspk_audio_init }
5078 #endif
5080 "sb16",
5081 "Creative Sound Blaster 16",
5084 { .init_isa = SB16_init }
5087 #ifdef CONFIG_CS4231A
5089 "cs4231a",
5090 "CS4231A",
5093 { .init_isa = cs4231a_init }
5095 #endif
5097 #ifdef CONFIG_ADLIB
5099 "adlib",
5100 #ifdef HAS_YMF262
5101 "Yamaha YMF262 (OPL3)",
5102 #else
5103 "Yamaha YM3812 (OPL2)",
5104 #endif
5107 { .init_isa = Adlib_init }
5109 #endif
5111 #ifdef CONFIG_GUS
5113 "gus",
5114 "Gravis Ultrasound GF1",
5117 { .init_isa = GUS_init }
5119 #endif
5121 #ifdef CONFIG_AC97
5123 "ac97",
5124 "Intel 82801AA AC97 Audio",
5127 { .init_pci = ac97_init }
5129 #endif
5132 "es1370",
5133 "ENSONIQ AudioPCI ES1370",
5136 { .init_pci = es1370_init }
5138 #endif
5140 { NULL, NULL, 0, 0, { NULL } }
5143 static void select_soundhw (const char *optarg)
5145 struct soundhw *c;
5147 if (*optarg == '?') {
5148 show_valid_cards:
5150 printf ("Valid sound card names (comma separated):\n");
5151 for (c = soundhw; c->name; ++c) {
5152 printf ("%-11s %s\n", c->name, c->descr);
5154 printf ("\n-soundhw all will enable all of the above\n");
5155 exit (*optarg != '?');
5157 else {
5158 size_t l;
5159 const char *p;
5160 char *e;
5161 int bad_card = 0;
5163 if (!strcmp (optarg, "all")) {
5164 for (c = soundhw; c->name; ++c) {
5165 c->enabled = 1;
5167 return;
5170 p = optarg;
5171 while (*p) {
5172 e = strchr (p, ',');
5173 l = !e ? strlen (p) : (size_t) (e - p);
5175 for (c = soundhw; c->name; ++c) {
5176 if (!strncmp (c->name, p, l)) {
5177 c->enabled = 1;
5178 break;
5182 if (!c->name) {
5183 if (l > 80) {
5184 fprintf (stderr,
5185 "Unknown sound card name (too big to show)\n");
5187 else {
5188 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5189 (int) l, p);
5191 bad_card = 1;
5193 p += l + (e != NULL);
5196 if (bad_card)
5197 goto show_valid_cards;
5200 #endif
5202 static void select_vgahw (const char *p)
5204 const char *opts;
5206 if (strstart(p, "std", &opts)) {
5207 cirrus_vga_enabled = 0;
5208 vmsvga_enabled = 0;
5209 } else if (strstart(p, "cirrus", &opts)) {
5210 cirrus_vga_enabled = 1;
5211 vmsvga_enabled = 0;
5212 } else if (strstart(p, "vmware", &opts)) {
5213 cirrus_vga_enabled = 0;
5214 vmsvga_enabled = 1;
5215 } else {
5216 invalid_vga:
5217 fprintf(stderr, "Unknown vga type: %s\n", p);
5218 exit(1);
5220 while (*opts) {
5221 const char *nextopt;
5223 if (strstart(opts, ",retrace=", &nextopt)) {
5224 opts = nextopt;
5225 if (strstart(opts, "dumb", &nextopt))
5226 vga_retrace_method = VGA_RETRACE_DUMB;
5227 else if (strstart(opts, "precise", &nextopt))
5228 vga_retrace_method = VGA_RETRACE_PRECISE;
5229 else goto invalid_vga;
5230 } else goto invalid_vga;
5231 opts = nextopt;
5235 #ifdef _WIN32
5236 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5238 exit(STATUS_CONTROL_C_EXIT);
5239 return TRUE;
5241 #endif
5243 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
5245 int ret;
5247 if(strlen(str) != 36)
5248 return -1;
5250 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
5251 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
5252 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
5254 if(ret != 16)
5255 return -1;
5257 return 0;
5260 #define MAX_NET_CLIENTS 32
5262 #ifndef _WIN32
5264 static void termsig_handler(int signal)
5266 qemu_system_shutdown_request();
5269 static void termsig_setup(void)
5271 struct sigaction act;
5273 memset(&act, 0, sizeof(act));
5274 act.sa_handler = termsig_handler;
5275 sigaction(SIGINT, &act, NULL);
5276 sigaction(SIGHUP, &act, NULL);
5277 sigaction(SIGTERM, &act, NULL);
5280 #endif
5282 int main(int argc, char **argv)
5284 #ifdef CONFIG_GDBSTUB
5285 int use_gdbstub;
5286 const char *gdbstub_port;
5287 #endif
5288 uint32_t boot_devices_bitmap = 0;
5289 int i;
5290 int snapshot, linux_boot, net_boot;
5291 const char *initrd_filename;
5292 const char *kernel_filename, *kernel_cmdline;
5293 const char *boot_devices = "";
5294 DisplayState *ds = &display_state;
5295 int cyls, heads, secs, translation;
5296 const char *net_clients[MAX_NET_CLIENTS];
5297 int nb_net_clients;
5298 int hda_index;
5299 int optind;
5300 const char *r, *optarg;
5301 CharDriverState *monitor_hd;
5302 const char *monitor_device;
5303 const char *serial_devices[MAX_SERIAL_PORTS];
5304 int serial_device_index;
5305 const char *parallel_devices[MAX_PARALLEL_PORTS];
5306 int parallel_device_index;
5307 const char *loadvm = NULL;
5308 QEMUMachine *machine;
5309 const char *cpu_model;
5310 const char *usb_devices[MAX_USB_CMDLINE];
5311 int usb_devices_index;
5312 int fds[2];
5313 int tb_size;
5314 const char *pid_file = NULL;
5315 int autostart;
5316 const char *incoming = NULL;
5318 LIST_INIT (&vm_change_state_head);
5319 #ifndef _WIN32
5321 struct sigaction act;
5322 sigfillset(&act.sa_mask);
5323 act.sa_flags = 0;
5324 act.sa_handler = SIG_IGN;
5325 sigaction(SIGPIPE, &act, NULL);
5327 #else
5328 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5329 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5330 QEMU to run on a single CPU */
5332 HANDLE h;
5333 DWORD mask, smask;
5334 int i;
5335 h = GetCurrentProcess();
5336 if (GetProcessAffinityMask(h, &mask, &smask)) {
5337 for(i = 0; i < 32; i++) {
5338 if (mask & (1 << i))
5339 break;
5341 if (i != 32) {
5342 mask = 1 << i;
5343 SetProcessAffinityMask(h, mask);
5347 #endif
5349 register_machines();
5350 machine = first_machine;
5351 cpu_model = NULL;
5352 initrd_filename = NULL;
5353 ram_size = 0;
5354 vga_ram_size = VGA_RAM_SIZE;
5355 #ifdef CONFIG_GDBSTUB
5356 use_gdbstub = 0;
5357 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5358 #endif
5359 snapshot = 0;
5360 nographic = 0;
5361 curses = 0;
5362 kernel_filename = NULL;
5363 kernel_cmdline = "";
5364 cyls = heads = secs = 0;
5365 translation = BIOS_ATA_TRANSLATION_AUTO;
5366 monitor_device = "vc";
5368 serial_devices[0] = "vc:80Cx24C";
5369 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5370 serial_devices[i] = NULL;
5371 serial_device_index = 0;
5373 parallel_devices[0] = "vc:640x480";
5374 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5375 parallel_devices[i] = NULL;
5376 parallel_device_index = 0;
5378 usb_devices_index = 0;
5380 nb_net_clients = 0;
5381 nb_drives = 0;
5382 nb_drives_opt = 0;
5383 hda_index = -1;
5385 nb_nics = 0;
5387 tb_size = 0;
5388 autostart= 1;
5390 optind = 1;
5391 for(;;) {
5392 if (optind >= argc)
5393 break;
5394 r = argv[optind];
5395 if (r[0] != '-') {
5396 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5397 } else {
5398 const QEMUOption *popt;
5400 optind++;
5401 /* Treat --foo the same as -foo. */
5402 if (r[1] == '-')
5403 r++;
5404 popt = qemu_options;
5405 for(;;) {
5406 if (!popt->name) {
5407 fprintf(stderr, "%s: invalid option -- '%s'\n",
5408 argv[0], r);
5409 exit(1);
5411 if (!strcmp(popt->name, r + 1))
5412 break;
5413 popt++;
5415 if (popt->flags & HAS_ARG) {
5416 if (optind >= argc) {
5417 fprintf(stderr, "%s: option '%s' requires an argument\n",
5418 argv[0], r);
5419 exit(1);
5421 optarg = argv[optind++];
5422 } else {
5423 optarg = NULL;
5426 switch(popt->index) {
5427 case QEMU_OPTION_M:
5428 machine = find_machine(optarg);
5429 if (!machine) {
5430 QEMUMachine *m;
5431 printf("Supported machines are:\n");
5432 for(m = first_machine; m != NULL; m = m->next) {
5433 printf("%-10s %s%s\n",
5434 m->name, m->desc,
5435 m == first_machine ? " (default)" : "");
5437 exit(*optarg != '?');
5439 break;
5440 case QEMU_OPTION_cpu:
5441 /* hw initialization will check this */
5442 if (*optarg == '?') {
5443 /* XXX: implement xxx_cpu_list for targets that still miss it */
5444 #if defined(cpu_list)
5445 cpu_list(stdout, &fprintf);
5446 #endif
5447 exit(0);
5448 } else {
5449 cpu_model = optarg;
5451 break;
5452 case QEMU_OPTION_initrd:
5453 initrd_filename = optarg;
5454 break;
5455 case QEMU_OPTION_hda:
5456 if (cyls == 0)
5457 hda_index = drive_add(optarg, HD_ALIAS, 0);
5458 else
5459 hda_index = drive_add(optarg, HD_ALIAS
5460 ",cyls=%d,heads=%d,secs=%d%s",
5461 0, cyls, heads, secs,
5462 translation == BIOS_ATA_TRANSLATION_LBA ?
5463 ",trans=lba" :
5464 translation == BIOS_ATA_TRANSLATION_NONE ?
5465 ",trans=none" : "");
5466 break;
5467 case QEMU_OPTION_hdb:
5468 case QEMU_OPTION_hdc:
5469 case QEMU_OPTION_hdd:
5470 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5471 break;
5472 case QEMU_OPTION_drive:
5473 drive_add(NULL, "%s", optarg);
5474 break;
5475 case QEMU_OPTION_mtdblock:
5476 drive_add(optarg, MTD_ALIAS);
5477 break;
5478 case QEMU_OPTION_sd:
5479 drive_add(optarg, SD_ALIAS);
5480 break;
5481 case QEMU_OPTION_pflash:
5482 drive_add(optarg, PFLASH_ALIAS);
5483 break;
5484 case QEMU_OPTION_snapshot:
5485 snapshot = 1;
5486 break;
5487 case QEMU_OPTION_hdachs:
5489 const char *p;
5490 p = optarg;
5491 cyls = strtol(p, (char **)&p, 0);
5492 if (cyls < 1 || cyls > 16383)
5493 goto chs_fail;
5494 if (*p != ',')
5495 goto chs_fail;
5496 p++;
5497 heads = strtol(p, (char **)&p, 0);
5498 if (heads < 1 || heads > 16)
5499 goto chs_fail;
5500 if (*p != ',')
5501 goto chs_fail;
5502 p++;
5503 secs = strtol(p, (char **)&p, 0);
5504 if (secs < 1 || secs > 63)
5505 goto chs_fail;
5506 if (*p == ',') {
5507 p++;
5508 if (!strcmp(p, "none"))
5509 translation = BIOS_ATA_TRANSLATION_NONE;
5510 else if (!strcmp(p, "lba"))
5511 translation = BIOS_ATA_TRANSLATION_LBA;
5512 else if (!strcmp(p, "auto"))
5513 translation = BIOS_ATA_TRANSLATION_AUTO;
5514 else
5515 goto chs_fail;
5516 } else if (*p != '\0') {
5517 chs_fail:
5518 fprintf(stderr, "qemu: invalid physical CHS format\n");
5519 exit(1);
5521 if (hda_index != -1)
5522 snprintf(drives_opt[hda_index].opt,
5523 sizeof(drives_opt[hda_index].opt),
5524 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5525 0, cyls, heads, secs,
5526 translation == BIOS_ATA_TRANSLATION_LBA ?
5527 ",trans=lba" :
5528 translation == BIOS_ATA_TRANSLATION_NONE ?
5529 ",trans=none" : "");
5531 break;
5532 case QEMU_OPTION_nographic:
5533 nographic = 1;
5534 break;
5535 #ifdef CONFIG_CURSES
5536 case QEMU_OPTION_curses:
5537 curses = 1;
5538 break;
5539 #endif
5540 case QEMU_OPTION_portrait:
5541 graphic_rotate = 1;
5542 break;
5543 case QEMU_OPTION_kernel:
5544 kernel_filename = optarg;
5545 break;
5546 case QEMU_OPTION_append:
5547 kernel_cmdline = optarg;
5548 break;
5549 case QEMU_OPTION_cdrom:
5550 drive_add(optarg, CDROM_ALIAS);
5551 break;
5552 case QEMU_OPTION_boot:
5553 boot_devices = optarg;
5554 /* We just do some generic consistency checks */
5556 /* Could easily be extended to 64 devices if needed */
5557 const char *p;
5559 boot_devices_bitmap = 0;
5560 for (p = boot_devices; *p != '\0'; p++) {
5561 /* Allowed boot devices are:
5562 * a b : floppy disk drives
5563 * c ... f : IDE disk drives
5564 * g ... m : machine implementation dependant drives
5565 * n ... p : network devices
5566 * It's up to each machine implementation to check
5567 * if the given boot devices match the actual hardware
5568 * implementation and firmware features.
5570 if (*p < 'a' || *p > 'q') {
5571 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5572 exit(1);
5574 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5575 fprintf(stderr,
5576 "Boot device '%c' was given twice\n",*p);
5577 exit(1);
5579 boot_devices_bitmap |= 1 << (*p - 'a');
5582 break;
5583 case QEMU_OPTION_fda:
5584 case QEMU_OPTION_fdb:
5585 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5586 break;
5587 #ifdef TARGET_I386
5588 case QEMU_OPTION_no_fd_bootchk:
5589 fd_bootchk = 0;
5590 break;
5591 #endif
5592 case QEMU_OPTION_net:
5593 if (nb_net_clients >= MAX_NET_CLIENTS) {
5594 fprintf(stderr, "qemu: too many network clients\n");
5595 exit(1);
5597 net_clients[nb_net_clients] = optarg;
5598 nb_net_clients++;
5599 break;
5600 #ifdef CONFIG_SLIRP
5601 case QEMU_OPTION_tftp:
5602 tftp_prefix = optarg;
5603 break;
5604 case QEMU_OPTION_bootp:
5605 bootp_filename = optarg;
5606 break;
5607 #ifndef _WIN32
5608 case QEMU_OPTION_smb:
5609 net_slirp_smb(optarg);
5610 break;
5611 #endif
5612 case QEMU_OPTION_redir:
5613 net_slirp_redir(optarg);
5614 break;
5615 #endif
5616 #ifdef HAS_AUDIO
5617 case QEMU_OPTION_audio_help:
5618 AUD_help ();
5619 exit (0);
5620 break;
5621 case QEMU_OPTION_soundhw:
5622 select_soundhw (optarg);
5623 break;
5624 #endif
5625 case QEMU_OPTION_h:
5626 help(0);
5627 break;
5628 case QEMU_OPTION_m: {
5629 uint64_t value;
5630 char *ptr;
5632 value = strtoul(optarg, &ptr, 10);
5633 switch (*ptr) {
5634 case 0: case 'M': case 'm':
5635 value <<= 20;
5636 break;
5637 case 'G': case 'g':
5638 value <<= 30;
5639 break;
5640 default:
5641 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5642 exit(1);
5645 /* On 32-bit hosts, QEMU is limited by virtual address space */
5646 if (value > (2047 << 20)
5647 #ifndef USE_KQEMU
5648 && HOST_LONG_BITS == 32
5649 #endif
5651 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5652 exit(1);
5654 if (value != (uint64_t)(ram_addr_t)value) {
5655 fprintf(stderr, "qemu: ram size too large\n");
5656 exit(1);
5658 ram_size = value;
5659 break;
5661 case QEMU_OPTION_d:
5663 int mask;
5664 const CPULogItem *item;
5666 mask = cpu_str_to_log_mask(optarg);
5667 if (!mask) {
5668 printf("Log items (comma separated):\n");
5669 for(item = cpu_log_items; item->mask != 0; item++) {
5670 printf("%-10s %s\n", item->name, item->help);
5672 exit(1);
5674 cpu_set_log(mask);
5676 break;
5677 #ifdef CONFIG_GDBSTUB
5678 case QEMU_OPTION_s:
5679 use_gdbstub = 1;
5680 break;
5681 case QEMU_OPTION_p:
5682 gdbstub_port = optarg;
5683 break;
5684 #endif
5685 case QEMU_OPTION_L:
5686 bios_dir = optarg;
5687 break;
5688 case QEMU_OPTION_bios:
5689 bios_name = optarg;
5690 break;
5691 case QEMU_OPTION_S:
5692 autostart = 0;
5693 break;
5694 case QEMU_OPTION_k:
5695 keyboard_layout = optarg;
5696 break;
5697 case QEMU_OPTION_localtime:
5698 rtc_utc = 0;
5699 break;
5700 case QEMU_OPTION_vga:
5701 select_vgahw (optarg);
5702 break;
5703 case QEMU_OPTION_g:
5705 const char *p;
5706 int w, h, depth;
5707 p = optarg;
5708 w = strtol(p, (char **)&p, 10);
5709 if (w <= 0) {
5710 graphic_error:
5711 fprintf(stderr, "qemu: invalid resolution or depth\n");
5712 exit(1);
5714 if (*p != 'x')
5715 goto graphic_error;
5716 p++;
5717 h = strtol(p, (char **)&p, 10);
5718 if (h <= 0)
5719 goto graphic_error;
5720 if (*p == 'x') {
5721 p++;
5722 depth = strtol(p, (char **)&p, 10);
5723 if (depth != 8 && depth != 15 && depth != 16 &&
5724 depth != 24 && depth != 32)
5725 goto graphic_error;
5726 } else if (*p == '\0') {
5727 depth = graphic_depth;
5728 } else {
5729 goto graphic_error;
5732 graphic_width = w;
5733 graphic_height = h;
5734 graphic_depth = depth;
5736 break;
5737 case QEMU_OPTION_echr:
5739 char *r;
5740 term_escape_char = strtol(optarg, &r, 0);
5741 if (r == optarg)
5742 printf("Bad argument to echr\n");
5743 break;
5745 case QEMU_OPTION_monitor:
5746 monitor_device = optarg;
5747 break;
5748 case QEMU_OPTION_serial:
5749 if (serial_device_index >= MAX_SERIAL_PORTS) {
5750 fprintf(stderr, "qemu: too many serial ports\n");
5751 exit(1);
5753 serial_devices[serial_device_index] = optarg;
5754 serial_device_index++;
5755 break;
5756 case QEMU_OPTION_parallel:
5757 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5758 fprintf(stderr, "qemu: too many parallel ports\n");
5759 exit(1);
5761 parallel_devices[parallel_device_index] = optarg;
5762 parallel_device_index++;
5763 break;
5764 case QEMU_OPTION_loadvm:
5765 loadvm = optarg;
5766 break;
5767 case QEMU_OPTION_full_screen:
5768 full_screen = 1;
5769 break;
5770 #ifdef CONFIG_SDL
5771 case QEMU_OPTION_no_frame:
5772 no_frame = 1;
5773 break;
5774 case QEMU_OPTION_alt_grab:
5775 alt_grab = 1;
5776 break;
5777 case QEMU_OPTION_no_quit:
5778 no_quit = 1;
5779 break;
5780 #endif
5781 case QEMU_OPTION_pidfile:
5782 pid_file = optarg;
5783 break;
5784 #ifdef TARGET_I386
5785 case QEMU_OPTION_win2k_hack:
5786 win2k_install_hack = 1;
5787 break;
5788 #endif
5789 #ifdef USE_KQEMU
5790 case QEMU_OPTION_no_kqemu:
5791 kqemu_allowed = 0;
5792 break;
5793 case QEMU_OPTION_kernel_kqemu:
5794 kqemu_allowed = 2;
5795 break;
5796 #endif
5797 case QEMU_OPTION_usb:
5798 usb_enabled = 1;
5799 break;
5800 case QEMU_OPTION_usbdevice:
5801 usb_enabled = 1;
5802 if (usb_devices_index >= MAX_USB_CMDLINE) {
5803 fprintf(stderr, "Too many USB devices\n");
5804 exit(1);
5806 usb_devices[usb_devices_index] = optarg;
5807 usb_devices_index++;
5808 break;
5809 case QEMU_OPTION_smp:
5810 smp_cpus = atoi(optarg);
5811 if (smp_cpus < 1) {
5812 fprintf(stderr, "Invalid number of CPUs\n");
5813 exit(1);
5815 break;
5816 case QEMU_OPTION_vnc:
5817 vnc_display = optarg;
5818 break;
5819 case QEMU_OPTION_no_acpi:
5820 acpi_enabled = 0;
5821 break;
5822 case QEMU_OPTION_no_reboot:
5823 no_reboot = 1;
5824 break;
5825 case QEMU_OPTION_no_shutdown:
5826 no_shutdown = 1;
5827 break;
5828 case QEMU_OPTION_show_cursor:
5829 cursor_hide = 0;
5830 break;
5831 case QEMU_OPTION_uuid:
5832 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5833 fprintf(stderr, "Fail to parse UUID string."
5834 " Wrong format.\n");
5835 exit(1);
5837 break;
5838 case QEMU_OPTION_daemonize:
5839 daemonize = 1;
5840 break;
5841 case QEMU_OPTION_option_rom:
5842 if (nb_option_roms >= MAX_OPTION_ROMS) {
5843 fprintf(stderr, "Too many option ROMs\n");
5844 exit(1);
5846 option_rom[nb_option_roms] = optarg;
5847 nb_option_roms++;
5848 break;
5849 case QEMU_OPTION_semihosting:
5850 semihosting_enabled = 1;
5851 break;
5852 case QEMU_OPTION_name:
5853 qemu_name = optarg;
5854 break;
5855 #ifdef TARGET_SPARC
5856 case QEMU_OPTION_prom_env:
5857 if (nb_prom_envs >= MAX_PROM_ENVS) {
5858 fprintf(stderr, "Too many prom variables\n");
5859 exit(1);
5861 prom_envs[nb_prom_envs] = optarg;
5862 nb_prom_envs++;
5863 break;
5864 #endif
5865 #ifdef TARGET_ARM
5866 case QEMU_OPTION_old_param:
5867 old_param = 1;
5868 break;
5869 #endif
5870 case QEMU_OPTION_clock:
5871 configure_alarms(optarg);
5872 break;
5873 case QEMU_OPTION_startdate:
5875 struct tm tm;
5876 time_t rtc_start_date;
5877 if (!strcmp(optarg, "now")) {
5878 rtc_date_offset = -1;
5879 } else {
5880 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5881 &tm.tm_year,
5882 &tm.tm_mon,
5883 &tm.tm_mday,
5884 &tm.tm_hour,
5885 &tm.tm_min,
5886 &tm.tm_sec) == 6) {
5887 /* OK */
5888 } else if (sscanf(optarg, "%d-%d-%d",
5889 &tm.tm_year,
5890 &tm.tm_mon,
5891 &tm.tm_mday) == 3) {
5892 tm.tm_hour = 0;
5893 tm.tm_min = 0;
5894 tm.tm_sec = 0;
5895 } else {
5896 goto date_fail;
5898 tm.tm_year -= 1900;
5899 tm.tm_mon--;
5900 rtc_start_date = mktimegm(&tm);
5901 if (rtc_start_date == -1) {
5902 date_fail:
5903 fprintf(stderr, "Invalid date format. Valid format are:\n"
5904 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5905 exit(1);
5907 rtc_date_offset = time(NULL) - rtc_start_date;
5910 break;
5911 case QEMU_OPTION_tb_size:
5912 tb_size = strtol(optarg, NULL, 0);
5913 if (tb_size < 0)
5914 tb_size = 0;
5915 break;
5916 case QEMU_OPTION_icount:
5917 use_icount = 1;
5918 if (strcmp(optarg, "auto") == 0) {
5919 icount_time_shift = -1;
5920 } else {
5921 icount_time_shift = strtol(optarg, NULL, 0);
5923 break;
5924 case QEMU_OPTION_incoming:
5925 incoming = optarg;
5926 break;
5931 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5932 if (smp_cpus > machine->max_cpus) {
5933 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5934 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5935 machine->max_cpus);
5936 exit(1);
5939 if (nographic) {
5940 if (serial_device_index == 0)
5941 serial_devices[0] = "stdio";
5942 if (parallel_device_index == 0)
5943 parallel_devices[0] = "null";
5944 if (strncmp(monitor_device, "vc", 2) == 0)
5945 monitor_device = "stdio";
5948 #ifndef _WIN32
5949 if (daemonize) {
5950 pid_t pid;
5952 if (pipe(fds) == -1)
5953 exit(1);
5955 pid = fork();
5956 if (pid > 0) {
5957 uint8_t status;
5958 ssize_t len;
5960 close(fds[1]);
5962 again:
5963 len = read(fds[0], &status, 1);
5964 if (len == -1 && (errno == EINTR))
5965 goto again;
5967 if (len != 1)
5968 exit(1);
5969 else if (status == 1) {
5970 fprintf(stderr, "Could not acquire pidfile\n");
5971 exit(1);
5972 } else
5973 exit(0);
5974 } else if (pid < 0)
5975 exit(1);
5977 setsid();
5979 pid = fork();
5980 if (pid > 0)
5981 exit(0);
5982 else if (pid < 0)
5983 exit(1);
5985 umask(027);
5987 signal(SIGTSTP, SIG_IGN);
5988 signal(SIGTTOU, SIG_IGN);
5989 signal(SIGTTIN, SIG_IGN);
5991 #endif
5993 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5994 if (daemonize) {
5995 uint8_t status = 1;
5996 write(fds[1], &status, 1);
5997 } else
5998 fprintf(stderr, "Could not acquire pid file\n");
5999 exit(1);
6002 #ifdef USE_KQEMU
6003 if (smp_cpus > 1)
6004 kqemu_allowed = 0;
6005 #endif
6006 linux_boot = (kernel_filename != NULL);
6007 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6009 if (!linux_boot && net_boot == 0 &&
6010 !machine->nodisk_ok && nb_drives_opt == 0)
6011 help(1);
6013 if (!linux_boot && *kernel_cmdline != '\0') {
6014 fprintf(stderr, "-append only allowed with -kernel option\n");
6015 exit(1);
6018 if (!linux_boot && initrd_filename != NULL) {
6019 fprintf(stderr, "-initrd only allowed with -kernel option\n");
6020 exit(1);
6023 /* boot to floppy or the default cd if no hard disk defined yet */
6024 if (!boot_devices[0]) {
6025 boot_devices = "cad";
6027 setvbuf(stdout, NULL, _IOLBF, 0);
6029 init_timers();
6030 init_timer_alarm();
6031 if (use_icount && icount_time_shift < 0) {
6032 use_icount = 2;
6033 /* 125MIPS seems a reasonable initial guess at the guest speed.
6034 It will be corrected fairly quickly anyway. */
6035 icount_time_shift = 3;
6036 init_icount_adjust();
6039 #ifdef _WIN32
6040 socket_init();
6041 #endif
6043 /* init network clients */
6044 if (nb_net_clients == 0) {
6045 /* if no clients, we use a default config */
6046 net_clients[nb_net_clients++] = "nic";
6047 #ifdef CONFIG_SLIRP
6048 net_clients[nb_net_clients++] = "user";
6049 #endif
6052 for(i = 0;i < nb_net_clients; i++) {
6053 if (net_client_parse(net_clients[i]) < 0)
6054 exit(1);
6056 net_client_check();
6058 #ifdef TARGET_I386
6059 /* XXX: this should be moved in the PC machine instantiation code */
6060 if (net_boot != 0) {
6061 int netroms = 0;
6062 for (i = 0; i < nb_nics && i < 4; i++) {
6063 const char *model = nd_table[i].model;
6064 char buf[1024];
6065 if (net_boot & (1 << i)) {
6066 if (model == NULL)
6067 model = "ne2k_pci";
6068 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
6069 if (get_image_size(buf) > 0) {
6070 if (nb_option_roms >= MAX_OPTION_ROMS) {
6071 fprintf(stderr, "Too many option ROMs\n");
6072 exit(1);
6074 option_rom[nb_option_roms] = strdup(buf);
6075 nb_option_roms++;
6076 netroms++;
6080 if (netroms == 0) {
6081 fprintf(stderr, "No valid PXE rom found for network device\n");
6082 exit(1);
6085 #endif
6087 /* init the memory */
6088 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
6090 if (machine->ram_require & RAMSIZE_FIXED) {
6091 if (ram_size > 0) {
6092 if (ram_size < phys_ram_size) {
6093 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
6094 machine->name, (unsigned long long) phys_ram_size);
6095 exit(-1);
6098 phys_ram_size = ram_size;
6099 } else
6100 ram_size = phys_ram_size;
6101 } else {
6102 if (ram_size == 0)
6103 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6105 phys_ram_size += ram_size;
6108 phys_ram_base = qemu_vmalloc(phys_ram_size);
6109 if (!phys_ram_base) {
6110 fprintf(stderr, "Could not allocate physical memory\n");
6111 exit(1);
6114 /* init the dynamic translator */
6115 cpu_exec_init_all(tb_size * 1024 * 1024);
6117 bdrv_init();
6119 /* we always create the cdrom drive, even if no disk is there */
6121 if (nb_drives_opt < MAX_DRIVES)
6122 drive_add(NULL, CDROM_ALIAS);
6124 /* we always create at least one floppy */
6126 if (nb_drives_opt < MAX_DRIVES)
6127 drive_add(NULL, FD_ALIAS, 0);
6129 /* we always create one sd slot, even if no card is in it */
6131 if (nb_drives_opt < MAX_DRIVES)
6132 drive_add(NULL, SD_ALIAS);
6134 /* open the virtual block devices */
6136 for(i = 0; i < nb_drives_opt; i++)
6137 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6138 exit(1);
6140 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6141 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6143 /* terminal init */
6144 memset(&display_state, 0, sizeof(display_state));
6145 if (nographic) {
6146 if (curses) {
6147 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
6148 exit(1);
6150 /* nearly nothing to do */
6151 dumb_display_init(ds);
6152 } else if (vnc_display != NULL) {
6153 vnc_display_init(ds);
6154 if (vnc_display_open(ds, vnc_display) < 0)
6155 exit(1);
6156 } else
6157 #if defined(CONFIG_CURSES)
6158 if (curses) {
6159 curses_display_init(ds, full_screen);
6160 } else
6161 #endif
6163 #if defined(CONFIG_SDL)
6164 sdl_display_init(ds, full_screen, no_frame);
6165 #elif defined(CONFIG_COCOA)
6166 cocoa_display_init(ds, full_screen);
6167 #else
6168 dumb_display_init(ds);
6169 #endif
6172 #ifndef _WIN32
6173 /* must be after terminal init, SDL library changes signal handlers */
6174 termsig_setup();
6175 #endif
6177 /* Maintain compatibility with multiple stdio monitors */
6178 if (!strcmp(monitor_device,"stdio")) {
6179 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6180 const char *devname = serial_devices[i];
6181 if (devname && !strcmp(devname,"mon:stdio")) {
6182 monitor_device = NULL;
6183 break;
6184 } else if (devname && !strcmp(devname,"stdio")) {
6185 monitor_device = NULL;
6186 serial_devices[i] = "mon:stdio";
6187 break;
6191 if (monitor_device) {
6192 monitor_hd = qemu_chr_open("monitor", monitor_device);
6193 if (!monitor_hd) {
6194 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6195 exit(1);
6197 monitor_init(monitor_hd, !nographic);
6200 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6201 const char *devname = serial_devices[i];
6202 if (devname && strcmp(devname, "none")) {
6203 char label[32];
6204 snprintf(label, sizeof(label), "serial%d", i);
6205 serial_hds[i] = qemu_chr_open(label, devname);
6206 if (!serial_hds[i]) {
6207 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6208 devname);
6209 exit(1);
6211 if (strstart(devname, "vc", 0))
6212 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6216 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6217 const char *devname = parallel_devices[i];
6218 if (devname && strcmp(devname, "none")) {
6219 char label[32];
6220 snprintf(label, sizeof(label), "parallel%d", i);
6221 parallel_hds[i] = qemu_chr_open(label, devname);
6222 if (!parallel_hds[i]) {
6223 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6224 devname);
6225 exit(1);
6227 if (strstart(devname, "vc", 0))
6228 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6232 machine->init(ram_size, vga_ram_size, boot_devices, ds,
6233 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6235 /* init USB devices */
6236 if (usb_enabled) {
6237 for(i = 0; i < usb_devices_index; i++) {
6238 if (usb_device_add(usb_devices[i]) < 0) {
6239 fprintf(stderr, "Warning: could not add USB device %s\n",
6240 usb_devices[i]);
6245 if (display_state.dpy_refresh) {
6246 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
6247 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
6250 #ifdef CONFIG_GDBSTUB
6251 if (use_gdbstub) {
6252 /* XXX: use standard host:port notation and modify options
6253 accordingly. */
6254 if (gdbserver_start(gdbstub_port) < 0) {
6255 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6256 gdbstub_port);
6257 exit(1);
6260 #endif
6262 if (loadvm)
6263 do_loadvm(loadvm);
6265 if (incoming) {
6266 autostart = 0; /* fixme how to deal with -daemonize */
6267 qemu_start_incoming_migration(incoming);
6271 /* XXX: simplify init */
6272 read_passwords();
6273 if (autostart) {
6274 vm_start();
6278 if (daemonize) {
6279 uint8_t status = 0;
6280 ssize_t len;
6281 int fd;
6283 again1:
6284 len = write(fds[1], &status, 1);
6285 if (len == -1 && (errno == EINTR))
6286 goto again1;
6288 if (len != 1)
6289 exit(1);
6291 chdir("/");
6292 TFR(fd = open("/dev/null", O_RDWR));
6293 if (fd == -1)
6294 exit(1);
6296 dup2(fd, 0);
6297 dup2(fd, 1);
6298 dup2(fd, 2);
6300 close(fd);
6303 main_loop();
6304 quit_timers();
6305 net_cleanup();
6307 return 0;