Don't use "hz" in identifiers to make AIX happy.
[qemu/mini2440/sniper_sniper_test.git] / vl.c
blob5f747cfa20426c9d082cfc25675d7c4746ddf098
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 static int no_frame = 0;
213 int no_quit = 0;
214 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
215 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
216 #ifdef TARGET_I386
217 int win2k_install_hack = 0;
218 #endif
219 int usb_enabled = 0;
220 int smp_cpus = 1;
221 const char *vnc_display;
222 int acpi_enabled = 1;
223 int fd_bootchk = 1;
224 int no_reboot = 0;
225 int no_shutdown = 0;
226 int cursor_hide = 1;
227 int graphic_rotate = 0;
228 int daemonize = 0;
229 const char *option_rom[MAX_OPTION_ROMS];
230 int nb_option_roms;
231 int semihosting_enabled = 0;
232 #ifdef TARGET_ARM
233 int old_param = 0;
234 #endif
235 const char *qemu_name;
236 int alt_grab = 0;
237 #ifdef TARGET_SPARC
238 unsigned int nb_prom_envs = 0;
239 const char *prom_envs[MAX_PROM_ENVS];
240 #endif
241 static int nb_drives_opt;
242 static struct drive_opt {
243 const char *file;
244 char opt[1024];
245 } drives_opt[MAX_DRIVES];
247 static CPUState *cur_cpu;
248 static CPUState *next_cpu;
249 static int event_pending = 1;
250 /* Conversion factor from emulated instructions to virtual clock ticks. */
251 static int icount_time_shift;
252 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
253 #define MAX_ICOUNT_SHIFT 10
254 /* Compensate for varying guest execution speed. */
255 static int64_t qemu_icount_bias;
256 static QEMUTimer *icount_rt_timer;
257 static QEMUTimer *icount_vm_timer;
259 uint8_t qemu_uuid[16];
261 /***********************************************************/
262 /* x86 ISA bus support */
264 target_phys_addr_t isa_mem_base = 0;
265 PicState2 *isa_pic;
267 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
268 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
270 static uint32_t ioport_read(int index, uint32_t address)
272 static IOPortReadFunc *default_func[3] = {
273 default_ioport_readb,
274 default_ioport_readw,
275 default_ioport_readl
277 IOPortReadFunc *func = ioport_read_table[index][address];
278 if (!func)
279 func = default_func[index];
280 return func(ioport_opaque[address], address);
283 static void ioport_write(int index, uint32_t address, uint32_t data)
285 static IOPortWriteFunc *default_func[3] = {
286 default_ioport_writeb,
287 default_ioport_writew,
288 default_ioport_writel
290 IOPortWriteFunc *func = ioport_write_table[index][address];
291 if (!func)
292 func = default_func[index];
293 func(ioport_opaque[address], address, data);
296 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
298 #ifdef DEBUG_UNUSED_IOPORT
299 fprintf(stderr, "unused inb: port=0x%04x\n", address);
300 #endif
301 return 0xff;
304 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
306 #ifdef DEBUG_UNUSED_IOPORT
307 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
308 #endif
311 /* default is to make two byte accesses */
312 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
314 uint32_t data;
315 data = ioport_read(0, address);
316 address = (address + 1) & (MAX_IOPORTS - 1);
317 data |= ioport_read(0, address) << 8;
318 return data;
321 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
323 ioport_write(0, address, data & 0xff);
324 address = (address + 1) & (MAX_IOPORTS - 1);
325 ioport_write(0, address, (data >> 8) & 0xff);
328 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
330 #ifdef DEBUG_UNUSED_IOPORT
331 fprintf(stderr, "unused inl: port=0x%04x\n", address);
332 #endif
333 return 0xffffffff;
336 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
338 #ifdef DEBUG_UNUSED_IOPORT
339 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
340 #endif
343 /* size is the word size in byte */
344 int register_ioport_read(int start, int length, int size,
345 IOPortReadFunc *func, void *opaque)
347 int i, bsize;
349 if (size == 1) {
350 bsize = 0;
351 } else if (size == 2) {
352 bsize = 1;
353 } else if (size == 4) {
354 bsize = 2;
355 } else {
356 hw_error("register_ioport_read: invalid size");
357 return -1;
359 for(i = start; i < start + length; i += size) {
360 ioport_read_table[bsize][i] = func;
361 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
362 hw_error("register_ioport_read: invalid opaque");
363 ioport_opaque[i] = opaque;
365 return 0;
368 /* size is the word size in byte */
369 int register_ioport_write(int start, int length, int size,
370 IOPortWriteFunc *func, void *opaque)
372 int i, bsize;
374 if (size == 1) {
375 bsize = 0;
376 } else if (size == 2) {
377 bsize = 1;
378 } else if (size == 4) {
379 bsize = 2;
380 } else {
381 hw_error("register_ioport_write: invalid size");
382 return -1;
384 for(i = start; i < start + length; i += size) {
385 ioport_write_table[bsize][i] = func;
386 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
387 hw_error("register_ioport_write: invalid opaque");
388 ioport_opaque[i] = opaque;
390 return 0;
393 void isa_unassign_ioport(int start, int length)
395 int i;
397 for(i = start; i < start + length; i++) {
398 ioport_read_table[0][i] = default_ioport_readb;
399 ioport_read_table[1][i] = default_ioport_readw;
400 ioport_read_table[2][i] = default_ioport_readl;
402 ioport_write_table[0][i] = default_ioport_writeb;
403 ioport_write_table[1][i] = default_ioport_writew;
404 ioport_write_table[2][i] = default_ioport_writel;
408 /***********************************************************/
410 void cpu_outb(CPUState *env, int addr, int val)
412 #ifdef DEBUG_IOPORT
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "outb: %04x %02x\n", addr, val);
415 #endif
416 ioport_write(0, addr, val);
417 #ifdef USE_KQEMU
418 if (env)
419 env->last_io_time = cpu_get_time_fast();
420 #endif
423 void cpu_outw(CPUState *env, int addr, int val)
425 #ifdef DEBUG_IOPORT
426 if (loglevel & CPU_LOG_IOPORT)
427 fprintf(logfile, "outw: %04x %04x\n", addr, val);
428 #endif
429 ioport_write(1, addr, val);
430 #ifdef USE_KQEMU
431 if (env)
432 env->last_io_time = cpu_get_time_fast();
433 #endif
436 void cpu_outl(CPUState *env, int addr, int val)
438 #ifdef DEBUG_IOPORT
439 if (loglevel & CPU_LOG_IOPORT)
440 fprintf(logfile, "outl: %04x %08x\n", addr, val);
441 #endif
442 ioport_write(2, addr, val);
443 #ifdef USE_KQEMU
444 if (env)
445 env->last_io_time = cpu_get_time_fast();
446 #endif
449 int cpu_inb(CPUState *env, int addr)
451 int val;
452 val = ioport_read(0, addr);
453 #ifdef DEBUG_IOPORT
454 if (loglevel & CPU_LOG_IOPORT)
455 fprintf(logfile, "inb : %04x %02x\n", addr, val);
456 #endif
457 #ifdef USE_KQEMU
458 if (env)
459 env->last_io_time = cpu_get_time_fast();
460 #endif
461 return val;
464 int cpu_inw(CPUState *env, int addr)
466 int val;
467 val = ioport_read(1, addr);
468 #ifdef DEBUG_IOPORT
469 if (loglevel & CPU_LOG_IOPORT)
470 fprintf(logfile, "inw : %04x %04x\n", addr, val);
471 #endif
472 #ifdef USE_KQEMU
473 if (env)
474 env->last_io_time = cpu_get_time_fast();
475 #endif
476 return val;
479 int cpu_inl(CPUState *env, int addr)
481 int val;
482 val = ioport_read(2, addr);
483 #ifdef DEBUG_IOPORT
484 if (loglevel & CPU_LOG_IOPORT)
485 fprintf(logfile, "inl : %04x %08x\n", addr, val);
486 #endif
487 #ifdef USE_KQEMU
488 if (env)
489 env->last_io_time = cpu_get_time_fast();
490 #endif
491 return val;
494 /***********************************************************/
495 void hw_error(const char *fmt, ...)
497 va_list ap;
498 CPUState *env;
500 va_start(ap, fmt);
501 fprintf(stderr, "qemu: hardware error: ");
502 vfprintf(stderr, fmt, ap);
503 fprintf(stderr, "\n");
504 for(env = first_cpu; env != NULL; env = env->next_cpu) {
505 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
506 #ifdef TARGET_I386
507 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
508 #else
509 cpu_dump_state(env, stderr, fprintf, 0);
510 #endif
512 va_end(ap);
513 abort();
516 /***********************************************************/
517 /* keyboard/mouse */
519 static QEMUPutKBDEvent *qemu_put_kbd_event;
520 static void *qemu_put_kbd_event_opaque;
521 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
522 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
524 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
526 qemu_put_kbd_event_opaque = opaque;
527 qemu_put_kbd_event = func;
530 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
531 void *opaque, int absolute,
532 const char *name)
534 QEMUPutMouseEntry *s, *cursor;
536 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
537 if (!s)
538 return NULL;
540 s->qemu_put_mouse_event = func;
541 s->qemu_put_mouse_event_opaque = opaque;
542 s->qemu_put_mouse_event_absolute = absolute;
543 s->qemu_put_mouse_event_name = qemu_strdup(name);
544 s->next = NULL;
546 if (!qemu_put_mouse_event_head) {
547 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
548 return s;
551 cursor = qemu_put_mouse_event_head;
552 while (cursor->next != NULL)
553 cursor = cursor->next;
555 cursor->next = s;
556 qemu_put_mouse_event_current = s;
558 return s;
561 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
563 QEMUPutMouseEntry *prev = NULL, *cursor;
565 if (!qemu_put_mouse_event_head || entry == NULL)
566 return;
568 cursor = qemu_put_mouse_event_head;
569 while (cursor != NULL && cursor != entry) {
570 prev = cursor;
571 cursor = cursor->next;
574 if (cursor == NULL) // does not exist or list empty
575 return;
576 else if (prev == NULL) { // entry is head
577 qemu_put_mouse_event_head = cursor->next;
578 if (qemu_put_mouse_event_current == entry)
579 qemu_put_mouse_event_current = cursor->next;
580 qemu_free(entry->qemu_put_mouse_event_name);
581 qemu_free(entry);
582 return;
585 prev->next = entry->next;
587 if (qemu_put_mouse_event_current == entry)
588 qemu_put_mouse_event_current = prev;
590 qemu_free(entry->qemu_put_mouse_event_name);
591 qemu_free(entry);
594 void kbd_put_keycode(int keycode)
596 if (qemu_put_kbd_event) {
597 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
601 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
603 QEMUPutMouseEvent *mouse_event;
604 void *mouse_event_opaque;
605 int width;
607 if (!qemu_put_mouse_event_current) {
608 return;
611 mouse_event =
612 qemu_put_mouse_event_current->qemu_put_mouse_event;
613 mouse_event_opaque =
614 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
616 if (mouse_event) {
617 if (graphic_rotate) {
618 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
619 width = 0x7fff;
620 else
621 width = graphic_width - 1;
622 mouse_event(mouse_event_opaque,
623 width - dy, dx, dz, buttons_state);
624 } else
625 mouse_event(mouse_event_opaque,
626 dx, dy, dz, buttons_state);
630 int kbd_mouse_is_absolute(void)
632 if (!qemu_put_mouse_event_current)
633 return 0;
635 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
638 void do_info_mice(void)
640 QEMUPutMouseEntry *cursor;
641 int index = 0;
643 if (!qemu_put_mouse_event_head) {
644 term_printf("No mouse devices connected\n");
645 return;
648 term_printf("Mouse devices available:\n");
649 cursor = qemu_put_mouse_event_head;
650 while (cursor != NULL) {
651 term_printf("%c Mouse #%d: %s\n",
652 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
653 index, cursor->qemu_put_mouse_event_name);
654 index++;
655 cursor = cursor->next;
659 void do_mouse_set(int index)
661 QEMUPutMouseEntry *cursor;
662 int i = 0;
664 if (!qemu_put_mouse_event_head) {
665 term_printf("No mouse devices connected\n");
666 return;
669 cursor = qemu_put_mouse_event_head;
670 while (cursor != NULL && index != i) {
671 i++;
672 cursor = cursor->next;
675 if (cursor != NULL)
676 qemu_put_mouse_event_current = cursor;
677 else
678 term_printf("Mouse at given index not found\n");
681 /* compute with 96 bit intermediate result: (a*b)/c */
682 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
684 union {
685 uint64_t ll;
686 struct {
687 #ifdef WORDS_BIGENDIAN
688 uint32_t high, low;
689 #else
690 uint32_t low, high;
691 #endif
692 } l;
693 } u, res;
694 uint64_t rl, rh;
696 u.ll = a;
697 rl = (uint64_t)u.l.low * (uint64_t)b;
698 rh = (uint64_t)u.l.high * (uint64_t)b;
699 rh += (rl >> 32);
700 res.l.high = rh / c;
701 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
702 return res.ll;
705 /***********************************************************/
706 /* real time host monotonic timer */
708 #define QEMU_TIMER_BASE 1000000000LL
710 #ifdef WIN32
712 static int64_t clock_freq;
714 static void init_get_clock(void)
716 LARGE_INTEGER freq;
717 int ret;
718 ret = QueryPerformanceFrequency(&freq);
719 if (ret == 0) {
720 fprintf(stderr, "Could not calibrate ticks\n");
721 exit(1);
723 clock_freq = freq.QuadPart;
726 static int64_t get_clock(void)
728 LARGE_INTEGER ti;
729 QueryPerformanceCounter(&ti);
730 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
733 #else
735 static int use_rt_clock;
737 static void init_get_clock(void)
739 use_rt_clock = 0;
740 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
742 struct timespec ts;
743 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
744 use_rt_clock = 1;
747 #endif
750 static int64_t get_clock(void)
752 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
753 if (use_rt_clock) {
754 struct timespec ts;
755 clock_gettime(CLOCK_MONOTONIC, &ts);
756 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
757 } else
758 #endif
760 /* XXX: using gettimeofday leads to problems if the date
761 changes, so it should be avoided. */
762 struct timeval tv;
763 gettimeofday(&tv, NULL);
764 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
767 #endif
769 /* Return the virtual CPU time, based on the instruction counter. */
770 static int64_t cpu_get_icount(void)
772 int64_t icount;
773 CPUState *env = cpu_single_env;;
774 icount = qemu_icount;
775 if (env) {
776 if (!can_do_io(env))
777 fprintf(stderr, "Bad clock read\n");
778 icount -= (env->icount_decr.u16.low + env->icount_extra);
780 return qemu_icount_bias + (icount << icount_time_shift);
783 /***********************************************************/
784 /* guest cycle counter */
786 static int64_t cpu_ticks_prev;
787 static int64_t cpu_ticks_offset;
788 static int64_t cpu_clock_offset;
789 static int cpu_ticks_enabled;
791 /* return the host CPU cycle counter and handle stop/restart */
792 int64_t cpu_get_ticks(void)
794 if (use_icount) {
795 return cpu_get_icount();
797 if (!cpu_ticks_enabled) {
798 return cpu_ticks_offset;
799 } else {
800 int64_t ticks;
801 ticks = cpu_get_real_ticks();
802 if (cpu_ticks_prev > ticks) {
803 /* Note: non increasing ticks may happen if the host uses
804 software suspend */
805 cpu_ticks_offset += cpu_ticks_prev - ticks;
807 cpu_ticks_prev = ticks;
808 return ticks + cpu_ticks_offset;
812 /* return the host CPU monotonic timer and handle stop/restart */
813 static int64_t cpu_get_clock(void)
815 int64_t ti;
816 if (!cpu_ticks_enabled) {
817 return cpu_clock_offset;
818 } else {
819 ti = get_clock();
820 return ti + cpu_clock_offset;
824 /* enable cpu_get_ticks() */
825 void cpu_enable_ticks(void)
827 if (!cpu_ticks_enabled) {
828 cpu_ticks_offset -= cpu_get_real_ticks();
829 cpu_clock_offset -= get_clock();
830 cpu_ticks_enabled = 1;
834 /* disable cpu_get_ticks() : the clock is stopped. You must not call
835 cpu_get_ticks() after that. */
836 void cpu_disable_ticks(void)
838 if (cpu_ticks_enabled) {
839 cpu_ticks_offset = cpu_get_ticks();
840 cpu_clock_offset = cpu_get_clock();
841 cpu_ticks_enabled = 0;
845 /***********************************************************/
846 /* timers */
848 #define QEMU_TIMER_REALTIME 0
849 #define QEMU_TIMER_VIRTUAL 1
851 struct QEMUClock {
852 int type;
853 /* XXX: add frequency */
856 struct QEMUTimer {
857 QEMUClock *clock;
858 int64_t expire_time;
859 QEMUTimerCB *cb;
860 void *opaque;
861 struct QEMUTimer *next;
864 struct qemu_alarm_timer {
865 char const *name;
866 unsigned int flags;
868 int (*start)(struct qemu_alarm_timer *t);
869 void (*stop)(struct qemu_alarm_timer *t);
870 void (*rearm)(struct qemu_alarm_timer *t);
871 void *priv;
874 #define ALARM_FLAG_DYNTICKS 0x1
875 #define ALARM_FLAG_EXPIRED 0x2
877 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
879 return t->flags & ALARM_FLAG_DYNTICKS;
882 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
884 if (!alarm_has_dynticks(t))
885 return;
887 t->rearm(t);
890 /* TODO: MIN_TIMER_REARM_US should be optimized */
891 #define MIN_TIMER_REARM_US 250
893 static struct qemu_alarm_timer *alarm_timer;
894 #ifndef _WIN32
895 static int alarm_timer_rfd, alarm_timer_wfd;
896 #endif
898 #ifdef _WIN32
900 struct qemu_alarm_win32 {
901 MMRESULT timerId;
902 HANDLE host_alarm;
903 unsigned int period;
904 } alarm_win32_data = {0, NULL, -1};
906 static int win32_start_timer(struct qemu_alarm_timer *t);
907 static void win32_stop_timer(struct qemu_alarm_timer *t);
908 static void win32_rearm_timer(struct qemu_alarm_timer *t);
910 #else
912 static int unix_start_timer(struct qemu_alarm_timer *t);
913 static void unix_stop_timer(struct qemu_alarm_timer *t);
915 #ifdef __linux__
917 static int dynticks_start_timer(struct qemu_alarm_timer *t);
918 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
919 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
921 static int hpet_start_timer(struct qemu_alarm_timer *t);
922 static void hpet_stop_timer(struct qemu_alarm_timer *t);
924 static int rtc_start_timer(struct qemu_alarm_timer *t);
925 static void rtc_stop_timer(struct qemu_alarm_timer *t);
927 #endif /* __linux__ */
929 #endif /* _WIN32 */
931 /* Correlation between real and virtual time is always going to be
932 fairly approximate, so ignore small variation.
933 When the guest is idle real and virtual time will be aligned in
934 the IO wait loop. */
935 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
937 static void icount_adjust(void)
939 int64_t cur_time;
940 int64_t cur_icount;
941 int64_t delta;
942 static int64_t last_delta;
943 /* If the VM is not running, then do nothing. */
944 if (!vm_running)
945 return;
947 cur_time = cpu_get_clock();
948 cur_icount = qemu_get_clock(vm_clock);
949 delta = cur_icount - cur_time;
950 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
951 if (delta > 0
952 && last_delta + ICOUNT_WOBBLE < delta * 2
953 && icount_time_shift > 0) {
954 /* The guest is getting too far ahead. Slow time down. */
955 icount_time_shift--;
957 if (delta < 0
958 && last_delta - ICOUNT_WOBBLE > delta * 2
959 && icount_time_shift < MAX_ICOUNT_SHIFT) {
960 /* The guest is getting too far behind. Speed time up. */
961 icount_time_shift++;
963 last_delta = delta;
964 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
967 static void icount_adjust_rt(void * opaque)
969 qemu_mod_timer(icount_rt_timer,
970 qemu_get_clock(rt_clock) + 1000);
971 icount_adjust();
974 static void icount_adjust_vm(void * opaque)
976 qemu_mod_timer(icount_vm_timer,
977 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
978 icount_adjust();
981 static void init_icount_adjust(void)
983 /* Have both realtime and virtual time triggers for speed adjustment.
984 The realtime trigger catches emulated time passing too slowly,
985 the virtual time trigger catches emulated time passing too fast.
986 Realtime triggers occur even when idle, so use them less frequently
987 than VM triggers. */
988 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
989 qemu_mod_timer(icount_rt_timer,
990 qemu_get_clock(rt_clock) + 1000);
991 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
992 qemu_mod_timer(icount_vm_timer,
993 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
996 static struct qemu_alarm_timer alarm_timers[] = {
997 #ifndef _WIN32
998 #ifdef __linux__
999 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1000 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1001 /* HPET - if available - is preferred */
1002 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1003 /* ...otherwise try RTC */
1004 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1005 #endif
1006 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1007 #else
1008 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1009 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1010 {"win32", 0, win32_start_timer,
1011 win32_stop_timer, NULL, &alarm_win32_data},
1012 #endif
1013 {NULL, }
1016 static void show_available_alarms(void)
1018 int i;
1020 printf("Available alarm timers, in order of precedence:\n");
1021 for (i = 0; alarm_timers[i].name; i++)
1022 printf("%s\n", alarm_timers[i].name);
1025 static void configure_alarms(char const *opt)
1027 int i;
1028 int cur = 0;
1029 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1030 char *arg;
1031 char *name;
1032 struct qemu_alarm_timer tmp;
1034 if (!strcmp(opt, "?")) {
1035 show_available_alarms();
1036 exit(0);
1039 arg = strdup(opt);
1041 /* Reorder the array */
1042 name = strtok(arg, ",");
1043 while (name) {
1044 for (i = 0; i < count && alarm_timers[i].name; i++) {
1045 if (!strcmp(alarm_timers[i].name, name))
1046 break;
1049 if (i == count) {
1050 fprintf(stderr, "Unknown clock %s\n", name);
1051 goto next;
1054 if (i < cur)
1055 /* Ignore */
1056 goto next;
1058 /* Swap */
1059 tmp = alarm_timers[i];
1060 alarm_timers[i] = alarm_timers[cur];
1061 alarm_timers[cur] = tmp;
1063 cur++;
1064 next:
1065 name = strtok(NULL, ",");
1068 free(arg);
1070 if (cur) {
1071 /* Disable remaining timers */
1072 for (i = cur; i < count; i++)
1073 alarm_timers[i].name = NULL;
1074 } else {
1075 show_available_alarms();
1076 exit(1);
1080 QEMUClock *rt_clock;
1081 QEMUClock *vm_clock;
1083 static QEMUTimer *active_timers[2];
1085 static QEMUClock *qemu_new_clock(int type)
1087 QEMUClock *clock;
1088 clock = qemu_mallocz(sizeof(QEMUClock));
1089 if (!clock)
1090 return NULL;
1091 clock->type = type;
1092 return clock;
1095 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1097 QEMUTimer *ts;
1099 ts = qemu_mallocz(sizeof(QEMUTimer));
1100 ts->clock = clock;
1101 ts->cb = cb;
1102 ts->opaque = opaque;
1103 return ts;
1106 void qemu_free_timer(QEMUTimer *ts)
1108 qemu_free(ts);
1111 /* stop a timer, but do not dealloc it */
1112 void qemu_del_timer(QEMUTimer *ts)
1114 QEMUTimer **pt, *t;
1116 /* NOTE: this code must be signal safe because
1117 qemu_timer_expired() can be called from a signal. */
1118 pt = &active_timers[ts->clock->type];
1119 for(;;) {
1120 t = *pt;
1121 if (!t)
1122 break;
1123 if (t == ts) {
1124 *pt = t->next;
1125 break;
1127 pt = &t->next;
1131 /* modify the current timer so that it will be fired when current_time
1132 >= expire_time. The corresponding callback will be called. */
1133 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1135 QEMUTimer **pt, *t;
1137 qemu_del_timer(ts);
1139 /* add the timer in the sorted list */
1140 /* NOTE: this code must be signal safe because
1141 qemu_timer_expired() can be called from a signal. */
1142 pt = &active_timers[ts->clock->type];
1143 for(;;) {
1144 t = *pt;
1145 if (!t)
1146 break;
1147 if (t->expire_time > expire_time)
1148 break;
1149 pt = &t->next;
1151 ts->expire_time = expire_time;
1152 ts->next = *pt;
1153 *pt = ts;
1155 /* Rearm if necessary */
1156 if (pt == &active_timers[ts->clock->type]) {
1157 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1158 qemu_rearm_alarm_timer(alarm_timer);
1160 /* Interrupt execution to force deadline recalculation. */
1161 if (use_icount && cpu_single_env) {
1162 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1167 int qemu_timer_pending(QEMUTimer *ts)
1169 QEMUTimer *t;
1170 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1171 if (t == ts)
1172 return 1;
1174 return 0;
1177 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1179 if (!timer_head)
1180 return 0;
1181 return (timer_head->expire_time <= current_time);
1184 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1186 QEMUTimer *ts;
1188 for(;;) {
1189 ts = *ptimer_head;
1190 if (!ts || ts->expire_time > current_time)
1191 break;
1192 /* remove timer from the list before calling the callback */
1193 *ptimer_head = ts->next;
1194 ts->next = NULL;
1196 /* run the callback (the timer list can be modified) */
1197 ts->cb(ts->opaque);
1201 int64_t qemu_get_clock(QEMUClock *clock)
1203 switch(clock->type) {
1204 case QEMU_TIMER_REALTIME:
1205 return get_clock() / 1000000;
1206 default:
1207 case QEMU_TIMER_VIRTUAL:
1208 if (use_icount) {
1209 return cpu_get_icount();
1210 } else {
1211 return cpu_get_clock();
1216 static void init_timers(void)
1218 init_get_clock();
1219 ticks_per_sec = QEMU_TIMER_BASE;
1220 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1221 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1224 /* save a timer */
1225 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1227 uint64_t expire_time;
1229 if (qemu_timer_pending(ts)) {
1230 expire_time = ts->expire_time;
1231 } else {
1232 expire_time = -1;
1234 qemu_put_be64(f, expire_time);
1237 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1239 uint64_t expire_time;
1241 expire_time = qemu_get_be64(f);
1242 if (expire_time != -1) {
1243 qemu_mod_timer(ts, expire_time);
1244 } else {
1245 qemu_del_timer(ts);
1249 static void timer_save(QEMUFile *f, void *opaque)
1251 if (cpu_ticks_enabled) {
1252 hw_error("cannot save state if virtual timers are running");
1254 qemu_put_be64(f, cpu_ticks_offset);
1255 qemu_put_be64(f, ticks_per_sec);
1256 qemu_put_be64(f, cpu_clock_offset);
1259 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1261 if (version_id != 1 && version_id != 2)
1262 return -EINVAL;
1263 if (cpu_ticks_enabled) {
1264 return -EINVAL;
1266 cpu_ticks_offset=qemu_get_be64(f);
1267 ticks_per_sec=qemu_get_be64(f);
1268 if (version_id == 2) {
1269 cpu_clock_offset=qemu_get_be64(f);
1271 return 0;
1274 #ifdef _WIN32
1275 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1276 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1277 #else
1278 static void host_alarm_handler(int host_signum)
1279 #endif
1281 #if 0
1282 #define DISP_FREQ 1000
1284 static int64_t delta_min = INT64_MAX;
1285 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1286 static int count;
1287 ti = qemu_get_clock(vm_clock);
1288 if (last_clock != 0) {
1289 delta = ti - last_clock;
1290 if (delta < delta_min)
1291 delta_min = delta;
1292 if (delta > delta_max)
1293 delta_max = delta;
1294 delta_cum += delta;
1295 if (++count == DISP_FREQ) {
1296 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1297 muldiv64(delta_min, 1000000, ticks_per_sec),
1298 muldiv64(delta_max, 1000000, ticks_per_sec),
1299 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1300 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1301 count = 0;
1302 delta_min = INT64_MAX;
1303 delta_max = 0;
1304 delta_cum = 0;
1307 last_clock = ti;
1309 #endif
1310 if (alarm_has_dynticks(alarm_timer) ||
1311 (!use_icount &&
1312 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1313 qemu_get_clock(vm_clock))) ||
1314 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1315 qemu_get_clock(rt_clock))) {
1316 CPUState *env = next_cpu;
1318 #ifdef _WIN32
1319 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1320 SetEvent(data->host_alarm);
1321 #else
1322 static const char byte = 0;
1323 write(alarm_timer_wfd, &byte, sizeof(byte));
1324 #endif
1325 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1327 if (env) {
1328 /* stop the currently executing cpu because a timer occured */
1329 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1330 #ifdef USE_KQEMU
1331 if (env->kqemu_enabled) {
1332 kqemu_cpu_interrupt(env);
1334 #endif
1336 event_pending = 1;
1340 static int64_t qemu_next_deadline(void)
1342 int64_t delta;
1344 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1345 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1346 qemu_get_clock(vm_clock);
1347 } else {
1348 /* To avoid problems with overflow limit this to 2^32. */
1349 delta = INT32_MAX;
1352 if (delta < 0)
1353 delta = 0;
1355 return delta;
1358 #if defined(__linux__) || defined(_WIN32)
1359 static uint64_t qemu_next_deadline_dyntick(void)
1361 int64_t delta;
1362 int64_t rtdelta;
1364 if (use_icount)
1365 delta = INT32_MAX;
1366 else
1367 delta = (qemu_next_deadline() + 999) / 1000;
1369 if (active_timers[QEMU_TIMER_REALTIME]) {
1370 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1371 qemu_get_clock(rt_clock))*1000;
1372 if (rtdelta < delta)
1373 delta = rtdelta;
1376 if (delta < MIN_TIMER_REARM_US)
1377 delta = MIN_TIMER_REARM_US;
1379 return delta;
1381 #endif
1383 #ifndef _WIN32
1385 /* Sets a specific flag */
1386 static int fcntl_setfl(int fd, int flag)
1388 int flags;
1390 flags = fcntl(fd, F_GETFL);
1391 if (flags == -1)
1392 return -errno;
1394 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1395 return -errno;
1397 return 0;
1400 #if defined(__linux__)
1402 #define RTC_FREQ 1024
1404 static void enable_sigio_timer(int fd)
1406 struct sigaction act;
1408 /* timer signal */
1409 sigfillset(&act.sa_mask);
1410 act.sa_flags = 0;
1411 act.sa_handler = host_alarm_handler;
1413 sigaction(SIGIO, &act, NULL);
1414 fcntl_setfl(fd, O_ASYNC);
1415 fcntl(fd, F_SETOWN, getpid());
1418 static int hpet_start_timer(struct qemu_alarm_timer *t)
1420 struct hpet_info info;
1421 int r, fd;
1423 fd = open("/dev/hpet", O_RDONLY);
1424 if (fd < 0)
1425 return -1;
1427 /* Set frequency */
1428 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1429 if (r < 0) {
1430 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1431 "error, but for better emulation accuracy type:\n"
1432 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1433 goto fail;
1436 /* Check capabilities */
1437 r = ioctl(fd, HPET_INFO, &info);
1438 if (r < 0)
1439 goto fail;
1441 /* Enable periodic mode */
1442 r = ioctl(fd, HPET_EPI, 0);
1443 if (info.hi_flags && (r < 0))
1444 goto fail;
1446 /* Enable interrupt */
1447 r = ioctl(fd, HPET_IE_ON, 0);
1448 if (r < 0)
1449 goto fail;
1451 enable_sigio_timer(fd);
1452 t->priv = (void *)(long)fd;
1454 return 0;
1455 fail:
1456 close(fd);
1457 return -1;
1460 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1462 int fd = (long)t->priv;
1464 close(fd);
1467 static int rtc_start_timer(struct qemu_alarm_timer *t)
1469 int rtc_fd;
1470 unsigned long current_rtc_freq = 0;
1472 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1473 if (rtc_fd < 0)
1474 return -1;
1475 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1476 if (current_rtc_freq != RTC_FREQ &&
1477 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1478 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1479 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1480 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1481 goto fail;
1483 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1484 fail:
1485 close(rtc_fd);
1486 return -1;
1489 enable_sigio_timer(rtc_fd);
1491 t->priv = (void *)(long)rtc_fd;
1493 return 0;
1496 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1498 int rtc_fd = (long)t->priv;
1500 close(rtc_fd);
1503 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1505 struct sigevent ev;
1506 timer_t host_timer;
1507 struct sigaction act;
1509 sigfillset(&act.sa_mask);
1510 act.sa_flags = 0;
1511 act.sa_handler = host_alarm_handler;
1513 sigaction(SIGALRM, &act, NULL);
1515 ev.sigev_value.sival_int = 0;
1516 ev.sigev_notify = SIGEV_SIGNAL;
1517 ev.sigev_signo = SIGALRM;
1519 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1520 perror("timer_create");
1522 /* disable dynticks */
1523 fprintf(stderr, "Dynamic Ticks disabled\n");
1525 return -1;
1528 t->priv = (void *)host_timer;
1530 return 0;
1533 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1535 timer_t host_timer = (timer_t)t->priv;
1537 timer_delete(host_timer);
1540 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1542 timer_t host_timer = (timer_t)t->priv;
1543 struct itimerspec timeout;
1544 int64_t nearest_delta_us = INT64_MAX;
1545 int64_t current_us;
1547 if (!active_timers[QEMU_TIMER_REALTIME] &&
1548 !active_timers[QEMU_TIMER_VIRTUAL])
1549 return;
1551 nearest_delta_us = qemu_next_deadline_dyntick();
1553 /* check whether a timer is already running */
1554 if (timer_gettime(host_timer, &timeout)) {
1555 perror("gettime");
1556 fprintf(stderr, "Internal timer error: aborting\n");
1557 exit(1);
1559 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1560 if (current_us && current_us <= nearest_delta_us)
1561 return;
1563 timeout.it_interval.tv_sec = 0;
1564 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1565 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1566 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1567 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1568 perror("settime");
1569 fprintf(stderr, "Internal timer error: aborting\n");
1570 exit(1);
1574 #endif /* defined(__linux__) */
1576 static int unix_start_timer(struct qemu_alarm_timer *t)
1578 struct sigaction act;
1579 struct itimerval itv;
1580 int err;
1582 /* timer signal */
1583 sigfillset(&act.sa_mask);
1584 act.sa_flags = 0;
1585 act.sa_handler = host_alarm_handler;
1587 sigaction(SIGALRM, &act, NULL);
1589 itv.it_interval.tv_sec = 0;
1590 /* for i386 kernel 2.6 to get 1 ms */
1591 itv.it_interval.tv_usec = 999;
1592 itv.it_value.tv_sec = 0;
1593 itv.it_value.tv_usec = 10 * 1000;
1595 err = setitimer(ITIMER_REAL, &itv, NULL);
1596 if (err)
1597 return -1;
1599 return 0;
1602 static void unix_stop_timer(struct qemu_alarm_timer *t)
1604 struct itimerval itv;
1606 memset(&itv, 0, sizeof(itv));
1607 setitimer(ITIMER_REAL, &itv, NULL);
1610 #endif /* !defined(_WIN32) */
1612 static void try_to_rearm_timer(void *opaque)
1614 struct qemu_alarm_timer *t = opaque;
1615 #ifndef _WIN32
1616 ssize_t len;
1618 /* Drain the notify pipe */
1619 do {
1620 char buffer[512];
1621 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1622 } while ((len == -1 && errno == EINTR) || len > 0);
1623 #endif
1625 /* vm time timers */
1626 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
1627 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
1628 qemu_get_clock(vm_clock));
1630 /* real time timers */
1631 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
1632 qemu_get_clock(rt_clock));
1634 if (t->flags & ALARM_FLAG_EXPIRED) {
1635 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1636 qemu_rearm_alarm_timer(alarm_timer);
1640 #ifdef _WIN32
1642 static int win32_start_timer(struct qemu_alarm_timer *t)
1644 TIMECAPS tc;
1645 struct qemu_alarm_win32 *data = t->priv;
1646 UINT flags;
1648 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1649 if (!data->host_alarm) {
1650 perror("Failed CreateEvent");
1651 return -1;
1654 memset(&tc, 0, sizeof(tc));
1655 timeGetDevCaps(&tc, sizeof(tc));
1657 if (data->period < tc.wPeriodMin)
1658 data->period = tc.wPeriodMin;
1660 timeBeginPeriod(data->period);
1662 flags = TIME_CALLBACK_FUNCTION;
1663 if (alarm_has_dynticks(t))
1664 flags |= TIME_ONESHOT;
1665 else
1666 flags |= TIME_PERIODIC;
1668 data->timerId = timeSetEvent(1, // interval (ms)
1669 data->period, // resolution
1670 host_alarm_handler, // function
1671 (DWORD)t, // parameter
1672 flags);
1674 if (!data->timerId) {
1675 perror("Failed to initialize win32 alarm timer");
1677 timeEndPeriod(data->period);
1678 CloseHandle(data->host_alarm);
1679 return -1;
1682 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1684 return 0;
1687 static void win32_stop_timer(struct qemu_alarm_timer *t)
1689 struct qemu_alarm_win32 *data = t->priv;
1691 timeKillEvent(data->timerId);
1692 timeEndPeriod(data->period);
1694 CloseHandle(data->host_alarm);
1697 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1699 struct qemu_alarm_win32 *data = t->priv;
1700 uint64_t nearest_delta_us;
1702 if (!active_timers[QEMU_TIMER_REALTIME] &&
1703 !active_timers[QEMU_TIMER_VIRTUAL])
1704 return;
1706 nearest_delta_us = qemu_next_deadline_dyntick();
1707 nearest_delta_us /= 1000;
1709 timeKillEvent(data->timerId);
1711 data->timerId = timeSetEvent(1,
1712 data->period,
1713 host_alarm_handler,
1714 (DWORD)t,
1715 TIME_ONESHOT | TIME_PERIODIC);
1717 if (!data->timerId) {
1718 perror("Failed to re-arm win32 alarm timer");
1720 timeEndPeriod(data->period);
1721 CloseHandle(data->host_alarm);
1722 exit(1);
1726 #endif /* _WIN32 */
1728 static int init_timer_alarm(void)
1730 struct qemu_alarm_timer *t = NULL;
1731 int i, err = -1;
1733 #ifndef _WIN32
1734 int fds[2];
1736 err = pipe(fds);
1737 if (err == -1)
1738 return -errno;
1740 err = fcntl_setfl(fds[0], O_NONBLOCK);
1741 if (err < 0)
1742 goto fail;
1744 err = fcntl_setfl(fds[1], O_NONBLOCK);
1745 if (err < 0)
1746 goto fail;
1748 alarm_timer_rfd = fds[0];
1749 alarm_timer_wfd = fds[1];
1750 #endif
1752 for (i = 0; alarm_timers[i].name; i++) {
1753 t = &alarm_timers[i];
1755 err = t->start(t);
1756 if (!err)
1757 break;
1760 if (err) {
1761 err = -ENOENT;
1762 goto fail;
1765 #ifndef _WIN32
1766 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1767 try_to_rearm_timer, NULL, t);
1768 #endif
1770 alarm_timer = t;
1772 return 0;
1774 fail:
1775 #ifndef _WIN32
1776 close(fds[0]);
1777 close(fds[1]);
1778 #endif
1779 return err;
1782 static void quit_timers(void)
1784 alarm_timer->stop(alarm_timer);
1785 alarm_timer = NULL;
1788 /***********************************************************/
1789 /* host time/date access */
1790 void qemu_get_timedate(struct tm *tm, int offset)
1792 time_t ti;
1793 struct tm *ret;
1795 time(&ti);
1796 ti += offset;
1797 if (rtc_date_offset == -1) {
1798 if (rtc_utc)
1799 ret = gmtime(&ti);
1800 else
1801 ret = localtime(&ti);
1802 } else {
1803 ti -= rtc_date_offset;
1804 ret = gmtime(&ti);
1807 memcpy(tm, ret, sizeof(struct tm));
1810 int qemu_timedate_diff(struct tm *tm)
1812 time_t seconds;
1814 if (rtc_date_offset == -1)
1815 if (rtc_utc)
1816 seconds = mktimegm(tm);
1817 else
1818 seconds = mktime(tm);
1819 else
1820 seconds = mktimegm(tm) + rtc_date_offset;
1822 return seconds - time(NULL);
1825 #ifdef _WIN32
1826 static void socket_cleanup(void)
1828 WSACleanup();
1831 static int socket_init(void)
1833 WSADATA Data;
1834 int ret, err;
1836 ret = WSAStartup(MAKEWORD(2,2), &Data);
1837 if (ret != 0) {
1838 err = WSAGetLastError();
1839 fprintf(stderr, "WSAStartup: %d\n", err);
1840 return -1;
1842 atexit(socket_cleanup);
1843 return 0;
1845 #endif
1847 const char *get_opt_name(char *buf, int buf_size, const char *p)
1849 char *q;
1851 q = buf;
1852 while (*p != '\0' && *p != '=') {
1853 if (q && (q - buf) < buf_size - 1)
1854 *q++ = *p;
1855 p++;
1857 if (q)
1858 *q = '\0';
1860 return p;
1863 const char *get_opt_value(char *buf, int buf_size, const char *p)
1865 char *q;
1867 q = buf;
1868 while (*p != '\0') {
1869 if (*p == ',') {
1870 if (*(p + 1) != ',')
1871 break;
1872 p++;
1874 if (q && (q - buf) < buf_size - 1)
1875 *q++ = *p;
1876 p++;
1878 if (q)
1879 *q = '\0';
1881 return p;
1884 int get_param_value(char *buf, int buf_size,
1885 const char *tag, const char *str)
1887 const char *p;
1888 char option[128];
1890 p = str;
1891 for(;;) {
1892 p = get_opt_name(option, sizeof(option), p);
1893 if (*p != '=')
1894 break;
1895 p++;
1896 if (!strcmp(tag, option)) {
1897 (void)get_opt_value(buf, buf_size, p);
1898 return strlen(buf);
1899 } else {
1900 p = get_opt_value(NULL, 0, p);
1902 if (*p != ',')
1903 break;
1904 p++;
1906 return 0;
1909 int check_params(char *buf, int buf_size,
1910 const char * const *params, const char *str)
1912 const char *p;
1913 int i;
1915 p = str;
1916 for(;;) {
1917 p = get_opt_name(buf, buf_size, p);
1918 if (*p != '=')
1919 return -1;
1920 p++;
1921 for(i = 0; params[i] != NULL; i++)
1922 if (!strcmp(params[i], buf))
1923 break;
1924 if (params[i] == NULL)
1925 return -1;
1926 p = get_opt_value(NULL, 0, p);
1927 if (*p != ',')
1928 break;
1929 p++;
1931 return 0;
1934 /***********************************************************/
1935 /* Bluetooth support */
1936 static int nb_hcis;
1937 static int cur_hci;
1938 static struct HCIInfo *hci_table[MAX_NICS];
1940 static struct bt_vlan_s {
1941 struct bt_scatternet_s net;
1942 int id;
1943 struct bt_vlan_s *next;
1944 } *first_bt_vlan;
1946 /* find or alloc a new bluetooth "VLAN" */
1947 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1949 struct bt_vlan_s **pvlan, *vlan;
1950 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1951 if (vlan->id == id)
1952 return &vlan->net;
1954 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1955 vlan->id = id;
1956 pvlan = &first_bt_vlan;
1957 while (*pvlan != NULL)
1958 pvlan = &(*pvlan)->next;
1959 *pvlan = vlan;
1960 return &vlan->net;
1963 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1967 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1969 return -ENOTSUP;
1972 static struct HCIInfo null_hci = {
1973 .cmd_send = null_hci_send,
1974 .sco_send = null_hci_send,
1975 .acl_send = null_hci_send,
1976 .bdaddr_set = null_hci_addr_set,
1979 struct HCIInfo *qemu_next_hci(void)
1981 if (cur_hci == nb_hcis)
1982 return &null_hci;
1984 return hci_table[cur_hci++];
1987 static struct HCIInfo *hci_init(const char *str)
1989 char *endp;
1990 struct bt_scatternet_s *vlan = 0;
1992 if (!strcmp(str, "null"))
1993 /* null */
1994 return &null_hci;
1995 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1996 /* host[:hciN] */
1997 return bt_host_hci(str[4] ? str + 5 : "hci0");
1998 else if (!strncmp(str, "hci", 3)) {
1999 /* hci[,vlan=n] */
2000 if (str[3]) {
2001 if (!strncmp(str + 3, ",vlan=", 6)) {
2002 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2003 if (*endp)
2004 vlan = 0;
2006 } else
2007 vlan = qemu_find_bt_vlan(0);
2008 if (vlan)
2009 return bt_new_hci(vlan);
2012 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2014 return 0;
2017 static int bt_hci_parse(const char *str)
2019 struct HCIInfo *hci;
2020 bdaddr_t bdaddr;
2022 if (nb_hcis >= MAX_NICS) {
2023 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2024 return -1;
2027 hci = hci_init(str);
2028 if (!hci)
2029 return -1;
2031 bdaddr.b[0] = 0x52;
2032 bdaddr.b[1] = 0x54;
2033 bdaddr.b[2] = 0x00;
2034 bdaddr.b[3] = 0x12;
2035 bdaddr.b[4] = 0x34;
2036 bdaddr.b[5] = 0x56 + nb_hcis;
2037 hci->bdaddr_set(hci, bdaddr.b);
2039 hci_table[nb_hcis++] = hci;
2041 return 0;
2044 static void bt_vhci_add(int vlan_id)
2046 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2048 if (!vlan->slave)
2049 fprintf(stderr, "qemu: warning: adding a VHCI to "
2050 "an empty scatternet %i\n", vlan_id);
2052 bt_vhci_init(bt_new_hci(vlan));
2055 static struct bt_device_s *bt_device_add(const char *opt)
2057 struct bt_scatternet_s *vlan;
2058 int vlan_id = 0;
2059 char *endp = strstr(opt, ",vlan=");
2060 int len = (endp ? endp - opt : strlen(opt)) + 1;
2061 char devname[10];
2063 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2065 if (endp) {
2066 vlan_id = strtol(endp + 6, &endp, 0);
2067 if (*endp) {
2068 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2069 return 0;
2073 vlan = qemu_find_bt_vlan(vlan_id);
2075 if (!vlan->slave)
2076 fprintf(stderr, "qemu: warning: adding a slave device to "
2077 "an empty scatternet %i\n", vlan_id);
2079 if (!strcmp(devname, "keyboard"))
2080 return bt_keyboard_init(vlan);
2082 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2083 return 0;
2086 static int bt_parse(const char *opt)
2088 const char *endp, *p;
2089 int vlan;
2091 if (strstart(opt, "hci", &endp)) {
2092 if (!*endp || *endp == ',') {
2093 if (*endp)
2094 if (!strstart(endp, ",vlan=", 0))
2095 opt = endp + 1;
2097 return bt_hci_parse(opt);
2099 } else if (strstart(opt, "vhci", &endp)) {
2100 if (!*endp || *endp == ',') {
2101 if (*endp) {
2102 if (strstart(endp, ",vlan=", &p)) {
2103 vlan = strtol(p, (char **) &endp, 0);
2104 if (*endp) {
2105 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2106 return 1;
2108 } else {
2109 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2110 return 1;
2112 } else
2113 vlan = 0;
2115 bt_vhci_add(vlan);
2116 return 0;
2118 } else if (strstart(opt, "device:", &endp))
2119 return !bt_device_add(endp);
2121 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2122 return 1;
2125 /***********************************************************/
2126 /* QEMU Block devices */
2128 #define HD_ALIAS "index=%d,media=disk"
2129 #ifdef TARGET_PPC
2130 #define CDROM_ALIAS "index=1,media=cdrom"
2131 #else
2132 #define CDROM_ALIAS "index=2,media=cdrom"
2133 #endif
2134 #define FD_ALIAS "index=%d,if=floppy"
2135 #define PFLASH_ALIAS "if=pflash"
2136 #define MTD_ALIAS "if=mtd"
2137 #define SD_ALIAS "index=0,if=sd"
2139 static int drive_add(const char *file, const char *fmt, ...)
2141 va_list ap;
2143 if (nb_drives_opt >= MAX_DRIVES) {
2144 fprintf(stderr, "qemu: too many drives\n");
2145 exit(1);
2148 drives_opt[nb_drives_opt].file = file;
2149 va_start(ap, fmt);
2150 vsnprintf(drives_opt[nb_drives_opt].opt,
2151 sizeof(drives_opt[0].opt), fmt, ap);
2152 va_end(ap);
2154 return nb_drives_opt++;
2157 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2159 int index;
2161 /* seek interface, bus and unit */
2163 for (index = 0; index < nb_drives; index++)
2164 if (drives_table[index].type == type &&
2165 drives_table[index].bus == bus &&
2166 drives_table[index].unit == unit)
2167 return index;
2169 return -1;
2172 int drive_get_max_bus(BlockInterfaceType type)
2174 int max_bus;
2175 int index;
2177 max_bus = -1;
2178 for (index = 0; index < nb_drives; index++) {
2179 if(drives_table[index].type == type &&
2180 drives_table[index].bus > max_bus)
2181 max_bus = drives_table[index].bus;
2183 return max_bus;
2186 static void bdrv_format_print(void *opaque, const char *name)
2188 fprintf(stderr, " %s", name);
2191 static int drive_init(struct drive_opt *arg, int snapshot,
2192 QEMUMachine *machine)
2194 char buf[128];
2195 char file[1024];
2196 char devname[128];
2197 const char *mediastr = "";
2198 BlockInterfaceType type;
2199 enum { MEDIA_DISK, MEDIA_CDROM } media;
2200 int bus_id, unit_id;
2201 int cyls, heads, secs, translation;
2202 BlockDriverState *bdrv;
2203 BlockDriver *drv = NULL;
2204 int max_devs;
2205 int index;
2206 int cache;
2207 int bdrv_flags;
2208 char *str = arg->opt;
2209 static const char * const params[] = { "bus", "unit", "if", "index",
2210 "cyls", "heads", "secs", "trans",
2211 "media", "snapshot", "file",
2212 "cache", "format", NULL };
2214 if (check_params(buf, sizeof(buf), params, str) < 0) {
2215 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2216 buf, str);
2217 return -1;
2220 file[0] = 0;
2221 cyls = heads = secs = 0;
2222 bus_id = 0;
2223 unit_id = -1;
2224 translation = BIOS_ATA_TRANSLATION_AUTO;
2225 index = -1;
2226 cache = 1;
2228 if (machine->use_scsi) {
2229 type = IF_SCSI;
2230 max_devs = MAX_SCSI_DEVS;
2231 pstrcpy(devname, sizeof(devname), "scsi");
2232 } else {
2233 type = IF_IDE;
2234 max_devs = MAX_IDE_DEVS;
2235 pstrcpy(devname, sizeof(devname), "ide");
2237 media = MEDIA_DISK;
2239 /* extract parameters */
2241 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2242 bus_id = strtol(buf, NULL, 0);
2243 if (bus_id < 0) {
2244 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2245 return -1;
2249 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2250 unit_id = strtol(buf, NULL, 0);
2251 if (unit_id < 0) {
2252 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2253 return -1;
2257 if (get_param_value(buf, sizeof(buf), "if", str)) {
2258 pstrcpy(devname, sizeof(devname), buf);
2259 if (!strcmp(buf, "ide")) {
2260 type = IF_IDE;
2261 max_devs = MAX_IDE_DEVS;
2262 } else if (!strcmp(buf, "scsi")) {
2263 type = IF_SCSI;
2264 max_devs = MAX_SCSI_DEVS;
2265 } else if (!strcmp(buf, "floppy")) {
2266 type = IF_FLOPPY;
2267 max_devs = 0;
2268 } else if (!strcmp(buf, "pflash")) {
2269 type = IF_PFLASH;
2270 max_devs = 0;
2271 } else if (!strcmp(buf, "mtd")) {
2272 type = IF_MTD;
2273 max_devs = 0;
2274 } else if (!strcmp(buf, "sd")) {
2275 type = IF_SD;
2276 max_devs = 0;
2277 } else {
2278 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2279 return -1;
2283 if (get_param_value(buf, sizeof(buf), "index", str)) {
2284 index = strtol(buf, NULL, 0);
2285 if (index < 0) {
2286 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2287 return -1;
2291 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2292 cyls = strtol(buf, NULL, 0);
2295 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2296 heads = strtol(buf, NULL, 0);
2299 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2300 secs = strtol(buf, NULL, 0);
2303 if (cyls || heads || secs) {
2304 if (cyls < 1 || cyls > 16383) {
2305 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2306 return -1;
2308 if (heads < 1 || heads > 16) {
2309 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2310 return -1;
2312 if (secs < 1 || secs > 63) {
2313 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2314 return -1;
2318 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2319 if (!cyls) {
2320 fprintf(stderr,
2321 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2322 str);
2323 return -1;
2325 if (!strcmp(buf, "none"))
2326 translation = BIOS_ATA_TRANSLATION_NONE;
2327 else if (!strcmp(buf, "lba"))
2328 translation = BIOS_ATA_TRANSLATION_LBA;
2329 else if (!strcmp(buf, "auto"))
2330 translation = BIOS_ATA_TRANSLATION_AUTO;
2331 else {
2332 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2333 return -1;
2337 if (get_param_value(buf, sizeof(buf), "media", str)) {
2338 if (!strcmp(buf, "disk")) {
2339 media = MEDIA_DISK;
2340 } else if (!strcmp(buf, "cdrom")) {
2341 if (cyls || secs || heads) {
2342 fprintf(stderr,
2343 "qemu: '%s' invalid physical CHS format\n", str);
2344 return -1;
2346 media = MEDIA_CDROM;
2347 } else {
2348 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2349 return -1;
2353 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2354 if (!strcmp(buf, "on"))
2355 snapshot = 1;
2356 else if (!strcmp(buf, "off"))
2357 snapshot = 0;
2358 else {
2359 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2360 return -1;
2364 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2365 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2366 cache = 0;
2367 else if (!strcmp(buf, "writethrough"))
2368 cache = 1;
2369 else if (!strcmp(buf, "writeback"))
2370 cache = 2;
2371 else {
2372 fprintf(stderr, "qemu: invalid cache option\n");
2373 return -1;
2377 if (get_param_value(buf, sizeof(buf), "format", str)) {
2378 if (strcmp(buf, "?") == 0) {
2379 fprintf(stderr, "qemu: Supported formats:");
2380 bdrv_iterate_format(bdrv_format_print, NULL);
2381 fprintf(stderr, "\n");
2382 return -1;
2384 drv = bdrv_find_format(buf);
2385 if (!drv) {
2386 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2387 return -1;
2391 if (arg->file == NULL)
2392 get_param_value(file, sizeof(file), "file", str);
2393 else
2394 pstrcpy(file, sizeof(file), arg->file);
2396 /* compute bus and unit according index */
2398 if (index != -1) {
2399 if (bus_id != 0 || unit_id != -1) {
2400 fprintf(stderr,
2401 "qemu: '%s' index cannot be used with bus and unit\n", str);
2402 return -1;
2404 if (max_devs == 0)
2406 unit_id = index;
2407 bus_id = 0;
2408 } else {
2409 unit_id = index % max_devs;
2410 bus_id = index / max_devs;
2414 /* if user doesn't specify a unit_id,
2415 * try to find the first free
2418 if (unit_id == -1) {
2419 unit_id = 0;
2420 while (drive_get_index(type, bus_id, unit_id) != -1) {
2421 unit_id++;
2422 if (max_devs && unit_id >= max_devs) {
2423 unit_id -= max_devs;
2424 bus_id++;
2429 /* check unit id */
2431 if (max_devs && unit_id >= max_devs) {
2432 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2433 str, unit_id, max_devs - 1);
2434 return -1;
2438 * ignore multiple definitions
2441 if (drive_get_index(type, bus_id, unit_id) != -1)
2442 return 0;
2444 /* init */
2446 if (type == IF_IDE || type == IF_SCSI)
2447 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2448 if (max_devs)
2449 snprintf(buf, sizeof(buf), "%s%i%s%i",
2450 devname, bus_id, mediastr, unit_id);
2451 else
2452 snprintf(buf, sizeof(buf), "%s%s%i",
2453 devname, mediastr, unit_id);
2454 bdrv = bdrv_new(buf);
2455 drives_table[nb_drives].bdrv = bdrv;
2456 drives_table[nb_drives].type = type;
2457 drives_table[nb_drives].bus = bus_id;
2458 drives_table[nb_drives].unit = unit_id;
2459 nb_drives++;
2461 switch(type) {
2462 case IF_IDE:
2463 case IF_SCSI:
2464 switch(media) {
2465 case MEDIA_DISK:
2466 if (cyls != 0) {
2467 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2468 bdrv_set_translation_hint(bdrv, translation);
2470 break;
2471 case MEDIA_CDROM:
2472 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2473 break;
2475 break;
2476 case IF_SD:
2477 /* FIXME: This isn't really a floppy, but it's a reasonable
2478 approximation. */
2479 case IF_FLOPPY:
2480 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2481 break;
2482 case IF_PFLASH:
2483 case IF_MTD:
2484 break;
2486 if (!file[0])
2487 return 0;
2488 bdrv_flags = 0;
2489 if (snapshot) {
2490 bdrv_flags |= BDRV_O_SNAPSHOT;
2491 cache = 2; /* always use write-back with snapshot */
2493 if (cache == 0) /* no caching */
2494 bdrv_flags |= BDRV_O_NOCACHE;
2495 else if (cache == 2) /* write-back */
2496 bdrv_flags |= BDRV_O_CACHE_WB;
2497 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2498 fprintf(stderr, "qemu: could not open disk image %s\n",
2499 file);
2500 return -1;
2502 return 0;
2505 /***********************************************************/
2506 /* USB devices */
2508 static USBPort *used_usb_ports;
2509 static USBPort *free_usb_ports;
2511 /* ??? Maybe change this to register a hub to keep track of the topology. */
2512 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2513 usb_attachfn attach)
2515 port->opaque = opaque;
2516 port->index = index;
2517 port->attach = attach;
2518 port->next = free_usb_ports;
2519 free_usb_ports = port;
2522 int usb_device_add_dev(USBDevice *dev)
2524 USBPort *port;
2526 /* Find a USB port to add the device to. */
2527 port = free_usb_ports;
2528 if (!port->next) {
2529 USBDevice *hub;
2531 /* Create a new hub and chain it on. */
2532 free_usb_ports = NULL;
2533 port->next = used_usb_ports;
2534 used_usb_ports = port;
2536 hub = usb_hub_init(VM_USB_HUB_SIZE);
2537 usb_attach(port, hub);
2538 port = free_usb_ports;
2541 free_usb_ports = port->next;
2542 port->next = used_usb_ports;
2543 used_usb_ports = port;
2544 usb_attach(port, dev);
2545 return 0;
2548 static int usb_device_add(const char *devname)
2550 const char *p;
2551 USBDevice *dev;
2553 if (!free_usb_ports)
2554 return -1;
2556 if (strstart(devname, "host:", &p)) {
2557 dev = usb_host_device_open(p);
2558 } else if (!strcmp(devname, "mouse")) {
2559 dev = usb_mouse_init();
2560 } else if (!strcmp(devname, "tablet")) {
2561 dev = usb_tablet_init();
2562 } else if (!strcmp(devname, "keyboard")) {
2563 dev = usb_keyboard_init();
2564 } else if (strstart(devname, "disk:", &p)) {
2565 dev = usb_msd_init(p);
2566 } else if (!strcmp(devname, "wacom-tablet")) {
2567 dev = usb_wacom_init();
2568 } else if (strstart(devname, "serial:", &p)) {
2569 dev = usb_serial_init(p);
2570 #ifdef CONFIG_BRLAPI
2571 } else if (!strcmp(devname, "braille")) {
2572 dev = usb_baum_init();
2573 #endif
2574 } else if (strstart(devname, "net:", &p)) {
2575 int nic = nb_nics;
2577 if (net_client_init("nic", p) < 0)
2578 return -1;
2579 nd_table[nic].model = "usb";
2580 dev = usb_net_init(&nd_table[nic]);
2581 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2582 dev = usb_bt_init(devname[2] ? hci_init(p) :
2583 bt_new_hci(qemu_find_bt_vlan(0)));
2584 } else {
2585 return -1;
2587 if (!dev)
2588 return -1;
2590 return usb_device_add_dev(dev);
2593 int usb_device_del_addr(int bus_num, int addr)
2595 USBPort *port;
2596 USBPort **lastp;
2597 USBDevice *dev;
2599 if (!used_usb_ports)
2600 return -1;
2602 if (bus_num != 0)
2603 return -1;
2605 lastp = &used_usb_ports;
2606 port = used_usb_ports;
2607 while (port && port->dev->addr != addr) {
2608 lastp = &port->next;
2609 port = port->next;
2612 if (!port)
2613 return -1;
2615 dev = port->dev;
2616 *lastp = port->next;
2617 usb_attach(port, NULL);
2618 dev->handle_destroy(dev);
2619 port->next = free_usb_ports;
2620 free_usb_ports = port;
2621 return 0;
2624 static int usb_device_del(const char *devname)
2626 int bus_num, addr;
2627 const char *p;
2629 if (strstart(devname, "host:", &p))
2630 return usb_host_device_close(p);
2632 if (!used_usb_ports)
2633 return -1;
2635 p = strchr(devname, '.');
2636 if (!p)
2637 return -1;
2638 bus_num = strtoul(devname, NULL, 0);
2639 addr = strtoul(p + 1, NULL, 0);
2641 return usb_device_del_addr(bus_num, addr);
2644 void do_usb_add(const char *devname)
2646 usb_device_add(devname);
2649 void do_usb_del(const char *devname)
2651 usb_device_del(devname);
2654 void usb_info(void)
2656 USBDevice *dev;
2657 USBPort *port;
2658 const char *speed_str;
2660 if (!usb_enabled) {
2661 term_printf("USB support not enabled\n");
2662 return;
2665 for (port = used_usb_ports; port; port = port->next) {
2666 dev = port->dev;
2667 if (!dev)
2668 continue;
2669 switch(dev->speed) {
2670 case USB_SPEED_LOW:
2671 speed_str = "1.5";
2672 break;
2673 case USB_SPEED_FULL:
2674 speed_str = "12";
2675 break;
2676 case USB_SPEED_HIGH:
2677 speed_str = "480";
2678 break;
2679 default:
2680 speed_str = "?";
2681 break;
2683 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2684 0, dev->addr, speed_str, dev->devname);
2688 /***********************************************************/
2689 /* PCMCIA/Cardbus */
2691 static struct pcmcia_socket_entry_s {
2692 struct pcmcia_socket_s *socket;
2693 struct pcmcia_socket_entry_s *next;
2694 } *pcmcia_sockets = 0;
2696 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2698 struct pcmcia_socket_entry_s *entry;
2700 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2701 entry->socket = socket;
2702 entry->next = pcmcia_sockets;
2703 pcmcia_sockets = entry;
2706 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2708 struct pcmcia_socket_entry_s *entry, **ptr;
2710 ptr = &pcmcia_sockets;
2711 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2712 if (entry->socket == socket) {
2713 *ptr = entry->next;
2714 qemu_free(entry);
2718 void pcmcia_info(void)
2720 struct pcmcia_socket_entry_s *iter;
2721 if (!pcmcia_sockets)
2722 term_printf("No PCMCIA sockets\n");
2724 for (iter = pcmcia_sockets; iter; iter = iter->next)
2725 term_printf("%s: %s\n", iter->socket->slot_string,
2726 iter->socket->attached ? iter->socket->card_string :
2727 "Empty");
2730 /***********************************************************/
2731 /* dumb display */
2733 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2737 static void dumb_resize(DisplayState *ds, int w, int h)
2741 static void dumb_display_init(DisplayState *ds)
2743 ds->data = NULL;
2744 ds->linesize = 0;
2745 ds->depth = 0;
2746 ds->dpy_update = dumb_update;
2747 ds->dpy_resize = dumb_resize;
2748 ds->dpy_refresh = NULL;
2749 ds->gui_timer_interval = 0;
2750 ds->idle = 1;
2753 /***********************************************************/
2754 /* I/O handling */
2756 #define MAX_IO_HANDLERS 64
2758 typedef struct IOHandlerRecord {
2759 int fd;
2760 IOCanRWHandler *fd_read_poll;
2761 IOHandler *fd_read;
2762 IOHandler *fd_write;
2763 int deleted;
2764 void *opaque;
2765 /* temporary data */
2766 struct pollfd *ufd;
2767 struct IOHandlerRecord *next;
2768 } IOHandlerRecord;
2770 static IOHandlerRecord *first_io_handler;
2772 /* XXX: fd_read_poll should be suppressed, but an API change is
2773 necessary in the character devices to suppress fd_can_read(). */
2774 int qemu_set_fd_handler2(int fd,
2775 IOCanRWHandler *fd_read_poll,
2776 IOHandler *fd_read,
2777 IOHandler *fd_write,
2778 void *opaque)
2780 IOHandlerRecord **pioh, *ioh;
2782 if (!fd_read && !fd_write) {
2783 pioh = &first_io_handler;
2784 for(;;) {
2785 ioh = *pioh;
2786 if (ioh == NULL)
2787 break;
2788 if (ioh->fd == fd) {
2789 ioh->deleted = 1;
2790 break;
2792 pioh = &ioh->next;
2794 } else {
2795 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2796 if (ioh->fd == fd)
2797 goto found;
2799 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2800 if (!ioh)
2801 return -1;
2802 ioh->next = first_io_handler;
2803 first_io_handler = ioh;
2804 found:
2805 ioh->fd = fd;
2806 ioh->fd_read_poll = fd_read_poll;
2807 ioh->fd_read = fd_read;
2808 ioh->fd_write = fd_write;
2809 ioh->opaque = opaque;
2810 ioh->deleted = 0;
2812 return 0;
2815 int qemu_set_fd_handler(int fd,
2816 IOHandler *fd_read,
2817 IOHandler *fd_write,
2818 void *opaque)
2820 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2823 #ifdef _WIN32
2824 /***********************************************************/
2825 /* Polling handling */
2827 typedef struct PollingEntry {
2828 PollingFunc *func;
2829 void *opaque;
2830 struct PollingEntry *next;
2831 } PollingEntry;
2833 static PollingEntry *first_polling_entry;
2835 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2837 PollingEntry **ppe, *pe;
2838 pe = qemu_mallocz(sizeof(PollingEntry));
2839 if (!pe)
2840 return -1;
2841 pe->func = func;
2842 pe->opaque = opaque;
2843 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2844 *ppe = pe;
2845 return 0;
2848 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2850 PollingEntry **ppe, *pe;
2851 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2852 pe = *ppe;
2853 if (pe->func == func && pe->opaque == opaque) {
2854 *ppe = pe->next;
2855 qemu_free(pe);
2856 break;
2861 /***********************************************************/
2862 /* Wait objects support */
2863 typedef struct WaitObjects {
2864 int num;
2865 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2866 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2867 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2868 } WaitObjects;
2870 static WaitObjects wait_objects = {0};
2872 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2874 WaitObjects *w = &wait_objects;
2876 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2877 return -1;
2878 w->events[w->num] = handle;
2879 w->func[w->num] = func;
2880 w->opaque[w->num] = opaque;
2881 w->num++;
2882 return 0;
2885 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2887 int i, found;
2888 WaitObjects *w = &wait_objects;
2890 found = 0;
2891 for (i = 0; i < w->num; i++) {
2892 if (w->events[i] == handle)
2893 found = 1;
2894 if (found) {
2895 w->events[i] = w->events[i + 1];
2896 w->func[i] = w->func[i + 1];
2897 w->opaque[i] = w->opaque[i + 1];
2900 if (found)
2901 w->num--;
2903 #endif
2905 /***********************************************************/
2906 /* ram save/restore */
2908 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2910 int v;
2912 v = qemu_get_byte(f);
2913 switch(v) {
2914 case 0:
2915 if (qemu_get_buffer(f, buf, len) != len)
2916 return -EIO;
2917 break;
2918 case 1:
2919 v = qemu_get_byte(f);
2920 memset(buf, v, len);
2921 break;
2922 default:
2923 return -EINVAL;
2926 if (qemu_file_has_error(f))
2927 return -EIO;
2929 return 0;
2932 static int ram_load_v1(QEMUFile *f, void *opaque)
2934 int ret;
2935 ram_addr_t i;
2937 if (qemu_get_be32(f) != phys_ram_size)
2938 return -EINVAL;
2939 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2940 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2941 if (ret)
2942 return ret;
2944 return 0;
2947 #define BDRV_HASH_BLOCK_SIZE 1024
2948 #define IOBUF_SIZE 4096
2949 #define RAM_CBLOCK_MAGIC 0xfabe
2951 typedef struct RamDecompressState {
2952 z_stream zstream;
2953 QEMUFile *f;
2954 uint8_t buf[IOBUF_SIZE];
2955 } RamDecompressState;
2957 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2959 int ret;
2960 memset(s, 0, sizeof(*s));
2961 s->f = f;
2962 ret = inflateInit(&s->zstream);
2963 if (ret != Z_OK)
2964 return -1;
2965 return 0;
2968 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2970 int ret, clen;
2972 s->zstream.avail_out = len;
2973 s->zstream.next_out = buf;
2974 while (s->zstream.avail_out > 0) {
2975 if (s->zstream.avail_in == 0) {
2976 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2977 return -1;
2978 clen = qemu_get_be16(s->f);
2979 if (clen > IOBUF_SIZE)
2980 return -1;
2981 qemu_get_buffer(s->f, s->buf, clen);
2982 s->zstream.avail_in = clen;
2983 s->zstream.next_in = s->buf;
2985 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2986 if (ret != Z_OK && ret != Z_STREAM_END) {
2987 return -1;
2990 return 0;
2993 static void ram_decompress_close(RamDecompressState *s)
2995 inflateEnd(&s->zstream);
2998 #define RAM_SAVE_FLAG_FULL 0x01
2999 #define RAM_SAVE_FLAG_COMPRESS 0x02
3000 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3001 #define RAM_SAVE_FLAG_PAGE 0x08
3002 #define RAM_SAVE_FLAG_EOS 0x10
3004 static int is_dup_page(uint8_t *page, uint8_t ch)
3006 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3007 uint32_t *array = (uint32_t *)page;
3008 int i;
3010 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3011 if (array[i] != val)
3012 return 0;
3015 return 1;
3018 static int ram_save_block(QEMUFile *f)
3020 static ram_addr_t current_addr = 0;
3021 ram_addr_t saved_addr = current_addr;
3022 ram_addr_t addr = 0;
3023 int found = 0;
3025 while (addr < phys_ram_size) {
3026 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3027 uint8_t ch;
3029 cpu_physical_memory_reset_dirty(current_addr,
3030 current_addr + TARGET_PAGE_SIZE,
3031 MIGRATION_DIRTY_FLAG);
3033 ch = *(phys_ram_base + current_addr);
3035 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3036 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3037 qemu_put_byte(f, ch);
3038 } else {
3039 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3040 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3043 found = 1;
3044 break;
3046 addr += TARGET_PAGE_SIZE;
3047 current_addr = (saved_addr + addr) % phys_ram_size;
3050 return found;
3053 static ram_addr_t ram_save_threshold = 10;
3055 static ram_addr_t ram_save_remaining(void)
3057 ram_addr_t addr;
3058 ram_addr_t count = 0;
3060 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3061 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3062 count++;
3065 return count;
3068 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3070 ram_addr_t addr;
3072 if (stage == 1) {
3073 /* Make sure all dirty bits are set */
3074 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3075 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3076 cpu_physical_memory_set_dirty(addr);
3079 /* Enable dirty memory tracking */
3080 cpu_physical_memory_set_dirty_tracking(1);
3082 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3085 while (!qemu_file_rate_limit(f)) {
3086 int ret;
3088 ret = ram_save_block(f);
3089 if (ret == 0) /* no more blocks */
3090 break;
3093 /* try transferring iterative blocks of memory */
3095 if (stage == 3) {
3096 cpu_physical_memory_set_dirty_tracking(0);
3098 /* flush all remaining blocks regardless of rate limiting */
3099 while (ram_save_block(f) != 0);
3102 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3104 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3107 static int ram_load_dead(QEMUFile *f, void *opaque)
3109 RamDecompressState s1, *s = &s1;
3110 uint8_t buf[10];
3111 ram_addr_t i;
3113 if (ram_decompress_open(s, f) < 0)
3114 return -EINVAL;
3115 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3116 if (ram_decompress_buf(s, buf, 1) < 0) {
3117 fprintf(stderr, "Error while reading ram block header\n");
3118 goto error;
3120 if (buf[0] == 0) {
3121 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3122 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3123 goto error;
3125 } else {
3126 error:
3127 printf("Error block header\n");
3128 return -EINVAL;
3131 ram_decompress_close(s);
3133 return 0;
3136 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3138 ram_addr_t addr;
3139 int flags;
3141 if (version_id == 1)
3142 return ram_load_v1(f, opaque);
3144 if (version_id == 2) {
3145 if (qemu_get_be32(f) != phys_ram_size)
3146 return -EINVAL;
3147 return ram_load_dead(f, opaque);
3150 if (version_id != 3)
3151 return -EINVAL;
3153 do {
3154 addr = qemu_get_be64(f);
3156 flags = addr & ~TARGET_PAGE_MASK;
3157 addr &= TARGET_PAGE_MASK;
3159 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3160 if (addr != phys_ram_size)
3161 return -EINVAL;
3164 if (flags & RAM_SAVE_FLAG_FULL) {
3165 if (ram_load_dead(f, opaque) < 0)
3166 return -EINVAL;
3169 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3170 uint8_t ch = qemu_get_byte(f);
3171 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3172 } else if (flags & RAM_SAVE_FLAG_PAGE)
3173 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3174 } while (!(flags & RAM_SAVE_FLAG_EOS));
3176 return 0;
3179 void qemu_service_io(void)
3181 CPUState *env = cpu_single_env;
3182 if (env) {
3183 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3184 #ifdef USE_KQEMU
3185 if (env->kqemu_enabled) {
3186 kqemu_cpu_interrupt(env);
3188 #endif
3192 /***********************************************************/
3193 /* bottom halves (can be seen as timers which expire ASAP) */
3195 struct QEMUBH {
3196 QEMUBHFunc *cb;
3197 void *opaque;
3198 int scheduled;
3199 int idle;
3200 int deleted;
3201 QEMUBH *next;
3204 static QEMUBH *first_bh = NULL;
3206 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3208 QEMUBH *bh;
3209 bh = qemu_mallocz(sizeof(QEMUBH));
3210 if (!bh)
3211 return NULL;
3212 bh->cb = cb;
3213 bh->opaque = opaque;
3214 bh->next = first_bh;
3215 first_bh = bh;
3216 return bh;
3219 int qemu_bh_poll(void)
3221 QEMUBH *bh, **bhp;
3222 int ret;
3224 ret = 0;
3225 for (bh = first_bh; bh; bh = bh->next) {
3226 if (!bh->deleted && bh->scheduled) {
3227 bh->scheduled = 0;
3228 if (!bh->idle)
3229 ret = 1;
3230 bh->idle = 0;
3231 bh->cb(bh->opaque);
3235 /* remove deleted bhs */
3236 bhp = &first_bh;
3237 while (*bhp) {
3238 bh = *bhp;
3239 if (bh->deleted) {
3240 *bhp = bh->next;
3241 qemu_free(bh);
3242 } else
3243 bhp = &bh->next;
3246 return ret;
3249 void qemu_bh_schedule_idle(QEMUBH *bh)
3251 if (bh->scheduled)
3252 return;
3253 bh->scheduled = 1;
3254 bh->idle = 1;
3257 void qemu_bh_schedule(QEMUBH *bh)
3259 CPUState *env = cpu_single_env;
3260 if (bh->scheduled)
3261 return;
3262 bh->scheduled = 1;
3263 bh->idle = 0;
3264 /* stop the currently executing CPU to execute the BH ASAP */
3265 if (env) {
3266 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3270 void qemu_bh_cancel(QEMUBH *bh)
3272 bh->scheduled = 0;
3275 void qemu_bh_delete(QEMUBH *bh)
3277 bh->scheduled = 0;
3278 bh->deleted = 1;
3281 static void qemu_bh_update_timeout(int *timeout)
3283 QEMUBH *bh;
3285 for (bh = first_bh; bh; bh = bh->next) {
3286 if (!bh->deleted && bh->scheduled) {
3287 if (bh->idle) {
3288 /* idle bottom halves will be polled at least
3289 * every 10ms */
3290 *timeout = MIN(10, *timeout);
3291 } else {
3292 /* non-idle bottom halves will be executed
3293 * immediately */
3294 *timeout = 0;
3295 break;
3301 /***********************************************************/
3302 /* machine registration */
3304 static QEMUMachine *first_machine = NULL;
3306 int qemu_register_machine(QEMUMachine *m)
3308 QEMUMachine **pm;
3309 pm = &first_machine;
3310 while (*pm != NULL)
3311 pm = &(*pm)->next;
3312 m->next = NULL;
3313 *pm = m;
3314 return 0;
3317 static QEMUMachine *find_machine(const char *name)
3319 QEMUMachine *m;
3321 for(m = first_machine; m != NULL; m = m->next) {
3322 if (!strcmp(m->name, name))
3323 return m;
3325 return NULL;
3328 /***********************************************************/
3329 /* main execution loop */
3331 static void gui_update(void *opaque)
3333 DisplayState *ds = opaque;
3334 ds->dpy_refresh(ds);
3335 qemu_mod_timer(ds->gui_timer,
3336 (ds->gui_timer_interval ?
3337 ds->gui_timer_interval :
3338 GUI_REFRESH_INTERVAL)
3339 + qemu_get_clock(rt_clock));
3342 struct vm_change_state_entry {
3343 VMChangeStateHandler *cb;
3344 void *opaque;
3345 LIST_ENTRY (vm_change_state_entry) entries;
3348 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3350 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3351 void *opaque)
3353 VMChangeStateEntry *e;
3355 e = qemu_mallocz(sizeof (*e));
3356 if (!e)
3357 return NULL;
3359 e->cb = cb;
3360 e->opaque = opaque;
3361 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3362 return e;
3365 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3367 LIST_REMOVE (e, entries);
3368 qemu_free (e);
3371 static void vm_state_notify(int running)
3373 VMChangeStateEntry *e;
3375 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3376 e->cb(e->opaque, running);
3380 /* XXX: support several handlers */
3381 static VMStopHandler *vm_stop_cb;
3382 static void *vm_stop_opaque;
3384 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3386 vm_stop_cb = cb;
3387 vm_stop_opaque = opaque;
3388 return 0;
3391 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3393 vm_stop_cb = NULL;
3396 void vm_start(void)
3398 if (!vm_running) {
3399 cpu_enable_ticks();
3400 vm_running = 1;
3401 vm_state_notify(1);
3402 qemu_rearm_alarm_timer(alarm_timer);
3406 void vm_stop(int reason)
3408 if (vm_running) {
3409 cpu_disable_ticks();
3410 vm_running = 0;
3411 if (reason != 0) {
3412 if (vm_stop_cb) {
3413 vm_stop_cb(vm_stop_opaque, reason);
3416 vm_state_notify(0);
3420 /* reset/shutdown handler */
3422 typedef struct QEMUResetEntry {
3423 QEMUResetHandler *func;
3424 void *opaque;
3425 struct QEMUResetEntry *next;
3426 } QEMUResetEntry;
3428 static QEMUResetEntry *first_reset_entry;
3429 static int reset_requested;
3430 static int shutdown_requested;
3431 static int powerdown_requested;
3433 int qemu_shutdown_requested(void)
3435 int r = shutdown_requested;
3436 shutdown_requested = 0;
3437 return r;
3440 int qemu_reset_requested(void)
3442 int r = reset_requested;
3443 reset_requested = 0;
3444 return r;
3447 int qemu_powerdown_requested(void)
3449 int r = powerdown_requested;
3450 powerdown_requested = 0;
3451 return r;
3454 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3456 QEMUResetEntry **pre, *re;
3458 pre = &first_reset_entry;
3459 while (*pre != NULL)
3460 pre = &(*pre)->next;
3461 re = qemu_mallocz(sizeof(QEMUResetEntry));
3462 re->func = func;
3463 re->opaque = opaque;
3464 re->next = NULL;
3465 *pre = re;
3468 void qemu_system_reset(void)
3470 QEMUResetEntry *re;
3472 /* reset all devices */
3473 for(re = first_reset_entry; re != NULL; re = re->next) {
3474 re->func(re->opaque);
3478 void qemu_system_reset_request(void)
3480 if (no_reboot) {
3481 shutdown_requested = 1;
3482 } else {
3483 reset_requested = 1;
3485 if (cpu_single_env)
3486 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3489 void qemu_system_shutdown_request(void)
3491 shutdown_requested = 1;
3492 if (cpu_single_env)
3493 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3496 void qemu_system_powerdown_request(void)
3498 powerdown_requested = 1;
3499 if (cpu_single_env)
3500 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3503 #ifdef _WIN32
3504 void host_main_loop_wait(int *timeout)
3506 int ret, ret2, i;
3507 PollingEntry *pe;
3510 /* XXX: need to suppress polling by better using win32 events */
3511 ret = 0;
3512 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3513 ret |= pe->func(pe->opaque);
3515 if (ret == 0) {
3516 int err;
3517 WaitObjects *w = &wait_objects;
3519 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3520 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3521 if (w->func[ret - WAIT_OBJECT_0])
3522 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3524 /* Check for additional signaled events */
3525 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3527 /* Check if event is signaled */
3528 ret2 = WaitForSingleObject(w->events[i], 0);
3529 if(ret2 == WAIT_OBJECT_0) {
3530 if (w->func[i])
3531 w->func[i](w->opaque[i]);
3532 } else if (ret2 == WAIT_TIMEOUT) {
3533 } else {
3534 err = GetLastError();
3535 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3538 } else if (ret == WAIT_TIMEOUT) {
3539 } else {
3540 err = GetLastError();
3541 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3545 *timeout = 0;
3547 #else
3548 void host_main_loop_wait(int *timeout)
3551 #endif
3553 void main_loop_wait(int timeout)
3555 IOHandlerRecord *ioh;
3556 fd_set rfds, wfds, xfds;
3557 int ret, nfds;
3558 struct timeval tv;
3560 qemu_bh_update_timeout(&timeout);
3562 host_main_loop_wait(&timeout);
3564 /* poll any events */
3565 /* XXX: separate device handlers from system ones */
3566 nfds = -1;
3567 FD_ZERO(&rfds);
3568 FD_ZERO(&wfds);
3569 FD_ZERO(&xfds);
3570 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3571 if (ioh->deleted)
3572 continue;
3573 if (ioh->fd_read &&
3574 (!ioh->fd_read_poll ||
3575 ioh->fd_read_poll(ioh->opaque) != 0)) {
3576 FD_SET(ioh->fd, &rfds);
3577 if (ioh->fd > nfds)
3578 nfds = ioh->fd;
3580 if (ioh->fd_write) {
3581 FD_SET(ioh->fd, &wfds);
3582 if (ioh->fd > nfds)
3583 nfds = ioh->fd;
3587 tv.tv_sec = timeout / 1000;
3588 tv.tv_usec = (timeout % 1000) * 1000;
3590 #if defined(CONFIG_SLIRP)
3591 if (slirp_is_inited()) {
3592 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3594 #endif
3595 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3596 if (ret > 0) {
3597 IOHandlerRecord **pioh;
3599 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3600 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3601 ioh->fd_read(ioh->opaque);
3603 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3604 ioh->fd_write(ioh->opaque);
3608 /* remove deleted IO handlers */
3609 pioh = &first_io_handler;
3610 while (*pioh) {
3611 ioh = *pioh;
3612 if (ioh->deleted) {
3613 *pioh = ioh->next;
3614 qemu_free(ioh);
3615 } else
3616 pioh = &ioh->next;
3619 #if defined(CONFIG_SLIRP)
3620 if (slirp_is_inited()) {
3621 if (ret < 0) {
3622 FD_ZERO(&rfds);
3623 FD_ZERO(&wfds);
3624 FD_ZERO(&xfds);
3626 slirp_select_poll(&rfds, &wfds, &xfds);
3628 #endif
3630 /* Check bottom-halves last in case any of the earlier events triggered
3631 them. */
3632 qemu_bh_poll();
3636 static int main_loop(void)
3638 int ret, timeout;
3639 #ifdef CONFIG_PROFILER
3640 int64_t ti;
3641 #endif
3642 CPUState *env;
3644 cur_cpu = first_cpu;
3645 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3646 for(;;) {
3647 if (vm_running) {
3649 for(;;) {
3650 /* get next cpu */
3651 env = next_cpu;
3652 #ifdef CONFIG_PROFILER
3653 ti = profile_getclock();
3654 #endif
3655 if (use_icount) {
3656 int64_t count;
3657 int decr;
3658 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3659 env->icount_decr.u16.low = 0;
3660 env->icount_extra = 0;
3661 count = qemu_next_deadline();
3662 count = (count + (1 << icount_time_shift) - 1)
3663 >> icount_time_shift;
3664 qemu_icount += count;
3665 decr = (count > 0xffff) ? 0xffff : count;
3666 count -= decr;
3667 env->icount_decr.u16.low = decr;
3668 env->icount_extra = count;
3670 ret = cpu_exec(env);
3671 #ifdef CONFIG_PROFILER
3672 qemu_time += profile_getclock() - ti;
3673 #endif
3674 if (use_icount) {
3675 /* Fold pending instructions back into the
3676 instruction counter, and clear the interrupt flag. */
3677 qemu_icount -= (env->icount_decr.u16.low
3678 + env->icount_extra);
3679 env->icount_decr.u32 = 0;
3680 env->icount_extra = 0;
3682 next_cpu = env->next_cpu ?: first_cpu;
3683 if (event_pending && likely(ret != EXCP_DEBUG)) {
3684 ret = EXCP_INTERRUPT;
3685 event_pending = 0;
3686 break;
3688 if (ret == EXCP_HLT) {
3689 /* Give the next CPU a chance to run. */
3690 cur_cpu = env;
3691 continue;
3693 if (ret != EXCP_HALTED)
3694 break;
3695 /* all CPUs are halted ? */
3696 if (env == cur_cpu)
3697 break;
3699 cur_cpu = env;
3701 if (shutdown_requested) {
3702 ret = EXCP_INTERRUPT;
3703 if (no_shutdown) {
3704 vm_stop(0);
3705 no_shutdown = 0;
3707 else
3708 break;
3710 if (reset_requested) {
3711 reset_requested = 0;
3712 qemu_system_reset();
3713 ret = EXCP_INTERRUPT;
3715 if (powerdown_requested) {
3716 powerdown_requested = 0;
3717 qemu_system_powerdown();
3718 ret = EXCP_INTERRUPT;
3720 if (unlikely(ret == EXCP_DEBUG)) {
3721 vm_stop(EXCP_DEBUG);
3723 /* If all cpus are halted then wait until the next IRQ */
3724 /* XXX: use timeout computed from timers */
3725 if (ret == EXCP_HALTED) {
3726 if (use_icount) {
3727 int64_t add;
3728 int64_t delta;
3729 /* Advance virtual time to the next event. */
3730 if (use_icount == 1) {
3731 /* When not using an adaptive execution frequency
3732 we tend to get badly out of sync with real time,
3733 so just delay for a reasonable amount of time. */
3734 delta = 0;
3735 } else {
3736 delta = cpu_get_icount() - cpu_get_clock();
3738 if (delta > 0) {
3739 /* If virtual time is ahead of real time then just
3740 wait for IO. */
3741 timeout = (delta / 1000000) + 1;
3742 } else {
3743 /* Wait for either IO to occur or the next
3744 timer event. */
3745 add = qemu_next_deadline();
3746 /* We advance the timer before checking for IO.
3747 Limit the amount we advance so that early IO
3748 activity won't get the guest too far ahead. */
3749 if (add > 10000000)
3750 add = 10000000;
3751 delta += add;
3752 add = (add + (1 << icount_time_shift) - 1)
3753 >> icount_time_shift;
3754 qemu_icount += add;
3755 timeout = delta / 1000000;
3756 if (timeout < 0)
3757 timeout = 0;
3759 } else {
3760 timeout = 5000;
3762 } else {
3763 timeout = 0;
3765 } else {
3766 if (shutdown_requested) {
3767 ret = EXCP_INTERRUPT;
3768 break;
3770 timeout = 5000;
3772 #ifdef CONFIG_PROFILER
3773 ti = profile_getclock();
3774 #endif
3775 main_loop_wait(timeout);
3776 #ifdef CONFIG_PROFILER
3777 dev_time += profile_getclock() - ti;
3778 #endif
3780 cpu_disable_ticks();
3781 return ret;
3784 static void help(int exitcode)
3786 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3787 "usage: %s [options] [disk_image]\n"
3788 "\n"
3789 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3790 "\n"
3791 "Standard options:\n"
3792 "-M machine select emulated machine (-M ? for list)\n"
3793 "-cpu cpu select CPU (-cpu ? for list)\n"
3794 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3795 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3796 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3797 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3798 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3799 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3800 " [,cache=writethrough|writeback|none][,format=f]\n"
3801 " use 'file' as a drive image\n"
3802 "-mtdblock file use 'file' as on-board Flash memory image\n"
3803 "-sd file use 'file' as SecureDigital card image\n"
3804 "-pflash file use 'file' as a parallel flash image\n"
3805 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3806 "-snapshot write to temporary files instead of disk image files\n"
3807 #ifdef CONFIG_SDL
3808 "-no-frame open SDL window without a frame and window decorations\n"
3809 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3810 "-no-quit disable SDL window close capability\n"
3811 #endif
3812 #ifdef TARGET_I386
3813 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3814 #endif
3815 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3816 "-smp n set the number of CPUs to 'n' [default=1]\n"
3817 "-nographic disable graphical output and redirect serial I/Os to console\n"
3818 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3819 #ifndef _WIN32
3820 "-k language use keyboard layout (for example \"fr\" for French)\n"
3821 #endif
3822 #ifdef HAS_AUDIO
3823 "-audio-help print list of audio drivers and their options\n"
3824 "-soundhw c1,... enable audio support\n"
3825 " and only specified sound cards (comma separated list)\n"
3826 " use -soundhw ? to get the list of supported cards\n"
3827 " use -soundhw all to enable all of them\n"
3828 #endif
3829 "-vga [std|cirrus|vmware]\n"
3830 " select video card type\n"
3831 "-localtime set the real time clock to local time [default=utc]\n"
3832 "-full-screen start in full screen\n"
3833 #ifdef TARGET_I386
3834 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3835 #endif
3836 "-usb enable the USB driver (will be the default soon)\n"
3837 "-usbdevice name add the host or guest USB device 'name'\n"
3838 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3839 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3840 #endif
3841 "-name string set the name of the guest\n"
3842 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
3843 "\n"
3844 "Network options:\n"
3845 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
3846 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3847 #ifdef CONFIG_SLIRP
3848 "-net user[,vlan=n][,hostname=host]\n"
3849 " connect the user mode network stack to VLAN 'n' and send\n"
3850 " hostname 'host' to DHCP clients\n"
3851 #endif
3852 #ifdef _WIN32
3853 "-net tap[,vlan=n],ifname=name\n"
3854 " connect the host TAP network interface to VLAN 'n'\n"
3855 #else
3856 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3857 " connect the host TAP network interface to VLAN 'n' and use the\n"
3858 " network scripts 'file' (default=%s)\n"
3859 " and 'dfile' (default=%s);\n"
3860 " use '[down]script=no' to disable script execution;\n"
3861 " use 'fd=h' to connect to an already opened TAP interface\n"
3862 #endif
3863 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3864 " connect the vlan 'n' to another VLAN using a socket connection\n"
3865 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
3866 " connect the vlan 'n' to multicast maddr and port\n"
3867 #ifdef CONFIG_VDE
3868 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3869 " connect the vlan 'n' to port 'n' of a vde switch running\n"
3870 " on host and listening for incoming connections on 'socketpath'.\n"
3871 " Use group 'groupname' and mode 'octalmode' to change default\n"
3872 " ownership and permissions for communication port.\n"
3873 #endif
3874 "-net none use it alone to have zero network devices; if no -net option\n"
3875 " is provided, the default is '-net nic -net user'\n"
3876 "\n"
3877 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
3878 "-bt hci,host[:id]\n"
3879 " Use host's HCI with the given name\n"
3880 "-bt hci[,vlan=n]\n"
3881 " Emulate a standard HCI in virtual scatternet 'n'\n"
3882 "-bt vhci[,vlan=n]\n"
3883 " Add host computer to virtual scatternet 'n' using VHCI\n"
3884 "-bt device:dev[,vlan=n]\n"
3885 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
3886 "\n"
3887 #ifdef CONFIG_SLIRP
3888 "-tftp dir allow tftp access to files in dir [-net user]\n"
3889 "-bootp file advertise file in BOOTP replies\n"
3890 #ifndef _WIN32
3891 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3892 #endif
3893 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3894 " redirect TCP or UDP connections from host to guest [-net user]\n"
3895 #endif
3896 "\n"
3897 "Linux boot specific:\n"
3898 "-kernel bzImage use 'bzImage' as kernel image\n"
3899 "-append cmdline use 'cmdline' as kernel command line\n"
3900 "-initrd file use 'file' as initial ram disk\n"
3901 "\n"
3902 "Debug/Expert options:\n"
3903 "-monitor dev redirect the monitor to char device 'dev'\n"
3904 "-serial dev redirect the serial port to char device 'dev'\n"
3905 "-parallel dev redirect the parallel port to char device 'dev'\n"
3906 "-pidfile file Write PID to 'file'\n"
3907 "-S freeze CPU at startup (use 'c' to start execution)\n"
3908 "-s wait gdb connection to port\n"
3909 "-p port set gdb connection port [default=%s]\n"
3910 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
3911 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
3912 " translation (t=none or lba) (usually qemu can guess them)\n"
3913 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
3914 #ifdef USE_KQEMU
3915 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
3916 "-no-kqemu disable KQEMU kernel module usage\n"
3917 #endif
3918 #ifdef CONFIG_KVM
3919 "-enable-kvm enable KVM full virtualization support\n"
3920 #endif
3921 #ifdef TARGET_I386
3922 "-no-acpi disable ACPI\n"
3923 #endif
3924 #ifdef CONFIG_CURSES
3925 "-curses use a curses/ncurses interface instead of SDL\n"
3926 #endif
3927 "-no-reboot exit instead of rebooting\n"
3928 "-no-shutdown stop before shutdown\n"
3929 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
3930 "-vnc display start a VNC server on display\n"
3931 #ifndef _WIN32
3932 "-daemonize daemonize QEMU after initializing\n"
3933 #endif
3934 "-option-rom rom load a file, rom, into the option ROM space\n"
3935 #ifdef TARGET_SPARC
3936 "-prom-env variable=value set OpenBIOS nvram variables\n"
3937 #endif
3938 "-clock force the use of the given methods for timer alarm.\n"
3939 " To see what timers are available use -clock ?\n"
3940 "-startdate select initial date of the clock\n"
3941 "-icount [N|auto]\n"
3942 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
3943 "\n"
3944 "During emulation, the following keys are useful:\n"
3945 "ctrl-alt-f toggle full screen\n"
3946 "ctrl-alt-n switch to virtual console 'n'\n"
3947 "ctrl-alt toggle mouse and keyboard grab\n"
3948 "\n"
3949 "When using -nographic, press 'ctrl-a h' to get some help.\n"
3951 "qemu",
3952 DEFAULT_RAM_SIZE,
3953 #ifndef _WIN32
3954 DEFAULT_NETWORK_SCRIPT,
3955 DEFAULT_NETWORK_DOWN_SCRIPT,
3956 #endif
3957 DEFAULT_GDBSTUB_PORT,
3958 "/tmp/qemu.log");
3959 exit(exitcode);
3962 #define HAS_ARG 0x0001
3964 enum {
3965 QEMU_OPTION_h,
3967 QEMU_OPTION_M,
3968 QEMU_OPTION_cpu,
3969 QEMU_OPTION_fda,
3970 QEMU_OPTION_fdb,
3971 QEMU_OPTION_hda,
3972 QEMU_OPTION_hdb,
3973 QEMU_OPTION_hdc,
3974 QEMU_OPTION_hdd,
3975 QEMU_OPTION_drive,
3976 QEMU_OPTION_cdrom,
3977 QEMU_OPTION_mtdblock,
3978 QEMU_OPTION_sd,
3979 QEMU_OPTION_pflash,
3980 QEMU_OPTION_boot,
3981 QEMU_OPTION_snapshot,
3982 #ifdef TARGET_I386
3983 QEMU_OPTION_no_fd_bootchk,
3984 #endif
3985 QEMU_OPTION_m,
3986 QEMU_OPTION_nographic,
3987 QEMU_OPTION_portrait,
3988 #ifdef HAS_AUDIO
3989 QEMU_OPTION_audio_help,
3990 QEMU_OPTION_soundhw,
3991 #endif
3993 QEMU_OPTION_net,
3994 QEMU_OPTION_tftp,
3995 QEMU_OPTION_bootp,
3996 QEMU_OPTION_smb,
3997 QEMU_OPTION_redir,
3998 QEMU_OPTION_bt,
4000 QEMU_OPTION_kernel,
4001 QEMU_OPTION_append,
4002 QEMU_OPTION_initrd,
4004 QEMU_OPTION_S,
4005 QEMU_OPTION_s,
4006 QEMU_OPTION_p,
4007 QEMU_OPTION_d,
4008 QEMU_OPTION_hdachs,
4009 QEMU_OPTION_L,
4010 QEMU_OPTION_bios,
4011 QEMU_OPTION_k,
4012 QEMU_OPTION_localtime,
4013 QEMU_OPTION_g,
4014 QEMU_OPTION_vga,
4015 QEMU_OPTION_echr,
4016 QEMU_OPTION_monitor,
4017 QEMU_OPTION_serial,
4018 QEMU_OPTION_parallel,
4019 QEMU_OPTION_loadvm,
4020 QEMU_OPTION_full_screen,
4021 QEMU_OPTION_no_frame,
4022 QEMU_OPTION_alt_grab,
4023 QEMU_OPTION_no_quit,
4024 QEMU_OPTION_pidfile,
4025 QEMU_OPTION_no_kqemu,
4026 QEMU_OPTION_kernel_kqemu,
4027 QEMU_OPTION_enable_kvm,
4028 QEMU_OPTION_win2k_hack,
4029 QEMU_OPTION_usb,
4030 QEMU_OPTION_usbdevice,
4031 QEMU_OPTION_smp,
4032 QEMU_OPTION_vnc,
4033 QEMU_OPTION_no_acpi,
4034 QEMU_OPTION_curses,
4035 QEMU_OPTION_no_reboot,
4036 QEMU_OPTION_no_shutdown,
4037 QEMU_OPTION_show_cursor,
4038 QEMU_OPTION_daemonize,
4039 QEMU_OPTION_option_rom,
4040 QEMU_OPTION_semihosting,
4041 QEMU_OPTION_name,
4042 QEMU_OPTION_prom_env,
4043 QEMU_OPTION_old_param,
4044 QEMU_OPTION_clock,
4045 QEMU_OPTION_startdate,
4046 QEMU_OPTION_tb_size,
4047 QEMU_OPTION_icount,
4048 QEMU_OPTION_uuid,
4049 QEMU_OPTION_incoming,
4052 typedef struct QEMUOption {
4053 const char *name;
4054 int flags;
4055 int index;
4056 } QEMUOption;
4058 static const QEMUOption qemu_options[] = {
4059 { "h", 0, QEMU_OPTION_h },
4060 { "help", 0, QEMU_OPTION_h },
4062 { "M", HAS_ARG, QEMU_OPTION_M },
4063 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4064 { "fda", HAS_ARG, QEMU_OPTION_fda },
4065 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4066 { "hda", HAS_ARG, QEMU_OPTION_hda },
4067 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4068 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4069 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4070 { "drive", HAS_ARG, QEMU_OPTION_drive },
4071 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4072 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4073 { "sd", HAS_ARG, QEMU_OPTION_sd },
4074 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4075 { "boot", HAS_ARG, QEMU_OPTION_boot },
4076 { "snapshot", 0, QEMU_OPTION_snapshot },
4077 #ifdef TARGET_I386
4078 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4079 #endif
4080 { "m", HAS_ARG, QEMU_OPTION_m },
4081 { "nographic", 0, QEMU_OPTION_nographic },
4082 { "portrait", 0, QEMU_OPTION_portrait },
4083 { "k", HAS_ARG, QEMU_OPTION_k },
4084 #ifdef HAS_AUDIO
4085 { "audio-help", 0, QEMU_OPTION_audio_help },
4086 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4087 #endif
4089 { "net", HAS_ARG, QEMU_OPTION_net},
4090 #ifdef CONFIG_SLIRP
4091 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4092 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4093 #ifndef _WIN32
4094 { "smb", HAS_ARG, QEMU_OPTION_smb },
4095 #endif
4096 { "redir", HAS_ARG, QEMU_OPTION_redir },
4097 #endif
4098 { "bt", HAS_ARG, QEMU_OPTION_bt },
4100 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4101 { "append", HAS_ARG, QEMU_OPTION_append },
4102 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4104 { "S", 0, QEMU_OPTION_S },
4105 { "s", 0, QEMU_OPTION_s },
4106 { "p", HAS_ARG, QEMU_OPTION_p },
4107 { "d", HAS_ARG, QEMU_OPTION_d },
4108 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4109 { "L", HAS_ARG, QEMU_OPTION_L },
4110 { "bios", HAS_ARG, QEMU_OPTION_bios },
4111 #ifdef USE_KQEMU
4112 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4113 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4114 #endif
4115 #ifdef CONFIG_KVM
4116 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4117 #endif
4118 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4119 { "g", 1, QEMU_OPTION_g },
4120 #endif
4121 { "localtime", 0, QEMU_OPTION_localtime },
4122 { "vga", HAS_ARG, QEMU_OPTION_vga },
4123 { "echr", HAS_ARG, QEMU_OPTION_echr },
4124 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4125 { "serial", HAS_ARG, QEMU_OPTION_serial },
4126 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4127 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4128 { "full-screen", 0, QEMU_OPTION_full_screen },
4129 #ifdef CONFIG_SDL
4130 { "no-frame", 0, QEMU_OPTION_no_frame },
4131 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4132 { "no-quit", 0, QEMU_OPTION_no_quit },
4133 #endif
4134 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4135 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4136 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4137 { "smp", HAS_ARG, QEMU_OPTION_smp },
4138 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4139 #ifdef CONFIG_CURSES
4140 { "curses", 0, QEMU_OPTION_curses },
4141 #endif
4142 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4144 /* temporary options */
4145 { "usb", 0, QEMU_OPTION_usb },
4146 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4147 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4148 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4149 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4150 { "daemonize", 0, QEMU_OPTION_daemonize },
4151 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4152 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4153 { "semihosting", 0, QEMU_OPTION_semihosting },
4154 #endif
4155 { "name", HAS_ARG, QEMU_OPTION_name },
4156 #if defined(TARGET_SPARC)
4157 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4158 #endif
4159 #if defined(TARGET_ARM)
4160 { "old-param", 0, QEMU_OPTION_old_param },
4161 #endif
4162 { "clock", HAS_ARG, QEMU_OPTION_clock },
4163 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4164 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4165 { "icount", HAS_ARG, QEMU_OPTION_icount },
4166 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4167 { NULL },
4170 /* password input */
4172 int qemu_key_check(BlockDriverState *bs, const char *name)
4174 char password[256];
4175 int i;
4177 if (!bdrv_is_encrypted(bs))
4178 return 0;
4180 term_printf("%s is encrypted.\n", name);
4181 for(i = 0; i < 3; i++) {
4182 monitor_readline("Password: ", 1, password, sizeof(password));
4183 if (bdrv_set_key(bs, password) == 0)
4184 return 0;
4185 term_printf("invalid password\n");
4187 return -EPERM;
4190 static BlockDriverState *get_bdrv(int index)
4192 if (index > nb_drives)
4193 return NULL;
4194 return drives_table[index].bdrv;
4197 static void read_passwords(void)
4199 BlockDriverState *bs;
4200 int i;
4202 for(i = 0; i < 6; i++) {
4203 bs = get_bdrv(i);
4204 if (bs)
4205 qemu_key_check(bs, bdrv_get_device_name(bs));
4209 #ifdef HAS_AUDIO
4210 struct soundhw soundhw[] = {
4211 #ifdef HAS_AUDIO_CHOICE
4212 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4214 "pcspk",
4215 "PC speaker",
4218 { .init_isa = pcspk_audio_init }
4220 #endif
4222 "sb16",
4223 "Creative Sound Blaster 16",
4226 { .init_isa = SB16_init }
4229 #ifdef CONFIG_CS4231A
4231 "cs4231a",
4232 "CS4231A",
4235 { .init_isa = cs4231a_init }
4237 #endif
4239 #ifdef CONFIG_ADLIB
4241 "adlib",
4242 #ifdef HAS_YMF262
4243 "Yamaha YMF262 (OPL3)",
4244 #else
4245 "Yamaha YM3812 (OPL2)",
4246 #endif
4249 { .init_isa = Adlib_init }
4251 #endif
4253 #ifdef CONFIG_GUS
4255 "gus",
4256 "Gravis Ultrasound GF1",
4259 { .init_isa = GUS_init }
4261 #endif
4263 #ifdef CONFIG_AC97
4265 "ac97",
4266 "Intel 82801AA AC97 Audio",
4269 { .init_pci = ac97_init }
4271 #endif
4274 "es1370",
4275 "ENSONIQ AudioPCI ES1370",
4278 { .init_pci = es1370_init }
4280 #endif
4282 { NULL, NULL, 0, 0, { NULL } }
4285 static void select_soundhw (const char *optarg)
4287 struct soundhw *c;
4289 if (*optarg == '?') {
4290 show_valid_cards:
4292 printf ("Valid sound card names (comma separated):\n");
4293 for (c = soundhw; c->name; ++c) {
4294 printf ("%-11s %s\n", c->name, c->descr);
4296 printf ("\n-soundhw all will enable all of the above\n");
4297 exit (*optarg != '?');
4299 else {
4300 size_t l;
4301 const char *p;
4302 char *e;
4303 int bad_card = 0;
4305 if (!strcmp (optarg, "all")) {
4306 for (c = soundhw; c->name; ++c) {
4307 c->enabled = 1;
4309 return;
4312 p = optarg;
4313 while (*p) {
4314 e = strchr (p, ',');
4315 l = !e ? strlen (p) : (size_t) (e - p);
4317 for (c = soundhw; c->name; ++c) {
4318 if (!strncmp (c->name, p, l)) {
4319 c->enabled = 1;
4320 break;
4324 if (!c->name) {
4325 if (l > 80) {
4326 fprintf (stderr,
4327 "Unknown sound card name (too big to show)\n");
4329 else {
4330 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4331 (int) l, p);
4333 bad_card = 1;
4335 p += l + (e != NULL);
4338 if (bad_card)
4339 goto show_valid_cards;
4342 #endif
4344 static void select_vgahw (const char *p)
4346 const char *opts;
4348 if (strstart(p, "std", &opts)) {
4349 cirrus_vga_enabled = 0;
4350 vmsvga_enabled = 0;
4351 } else if (strstart(p, "cirrus", &opts)) {
4352 cirrus_vga_enabled = 1;
4353 vmsvga_enabled = 0;
4354 } else if (strstart(p, "vmware", &opts)) {
4355 cirrus_vga_enabled = 0;
4356 vmsvga_enabled = 1;
4357 } else {
4358 invalid_vga:
4359 fprintf(stderr, "Unknown vga type: %s\n", p);
4360 exit(1);
4362 while (*opts) {
4363 const char *nextopt;
4365 if (strstart(opts, ",retrace=", &nextopt)) {
4366 opts = nextopt;
4367 if (strstart(opts, "dumb", &nextopt))
4368 vga_retrace_method = VGA_RETRACE_DUMB;
4369 else if (strstart(opts, "precise", &nextopt))
4370 vga_retrace_method = VGA_RETRACE_PRECISE;
4371 else goto invalid_vga;
4372 } else goto invalid_vga;
4373 opts = nextopt;
4377 #ifdef _WIN32
4378 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4380 exit(STATUS_CONTROL_C_EXIT);
4381 return TRUE;
4383 #endif
4385 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4387 int ret;
4389 if(strlen(str) != 36)
4390 return -1;
4392 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4393 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4394 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4396 if(ret != 16)
4397 return -1;
4399 return 0;
4402 #define MAX_NET_CLIENTS 32
4404 #ifndef _WIN32
4406 static void termsig_handler(int signal)
4408 qemu_system_shutdown_request();
4411 static void termsig_setup(void)
4413 struct sigaction act;
4415 memset(&act, 0, sizeof(act));
4416 act.sa_handler = termsig_handler;
4417 sigaction(SIGINT, &act, NULL);
4418 sigaction(SIGHUP, &act, NULL);
4419 sigaction(SIGTERM, &act, NULL);
4422 #endif
4424 int main(int argc, char **argv)
4426 #ifdef CONFIG_GDBSTUB
4427 int use_gdbstub;
4428 const char *gdbstub_port;
4429 #endif
4430 uint32_t boot_devices_bitmap = 0;
4431 int i;
4432 int snapshot, linux_boot, net_boot;
4433 const char *initrd_filename;
4434 const char *kernel_filename, *kernel_cmdline;
4435 const char *boot_devices = "";
4436 DisplayState *ds = &display_state;
4437 int cyls, heads, secs, translation;
4438 const char *net_clients[MAX_NET_CLIENTS];
4439 int nb_net_clients;
4440 const char *bt_opts[MAX_BT_CMDLINE];
4441 int nb_bt_opts;
4442 int hda_index;
4443 int optind;
4444 const char *r, *optarg;
4445 CharDriverState *monitor_hd;
4446 const char *monitor_device;
4447 const char *serial_devices[MAX_SERIAL_PORTS];
4448 int serial_device_index;
4449 const char *parallel_devices[MAX_PARALLEL_PORTS];
4450 int parallel_device_index;
4451 const char *loadvm = NULL;
4452 QEMUMachine *machine;
4453 const char *cpu_model;
4454 const char *usb_devices[MAX_USB_CMDLINE];
4455 int usb_devices_index;
4456 int fds[2];
4457 int tb_size;
4458 const char *pid_file = NULL;
4459 int autostart;
4460 const char *incoming = NULL;
4462 LIST_INIT (&vm_change_state_head);
4463 #ifndef _WIN32
4465 struct sigaction act;
4466 sigfillset(&act.sa_mask);
4467 act.sa_flags = 0;
4468 act.sa_handler = SIG_IGN;
4469 sigaction(SIGPIPE, &act, NULL);
4471 #else
4472 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4473 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4474 QEMU to run on a single CPU */
4476 HANDLE h;
4477 DWORD mask, smask;
4478 int i;
4479 h = GetCurrentProcess();
4480 if (GetProcessAffinityMask(h, &mask, &smask)) {
4481 for(i = 0; i < 32; i++) {
4482 if (mask & (1 << i))
4483 break;
4485 if (i != 32) {
4486 mask = 1 << i;
4487 SetProcessAffinityMask(h, mask);
4491 #endif
4493 register_machines();
4494 machine = first_machine;
4495 cpu_model = NULL;
4496 initrd_filename = NULL;
4497 ram_size = 0;
4498 vga_ram_size = VGA_RAM_SIZE;
4499 #ifdef CONFIG_GDBSTUB
4500 use_gdbstub = 0;
4501 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4502 #endif
4503 snapshot = 0;
4504 nographic = 0;
4505 curses = 0;
4506 kernel_filename = NULL;
4507 kernel_cmdline = "";
4508 cyls = heads = secs = 0;
4509 translation = BIOS_ATA_TRANSLATION_AUTO;
4510 monitor_device = "vc";
4512 serial_devices[0] = "vc:80Cx24C";
4513 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4514 serial_devices[i] = NULL;
4515 serial_device_index = 0;
4517 parallel_devices[0] = "vc:640x480";
4518 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4519 parallel_devices[i] = NULL;
4520 parallel_device_index = 0;
4522 usb_devices_index = 0;
4524 nb_net_clients = 0;
4525 nb_bt_opts = 0;
4526 nb_drives = 0;
4527 nb_drives_opt = 0;
4528 hda_index = -1;
4530 nb_nics = 0;
4532 tb_size = 0;
4533 autostart= 1;
4535 optind = 1;
4536 for(;;) {
4537 if (optind >= argc)
4538 break;
4539 r = argv[optind];
4540 if (r[0] != '-') {
4541 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4542 } else {
4543 const QEMUOption *popt;
4545 optind++;
4546 /* Treat --foo the same as -foo. */
4547 if (r[1] == '-')
4548 r++;
4549 popt = qemu_options;
4550 for(;;) {
4551 if (!popt->name) {
4552 fprintf(stderr, "%s: invalid option -- '%s'\n",
4553 argv[0], r);
4554 exit(1);
4556 if (!strcmp(popt->name, r + 1))
4557 break;
4558 popt++;
4560 if (popt->flags & HAS_ARG) {
4561 if (optind >= argc) {
4562 fprintf(stderr, "%s: option '%s' requires an argument\n",
4563 argv[0], r);
4564 exit(1);
4566 optarg = argv[optind++];
4567 } else {
4568 optarg = NULL;
4571 switch(popt->index) {
4572 case QEMU_OPTION_M:
4573 machine = find_machine(optarg);
4574 if (!machine) {
4575 QEMUMachine *m;
4576 printf("Supported machines are:\n");
4577 for(m = first_machine; m != NULL; m = m->next) {
4578 printf("%-10s %s%s\n",
4579 m->name, m->desc,
4580 m == first_machine ? " (default)" : "");
4582 exit(*optarg != '?');
4584 break;
4585 case QEMU_OPTION_cpu:
4586 /* hw initialization will check this */
4587 if (*optarg == '?') {
4588 /* XXX: implement xxx_cpu_list for targets that still miss it */
4589 #if defined(cpu_list)
4590 cpu_list(stdout, &fprintf);
4591 #endif
4592 exit(0);
4593 } else {
4594 cpu_model = optarg;
4596 break;
4597 case QEMU_OPTION_initrd:
4598 initrd_filename = optarg;
4599 break;
4600 case QEMU_OPTION_hda:
4601 if (cyls == 0)
4602 hda_index = drive_add(optarg, HD_ALIAS, 0);
4603 else
4604 hda_index = drive_add(optarg, HD_ALIAS
4605 ",cyls=%d,heads=%d,secs=%d%s",
4606 0, cyls, heads, secs,
4607 translation == BIOS_ATA_TRANSLATION_LBA ?
4608 ",trans=lba" :
4609 translation == BIOS_ATA_TRANSLATION_NONE ?
4610 ",trans=none" : "");
4611 break;
4612 case QEMU_OPTION_hdb:
4613 case QEMU_OPTION_hdc:
4614 case QEMU_OPTION_hdd:
4615 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4616 break;
4617 case QEMU_OPTION_drive:
4618 drive_add(NULL, "%s", optarg);
4619 break;
4620 case QEMU_OPTION_mtdblock:
4621 drive_add(optarg, MTD_ALIAS);
4622 break;
4623 case QEMU_OPTION_sd:
4624 drive_add(optarg, SD_ALIAS);
4625 break;
4626 case QEMU_OPTION_pflash:
4627 drive_add(optarg, PFLASH_ALIAS);
4628 break;
4629 case QEMU_OPTION_snapshot:
4630 snapshot = 1;
4631 break;
4632 case QEMU_OPTION_hdachs:
4634 const char *p;
4635 p = optarg;
4636 cyls = strtol(p, (char **)&p, 0);
4637 if (cyls < 1 || cyls > 16383)
4638 goto chs_fail;
4639 if (*p != ',')
4640 goto chs_fail;
4641 p++;
4642 heads = strtol(p, (char **)&p, 0);
4643 if (heads < 1 || heads > 16)
4644 goto chs_fail;
4645 if (*p != ',')
4646 goto chs_fail;
4647 p++;
4648 secs = strtol(p, (char **)&p, 0);
4649 if (secs < 1 || secs > 63)
4650 goto chs_fail;
4651 if (*p == ',') {
4652 p++;
4653 if (!strcmp(p, "none"))
4654 translation = BIOS_ATA_TRANSLATION_NONE;
4655 else if (!strcmp(p, "lba"))
4656 translation = BIOS_ATA_TRANSLATION_LBA;
4657 else if (!strcmp(p, "auto"))
4658 translation = BIOS_ATA_TRANSLATION_AUTO;
4659 else
4660 goto chs_fail;
4661 } else if (*p != '\0') {
4662 chs_fail:
4663 fprintf(stderr, "qemu: invalid physical CHS format\n");
4664 exit(1);
4666 if (hda_index != -1)
4667 snprintf(drives_opt[hda_index].opt,
4668 sizeof(drives_opt[hda_index].opt),
4669 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4670 0, cyls, heads, secs,
4671 translation == BIOS_ATA_TRANSLATION_LBA ?
4672 ",trans=lba" :
4673 translation == BIOS_ATA_TRANSLATION_NONE ?
4674 ",trans=none" : "");
4676 break;
4677 case QEMU_OPTION_nographic:
4678 nographic = 1;
4679 break;
4680 #ifdef CONFIG_CURSES
4681 case QEMU_OPTION_curses:
4682 curses = 1;
4683 break;
4684 #endif
4685 case QEMU_OPTION_portrait:
4686 graphic_rotate = 1;
4687 break;
4688 case QEMU_OPTION_kernel:
4689 kernel_filename = optarg;
4690 break;
4691 case QEMU_OPTION_append:
4692 kernel_cmdline = optarg;
4693 break;
4694 case QEMU_OPTION_cdrom:
4695 drive_add(optarg, CDROM_ALIAS);
4696 break;
4697 case QEMU_OPTION_boot:
4698 boot_devices = optarg;
4699 /* We just do some generic consistency checks */
4701 /* Could easily be extended to 64 devices if needed */
4702 const char *p;
4704 boot_devices_bitmap = 0;
4705 for (p = boot_devices; *p != '\0'; p++) {
4706 /* Allowed boot devices are:
4707 * a b : floppy disk drives
4708 * c ... f : IDE disk drives
4709 * g ... m : machine implementation dependant drives
4710 * n ... p : network devices
4711 * It's up to each machine implementation to check
4712 * if the given boot devices match the actual hardware
4713 * implementation and firmware features.
4715 if (*p < 'a' || *p > 'q') {
4716 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4717 exit(1);
4719 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4720 fprintf(stderr,
4721 "Boot device '%c' was given twice\n",*p);
4722 exit(1);
4724 boot_devices_bitmap |= 1 << (*p - 'a');
4727 break;
4728 case QEMU_OPTION_fda:
4729 case QEMU_OPTION_fdb:
4730 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4731 break;
4732 #ifdef TARGET_I386
4733 case QEMU_OPTION_no_fd_bootchk:
4734 fd_bootchk = 0;
4735 break;
4736 #endif
4737 case QEMU_OPTION_net:
4738 if (nb_net_clients >= MAX_NET_CLIENTS) {
4739 fprintf(stderr, "qemu: too many network clients\n");
4740 exit(1);
4742 net_clients[nb_net_clients] = optarg;
4743 nb_net_clients++;
4744 break;
4745 #ifdef CONFIG_SLIRP
4746 case QEMU_OPTION_tftp:
4747 tftp_prefix = optarg;
4748 break;
4749 case QEMU_OPTION_bootp:
4750 bootp_filename = optarg;
4751 break;
4752 #ifndef _WIN32
4753 case QEMU_OPTION_smb:
4754 net_slirp_smb(optarg);
4755 break;
4756 #endif
4757 case QEMU_OPTION_redir:
4758 net_slirp_redir(optarg);
4759 break;
4760 #endif
4761 case QEMU_OPTION_bt:
4762 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4763 fprintf(stderr, "qemu: too many bluetooth options\n");
4764 exit(1);
4766 bt_opts[nb_bt_opts++] = optarg;
4767 break;
4768 #ifdef HAS_AUDIO
4769 case QEMU_OPTION_audio_help:
4770 AUD_help ();
4771 exit (0);
4772 break;
4773 case QEMU_OPTION_soundhw:
4774 select_soundhw (optarg);
4775 break;
4776 #endif
4777 case QEMU_OPTION_h:
4778 help(0);
4779 break;
4780 case QEMU_OPTION_m: {
4781 uint64_t value;
4782 char *ptr;
4784 value = strtoul(optarg, &ptr, 10);
4785 switch (*ptr) {
4786 case 0: case 'M': case 'm':
4787 value <<= 20;
4788 break;
4789 case 'G': case 'g':
4790 value <<= 30;
4791 break;
4792 default:
4793 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4794 exit(1);
4797 /* On 32-bit hosts, QEMU is limited by virtual address space */
4798 if (value > (2047 << 20)
4799 #ifndef USE_KQEMU
4800 && HOST_LONG_BITS == 32
4801 #endif
4803 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4804 exit(1);
4806 if (value != (uint64_t)(ram_addr_t)value) {
4807 fprintf(stderr, "qemu: ram size too large\n");
4808 exit(1);
4810 ram_size = value;
4811 break;
4813 case QEMU_OPTION_d:
4815 int mask;
4816 const CPULogItem *item;
4818 mask = cpu_str_to_log_mask(optarg);
4819 if (!mask) {
4820 printf("Log items (comma separated):\n");
4821 for(item = cpu_log_items; item->mask != 0; item++) {
4822 printf("%-10s %s\n", item->name, item->help);
4824 exit(1);
4826 cpu_set_log(mask);
4828 break;
4829 #ifdef CONFIG_GDBSTUB
4830 case QEMU_OPTION_s:
4831 use_gdbstub = 1;
4832 break;
4833 case QEMU_OPTION_p:
4834 gdbstub_port = optarg;
4835 break;
4836 #endif
4837 case QEMU_OPTION_L:
4838 bios_dir = optarg;
4839 break;
4840 case QEMU_OPTION_bios:
4841 bios_name = optarg;
4842 break;
4843 case QEMU_OPTION_S:
4844 autostart = 0;
4845 break;
4846 case QEMU_OPTION_k:
4847 keyboard_layout = optarg;
4848 break;
4849 case QEMU_OPTION_localtime:
4850 rtc_utc = 0;
4851 break;
4852 case QEMU_OPTION_vga:
4853 select_vgahw (optarg);
4854 break;
4855 case QEMU_OPTION_g:
4857 const char *p;
4858 int w, h, depth;
4859 p = optarg;
4860 w = strtol(p, (char **)&p, 10);
4861 if (w <= 0) {
4862 graphic_error:
4863 fprintf(stderr, "qemu: invalid resolution or depth\n");
4864 exit(1);
4866 if (*p != 'x')
4867 goto graphic_error;
4868 p++;
4869 h = strtol(p, (char **)&p, 10);
4870 if (h <= 0)
4871 goto graphic_error;
4872 if (*p == 'x') {
4873 p++;
4874 depth = strtol(p, (char **)&p, 10);
4875 if (depth != 8 && depth != 15 && depth != 16 &&
4876 depth != 24 && depth != 32)
4877 goto graphic_error;
4878 } else if (*p == '\0') {
4879 depth = graphic_depth;
4880 } else {
4881 goto graphic_error;
4884 graphic_width = w;
4885 graphic_height = h;
4886 graphic_depth = depth;
4888 break;
4889 case QEMU_OPTION_echr:
4891 char *r;
4892 term_escape_char = strtol(optarg, &r, 0);
4893 if (r == optarg)
4894 printf("Bad argument to echr\n");
4895 break;
4897 case QEMU_OPTION_monitor:
4898 monitor_device = optarg;
4899 break;
4900 case QEMU_OPTION_serial:
4901 if (serial_device_index >= MAX_SERIAL_PORTS) {
4902 fprintf(stderr, "qemu: too many serial ports\n");
4903 exit(1);
4905 serial_devices[serial_device_index] = optarg;
4906 serial_device_index++;
4907 break;
4908 case QEMU_OPTION_parallel:
4909 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4910 fprintf(stderr, "qemu: too many parallel ports\n");
4911 exit(1);
4913 parallel_devices[parallel_device_index] = optarg;
4914 parallel_device_index++;
4915 break;
4916 case QEMU_OPTION_loadvm:
4917 loadvm = optarg;
4918 break;
4919 case QEMU_OPTION_full_screen:
4920 full_screen = 1;
4921 break;
4922 #ifdef CONFIG_SDL
4923 case QEMU_OPTION_no_frame:
4924 no_frame = 1;
4925 break;
4926 case QEMU_OPTION_alt_grab:
4927 alt_grab = 1;
4928 break;
4929 case QEMU_OPTION_no_quit:
4930 no_quit = 1;
4931 break;
4932 #endif
4933 case QEMU_OPTION_pidfile:
4934 pid_file = optarg;
4935 break;
4936 #ifdef TARGET_I386
4937 case QEMU_OPTION_win2k_hack:
4938 win2k_install_hack = 1;
4939 break;
4940 #endif
4941 #ifdef USE_KQEMU
4942 case QEMU_OPTION_no_kqemu:
4943 kqemu_allowed = 0;
4944 break;
4945 case QEMU_OPTION_kernel_kqemu:
4946 kqemu_allowed = 2;
4947 break;
4948 #endif
4949 #ifdef CONFIG_KVM
4950 case QEMU_OPTION_enable_kvm:
4951 kvm_allowed = 1;
4952 #ifdef USE_KQEMU
4953 kqemu_allowed = 0;
4954 #endif
4955 break;
4956 #endif
4957 case QEMU_OPTION_usb:
4958 usb_enabled = 1;
4959 break;
4960 case QEMU_OPTION_usbdevice:
4961 usb_enabled = 1;
4962 if (usb_devices_index >= MAX_USB_CMDLINE) {
4963 fprintf(stderr, "Too many USB devices\n");
4964 exit(1);
4966 usb_devices[usb_devices_index] = optarg;
4967 usb_devices_index++;
4968 break;
4969 case QEMU_OPTION_smp:
4970 smp_cpus = atoi(optarg);
4971 if (smp_cpus < 1) {
4972 fprintf(stderr, "Invalid number of CPUs\n");
4973 exit(1);
4975 break;
4976 case QEMU_OPTION_vnc:
4977 vnc_display = optarg;
4978 break;
4979 case QEMU_OPTION_no_acpi:
4980 acpi_enabled = 0;
4981 break;
4982 case QEMU_OPTION_no_reboot:
4983 no_reboot = 1;
4984 break;
4985 case QEMU_OPTION_no_shutdown:
4986 no_shutdown = 1;
4987 break;
4988 case QEMU_OPTION_show_cursor:
4989 cursor_hide = 0;
4990 break;
4991 case QEMU_OPTION_uuid:
4992 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4993 fprintf(stderr, "Fail to parse UUID string."
4994 " Wrong format.\n");
4995 exit(1);
4997 break;
4998 case QEMU_OPTION_daemonize:
4999 daemonize = 1;
5000 break;
5001 case QEMU_OPTION_option_rom:
5002 if (nb_option_roms >= MAX_OPTION_ROMS) {
5003 fprintf(stderr, "Too many option ROMs\n");
5004 exit(1);
5006 option_rom[nb_option_roms] = optarg;
5007 nb_option_roms++;
5008 break;
5009 case QEMU_OPTION_semihosting:
5010 semihosting_enabled = 1;
5011 break;
5012 case QEMU_OPTION_name:
5013 qemu_name = optarg;
5014 break;
5015 #ifdef TARGET_SPARC
5016 case QEMU_OPTION_prom_env:
5017 if (nb_prom_envs >= MAX_PROM_ENVS) {
5018 fprintf(stderr, "Too many prom variables\n");
5019 exit(1);
5021 prom_envs[nb_prom_envs] = optarg;
5022 nb_prom_envs++;
5023 break;
5024 #endif
5025 #ifdef TARGET_ARM
5026 case QEMU_OPTION_old_param:
5027 old_param = 1;
5028 break;
5029 #endif
5030 case QEMU_OPTION_clock:
5031 configure_alarms(optarg);
5032 break;
5033 case QEMU_OPTION_startdate:
5035 struct tm tm;
5036 time_t rtc_start_date;
5037 if (!strcmp(optarg, "now")) {
5038 rtc_date_offset = -1;
5039 } else {
5040 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5041 &tm.tm_year,
5042 &tm.tm_mon,
5043 &tm.tm_mday,
5044 &tm.tm_hour,
5045 &tm.tm_min,
5046 &tm.tm_sec) == 6) {
5047 /* OK */
5048 } else if (sscanf(optarg, "%d-%d-%d",
5049 &tm.tm_year,
5050 &tm.tm_mon,
5051 &tm.tm_mday) == 3) {
5052 tm.tm_hour = 0;
5053 tm.tm_min = 0;
5054 tm.tm_sec = 0;
5055 } else {
5056 goto date_fail;
5058 tm.tm_year -= 1900;
5059 tm.tm_mon--;
5060 rtc_start_date = mktimegm(&tm);
5061 if (rtc_start_date == -1) {
5062 date_fail:
5063 fprintf(stderr, "Invalid date format. Valid format are:\n"
5064 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5065 exit(1);
5067 rtc_date_offset = time(NULL) - rtc_start_date;
5070 break;
5071 case QEMU_OPTION_tb_size:
5072 tb_size = strtol(optarg, NULL, 0);
5073 if (tb_size < 0)
5074 tb_size = 0;
5075 break;
5076 case QEMU_OPTION_icount:
5077 use_icount = 1;
5078 if (strcmp(optarg, "auto") == 0) {
5079 icount_time_shift = -1;
5080 } else {
5081 icount_time_shift = strtol(optarg, NULL, 0);
5083 break;
5084 case QEMU_OPTION_incoming:
5085 incoming = optarg;
5086 break;
5091 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5092 if (kvm_allowed && kqemu_allowed) {
5093 fprintf(stderr,
5094 "You can not enable both KVM and kqemu at the same time\n");
5095 exit(1);
5097 #endif
5099 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5100 if (smp_cpus > machine->max_cpus) {
5101 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5102 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5103 machine->max_cpus);
5104 exit(1);
5107 if (nographic) {
5108 if (serial_device_index == 0)
5109 serial_devices[0] = "stdio";
5110 if (parallel_device_index == 0)
5111 parallel_devices[0] = "null";
5112 if (strncmp(monitor_device, "vc", 2) == 0)
5113 monitor_device = "stdio";
5116 #ifndef _WIN32
5117 if (daemonize) {
5118 pid_t pid;
5120 if (pipe(fds) == -1)
5121 exit(1);
5123 pid = fork();
5124 if (pid > 0) {
5125 uint8_t status;
5126 ssize_t len;
5128 close(fds[1]);
5130 again:
5131 len = read(fds[0], &status, 1);
5132 if (len == -1 && (errno == EINTR))
5133 goto again;
5135 if (len != 1)
5136 exit(1);
5137 else if (status == 1) {
5138 fprintf(stderr, "Could not acquire pidfile\n");
5139 exit(1);
5140 } else
5141 exit(0);
5142 } else if (pid < 0)
5143 exit(1);
5145 setsid();
5147 pid = fork();
5148 if (pid > 0)
5149 exit(0);
5150 else if (pid < 0)
5151 exit(1);
5153 umask(027);
5155 signal(SIGTSTP, SIG_IGN);
5156 signal(SIGTTOU, SIG_IGN);
5157 signal(SIGTTIN, SIG_IGN);
5159 #endif
5161 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5162 if (daemonize) {
5163 uint8_t status = 1;
5164 write(fds[1], &status, 1);
5165 } else
5166 fprintf(stderr, "Could not acquire pid file\n");
5167 exit(1);
5170 #ifdef USE_KQEMU
5171 if (smp_cpus > 1)
5172 kqemu_allowed = 0;
5173 #endif
5174 linux_boot = (kernel_filename != NULL);
5175 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5177 if (!linux_boot && net_boot == 0 &&
5178 !machine->nodisk_ok && nb_drives_opt == 0)
5179 help(1);
5181 if (!linux_boot && *kernel_cmdline != '\0') {
5182 fprintf(stderr, "-append only allowed with -kernel option\n");
5183 exit(1);
5186 if (!linux_boot && initrd_filename != NULL) {
5187 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5188 exit(1);
5191 /* boot to floppy or the default cd if no hard disk defined yet */
5192 if (!boot_devices[0]) {
5193 boot_devices = "cad";
5195 setvbuf(stdout, NULL, _IOLBF, 0);
5197 init_timers();
5198 if (init_timer_alarm() < 0) {
5199 fprintf(stderr, "could not initialize alarm timer\n");
5200 exit(1);
5202 if (use_icount && icount_time_shift < 0) {
5203 use_icount = 2;
5204 /* 125MIPS seems a reasonable initial guess at the guest speed.
5205 It will be corrected fairly quickly anyway. */
5206 icount_time_shift = 3;
5207 init_icount_adjust();
5210 #ifdef _WIN32
5211 socket_init();
5212 #endif
5214 /* init network clients */
5215 if (nb_net_clients == 0) {
5216 /* if no clients, we use a default config */
5217 net_clients[nb_net_clients++] = "nic";
5218 #ifdef CONFIG_SLIRP
5219 net_clients[nb_net_clients++] = "user";
5220 #endif
5223 for(i = 0;i < nb_net_clients; i++) {
5224 if (net_client_parse(net_clients[i]) < 0)
5225 exit(1);
5227 net_client_check();
5229 #ifdef TARGET_I386
5230 /* XXX: this should be moved in the PC machine instantiation code */
5231 if (net_boot != 0) {
5232 int netroms = 0;
5233 for (i = 0; i < nb_nics && i < 4; i++) {
5234 const char *model = nd_table[i].model;
5235 char buf[1024];
5236 if (net_boot & (1 << i)) {
5237 if (model == NULL)
5238 model = "ne2k_pci";
5239 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5240 if (get_image_size(buf) > 0) {
5241 if (nb_option_roms >= MAX_OPTION_ROMS) {
5242 fprintf(stderr, "Too many option ROMs\n");
5243 exit(1);
5245 option_rom[nb_option_roms] = strdup(buf);
5246 nb_option_roms++;
5247 netroms++;
5251 if (netroms == 0) {
5252 fprintf(stderr, "No valid PXE rom found for network device\n");
5253 exit(1);
5256 #endif
5258 /* init the bluetooth world */
5259 for (i = 0; i < nb_bt_opts; i++)
5260 if (bt_parse(bt_opts[i]))
5261 exit(1);
5263 /* init the memory */
5264 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5266 if (machine->ram_require & RAMSIZE_FIXED) {
5267 if (ram_size > 0) {
5268 if (ram_size < phys_ram_size) {
5269 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5270 machine->name, (unsigned long long) phys_ram_size);
5271 exit(-1);
5274 phys_ram_size = ram_size;
5275 } else
5276 ram_size = phys_ram_size;
5277 } else {
5278 if (ram_size == 0)
5279 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5281 phys_ram_size += ram_size;
5284 phys_ram_base = qemu_vmalloc(phys_ram_size);
5285 if (!phys_ram_base) {
5286 fprintf(stderr, "Could not allocate physical memory\n");
5287 exit(1);
5290 /* init the dynamic translator */
5291 cpu_exec_init_all(tb_size * 1024 * 1024);
5293 bdrv_init();
5295 /* we always create the cdrom drive, even if no disk is there */
5297 if (nb_drives_opt < MAX_DRIVES)
5298 drive_add(NULL, CDROM_ALIAS);
5300 /* we always create at least one floppy */
5302 if (nb_drives_opt < MAX_DRIVES)
5303 drive_add(NULL, FD_ALIAS, 0);
5305 /* we always create one sd slot, even if no card is in it */
5307 if (nb_drives_opt < MAX_DRIVES)
5308 drive_add(NULL, SD_ALIAS);
5310 /* open the virtual block devices */
5312 for(i = 0; i < nb_drives_opt; i++)
5313 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5314 exit(1);
5316 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5317 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5319 /* terminal init */
5320 memset(&display_state, 0, sizeof(display_state));
5321 if (nographic) {
5322 if (curses) {
5323 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5324 exit(1);
5326 /* nearly nothing to do */
5327 dumb_display_init(ds);
5328 } else if (vnc_display != NULL) {
5329 vnc_display_init(ds);
5330 if (vnc_display_open(ds, vnc_display) < 0)
5331 exit(1);
5332 } else
5333 #if defined(CONFIG_CURSES)
5334 if (curses) {
5335 curses_display_init(ds, full_screen);
5336 } else
5337 #endif
5339 #if defined(CONFIG_SDL)
5340 sdl_display_init(ds, full_screen, no_frame);
5341 #elif defined(CONFIG_COCOA)
5342 cocoa_display_init(ds, full_screen);
5343 #else
5344 dumb_display_init(ds);
5345 #endif
5348 #ifndef _WIN32
5349 /* must be after terminal init, SDL library changes signal handlers */
5350 termsig_setup();
5351 #endif
5353 /* Maintain compatibility with multiple stdio monitors */
5354 if (!strcmp(monitor_device,"stdio")) {
5355 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5356 const char *devname = serial_devices[i];
5357 if (devname && !strcmp(devname,"mon:stdio")) {
5358 monitor_device = NULL;
5359 break;
5360 } else if (devname && !strcmp(devname,"stdio")) {
5361 monitor_device = NULL;
5362 serial_devices[i] = "mon:stdio";
5363 break;
5367 if (monitor_device) {
5368 monitor_hd = qemu_chr_open("monitor", monitor_device);
5369 if (!monitor_hd) {
5370 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5371 exit(1);
5373 monitor_init(monitor_hd, !nographic);
5376 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5377 const char *devname = serial_devices[i];
5378 if (devname && strcmp(devname, "none")) {
5379 char label[32];
5380 snprintf(label, sizeof(label), "serial%d", i);
5381 serial_hds[i] = qemu_chr_open(label, devname);
5382 if (!serial_hds[i]) {
5383 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5384 devname);
5385 exit(1);
5387 if (strstart(devname, "vc", 0))
5388 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5392 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5393 const char *devname = parallel_devices[i];
5394 if (devname && strcmp(devname, "none")) {
5395 char label[32];
5396 snprintf(label, sizeof(label), "parallel%d", i);
5397 parallel_hds[i] = qemu_chr_open(label, devname);
5398 if (!parallel_hds[i]) {
5399 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5400 devname);
5401 exit(1);
5403 if (strstart(devname, "vc", 0))
5404 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5408 if (kvm_enabled()) {
5409 int ret;
5411 ret = kvm_init(smp_cpus);
5412 if (ret < 0) {
5413 fprintf(stderr, "failed to initialize KVM\n");
5414 exit(1);
5418 machine->init(ram_size, vga_ram_size, boot_devices, ds,
5419 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5421 /* init USB devices */
5422 if (usb_enabled) {
5423 for(i = 0; i < usb_devices_index; i++) {
5424 if (usb_device_add(usb_devices[i]) < 0) {
5425 fprintf(stderr, "Warning: could not add USB device %s\n",
5426 usb_devices[i]);
5431 if (display_state.dpy_refresh) {
5432 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5433 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5436 #ifdef CONFIG_GDBSTUB
5437 if (use_gdbstub) {
5438 /* XXX: use standard host:port notation and modify options
5439 accordingly. */
5440 if (gdbserver_start(gdbstub_port) < 0) {
5441 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5442 gdbstub_port);
5443 exit(1);
5446 #endif
5448 if (loadvm)
5449 do_loadvm(loadvm);
5451 if (incoming) {
5452 autostart = 0; /* fixme how to deal with -daemonize */
5453 qemu_start_incoming_migration(incoming);
5457 /* XXX: simplify init */
5458 read_passwords();
5459 if (autostart) {
5460 vm_start();
5464 if (daemonize) {
5465 uint8_t status = 0;
5466 ssize_t len;
5467 int fd;
5469 again1:
5470 len = write(fds[1], &status, 1);
5471 if (len == -1 && (errno == EINTR))
5472 goto again1;
5474 if (len != 1)
5475 exit(1);
5477 chdir("/");
5478 TFR(fd = open("/dev/null", O_RDWR));
5479 if (fd == -1)
5480 exit(1);
5482 dup2(fd, 0);
5483 dup2(fd, 1);
5484 dup2(fd, 2);
5486 close(fd);
5489 main_loop();
5490 quit_timers();
5491 net_cleanup();
5493 return 0;