Fix alignment of 64bit args
[qemu/mini2440.git] / vl.c
blobe4edf20a72a965ee957e305cbc86a9a6f9d68427
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "block.h"
40 #include "audio/audio.h"
41 #include "migration.h"
42 #include "kvm.h"
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <time.h>
48 #include <errno.h>
49 #include <sys/time.h>
50 #include <zlib.h>
52 #ifndef _WIN32
53 #include <sys/times.h>
54 #include <sys/wait.h>
55 #include <termios.h>
56 #include <sys/mman.h>
57 #include <sys/ioctl.h>
58 #include <sys/resource.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <net/if.h>
62 #if defined(__NetBSD__)
63 #include <net/if_tap.h>
64 #endif
65 #ifdef __linux__
66 #include <linux/if_tun.h>
67 #endif
68 #include <arpa/inet.h>
69 #include <dirent.h>
70 #include <netdb.h>
71 #include <sys/select.h>
72 #ifdef _BSD
73 #include <sys/stat.h>
74 #ifdef __FreeBSD__
75 #include <libutil.h>
76 #else
77 #include <util.h>
78 #endif
79 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
80 #include <freebsd/stdlib.h>
81 #else
82 #ifdef __linux__
83 #include <pty.h>
84 #include <malloc.h>
85 #include <linux/rtc.h>
87 /* For the benefit of older linux systems which don't supply it,
88 we use a local copy of hpet.h. */
89 /* #include <linux/hpet.h> */
90 #include "hpet.h"
92 #include <linux/ppdev.h>
93 #include <linux/parport.h>
94 #endif
95 #ifdef __sun__
96 #include <sys/stat.h>
97 #include <sys/ethernet.h>
98 #include <sys/sockio.h>
99 #include <netinet/arp.h>
100 #include <netinet/in.h>
101 #include <netinet/in_systm.h>
102 #include <netinet/ip.h>
103 #include <netinet/ip_icmp.h> // must come after ip.h
104 #include <netinet/udp.h>
105 #include <netinet/tcp.h>
106 #include <net/if.h>
107 #include <syslog.h>
108 #include <stropts.h>
109 #endif
110 #endif
111 #endif
113 #include "qemu_socket.h"
115 #if defined(CONFIG_SLIRP)
116 #include "libslirp.h"
117 #endif
119 #if defined(__OpenBSD__)
120 #include <util.h>
121 #endif
123 #if defined(CONFIG_VDE)
124 #include <libvdeplug.h>
125 #endif
127 #ifdef _WIN32
128 #include <malloc.h>
129 #include <sys/timeb.h>
130 #include <mmsystem.h>
131 #define getopt_long_only getopt_long
132 #define memalign(align, size) malloc(size)
133 #endif
135 #ifdef CONFIG_SDL
136 #ifdef __APPLE__
137 #include <SDL/SDL.h>
138 #endif
139 #endif /* CONFIG_SDL */
141 #ifdef CONFIG_COCOA
142 #undef main
143 #define main qemu_main
144 #endif /* CONFIG_COCOA */
146 #include "disas.h"
148 #include "exec-all.h"
150 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
151 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
152 #ifdef __sun__
153 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
154 #else
155 #define SMBD_COMMAND "/usr/sbin/smbd"
156 #endif
158 //#define DEBUG_UNUSED_IOPORT
159 //#define DEBUG_IOPORT
160 //#define DEBUG_NET
161 //#define DEBUG_SLIRP
163 #ifdef TARGET_PPC
164 #define DEFAULT_RAM_SIZE 144
165 #else
166 #define DEFAULT_RAM_SIZE 128
167 #endif
169 /* Max number of USB devices that can be specified on the commandline. */
170 #define MAX_USB_CMDLINE 8
172 /* Max number of bluetooth switches on the commandline. */
173 #define MAX_BT_CMDLINE 10
175 /* XXX: use a two level table to limit memory usage */
176 #define MAX_IOPORTS 65536
178 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
179 const char *bios_name = NULL;
180 static void *ioport_opaque[MAX_IOPORTS];
181 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
182 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
183 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
184 to store the VM snapshots */
185 DriveInfo drives_table[MAX_DRIVES+1];
186 int nb_drives;
187 static int vga_ram_size;
188 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
189 DisplayState display_state;
190 int nographic;
191 static int curses;
192 const char* keyboard_layout = NULL;
193 int64_t ticks_per_sec;
194 ram_addr_t ram_size;
195 int nb_nics;
196 NICInfo nd_table[MAX_NICS];
197 int vm_running;
198 static int rtc_utc = 1;
199 static int rtc_date_offset = -1; /* -1 means no change */
200 int cirrus_vga_enabled = 1;
201 int vmsvga_enabled = 0;
202 #ifdef TARGET_SPARC
203 int graphic_width = 1024;
204 int graphic_height = 768;
205 int graphic_depth = 8;
206 #else
207 int graphic_width = 800;
208 int graphic_height = 600;
209 int graphic_depth = 15;
210 #endif
211 static int full_screen = 0;
212 #ifdef CONFIG_SDL
213 static int no_frame = 0;
214 #endif
215 int no_quit = 0;
216 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
217 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
218 #ifdef TARGET_I386
219 int win2k_install_hack = 0;
220 #endif
221 int usb_enabled = 0;
222 int smp_cpus = 1;
223 const char *vnc_display;
224 int acpi_enabled = 1;
225 int fd_bootchk = 1;
226 int no_reboot = 0;
227 int no_shutdown = 0;
228 int cursor_hide = 1;
229 int graphic_rotate = 0;
230 int daemonize = 0;
231 const char *option_rom[MAX_OPTION_ROMS];
232 int nb_option_roms;
233 int semihosting_enabled = 0;
234 #ifdef TARGET_ARM
235 int old_param = 0;
236 #endif
237 const char *qemu_name;
238 int alt_grab = 0;
239 #ifdef TARGET_SPARC
240 unsigned int nb_prom_envs = 0;
241 const char *prom_envs[MAX_PROM_ENVS];
242 #endif
243 static int nb_drives_opt;
244 static struct drive_opt {
245 const char *file;
246 char opt[1024];
247 } drives_opt[MAX_DRIVES];
249 static CPUState *cur_cpu;
250 static CPUState *next_cpu;
251 static int event_pending = 1;
252 /* Conversion factor from emulated instructions to virtual clock ticks. */
253 static int icount_time_shift;
254 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
255 #define MAX_ICOUNT_SHIFT 10
256 /* Compensate for varying guest execution speed. */
257 static int64_t qemu_icount_bias;
258 static QEMUTimer *icount_rt_timer;
259 static QEMUTimer *icount_vm_timer;
261 uint8_t qemu_uuid[16];
263 /***********************************************************/
264 /* x86 ISA bus support */
266 target_phys_addr_t isa_mem_base = 0;
267 PicState2 *isa_pic;
269 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
270 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
272 static uint32_t ioport_read(int index, uint32_t address)
274 static IOPortReadFunc *default_func[3] = {
275 default_ioport_readb,
276 default_ioport_readw,
277 default_ioport_readl
279 IOPortReadFunc *func = ioport_read_table[index][address];
280 if (!func)
281 func = default_func[index];
282 return func(ioport_opaque[address], address);
285 static void ioport_write(int index, uint32_t address, uint32_t data)
287 static IOPortWriteFunc *default_func[3] = {
288 default_ioport_writeb,
289 default_ioport_writew,
290 default_ioport_writel
292 IOPortWriteFunc *func = ioport_write_table[index][address];
293 if (!func)
294 func = default_func[index];
295 func(ioport_opaque[address], address, data);
298 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
300 #ifdef DEBUG_UNUSED_IOPORT
301 fprintf(stderr, "unused inb: port=0x%04x\n", address);
302 #endif
303 return 0xff;
306 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
308 #ifdef DEBUG_UNUSED_IOPORT
309 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
310 #endif
313 /* default is to make two byte accesses */
314 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
316 uint32_t data;
317 data = ioport_read(0, address);
318 address = (address + 1) & (MAX_IOPORTS - 1);
319 data |= ioport_read(0, address) << 8;
320 return data;
323 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
325 ioport_write(0, address, data & 0xff);
326 address = (address + 1) & (MAX_IOPORTS - 1);
327 ioport_write(0, address, (data >> 8) & 0xff);
330 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
332 #ifdef DEBUG_UNUSED_IOPORT
333 fprintf(stderr, "unused inl: port=0x%04x\n", address);
334 #endif
335 return 0xffffffff;
338 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
340 #ifdef DEBUG_UNUSED_IOPORT
341 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
342 #endif
345 /* size is the word size in byte */
346 int register_ioport_read(int start, int length, int size,
347 IOPortReadFunc *func, void *opaque)
349 int i, bsize;
351 if (size == 1) {
352 bsize = 0;
353 } else if (size == 2) {
354 bsize = 1;
355 } else if (size == 4) {
356 bsize = 2;
357 } else {
358 hw_error("register_ioport_read: invalid size");
359 return -1;
361 for(i = start; i < start + length; i += size) {
362 ioport_read_table[bsize][i] = func;
363 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
364 hw_error("register_ioport_read: invalid opaque");
365 ioport_opaque[i] = opaque;
367 return 0;
370 /* size is the word size in byte */
371 int register_ioport_write(int start, int length, int size,
372 IOPortWriteFunc *func, void *opaque)
374 int i, bsize;
376 if (size == 1) {
377 bsize = 0;
378 } else if (size == 2) {
379 bsize = 1;
380 } else if (size == 4) {
381 bsize = 2;
382 } else {
383 hw_error("register_ioport_write: invalid size");
384 return -1;
386 for(i = start; i < start + length; i += size) {
387 ioport_write_table[bsize][i] = func;
388 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
389 hw_error("register_ioport_write: invalid opaque");
390 ioport_opaque[i] = opaque;
392 return 0;
395 void isa_unassign_ioport(int start, int length)
397 int i;
399 for(i = start; i < start + length; i++) {
400 ioport_read_table[0][i] = default_ioport_readb;
401 ioport_read_table[1][i] = default_ioport_readw;
402 ioport_read_table[2][i] = default_ioport_readl;
404 ioport_write_table[0][i] = default_ioport_writeb;
405 ioport_write_table[1][i] = default_ioport_writew;
406 ioport_write_table[2][i] = default_ioport_writel;
410 /***********************************************************/
412 void cpu_outb(CPUState *env, int addr, int val)
414 #ifdef DEBUG_IOPORT
415 if (loglevel & CPU_LOG_IOPORT)
416 fprintf(logfile, "outb: %04x %02x\n", addr, val);
417 #endif
418 ioport_write(0, addr, val);
419 #ifdef USE_KQEMU
420 if (env)
421 env->last_io_time = cpu_get_time_fast();
422 #endif
425 void cpu_outw(CPUState *env, int addr, int val)
427 #ifdef DEBUG_IOPORT
428 if (loglevel & CPU_LOG_IOPORT)
429 fprintf(logfile, "outw: %04x %04x\n", addr, val);
430 #endif
431 ioport_write(1, addr, val);
432 #ifdef USE_KQEMU
433 if (env)
434 env->last_io_time = cpu_get_time_fast();
435 #endif
438 void cpu_outl(CPUState *env, int addr, int val)
440 #ifdef DEBUG_IOPORT
441 if (loglevel & CPU_LOG_IOPORT)
442 fprintf(logfile, "outl: %04x %08x\n", addr, val);
443 #endif
444 ioport_write(2, addr, val);
445 #ifdef USE_KQEMU
446 if (env)
447 env->last_io_time = cpu_get_time_fast();
448 #endif
451 int cpu_inb(CPUState *env, int addr)
453 int val;
454 val = ioport_read(0, addr);
455 #ifdef DEBUG_IOPORT
456 if (loglevel & CPU_LOG_IOPORT)
457 fprintf(logfile, "inb : %04x %02x\n", addr, val);
458 #endif
459 #ifdef USE_KQEMU
460 if (env)
461 env->last_io_time = cpu_get_time_fast();
462 #endif
463 return val;
466 int cpu_inw(CPUState *env, int addr)
468 int val;
469 val = ioport_read(1, addr);
470 #ifdef DEBUG_IOPORT
471 if (loglevel & CPU_LOG_IOPORT)
472 fprintf(logfile, "inw : %04x %04x\n", addr, val);
473 #endif
474 #ifdef USE_KQEMU
475 if (env)
476 env->last_io_time = cpu_get_time_fast();
477 #endif
478 return val;
481 int cpu_inl(CPUState *env, int addr)
483 int val;
484 val = ioport_read(2, addr);
485 #ifdef DEBUG_IOPORT
486 if (loglevel & CPU_LOG_IOPORT)
487 fprintf(logfile, "inl : %04x %08x\n", addr, val);
488 #endif
489 #ifdef USE_KQEMU
490 if (env)
491 env->last_io_time = cpu_get_time_fast();
492 #endif
493 return val;
496 /***********************************************************/
497 void hw_error(const char *fmt, ...)
499 va_list ap;
500 CPUState *env;
502 va_start(ap, fmt);
503 fprintf(stderr, "qemu: hardware error: ");
504 vfprintf(stderr, fmt, ap);
505 fprintf(stderr, "\n");
506 for(env = first_cpu; env != NULL; env = env->next_cpu) {
507 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
508 #ifdef TARGET_I386
509 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
510 #else
511 cpu_dump_state(env, stderr, fprintf, 0);
512 #endif
514 va_end(ap);
515 abort();
518 /***********************************************************/
519 /* keyboard/mouse */
521 static QEMUPutKBDEvent *qemu_put_kbd_event;
522 static void *qemu_put_kbd_event_opaque;
523 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
524 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
526 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
528 qemu_put_kbd_event_opaque = opaque;
529 qemu_put_kbd_event = func;
532 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
533 void *opaque, int absolute,
534 const char *name)
536 QEMUPutMouseEntry *s, *cursor;
538 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
539 if (!s)
540 return NULL;
542 s->qemu_put_mouse_event = func;
543 s->qemu_put_mouse_event_opaque = opaque;
544 s->qemu_put_mouse_event_absolute = absolute;
545 s->qemu_put_mouse_event_name = qemu_strdup(name);
546 s->next = NULL;
548 if (!qemu_put_mouse_event_head) {
549 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
550 return s;
553 cursor = qemu_put_mouse_event_head;
554 while (cursor->next != NULL)
555 cursor = cursor->next;
557 cursor->next = s;
558 qemu_put_mouse_event_current = s;
560 return s;
563 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
565 QEMUPutMouseEntry *prev = NULL, *cursor;
567 if (!qemu_put_mouse_event_head || entry == NULL)
568 return;
570 cursor = qemu_put_mouse_event_head;
571 while (cursor != NULL && cursor != entry) {
572 prev = cursor;
573 cursor = cursor->next;
576 if (cursor == NULL) // does not exist or list empty
577 return;
578 else if (prev == NULL) { // entry is head
579 qemu_put_mouse_event_head = cursor->next;
580 if (qemu_put_mouse_event_current == entry)
581 qemu_put_mouse_event_current = cursor->next;
582 qemu_free(entry->qemu_put_mouse_event_name);
583 qemu_free(entry);
584 return;
587 prev->next = entry->next;
589 if (qemu_put_mouse_event_current == entry)
590 qemu_put_mouse_event_current = prev;
592 qemu_free(entry->qemu_put_mouse_event_name);
593 qemu_free(entry);
596 void kbd_put_keycode(int keycode)
598 if (qemu_put_kbd_event) {
599 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
603 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
605 QEMUPutMouseEvent *mouse_event;
606 void *mouse_event_opaque;
607 int width;
609 if (!qemu_put_mouse_event_current) {
610 return;
613 mouse_event =
614 qemu_put_mouse_event_current->qemu_put_mouse_event;
615 mouse_event_opaque =
616 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
618 if (mouse_event) {
619 if (graphic_rotate) {
620 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
621 width = 0x7fff;
622 else
623 width = graphic_width - 1;
624 mouse_event(mouse_event_opaque,
625 width - dy, dx, dz, buttons_state);
626 } else
627 mouse_event(mouse_event_opaque,
628 dx, dy, dz, buttons_state);
632 int kbd_mouse_is_absolute(void)
634 if (!qemu_put_mouse_event_current)
635 return 0;
637 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
640 void do_info_mice(void)
642 QEMUPutMouseEntry *cursor;
643 int index = 0;
645 if (!qemu_put_mouse_event_head) {
646 term_printf("No mouse devices connected\n");
647 return;
650 term_printf("Mouse devices available:\n");
651 cursor = qemu_put_mouse_event_head;
652 while (cursor != NULL) {
653 term_printf("%c Mouse #%d: %s\n",
654 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
655 index, cursor->qemu_put_mouse_event_name);
656 index++;
657 cursor = cursor->next;
661 void do_mouse_set(int index)
663 QEMUPutMouseEntry *cursor;
664 int i = 0;
666 if (!qemu_put_mouse_event_head) {
667 term_printf("No mouse devices connected\n");
668 return;
671 cursor = qemu_put_mouse_event_head;
672 while (cursor != NULL && index != i) {
673 i++;
674 cursor = cursor->next;
677 if (cursor != NULL)
678 qemu_put_mouse_event_current = cursor;
679 else
680 term_printf("Mouse at given index not found\n");
683 /* compute with 96 bit intermediate result: (a*b)/c */
684 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
686 union {
687 uint64_t ll;
688 struct {
689 #ifdef WORDS_BIGENDIAN
690 uint32_t high, low;
691 #else
692 uint32_t low, high;
693 #endif
694 } l;
695 } u, res;
696 uint64_t rl, rh;
698 u.ll = a;
699 rl = (uint64_t)u.l.low * (uint64_t)b;
700 rh = (uint64_t)u.l.high * (uint64_t)b;
701 rh += (rl >> 32);
702 res.l.high = rh / c;
703 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
704 return res.ll;
707 /***********************************************************/
708 /* real time host monotonic timer */
710 #define QEMU_TIMER_BASE 1000000000LL
712 #ifdef WIN32
714 static int64_t clock_freq;
716 static void init_get_clock(void)
718 LARGE_INTEGER freq;
719 int ret;
720 ret = QueryPerformanceFrequency(&freq);
721 if (ret == 0) {
722 fprintf(stderr, "Could not calibrate ticks\n");
723 exit(1);
725 clock_freq = freq.QuadPart;
728 static int64_t get_clock(void)
730 LARGE_INTEGER ti;
731 QueryPerformanceCounter(&ti);
732 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
735 #else
737 static int use_rt_clock;
739 static void init_get_clock(void)
741 use_rt_clock = 0;
742 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
744 struct timespec ts;
745 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
746 use_rt_clock = 1;
749 #endif
752 static int64_t get_clock(void)
754 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
755 if (use_rt_clock) {
756 struct timespec ts;
757 clock_gettime(CLOCK_MONOTONIC, &ts);
758 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
759 } else
760 #endif
762 /* XXX: using gettimeofday leads to problems if the date
763 changes, so it should be avoided. */
764 struct timeval tv;
765 gettimeofday(&tv, NULL);
766 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
769 #endif
771 /* Return the virtual CPU time, based on the instruction counter. */
772 static int64_t cpu_get_icount(void)
774 int64_t icount;
775 CPUState *env = cpu_single_env;;
776 icount = qemu_icount;
777 if (env) {
778 if (!can_do_io(env))
779 fprintf(stderr, "Bad clock read\n");
780 icount -= (env->icount_decr.u16.low + env->icount_extra);
782 return qemu_icount_bias + (icount << icount_time_shift);
785 /***********************************************************/
786 /* guest cycle counter */
788 static int64_t cpu_ticks_prev;
789 static int64_t cpu_ticks_offset;
790 static int64_t cpu_clock_offset;
791 static int cpu_ticks_enabled;
793 /* return the host CPU cycle counter and handle stop/restart */
794 int64_t cpu_get_ticks(void)
796 if (use_icount) {
797 return cpu_get_icount();
799 if (!cpu_ticks_enabled) {
800 return cpu_ticks_offset;
801 } else {
802 int64_t ticks;
803 ticks = cpu_get_real_ticks();
804 if (cpu_ticks_prev > ticks) {
805 /* Note: non increasing ticks may happen if the host uses
806 software suspend */
807 cpu_ticks_offset += cpu_ticks_prev - ticks;
809 cpu_ticks_prev = ticks;
810 return ticks + cpu_ticks_offset;
814 /* return the host CPU monotonic timer and handle stop/restart */
815 static int64_t cpu_get_clock(void)
817 int64_t ti;
818 if (!cpu_ticks_enabled) {
819 return cpu_clock_offset;
820 } else {
821 ti = get_clock();
822 return ti + cpu_clock_offset;
826 /* enable cpu_get_ticks() */
827 void cpu_enable_ticks(void)
829 if (!cpu_ticks_enabled) {
830 cpu_ticks_offset -= cpu_get_real_ticks();
831 cpu_clock_offset -= get_clock();
832 cpu_ticks_enabled = 1;
836 /* disable cpu_get_ticks() : the clock is stopped. You must not call
837 cpu_get_ticks() after that. */
838 void cpu_disable_ticks(void)
840 if (cpu_ticks_enabled) {
841 cpu_ticks_offset = cpu_get_ticks();
842 cpu_clock_offset = cpu_get_clock();
843 cpu_ticks_enabled = 0;
847 /***********************************************************/
848 /* timers */
850 #define QEMU_TIMER_REALTIME 0
851 #define QEMU_TIMER_VIRTUAL 1
853 struct QEMUClock {
854 int type;
855 /* XXX: add frequency */
858 struct QEMUTimer {
859 QEMUClock *clock;
860 int64_t expire_time;
861 QEMUTimerCB *cb;
862 void *opaque;
863 struct QEMUTimer *next;
866 struct qemu_alarm_timer {
867 char const *name;
868 unsigned int flags;
870 int (*start)(struct qemu_alarm_timer *t);
871 void (*stop)(struct qemu_alarm_timer *t);
872 void (*rearm)(struct qemu_alarm_timer *t);
873 void *priv;
876 #define ALARM_FLAG_DYNTICKS 0x1
877 #define ALARM_FLAG_EXPIRED 0x2
879 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
881 return t->flags & ALARM_FLAG_DYNTICKS;
884 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
886 if (!alarm_has_dynticks(t))
887 return;
889 t->rearm(t);
892 /* TODO: MIN_TIMER_REARM_US should be optimized */
893 #define MIN_TIMER_REARM_US 250
895 static struct qemu_alarm_timer *alarm_timer;
896 #ifndef _WIN32
897 static int alarm_timer_rfd, alarm_timer_wfd;
898 #endif
900 #ifdef _WIN32
902 struct qemu_alarm_win32 {
903 MMRESULT timerId;
904 HANDLE host_alarm;
905 unsigned int period;
906 } alarm_win32_data = {0, NULL, -1};
908 static int win32_start_timer(struct qemu_alarm_timer *t);
909 static void win32_stop_timer(struct qemu_alarm_timer *t);
910 static void win32_rearm_timer(struct qemu_alarm_timer *t);
912 #else
914 static int unix_start_timer(struct qemu_alarm_timer *t);
915 static void unix_stop_timer(struct qemu_alarm_timer *t);
917 #ifdef __linux__
919 static int dynticks_start_timer(struct qemu_alarm_timer *t);
920 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
921 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
923 static int hpet_start_timer(struct qemu_alarm_timer *t);
924 static void hpet_stop_timer(struct qemu_alarm_timer *t);
926 static int rtc_start_timer(struct qemu_alarm_timer *t);
927 static void rtc_stop_timer(struct qemu_alarm_timer *t);
929 #endif /* __linux__ */
931 #endif /* _WIN32 */
933 /* Correlation between real and virtual time is always going to be
934 fairly approximate, so ignore small variation.
935 When the guest is idle real and virtual time will be aligned in
936 the IO wait loop. */
937 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
939 static void icount_adjust(void)
941 int64_t cur_time;
942 int64_t cur_icount;
943 int64_t delta;
944 static int64_t last_delta;
945 /* If the VM is not running, then do nothing. */
946 if (!vm_running)
947 return;
949 cur_time = cpu_get_clock();
950 cur_icount = qemu_get_clock(vm_clock);
951 delta = cur_icount - cur_time;
952 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
953 if (delta > 0
954 && last_delta + ICOUNT_WOBBLE < delta * 2
955 && icount_time_shift > 0) {
956 /* The guest is getting too far ahead. Slow time down. */
957 icount_time_shift--;
959 if (delta < 0
960 && last_delta - ICOUNT_WOBBLE > delta * 2
961 && icount_time_shift < MAX_ICOUNT_SHIFT) {
962 /* The guest is getting too far behind. Speed time up. */
963 icount_time_shift++;
965 last_delta = delta;
966 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
969 static void icount_adjust_rt(void * opaque)
971 qemu_mod_timer(icount_rt_timer,
972 qemu_get_clock(rt_clock) + 1000);
973 icount_adjust();
976 static void icount_adjust_vm(void * opaque)
978 qemu_mod_timer(icount_vm_timer,
979 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
980 icount_adjust();
983 static void init_icount_adjust(void)
985 /* Have both realtime and virtual time triggers for speed adjustment.
986 The realtime trigger catches emulated time passing too slowly,
987 the virtual time trigger catches emulated time passing too fast.
988 Realtime triggers occur even when idle, so use them less frequently
989 than VM triggers. */
990 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
991 qemu_mod_timer(icount_rt_timer,
992 qemu_get_clock(rt_clock) + 1000);
993 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
994 qemu_mod_timer(icount_vm_timer,
995 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
998 static struct qemu_alarm_timer alarm_timers[] = {
999 #ifndef _WIN32
1000 #ifdef __linux__
1001 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1002 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1003 /* HPET - if available - is preferred */
1004 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1005 /* ...otherwise try RTC */
1006 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1007 #endif
1008 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1009 #else
1010 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1011 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1012 {"win32", 0, win32_start_timer,
1013 win32_stop_timer, NULL, &alarm_win32_data},
1014 #endif
1015 {NULL, }
1018 static void show_available_alarms(void)
1020 int i;
1022 printf("Available alarm timers, in order of precedence:\n");
1023 for (i = 0; alarm_timers[i].name; i++)
1024 printf("%s\n", alarm_timers[i].name);
1027 static void configure_alarms(char const *opt)
1029 int i;
1030 int cur = 0;
1031 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1032 char *arg;
1033 char *name;
1034 struct qemu_alarm_timer tmp;
1036 if (!strcmp(opt, "?")) {
1037 show_available_alarms();
1038 exit(0);
1041 arg = strdup(opt);
1043 /* Reorder the array */
1044 name = strtok(arg, ",");
1045 while (name) {
1046 for (i = 0; i < count && alarm_timers[i].name; i++) {
1047 if (!strcmp(alarm_timers[i].name, name))
1048 break;
1051 if (i == count) {
1052 fprintf(stderr, "Unknown clock %s\n", name);
1053 goto next;
1056 if (i < cur)
1057 /* Ignore */
1058 goto next;
1060 /* Swap */
1061 tmp = alarm_timers[i];
1062 alarm_timers[i] = alarm_timers[cur];
1063 alarm_timers[cur] = tmp;
1065 cur++;
1066 next:
1067 name = strtok(NULL, ",");
1070 free(arg);
1072 if (cur) {
1073 /* Disable remaining timers */
1074 for (i = cur; i < count; i++)
1075 alarm_timers[i].name = NULL;
1076 } else {
1077 show_available_alarms();
1078 exit(1);
1082 QEMUClock *rt_clock;
1083 QEMUClock *vm_clock;
1085 static QEMUTimer *active_timers[2];
1087 static QEMUClock *qemu_new_clock(int type)
1089 QEMUClock *clock;
1090 clock = qemu_mallocz(sizeof(QEMUClock));
1091 if (!clock)
1092 return NULL;
1093 clock->type = type;
1094 return clock;
1097 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1099 QEMUTimer *ts;
1101 ts = qemu_mallocz(sizeof(QEMUTimer));
1102 ts->clock = clock;
1103 ts->cb = cb;
1104 ts->opaque = opaque;
1105 return ts;
1108 void qemu_free_timer(QEMUTimer *ts)
1110 qemu_free(ts);
1113 /* stop a timer, but do not dealloc it */
1114 void qemu_del_timer(QEMUTimer *ts)
1116 QEMUTimer **pt, *t;
1118 /* NOTE: this code must be signal safe because
1119 qemu_timer_expired() can be called from a signal. */
1120 pt = &active_timers[ts->clock->type];
1121 for(;;) {
1122 t = *pt;
1123 if (!t)
1124 break;
1125 if (t == ts) {
1126 *pt = t->next;
1127 break;
1129 pt = &t->next;
1133 /* modify the current timer so that it will be fired when current_time
1134 >= expire_time. The corresponding callback will be called. */
1135 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1137 QEMUTimer **pt, *t;
1139 qemu_del_timer(ts);
1141 /* add the timer in the sorted list */
1142 /* NOTE: this code must be signal safe because
1143 qemu_timer_expired() can be called from a signal. */
1144 pt = &active_timers[ts->clock->type];
1145 for(;;) {
1146 t = *pt;
1147 if (!t)
1148 break;
1149 if (t->expire_time > expire_time)
1150 break;
1151 pt = &t->next;
1153 ts->expire_time = expire_time;
1154 ts->next = *pt;
1155 *pt = ts;
1157 /* Rearm if necessary */
1158 if (pt == &active_timers[ts->clock->type]) {
1159 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1160 qemu_rearm_alarm_timer(alarm_timer);
1162 /* Interrupt execution to force deadline recalculation. */
1163 if (use_icount && cpu_single_env) {
1164 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1169 int qemu_timer_pending(QEMUTimer *ts)
1171 QEMUTimer *t;
1172 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1173 if (t == ts)
1174 return 1;
1176 return 0;
1179 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1181 if (!timer_head)
1182 return 0;
1183 return (timer_head->expire_time <= current_time);
1186 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1188 QEMUTimer *ts;
1190 for(;;) {
1191 ts = *ptimer_head;
1192 if (!ts || ts->expire_time > current_time)
1193 break;
1194 /* remove timer from the list before calling the callback */
1195 *ptimer_head = ts->next;
1196 ts->next = NULL;
1198 /* run the callback (the timer list can be modified) */
1199 ts->cb(ts->opaque);
1203 int64_t qemu_get_clock(QEMUClock *clock)
1205 switch(clock->type) {
1206 case QEMU_TIMER_REALTIME:
1207 return get_clock() / 1000000;
1208 default:
1209 case QEMU_TIMER_VIRTUAL:
1210 if (use_icount) {
1211 return cpu_get_icount();
1212 } else {
1213 return cpu_get_clock();
1218 static void init_timers(void)
1220 init_get_clock();
1221 ticks_per_sec = QEMU_TIMER_BASE;
1222 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1223 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1226 /* save a timer */
1227 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1229 uint64_t expire_time;
1231 if (qemu_timer_pending(ts)) {
1232 expire_time = ts->expire_time;
1233 } else {
1234 expire_time = -1;
1236 qemu_put_be64(f, expire_time);
1239 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1241 uint64_t expire_time;
1243 expire_time = qemu_get_be64(f);
1244 if (expire_time != -1) {
1245 qemu_mod_timer(ts, expire_time);
1246 } else {
1247 qemu_del_timer(ts);
1251 static void timer_save(QEMUFile *f, void *opaque)
1253 if (cpu_ticks_enabled) {
1254 hw_error("cannot save state if virtual timers are running");
1256 qemu_put_be64(f, cpu_ticks_offset);
1257 qemu_put_be64(f, ticks_per_sec);
1258 qemu_put_be64(f, cpu_clock_offset);
1261 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1263 if (version_id != 1 && version_id != 2)
1264 return -EINVAL;
1265 if (cpu_ticks_enabled) {
1266 return -EINVAL;
1268 cpu_ticks_offset=qemu_get_be64(f);
1269 ticks_per_sec=qemu_get_be64(f);
1270 if (version_id == 2) {
1271 cpu_clock_offset=qemu_get_be64(f);
1273 return 0;
1276 #ifdef _WIN32
1277 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1278 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1279 #else
1280 static void host_alarm_handler(int host_signum)
1281 #endif
1283 #if 0
1284 #define DISP_FREQ 1000
1286 static int64_t delta_min = INT64_MAX;
1287 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1288 static int count;
1289 ti = qemu_get_clock(vm_clock);
1290 if (last_clock != 0) {
1291 delta = ti - last_clock;
1292 if (delta < delta_min)
1293 delta_min = delta;
1294 if (delta > delta_max)
1295 delta_max = delta;
1296 delta_cum += delta;
1297 if (++count == DISP_FREQ) {
1298 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1299 muldiv64(delta_min, 1000000, ticks_per_sec),
1300 muldiv64(delta_max, 1000000, ticks_per_sec),
1301 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1302 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1303 count = 0;
1304 delta_min = INT64_MAX;
1305 delta_max = 0;
1306 delta_cum = 0;
1309 last_clock = ti;
1311 #endif
1312 if (alarm_has_dynticks(alarm_timer) ||
1313 (!use_icount &&
1314 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1315 qemu_get_clock(vm_clock))) ||
1316 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1317 qemu_get_clock(rt_clock))) {
1318 CPUState *env = next_cpu;
1320 #ifdef _WIN32
1321 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1322 SetEvent(data->host_alarm);
1323 #else
1324 static const char byte = 0;
1325 write(alarm_timer_wfd, &byte, sizeof(byte));
1326 #endif
1327 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1329 if (env) {
1330 /* stop the currently executing cpu because a timer occured */
1331 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1332 #ifdef USE_KQEMU
1333 if (env->kqemu_enabled) {
1334 kqemu_cpu_interrupt(env);
1336 #endif
1338 event_pending = 1;
1342 static int64_t qemu_next_deadline(void)
1344 int64_t delta;
1346 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1347 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1348 qemu_get_clock(vm_clock);
1349 } else {
1350 /* To avoid problems with overflow limit this to 2^32. */
1351 delta = INT32_MAX;
1354 if (delta < 0)
1355 delta = 0;
1357 return delta;
1360 #if defined(__linux__) || defined(_WIN32)
1361 static uint64_t qemu_next_deadline_dyntick(void)
1363 int64_t delta;
1364 int64_t rtdelta;
1366 if (use_icount)
1367 delta = INT32_MAX;
1368 else
1369 delta = (qemu_next_deadline() + 999) / 1000;
1371 if (active_timers[QEMU_TIMER_REALTIME]) {
1372 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1373 qemu_get_clock(rt_clock))*1000;
1374 if (rtdelta < delta)
1375 delta = rtdelta;
1378 if (delta < MIN_TIMER_REARM_US)
1379 delta = MIN_TIMER_REARM_US;
1381 return delta;
1383 #endif
1385 #ifndef _WIN32
1387 /* Sets a specific flag */
1388 static int fcntl_setfl(int fd, int flag)
1390 int flags;
1392 flags = fcntl(fd, F_GETFL);
1393 if (flags == -1)
1394 return -errno;
1396 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1397 return -errno;
1399 return 0;
1402 #if defined(__linux__)
1404 #define RTC_FREQ 1024
1406 static void enable_sigio_timer(int fd)
1408 struct sigaction act;
1410 /* timer signal */
1411 sigfillset(&act.sa_mask);
1412 act.sa_flags = 0;
1413 act.sa_handler = host_alarm_handler;
1415 sigaction(SIGIO, &act, NULL);
1416 fcntl_setfl(fd, O_ASYNC);
1417 fcntl(fd, F_SETOWN, getpid());
1420 static int hpet_start_timer(struct qemu_alarm_timer *t)
1422 struct hpet_info info;
1423 int r, fd;
1425 fd = open("/dev/hpet", O_RDONLY);
1426 if (fd < 0)
1427 return -1;
1429 /* Set frequency */
1430 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1431 if (r < 0) {
1432 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1433 "error, but for better emulation accuracy type:\n"
1434 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1435 goto fail;
1438 /* Check capabilities */
1439 r = ioctl(fd, HPET_INFO, &info);
1440 if (r < 0)
1441 goto fail;
1443 /* Enable periodic mode */
1444 r = ioctl(fd, HPET_EPI, 0);
1445 if (info.hi_flags && (r < 0))
1446 goto fail;
1448 /* Enable interrupt */
1449 r = ioctl(fd, HPET_IE_ON, 0);
1450 if (r < 0)
1451 goto fail;
1453 enable_sigio_timer(fd);
1454 t->priv = (void *)(long)fd;
1456 return 0;
1457 fail:
1458 close(fd);
1459 return -1;
1462 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1464 int fd = (long)t->priv;
1466 close(fd);
1469 static int rtc_start_timer(struct qemu_alarm_timer *t)
1471 int rtc_fd;
1472 unsigned long current_rtc_freq = 0;
1474 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1475 if (rtc_fd < 0)
1476 return -1;
1477 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1478 if (current_rtc_freq != RTC_FREQ &&
1479 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1480 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1481 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1482 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1483 goto fail;
1485 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1486 fail:
1487 close(rtc_fd);
1488 return -1;
1491 enable_sigio_timer(rtc_fd);
1493 t->priv = (void *)(long)rtc_fd;
1495 return 0;
1498 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1500 int rtc_fd = (long)t->priv;
1502 close(rtc_fd);
1505 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1507 struct sigevent ev;
1508 timer_t host_timer;
1509 struct sigaction act;
1511 sigfillset(&act.sa_mask);
1512 act.sa_flags = 0;
1513 act.sa_handler = host_alarm_handler;
1515 sigaction(SIGALRM, &act, NULL);
1517 ev.sigev_value.sival_int = 0;
1518 ev.sigev_notify = SIGEV_SIGNAL;
1519 ev.sigev_signo = SIGALRM;
1521 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1522 perror("timer_create");
1524 /* disable dynticks */
1525 fprintf(stderr, "Dynamic Ticks disabled\n");
1527 return -1;
1530 t->priv = (void *)(long)host_timer;
1532 return 0;
1535 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1537 timer_t host_timer = (timer_t)(long)t->priv;
1539 timer_delete(host_timer);
1542 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1544 timer_t host_timer = (timer_t)(long)t->priv;
1545 struct itimerspec timeout;
1546 int64_t nearest_delta_us = INT64_MAX;
1547 int64_t current_us;
1549 if (!active_timers[QEMU_TIMER_REALTIME] &&
1550 !active_timers[QEMU_TIMER_VIRTUAL])
1551 return;
1553 nearest_delta_us = qemu_next_deadline_dyntick();
1555 /* check whether a timer is already running */
1556 if (timer_gettime(host_timer, &timeout)) {
1557 perror("gettime");
1558 fprintf(stderr, "Internal timer error: aborting\n");
1559 exit(1);
1561 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1562 if (current_us && current_us <= nearest_delta_us)
1563 return;
1565 timeout.it_interval.tv_sec = 0;
1566 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1567 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1568 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1569 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1570 perror("settime");
1571 fprintf(stderr, "Internal timer error: aborting\n");
1572 exit(1);
1576 #endif /* defined(__linux__) */
1578 static int unix_start_timer(struct qemu_alarm_timer *t)
1580 struct sigaction act;
1581 struct itimerval itv;
1582 int err;
1584 /* timer signal */
1585 sigfillset(&act.sa_mask);
1586 act.sa_flags = 0;
1587 act.sa_handler = host_alarm_handler;
1589 sigaction(SIGALRM, &act, NULL);
1591 itv.it_interval.tv_sec = 0;
1592 /* for i386 kernel 2.6 to get 1 ms */
1593 itv.it_interval.tv_usec = 999;
1594 itv.it_value.tv_sec = 0;
1595 itv.it_value.tv_usec = 10 * 1000;
1597 err = setitimer(ITIMER_REAL, &itv, NULL);
1598 if (err)
1599 return -1;
1601 return 0;
1604 static void unix_stop_timer(struct qemu_alarm_timer *t)
1606 struct itimerval itv;
1608 memset(&itv, 0, sizeof(itv));
1609 setitimer(ITIMER_REAL, &itv, NULL);
1612 #endif /* !defined(_WIN32) */
1614 static void try_to_rearm_timer(void *opaque)
1616 struct qemu_alarm_timer *t = opaque;
1617 #ifndef _WIN32
1618 ssize_t len;
1620 /* Drain the notify pipe */
1621 do {
1622 char buffer[512];
1623 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1624 } while ((len == -1 && errno == EINTR) || len > 0);
1625 #endif
1627 if (t->flags & ALARM_FLAG_EXPIRED) {
1628 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1629 qemu_rearm_alarm_timer(alarm_timer);
1633 #ifdef _WIN32
1635 static int win32_start_timer(struct qemu_alarm_timer *t)
1637 TIMECAPS tc;
1638 struct qemu_alarm_win32 *data = t->priv;
1639 UINT flags;
1641 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1642 if (!data->host_alarm) {
1643 perror("Failed CreateEvent");
1644 return -1;
1647 memset(&tc, 0, sizeof(tc));
1648 timeGetDevCaps(&tc, sizeof(tc));
1650 if (data->period < tc.wPeriodMin)
1651 data->period = tc.wPeriodMin;
1653 timeBeginPeriod(data->period);
1655 flags = TIME_CALLBACK_FUNCTION;
1656 if (alarm_has_dynticks(t))
1657 flags |= TIME_ONESHOT;
1658 else
1659 flags |= TIME_PERIODIC;
1661 data->timerId = timeSetEvent(1, // interval (ms)
1662 data->period, // resolution
1663 host_alarm_handler, // function
1664 (DWORD)t, // parameter
1665 flags);
1667 if (!data->timerId) {
1668 perror("Failed to initialize win32 alarm timer");
1670 timeEndPeriod(data->period);
1671 CloseHandle(data->host_alarm);
1672 return -1;
1675 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1677 return 0;
1680 static void win32_stop_timer(struct qemu_alarm_timer *t)
1682 struct qemu_alarm_win32 *data = t->priv;
1684 timeKillEvent(data->timerId);
1685 timeEndPeriod(data->period);
1687 CloseHandle(data->host_alarm);
1690 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1692 struct qemu_alarm_win32 *data = t->priv;
1693 uint64_t nearest_delta_us;
1695 if (!active_timers[QEMU_TIMER_REALTIME] &&
1696 !active_timers[QEMU_TIMER_VIRTUAL])
1697 return;
1699 nearest_delta_us = qemu_next_deadline_dyntick();
1700 nearest_delta_us /= 1000;
1702 timeKillEvent(data->timerId);
1704 data->timerId = timeSetEvent(1,
1705 data->period,
1706 host_alarm_handler,
1707 (DWORD)t,
1708 TIME_ONESHOT | TIME_PERIODIC);
1710 if (!data->timerId) {
1711 perror("Failed to re-arm win32 alarm timer");
1713 timeEndPeriod(data->period);
1714 CloseHandle(data->host_alarm);
1715 exit(1);
1719 #endif /* _WIN32 */
1721 static int init_timer_alarm(void)
1723 struct qemu_alarm_timer *t = NULL;
1724 int i, err = -1;
1726 #ifndef _WIN32
1727 int fds[2];
1729 err = pipe(fds);
1730 if (err == -1)
1731 return -errno;
1733 err = fcntl_setfl(fds[0], O_NONBLOCK);
1734 if (err < 0)
1735 goto fail;
1737 err = fcntl_setfl(fds[1], O_NONBLOCK);
1738 if (err < 0)
1739 goto fail;
1741 alarm_timer_rfd = fds[0];
1742 alarm_timer_wfd = fds[1];
1743 #endif
1745 for (i = 0; alarm_timers[i].name; i++) {
1746 t = &alarm_timers[i];
1748 err = t->start(t);
1749 if (!err)
1750 break;
1753 if (err) {
1754 err = -ENOENT;
1755 goto fail;
1758 #ifndef _WIN32
1759 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1760 try_to_rearm_timer, NULL, t);
1761 #endif
1763 alarm_timer = t;
1765 return 0;
1767 fail:
1768 #ifndef _WIN32
1769 close(fds[0]);
1770 close(fds[1]);
1771 #endif
1772 return err;
1775 static void quit_timers(void)
1777 alarm_timer->stop(alarm_timer);
1778 alarm_timer = NULL;
1781 /***********************************************************/
1782 /* host time/date access */
1783 void qemu_get_timedate(struct tm *tm, int offset)
1785 time_t ti;
1786 struct tm *ret;
1788 time(&ti);
1789 ti += offset;
1790 if (rtc_date_offset == -1) {
1791 if (rtc_utc)
1792 ret = gmtime(&ti);
1793 else
1794 ret = localtime(&ti);
1795 } else {
1796 ti -= rtc_date_offset;
1797 ret = gmtime(&ti);
1800 memcpy(tm, ret, sizeof(struct tm));
1803 int qemu_timedate_diff(struct tm *tm)
1805 time_t seconds;
1807 if (rtc_date_offset == -1)
1808 if (rtc_utc)
1809 seconds = mktimegm(tm);
1810 else
1811 seconds = mktime(tm);
1812 else
1813 seconds = mktimegm(tm) + rtc_date_offset;
1815 return seconds - time(NULL);
1818 #ifdef _WIN32
1819 static void socket_cleanup(void)
1821 WSACleanup();
1824 static int socket_init(void)
1826 WSADATA Data;
1827 int ret, err;
1829 ret = WSAStartup(MAKEWORD(2,2), &Data);
1830 if (ret != 0) {
1831 err = WSAGetLastError();
1832 fprintf(stderr, "WSAStartup: %d\n", err);
1833 return -1;
1835 atexit(socket_cleanup);
1836 return 0;
1838 #endif
1840 const char *get_opt_name(char *buf, int buf_size, const char *p)
1842 char *q;
1844 q = buf;
1845 while (*p != '\0' && *p != '=') {
1846 if (q && (q - buf) < buf_size - 1)
1847 *q++ = *p;
1848 p++;
1850 if (q)
1851 *q = '\0';
1853 return p;
1856 const char *get_opt_value(char *buf, int buf_size, const char *p)
1858 char *q;
1860 q = buf;
1861 while (*p != '\0') {
1862 if (*p == ',') {
1863 if (*(p + 1) != ',')
1864 break;
1865 p++;
1867 if (q && (q - buf) < buf_size - 1)
1868 *q++ = *p;
1869 p++;
1871 if (q)
1872 *q = '\0';
1874 return p;
1877 int get_param_value(char *buf, int buf_size,
1878 const char *tag, const char *str)
1880 const char *p;
1881 char option[128];
1883 p = str;
1884 for(;;) {
1885 p = get_opt_name(option, sizeof(option), p);
1886 if (*p != '=')
1887 break;
1888 p++;
1889 if (!strcmp(tag, option)) {
1890 (void)get_opt_value(buf, buf_size, p);
1891 return strlen(buf);
1892 } else {
1893 p = get_opt_value(NULL, 0, p);
1895 if (*p != ',')
1896 break;
1897 p++;
1899 return 0;
1902 int check_params(char *buf, int buf_size,
1903 const char * const *params, const char *str)
1905 const char *p;
1906 int i;
1908 p = str;
1909 for(;;) {
1910 p = get_opt_name(buf, buf_size, p);
1911 if (*p != '=')
1912 return -1;
1913 p++;
1914 for(i = 0; params[i] != NULL; i++)
1915 if (!strcmp(params[i], buf))
1916 break;
1917 if (params[i] == NULL)
1918 return -1;
1919 p = get_opt_value(NULL, 0, p);
1920 if (*p != ',')
1921 break;
1922 p++;
1924 return 0;
1927 /***********************************************************/
1928 /* Bluetooth support */
1929 static int nb_hcis;
1930 static int cur_hci;
1931 static struct HCIInfo *hci_table[MAX_NICS];
1933 static struct bt_vlan_s {
1934 struct bt_scatternet_s net;
1935 int id;
1936 struct bt_vlan_s *next;
1937 } *first_bt_vlan;
1939 /* find or alloc a new bluetooth "VLAN" */
1940 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1942 struct bt_vlan_s **pvlan, *vlan;
1943 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1944 if (vlan->id == id)
1945 return &vlan->net;
1947 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1948 vlan->id = id;
1949 pvlan = &first_bt_vlan;
1950 while (*pvlan != NULL)
1951 pvlan = &(*pvlan)->next;
1952 *pvlan = vlan;
1953 return &vlan->net;
1956 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1960 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1962 return -ENOTSUP;
1965 static struct HCIInfo null_hci = {
1966 .cmd_send = null_hci_send,
1967 .sco_send = null_hci_send,
1968 .acl_send = null_hci_send,
1969 .bdaddr_set = null_hci_addr_set,
1972 struct HCIInfo *qemu_next_hci(void)
1974 if (cur_hci == nb_hcis)
1975 return &null_hci;
1977 return hci_table[cur_hci++];
1980 static struct HCIInfo *hci_init(const char *str)
1982 char *endp;
1983 struct bt_scatternet_s *vlan = 0;
1985 if (!strcmp(str, "null"))
1986 /* null */
1987 return &null_hci;
1988 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1989 /* host[:hciN] */
1990 return bt_host_hci(str[4] ? str + 5 : "hci0");
1991 else if (!strncmp(str, "hci", 3)) {
1992 /* hci[,vlan=n] */
1993 if (str[3]) {
1994 if (!strncmp(str + 3, ",vlan=", 6)) {
1995 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1996 if (*endp)
1997 vlan = 0;
1999 } else
2000 vlan = qemu_find_bt_vlan(0);
2001 if (vlan)
2002 return bt_new_hci(vlan);
2005 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2007 return 0;
2010 static int bt_hci_parse(const char *str)
2012 struct HCIInfo *hci;
2013 bdaddr_t bdaddr;
2015 if (nb_hcis >= MAX_NICS) {
2016 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2017 return -1;
2020 hci = hci_init(str);
2021 if (!hci)
2022 return -1;
2024 bdaddr.b[0] = 0x52;
2025 bdaddr.b[1] = 0x54;
2026 bdaddr.b[2] = 0x00;
2027 bdaddr.b[3] = 0x12;
2028 bdaddr.b[4] = 0x34;
2029 bdaddr.b[5] = 0x56 + nb_hcis;
2030 hci->bdaddr_set(hci, bdaddr.b);
2032 hci_table[nb_hcis++] = hci;
2034 return 0;
2037 static void bt_vhci_add(int vlan_id)
2039 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2041 if (!vlan->slave)
2042 fprintf(stderr, "qemu: warning: adding a VHCI to "
2043 "an empty scatternet %i\n", vlan_id);
2045 bt_vhci_init(bt_new_hci(vlan));
2048 static struct bt_device_s *bt_device_add(const char *opt)
2050 struct bt_scatternet_s *vlan;
2051 int vlan_id = 0;
2052 char *endp = strstr(opt, ",vlan=");
2053 int len = (endp ? endp - opt : strlen(opt)) + 1;
2054 char devname[10];
2056 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2058 if (endp) {
2059 vlan_id = strtol(endp + 6, &endp, 0);
2060 if (*endp) {
2061 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2062 return 0;
2066 vlan = qemu_find_bt_vlan(vlan_id);
2068 if (!vlan->slave)
2069 fprintf(stderr, "qemu: warning: adding a slave device to "
2070 "an empty scatternet %i\n", vlan_id);
2072 if (!strcmp(devname, "keyboard"))
2073 return bt_keyboard_init(vlan);
2075 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2076 return 0;
2079 static int bt_parse(const char *opt)
2081 const char *endp, *p;
2082 int vlan;
2084 if (strstart(opt, "hci", &endp)) {
2085 if (!*endp || *endp == ',') {
2086 if (*endp)
2087 if (!strstart(endp, ",vlan=", 0))
2088 opt = endp + 1;
2090 return bt_hci_parse(opt);
2092 } else if (strstart(opt, "vhci", &endp)) {
2093 if (!*endp || *endp == ',') {
2094 if (*endp) {
2095 if (strstart(endp, ",vlan=", &p)) {
2096 vlan = strtol(p, (char **) &endp, 0);
2097 if (*endp) {
2098 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2099 return 1;
2101 } else {
2102 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2103 return 1;
2105 } else
2106 vlan = 0;
2108 bt_vhci_add(vlan);
2109 return 0;
2111 } else if (strstart(opt, "device:", &endp))
2112 return !bt_device_add(endp);
2114 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2115 return 1;
2118 /***********************************************************/
2119 /* QEMU Block devices */
2121 #define HD_ALIAS "index=%d,media=disk"
2122 #ifdef TARGET_PPC
2123 #define CDROM_ALIAS "index=1,media=cdrom"
2124 #else
2125 #define CDROM_ALIAS "index=2,media=cdrom"
2126 #endif
2127 #define FD_ALIAS "index=%d,if=floppy"
2128 #define PFLASH_ALIAS "if=pflash"
2129 #define MTD_ALIAS "if=mtd"
2130 #define SD_ALIAS "index=0,if=sd"
2132 static int drive_add(const char *file, const char *fmt, ...)
2134 va_list ap;
2136 if (nb_drives_opt >= MAX_DRIVES) {
2137 fprintf(stderr, "qemu: too many drives\n");
2138 exit(1);
2141 drives_opt[nb_drives_opt].file = file;
2142 va_start(ap, fmt);
2143 vsnprintf(drives_opt[nb_drives_opt].opt,
2144 sizeof(drives_opt[0].opt), fmt, ap);
2145 va_end(ap);
2147 return nb_drives_opt++;
2150 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2152 int index;
2154 /* seek interface, bus and unit */
2156 for (index = 0; index < nb_drives; index++)
2157 if (drives_table[index].type == type &&
2158 drives_table[index].bus == bus &&
2159 drives_table[index].unit == unit)
2160 return index;
2162 return -1;
2165 int drive_get_max_bus(BlockInterfaceType type)
2167 int max_bus;
2168 int index;
2170 max_bus = -1;
2171 for (index = 0; index < nb_drives; index++) {
2172 if(drives_table[index].type == type &&
2173 drives_table[index].bus > max_bus)
2174 max_bus = drives_table[index].bus;
2176 return max_bus;
2179 static void bdrv_format_print(void *opaque, const char *name)
2181 fprintf(stderr, " %s", name);
2184 static int drive_init(struct drive_opt *arg, int snapshot,
2185 QEMUMachine *machine)
2187 char buf[128];
2188 char file[1024];
2189 char devname[128];
2190 const char *mediastr = "";
2191 BlockInterfaceType type;
2192 enum { MEDIA_DISK, MEDIA_CDROM } media;
2193 int bus_id, unit_id;
2194 int cyls, heads, secs, translation;
2195 BlockDriverState *bdrv;
2196 BlockDriver *drv = NULL;
2197 int max_devs;
2198 int index;
2199 int cache;
2200 int bdrv_flags;
2201 char *str = arg->opt;
2202 static const char * const params[] = { "bus", "unit", "if", "index",
2203 "cyls", "heads", "secs", "trans",
2204 "media", "snapshot", "file",
2205 "cache", "format", NULL };
2207 if (check_params(buf, sizeof(buf), params, str) < 0) {
2208 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2209 buf, str);
2210 return -1;
2213 file[0] = 0;
2214 cyls = heads = secs = 0;
2215 bus_id = 0;
2216 unit_id = -1;
2217 translation = BIOS_ATA_TRANSLATION_AUTO;
2218 index = -1;
2219 cache = 1;
2221 if (machine->use_scsi) {
2222 type = IF_SCSI;
2223 max_devs = MAX_SCSI_DEVS;
2224 pstrcpy(devname, sizeof(devname), "scsi");
2225 } else {
2226 type = IF_IDE;
2227 max_devs = MAX_IDE_DEVS;
2228 pstrcpy(devname, sizeof(devname), "ide");
2230 media = MEDIA_DISK;
2232 /* extract parameters */
2234 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2235 bus_id = strtol(buf, NULL, 0);
2236 if (bus_id < 0) {
2237 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2238 return -1;
2242 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2243 unit_id = strtol(buf, NULL, 0);
2244 if (unit_id < 0) {
2245 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2246 return -1;
2250 if (get_param_value(buf, sizeof(buf), "if", str)) {
2251 pstrcpy(devname, sizeof(devname), buf);
2252 if (!strcmp(buf, "ide")) {
2253 type = IF_IDE;
2254 max_devs = MAX_IDE_DEVS;
2255 } else if (!strcmp(buf, "scsi")) {
2256 type = IF_SCSI;
2257 max_devs = MAX_SCSI_DEVS;
2258 } else if (!strcmp(buf, "floppy")) {
2259 type = IF_FLOPPY;
2260 max_devs = 0;
2261 } else if (!strcmp(buf, "pflash")) {
2262 type = IF_PFLASH;
2263 max_devs = 0;
2264 } else if (!strcmp(buf, "mtd")) {
2265 type = IF_MTD;
2266 max_devs = 0;
2267 } else if (!strcmp(buf, "sd")) {
2268 type = IF_SD;
2269 max_devs = 0;
2270 } else {
2271 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2272 return -1;
2276 if (get_param_value(buf, sizeof(buf), "index", str)) {
2277 index = strtol(buf, NULL, 0);
2278 if (index < 0) {
2279 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2280 return -1;
2284 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2285 cyls = strtol(buf, NULL, 0);
2288 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2289 heads = strtol(buf, NULL, 0);
2292 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2293 secs = strtol(buf, NULL, 0);
2296 if (cyls || heads || secs) {
2297 if (cyls < 1 || cyls > 16383) {
2298 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2299 return -1;
2301 if (heads < 1 || heads > 16) {
2302 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2303 return -1;
2305 if (secs < 1 || secs > 63) {
2306 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2307 return -1;
2311 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2312 if (!cyls) {
2313 fprintf(stderr,
2314 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2315 str);
2316 return -1;
2318 if (!strcmp(buf, "none"))
2319 translation = BIOS_ATA_TRANSLATION_NONE;
2320 else if (!strcmp(buf, "lba"))
2321 translation = BIOS_ATA_TRANSLATION_LBA;
2322 else if (!strcmp(buf, "auto"))
2323 translation = BIOS_ATA_TRANSLATION_AUTO;
2324 else {
2325 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2326 return -1;
2330 if (get_param_value(buf, sizeof(buf), "media", str)) {
2331 if (!strcmp(buf, "disk")) {
2332 media = MEDIA_DISK;
2333 } else if (!strcmp(buf, "cdrom")) {
2334 if (cyls || secs || heads) {
2335 fprintf(stderr,
2336 "qemu: '%s' invalid physical CHS format\n", str);
2337 return -1;
2339 media = MEDIA_CDROM;
2340 } else {
2341 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2342 return -1;
2346 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2347 if (!strcmp(buf, "on"))
2348 snapshot = 1;
2349 else if (!strcmp(buf, "off"))
2350 snapshot = 0;
2351 else {
2352 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2353 return -1;
2357 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2358 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2359 cache = 0;
2360 else if (!strcmp(buf, "writethrough"))
2361 cache = 1;
2362 else if (!strcmp(buf, "writeback"))
2363 cache = 2;
2364 else {
2365 fprintf(stderr, "qemu: invalid cache option\n");
2366 return -1;
2370 if (get_param_value(buf, sizeof(buf), "format", str)) {
2371 if (strcmp(buf, "?") == 0) {
2372 fprintf(stderr, "qemu: Supported formats:");
2373 bdrv_iterate_format(bdrv_format_print, NULL);
2374 fprintf(stderr, "\n");
2375 return -1;
2377 drv = bdrv_find_format(buf);
2378 if (!drv) {
2379 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2380 return -1;
2384 if (arg->file == NULL)
2385 get_param_value(file, sizeof(file), "file", str);
2386 else
2387 pstrcpy(file, sizeof(file), arg->file);
2389 /* compute bus and unit according index */
2391 if (index != -1) {
2392 if (bus_id != 0 || unit_id != -1) {
2393 fprintf(stderr,
2394 "qemu: '%s' index cannot be used with bus and unit\n", str);
2395 return -1;
2397 if (max_devs == 0)
2399 unit_id = index;
2400 bus_id = 0;
2401 } else {
2402 unit_id = index % max_devs;
2403 bus_id = index / max_devs;
2407 /* if user doesn't specify a unit_id,
2408 * try to find the first free
2411 if (unit_id == -1) {
2412 unit_id = 0;
2413 while (drive_get_index(type, bus_id, unit_id) != -1) {
2414 unit_id++;
2415 if (max_devs && unit_id >= max_devs) {
2416 unit_id -= max_devs;
2417 bus_id++;
2422 /* check unit id */
2424 if (max_devs && unit_id >= max_devs) {
2425 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2426 str, unit_id, max_devs - 1);
2427 return -1;
2431 * ignore multiple definitions
2434 if (drive_get_index(type, bus_id, unit_id) != -1)
2435 return 0;
2437 /* init */
2439 if (type == IF_IDE || type == IF_SCSI)
2440 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2441 if (max_devs)
2442 snprintf(buf, sizeof(buf), "%s%i%s%i",
2443 devname, bus_id, mediastr, unit_id);
2444 else
2445 snprintf(buf, sizeof(buf), "%s%s%i",
2446 devname, mediastr, unit_id);
2447 bdrv = bdrv_new(buf);
2448 drives_table[nb_drives].bdrv = bdrv;
2449 drives_table[nb_drives].type = type;
2450 drives_table[nb_drives].bus = bus_id;
2451 drives_table[nb_drives].unit = unit_id;
2452 nb_drives++;
2454 switch(type) {
2455 case IF_IDE:
2456 case IF_SCSI:
2457 switch(media) {
2458 case MEDIA_DISK:
2459 if (cyls != 0) {
2460 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2461 bdrv_set_translation_hint(bdrv, translation);
2463 break;
2464 case MEDIA_CDROM:
2465 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2466 break;
2468 break;
2469 case IF_SD:
2470 /* FIXME: This isn't really a floppy, but it's a reasonable
2471 approximation. */
2472 case IF_FLOPPY:
2473 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2474 break;
2475 case IF_PFLASH:
2476 case IF_MTD:
2477 break;
2479 if (!file[0])
2480 return 0;
2481 bdrv_flags = 0;
2482 if (snapshot) {
2483 bdrv_flags |= BDRV_O_SNAPSHOT;
2484 cache = 2; /* always use write-back with snapshot */
2486 if (cache == 0) /* no caching */
2487 bdrv_flags |= BDRV_O_NOCACHE;
2488 else if (cache == 2) /* write-back */
2489 bdrv_flags |= BDRV_O_CACHE_WB;
2490 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2491 fprintf(stderr, "qemu: could not open disk image %s\n",
2492 file);
2493 return -1;
2495 return 0;
2498 /***********************************************************/
2499 /* USB devices */
2501 static USBPort *used_usb_ports;
2502 static USBPort *free_usb_ports;
2504 /* ??? Maybe change this to register a hub to keep track of the topology. */
2505 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2506 usb_attachfn attach)
2508 port->opaque = opaque;
2509 port->index = index;
2510 port->attach = attach;
2511 port->next = free_usb_ports;
2512 free_usb_ports = port;
2515 int usb_device_add_dev(USBDevice *dev)
2517 USBPort *port;
2519 /* Find a USB port to add the device to. */
2520 port = free_usb_ports;
2521 if (!port->next) {
2522 USBDevice *hub;
2524 /* Create a new hub and chain it on. */
2525 free_usb_ports = NULL;
2526 port->next = used_usb_ports;
2527 used_usb_ports = port;
2529 hub = usb_hub_init(VM_USB_HUB_SIZE);
2530 usb_attach(port, hub);
2531 port = free_usb_ports;
2534 free_usb_ports = port->next;
2535 port->next = used_usb_ports;
2536 used_usb_ports = port;
2537 usb_attach(port, dev);
2538 return 0;
2541 static int usb_device_add(const char *devname)
2543 const char *p;
2544 USBDevice *dev;
2546 if (!free_usb_ports)
2547 return -1;
2549 if (strstart(devname, "host:", &p)) {
2550 dev = usb_host_device_open(p);
2551 } else if (!strcmp(devname, "mouse")) {
2552 dev = usb_mouse_init();
2553 } else if (!strcmp(devname, "tablet")) {
2554 dev = usb_tablet_init();
2555 } else if (!strcmp(devname, "keyboard")) {
2556 dev = usb_keyboard_init();
2557 } else if (strstart(devname, "disk:", &p)) {
2558 dev = usb_msd_init(p);
2559 } else if (!strcmp(devname, "wacom-tablet")) {
2560 dev = usb_wacom_init();
2561 } else if (strstart(devname, "serial:", &p)) {
2562 dev = usb_serial_init(p);
2563 #ifdef CONFIG_BRLAPI
2564 } else if (!strcmp(devname, "braille")) {
2565 dev = usb_baum_init();
2566 #endif
2567 } else if (strstart(devname, "net:", &p)) {
2568 int nic = nb_nics;
2570 if (net_client_init("nic", p) < 0)
2571 return -1;
2572 nd_table[nic].model = "usb";
2573 dev = usb_net_init(&nd_table[nic]);
2574 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2575 dev = usb_bt_init(devname[2] ? hci_init(p) :
2576 bt_new_hci(qemu_find_bt_vlan(0)));
2577 } else {
2578 return -1;
2580 if (!dev)
2581 return -1;
2583 return usb_device_add_dev(dev);
2586 int usb_device_del_addr(int bus_num, int addr)
2588 USBPort *port;
2589 USBPort **lastp;
2590 USBDevice *dev;
2592 if (!used_usb_ports)
2593 return -1;
2595 if (bus_num != 0)
2596 return -1;
2598 lastp = &used_usb_ports;
2599 port = used_usb_ports;
2600 while (port && port->dev->addr != addr) {
2601 lastp = &port->next;
2602 port = port->next;
2605 if (!port)
2606 return -1;
2608 dev = port->dev;
2609 *lastp = port->next;
2610 usb_attach(port, NULL);
2611 dev->handle_destroy(dev);
2612 port->next = free_usb_ports;
2613 free_usb_ports = port;
2614 return 0;
2617 static int usb_device_del(const char *devname)
2619 int bus_num, addr;
2620 const char *p;
2622 if (strstart(devname, "host:", &p))
2623 return usb_host_device_close(p);
2625 if (!used_usb_ports)
2626 return -1;
2628 p = strchr(devname, '.');
2629 if (!p)
2630 return -1;
2631 bus_num = strtoul(devname, NULL, 0);
2632 addr = strtoul(p + 1, NULL, 0);
2634 return usb_device_del_addr(bus_num, addr);
2637 void do_usb_add(const char *devname)
2639 usb_device_add(devname);
2642 void do_usb_del(const char *devname)
2644 usb_device_del(devname);
2647 void usb_info(void)
2649 USBDevice *dev;
2650 USBPort *port;
2651 const char *speed_str;
2653 if (!usb_enabled) {
2654 term_printf("USB support not enabled\n");
2655 return;
2658 for (port = used_usb_ports; port; port = port->next) {
2659 dev = port->dev;
2660 if (!dev)
2661 continue;
2662 switch(dev->speed) {
2663 case USB_SPEED_LOW:
2664 speed_str = "1.5";
2665 break;
2666 case USB_SPEED_FULL:
2667 speed_str = "12";
2668 break;
2669 case USB_SPEED_HIGH:
2670 speed_str = "480";
2671 break;
2672 default:
2673 speed_str = "?";
2674 break;
2676 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2677 0, dev->addr, speed_str, dev->devname);
2681 /***********************************************************/
2682 /* PCMCIA/Cardbus */
2684 static struct pcmcia_socket_entry_s {
2685 struct pcmcia_socket_s *socket;
2686 struct pcmcia_socket_entry_s *next;
2687 } *pcmcia_sockets = 0;
2689 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2691 struct pcmcia_socket_entry_s *entry;
2693 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2694 entry->socket = socket;
2695 entry->next = pcmcia_sockets;
2696 pcmcia_sockets = entry;
2699 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2701 struct pcmcia_socket_entry_s *entry, **ptr;
2703 ptr = &pcmcia_sockets;
2704 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2705 if (entry->socket == socket) {
2706 *ptr = entry->next;
2707 qemu_free(entry);
2711 void pcmcia_info(void)
2713 struct pcmcia_socket_entry_s *iter;
2714 if (!pcmcia_sockets)
2715 term_printf("No PCMCIA sockets\n");
2717 for (iter = pcmcia_sockets; iter; iter = iter->next)
2718 term_printf("%s: %s\n", iter->socket->slot_string,
2719 iter->socket->attached ? iter->socket->card_string :
2720 "Empty");
2723 /***********************************************************/
2724 /* dumb display */
2726 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2730 static void dumb_resize(DisplayState *ds, int w, int h)
2734 static void dumb_display_init(DisplayState *ds)
2736 ds->data = NULL;
2737 ds->linesize = 0;
2738 ds->depth = 0;
2739 ds->dpy_update = dumb_update;
2740 ds->dpy_resize = dumb_resize;
2741 ds->dpy_refresh = NULL;
2742 ds->gui_timer_interval = 0;
2743 ds->idle = 1;
2746 /***********************************************************/
2747 /* I/O handling */
2749 #define MAX_IO_HANDLERS 64
2751 typedef struct IOHandlerRecord {
2752 int fd;
2753 IOCanRWHandler *fd_read_poll;
2754 IOHandler *fd_read;
2755 IOHandler *fd_write;
2756 int deleted;
2757 void *opaque;
2758 /* temporary data */
2759 struct pollfd *ufd;
2760 struct IOHandlerRecord *next;
2761 } IOHandlerRecord;
2763 static IOHandlerRecord *first_io_handler;
2765 /* XXX: fd_read_poll should be suppressed, but an API change is
2766 necessary in the character devices to suppress fd_can_read(). */
2767 int qemu_set_fd_handler2(int fd,
2768 IOCanRWHandler *fd_read_poll,
2769 IOHandler *fd_read,
2770 IOHandler *fd_write,
2771 void *opaque)
2773 IOHandlerRecord **pioh, *ioh;
2775 if (!fd_read && !fd_write) {
2776 pioh = &first_io_handler;
2777 for(;;) {
2778 ioh = *pioh;
2779 if (ioh == NULL)
2780 break;
2781 if (ioh->fd == fd) {
2782 ioh->deleted = 1;
2783 break;
2785 pioh = &ioh->next;
2787 } else {
2788 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2789 if (ioh->fd == fd)
2790 goto found;
2792 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2793 if (!ioh)
2794 return -1;
2795 ioh->next = first_io_handler;
2796 first_io_handler = ioh;
2797 found:
2798 ioh->fd = fd;
2799 ioh->fd_read_poll = fd_read_poll;
2800 ioh->fd_read = fd_read;
2801 ioh->fd_write = fd_write;
2802 ioh->opaque = opaque;
2803 ioh->deleted = 0;
2805 return 0;
2808 int qemu_set_fd_handler(int fd,
2809 IOHandler *fd_read,
2810 IOHandler *fd_write,
2811 void *opaque)
2813 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2816 #ifdef _WIN32
2817 /***********************************************************/
2818 /* Polling handling */
2820 typedef struct PollingEntry {
2821 PollingFunc *func;
2822 void *opaque;
2823 struct PollingEntry *next;
2824 } PollingEntry;
2826 static PollingEntry *first_polling_entry;
2828 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2830 PollingEntry **ppe, *pe;
2831 pe = qemu_mallocz(sizeof(PollingEntry));
2832 if (!pe)
2833 return -1;
2834 pe->func = func;
2835 pe->opaque = opaque;
2836 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2837 *ppe = pe;
2838 return 0;
2841 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2843 PollingEntry **ppe, *pe;
2844 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2845 pe = *ppe;
2846 if (pe->func == func && pe->opaque == opaque) {
2847 *ppe = pe->next;
2848 qemu_free(pe);
2849 break;
2854 /***********************************************************/
2855 /* Wait objects support */
2856 typedef struct WaitObjects {
2857 int num;
2858 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2859 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2860 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2861 } WaitObjects;
2863 static WaitObjects wait_objects = {0};
2865 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2867 WaitObjects *w = &wait_objects;
2869 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2870 return -1;
2871 w->events[w->num] = handle;
2872 w->func[w->num] = func;
2873 w->opaque[w->num] = opaque;
2874 w->num++;
2875 return 0;
2878 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2880 int i, found;
2881 WaitObjects *w = &wait_objects;
2883 found = 0;
2884 for (i = 0; i < w->num; i++) {
2885 if (w->events[i] == handle)
2886 found = 1;
2887 if (found) {
2888 w->events[i] = w->events[i + 1];
2889 w->func[i] = w->func[i + 1];
2890 w->opaque[i] = w->opaque[i + 1];
2893 if (found)
2894 w->num--;
2896 #endif
2898 /***********************************************************/
2899 /* ram save/restore */
2901 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2903 int v;
2905 v = qemu_get_byte(f);
2906 switch(v) {
2907 case 0:
2908 if (qemu_get_buffer(f, buf, len) != len)
2909 return -EIO;
2910 break;
2911 case 1:
2912 v = qemu_get_byte(f);
2913 memset(buf, v, len);
2914 break;
2915 default:
2916 return -EINVAL;
2919 if (qemu_file_has_error(f))
2920 return -EIO;
2922 return 0;
2925 static int ram_load_v1(QEMUFile *f, void *opaque)
2927 int ret;
2928 ram_addr_t i;
2930 if (qemu_get_be32(f) != phys_ram_size)
2931 return -EINVAL;
2932 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2933 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2934 if (ret)
2935 return ret;
2937 return 0;
2940 #define BDRV_HASH_BLOCK_SIZE 1024
2941 #define IOBUF_SIZE 4096
2942 #define RAM_CBLOCK_MAGIC 0xfabe
2944 typedef struct RamDecompressState {
2945 z_stream zstream;
2946 QEMUFile *f;
2947 uint8_t buf[IOBUF_SIZE];
2948 } RamDecompressState;
2950 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2952 int ret;
2953 memset(s, 0, sizeof(*s));
2954 s->f = f;
2955 ret = inflateInit(&s->zstream);
2956 if (ret != Z_OK)
2957 return -1;
2958 return 0;
2961 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2963 int ret, clen;
2965 s->zstream.avail_out = len;
2966 s->zstream.next_out = buf;
2967 while (s->zstream.avail_out > 0) {
2968 if (s->zstream.avail_in == 0) {
2969 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2970 return -1;
2971 clen = qemu_get_be16(s->f);
2972 if (clen > IOBUF_SIZE)
2973 return -1;
2974 qemu_get_buffer(s->f, s->buf, clen);
2975 s->zstream.avail_in = clen;
2976 s->zstream.next_in = s->buf;
2978 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2979 if (ret != Z_OK && ret != Z_STREAM_END) {
2980 return -1;
2983 return 0;
2986 static void ram_decompress_close(RamDecompressState *s)
2988 inflateEnd(&s->zstream);
2991 #define RAM_SAVE_FLAG_FULL 0x01
2992 #define RAM_SAVE_FLAG_COMPRESS 0x02
2993 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2994 #define RAM_SAVE_FLAG_PAGE 0x08
2995 #define RAM_SAVE_FLAG_EOS 0x10
2997 static int is_dup_page(uint8_t *page, uint8_t ch)
2999 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3000 uint32_t *array = (uint32_t *)page;
3001 int i;
3003 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3004 if (array[i] != val)
3005 return 0;
3008 return 1;
3011 static int ram_save_block(QEMUFile *f)
3013 static ram_addr_t current_addr = 0;
3014 ram_addr_t saved_addr = current_addr;
3015 ram_addr_t addr = 0;
3016 int found = 0;
3018 while (addr < phys_ram_size) {
3019 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3020 uint8_t ch;
3022 cpu_physical_memory_reset_dirty(current_addr,
3023 current_addr + TARGET_PAGE_SIZE,
3024 MIGRATION_DIRTY_FLAG);
3026 ch = *(phys_ram_base + current_addr);
3028 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3029 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3030 qemu_put_byte(f, ch);
3031 } else {
3032 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3033 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3036 found = 1;
3037 break;
3039 addr += TARGET_PAGE_SIZE;
3040 current_addr = (saved_addr + addr) % phys_ram_size;
3043 return found;
3046 static ram_addr_t ram_save_threshold = 10;
3048 static ram_addr_t ram_save_remaining(void)
3050 ram_addr_t addr;
3051 ram_addr_t count = 0;
3053 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3054 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3055 count++;
3058 return count;
3061 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3063 ram_addr_t addr;
3065 if (stage == 1) {
3066 /* Make sure all dirty bits are set */
3067 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3068 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3069 cpu_physical_memory_set_dirty(addr);
3072 /* Enable dirty memory tracking */
3073 cpu_physical_memory_set_dirty_tracking(1);
3075 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3078 while (!qemu_file_rate_limit(f)) {
3079 int ret;
3081 ret = ram_save_block(f);
3082 if (ret == 0) /* no more blocks */
3083 break;
3086 /* try transferring iterative blocks of memory */
3088 if (stage == 3) {
3089 cpu_physical_memory_set_dirty_tracking(0);
3091 /* flush all remaining blocks regardless of rate limiting */
3092 while (ram_save_block(f) != 0);
3095 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3097 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3100 static int ram_load_dead(QEMUFile *f, void *opaque)
3102 RamDecompressState s1, *s = &s1;
3103 uint8_t buf[10];
3104 ram_addr_t i;
3106 if (ram_decompress_open(s, f) < 0)
3107 return -EINVAL;
3108 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3109 if (ram_decompress_buf(s, buf, 1) < 0) {
3110 fprintf(stderr, "Error while reading ram block header\n");
3111 goto error;
3113 if (buf[0] == 0) {
3114 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3115 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3116 goto error;
3118 } else {
3119 error:
3120 printf("Error block header\n");
3121 return -EINVAL;
3124 ram_decompress_close(s);
3126 return 0;
3129 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3131 ram_addr_t addr;
3132 int flags;
3134 if (version_id == 1)
3135 return ram_load_v1(f, opaque);
3137 if (version_id == 2) {
3138 if (qemu_get_be32(f) != phys_ram_size)
3139 return -EINVAL;
3140 return ram_load_dead(f, opaque);
3143 if (version_id != 3)
3144 return -EINVAL;
3146 do {
3147 addr = qemu_get_be64(f);
3149 flags = addr & ~TARGET_PAGE_MASK;
3150 addr &= TARGET_PAGE_MASK;
3152 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3153 if (addr != phys_ram_size)
3154 return -EINVAL;
3157 if (flags & RAM_SAVE_FLAG_FULL) {
3158 if (ram_load_dead(f, opaque) < 0)
3159 return -EINVAL;
3162 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3163 uint8_t ch = qemu_get_byte(f);
3164 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3165 } else if (flags & RAM_SAVE_FLAG_PAGE)
3166 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3167 } while (!(flags & RAM_SAVE_FLAG_EOS));
3169 return 0;
3172 void qemu_service_io(void)
3174 CPUState *env = cpu_single_env;
3175 if (env) {
3176 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3177 #ifdef USE_KQEMU
3178 if (env->kqemu_enabled) {
3179 kqemu_cpu_interrupt(env);
3181 #endif
3185 /***********************************************************/
3186 /* bottom halves (can be seen as timers which expire ASAP) */
3188 struct QEMUBH {
3189 QEMUBHFunc *cb;
3190 void *opaque;
3191 int scheduled;
3192 int idle;
3193 int deleted;
3194 QEMUBH *next;
3197 static QEMUBH *first_bh = NULL;
3199 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3201 QEMUBH *bh;
3202 bh = qemu_mallocz(sizeof(QEMUBH));
3203 if (!bh)
3204 return NULL;
3205 bh->cb = cb;
3206 bh->opaque = opaque;
3207 bh->next = first_bh;
3208 first_bh = bh;
3209 return bh;
3212 int qemu_bh_poll(void)
3214 QEMUBH *bh, **bhp;
3215 int ret;
3217 ret = 0;
3218 for (bh = first_bh; bh; bh = bh->next) {
3219 if (!bh->deleted && bh->scheduled) {
3220 bh->scheduled = 0;
3221 if (!bh->idle)
3222 ret = 1;
3223 bh->idle = 0;
3224 bh->cb(bh->opaque);
3228 /* remove deleted bhs */
3229 bhp = &first_bh;
3230 while (*bhp) {
3231 bh = *bhp;
3232 if (bh->deleted) {
3233 *bhp = bh->next;
3234 qemu_free(bh);
3235 } else
3236 bhp = &bh->next;
3239 return ret;
3242 void qemu_bh_schedule_idle(QEMUBH *bh)
3244 if (bh->scheduled)
3245 return;
3246 bh->scheduled = 1;
3247 bh->idle = 1;
3250 void qemu_bh_schedule(QEMUBH *bh)
3252 CPUState *env = cpu_single_env;
3253 if (bh->scheduled)
3254 return;
3255 bh->scheduled = 1;
3256 bh->idle = 0;
3257 /* stop the currently executing CPU to execute the BH ASAP */
3258 if (env) {
3259 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3263 void qemu_bh_cancel(QEMUBH *bh)
3265 bh->scheduled = 0;
3268 void qemu_bh_delete(QEMUBH *bh)
3270 bh->scheduled = 0;
3271 bh->deleted = 1;
3274 static void qemu_bh_update_timeout(int *timeout)
3276 QEMUBH *bh;
3278 for (bh = first_bh; bh; bh = bh->next) {
3279 if (!bh->deleted && bh->scheduled) {
3280 if (bh->idle) {
3281 /* idle bottom halves will be polled at least
3282 * every 10ms */
3283 *timeout = MIN(10, *timeout);
3284 } else {
3285 /* non-idle bottom halves will be executed
3286 * immediately */
3287 *timeout = 0;
3288 break;
3294 /***********************************************************/
3295 /* machine registration */
3297 static QEMUMachine *first_machine = NULL;
3299 int qemu_register_machine(QEMUMachine *m)
3301 QEMUMachine **pm;
3302 pm = &first_machine;
3303 while (*pm != NULL)
3304 pm = &(*pm)->next;
3305 m->next = NULL;
3306 *pm = m;
3307 return 0;
3310 static QEMUMachine *find_machine(const char *name)
3312 QEMUMachine *m;
3314 for(m = first_machine; m != NULL; m = m->next) {
3315 if (!strcmp(m->name, name))
3316 return m;
3318 return NULL;
3321 /***********************************************************/
3322 /* main execution loop */
3324 static void gui_update(void *opaque)
3326 DisplayState *ds = opaque;
3327 ds->dpy_refresh(ds);
3328 qemu_mod_timer(ds->gui_timer,
3329 (ds->gui_timer_interval ?
3330 ds->gui_timer_interval :
3331 GUI_REFRESH_INTERVAL)
3332 + qemu_get_clock(rt_clock));
3335 struct vm_change_state_entry {
3336 VMChangeStateHandler *cb;
3337 void *opaque;
3338 LIST_ENTRY (vm_change_state_entry) entries;
3341 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3343 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3344 void *opaque)
3346 VMChangeStateEntry *e;
3348 e = qemu_mallocz(sizeof (*e));
3349 if (!e)
3350 return NULL;
3352 e->cb = cb;
3353 e->opaque = opaque;
3354 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3355 return e;
3358 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3360 LIST_REMOVE (e, entries);
3361 qemu_free (e);
3364 static void vm_state_notify(int running)
3366 VMChangeStateEntry *e;
3368 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3369 e->cb(e->opaque, running);
3373 /* XXX: support several handlers */
3374 static VMStopHandler *vm_stop_cb;
3375 static void *vm_stop_opaque;
3377 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3379 vm_stop_cb = cb;
3380 vm_stop_opaque = opaque;
3381 return 0;
3384 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3386 vm_stop_cb = NULL;
3389 void vm_start(void)
3391 if (!vm_running) {
3392 cpu_enable_ticks();
3393 vm_running = 1;
3394 vm_state_notify(1);
3395 qemu_rearm_alarm_timer(alarm_timer);
3399 void vm_stop(int reason)
3401 if (vm_running) {
3402 cpu_disable_ticks();
3403 vm_running = 0;
3404 if (reason != 0) {
3405 if (vm_stop_cb) {
3406 vm_stop_cb(vm_stop_opaque, reason);
3409 vm_state_notify(0);
3413 /* reset/shutdown handler */
3415 typedef struct QEMUResetEntry {
3416 QEMUResetHandler *func;
3417 void *opaque;
3418 struct QEMUResetEntry *next;
3419 } QEMUResetEntry;
3421 static QEMUResetEntry *first_reset_entry;
3422 static int reset_requested;
3423 static int shutdown_requested;
3424 static int powerdown_requested;
3426 int qemu_shutdown_requested(void)
3428 int r = shutdown_requested;
3429 shutdown_requested = 0;
3430 return r;
3433 int qemu_reset_requested(void)
3435 int r = reset_requested;
3436 reset_requested = 0;
3437 return r;
3440 int qemu_powerdown_requested(void)
3442 int r = powerdown_requested;
3443 powerdown_requested = 0;
3444 return r;
3447 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3449 QEMUResetEntry **pre, *re;
3451 pre = &first_reset_entry;
3452 while (*pre != NULL)
3453 pre = &(*pre)->next;
3454 re = qemu_mallocz(sizeof(QEMUResetEntry));
3455 re->func = func;
3456 re->opaque = opaque;
3457 re->next = NULL;
3458 *pre = re;
3461 void qemu_system_reset(void)
3463 QEMUResetEntry *re;
3465 /* reset all devices */
3466 for(re = first_reset_entry; re != NULL; re = re->next) {
3467 re->func(re->opaque);
3471 void qemu_system_reset_request(void)
3473 if (no_reboot) {
3474 shutdown_requested = 1;
3475 } else {
3476 reset_requested = 1;
3478 if (cpu_single_env)
3479 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3482 void qemu_system_shutdown_request(void)
3484 shutdown_requested = 1;
3485 if (cpu_single_env)
3486 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3489 void qemu_system_powerdown_request(void)
3491 powerdown_requested = 1;
3492 if (cpu_single_env)
3493 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3496 #ifdef _WIN32
3497 void host_main_loop_wait(int *timeout)
3499 int ret, ret2, i;
3500 PollingEntry *pe;
3503 /* XXX: need to suppress polling by better using win32 events */
3504 ret = 0;
3505 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3506 ret |= pe->func(pe->opaque);
3508 if (ret == 0) {
3509 int err;
3510 WaitObjects *w = &wait_objects;
3512 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3513 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3514 if (w->func[ret - WAIT_OBJECT_0])
3515 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3517 /* Check for additional signaled events */
3518 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3520 /* Check if event is signaled */
3521 ret2 = WaitForSingleObject(w->events[i], 0);
3522 if(ret2 == WAIT_OBJECT_0) {
3523 if (w->func[i])
3524 w->func[i](w->opaque[i]);
3525 } else if (ret2 == WAIT_TIMEOUT) {
3526 } else {
3527 err = GetLastError();
3528 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3531 } else if (ret == WAIT_TIMEOUT) {
3532 } else {
3533 err = GetLastError();
3534 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3538 *timeout = 0;
3540 #else
3541 void host_main_loop_wait(int *timeout)
3544 #endif
3546 void main_loop_wait(int timeout)
3548 IOHandlerRecord *ioh;
3549 fd_set rfds, wfds, xfds;
3550 int ret, nfds;
3551 struct timeval tv;
3553 qemu_bh_update_timeout(&timeout);
3555 host_main_loop_wait(&timeout);
3557 /* poll any events */
3558 /* XXX: separate device handlers from system ones */
3559 nfds = -1;
3560 FD_ZERO(&rfds);
3561 FD_ZERO(&wfds);
3562 FD_ZERO(&xfds);
3563 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3564 if (ioh->deleted)
3565 continue;
3566 if (ioh->fd_read &&
3567 (!ioh->fd_read_poll ||
3568 ioh->fd_read_poll(ioh->opaque) != 0)) {
3569 FD_SET(ioh->fd, &rfds);
3570 if (ioh->fd > nfds)
3571 nfds = ioh->fd;
3573 if (ioh->fd_write) {
3574 FD_SET(ioh->fd, &wfds);
3575 if (ioh->fd > nfds)
3576 nfds = ioh->fd;
3580 tv.tv_sec = timeout / 1000;
3581 tv.tv_usec = (timeout % 1000) * 1000;
3583 #if defined(CONFIG_SLIRP)
3584 if (slirp_is_inited()) {
3585 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3587 #endif
3588 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3589 if (ret > 0) {
3590 IOHandlerRecord **pioh;
3592 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3593 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3594 ioh->fd_read(ioh->opaque);
3596 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3597 ioh->fd_write(ioh->opaque);
3601 /* remove deleted IO handlers */
3602 pioh = &first_io_handler;
3603 while (*pioh) {
3604 ioh = *pioh;
3605 if (ioh->deleted) {
3606 *pioh = ioh->next;
3607 qemu_free(ioh);
3608 } else
3609 pioh = &ioh->next;
3612 #if defined(CONFIG_SLIRP)
3613 if (slirp_is_inited()) {
3614 if (ret < 0) {
3615 FD_ZERO(&rfds);
3616 FD_ZERO(&wfds);
3617 FD_ZERO(&xfds);
3619 slirp_select_poll(&rfds, &wfds, &xfds);
3621 #endif
3623 /* vm time timers */
3624 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3625 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3626 qemu_get_clock(vm_clock));
3628 /* real time timers */
3629 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3630 qemu_get_clock(rt_clock));
3632 /* Check bottom-halves last in case any of the earlier events triggered
3633 them. */
3634 qemu_bh_poll();
3638 static int main_loop(void)
3640 int ret, timeout;
3641 #ifdef CONFIG_PROFILER
3642 int64_t ti;
3643 #endif
3644 CPUState *env;
3646 cur_cpu = first_cpu;
3647 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3648 for(;;) {
3649 if (vm_running) {
3651 for(;;) {
3652 /* get next cpu */
3653 env = next_cpu;
3654 #ifdef CONFIG_PROFILER
3655 ti = profile_getclock();
3656 #endif
3657 if (use_icount) {
3658 int64_t count;
3659 int decr;
3660 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3661 env->icount_decr.u16.low = 0;
3662 env->icount_extra = 0;
3663 count = qemu_next_deadline();
3664 count = (count + (1 << icount_time_shift) - 1)
3665 >> icount_time_shift;
3666 qemu_icount += count;
3667 decr = (count > 0xffff) ? 0xffff : count;
3668 count -= decr;
3669 env->icount_decr.u16.low = decr;
3670 env->icount_extra = count;
3672 ret = cpu_exec(env);
3673 #ifdef CONFIG_PROFILER
3674 qemu_time += profile_getclock() - ti;
3675 #endif
3676 if (use_icount) {
3677 /* Fold pending instructions back into the
3678 instruction counter, and clear the interrupt flag. */
3679 qemu_icount -= (env->icount_decr.u16.low
3680 + env->icount_extra);
3681 env->icount_decr.u32 = 0;
3682 env->icount_extra = 0;
3684 next_cpu = env->next_cpu ?: first_cpu;
3685 if (event_pending && likely(ret != EXCP_DEBUG)) {
3686 ret = EXCP_INTERRUPT;
3687 event_pending = 0;
3688 break;
3690 if (ret == EXCP_HLT) {
3691 /* Give the next CPU a chance to run. */
3692 cur_cpu = env;
3693 continue;
3695 if (ret != EXCP_HALTED)
3696 break;
3697 /* all CPUs are halted ? */
3698 if (env == cur_cpu)
3699 break;
3701 cur_cpu = env;
3703 if (shutdown_requested) {
3704 ret = EXCP_INTERRUPT;
3705 if (no_shutdown) {
3706 vm_stop(0);
3707 no_shutdown = 0;
3709 else
3710 break;
3712 if (reset_requested) {
3713 reset_requested = 0;
3714 qemu_system_reset();
3715 ret = EXCP_INTERRUPT;
3717 if (powerdown_requested) {
3718 powerdown_requested = 0;
3719 qemu_system_powerdown();
3720 ret = EXCP_INTERRUPT;
3722 if (unlikely(ret == EXCP_DEBUG)) {
3723 gdb_set_stop_cpu(cur_cpu);
3724 vm_stop(EXCP_DEBUG);
3726 /* If all cpus are halted then wait until the next IRQ */
3727 /* XXX: use timeout computed from timers */
3728 if (ret == EXCP_HALTED) {
3729 if (use_icount) {
3730 int64_t add;
3731 int64_t delta;
3732 /* Advance virtual time to the next event. */
3733 if (use_icount == 1) {
3734 /* When not using an adaptive execution frequency
3735 we tend to get badly out of sync with real time,
3736 so just delay for a reasonable amount of time. */
3737 delta = 0;
3738 } else {
3739 delta = cpu_get_icount() - cpu_get_clock();
3741 if (delta > 0) {
3742 /* If virtual time is ahead of real time then just
3743 wait for IO. */
3744 timeout = (delta / 1000000) + 1;
3745 } else {
3746 /* Wait for either IO to occur or the next
3747 timer event. */
3748 add = qemu_next_deadline();
3749 /* We advance the timer before checking for IO.
3750 Limit the amount we advance so that early IO
3751 activity won't get the guest too far ahead. */
3752 if (add > 10000000)
3753 add = 10000000;
3754 delta += add;
3755 add = (add + (1 << icount_time_shift) - 1)
3756 >> icount_time_shift;
3757 qemu_icount += add;
3758 timeout = delta / 1000000;
3759 if (timeout < 0)
3760 timeout = 0;
3762 } else {
3763 timeout = 5000;
3765 } else {
3766 timeout = 0;
3768 } else {
3769 if (shutdown_requested) {
3770 ret = EXCP_INTERRUPT;
3771 break;
3773 timeout = 5000;
3775 #ifdef CONFIG_PROFILER
3776 ti = profile_getclock();
3777 #endif
3778 main_loop_wait(timeout);
3779 #ifdef CONFIG_PROFILER
3780 dev_time += profile_getclock() - ti;
3781 #endif
3783 cpu_disable_ticks();
3784 return ret;
3787 static void help(int exitcode)
3789 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3790 "usage: %s [options] [disk_image]\n"
3791 "\n"
3792 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3793 "\n"
3794 "Standard options:\n"
3795 "-M machine select emulated machine (-M ? for list)\n"
3796 "-cpu cpu select CPU (-cpu ? for list)\n"
3797 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3798 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3799 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3800 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3801 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3802 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3803 " [,cache=writethrough|writeback|none][,format=f]\n"
3804 " use 'file' as a drive image\n"
3805 "-mtdblock file use 'file' as on-board Flash memory image\n"
3806 "-sd file use 'file' as SecureDigital card image\n"
3807 "-pflash file use 'file' as a parallel flash image\n"
3808 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3809 "-snapshot write to temporary files instead of disk image files\n"
3810 #ifdef CONFIG_SDL
3811 "-no-frame open SDL window without a frame and window decorations\n"
3812 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3813 "-no-quit disable SDL window close capability\n"
3814 #endif
3815 #ifdef TARGET_I386
3816 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3817 #endif
3818 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3819 "-smp n set the number of CPUs to 'n' [default=1]\n"
3820 "-nographic disable graphical output and redirect serial I/Os to console\n"
3821 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3822 #ifndef _WIN32
3823 "-k language use keyboard layout (for example \"fr\" for French)\n"
3824 #endif
3825 #ifdef HAS_AUDIO
3826 "-audio-help print list of audio drivers and their options\n"
3827 "-soundhw c1,... enable audio support\n"
3828 " and only specified sound cards (comma separated list)\n"
3829 " use -soundhw ? to get the list of supported cards\n"
3830 " use -soundhw all to enable all of them\n"
3831 #endif
3832 "-vga [std|cirrus|vmware]\n"
3833 " select video card type\n"
3834 "-localtime set the real time clock to local time [default=utc]\n"
3835 "-full-screen start in full screen\n"
3836 #ifdef TARGET_I386
3837 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3838 #endif
3839 "-usb enable the USB driver (will be the default soon)\n"
3840 "-usbdevice name add the host or guest USB device 'name'\n"
3841 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3842 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3843 #endif
3844 "-name string set the name of the guest\n"
3845 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
3846 "\n"
3847 "Network options:\n"
3848 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
3849 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3850 #ifdef CONFIG_SLIRP
3851 "-net user[,vlan=n][,hostname=host]\n"
3852 " connect the user mode network stack to VLAN 'n' and send\n"
3853 " hostname 'host' to DHCP clients\n"
3854 #endif
3855 #ifdef _WIN32
3856 "-net tap[,vlan=n],ifname=name\n"
3857 " connect the host TAP network interface to VLAN 'n'\n"
3858 #else
3859 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3860 " connect the host TAP network interface to VLAN 'n' and use the\n"
3861 " network scripts 'file' (default=%s)\n"
3862 " and 'dfile' (default=%s);\n"
3863 " use '[down]script=no' to disable script execution;\n"
3864 " use 'fd=h' to connect to an already opened TAP interface\n"
3865 #endif
3866 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3867 " connect the vlan 'n' to another VLAN using a socket connection\n"
3868 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
3869 " connect the vlan 'n' to multicast maddr and port\n"
3870 #ifdef CONFIG_VDE
3871 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3872 " connect the vlan 'n' to port 'n' of a vde switch running\n"
3873 " on host and listening for incoming connections on 'socketpath'.\n"
3874 " Use group 'groupname' and mode 'octalmode' to change default\n"
3875 " ownership and permissions for communication port.\n"
3876 #endif
3877 "-net none use it alone to have zero network devices; if no -net option\n"
3878 " is provided, the default is '-net nic -net user'\n"
3879 "\n"
3880 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
3881 "-bt hci,host[:id]\n"
3882 " Use host's HCI with the given name\n"
3883 "-bt hci[,vlan=n]\n"
3884 " Emulate a standard HCI in virtual scatternet 'n'\n"
3885 "-bt vhci[,vlan=n]\n"
3886 " Add host computer to virtual scatternet 'n' using VHCI\n"
3887 "-bt device:dev[,vlan=n]\n"
3888 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
3889 "\n"
3890 #ifdef CONFIG_SLIRP
3891 "-tftp dir allow tftp access to files in dir [-net user]\n"
3892 "-bootp file advertise file in BOOTP replies\n"
3893 #ifndef _WIN32
3894 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3895 #endif
3896 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3897 " redirect TCP or UDP connections from host to guest [-net user]\n"
3898 #endif
3899 "\n"
3900 "Linux boot specific:\n"
3901 "-kernel bzImage use 'bzImage' as kernel image\n"
3902 "-append cmdline use 'cmdline' as kernel command line\n"
3903 "-initrd file use 'file' as initial ram disk\n"
3904 "\n"
3905 "Debug/Expert options:\n"
3906 "-monitor dev redirect the monitor to char device 'dev'\n"
3907 "-serial dev redirect the serial port to char device 'dev'\n"
3908 "-parallel dev redirect the parallel port to char device 'dev'\n"
3909 "-pidfile file Write PID to 'file'\n"
3910 "-S freeze CPU at startup (use 'c' to start execution)\n"
3911 "-s wait gdb connection to port\n"
3912 "-p port set gdb connection port [default=%s]\n"
3913 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
3914 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
3915 " translation (t=none or lba) (usually qemu can guess them)\n"
3916 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
3917 #ifdef USE_KQEMU
3918 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
3919 "-no-kqemu disable KQEMU kernel module usage\n"
3920 #endif
3921 #ifdef CONFIG_KVM
3922 "-enable-kvm enable KVM full virtualization support\n"
3923 #endif
3924 #ifdef TARGET_I386
3925 "-no-acpi disable ACPI\n"
3926 #endif
3927 #ifdef CONFIG_CURSES
3928 "-curses use a curses/ncurses interface instead of SDL\n"
3929 #endif
3930 "-no-reboot exit instead of rebooting\n"
3931 "-no-shutdown stop before shutdown\n"
3932 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
3933 "-vnc display start a VNC server on display\n"
3934 #ifndef _WIN32
3935 "-daemonize daemonize QEMU after initializing\n"
3936 #endif
3937 "-option-rom rom load a file, rom, into the option ROM space\n"
3938 #ifdef TARGET_SPARC
3939 "-prom-env variable=value set OpenBIOS nvram variables\n"
3940 #endif
3941 "-clock force the use of the given methods for timer alarm.\n"
3942 " To see what timers are available use -clock ?\n"
3943 "-startdate select initial date of the clock\n"
3944 "-icount [N|auto]\n"
3945 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
3946 "\n"
3947 "During emulation, the following keys are useful:\n"
3948 "ctrl-alt-f toggle full screen\n"
3949 "ctrl-alt-n switch to virtual console 'n'\n"
3950 "ctrl-alt toggle mouse and keyboard grab\n"
3951 "\n"
3952 "When using -nographic, press 'ctrl-a h' to get some help.\n"
3954 "qemu",
3955 DEFAULT_RAM_SIZE,
3956 #ifndef _WIN32
3957 DEFAULT_NETWORK_SCRIPT,
3958 DEFAULT_NETWORK_DOWN_SCRIPT,
3959 #endif
3960 DEFAULT_GDBSTUB_PORT,
3961 "/tmp/qemu.log");
3962 exit(exitcode);
3965 #define HAS_ARG 0x0001
3967 enum {
3968 QEMU_OPTION_h,
3970 QEMU_OPTION_M,
3971 QEMU_OPTION_cpu,
3972 QEMU_OPTION_fda,
3973 QEMU_OPTION_fdb,
3974 QEMU_OPTION_hda,
3975 QEMU_OPTION_hdb,
3976 QEMU_OPTION_hdc,
3977 QEMU_OPTION_hdd,
3978 QEMU_OPTION_drive,
3979 QEMU_OPTION_cdrom,
3980 QEMU_OPTION_mtdblock,
3981 QEMU_OPTION_sd,
3982 QEMU_OPTION_pflash,
3983 QEMU_OPTION_boot,
3984 QEMU_OPTION_snapshot,
3985 #ifdef TARGET_I386
3986 QEMU_OPTION_no_fd_bootchk,
3987 #endif
3988 QEMU_OPTION_m,
3989 QEMU_OPTION_nographic,
3990 QEMU_OPTION_portrait,
3991 #ifdef HAS_AUDIO
3992 QEMU_OPTION_audio_help,
3993 QEMU_OPTION_soundhw,
3994 #endif
3996 QEMU_OPTION_net,
3997 QEMU_OPTION_tftp,
3998 QEMU_OPTION_bootp,
3999 QEMU_OPTION_smb,
4000 QEMU_OPTION_redir,
4001 QEMU_OPTION_bt,
4003 QEMU_OPTION_kernel,
4004 QEMU_OPTION_append,
4005 QEMU_OPTION_initrd,
4007 QEMU_OPTION_S,
4008 QEMU_OPTION_s,
4009 QEMU_OPTION_p,
4010 QEMU_OPTION_d,
4011 QEMU_OPTION_hdachs,
4012 QEMU_OPTION_L,
4013 QEMU_OPTION_bios,
4014 QEMU_OPTION_k,
4015 QEMU_OPTION_localtime,
4016 QEMU_OPTION_g,
4017 QEMU_OPTION_vga,
4018 QEMU_OPTION_echr,
4019 QEMU_OPTION_monitor,
4020 QEMU_OPTION_serial,
4021 QEMU_OPTION_parallel,
4022 QEMU_OPTION_loadvm,
4023 QEMU_OPTION_full_screen,
4024 QEMU_OPTION_no_frame,
4025 QEMU_OPTION_alt_grab,
4026 QEMU_OPTION_no_quit,
4027 QEMU_OPTION_pidfile,
4028 QEMU_OPTION_no_kqemu,
4029 QEMU_OPTION_kernel_kqemu,
4030 QEMU_OPTION_enable_kvm,
4031 QEMU_OPTION_win2k_hack,
4032 QEMU_OPTION_usb,
4033 QEMU_OPTION_usbdevice,
4034 QEMU_OPTION_smp,
4035 QEMU_OPTION_vnc,
4036 QEMU_OPTION_no_acpi,
4037 QEMU_OPTION_curses,
4038 QEMU_OPTION_no_reboot,
4039 QEMU_OPTION_no_shutdown,
4040 QEMU_OPTION_show_cursor,
4041 QEMU_OPTION_daemonize,
4042 QEMU_OPTION_option_rom,
4043 QEMU_OPTION_semihosting,
4044 QEMU_OPTION_name,
4045 QEMU_OPTION_prom_env,
4046 QEMU_OPTION_old_param,
4047 QEMU_OPTION_clock,
4048 QEMU_OPTION_startdate,
4049 QEMU_OPTION_tb_size,
4050 QEMU_OPTION_icount,
4051 QEMU_OPTION_uuid,
4052 QEMU_OPTION_incoming,
4055 typedef struct QEMUOption {
4056 const char *name;
4057 int flags;
4058 int index;
4059 } QEMUOption;
4061 static const QEMUOption qemu_options[] = {
4062 { "h", 0, QEMU_OPTION_h },
4063 { "help", 0, QEMU_OPTION_h },
4065 { "M", HAS_ARG, QEMU_OPTION_M },
4066 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4067 { "fda", HAS_ARG, QEMU_OPTION_fda },
4068 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4069 { "hda", HAS_ARG, QEMU_OPTION_hda },
4070 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4071 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4072 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4073 { "drive", HAS_ARG, QEMU_OPTION_drive },
4074 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4075 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4076 { "sd", HAS_ARG, QEMU_OPTION_sd },
4077 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4078 { "boot", HAS_ARG, QEMU_OPTION_boot },
4079 { "snapshot", 0, QEMU_OPTION_snapshot },
4080 #ifdef TARGET_I386
4081 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4082 #endif
4083 { "m", HAS_ARG, QEMU_OPTION_m },
4084 { "nographic", 0, QEMU_OPTION_nographic },
4085 { "portrait", 0, QEMU_OPTION_portrait },
4086 { "k", HAS_ARG, QEMU_OPTION_k },
4087 #ifdef HAS_AUDIO
4088 { "audio-help", 0, QEMU_OPTION_audio_help },
4089 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4090 #endif
4092 { "net", HAS_ARG, QEMU_OPTION_net},
4093 #ifdef CONFIG_SLIRP
4094 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4095 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4096 #ifndef _WIN32
4097 { "smb", HAS_ARG, QEMU_OPTION_smb },
4098 #endif
4099 { "redir", HAS_ARG, QEMU_OPTION_redir },
4100 #endif
4101 { "bt", HAS_ARG, QEMU_OPTION_bt },
4103 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4104 { "append", HAS_ARG, QEMU_OPTION_append },
4105 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4107 { "S", 0, QEMU_OPTION_S },
4108 { "s", 0, QEMU_OPTION_s },
4109 { "p", HAS_ARG, QEMU_OPTION_p },
4110 { "d", HAS_ARG, QEMU_OPTION_d },
4111 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4112 { "L", HAS_ARG, QEMU_OPTION_L },
4113 { "bios", HAS_ARG, QEMU_OPTION_bios },
4114 #ifdef USE_KQEMU
4115 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4116 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4117 #endif
4118 #ifdef CONFIG_KVM
4119 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4120 #endif
4121 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4122 { "g", 1, QEMU_OPTION_g },
4123 #endif
4124 { "localtime", 0, QEMU_OPTION_localtime },
4125 { "vga", HAS_ARG, QEMU_OPTION_vga },
4126 { "echr", HAS_ARG, QEMU_OPTION_echr },
4127 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4128 { "serial", HAS_ARG, QEMU_OPTION_serial },
4129 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4130 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4131 { "full-screen", 0, QEMU_OPTION_full_screen },
4132 #ifdef CONFIG_SDL
4133 { "no-frame", 0, QEMU_OPTION_no_frame },
4134 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4135 { "no-quit", 0, QEMU_OPTION_no_quit },
4136 #endif
4137 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4138 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4139 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4140 { "smp", HAS_ARG, QEMU_OPTION_smp },
4141 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4142 #ifdef CONFIG_CURSES
4143 { "curses", 0, QEMU_OPTION_curses },
4144 #endif
4145 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4147 /* temporary options */
4148 { "usb", 0, QEMU_OPTION_usb },
4149 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4150 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4151 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4152 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4153 { "daemonize", 0, QEMU_OPTION_daemonize },
4154 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4155 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4156 { "semihosting", 0, QEMU_OPTION_semihosting },
4157 #endif
4158 { "name", HAS_ARG, QEMU_OPTION_name },
4159 #if defined(TARGET_SPARC)
4160 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4161 #endif
4162 #if defined(TARGET_ARM)
4163 { "old-param", 0, QEMU_OPTION_old_param },
4164 #endif
4165 { "clock", HAS_ARG, QEMU_OPTION_clock },
4166 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4167 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4168 { "icount", HAS_ARG, QEMU_OPTION_icount },
4169 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4170 { NULL },
4173 /* password input */
4175 int qemu_key_check(BlockDriverState *bs, const char *name)
4177 char password[256];
4178 int i;
4180 if (!bdrv_is_encrypted(bs))
4181 return 0;
4183 term_printf("%s is encrypted.\n", name);
4184 for(i = 0; i < 3; i++) {
4185 monitor_readline("Password: ", 1, password, sizeof(password));
4186 if (bdrv_set_key(bs, password) == 0)
4187 return 0;
4188 term_printf("invalid password\n");
4190 return -EPERM;
4193 static BlockDriverState *get_bdrv(int index)
4195 if (index > nb_drives)
4196 return NULL;
4197 return drives_table[index].bdrv;
4200 static void read_passwords(void)
4202 BlockDriverState *bs;
4203 int i;
4205 for(i = 0; i < 6; i++) {
4206 bs = get_bdrv(i);
4207 if (bs)
4208 qemu_key_check(bs, bdrv_get_device_name(bs));
4212 #ifdef HAS_AUDIO
4213 struct soundhw soundhw[] = {
4214 #ifdef HAS_AUDIO_CHOICE
4215 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4217 "pcspk",
4218 "PC speaker",
4221 { .init_isa = pcspk_audio_init }
4223 #endif
4225 "sb16",
4226 "Creative Sound Blaster 16",
4229 { .init_isa = SB16_init }
4232 #ifdef CONFIG_CS4231A
4234 "cs4231a",
4235 "CS4231A",
4238 { .init_isa = cs4231a_init }
4240 #endif
4242 #ifdef CONFIG_ADLIB
4244 "adlib",
4245 #ifdef HAS_YMF262
4246 "Yamaha YMF262 (OPL3)",
4247 #else
4248 "Yamaha YM3812 (OPL2)",
4249 #endif
4252 { .init_isa = Adlib_init }
4254 #endif
4256 #ifdef CONFIG_GUS
4258 "gus",
4259 "Gravis Ultrasound GF1",
4262 { .init_isa = GUS_init }
4264 #endif
4266 #ifdef CONFIG_AC97
4268 "ac97",
4269 "Intel 82801AA AC97 Audio",
4272 { .init_pci = ac97_init }
4274 #endif
4277 "es1370",
4278 "ENSONIQ AudioPCI ES1370",
4281 { .init_pci = es1370_init }
4283 #endif
4285 { NULL, NULL, 0, 0, { NULL } }
4288 static void select_soundhw (const char *optarg)
4290 struct soundhw *c;
4292 if (*optarg == '?') {
4293 show_valid_cards:
4295 printf ("Valid sound card names (comma separated):\n");
4296 for (c = soundhw; c->name; ++c) {
4297 printf ("%-11s %s\n", c->name, c->descr);
4299 printf ("\n-soundhw all will enable all of the above\n");
4300 exit (*optarg != '?');
4302 else {
4303 size_t l;
4304 const char *p;
4305 char *e;
4306 int bad_card = 0;
4308 if (!strcmp (optarg, "all")) {
4309 for (c = soundhw; c->name; ++c) {
4310 c->enabled = 1;
4312 return;
4315 p = optarg;
4316 while (*p) {
4317 e = strchr (p, ',');
4318 l = !e ? strlen (p) : (size_t) (e - p);
4320 for (c = soundhw; c->name; ++c) {
4321 if (!strncmp (c->name, p, l)) {
4322 c->enabled = 1;
4323 break;
4327 if (!c->name) {
4328 if (l > 80) {
4329 fprintf (stderr,
4330 "Unknown sound card name (too big to show)\n");
4332 else {
4333 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4334 (int) l, p);
4336 bad_card = 1;
4338 p += l + (e != NULL);
4341 if (bad_card)
4342 goto show_valid_cards;
4345 #endif
4347 static void select_vgahw (const char *p)
4349 const char *opts;
4351 if (strstart(p, "std", &opts)) {
4352 cirrus_vga_enabled = 0;
4353 vmsvga_enabled = 0;
4354 } else if (strstart(p, "cirrus", &opts)) {
4355 cirrus_vga_enabled = 1;
4356 vmsvga_enabled = 0;
4357 } else if (strstart(p, "vmware", &opts)) {
4358 cirrus_vga_enabled = 0;
4359 vmsvga_enabled = 1;
4360 } else {
4361 invalid_vga:
4362 fprintf(stderr, "Unknown vga type: %s\n", p);
4363 exit(1);
4365 while (*opts) {
4366 const char *nextopt;
4368 if (strstart(opts, ",retrace=", &nextopt)) {
4369 opts = nextopt;
4370 if (strstart(opts, "dumb", &nextopt))
4371 vga_retrace_method = VGA_RETRACE_DUMB;
4372 else if (strstart(opts, "precise", &nextopt))
4373 vga_retrace_method = VGA_RETRACE_PRECISE;
4374 else goto invalid_vga;
4375 } else goto invalid_vga;
4376 opts = nextopt;
4380 #ifdef _WIN32
4381 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4383 exit(STATUS_CONTROL_C_EXIT);
4384 return TRUE;
4386 #endif
4388 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4390 int ret;
4392 if(strlen(str) != 36)
4393 return -1;
4395 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4396 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4397 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4399 if(ret != 16)
4400 return -1;
4402 return 0;
4405 #define MAX_NET_CLIENTS 32
4407 #ifndef _WIN32
4409 static void termsig_handler(int signal)
4411 qemu_system_shutdown_request();
4414 static void termsig_setup(void)
4416 struct sigaction act;
4418 memset(&act, 0, sizeof(act));
4419 act.sa_handler = termsig_handler;
4420 sigaction(SIGINT, &act, NULL);
4421 sigaction(SIGHUP, &act, NULL);
4422 sigaction(SIGTERM, &act, NULL);
4425 #endif
4427 int main(int argc, char **argv)
4429 #ifdef CONFIG_GDBSTUB
4430 int use_gdbstub;
4431 const char *gdbstub_port;
4432 #endif
4433 uint32_t boot_devices_bitmap = 0;
4434 int i;
4435 int snapshot, linux_boot, net_boot;
4436 const char *initrd_filename;
4437 const char *kernel_filename, *kernel_cmdline;
4438 const char *boot_devices = "";
4439 DisplayState *ds = &display_state;
4440 int cyls, heads, secs, translation;
4441 const char *net_clients[MAX_NET_CLIENTS];
4442 int nb_net_clients;
4443 const char *bt_opts[MAX_BT_CMDLINE];
4444 int nb_bt_opts;
4445 int hda_index;
4446 int optind;
4447 const char *r, *optarg;
4448 CharDriverState *monitor_hd;
4449 const char *monitor_device;
4450 const char *serial_devices[MAX_SERIAL_PORTS];
4451 int serial_device_index;
4452 const char *parallel_devices[MAX_PARALLEL_PORTS];
4453 int parallel_device_index;
4454 const char *loadvm = NULL;
4455 QEMUMachine *machine;
4456 const char *cpu_model;
4457 const char *usb_devices[MAX_USB_CMDLINE];
4458 int usb_devices_index;
4459 int fds[2];
4460 int tb_size;
4461 const char *pid_file = NULL;
4462 int autostart;
4463 const char *incoming = NULL;
4465 LIST_INIT (&vm_change_state_head);
4466 #ifndef _WIN32
4468 struct sigaction act;
4469 sigfillset(&act.sa_mask);
4470 act.sa_flags = 0;
4471 act.sa_handler = SIG_IGN;
4472 sigaction(SIGPIPE, &act, NULL);
4474 #else
4475 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4476 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4477 QEMU to run on a single CPU */
4479 HANDLE h;
4480 DWORD mask, smask;
4481 int i;
4482 h = GetCurrentProcess();
4483 if (GetProcessAffinityMask(h, &mask, &smask)) {
4484 for(i = 0; i < 32; i++) {
4485 if (mask & (1 << i))
4486 break;
4488 if (i != 32) {
4489 mask = 1 << i;
4490 SetProcessAffinityMask(h, mask);
4494 #endif
4496 register_machines();
4497 machine = first_machine;
4498 cpu_model = NULL;
4499 initrd_filename = NULL;
4500 ram_size = 0;
4501 vga_ram_size = VGA_RAM_SIZE;
4502 #ifdef CONFIG_GDBSTUB
4503 use_gdbstub = 0;
4504 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4505 #endif
4506 snapshot = 0;
4507 nographic = 0;
4508 curses = 0;
4509 kernel_filename = NULL;
4510 kernel_cmdline = "";
4511 cyls = heads = secs = 0;
4512 translation = BIOS_ATA_TRANSLATION_AUTO;
4513 monitor_device = "vc";
4515 serial_devices[0] = "vc:80Cx24C";
4516 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4517 serial_devices[i] = NULL;
4518 serial_device_index = 0;
4520 parallel_devices[0] = "vc:640x480";
4521 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4522 parallel_devices[i] = NULL;
4523 parallel_device_index = 0;
4525 usb_devices_index = 0;
4527 nb_net_clients = 0;
4528 nb_bt_opts = 0;
4529 nb_drives = 0;
4530 nb_drives_opt = 0;
4531 hda_index = -1;
4533 nb_nics = 0;
4535 tb_size = 0;
4536 autostart= 1;
4538 optind = 1;
4539 for(;;) {
4540 if (optind >= argc)
4541 break;
4542 r = argv[optind];
4543 if (r[0] != '-') {
4544 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4545 } else {
4546 const QEMUOption *popt;
4548 optind++;
4549 /* Treat --foo the same as -foo. */
4550 if (r[1] == '-')
4551 r++;
4552 popt = qemu_options;
4553 for(;;) {
4554 if (!popt->name) {
4555 fprintf(stderr, "%s: invalid option -- '%s'\n",
4556 argv[0], r);
4557 exit(1);
4559 if (!strcmp(popt->name, r + 1))
4560 break;
4561 popt++;
4563 if (popt->flags & HAS_ARG) {
4564 if (optind >= argc) {
4565 fprintf(stderr, "%s: option '%s' requires an argument\n",
4566 argv[0], r);
4567 exit(1);
4569 optarg = argv[optind++];
4570 } else {
4571 optarg = NULL;
4574 switch(popt->index) {
4575 case QEMU_OPTION_M:
4576 machine = find_machine(optarg);
4577 if (!machine) {
4578 QEMUMachine *m;
4579 printf("Supported machines are:\n");
4580 for(m = first_machine; m != NULL; m = m->next) {
4581 printf("%-10s %s%s\n",
4582 m->name, m->desc,
4583 m == first_machine ? " (default)" : "");
4585 exit(*optarg != '?');
4587 break;
4588 case QEMU_OPTION_cpu:
4589 /* hw initialization will check this */
4590 if (*optarg == '?') {
4591 /* XXX: implement xxx_cpu_list for targets that still miss it */
4592 #if defined(cpu_list)
4593 cpu_list(stdout, &fprintf);
4594 #endif
4595 exit(0);
4596 } else {
4597 cpu_model = optarg;
4599 break;
4600 case QEMU_OPTION_initrd:
4601 initrd_filename = optarg;
4602 break;
4603 case QEMU_OPTION_hda:
4604 if (cyls == 0)
4605 hda_index = drive_add(optarg, HD_ALIAS, 0);
4606 else
4607 hda_index = drive_add(optarg, HD_ALIAS
4608 ",cyls=%d,heads=%d,secs=%d%s",
4609 0, cyls, heads, secs,
4610 translation == BIOS_ATA_TRANSLATION_LBA ?
4611 ",trans=lba" :
4612 translation == BIOS_ATA_TRANSLATION_NONE ?
4613 ",trans=none" : "");
4614 break;
4615 case QEMU_OPTION_hdb:
4616 case QEMU_OPTION_hdc:
4617 case QEMU_OPTION_hdd:
4618 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4619 break;
4620 case QEMU_OPTION_drive:
4621 drive_add(NULL, "%s", optarg);
4622 break;
4623 case QEMU_OPTION_mtdblock:
4624 drive_add(optarg, MTD_ALIAS);
4625 break;
4626 case QEMU_OPTION_sd:
4627 drive_add(optarg, SD_ALIAS);
4628 break;
4629 case QEMU_OPTION_pflash:
4630 drive_add(optarg, PFLASH_ALIAS);
4631 break;
4632 case QEMU_OPTION_snapshot:
4633 snapshot = 1;
4634 break;
4635 case QEMU_OPTION_hdachs:
4637 const char *p;
4638 p = optarg;
4639 cyls = strtol(p, (char **)&p, 0);
4640 if (cyls < 1 || cyls > 16383)
4641 goto chs_fail;
4642 if (*p != ',')
4643 goto chs_fail;
4644 p++;
4645 heads = strtol(p, (char **)&p, 0);
4646 if (heads < 1 || heads > 16)
4647 goto chs_fail;
4648 if (*p != ',')
4649 goto chs_fail;
4650 p++;
4651 secs = strtol(p, (char **)&p, 0);
4652 if (secs < 1 || secs > 63)
4653 goto chs_fail;
4654 if (*p == ',') {
4655 p++;
4656 if (!strcmp(p, "none"))
4657 translation = BIOS_ATA_TRANSLATION_NONE;
4658 else if (!strcmp(p, "lba"))
4659 translation = BIOS_ATA_TRANSLATION_LBA;
4660 else if (!strcmp(p, "auto"))
4661 translation = BIOS_ATA_TRANSLATION_AUTO;
4662 else
4663 goto chs_fail;
4664 } else if (*p != '\0') {
4665 chs_fail:
4666 fprintf(stderr, "qemu: invalid physical CHS format\n");
4667 exit(1);
4669 if (hda_index != -1)
4670 snprintf(drives_opt[hda_index].opt,
4671 sizeof(drives_opt[hda_index].opt),
4672 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4673 0, cyls, heads, secs,
4674 translation == BIOS_ATA_TRANSLATION_LBA ?
4675 ",trans=lba" :
4676 translation == BIOS_ATA_TRANSLATION_NONE ?
4677 ",trans=none" : "");
4679 break;
4680 case QEMU_OPTION_nographic:
4681 nographic = 1;
4682 break;
4683 #ifdef CONFIG_CURSES
4684 case QEMU_OPTION_curses:
4685 curses = 1;
4686 break;
4687 #endif
4688 case QEMU_OPTION_portrait:
4689 graphic_rotate = 1;
4690 break;
4691 case QEMU_OPTION_kernel:
4692 kernel_filename = optarg;
4693 break;
4694 case QEMU_OPTION_append:
4695 kernel_cmdline = optarg;
4696 break;
4697 case QEMU_OPTION_cdrom:
4698 drive_add(optarg, CDROM_ALIAS);
4699 break;
4700 case QEMU_OPTION_boot:
4701 boot_devices = optarg;
4702 /* We just do some generic consistency checks */
4704 /* Could easily be extended to 64 devices if needed */
4705 const char *p;
4707 boot_devices_bitmap = 0;
4708 for (p = boot_devices; *p != '\0'; p++) {
4709 /* Allowed boot devices are:
4710 * a b : floppy disk drives
4711 * c ... f : IDE disk drives
4712 * g ... m : machine implementation dependant drives
4713 * n ... p : network devices
4714 * It's up to each machine implementation to check
4715 * if the given boot devices match the actual hardware
4716 * implementation and firmware features.
4718 if (*p < 'a' || *p > 'q') {
4719 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4720 exit(1);
4722 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4723 fprintf(stderr,
4724 "Boot device '%c' was given twice\n",*p);
4725 exit(1);
4727 boot_devices_bitmap |= 1 << (*p - 'a');
4730 break;
4731 case QEMU_OPTION_fda:
4732 case QEMU_OPTION_fdb:
4733 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4734 break;
4735 #ifdef TARGET_I386
4736 case QEMU_OPTION_no_fd_bootchk:
4737 fd_bootchk = 0;
4738 break;
4739 #endif
4740 case QEMU_OPTION_net:
4741 if (nb_net_clients >= MAX_NET_CLIENTS) {
4742 fprintf(stderr, "qemu: too many network clients\n");
4743 exit(1);
4745 net_clients[nb_net_clients] = optarg;
4746 nb_net_clients++;
4747 break;
4748 #ifdef CONFIG_SLIRP
4749 case QEMU_OPTION_tftp:
4750 tftp_prefix = optarg;
4751 break;
4752 case QEMU_OPTION_bootp:
4753 bootp_filename = optarg;
4754 break;
4755 #ifndef _WIN32
4756 case QEMU_OPTION_smb:
4757 net_slirp_smb(optarg);
4758 break;
4759 #endif
4760 case QEMU_OPTION_redir:
4761 net_slirp_redir(optarg);
4762 break;
4763 #endif
4764 case QEMU_OPTION_bt:
4765 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4766 fprintf(stderr, "qemu: too many bluetooth options\n");
4767 exit(1);
4769 bt_opts[nb_bt_opts++] = optarg;
4770 break;
4771 #ifdef HAS_AUDIO
4772 case QEMU_OPTION_audio_help:
4773 AUD_help ();
4774 exit (0);
4775 break;
4776 case QEMU_OPTION_soundhw:
4777 select_soundhw (optarg);
4778 break;
4779 #endif
4780 case QEMU_OPTION_h:
4781 help(0);
4782 break;
4783 case QEMU_OPTION_m: {
4784 uint64_t value;
4785 char *ptr;
4787 value = strtoul(optarg, &ptr, 10);
4788 switch (*ptr) {
4789 case 0: case 'M': case 'm':
4790 value <<= 20;
4791 break;
4792 case 'G': case 'g':
4793 value <<= 30;
4794 break;
4795 default:
4796 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4797 exit(1);
4800 /* On 32-bit hosts, QEMU is limited by virtual address space */
4801 if (value > (2047 << 20)
4802 #ifndef USE_KQEMU
4803 && HOST_LONG_BITS == 32
4804 #endif
4806 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4807 exit(1);
4809 if (value != (uint64_t)(ram_addr_t)value) {
4810 fprintf(stderr, "qemu: ram size too large\n");
4811 exit(1);
4813 ram_size = value;
4814 break;
4816 case QEMU_OPTION_d:
4818 int mask;
4819 const CPULogItem *item;
4821 mask = cpu_str_to_log_mask(optarg);
4822 if (!mask) {
4823 printf("Log items (comma separated):\n");
4824 for(item = cpu_log_items; item->mask != 0; item++) {
4825 printf("%-10s %s\n", item->name, item->help);
4827 exit(1);
4829 cpu_set_log(mask);
4831 break;
4832 #ifdef CONFIG_GDBSTUB
4833 case QEMU_OPTION_s:
4834 use_gdbstub = 1;
4835 break;
4836 case QEMU_OPTION_p:
4837 gdbstub_port = optarg;
4838 break;
4839 #endif
4840 case QEMU_OPTION_L:
4841 bios_dir = optarg;
4842 break;
4843 case QEMU_OPTION_bios:
4844 bios_name = optarg;
4845 break;
4846 case QEMU_OPTION_S:
4847 autostart = 0;
4848 break;
4849 case QEMU_OPTION_k:
4850 keyboard_layout = optarg;
4851 break;
4852 case QEMU_OPTION_localtime:
4853 rtc_utc = 0;
4854 break;
4855 case QEMU_OPTION_vga:
4856 select_vgahw (optarg);
4857 break;
4858 case QEMU_OPTION_g:
4860 const char *p;
4861 int w, h, depth;
4862 p = optarg;
4863 w = strtol(p, (char **)&p, 10);
4864 if (w <= 0) {
4865 graphic_error:
4866 fprintf(stderr, "qemu: invalid resolution or depth\n");
4867 exit(1);
4869 if (*p != 'x')
4870 goto graphic_error;
4871 p++;
4872 h = strtol(p, (char **)&p, 10);
4873 if (h <= 0)
4874 goto graphic_error;
4875 if (*p == 'x') {
4876 p++;
4877 depth = strtol(p, (char **)&p, 10);
4878 if (depth != 8 && depth != 15 && depth != 16 &&
4879 depth != 24 && depth != 32)
4880 goto graphic_error;
4881 } else if (*p == '\0') {
4882 depth = graphic_depth;
4883 } else {
4884 goto graphic_error;
4887 graphic_width = w;
4888 graphic_height = h;
4889 graphic_depth = depth;
4891 break;
4892 case QEMU_OPTION_echr:
4894 char *r;
4895 term_escape_char = strtol(optarg, &r, 0);
4896 if (r == optarg)
4897 printf("Bad argument to echr\n");
4898 break;
4900 case QEMU_OPTION_monitor:
4901 monitor_device = optarg;
4902 break;
4903 case QEMU_OPTION_serial:
4904 if (serial_device_index >= MAX_SERIAL_PORTS) {
4905 fprintf(stderr, "qemu: too many serial ports\n");
4906 exit(1);
4908 serial_devices[serial_device_index] = optarg;
4909 serial_device_index++;
4910 break;
4911 case QEMU_OPTION_parallel:
4912 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4913 fprintf(stderr, "qemu: too many parallel ports\n");
4914 exit(1);
4916 parallel_devices[parallel_device_index] = optarg;
4917 parallel_device_index++;
4918 break;
4919 case QEMU_OPTION_loadvm:
4920 loadvm = optarg;
4921 break;
4922 case QEMU_OPTION_full_screen:
4923 full_screen = 1;
4924 break;
4925 #ifdef CONFIG_SDL
4926 case QEMU_OPTION_no_frame:
4927 no_frame = 1;
4928 break;
4929 case QEMU_OPTION_alt_grab:
4930 alt_grab = 1;
4931 break;
4932 case QEMU_OPTION_no_quit:
4933 no_quit = 1;
4934 break;
4935 #endif
4936 case QEMU_OPTION_pidfile:
4937 pid_file = optarg;
4938 break;
4939 #ifdef TARGET_I386
4940 case QEMU_OPTION_win2k_hack:
4941 win2k_install_hack = 1;
4942 break;
4943 #endif
4944 #ifdef USE_KQEMU
4945 case QEMU_OPTION_no_kqemu:
4946 kqemu_allowed = 0;
4947 break;
4948 case QEMU_OPTION_kernel_kqemu:
4949 kqemu_allowed = 2;
4950 break;
4951 #endif
4952 #ifdef CONFIG_KVM
4953 case QEMU_OPTION_enable_kvm:
4954 kvm_allowed = 1;
4955 #ifdef USE_KQEMU
4956 kqemu_allowed = 0;
4957 #endif
4958 break;
4959 #endif
4960 case QEMU_OPTION_usb:
4961 usb_enabled = 1;
4962 break;
4963 case QEMU_OPTION_usbdevice:
4964 usb_enabled = 1;
4965 if (usb_devices_index >= MAX_USB_CMDLINE) {
4966 fprintf(stderr, "Too many USB devices\n");
4967 exit(1);
4969 usb_devices[usb_devices_index] = optarg;
4970 usb_devices_index++;
4971 break;
4972 case QEMU_OPTION_smp:
4973 smp_cpus = atoi(optarg);
4974 if (smp_cpus < 1) {
4975 fprintf(stderr, "Invalid number of CPUs\n");
4976 exit(1);
4978 break;
4979 case QEMU_OPTION_vnc:
4980 vnc_display = optarg;
4981 break;
4982 case QEMU_OPTION_no_acpi:
4983 acpi_enabled = 0;
4984 break;
4985 case QEMU_OPTION_no_reboot:
4986 no_reboot = 1;
4987 break;
4988 case QEMU_OPTION_no_shutdown:
4989 no_shutdown = 1;
4990 break;
4991 case QEMU_OPTION_show_cursor:
4992 cursor_hide = 0;
4993 break;
4994 case QEMU_OPTION_uuid:
4995 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4996 fprintf(stderr, "Fail to parse UUID string."
4997 " Wrong format.\n");
4998 exit(1);
5000 break;
5001 case QEMU_OPTION_daemonize:
5002 daemonize = 1;
5003 break;
5004 case QEMU_OPTION_option_rom:
5005 if (nb_option_roms >= MAX_OPTION_ROMS) {
5006 fprintf(stderr, "Too many option ROMs\n");
5007 exit(1);
5009 option_rom[nb_option_roms] = optarg;
5010 nb_option_roms++;
5011 break;
5012 case QEMU_OPTION_semihosting:
5013 semihosting_enabled = 1;
5014 break;
5015 case QEMU_OPTION_name:
5016 qemu_name = optarg;
5017 break;
5018 #ifdef TARGET_SPARC
5019 case QEMU_OPTION_prom_env:
5020 if (nb_prom_envs >= MAX_PROM_ENVS) {
5021 fprintf(stderr, "Too many prom variables\n");
5022 exit(1);
5024 prom_envs[nb_prom_envs] = optarg;
5025 nb_prom_envs++;
5026 break;
5027 #endif
5028 #ifdef TARGET_ARM
5029 case QEMU_OPTION_old_param:
5030 old_param = 1;
5031 break;
5032 #endif
5033 case QEMU_OPTION_clock:
5034 configure_alarms(optarg);
5035 break;
5036 case QEMU_OPTION_startdate:
5038 struct tm tm;
5039 time_t rtc_start_date;
5040 if (!strcmp(optarg, "now")) {
5041 rtc_date_offset = -1;
5042 } else {
5043 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5044 &tm.tm_year,
5045 &tm.tm_mon,
5046 &tm.tm_mday,
5047 &tm.tm_hour,
5048 &tm.tm_min,
5049 &tm.tm_sec) == 6) {
5050 /* OK */
5051 } else if (sscanf(optarg, "%d-%d-%d",
5052 &tm.tm_year,
5053 &tm.tm_mon,
5054 &tm.tm_mday) == 3) {
5055 tm.tm_hour = 0;
5056 tm.tm_min = 0;
5057 tm.tm_sec = 0;
5058 } else {
5059 goto date_fail;
5061 tm.tm_year -= 1900;
5062 tm.tm_mon--;
5063 rtc_start_date = mktimegm(&tm);
5064 if (rtc_start_date == -1) {
5065 date_fail:
5066 fprintf(stderr, "Invalid date format. Valid format are:\n"
5067 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5068 exit(1);
5070 rtc_date_offset = time(NULL) - rtc_start_date;
5073 break;
5074 case QEMU_OPTION_tb_size:
5075 tb_size = strtol(optarg, NULL, 0);
5076 if (tb_size < 0)
5077 tb_size = 0;
5078 break;
5079 case QEMU_OPTION_icount:
5080 use_icount = 1;
5081 if (strcmp(optarg, "auto") == 0) {
5082 icount_time_shift = -1;
5083 } else {
5084 icount_time_shift = strtol(optarg, NULL, 0);
5086 break;
5087 case QEMU_OPTION_incoming:
5088 incoming = optarg;
5089 break;
5094 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5095 if (kvm_allowed && kqemu_allowed) {
5096 fprintf(stderr,
5097 "You can not enable both KVM and kqemu at the same time\n");
5098 exit(1);
5100 #endif
5102 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5103 if (smp_cpus > machine->max_cpus) {
5104 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5105 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5106 machine->max_cpus);
5107 exit(1);
5110 if (nographic) {
5111 if (serial_device_index == 0)
5112 serial_devices[0] = "stdio";
5113 if (parallel_device_index == 0)
5114 parallel_devices[0] = "null";
5115 if (strncmp(monitor_device, "vc", 2) == 0)
5116 monitor_device = "stdio";
5119 #ifndef _WIN32
5120 if (daemonize) {
5121 pid_t pid;
5123 if (pipe(fds) == -1)
5124 exit(1);
5126 pid = fork();
5127 if (pid > 0) {
5128 uint8_t status;
5129 ssize_t len;
5131 close(fds[1]);
5133 again:
5134 len = read(fds[0], &status, 1);
5135 if (len == -1 && (errno == EINTR))
5136 goto again;
5138 if (len != 1)
5139 exit(1);
5140 else if (status == 1) {
5141 fprintf(stderr, "Could not acquire pidfile\n");
5142 exit(1);
5143 } else
5144 exit(0);
5145 } else if (pid < 0)
5146 exit(1);
5148 setsid();
5150 pid = fork();
5151 if (pid > 0)
5152 exit(0);
5153 else if (pid < 0)
5154 exit(1);
5156 umask(027);
5158 signal(SIGTSTP, SIG_IGN);
5159 signal(SIGTTOU, SIG_IGN);
5160 signal(SIGTTIN, SIG_IGN);
5162 #endif
5164 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5165 if (daemonize) {
5166 uint8_t status = 1;
5167 write(fds[1], &status, 1);
5168 } else
5169 fprintf(stderr, "Could not acquire pid file\n");
5170 exit(1);
5173 #ifdef USE_KQEMU
5174 if (smp_cpus > 1)
5175 kqemu_allowed = 0;
5176 #endif
5177 linux_boot = (kernel_filename != NULL);
5178 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5180 if (!linux_boot && net_boot == 0 &&
5181 !machine->nodisk_ok && nb_drives_opt == 0)
5182 help(1);
5184 if (!linux_boot && *kernel_cmdline != '\0') {
5185 fprintf(stderr, "-append only allowed with -kernel option\n");
5186 exit(1);
5189 if (!linux_boot && initrd_filename != NULL) {
5190 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5191 exit(1);
5194 /* boot to floppy or the default cd if no hard disk defined yet */
5195 if (!boot_devices[0]) {
5196 boot_devices = "cad";
5198 setvbuf(stdout, NULL, _IOLBF, 0);
5200 init_timers();
5201 if (init_timer_alarm() < 0) {
5202 fprintf(stderr, "could not initialize alarm timer\n");
5203 exit(1);
5205 if (use_icount && icount_time_shift < 0) {
5206 use_icount = 2;
5207 /* 125MIPS seems a reasonable initial guess at the guest speed.
5208 It will be corrected fairly quickly anyway. */
5209 icount_time_shift = 3;
5210 init_icount_adjust();
5213 #ifdef _WIN32
5214 socket_init();
5215 #endif
5217 /* init network clients */
5218 if (nb_net_clients == 0) {
5219 /* if no clients, we use a default config */
5220 net_clients[nb_net_clients++] = "nic";
5221 #ifdef CONFIG_SLIRP
5222 net_clients[nb_net_clients++] = "user";
5223 #endif
5226 for(i = 0;i < nb_net_clients; i++) {
5227 if (net_client_parse(net_clients[i]) < 0)
5228 exit(1);
5230 net_client_check();
5232 #ifdef TARGET_I386
5233 /* XXX: this should be moved in the PC machine instantiation code */
5234 if (net_boot != 0) {
5235 int netroms = 0;
5236 for (i = 0; i < nb_nics && i < 4; i++) {
5237 const char *model = nd_table[i].model;
5238 char buf[1024];
5239 if (net_boot & (1 << i)) {
5240 if (model == NULL)
5241 model = "ne2k_pci";
5242 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5243 if (get_image_size(buf) > 0) {
5244 if (nb_option_roms >= MAX_OPTION_ROMS) {
5245 fprintf(stderr, "Too many option ROMs\n");
5246 exit(1);
5248 option_rom[nb_option_roms] = strdup(buf);
5249 nb_option_roms++;
5250 netroms++;
5254 if (netroms == 0) {
5255 fprintf(stderr, "No valid PXE rom found for network device\n");
5256 exit(1);
5259 #endif
5261 /* init the bluetooth world */
5262 for (i = 0; i < nb_bt_opts; i++)
5263 if (bt_parse(bt_opts[i]))
5264 exit(1);
5266 /* init the memory */
5267 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5269 if (machine->ram_require & RAMSIZE_FIXED) {
5270 if (ram_size > 0) {
5271 if (ram_size < phys_ram_size) {
5272 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5273 machine->name, (unsigned long long) phys_ram_size);
5274 exit(-1);
5277 phys_ram_size = ram_size;
5278 } else
5279 ram_size = phys_ram_size;
5280 } else {
5281 if (ram_size == 0)
5282 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5284 phys_ram_size += ram_size;
5287 phys_ram_base = qemu_vmalloc(phys_ram_size);
5288 if (!phys_ram_base) {
5289 fprintf(stderr, "Could not allocate physical memory\n");
5290 exit(1);
5293 /* init the dynamic translator */
5294 cpu_exec_init_all(tb_size * 1024 * 1024);
5296 bdrv_init();
5298 /* we always create the cdrom drive, even if no disk is there */
5300 if (nb_drives_opt < MAX_DRIVES)
5301 drive_add(NULL, CDROM_ALIAS);
5303 /* we always create at least one floppy */
5305 if (nb_drives_opt < MAX_DRIVES)
5306 drive_add(NULL, FD_ALIAS, 0);
5308 /* we always create one sd slot, even if no card is in it */
5310 if (nb_drives_opt < MAX_DRIVES)
5311 drive_add(NULL, SD_ALIAS);
5313 /* open the virtual block devices */
5315 for(i = 0; i < nb_drives_opt; i++)
5316 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5317 exit(1);
5319 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5320 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5322 /* terminal init */
5323 memset(&display_state, 0, sizeof(display_state));
5324 if (nographic) {
5325 if (curses) {
5326 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5327 exit(1);
5329 /* nearly nothing to do */
5330 dumb_display_init(ds);
5331 } else if (vnc_display != NULL) {
5332 vnc_display_init(ds);
5333 if (vnc_display_open(ds, vnc_display) < 0)
5334 exit(1);
5335 } else
5336 #if defined(CONFIG_CURSES)
5337 if (curses) {
5338 curses_display_init(ds, full_screen);
5339 } else
5340 #endif
5342 #if defined(CONFIG_SDL)
5343 sdl_display_init(ds, full_screen, no_frame);
5344 #elif defined(CONFIG_COCOA)
5345 cocoa_display_init(ds, full_screen);
5346 #else
5347 dumb_display_init(ds);
5348 #endif
5351 #ifndef _WIN32
5352 /* must be after terminal init, SDL library changes signal handlers */
5353 termsig_setup();
5354 #endif
5356 /* Maintain compatibility with multiple stdio monitors */
5357 if (!strcmp(monitor_device,"stdio")) {
5358 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5359 const char *devname = serial_devices[i];
5360 if (devname && !strcmp(devname,"mon:stdio")) {
5361 monitor_device = NULL;
5362 break;
5363 } else if (devname && !strcmp(devname,"stdio")) {
5364 monitor_device = NULL;
5365 serial_devices[i] = "mon:stdio";
5366 break;
5370 if (monitor_device) {
5371 monitor_hd = qemu_chr_open("monitor", monitor_device);
5372 if (!monitor_hd) {
5373 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5374 exit(1);
5376 monitor_init(monitor_hd, !nographic);
5379 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5380 const char *devname = serial_devices[i];
5381 if (devname && strcmp(devname, "none")) {
5382 char label[32];
5383 snprintf(label, sizeof(label), "serial%d", i);
5384 serial_hds[i] = qemu_chr_open(label, devname);
5385 if (!serial_hds[i]) {
5386 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5387 devname);
5388 exit(1);
5390 if (strstart(devname, "vc", 0))
5391 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5395 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5396 const char *devname = parallel_devices[i];
5397 if (devname && strcmp(devname, "none")) {
5398 char label[32];
5399 snprintf(label, sizeof(label), "parallel%d", i);
5400 parallel_hds[i] = qemu_chr_open(label, devname);
5401 if (!parallel_hds[i]) {
5402 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5403 devname);
5404 exit(1);
5406 if (strstart(devname, "vc", 0))
5407 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5411 if (kvm_enabled()) {
5412 int ret;
5414 ret = kvm_init(smp_cpus);
5415 if (ret < 0) {
5416 fprintf(stderr, "failed to initialize KVM\n");
5417 exit(1);
5421 machine->init(ram_size, vga_ram_size, boot_devices, ds,
5422 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5424 /* init USB devices */
5425 if (usb_enabled) {
5426 for(i = 0; i < usb_devices_index; i++) {
5427 if (usb_device_add(usb_devices[i]) < 0) {
5428 fprintf(stderr, "Warning: could not add USB device %s\n",
5429 usb_devices[i]);
5434 if (display_state.dpy_refresh) {
5435 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5436 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5439 #ifdef CONFIG_GDBSTUB
5440 if (use_gdbstub) {
5441 /* XXX: use standard host:port notation and modify options
5442 accordingly. */
5443 if (gdbserver_start(gdbstub_port) < 0) {
5444 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5445 gdbstub_port);
5446 exit(1);
5449 #endif
5451 if (loadvm)
5452 do_loadvm(loadvm);
5454 if (incoming) {
5455 autostart = 0; /* fixme how to deal with -daemonize */
5456 qemu_start_incoming_migration(incoming);
5460 /* XXX: simplify init */
5461 read_passwords();
5462 if (autostart) {
5463 vm_start();
5467 if (daemonize) {
5468 uint8_t status = 0;
5469 ssize_t len;
5470 int fd;
5472 again1:
5473 len = write(fds[1], &status, 1);
5474 if (len == -1 && (errno == EINTR))
5475 goto again1;
5477 if (len != 1)
5478 exit(1);
5480 chdir("/");
5481 TFR(fd = open("/dev/null", O_RDWR));
5482 if (fd == -1)
5483 exit(1);
5485 dup2(fd, 0);
5486 dup2(fd, 1);
5487 dup2(fd, 2);
5489 close(fd);
5492 main_loop();
5493 quit_timers();
5494 net_cleanup();
5496 return 0;