target-ppc: Add float register read/write using XML
[qemu/mini2440/sniper_sniper_test.git] / vl.c
blob7df4749ee7ec285f1dc22076cb29ca4de5731e68
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "migration.h"
43 #include "kvm.h"
44 #include "balloon.h"
46 #include <unistd.h>
47 #include <fcntl.h>
48 #include <signal.h>
49 #include <time.h>
50 #include <errno.h>
51 #include <sys/time.h>
52 #include <zlib.h>
54 #ifndef _WIN32
55 #include <sys/times.h>
56 #include <sys/wait.h>
57 #include <termios.h>
58 #include <sys/mman.h>
59 #include <sys/ioctl.h>
60 #include <sys/resource.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <net/if.h>
64 #if defined(__NetBSD__)
65 #include <net/if_tap.h>
66 #endif
67 #ifdef __linux__
68 #include <linux/if_tun.h>
69 #endif
70 #include <arpa/inet.h>
71 #include <dirent.h>
72 #include <netdb.h>
73 #include <sys/select.h>
74 #ifdef _BSD
75 #include <sys/stat.h>
76 #ifdef __FreeBSD__
77 #include <libutil.h>
78 #else
79 #include <util.h>
80 #endif
81 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
82 #include <freebsd/stdlib.h>
83 #else
84 #ifdef __linux__
85 #include <pty.h>
86 #include <malloc.h>
87 #include <linux/rtc.h>
89 /* For the benefit of older linux systems which don't supply it,
90 we use a local copy of hpet.h. */
91 /* #include <linux/hpet.h> */
92 #include "hpet.h"
94 #include <linux/ppdev.h>
95 #include <linux/parport.h>
96 #endif
97 #ifdef __sun__
98 #include <sys/stat.h>
99 #include <sys/ethernet.h>
100 #include <sys/sockio.h>
101 #include <netinet/arp.h>
102 #include <netinet/in.h>
103 #include <netinet/in_systm.h>
104 #include <netinet/ip.h>
105 #include <netinet/ip_icmp.h> // must come after ip.h
106 #include <netinet/udp.h>
107 #include <netinet/tcp.h>
108 #include <net/if.h>
109 #include <syslog.h>
110 #include <stropts.h>
111 #endif
112 #endif
113 #endif
115 #include "qemu_socket.h"
117 #if defined(CONFIG_SLIRP)
118 #include "libslirp.h"
119 #endif
121 #if defined(__OpenBSD__)
122 #include <util.h>
123 #endif
125 #if defined(CONFIG_VDE)
126 #include <libvdeplug.h>
127 #endif
129 #ifdef _WIN32
130 #include <malloc.h>
131 #include <sys/timeb.h>
132 #include <mmsystem.h>
133 #define getopt_long_only getopt_long
134 #define memalign(align, size) malloc(size)
135 #endif
137 #ifdef CONFIG_SDL
138 #ifdef __APPLE__
139 #include <SDL/SDL.h>
140 #endif
141 #endif /* CONFIG_SDL */
143 #ifdef CONFIG_COCOA
144 #undef main
145 #define main qemu_main
146 #endif /* CONFIG_COCOA */
148 #include "disas.h"
150 #include "exec-all.h"
152 //#define DEBUG_UNUSED_IOPORT
153 //#define DEBUG_IOPORT
154 //#define DEBUG_NET
155 //#define DEBUG_SLIRP
158 #ifdef DEBUG_IOPORT
159 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
160 #else
161 # define LOG_IOPORT(...) do { } while (0)
162 #endif
164 #define DEFAULT_RAM_SIZE 128
166 /* Max number of USB devices that can be specified on the commandline. */
167 #define MAX_USB_CMDLINE 8
169 /* Max number of bluetooth switches on the commandline. */
170 #define MAX_BT_CMDLINE 10
172 /* XXX: use a two level table to limit memory usage */
173 #define MAX_IOPORTS 65536
175 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
176 const char *bios_name = NULL;
177 static void *ioport_opaque[MAX_IOPORTS];
178 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
179 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 DriveInfo drives_table[MAX_DRIVES+1];
183 int nb_drives;
184 static int vga_ram_size;
185 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186 static DisplayState *display_state;
187 int nographic;
188 static int curses;
189 static int sdl;
190 const char* keyboard_layout = NULL;
191 int64_t ticks_per_sec;
192 ram_addr_t ram_size;
193 int nb_nics;
194 NICInfo nd_table[MAX_NICS];
195 int vm_running;
196 static int rtc_utc = 1;
197 static int rtc_date_offset = -1; /* -1 means no change */
198 int cirrus_vga_enabled = 1;
199 int std_vga_enabled = 0;
200 int vmsvga_enabled = 0;
201 #ifdef TARGET_SPARC
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
205 #else
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
209 #endif
210 static int full_screen = 0;
211 #ifdef CONFIG_SDL
212 static int no_frame = 0;
213 #endif
214 int no_quit = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
218 #ifdef TARGET_I386
219 int win2k_install_hack = 0;
220 int rtc_td_hack = 0;
221 #endif
222 int usb_enabled = 0;
223 int smp_cpus = 1;
224 const char *vnc_display;
225 int acpi_enabled = 1;
226 int no_hpet = 0;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 int daemonize = 0;
233 const char *option_rom[MAX_OPTION_ROMS];
234 int nb_option_roms;
235 int semihosting_enabled = 0;
236 #ifdef TARGET_ARM
237 int old_param = 0;
238 #endif
239 const char *qemu_name;
240 int alt_grab = 0;
241 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
242 unsigned int nb_prom_envs = 0;
243 const char *prom_envs[MAX_PROM_ENVS];
244 #endif
245 static int nb_drives_opt;
246 static struct drive_opt {
247 const char *file;
248 char opt[1024];
249 } drives_opt[MAX_DRIVES];
251 static CPUState *cur_cpu;
252 static CPUState *next_cpu;
253 static int event_pending = 1;
254 /* Conversion factor from emulated instructions to virtual clock ticks. */
255 static int icount_time_shift;
256 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
257 #define MAX_ICOUNT_SHIFT 10
258 /* Compensate for varying guest execution speed. */
259 static int64_t qemu_icount_bias;
260 static QEMUTimer *icount_rt_timer;
261 static QEMUTimer *icount_vm_timer;
262 static QEMUTimer *nographic_timer;
264 uint8_t qemu_uuid[16];
266 /***********************************************************/
267 /* x86 ISA bus support */
269 target_phys_addr_t isa_mem_base = 0;
270 PicState2 *isa_pic;
272 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
273 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
275 static uint32_t ioport_read(int index, uint32_t address)
277 static IOPortReadFunc *default_func[3] = {
278 default_ioport_readb,
279 default_ioport_readw,
280 default_ioport_readl
282 IOPortReadFunc *func = ioport_read_table[index][address];
283 if (!func)
284 func = default_func[index];
285 return func(ioport_opaque[address], address);
288 static void ioport_write(int index, uint32_t address, uint32_t data)
290 static IOPortWriteFunc *default_func[3] = {
291 default_ioport_writeb,
292 default_ioport_writew,
293 default_ioport_writel
295 IOPortWriteFunc *func = ioport_write_table[index][address];
296 if (!func)
297 func = default_func[index];
298 func(ioport_opaque[address], address, data);
301 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
303 #ifdef DEBUG_UNUSED_IOPORT
304 fprintf(stderr, "unused inb: port=0x%04x\n", address);
305 #endif
306 return 0xff;
309 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
311 #ifdef DEBUG_UNUSED_IOPORT
312 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
313 #endif
316 /* default is to make two byte accesses */
317 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
319 uint32_t data;
320 data = ioport_read(0, address);
321 address = (address + 1) & (MAX_IOPORTS - 1);
322 data |= ioport_read(0, address) << 8;
323 return data;
326 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
328 ioport_write(0, address, data & 0xff);
329 address = (address + 1) & (MAX_IOPORTS - 1);
330 ioport_write(0, address, (data >> 8) & 0xff);
333 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
335 #ifdef DEBUG_UNUSED_IOPORT
336 fprintf(stderr, "unused inl: port=0x%04x\n", address);
337 #endif
338 return 0xffffffff;
341 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
343 #ifdef DEBUG_UNUSED_IOPORT
344 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
345 #endif
348 /* size is the word size in byte */
349 int register_ioport_read(int start, int length, int size,
350 IOPortReadFunc *func, void *opaque)
352 int i, bsize;
354 if (size == 1) {
355 bsize = 0;
356 } else if (size == 2) {
357 bsize = 1;
358 } else if (size == 4) {
359 bsize = 2;
360 } else {
361 hw_error("register_ioport_read: invalid size");
362 return -1;
364 for(i = start; i < start + length; i += size) {
365 ioport_read_table[bsize][i] = func;
366 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
367 hw_error("register_ioport_read: invalid opaque");
368 ioport_opaque[i] = opaque;
370 return 0;
373 /* size is the word size in byte */
374 int register_ioport_write(int start, int length, int size,
375 IOPortWriteFunc *func, void *opaque)
377 int i, bsize;
379 if (size == 1) {
380 bsize = 0;
381 } else if (size == 2) {
382 bsize = 1;
383 } else if (size == 4) {
384 bsize = 2;
385 } else {
386 hw_error("register_ioport_write: invalid size");
387 return -1;
389 for(i = start; i < start + length; i += size) {
390 ioport_write_table[bsize][i] = func;
391 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
392 hw_error("register_ioport_write: invalid opaque");
393 ioport_opaque[i] = opaque;
395 return 0;
398 void isa_unassign_ioport(int start, int length)
400 int i;
402 for(i = start; i < start + length; i++) {
403 ioport_read_table[0][i] = default_ioport_readb;
404 ioport_read_table[1][i] = default_ioport_readw;
405 ioport_read_table[2][i] = default_ioport_readl;
407 ioport_write_table[0][i] = default_ioport_writeb;
408 ioport_write_table[1][i] = default_ioport_writew;
409 ioport_write_table[2][i] = default_ioport_writel;
413 /***********************************************************/
415 void cpu_outb(CPUState *env, int addr, int val)
417 LOG_IOPORT("outb: %04x %02x\n", addr, val);
418 ioport_write(0, addr, val);
419 #ifdef USE_KQEMU
420 if (env)
421 env->last_io_time = cpu_get_time_fast();
422 #endif
425 void cpu_outw(CPUState *env, int addr, int val)
427 LOG_IOPORT("outw: %04x %04x\n", addr, val);
428 ioport_write(1, addr, val);
429 #ifdef USE_KQEMU
430 if (env)
431 env->last_io_time = cpu_get_time_fast();
432 #endif
435 void cpu_outl(CPUState *env, int addr, int val)
437 LOG_IOPORT("outl: %04x %08x\n", addr, val);
438 ioport_write(2, addr, val);
439 #ifdef USE_KQEMU
440 if (env)
441 env->last_io_time = cpu_get_time_fast();
442 #endif
445 int cpu_inb(CPUState *env, int addr)
447 int val;
448 val = ioport_read(0, addr);
449 LOG_IOPORT("inb : %04x %02x\n", addr, val);
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 LOG_IOPORT("inw : %04x %04x\n", addr, val);
462 #ifdef USE_KQEMU
463 if (env)
464 env->last_io_time = cpu_get_time_fast();
465 #endif
466 return val;
469 int cpu_inl(CPUState *env, int addr)
471 int val;
472 val = ioport_read(2, addr);
473 LOG_IOPORT("inl : %04x %08x\n", addr, val);
474 #ifdef USE_KQEMU
475 if (env)
476 env->last_io_time = cpu_get_time_fast();
477 #endif
478 return val;
481 /***********************************************************/
482 void hw_error(const char *fmt, ...)
484 va_list ap;
485 CPUState *env;
487 va_start(ap, fmt);
488 fprintf(stderr, "qemu: hardware error: ");
489 vfprintf(stderr, fmt, ap);
490 fprintf(stderr, "\n");
491 for(env = first_cpu; env != NULL; env = env->next_cpu) {
492 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
493 #ifdef TARGET_I386
494 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
495 #else
496 cpu_dump_state(env, stderr, fprintf, 0);
497 #endif
499 va_end(ap);
500 abort();
503 /***************/
504 /* ballooning */
506 static QEMUBalloonEvent *qemu_balloon_event;
507 void *qemu_balloon_event_opaque;
509 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
511 qemu_balloon_event = func;
512 qemu_balloon_event_opaque = opaque;
515 void qemu_balloon(ram_addr_t target)
517 if (qemu_balloon_event)
518 qemu_balloon_event(qemu_balloon_event_opaque, target);
521 ram_addr_t qemu_balloon_status(void)
523 if (qemu_balloon_event)
524 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
525 return 0;
528 /***********************************************************/
529 /* keyboard/mouse */
531 static QEMUPutKBDEvent *qemu_put_kbd_event;
532 static void *qemu_put_kbd_event_opaque;
533 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
534 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
536 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
538 qemu_put_kbd_event_opaque = opaque;
539 qemu_put_kbd_event = func;
542 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
543 void *opaque, int absolute,
544 const char *name)
546 QEMUPutMouseEntry *s, *cursor;
548 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
549 if (!s)
550 return NULL;
552 s->qemu_put_mouse_event = func;
553 s->qemu_put_mouse_event_opaque = opaque;
554 s->qemu_put_mouse_event_absolute = absolute;
555 s->qemu_put_mouse_event_name = qemu_strdup(name);
556 s->next = NULL;
558 if (!qemu_put_mouse_event_head) {
559 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
560 return s;
563 cursor = qemu_put_mouse_event_head;
564 while (cursor->next != NULL)
565 cursor = cursor->next;
567 cursor->next = s;
568 qemu_put_mouse_event_current = s;
570 return s;
573 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
575 QEMUPutMouseEntry *prev = NULL, *cursor;
577 if (!qemu_put_mouse_event_head || entry == NULL)
578 return;
580 cursor = qemu_put_mouse_event_head;
581 while (cursor != NULL && cursor != entry) {
582 prev = cursor;
583 cursor = cursor->next;
586 if (cursor == NULL) // does not exist or list empty
587 return;
588 else if (prev == NULL) { // entry is head
589 qemu_put_mouse_event_head = cursor->next;
590 if (qemu_put_mouse_event_current == entry)
591 qemu_put_mouse_event_current = cursor->next;
592 qemu_free(entry->qemu_put_mouse_event_name);
593 qemu_free(entry);
594 return;
597 prev->next = entry->next;
599 if (qemu_put_mouse_event_current == entry)
600 qemu_put_mouse_event_current = prev;
602 qemu_free(entry->qemu_put_mouse_event_name);
603 qemu_free(entry);
606 void kbd_put_keycode(int keycode)
608 if (qemu_put_kbd_event) {
609 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
613 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
615 QEMUPutMouseEvent *mouse_event;
616 void *mouse_event_opaque;
617 int width;
619 if (!qemu_put_mouse_event_current) {
620 return;
623 mouse_event =
624 qemu_put_mouse_event_current->qemu_put_mouse_event;
625 mouse_event_opaque =
626 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
628 if (mouse_event) {
629 if (graphic_rotate) {
630 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
631 width = 0x7fff;
632 else
633 width = graphic_width - 1;
634 mouse_event(mouse_event_opaque,
635 width - dy, dx, dz, buttons_state);
636 } else
637 mouse_event(mouse_event_opaque,
638 dx, dy, dz, buttons_state);
642 int kbd_mouse_is_absolute(void)
644 if (!qemu_put_mouse_event_current)
645 return 0;
647 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
650 void do_info_mice(void)
652 QEMUPutMouseEntry *cursor;
653 int index = 0;
655 if (!qemu_put_mouse_event_head) {
656 term_printf("No mouse devices connected\n");
657 return;
660 term_printf("Mouse devices available:\n");
661 cursor = qemu_put_mouse_event_head;
662 while (cursor != NULL) {
663 term_printf("%c Mouse #%d: %s\n",
664 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
665 index, cursor->qemu_put_mouse_event_name);
666 index++;
667 cursor = cursor->next;
671 void do_mouse_set(int index)
673 QEMUPutMouseEntry *cursor;
674 int i = 0;
676 if (!qemu_put_mouse_event_head) {
677 term_printf("No mouse devices connected\n");
678 return;
681 cursor = qemu_put_mouse_event_head;
682 while (cursor != NULL && index != i) {
683 i++;
684 cursor = cursor->next;
687 if (cursor != NULL)
688 qemu_put_mouse_event_current = cursor;
689 else
690 term_printf("Mouse at given index not found\n");
693 /* compute with 96 bit intermediate result: (a*b)/c */
694 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
696 union {
697 uint64_t ll;
698 struct {
699 #ifdef WORDS_BIGENDIAN
700 uint32_t high, low;
701 #else
702 uint32_t low, high;
703 #endif
704 } l;
705 } u, res;
706 uint64_t rl, rh;
708 u.ll = a;
709 rl = (uint64_t)u.l.low * (uint64_t)b;
710 rh = (uint64_t)u.l.high * (uint64_t)b;
711 rh += (rl >> 32);
712 res.l.high = rh / c;
713 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
714 return res.ll;
717 /***********************************************************/
718 /* real time host monotonic timer */
720 #define QEMU_TIMER_BASE 1000000000LL
722 #ifdef WIN32
724 static int64_t clock_freq;
726 static void init_get_clock(void)
728 LARGE_INTEGER freq;
729 int ret;
730 ret = QueryPerformanceFrequency(&freq);
731 if (ret == 0) {
732 fprintf(stderr, "Could not calibrate ticks\n");
733 exit(1);
735 clock_freq = freq.QuadPart;
738 static int64_t get_clock(void)
740 LARGE_INTEGER ti;
741 QueryPerformanceCounter(&ti);
742 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
745 #else
747 static int use_rt_clock;
749 static void init_get_clock(void)
751 use_rt_clock = 0;
752 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
754 struct timespec ts;
755 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
756 use_rt_clock = 1;
759 #endif
762 static int64_t get_clock(void)
764 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
765 if (use_rt_clock) {
766 struct timespec ts;
767 clock_gettime(CLOCK_MONOTONIC, &ts);
768 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
769 } else
770 #endif
772 /* XXX: using gettimeofday leads to problems if the date
773 changes, so it should be avoided. */
774 struct timeval tv;
775 gettimeofday(&tv, NULL);
776 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
779 #endif
781 /* Return the virtual CPU time, based on the instruction counter. */
782 static int64_t cpu_get_icount(void)
784 int64_t icount;
785 CPUState *env = cpu_single_env;;
786 icount = qemu_icount;
787 if (env) {
788 if (!can_do_io(env))
789 fprintf(stderr, "Bad clock read\n");
790 icount -= (env->icount_decr.u16.low + env->icount_extra);
792 return qemu_icount_bias + (icount << icount_time_shift);
795 /***********************************************************/
796 /* guest cycle counter */
798 static int64_t cpu_ticks_prev;
799 static int64_t cpu_ticks_offset;
800 static int64_t cpu_clock_offset;
801 static int cpu_ticks_enabled;
803 /* return the host CPU cycle counter and handle stop/restart */
804 int64_t cpu_get_ticks(void)
806 if (use_icount) {
807 return cpu_get_icount();
809 if (!cpu_ticks_enabled) {
810 return cpu_ticks_offset;
811 } else {
812 int64_t ticks;
813 ticks = cpu_get_real_ticks();
814 if (cpu_ticks_prev > ticks) {
815 /* Note: non increasing ticks may happen if the host uses
816 software suspend */
817 cpu_ticks_offset += cpu_ticks_prev - ticks;
819 cpu_ticks_prev = ticks;
820 return ticks + cpu_ticks_offset;
824 /* return the host CPU monotonic timer and handle stop/restart */
825 static int64_t cpu_get_clock(void)
827 int64_t ti;
828 if (!cpu_ticks_enabled) {
829 return cpu_clock_offset;
830 } else {
831 ti = get_clock();
832 return ti + cpu_clock_offset;
836 /* enable cpu_get_ticks() */
837 void cpu_enable_ticks(void)
839 if (!cpu_ticks_enabled) {
840 cpu_ticks_offset -= cpu_get_real_ticks();
841 cpu_clock_offset -= get_clock();
842 cpu_ticks_enabled = 1;
846 /* disable cpu_get_ticks() : the clock is stopped. You must not call
847 cpu_get_ticks() after that. */
848 void cpu_disable_ticks(void)
850 if (cpu_ticks_enabled) {
851 cpu_ticks_offset = cpu_get_ticks();
852 cpu_clock_offset = cpu_get_clock();
853 cpu_ticks_enabled = 0;
857 /***********************************************************/
858 /* timers */
860 #define QEMU_TIMER_REALTIME 0
861 #define QEMU_TIMER_VIRTUAL 1
863 struct QEMUClock {
864 int type;
865 /* XXX: add frequency */
868 struct QEMUTimer {
869 QEMUClock *clock;
870 int64_t expire_time;
871 QEMUTimerCB *cb;
872 void *opaque;
873 struct QEMUTimer *next;
876 struct qemu_alarm_timer {
877 char const *name;
878 unsigned int flags;
880 int (*start)(struct qemu_alarm_timer *t);
881 void (*stop)(struct qemu_alarm_timer *t);
882 void (*rearm)(struct qemu_alarm_timer *t);
883 void *priv;
886 #define ALARM_FLAG_DYNTICKS 0x1
887 #define ALARM_FLAG_EXPIRED 0x2
889 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
891 return t->flags & ALARM_FLAG_DYNTICKS;
894 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
896 if (!alarm_has_dynticks(t))
897 return;
899 t->rearm(t);
902 /* TODO: MIN_TIMER_REARM_US should be optimized */
903 #define MIN_TIMER_REARM_US 250
905 static struct qemu_alarm_timer *alarm_timer;
906 #ifndef _WIN32
907 static int alarm_timer_rfd, alarm_timer_wfd;
908 #endif
910 #ifdef _WIN32
912 struct qemu_alarm_win32 {
913 MMRESULT timerId;
914 HANDLE host_alarm;
915 unsigned int period;
916 } alarm_win32_data = {0, NULL, -1};
918 static int win32_start_timer(struct qemu_alarm_timer *t);
919 static void win32_stop_timer(struct qemu_alarm_timer *t);
920 static void win32_rearm_timer(struct qemu_alarm_timer *t);
922 #else
924 static int unix_start_timer(struct qemu_alarm_timer *t);
925 static void unix_stop_timer(struct qemu_alarm_timer *t);
927 #ifdef __linux__
929 static int dynticks_start_timer(struct qemu_alarm_timer *t);
930 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
931 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
933 static int hpet_start_timer(struct qemu_alarm_timer *t);
934 static void hpet_stop_timer(struct qemu_alarm_timer *t);
936 static int rtc_start_timer(struct qemu_alarm_timer *t);
937 static void rtc_stop_timer(struct qemu_alarm_timer *t);
939 #endif /* __linux__ */
941 #endif /* _WIN32 */
943 /* Correlation between real and virtual time is always going to be
944 fairly approximate, so ignore small variation.
945 When the guest is idle real and virtual time will be aligned in
946 the IO wait loop. */
947 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
949 static void icount_adjust(void)
951 int64_t cur_time;
952 int64_t cur_icount;
953 int64_t delta;
954 static int64_t last_delta;
955 /* If the VM is not running, then do nothing. */
956 if (!vm_running)
957 return;
959 cur_time = cpu_get_clock();
960 cur_icount = qemu_get_clock(vm_clock);
961 delta = cur_icount - cur_time;
962 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
963 if (delta > 0
964 && last_delta + ICOUNT_WOBBLE < delta * 2
965 && icount_time_shift > 0) {
966 /* The guest is getting too far ahead. Slow time down. */
967 icount_time_shift--;
969 if (delta < 0
970 && last_delta - ICOUNT_WOBBLE > delta * 2
971 && icount_time_shift < MAX_ICOUNT_SHIFT) {
972 /* The guest is getting too far behind. Speed time up. */
973 icount_time_shift++;
975 last_delta = delta;
976 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
979 static void icount_adjust_rt(void * opaque)
981 qemu_mod_timer(icount_rt_timer,
982 qemu_get_clock(rt_clock) + 1000);
983 icount_adjust();
986 static void icount_adjust_vm(void * opaque)
988 qemu_mod_timer(icount_vm_timer,
989 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
990 icount_adjust();
993 static void init_icount_adjust(void)
995 /* Have both realtime and virtual time triggers for speed adjustment.
996 The realtime trigger catches emulated time passing too slowly,
997 the virtual time trigger catches emulated time passing too fast.
998 Realtime triggers occur even when idle, so use them less frequently
999 than VM triggers. */
1000 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1001 qemu_mod_timer(icount_rt_timer,
1002 qemu_get_clock(rt_clock) + 1000);
1003 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1004 qemu_mod_timer(icount_vm_timer,
1005 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1008 static struct qemu_alarm_timer alarm_timers[] = {
1009 #ifndef _WIN32
1010 #ifdef __linux__
1011 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1012 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1013 /* HPET - if available - is preferred */
1014 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1015 /* ...otherwise try RTC */
1016 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1017 #endif
1018 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1019 #else
1020 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1021 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1022 {"win32", 0, win32_start_timer,
1023 win32_stop_timer, NULL, &alarm_win32_data},
1024 #endif
1025 {NULL, }
1028 static void show_available_alarms(void)
1030 int i;
1032 printf("Available alarm timers, in order of precedence:\n");
1033 for (i = 0; alarm_timers[i].name; i++)
1034 printf("%s\n", alarm_timers[i].name);
1037 static void configure_alarms(char const *opt)
1039 int i;
1040 int cur = 0;
1041 int count = ARRAY_SIZE(alarm_timers) - 1;
1042 char *arg;
1043 char *name;
1044 struct qemu_alarm_timer tmp;
1046 if (!strcmp(opt, "?")) {
1047 show_available_alarms();
1048 exit(0);
1051 arg = strdup(opt);
1053 /* Reorder the array */
1054 name = strtok(arg, ",");
1055 while (name) {
1056 for (i = 0; i < count && alarm_timers[i].name; i++) {
1057 if (!strcmp(alarm_timers[i].name, name))
1058 break;
1061 if (i == count) {
1062 fprintf(stderr, "Unknown clock %s\n", name);
1063 goto next;
1066 if (i < cur)
1067 /* Ignore */
1068 goto next;
1070 /* Swap */
1071 tmp = alarm_timers[i];
1072 alarm_timers[i] = alarm_timers[cur];
1073 alarm_timers[cur] = tmp;
1075 cur++;
1076 next:
1077 name = strtok(NULL, ",");
1080 free(arg);
1082 if (cur) {
1083 /* Disable remaining timers */
1084 for (i = cur; i < count; i++)
1085 alarm_timers[i].name = NULL;
1086 } else {
1087 show_available_alarms();
1088 exit(1);
1092 QEMUClock *rt_clock;
1093 QEMUClock *vm_clock;
1095 static QEMUTimer *active_timers[2];
1097 static QEMUClock *qemu_new_clock(int type)
1099 QEMUClock *clock;
1100 clock = qemu_mallocz(sizeof(QEMUClock));
1101 if (!clock)
1102 return NULL;
1103 clock->type = type;
1104 return clock;
1107 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1109 QEMUTimer *ts;
1111 ts = qemu_mallocz(sizeof(QEMUTimer));
1112 ts->clock = clock;
1113 ts->cb = cb;
1114 ts->opaque = opaque;
1115 return ts;
1118 void qemu_free_timer(QEMUTimer *ts)
1120 qemu_free(ts);
1123 /* stop a timer, but do not dealloc it */
1124 void qemu_del_timer(QEMUTimer *ts)
1126 QEMUTimer **pt, *t;
1128 /* NOTE: this code must be signal safe because
1129 qemu_timer_expired() can be called from a signal. */
1130 pt = &active_timers[ts->clock->type];
1131 for(;;) {
1132 t = *pt;
1133 if (!t)
1134 break;
1135 if (t == ts) {
1136 *pt = t->next;
1137 break;
1139 pt = &t->next;
1143 /* modify the current timer so that it will be fired when current_time
1144 >= expire_time. The corresponding callback will be called. */
1145 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1147 QEMUTimer **pt, *t;
1149 qemu_del_timer(ts);
1151 /* add the timer in the sorted list */
1152 /* NOTE: this code must be signal safe because
1153 qemu_timer_expired() can be called from a signal. */
1154 pt = &active_timers[ts->clock->type];
1155 for(;;) {
1156 t = *pt;
1157 if (!t)
1158 break;
1159 if (t->expire_time > expire_time)
1160 break;
1161 pt = &t->next;
1163 ts->expire_time = expire_time;
1164 ts->next = *pt;
1165 *pt = ts;
1167 /* Rearm if necessary */
1168 if (pt == &active_timers[ts->clock->type]) {
1169 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1170 qemu_rearm_alarm_timer(alarm_timer);
1172 /* Interrupt execution to force deadline recalculation. */
1173 if (use_icount && cpu_single_env) {
1174 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1179 int qemu_timer_pending(QEMUTimer *ts)
1181 QEMUTimer *t;
1182 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1183 if (t == ts)
1184 return 1;
1186 return 0;
1189 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1191 if (!timer_head)
1192 return 0;
1193 return (timer_head->expire_time <= current_time);
1196 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1198 QEMUTimer *ts;
1200 for(;;) {
1201 ts = *ptimer_head;
1202 if (!ts || ts->expire_time > current_time)
1203 break;
1204 /* remove timer from the list before calling the callback */
1205 *ptimer_head = ts->next;
1206 ts->next = NULL;
1208 /* run the callback (the timer list can be modified) */
1209 ts->cb(ts->opaque);
1213 int64_t qemu_get_clock(QEMUClock *clock)
1215 switch(clock->type) {
1216 case QEMU_TIMER_REALTIME:
1217 return get_clock() / 1000000;
1218 default:
1219 case QEMU_TIMER_VIRTUAL:
1220 if (use_icount) {
1221 return cpu_get_icount();
1222 } else {
1223 return cpu_get_clock();
1228 static void init_timers(void)
1230 init_get_clock();
1231 ticks_per_sec = QEMU_TIMER_BASE;
1232 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1233 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1236 /* save a timer */
1237 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1239 uint64_t expire_time;
1241 if (qemu_timer_pending(ts)) {
1242 expire_time = ts->expire_time;
1243 } else {
1244 expire_time = -1;
1246 qemu_put_be64(f, expire_time);
1249 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1251 uint64_t expire_time;
1253 expire_time = qemu_get_be64(f);
1254 if (expire_time != -1) {
1255 qemu_mod_timer(ts, expire_time);
1256 } else {
1257 qemu_del_timer(ts);
1261 static void timer_save(QEMUFile *f, void *opaque)
1263 if (cpu_ticks_enabled) {
1264 hw_error("cannot save state if virtual timers are running");
1266 qemu_put_be64(f, cpu_ticks_offset);
1267 qemu_put_be64(f, ticks_per_sec);
1268 qemu_put_be64(f, cpu_clock_offset);
1271 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1273 if (version_id != 1 && version_id != 2)
1274 return -EINVAL;
1275 if (cpu_ticks_enabled) {
1276 return -EINVAL;
1278 cpu_ticks_offset=qemu_get_be64(f);
1279 ticks_per_sec=qemu_get_be64(f);
1280 if (version_id == 2) {
1281 cpu_clock_offset=qemu_get_be64(f);
1283 return 0;
1286 #ifdef _WIN32
1287 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1288 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1289 #else
1290 static void host_alarm_handler(int host_signum)
1291 #endif
1293 #if 0
1294 #define DISP_FREQ 1000
1296 static int64_t delta_min = INT64_MAX;
1297 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1298 static int count;
1299 ti = qemu_get_clock(vm_clock);
1300 if (last_clock != 0) {
1301 delta = ti - last_clock;
1302 if (delta < delta_min)
1303 delta_min = delta;
1304 if (delta > delta_max)
1305 delta_max = delta;
1306 delta_cum += delta;
1307 if (++count == DISP_FREQ) {
1308 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1309 muldiv64(delta_min, 1000000, ticks_per_sec),
1310 muldiv64(delta_max, 1000000, ticks_per_sec),
1311 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1312 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1313 count = 0;
1314 delta_min = INT64_MAX;
1315 delta_max = 0;
1316 delta_cum = 0;
1319 last_clock = ti;
1321 #endif
1322 if (alarm_has_dynticks(alarm_timer) ||
1323 (!use_icount &&
1324 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1325 qemu_get_clock(vm_clock))) ||
1326 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1327 qemu_get_clock(rt_clock))) {
1328 CPUState *env = next_cpu;
1330 #ifdef _WIN32
1331 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1332 SetEvent(data->host_alarm);
1333 #else
1334 static const char byte = 0;
1335 write(alarm_timer_wfd, &byte, sizeof(byte));
1336 #endif
1337 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1339 if (env) {
1340 /* stop the currently executing cpu because a timer occured */
1341 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1342 #ifdef USE_KQEMU
1343 if (env->kqemu_enabled) {
1344 kqemu_cpu_interrupt(env);
1346 #endif
1348 event_pending = 1;
1352 static int64_t qemu_next_deadline(void)
1354 int64_t delta;
1356 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1357 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1358 qemu_get_clock(vm_clock);
1359 } else {
1360 /* To avoid problems with overflow limit this to 2^32. */
1361 delta = INT32_MAX;
1364 if (delta < 0)
1365 delta = 0;
1367 return delta;
1370 #if defined(__linux__) || defined(_WIN32)
1371 static uint64_t qemu_next_deadline_dyntick(void)
1373 int64_t delta;
1374 int64_t rtdelta;
1376 if (use_icount)
1377 delta = INT32_MAX;
1378 else
1379 delta = (qemu_next_deadline() + 999) / 1000;
1381 if (active_timers[QEMU_TIMER_REALTIME]) {
1382 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1383 qemu_get_clock(rt_clock))*1000;
1384 if (rtdelta < delta)
1385 delta = rtdelta;
1388 if (delta < MIN_TIMER_REARM_US)
1389 delta = MIN_TIMER_REARM_US;
1391 return delta;
1393 #endif
1395 #ifndef _WIN32
1397 /* Sets a specific flag */
1398 static int fcntl_setfl(int fd, int flag)
1400 int flags;
1402 flags = fcntl(fd, F_GETFL);
1403 if (flags == -1)
1404 return -errno;
1406 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1407 return -errno;
1409 return 0;
1412 #if defined(__linux__)
1414 #define RTC_FREQ 1024
1416 static void enable_sigio_timer(int fd)
1418 struct sigaction act;
1420 /* timer signal */
1421 sigfillset(&act.sa_mask);
1422 act.sa_flags = 0;
1423 act.sa_handler = host_alarm_handler;
1425 sigaction(SIGIO, &act, NULL);
1426 fcntl_setfl(fd, O_ASYNC);
1427 fcntl(fd, F_SETOWN, getpid());
1430 static int hpet_start_timer(struct qemu_alarm_timer *t)
1432 struct hpet_info info;
1433 int r, fd;
1435 fd = open("/dev/hpet", O_RDONLY);
1436 if (fd < 0)
1437 return -1;
1439 /* Set frequency */
1440 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1441 if (r < 0) {
1442 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1443 "error, but for better emulation accuracy type:\n"
1444 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1445 goto fail;
1448 /* Check capabilities */
1449 r = ioctl(fd, HPET_INFO, &info);
1450 if (r < 0)
1451 goto fail;
1453 /* Enable periodic mode */
1454 r = ioctl(fd, HPET_EPI, 0);
1455 if (info.hi_flags && (r < 0))
1456 goto fail;
1458 /* Enable interrupt */
1459 r = ioctl(fd, HPET_IE_ON, 0);
1460 if (r < 0)
1461 goto fail;
1463 enable_sigio_timer(fd);
1464 t->priv = (void *)(long)fd;
1466 return 0;
1467 fail:
1468 close(fd);
1469 return -1;
1472 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1474 int fd = (long)t->priv;
1476 close(fd);
1479 static int rtc_start_timer(struct qemu_alarm_timer *t)
1481 int rtc_fd;
1482 unsigned long current_rtc_freq = 0;
1484 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1485 if (rtc_fd < 0)
1486 return -1;
1487 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1488 if (current_rtc_freq != RTC_FREQ &&
1489 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1490 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1491 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1492 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1493 goto fail;
1495 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1496 fail:
1497 close(rtc_fd);
1498 return -1;
1501 enable_sigio_timer(rtc_fd);
1503 t->priv = (void *)(long)rtc_fd;
1505 return 0;
1508 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1510 int rtc_fd = (long)t->priv;
1512 close(rtc_fd);
1515 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1517 struct sigevent ev;
1518 timer_t host_timer;
1519 struct sigaction act;
1521 sigfillset(&act.sa_mask);
1522 act.sa_flags = 0;
1523 act.sa_handler = host_alarm_handler;
1525 sigaction(SIGALRM, &act, NULL);
1527 ev.sigev_value.sival_int = 0;
1528 ev.sigev_notify = SIGEV_SIGNAL;
1529 ev.sigev_signo = SIGALRM;
1531 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1532 perror("timer_create");
1534 /* disable dynticks */
1535 fprintf(stderr, "Dynamic Ticks disabled\n");
1537 return -1;
1540 t->priv = (void *)(long)host_timer;
1542 return 0;
1545 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1547 timer_t host_timer = (timer_t)(long)t->priv;
1549 timer_delete(host_timer);
1552 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1554 timer_t host_timer = (timer_t)(long)t->priv;
1555 struct itimerspec timeout;
1556 int64_t nearest_delta_us = INT64_MAX;
1557 int64_t current_us;
1559 if (!active_timers[QEMU_TIMER_REALTIME] &&
1560 !active_timers[QEMU_TIMER_VIRTUAL])
1561 return;
1563 nearest_delta_us = qemu_next_deadline_dyntick();
1565 /* check whether a timer is already running */
1566 if (timer_gettime(host_timer, &timeout)) {
1567 perror("gettime");
1568 fprintf(stderr, "Internal timer error: aborting\n");
1569 exit(1);
1571 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1572 if (current_us && current_us <= nearest_delta_us)
1573 return;
1575 timeout.it_interval.tv_sec = 0;
1576 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1577 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1578 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1579 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1580 perror("settime");
1581 fprintf(stderr, "Internal timer error: aborting\n");
1582 exit(1);
1586 #endif /* defined(__linux__) */
1588 static int unix_start_timer(struct qemu_alarm_timer *t)
1590 struct sigaction act;
1591 struct itimerval itv;
1592 int err;
1594 /* timer signal */
1595 sigfillset(&act.sa_mask);
1596 act.sa_flags = 0;
1597 act.sa_handler = host_alarm_handler;
1599 sigaction(SIGALRM, &act, NULL);
1601 itv.it_interval.tv_sec = 0;
1602 /* for i386 kernel 2.6 to get 1 ms */
1603 itv.it_interval.tv_usec = 999;
1604 itv.it_value.tv_sec = 0;
1605 itv.it_value.tv_usec = 10 * 1000;
1607 err = setitimer(ITIMER_REAL, &itv, NULL);
1608 if (err)
1609 return -1;
1611 return 0;
1614 static void unix_stop_timer(struct qemu_alarm_timer *t)
1616 struct itimerval itv;
1618 memset(&itv, 0, sizeof(itv));
1619 setitimer(ITIMER_REAL, &itv, NULL);
1622 #endif /* !defined(_WIN32) */
1624 static void try_to_rearm_timer(void *opaque)
1626 struct qemu_alarm_timer *t = opaque;
1627 #ifndef _WIN32
1628 ssize_t len;
1630 /* Drain the notify pipe */
1631 do {
1632 char buffer[512];
1633 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1634 } while ((len == -1 && errno == EINTR) || len > 0);
1635 #endif
1637 if (t->flags & ALARM_FLAG_EXPIRED) {
1638 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1639 qemu_rearm_alarm_timer(alarm_timer);
1643 #ifdef _WIN32
1645 static int win32_start_timer(struct qemu_alarm_timer *t)
1647 TIMECAPS tc;
1648 struct qemu_alarm_win32 *data = t->priv;
1649 UINT flags;
1651 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1652 if (!data->host_alarm) {
1653 perror("Failed CreateEvent");
1654 return -1;
1657 memset(&tc, 0, sizeof(tc));
1658 timeGetDevCaps(&tc, sizeof(tc));
1660 if (data->period < tc.wPeriodMin)
1661 data->period = tc.wPeriodMin;
1663 timeBeginPeriod(data->period);
1665 flags = TIME_CALLBACK_FUNCTION;
1666 if (alarm_has_dynticks(t))
1667 flags |= TIME_ONESHOT;
1668 else
1669 flags |= TIME_PERIODIC;
1671 data->timerId = timeSetEvent(1, // interval (ms)
1672 data->period, // resolution
1673 host_alarm_handler, // function
1674 (DWORD)t, // parameter
1675 flags);
1677 if (!data->timerId) {
1678 perror("Failed to initialize win32 alarm timer");
1680 timeEndPeriod(data->period);
1681 CloseHandle(data->host_alarm);
1682 return -1;
1685 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1687 return 0;
1690 static void win32_stop_timer(struct qemu_alarm_timer *t)
1692 struct qemu_alarm_win32 *data = t->priv;
1694 timeKillEvent(data->timerId);
1695 timeEndPeriod(data->period);
1697 CloseHandle(data->host_alarm);
1700 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1702 struct qemu_alarm_win32 *data = t->priv;
1703 uint64_t nearest_delta_us;
1705 if (!active_timers[QEMU_TIMER_REALTIME] &&
1706 !active_timers[QEMU_TIMER_VIRTUAL])
1707 return;
1709 nearest_delta_us = qemu_next_deadline_dyntick();
1710 nearest_delta_us /= 1000;
1712 timeKillEvent(data->timerId);
1714 data->timerId = timeSetEvent(1,
1715 data->period,
1716 host_alarm_handler,
1717 (DWORD)t,
1718 TIME_ONESHOT | TIME_PERIODIC);
1720 if (!data->timerId) {
1721 perror("Failed to re-arm win32 alarm timer");
1723 timeEndPeriod(data->period);
1724 CloseHandle(data->host_alarm);
1725 exit(1);
1729 #endif /* _WIN32 */
1731 static int init_timer_alarm(void)
1733 struct qemu_alarm_timer *t = NULL;
1734 int i, err = -1;
1736 #ifndef _WIN32
1737 int fds[2];
1739 err = pipe(fds);
1740 if (err == -1)
1741 return -errno;
1743 err = fcntl_setfl(fds[0], O_NONBLOCK);
1744 if (err < 0)
1745 goto fail;
1747 err = fcntl_setfl(fds[1], O_NONBLOCK);
1748 if (err < 0)
1749 goto fail;
1751 alarm_timer_rfd = fds[0];
1752 alarm_timer_wfd = fds[1];
1753 #endif
1755 for (i = 0; alarm_timers[i].name; i++) {
1756 t = &alarm_timers[i];
1758 err = t->start(t);
1759 if (!err)
1760 break;
1763 if (err) {
1764 err = -ENOENT;
1765 goto fail;
1768 #ifndef _WIN32
1769 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1770 try_to_rearm_timer, NULL, t);
1771 #endif
1773 alarm_timer = t;
1775 return 0;
1777 fail:
1778 #ifndef _WIN32
1779 close(fds[0]);
1780 close(fds[1]);
1781 #endif
1782 return err;
1785 static void quit_timers(void)
1787 alarm_timer->stop(alarm_timer);
1788 alarm_timer = NULL;
1791 /***********************************************************/
1792 /* host time/date access */
1793 void qemu_get_timedate(struct tm *tm, int offset)
1795 time_t ti;
1796 struct tm *ret;
1798 time(&ti);
1799 ti += offset;
1800 if (rtc_date_offset == -1) {
1801 if (rtc_utc)
1802 ret = gmtime(&ti);
1803 else
1804 ret = localtime(&ti);
1805 } else {
1806 ti -= rtc_date_offset;
1807 ret = gmtime(&ti);
1810 memcpy(tm, ret, sizeof(struct tm));
1813 int qemu_timedate_diff(struct tm *tm)
1815 time_t seconds;
1817 if (rtc_date_offset == -1)
1818 if (rtc_utc)
1819 seconds = mktimegm(tm);
1820 else
1821 seconds = mktime(tm);
1822 else
1823 seconds = mktimegm(tm) + rtc_date_offset;
1825 return seconds - time(NULL);
1828 #ifdef _WIN32
1829 static void socket_cleanup(void)
1831 WSACleanup();
1834 static int socket_init(void)
1836 WSADATA Data;
1837 int ret, err;
1839 ret = WSAStartup(MAKEWORD(2,2), &Data);
1840 if (ret != 0) {
1841 err = WSAGetLastError();
1842 fprintf(stderr, "WSAStartup: %d\n", err);
1843 return -1;
1845 atexit(socket_cleanup);
1846 return 0;
1848 #endif
1850 const char *get_opt_name(char *buf, int buf_size, const char *p)
1852 char *q;
1854 q = buf;
1855 while (*p != '\0' && *p != '=') {
1856 if (q && (q - buf) < buf_size - 1)
1857 *q++ = *p;
1858 p++;
1860 if (q)
1861 *q = '\0';
1863 return p;
1866 const char *get_opt_value(char *buf, int buf_size, const char *p)
1868 char *q;
1870 q = buf;
1871 while (*p != '\0') {
1872 if (*p == ',') {
1873 if (*(p + 1) != ',')
1874 break;
1875 p++;
1877 if (q && (q - buf) < buf_size - 1)
1878 *q++ = *p;
1879 p++;
1881 if (q)
1882 *q = '\0';
1884 return p;
1887 int get_param_value(char *buf, int buf_size,
1888 const char *tag, const char *str)
1890 const char *p;
1891 char option[128];
1893 p = str;
1894 for(;;) {
1895 p = get_opt_name(option, sizeof(option), p);
1896 if (*p != '=')
1897 break;
1898 p++;
1899 if (!strcmp(tag, option)) {
1900 (void)get_opt_value(buf, buf_size, p);
1901 return strlen(buf);
1902 } else {
1903 p = get_opt_value(NULL, 0, p);
1905 if (*p != ',')
1906 break;
1907 p++;
1909 return 0;
1912 int check_params(char *buf, int buf_size,
1913 const char * const *params, const char *str)
1915 const char *p;
1916 int i;
1918 p = str;
1919 for(;;) {
1920 p = get_opt_name(buf, buf_size, p);
1921 if (*p != '=')
1922 return -1;
1923 p++;
1924 for(i = 0; params[i] != NULL; i++)
1925 if (!strcmp(params[i], buf))
1926 break;
1927 if (params[i] == NULL)
1928 return -1;
1929 p = get_opt_value(NULL, 0, p);
1930 if (*p != ',')
1931 break;
1932 p++;
1934 return 0;
1937 /***********************************************************/
1938 /* Bluetooth support */
1939 static int nb_hcis;
1940 static int cur_hci;
1941 static struct HCIInfo *hci_table[MAX_NICS];
1943 static struct bt_vlan_s {
1944 struct bt_scatternet_s net;
1945 int id;
1946 struct bt_vlan_s *next;
1947 } *first_bt_vlan;
1949 /* find or alloc a new bluetooth "VLAN" */
1950 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1952 struct bt_vlan_s **pvlan, *vlan;
1953 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1954 if (vlan->id == id)
1955 return &vlan->net;
1957 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1958 vlan->id = id;
1959 pvlan = &first_bt_vlan;
1960 while (*pvlan != NULL)
1961 pvlan = &(*pvlan)->next;
1962 *pvlan = vlan;
1963 return &vlan->net;
1966 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1970 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1972 return -ENOTSUP;
1975 static struct HCIInfo null_hci = {
1976 .cmd_send = null_hci_send,
1977 .sco_send = null_hci_send,
1978 .acl_send = null_hci_send,
1979 .bdaddr_set = null_hci_addr_set,
1982 struct HCIInfo *qemu_next_hci(void)
1984 if (cur_hci == nb_hcis)
1985 return &null_hci;
1987 return hci_table[cur_hci++];
1990 static struct HCIInfo *hci_init(const char *str)
1992 char *endp;
1993 struct bt_scatternet_s *vlan = 0;
1995 if (!strcmp(str, "null"))
1996 /* null */
1997 return &null_hci;
1998 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1999 /* host[:hciN] */
2000 return bt_host_hci(str[4] ? str + 5 : "hci0");
2001 else if (!strncmp(str, "hci", 3)) {
2002 /* hci[,vlan=n] */
2003 if (str[3]) {
2004 if (!strncmp(str + 3, ",vlan=", 6)) {
2005 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2006 if (*endp)
2007 vlan = 0;
2009 } else
2010 vlan = qemu_find_bt_vlan(0);
2011 if (vlan)
2012 return bt_new_hci(vlan);
2015 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2017 return 0;
2020 static int bt_hci_parse(const char *str)
2022 struct HCIInfo *hci;
2023 bdaddr_t bdaddr;
2025 if (nb_hcis >= MAX_NICS) {
2026 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2027 return -1;
2030 hci = hci_init(str);
2031 if (!hci)
2032 return -1;
2034 bdaddr.b[0] = 0x52;
2035 bdaddr.b[1] = 0x54;
2036 bdaddr.b[2] = 0x00;
2037 bdaddr.b[3] = 0x12;
2038 bdaddr.b[4] = 0x34;
2039 bdaddr.b[5] = 0x56 + nb_hcis;
2040 hci->bdaddr_set(hci, bdaddr.b);
2042 hci_table[nb_hcis++] = hci;
2044 return 0;
2047 static void bt_vhci_add(int vlan_id)
2049 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2051 if (!vlan->slave)
2052 fprintf(stderr, "qemu: warning: adding a VHCI to "
2053 "an empty scatternet %i\n", vlan_id);
2055 bt_vhci_init(bt_new_hci(vlan));
2058 static struct bt_device_s *bt_device_add(const char *opt)
2060 struct bt_scatternet_s *vlan;
2061 int vlan_id = 0;
2062 char *endp = strstr(opt, ",vlan=");
2063 int len = (endp ? endp - opt : strlen(opt)) + 1;
2064 char devname[10];
2066 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2068 if (endp) {
2069 vlan_id = strtol(endp + 6, &endp, 0);
2070 if (*endp) {
2071 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2072 return 0;
2076 vlan = qemu_find_bt_vlan(vlan_id);
2078 if (!vlan->slave)
2079 fprintf(stderr, "qemu: warning: adding a slave device to "
2080 "an empty scatternet %i\n", vlan_id);
2082 if (!strcmp(devname, "keyboard"))
2083 return bt_keyboard_init(vlan);
2085 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2086 return 0;
2089 static int bt_parse(const char *opt)
2091 const char *endp, *p;
2092 int vlan;
2094 if (strstart(opt, "hci", &endp)) {
2095 if (!*endp || *endp == ',') {
2096 if (*endp)
2097 if (!strstart(endp, ",vlan=", 0))
2098 opt = endp + 1;
2100 return bt_hci_parse(opt);
2102 } else if (strstart(opt, "vhci", &endp)) {
2103 if (!*endp || *endp == ',') {
2104 if (*endp) {
2105 if (strstart(endp, ",vlan=", &p)) {
2106 vlan = strtol(p, (char **) &endp, 0);
2107 if (*endp) {
2108 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2109 return 1;
2111 } else {
2112 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2113 return 1;
2115 } else
2116 vlan = 0;
2118 bt_vhci_add(vlan);
2119 return 0;
2121 } else if (strstart(opt, "device:", &endp))
2122 return !bt_device_add(endp);
2124 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2125 return 1;
2128 /***********************************************************/
2129 /* QEMU Block devices */
2131 #define HD_ALIAS "index=%d,media=disk"
2132 #ifdef TARGET_PPC
2133 #define CDROM_ALIAS "index=1,media=cdrom"
2134 #else
2135 #define CDROM_ALIAS "index=2,media=cdrom"
2136 #endif
2137 #define FD_ALIAS "index=%d,if=floppy"
2138 #define PFLASH_ALIAS "if=pflash"
2139 #define MTD_ALIAS "if=mtd"
2140 #define SD_ALIAS "index=0,if=sd"
2142 static int drive_add(const char *file, const char *fmt, ...)
2144 va_list ap;
2146 if (nb_drives_opt >= MAX_DRIVES) {
2147 fprintf(stderr, "qemu: too many drives\n");
2148 exit(1);
2151 drives_opt[nb_drives_opt].file = file;
2152 va_start(ap, fmt);
2153 vsnprintf(drives_opt[nb_drives_opt].opt,
2154 sizeof(drives_opt[0].opt), fmt, ap);
2155 va_end(ap);
2157 return nb_drives_opt++;
2160 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2162 int index;
2164 /* seek interface, bus and unit */
2166 for (index = 0; index < nb_drives; index++)
2167 if (drives_table[index].type == type &&
2168 drives_table[index].bus == bus &&
2169 drives_table[index].unit == unit)
2170 return index;
2172 return -1;
2175 int drive_get_max_bus(BlockInterfaceType type)
2177 int max_bus;
2178 int index;
2180 max_bus = -1;
2181 for (index = 0; index < nb_drives; index++) {
2182 if(drives_table[index].type == type &&
2183 drives_table[index].bus > max_bus)
2184 max_bus = drives_table[index].bus;
2186 return max_bus;
2189 const char *drive_get_serial(BlockDriverState *bdrv)
2191 int index;
2193 for (index = 0; index < nb_drives; index++)
2194 if (drives_table[index].bdrv == bdrv)
2195 return drives_table[index].serial;
2197 return "\0";
2200 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2202 int index;
2204 for (index = 0; index < nb_drives; index++)
2205 if (drives_table[index].bdrv == bdrv)
2206 return drives_table[index].onerror;
2208 return BLOCK_ERR_REPORT;
2211 static void bdrv_format_print(void *opaque, const char *name)
2213 fprintf(stderr, " %s", name);
2216 static int drive_init(struct drive_opt *arg, int snapshot,
2217 QEMUMachine *machine)
2219 char buf[128];
2220 char file[1024];
2221 char devname[128];
2222 char serial[21];
2223 const char *mediastr = "";
2224 BlockInterfaceType type;
2225 enum { MEDIA_DISK, MEDIA_CDROM } media;
2226 int bus_id, unit_id;
2227 int cyls, heads, secs, translation;
2228 BlockDriverState *bdrv;
2229 BlockDriver *drv = NULL;
2230 int max_devs;
2231 int index;
2232 int cache;
2233 int bdrv_flags, onerror;
2234 char *str = arg->opt;
2235 static const char * const params[] = { "bus", "unit", "if", "index",
2236 "cyls", "heads", "secs", "trans",
2237 "media", "snapshot", "file",
2238 "cache", "format", "serial", "werror",
2239 NULL };
2241 if (check_params(buf, sizeof(buf), params, str) < 0) {
2242 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2243 buf, str);
2244 return -1;
2247 file[0] = 0;
2248 cyls = heads = secs = 0;
2249 bus_id = 0;
2250 unit_id = -1;
2251 translation = BIOS_ATA_TRANSLATION_AUTO;
2252 index = -1;
2253 cache = 3;
2255 if (machine->use_scsi) {
2256 type = IF_SCSI;
2257 max_devs = MAX_SCSI_DEVS;
2258 pstrcpy(devname, sizeof(devname), "scsi");
2259 } else {
2260 type = IF_IDE;
2261 max_devs = MAX_IDE_DEVS;
2262 pstrcpy(devname, sizeof(devname), "ide");
2264 media = MEDIA_DISK;
2266 /* extract parameters */
2268 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2269 bus_id = strtol(buf, NULL, 0);
2270 if (bus_id < 0) {
2271 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2272 return -1;
2276 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2277 unit_id = strtol(buf, NULL, 0);
2278 if (unit_id < 0) {
2279 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2280 return -1;
2284 if (get_param_value(buf, sizeof(buf), "if", str)) {
2285 pstrcpy(devname, sizeof(devname), buf);
2286 if (!strcmp(buf, "ide")) {
2287 type = IF_IDE;
2288 max_devs = MAX_IDE_DEVS;
2289 } else if (!strcmp(buf, "scsi")) {
2290 type = IF_SCSI;
2291 max_devs = MAX_SCSI_DEVS;
2292 } else if (!strcmp(buf, "floppy")) {
2293 type = IF_FLOPPY;
2294 max_devs = 0;
2295 } else if (!strcmp(buf, "pflash")) {
2296 type = IF_PFLASH;
2297 max_devs = 0;
2298 } else if (!strcmp(buf, "mtd")) {
2299 type = IF_MTD;
2300 max_devs = 0;
2301 } else if (!strcmp(buf, "sd")) {
2302 type = IF_SD;
2303 max_devs = 0;
2304 } else if (!strcmp(buf, "virtio")) {
2305 type = IF_VIRTIO;
2306 max_devs = 0;
2307 } else {
2308 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2309 return -1;
2313 if (get_param_value(buf, sizeof(buf), "index", str)) {
2314 index = strtol(buf, NULL, 0);
2315 if (index < 0) {
2316 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2317 return -1;
2321 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2322 cyls = strtol(buf, NULL, 0);
2325 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2326 heads = strtol(buf, NULL, 0);
2329 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2330 secs = strtol(buf, NULL, 0);
2333 if (cyls || heads || secs) {
2334 if (cyls < 1 || cyls > 16383) {
2335 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2336 return -1;
2338 if (heads < 1 || heads > 16) {
2339 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2340 return -1;
2342 if (secs < 1 || secs > 63) {
2343 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2344 return -1;
2348 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2349 if (!cyls) {
2350 fprintf(stderr,
2351 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2352 str);
2353 return -1;
2355 if (!strcmp(buf, "none"))
2356 translation = BIOS_ATA_TRANSLATION_NONE;
2357 else if (!strcmp(buf, "lba"))
2358 translation = BIOS_ATA_TRANSLATION_LBA;
2359 else if (!strcmp(buf, "auto"))
2360 translation = BIOS_ATA_TRANSLATION_AUTO;
2361 else {
2362 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2363 return -1;
2367 if (get_param_value(buf, sizeof(buf), "media", str)) {
2368 if (!strcmp(buf, "disk")) {
2369 media = MEDIA_DISK;
2370 } else if (!strcmp(buf, "cdrom")) {
2371 if (cyls || secs || heads) {
2372 fprintf(stderr,
2373 "qemu: '%s' invalid physical CHS format\n", str);
2374 return -1;
2376 media = MEDIA_CDROM;
2377 } else {
2378 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2379 return -1;
2383 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2384 if (!strcmp(buf, "on"))
2385 snapshot = 1;
2386 else if (!strcmp(buf, "off"))
2387 snapshot = 0;
2388 else {
2389 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2390 return -1;
2394 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2395 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2396 cache = 0;
2397 else if (!strcmp(buf, "writethrough"))
2398 cache = 1;
2399 else if (!strcmp(buf, "writeback"))
2400 cache = 2;
2401 else {
2402 fprintf(stderr, "qemu: invalid cache option\n");
2403 return -1;
2407 if (get_param_value(buf, sizeof(buf), "format", str)) {
2408 if (strcmp(buf, "?") == 0) {
2409 fprintf(stderr, "qemu: Supported formats:");
2410 bdrv_iterate_format(bdrv_format_print, NULL);
2411 fprintf(stderr, "\n");
2412 return -1;
2414 drv = bdrv_find_format(buf);
2415 if (!drv) {
2416 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2417 return -1;
2421 if (arg->file == NULL)
2422 get_param_value(file, sizeof(file), "file", str);
2423 else
2424 pstrcpy(file, sizeof(file), arg->file);
2426 if (!get_param_value(serial, sizeof(serial), "serial", str))
2427 memset(serial, 0, sizeof(serial));
2429 onerror = BLOCK_ERR_REPORT;
2430 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2431 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2432 fprintf(stderr, "werror is no supported by this format\n");
2433 return -1;
2435 if (!strcmp(buf, "ignore"))
2436 onerror = BLOCK_ERR_IGNORE;
2437 else if (!strcmp(buf, "enospc"))
2438 onerror = BLOCK_ERR_STOP_ENOSPC;
2439 else if (!strcmp(buf, "stop"))
2440 onerror = BLOCK_ERR_STOP_ANY;
2441 else if (!strcmp(buf, "report"))
2442 onerror = BLOCK_ERR_REPORT;
2443 else {
2444 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2445 return -1;
2449 /* compute bus and unit according index */
2451 if (index != -1) {
2452 if (bus_id != 0 || unit_id != -1) {
2453 fprintf(stderr,
2454 "qemu: '%s' index cannot be used with bus and unit\n", str);
2455 return -1;
2457 if (max_devs == 0)
2459 unit_id = index;
2460 bus_id = 0;
2461 } else {
2462 unit_id = index % max_devs;
2463 bus_id = index / max_devs;
2467 /* if user doesn't specify a unit_id,
2468 * try to find the first free
2471 if (unit_id == -1) {
2472 unit_id = 0;
2473 while (drive_get_index(type, bus_id, unit_id) != -1) {
2474 unit_id++;
2475 if (max_devs && unit_id >= max_devs) {
2476 unit_id -= max_devs;
2477 bus_id++;
2482 /* check unit id */
2484 if (max_devs && unit_id >= max_devs) {
2485 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2486 str, unit_id, max_devs - 1);
2487 return -1;
2491 * ignore multiple definitions
2494 if (drive_get_index(type, bus_id, unit_id) != -1)
2495 return 0;
2497 /* init */
2499 if (type == IF_IDE || type == IF_SCSI)
2500 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2501 if (max_devs)
2502 snprintf(buf, sizeof(buf), "%s%i%s%i",
2503 devname, bus_id, mediastr, unit_id);
2504 else
2505 snprintf(buf, sizeof(buf), "%s%s%i",
2506 devname, mediastr, unit_id);
2507 bdrv = bdrv_new(buf);
2508 drives_table[nb_drives].bdrv = bdrv;
2509 drives_table[nb_drives].type = type;
2510 drives_table[nb_drives].bus = bus_id;
2511 drives_table[nb_drives].unit = unit_id;
2512 drives_table[nb_drives].onerror = onerror;
2513 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2514 nb_drives++;
2516 switch(type) {
2517 case IF_IDE:
2518 case IF_SCSI:
2519 switch(media) {
2520 case MEDIA_DISK:
2521 if (cyls != 0) {
2522 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2523 bdrv_set_translation_hint(bdrv, translation);
2525 break;
2526 case MEDIA_CDROM:
2527 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2528 break;
2530 break;
2531 case IF_SD:
2532 /* FIXME: This isn't really a floppy, but it's a reasonable
2533 approximation. */
2534 case IF_FLOPPY:
2535 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2536 break;
2537 case IF_PFLASH:
2538 case IF_MTD:
2539 case IF_VIRTIO:
2540 break;
2542 if (!file[0])
2543 return 0;
2544 bdrv_flags = 0;
2545 if (snapshot) {
2546 bdrv_flags |= BDRV_O_SNAPSHOT;
2547 cache = 2; /* always use write-back with snapshot */
2549 if (cache == 0) /* no caching */
2550 bdrv_flags |= BDRV_O_NOCACHE;
2551 else if (cache == 2) /* write-back */
2552 bdrv_flags |= BDRV_O_CACHE_WB;
2553 else if (cache == 3) /* not specified */
2554 bdrv_flags |= BDRV_O_CACHE_DEF;
2555 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2556 fprintf(stderr, "qemu: could not open disk image %s\n",
2557 file);
2558 return -1;
2560 return 0;
2563 /***********************************************************/
2564 /* USB devices */
2566 static USBPort *used_usb_ports;
2567 static USBPort *free_usb_ports;
2569 /* ??? Maybe change this to register a hub to keep track of the topology. */
2570 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2571 usb_attachfn attach)
2573 port->opaque = opaque;
2574 port->index = index;
2575 port->attach = attach;
2576 port->next = free_usb_ports;
2577 free_usb_ports = port;
2580 int usb_device_add_dev(USBDevice *dev)
2582 USBPort *port;
2584 /* Find a USB port to add the device to. */
2585 port = free_usb_ports;
2586 if (!port->next) {
2587 USBDevice *hub;
2589 /* Create a new hub and chain it on. */
2590 free_usb_ports = NULL;
2591 port->next = used_usb_ports;
2592 used_usb_ports = port;
2594 hub = usb_hub_init(VM_USB_HUB_SIZE);
2595 usb_attach(port, hub);
2596 port = free_usb_ports;
2599 free_usb_ports = port->next;
2600 port->next = used_usb_ports;
2601 used_usb_ports = port;
2602 usb_attach(port, dev);
2603 return 0;
2606 static int usb_device_add(const char *devname)
2608 const char *p;
2609 USBDevice *dev;
2611 if (!free_usb_ports)
2612 return -1;
2614 if (strstart(devname, "host:", &p)) {
2615 dev = usb_host_device_open(p);
2616 } else if (!strcmp(devname, "mouse")) {
2617 dev = usb_mouse_init();
2618 } else if (!strcmp(devname, "tablet")) {
2619 dev = usb_tablet_init();
2620 } else if (!strcmp(devname, "keyboard")) {
2621 dev = usb_keyboard_init();
2622 } else if (strstart(devname, "disk:", &p)) {
2623 dev = usb_msd_init(p);
2624 } else if (!strcmp(devname, "wacom-tablet")) {
2625 dev = usb_wacom_init();
2626 } else if (strstart(devname, "serial:", &p)) {
2627 dev = usb_serial_init(p);
2628 #ifdef CONFIG_BRLAPI
2629 } else if (!strcmp(devname, "braille")) {
2630 dev = usb_baum_init();
2631 #endif
2632 } else if (strstart(devname, "net:", &p)) {
2633 int nic = nb_nics;
2635 if (net_client_init("nic", p) < 0)
2636 return -1;
2637 nd_table[nic].model = "usb";
2638 dev = usb_net_init(&nd_table[nic]);
2639 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2640 dev = usb_bt_init(devname[2] ? hci_init(p) :
2641 bt_new_hci(qemu_find_bt_vlan(0)));
2642 } else {
2643 return -1;
2645 if (!dev)
2646 return -1;
2648 return usb_device_add_dev(dev);
2651 int usb_device_del_addr(int bus_num, int addr)
2653 USBPort *port;
2654 USBPort **lastp;
2655 USBDevice *dev;
2657 if (!used_usb_ports)
2658 return -1;
2660 if (bus_num != 0)
2661 return -1;
2663 lastp = &used_usb_ports;
2664 port = used_usb_ports;
2665 while (port && port->dev->addr != addr) {
2666 lastp = &port->next;
2667 port = port->next;
2670 if (!port)
2671 return -1;
2673 dev = port->dev;
2674 *lastp = port->next;
2675 usb_attach(port, NULL);
2676 dev->handle_destroy(dev);
2677 port->next = free_usb_ports;
2678 free_usb_ports = port;
2679 return 0;
2682 static int usb_device_del(const char *devname)
2684 int bus_num, addr;
2685 const char *p;
2687 if (strstart(devname, "host:", &p))
2688 return usb_host_device_close(p);
2690 if (!used_usb_ports)
2691 return -1;
2693 p = strchr(devname, '.');
2694 if (!p)
2695 return -1;
2696 bus_num = strtoul(devname, NULL, 0);
2697 addr = strtoul(p + 1, NULL, 0);
2699 return usb_device_del_addr(bus_num, addr);
2702 void do_usb_add(const char *devname)
2704 usb_device_add(devname);
2707 void do_usb_del(const char *devname)
2709 usb_device_del(devname);
2712 void usb_info(void)
2714 USBDevice *dev;
2715 USBPort *port;
2716 const char *speed_str;
2718 if (!usb_enabled) {
2719 term_printf("USB support not enabled\n");
2720 return;
2723 for (port = used_usb_ports; port; port = port->next) {
2724 dev = port->dev;
2725 if (!dev)
2726 continue;
2727 switch(dev->speed) {
2728 case USB_SPEED_LOW:
2729 speed_str = "1.5";
2730 break;
2731 case USB_SPEED_FULL:
2732 speed_str = "12";
2733 break;
2734 case USB_SPEED_HIGH:
2735 speed_str = "480";
2736 break;
2737 default:
2738 speed_str = "?";
2739 break;
2741 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2742 0, dev->addr, speed_str, dev->devname);
2746 /***********************************************************/
2747 /* PCMCIA/Cardbus */
2749 static struct pcmcia_socket_entry_s {
2750 struct pcmcia_socket_s *socket;
2751 struct pcmcia_socket_entry_s *next;
2752 } *pcmcia_sockets = 0;
2754 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2756 struct pcmcia_socket_entry_s *entry;
2758 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2759 entry->socket = socket;
2760 entry->next = pcmcia_sockets;
2761 pcmcia_sockets = entry;
2764 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2766 struct pcmcia_socket_entry_s *entry, **ptr;
2768 ptr = &pcmcia_sockets;
2769 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2770 if (entry->socket == socket) {
2771 *ptr = entry->next;
2772 qemu_free(entry);
2776 void pcmcia_info(void)
2778 struct pcmcia_socket_entry_s *iter;
2779 if (!pcmcia_sockets)
2780 term_printf("No PCMCIA sockets\n");
2782 for (iter = pcmcia_sockets; iter; iter = iter->next)
2783 term_printf("%s: %s\n", iter->socket->slot_string,
2784 iter->socket->attached ? iter->socket->card_string :
2785 "Empty");
2788 /***********************************************************/
2789 /* register display */
2791 void register_displaystate(DisplayState *ds)
2793 DisplayState **s;
2794 s = &display_state;
2795 while (*s != NULL)
2796 s = &(*s)->next;
2797 ds->next = NULL;
2798 *s = ds;
2801 DisplayState *get_displaystate(void)
2803 return display_state;
2806 /* dumb display */
2808 static void dumb_display_init(void)
2810 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2811 if (ds == NULL) {
2812 fprintf(stderr, "dumb_display_init: DisplayState allocation failed\n");
2813 exit(1);
2815 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2816 register_displaystate(ds);
2819 /***********************************************************/
2820 /* I/O handling */
2822 #define MAX_IO_HANDLERS 64
2824 typedef struct IOHandlerRecord {
2825 int fd;
2826 IOCanRWHandler *fd_read_poll;
2827 IOHandler *fd_read;
2828 IOHandler *fd_write;
2829 int deleted;
2830 void *opaque;
2831 /* temporary data */
2832 struct pollfd *ufd;
2833 struct IOHandlerRecord *next;
2834 } IOHandlerRecord;
2836 static IOHandlerRecord *first_io_handler;
2838 /* XXX: fd_read_poll should be suppressed, but an API change is
2839 necessary in the character devices to suppress fd_can_read(). */
2840 int qemu_set_fd_handler2(int fd,
2841 IOCanRWHandler *fd_read_poll,
2842 IOHandler *fd_read,
2843 IOHandler *fd_write,
2844 void *opaque)
2846 IOHandlerRecord **pioh, *ioh;
2848 if (!fd_read && !fd_write) {
2849 pioh = &first_io_handler;
2850 for(;;) {
2851 ioh = *pioh;
2852 if (ioh == NULL)
2853 break;
2854 if (ioh->fd == fd) {
2855 ioh->deleted = 1;
2856 break;
2858 pioh = &ioh->next;
2860 } else {
2861 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2862 if (ioh->fd == fd)
2863 goto found;
2865 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2866 if (!ioh)
2867 return -1;
2868 ioh->next = first_io_handler;
2869 first_io_handler = ioh;
2870 found:
2871 ioh->fd = fd;
2872 ioh->fd_read_poll = fd_read_poll;
2873 ioh->fd_read = fd_read;
2874 ioh->fd_write = fd_write;
2875 ioh->opaque = opaque;
2876 ioh->deleted = 0;
2878 return 0;
2881 int qemu_set_fd_handler(int fd,
2882 IOHandler *fd_read,
2883 IOHandler *fd_write,
2884 void *opaque)
2886 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2889 #ifdef _WIN32
2890 /***********************************************************/
2891 /* Polling handling */
2893 typedef struct PollingEntry {
2894 PollingFunc *func;
2895 void *opaque;
2896 struct PollingEntry *next;
2897 } PollingEntry;
2899 static PollingEntry *first_polling_entry;
2901 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2903 PollingEntry **ppe, *pe;
2904 pe = qemu_mallocz(sizeof(PollingEntry));
2905 if (!pe)
2906 return -1;
2907 pe->func = func;
2908 pe->opaque = opaque;
2909 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2910 *ppe = pe;
2911 return 0;
2914 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2916 PollingEntry **ppe, *pe;
2917 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2918 pe = *ppe;
2919 if (pe->func == func && pe->opaque == opaque) {
2920 *ppe = pe->next;
2921 qemu_free(pe);
2922 break;
2927 /***********************************************************/
2928 /* Wait objects support */
2929 typedef struct WaitObjects {
2930 int num;
2931 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2932 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2933 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2934 } WaitObjects;
2936 static WaitObjects wait_objects = {0};
2938 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2940 WaitObjects *w = &wait_objects;
2942 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2943 return -1;
2944 w->events[w->num] = handle;
2945 w->func[w->num] = func;
2946 w->opaque[w->num] = opaque;
2947 w->num++;
2948 return 0;
2951 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2953 int i, found;
2954 WaitObjects *w = &wait_objects;
2956 found = 0;
2957 for (i = 0; i < w->num; i++) {
2958 if (w->events[i] == handle)
2959 found = 1;
2960 if (found) {
2961 w->events[i] = w->events[i + 1];
2962 w->func[i] = w->func[i + 1];
2963 w->opaque[i] = w->opaque[i + 1];
2966 if (found)
2967 w->num--;
2969 #endif
2971 /***********************************************************/
2972 /* ram save/restore */
2974 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2976 int v;
2978 v = qemu_get_byte(f);
2979 switch(v) {
2980 case 0:
2981 if (qemu_get_buffer(f, buf, len) != len)
2982 return -EIO;
2983 break;
2984 case 1:
2985 v = qemu_get_byte(f);
2986 memset(buf, v, len);
2987 break;
2988 default:
2989 return -EINVAL;
2992 if (qemu_file_has_error(f))
2993 return -EIO;
2995 return 0;
2998 static int ram_load_v1(QEMUFile *f, void *opaque)
3000 int ret;
3001 ram_addr_t i;
3003 if (qemu_get_be32(f) != phys_ram_size)
3004 return -EINVAL;
3005 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3006 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3007 if (ret)
3008 return ret;
3010 return 0;
3013 #define BDRV_HASH_BLOCK_SIZE 1024
3014 #define IOBUF_SIZE 4096
3015 #define RAM_CBLOCK_MAGIC 0xfabe
3017 typedef struct RamDecompressState {
3018 z_stream zstream;
3019 QEMUFile *f;
3020 uint8_t buf[IOBUF_SIZE];
3021 } RamDecompressState;
3023 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3025 int ret;
3026 memset(s, 0, sizeof(*s));
3027 s->f = f;
3028 ret = inflateInit(&s->zstream);
3029 if (ret != Z_OK)
3030 return -1;
3031 return 0;
3034 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3036 int ret, clen;
3038 s->zstream.avail_out = len;
3039 s->zstream.next_out = buf;
3040 while (s->zstream.avail_out > 0) {
3041 if (s->zstream.avail_in == 0) {
3042 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3043 return -1;
3044 clen = qemu_get_be16(s->f);
3045 if (clen > IOBUF_SIZE)
3046 return -1;
3047 qemu_get_buffer(s->f, s->buf, clen);
3048 s->zstream.avail_in = clen;
3049 s->zstream.next_in = s->buf;
3051 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3052 if (ret != Z_OK && ret != Z_STREAM_END) {
3053 return -1;
3056 return 0;
3059 static void ram_decompress_close(RamDecompressState *s)
3061 inflateEnd(&s->zstream);
3064 #define RAM_SAVE_FLAG_FULL 0x01
3065 #define RAM_SAVE_FLAG_COMPRESS 0x02
3066 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3067 #define RAM_SAVE_FLAG_PAGE 0x08
3068 #define RAM_SAVE_FLAG_EOS 0x10
3070 static int is_dup_page(uint8_t *page, uint8_t ch)
3072 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3073 uint32_t *array = (uint32_t *)page;
3074 int i;
3076 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3077 if (array[i] != val)
3078 return 0;
3081 return 1;
3084 static int ram_save_block(QEMUFile *f)
3086 static ram_addr_t current_addr = 0;
3087 ram_addr_t saved_addr = current_addr;
3088 ram_addr_t addr = 0;
3089 int found = 0;
3091 while (addr < phys_ram_size) {
3092 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3093 uint8_t ch;
3095 cpu_physical_memory_reset_dirty(current_addr,
3096 current_addr + TARGET_PAGE_SIZE,
3097 MIGRATION_DIRTY_FLAG);
3099 ch = *(phys_ram_base + current_addr);
3101 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3102 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3103 qemu_put_byte(f, ch);
3104 } else {
3105 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3106 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3109 found = 1;
3110 break;
3112 addr += TARGET_PAGE_SIZE;
3113 current_addr = (saved_addr + addr) % phys_ram_size;
3116 return found;
3119 static ram_addr_t ram_save_threshold = 10;
3121 static ram_addr_t ram_save_remaining(void)
3123 ram_addr_t addr;
3124 ram_addr_t count = 0;
3126 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3127 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3128 count++;
3131 return count;
3134 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3136 ram_addr_t addr;
3138 if (stage == 1) {
3139 /* Make sure all dirty bits are set */
3140 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3141 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3142 cpu_physical_memory_set_dirty(addr);
3145 /* Enable dirty memory tracking */
3146 cpu_physical_memory_set_dirty_tracking(1);
3148 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3151 while (!qemu_file_rate_limit(f)) {
3152 int ret;
3154 ret = ram_save_block(f);
3155 if (ret == 0) /* no more blocks */
3156 break;
3159 /* try transferring iterative blocks of memory */
3161 if (stage == 3) {
3162 cpu_physical_memory_set_dirty_tracking(0);
3164 /* flush all remaining blocks regardless of rate limiting */
3165 while (ram_save_block(f) != 0);
3168 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3170 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3173 static int ram_load_dead(QEMUFile *f, void *opaque)
3175 RamDecompressState s1, *s = &s1;
3176 uint8_t buf[10];
3177 ram_addr_t i;
3179 if (ram_decompress_open(s, f) < 0)
3180 return -EINVAL;
3181 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3182 if (ram_decompress_buf(s, buf, 1) < 0) {
3183 fprintf(stderr, "Error while reading ram block header\n");
3184 goto error;
3186 if (buf[0] == 0) {
3187 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3188 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3189 goto error;
3191 } else {
3192 error:
3193 printf("Error block header\n");
3194 return -EINVAL;
3197 ram_decompress_close(s);
3199 return 0;
3202 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3204 ram_addr_t addr;
3205 int flags;
3207 if (version_id == 1)
3208 return ram_load_v1(f, opaque);
3210 if (version_id == 2) {
3211 if (qemu_get_be32(f) != phys_ram_size)
3212 return -EINVAL;
3213 return ram_load_dead(f, opaque);
3216 if (version_id != 3)
3217 return -EINVAL;
3219 do {
3220 addr = qemu_get_be64(f);
3222 flags = addr & ~TARGET_PAGE_MASK;
3223 addr &= TARGET_PAGE_MASK;
3225 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3226 if (addr != phys_ram_size)
3227 return -EINVAL;
3230 if (flags & RAM_SAVE_FLAG_FULL) {
3231 if (ram_load_dead(f, opaque) < 0)
3232 return -EINVAL;
3235 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3236 uint8_t ch = qemu_get_byte(f);
3237 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3238 } else if (flags & RAM_SAVE_FLAG_PAGE)
3239 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3240 } while (!(flags & RAM_SAVE_FLAG_EOS));
3242 return 0;
3245 void qemu_service_io(void)
3247 CPUState *env = cpu_single_env;
3248 if (env) {
3249 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3250 #ifdef USE_KQEMU
3251 if (env->kqemu_enabled) {
3252 kqemu_cpu_interrupt(env);
3254 #endif
3258 /***********************************************************/
3259 /* bottom halves (can be seen as timers which expire ASAP) */
3261 struct QEMUBH {
3262 QEMUBHFunc *cb;
3263 void *opaque;
3264 int scheduled;
3265 int idle;
3266 int deleted;
3267 QEMUBH *next;
3270 static QEMUBH *first_bh = NULL;
3272 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3274 QEMUBH *bh;
3275 bh = qemu_mallocz(sizeof(QEMUBH));
3276 if (!bh)
3277 return NULL;
3278 bh->cb = cb;
3279 bh->opaque = opaque;
3280 bh->next = first_bh;
3281 first_bh = bh;
3282 return bh;
3285 int qemu_bh_poll(void)
3287 QEMUBH *bh, **bhp;
3288 int ret;
3290 ret = 0;
3291 for (bh = first_bh; bh; bh = bh->next) {
3292 if (!bh->deleted && bh->scheduled) {
3293 bh->scheduled = 0;
3294 if (!bh->idle)
3295 ret = 1;
3296 bh->idle = 0;
3297 bh->cb(bh->opaque);
3301 /* remove deleted bhs */
3302 bhp = &first_bh;
3303 while (*bhp) {
3304 bh = *bhp;
3305 if (bh->deleted) {
3306 *bhp = bh->next;
3307 qemu_free(bh);
3308 } else
3309 bhp = &bh->next;
3312 return ret;
3315 void qemu_bh_schedule_idle(QEMUBH *bh)
3317 if (bh->scheduled)
3318 return;
3319 bh->scheduled = 1;
3320 bh->idle = 1;
3323 void qemu_bh_schedule(QEMUBH *bh)
3325 CPUState *env = cpu_single_env;
3326 if (bh->scheduled)
3327 return;
3328 bh->scheduled = 1;
3329 bh->idle = 0;
3330 /* stop the currently executing CPU to execute the BH ASAP */
3331 if (env) {
3332 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3336 void qemu_bh_cancel(QEMUBH *bh)
3338 bh->scheduled = 0;
3341 void qemu_bh_delete(QEMUBH *bh)
3343 bh->scheduled = 0;
3344 bh->deleted = 1;
3347 static void qemu_bh_update_timeout(int *timeout)
3349 QEMUBH *bh;
3351 for (bh = first_bh; bh; bh = bh->next) {
3352 if (!bh->deleted && bh->scheduled) {
3353 if (bh->idle) {
3354 /* idle bottom halves will be polled at least
3355 * every 10ms */
3356 *timeout = MIN(10, *timeout);
3357 } else {
3358 /* non-idle bottom halves will be executed
3359 * immediately */
3360 *timeout = 0;
3361 break;
3367 /***********************************************************/
3368 /* machine registration */
3370 static QEMUMachine *first_machine = NULL;
3372 int qemu_register_machine(QEMUMachine *m)
3374 QEMUMachine **pm;
3375 pm = &first_machine;
3376 while (*pm != NULL)
3377 pm = &(*pm)->next;
3378 m->next = NULL;
3379 *pm = m;
3380 return 0;
3383 static QEMUMachine *find_machine(const char *name)
3385 QEMUMachine *m;
3387 for(m = first_machine; m != NULL; m = m->next) {
3388 if (!strcmp(m->name, name))
3389 return m;
3391 return NULL;
3394 /***********************************************************/
3395 /* main execution loop */
3397 static void gui_update(void *opaque)
3399 uint64_t interval = GUI_REFRESH_INTERVAL;
3400 DisplayState *ds = opaque;
3401 DisplayChangeListener *dcl = ds->listeners;
3403 dpy_refresh(ds);
3405 while (dcl != NULL) {
3406 if (dcl->gui_timer_interval &&
3407 dcl->gui_timer_interval < interval)
3408 interval = dcl->gui_timer_interval;
3409 dcl = dcl->next;
3411 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3414 static void nographic_update(void *opaque)
3416 uint64_t interval = GUI_REFRESH_INTERVAL;
3418 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3421 struct vm_change_state_entry {
3422 VMChangeStateHandler *cb;
3423 void *opaque;
3424 LIST_ENTRY (vm_change_state_entry) entries;
3427 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3429 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3430 void *opaque)
3432 VMChangeStateEntry *e;
3434 e = qemu_mallocz(sizeof (*e));
3435 if (!e)
3436 return NULL;
3438 e->cb = cb;
3439 e->opaque = opaque;
3440 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3441 return e;
3444 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3446 LIST_REMOVE (e, entries);
3447 qemu_free (e);
3450 static void vm_state_notify(int running, int reason)
3452 VMChangeStateEntry *e;
3454 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3455 e->cb(e->opaque, running, reason);
3459 void vm_start(void)
3461 if (!vm_running) {
3462 cpu_enable_ticks();
3463 vm_running = 1;
3464 vm_state_notify(1, 0);
3465 qemu_rearm_alarm_timer(alarm_timer);
3469 void vm_stop(int reason)
3471 if (vm_running) {
3472 cpu_disable_ticks();
3473 vm_running = 0;
3474 vm_state_notify(0, reason);
3478 /* reset/shutdown handler */
3480 typedef struct QEMUResetEntry {
3481 QEMUResetHandler *func;
3482 void *opaque;
3483 struct QEMUResetEntry *next;
3484 } QEMUResetEntry;
3486 static QEMUResetEntry *first_reset_entry;
3487 static int reset_requested;
3488 static int shutdown_requested;
3489 static int powerdown_requested;
3491 int qemu_shutdown_requested(void)
3493 int r = shutdown_requested;
3494 shutdown_requested = 0;
3495 return r;
3498 int qemu_reset_requested(void)
3500 int r = reset_requested;
3501 reset_requested = 0;
3502 return r;
3505 int qemu_powerdown_requested(void)
3507 int r = powerdown_requested;
3508 powerdown_requested = 0;
3509 return r;
3512 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3514 QEMUResetEntry **pre, *re;
3516 pre = &first_reset_entry;
3517 while (*pre != NULL)
3518 pre = &(*pre)->next;
3519 re = qemu_mallocz(sizeof(QEMUResetEntry));
3520 re->func = func;
3521 re->opaque = opaque;
3522 re->next = NULL;
3523 *pre = re;
3526 void qemu_system_reset(void)
3528 QEMUResetEntry *re;
3530 /* reset all devices */
3531 for(re = first_reset_entry; re != NULL; re = re->next) {
3532 re->func(re->opaque);
3536 void qemu_system_reset_request(void)
3538 if (no_reboot) {
3539 shutdown_requested = 1;
3540 } else {
3541 reset_requested = 1;
3543 if (cpu_single_env)
3544 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3547 void qemu_system_shutdown_request(void)
3549 shutdown_requested = 1;
3550 if (cpu_single_env)
3551 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3554 void qemu_system_powerdown_request(void)
3556 powerdown_requested = 1;
3557 if (cpu_single_env)
3558 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3561 #ifdef _WIN32
3562 static void host_main_loop_wait(int *timeout)
3564 int ret, ret2, i;
3565 PollingEntry *pe;
3568 /* XXX: need to suppress polling by better using win32 events */
3569 ret = 0;
3570 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3571 ret |= pe->func(pe->opaque);
3573 if (ret == 0) {
3574 int err;
3575 WaitObjects *w = &wait_objects;
3577 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3578 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3579 if (w->func[ret - WAIT_OBJECT_0])
3580 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3582 /* Check for additional signaled events */
3583 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3585 /* Check if event is signaled */
3586 ret2 = WaitForSingleObject(w->events[i], 0);
3587 if(ret2 == WAIT_OBJECT_0) {
3588 if (w->func[i])
3589 w->func[i](w->opaque[i]);
3590 } else if (ret2 == WAIT_TIMEOUT) {
3591 } else {
3592 err = GetLastError();
3593 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3596 } else if (ret == WAIT_TIMEOUT) {
3597 } else {
3598 err = GetLastError();
3599 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3603 *timeout = 0;
3605 #else
3606 static void host_main_loop_wait(int *timeout)
3609 #endif
3611 void main_loop_wait(int timeout)
3613 IOHandlerRecord *ioh;
3614 fd_set rfds, wfds, xfds;
3615 int ret, nfds;
3616 struct timeval tv;
3618 qemu_bh_update_timeout(&timeout);
3620 host_main_loop_wait(&timeout);
3622 /* poll any events */
3623 /* XXX: separate device handlers from system ones */
3624 nfds = -1;
3625 FD_ZERO(&rfds);
3626 FD_ZERO(&wfds);
3627 FD_ZERO(&xfds);
3628 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3629 if (ioh->deleted)
3630 continue;
3631 if (ioh->fd_read &&
3632 (!ioh->fd_read_poll ||
3633 ioh->fd_read_poll(ioh->opaque) != 0)) {
3634 FD_SET(ioh->fd, &rfds);
3635 if (ioh->fd > nfds)
3636 nfds = ioh->fd;
3638 if (ioh->fd_write) {
3639 FD_SET(ioh->fd, &wfds);
3640 if (ioh->fd > nfds)
3641 nfds = ioh->fd;
3645 tv.tv_sec = timeout / 1000;
3646 tv.tv_usec = (timeout % 1000) * 1000;
3648 #if defined(CONFIG_SLIRP)
3649 if (slirp_is_inited()) {
3650 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3652 #endif
3653 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3654 if (ret > 0) {
3655 IOHandlerRecord **pioh;
3657 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3658 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3659 ioh->fd_read(ioh->opaque);
3661 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3662 ioh->fd_write(ioh->opaque);
3666 /* remove deleted IO handlers */
3667 pioh = &first_io_handler;
3668 while (*pioh) {
3669 ioh = *pioh;
3670 if (ioh->deleted) {
3671 *pioh = ioh->next;
3672 qemu_free(ioh);
3673 } else
3674 pioh = &ioh->next;
3677 #if defined(CONFIG_SLIRP)
3678 if (slirp_is_inited()) {
3679 if (ret < 0) {
3680 FD_ZERO(&rfds);
3681 FD_ZERO(&wfds);
3682 FD_ZERO(&xfds);
3684 slirp_select_poll(&rfds, &wfds, &xfds);
3686 #endif
3688 /* vm time timers */
3689 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3690 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3691 qemu_get_clock(vm_clock));
3693 /* real time timers */
3694 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3695 qemu_get_clock(rt_clock));
3697 /* Check bottom-halves last in case any of the earlier events triggered
3698 them. */
3699 qemu_bh_poll();
3703 static int main_loop(void)
3705 int ret, timeout;
3706 #ifdef CONFIG_PROFILER
3707 int64_t ti;
3708 #endif
3709 CPUState *env;
3711 cur_cpu = first_cpu;
3712 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3713 for(;;) {
3714 if (vm_running) {
3716 for(;;) {
3717 /* get next cpu */
3718 env = next_cpu;
3719 #ifdef CONFIG_PROFILER
3720 ti = profile_getclock();
3721 #endif
3722 if (use_icount) {
3723 int64_t count;
3724 int decr;
3725 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3726 env->icount_decr.u16.low = 0;
3727 env->icount_extra = 0;
3728 count = qemu_next_deadline();
3729 count = (count + (1 << icount_time_shift) - 1)
3730 >> icount_time_shift;
3731 qemu_icount += count;
3732 decr = (count > 0xffff) ? 0xffff : count;
3733 count -= decr;
3734 env->icount_decr.u16.low = decr;
3735 env->icount_extra = count;
3737 ret = cpu_exec(env);
3738 #ifdef CONFIG_PROFILER
3739 qemu_time += profile_getclock() - ti;
3740 #endif
3741 if (use_icount) {
3742 /* Fold pending instructions back into the
3743 instruction counter, and clear the interrupt flag. */
3744 qemu_icount -= (env->icount_decr.u16.low
3745 + env->icount_extra);
3746 env->icount_decr.u32 = 0;
3747 env->icount_extra = 0;
3749 next_cpu = env->next_cpu ?: first_cpu;
3750 if (event_pending && likely(ret != EXCP_DEBUG)) {
3751 ret = EXCP_INTERRUPT;
3752 event_pending = 0;
3753 break;
3755 if (ret == EXCP_HLT) {
3756 /* Give the next CPU a chance to run. */
3757 cur_cpu = env;
3758 continue;
3760 if (ret != EXCP_HALTED)
3761 break;
3762 /* all CPUs are halted ? */
3763 if (env == cur_cpu)
3764 break;
3766 cur_cpu = env;
3768 if (shutdown_requested) {
3769 ret = EXCP_INTERRUPT;
3770 if (no_shutdown) {
3771 vm_stop(0);
3772 no_shutdown = 0;
3774 else
3775 break;
3777 if (reset_requested) {
3778 reset_requested = 0;
3779 qemu_system_reset();
3780 ret = EXCP_INTERRUPT;
3782 if (powerdown_requested) {
3783 powerdown_requested = 0;
3784 qemu_system_powerdown();
3785 ret = EXCP_INTERRUPT;
3787 if (unlikely(ret == EXCP_DEBUG)) {
3788 gdb_set_stop_cpu(cur_cpu);
3789 vm_stop(EXCP_DEBUG);
3791 /* If all cpus are halted then wait until the next IRQ */
3792 /* XXX: use timeout computed from timers */
3793 if (ret == EXCP_HALTED) {
3794 if (use_icount) {
3795 int64_t add;
3796 int64_t delta;
3797 /* Advance virtual time to the next event. */
3798 if (use_icount == 1) {
3799 /* When not using an adaptive execution frequency
3800 we tend to get badly out of sync with real time,
3801 so just delay for a reasonable amount of time. */
3802 delta = 0;
3803 } else {
3804 delta = cpu_get_icount() - cpu_get_clock();
3806 if (delta > 0) {
3807 /* If virtual time is ahead of real time then just
3808 wait for IO. */
3809 timeout = (delta / 1000000) + 1;
3810 } else {
3811 /* Wait for either IO to occur or the next
3812 timer event. */
3813 add = qemu_next_deadline();
3814 /* We advance the timer before checking for IO.
3815 Limit the amount we advance so that early IO
3816 activity won't get the guest too far ahead. */
3817 if (add > 10000000)
3818 add = 10000000;
3819 delta += add;
3820 add = (add + (1 << icount_time_shift) - 1)
3821 >> icount_time_shift;
3822 qemu_icount += add;
3823 timeout = delta / 1000000;
3824 if (timeout < 0)
3825 timeout = 0;
3827 } else {
3828 timeout = 5000;
3830 } else {
3831 timeout = 0;
3833 } else {
3834 if (shutdown_requested) {
3835 ret = EXCP_INTERRUPT;
3836 break;
3838 timeout = 5000;
3840 #ifdef CONFIG_PROFILER
3841 ti = profile_getclock();
3842 #endif
3843 main_loop_wait(timeout);
3844 #ifdef CONFIG_PROFILER
3845 dev_time += profile_getclock() - ti;
3846 #endif
3848 cpu_disable_ticks();
3849 return ret;
3852 static void help(int exitcode)
3854 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3855 "usage: %s [options] [disk_image]\n"
3856 "\n"
3857 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3858 "\n"
3859 "Standard options:\n"
3860 "-M machine select emulated machine (-M ? for list)\n"
3861 "-cpu cpu select CPU (-cpu ? for list)\n"
3862 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3863 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3864 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3865 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3866 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3867 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3868 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3869 " use 'file' as a drive image\n"
3870 "-mtdblock file use 'file' as on-board Flash memory image\n"
3871 "-sd file use 'file' as SecureDigital card image\n"
3872 "-pflash file use 'file' as a parallel flash image\n"
3873 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3874 "-snapshot write to temporary files instead of disk image files\n"
3875 #ifdef CONFIG_SDL
3876 "-no-frame open SDL window without a frame and window decorations\n"
3877 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3878 "-no-quit disable SDL window close capability\n"
3879 "-sdl enable SDL\n"
3880 #endif
3881 #ifdef TARGET_I386
3882 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3883 #endif
3884 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3885 "-smp n set the number of CPUs to 'n' [default=1]\n"
3886 "-nographic disable graphical output and redirect serial I/Os to console\n"
3887 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3888 #ifndef _WIN32
3889 "-k language use keyboard layout (for example \"fr\" for French)\n"
3890 #endif
3891 #ifdef HAS_AUDIO
3892 "-audio-help print list of audio drivers and their options\n"
3893 "-soundhw c1,... enable audio support\n"
3894 " and only specified sound cards (comma separated list)\n"
3895 " use -soundhw ? to get the list of supported cards\n"
3896 " use -soundhw all to enable all of them\n"
3897 #endif
3898 "-vga [std|cirrus|vmware|none]\n"
3899 " select video card type\n"
3900 "-localtime set the real time clock to local time [default=utc]\n"
3901 "-full-screen start in full screen\n"
3902 #ifdef TARGET_I386
3903 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3904 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
3905 #endif
3906 "-usb enable the USB driver (will be the default soon)\n"
3907 "-usbdevice name add the host or guest USB device 'name'\n"
3908 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3909 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3910 #endif
3911 "-name string set the name of the guest\n"
3912 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
3913 "\n"
3914 "Network options:\n"
3915 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3916 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3917 #ifdef CONFIG_SLIRP
3918 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3919 " connect the user mode network stack to VLAN 'n' and send\n"
3920 " hostname 'host' to DHCP clients\n"
3921 #endif
3922 #ifdef _WIN32
3923 "-net tap[,vlan=n][,name=str],ifname=name\n"
3924 " connect the host TAP network interface to VLAN 'n'\n"
3925 #else
3926 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3927 " connect the host TAP network interface to VLAN 'n' and use the\n"
3928 " network scripts 'file' (default=%s)\n"
3929 " and 'dfile' (default=%s);\n"
3930 " use '[down]script=no' to disable script execution;\n"
3931 " use 'fd=h' to connect to an already opened TAP interface\n"
3932 #endif
3933 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3934 " connect the vlan 'n' to another VLAN using a socket connection\n"
3935 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
3936 " connect the vlan 'n' to multicast maddr and port\n"
3937 #ifdef CONFIG_VDE
3938 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3939 " connect the vlan 'n' to port 'n' of a vde switch running\n"
3940 " on host and listening for incoming connections on 'socketpath'.\n"
3941 " Use group 'groupname' and mode 'octalmode' to change default\n"
3942 " ownership and permissions for communication port.\n"
3943 #endif
3944 "-net none use it alone to have zero network devices; if no -net option\n"
3945 " is provided, the default is '-net nic -net user'\n"
3946 "\n"
3947 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
3948 "-bt hci,host[:id]\n"
3949 " Use host's HCI with the given name\n"
3950 "-bt hci[,vlan=n]\n"
3951 " Emulate a standard HCI in virtual scatternet 'n'\n"
3952 "-bt vhci[,vlan=n]\n"
3953 " Add host computer to virtual scatternet 'n' using VHCI\n"
3954 "-bt device:dev[,vlan=n]\n"
3955 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
3956 "\n"
3957 #ifdef CONFIG_SLIRP
3958 "-tftp dir allow tftp access to files in dir [-net user]\n"
3959 "-bootp file advertise file in BOOTP replies\n"
3960 #ifndef _WIN32
3961 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3962 #endif
3963 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3964 " redirect TCP or UDP connections from host to guest [-net user]\n"
3965 #endif
3966 "\n"
3967 "Linux boot specific:\n"
3968 "-kernel bzImage use 'bzImage' as kernel image\n"
3969 "-append cmdline use 'cmdline' as kernel command line\n"
3970 "-initrd file use 'file' as initial ram disk\n"
3971 "\n"
3972 "Debug/Expert options:\n"
3973 "-monitor dev redirect the monitor to char device 'dev'\n"
3974 "-serial dev redirect the serial port to char device 'dev'\n"
3975 "-parallel dev redirect the parallel port to char device 'dev'\n"
3976 "-pidfile file Write PID to 'file'\n"
3977 "-S freeze CPU at startup (use 'c' to start execution)\n"
3978 "-s wait gdb connection to port\n"
3979 "-p port set gdb connection port [default=%s]\n"
3980 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
3981 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
3982 " translation (t=none or lba) (usually qemu can guess them)\n"
3983 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
3984 #ifdef USE_KQEMU
3985 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
3986 "-no-kqemu disable KQEMU kernel module usage\n"
3987 #endif
3988 #ifdef CONFIG_KVM
3989 "-enable-kvm enable KVM full virtualization support\n"
3990 #endif
3991 #ifdef TARGET_I386
3992 "-no-acpi disable ACPI\n"
3993 "-no-hpet disable HPET\n"
3994 #endif
3995 #ifdef CONFIG_CURSES
3996 "-curses use a curses/ncurses interface instead of SDL\n"
3997 #endif
3998 "-no-reboot exit instead of rebooting\n"
3999 "-no-shutdown stop before shutdown\n"
4000 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
4001 "-vnc display start a VNC server on display\n"
4002 #ifndef _WIN32
4003 "-daemonize daemonize QEMU after initializing\n"
4004 #endif
4005 "-option-rom rom load a file, rom, into the option ROM space\n"
4006 #ifdef TARGET_SPARC
4007 "-prom-env variable=value set OpenBIOS nvram variables\n"
4008 #endif
4009 "-clock force the use of the given methods for timer alarm.\n"
4010 " To see what timers are available use -clock ?\n"
4011 "-startdate select initial date of the clock\n"
4012 "-icount [N|auto]\n"
4013 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4014 "\n"
4015 "During emulation, the following keys are useful:\n"
4016 "ctrl-alt-f toggle full screen\n"
4017 "ctrl-alt-n switch to virtual console 'n'\n"
4018 "ctrl-alt toggle mouse and keyboard grab\n"
4019 "\n"
4020 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4022 "qemu",
4023 DEFAULT_RAM_SIZE,
4024 #ifndef _WIN32
4025 DEFAULT_NETWORK_SCRIPT,
4026 DEFAULT_NETWORK_DOWN_SCRIPT,
4027 #endif
4028 DEFAULT_GDBSTUB_PORT,
4029 "/tmp/qemu.log");
4030 exit(exitcode);
4033 #define HAS_ARG 0x0001
4035 enum {
4036 QEMU_OPTION_h,
4038 QEMU_OPTION_M,
4039 QEMU_OPTION_cpu,
4040 QEMU_OPTION_fda,
4041 QEMU_OPTION_fdb,
4042 QEMU_OPTION_hda,
4043 QEMU_OPTION_hdb,
4044 QEMU_OPTION_hdc,
4045 QEMU_OPTION_hdd,
4046 QEMU_OPTION_drive,
4047 QEMU_OPTION_cdrom,
4048 QEMU_OPTION_mtdblock,
4049 QEMU_OPTION_sd,
4050 QEMU_OPTION_pflash,
4051 QEMU_OPTION_boot,
4052 QEMU_OPTION_snapshot,
4053 #ifdef TARGET_I386
4054 QEMU_OPTION_no_fd_bootchk,
4055 #endif
4056 QEMU_OPTION_m,
4057 QEMU_OPTION_nographic,
4058 QEMU_OPTION_portrait,
4059 #ifdef HAS_AUDIO
4060 QEMU_OPTION_audio_help,
4061 QEMU_OPTION_soundhw,
4062 #endif
4064 QEMU_OPTION_net,
4065 QEMU_OPTION_tftp,
4066 QEMU_OPTION_bootp,
4067 QEMU_OPTION_smb,
4068 QEMU_OPTION_redir,
4069 QEMU_OPTION_bt,
4071 QEMU_OPTION_kernel,
4072 QEMU_OPTION_append,
4073 QEMU_OPTION_initrd,
4075 QEMU_OPTION_S,
4076 QEMU_OPTION_s,
4077 QEMU_OPTION_p,
4078 QEMU_OPTION_d,
4079 QEMU_OPTION_hdachs,
4080 QEMU_OPTION_L,
4081 QEMU_OPTION_bios,
4082 QEMU_OPTION_k,
4083 QEMU_OPTION_localtime,
4084 QEMU_OPTION_g,
4085 QEMU_OPTION_vga,
4086 QEMU_OPTION_echr,
4087 QEMU_OPTION_monitor,
4088 QEMU_OPTION_serial,
4089 QEMU_OPTION_virtiocon,
4090 QEMU_OPTION_parallel,
4091 QEMU_OPTION_loadvm,
4092 QEMU_OPTION_full_screen,
4093 QEMU_OPTION_no_frame,
4094 QEMU_OPTION_alt_grab,
4095 QEMU_OPTION_no_quit,
4096 QEMU_OPTION_sdl,
4097 QEMU_OPTION_pidfile,
4098 QEMU_OPTION_no_kqemu,
4099 QEMU_OPTION_kernel_kqemu,
4100 QEMU_OPTION_enable_kvm,
4101 QEMU_OPTION_win2k_hack,
4102 QEMU_OPTION_rtc_td_hack,
4103 QEMU_OPTION_usb,
4104 QEMU_OPTION_usbdevice,
4105 QEMU_OPTION_smp,
4106 QEMU_OPTION_vnc,
4107 QEMU_OPTION_no_acpi,
4108 QEMU_OPTION_no_hpet,
4109 QEMU_OPTION_curses,
4110 QEMU_OPTION_no_reboot,
4111 QEMU_OPTION_no_shutdown,
4112 QEMU_OPTION_show_cursor,
4113 QEMU_OPTION_daemonize,
4114 QEMU_OPTION_option_rom,
4115 QEMU_OPTION_semihosting,
4116 QEMU_OPTION_name,
4117 QEMU_OPTION_prom_env,
4118 QEMU_OPTION_old_param,
4119 QEMU_OPTION_clock,
4120 QEMU_OPTION_startdate,
4121 QEMU_OPTION_tb_size,
4122 QEMU_OPTION_icount,
4123 QEMU_OPTION_uuid,
4124 QEMU_OPTION_incoming,
4127 typedef struct QEMUOption {
4128 const char *name;
4129 int flags;
4130 int index;
4131 } QEMUOption;
4133 static const QEMUOption qemu_options[] = {
4134 { "h", 0, QEMU_OPTION_h },
4135 { "help", 0, QEMU_OPTION_h },
4137 { "M", HAS_ARG, QEMU_OPTION_M },
4138 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4139 { "fda", HAS_ARG, QEMU_OPTION_fda },
4140 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4141 { "hda", HAS_ARG, QEMU_OPTION_hda },
4142 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4143 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4144 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4145 { "drive", HAS_ARG, QEMU_OPTION_drive },
4146 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4147 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4148 { "sd", HAS_ARG, QEMU_OPTION_sd },
4149 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4150 { "boot", HAS_ARG, QEMU_OPTION_boot },
4151 { "snapshot", 0, QEMU_OPTION_snapshot },
4152 #ifdef TARGET_I386
4153 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4154 #endif
4155 { "m", HAS_ARG, QEMU_OPTION_m },
4156 { "nographic", 0, QEMU_OPTION_nographic },
4157 { "portrait", 0, QEMU_OPTION_portrait },
4158 { "k", HAS_ARG, QEMU_OPTION_k },
4159 #ifdef HAS_AUDIO
4160 { "audio-help", 0, QEMU_OPTION_audio_help },
4161 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4162 #endif
4164 { "net", HAS_ARG, QEMU_OPTION_net},
4165 #ifdef CONFIG_SLIRP
4166 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4167 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4168 #ifndef _WIN32
4169 { "smb", HAS_ARG, QEMU_OPTION_smb },
4170 #endif
4171 { "redir", HAS_ARG, QEMU_OPTION_redir },
4172 #endif
4173 { "bt", HAS_ARG, QEMU_OPTION_bt },
4175 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4176 { "append", HAS_ARG, QEMU_OPTION_append },
4177 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4179 { "S", 0, QEMU_OPTION_S },
4180 { "s", 0, QEMU_OPTION_s },
4181 { "p", HAS_ARG, QEMU_OPTION_p },
4182 { "d", HAS_ARG, QEMU_OPTION_d },
4183 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4184 { "L", HAS_ARG, QEMU_OPTION_L },
4185 { "bios", HAS_ARG, QEMU_OPTION_bios },
4186 #ifdef USE_KQEMU
4187 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4188 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4189 #endif
4190 #ifdef CONFIG_KVM
4191 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4192 #endif
4193 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4194 { "g", 1, QEMU_OPTION_g },
4195 #endif
4196 { "localtime", 0, QEMU_OPTION_localtime },
4197 { "vga", HAS_ARG, QEMU_OPTION_vga },
4198 { "echr", HAS_ARG, QEMU_OPTION_echr },
4199 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4200 { "serial", HAS_ARG, QEMU_OPTION_serial },
4201 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4202 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4203 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4204 { "full-screen", 0, QEMU_OPTION_full_screen },
4205 #ifdef CONFIG_SDL
4206 { "no-frame", 0, QEMU_OPTION_no_frame },
4207 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4208 { "no-quit", 0, QEMU_OPTION_no_quit },
4209 { "sdl", 0, QEMU_OPTION_sdl },
4210 #endif
4211 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4212 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4213 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4214 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4215 { "smp", HAS_ARG, QEMU_OPTION_smp },
4216 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4217 #ifdef CONFIG_CURSES
4218 { "curses", 0, QEMU_OPTION_curses },
4219 #endif
4220 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4222 /* temporary options */
4223 { "usb", 0, QEMU_OPTION_usb },
4224 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4225 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4226 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4227 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4228 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4229 { "daemonize", 0, QEMU_OPTION_daemonize },
4230 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4231 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4232 { "semihosting", 0, QEMU_OPTION_semihosting },
4233 #endif
4234 { "name", HAS_ARG, QEMU_OPTION_name },
4235 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4236 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4237 #endif
4238 #if defined(TARGET_ARM)
4239 { "old-param", 0, QEMU_OPTION_old_param },
4240 #endif
4241 { "clock", HAS_ARG, QEMU_OPTION_clock },
4242 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4243 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4244 { "icount", HAS_ARG, QEMU_OPTION_icount },
4245 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4246 { NULL },
4249 /* password input */
4251 int qemu_key_check(BlockDriverState *bs, const char *name)
4253 char password[256];
4254 int i;
4256 if (!bdrv_is_encrypted(bs))
4257 return 0;
4259 term_printf("%s is encrypted.\n", name);
4260 for(i = 0; i < 3; i++) {
4261 monitor_readline("Password: ", 1, password, sizeof(password));
4262 if (bdrv_set_key(bs, password) == 0)
4263 return 0;
4264 term_printf("invalid password\n");
4266 return -EPERM;
4269 static BlockDriverState *get_bdrv(int index)
4271 if (index > nb_drives)
4272 return NULL;
4273 return drives_table[index].bdrv;
4276 static void read_passwords(void)
4278 BlockDriverState *bs;
4279 int i;
4281 for(i = 0; i < 6; i++) {
4282 bs = get_bdrv(i);
4283 if (bs)
4284 qemu_key_check(bs, bdrv_get_device_name(bs));
4288 #ifdef HAS_AUDIO
4289 struct soundhw soundhw[] = {
4290 #ifdef HAS_AUDIO_CHOICE
4291 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4293 "pcspk",
4294 "PC speaker",
4297 { .init_isa = pcspk_audio_init }
4299 #endif
4301 #ifdef CONFIG_SB16
4303 "sb16",
4304 "Creative Sound Blaster 16",
4307 { .init_isa = SB16_init }
4309 #endif
4311 #ifdef CONFIG_CS4231A
4313 "cs4231a",
4314 "CS4231A",
4317 { .init_isa = cs4231a_init }
4319 #endif
4321 #ifdef CONFIG_ADLIB
4323 "adlib",
4324 #ifdef HAS_YMF262
4325 "Yamaha YMF262 (OPL3)",
4326 #else
4327 "Yamaha YM3812 (OPL2)",
4328 #endif
4331 { .init_isa = Adlib_init }
4333 #endif
4335 #ifdef CONFIG_GUS
4337 "gus",
4338 "Gravis Ultrasound GF1",
4341 { .init_isa = GUS_init }
4343 #endif
4345 #ifdef CONFIG_AC97
4347 "ac97",
4348 "Intel 82801AA AC97 Audio",
4351 { .init_pci = ac97_init }
4353 #endif
4355 #ifdef CONFIG_ES1370
4357 "es1370",
4358 "ENSONIQ AudioPCI ES1370",
4361 { .init_pci = es1370_init }
4363 #endif
4365 #endif /* HAS_AUDIO_CHOICE */
4367 { NULL, NULL, 0, 0, { NULL } }
4370 static void select_soundhw (const char *optarg)
4372 struct soundhw *c;
4374 if (*optarg == '?') {
4375 show_valid_cards:
4377 printf ("Valid sound card names (comma separated):\n");
4378 for (c = soundhw; c->name; ++c) {
4379 printf ("%-11s %s\n", c->name, c->descr);
4381 printf ("\n-soundhw all will enable all of the above\n");
4382 exit (*optarg != '?');
4384 else {
4385 size_t l;
4386 const char *p;
4387 char *e;
4388 int bad_card = 0;
4390 if (!strcmp (optarg, "all")) {
4391 for (c = soundhw; c->name; ++c) {
4392 c->enabled = 1;
4394 return;
4397 p = optarg;
4398 while (*p) {
4399 e = strchr (p, ',');
4400 l = !e ? strlen (p) : (size_t) (e - p);
4402 for (c = soundhw; c->name; ++c) {
4403 if (!strncmp (c->name, p, l)) {
4404 c->enabled = 1;
4405 break;
4409 if (!c->name) {
4410 if (l > 80) {
4411 fprintf (stderr,
4412 "Unknown sound card name (too big to show)\n");
4414 else {
4415 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4416 (int) l, p);
4418 bad_card = 1;
4420 p += l + (e != NULL);
4423 if (bad_card)
4424 goto show_valid_cards;
4427 #endif
4429 static void select_vgahw (const char *p)
4431 const char *opts;
4433 if (strstart(p, "std", &opts)) {
4434 std_vga_enabled = 1;
4435 cirrus_vga_enabled = 0;
4436 vmsvga_enabled = 0;
4437 } else if (strstart(p, "cirrus", &opts)) {
4438 cirrus_vga_enabled = 1;
4439 std_vga_enabled = 0;
4440 vmsvga_enabled = 0;
4441 } else if (strstart(p, "vmware", &opts)) {
4442 cirrus_vga_enabled = 0;
4443 std_vga_enabled = 0;
4444 vmsvga_enabled = 1;
4445 } else if (strstart(p, "none", &opts)) {
4446 cirrus_vga_enabled = 0;
4447 std_vga_enabled = 0;
4448 vmsvga_enabled = 0;
4449 } else {
4450 invalid_vga:
4451 fprintf(stderr, "Unknown vga type: %s\n", p);
4452 exit(1);
4454 while (*opts) {
4455 const char *nextopt;
4457 if (strstart(opts, ",retrace=", &nextopt)) {
4458 opts = nextopt;
4459 if (strstart(opts, "dumb", &nextopt))
4460 vga_retrace_method = VGA_RETRACE_DUMB;
4461 else if (strstart(opts, "precise", &nextopt))
4462 vga_retrace_method = VGA_RETRACE_PRECISE;
4463 else goto invalid_vga;
4464 } else goto invalid_vga;
4465 opts = nextopt;
4469 #ifdef _WIN32
4470 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4472 exit(STATUS_CONTROL_C_EXIT);
4473 return TRUE;
4475 #endif
4477 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4479 int ret;
4481 if(strlen(str) != 36)
4482 return -1;
4484 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4485 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4486 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4488 if(ret != 16)
4489 return -1;
4491 return 0;
4494 #define MAX_NET_CLIENTS 32
4496 #ifndef _WIN32
4498 static void termsig_handler(int signal)
4500 qemu_system_shutdown_request();
4503 static void termsig_setup(void)
4505 struct sigaction act;
4507 memset(&act, 0, sizeof(act));
4508 act.sa_handler = termsig_handler;
4509 sigaction(SIGINT, &act, NULL);
4510 sigaction(SIGHUP, &act, NULL);
4511 sigaction(SIGTERM, &act, NULL);
4514 #endif
4516 int main(int argc, char **argv, char **envp)
4518 #ifdef CONFIG_GDBSTUB
4519 int use_gdbstub;
4520 const char *gdbstub_port;
4521 #endif
4522 uint32_t boot_devices_bitmap = 0;
4523 int i;
4524 int snapshot, linux_boot, net_boot;
4525 const char *initrd_filename;
4526 const char *kernel_filename, *kernel_cmdline;
4527 const char *boot_devices = "";
4528 DisplayState *ds;
4529 DisplayChangeListener *dcl;
4530 int cyls, heads, secs, translation;
4531 const char *net_clients[MAX_NET_CLIENTS];
4532 int nb_net_clients;
4533 const char *bt_opts[MAX_BT_CMDLINE];
4534 int nb_bt_opts;
4535 int hda_index;
4536 int optind;
4537 const char *r, *optarg;
4538 CharDriverState *monitor_hd = NULL;
4539 const char *monitor_device;
4540 const char *serial_devices[MAX_SERIAL_PORTS];
4541 int serial_device_index;
4542 const char *parallel_devices[MAX_PARALLEL_PORTS];
4543 int parallel_device_index;
4544 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4545 int virtio_console_index;
4546 const char *loadvm = NULL;
4547 QEMUMachine *machine;
4548 const char *cpu_model;
4549 const char *usb_devices[MAX_USB_CMDLINE];
4550 int usb_devices_index;
4551 int fds[2];
4552 int tb_size;
4553 const char *pid_file = NULL;
4554 int autostart;
4555 const char *incoming = NULL;
4557 qemu_cache_utils_init(envp);
4559 LIST_INIT (&vm_change_state_head);
4560 #ifndef _WIN32
4562 struct sigaction act;
4563 sigfillset(&act.sa_mask);
4564 act.sa_flags = 0;
4565 act.sa_handler = SIG_IGN;
4566 sigaction(SIGPIPE, &act, NULL);
4568 #else
4569 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4570 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4571 QEMU to run on a single CPU */
4573 HANDLE h;
4574 DWORD mask, smask;
4575 int i;
4576 h = GetCurrentProcess();
4577 if (GetProcessAffinityMask(h, &mask, &smask)) {
4578 for(i = 0; i < 32; i++) {
4579 if (mask & (1 << i))
4580 break;
4582 if (i != 32) {
4583 mask = 1 << i;
4584 SetProcessAffinityMask(h, mask);
4588 #endif
4590 register_machines();
4591 machine = first_machine;
4592 cpu_model = NULL;
4593 initrd_filename = NULL;
4594 ram_size = 0;
4595 vga_ram_size = VGA_RAM_SIZE;
4596 #ifdef CONFIG_GDBSTUB
4597 use_gdbstub = 0;
4598 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4599 #endif
4600 snapshot = 0;
4601 nographic = 0;
4602 curses = 0;
4603 kernel_filename = NULL;
4604 kernel_cmdline = "";
4605 cyls = heads = secs = 0;
4606 translation = BIOS_ATA_TRANSLATION_AUTO;
4607 monitor_device = "vc";
4609 serial_devices[0] = "vc:80Cx24C";
4610 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4611 serial_devices[i] = NULL;
4612 serial_device_index = 0;
4614 parallel_devices[0] = "vc:640x480";
4615 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4616 parallel_devices[i] = NULL;
4617 parallel_device_index = 0;
4619 virtio_consoles[0] = "vc:80Cx24C";
4620 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4621 virtio_consoles[i] = NULL;
4622 virtio_console_index = 0;
4624 usb_devices_index = 0;
4626 nb_net_clients = 0;
4627 nb_bt_opts = 0;
4628 nb_drives = 0;
4629 nb_drives_opt = 0;
4630 hda_index = -1;
4632 nb_nics = 0;
4634 tb_size = 0;
4635 autostart= 1;
4637 optind = 1;
4638 for(;;) {
4639 if (optind >= argc)
4640 break;
4641 r = argv[optind];
4642 if (r[0] != '-') {
4643 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4644 } else {
4645 const QEMUOption *popt;
4647 optind++;
4648 /* Treat --foo the same as -foo. */
4649 if (r[1] == '-')
4650 r++;
4651 popt = qemu_options;
4652 for(;;) {
4653 if (!popt->name) {
4654 fprintf(stderr, "%s: invalid option -- '%s'\n",
4655 argv[0], r);
4656 exit(1);
4658 if (!strcmp(popt->name, r + 1))
4659 break;
4660 popt++;
4662 if (popt->flags & HAS_ARG) {
4663 if (optind >= argc) {
4664 fprintf(stderr, "%s: option '%s' requires an argument\n",
4665 argv[0], r);
4666 exit(1);
4668 optarg = argv[optind++];
4669 } else {
4670 optarg = NULL;
4673 switch(popt->index) {
4674 case QEMU_OPTION_M:
4675 machine = find_machine(optarg);
4676 if (!machine) {
4677 QEMUMachine *m;
4678 printf("Supported machines are:\n");
4679 for(m = first_machine; m != NULL; m = m->next) {
4680 printf("%-10s %s%s\n",
4681 m->name, m->desc,
4682 m == first_machine ? " (default)" : "");
4684 exit(*optarg != '?');
4686 break;
4687 case QEMU_OPTION_cpu:
4688 /* hw initialization will check this */
4689 if (*optarg == '?') {
4690 /* XXX: implement xxx_cpu_list for targets that still miss it */
4691 #if defined(cpu_list)
4692 cpu_list(stdout, &fprintf);
4693 #endif
4694 exit(0);
4695 } else {
4696 cpu_model = optarg;
4698 break;
4699 case QEMU_OPTION_initrd:
4700 initrd_filename = optarg;
4701 break;
4702 case QEMU_OPTION_hda:
4703 if (cyls == 0)
4704 hda_index = drive_add(optarg, HD_ALIAS, 0);
4705 else
4706 hda_index = drive_add(optarg, HD_ALIAS
4707 ",cyls=%d,heads=%d,secs=%d%s",
4708 0, cyls, heads, secs,
4709 translation == BIOS_ATA_TRANSLATION_LBA ?
4710 ",trans=lba" :
4711 translation == BIOS_ATA_TRANSLATION_NONE ?
4712 ",trans=none" : "");
4713 break;
4714 case QEMU_OPTION_hdb:
4715 case QEMU_OPTION_hdc:
4716 case QEMU_OPTION_hdd:
4717 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4718 break;
4719 case QEMU_OPTION_drive:
4720 drive_add(NULL, "%s", optarg);
4721 break;
4722 case QEMU_OPTION_mtdblock:
4723 drive_add(optarg, MTD_ALIAS);
4724 break;
4725 case QEMU_OPTION_sd:
4726 drive_add(optarg, SD_ALIAS);
4727 break;
4728 case QEMU_OPTION_pflash:
4729 drive_add(optarg, PFLASH_ALIAS);
4730 break;
4731 case QEMU_OPTION_snapshot:
4732 snapshot = 1;
4733 break;
4734 case QEMU_OPTION_hdachs:
4736 const char *p;
4737 p = optarg;
4738 cyls = strtol(p, (char **)&p, 0);
4739 if (cyls < 1 || cyls > 16383)
4740 goto chs_fail;
4741 if (*p != ',')
4742 goto chs_fail;
4743 p++;
4744 heads = strtol(p, (char **)&p, 0);
4745 if (heads < 1 || heads > 16)
4746 goto chs_fail;
4747 if (*p != ',')
4748 goto chs_fail;
4749 p++;
4750 secs = strtol(p, (char **)&p, 0);
4751 if (secs < 1 || secs > 63)
4752 goto chs_fail;
4753 if (*p == ',') {
4754 p++;
4755 if (!strcmp(p, "none"))
4756 translation = BIOS_ATA_TRANSLATION_NONE;
4757 else if (!strcmp(p, "lba"))
4758 translation = BIOS_ATA_TRANSLATION_LBA;
4759 else if (!strcmp(p, "auto"))
4760 translation = BIOS_ATA_TRANSLATION_AUTO;
4761 else
4762 goto chs_fail;
4763 } else if (*p != '\0') {
4764 chs_fail:
4765 fprintf(stderr, "qemu: invalid physical CHS format\n");
4766 exit(1);
4768 if (hda_index != -1)
4769 snprintf(drives_opt[hda_index].opt,
4770 sizeof(drives_opt[hda_index].opt),
4771 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4772 0, cyls, heads, secs,
4773 translation == BIOS_ATA_TRANSLATION_LBA ?
4774 ",trans=lba" :
4775 translation == BIOS_ATA_TRANSLATION_NONE ?
4776 ",trans=none" : "");
4778 break;
4779 case QEMU_OPTION_nographic:
4780 nographic = 1;
4781 break;
4782 #ifdef CONFIG_CURSES
4783 case QEMU_OPTION_curses:
4784 curses = 1;
4785 break;
4786 #endif
4787 case QEMU_OPTION_portrait:
4788 graphic_rotate = 1;
4789 break;
4790 case QEMU_OPTION_kernel:
4791 kernel_filename = optarg;
4792 break;
4793 case QEMU_OPTION_append:
4794 kernel_cmdline = optarg;
4795 break;
4796 case QEMU_OPTION_cdrom:
4797 drive_add(optarg, CDROM_ALIAS);
4798 break;
4799 case QEMU_OPTION_boot:
4800 boot_devices = optarg;
4801 /* We just do some generic consistency checks */
4803 /* Could easily be extended to 64 devices if needed */
4804 const char *p;
4806 boot_devices_bitmap = 0;
4807 for (p = boot_devices; *p != '\0'; p++) {
4808 /* Allowed boot devices are:
4809 * a b : floppy disk drives
4810 * c ... f : IDE disk drives
4811 * g ... m : machine implementation dependant drives
4812 * n ... p : network devices
4813 * It's up to each machine implementation to check
4814 * if the given boot devices match the actual hardware
4815 * implementation and firmware features.
4817 if (*p < 'a' || *p > 'q') {
4818 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4819 exit(1);
4821 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4822 fprintf(stderr,
4823 "Boot device '%c' was given twice\n",*p);
4824 exit(1);
4826 boot_devices_bitmap |= 1 << (*p - 'a');
4829 break;
4830 case QEMU_OPTION_fda:
4831 case QEMU_OPTION_fdb:
4832 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4833 break;
4834 #ifdef TARGET_I386
4835 case QEMU_OPTION_no_fd_bootchk:
4836 fd_bootchk = 0;
4837 break;
4838 #endif
4839 case QEMU_OPTION_net:
4840 if (nb_net_clients >= MAX_NET_CLIENTS) {
4841 fprintf(stderr, "qemu: too many network clients\n");
4842 exit(1);
4844 net_clients[nb_net_clients] = optarg;
4845 nb_net_clients++;
4846 break;
4847 #ifdef CONFIG_SLIRP
4848 case QEMU_OPTION_tftp:
4849 tftp_prefix = optarg;
4850 break;
4851 case QEMU_OPTION_bootp:
4852 bootp_filename = optarg;
4853 break;
4854 #ifndef _WIN32
4855 case QEMU_OPTION_smb:
4856 net_slirp_smb(optarg);
4857 break;
4858 #endif
4859 case QEMU_OPTION_redir:
4860 net_slirp_redir(optarg);
4861 break;
4862 #endif
4863 case QEMU_OPTION_bt:
4864 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4865 fprintf(stderr, "qemu: too many bluetooth options\n");
4866 exit(1);
4868 bt_opts[nb_bt_opts++] = optarg;
4869 break;
4870 #ifdef HAS_AUDIO
4871 case QEMU_OPTION_audio_help:
4872 AUD_help ();
4873 exit (0);
4874 break;
4875 case QEMU_OPTION_soundhw:
4876 select_soundhw (optarg);
4877 break;
4878 #endif
4879 case QEMU_OPTION_h:
4880 help(0);
4881 break;
4882 case QEMU_OPTION_m: {
4883 uint64_t value;
4884 char *ptr;
4886 value = strtoul(optarg, &ptr, 10);
4887 switch (*ptr) {
4888 case 0: case 'M': case 'm':
4889 value <<= 20;
4890 break;
4891 case 'G': case 'g':
4892 value <<= 30;
4893 break;
4894 default:
4895 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4896 exit(1);
4899 /* On 32-bit hosts, QEMU is limited by virtual address space */
4900 if (value > (2047 << 20)
4901 #ifndef USE_KQEMU
4902 && HOST_LONG_BITS == 32
4903 #endif
4905 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4906 exit(1);
4908 if (value != (uint64_t)(ram_addr_t)value) {
4909 fprintf(stderr, "qemu: ram size too large\n");
4910 exit(1);
4912 ram_size = value;
4913 break;
4915 case QEMU_OPTION_d:
4917 int mask;
4918 const CPULogItem *item;
4920 mask = cpu_str_to_log_mask(optarg);
4921 if (!mask) {
4922 printf("Log items (comma separated):\n");
4923 for(item = cpu_log_items; item->mask != 0; item++) {
4924 printf("%-10s %s\n", item->name, item->help);
4926 exit(1);
4928 cpu_set_log(mask);
4930 break;
4931 #ifdef CONFIG_GDBSTUB
4932 case QEMU_OPTION_s:
4933 use_gdbstub = 1;
4934 break;
4935 case QEMU_OPTION_p:
4936 gdbstub_port = optarg;
4937 break;
4938 #endif
4939 case QEMU_OPTION_L:
4940 bios_dir = optarg;
4941 break;
4942 case QEMU_OPTION_bios:
4943 bios_name = optarg;
4944 break;
4945 case QEMU_OPTION_S:
4946 autostart = 0;
4947 break;
4948 case QEMU_OPTION_k:
4949 keyboard_layout = optarg;
4950 break;
4951 case QEMU_OPTION_localtime:
4952 rtc_utc = 0;
4953 break;
4954 case QEMU_OPTION_vga:
4955 select_vgahw (optarg);
4956 break;
4957 case QEMU_OPTION_g:
4959 const char *p;
4960 int w, h, depth;
4961 p = optarg;
4962 w = strtol(p, (char **)&p, 10);
4963 if (w <= 0) {
4964 graphic_error:
4965 fprintf(stderr, "qemu: invalid resolution or depth\n");
4966 exit(1);
4968 if (*p != 'x')
4969 goto graphic_error;
4970 p++;
4971 h = strtol(p, (char **)&p, 10);
4972 if (h <= 0)
4973 goto graphic_error;
4974 if (*p == 'x') {
4975 p++;
4976 depth = strtol(p, (char **)&p, 10);
4977 if (depth != 8 && depth != 15 && depth != 16 &&
4978 depth != 24 && depth != 32)
4979 goto graphic_error;
4980 } else if (*p == '\0') {
4981 depth = graphic_depth;
4982 } else {
4983 goto graphic_error;
4986 graphic_width = w;
4987 graphic_height = h;
4988 graphic_depth = depth;
4990 break;
4991 case QEMU_OPTION_echr:
4993 char *r;
4994 term_escape_char = strtol(optarg, &r, 0);
4995 if (r == optarg)
4996 printf("Bad argument to echr\n");
4997 break;
4999 case QEMU_OPTION_monitor:
5000 monitor_device = optarg;
5001 break;
5002 case QEMU_OPTION_serial:
5003 if (serial_device_index >= MAX_SERIAL_PORTS) {
5004 fprintf(stderr, "qemu: too many serial ports\n");
5005 exit(1);
5007 serial_devices[serial_device_index] = optarg;
5008 serial_device_index++;
5009 break;
5010 case QEMU_OPTION_virtiocon:
5011 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5012 fprintf(stderr, "qemu: too many virtio consoles\n");
5013 exit(1);
5015 virtio_consoles[virtio_console_index] = optarg;
5016 virtio_console_index++;
5017 break;
5018 case QEMU_OPTION_parallel:
5019 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5020 fprintf(stderr, "qemu: too many parallel ports\n");
5021 exit(1);
5023 parallel_devices[parallel_device_index] = optarg;
5024 parallel_device_index++;
5025 break;
5026 case QEMU_OPTION_loadvm:
5027 loadvm = optarg;
5028 break;
5029 case QEMU_OPTION_full_screen:
5030 full_screen = 1;
5031 break;
5032 #ifdef CONFIG_SDL
5033 case QEMU_OPTION_no_frame:
5034 no_frame = 1;
5035 break;
5036 case QEMU_OPTION_alt_grab:
5037 alt_grab = 1;
5038 break;
5039 case QEMU_OPTION_no_quit:
5040 no_quit = 1;
5041 break;
5042 case QEMU_OPTION_sdl:
5043 sdl = 1;
5044 break;
5045 #endif
5046 case QEMU_OPTION_pidfile:
5047 pid_file = optarg;
5048 break;
5049 #ifdef TARGET_I386
5050 case QEMU_OPTION_win2k_hack:
5051 win2k_install_hack = 1;
5052 break;
5053 case QEMU_OPTION_rtc_td_hack:
5054 rtc_td_hack = 1;
5055 break;
5056 #endif
5057 #ifdef USE_KQEMU
5058 case QEMU_OPTION_no_kqemu:
5059 kqemu_allowed = 0;
5060 break;
5061 case QEMU_OPTION_kernel_kqemu:
5062 kqemu_allowed = 2;
5063 break;
5064 #endif
5065 #ifdef CONFIG_KVM
5066 case QEMU_OPTION_enable_kvm:
5067 kvm_allowed = 1;
5068 #ifdef USE_KQEMU
5069 kqemu_allowed = 0;
5070 #endif
5071 break;
5072 #endif
5073 case QEMU_OPTION_usb:
5074 usb_enabled = 1;
5075 break;
5076 case QEMU_OPTION_usbdevice:
5077 usb_enabled = 1;
5078 if (usb_devices_index >= MAX_USB_CMDLINE) {
5079 fprintf(stderr, "Too many USB devices\n");
5080 exit(1);
5082 usb_devices[usb_devices_index] = optarg;
5083 usb_devices_index++;
5084 break;
5085 case QEMU_OPTION_smp:
5086 smp_cpus = atoi(optarg);
5087 if (smp_cpus < 1) {
5088 fprintf(stderr, "Invalid number of CPUs\n");
5089 exit(1);
5091 break;
5092 case QEMU_OPTION_vnc:
5093 vnc_display = optarg;
5094 break;
5095 case QEMU_OPTION_no_acpi:
5096 acpi_enabled = 0;
5097 break;
5098 case QEMU_OPTION_no_hpet:
5099 no_hpet = 1;
5100 break;
5101 case QEMU_OPTION_no_reboot:
5102 no_reboot = 1;
5103 break;
5104 case QEMU_OPTION_no_shutdown:
5105 no_shutdown = 1;
5106 break;
5107 case QEMU_OPTION_show_cursor:
5108 cursor_hide = 0;
5109 break;
5110 case QEMU_OPTION_uuid:
5111 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5112 fprintf(stderr, "Fail to parse UUID string."
5113 " Wrong format.\n");
5114 exit(1);
5116 break;
5117 case QEMU_OPTION_daemonize:
5118 daemonize = 1;
5119 break;
5120 case QEMU_OPTION_option_rom:
5121 if (nb_option_roms >= MAX_OPTION_ROMS) {
5122 fprintf(stderr, "Too many option ROMs\n");
5123 exit(1);
5125 option_rom[nb_option_roms] = optarg;
5126 nb_option_roms++;
5127 break;
5128 case QEMU_OPTION_semihosting:
5129 semihosting_enabled = 1;
5130 break;
5131 case QEMU_OPTION_name:
5132 qemu_name = optarg;
5133 break;
5134 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5135 case QEMU_OPTION_prom_env:
5136 if (nb_prom_envs >= MAX_PROM_ENVS) {
5137 fprintf(stderr, "Too many prom variables\n");
5138 exit(1);
5140 prom_envs[nb_prom_envs] = optarg;
5141 nb_prom_envs++;
5142 break;
5143 #endif
5144 #ifdef TARGET_ARM
5145 case QEMU_OPTION_old_param:
5146 old_param = 1;
5147 break;
5148 #endif
5149 case QEMU_OPTION_clock:
5150 configure_alarms(optarg);
5151 break;
5152 case QEMU_OPTION_startdate:
5154 struct tm tm;
5155 time_t rtc_start_date;
5156 if (!strcmp(optarg, "now")) {
5157 rtc_date_offset = -1;
5158 } else {
5159 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5160 &tm.tm_year,
5161 &tm.tm_mon,
5162 &tm.tm_mday,
5163 &tm.tm_hour,
5164 &tm.tm_min,
5165 &tm.tm_sec) == 6) {
5166 /* OK */
5167 } else if (sscanf(optarg, "%d-%d-%d",
5168 &tm.tm_year,
5169 &tm.tm_mon,
5170 &tm.tm_mday) == 3) {
5171 tm.tm_hour = 0;
5172 tm.tm_min = 0;
5173 tm.tm_sec = 0;
5174 } else {
5175 goto date_fail;
5177 tm.tm_year -= 1900;
5178 tm.tm_mon--;
5179 rtc_start_date = mktimegm(&tm);
5180 if (rtc_start_date == -1) {
5181 date_fail:
5182 fprintf(stderr, "Invalid date format. Valid format are:\n"
5183 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5184 exit(1);
5186 rtc_date_offset = time(NULL) - rtc_start_date;
5189 break;
5190 case QEMU_OPTION_tb_size:
5191 tb_size = strtol(optarg, NULL, 0);
5192 if (tb_size < 0)
5193 tb_size = 0;
5194 break;
5195 case QEMU_OPTION_icount:
5196 use_icount = 1;
5197 if (strcmp(optarg, "auto") == 0) {
5198 icount_time_shift = -1;
5199 } else {
5200 icount_time_shift = strtol(optarg, NULL, 0);
5202 break;
5203 case QEMU_OPTION_incoming:
5204 incoming = optarg;
5205 break;
5210 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5211 if (kvm_allowed && kqemu_allowed) {
5212 fprintf(stderr,
5213 "You can not enable both KVM and kqemu at the same time\n");
5214 exit(1);
5216 #endif
5218 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5219 if (smp_cpus > machine->max_cpus) {
5220 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5221 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5222 machine->max_cpus);
5223 exit(1);
5226 if (nographic) {
5227 if (serial_device_index == 0)
5228 serial_devices[0] = "stdio";
5229 if (parallel_device_index == 0)
5230 parallel_devices[0] = "null";
5231 if (strncmp(monitor_device, "vc", 2) == 0)
5232 monitor_device = "stdio";
5233 if (virtio_console_index == 0)
5234 virtio_consoles[0] = "null";
5237 #ifndef _WIN32
5238 if (daemonize) {
5239 pid_t pid;
5241 if (pipe(fds) == -1)
5242 exit(1);
5244 pid = fork();
5245 if (pid > 0) {
5246 uint8_t status;
5247 ssize_t len;
5249 close(fds[1]);
5251 again:
5252 len = read(fds[0], &status, 1);
5253 if (len == -1 && (errno == EINTR))
5254 goto again;
5256 if (len != 1)
5257 exit(1);
5258 else if (status == 1) {
5259 fprintf(stderr, "Could not acquire pidfile\n");
5260 exit(1);
5261 } else
5262 exit(0);
5263 } else if (pid < 0)
5264 exit(1);
5266 setsid();
5268 pid = fork();
5269 if (pid > 0)
5270 exit(0);
5271 else if (pid < 0)
5272 exit(1);
5274 umask(027);
5276 signal(SIGTSTP, SIG_IGN);
5277 signal(SIGTTOU, SIG_IGN);
5278 signal(SIGTTIN, SIG_IGN);
5280 #endif
5282 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5283 if (daemonize) {
5284 uint8_t status = 1;
5285 write(fds[1], &status, 1);
5286 } else
5287 fprintf(stderr, "Could not acquire pid file\n");
5288 exit(1);
5291 #ifdef USE_KQEMU
5292 if (smp_cpus > 1)
5293 kqemu_allowed = 0;
5294 #endif
5295 linux_boot = (kernel_filename != NULL);
5296 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5298 if (!linux_boot && net_boot == 0 &&
5299 !machine->nodisk_ok && nb_drives_opt == 0)
5300 help(1);
5302 if (!linux_boot && *kernel_cmdline != '\0') {
5303 fprintf(stderr, "-append only allowed with -kernel option\n");
5304 exit(1);
5307 if (!linux_boot && initrd_filename != NULL) {
5308 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5309 exit(1);
5312 /* boot to floppy or the default cd if no hard disk defined yet */
5313 if (!boot_devices[0]) {
5314 boot_devices = "cad";
5316 setvbuf(stdout, NULL, _IOLBF, 0);
5318 init_timers();
5319 if (init_timer_alarm() < 0) {
5320 fprintf(stderr, "could not initialize alarm timer\n");
5321 exit(1);
5323 if (use_icount && icount_time_shift < 0) {
5324 use_icount = 2;
5325 /* 125MIPS seems a reasonable initial guess at the guest speed.
5326 It will be corrected fairly quickly anyway. */
5327 icount_time_shift = 3;
5328 init_icount_adjust();
5331 #ifdef _WIN32
5332 socket_init();
5333 #endif
5335 /* init network clients */
5336 if (nb_net_clients == 0) {
5337 /* if no clients, we use a default config */
5338 net_clients[nb_net_clients++] = "nic";
5339 #ifdef CONFIG_SLIRP
5340 net_clients[nb_net_clients++] = "user";
5341 #endif
5344 for(i = 0;i < nb_net_clients; i++) {
5345 if (net_client_parse(net_clients[i]) < 0)
5346 exit(1);
5348 net_client_check();
5350 #ifdef TARGET_I386
5351 /* XXX: this should be moved in the PC machine instantiation code */
5352 if (net_boot != 0) {
5353 int netroms = 0;
5354 for (i = 0; i < nb_nics && i < 4; i++) {
5355 const char *model = nd_table[i].model;
5356 char buf[1024];
5357 if (net_boot & (1 << i)) {
5358 if (model == NULL)
5359 model = "ne2k_pci";
5360 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5361 if (get_image_size(buf) > 0) {
5362 if (nb_option_roms >= MAX_OPTION_ROMS) {
5363 fprintf(stderr, "Too many option ROMs\n");
5364 exit(1);
5366 option_rom[nb_option_roms] = strdup(buf);
5367 nb_option_roms++;
5368 netroms++;
5372 if (netroms == 0) {
5373 fprintf(stderr, "No valid PXE rom found for network device\n");
5374 exit(1);
5377 #endif
5379 /* init the bluetooth world */
5380 for (i = 0; i < nb_bt_opts; i++)
5381 if (bt_parse(bt_opts[i]))
5382 exit(1);
5384 /* init the memory */
5385 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5387 if (machine->ram_require & RAMSIZE_FIXED) {
5388 if (ram_size > 0) {
5389 if (ram_size < phys_ram_size) {
5390 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5391 machine->name, (unsigned long long) phys_ram_size);
5392 exit(-1);
5395 phys_ram_size = ram_size;
5396 } else
5397 ram_size = phys_ram_size;
5398 } else {
5399 if (ram_size == 0)
5400 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5402 phys_ram_size += ram_size;
5405 phys_ram_base = qemu_vmalloc(phys_ram_size);
5406 if (!phys_ram_base) {
5407 fprintf(stderr, "Could not allocate physical memory\n");
5408 exit(1);
5411 /* init the dynamic translator */
5412 cpu_exec_init_all(tb_size * 1024 * 1024);
5414 bdrv_init();
5416 /* we always create the cdrom drive, even if no disk is there */
5418 if (nb_drives_opt < MAX_DRIVES)
5419 drive_add(NULL, CDROM_ALIAS);
5421 /* we always create at least one floppy */
5423 if (nb_drives_opt < MAX_DRIVES)
5424 drive_add(NULL, FD_ALIAS, 0);
5426 /* we always create one sd slot, even if no card is in it */
5428 if (nb_drives_opt < MAX_DRIVES)
5429 drive_add(NULL, SD_ALIAS);
5431 /* open the virtual block devices */
5433 for(i = 0; i < nb_drives_opt; i++)
5434 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5435 exit(1);
5437 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5438 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5440 #ifndef _WIN32
5441 /* must be after terminal init, SDL library changes signal handlers */
5442 termsig_setup();
5443 #endif
5445 /* Maintain compatibility with multiple stdio monitors */
5446 if (!strcmp(monitor_device,"stdio")) {
5447 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5448 const char *devname = serial_devices[i];
5449 if (devname && !strcmp(devname,"mon:stdio")) {
5450 monitor_device = NULL;
5451 break;
5452 } else if (devname && !strcmp(devname,"stdio")) {
5453 monitor_device = NULL;
5454 serial_devices[i] = "mon:stdio";
5455 break;
5460 if (kvm_enabled()) {
5461 int ret;
5463 ret = kvm_init(smp_cpus);
5464 if (ret < 0) {
5465 fprintf(stderr, "failed to initialize KVM\n");
5466 exit(1);
5470 if (monitor_device) {
5471 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5472 if (!monitor_hd) {
5473 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5474 exit(1);
5478 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5479 const char *devname = serial_devices[i];
5480 if (devname && strcmp(devname, "none")) {
5481 char label[32];
5482 snprintf(label, sizeof(label), "serial%d", i);
5483 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5484 if (!serial_hds[i]) {
5485 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5486 devname);
5487 exit(1);
5492 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5493 const char *devname = parallel_devices[i];
5494 if (devname && strcmp(devname, "none")) {
5495 char label[32];
5496 snprintf(label, sizeof(label), "parallel%d", i);
5497 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5498 if (!parallel_hds[i]) {
5499 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5500 devname);
5501 exit(1);
5506 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5507 const char *devname = virtio_consoles[i];
5508 if (devname && strcmp(devname, "none")) {
5509 char label[32];
5510 snprintf(label, sizeof(label), "virtcon%d", i);
5511 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5512 if (!virtcon_hds[i]) {
5513 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5514 devname);
5515 exit(1);
5520 machine->init(ram_size, vga_ram_size, boot_devices,
5521 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5523 /* Set KVM's vcpu state to qemu's initial CPUState. */
5524 if (kvm_enabled()) {
5525 int ret;
5527 ret = kvm_sync_vcpus();
5528 if (ret < 0) {
5529 fprintf(stderr, "failed to initialize vcpus\n");
5530 exit(1);
5534 /* init USB devices */
5535 if (usb_enabled) {
5536 for(i = 0; i < usb_devices_index; i++) {
5537 if (usb_device_add(usb_devices[i]) < 0) {
5538 fprintf(stderr, "Warning: could not add USB device %s\n",
5539 usb_devices[i]);
5544 if (!display_state)
5545 dumb_display_init();
5546 /* just use the first displaystate for the moment */
5547 ds = display_state;
5548 /* terminal init */
5549 if (nographic) {
5550 if (curses) {
5551 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5552 exit(1);
5554 } else {
5555 #if defined(CONFIG_CURSES)
5556 if (curses) {
5557 /* At the moment curses cannot be used with other displays */
5558 curses_display_init(ds, full_screen);
5559 } else
5560 #endif
5562 if (vnc_display != NULL) {
5563 vnc_display_init(ds);
5564 if (vnc_display_open(ds, vnc_display) < 0)
5565 exit(1);
5567 #if defined(CONFIG_SDL)
5568 if (sdl || !vnc_display)
5569 sdl_display_init(ds, full_screen, no_frame);
5570 #elif defined(CONFIG_COCOA)
5571 if (sdl || !vnc_display)
5572 cocoa_display_init(ds, full_screen);
5573 #endif
5576 dpy_resize(ds);
5578 dcl = ds->listeners;
5579 while (dcl != NULL) {
5580 if (dcl->dpy_refresh != NULL) {
5581 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5582 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5584 dcl = dcl->next;
5587 if (nographic || (vnc_display && !sdl)) {
5588 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5589 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5592 text_consoles_set_display(display_state);
5594 if (monitor_device && monitor_hd)
5595 monitor_init(monitor_hd, !nographic);
5597 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5598 const char *devname = serial_devices[i];
5599 if (devname && strcmp(devname, "none")) {
5600 char label[32];
5601 snprintf(label, sizeof(label), "serial%d", i);
5602 if (strstart(devname, "vc", 0))
5603 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5607 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5608 const char *devname = parallel_devices[i];
5609 if (devname && strcmp(devname, "none")) {
5610 char label[32];
5611 snprintf(label, sizeof(label), "parallel%d", i);
5612 if (strstart(devname, "vc", 0))
5613 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5617 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5618 const char *devname = virtio_consoles[i];
5619 if (virtcon_hds[i] && devname) {
5620 char label[32];
5621 snprintf(label, sizeof(label), "virtcon%d", i);
5622 if (strstart(devname, "vc", 0))
5623 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5627 #ifdef CONFIG_GDBSTUB
5628 if (use_gdbstub) {
5629 /* XXX: use standard host:port notation and modify options
5630 accordingly. */
5631 if (gdbserver_start(gdbstub_port) < 0) {
5632 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5633 gdbstub_port);
5634 exit(1);
5637 #endif
5639 if (loadvm)
5640 do_loadvm(loadvm);
5642 if (incoming) {
5643 autostart = 0; /* fixme how to deal with -daemonize */
5644 qemu_start_incoming_migration(incoming);
5648 /* XXX: simplify init */
5649 read_passwords();
5650 if (autostart) {
5651 vm_start();
5655 if (daemonize) {
5656 uint8_t status = 0;
5657 ssize_t len;
5658 int fd;
5660 again1:
5661 len = write(fds[1], &status, 1);
5662 if (len == -1 && (errno == EINTR))
5663 goto again1;
5665 if (len != 1)
5666 exit(1);
5668 chdir("/");
5669 TFR(fd = open("/dev/null", O_RDWR));
5670 if (fd == -1)
5671 exit(1);
5673 dup2(fd, 0);
5674 dup2(fd, 1);
5675 dup2(fd, 2);
5677 close(fd);
5680 main_loop();
5681 quit_timers();
5682 net_cleanup();
5684 return 0;