Add missing files from last commit.
[qemu/mini2440/sniper_sniper_test.git] / vl.c
blob2379986877d5291372aff0558398273264da6076
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
157 #ifdef TARGET_PPC
158 #define DEFAULT_RAM_SIZE 144
159 #else
160 #define DEFAULT_RAM_SIZE 128
161 #endif
163 /* Max number of USB devices that can be specified on the commandline. */
164 #define MAX_USB_CMDLINE 8
166 /* Max number of bluetooth switches on the commandline. */
167 #define MAX_BT_CMDLINE 10
169 /* XXX: use a two level table to limit memory usage */
170 #define MAX_IOPORTS 65536
172 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
173 const char *bios_name = NULL;
174 static void *ioport_opaque[MAX_IOPORTS];
175 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
176 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
177 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
178 to store the VM snapshots */
179 DriveInfo drives_table[MAX_DRIVES+1];
180 int nb_drives;
181 static int vga_ram_size;
182 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
183 DisplayState display_state;
184 int nographic;
185 static int curses;
186 const char* keyboard_layout = NULL;
187 int64_t ticks_per_sec;
188 ram_addr_t ram_size;
189 int nb_nics;
190 NICInfo nd_table[MAX_NICS];
191 int vm_running;
192 static int rtc_utc = 1;
193 static int rtc_date_offset = -1; /* -1 means no change */
194 int cirrus_vga_enabled = 1;
195 int vmsvga_enabled = 0;
196 #ifdef TARGET_SPARC
197 int graphic_width = 1024;
198 int graphic_height = 768;
199 int graphic_depth = 8;
200 #else
201 int graphic_width = 800;
202 int graphic_height = 600;
203 int graphic_depth = 15;
204 #endif
205 static int full_screen = 0;
206 #ifdef CONFIG_SDL
207 static int no_frame = 0;
208 #endif
209 int no_quit = 0;
210 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
211 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
212 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
213 #ifdef TARGET_I386
214 int win2k_install_hack = 0;
215 #endif
216 int usb_enabled = 0;
217 int smp_cpus = 1;
218 const char *vnc_display;
219 int acpi_enabled = 1;
220 int no_hpet = 0;
221 int fd_bootchk = 1;
222 int no_reboot = 0;
223 int no_shutdown = 0;
224 int cursor_hide = 1;
225 int graphic_rotate = 0;
226 int daemonize = 0;
227 const char *option_rom[MAX_OPTION_ROMS];
228 int nb_option_roms;
229 int semihosting_enabled = 0;
230 #ifdef TARGET_ARM
231 int old_param = 0;
232 #endif
233 const char *qemu_name;
234 int alt_grab = 0;
235 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
236 unsigned int nb_prom_envs = 0;
237 const char *prom_envs[MAX_PROM_ENVS];
238 #endif
239 static int nb_drives_opt;
240 static struct drive_opt {
241 const char *file;
242 char opt[1024];
243 } drives_opt[MAX_DRIVES];
245 static CPUState *cur_cpu;
246 static CPUState *next_cpu;
247 static int event_pending = 1;
248 /* Conversion factor from emulated instructions to virtual clock ticks. */
249 static int icount_time_shift;
250 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
251 #define MAX_ICOUNT_SHIFT 10
252 /* Compensate for varying guest execution speed. */
253 static int64_t qemu_icount_bias;
254 static QEMUTimer *icount_rt_timer;
255 static QEMUTimer *icount_vm_timer;
257 uint8_t qemu_uuid[16];
259 /***********************************************************/
260 /* x86 ISA bus support */
262 target_phys_addr_t isa_mem_base = 0;
263 PicState2 *isa_pic;
265 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
266 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
268 static uint32_t ioport_read(int index, uint32_t address)
270 static IOPortReadFunc *default_func[3] = {
271 default_ioport_readb,
272 default_ioport_readw,
273 default_ioport_readl
275 IOPortReadFunc *func = ioport_read_table[index][address];
276 if (!func)
277 func = default_func[index];
278 return func(ioport_opaque[address], address);
281 static void ioport_write(int index, uint32_t address, uint32_t data)
283 static IOPortWriteFunc *default_func[3] = {
284 default_ioport_writeb,
285 default_ioport_writew,
286 default_ioport_writel
288 IOPortWriteFunc *func = ioport_write_table[index][address];
289 if (!func)
290 func = default_func[index];
291 func(ioport_opaque[address], address, data);
294 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
296 #ifdef DEBUG_UNUSED_IOPORT
297 fprintf(stderr, "unused inb: port=0x%04x\n", address);
298 #endif
299 return 0xff;
302 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
304 #ifdef DEBUG_UNUSED_IOPORT
305 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
306 #endif
309 /* default is to make two byte accesses */
310 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
312 uint32_t data;
313 data = ioport_read(0, address);
314 address = (address + 1) & (MAX_IOPORTS - 1);
315 data |= ioport_read(0, address) << 8;
316 return data;
319 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
321 ioport_write(0, address, data & 0xff);
322 address = (address + 1) & (MAX_IOPORTS - 1);
323 ioport_write(0, address, (data >> 8) & 0xff);
326 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
328 #ifdef DEBUG_UNUSED_IOPORT
329 fprintf(stderr, "unused inl: port=0x%04x\n", address);
330 #endif
331 return 0xffffffff;
334 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
336 #ifdef DEBUG_UNUSED_IOPORT
337 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
338 #endif
341 /* size is the word size in byte */
342 int register_ioport_read(int start, int length, int size,
343 IOPortReadFunc *func, void *opaque)
345 int i, bsize;
347 if (size == 1) {
348 bsize = 0;
349 } else if (size == 2) {
350 bsize = 1;
351 } else if (size == 4) {
352 bsize = 2;
353 } else {
354 hw_error("register_ioport_read: invalid size");
355 return -1;
357 for(i = start; i < start + length; i += size) {
358 ioport_read_table[bsize][i] = func;
359 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
360 hw_error("register_ioport_read: invalid opaque");
361 ioport_opaque[i] = opaque;
363 return 0;
366 /* size is the word size in byte */
367 int register_ioport_write(int start, int length, int size,
368 IOPortWriteFunc *func, void *opaque)
370 int i, bsize;
372 if (size == 1) {
373 bsize = 0;
374 } else if (size == 2) {
375 bsize = 1;
376 } else if (size == 4) {
377 bsize = 2;
378 } else {
379 hw_error("register_ioport_write: invalid size");
380 return -1;
382 for(i = start; i < start + length; i += size) {
383 ioport_write_table[bsize][i] = func;
384 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
385 hw_error("register_ioport_write: invalid opaque");
386 ioport_opaque[i] = opaque;
388 return 0;
391 void isa_unassign_ioport(int start, int length)
393 int i;
395 for(i = start; i < start + length; i++) {
396 ioport_read_table[0][i] = default_ioport_readb;
397 ioport_read_table[1][i] = default_ioport_readw;
398 ioport_read_table[2][i] = default_ioport_readl;
400 ioport_write_table[0][i] = default_ioport_writeb;
401 ioport_write_table[1][i] = default_ioport_writew;
402 ioport_write_table[2][i] = default_ioport_writel;
406 /***********************************************************/
408 void cpu_outb(CPUState *env, int addr, int val)
410 #ifdef DEBUG_IOPORT
411 if (loglevel & CPU_LOG_IOPORT)
412 fprintf(logfile, "outb: %04x %02x\n", addr, val);
413 #endif
414 ioport_write(0, addr, val);
415 #ifdef USE_KQEMU
416 if (env)
417 env->last_io_time = cpu_get_time_fast();
418 #endif
421 void cpu_outw(CPUState *env, int addr, int val)
423 #ifdef DEBUG_IOPORT
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "outw: %04x %04x\n", addr, val);
426 #endif
427 ioport_write(1, addr, val);
428 #ifdef USE_KQEMU
429 if (env)
430 env->last_io_time = cpu_get_time_fast();
431 #endif
434 void cpu_outl(CPUState *env, int addr, int val)
436 #ifdef DEBUG_IOPORT
437 if (loglevel & CPU_LOG_IOPORT)
438 fprintf(logfile, "outl: %04x %08x\n", addr, val);
439 #endif
440 ioport_write(2, addr, val);
441 #ifdef USE_KQEMU
442 if (env)
443 env->last_io_time = cpu_get_time_fast();
444 #endif
447 int cpu_inb(CPUState *env, int addr)
449 int val;
450 val = ioport_read(0, addr);
451 #ifdef DEBUG_IOPORT
452 if (loglevel & CPU_LOG_IOPORT)
453 fprintf(logfile, "inb : %04x %02x\n", addr, val);
454 #endif
455 #ifdef USE_KQEMU
456 if (env)
457 env->last_io_time = cpu_get_time_fast();
458 #endif
459 return val;
462 int cpu_inw(CPUState *env, int addr)
464 int val;
465 val = ioport_read(1, addr);
466 #ifdef DEBUG_IOPORT
467 if (loglevel & CPU_LOG_IOPORT)
468 fprintf(logfile, "inw : %04x %04x\n", addr, val);
469 #endif
470 #ifdef USE_KQEMU
471 if (env)
472 env->last_io_time = cpu_get_time_fast();
473 #endif
474 return val;
477 int cpu_inl(CPUState *env, int addr)
479 int val;
480 val = ioport_read(2, addr);
481 #ifdef DEBUG_IOPORT
482 if (loglevel & CPU_LOG_IOPORT)
483 fprintf(logfile, "inl : %04x %08x\n", addr, val);
484 #endif
485 #ifdef USE_KQEMU
486 if (env)
487 env->last_io_time = cpu_get_time_fast();
488 #endif
489 return val;
492 /***********************************************************/
493 void hw_error(const char *fmt, ...)
495 va_list ap;
496 CPUState *env;
498 va_start(ap, fmt);
499 fprintf(stderr, "qemu: hardware error: ");
500 vfprintf(stderr, fmt, ap);
501 fprintf(stderr, "\n");
502 for(env = first_cpu; env != NULL; env = env->next_cpu) {
503 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
504 #ifdef TARGET_I386
505 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
506 #else
507 cpu_dump_state(env, stderr, fprintf, 0);
508 #endif
510 va_end(ap);
511 abort();
514 /***************/
515 /* ballooning */
517 static QEMUBalloonEvent *qemu_balloon_event;
518 void *qemu_balloon_event_opaque;
520 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
522 qemu_balloon_event = func;
523 qemu_balloon_event_opaque = opaque;
526 void qemu_balloon(ram_addr_t target)
528 if (qemu_balloon_event)
529 qemu_balloon_event(qemu_balloon_event_opaque, target);
532 ram_addr_t qemu_balloon_status(void)
534 if (qemu_balloon_event)
535 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
536 return 0;
539 /***********************************************************/
540 /* keyboard/mouse */
542 static QEMUPutKBDEvent *qemu_put_kbd_event;
543 static void *qemu_put_kbd_event_opaque;
544 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
545 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
547 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
549 qemu_put_kbd_event_opaque = opaque;
550 qemu_put_kbd_event = func;
553 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
554 void *opaque, int absolute,
555 const char *name)
557 QEMUPutMouseEntry *s, *cursor;
559 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
560 if (!s)
561 return NULL;
563 s->qemu_put_mouse_event = func;
564 s->qemu_put_mouse_event_opaque = opaque;
565 s->qemu_put_mouse_event_absolute = absolute;
566 s->qemu_put_mouse_event_name = qemu_strdup(name);
567 s->next = NULL;
569 if (!qemu_put_mouse_event_head) {
570 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
571 return s;
574 cursor = qemu_put_mouse_event_head;
575 while (cursor->next != NULL)
576 cursor = cursor->next;
578 cursor->next = s;
579 qemu_put_mouse_event_current = s;
581 return s;
584 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
586 QEMUPutMouseEntry *prev = NULL, *cursor;
588 if (!qemu_put_mouse_event_head || entry == NULL)
589 return;
591 cursor = qemu_put_mouse_event_head;
592 while (cursor != NULL && cursor != entry) {
593 prev = cursor;
594 cursor = cursor->next;
597 if (cursor == NULL) // does not exist or list empty
598 return;
599 else if (prev == NULL) { // entry is head
600 qemu_put_mouse_event_head = cursor->next;
601 if (qemu_put_mouse_event_current == entry)
602 qemu_put_mouse_event_current = cursor->next;
603 qemu_free(entry->qemu_put_mouse_event_name);
604 qemu_free(entry);
605 return;
608 prev->next = entry->next;
610 if (qemu_put_mouse_event_current == entry)
611 qemu_put_mouse_event_current = prev;
613 qemu_free(entry->qemu_put_mouse_event_name);
614 qemu_free(entry);
617 void kbd_put_keycode(int keycode)
619 if (qemu_put_kbd_event) {
620 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
624 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
626 QEMUPutMouseEvent *mouse_event;
627 void *mouse_event_opaque;
628 int width;
630 if (!qemu_put_mouse_event_current) {
631 return;
634 mouse_event =
635 qemu_put_mouse_event_current->qemu_put_mouse_event;
636 mouse_event_opaque =
637 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
639 if (mouse_event) {
640 if (graphic_rotate) {
641 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
642 width = 0x7fff;
643 else
644 width = graphic_width - 1;
645 mouse_event(mouse_event_opaque,
646 width - dy, dx, dz, buttons_state);
647 } else
648 mouse_event(mouse_event_opaque,
649 dx, dy, dz, buttons_state);
653 int kbd_mouse_is_absolute(void)
655 if (!qemu_put_mouse_event_current)
656 return 0;
658 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
661 void do_info_mice(void)
663 QEMUPutMouseEntry *cursor;
664 int index = 0;
666 if (!qemu_put_mouse_event_head) {
667 term_printf("No mouse devices connected\n");
668 return;
671 term_printf("Mouse devices available:\n");
672 cursor = qemu_put_mouse_event_head;
673 while (cursor != NULL) {
674 term_printf("%c Mouse #%d: %s\n",
675 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
676 index, cursor->qemu_put_mouse_event_name);
677 index++;
678 cursor = cursor->next;
682 void do_mouse_set(int index)
684 QEMUPutMouseEntry *cursor;
685 int i = 0;
687 if (!qemu_put_mouse_event_head) {
688 term_printf("No mouse devices connected\n");
689 return;
692 cursor = qemu_put_mouse_event_head;
693 while (cursor != NULL && index != i) {
694 i++;
695 cursor = cursor->next;
698 if (cursor != NULL)
699 qemu_put_mouse_event_current = cursor;
700 else
701 term_printf("Mouse at given index not found\n");
704 /* compute with 96 bit intermediate result: (a*b)/c */
705 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
707 union {
708 uint64_t ll;
709 struct {
710 #ifdef WORDS_BIGENDIAN
711 uint32_t high, low;
712 #else
713 uint32_t low, high;
714 #endif
715 } l;
716 } u, res;
717 uint64_t rl, rh;
719 u.ll = a;
720 rl = (uint64_t)u.l.low * (uint64_t)b;
721 rh = (uint64_t)u.l.high * (uint64_t)b;
722 rh += (rl >> 32);
723 res.l.high = rh / c;
724 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
725 return res.ll;
728 /***********************************************************/
729 /* real time host monotonic timer */
731 #define QEMU_TIMER_BASE 1000000000LL
733 #ifdef WIN32
735 static int64_t clock_freq;
737 static void init_get_clock(void)
739 LARGE_INTEGER freq;
740 int ret;
741 ret = QueryPerformanceFrequency(&freq);
742 if (ret == 0) {
743 fprintf(stderr, "Could not calibrate ticks\n");
744 exit(1);
746 clock_freq = freq.QuadPart;
749 static int64_t get_clock(void)
751 LARGE_INTEGER ti;
752 QueryPerformanceCounter(&ti);
753 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
756 #else
758 static int use_rt_clock;
760 static void init_get_clock(void)
762 use_rt_clock = 0;
763 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
765 struct timespec ts;
766 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
767 use_rt_clock = 1;
770 #endif
773 static int64_t get_clock(void)
775 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
776 if (use_rt_clock) {
777 struct timespec ts;
778 clock_gettime(CLOCK_MONOTONIC, &ts);
779 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
780 } else
781 #endif
783 /* XXX: using gettimeofday leads to problems if the date
784 changes, so it should be avoided. */
785 struct timeval tv;
786 gettimeofday(&tv, NULL);
787 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
790 #endif
792 /* Return the virtual CPU time, based on the instruction counter. */
793 static int64_t cpu_get_icount(void)
795 int64_t icount;
796 CPUState *env = cpu_single_env;;
797 icount = qemu_icount;
798 if (env) {
799 if (!can_do_io(env))
800 fprintf(stderr, "Bad clock read\n");
801 icount -= (env->icount_decr.u16.low + env->icount_extra);
803 return qemu_icount_bias + (icount << icount_time_shift);
806 /***********************************************************/
807 /* guest cycle counter */
809 static int64_t cpu_ticks_prev;
810 static int64_t cpu_ticks_offset;
811 static int64_t cpu_clock_offset;
812 static int cpu_ticks_enabled;
814 /* return the host CPU cycle counter and handle stop/restart */
815 int64_t cpu_get_ticks(void)
817 if (use_icount) {
818 return cpu_get_icount();
820 if (!cpu_ticks_enabled) {
821 return cpu_ticks_offset;
822 } else {
823 int64_t ticks;
824 ticks = cpu_get_real_ticks();
825 if (cpu_ticks_prev > ticks) {
826 /* Note: non increasing ticks may happen if the host uses
827 software suspend */
828 cpu_ticks_offset += cpu_ticks_prev - ticks;
830 cpu_ticks_prev = ticks;
831 return ticks + cpu_ticks_offset;
835 /* return the host CPU monotonic timer and handle stop/restart */
836 static int64_t cpu_get_clock(void)
838 int64_t ti;
839 if (!cpu_ticks_enabled) {
840 return cpu_clock_offset;
841 } else {
842 ti = get_clock();
843 return ti + cpu_clock_offset;
847 /* enable cpu_get_ticks() */
848 void cpu_enable_ticks(void)
850 if (!cpu_ticks_enabled) {
851 cpu_ticks_offset -= cpu_get_real_ticks();
852 cpu_clock_offset -= get_clock();
853 cpu_ticks_enabled = 1;
857 /* disable cpu_get_ticks() : the clock is stopped. You must not call
858 cpu_get_ticks() after that. */
859 void cpu_disable_ticks(void)
861 if (cpu_ticks_enabled) {
862 cpu_ticks_offset = cpu_get_ticks();
863 cpu_clock_offset = cpu_get_clock();
864 cpu_ticks_enabled = 0;
868 /***********************************************************/
869 /* timers */
871 #define QEMU_TIMER_REALTIME 0
872 #define QEMU_TIMER_VIRTUAL 1
874 struct QEMUClock {
875 int type;
876 /* XXX: add frequency */
879 struct QEMUTimer {
880 QEMUClock *clock;
881 int64_t expire_time;
882 QEMUTimerCB *cb;
883 void *opaque;
884 struct QEMUTimer *next;
887 struct qemu_alarm_timer {
888 char const *name;
889 unsigned int flags;
891 int (*start)(struct qemu_alarm_timer *t);
892 void (*stop)(struct qemu_alarm_timer *t);
893 void (*rearm)(struct qemu_alarm_timer *t);
894 void *priv;
897 #define ALARM_FLAG_DYNTICKS 0x1
898 #define ALARM_FLAG_EXPIRED 0x2
900 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
902 return t->flags & ALARM_FLAG_DYNTICKS;
905 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
907 if (!alarm_has_dynticks(t))
908 return;
910 t->rearm(t);
913 /* TODO: MIN_TIMER_REARM_US should be optimized */
914 #define MIN_TIMER_REARM_US 250
916 static struct qemu_alarm_timer *alarm_timer;
917 #ifndef _WIN32
918 static int alarm_timer_rfd, alarm_timer_wfd;
919 #endif
921 #ifdef _WIN32
923 struct qemu_alarm_win32 {
924 MMRESULT timerId;
925 HANDLE host_alarm;
926 unsigned int period;
927 } alarm_win32_data = {0, NULL, -1};
929 static int win32_start_timer(struct qemu_alarm_timer *t);
930 static void win32_stop_timer(struct qemu_alarm_timer *t);
931 static void win32_rearm_timer(struct qemu_alarm_timer *t);
933 #else
935 static int unix_start_timer(struct qemu_alarm_timer *t);
936 static void unix_stop_timer(struct qemu_alarm_timer *t);
938 #ifdef __linux__
940 static int dynticks_start_timer(struct qemu_alarm_timer *t);
941 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
942 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
944 static int hpet_start_timer(struct qemu_alarm_timer *t);
945 static void hpet_stop_timer(struct qemu_alarm_timer *t);
947 static int rtc_start_timer(struct qemu_alarm_timer *t);
948 static void rtc_stop_timer(struct qemu_alarm_timer *t);
950 #endif /* __linux__ */
952 #endif /* _WIN32 */
954 /* Correlation between real and virtual time is always going to be
955 fairly approximate, so ignore small variation.
956 When the guest is idle real and virtual time will be aligned in
957 the IO wait loop. */
958 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
960 static void icount_adjust(void)
962 int64_t cur_time;
963 int64_t cur_icount;
964 int64_t delta;
965 static int64_t last_delta;
966 /* If the VM is not running, then do nothing. */
967 if (!vm_running)
968 return;
970 cur_time = cpu_get_clock();
971 cur_icount = qemu_get_clock(vm_clock);
972 delta = cur_icount - cur_time;
973 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
974 if (delta > 0
975 && last_delta + ICOUNT_WOBBLE < delta * 2
976 && icount_time_shift > 0) {
977 /* The guest is getting too far ahead. Slow time down. */
978 icount_time_shift--;
980 if (delta < 0
981 && last_delta - ICOUNT_WOBBLE > delta * 2
982 && icount_time_shift < MAX_ICOUNT_SHIFT) {
983 /* The guest is getting too far behind. Speed time up. */
984 icount_time_shift++;
986 last_delta = delta;
987 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
990 static void icount_adjust_rt(void * opaque)
992 qemu_mod_timer(icount_rt_timer,
993 qemu_get_clock(rt_clock) + 1000);
994 icount_adjust();
997 static void icount_adjust_vm(void * opaque)
999 qemu_mod_timer(icount_vm_timer,
1000 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1001 icount_adjust();
1004 static void init_icount_adjust(void)
1006 /* Have both realtime and virtual time triggers for speed adjustment.
1007 The realtime trigger catches emulated time passing too slowly,
1008 the virtual time trigger catches emulated time passing too fast.
1009 Realtime triggers occur even when idle, so use them less frequently
1010 than VM triggers. */
1011 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1012 qemu_mod_timer(icount_rt_timer,
1013 qemu_get_clock(rt_clock) + 1000);
1014 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1015 qemu_mod_timer(icount_vm_timer,
1016 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1019 static struct qemu_alarm_timer alarm_timers[] = {
1020 #ifndef _WIN32
1021 #ifdef __linux__
1022 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1023 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1024 /* HPET - if available - is preferred */
1025 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1026 /* ...otherwise try RTC */
1027 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1028 #endif
1029 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1030 #else
1031 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1032 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1033 {"win32", 0, win32_start_timer,
1034 win32_stop_timer, NULL, &alarm_win32_data},
1035 #endif
1036 {NULL, }
1039 static void show_available_alarms(void)
1041 int i;
1043 printf("Available alarm timers, in order of precedence:\n");
1044 for (i = 0; alarm_timers[i].name; i++)
1045 printf("%s\n", alarm_timers[i].name);
1048 static void configure_alarms(char const *opt)
1050 int i;
1051 int cur = 0;
1052 int count = ARRAY_SIZE(alarm_timers) - 1;
1053 char *arg;
1054 char *name;
1055 struct qemu_alarm_timer tmp;
1057 if (!strcmp(opt, "?")) {
1058 show_available_alarms();
1059 exit(0);
1062 arg = strdup(opt);
1064 /* Reorder the array */
1065 name = strtok(arg, ",");
1066 while (name) {
1067 for (i = 0; i < count && alarm_timers[i].name; i++) {
1068 if (!strcmp(alarm_timers[i].name, name))
1069 break;
1072 if (i == count) {
1073 fprintf(stderr, "Unknown clock %s\n", name);
1074 goto next;
1077 if (i < cur)
1078 /* Ignore */
1079 goto next;
1081 /* Swap */
1082 tmp = alarm_timers[i];
1083 alarm_timers[i] = alarm_timers[cur];
1084 alarm_timers[cur] = tmp;
1086 cur++;
1087 next:
1088 name = strtok(NULL, ",");
1091 free(arg);
1093 if (cur) {
1094 /* Disable remaining timers */
1095 for (i = cur; i < count; i++)
1096 alarm_timers[i].name = NULL;
1097 } else {
1098 show_available_alarms();
1099 exit(1);
1103 QEMUClock *rt_clock;
1104 QEMUClock *vm_clock;
1106 static QEMUTimer *active_timers[2];
1108 static QEMUClock *qemu_new_clock(int type)
1110 QEMUClock *clock;
1111 clock = qemu_mallocz(sizeof(QEMUClock));
1112 if (!clock)
1113 return NULL;
1114 clock->type = type;
1115 return clock;
1118 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1120 QEMUTimer *ts;
1122 ts = qemu_mallocz(sizeof(QEMUTimer));
1123 ts->clock = clock;
1124 ts->cb = cb;
1125 ts->opaque = opaque;
1126 return ts;
1129 void qemu_free_timer(QEMUTimer *ts)
1131 qemu_free(ts);
1134 /* stop a timer, but do not dealloc it */
1135 void qemu_del_timer(QEMUTimer *ts)
1137 QEMUTimer **pt, *t;
1139 /* NOTE: this code must be signal safe because
1140 qemu_timer_expired() can be called from a signal. */
1141 pt = &active_timers[ts->clock->type];
1142 for(;;) {
1143 t = *pt;
1144 if (!t)
1145 break;
1146 if (t == ts) {
1147 *pt = t->next;
1148 break;
1150 pt = &t->next;
1154 /* modify the current timer so that it will be fired when current_time
1155 >= expire_time. The corresponding callback will be called. */
1156 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1158 QEMUTimer **pt, *t;
1160 qemu_del_timer(ts);
1162 /* add the timer in the sorted list */
1163 /* NOTE: this code must be signal safe because
1164 qemu_timer_expired() can be called from a signal. */
1165 pt = &active_timers[ts->clock->type];
1166 for(;;) {
1167 t = *pt;
1168 if (!t)
1169 break;
1170 if (t->expire_time > expire_time)
1171 break;
1172 pt = &t->next;
1174 ts->expire_time = expire_time;
1175 ts->next = *pt;
1176 *pt = ts;
1178 /* Rearm if necessary */
1179 if (pt == &active_timers[ts->clock->type]) {
1180 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1181 qemu_rearm_alarm_timer(alarm_timer);
1183 /* Interrupt execution to force deadline recalculation. */
1184 if (use_icount && cpu_single_env) {
1185 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1190 int qemu_timer_pending(QEMUTimer *ts)
1192 QEMUTimer *t;
1193 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1194 if (t == ts)
1195 return 1;
1197 return 0;
1200 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1202 if (!timer_head)
1203 return 0;
1204 return (timer_head->expire_time <= current_time);
1207 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1209 QEMUTimer *ts;
1211 for(;;) {
1212 ts = *ptimer_head;
1213 if (!ts || ts->expire_time > current_time)
1214 break;
1215 /* remove timer from the list before calling the callback */
1216 *ptimer_head = ts->next;
1217 ts->next = NULL;
1219 /* run the callback (the timer list can be modified) */
1220 ts->cb(ts->opaque);
1224 int64_t qemu_get_clock(QEMUClock *clock)
1226 switch(clock->type) {
1227 case QEMU_TIMER_REALTIME:
1228 return get_clock() / 1000000;
1229 default:
1230 case QEMU_TIMER_VIRTUAL:
1231 if (use_icount) {
1232 return cpu_get_icount();
1233 } else {
1234 return cpu_get_clock();
1239 static void init_timers(void)
1241 init_get_clock();
1242 ticks_per_sec = QEMU_TIMER_BASE;
1243 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1244 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1247 /* save a timer */
1248 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1250 uint64_t expire_time;
1252 if (qemu_timer_pending(ts)) {
1253 expire_time = ts->expire_time;
1254 } else {
1255 expire_time = -1;
1257 qemu_put_be64(f, expire_time);
1260 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1262 uint64_t expire_time;
1264 expire_time = qemu_get_be64(f);
1265 if (expire_time != -1) {
1266 qemu_mod_timer(ts, expire_time);
1267 } else {
1268 qemu_del_timer(ts);
1272 static void timer_save(QEMUFile *f, void *opaque)
1274 if (cpu_ticks_enabled) {
1275 hw_error("cannot save state if virtual timers are running");
1277 qemu_put_be64(f, cpu_ticks_offset);
1278 qemu_put_be64(f, ticks_per_sec);
1279 qemu_put_be64(f, cpu_clock_offset);
1282 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1284 if (version_id != 1 && version_id != 2)
1285 return -EINVAL;
1286 if (cpu_ticks_enabled) {
1287 return -EINVAL;
1289 cpu_ticks_offset=qemu_get_be64(f);
1290 ticks_per_sec=qemu_get_be64(f);
1291 if (version_id == 2) {
1292 cpu_clock_offset=qemu_get_be64(f);
1294 return 0;
1297 #ifdef _WIN32
1298 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1299 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1300 #else
1301 static void host_alarm_handler(int host_signum)
1302 #endif
1304 #if 0
1305 #define DISP_FREQ 1000
1307 static int64_t delta_min = INT64_MAX;
1308 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1309 static int count;
1310 ti = qemu_get_clock(vm_clock);
1311 if (last_clock != 0) {
1312 delta = ti - last_clock;
1313 if (delta < delta_min)
1314 delta_min = delta;
1315 if (delta > delta_max)
1316 delta_max = delta;
1317 delta_cum += delta;
1318 if (++count == DISP_FREQ) {
1319 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1320 muldiv64(delta_min, 1000000, ticks_per_sec),
1321 muldiv64(delta_max, 1000000, ticks_per_sec),
1322 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1323 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1324 count = 0;
1325 delta_min = INT64_MAX;
1326 delta_max = 0;
1327 delta_cum = 0;
1330 last_clock = ti;
1332 #endif
1333 if (alarm_has_dynticks(alarm_timer) ||
1334 (!use_icount &&
1335 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1336 qemu_get_clock(vm_clock))) ||
1337 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1338 qemu_get_clock(rt_clock))) {
1339 CPUState *env = next_cpu;
1341 #ifdef _WIN32
1342 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1343 SetEvent(data->host_alarm);
1344 #else
1345 static const char byte = 0;
1346 write(alarm_timer_wfd, &byte, sizeof(byte));
1347 #endif
1348 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1350 if (env) {
1351 /* stop the currently executing cpu because a timer occured */
1352 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1353 #ifdef USE_KQEMU
1354 if (env->kqemu_enabled) {
1355 kqemu_cpu_interrupt(env);
1357 #endif
1359 event_pending = 1;
1363 static int64_t qemu_next_deadline(void)
1365 int64_t delta;
1367 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1368 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1369 qemu_get_clock(vm_clock);
1370 } else {
1371 /* To avoid problems with overflow limit this to 2^32. */
1372 delta = INT32_MAX;
1375 if (delta < 0)
1376 delta = 0;
1378 return delta;
1381 #if defined(__linux__) || defined(_WIN32)
1382 static uint64_t qemu_next_deadline_dyntick(void)
1384 int64_t delta;
1385 int64_t rtdelta;
1387 if (use_icount)
1388 delta = INT32_MAX;
1389 else
1390 delta = (qemu_next_deadline() + 999) / 1000;
1392 if (active_timers[QEMU_TIMER_REALTIME]) {
1393 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1394 qemu_get_clock(rt_clock))*1000;
1395 if (rtdelta < delta)
1396 delta = rtdelta;
1399 if (delta < MIN_TIMER_REARM_US)
1400 delta = MIN_TIMER_REARM_US;
1402 return delta;
1404 #endif
1406 #ifndef _WIN32
1408 /* Sets a specific flag */
1409 static int fcntl_setfl(int fd, int flag)
1411 int flags;
1413 flags = fcntl(fd, F_GETFL);
1414 if (flags == -1)
1415 return -errno;
1417 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1418 return -errno;
1420 return 0;
1423 #if defined(__linux__)
1425 #define RTC_FREQ 1024
1427 static void enable_sigio_timer(int fd)
1429 struct sigaction act;
1431 /* timer signal */
1432 sigfillset(&act.sa_mask);
1433 act.sa_flags = 0;
1434 act.sa_handler = host_alarm_handler;
1436 sigaction(SIGIO, &act, NULL);
1437 fcntl_setfl(fd, O_ASYNC);
1438 fcntl(fd, F_SETOWN, getpid());
1441 static int hpet_start_timer(struct qemu_alarm_timer *t)
1443 struct hpet_info info;
1444 int r, fd;
1446 fd = open("/dev/hpet", O_RDONLY);
1447 if (fd < 0)
1448 return -1;
1450 /* Set frequency */
1451 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1452 if (r < 0) {
1453 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1454 "error, but for better emulation accuracy type:\n"
1455 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1456 goto fail;
1459 /* Check capabilities */
1460 r = ioctl(fd, HPET_INFO, &info);
1461 if (r < 0)
1462 goto fail;
1464 /* Enable periodic mode */
1465 r = ioctl(fd, HPET_EPI, 0);
1466 if (info.hi_flags && (r < 0))
1467 goto fail;
1469 /* Enable interrupt */
1470 r = ioctl(fd, HPET_IE_ON, 0);
1471 if (r < 0)
1472 goto fail;
1474 enable_sigio_timer(fd);
1475 t->priv = (void *)(long)fd;
1477 return 0;
1478 fail:
1479 close(fd);
1480 return -1;
1483 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1485 int fd = (long)t->priv;
1487 close(fd);
1490 static int rtc_start_timer(struct qemu_alarm_timer *t)
1492 int rtc_fd;
1493 unsigned long current_rtc_freq = 0;
1495 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1496 if (rtc_fd < 0)
1497 return -1;
1498 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1499 if (current_rtc_freq != RTC_FREQ &&
1500 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1501 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1502 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1503 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1504 goto fail;
1506 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1507 fail:
1508 close(rtc_fd);
1509 return -1;
1512 enable_sigio_timer(rtc_fd);
1514 t->priv = (void *)(long)rtc_fd;
1516 return 0;
1519 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1521 int rtc_fd = (long)t->priv;
1523 close(rtc_fd);
1526 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1528 struct sigevent ev;
1529 timer_t host_timer;
1530 struct sigaction act;
1532 sigfillset(&act.sa_mask);
1533 act.sa_flags = 0;
1534 act.sa_handler = host_alarm_handler;
1536 sigaction(SIGALRM, &act, NULL);
1538 ev.sigev_value.sival_int = 0;
1539 ev.sigev_notify = SIGEV_SIGNAL;
1540 ev.sigev_signo = SIGALRM;
1542 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1543 perror("timer_create");
1545 /* disable dynticks */
1546 fprintf(stderr, "Dynamic Ticks disabled\n");
1548 return -1;
1551 t->priv = (void *)(long)host_timer;
1553 return 0;
1556 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1558 timer_t host_timer = (timer_t)(long)t->priv;
1560 timer_delete(host_timer);
1563 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1565 timer_t host_timer = (timer_t)(long)t->priv;
1566 struct itimerspec timeout;
1567 int64_t nearest_delta_us = INT64_MAX;
1568 int64_t current_us;
1570 if (!active_timers[QEMU_TIMER_REALTIME] &&
1571 !active_timers[QEMU_TIMER_VIRTUAL])
1572 return;
1574 nearest_delta_us = qemu_next_deadline_dyntick();
1576 /* check whether a timer is already running */
1577 if (timer_gettime(host_timer, &timeout)) {
1578 perror("gettime");
1579 fprintf(stderr, "Internal timer error: aborting\n");
1580 exit(1);
1582 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1583 if (current_us && current_us <= nearest_delta_us)
1584 return;
1586 timeout.it_interval.tv_sec = 0;
1587 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1588 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1589 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1590 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1591 perror("settime");
1592 fprintf(stderr, "Internal timer error: aborting\n");
1593 exit(1);
1597 #endif /* defined(__linux__) */
1599 static int unix_start_timer(struct qemu_alarm_timer *t)
1601 struct sigaction act;
1602 struct itimerval itv;
1603 int err;
1605 /* timer signal */
1606 sigfillset(&act.sa_mask);
1607 act.sa_flags = 0;
1608 act.sa_handler = host_alarm_handler;
1610 sigaction(SIGALRM, &act, NULL);
1612 itv.it_interval.tv_sec = 0;
1613 /* for i386 kernel 2.6 to get 1 ms */
1614 itv.it_interval.tv_usec = 999;
1615 itv.it_value.tv_sec = 0;
1616 itv.it_value.tv_usec = 10 * 1000;
1618 err = setitimer(ITIMER_REAL, &itv, NULL);
1619 if (err)
1620 return -1;
1622 return 0;
1625 static void unix_stop_timer(struct qemu_alarm_timer *t)
1627 struct itimerval itv;
1629 memset(&itv, 0, sizeof(itv));
1630 setitimer(ITIMER_REAL, &itv, NULL);
1633 #endif /* !defined(_WIN32) */
1635 static void try_to_rearm_timer(void *opaque)
1637 struct qemu_alarm_timer *t = opaque;
1638 #ifndef _WIN32
1639 ssize_t len;
1641 /* Drain the notify pipe */
1642 do {
1643 char buffer[512];
1644 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1645 } while ((len == -1 && errno == EINTR) || len > 0);
1646 #endif
1648 if (t->flags & ALARM_FLAG_EXPIRED) {
1649 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1650 qemu_rearm_alarm_timer(alarm_timer);
1654 #ifdef _WIN32
1656 static int win32_start_timer(struct qemu_alarm_timer *t)
1658 TIMECAPS tc;
1659 struct qemu_alarm_win32 *data = t->priv;
1660 UINT flags;
1662 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1663 if (!data->host_alarm) {
1664 perror("Failed CreateEvent");
1665 return -1;
1668 memset(&tc, 0, sizeof(tc));
1669 timeGetDevCaps(&tc, sizeof(tc));
1671 if (data->period < tc.wPeriodMin)
1672 data->period = tc.wPeriodMin;
1674 timeBeginPeriod(data->period);
1676 flags = TIME_CALLBACK_FUNCTION;
1677 if (alarm_has_dynticks(t))
1678 flags |= TIME_ONESHOT;
1679 else
1680 flags |= TIME_PERIODIC;
1682 data->timerId = timeSetEvent(1, // interval (ms)
1683 data->period, // resolution
1684 host_alarm_handler, // function
1685 (DWORD)t, // parameter
1686 flags);
1688 if (!data->timerId) {
1689 perror("Failed to initialize win32 alarm timer");
1691 timeEndPeriod(data->period);
1692 CloseHandle(data->host_alarm);
1693 return -1;
1696 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1698 return 0;
1701 static void win32_stop_timer(struct qemu_alarm_timer *t)
1703 struct qemu_alarm_win32 *data = t->priv;
1705 timeKillEvent(data->timerId);
1706 timeEndPeriod(data->period);
1708 CloseHandle(data->host_alarm);
1711 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1713 struct qemu_alarm_win32 *data = t->priv;
1714 uint64_t nearest_delta_us;
1716 if (!active_timers[QEMU_TIMER_REALTIME] &&
1717 !active_timers[QEMU_TIMER_VIRTUAL])
1718 return;
1720 nearest_delta_us = qemu_next_deadline_dyntick();
1721 nearest_delta_us /= 1000;
1723 timeKillEvent(data->timerId);
1725 data->timerId = timeSetEvent(1,
1726 data->period,
1727 host_alarm_handler,
1728 (DWORD)t,
1729 TIME_ONESHOT | TIME_PERIODIC);
1731 if (!data->timerId) {
1732 perror("Failed to re-arm win32 alarm timer");
1734 timeEndPeriod(data->period);
1735 CloseHandle(data->host_alarm);
1736 exit(1);
1740 #endif /* _WIN32 */
1742 static int init_timer_alarm(void)
1744 struct qemu_alarm_timer *t = NULL;
1745 int i, err = -1;
1747 #ifndef _WIN32
1748 int fds[2];
1750 err = pipe(fds);
1751 if (err == -1)
1752 return -errno;
1754 err = fcntl_setfl(fds[0], O_NONBLOCK);
1755 if (err < 0)
1756 goto fail;
1758 err = fcntl_setfl(fds[1], O_NONBLOCK);
1759 if (err < 0)
1760 goto fail;
1762 alarm_timer_rfd = fds[0];
1763 alarm_timer_wfd = fds[1];
1764 #endif
1766 for (i = 0; alarm_timers[i].name; i++) {
1767 t = &alarm_timers[i];
1769 err = t->start(t);
1770 if (!err)
1771 break;
1774 if (err) {
1775 err = -ENOENT;
1776 goto fail;
1779 #ifndef _WIN32
1780 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1781 try_to_rearm_timer, NULL, t);
1782 #endif
1784 alarm_timer = t;
1786 return 0;
1788 fail:
1789 #ifndef _WIN32
1790 close(fds[0]);
1791 close(fds[1]);
1792 #endif
1793 return err;
1796 static void quit_timers(void)
1798 alarm_timer->stop(alarm_timer);
1799 alarm_timer = NULL;
1802 /***********************************************************/
1803 /* host time/date access */
1804 void qemu_get_timedate(struct tm *tm, int offset)
1806 time_t ti;
1807 struct tm *ret;
1809 time(&ti);
1810 ti += offset;
1811 if (rtc_date_offset == -1) {
1812 if (rtc_utc)
1813 ret = gmtime(&ti);
1814 else
1815 ret = localtime(&ti);
1816 } else {
1817 ti -= rtc_date_offset;
1818 ret = gmtime(&ti);
1821 memcpy(tm, ret, sizeof(struct tm));
1824 int qemu_timedate_diff(struct tm *tm)
1826 time_t seconds;
1828 if (rtc_date_offset == -1)
1829 if (rtc_utc)
1830 seconds = mktimegm(tm);
1831 else
1832 seconds = mktime(tm);
1833 else
1834 seconds = mktimegm(tm) + rtc_date_offset;
1836 return seconds - time(NULL);
1839 #ifdef _WIN32
1840 static void socket_cleanup(void)
1842 WSACleanup();
1845 static int socket_init(void)
1847 WSADATA Data;
1848 int ret, err;
1850 ret = WSAStartup(MAKEWORD(2,2), &Data);
1851 if (ret != 0) {
1852 err = WSAGetLastError();
1853 fprintf(stderr, "WSAStartup: %d\n", err);
1854 return -1;
1856 atexit(socket_cleanup);
1857 return 0;
1859 #endif
1861 const char *get_opt_name(char *buf, int buf_size, const char *p)
1863 char *q;
1865 q = buf;
1866 while (*p != '\0' && *p != '=') {
1867 if (q && (q - buf) < buf_size - 1)
1868 *q++ = *p;
1869 p++;
1871 if (q)
1872 *q = '\0';
1874 return p;
1877 const char *get_opt_value(char *buf, int buf_size, const char *p)
1879 char *q;
1881 q = buf;
1882 while (*p != '\0') {
1883 if (*p == ',') {
1884 if (*(p + 1) != ',')
1885 break;
1886 p++;
1888 if (q && (q - buf) < buf_size - 1)
1889 *q++ = *p;
1890 p++;
1892 if (q)
1893 *q = '\0';
1895 return p;
1898 int get_param_value(char *buf, int buf_size,
1899 const char *tag, const char *str)
1901 const char *p;
1902 char option[128];
1904 p = str;
1905 for(;;) {
1906 p = get_opt_name(option, sizeof(option), p);
1907 if (*p != '=')
1908 break;
1909 p++;
1910 if (!strcmp(tag, option)) {
1911 (void)get_opt_value(buf, buf_size, p);
1912 return strlen(buf);
1913 } else {
1914 p = get_opt_value(NULL, 0, p);
1916 if (*p != ',')
1917 break;
1918 p++;
1920 return 0;
1923 int check_params(char *buf, int buf_size,
1924 const char * const *params, const char *str)
1926 const char *p;
1927 int i;
1929 p = str;
1930 for(;;) {
1931 p = get_opt_name(buf, buf_size, p);
1932 if (*p != '=')
1933 return -1;
1934 p++;
1935 for(i = 0; params[i] != NULL; i++)
1936 if (!strcmp(params[i], buf))
1937 break;
1938 if (params[i] == NULL)
1939 return -1;
1940 p = get_opt_value(NULL, 0, p);
1941 if (*p != ',')
1942 break;
1943 p++;
1945 return 0;
1948 /***********************************************************/
1949 /* Bluetooth support */
1950 static int nb_hcis;
1951 static int cur_hci;
1952 static struct HCIInfo *hci_table[MAX_NICS];
1954 static struct bt_vlan_s {
1955 struct bt_scatternet_s net;
1956 int id;
1957 struct bt_vlan_s *next;
1958 } *first_bt_vlan;
1960 /* find or alloc a new bluetooth "VLAN" */
1961 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1963 struct bt_vlan_s **pvlan, *vlan;
1964 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1965 if (vlan->id == id)
1966 return &vlan->net;
1968 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1969 vlan->id = id;
1970 pvlan = &first_bt_vlan;
1971 while (*pvlan != NULL)
1972 pvlan = &(*pvlan)->next;
1973 *pvlan = vlan;
1974 return &vlan->net;
1977 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1981 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1983 return -ENOTSUP;
1986 static struct HCIInfo null_hci = {
1987 .cmd_send = null_hci_send,
1988 .sco_send = null_hci_send,
1989 .acl_send = null_hci_send,
1990 .bdaddr_set = null_hci_addr_set,
1993 struct HCIInfo *qemu_next_hci(void)
1995 if (cur_hci == nb_hcis)
1996 return &null_hci;
1998 return hci_table[cur_hci++];
2001 static struct HCIInfo *hci_init(const char *str)
2003 char *endp;
2004 struct bt_scatternet_s *vlan = 0;
2006 if (!strcmp(str, "null"))
2007 /* null */
2008 return &null_hci;
2009 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2010 /* host[:hciN] */
2011 return bt_host_hci(str[4] ? str + 5 : "hci0");
2012 else if (!strncmp(str, "hci", 3)) {
2013 /* hci[,vlan=n] */
2014 if (str[3]) {
2015 if (!strncmp(str + 3, ",vlan=", 6)) {
2016 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2017 if (*endp)
2018 vlan = 0;
2020 } else
2021 vlan = qemu_find_bt_vlan(0);
2022 if (vlan)
2023 return bt_new_hci(vlan);
2026 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2028 return 0;
2031 static int bt_hci_parse(const char *str)
2033 struct HCIInfo *hci;
2034 bdaddr_t bdaddr;
2036 if (nb_hcis >= MAX_NICS) {
2037 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2038 return -1;
2041 hci = hci_init(str);
2042 if (!hci)
2043 return -1;
2045 bdaddr.b[0] = 0x52;
2046 bdaddr.b[1] = 0x54;
2047 bdaddr.b[2] = 0x00;
2048 bdaddr.b[3] = 0x12;
2049 bdaddr.b[4] = 0x34;
2050 bdaddr.b[5] = 0x56 + nb_hcis;
2051 hci->bdaddr_set(hci, bdaddr.b);
2053 hci_table[nb_hcis++] = hci;
2055 return 0;
2058 static void bt_vhci_add(int vlan_id)
2060 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2062 if (!vlan->slave)
2063 fprintf(stderr, "qemu: warning: adding a VHCI to "
2064 "an empty scatternet %i\n", vlan_id);
2066 bt_vhci_init(bt_new_hci(vlan));
2069 static struct bt_device_s *bt_device_add(const char *opt)
2071 struct bt_scatternet_s *vlan;
2072 int vlan_id = 0;
2073 char *endp = strstr(opt, ",vlan=");
2074 int len = (endp ? endp - opt : strlen(opt)) + 1;
2075 char devname[10];
2077 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2079 if (endp) {
2080 vlan_id = strtol(endp + 6, &endp, 0);
2081 if (*endp) {
2082 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2083 return 0;
2087 vlan = qemu_find_bt_vlan(vlan_id);
2089 if (!vlan->slave)
2090 fprintf(stderr, "qemu: warning: adding a slave device to "
2091 "an empty scatternet %i\n", vlan_id);
2093 if (!strcmp(devname, "keyboard"))
2094 return bt_keyboard_init(vlan);
2096 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2097 return 0;
2100 static int bt_parse(const char *opt)
2102 const char *endp, *p;
2103 int vlan;
2105 if (strstart(opt, "hci", &endp)) {
2106 if (!*endp || *endp == ',') {
2107 if (*endp)
2108 if (!strstart(endp, ",vlan=", 0))
2109 opt = endp + 1;
2111 return bt_hci_parse(opt);
2113 } else if (strstart(opt, "vhci", &endp)) {
2114 if (!*endp || *endp == ',') {
2115 if (*endp) {
2116 if (strstart(endp, ",vlan=", &p)) {
2117 vlan = strtol(p, (char **) &endp, 0);
2118 if (*endp) {
2119 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2120 return 1;
2122 } else {
2123 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2124 return 1;
2126 } else
2127 vlan = 0;
2129 bt_vhci_add(vlan);
2130 return 0;
2132 } else if (strstart(opt, "device:", &endp))
2133 return !bt_device_add(endp);
2135 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2136 return 1;
2139 /***********************************************************/
2140 /* QEMU Block devices */
2142 #define HD_ALIAS "index=%d,media=disk"
2143 #ifdef TARGET_PPC
2144 #define CDROM_ALIAS "index=1,media=cdrom"
2145 #else
2146 #define CDROM_ALIAS "index=2,media=cdrom"
2147 #endif
2148 #define FD_ALIAS "index=%d,if=floppy"
2149 #define PFLASH_ALIAS "if=pflash"
2150 #define MTD_ALIAS "if=mtd"
2151 #define SD_ALIAS "index=0,if=sd"
2153 static int drive_add(const char *file, const char *fmt, ...)
2155 va_list ap;
2157 if (nb_drives_opt >= MAX_DRIVES) {
2158 fprintf(stderr, "qemu: too many drives\n");
2159 exit(1);
2162 drives_opt[nb_drives_opt].file = file;
2163 va_start(ap, fmt);
2164 vsnprintf(drives_opt[nb_drives_opt].opt,
2165 sizeof(drives_opt[0].opt), fmt, ap);
2166 va_end(ap);
2168 return nb_drives_opt++;
2171 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2173 int index;
2175 /* seek interface, bus and unit */
2177 for (index = 0; index < nb_drives; index++)
2178 if (drives_table[index].type == type &&
2179 drives_table[index].bus == bus &&
2180 drives_table[index].unit == unit)
2181 return index;
2183 return -1;
2186 int drive_get_max_bus(BlockInterfaceType type)
2188 int max_bus;
2189 int index;
2191 max_bus = -1;
2192 for (index = 0; index < nb_drives; index++) {
2193 if(drives_table[index].type == type &&
2194 drives_table[index].bus > max_bus)
2195 max_bus = drives_table[index].bus;
2197 return max_bus;
2200 const char *drive_get_serial(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].serial;
2208 return "\0";
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;
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", NULL };
2240 if (check_params(buf, sizeof(buf), params, str) < 0) {
2241 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2242 buf, str);
2243 return -1;
2246 file[0] = 0;
2247 cyls = heads = secs = 0;
2248 bus_id = 0;
2249 unit_id = -1;
2250 translation = BIOS_ATA_TRANSLATION_AUTO;
2251 index = -1;
2252 cache = 3;
2254 if (machine->use_scsi) {
2255 type = IF_SCSI;
2256 max_devs = MAX_SCSI_DEVS;
2257 pstrcpy(devname, sizeof(devname), "scsi");
2258 } else {
2259 type = IF_IDE;
2260 max_devs = MAX_IDE_DEVS;
2261 pstrcpy(devname, sizeof(devname), "ide");
2263 media = MEDIA_DISK;
2265 /* extract parameters */
2267 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2268 bus_id = strtol(buf, NULL, 0);
2269 if (bus_id < 0) {
2270 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2271 return -1;
2275 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2276 unit_id = strtol(buf, NULL, 0);
2277 if (unit_id < 0) {
2278 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2279 return -1;
2283 if (get_param_value(buf, sizeof(buf), "if", str)) {
2284 pstrcpy(devname, sizeof(devname), buf);
2285 if (!strcmp(buf, "ide")) {
2286 type = IF_IDE;
2287 max_devs = MAX_IDE_DEVS;
2288 } else if (!strcmp(buf, "scsi")) {
2289 type = IF_SCSI;
2290 max_devs = MAX_SCSI_DEVS;
2291 } else if (!strcmp(buf, "floppy")) {
2292 type = IF_FLOPPY;
2293 max_devs = 0;
2294 } else if (!strcmp(buf, "pflash")) {
2295 type = IF_PFLASH;
2296 max_devs = 0;
2297 } else if (!strcmp(buf, "mtd")) {
2298 type = IF_MTD;
2299 max_devs = 0;
2300 } else if (!strcmp(buf, "sd")) {
2301 type = IF_SD;
2302 max_devs = 0;
2303 } else if (!strcmp(buf, "virtio")) {
2304 type = IF_VIRTIO;
2305 max_devs = 0;
2306 } else {
2307 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2308 return -1;
2312 if (get_param_value(buf, sizeof(buf), "index", str)) {
2313 index = strtol(buf, NULL, 0);
2314 if (index < 0) {
2315 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2316 return -1;
2320 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2321 cyls = strtol(buf, NULL, 0);
2324 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2325 heads = strtol(buf, NULL, 0);
2328 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2329 secs = strtol(buf, NULL, 0);
2332 if (cyls || heads || secs) {
2333 if (cyls < 1 || cyls > 16383) {
2334 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2335 return -1;
2337 if (heads < 1 || heads > 16) {
2338 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2339 return -1;
2341 if (secs < 1 || secs > 63) {
2342 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2343 return -1;
2347 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2348 if (!cyls) {
2349 fprintf(stderr,
2350 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2351 str);
2352 return -1;
2354 if (!strcmp(buf, "none"))
2355 translation = BIOS_ATA_TRANSLATION_NONE;
2356 else if (!strcmp(buf, "lba"))
2357 translation = BIOS_ATA_TRANSLATION_LBA;
2358 else if (!strcmp(buf, "auto"))
2359 translation = BIOS_ATA_TRANSLATION_AUTO;
2360 else {
2361 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2362 return -1;
2366 if (get_param_value(buf, sizeof(buf), "media", str)) {
2367 if (!strcmp(buf, "disk")) {
2368 media = MEDIA_DISK;
2369 } else if (!strcmp(buf, "cdrom")) {
2370 if (cyls || secs || heads) {
2371 fprintf(stderr,
2372 "qemu: '%s' invalid physical CHS format\n", str);
2373 return -1;
2375 media = MEDIA_CDROM;
2376 } else {
2377 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2378 return -1;
2382 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2383 if (!strcmp(buf, "on"))
2384 snapshot = 1;
2385 else if (!strcmp(buf, "off"))
2386 snapshot = 0;
2387 else {
2388 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2389 return -1;
2393 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2394 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2395 cache = 0;
2396 else if (!strcmp(buf, "writethrough"))
2397 cache = 1;
2398 else if (!strcmp(buf, "writeback"))
2399 cache = 2;
2400 else {
2401 fprintf(stderr, "qemu: invalid cache option\n");
2402 return -1;
2406 if (get_param_value(buf, sizeof(buf), "format", str)) {
2407 if (strcmp(buf, "?") == 0) {
2408 fprintf(stderr, "qemu: Supported formats:");
2409 bdrv_iterate_format(bdrv_format_print, NULL);
2410 fprintf(stderr, "\n");
2411 return -1;
2413 drv = bdrv_find_format(buf);
2414 if (!drv) {
2415 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2416 return -1;
2420 if (arg->file == NULL)
2421 get_param_value(file, sizeof(file), "file", str);
2422 else
2423 pstrcpy(file, sizeof(file), arg->file);
2425 if (!get_param_value(serial, sizeof(serial), "serial", str))
2426 memset(serial, 0, sizeof(serial));
2428 /* compute bus and unit according index */
2430 if (index != -1) {
2431 if (bus_id != 0 || unit_id != -1) {
2432 fprintf(stderr,
2433 "qemu: '%s' index cannot be used with bus and unit\n", str);
2434 return -1;
2436 if (max_devs == 0)
2438 unit_id = index;
2439 bus_id = 0;
2440 } else {
2441 unit_id = index % max_devs;
2442 bus_id = index / max_devs;
2446 /* if user doesn't specify a unit_id,
2447 * try to find the first free
2450 if (unit_id == -1) {
2451 unit_id = 0;
2452 while (drive_get_index(type, bus_id, unit_id) != -1) {
2453 unit_id++;
2454 if (max_devs && unit_id >= max_devs) {
2455 unit_id -= max_devs;
2456 bus_id++;
2461 /* check unit id */
2463 if (max_devs && unit_id >= max_devs) {
2464 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2465 str, unit_id, max_devs - 1);
2466 return -1;
2470 * ignore multiple definitions
2473 if (drive_get_index(type, bus_id, unit_id) != -1)
2474 return 0;
2476 /* init */
2478 if (type == IF_IDE || type == IF_SCSI)
2479 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2480 if (max_devs)
2481 snprintf(buf, sizeof(buf), "%s%i%s%i",
2482 devname, bus_id, mediastr, unit_id);
2483 else
2484 snprintf(buf, sizeof(buf), "%s%s%i",
2485 devname, mediastr, unit_id);
2486 bdrv = bdrv_new(buf);
2487 drives_table[nb_drives].bdrv = bdrv;
2488 drives_table[nb_drives].type = type;
2489 drives_table[nb_drives].bus = bus_id;
2490 drives_table[nb_drives].unit = unit_id;
2491 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2492 nb_drives++;
2494 switch(type) {
2495 case IF_IDE:
2496 case IF_SCSI:
2497 switch(media) {
2498 case MEDIA_DISK:
2499 if (cyls != 0) {
2500 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2501 bdrv_set_translation_hint(bdrv, translation);
2503 break;
2504 case MEDIA_CDROM:
2505 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2506 break;
2508 break;
2509 case IF_SD:
2510 /* FIXME: This isn't really a floppy, but it's a reasonable
2511 approximation. */
2512 case IF_FLOPPY:
2513 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2514 break;
2515 case IF_PFLASH:
2516 case IF_MTD:
2517 case IF_VIRTIO:
2518 break;
2520 if (!file[0])
2521 return 0;
2522 bdrv_flags = 0;
2523 if (snapshot) {
2524 bdrv_flags |= BDRV_O_SNAPSHOT;
2525 cache = 2; /* always use write-back with snapshot */
2527 if (cache == 0) /* no caching */
2528 bdrv_flags |= BDRV_O_NOCACHE;
2529 else if (cache == 2) /* write-back */
2530 bdrv_flags |= BDRV_O_CACHE_WB;
2531 else if (cache == 3) /* not specified */
2532 bdrv_flags |= BDRV_O_CACHE_DEF;
2533 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2534 fprintf(stderr, "qemu: could not open disk image %s\n",
2535 file);
2536 return -1;
2538 return 0;
2541 /***********************************************************/
2542 /* USB devices */
2544 static USBPort *used_usb_ports;
2545 static USBPort *free_usb_ports;
2547 /* ??? Maybe change this to register a hub to keep track of the topology. */
2548 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2549 usb_attachfn attach)
2551 port->opaque = opaque;
2552 port->index = index;
2553 port->attach = attach;
2554 port->next = free_usb_ports;
2555 free_usb_ports = port;
2558 int usb_device_add_dev(USBDevice *dev)
2560 USBPort *port;
2562 /* Find a USB port to add the device to. */
2563 port = free_usb_ports;
2564 if (!port->next) {
2565 USBDevice *hub;
2567 /* Create a new hub and chain it on. */
2568 free_usb_ports = NULL;
2569 port->next = used_usb_ports;
2570 used_usb_ports = port;
2572 hub = usb_hub_init(VM_USB_HUB_SIZE);
2573 usb_attach(port, hub);
2574 port = free_usb_ports;
2577 free_usb_ports = port->next;
2578 port->next = used_usb_ports;
2579 used_usb_ports = port;
2580 usb_attach(port, dev);
2581 return 0;
2584 static int usb_device_add(const char *devname)
2586 const char *p;
2587 USBDevice *dev;
2589 if (!free_usb_ports)
2590 return -1;
2592 if (strstart(devname, "host:", &p)) {
2593 dev = usb_host_device_open(p);
2594 } else if (!strcmp(devname, "mouse")) {
2595 dev = usb_mouse_init();
2596 } else if (!strcmp(devname, "tablet")) {
2597 dev = usb_tablet_init();
2598 } else if (!strcmp(devname, "keyboard")) {
2599 dev = usb_keyboard_init();
2600 } else if (strstart(devname, "disk:", &p)) {
2601 dev = usb_msd_init(p);
2602 } else if (!strcmp(devname, "wacom-tablet")) {
2603 dev = usb_wacom_init();
2604 } else if (strstart(devname, "serial:", &p)) {
2605 dev = usb_serial_init(p);
2606 #ifdef CONFIG_BRLAPI
2607 } else if (!strcmp(devname, "braille")) {
2608 dev = usb_baum_init();
2609 #endif
2610 } else if (strstart(devname, "net:", &p)) {
2611 int nic = nb_nics;
2613 if (net_client_init("nic", p) < 0)
2614 return -1;
2615 nd_table[nic].model = "usb";
2616 dev = usb_net_init(&nd_table[nic]);
2617 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2618 dev = usb_bt_init(devname[2] ? hci_init(p) :
2619 bt_new_hci(qemu_find_bt_vlan(0)));
2620 } else {
2621 return -1;
2623 if (!dev)
2624 return -1;
2626 return usb_device_add_dev(dev);
2629 int usb_device_del_addr(int bus_num, int addr)
2631 USBPort *port;
2632 USBPort **lastp;
2633 USBDevice *dev;
2635 if (!used_usb_ports)
2636 return -1;
2638 if (bus_num != 0)
2639 return -1;
2641 lastp = &used_usb_ports;
2642 port = used_usb_ports;
2643 while (port && port->dev->addr != addr) {
2644 lastp = &port->next;
2645 port = port->next;
2648 if (!port)
2649 return -1;
2651 dev = port->dev;
2652 *lastp = port->next;
2653 usb_attach(port, NULL);
2654 dev->handle_destroy(dev);
2655 port->next = free_usb_ports;
2656 free_usb_ports = port;
2657 return 0;
2660 static int usb_device_del(const char *devname)
2662 int bus_num, addr;
2663 const char *p;
2665 if (strstart(devname, "host:", &p))
2666 return usb_host_device_close(p);
2668 if (!used_usb_ports)
2669 return -1;
2671 p = strchr(devname, '.');
2672 if (!p)
2673 return -1;
2674 bus_num = strtoul(devname, NULL, 0);
2675 addr = strtoul(p + 1, NULL, 0);
2677 return usb_device_del_addr(bus_num, addr);
2680 void do_usb_add(const char *devname)
2682 usb_device_add(devname);
2685 void do_usb_del(const char *devname)
2687 usb_device_del(devname);
2690 void usb_info(void)
2692 USBDevice *dev;
2693 USBPort *port;
2694 const char *speed_str;
2696 if (!usb_enabled) {
2697 term_printf("USB support not enabled\n");
2698 return;
2701 for (port = used_usb_ports; port; port = port->next) {
2702 dev = port->dev;
2703 if (!dev)
2704 continue;
2705 switch(dev->speed) {
2706 case USB_SPEED_LOW:
2707 speed_str = "1.5";
2708 break;
2709 case USB_SPEED_FULL:
2710 speed_str = "12";
2711 break;
2712 case USB_SPEED_HIGH:
2713 speed_str = "480";
2714 break;
2715 default:
2716 speed_str = "?";
2717 break;
2719 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2720 0, dev->addr, speed_str, dev->devname);
2724 /***********************************************************/
2725 /* PCMCIA/Cardbus */
2727 static struct pcmcia_socket_entry_s {
2728 struct pcmcia_socket_s *socket;
2729 struct pcmcia_socket_entry_s *next;
2730 } *pcmcia_sockets = 0;
2732 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2734 struct pcmcia_socket_entry_s *entry;
2736 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2737 entry->socket = socket;
2738 entry->next = pcmcia_sockets;
2739 pcmcia_sockets = entry;
2742 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2744 struct pcmcia_socket_entry_s *entry, **ptr;
2746 ptr = &pcmcia_sockets;
2747 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2748 if (entry->socket == socket) {
2749 *ptr = entry->next;
2750 qemu_free(entry);
2754 void pcmcia_info(void)
2756 struct pcmcia_socket_entry_s *iter;
2757 if (!pcmcia_sockets)
2758 term_printf("No PCMCIA sockets\n");
2760 for (iter = pcmcia_sockets; iter; iter = iter->next)
2761 term_printf("%s: %s\n", iter->socket->slot_string,
2762 iter->socket->attached ? iter->socket->card_string :
2763 "Empty");
2766 /***********************************************************/
2767 /* dumb display */
2769 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2773 static void dumb_resize(DisplayState *ds, int w, int h)
2777 static void dumb_display_init(DisplayState *ds)
2779 ds->data = NULL;
2780 ds->linesize = 0;
2781 ds->depth = 0;
2782 ds->dpy_update = dumb_update;
2783 ds->dpy_resize = dumb_resize;
2784 ds->dpy_refresh = NULL;
2785 ds->gui_timer_interval = 0;
2786 ds->idle = 1;
2789 /***********************************************************/
2790 /* I/O handling */
2792 #define MAX_IO_HANDLERS 64
2794 typedef struct IOHandlerRecord {
2795 int fd;
2796 IOCanRWHandler *fd_read_poll;
2797 IOHandler *fd_read;
2798 IOHandler *fd_write;
2799 int deleted;
2800 void *opaque;
2801 /* temporary data */
2802 struct pollfd *ufd;
2803 struct IOHandlerRecord *next;
2804 } IOHandlerRecord;
2806 static IOHandlerRecord *first_io_handler;
2808 /* XXX: fd_read_poll should be suppressed, but an API change is
2809 necessary in the character devices to suppress fd_can_read(). */
2810 int qemu_set_fd_handler2(int fd,
2811 IOCanRWHandler *fd_read_poll,
2812 IOHandler *fd_read,
2813 IOHandler *fd_write,
2814 void *opaque)
2816 IOHandlerRecord **pioh, *ioh;
2818 if (!fd_read && !fd_write) {
2819 pioh = &first_io_handler;
2820 for(;;) {
2821 ioh = *pioh;
2822 if (ioh == NULL)
2823 break;
2824 if (ioh->fd == fd) {
2825 ioh->deleted = 1;
2826 break;
2828 pioh = &ioh->next;
2830 } else {
2831 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2832 if (ioh->fd == fd)
2833 goto found;
2835 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2836 if (!ioh)
2837 return -1;
2838 ioh->next = first_io_handler;
2839 first_io_handler = ioh;
2840 found:
2841 ioh->fd = fd;
2842 ioh->fd_read_poll = fd_read_poll;
2843 ioh->fd_read = fd_read;
2844 ioh->fd_write = fd_write;
2845 ioh->opaque = opaque;
2846 ioh->deleted = 0;
2848 return 0;
2851 int qemu_set_fd_handler(int fd,
2852 IOHandler *fd_read,
2853 IOHandler *fd_write,
2854 void *opaque)
2856 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2859 #ifdef _WIN32
2860 /***********************************************************/
2861 /* Polling handling */
2863 typedef struct PollingEntry {
2864 PollingFunc *func;
2865 void *opaque;
2866 struct PollingEntry *next;
2867 } PollingEntry;
2869 static PollingEntry *first_polling_entry;
2871 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2873 PollingEntry **ppe, *pe;
2874 pe = qemu_mallocz(sizeof(PollingEntry));
2875 if (!pe)
2876 return -1;
2877 pe->func = func;
2878 pe->opaque = opaque;
2879 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2880 *ppe = pe;
2881 return 0;
2884 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2886 PollingEntry **ppe, *pe;
2887 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2888 pe = *ppe;
2889 if (pe->func == func && pe->opaque == opaque) {
2890 *ppe = pe->next;
2891 qemu_free(pe);
2892 break;
2897 /***********************************************************/
2898 /* Wait objects support */
2899 typedef struct WaitObjects {
2900 int num;
2901 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2902 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2903 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2904 } WaitObjects;
2906 static WaitObjects wait_objects = {0};
2908 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2910 WaitObjects *w = &wait_objects;
2912 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2913 return -1;
2914 w->events[w->num] = handle;
2915 w->func[w->num] = func;
2916 w->opaque[w->num] = opaque;
2917 w->num++;
2918 return 0;
2921 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2923 int i, found;
2924 WaitObjects *w = &wait_objects;
2926 found = 0;
2927 for (i = 0; i < w->num; i++) {
2928 if (w->events[i] == handle)
2929 found = 1;
2930 if (found) {
2931 w->events[i] = w->events[i + 1];
2932 w->func[i] = w->func[i + 1];
2933 w->opaque[i] = w->opaque[i + 1];
2936 if (found)
2937 w->num--;
2939 #endif
2941 /***********************************************************/
2942 /* ram save/restore */
2944 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2946 int v;
2948 v = qemu_get_byte(f);
2949 switch(v) {
2950 case 0:
2951 if (qemu_get_buffer(f, buf, len) != len)
2952 return -EIO;
2953 break;
2954 case 1:
2955 v = qemu_get_byte(f);
2956 memset(buf, v, len);
2957 break;
2958 default:
2959 return -EINVAL;
2962 if (qemu_file_has_error(f))
2963 return -EIO;
2965 return 0;
2968 static int ram_load_v1(QEMUFile *f, void *opaque)
2970 int ret;
2971 ram_addr_t i;
2973 if (qemu_get_be32(f) != phys_ram_size)
2974 return -EINVAL;
2975 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2976 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2977 if (ret)
2978 return ret;
2980 return 0;
2983 #define BDRV_HASH_BLOCK_SIZE 1024
2984 #define IOBUF_SIZE 4096
2985 #define RAM_CBLOCK_MAGIC 0xfabe
2987 typedef struct RamDecompressState {
2988 z_stream zstream;
2989 QEMUFile *f;
2990 uint8_t buf[IOBUF_SIZE];
2991 } RamDecompressState;
2993 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2995 int ret;
2996 memset(s, 0, sizeof(*s));
2997 s->f = f;
2998 ret = inflateInit(&s->zstream);
2999 if (ret != Z_OK)
3000 return -1;
3001 return 0;
3004 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3006 int ret, clen;
3008 s->zstream.avail_out = len;
3009 s->zstream.next_out = buf;
3010 while (s->zstream.avail_out > 0) {
3011 if (s->zstream.avail_in == 0) {
3012 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3013 return -1;
3014 clen = qemu_get_be16(s->f);
3015 if (clen > IOBUF_SIZE)
3016 return -1;
3017 qemu_get_buffer(s->f, s->buf, clen);
3018 s->zstream.avail_in = clen;
3019 s->zstream.next_in = s->buf;
3021 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3022 if (ret != Z_OK && ret != Z_STREAM_END) {
3023 return -1;
3026 return 0;
3029 static void ram_decompress_close(RamDecompressState *s)
3031 inflateEnd(&s->zstream);
3034 #define RAM_SAVE_FLAG_FULL 0x01
3035 #define RAM_SAVE_FLAG_COMPRESS 0x02
3036 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3037 #define RAM_SAVE_FLAG_PAGE 0x08
3038 #define RAM_SAVE_FLAG_EOS 0x10
3040 static int is_dup_page(uint8_t *page, uint8_t ch)
3042 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3043 uint32_t *array = (uint32_t *)page;
3044 int i;
3046 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3047 if (array[i] != val)
3048 return 0;
3051 return 1;
3054 static int ram_save_block(QEMUFile *f)
3056 static ram_addr_t current_addr = 0;
3057 ram_addr_t saved_addr = current_addr;
3058 ram_addr_t addr = 0;
3059 int found = 0;
3061 while (addr < phys_ram_size) {
3062 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3063 uint8_t ch;
3065 cpu_physical_memory_reset_dirty(current_addr,
3066 current_addr + TARGET_PAGE_SIZE,
3067 MIGRATION_DIRTY_FLAG);
3069 ch = *(phys_ram_base + current_addr);
3071 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3072 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3073 qemu_put_byte(f, ch);
3074 } else {
3075 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3076 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3079 found = 1;
3080 break;
3082 addr += TARGET_PAGE_SIZE;
3083 current_addr = (saved_addr + addr) % phys_ram_size;
3086 return found;
3089 static ram_addr_t ram_save_threshold = 10;
3091 static ram_addr_t ram_save_remaining(void)
3093 ram_addr_t addr;
3094 ram_addr_t count = 0;
3096 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3097 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3098 count++;
3101 return count;
3104 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3106 ram_addr_t addr;
3108 if (stage == 1) {
3109 /* Make sure all dirty bits are set */
3110 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3111 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3112 cpu_physical_memory_set_dirty(addr);
3115 /* Enable dirty memory tracking */
3116 cpu_physical_memory_set_dirty_tracking(1);
3118 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3121 while (!qemu_file_rate_limit(f)) {
3122 int ret;
3124 ret = ram_save_block(f);
3125 if (ret == 0) /* no more blocks */
3126 break;
3129 /* try transferring iterative blocks of memory */
3131 if (stage == 3) {
3132 cpu_physical_memory_set_dirty_tracking(0);
3134 /* flush all remaining blocks regardless of rate limiting */
3135 while (ram_save_block(f) != 0);
3138 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3140 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3143 static int ram_load_dead(QEMUFile *f, void *opaque)
3145 RamDecompressState s1, *s = &s1;
3146 uint8_t buf[10];
3147 ram_addr_t i;
3149 if (ram_decompress_open(s, f) < 0)
3150 return -EINVAL;
3151 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3152 if (ram_decompress_buf(s, buf, 1) < 0) {
3153 fprintf(stderr, "Error while reading ram block header\n");
3154 goto error;
3156 if (buf[0] == 0) {
3157 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3158 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3159 goto error;
3161 } else {
3162 error:
3163 printf("Error block header\n");
3164 return -EINVAL;
3167 ram_decompress_close(s);
3169 return 0;
3172 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3174 ram_addr_t addr;
3175 int flags;
3177 if (version_id == 1)
3178 return ram_load_v1(f, opaque);
3180 if (version_id == 2) {
3181 if (qemu_get_be32(f) != phys_ram_size)
3182 return -EINVAL;
3183 return ram_load_dead(f, opaque);
3186 if (version_id != 3)
3187 return -EINVAL;
3189 do {
3190 addr = qemu_get_be64(f);
3192 flags = addr & ~TARGET_PAGE_MASK;
3193 addr &= TARGET_PAGE_MASK;
3195 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3196 if (addr != phys_ram_size)
3197 return -EINVAL;
3200 if (flags & RAM_SAVE_FLAG_FULL) {
3201 if (ram_load_dead(f, opaque) < 0)
3202 return -EINVAL;
3205 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3206 uint8_t ch = qemu_get_byte(f);
3207 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3208 } else if (flags & RAM_SAVE_FLAG_PAGE)
3209 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3210 } while (!(flags & RAM_SAVE_FLAG_EOS));
3212 return 0;
3215 void qemu_service_io(void)
3217 CPUState *env = cpu_single_env;
3218 if (env) {
3219 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3220 #ifdef USE_KQEMU
3221 if (env->kqemu_enabled) {
3222 kqemu_cpu_interrupt(env);
3224 #endif
3228 /***********************************************************/
3229 /* bottom halves (can be seen as timers which expire ASAP) */
3231 struct QEMUBH {
3232 QEMUBHFunc *cb;
3233 void *opaque;
3234 int scheduled;
3235 int idle;
3236 int deleted;
3237 QEMUBH *next;
3240 static QEMUBH *first_bh = NULL;
3242 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3244 QEMUBH *bh;
3245 bh = qemu_mallocz(sizeof(QEMUBH));
3246 if (!bh)
3247 return NULL;
3248 bh->cb = cb;
3249 bh->opaque = opaque;
3250 bh->next = first_bh;
3251 first_bh = bh;
3252 return bh;
3255 int qemu_bh_poll(void)
3257 QEMUBH *bh, **bhp;
3258 int ret;
3260 ret = 0;
3261 for (bh = first_bh; bh; bh = bh->next) {
3262 if (!bh->deleted && bh->scheduled) {
3263 bh->scheduled = 0;
3264 if (!bh->idle)
3265 ret = 1;
3266 bh->idle = 0;
3267 bh->cb(bh->opaque);
3271 /* remove deleted bhs */
3272 bhp = &first_bh;
3273 while (*bhp) {
3274 bh = *bhp;
3275 if (bh->deleted) {
3276 *bhp = bh->next;
3277 qemu_free(bh);
3278 } else
3279 bhp = &bh->next;
3282 return ret;
3285 void qemu_bh_schedule_idle(QEMUBH *bh)
3287 if (bh->scheduled)
3288 return;
3289 bh->scheduled = 1;
3290 bh->idle = 1;
3293 void qemu_bh_schedule(QEMUBH *bh)
3295 CPUState *env = cpu_single_env;
3296 if (bh->scheduled)
3297 return;
3298 bh->scheduled = 1;
3299 bh->idle = 0;
3300 /* stop the currently executing CPU to execute the BH ASAP */
3301 if (env) {
3302 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3306 void qemu_bh_cancel(QEMUBH *bh)
3308 bh->scheduled = 0;
3311 void qemu_bh_delete(QEMUBH *bh)
3313 bh->scheduled = 0;
3314 bh->deleted = 1;
3317 static void qemu_bh_update_timeout(int *timeout)
3319 QEMUBH *bh;
3321 for (bh = first_bh; bh; bh = bh->next) {
3322 if (!bh->deleted && bh->scheduled) {
3323 if (bh->idle) {
3324 /* idle bottom halves will be polled at least
3325 * every 10ms */
3326 *timeout = MIN(10, *timeout);
3327 } else {
3328 /* non-idle bottom halves will be executed
3329 * immediately */
3330 *timeout = 0;
3331 break;
3337 /***********************************************************/
3338 /* machine registration */
3340 static QEMUMachine *first_machine = NULL;
3342 int qemu_register_machine(QEMUMachine *m)
3344 QEMUMachine **pm;
3345 pm = &first_machine;
3346 while (*pm != NULL)
3347 pm = &(*pm)->next;
3348 m->next = NULL;
3349 *pm = m;
3350 return 0;
3353 static QEMUMachine *find_machine(const char *name)
3355 QEMUMachine *m;
3357 for(m = first_machine; m != NULL; m = m->next) {
3358 if (!strcmp(m->name, name))
3359 return m;
3361 return NULL;
3364 /***********************************************************/
3365 /* main execution loop */
3367 static void gui_update(void *opaque)
3369 DisplayState *ds = opaque;
3370 ds->dpy_refresh(ds);
3371 qemu_mod_timer(ds->gui_timer,
3372 (ds->gui_timer_interval ?
3373 ds->gui_timer_interval :
3374 GUI_REFRESH_INTERVAL)
3375 + qemu_get_clock(rt_clock));
3378 struct vm_change_state_entry {
3379 VMChangeStateHandler *cb;
3380 void *opaque;
3381 LIST_ENTRY (vm_change_state_entry) entries;
3384 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3386 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3387 void *opaque)
3389 VMChangeStateEntry *e;
3391 e = qemu_mallocz(sizeof (*e));
3392 if (!e)
3393 return NULL;
3395 e->cb = cb;
3396 e->opaque = opaque;
3397 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3398 return e;
3401 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3403 LIST_REMOVE (e, entries);
3404 qemu_free (e);
3407 static void vm_state_notify(int running)
3409 VMChangeStateEntry *e;
3411 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3412 e->cb(e->opaque, running);
3416 /* XXX: support several handlers */
3417 static VMStopHandler *vm_stop_cb;
3418 static void *vm_stop_opaque;
3420 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3422 vm_stop_cb = cb;
3423 vm_stop_opaque = opaque;
3424 return 0;
3427 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3429 vm_stop_cb = NULL;
3432 void vm_start(void)
3434 if (!vm_running) {
3435 cpu_enable_ticks();
3436 vm_running = 1;
3437 vm_state_notify(1);
3438 qemu_rearm_alarm_timer(alarm_timer);
3442 void vm_stop(int reason)
3444 if (vm_running) {
3445 cpu_disable_ticks();
3446 vm_running = 0;
3447 if (reason != 0) {
3448 if (vm_stop_cb) {
3449 vm_stop_cb(vm_stop_opaque, reason);
3452 vm_state_notify(0);
3456 /* reset/shutdown handler */
3458 typedef struct QEMUResetEntry {
3459 QEMUResetHandler *func;
3460 void *opaque;
3461 struct QEMUResetEntry *next;
3462 } QEMUResetEntry;
3464 static QEMUResetEntry *first_reset_entry;
3465 static int reset_requested;
3466 static int shutdown_requested;
3467 static int powerdown_requested;
3469 int qemu_shutdown_requested(void)
3471 int r = shutdown_requested;
3472 shutdown_requested = 0;
3473 return r;
3476 int qemu_reset_requested(void)
3478 int r = reset_requested;
3479 reset_requested = 0;
3480 return r;
3483 int qemu_powerdown_requested(void)
3485 int r = powerdown_requested;
3486 powerdown_requested = 0;
3487 return r;
3490 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3492 QEMUResetEntry **pre, *re;
3494 pre = &first_reset_entry;
3495 while (*pre != NULL)
3496 pre = &(*pre)->next;
3497 re = qemu_mallocz(sizeof(QEMUResetEntry));
3498 re->func = func;
3499 re->opaque = opaque;
3500 re->next = NULL;
3501 *pre = re;
3504 void qemu_system_reset(void)
3506 QEMUResetEntry *re;
3508 /* reset all devices */
3509 for(re = first_reset_entry; re != NULL; re = re->next) {
3510 re->func(re->opaque);
3514 void qemu_system_reset_request(void)
3516 if (no_reboot) {
3517 shutdown_requested = 1;
3518 } else {
3519 reset_requested = 1;
3521 if (cpu_single_env)
3522 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3525 void qemu_system_shutdown_request(void)
3527 shutdown_requested = 1;
3528 if (cpu_single_env)
3529 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3532 void qemu_system_powerdown_request(void)
3534 powerdown_requested = 1;
3535 if (cpu_single_env)
3536 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3539 #ifdef _WIN32
3540 static void host_main_loop_wait(int *timeout)
3542 int ret, ret2, i;
3543 PollingEntry *pe;
3546 /* XXX: need to suppress polling by better using win32 events */
3547 ret = 0;
3548 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3549 ret |= pe->func(pe->opaque);
3551 if (ret == 0) {
3552 int err;
3553 WaitObjects *w = &wait_objects;
3555 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3556 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3557 if (w->func[ret - WAIT_OBJECT_0])
3558 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3560 /* Check for additional signaled events */
3561 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3563 /* Check if event is signaled */
3564 ret2 = WaitForSingleObject(w->events[i], 0);
3565 if(ret2 == WAIT_OBJECT_0) {
3566 if (w->func[i])
3567 w->func[i](w->opaque[i]);
3568 } else if (ret2 == WAIT_TIMEOUT) {
3569 } else {
3570 err = GetLastError();
3571 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3574 } else if (ret == WAIT_TIMEOUT) {
3575 } else {
3576 err = GetLastError();
3577 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3581 *timeout = 0;
3583 #else
3584 static void host_main_loop_wait(int *timeout)
3587 #endif
3589 void main_loop_wait(int timeout)
3591 IOHandlerRecord *ioh;
3592 fd_set rfds, wfds, xfds;
3593 int ret, nfds;
3594 struct timeval tv;
3596 qemu_bh_update_timeout(&timeout);
3598 host_main_loop_wait(&timeout);
3600 /* poll any events */
3601 /* XXX: separate device handlers from system ones */
3602 nfds = -1;
3603 FD_ZERO(&rfds);
3604 FD_ZERO(&wfds);
3605 FD_ZERO(&xfds);
3606 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3607 if (ioh->deleted)
3608 continue;
3609 if (ioh->fd_read &&
3610 (!ioh->fd_read_poll ||
3611 ioh->fd_read_poll(ioh->opaque) != 0)) {
3612 FD_SET(ioh->fd, &rfds);
3613 if (ioh->fd > nfds)
3614 nfds = ioh->fd;
3616 if (ioh->fd_write) {
3617 FD_SET(ioh->fd, &wfds);
3618 if (ioh->fd > nfds)
3619 nfds = ioh->fd;
3623 tv.tv_sec = timeout / 1000;
3624 tv.tv_usec = (timeout % 1000) * 1000;
3626 #if defined(CONFIG_SLIRP)
3627 if (slirp_is_inited()) {
3628 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3630 #endif
3631 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3632 if (ret > 0) {
3633 IOHandlerRecord **pioh;
3635 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3636 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3637 ioh->fd_read(ioh->opaque);
3639 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3640 ioh->fd_write(ioh->opaque);
3644 /* remove deleted IO handlers */
3645 pioh = &first_io_handler;
3646 while (*pioh) {
3647 ioh = *pioh;
3648 if (ioh->deleted) {
3649 *pioh = ioh->next;
3650 qemu_free(ioh);
3651 } else
3652 pioh = &ioh->next;
3655 #if defined(CONFIG_SLIRP)
3656 if (slirp_is_inited()) {
3657 if (ret < 0) {
3658 FD_ZERO(&rfds);
3659 FD_ZERO(&wfds);
3660 FD_ZERO(&xfds);
3662 slirp_select_poll(&rfds, &wfds, &xfds);
3664 #endif
3666 /* vm time timers */
3667 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3668 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3669 qemu_get_clock(vm_clock));
3671 /* real time timers */
3672 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3673 qemu_get_clock(rt_clock));
3675 /* Check bottom-halves last in case any of the earlier events triggered
3676 them. */
3677 qemu_bh_poll();
3681 static int main_loop(void)
3683 int ret, timeout;
3684 #ifdef CONFIG_PROFILER
3685 int64_t ti;
3686 #endif
3687 CPUState *env;
3689 cur_cpu = first_cpu;
3690 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3691 for(;;) {
3692 if (vm_running) {
3694 for(;;) {
3695 /* get next cpu */
3696 env = next_cpu;
3697 #ifdef CONFIG_PROFILER
3698 ti = profile_getclock();
3699 #endif
3700 if (use_icount) {
3701 int64_t count;
3702 int decr;
3703 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3704 env->icount_decr.u16.low = 0;
3705 env->icount_extra = 0;
3706 count = qemu_next_deadline();
3707 count = (count + (1 << icount_time_shift) - 1)
3708 >> icount_time_shift;
3709 qemu_icount += count;
3710 decr = (count > 0xffff) ? 0xffff : count;
3711 count -= decr;
3712 env->icount_decr.u16.low = decr;
3713 env->icount_extra = count;
3715 ret = cpu_exec(env);
3716 #ifdef CONFIG_PROFILER
3717 qemu_time += profile_getclock() - ti;
3718 #endif
3719 if (use_icount) {
3720 /* Fold pending instructions back into the
3721 instruction counter, and clear the interrupt flag. */
3722 qemu_icount -= (env->icount_decr.u16.low
3723 + env->icount_extra);
3724 env->icount_decr.u32 = 0;
3725 env->icount_extra = 0;
3727 next_cpu = env->next_cpu ?: first_cpu;
3728 if (event_pending && likely(ret != EXCP_DEBUG)) {
3729 ret = EXCP_INTERRUPT;
3730 event_pending = 0;
3731 break;
3733 if (ret == EXCP_HLT) {
3734 /* Give the next CPU a chance to run. */
3735 cur_cpu = env;
3736 continue;
3738 if (ret != EXCP_HALTED)
3739 break;
3740 /* all CPUs are halted ? */
3741 if (env == cur_cpu)
3742 break;
3744 cur_cpu = env;
3746 if (shutdown_requested) {
3747 ret = EXCP_INTERRUPT;
3748 if (no_shutdown) {
3749 vm_stop(0);
3750 no_shutdown = 0;
3752 else
3753 break;
3755 if (reset_requested) {
3756 reset_requested = 0;
3757 qemu_system_reset();
3758 ret = EXCP_INTERRUPT;
3760 if (powerdown_requested) {
3761 powerdown_requested = 0;
3762 qemu_system_powerdown();
3763 ret = EXCP_INTERRUPT;
3765 if (unlikely(ret == EXCP_DEBUG)) {
3766 gdb_set_stop_cpu(cur_cpu);
3767 vm_stop(EXCP_DEBUG);
3769 /* If all cpus are halted then wait until the next IRQ */
3770 /* XXX: use timeout computed from timers */
3771 if (ret == EXCP_HALTED) {
3772 if (use_icount) {
3773 int64_t add;
3774 int64_t delta;
3775 /* Advance virtual time to the next event. */
3776 if (use_icount == 1) {
3777 /* When not using an adaptive execution frequency
3778 we tend to get badly out of sync with real time,
3779 so just delay for a reasonable amount of time. */
3780 delta = 0;
3781 } else {
3782 delta = cpu_get_icount() - cpu_get_clock();
3784 if (delta > 0) {
3785 /* If virtual time is ahead of real time then just
3786 wait for IO. */
3787 timeout = (delta / 1000000) + 1;
3788 } else {
3789 /* Wait for either IO to occur or the next
3790 timer event. */
3791 add = qemu_next_deadline();
3792 /* We advance the timer before checking for IO.
3793 Limit the amount we advance so that early IO
3794 activity won't get the guest too far ahead. */
3795 if (add > 10000000)
3796 add = 10000000;
3797 delta += add;
3798 add = (add + (1 << icount_time_shift) - 1)
3799 >> icount_time_shift;
3800 qemu_icount += add;
3801 timeout = delta / 1000000;
3802 if (timeout < 0)
3803 timeout = 0;
3805 } else {
3806 timeout = 5000;
3808 } else {
3809 timeout = 0;
3811 } else {
3812 if (shutdown_requested) {
3813 ret = EXCP_INTERRUPT;
3814 break;
3816 timeout = 5000;
3818 #ifdef CONFIG_PROFILER
3819 ti = profile_getclock();
3820 #endif
3821 main_loop_wait(timeout);
3822 #ifdef CONFIG_PROFILER
3823 dev_time += profile_getclock() - ti;
3824 #endif
3826 cpu_disable_ticks();
3827 return ret;
3830 static void help(int exitcode)
3832 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3833 "usage: %s [options] [disk_image]\n"
3834 "\n"
3835 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3836 "\n"
3837 "Standard options:\n"
3838 "-M machine select emulated machine (-M ? for list)\n"
3839 "-cpu cpu select CPU (-cpu ? for list)\n"
3840 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3841 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3842 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3843 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3844 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3845 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3846 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3847 " use 'file' as a drive image\n"
3848 "-mtdblock file use 'file' as on-board Flash memory image\n"
3849 "-sd file use 'file' as SecureDigital card image\n"
3850 "-pflash file use 'file' as a parallel flash image\n"
3851 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3852 "-snapshot write to temporary files instead of disk image files\n"
3853 #ifdef CONFIG_SDL
3854 "-no-frame open SDL window without a frame and window decorations\n"
3855 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3856 "-no-quit disable SDL window close capability\n"
3857 #endif
3858 #ifdef TARGET_I386
3859 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3860 #endif
3861 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3862 "-smp n set the number of CPUs to 'n' [default=1]\n"
3863 "-nographic disable graphical output and redirect serial I/Os to console\n"
3864 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3865 #ifndef _WIN32
3866 "-k language use keyboard layout (for example \"fr\" for French)\n"
3867 #endif
3868 #ifdef HAS_AUDIO
3869 "-audio-help print list of audio drivers and their options\n"
3870 "-soundhw c1,... enable audio support\n"
3871 " and only specified sound cards (comma separated list)\n"
3872 " use -soundhw ? to get the list of supported cards\n"
3873 " use -soundhw all to enable all of them\n"
3874 #endif
3875 "-vga [std|cirrus|vmware]\n"
3876 " select video card type\n"
3877 "-localtime set the real time clock to local time [default=utc]\n"
3878 "-full-screen start in full screen\n"
3879 #ifdef TARGET_I386
3880 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3881 #endif
3882 "-usb enable the USB driver (will be the default soon)\n"
3883 "-usbdevice name add the host or guest USB device 'name'\n"
3884 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3885 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3886 #endif
3887 "-name string set the name of the guest\n"
3888 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
3889 "\n"
3890 "Network options:\n"
3891 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3892 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3893 #ifdef CONFIG_SLIRP
3894 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3895 " connect the user mode network stack to VLAN 'n' and send\n"
3896 " hostname 'host' to DHCP clients\n"
3897 #endif
3898 #ifdef _WIN32
3899 "-net tap[,vlan=n][,name=str],ifname=name\n"
3900 " connect the host TAP network interface to VLAN 'n'\n"
3901 #else
3902 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3903 " connect the host TAP network interface to VLAN 'n' and use the\n"
3904 " network scripts 'file' (default=%s)\n"
3905 " and 'dfile' (default=%s);\n"
3906 " use '[down]script=no' to disable script execution;\n"
3907 " use 'fd=h' to connect to an already opened TAP interface\n"
3908 #endif
3909 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3910 " connect the vlan 'n' to another VLAN using a socket connection\n"
3911 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
3912 " connect the vlan 'n' to multicast maddr and port\n"
3913 #ifdef CONFIG_VDE
3914 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3915 " connect the vlan 'n' to port 'n' of a vde switch running\n"
3916 " on host and listening for incoming connections on 'socketpath'.\n"
3917 " Use group 'groupname' and mode 'octalmode' to change default\n"
3918 " ownership and permissions for communication port.\n"
3919 #endif
3920 "-net none use it alone to have zero network devices; if no -net option\n"
3921 " is provided, the default is '-net nic -net user'\n"
3922 "\n"
3923 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
3924 "-bt hci,host[:id]\n"
3925 " Use host's HCI with the given name\n"
3926 "-bt hci[,vlan=n]\n"
3927 " Emulate a standard HCI in virtual scatternet 'n'\n"
3928 "-bt vhci[,vlan=n]\n"
3929 " Add host computer to virtual scatternet 'n' using VHCI\n"
3930 "-bt device:dev[,vlan=n]\n"
3931 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
3932 "\n"
3933 #ifdef CONFIG_SLIRP
3934 "-tftp dir allow tftp access to files in dir [-net user]\n"
3935 "-bootp file advertise file in BOOTP replies\n"
3936 #ifndef _WIN32
3937 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3938 #endif
3939 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3940 " redirect TCP or UDP connections from host to guest [-net user]\n"
3941 #endif
3942 "\n"
3943 "Linux boot specific:\n"
3944 "-kernel bzImage use 'bzImage' as kernel image\n"
3945 "-append cmdline use 'cmdline' as kernel command line\n"
3946 "-initrd file use 'file' as initial ram disk\n"
3947 "\n"
3948 "Debug/Expert options:\n"
3949 "-monitor dev redirect the monitor to char device 'dev'\n"
3950 "-serial dev redirect the serial port to char device 'dev'\n"
3951 "-parallel dev redirect the parallel port to char device 'dev'\n"
3952 "-pidfile file Write PID to 'file'\n"
3953 "-S freeze CPU at startup (use 'c' to start execution)\n"
3954 "-s wait gdb connection to port\n"
3955 "-p port set gdb connection port [default=%s]\n"
3956 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
3957 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
3958 " translation (t=none or lba) (usually qemu can guess them)\n"
3959 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
3960 #ifdef USE_KQEMU
3961 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
3962 "-no-kqemu disable KQEMU kernel module usage\n"
3963 #endif
3964 #ifdef CONFIG_KVM
3965 "-enable-kvm enable KVM full virtualization support\n"
3966 #endif
3967 #ifdef TARGET_I386
3968 "-no-acpi disable ACPI\n"
3969 "-no-hpet disable HPET\n"
3970 #endif
3971 #ifdef CONFIG_CURSES
3972 "-curses use a curses/ncurses interface instead of SDL\n"
3973 #endif
3974 "-no-reboot exit instead of rebooting\n"
3975 "-no-shutdown stop before shutdown\n"
3976 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
3977 "-vnc display start a VNC server on display\n"
3978 #ifndef _WIN32
3979 "-daemonize daemonize QEMU after initializing\n"
3980 #endif
3981 "-option-rom rom load a file, rom, into the option ROM space\n"
3982 #ifdef TARGET_SPARC
3983 "-prom-env variable=value set OpenBIOS nvram variables\n"
3984 #endif
3985 "-clock force the use of the given methods for timer alarm.\n"
3986 " To see what timers are available use -clock ?\n"
3987 "-startdate select initial date of the clock\n"
3988 "-icount [N|auto]\n"
3989 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
3990 "\n"
3991 "During emulation, the following keys are useful:\n"
3992 "ctrl-alt-f toggle full screen\n"
3993 "ctrl-alt-n switch to virtual console 'n'\n"
3994 "ctrl-alt toggle mouse and keyboard grab\n"
3995 "\n"
3996 "When using -nographic, press 'ctrl-a h' to get some help.\n"
3998 "qemu",
3999 DEFAULT_RAM_SIZE,
4000 #ifndef _WIN32
4001 DEFAULT_NETWORK_SCRIPT,
4002 DEFAULT_NETWORK_DOWN_SCRIPT,
4003 #endif
4004 DEFAULT_GDBSTUB_PORT,
4005 "/tmp/qemu.log");
4006 exit(exitcode);
4009 #define HAS_ARG 0x0001
4011 enum {
4012 QEMU_OPTION_h,
4014 QEMU_OPTION_M,
4015 QEMU_OPTION_cpu,
4016 QEMU_OPTION_fda,
4017 QEMU_OPTION_fdb,
4018 QEMU_OPTION_hda,
4019 QEMU_OPTION_hdb,
4020 QEMU_OPTION_hdc,
4021 QEMU_OPTION_hdd,
4022 QEMU_OPTION_drive,
4023 QEMU_OPTION_cdrom,
4024 QEMU_OPTION_mtdblock,
4025 QEMU_OPTION_sd,
4026 QEMU_OPTION_pflash,
4027 QEMU_OPTION_boot,
4028 QEMU_OPTION_snapshot,
4029 #ifdef TARGET_I386
4030 QEMU_OPTION_no_fd_bootchk,
4031 #endif
4032 QEMU_OPTION_m,
4033 QEMU_OPTION_nographic,
4034 QEMU_OPTION_portrait,
4035 #ifdef HAS_AUDIO
4036 QEMU_OPTION_audio_help,
4037 QEMU_OPTION_soundhw,
4038 #endif
4040 QEMU_OPTION_net,
4041 QEMU_OPTION_tftp,
4042 QEMU_OPTION_bootp,
4043 QEMU_OPTION_smb,
4044 QEMU_OPTION_redir,
4045 QEMU_OPTION_bt,
4047 QEMU_OPTION_kernel,
4048 QEMU_OPTION_append,
4049 QEMU_OPTION_initrd,
4051 QEMU_OPTION_S,
4052 QEMU_OPTION_s,
4053 QEMU_OPTION_p,
4054 QEMU_OPTION_d,
4055 QEMU_OPTION_hdachs,
4056 QEMU_OPTION_L,
4057 QEMU_OPTION_bios,
4058 QEMU_OPTION_k,
4059 QEMU_OPTION_localtime,
4060 QEMU_OPTION_g,
4061 QEMU_OPTION_vga,
4062 QEMU_OPTION_echr,
4063 QEMU_OPTION_monitor,
4064 QEMU_OPTION_serial,
4065 QEMU_OPTION_parallel,
4066 QEMU_OPTION_loadvm,
4067 QEMU_OPTION_full_screen,
4068 QEMU_OPTION_no_frame,
4069 QEMU_OPTION_alt_grab,
4070 QEMU_OPTION_no_quit,
4071 QEMU_OPTION_pidfile,
4072 QEMU_OPTION_no_kqemu,
4073 QEMU_OPTION_kernel_kqemu,
4074 QEMU_OPTION_enable_kvm,
4075 QEMU_OPTION_win2k_hack,
4076 QEMU_OPTION_usb,
4077 QEMU_OPTION_usbdevice,
4078 QEMU_OPTION_smp,
4079 QEMU_OPTION_vnc,
4080 QEMU_OPTION_no_acpi,
4081 QEMU_OPTION_no_hpet,
4082 QEMU_OPTION_curses,
4083 QEMU_OPTION_no_reboot,
4084 QEMU_OPTION_no_shutdown,
4085 QEMU_OPTION_show_cursor,
4086 QEMU_OPTION_daemonize,
4087 QEMU_OPTION_option_rom,
4088 QEMU_OPTION_semihosting,
4089 QEMU_OPTION_name,
4090 QEMU_OPTION_prom_env,
4091 QEMU_OPTION_old_param,
4092 QEMU_OPTION_clock,
4093 QEMU_OPTION_startdate,
4094 QEMU_OPTION_tb_size,
4095 QEMU_OPTION_icount,
4096 QEMU_OPTION_uuid,
4097 QEMU_OPTION_incoming,
4100 typedef struct QEMUOption {
4101 const char *name;
4102 int flags;
4103 int index;
4104 } QEMUOption;
4106 static const QEMUOption qemu_options[] = {
4107 { "h", 0, QEMU_OPTION_h },
4108 { "help", 0, QEMU_OPTION_h },
4110 { "M", HAS_ARG, QEMU_OPTION_M },
4111 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4112 { "fda", HAS_ARG, QEMU_OPTION_fda },
4113 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4114 { "hda", HAS_ARG, QEMU_OPTION_hda },
4115 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4116 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4117 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4118 { "drive", HAS_ARG, QEMU_OPTION_drive },
4119 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4120 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4121 { "sd", HAS_ARG, QEMU_OPTION_sd },
4122 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4123 { "boot", HAS_ARG, QEMU_OPTION_boot },
4124 { "snapshot", 0, QEMU_OPTION_snapshot },
4125 #ifdef TARGET_I386
4126 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4127 #endif
4128 { "m", HAS_ARG, QEMU_OPTION_m },
4129 { "nographic", 0, QEMU_OPTION_nographic },
4130 { "portrait", 0, QEMU_OPTION_portrait },
4131 { "k", HAS_ARG, QEMU_OPTION_k },
4132 #ifdef HAS_AUDIO
4133 { "audio-help", 0, QEMU_OPTION_audio_help },
4134 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4135 #endif
4137 { "net", HAS_ARG, QEMU_OPTION_net},
4138 #ifdef CONFIG_SLIRP
4139 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4140 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4141 #ifndef _WIN32
4142 { "smb", HAS_ARG, QEMU_OPTION_smb },
4143 #endif
4144 { "redir", HAS_ARG, QEMU_OPTION_redir },
4145 #endif
4146 { "bt", HAS_ARG, QEMU_OPTION_bt },
4148 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4149 { "append", HAS_ARG, QEMU_OPTION_append },
4150 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4152 { "S", 0, QEMU_OPTION_S },
4153 { "s", 0, QEMU_OPTION_s },
4154 { "p", HAS_ARG, QEMU_OPTION_p },
4155 { "d", HAS_ARG, QEMU_OPTION_d },
4156 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4157 { "L", HAS_ARG, QEMU_OPTION_L },
4158 { "bios", HAS_ARG, QEMU_OPTION_bios },
4159 #ifdef USE_KQEMU
4160 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4161 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4162 #endif
4163 #ifdef CONFIG_KVM
4164 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4165 #endif
4166 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4167 { "g", 1, QEMU_OPTION_g },
4168 #endif
4169 { "localtime", 0, QEMU_OPTION_localtime },
4170 { "vga", HAS_ARG, QEMU_OPTION_vga },
4171 { "echr", HAS_ARG, QEMU_OPTION_echr },
4172 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4173 { "serial", HAS_ARG, QEMU_OPTION_serial },
4174 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4175 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4176 { "full-screen", 0, QEMU_OPTION_full_screen },
4177 #ifdef CONFIG_SDL
4178 { "no-frame", 0, QEMU_OPTION_no_frame },
4179 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4180 { "no-quit", 0, QEMU_OPTION_no_quit },
4181 #endif
4182 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4183 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4184 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4185 { "smp", HAS_ARG, QEMU_OPTION_smp },
4186 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4187 #ifdef CONFIG_CURSES
4188 { "curses", 0, QEMU_OPTION_curses },
4189 #endif
4190 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4192 /* temporary options */
4193 { "usb", 0, QEMU_OPTION_usb },
4194 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4195 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4196 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4197 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4198 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4199 { "daemonize", 0, QEMU_OPTION_daemonize },
4200 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4201 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4202 { "semihosting", 0, QEMU_OPTION_semihosting },
4203 #endif
4204 { "name", HAS_ARG, QEMU_OPTION_name },
4205 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4206 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4207 #endif
4208 #if defined(TARGET_ARM)
4209 { "old-param", 0, QEMU_OPTION_old_param },
4210 #endif
4211 { "clock", HAS_ARG, QEMU_OPTION_clock },
4212 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4213 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4214 { "icount", HAS_ARG, QEMU_OPTION_icount },
4215 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4216 { NULL },
4219 /* password input */
4221 int qemu_key_check(BlockDriverState *bs, const char *name)
4223 char password[256];
4224 int i;
4226 if (!bdrv_is_encrypted(bs))
4227 return 0;
4229 term_printf("%s is encrypted.\n", name);
4230 for(i = 0; i < 3; i++) {
4231 monitor_readline("Password: ", 1, password, sizeof(password));
4232 if (bdrv_set_key(bs, password) == 0)
4233 return 0;
4234 term_printf("invalid password\n");
4236 return -EPERM;
4239 static BlockDriverState *get_bdrv(int index)
4241 if (index > nb_drives)
4242 return NULL;
4243 return drives_table[index].bdrv;
4246 static void read_passwords(void)
4248 BlockDriverState *bs;
4249 int i;
4251 for(i = 0; i < 6; i++) {
4252 bs = get_bdrv(i);
4253 if (bs)
4254 qemu_key_check(bs, bdrv_get_device_name(bs));
4258 #ifdef HAS_AUDIO
4259 struct soundhw soundhw[] = {
4260 #ifdef HAS_AUDIO_CHOICE
4261 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4263 "pcspk",
4264 "PC speaker",
4267 { .init_isa = pcspk_audio_init }
4269 #endif
4271 #ifdef CONFIG_SB16
4273 "sb16",
4274 "Creative Sound Blaster 16",
4277 { .init_isa = SB16_init }
4279 #endif
4281 #ifdef CONFIG_CS4231A
4283 "cs4231a",
4284 "CS4231A",
4287 { .init_isa = cs4231a_init }
4289 #endif
4291 #ifdef CONFIG_ADLIB
4293 "adlib",
4294 #ifdef HAS_YMF262
4295 "Yamaha YMF262 (OPL3)",
4296 #else
4297 "Yamaha YM3812 (OPL2)",
4298 #endif
4301 { .init_isa = Adlib_init }
4303 #endif
4305 #ifdef CONFIG_GUS
4307 "gus",
4308 "Gravis Ultrasound GF1",
4311 { .init_isa = GUS_init }
4313 #endif
4315 #ifdef CONFIG_AC97
4317 "ac97",
4318 "Intel 82801AA AC97 Audio",
4321 { .init_pci = ac97_init }
4323 #endif
4325 #ifdef CONFIG_ES1370
4327 "es1370",
4328 "ENSONIQ AudioPCI ES1370",
4331 { .init_pci = es1370_init }
4333 #endif
4335 #endif /* HAS_AUDIO_CHOICE */
4337 { NULL, NULL, 0, 0, { NULL } }
4340 static void select_soundhw (const char *optarg)
4342 struct soundhw *c;
4344 if (*optarg == '?') {
4345 show_valid_cards:
4347 printf ("Valid sound card names (comma separated):\n");
4348 for (c = soundhw; c->name; ++c) {
4349 printf ("%-11s %s\n", c->name, c->descr);
4351 printf ("\n-soundhw all will enable all of the above\n");
4352 exit (*optarg != '?');
4354 else {
4355 size_t l;
4356 const char *p;
4357 char *e;
4358 int bad_card = 0;
4360 if (!strcmp (optarg, "all")) {
4361 for (c = soundhw; c->name; ++c) {
4362 c->enabled = 1;
4364 return;
4367 p = optarg;
4368 while (*p) {
4369 e = strchr (p, ',');
4370 l = !e ? strlen (p) : (size_t) (e - p);
4372 for (c = soundhw; c->name; ++c) {
4373 if (!strncmp (c->name, p, l)) {
4374 c->enabled = 1;
4375 break;
4379 if (!c->name) {
4380 if (l > 80) {
4381 fprintf (stderr,
4382 "Unknown sound card name (too big to show)\n");
4384 else {
4385 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4386 (int) l, p);
4388 bad_card = 1;
4390 p += l + (e != NULL);
4393 if (bad_card)
4394 goto show_valid_cards;
4397 #endif
4399 static void select_vgahw (const char *p)
4401 const char *opts;
4403 if (strstart(p, "std", &opts)) {
4404 cirrus_vga_enabled = 0;
4405 vmsvga_enabled = 0;
4406 } else if (strstart(p, "cirrus", &opts)) {
4407 cirrus_vga_enabled = 1;
4408 vmsvga_enabled = 0;
4409 } else if (strstart(p, "vmware", &opts)) {
4410 cirrus_vga_enabled = 0;
4411 vmsvga_enabled = 1;
4412 } else {
4413 invalid_vga:
4414 fprintf(stderr, "Unknown vga type: %s\n", p);
4415 exit(1);
4417 while (*opts) {
4418 const char *nextopt;
4420 if (strstart(opts, ",retrace=", &nextopt)) {
4421 opts = nextopt;
4422 if (strstart(opts, "dumb", &nextopt))
4423 vga_retrace_method = VGA_RETRACE_DUMB;
4424 else if (strstart(opts, "precise", &nextopt))
4425 vga_retrace_method = VGA_RETRACE_PRECISE;
4426 else goto invalid_vga;
4427 } else goto invalid_vga;
4428 opts = nextopt;
4432 #ifdef _WIN32
4433 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4435 exit(STATUS_CONTROL_C_EXIT);
4436 return TRUE;
4438 #endif
4440 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4442 int ret;
4444 if(strlen(str) != 36)
4445 return -1;
4447 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4448 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4449 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4451 if(ret != 16)
4452 return -1;
4454 return 0;
4457 #define MAX_NET_CLIENTS 32
4459 #ifndef _WIN32
4461 static void termsig_handler(int signal)
4463 qemu_system_shutdown_request();
4466 static void termsig_setup(void)
4468 struct sigaction act;
4470 memset(&act, 0, sizeof(act));
4471 act.sa_handler = termsig_handler;
4472 sigaction(SIGINT, &act, NULL);
4473 sigaction(SIGHUP, &act, NULL);
4474 sigaction(SIGTERM, &act, NULL);
4477 #endif
4479 int main(int argc, char **argv, char **envp)
4481 #ifdef CONFIG_GDBSTUB
4482 int use_gdbstub;
4483 const char *gdbstub_port;
4484 #endif
4485 uint32_t boot_devices_bitmap = 0;
4486 int i;
4487 int snapshot, linux_boot, net_boot;
4488 const char *initrd_filename;
4489 const char *kernel_filename, *kernel_cmdline;
4490 const char *boot_devices = "";
4491 DisplayState *ds = &display_state;
4492 int cyls, heads, secs, translation;
4493 const char *net_clients[MAX_NET_CLIENTS];
4494 int nb_net_clients;
4495 const char *bt_opts[MAX_BT_CMDLINE];
4496 int nb_bt_opts;
4497 int hda_index;
4498 int optind;
4499 const char *r, *optarg;
4500 CharDriverState *monitor_hd;
4501 const char *monitor_device;
4502 const char *serial_devices[MAX_SERIAL_PORTS];
4503 int serial_device_index;
4504 const char *parallel_devices[MAX_PARALLEL_PORTS];
4505 int parallel_device_index;
4506 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4507 int virtio_console_index;
4508 const char *loadvm = NULL;
4509 QEMUMachine *machine;
4510 const char *cpu_model;
4511 const char *usb_devices[MAX_USB_CMDLINE];
4512 int usb_devices_index;
4513 int fds[2];
4514 int tb_size;
4515 const char *pid_file = NULL;
4516 int autostart;
4517 const char *incoming = NULL;
4519 qemu_cache_utils_init(envp);
4521 LIST_INIT (&vm_change_state_head);
4522 #ifndef _WIN32
4524 struct sigaction act;
4525 sigfillset(&act.sa_mask);
4526 act.sa_flags = 0;
4527 act.sa_handler = SIG_IGN;
4528 sigaction(SIGPIPE, &act, NULL);
4530 #else
4531 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4532 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4533 QEMU to run on a single CPU */
4535 HANDLE h;
4536 DWORD mask, smask;
4537 int i;
4538 h = GetCurrentProcess();
4539 if (GetProcessAffinityMask(h, &mask, &smask)) {
4540 for(i = 0; i < 32; i++) {
4541 if (mask & (1 << i))
4542 break;
4544 if (i != 32) {
4545 mask = 1 << i;
4546 SetProcessAffinityMask(h, mask);
4550 #endif
4552 register_machines();
4553 machine = first_machine;
4554 cpu_model = NULL;
4555 initrd_filename = NULL;
4556 ram_size = 0;
4557 vga_ram_size = VGA_RAM_SIZE;
4558 #ifdef CONFIG_GDBSTUB
4559 use_gdbstub = 0;
4560 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4561 #endif
4562 snapshot = 0;
4563 nographic = 0;
4564 curses = 0;
4565 kernel_filename = NULL;
4566 kernel_cmdline = "";
4567 cyls = heads = secs = 0;
4568 translation = BIOS_ATA_TRANSLATION_AUTO;
4569 monitor_device = "vc";
4571 serial_devices[0] = "vc:80Cx24C";
4572 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4573 serial_devices[i] = NULL;
4574 serial_device_index = 0;
4576 parallel_devices[0] = "vc:640x480";
4577 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4578 parallel_devices[i] = NULL;
4579 parallel_device_index = 0;
4581 virtio_consoles[0] = "vc:80Cx24C";
4582 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4583 virtio_consoles[i] = NULL;
4584 virtio_console_index = 0;
4586 usb_devices_index = 0;
4588 nb_net_clients = 0;
4589 nb_bt_opts = 0;
4590 nb_drives = 0;
4591 nb_drives_opt = 0;
4592 hda_index = -1;
4594 nb_nics = 0;
4596 tb_size = 0;
4597 autostart= 1;
4599 optind = 1;
4600 for(;;) {
4601 if (optind >= argc)
4602 break;
4603 r = argv[optind];
4604 if (r[0] != '-') {
4605 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4606 } else {
4607 const QEMUOption *popt;
4609 optind++;
4610 /* Treat --foo the same as -foo. */
4611 if (r[1] == '-')
4612 r++;
4613 popt = qemu_options;
4614 for(;;) {
4615 if (!popt->name) {
4616 fprintf(stderr, "%s: invalid option -- '%s'\n",
4617 argv[0], r);
4618 exit(1);
4620 if (!strcmp(popt->name, r + 1))
4621 break;
4622 popt++;
4624 if (popt->flags & HAS_ARG) {
4625 if (optind >= argc) {
4626 fprintf(stderr, "%s: option '%s' requires an argument\n",
4627 argv[0], r);
4628 exit(1);
4630 optarg = argv[optind++];
4631 } else {
4632 optarg = NULL;
4635 switch(popt->index) {
4636 case QEMU_OPTION_M:
4637 machine = find_machine(optarg);
4638 if (!machine) {
4639 QEMUMachine *m;
4640 printf("Supported machines are:\n");
4641 for(m = first_machine; m != NULL; m = m->next) {
4642 printf("%-10s %s%s\n",
4643 m->name, m->desc,
4644 m == first_machine ? " (default)" : "");
4646 exit(*optarg != '?');
4648 break;
4649 case QEMU_OPTION_cpu:
4650 /* hw initialization will check this */
4651 if (*optarg == '?') {
4652 /* XXX: implement xxx_cpu_list for targets that still miss it */
4653 #if defined(cpu_list)
4654 cpu_list(stdout, &fprintf);
4655 #endif
4656 exit(0);
4657 } else {
4658 cpu_model = optarg;
4660 break;
4661 case QEMU_OPTION_initrd:
4662 initrd_filename = optarg;
4663 break;
4664 case QEMU_OPTION_hda:
4665 if (cyls == 0)
4666 hda_index = drive_add(optarg, HD_ALIAS, 0);
4667 else
4668 hda_index = drive_add(optarg, HD_ALIAS
4669 ",cyls=%d,heads=%d,secs=%d%s",
4670 0, cyls, heads, secs,
4671 translation == BIOS_ATA_TRANSLATION_LBA ?
4672 ",trans=lba" :
4673 translation == BIOS_ATA_TRANSLATION_NONE ?
4674 ",trans=none" : "");
4675 break;
4676 case QEMU_OPTION_hdb:
4677 case QEMU_OPTION_hdc:
4678 case QEMU_OPTION_hdd:
4679 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4680 break;
4681 case QEMU_OPTION_drive:
4682 drive_add(NULL, "%s", optarg);
4683 break;
4684 case QEMU_OPTION_mtdblock:
4685 drive_add(optarg, MTD_ALIAS);
4686 break;
4687 case QEMU_OPTION_sd:
4688 drive_add(optarg, SD_ALIAS);
4689 break;
4690 case QEMU_OPTION_pflash:
4691 drive_add(optarg, PFLASH_ALIAS);
4692 break;
4693 case QEMU_OPTION_snapshot:
4694 snapshot = 1;
4695 break;
4696 case QEMU_OPTION_hdachs:
4698 const char *p;
4699 p = optarg;
4700 cyls = strtol(p, (char **)&p, 0);
4701 if (cyls < 1 || cyls > 16383)
4702 goto chs_fail;
4703 if (*p != ',')
4704 goto chs_fail;
4705 p++;
4706 heads = strtol(p, (char **)&p, 0);
4707 if (heads < 1 || heads > 16)
4708 goto chs_fail;
4709 if (*p != ',')
4710 goto chs_fail;
4711 p++;
4712 secs = strtol(p, (char **)&p, 0);
4713 if (secs < 1 || secs > 63)
4714 goto chs_fail;
4715 if (*p == ',') {
4716 p++;
4717 if (!strcmp(p, "none"))
4718 translation = BIOS_ATA_TRANSLATION_NONE;
4719 else if (!strcmp(p, "lba"))
4720 translation = BIOS_ATA_TRANSLATION_LBA;
4721 else if (!strcmp(p, "auto"))
4722 translation = BIOS_ATA_TRANSLATION_AUTO;
4723 else
4724 goto chs_fail;
4725 } else if (*p != '\0') {
4726 chs_fail:
4727 fprintf(stderr, "qemu: invalid physical CHS format\n");
4728 exit(1);
4730 if (hda_index != -1)
4731 snprintf(drives_opt[hda_index].opt,
4732 sizeof(drives_opt[hda_index].opt),
4733 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4734 0, cyls, heads, secs,
4735 translation == BIOS_ATA_TRANSLATION_LBA ?
4736 ",trans=lba" :
4737 translation == BIOS_ATA_TRANSLATION_NONE ?
4738 ",trans=none" : "");
4740 break;
4741 case QEMU_OPTION_nographic:
4742 nographic = 1;
4743 break;
4744 #ifdef CONFIG_CURSES
4745 case QEMU_OPTION_curses:
4746 curses = 1;
4747 break;
4748 #endif
4749 case QEMU_OPTION_portrait:
4750 graphic_rotate = 1;
4751 break;
4752 case QEMU_OPTION_kernel:
4753 kernel_filename = optarg;
4754 break;
4755 case QEMU_OPTION_append:
4756 kernel_cmdline = optarg;
4757 break;
4758 case QEMU_OPTION_cdrom:
4759 drive_add(optarg, CDROM_ALIAS);
4760 break;
4761 case QEMU_OPTION_boot:
4762 boot_devices = optarg;
4763 /* We just do some generic consistency checks */
4765 /* Could easily be extended to 64 devices if needed */
4766 const char *p;
4768 boot_devices_bitmap = 0;
4769 for (p = boot_devices; *p != '\0'; p++) {
4770 /* Allowed boot devices are:
4771 * a b : floppy disk drives
4772 * c ... f : IDE disk drives
4773 * g ... m : machine implementation dependant drives
4774 * n ... p : network devices
4775 * It's up to each machine implementation to check
4776 * if the given boot devices match the actual hardware
4777 * implementation and firmware features.
4779 if (*p < 'a' || *p > 'q') {
4780 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4781 exit(1);
4783 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4784 fprintf(stderr,
4785 "Boot device '%c' was given twice\n",*p);
4786 exit(1);
4788 boot_devices_bitmap |= 1 << (*p - 'a');
4791 break;
4792 case QEMU_OPTION_fda:
4793 case QEMU_OPTION_fdb:
4794 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4795 break;
4796 #ifdef TARGET_I386
4797 case QEMU_OPTION_no_fd_bootchk:
4798 fd_bootchk = 0;
4799 break;
4800 #endif
4801 case QEMU_OPTION_net:
4802 if (nb_net_clients >= MAX_NET_CLIENTS) {
4803 fprintf(stderr, "qemu: too many network clients\n");
4804 exit(1);
4806 net_clients[nb_net_clients] = optarg;
4807 nb_net_clients++;
4808 break;
4809 #ifdef CONFIG_SLIRP
4810 case QEMU_OPTION_tftp:
4811 tftp_prefix = optarg;
4812 break;
4813 case QEMU_OPTION_bootp:
4814 bootp_filename = optarg;
4815 break;
4816 #ifndef _WIN32
4817 case QEMU_OPTION_smb:
4818 net_slirp_smb(optarg);
4819 break;
4820 #endif
4821 case QEMU_OPTION_redir:
4822 net_slirp_redir(optarg);
4823 break;
4824 #endif
4825 case QEMU_OPTION_bt:
4826 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4827 fprintf(stderr, "qemu: too many bluetooth options\n");
4828 exit(1);
4830 bt_opts[nb_bt_opts++] = optarg;
4831 break;
4832 #ifdef HAS_AUDIO
4833 case QEMU_OPTION_audio_help:
4834 AUD_help ();
4835 exit (0);
4836 break;
4837 case QEMU_OPTION_soundhw:
4838 select_soundhw (optarg);
4839 break;
4840 #endif
4841 case QEMU_OPTION_h:
4842 help(0);
4843 break;
4844 case QEMU_OPTION_m: {
4845 uint64_t value;
4846 char *ptr;
4848 value = strtoul(optarg, &ptr, 10);
4849 switch (*ptr) {
4850 case 0: case 'M': case 'm':
4851 value <<= 20;
4852 break;
4853 case 'G': case 'g':
4854 value <<= 30;
4855 break;
4856 default:
4857 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4858 exit(1);
4861 /* On 32-bit hosts, QEMU is limited by virtual address space */
4862 if (value > (2047 << 20)
4863 #ifndef USE_KQEMU
4864 && HOST_LONG_BITS == 32
4865 #endif
4867 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4868 exit(1);
4870 if (value != (uint64_t)(ram_addr_t)value) {
4871 fprintf(stderr, "qemu: ram size too large\n");
4872 exit(1);
4874 ram_size = value;
4875 break;
4877 case QEMU_OPTION_d:
4879 int mask;
4880 const CPULogItem *item;
4882 mask = cpu_str_to_log_mask(optarg);
4883 if (!mask) {
4884 printf("Log items (comma separated):\n");
4885 for(item = cpu_log_items; item->mask != 0; item++) {
4886 printf("%-10s %s\n", item->name, item->help);
4888 exit(1);
4890 cpu_set_log(mask);
4892 break;
4893 #ifdef CONFIG_GDBSTUB
4894 case QEMU_OPTION_s:
4895 use_gdbstub = 1;
4896 break;
4897 case QEMU_OPTION_p:
4898 gdbstub_port = optarg;
4899 break;
4900 #endif
4901 case QEMU_OPTION_L:
4902 bios_dir = optarg;
4903 break;
4904 case QEMU_OPTION_bios:
4905 bios_name = optarg;
4906 break;
4907 case QEMU_OPTION_S:
4908 autostart = 0;
4909 break;
4910 case QEMU_OPTION_k:
4911 keyboard_layout = optarg;
4912 break;
4913 case QEMU_OPTION_localtime:
4914 rtc_utc = 0;
4915 break;
4916 case QEMU_OPTION_vga:
4917 select_vgahw (optarg);
4918 break;
4919 case QEMU_OPTION_g:
4921 const char *p;
4922 int w, h, depth;
4923 p = optarg;
4924 w = strtol(p, (char **)&p, 10);
4925 if (w <= 0) {
4926 graphic_error:
4927 fprintf(stderr, "qemu: invalid resolution or depth\n");
4928 exit(1);
4930 if (*p != 'x')
4931 goto graphic_error;
4932 p++;
4933 h = strtol(p, (char **)&p, 10);
4934 if (h <= 0)
4935 goto graphic_error;
4936 if (*p == 'x') {
4937 p++;
4938 depth = strtol(p, (char **)&p, 10);
4939 if (depth != 8 && depth != 15 && depth != 16 &&
4940 depth != 24 && depth != 32)
4941 goto graphic_error;
4942 } else if (*p == '\0') {
4943 depth = graphic_depth;
4944 } else {
4945 goto graphic_error;
4948 graphic_width = w;
4949 graphic_height = h;
4950 graphic_depth = depth;
4952 break;
4953 case QEMU_OPTION_echr:
4955 char *r;
4956 term_escape_char = strtol(optarg, &r, 0);
4957 if (r == optarg)
4958 printf("Bad argument to echr\n");
4959 break;
4961 case QEMU_OPTION_monitor:
4962 monitor_device = optarg;
4963 break;
4964 case QEMU_OPTION_serial:
4965 if (serial_device_index >= MAX_SERIAL_PORTS) {
4966 fprintf(stderr, "qemu: too many serial ports\n");
4967 exit(1);
4969 serial_devices[serial_device_index] = optarg;
4970 serial_device_index++;
4971 break;
4972 case QEMU_OPTION_parallel:
4973 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4974 fprintf(stderr, "qemu: too many parallel ports\n");
4975 exit(1);
4977 parallel_devices[parallel_device_index] = optarg;
4978 parallel_device_index++;
4979 break;
4980 case QEMU_OPTION_loadvm:
4981 loadvm = optarg;
4982 break;
4983 case QEMU_OPTION_full_screen:
4984 full_screen = 1;
4985 break;
4986 #ifdef CONFIG_SDL
4987 case QEMU_OPTION_no_frame:
4988 no_frame = 1;
4989 break;
4990 case QEMU_OPTION_alt_grab:
4991 alt_grab = 1;
4992 break;
4993 case QEMU_OPTION_no_quit:
4994 no_quit = 1;
4995 break;
4996 #endif
4997 case QEMU_OPTION_pidfile:
4998 pid_file = optarg;
4999 break;
5000 #ifdef TARGET_I386
5001 case QEMU_OPTION_win2k_hack:
5002 win2k_install_hack = 1;
5003 break;
5004 #endif
5005 #ifdef USE_KQEMU
5006 case QEMU_OPTION_no_kqemu:
5007 kqemu_allowed = 0;
5008 break;
5009 case QEMU_OPTION_kernel_kqemu:
5010 kqemu_allowed = 2;
5011 break;
5012 #endif
5013 #ifdef CONFIG_KVM
5014 case QEMU_OPTION_enable_kvm:
5015 kvm_allowed = 1;
5016 #ifdef USE_KQEMU
5017 kqemu_allowed = 0;
5018 #endif
5019 break;
5020 #endif
5021 case QEMU_OPTION_usb:
5022 usb_enabled = 1;
5023 break;
5024 case QEMU_OPTION_usbdevice:
5025 usb_enabled = 1;
5026 if (usb_devices_index >= MAX_USB_CMDLINE) {
5027 fprintf(stderr, "Too many USB devices\n");
5028 exit(1);
5030 usb_devices[usb_devices_index] = optarg;
5031 usb_devices_index++;
5032 break;
5033 case QEMU_OPTION_smp:
5034 smp_cpus = atoi(optarg);
5035 if (smp_cpus < 1) {
5036 fprintf(stderr, "Invalid number of CPUs\n");
5037 exit(1);
5039 break;
5040 case QEMU_OPTION_vnc:
5041 vnc_display = optarg;
5042 break;
5043 case QEMU_OPTION_no_acpi:
5044 acpi_enabled = 0;
5045 break;
5046 case QEMU_OPTION_no_hpet:
5047 no_hpet = 1;
5048 break;
5049 case QEMU_OPTION_no_reboot:
5050 no_reboot = 1;
5051 break;
5052 case QEMU_OPTION_no_shutdown:
5053 no_shutdown = 1;
5054 break;
5055 case QEMU_OPTION_show_cursor:
5056 cursor_hide = 0;
5057 break;
5058 case QEMU_OPTION_uuid:
5059 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5060 fprintf(stderr, "Fail to parse UUID string."
5061 " Wrong format.\n");
5062 exit(1);
5064 break;
5065 case QEMU_OPTION_daemonize:
5066 daemonize = 1;
5067 break;
5068 case QEMU_OPTION_option_rom:
5069 if (nb_option_roms >= MAX_OPTION_ROMS) {
5070 fprintf(stderr, "Too many option ROMs\n");
5071 exit(1);
5073 option_rom[nb_option_roms] = optarg;
5074 nb_option_roms++;
5075 break;
5076 case QEMU_OPTION_semihosting:
5077 semihosting_enabled = 1;
5078 break;
5079 case QEMU_OPTION_name:
5080 qemu_name = optarg;
5081 break;
5082 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5083 case QEMU_OPTION_prom_env:
5084 if (nb_prom_envs >= MAX_PROM_ENVS) {
5085 fprintf(stderr, "Too many prom variables\n");
5086 exit(1);
5088 prom_envs[nb_prom_envs] = optarg;
5089 nb_prom_envs++;
5090 break;
5091 #endif
5092 #ifdef TARGET_ARM
5093 case QEMU_OPTION_old_param:
5094 old_param = 1;
5095 break;
5096 #endif
5097 case QEMU_OPTION_clock:
5098 configure_alarms(optarg);
5099 break;
5100 case QEMU_OPTION_startdate:
5102 struct tm tm;
5103 time_t rtc_start_date;
5104 if (!strcmp(optarg, "now")) {
5105 rtc_date_offset = -1;
5106 } else {
5107 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5108 &tm.tm_year,
5109 &tm.tm_mon,
5110 &tm.tm_mday,
5111 &tm.tm_hour,
5112 &tm.tm_min,
5113 &tm.tm_sec) == 6) {
5114 /* OK */
5115 } else if (sscanf(optarg, "%d-%d-%d",
5116 &tm.tm_year,
5117 &tm.tm_mon,
5118 &tm.tm_mday) == 3) {
5119 tm.tm_hour = 0;
5120 tm.tm_min = 0;
5121 tm.tm_sec = 0;
5122 } else {
5123 goto date_fail;
5125 tm.tm_year -= 1900;
5126 tm.tm_mon--;
5127 rtc_start_date = mktimegm(&tm);
5128 if (rtc_start_date == -1) {
5129 date_fail:
5130 fprintf(stderr, "Invalid date format. Valid format are:\n"
5131 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5132 exit(1);
5134 rtc_date_offset = time(NULL) - rtc_start_date;
5137 break;
5138 case QEMU_OPTION_tb_size:
5139 tb_size = strtol(optarg, NULL, 0);
5140 if (tb_size < 0)
5141 tb_size = 0;
5142 break;
5143 case QEMU_OPTION_icount:
5144 use_icount = 1;
5145 if (strcmp(optarg, "auto") == 0) {
5146 icount_time_shift = -1;
5147 } else {
5148 icount_time_shift = strtol(optarg, NULL, 0);
5150 break;
5151 case QEMU_OPTION_incoming:
5152 incoming = optarg;
5153 break;
5158 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5159 if (kvm_allowed && kqemu_allowed) {
5160 fprintf(stderr,
5161 "You can not enable both KVM and kqemu at the same time\n");
5162 exit(1);
5164 #endif
5166 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5167 if (smp_cpus > machine->max_cpus) {
5168 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5169 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5170 machine->max_cpus);
5171 exit(1);
5174 if (nographic) {
5175 if (serial_device_index == 0)
5176 serial_devices[0] = "stdio";
5177 if (parallel_device_index == 0)
5178 parallel_devices[0] = "null";
5179 if (strncmp(monitor_device, "vc", 2) == 0)
5180 monitor_device = "stdio";
5181 if (virtio_console_index == 0)
5182 virtio_consoles[0] = "null";
5185 #ifndef _WIN32
5186 if (daemonize) {
5187 pid_t pid;
5189 if (pipe(fds) == -1)
5190 exit(1);
5192 pid = fork();
5193 if (pid > 0) {
5194 uint8_t status;
5195 ssize_t len;
5197 close(fds[1]);
5199 again:
5200 len = read(fds[0], &status, 1);
5201 if (len == -1 && (errno == EINTR))
5202 goto again;
5204 if (len != 1)
5205 exit(1);
5206 else if (status == 1) {
5207 fprintf(stderr, "Could not acquire pidfile\n");
5208 exit(1);
5209 } else
5210 exit(0);
5211 } else if (pid < 0)
5212 exit(1);
5214 setsid();
5216 pid = fork();
5217 if (pid > 0)
5218 exit(0);
5219 else if (pid < 0)
5220 exit(1);
5222 umask(027);
5224 signal(SIGTSTP, SIG_IGN);
5225 signal(SIGTTOU, SIG_IGN);
5226 signal(SIGTTIN, SIG_IGN);
5228 #endif
5230 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5231 if (daemonize) {
5232 uint8_t status = 1;
5233 write(fds[1], &status, 1);
5234 } else
5235 fprintf(stderr, "Could not acquire pid file\n");
5236 exit(1);
5239 #ifdef USE_KQEMU
5240 if (smp_cpus > 1)
5241 kqemu_allowed = 0;
5242 #endif
5243 linux_boot = (kernel_filename != NULL);
5244 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5246 if (!linux_boot && net_boot == 0 &&
5247 !machine->nodisk_ok && nb_drives_opt == 0)
5248 help(1);
5250 if (!linux_boot && *kernel_cmdline != '\0') {
5251 fprintf(stderr, "-append only allowed with -kernel option\n");
5252 exit(1);
5255 if (!linux_boot && initrd_filename != NULL) {
5256 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5257 exit(1);
5260 /* boot to floppy or the default cd if no hard disk defined yet */
5261 if (!boot_devices[0]) {
5262 boot_devices = "cad";
5264 setvbuf(stdout, NULL, _IOLBF, 0);
5266 init_timers();
5267 if (init_timer_alarm() < 0) {
5268 fprintf(stderr, "could not initialize alarm timer\n");
5269 exit(1);
5271 if (use_icount && icount_time_shift < 0) {
5272 use_icount = 2;
5273 /* 125MIPS seems a reasonable initial guess at the guest speed.
5274 It will be corrected fairly quickly anyway. */
5275 icount_time_shift = 3;
5276 init_icount_adjust();
5279 #ifdef _WIN32
5280 socket_init();
5281 #endif
5283 /* init network clients */
5284 if (nb_net_clients == 0) {
5285 /* if no clients, we use a default config */
5286 net_clients[nb_net_clients++] = "nic";
5287 #ifdef CONFIG_SLIRP
5288 net_clients[nb_net_clients++] = "user";
5289 #endif
5292 for(i = 0;i < nb_net_clients; i++) {
5293 if (net_client_parse(net_clients[i]) < 0)
5294 exit(1);
5296 net_client_check();
5298 #ifdef TARGET_I386
5299 /* XXX: this should be moved in the PC machine instantiation code */
5300 if (net_boot != 0) {
5301 int netroms = 0;
5302 for (i = 0; i < nb_nics && i < 4; i++) {
5303 const char *model = nd_table[i].model;
5304 char buf[1024];
5305 if (net_boot & (1 << i)) {
5306 if (model == NULL)
5307 model = "ne2k_pci";
5308 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5309 if (get_image_size(buf) > 0) {
5310 if (nb_option_roms >= MAX_OPTION_ROMS) {
5311 fprintf(stderr, "Too many option ROMs\n");
5312 exit(1);
5314 option_rom[nb_option_roms] = strdup(buf);
5315 nb_option_roms++;
5316 netroms++;
5320 if (netroms == 0) {
5321 fprintf(stderr, "No valid PXE rom found for network device\n");
5322 exit(1);
5325 #endif
5327 /* init the bluetooth world */
5328 for (i = 0; i < nb_bt_opts; i++)
5329 if (bt_parse(bt_opts[i]))
5330 exit(1);
5332 /* init the memory */
5333 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5335 if (machine->ram_require & RAMSIZE_FIXED) {
5336 if (ram_size > 0) {
5337 if (ram_size < phys_ram_size) {
5338 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5339 machine->name, (unsigned long long) phys_ram_size);
5340 exit(-1);
5343 phys_ram_size = ram_size;
5344 } else
5345 ram_size = phys_ram_size;
5346 } else {
5347 if (ram_size == 0)
5348 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5350 phys_ram_size += ram_size;
5353 phys_ram_base = qemu_vmalloc(phys_ram_size);
5354 if (!phys_ram_base) {
5355 fprintf(stderr, "Could not allocate physical memory\n");
5356 exit(1);
5359 /* init the dynamic translator */
5360 cpu_exec_init_all(tb_size * 1024 * 1024);
5362 bdrv_init();
5364 /* we always create the cdrom drive, even if no disk is there */
5366 if (nb_drives_opt < MAX_DRIVES)
5367 drive_add(NULL, CDROM_ALIAS);
5369 /* we always create at least one floppy */
5371 if (nb_drives_opt < MAX_DRIVES)
5372 drive_add(NULL, FD_ALIAS, 0);
5374 /* we always create one sd slot, even if no card is in it */
5376 if (nb_drives_opt < MAX_DRIVES)
5377 drive_add(NULL, SD_ALIAS);
5379 /* open the virtual block devices */
5381 for(i = 0; i < nb_drives_opt; i++)
5382 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5383 exit(1);
5385 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5386 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5388 /* terminal init */
5389 memset(&display_state, 0, sizeof(display_state));
5390 if (nographic) {
5391 if (curses) {
5392 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5393 exit(1);
5395 /* nearly nothing to do */
5396 dumb_display_init(ds);
5397 } else if (vnc_display != NULL) {
5398 vnc_display_init(ds);
5399 if (vnc_display_open(ds, vnc_display) < 0)
5400 exit(1);
5401 } else
5402 #if defined(CONFIG_CURSES)
5403 if (curses) {
5404 curses_display_init(ds, full_screen);
5405 } else
5406 #endif
5408 #if defined(CONFIG_SDL)
5409 sdl_display_init(ds, full_screen, no_frame);
5410 #elif defined(CONFIG_COCOA)
5411 cocoa_display_init(ds, full_screen);
5412 #else
5413 dumb_display_init(ds);
5414 #endif
5417 #ifndef _WIN32
5418 /* must be after terminal init, SDL library changes signal handlers */
5419 termsig_setup();
5420 #endif
5422 /* Maintain compatibility with multiple stdio monitors */
5423 if (!strcmp(monitor_device,"stdio")) {
5424 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5425 const char *devname = serial_devices[i];
5426 if (devname && !strcmp(devname,"mon:stdio")) {
5427 monitor_device = NULL;
5428 break;
5429 } else if (devname && !strcmp(devname,"stdio")) {
5430 monitor_device = NULL;
5431 serial_devices[i] = "mon:stdio";
5432 break;
5436 if (monitor_device) {
5437 monitor_hd = qemu_chr_open("monitor", monitor_device);
5438 if (!monitor_hd) {
5439 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5440 exit(1);
5442 monitor_init(monitor_hd, !nographic);
5445 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5446 const char *devname = serial_devices[i];
5447 if (devname && strcmp(devname, "none")) {
5448 char label[32];
5449 snprintf(label, sizeof(label), "serial%d", i);
5450 serial_hds[i] = qemu_chr_open(label, devname);
5451 if (!serial_hds[i]) {
5452 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5453 devname);
5454 exit(1);
5456 if (strstart(devname, "vc", 0))
5457 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5461 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5462 const char *devname = parallel_devices[i];
5463 if (devname && strcmp(devname, "none")) {
5464 char label[32];
5465 snprintf(label, sizeof(label), "parallel%d", i);
5466 parallel_hds[i] = qemu_chr_open(label, devname);
5467 if (!parallel_hds[i]) {
5468 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5469 devname);
5470 exit(1);
5472 if (strstart(devname, "vc", 0))
5473 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5477 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5478 const char *devname = virtio_consoles[i];
5479 if (devname && strcmp(devname, "none")) {
5480 char label[32];
5481 snprintf(label, sizeof(label), "virtcon%d", i);
5482 virtcon_hds[i] = qemu_chr_open(label, devname);
5483 if (!virtcon_hds[i]) {
5484 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5485 devname);
5486 exit(1);
5488 if (strstart(devname, "vc", 0))
5489 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5493 if (kvm_enabled()) {
5494 int ret;
5496 ret = kvm_init(smp_cpus);
5497 if (ret < 0) {
5498 fprintf(stderr, "failed to initialize KVM\n");
5499 exit(1);
5503 machine->init(ram_size, vga_ram_size, boot_devices, ds,
5504 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5506 /* Set KVM's vcpu state to qemu's initial CPUState. */
5507 if (kvm_enabled()) {
5508 int ret;
5510 ret = kvm_sync_vcpus();
5511 if (ret < 0) {
5512 fprintf(stderr, "failed to initialize vcpus\n");
5513 exit(1);
5517 /* init USB devices */
5518 if (usb_enabled) {
5519 for(i = 0; i < usb_devices_index; i++) {
5520 if (usb_device_add(usb_devices[i]) < 0) {
5521 fprintf(stderr, "Warning: could not add USB device %s\n",
5522 usb_devices[i]);
5527 if (display_state.dpy_refresh) {
5528 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5529 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5532 #ifdef CONFIG_GDBSTUB
5533 if (use_gdbstub) {
5534 /* XXX: use standard host:port notation and modify options
5535 accordingly. */
5536 if (gdbserver_start(gdbstub_port) < 0) {
5537 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5538 gdbstub_port);
5539 exit(1);
5542 #endif
5544 if (loadvm)
5545 do_loadvm(loadvm);
5547 if (incoming) {
5548 autostart = 0; /* fixme how to deal with -daemonize */
5549 qemu_start_incoming_migration(incoming);
5553 /* XXX: simplify init */
5554 read_passwords();
5555 if (autostart) {
5556 vm_start();
5560 if (daemonize) {
5561 uint8_t status = 0;
5562 ssize_t len;
5563 int fd;
5565 again1:
5566 len = write(fds[1], &status, 1);
5567 if (len == -1 && (errno == EINTR))
5568 goto again1;
5570 if (len != 1)
5571 exit(1);
5573 chdir("/");
5574 TFR(fd = open("/dev/null", O_RDWR));
5575 if (fd == -1)
5576 exit(1);
5578 dup2(fd, 0);
5579 dup2(fd, 1);
5580 dup2(fd, 2);
5582 close(fd);
5585 main_loop();
5586 quit_timers();
5587 net_cleanup();
5589 return 0;