monitor: Don't change VNC server when disabled (Jan Kiszka)
[qemu.git] / vl.c
blob5f237d0a06843b85da12c86c94e9207ee600f045
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "migration.h"
43 #include "kvm.h"
44 #include "balloon.h"
46 #include <unistd.h>
47 #include <fcntl.h>
48 #include <signal.h>
49 #include <time.h>
50 #include <errno.h>
51 #include <sys/time.h>
52 #include <zlib.h>
54 #ifndef _WIN32
55 #include <sys/times.h>
56 #include <sys/wait.h>
57 #include <termios.h>
58 #include <sys/mman.h>
59 #include <sys/ioctl.h>
60 #include <sys/resource.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <net/if.h>
64 #if defined(__NetBSD__)
65 #include <net/if_tap.h>
66 #endif
67 #ifdef __linux__
68 #include <linux/if_tun.h>
69 #endif
70 #include <arpa/inet.h>
71 #include <dirent.h>
72 #include <netdb.h>
73 #include <sys/select.h>
74 #ifdef _BSD
75 #include <sys/stat.h>
76 #ifdef __FreeBSD__
77 #include <libutil.h>
78 #else
79 #include <util.h>
80 #endif
81 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
82 #include <freebsd/stdlib.h>
83 #else
84 #ifdef __linux__
85 #include <pty.h>
86 #include <malloc.h>
87 #include <linux/rtc.h>
89 /* For the benefit of older linux systems which don't supply it,
90 we use a local copy of hpet.h. */
91 /* #include <linux/hpet.h> */
92 #include "hpet.h"
94 #include <linux/ppdev.h>
95 #include <linux/parport.h>
96 #endif
97 #ifdef __sun__
98 #include <sys/stat.h>
99 #include <sys/ethernet.h>
100 #include <sys/sockio.h>
101 #include <netinet/arp.h>
102 #include <netinet/in.h>
103 #include <netinet/in_systm.h>
104 #include <netinet/ip.h>
105 #include <netinet/ip_icmp.h> // must come after ip.h
106 #include <netinet/udp.h>
107 #include <netinet/tcp.h>
108 #include <net/if.h>
109 #include <syslog.h>
110 #include <stropts.h>
111 #endif
112 #endif
113 #endif
115 #include "qemu_socket.h"
117 #if defined(CONFIG_SLIRP)
118 #include "libslirp.h"
119 #endif
121 #if defined(__OpenBSD__)
122 #include <util.h>
123 #endif
125 #if defined(CONFIG_VDE)
126 #include <libvdeplug.h>
127 #endif
129 #ifdef _WIN32
130 #include <malloc.h>
131 #include <sys/timeb.h>
132 #include <mmsystem.h>
133 #define getopt_long_only getopt_long
134 #define memalign(align, size) malloc(size)
135 #endif
137 #ifdef CONFIG_SDL
138 #ifdef __APPLE__
139 #include <SDL/SDL.h>
140 #endif
141 #endif /* CONFIG_SDL */
143 #ifdef CONFIG_COCOA
144 #undef main
145 #define main qemu_main
146 #endif /* CONFIG_COCOA */
148 #include "disas.h"
150 #include "exec-all.h"
152 //#define DEBUG_UNUSED_IOPORT
153 //#define DEBUG_IOPORT
154 //#define DEBUG_NET
155 //#define DEBUG_SLIRP
158 #ifdef DEBUG_IOPORT
159 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
160 #else
161 # define LOG_IOPORT(...) do { } while (0)
162 #endif
164 #define DEFAULT_RAM_SIZE 128
166 /* Max number of USB devices that can be specified on the commandline. */
167 #define MAX_USB_CMDLINE 8
169 /* Max number of bluetooth switches on the commandline. */
170 #define MAX_BT_CMDLINE 10
172 /* XXX: use a two level table to limit memory usage */
173 #define MAX_IOPORTS 65536
175 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
176 const char *bios_name = NULL;
177 static void *ioport_opaque[MAX_IOPORTS];
178 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
179 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
180 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181 to store the VM snapshots */
182 DriveInfo drives_table[MAX_DRIVES+1];
183 int nb_drives;
184 static int vga_ram_size;
185 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186 static DisplayState *display_state;
187 int nographic;
188 static int curses;
189 static int sdl;
190 const char* keyboard_layout = NULL;
191 int64_t ticks_per_sec;
192 ram_addr_t ram_size;
193 int nb_nics;
194 NICInfo nd_table[MAX_NICS];
195 int vm_running;
196 static int rtc_utc = 1;
197 static int rtc_date_offset = -1; /* -1 means no change */
198 int cirrus_vga_enabled = 1;
199 int std_vga_enabled = 0;
200 int vmsvga_enabled = 0;
201 #ifdef TARGET_SPARC
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
205 #else
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
209 #endif
210 static int full_screen = 0;
211 #ifdef CONFIG_SDL
212 static int no_frame = 0;
213 #endif
214 int no_quit = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
218 #ifdef TARGET_I386
219 int win2k_install_hack = 0;
220 int rtc_td_hack = 0;
221 #endif
222 int usb_enabled = 0;
223 int smp_cpus = 1;
224 const char *vnc_display;
225 int acpi_enabled = 1;
226 int no_hpet = 0;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 int daemonize = 0;
233 const char *option_rom[MAX_OPTION_ROMS];
234 int nb_option_roms;
235 int semihosting_enabled = 0;
236 #ifdef TARGET_ARM
237 int old_param = 0;
238 #endif
239 const char *qemu_name;
240 int alt_grab = 0;
241 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
242 unsigned int nb_prom_envs = 0;
243 const char *prom_envs[MAX_PROM_ENVS];
244 #endif
245 int nb_drives_opt;
246 struct drive_opt drives_opt[MAX_DRIVES];
248 static CPUState *cur_cpu;
249 static CPUState *next_cpu;
250 static int event_pending = 1;
251 /* Conversion factor from emulated instructions to virtual clock ticks. */
252 static int icount_time_shift;
253 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
254 #define MAX_ICOUNT_SHIFT 10
255 /* Compensate for varying guest execution speed. */
256 static int64_t qemu_icount_bias;
257 static QEMUTimer *icount_rt_timer;
258 static QEMUTimer *icount_vm_timer;
259 static QEMUTimer *nographic_timer;
261 uint8_t qemu_uuid[16];
263 /***********************************************************/
264 /* x86 ISA bus support */
266 target_phys_addr_t isa_mem_base = 0;
267 PicState2 *isa_pic;
269 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
270 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
272 static uint32_t ioport_read(int index, uint32_t address)
274 static IOPortReadFunc *default_func[3] = {
275 default_ioport_readb,
276 default_ioport_readw,
277 default_ioport_readl
279 IOPortReadFunc *func = ioport_read_table[index][address];
280 if (!func)
281 func = default_func[index];
282 return func(ioport_opaque[address], address);
285 static void ioport_write(int index, uint32_t address, uint32_t data)
287 static IOPortWriteFunc *default_func[3] = {
288 default_ioport_writeb,
289 default_ioport_writew,
290 default_ioport_writel
292 IOPortWriteFunc *func = ioport_write_table[index][address];
293 if (!func)
294 func = default_func[index];
295 func(ioport_opaque[address], address, data);
298 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
300 #ifdef DEBUG_UNUSED_IOPORT
301 fprintf(stderr, "unused inb: port=0x%04x\n", address);
302 #endif
303 return 0xff;
306 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
308 #ifdef DEBUG_UNUSED_IOPORT
309 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
310 #endif
313 /* default is to make two byte accesses */
314 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
316 uint32_t data;
317 data = ioport_read(0, address);
318 address = (address + 1) & (MAX_IOPORTS - 1);
319 data |= ioport_read(0, address) << 8;
320 return data;
323 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
325 ioport_write(0, address, data & 0xff);
326 address = (address + 1) & (MAX_IOPORTS - 1);
327 ioport_write(0, address, (data >> 8) & 0xff);
330 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
332 #ifdef DEBUG_UNUSED_IOPORT
333 fprintf(stderr, "unused inl: port=0x%04x\n", address);
334 #endif
335 return 0xffffffff;
338 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
340 #ifdef DEBUG_UNUSED_IOPORT
341 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
342 #endif
345 /* size is the word size in byte */
346 int register_ioport_read(int start, int length, int size,
347 IOPortReadFunc *func, void *opaque)
349 int i, bsize;
351 if (size == 1) {
352 bsize = 0;
353 } else if (size == 2) {
354 bsize = 1;
355 } else if (size == 4) {
356 bsize = 2;
357 } else {
358 hw_error("register_ioport_read: invalid size");
359 return -1;
361 for(i = start; i < start + length; i += size) {
362 ioport_read_table[bsize][i] = func;
363 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
364 hw_error("register_ioport_read: invalid opaque");
365 ioport_opaque[i] = opaque;
367 return 0;
370 /* size is the word size in byte */
371 int register_ioport_write(int start, int length, int size,
372 IOPortWriteFunc *func, void *opaque)
374 int i, bsize;
376 if (size == 1) {
377 bsize = 0;
378 } else if (size == 2) {
379 bsize = 1;
380 } else if (size == 4) {
381 bsize = 2;
382 } else {
383 hw_error("register_ioport_write: invalid size");
384 return -1;
386 for(i = start; i < start + length; i += size) {
387 ioport_write_table[bsize][i] = func;
388 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
389 hw_error("register_ioport_write: invalid opaque");
390 ioport_opaque[i] = opaque;
392 return 0;
395 void isa_unassign_ioport(int start, int length)
397 int i;
399 for(i = start; i < start + length; i++) {
400 ioport_read_table[0][i] = default_ioport_readb;
401 ioport_read_table[1][i] = default_ioport_readw;
402 ioport_read_table[2][i] = default_ioport_readl;
404 ioport_write_table[0][i] = default_ioport_writeb;
405 ioport_write_table[1][i] = default_ioport_writew;
406 ioport_write_table[2][i] = default_ioport_writel;
408 ioport_opaque[i] = NULL;
412 /***********************************************************/
414 void cpu_outb(CPUState *env, int addr, int val)
416 LOG_IOPORT("outb: %04x %02x\n", addr, val);
417 ioport_write(0, addr, val);
418 #ifdef USE_KQEMU
419 if (env)
420 env->last_io_time = cpu_get_time_fast();
421 #endif
424 void cpu_outw(CPUState *env, int addr, int val)
426 LOG_IOPORT("outw: %04x %04x\n", addr, val);
427 ioport_write(1, addr, val);
428 #ifdef USE_KQEMU
429 if (env)
430 env->last_io_time = cpu_get_time_fast();
431 #endif
434 void cpu_outl(CPUState *env, int addr, int val)
436 LOG_IOPORT("outl: %04x %08x\n", addr, val);
437 ioport_write(2, addr, val);
438 #ifdef USE_KQEMU
439 if (env)
440 env->last_io_time = cpu_get_time_fast();
441 #endif
444 int cpu_inb(CPUState *env, int addr)
446 int val;
447 val = ioport_read(0, addr);
448 LOG_IOPORT("inb : %04x %02x\n", addr, val);
449 #ifdef USE_KQEMU
450 if (env)
451 env->last_io_time = cpu_get_time_fast();
452 #endif
453 return val;
456 int cpu_inw(CPUState *env, int addr)
458 int val;
459 val = ioport_read(1, addr);
460 LOG_IOPORT("inw : %04x %04x\n", addr, val);
461 #ifdef USE_KQEMU
462 if (env)
463 env->last_io_time = cpu_get_time_fast();
464 #endif
465 return val;
468 int cpu_inl(CPUState *env, int addr)
470 int val;
471 val = ioport_read(2, addr);
472 LOG_IOPORT("inl : %04x %08x\n", addr, val);
473 #ifdef USE_KQEMU
474 if (env)
475 env->last_io_time = cpu_get_time_fast();
476 #endif
477 return val;
480 /***********************************************************/
481 void hw_error(const char *fmt, ...)
483 va_list ap;
484 CPUState *env;
486 va_start(ap, fmt);
487 fprintf(stderr, "qemu: hardware error: ");
488 vfprintf(stderr, fmt, ap);
489 fprintf(stderr, "\n");
490 for(env = first_cpu; env != NULL; env = env->next_cpu) {
491 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
492 #ifdef TARGET_I386
493 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
494 #else
495 cpu_dump_state(env, stderr, fprintf, 0);
496 #endif
498 va_end(ap);
499 abort();
502 /***************/
503 /* ballooning */
505 static QEMUBalloonEvent *qemu_balloon_event;
506 void *qemu_balloon_event_opaque;
508 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
510 qemu_balloon_event = func;
511 qemu_balloon_event_opaque = opaque;
514 void qemu_balloon(ram_addr_t target)
516 if (qemu_balloon_event)
517 qemu_balloon_event(qemu_balloon_event_opaque, target);
520 ram_addr_t qemu_balloon_status(void)
522 if (qemu_balloon_event)
523 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
524 return 0;
527 /***********************************************************/
528 /* keyboard/mouse */
530 static QEMUPutKBDEvent *qemu_put_kbd_event;
531 static void *qemu_put_kbd_event_opaque;
532 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
533 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
535 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
537 qemu_put_kbd_event_opaque = opaque;
538 qemu_put_kbd_event = func;
541 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
542 void *opaque, int absolute,
543 const char *name)
545 QEMUPutMouseEntry *s, *cursor;
547 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
549 s->qemu_put_mouse_event = func;
550 s->qemu_put_mouse_event_opaque = opaque;
551 s->qemu_put_mouse_event_absolute = absolute;
552 s->qemu_put_mouse_event_name = qemu_strdup(name);
553 s->next = NULL;
555 if (!qemu_put_mouse_event_head) {
556 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
557 return s;
560 cursor = qemu_put_mouse_event_head;
561 while (cursor->next != NULL)
562 cursor = cursor->next;
564 cursor->next = s;
565 qemu_put_mouse_event_current = s;
567 return s;
570 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
572 QEMUPutMouseEntry *prev = NULL, *cursor;
574 if (!qemu_put_mouse_event_head || entry == NULL)
575 return;
577 cursor = qemu_put_mouse_event_head;
578 while (cursor != NULL && cursor != entry) {
579 prev = cursor;
580 cursor = cursor->next;
583 if (cursor == NULL) // does not exist or list empty
584 return;
585 else if (prev == NULL) { // entry is head
586 qemu_put_mouse_event_head = cursor->next;
587 if (qemu_put_mouse_event_current == entry)
588 qemu_put_mouse_event_current = cursor->next;
589 qemu_free(entry->qemu_put_mouse_event_name);
590 qemu_free(entry);
591 return;
594 prev->next = entry->next;
596 if (qemu_put_mouse_event_current == entry)
597 qemu_put_mouse_event_current = prev;
599 qemu_free(entry->qemu_put_mouse_event_name);
600 qemu_free(entry);
603 void kbd_put_keycode(int keycode)
605 if (qemu_put_kbd_event) {
606 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
610 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
612 QEMUPutMouseEvent *mouse_event;
613 void *mouse_event_opaque;
614 int width;
616 if (!qemu_put_mouse_event_current) {
617 return;
620 mouse_event =
621 qemu_put_mouse_event_current->qemu_put_mouse_event;
622 mouse_event_opaque =
623 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
625 if (mouse_event) {
626 if (graphic_rotate) {
627 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
628 width = 0x7fff;
629 else
630 width = graphic_width - 1;
631 mouse_event(mouse_event_opaque,
632 width - dy, dx, dz, buttons_state);
633 } else
634 mouse_event(mouse_event_opaque,
635 dx, dy, dz, buttons_state);
639 int kbd_mouse_is_absolute(void)
641 if (!qemu_put_mouse_event_current)
642 return 0;
644 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
647 void do_info_mice(void)
649 QEMUPutMouseEntry *cursor;
650 int index = 0;
652 if (!qemu_put_mouse_event_head) {
653 term_printf("No mouse devices connected\n");
654 return;
657 term_printf("Mouse devices available:\n");
658 cursor = qemu_put_mouse_event_head;
659 while (cursor != NULL) {
660 term_printf("%c Mouse #%d: %s\n",
661 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
662 index, cursor->qemu_put_mouse_event_name);
663 index++;
664 cursor = cursor->next;
668 void do_mouse_set(int index)
670 QEMUPutMouseEntry *cursor;
671 int i = 0;
673 if (!qemu_put_mouse_event_head) {
674 term_printf("No mouse devices connected\n");
675 return;
678 cursor = qemu_put_mouse_event_head;
679 while (cursor != NULL && index != i) {
680 i++;
681 cursor = cursor->next;
684 if (cursor != NULL)
685 qemu_put_mouse_event_current = cursor;
686 else
687 term_printf("Mouse at given index not found\n");
690 /* compute with 96 bit intermediate result: (a*b)/c */
691 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
693 union {
694 uint64_t ll;
695 struct {
696 #ifdef WORDS_BIGENDIAN
697 uint32_t high, low;
698 #else
699 uint32_t low, high;
700 #endif
701 } l;
702 } u, res;
703 uint64_t rl, rh;
705 u.ll = a;
706 rl = (uint64_t)u.l.low * (uint64_t)b;
707 rh = (uint64_t)u.l.high * (uint64_t)b;
708 rh += (rl >> 32);
709 res.l.high = rh / c;
710 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
711 return res.ll;
714 /***********************************************************/
715 /* real time host monotonic timer */
717 #define QEMU_TIMER_BASE 1000000000LL
719 #ifdef WIN32
721 static int64_t clock_freq;
723 static void init_get_clock(void)
725 LARGE_INTEGER freq;
726 int ret;
727 ret = QueryPerformanceFrequency(&freq);
728 if (ret == 0) {
729 fprintf(stderr, "Could not calibrate ticks\n");
730 exit(1);
732 clock_freq = freq.QuadPart;
735 static int64_t get_clock(void)
737 LARGE_INTEGER ti;
738 QueryPerformanceCounter(&ti);
739 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
742 #else
744 static int use_rt_clock;
746 static void init_get_clock(void)
748 use_rt_clock = 0;
749 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
751 struct timespec ts;
752 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
753 use_rt_clock = 1;
756 #endif
759 static int64_t get_clock(void)
761 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
762 if (use_rt_clock) {
763 struct timespec ts;
764 clock_gettime(CLOCK_MONOTONIC, &ts);
765 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
766 } else
767 #endif
769 /* XXX: using gettimeofday leads to problems if the date
770 changes, so it should be avoided. */
771 struct timeval tv;
772 gettimeofday(&tv, NULL);
773 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
776 #endif
778 /* Return the virtual CPU time, based on the instruction counter. */
779 static int64_t cpu_get_icount(void)
781 int64_t icount;
782 CPUState *env = cpu_single_env;;
783 icount = qemu_icount;
784 if (env) {
785 if (!can_do_io(env))
786 fprintf(stderr, "Bad clock read\n");
787 icount -= (env->icount_decr.u16.low + env->icount_extra);
789 return qemu_icount_bias + (icount << icount_time_shift);
792 /***********************************************************/
793 /* guest cycle counter */
795 static int64_t cpu_ticks_prev;
796 static int64_t cpu_ticks_offset;
797 static int64_t cpu_clock_offset;
798 static int cpu_ticks_enabled;
800 /* return the host CPU cycle counter and handle stop/restart */
801 int64_t cpu_get_ticks(void)
803 if (use_icount) {
804 return cpu_get_icount();
806 if (!cpu_ticks_enabled) {
807 return cpu_ticks_offset;
808 } else {
809 int64_t ticks;
810 ticks = cpu_get_real_ticks();
811 if (cpu_ticks_prev > ticks) {
812 /* Note: non increasing ticks may happen if the host uses
813 software suspend */
814 cpu_ticks_offset += cpu_ticks_prev - ticks;
816 cpu_ticks_prev = ticks;
817 return ticks + cpu_ticks_offset;
821 /* return the host CPU monotonic timer and handle stop/restart */
822 static int64_t cpu_get_clock(void)
824 int64_t ti;
825 if (!cpu_ticks_enabled) {
826 return cpu_clock_offset;
827 } else {
828 ti = get_clock();
829 return ti + cpu_clock_offset;
833 /* enable cpu_get_ticks() */
834 void cpu_enable_ticks(void)
836 if (!cpu_ticks_enabled) {
837 cpu_ticks_offset -= cpu_get_real_ticks();
838 cpu_clock_offset -= get_clock();
839 cpu_ticks_enabled = 1;
843 /* disable cpu_get_ticks() : the clock is stopped. You must not call
844 cpu_get_ticks() after that. */
845 void cpu_disable_ticks(void)
847 if (cpu_ticks_enabled) {
848 cpu_ticks_offset = cpu_get_ticks();
849 cpu_clock_offset = cpu_get_clock();
850 cpu_ticks_enabled = 0;
854 /***********************************************************/
855 /* timers */
857 #define QEMU_TIMER_REALTIME 0
858 #define QEMU_TIMER_VIRTUAL 1
860 struct QEMUClock {
861 int type;
862 /* XXX: add frequency */
865 struct QEMUTimer {
866 QEMUClock *clock;
867 int64_t expire_time;
868 QEMUTimerCB *cb;
869 void *opaque;
870 struct QEMUTimer *next;
873 struct qemu_alarm_timer {
874 char const *name;
875 unsigned int flags;
877 int (*start)(struct qemu_alarm_timer *t);
878 void (*stop)(struct qemu_alarm_timer *t);
879 void (*rearm)(struct qemu_alarm_timer *t);
880 void *priv;
883 #define ALARM_FLAG_DYNTICKS 0x1
884 #define ALARM_FLAG_EXPIRED 0x2
886 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
888 return t->flags & ALARM_FLAG_DYNTICKS;
891 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
893 if (!alarm_has_dynticks(t))
894 return;
896 t->rearm(t);
899 /* TODO: MIN_TIMER_REARM_US should be optimized */
900 #define MIN_TIMER_REARM_US 250
902 static struct qemu_alarm_timer *alarm_timer;
903 #ifndef _WIN32
904 static int alarm_timer_rfd, alarm_timer_wfd;
905 #endif
907 #ifdef _WIN32
909 struct qemu_alarm_win32 {
910 MMRESULT timerId;
911 HANDLE host_alarm;
912 unsigned int period;
913 } alarm_win32_data = {0, NULL, -1};
915 static int win32_start_timer(struct qemu_alarm_timer *t);
916 static void win32_stop_timer(struct qemu_alarm_timer *t);
917 static void win32_rearm_timer(struct qemu_alarm_timer *t);
919 #else
921 static int unix_start_timer(struct qemu_alarm_timer *t);
922 static void unix_stop_timer(struct qemu_alarm_timer *t);
924 #ifdef __linux__
926 static int dynticks_start_timer(struct qemu_alarm_timer *t);
927 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
928 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
930 static int hpet_start_timer(struct qemu_alarm_timer *t);
931 static void hpet_stop_timer(struct qemu_alarm_timer *t);
933 static int rtc_start_timer(struct qemu_alarm_timer *t);
934 static void rtc_stop_timer(struct qemu_alarm_timer *t);
936 #endif /* __linux__ */
938 #endif /* _WIN32 */
940 /* Correlation between real and virtual time is always going to be
941 fairly approximate, so ignore small variation.
942 When the guest is idle real and virtual time will be aligned in
943 the IO wait loop. */
944 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
946 static void icount_adjust(void)
948 int64_t cur_time;
949 int64_t cur_icount;
950 int64_t delta;
951 static int64_t last_delta;
952 /* If the VM is not running, then do nothing. */
953 if (!vm_running)
954 return;
956 cur_time = cpu_get_clock();
957 cur_icount = qemu_get_clock(vm_clock);
958 delta = cur_icount - cur_time;
959 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
960 if (delta > 0
961 && last_delta + ICOUNT_WOBBLE < delta * 2
962 && icount_time_shift > 0) {
963 /* The guest is getting too far ahead. Slow time down. */
964 icount_time_shift--;
966 if (delta < 0
967 && last_delta - ICOUNT_WOBBLE > delta * 2
968 && icount_time_shift < MAX_ICOUNT_SHIFT) {
969 /* The guest is getting too far behind. Speed time up. */
970 icount_time_shift++;
972 last_delta = delta;
973 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
976 static void icount_adjust_rt(void * opaque)
978 qemu_mod_timer(icount_rt_timer,
979 qemu_get_clock(rt_clock) + 1000);
980 icount_adjust();
983 static void icount_adjust_vm(void * opaque)
985 qemu_mod_timer(icount_vm_timer,
986 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
987 icount_adjust();
990 static void init_icount_adjust(void)
992 /* Have both realtime and virtual time triggers for speed adjustment.
993 The realtime trigger catches emulated time passing too slowly,
994 the virtual time trigger catches emulated time passing too fast.
995 Realtime triggers occur even when idle, so use them less frequently
996 than VM triggers. */
997 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
998 qemu_mod_timer(icount_rt_timer,
999 qemu_get_clock(rt_clock) + 1000);
1000 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1001 qemu_mod_timer(icount_vm_timer,
1002 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1005 static struct qemu_alarm_timer alarm_timers[] = {
1006 #ifndef _WIN32
1007 #ifdef __linux__
1008 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1009 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1010 /* HPET - if available - is preferred */
1011 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1012 /* ...otherwise try RTC */
1013 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1014 #endif
1015 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1016 #else
1017 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1018 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1019 {"win32", 0, win32_start_timer,
1020 win32_stop_timer, NULL, &alarm_win32_data},
1021 #endif
1022 {NULL, }
1025 static void show_available_alarms(void)
1027 int i;
1029 printf("Available alarm timers, in order of precedence:\n");
1030 for (i = 0; alarm_timers[i].name; i++)
1031 printf("%s\n", alarm_timers[i].name);
1034 static void configure_alarms(char const *opt)
1036 int i;
1037 int cur = 0;
1038 int count = ARRAY_SIZE(alarm_timers) - 1;
1039 char *arg;
1040 char *name;
1041 struct qemu_alarm_timer tmp;
1043 if (!strcmp(opt, "?")) {
1044 show_available_alarms();
1045 exit(0);
1048 arg = strdup(opt);
1050 /* Reorder the array */
1051 name = strtok(arg, ",");
1052 while (name) {
1053 for (i = 0; i < count && alarm_timers[i].name; i++) {
1054 if (!strcmp(alarm_timers[i].name, name))
1055 break;
1058 if (i == count) {
1059 fprintf(stderr, "Unknown clock %s\n", name);
1060 goto next;
1063 if (i < cur)
1064 /* Ignore */
1065 goto next;
1067 /* Swap */
1068 tmp = alarm_timers[i];
1069 alarm_timers[i] = alarm_timers[cur];
1070 alarm_timers[cur] = tmp;
1072 cur++;
1073 next:
1074 name = strtok(NULL, ",");
1077 free(arg);
1079 if (cur) {
1080 /* Disable remaining timers */
1081 for (i = cur; i < count; i++)
1082 alarm_timers[i].name = NULL;
1083 } else {
1084 show_available_alarms();
1085 exit(1);
1089 QEMUClock *rt_clock;
1090 QEMUClock *vm_clock;
1092 static QEMUTimer *active_timers[2];
1094 static QEMUClock *qemu_new_clock(int type)
1096 QEMUClock *clock;
1097 clock = qemu_mallocz(sizeof(QEMUClock));
1098 clock->type = type;
1099 return clock;
1102 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1104 QEMUTimer *ts;
1106 ts = qemu_mallocz(sizeof(QEMUTimer));
1107 ts->clock = clock;
1108 ts->cb = cb;
1109 ts->opaque = opaque;
1110 return ts;
1113 void qemu_free_timer(QEMUTimer *ts)
1115 qemu_free(ts);
1118 /* stop a timer, but do not dealloc it */
1119 void qemu_del_timer(QEMUTimer *ts)
1121 QEMUTimer **pt, *t;
1123 /* NOTE: this code must be signal safe because
1124 qemu_timer_expired() can be called from a signal. */
1125 pt = &active_timers[ts->clock->type];
1126 for(;;) {
1127 t = *pt;
1128 if (!t)
1129 break;
1130 if (t == ts) {
1131 *pt = t->next;
1132 break;
1134 pt = &t->next;
1138 /* modify the current timer so that it will be fired when current_time
1139 >= expire_time. The corresponding callback will be called. */
1140 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1142 QEMUTimer **pt, *t;
1144 qemu_del_timer(ts);
1146 /* add the timer in the sorted list */
1147 /* NOTE: this code must be signal safe because
1148 qemu_timer_expired() can be called from a signal. */
1149 pt = &active_timers[ts->clock->type];
1150 for(;;) {
1151 t = *pt;
1152 if (!t)
1153 break;
1154 if (t->expire_time > expire_time)
1155 break;
1156 pt = &t->next;
1158 ts->expire_time = expire_time;
1159 ts->next = *pt;
1160 *pt = ts;
1162 /* Rearm if necessary */
1163 if (pt == &active_timers[ts->clock->type]) {
1164 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1165 qemu_rearm_alarm_timer(alarm_timer);
1167 /* Interrupt execution to force deadline recalculation. */
1168 if (use_icount && cpu_single_env) {
1169 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1174 int qemu_timer_pending(QEMUTimer *ts)
1176 QEMUTimer *t;
1177 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1178 if (t == ts)
1179 return 1;
1181 return 0;
1184 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1186 if (!timer_head)
1187 return 0;
1188 return (timer_head->expire_time <= current_time);
1191 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1193 QEMUTimer *ts;
1195 for(;;) {
1196 ts = *ptimer_head;
1197 if (!ts || ts->expire_time > current_time)
1198 break;
1199 /* remove timer from the list before calling the callback */
1200 *ptimer_head = ts->next;
1201 ts->next = NULL;
1203 /* run the callback (the timer list can be modified) */
1204 ts->cb(ts->opaque);
1208 int64_t qemu_get_clock(QEMUClock *clock)
1210 switch(clock->type) {
1211 case QEMU_TIMER_REALTIME:
1212 return get_clock() / 1000000;
1213 default:
1214 case QEMU_TIMER_VIRTUAL:
1215 if (use_icount) {
1216 return cpu_get_icount();
1217 } else {
1218 return cpu_get_clock();
1223 static void init_timers(void)
1225 init_get_clock();
1226 ticks_per_sec = QEMU_TIMER_BASE;
1227 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1228 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1231 /* save a timer */
1232 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1234 uint64_t expire_time;
1236 if (qemu_timer_pending(ts)) {
1237 expire_time = ts->expire_time;
1238 } else {
1239 expire_time = -1;
1241 qemu_put_be64(f, expire_time);
1244 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1246 uint64_t expire_time;
1248 expire_time = qemu_get_be64(f);
1249 if (expire_time != -1) {
1250 qemu_mod_timer(ts, expire_time);
1251 } else {
1252 qemu_del_timer(ts);
1256 static void timer_save(QEMUFile *f, void *opaque)
1258 if (cpu_ticks_enabled) {
1259 hw_error("cannot save state if virtual timers are running");
1261 qemu_put_be64(f, cpu_ticks_offset);
1262 qemu_put_be64(f, ticks_per_sec);
1263 qemu_put_be64(f, cpu_clock_offset);
1266 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1268 if (version_id != 1 && version_id != 2)
1269 return -EINVAL;
1270 if (cpu_ticks_enabled) {
1271 return -EINVAL;
1273 cpu_ticks_offset=qemu_get_be64(f);
1274 ticks_per_sec=qemu_get_be64(f);
1275 if (version_id == 2) {
1276 cpu_clock_offset=qemu_get_be64(f);
1278 return 0;
1281 #ifdef _WIN32
1282 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1283 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1284 #else
1285 static void host_alarm_handler(int host_signum)
1286 #endif
1288 #if 0
1289 #define DISP_FREQ 1000
1291 static int64_t delta_min = INT64_MAX;
1292 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1293 static int count;
1294 ti = qemu_get_clock(vm_clock);
1295 if (last_clock != 0) {
1296 delta = ti - last_clock;
1297 if (delta < delta_min)
1298 delta_min = delta;
1299 if (delta > delta_max)
1300 delta_max = delta;
1301 delta_cum += delta;
1302 if (++count == DISP_FREQ) {
1303 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1304 muldiv64(delta_min, 1000000, ticks_per_sec),
1305 muldiv64(delta_max, 1000000, ticks_per_sec),
1306 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1307 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1308 count = 0;
1309 delta_min = INT64_MAX;
1310 delta_max = 0;
1311 delta_cum = 0;
1314 last_clock = ti;
1316 #endif
1317 if (alarm_has_dynticks(alarm_timer) ||
1318 (!use_icount &&
1319 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1320 qemu_get_clock(vm_clock))) ||
1321 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1322 qemu_get_clock(rt_clock))) {
1323 CPUState *env = next_cpu;
1325 #ifdef _WIN32
1326 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1327 SetEvent(data->host_alarm);
1328 #else
1329 static const char byte = 0;
1330 write(alarm_timer_wfd, &byte, sizeof(byte));
1331 #endif
1332 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1334 if (env) {
1335 /* stop the currently executing cpu because a timer occured */
1336 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1337 #ifdef USE_KQEMU
1338 if (env->kqemu_enabled) {
1339 kqemu_cpu_interrupt(env);
1341 #endif
1343 event_pending = 1;
1347 static int64_t qemu_next_deadline(void)
1349 int64_t delta;
1351 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1352 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1353 qemu_get_clock(vm_clock);
1354 } else {
1355 /* To avoid problems with overflow limit this to 2^32. */
1356 delta = INT32_MAX;
1359 if (delta < 0)
1360 delta = 0;
1362 return delta;
1365 #if defined(__linux__) || defined(_WIN32)
1366 static uint64_t qemu_next_deadline_dyntick(void)
1368 int64_t delta;
1369 int64_t rtdelta;
1371 if (use_icount)
1372 delta = INT32_MAX;
1373 else
1374 delta = (qemu_next_deadline() + 999) / 1000;
1376 if (active_timers[QEMU_TIMER_REALTIME]) {
1377 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1378 qemu_get_clock(rt_clock))*1000;
1379 if (rtdelta < delta)
1380 delta = rtdelta;
1383 if (delta < MIN_TIMER_REARM_US)
1384 delta = MIN_TIMER_REARM_US;
1386 return delta;
1388 #endif
1390 #ifndef _WIN32
1392 /* Sets a specific flag */
1393 static int fcntl_setfl(int fd, int flag)
1395 int flags;
1397 flags = fcntl(fd, F_GETFL);
1398 if (flags == -1)
1399 return -errno;
1401 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1402 return -errno;
1404 return 0;
1407 #if defined(__linux__)
1409 #define RTC_FREQ 1024
1411 static void enable_sigio_timer(int fd)
1413 struct sigaction act;
1415 /* timer signal */
1416 sigfillset(&act.sa_mask);
1417 act.sa_flags = 0;
1418 act.sa_handler = host_alarm_handler;
1420 sigaction(SIGIO, &act, NULL);
1421 fcntl_setfl(fd, O_ASYNC);
1422 fcntl(fd, F_SETOWN, getpid());
1425 static int hpet_start_timer(struct qemu_alarm_timer *t)
1427 struct hpet_info info;
1428 int r, fd;
1430 fd = open("/dev/hpet", O_RDONLY);
1431 if (fd < 0)
1432 return -1;
1434 /* Set frequency */
1435 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1436 if (r < 0) {
1437 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1438 "error, but for better emulation accuracy type:\n"
1439 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1440 goto fail;
1443 /* Check capabilities */
1444 r = ioctl(fd, HPET_INFO, &info);
1445 if (r < 0)
1446 goto fail;
1448 /* Enable periodic mode */
1449 r = ioctl(fd, HPET_EPI, 0);
1450 if (info.hi_flags && (r < 0))
1451 goto fail;
1453 /* Enable interrupt */
1454 r = ioctl(fd, HPET_IE_ON, 0);
1455 if (r < 0)
1456 goto fail;
1458 enable_sigio_timer(fd);
1459 t->priv = (void *)(long)fd;
1461 return 0;
1462 fail:
1463 close(fd);
1464 return -1;
1467 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1469 int fd = (long)t->priv;
1471 close(fd);
1474 static int rtc_start_timer(struct qemu_alarm_timer *t)
1476 int rtc_fd;
1477 unsigned long current_rtc_freq = 0;
1479 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1480 if (rtc_fd < 0)
1481 return -1;
1482 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1483 if (current_rtc_freq != RTC_FREQ &&
1484 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1485 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1486 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1487 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1488 goto fail;
1490 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1491 fail:
1492 close(rtc_fd);
1493 return -1;
1496 enable_sigio_timer(rtc_fd);
1498 t->priv = (void *)(long)rtc_fd;
1500 return 0;
1503 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1505 int rtc_fd = (long)t->priv;
1507 close(rtc_fd);
1510 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1512 struct sigevent ev;
1513 timer_t host_timer;
1514 struct sigaction act;
1516 sigfillset(&act.sa_mask);
1517 act.sa_flags = 0;
1518 act.sa_handler = host_alarm_handler;
1520 sigaction(SIGALRM, &act, NULL);
1522 ev.sigev_value.sival_int = 0;
1523 ev.sigev_notify = SIGEV_SIGNAL;
1524 ev.sigev_signo = SIGALRM;
1526 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1527 perror("timer_create");
1529 /* disable dynticks */
1530 fprintf(stderr, "Dynamic Ticks disabled\n");
1532 return -1;
1535 t->priv = (void *)(long)host_timer;
1537 return 0;
1540 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1542 timer_t host_timer = (timer_t)(long)t->priv;
1544 timer_delete(host_timer);
1547 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1549 timer_t host_timer = (timer_t)(long)t->priv;
1550 struct itimerspec timeout;
1551 int64_t nearest_delta_us = INT64_MAX;
1552 int64_t current_us;
1554 if (!active_timers[QEMU_TIMER_REALTIME] &&
1555 !active_timers[QEMU_TIMER_VIRTUAL])
1556 return;
1558 nearest_delta_us = qemu_next_deadline_dyntick();
1560 /* check whether a timer is already running */
1561 if (timer_gettime(host_timer, &timeout)) {
1562 perror("gettime");
1563 fprintf(stderr, "Internal timer error: aborting\n");
1564 exit(1);
1566 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1567 if (current_us && current_us <= nearest_delta_us)
1568 return;
1570 timeout.it_interval.tv_sec = 0;
1571 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1572 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1573 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1574 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1575 perror("settime");
1576 fprintf(stderr, "Internal timer error: aborting\n");
1577 exit(1);
1581 #endif /* defined(__linux__) */
1583 static int unix_start_timer(struct qemu_alarm_timer *t)
1585 struct sigaction act;
1586 struct itimerval itv;
1587 int err;
1589 /* timer signal */
1590 sigfillset(&act.sa_mask);
1591 act.sa_flags = 0;
1592 act.sa_handler = host_alarm_handler;
1594 sigaction(SIGALRM, &act, NULL);
1596 itv.it_interval.tv_sec = 0;
1597 /* for i386 kernel 2.6 to get 1 ms */
1598 itv.it_interval.tv_usec = 999;
1599 itv.it_value.tv_sec = 0;
1600 itv.it_value.tv_usec = 10 * 1000;
1602 err = setitimer(ITIMER_REAL, &itv, NULL);
1603 if (err)
1604 return -1;
1606 return 0;
1609 static void unix_stop_timer(struct qemu_alarm_timer *t)
1611 struct itimerval itv;
1613 memset(&itv, 0, sizeof(itv));
1614 setitimer(ITIMER_REAL, &itv, NULL);
1617 #endif /* !defined(_WIN32) */
1619 static void try_to_rearm_timer(void *opaque)
1621 struct qemu_alarm_timer *t = opaque;
1622 #ifndef _WIN32
1623 ssize_t len;
1625 /* Drain the notify pipe */
1626 do {
1627 char buffer[512];
1628 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1629 } while ((len == -1 && errno == EINTR) || len > 0);
1630 #endif
1632 if (t->flags & ALARM_FLAG_EXPIRED) {
1633 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1634 qemu_rearm_alarm_timer(alarm_timer);
1638 #ifdef _WIN32
1640 static int win32_start_timer(struct qemu_alarm_timer *t)
1642 TIMECAPS tc;
1643 struct qemu_alarm_win32 *data = t->priv;
1644 UINT flags;
1646 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1647 if (!data->host_alarm) {
1648 perror("Failed CreateEvent");
1649 return -1;
1652 memset(&tc, 0, sizeof(tc));
1653 timeGetDevCaps(&tc, sizeof(tc));
1655 if (data->period < tc.wPeriodMin)
1656 data->period = tc.wPeriodMin;
1658 timeBeginPeriod(data->period);
1660 flags = TIME_CALLBACK_FUNCTION;
1661 if (alarm_has_dynticks(t))
1662 flags |= TIME_ONESHOT;
1663 else
1664 flags |= TIME_PERIODIC;
1666 data->timerId = timeSetEvent(1, // interval (ms)
1667 data->period, // resolution
1668 host_alarm_handler, // function
1669 (DWORD)t, // parameter
1670 flags);
1672 if (!data->timerId) {
1673 perror("Failed to initialize win32 alarm timer");
1675 timeEndPeriod(data->period);
1676 CloseHandle(data->host_alarm);
1677 return -1;
1680 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1682 return 0;
1685 static void win32_stop_timer(struct qemu_alarm_timer *t)
1687 struct qemu_alarm_win32 *data = t->priv;
1689 timeKillEvent(data->timerId);
1690 timeEndPeriod(data->period);
1692 CloseHandle(data->host_alarm);
1695 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1697 struct qemu_alarm_win32 *data = t->priv;
1698 uint64_t nearest_delta_us;
1700 if (!active_timers[QEMU_TIMER_REALTIME] &&
1701 !active_timers[QEMU_TIMER_VIRTUAL])
1702 return;
1704 nearest_delta_us = qemu_next_deadline_dyntick();
1705 nearest_delta_us /= 1000;
1707 timeKillEvent(data->timerId);
1709 data->timerId = timeSetEvent(1,
1710 data->period,
1711 host_alarm_handler,
1712 (DWORD)t,
1713 TIME_ONESHOT | TIME_PERIODIC);
1715 if (!data->timerId) {
1716 perror("Failed to re-arm win32 alarm timer");
1718 timeEndPeriod(data->period);
1719 CloseHandle(data->host_alarm);
1720 exit(1);
1724 #endif /* _WIN32 */
1726 static int init_timer_alarm(void)
1728 struct qemu_alarm_timer *t = NULL;
1729 int i, err = -1;
1731 #ifndef _WIN32
1732 int fds[2];
1734 err = pipe(fds);
1735 if (err == -1)
1736 return -errno;
1738 err = fcntl_setfl(fds[0], O_NONBLOCK);
1739 if (err < 0)
1740 goto fail;
1742 err = fcntl_setfl(fds[1], O_NONBLOCK);
1743 if (err < 0)
1744 goto fail;
1746 alarm_timer_rfd = fds[0];
1747 alarm_timer_wfd = fds[1];
1748 #endif
1750 for (i = 0; alarm_timers[i].name; i++) {
1751 t = &alarm_timers[i];
1753 err = t->start(t);
1754 if (!err)
1755 break;
1758 if (err) {
1759 err = -ENOENT;
1760 goto fail;
1763 #ifndef _WIN32
1764 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1765 try_to_rearm_timer, NULL, t);
1766 #endif
1768 alarm_timer = t;
1770 return 0;
1772 fail:
1773 #ifndef _WIN32
1774 close(fds[0]);
1775 close(fds[1]);
1776 #endif
1777 return err;
1780 static void quit_timers(void)
1782 alarm_timer->stop(alarm_timer);
1783 alarm_timer = NULL;
1786 /***********************************************************/
1787 /* host time/date access */
1788 void qemu_get_timedate(struct tm *tm, int offset)
1790 time_t ti;
1791 struct tm *ret;
1793 time(&ti);
1794 ti += offset;
1795 if (rtc_date_offset == -1) {
1796 if (rtc_utc)
1797 ret = gmtime(&ti);
1798 else
1799 ret = localtime(&ti);
1800 } else {
1801 ti -= rtc_date_offset;
1802 ret = gmtime(&ti);
1805 memcpy(tm, ret, sizeof(struct tm));
1808 int qemu_timedate_diff(struct tm *tm)
1810 time_t seconds;
1812 if (rtc_date_offset == -1)
1813 if (rtc_utc)
1814 seconds = mktimegm(tm);
1815 else
1816 seconds = mktime(tm);
1817 else
1818 seconds = mktimegm(tm) + rtc_date_offset;
1820 return seconds - time(NULL);
1823 #ifdef _WIN32
1824 static void socket_cleanup(void)
1826 WSACleanup();
1829 static int socket_init(void)
1831 WSADATA Data;
1832 int ret, err;
1834 ret = WSAStartup(MAKEWORD(2,2), &Data);
1835 if (ret != 0) {
1836 err = WSAGetLastError();
1837 fprintf(stderr, "WSAStartup: %d\n", err);
1838 return -1;
1840 atexit(socket_cleanup);
1841 return 0;
1843 #endif
1845 const char *get_opt_name(char *buf, int buf_size, const char *p)
1847 char *q;
1849 q = buf;
1850 while (*p != '\0' && *p != '=') {
1851 if (q && (q - buf) < buf_size - 1)
1852 *q++ = *p;
1853 p++;
1855 if (q)
1856 *q = '\0';
1858 return p;
1861 const char *get_opt_value(char *buf, int buf_size, const char *p)
1863 char *q;
1865 q = buf;
1866 while (*p != '\0') {
1867 if (*p == ',') {
1868 if (*(p + 1) != ',')
1869 break;
1870 p++;
1872 if (q && (q - buf) < buf_size - 1)
1873 *q++ = *p;
1874 p++;
1876 if (q)
1877 *q = '\0';
1879 return p;
1882 int get_param_value(char *buf, int buf_size,
1883 const char *tag, const char *str)
1885 const char *p;
1886 char option[128];
1888 p = str;
1889 for(;;) {
1890 p = get_opt_name(option, sizeof(option), p);
1891 if (*p != '=')
1892 break;
1893 p++;
1894 if (!strcmp(tag, option)) {
1895 (void)get_opt_value(buf, buf_size, p);
1896 return strlen(buf);
1897 } else {
1898 p = get_opt_value(NULL, 0, p);
1900 if (*p != ',')
1901 break;
1902 p++;
1904 return 0;
1907 int check_params(char *buf, int buf_size,
1908 const char * const *params, const char *str)
1910 const char *p;
1911 int i;
1913 p = str;
1914 for(;;) {
1915 p = get_opt_name(buf, buf_size, p);
1916 if (*p != '=')
1917 return -1;
1918 p++;
1919 for(i = 0; params[i] != NULL; i++)
1920 if (!strcmp(params[i], buf))
1921 break;
1922 if (params[i] == NULL)
1923 return -1;
1924 p = get_opt_value(NULL, 0, p);
1925 if (*p != ',')
1926 break;
1927 p++;
1929 return 0;
1932 /***********************************************************/
1933 /* Bluetooth support */
1934 static int nb_hcis;
1935 static int cur_hci;
1936 static struct HCIInfo *hci_table[MAX_NICS];
1938 static struct bt_vlan_s {
1939 struct bt_scatternet_s net;
1940 int id;
1941 struct bt_vlan_s *next;
1942 } *first_bt_vlan;
1944 /* find or alloc a new bluetooth "VLAN" */
1945 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1947 struct bt_vlan_s **pvlan, *vlan;
1948 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1949 if (vlan->id == id)
1950 return &vlan->net;
1952 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1953 vlan->id = id;
1954 pvlan = &first_bt_vlan;
1955 while (*pvlan != NULL)
1956 pvlan = &(*pvlan)->next;
1957 *pvlan = vlan;
1958 return &vlan->net;
1961 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1965 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1967 return -ENOTSUP;
1970 static struct HCIInfo null_hci = {
1971 .cmd_send = null_hci_send,
1972 .sco_send = null_hci_send,
1973 .acl_send = null_hci_send,
1974 .bdaddr_set = null_hci_addr_set,
1977 struct HCIInfo *qemu_next_hci(void)
1979 if (cur_hci == nb_hcis)
1980 return &null_hci;
1982 return hci_table[cur_hci++];
1985 static struct HCIInfo *hci_init(const char *str)
1987 char *endp;
1988 struct bt_scatternet_s *vlan = 0;
1990 if (!strcmp(str, "null"))
1991 /* null */
1992 return &null_hci;
1993 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1994 /* host[:hciN] */
1995 return bt_host_hci(str[4] ? str + 5 : "hci0");
1996 else if (!strncmp(str, "hci", 3)) {
1997 /* hci[,vlan=n] */
1998 if (str[3]) {
1999 if (!strncmp(str + 3, ",vlan=", 6)) {
2000 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2001 if (*endp)
2002 vlan = 0;
2004 } else
2005 vlan = qemu_find_bt_vlan(0);
2006 if (vlan)
2007 return bt_new_hci(vlan);
2010 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2012 return 0;
2015 static int bt_hci_parse(const char *str)
2017 struct HCIInfo *hci;
2018 bdaddr_t bdaddr;
2020 if (nb_hcis >= MAX_NICS) {
2021 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2022 return -1;
2025 hci = hci_init(str);
2026 if (!hci)
2027 return -1;
2029 bdaddr.b[0] = 0x52;
2030 bdaddr.b[1] = 0x54;
2031 bdaddr.b[2] = 0x00;
2032 bdaddr.b[3] = 0x12;
2033 bdaddr.b[4] = 0x34;
2034 bdaddr.b[5] = 0x56 + nb_hcis;
2035 hci->bdaddr_set(hci, bdaddr.b);
2037 hci_table[nb_hcis++] = hci;
2039 return 0;
2042 static void bt_vhci_add(int vlan_id)
2044 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2046 if (!vlan->slave)
2047 fprintf(stderr, "qemu: warning: adding a VHCI to "
2048 "an empty scatternet %i\n", vlan_id);
2050 bt_vhci_init(bt_new_hci(vlan));
2053 static struct bt_device_s *bt_device_add(const char *opt)
2055 struct bt_scatternet_s *vlan;
2056 int vlan_id = 0;
2057 char *endp = strstr(opt, ",vlan=");
2058 int len = (endp ? endp - opt : strlen(opt)) + 1;
2059 char devname[10];
2061 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2063 if (endp) {
2064 vlan_id = strtol(endp + 6, &endp, 0);
2065 if (*endp) {
2066 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2067 return 0;
2071 vlan = qemu_find_bt_vlan(vlan_id);
2073 if (!vlan->slave)
2074 fprintf(stderr, "qemu: warning: adding a slave device to "
2075 "an empty scatternet %i\n", vlan_id);
2077 if (!strcmp(devname, "keyboard"))
2078 return bt_keyboard_init(vlan);
2080 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2081 return 0;
2084 static int bt_parse(const char *opt)
2086 const char *endp, *p;
2087 int vlan;
2089 if (strstart(opt, "hci", &endp)) {
2090 if (!*endp || *endp == ',') {
2091 if (*endp)
2092 if (!strstart(endp, ",vlan=", 0))
2093 opt = endp + 1;
2095 return bt_hci_parse(opt);
2097 } else if (strstart(opt, "vhci", &endp)) {
2098 if (!*endp || *endp == ',') {
2099 if (*endp) {
2100 if (strstart(endp, ",vlan=", &p)) {
2101 vlan = strtol(p, (char **) &endp, 0);
2102 if (*endp) {
2103 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2104 return 1;
2106 } else {
2107 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2108 return 1;
2110 } else
2111 vlan = 0;
2113 bt_vhci_add(vlan);
2114 return 0;
2116 } else if (strstart(opt, "device:", &endp))
2117 return !bt_device_add(endp);
2119 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2120 return 1;
2123 /***********************************************************/
2124 /* QEMU Block devices */
2126 #define HD_ALIAS "index=%d,media=disk"
2127 #ifdef TARGET_PPC
2128 #define CDROM_ALIAS "index=1,media=cdrom"
2129 #else
2130 #define CDROM_ALIAS "index=2,media=cdrom"
2131 #endif
2132 #define FD_ALIAS "index=%d,if=floppy"
2133 #define PFLASH_ALIAS "if=pflash"
2134 #define MTD_ALIAS "if=mtd"
2135 #define SD_ALIAS "index=0,if=sd"
2137 static int drive_opt_get_free_idx(void)
2139 int index;
2141 for (index = 0; index < MAX_DRIVES; index++)
2142 if (!drives_opt[index].used) {
2143 drives_opt[index].used = 1;
2144 return index;
2147 return -1;
2150 static int drive_get_free_idx(void)
2152 int index;
2154 for (index = 0; index < MAX_DRIVES; index++)
2155 if (!drives_table[index].used) {
2156 drives_table[index].used = 1;
2157 return index;
2160 return -1;
2163 int drive_add(const char *file, const char *fmt, ...)
2165 va_list ap;
2166 int index = drive_opt_get_free_idx();
2168 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2169 fprintf(stderr, "qemu: too many drives\n");
2170 return -1;
2173 drives_opt[index].file = file;
2174 va_start(ap, fmt);
2175 vsnprintf(drives_opt[index].opt,
2176 sizeof(drives_opt[0].opt), fmt, ap);
2177 va_end(ap);
2179 nb_drives_opt++;
2180 return index;
2183 void drive_remove(int index)
2185 drives_opt[index].used = 0;
2186 nb_drives_opt--;
2189 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2191 int index;
2193 /* seek interface, bus and unit */
2195 for (index = 0; index < MAX_DRIVES; index++)
2196 if (drives_table[index].type == type &&
2197 drives_table[index].bus == bus &&
2198 drives_table[index].unit == unit &&
2199 drives_table[index].used)
2200 return index;
2202 return -1;
2205 int drive_get_max_bus(BlockInterfaceType type)
2207 int max_bus;
2208 int index;
2210 max_bus = -1;
2211 for (index = 0; index < nb_drives; index++) {
2212 if(drives_table[index].type == type &&
2213 drives_table[index].bus > max_bus)
2214 max_bus = drives_table[index].bus;
2216 return max_bus;
2219 const char *drive_get_serial(BlockDriverState *bdrv)
2221 int index;
2223 for (index = 0; index < nb_drives; index++)
2224 if (drives_table[index].bdrv == bdrv)
2225 return drives_table[index].serial;
2227 return "\0";
2230 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2232 int index;
2234 for (index = 0; index < nb_drives; index++)
2235 if (drives_table[index].bdrv == bdrv)
2236 return drives_table[index].onerror;
2238 return BLOCK_ERR_REPORT;
2241 static void bdrv_format_print(void *opaque, const char *name)
2243 fprintf(stderr, " %s", name);
2246 void drive_uninit(BlockDriverState *bdrv)
2248 int i;
2250 for (i = 0; i < MAX_DRIVES; i++)
2251 if (drives_table[i].bdrv == bdrv) {
2252 drives_table[i].bdrv = NULL;
2253 drives_table[i].used = 0;
2254 drive_remove(drives_table[i].drive_opt_idx);
2255 nb_drives--;
2256 break;
2260 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2262 char buf[128];
2263 char file[1024];
2264 char devname[128];
2265 char serial[21];
2266 const char *mediastr = "";
2267 BlockInterfaceType type;
2268 enum { MEDIA_DISK, MEDIA_CDROM } media;
2269 int bus_id, unit_id;
2270 int cyls, heads, secs, translation;
2271 BlockDriverState *bdrv;
2272 BlockDriver *drv = NULL;
2273 QEMUMachine *machine = opaque;
2274 int max_devs;
2275 int index;
2276 int cache;
2277 int bdrv_flags, onerror;
2278 int drives_table_idx;
2279 char *str = arg->opt;
2280 static const char * const params[] = { "bus", "unit", "if", "index",
2281 "cyls", "heads", "secs", "trans",
2282 "media", "snapshot", "file",
2283 "cache", "format", "serial", "werror",
2284 NULL };
2286 if (check_params(buf, sizeof(buf), params, str) < 0) {
2287 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2288 buf, str);
2289 return -1;
2292 file[0] = 0;
2293 cyls = heads = secs = 0;
2294 bus_id = 0;
2295 unit_id = -1;
2296 translation = BIOS_ATA_TRANSLATION_AUTO;
2297 index = -1;
2298 cache = 3;
2300 if (machine->use_scsi) {
2301 type = IF_SCSI;
2302 max_devs = MAX_SCSI_DEVS;
2303 pstrcpy(devname, sizeof(devname), "scsi");
2304 } else {
2305 type = IF_IDE;
2306 max_devs = MAX_IDE_DEVS;
2307 pstrcpy(devname, sizeof(devname), "ide");
2309 media = MEDIA_DISK;
2311 /* extract parameters */
2313 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2314 bus_id = strtol(buf, NULL, 0);
2315 if (bus_id < 0) {
2316 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2317 return -1;
2321 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2322 unit_id = strtol(buf, NULL, 0);
2323 if (unit_id < 0) {
2324 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2325 return -1;
2329 if (get_param_value(buf, sizeof(buf), "if", str)) {
2330 pstrcpy(devname, sizeof(devname), buf);
2331 if (!strcmp(buf, "ide")) {
2332 type = IF_IDE;
2333 max_devs = MAX_IDE_DEVS;
2334 } else if (!strcmp(buf, "scsi")) {
2335 type = IF_SCSI;
2336 max_devs = MAX_SCSI_DEVS;
2337 } else if (!strcmp(buf, "floppy")) {
2338 type = IF_FLOPPY;
2339 max_devs = 0;
2340 } else if (!strcmp(buf, "pflash")) {
2341 type = IF_PFLASH;
2342 max_devs = 0;
2343 } else if (!strcmp(buf, "mtd")) {
2344 type = IF_MTD;
2345 max_devs = 0;
2346 } else if (!strcmp(buf, "sd")) {
2347 type = IF_SD;
2348 max_devs = 0;
2349 } else if (!strcmp(buf, "virtio")) {
2350 type = IF_VIRTIO;
2351 max_devs = 0;
2352 } else {
2353 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2354 return -1;
2358 if (get_param_value(buf, sizeof(buf), "index", str)) {
2359 index = strtol(buf, NULL, 0);
2360 if (index < 0) {
2361 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2362 return -1;
2366 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2367 cyls = strtol(buf, NULL, 0);
2370 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2371 heads = strtol(buf, NULL, 0);
2374 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2375 secs = strtol(buf, NULL, 0);
2378 if (cyls || heads || secs) {
2379 if (cyls < 1 || cyls > 16383) {
2380 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2381 return -1;
2383 if (heads < 1 || heads > 16) {
2384 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2385 return -1;
2387 if (secs < 1 || secs > 63) {
2388 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2389 return -1;
2393 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2394 if (!cyls) {
2395 fprintf(stderr,
2396 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2397 str);
2398 return -1;
2400 if (!strcmp(buf, "none"))
2401 translation = BIOS_ATA_TRANSLATION_NONE;
2402 else if (!strcmp(buf, "lba"))
2403 translation = BIOS_ATA_TRANSLATION_LBA;
2404 else if (!strcmp(buf, "auto"))
2405 translation = BIOS_ATA_TRANSLATION_AUTO;
2406 else {
2407 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2408 return -1;
2412 if (get_param_value(buf, sizeof(buf), "media", str)) {
2413 if (!strcmp(buf, "disk")) {
2414 media = MEDIA_DISK;
2415 } else if (!strcmp(buf, "cdrom")) {
2416 if (cyls || secs || heads) {
2417 fprintf(stderr,
2418 "qemu: '%s' invalid physical CHS format\n", str);
2419 return -1;
2421 media = MEDIA_CDROM;
2422 } else {
2423 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2424 return -1;
2428 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2429 if (!strcmp(buf, "on"))
2430 snapshot = 1;
2431 else if (!strcmp(buf, "off"))
2432 snapshot = 0;
2433 else {
2434 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2435 return -1;
2439 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2440 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2441 cache = 0;
2442 else if (!strcmp(buf, "writethrough"))
2443 cache = 1;
2444 else if (!strcmp(buf, "writeback"))
2445 cache = 2;
2446 else {
2447 fprintf(stderr, "qemu: invalid cache option\n");
2448 return -1;
2452 if (get_param_value(buf, sizeof(buf), "format", str)) {
2453 if (strcmp(buf, "?") == 0) {
2454 fprintf(stderr, "qemu: Supported formats:");
2455 bdrv_iterate_format(bdrv_format_print, NULL);
2456 fprintf(stderr, "\n");
2457 return -1;
2459 drv = bdrv_find_format(buf);
2460 if (!drv) {
2461 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2462 return -1;
2466 if (arg->file == NULL)
2467 get_param_value(file, sizeof(file), "file", str);
2468 else
2469 pstrcpy(file, sizeof(file), arg->file);
2471 if (!get_param_value(serial, sizeof(serial), "serial", str))
2472 memset(serial, 0, sizeof(serial));
2474 onerror = BLOCK_ERR_REPORT;
2475 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2476 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2477 fprintf(stderr, "werror is no supported by this format\n");
2478 return -1;
2480 if (!strcmp(buf, "ignore"))
2481 onerror = BLOCK_ERR_IGNORE;
2482 else if (!strcmp(buf, "enospc"))
2483 onerror = BLOCK_ERR_STOP_ENOSPC;
2484 else if (!strcmp(buf, "stop"))
2485 onerror = BLOCK_ERR_STOP_ANY;
2486 else if (!strcmp(buf, "report"))
2487 onerror = BLOCK_ERR_REPORT;
2488 else {
2489 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2490 return -1;
2494 /* compute bus and unit according index */
2496 if (index != -1) {
2497 if (bus_id != 0 || unit_id != -1) {
2498 fprintf(stderr,
2499 "qemu: '%s' index cannot be used with bus and unit\n", str);
2500 return -1;
2502 if (max_devs == 0)
2504 unit_id = index;
2505 bus_id = 0;
2506 } else {
2507 unit_id = index % max_devs;
2508 bus_id = index / max_devs;
2512 /* if user doesn't specify a unit_id,
2513 * try to find the first free
2516 if (unit_id == -1) {
2517 unit_id = 0;
2518 while (drive_get_index(type, bus_id, unit_id) != -1) {
2519 unit_id++;
2520 if (max_devs && unit_id >= max_devs) {
2521 unit_id -= max_devs;
2522 bus_id++;
2527 /* check unit id */
2529 if (max_devs && unit_id >= max_devs) {
2530 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2531 str, unit_id, max_devs - 1);
2532 return -1;
2536 * ignore multiple definitions
2539 if (drive_get_index(type, bus_id, unit_id) != -1)
2540 return -2;
2542 /* init */
2544 if (type == IF_IDE || type == IF_SCSI)
2545 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2546 if (max_devs)
2547 snprintf(buf, sizeof(buf), "%s%i%s%i",
2548 devname, bus_id, mediastr, unit_id);
2549 else
2550 snprintf(buf, sizeof(buf), "%s%s%i",
2551 devname, mediastr, unit_id);
2552 bdrv = bdrv_new(buf);
2553 drives_table_idx = drive_get_free_idx();
2554 drives_table[drives_table_idx].bdrv = bdrv;
2555 drives_table[drives_table_idx].type = type;
2556 drives_table[drives_table_idx].bus = bus_id;
2557 drives_table[drives_table_idx].unit = unit_id;
2558 drives_table[drives_table_idx].onerror = onerror;
2559 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2560 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2561 nb_drives++;
2563 switch(type) {
2564 case IF_IDE:
2565 case IF_SCSI:
2566 switch(media) {
2567 case MEDIA_DISK:
2568 if (cyls != 0) {
2569 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2570 bdrv_set_translation_hint(bdrv, translation);
2572 break;
2573 case MEDIA_CDROM:
2574 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2575 break;
2577 break;
2578 case IF_SD:
2579 /* FIXME: This isn't really a floppy, but it's a reasonable
2580 approximation. */
2581 case IF_FLOPPY:
2582 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2583 break;
2584 case IF_PFLASH:
2585 case IF_MTD:
2586 case IF_VIRTIO:
2587 break;
2589 if (!file[0])
2590 return -2;
2591 bdrv_flags = 0;
2592 if (snapshot) {
2593 bdrv_flags |= BDRV_O_SNAPSHOT;
2594 cache = 2; /* always use write-back with snapshot */
2596 if (cache == 0) /* no caching */
2597 bdrv_flags |= BDRV_O_NOCACHE;
2598 else if (cache == 2) /* write-back */
2599 bdrv_flags |= BDRV_O_CACHE_WB;
2600 else if (cache == 3) /* not specified */
2601 bdrv_flags |= BDRV_O_CACHE_DEF;
2602 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2603 fprintf(stderr, "qemu: could not open disk image %s\n",
2604 file);
2605 return -1;
2607 return drives_table_idx;
2610 /***********************************************************/
2611 /* USB devices */
2613 static USBPort *used_usb_ports;
2614 static USBPort *free_usb_ports;
2616 /* ??? Maybe change this to register a hub to keep track of the topology. */
2617 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2618 usb_attachfn attach)
2620 port->opaque = opaque;
2621 port->index = index;
2622 port->attach = attach;
2623 port->next = free_usb_ports;
2624 free_usb_ports = port;
2627 int usb_device_add_dev(USBDevice *dev)
2629 USBPort *port;
2631 /* Find a USB port to add the device to. */
2632 port = free_usb_ports;
2633 if (!port->next) {
2634 USBDevice *hub;
2636 /* Create a new hub and chain it on. */
2637 free_usb_ports = NULL;
2638 port->next = used_usb_ports;
2639 used_usb_ports = port;
2641 hub = usb_hub_init(VM_USB_HUB_SIZE);
2642 usb_attach(port, hub);
2643 port = free_usb_ports;
2646 free_usb_ports = port->next;
2647 port->next = used_usb_ports;
2648 used_usb_ports = port;
2649 usb_attach(port, dev);
2650 return 0;
2653 static int usb_device_add(const char *devname)
2655 const char *p;
2656 USBDevice *dev;
2658 if (!free_usb_ports)
2659 return -1;
2661 if (strstart(devname, "host:", &p)) {
2662 dev = usb_host_device_open(p);
2663 } else if (!strcmp(devname, "mouse")) {
2664 dev = usb_mouse_init();
2665 } else if (!strcmp(devname, "tablet")) {
2666 dev = usb_tablet_init();
2667 } else if (!strcmp(devname, "keyboard")) {
2668 dev = usb_keyboard_init();
2669 } else if (strstart(devname, "disk:", &p)) {
2670 dev = usb_msd_init(p);
2671 } else if (!strcmp(devname, "wacom-tablet")) {
2672 dev = usb_wacom_init();
2673 } else if (strstart(devname, "serial:", &p)) {
2674 dev = usb_serial_init(p);
2675 #ifdef CONFIG_BRLAPI
2676 } else if (!strcmp(devname, "braille")) {
2677 dev = usb_baum_init();
2678 #endif
2679 } else if (strstart(devname, "net:", &p)) {
2680 int nic = nb_nics;
2682 if (net_client_init("nic", p) < 0)
2683 return -1;
2684 nd_table[nic].model = "usb";
2685 dev = usb_net_init(&nd_table[nic]);
2686 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2687 dev = usb_bt_init(devname[2] ? hci_init(p) :
2688 bt_new_hci(qemu_find_bt_vlan(0)));
2689 } else {
2690 return -1;
2692 if (!dev)
2693 return -1;
2695 return usb_device_add_dev(dev);
2698 int usb_device_del_addr(int bus_num, int addr)
2700 USBPort *port;
2701 USBPort **lastp;
2702 USBDevice *dev;
2704 if (!used_usb_ports)
2705 return -1;
2707 if (bus_num != 0)
2708 return -1;
2710 lastp = &used_usb_ports;
2711 port = used_usb_ports;
2712 while (port && port->dev->addr != addr) {
2713 lastp = &port->next;
2714 port = port->next;
2717 if (!port)
2718 return -1;
2720 dev = port->dev;
2721 *lastp = port->next;
2722 usb_attach(port, NULL);
2723 dev->handle_destroy(dev);
2724 port->next = free_usb_ports;
2725 free_usb_ports = port;
2726 return 0;
2729 static int usb_device_del(const char *devname)
2731 int bus_num, addr;
2732 const char *p;
2734 if (strstart(devname, "host:", &p))
2735 return usb_host_device_close(p);
2737 if (!used_usb_ports)
2738 return -1;
2740 p = strchr(devname, '.');
2741 if (!p)
2742 return -1;
2743 bus_num = strtoul(devname, NULL, 0);
2744 addr = strtoul(p + 1, NULL, 0);
2746 return usb_device_del_addr(bus_num, addr);
2749 void do_usb_add(const char *devname)
2751 usb_device_add(devname);
2754 void do_usb_del(const char *devname)
2756 usb_device_del(devname);
2759 void usb_info(void)
2761 USBDevice *dev;
2762 USBPort *port;
2763 const char *speed_str;
2765 if (!usb_enabled) {
2766 term_printf("USB support not enabled\n");
2767 return;
2770 for (port = used_usb_ports; port; port = port->next) {
2771 dev = port->dev;
2772 if (!dev)
2773 continue;
2774 switch(dev->speed) {
2775 case USB_SPEED_LOW:
2776 speed_str = "1.5";
2777 break;
2778 case USB_SPEED_FULL:
2779 speed_str = "12";
2780 break;
2781 case USB_SPEED_HIGH:
2782 speed_str = "480";
2783 break;
2784 default:
2785 speed_str = "?";
2786 break;
2788 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2789 0, dev->addr, speed_str, dev->devname);
2793 /***********************************************************/
2794 /* PCMCIA/Cardbus */
2796 static struct pcmcia_socket_entry_s {
2797 struct pcmcia_socket_s *socket;
2798 struct pcmcia_socket_entry_s *next;
2799 } *pcmcia_sockets = 0;
2801 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2803 struct pcmcia_socket_entry_s *entry;
2805 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2806 entry->socket = socket;
2807 entry->next = pcmcia_sockets;
2808 pcmcia_sockets = entry;
2811 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2813 struct pcmcia_socket_entry_s *entry, **ptr;
2815 ptr = &pcmcia_sockets;
2816 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2817 if (entry->socket == socket) {
2818 *ptr = entry->next;
2819 qemu_free(entry);
2823 void pcmcia_info(void)
2825 struct pcmcia_socket_entry_s *iter;
2826 if (!pcmcia_sockets)
2827 term_printf("No PCMCIA sockets\n");
2829 for (iter = pcmcia_sockets; iter; iter = iter->next)
2830 term_printf("%s: %s\n", iter->socket->slot_string,
2831 iter->socket->attached ? iter->socket->card_string :
2832 "Empty");
2835 /***********************************************************/
2836 /* register display */
2838 void register_displaystate(DisplayState *ds)
2840 DisplayState **s;
2841 s = &display_state;
2842 while (*s != NULL)
2843 s = &(*s)->next;
2844 ds->next = NULL;
2845 *s = ds;
2848 DisplayState *get_displaystate(void)
2850 return display_state;
2853 /* dumb display */
2855 static void dumb_display_init(void)
2857 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2858 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2859 register_displaystate(ds);
2862 /***********************************************************/
2863 /* I/O handling */
2865 #define MAX_IO_HANDLERS 64
2867 typedef struct IOHandlerRecord {
2868 int fd;
2869 IOCanRWHandler *fd_read_poll;
2870 IOHandler *fd_read;
2871 IOHandler *fd_write;
2872 int deleted;
2873 void *opaque;
2874 /* temporary data */
2875 struct pollfd *ufd;
2876 struct IOHandlerRecord *next;
2877 } IOHandlerRecord;
2879 static IOHandlerRecord *first_io_handler;
2881 /* XXX: fd_read_poll should be suppressed, but an API change is
2882 necessary in the character devices to suppress fd_can_read(). */
2883 int qemu_set_fd_handler2(int fd,
2884 IOCanRWHandler *fd_read_poll,
2885 IOHandler *fd_read,
2886 IOHandler *fd_write,
2887 void *opaque)
2889 IOHandlerRecord **pioh, *ioh;
2891 if (!fd_read && !fd_write) {
2892 pioh = &first_io_handler;
2893 for(;;) {
2894 ioh = *pioh;
2895 if (ioh == NULL)
2896 break;
2897 if (ioh->fd == fd) {
2898 ioh->deleted = 1;
2899 break;
2901 pioh = &ioh->next;
2903 } else {
2904 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2905 if (ioh->fd == fd)
2906 goto found;
2908 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2909 ioh->next = first_io_handler;
2910 first_io_handler = ioh;
2911 found:
2912 ioh->fd = fd;
2913 ioh->fd_read_poll = fd_read_poll;
2914 ioh->fd_read = fd_read;
2915 ioh->fd_write = fd_write;
2916 ioh->opaque = opaque;
2917 ioh->deleted = 0;
2919 return 0;
2922 int qemu_set_fd_handler(int fd,
2923 IOHandler *fd_read,
2924 IOHandler *fd_write,
2925 void *opaque)
2927 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2930 #ifdef _WIN32
2931 /***********************************************************/
2932 /* Polling handling */
2934 typedef struct PollingEntry {
2935 PollingFunc *func;
2936 void *opaque;
2937 struct PollingEntry *next;
2938 } PollingEntry;
2940 static PollingEntry *first_polling_entry;
2942 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2944 PollingEntry **ppe, *pe;
2945 pe = qemu_mallocz(sizeof(PollingEntry));
2946 pe->func = func;
2947 pe->opaque = opaque;
2948 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2949 *ppe = pe;
2950 return 0;
2953 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2955 PollingEntry **ppe, *pe;
2956 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2957 pe = *ppe;
2958 if (pe->func == func && pe->opaque == opaque) {
2959 *ppe = pe->next;
2960 qemu_free(pe);
2961 break;
2966 /***********************************************************/
2967 /* Wait objects support */
2968 typedef struct WaitObjects {
2969 int num;
2970 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2971 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2972 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2973 } WaitObjects;
2975 static WaitObjects wait_objects = {0};
2977 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2979 WaitObjects *w = &wait_objects;
2981 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2982 return -1;
2983 w->events[w->num] = handle;
2984 w->func[w->num] = func;
2985 w->opaque[w->num] = opaque;
2986 w->num++;
2987 return 0;
2990 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2992 int i, found;
2993 WaitObjects *w = &wait_objects;
2995 found = 0;
2996 for (i = 0; i < w->num; i++) {
2997 if (w->events[i] == handle)
2998 found = 1;
2999 if (found) {
3000 w->events[i] = w->events[i + 1];
3001 w->func[i] = w->func[i + 1];
3002 w->opaque[i] = w->opaque[i + 1];
3005 if (found)
3006 w->num--;
3008 #endif
3010 /***********************************************************/
3011 /* ram save/restore */
3013 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3015 int v;
3017 v = qemu_get_byte(f);
3018 switch(v) {
3019 case 0:
3020 if (qemu_get_buffer(f, buf, len) != len)
3021 return -EIO;
3022 break;
3023 case 1:
3024 v = qemu_get_byte(f);
3025 memset(buf, v, len);
3026 break;
3027 default:
3028 return -EINVAL;
3031 if (qemu_file_has_error(f))
3032 return -EIO;
3034 return 0;
3037 static int ram_load_v1(QEMUFile *f, void *opaque)
3039 int ret;
3040 ram_addr_t i;
3042 if (qemu_get_be32(f) != phys_ram_size)
3043 return -EINVAL;
3044 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3045 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3046 if (ret)
3047 return ret;
3049 return 0;
3052 #define BDRV_HASH_BLOCK_SIZE 1024
3053 #define IOBUF_SIZE 4096
3054 #define RAM_CBLOCK_MAGIC 0xfabe
3056 typedef struct RamDecompressState {
3057 z_stream zstream;
3058 QEMUFile *f;
3059 uint8_t buf[IOBUF_SIZE];
3060 } RamDecompressState;
3062 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3064 int ret;
3065 memset(s, 0, sizeof(*s));
3066 s->f = f;
3067 ret = inflateInit(&s->zstream);
3068 if (ret != Z_OK)
3069 return -1;
3070 return 0;
3073 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3075 int ret, clen;
3077 s->zstream.avail_out = len;
3078 s->zstream.next_out = buf;
3079 while (s->zstream.avail_out > 0) {
3080 if (s->zstream.avail_in == 0) {
3081 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3082 return -1;
3083 clen = qemu_get_be16(s->f);
3084 if (clen > IOBUF_SIZE)
3085 return -1;
3086 qemu_get_buffer(s->f, s->buf, clen);
3087 s->zstream.avail_in = clen;
3088 s->zstream.next_in = s->buf;
3090 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3091 if (ret != Z_OK && ret != Z_STREAM_END) {
3092 return -1;
3095 return 0;
3098 static void ram_decompress_close(RamDecompressState *s)
3100 inflateEnd(&s->zstream);
3103 #define RAM_SAVE_FLAG_FULL 0x01
3104 #define RAM_SAVE_FLAG_COMPRESS 0x02
3105 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3106 #define RAM_SAVE_FLAG_PAGE 0x08
3107 #define RAM_SAVE_FLAG_EOS 0x10
3109 static int is_dup_page(uint8_t *page, uint8_t ch)
3111 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3112 uint32_t *array = (uint32_t *)page;
3113 int i;
3115 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3116 if (array[i] != val)
3117 return 0;
3120 return 1;
3123 static int ram_save_block(QEMUFile *f)
3125 static ram_addr_t current_addr = 0;
3126 ram_addr_t saved_addr = current_addr;
3127 ram_addr_t addr = 0;
3128 int found = 0;
3130 while (addr < phys_ram_size) {
3131 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3132 uint8_t ch;
3134 cpu_physical_memory_reset_dirty(current_addr,
3135 current_addr + TARGET_PAGE_SIZE,
3136 MIGRATION_DIRTY_FLAG);
3138 ch = *(phys_ram_base + current_addr);
3140 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3141 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3142 qemu_put_byte(f, ch);
3143 } else {
3144 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3145 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3148 found = 1;
3149 break;
3151 addr += TARGET_PAGE_SIZE;
3152 current_addr = (saved_addr + addr) % phys_ram_size;
3155 return found;
3158 static ram_addr_t ram_save_threshold = 10;
3160 static ram_addr_t ram_save_remaining(void)
3162 ram_addr_t addr;
3163 ram_addr_t count = 0;
3165 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3166 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3167 count++;
3170 return count;
3173 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3175 ram_addr_t addr;
3177 if (stage == 1) {
3178 /* Make sure all dirty bits are set */
3179 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3180 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3181 cpu_physical_memory_set_dirty(addr);
3184 /* Enable dirty memory tracking */
3185 cpu_physical_memory_set_dirty_tracking(1);
3187 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3190 while (!qemu_file_rate_limit(f)) {
3191 int ret;
3193 ret = ram_save_block(f);
3194 if (ret == 0) /* no more blocks */
3195 break;
3198 /* try transferring iterative blocks of memory */
3200 if (stage == 3) {
3201 cpu_physical_memory_set_dirty_tracking(0);
3203 /* flush all remaining blocks regardless of rate limiting */
3204 while (ram_save_block(f) != 0);
3207 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3209 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3212 static int ram_load_dead(QEMUFile *f, void *opaque)
3214 RamDecompressState s1, *s = &s1;
3215 uint8_t buf[10];
3216 ram_addr_t i;
3218 if (ram_decompress_open(s, f) < 0)
3219 return -EINVAL;
3220 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3221 if (ram_decompress_buf(s, buf, 1) < 0) {
3222 fprintf(stderr, "Error while reading ram block header\n");
3223 goto error;
3225 if (buf[0] == 0) {
3226 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3227 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3228 goto error;
3230 } else {
3231 error:
3232 printf("Error block header\n");
3233 return -EINVAL;
3236 ram_decompress_close(s);
3238 return 0;
3241 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3243 ram_addr_t addr;
3244 int flags;
3246 if (version_id == 1)
3247 return ram_load_v1(f, opaque);
3249 if (version_id == 2) {
3250 if (qemu_get_be32(f) != phys_ram_size)
3251 return -EINVAL;
3252 return ram_load_dead(f, opaque);
3255 if (version_id != 3)
3256 return -EINVAL;
3258 do {
3259 addr = qemu_get_be64(f);
3261 flags = addr & ~TARGET_PAGE_MASK;
3262 addr &= TARGET_PAGE_MASK;
3264 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3265 if (addr != phys_ram_size)
3266 return -EINVAL;
3269 if (flags & RAM_SAVE_FLAG_FULL) {
3270 if (ram_load_dead(f, opaque) < 0)
3271 return -EINVAL;
3274 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3275 uint8_t ch = qemu_get_byte(f);
3276 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3277 } else if (flags & RAM_SAVE_FLAG_PAGE)
3278 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3279 } while (!(flags & RAM_SAVE_FLAG_EOS));
3281 return 0;
3284 void qemu_service_io(void)
3286 CPUState *env = cpu_single_env;
3287 if (env) {
3288 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3289 #ifdef USE_KQEMU
3290 if (env->kqemu_enabled) {
3291 kqemu_cpu_interrupt(env);
3293 #endif
3297 /***********************************************************/
3298 /* bottom halves (can be seen as timers which expire ASAP) */
3300 struct QEMUBH {
3301 QEMUBHFunc *cb;
3302 void *opaque;
3303 int scheduled;
3304 int idle;
3305 int deleted;
3306 QEMUBH *next;
3309 static QEMUBH *first_bh = NULL;
3311 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3313 QEMUBH *bh;
3314 bh = qemu_mallocz(sizeof(QEMUBH));
3315 bh->cb = cb;
3316 bh->opaque = opaque;
3317 bh->next = first_bh;
3318 first_bh = bh;
3319 return bh;
3322 int qemu_bh_poll(void)
3324 QEMUBH *bh, **bhp;
3325 int ret;
3327 ret = 0;
3328 for (bh = first_bh; bh; bh = bh->next) {
3329 if (!bh->deleted && bh->scheduled) {
3330 bh->scheduled = 0;
3331 if (!bh->idle)
3332 ret = 1;
3333 bh->idle = 0;
3334 bh->cb(bh->opaque);
3338 /* remove deleted bhs */
3339 bhp = &first_bh;
3340 while (*bhp) {
3341 bh = *bhp;
3342 if (bh->deleted) {
3343 *bhp = bh->next;
3344 qemu_free(bh);
3345 } else
3346 bhp = &bh->next;
3349 return ret;
3352 void qemu_bh_schedule_idle(QEMUBH *bh)
3354 if (bh->scheduled)
3355 return;
3356 bh->scheduled = 1;
3357 bh->idle = 1;
3360 void qemu_bh_schedule(QEMUBH *bh)
3362 CPUState *env = cpu_single_env;
3363 if (bh->scheduled)
3364 return;
3365 bh->scheduled = 1;
3366 bh->idle = 0;
3367 /* stop the currently executing CPU to execute the BH ASAP */
3368 if (env) {
3369 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3373 void qemu_bh_cancel(QEMUBH *bh)
3375 bh->scheduled = 0;
3378 void qemu_bh_delete(QEMUBH *bh)
3380 bh->scheduled = 0;
3381 bh->deleted = 1;
3384 static void qemu_bh_update_timeout(int *timeout)
3386 QEMUBH *bh;
3388 for (bh = first_bh; bh; bh = bh->next) {
3389 if (!bh->deleted && bh->scheduled) {
3390 if (bh->idle) {
3391 /* idle bottom halves will be polled at least
3392 * every 10ms */
3393 *timeout = MIN(10, *timeout);
3394 } else {
3395 /* non-idle bottom halves will be executed
3396 * immediately */
3397 *timeout = 0;
3398 break;
3404 /***********************************************************/
3405 /* machine registration */
3407 static QEMUMachine *first_machine = NULL;
3408 QEMUMachine *current_machine = NULL;
3410 int qemu_register_machine(QEMUMachine *m)
3412 QEMUMachine **pm;
3413 pm = &first_machine;
3414 while (*pm != NULL)
3415 pm = &(*pm)->next;
3416 m->next = NULL;
3417 *pm = m;
3418 return 0;
3421 static QEMUMachine *find_machine(const char *name)
3423 QEMUMachine *m;
3425 for(m = first_machine; m != NULL; m = m->next) {
3426 if (!strcmp(m->name, name))
3427 return m;
3429 return NULL;
3432 /***********************************************************/
3433 /* main execution loop */
3435 static void gui_update(void *opaque)
3437 uint64_t interval = GUI_REFRESH_INTERVAL;
3438 DisplayState *ds = opaque;
3439 DisplayChangeListener *dcl = ds->listeners;
3441 dpy_refresh(ds);
3443 while (dcl != NULL) {
3444 if (dcl->gui_timer_interval &&
3445 dcl->gui_timer_interval < interval)
3446 interval = dcl->gui_timer_interval;
3447 dcl = dcl->next;
3449 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3452 static void nographic_update(void *opaque)
3454 uint64_t interval = GUI_REFRESH_INTERVAL;
3456 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3459 struct vm_change_state_entry {
3460 VMChangeStateHandler *cb;
3461 void *opaque;
3462 LIST_ENTRY (vm_change_state_entry) entries;
3465 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3467 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3468 void *opaque)
3470 VMChangeStateEntry *e;
3472 e = qemu_mallocz(sizeof (*e));
3474 e->cb = cb;
3475 e->opaque = opaque;
3476 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3477 return e;
3480 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3482 LIST_REMOVE (e, entries);
3483 qemu_free (e);
3486 static void vm_state_notify(int running, int reason)
3488 VMChangeStateEntry *e;
3490 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3491 e->cb(e->opaque, running, reason);
3495 void vm_start(void)
3497 if (!vm_running) {
3498 cpu_enable_ticks();
3499 vm_running = 1;
3500 vm_state_notify(1, 0);
3501 qemu_rearm_alarm_timer(alarm_timer);
3505 void vm_stop(int reason)
3507 if (vm_running) {
3508 cpu_disable_ticks();
3509 vm_running = 0;
3510 vm_state_notify(0, reason);
3514 /* reset/shutdown handler */
3516 typedef struct QEMUResetEntry {
3517 QEMUResetHandler *func;
3518 void *opaque;
3519 struct QEMUResetEntry *next;
3520 } QEMUResetEntry;
3522 static QEMUResetEntry *first_reset_entry;
3523 static int reset_requested;
3524 static int shutdown_requested;
3525 static int powerdown_requested;
3527 int qemu_shutdown_requested(void)
3529 int r = shutdown_requested;
3530 shutdown_requested = 0;
3531 return r;
3534 int qemu_reset_requested(void)
3536 int r = reset_requested;
3537 reset_requested = 0;
3538 return r;
3541 int qemu_powerdown_requested(void)
3543 int r = powerdown_requested;
3544 powerdown_requested = 0;
3545 return r;
3548 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3550 QEMUResetEntry **pre, *re;
3552 pre = &first_reset_entry;
3553 while (*pre != NULL)
3554 pre = &(*pre)->next;
3555 re = qemu_mallocz(sizeof(QEMUResetEntry));
3556 re->func = func;
3557 re->opaque = opaque;
3558 re->next = NULL;
3559 *pre = re;
3562 void qemu_system_reset(void)
3564 QEMUResetEntry *re;
3566 /* reset all devices */
3567 for(re = first_reset_entry; re != NULL; re = re->next) {
3568 re->func(re->opaque);
3572 void qemu_system_reset_request(void)
3574 if (no_reboot) {
3575 shutdown_requested = 1;
3576 } else {
3577 reset_requested = 1;
3579 if (cpu_single_env)
3580 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3583 void qemu_system_shutdown_request(void)
3585 shutdown_requested = 1;
3586 if (cpu_single_env)
3587 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3590 void qemu_system_powerdown_request(void)
3592 powerdown_requested = 1;
3593 if (cpu_single_env)
3594 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3597 #ifdef _WIN32
3598 static void host_main_loop_wait(int *timeout)
3600 int ret, ret2, i;
3601 PollingEntry *pe;
3604 /* XXX: need to suppress polling by better using win32 events */
3605 ret = 0;
3606 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3607 ret |= pe->func(pe->opaque);
3609 if (ret == 0) {
3610 int err;
3611 WaitObjects *w = &wait_objects;
3613 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3614 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3615 if (w->func[ret - WAIT_OBJECT_0])
3616 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3618 /* Check for additional signaled events */
3619 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3621 /* Check if event is signaled */
3622 ret2 = WaitForSingleObject(w->events[i], 0);
3623 if(ret2 == WAIT_OBJECT_0) {
3624 if (w->func[i])
3625 w->func[i](w->opaque[i]);
3626 } else if (ret2 == WAIT_TIMEOUT) {
3627 } else {
3628 err = GetLastError();
3629 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3632 } else if (ret == WAIT_TIMEOUT) {
3633 } else {
3634 err = GetLastError();
3635 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3639 *timeout = 0;
3641 #else
3642 static void host_main_loop_wait(int *timeout)
3645 #endif
3647 void main_loop_wait(int timeout)
3649 IOHandlerRecord *ioh;
3650 fd_set rfds, wfds, xfds;
3651 int ret, nfds;
3652 struct timeval tv;
3654 qemu_bh_update_timeout(&timeout);
3656 host_main_loop_wait(&timeout);
3658 /* poll any events */
3659 /* XXX: separate device handlers from system ones */
3660 nfds = -1;
3661 FD_ZERO(&rfds);
3662 FD_ZERO(&wfds);
3663 FD_ZERO(&xfds);
3664 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3665 if (ioh->deleted)
3666 continue;
3667 if (ioh->fd_read &&
3668 (!ioh->fd_read_poll ||
3669 ioh->fd_read_poll(ioh->opaque) != 0)) {
3670 FD_SET(ioh->fd, &rfds);
3671 if (ioh->fd > nfds)
3672 nfds = ioh->fd;
3674 if (ioh->fd_write) {
3675 FD_SET(ioh->fd, &wfds);
3676 if (ioh->fd > nfds)
3677 nfds = ioh->fd;
3681 tv.tv_sec = timeout / 1000;
3682 tv.tv_usec = (timeout % 1000) * 1000;
3684 #if defined(CONFIG_SLIRP)
3685 if (slirp_is_inited()) {
3686 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3688 #endif
3689 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3690 if (ret > 0) {
3691 IOHandlerRecord **pioh;
3693 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3694 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3695 ioh->fd_read(ioh->opaque);
3697 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3698 ioh->fd_write(ioh->opaque);
3702 /* remove deleted IO handlers */
3703 pioh = &first_io_handler;
3704 while (*pioh) {
3705 ioh = *pioh;
3706 if (ioh->deleted) {
3707 *pioh = ioh->next;
3708 qemu_free(ioh);
3709 } else
3710 pioh = &ioh->next;
3713 #if defined(CONFIG_SLIRP)
3714 if (slirp_is_inited()) {
3715 if (ret < 0) {
3716 FD_ZERO(&rfds);
3717 FD_ZERO(&wfds);
3718 FD_ZERO(&xfds);
3720 slirp_select_poll(&rfds, &wfds, &xfds);
3722 #endif
3724 /* vm time timers */
3725 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3726 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3727 qemu_get_clock(vm_clock));
3729 /* real time timers */
3730 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3731 qemu_get_clock(rt_clock));
3733 /* Check bottom-halves last in case any of the earlier events triggered
3734 them. */
3735 qemu_bh_poll();
3739 static int main_loop(void)
3741 int ret, timeout;
3742 #ifdef CONFIG_PROFILER
3743 int64_t ti;
3744 #endif
3745 CPUState *env;
3747 cur_cpu = first_cpu;
3748 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3749 for(;;) {
3750 if (vm_running) {
3752 for(;;) {
3753 /* get next cpu */
3754 env = next_cpu;
3755 #ifdef CONFIG_PROFILER
3756 ti = profile_getclock();
3757 #endif
3758 if (use_icount) {
3759 int64_t count;
3760 int decr;
3761 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3762 env->icount_decr.u16.low = 0;
3763 env->icount_extra = 0;
3764 count = qemu_next_deadline();
3765 count = (count + (1 << icount_time_shift) - 1)
3766 >> icount_time_shift;
3767 qemu_icount += count;
3768 decr = (count > 0xffff) ? 0xffff : count;
3769 count -= decr;
3770 env->icount_decr.u16.low = decr;
3771 env->icount_extra = count;
3773 ret = cpu_exec(env);
3774 #ifdef CONFIG_PROFILER
3775 qemu_time += profile_getclock() - ti;
3776 #endif
3777 if (use_icount) {
3778 /* Fold pending instructions back into the
3779 instruction counter, and clear the interrupt flag. */
3780 qemu_icount -= (env->icount_decr.u16.low
3781 + env->icount_extra);
3782 env->icount_decr.u32 = 0;
3783 env->icount_extra = 0;
3785 next_cpu = env->next_cpu ?: first_cpu;
3786 if (event_pending && likely(ret != EXCP_DEBUG)) {
3787 ret = EXCP_INTERRUPT;
3788 event_pending = 0;
3789 break;
3791 if (ret == EXCP_HLT) {
3792 /* Give the next CPU a chance to run. */
3793 cur_cpu = env;
3794 continue;
3796 if (ret != EXCP_HALTED)
3797 break;
3798 /* all CPUs are halted ? */
3799 if (env == cur_cpu)
3800 break;
3802 cur_cpu = env;
3804 if (shutdown_requested) {
3805 ret = EXCP_INTERRUPT;
3806 if (no_shutdown) {
3807 vm_stop(0);
3808 no_shutdown = 0;
3810 else
3811 break;
3813 if (reset_requested) {
3814 reset_requested = 0;
3815 qemu_system_reset();
3816 ret = EXCP_INTERRUPT;
3818 if (powerdown_requested) {
3819 powerdown_requested = 0;
3820 qemu_system_powerdown();
3821 ret = EXCP_INTERRUPT;
3823 if (unlikely(ret == EXCP_DEBUG)) {
3824 gdb_set_stop_cpu(cur_cpu);
3825 vm_stop(EXCP_DEBUG);
3827 /* If all cpus are halted then wait until the next IRQ */
3828 /* XXX: use timeout computed from timers */
3829 if (ret == EXCP_HALTED) {
3830 if (use_icount) {
3831 int64_t add;
3832 int64_t delta;
3833 /* Advance virtual time to the next event. */
3834 if (use_icount == 1) {
3835 /* When not using an adaptive execution frequency
3836 we tend to get badly out of sync with real time,
3837 so just delay for a reasonable amount of time. */
3838 delta = 0;
3839 } else {
3840 delta = cpu_get_icount() - cpu_get_clock();
3842 if (delta > 0) {
3843 /* If virtual time is ahead of real time then just
3844 wait for IO. */
3845 timeout = (delta / 1000000) + 1;
3846 } else {
3847 /* Wait for either IO to occur or the next
3848 timer event. */
3849 add = qemu_next_deadline();
3850 /* We advance the timer before checking for IO.
3851 Limit the amount we advance so that early IO
3852 activity won't get the guest too far ahead. */
3853 if (add > 10000000)
3854 add = 10000000;
3855 delta += add;
3856 add = (add + (1 << icount_time_shift) - 1)
3857 >> icount_time_shift;
3858 qemu_icount += add;
3859 timeout = delta / 1000000;
3860 if (timeout < 0)
3861 timeout = 0;
3863 } else {
3864 timeout = 5000;
3866 } else {
3867 timeout = 0;
3869 } else {
3870 if (shutdown_requested) {
3871 ret = EXCP_INTERRUPT;
3872 break;
3874 timeout = 5000;
3876 #ifdef CONFIG_PROFILER
3877 ti = profile_getclock();
3878 #endif
3879 main_loop_wait(timeout);
3880 #ifdef CONFIG_PROFILER
3881 dev_time += profile_getclock() - ti;
3882 #endif
3884 cpu_disable_ticks();
3885 return ret;
3888 static void help(int exitcode)
3890 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3891 and qemu-doc.texi */
3892 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3893 "usage: %s [options] [disk_image]\n"
3894 "\n"
3895 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3896 "\n"
3897 "Standard options:\n"
3898 "-h or -help display this help and exit\n"
3899 "-M machine select emulated machine (-M ? for list)\n"
3900 "-cpu cpu select CPU (-cpu ? for list)\n"
3901 "-smp n set the number of CPUs to 'n' [default=1]\n"
3902 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3903 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3904 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3905 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3906 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3907 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3908 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3909 " use 'file' as a drive image\n"
3910 "-mtdblock file use 'file' as on-board Flash memory image\n"
3911 "-sd file use 'file' as SecureDigital card image\n"
3912 "-pflash file use 'file' as a parallel flash image\n"
3913 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3914 "-snapshot write to temporary files instead of disk image files\n"
3915 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3916 #ifndef _WIN32
3917 "-k language use keyboard layout (for example \"fr\" for French)\n"
3918 #endif
3919 #ifdef HAS_AUDIO
3920 "-audio-help print list of audio drivers and their options\n"
3921 "-soundhw c1,... enable audio support\n"
3922 " and only specified sound cards (comma separated list)\n"
3923 " use -soundhw ? to get the list of supported cards\n"
3924 " use -soundhw all to enable all of them\n"
3925 #endif
3926 "-usb enable the USB driver (will be the default soon)\n"
3927 "-usbdevice name add the host or guest USB device 'name'\n"
3928 "-name string set the name of the guest\n"
3929 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3930 " specify machine UUID\n"
3931 "\n"
3932 "Display options:\n"
3933 "-nographic disable graphical output and redirect serial I/Os to console\n"
3934 #ifdef CONFIG_CURSES
3935 "-curses use a curses/ncurses interface instead of SDL\n"
3936 #endif
3937 #ifdef CONFIG_SDL
3938 "-no-frame open SDL window without a frame and window decorations\n"
3939 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3940 "-no-quit disable SDL window close capability\n"
3941 "-sdl enable SDL\n"
3942 #endif
3943 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3944 "-vga [std|cirrus|vmware|none]\n"
3945 " select video card type\n"
3946 "-full-screen start in full screen\n"
3947 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3948 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3949 #endif
3950 "-vnc display start a VNC server on display\n"
3951 "\n"
3952 "Network options:\n"
3953 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3954 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3955 #ifdef CONFIG_SLIRP
3956 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3957 " connect the user mode network stack to VLAN 'n' and send\n"
3958 " hostname 'host' to DHCP clients\n"
3959 #endif
3960 #ifdef _WIN32
3961 "-net tap[,vlan=n][,name=str],ifname=name\n"
3962 " connect the host TAP network interface to VLAN 'n'\n"
3963 #else
3964 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3965 " connect the host TAP network interface to VLAN 'n' and use the\n"
3966 " network scripts 'file' (default=%s)\n"
3967 " and 'dfile' (default=%s);\n"
3968 " use '[down]script=no' to disable script execution;\n"
3969 " use 'fd=h' to connect to an already opened TAP interface\n"
3970 #endif
3971 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3972 " connect the vlan 'n' to another VLAN using a socket connection\n"
3973 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
3974 " connect the vlan 'n' to multicast maddr and port\n"
3975 #ifdef CONFIG_VDE
3976 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3977 " connect the vlan 'n' to port 'n' of a vde switch running\n"
3978 " on host and listening for incoming connections on 'socketpath'.\n"
3979 " Use group 'groupname' and mode 'octalmode' to change default\n"
3980 " ownership and permissions for communication port.\n"
3981 #endif
3982 "-net none use it alone to have zero network devices; if no -net option\n"
3983 " is provided, the default is '-net nic -net user'\n"
3984 #ifdef CONFIG_SLIRP
3985 "-tftp dir allow tftp access to files in dir [-net user]\n"
3986 "-bootp file advertise file in BOOTP replies\n"
3987 #ifndef _WIN32
3988 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3989 #endif
3990 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3991 " redirect TCP or UDP connections from host to guest [-net user]\n"
3992 #endif
3993 "\n"
3994 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
3995 "-bt hci,host[:id]\n"
3996 " use host's HCI with the given name\n"
3997 "-bt hci[,vlan=n]\n"
3998 " emulate a standard HCI in virtual scatternet 'n'\n"
3999 "-bt vhci[,vlan=n]\n"
4000 " add host computer to virtual scatternet 'n' using VHCI\n"
4001 "-bt device:dev[,vlan=n]\n"
4002 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4003 "\n"
4004 #ifdef TARGET_I386
4005 "\n"
4006 "i386 target only:\n"
4007 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4008 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4009 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4010 "-no-acpi disable ACPI\n"
4011 "-no-hpet disable HPET\n"
4012 #endif
4013 "Linux boot specific:\n"
4014 "-kernel bzImage use 'bzImage' as kernel image\n"
4015 "-append cmdline use 'cmdline' as kernel command line\n"
4016 "-initrd file use 'file' as initial ram disk\n"
4017 "\n"
4018 "Debug/Expert options:\n"
4019 "-serial dev redirect the serial port to char device 'dev'\n"
4020 "-parallel dev redirect the parallel port to char device 'dev'\n"
4021 "-monitor dev redirect the monitor to char device 'dev'\n"
4022 "-pidfile file write PID to 'file'\n"
4023 "-S freeze CPU at startup (use 'c' to start execution)\n"
4024 "-s wait gdb connection to port\n"
4025 "-p port set gdb connection port [default=%s]\n"
4026 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4027 "-hdachs c,h,s[,t]\n"
4028 " force hard disk 0 physical geometry and the optional BIOS\n"
4029 " translation (t=none or lba) (usually qemu can guess them)\n"
4030 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4031 "-bios file set the filename for the BIOS\n"
4032 #ifdef USE_KQEMU
4033 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4034 "-no-kqemu disable KQEMU kernel module usage\n"
4035 #endif
4036 #ifdef CONFIG_KVM
4037 "-enable-kvm enable KVM full virtualization support\n"
4038 #endif
4039 "-no-reboot exit instead of rebooting\n"
4040 "-no-shutdown stop before shutdown\n"
4041 "-loadvm [tag|id]\n"
4042 " start right away with a saved state (loadvm in monitor)\n"
4043 #ifndef _WIN32
4044 "-daemonize daemonize QEMU after initializing\n"
4045 #endif
4046 "-option-rom rom load a file, rom, into the option ROM space\n"
4047 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4048 "-prom-env variable=value\n"
4049 " set OpenBIOS nvram variables\n"
4050 #endif
4051 "-clock force the use of the given methods for timer alarm.\n"
4052 " To see what timers are available use -clock ?\n"
4053 "-localtime set the real time clock to local time [default=utc]\n"
4054 "-startdate select initial date of the clock\n"
4055 "-icount [N|auto]\n"
4056 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4057 "-echr chr set terminal escape character instead of ctrl-a\n"
4058 "-virtioconsole c\n"
4059 " set virtio console\n"
4060 "-show-cursor show cursor\n"
4061 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4062 "-semihosting semihosting mode\n"
4063 #endif
4064 #if defined(TARGET_ARM)
4065 "-old-param old param mode\n"
4066 #endif
4067 "-tb-size n set TB size\n"
4068 "-incoming p prepare for incoming migration, listen on port p\n"
4069 "\n"
4070 "During emulation, the following keys are useful:\n"
4071 "ctrl-alt-f toggle full screen\n"
4072 "ctrl-alt-n switch to virtual console 'n'\n"
4073 "ctrl-alt toggle mouse and keyboard grab\n"
4074 "\n"
4075 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4077 "qemu",
4078 DEFAULT_RAM_SIZE,
4079 #ifndef _WIN32
4080 DEFAULT_NETWORK_SCRIPT,
4081 DEFAULT_NETWORK_DOWN_SCRIPT,
4082 #endif
4083 DEFAULT_GDBSTUB_PORT,
4084 "/tmp/qemu.log");
4085 exit(exitcode);
4088 #define HAS_ARG 0x0001
4090 enum {
4091 /* Please keep in synch with help, qemu_options[] and
4092 qemu-doc.texi */
4093 /* Standard options: */
4094 QEMU_OPTION_h,
4095 QEMU_OPTION_M,
4096 QEMU_OPTION_cpu,
4097 QEMU_OPTION_smp,
4098 QEMU_OPTION_fda,
4099 QEMU_OPTION_fdb,
4100 QEMU_OPTION_hda,
4101 QEMU_OPTION_hdb,
4102 QEMU_OPTION_hdc,
4103 QEMU_OPTION_hdd,
4104 QEMU_OPTION_cdrom,
4105 QEMU_OPTION_drive,
4106 QEMU_OPTION_mtdblock,
4107 QEMU_OPTION_sd,
4108 QEMU_OPTION_pflash,
4109 QEMU_OPTION_boot,
4110 QEMU_OPTION_snapshot,
4111 QEMU_OPTION_m,
4112 QEMU_OPTION_k,
4113 QEMU_OPTION_audio_help,
4114 QEMU_OPTION_soundhw,
4115 QEMU_OPTION_usb,
4116 QEMU_OPTION_usbdevice,
4117 QEMU_OPTION_name,
4118 QEMU_OPTION_uuid,
4120 /* Display options: */
4121 QEMU_OPTION_nographic,
4122 QEMU_OPTION_curses,
4123 QEMU_OPTION_no_frame,
4124 QEMU_OPTION_alt_grab,
4125 QEMU_OPTION_no_quit,
4126 QEMU_OPTION_sdl,
4127 QEMU_OPTION_portrait,
4128 QEMU_OPTION_vga,
4129 QEMU_OPTION_full_screen,
4130 QEMU_OPTION_g,
4131 QEMU_OPTION_vnc,
4133 /* Network options: */
4134 QEMU_OPTION_net,
4135 QEMU_OPTION_tftp,
4136 QEMU_OPTION_bootp,
4137 QEMU_OPTION_smb,
4138 QEMU_OPTION_redir,
4139 QEMU_OPTION_bt,
4141 /* i386 target only: */
4142 QEMU_OPTION_win2k_hack,
4143 QEMU_OPTION_rtc_td_hack,
4144 QEMU_OPTION_no_fd_bootchk,
4145 QEMU_OPTION_no_acpi,
4146 QEMU_OPTION_no_hpet,
4148 /* Linux boot specific: */
4149 QEMU_OPTION_kernel,
4150 QEMU_OPTION_append,
4151 QEMU_OPTION_initrd,
4153 /* Debug/Expert options: */
4154 QEMU_OPTION_serial,
4155 QEMU_OPTION_parallel,
4156 QEMU_OPTION_monitor,
4157 QEMU_OPTION_pidfile,
4158 QEMU_OPTION_S,
4159 QEMU_OPTION_s,
4160 QEMU_OPTION_p,
4161 QEMU_OPTION_d,
4162 QEMU_OPTION_hdachs,
4163 QEMU_OPTION_L,
4164 QEMU_OPTION_bios,
4165 QEMU_OPTION_kernel_kqemu,
4166 QEMU_OPTION_no_kqemu,
4167 QEMU_OPTION_enable_kvm,
4168 QEMU_OPTION_no_reboot,
4169 QEMU_OPTION_no_shutdown,
4170 QEMU_OPTION_loadvm,
4171 QEMU_OPTION_daemonize,
4172 QEMU_OPTION_option_rom,
4173 QEMU_OPTION_prom_env,
4174 QEMU_OPTION_clock,
4175 QEMU_OPTION_localtime,
4176 QEMU_OPTION_startdate,
4177 QEMU_OPTION_icount,
4178 QEMU_OPTION_echr,
4179 QEMU_OPTION_virtiocon,
4180 QEMU_OPTION_show_cursor,
4181 QEMU_OPTION_semihosting,
4182 QEMU_OPTION_old_param,
4183 QEMU_OPTION_tb_size,
4184 QEMU_OPTION_incoming,
4187 typedef struct QEMUOption {
4188 const char *name;
4189 int flags;
4190 int index;
4191 } QEMUOption;
4193 static const QEMUOption qemu_options[] = {
4194 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4195 qemu-doc.texi */
4196 /* Standard options: */
4197 { "h", 0, QEMU_OPTION_h },
4198 { "help", 0, QEMU_OPTION_h },
4199 { "M", HAS_ARG, QEMU_OPTION_M },
4200 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4201 { "smp", HAS_ARG, QEMU_OPTION_smp },
4202 { "fda", HAS_ARG, QEMU_OPTION_fda },
4203 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4204 { "hda", HAS_ARG, QEMU_OPTION_hda },
4205 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4206 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4207 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4208 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4209 { "drive", HAS_ARG, QEMU_OPTION_drive },
4210 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4211 { "sd", HAS_ARG, QEMU_OPTION_sd },
4212 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4213 { "boot", HAS_ARG, QEMU_OPTION_boot },
4214 { "snapshot", 0, QEMU_OPTION_snapshot },
4215 { "m", HAS_ARG, QEMU_OPTION_m },
4216 #ifndef _WIN32
4217 { "k", HAS_ARG, QEMU_OPTION_k },
4218 #endif
4219 #ifdef HAS_AUDIO
4220 { "audio-help", 0, QEMU_OPTION_audio_help },
4221 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4222 #endif
4223 { "usb", 0, QEMU_OPTION_usb },
4224 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4225 { "name", HAS_ARG, QEMU_OPTION_name },
4226 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4228 /* Display options: */
4229 { "nographic", 0, QEMU_OPTION_nographic },
4230 #ifdef CONFIG_CURSES
4231 { "curses", 0, QEMU_OPTION_curses },
4232 #endif
4233 #ifdef CONFIG_SDL
4234 { "no-frame", 0, QEMU_OPTION_no_frame },
4235 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4236 { "no-quit", 0, QEMU_OPTION_no_quit },
4237 { "sdl", 0, QEMU_OPTION_sdl },
4238 #endif
4239 { "portrait", 0, QEMU_OPTION_portrait },
4240 { "vga", HAS_ARG, QEMU_OPTION_vga },
4241 { "full-screen", 0, QEMU_OPTION_full_screen },
4242 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4243 { "g", 1, QEMU_OPTION_g },
4244 #endif
4245 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4247 /* Network options: */
4248 { "net", HAS_ARG, QEMU_OPTION_net},
4249 #ifdef CONFIG_SLIRP
4250 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4251 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4252 #ifndef _WIN32
4253 { "smb", HAS_ARG, QEMU_OPTION_smb },
4254 #endif
4255 { "redir", HAS_ARG, QEMU_OPTION_redir },
4256 #endif
4257 { "bt", HAS_ARG, QEMU_OPTION_bt },
4258 #ifdef TARGET_I386
4259 /* i386 target only: */
4260 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4261 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4262 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4263 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4264 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4265 #endif
4267 /* Linux boot specific: */
4268 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4269 { "append", HAS_ARG, QEMU_OPTION_append },
4270 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4272 /* Debug/Expert options: */
4273 { "serial", HAS_ARG, QEMU_OPTION_serial },
4274 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4275 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4276 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4277 { "S", 0, QEMU_OPTION_S },
4278 { "s", 0, QEMU_OPTION_s },
4279 { "p", HAS_ARG, QEMU_OPTION_p },
4280 { "d", HAS_ARG, QEMU_OPTION_d },
4281 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4282 { "L", HAS_ARG, QEMU_OPTION_L },
4283 { "bios", HAS_ARG, QEMU_OPTION_bios },
4284 #ifdef USE_KQEMU
4285 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4286 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4287 #endif
4288 #ifdef CONFIG_KVM
4289 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4290 #endif
4291 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4292 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4293 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4294 { "daemonize", 0, QEMU_OPTION_daemonize },
4295 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4296 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4297 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4298 #endif
4299 { "clock", HAS_ARG, QEMU_OPTION_clock },
4300 { "localtime", 0, QEMU_OPTION_localtime },
4301 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4302 { "icount", HAS_ARG, QEMU_OPTION_icount },
4303 { "echr", HAS_ARG, QEMU_OPTION_echr },
4304 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4305 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4306 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4307 { "semihosting", 0, QEMU_OPTION_semihosting },
4308 #endif
4309 #if defined(TARGET_ARM)
4310 { "old-param", 0, QEMU_OPTION_old_param },
4311 #endif
4312 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4313 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4314 { NULL },
4317 /* password input */
4319 int qemu_key_check(BlockDriverState *bs, const char *name)
4321 char password[256];
4322 int i;
4324 if (!bdrv_is_encrypted(bs))
4325 return 0;
4327 term_printf("%s is encrypted.\n", name);
4328 for(i = 0; i < 3; i++) {
4329 monitor_readline("Password: ", 1, password, sizeof(password));
4330 if (bdrv_set_key(bs, password) == 0)
4331 return 0;
4332 term_printf("invalid password\n");
4334 return -EPERM;
4337 static BlockDriverState *get_bdrv(int index)
4339 if (index > nb_drives)
4340 return NULL;
4341 return drives_table[index].bdrv;
4344 static void read_passwords(void)
4346 BlockDriverState *bs;
4347 int i;
4349 for(i = 0; i < 6; i++) {
4350 bs = get_bdrv(i);
4351 if (bs)
4352 qemu_key_check(bs, bdrv_get_device_name(bs));
4356 #ifdef HAS_AUDIO
4357 struct soundhw soundhw[] = {
4358 #ifdef HAS_AUDIO_CHOICE
4359 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4361 "pcspk",
4362 "PC speaker",
4365 { .init_isa = pcspk_audio_init }
4367 #endif
4369 #ifdef CONFIG_SB16
4371 "sb16",
4372 "Creative Sound Blaster 16",
4375 { .init_isa = SB16_init }
4377 #endif
4379 #ifdef CONFIG_CS4231A
4381 "cs4231a",
4382 "CS4231A",
4385 { .init_isa = cs4231a_init }
4387 #endif
4389 #ifdef CONFIG_ADLIB
4391 "adlib",
4392 #ifdef HAS_YMF262
4393 "Yamaha YMF262 (OPL3)",
4394 #else
4395 "Yamaha YM3812 (OPL2)",
4396 #endif
4399 { .init_isa = Adlib_init }
4401 #endif
4403 #ifdef CONFIG_GUS
4405 "gus",
4406 "Gravis Ultrasound GF1",
4409 { .init_isa = GUS_init }
4411 #endif
4413 #ifdef CONFIG_AC97
4415 "ac97",
4416 "Intel 82801AA AC97 Audio",
4419 { .init_pci = ac97_init }
4421 #endif
4423 #ifdef CONFIG_ES1370
4425 "es1370",
4426 "ENSONIQ AudioPCI ES1370",
4429 { .init_pci = es1370_init }
4431 #endif
4433 #endif /* HAS_AUDIO_CHOICE */
4435 { NULL, NULL, 0, 0, { NULL } }
4438 static void select_soundhw (const char *optarg)
4440 struct soundhw *c;
4442 if (*optarg == '?') {
4443 show_valid_cards:
4445 printf ("Valid sound card names (comma separated):\n");
4446 for (c = soundhw; c->name; ++c) {
4447 printf ("%-11s %s\n", c->name, c->descr);
4449 printf ("\n-soundhw all will enable all of the above\n");
4450 exit (*optarg != '?');
4452 else {
4453 size_t l;
4454 const char *p;
4455 char *e;
4456 int bad_card = 0;
4458 if (!strcmp (optarg, "all")) {
4459 for (c = soundhw; c->name; ++c) {
4460 c->enabled = 1;
4462 return;
4465 p = optarg;
4466 while (*p) {
4467 e = strchr (p, ',');
4468 l = !e ? strlen (p) : (size_t) (e - p);
4470 for (c = soundhw; c->name; ++c) {
4471 if (!strncmp (c->name, p, l)) {
4472 c->enabled = 1;
4473 break;
4477 if (!c->name) {
4478 if (l > 80) {
4479 fprintf (stderr,
4480 "Unknown sound card name (too big to show)\n");
4482 else {
4483 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4484 (int) l, p);
4486 bad_card = 1;
4488 p += l + (e != NULL);
4491 if (bad_card)
4492 goto show_valid_cards;
4495 #endif
4497 static void select_vgahw (const char *p)
4499 const char *opts;
4501 if (strstart(p, "std", &opts)) {
4502 std_vga_enabled = 1;
4503 cirrus_vga_enabled = 0;
4504 vmsvga_enabled = 0;
4505 } else if (strstart(p, "cirrus", &opts)) {
4506 cirrus_vga_enabled = 1;
4507 std_vga_enabled = 0;
4508 vmsvga_enabled = 0;
4509 } else if (strstart(p, "vmware", &opts)) {
4510 cirrus_vga_enabled = 0;
4511 std_vga_enabled = 0;
4512 vmsvga_enabled = 1;
4513 } else if (strstart(p, "none", &opts)) {
4514 cirrus_vga_enabled = 0;
4515 std_vga_enabled = 0;
4516 vmsvga_enabled = 0;
4517 } else {
4518 invalid_vga:
4519 fprintf(stderr, "Unknown vga type: %s\n", p);
4520 exit(1);
4522 while (*opts) {
4523 const char *nextopt;
4525 if (strstart(opts, ",retrace=", &nextopt)) {
4526 opts = nextopt;
4527 if (strstart(opts, "dumb", &nextopt))
4528 vga_retrace_method = VGA_RETRACE_DUMB;
4529 else if (strstart(opts, "precise", &nextopt))
4530 vga_retrace_method = VGA_RETRACE_PRECISE;
4531 else goto invalid_vga;
4532 } else goto invalid_vga;
4533 opts = nextopt;
4537 #ifdef _WIN32
4538 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4540 exit(STATUS_CONTROL_C_EXIT);
4541 return TRUE;
4543 #endif
4545 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4547 int ret;
4549 if(strlen(str) != 36)
4550 return -1;
4552 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4553 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4554 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4556 if(ret != 16)
4557 return -1;
4559 return 0;
4562 #define MAX_NET_CLIENTS 32
4564 #ifndef _WIN32
4566 static void termsig_handler(int signal)
4568 qemu_system_shutdown_request();
4571 static void termsig_setup(void)
4573 struct sigaction act;
4575 memset(&act, 0, sizeof(act));
4576 act.sa_handler = termsig_handler;
4577 sigaction(SIGINT, &act, NULL);
4578 sigaction(SIGHUP, &act, NULL);
4579 sigaction(SIGTERM, &act, NULL);
4582 #endif
4584 int main(int argc, char **argv, char **envp)
4586 #ifdef CONFIG_GDBSTUB
4587 int use_gdbstub;
4588 const char *gdbstub_port;
4589 #endif
4590 uint32_t boot_devices_bitmap = 0;
4591 int i;
4592 int snapshot, linux_boot, net_boot;
4593 const char *initrd_filename;
4594 const char *kernel_filename, *kernel_cmdline;
4595 const char *boot_devices = "";
4596 DisplayState *ds;
4597 DisplayChangeListener *dcl;
4598 int cyls, heads, secs, translation;
4599 const char *net_clients[MAX_NET_CLIENTS];
4600 int nb_net_clients;
4601 const char *bt_opts[MAX_BT_CMDLINE];
4602 int nb_bt_opts;
4603 int hda_index;
4604 int optind;
4605 const char *r, *optarg;
4606 CharDriverState *monitor_hd = NULL;
4607 const char *monitor_device;
4608 const char *serial_devices[MAX_SERIAL_PORTS];
4609 int serial_device_index;
4610 const char *parallel_devices[MAX_PARALLEL_PORTS];
4611 int parallel_device_index;
4612 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4613 int virtio_console_index;
4614 const char *loadvm = NULL;
4615 QEMUMachine *machine;
4616 const char *cpu_model;
4617 const char *usb_devices[MAX_USB_CMDLINE];
4618 int usb_devices_index;
4619 int fds[2];
4620 int tb_size;
4621 const char *pid_file = NULL;
4622 int autostart;
4623 const char *incoming = NULL;
4625 qemu_cache_utils_init(envp);
4627 LIST_INIT (&vm_change_state_head);
4628 #ifndef _WIN32
4630 struct sigaction act;
4631 sigfillset(&act.sa_mask);
4632 act.sa_flags = 0;
4633 act.sa_handler = SIG_IGN;
4634 sigaction(SIGPIPE, &act, NULL);
4636 #else
4637 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4638 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4639 QEMU to run on a single CPU */
4641 HANDLE h;
4642 DWORD mask, smask;
4643 int i;
4644 h = GetCurrentProcess();
4645 if (GetProcessAffinityMask(h, &mask, &smask)) {
4646 for(i = 0; i < 32; i++) {
4647 if (mask & (1 << i))
4648 break;
4650 if (i != 32) {
4651 mask = 1 << i;
4652 SetProcessAffinityMask(h, mask);
4656 #endif
4658 register_machines();
4659 machine = first_machine;
4660 cpu_model = NULL;
4661 initrd_filename = NULL;
4662 ram_size = 0;
4663 vga_ram_size = VGA_RAM_SIZE;
4664 #ifdef CONFIG_GDBSTUB
4665 use_gdbstub = 0;
4666 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4667 #endif
4668 snapshot = 0;
4669 nographic = 0;
4670 curses = 0;
4671 kernel_filename = NULL;
4672 kernel_cmdline = "";
4673 cyls = heads = secs = 0;
4674 translation = BIOS_ATA_TRANSLATION_AUTO;
4675 monitor_device = "vc";
4677 serial_devices[0] = "vc:80Cx24C";
4678 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4679 serial_devices[i] = NULL;
4680 serial_device_index = 0;
4682 parallel_devices[0] = "vc:640x480";
4683 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4684 parallel_devices[i] = NULL;
4685 parallel_device_index = 0;
4687 virtio_consoles[0] = "vc:80Cx24C";
4688 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4689 virtio_consoles[i] = NULL;
4690 virtio_console_index = 0;
4692 usb_devices_index = 0;
4694 nb_net_clients = 0;
4695 nb_bt_opts = 0;
4696 nb_drives = 0;
4697 nb_drives_opt = 0;
4698 hda_index = -1;
4700 nb_nics = 0;
4702 tb_size = 0;
4703 autostart= 1;
4705 optind = 1;
4706 for(;;) {
4707 if (optind >= argc)
4708 break;
4709 r = argv[optind];
4710 if (r[0] != '-') {
4711 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4712 } else {
4713 const QEMUOption *popt;
4715 optind++;
4716 /* Treat --foo the same as -foo. */
4717 if (r[1] == '-')
4718 r++;
4719 popt = qemu_options;
4720 for(;;) {
4721 if (!popt->name) {
4722 fprintf(stderr, "%s: invalid option -- '%s'\n",
4723 argv[0], r);
4724 exit(1);
4726 if (!strcmp(popt->name, r + 1))
4727 break;
4728 popt++;
4730 if (popt->flags & HAS_ARG) {
4731 if (optind >= argc) {
4732 fprintf(stderr, "%s: option '%s' requires an argument\n",
4733 argv[0], r);
4734 exit(1);
4736 optarg = argv[optind++];
4737 } else {
4738 optarg = NULL;
4741 switch(popt->index) {
4742 case QEMU_OPTION_M:
4743 machine = find_machine(optarg);
4744 if (!machine) {
4745 QEMUMachine *m;
4746 printf("Supported machines are:\n");
4747 for(m = first_machine; m != NULL; m = m->next) {
4748 printf("%-10s %s%s\n",
4749 m->name, m->desc,
4750 m == first_machine ? " (default)" : "");
4752 exit(*optarg != '?');
4754 break;
4755 case QEMU_OPTION_cpu:
4756 /* hw initialization will check this */
4757 if (*optarg == '?') {
4758 /* XXX: implement xxx_cpu_list for targets that still miss it */
4759 #if defined(cpu_list)
4760 cpu_list(stdout, &fprintf);
4761 #endif
4762 exit(0);
4763 } else {
4764 cpu_model = optarg;
4766 break;
4767 case QEMU_OPTION_initrd:
4768 initrd_filename = optarg;
4769 break;
4770 case QEMU_OPTION_hda:
4771 if (cyls == 0)
4772 hda_index = drive_add(optarg, HD_ALIAS, 0);
4773 else
4774 hda_index = drive_add(optarg, HD_ALIAS
4775 ",cyls=%d,heads=%d,secs=%d%s",
4776 0, cyls, heads, secs,
4777 translation == BIOS_ATA_TRANSLATION_LBA ?
4778 ",trans=lba" :
4779 translation == BIOS_ATA_TRANSLATION_NONE ?
4780 ",trans=none" : "");
4781 break;
4782 case QEMU_OPTION_hdb:
4783 case QEMU_OPTION_hdc:
4784 case QEMU_OPTION_hdd:
4785 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4786 break;
4787 case QEMU_OPTION_drive:
4788 drive_add(NULL, "%s", optarg);
4789 break;
4790 case QEMU_OPTION_mtdblock:
4791 drive_add(optarg, MTD_ALIAS);
4792 break;
4793 case QEMU_OPTION_sd:
4794 drive_add(optarg, SD_ALIAS);
4795 break;
4796 case QEMU_OPTION_pflash:
4797 drive_add(optarg, PFLASH_ALIAS);
4798 break;
4799 case QEMU_OPTION_snapshot:
4800 snapshot = 1;
4801 break;
4802 case QEMU_OPTION_hdachs:
4804 const char *p;
4805 p = optarg;
4806 cyls = strtol(p, (char **)&p, 0);
4807 if (cyls < 1 || cyls > 16383)
4808 goto chs_fail;
4809 if (*p != ',')
4810 goto chs_fail;
4811 p++;
4812 heads = strtol(p, (char **)&p, 0);
4813 if (heads < 1 || heads > 16)
4814 goto chs_fail;
4815 if (*p != ',')
4816 goto chs_fail;
4817 p++;
4818 secs = strtol(p, (char **)&p, 0);
4819 if (secs < 1 || secs > 63)
4820 goto chs_fail;
4821 if (*p == ',') {
4822 p++;
4823 if (!strcmp(p, "none"))
4824 translation = BIOS_ATA_TRANSLATION_NONE;
4825 else if (!strcmp(p, "lba"))
4826 translation = BIOS_ATA_TRANSLATION_LBA;
4827 else if (!strcmp(p, "auto"))
4828 translation = BIOS_ATA_TRANSLATION_AUTO;
4829 else
4830 goto chs_fail;
4831 } else if (*p != '\0') {
4832 chs_fail:
4833 fprintf(stderr, "qemu: invalid physical CHS format\n");
4834 exit(1);
4836 if (hda_index != -1)
4837 snprintf(drives_opt[hda_index].opt,
4838 sizeof(drives_opt[hda_index].opt),
4839 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4840 0, cyls, heads, secs,
4841 translation == BIOS_ATA_TRANSLATION_LBA ?
4842 ",trans=lba" :
4843 translation == BIOS_ATA_TRANSLATION_NONE ?
4844 ",trans=none" : "");
4846 break;
4847 case QEMU_OPTION_nographic:
4848 nographic = 1;
4849 break;
4850 #ifdef CONFIG_CURSES
4851 case QEMU_OPTION_curses:
4852 curses = 1;
4853 break;
4854 #endif
4855 case QEMU_OPTION_portrait:
4856 graphic_rotate = 1;
4857 break;
4858 case QEMU_OPTION_kernel:
4859 kernel_filename = optarg;
4860 break;
4861 case QEMU_OPTION_append:
4862 kernel_cmdline = optarg;
4863 break;
4864 case QEMU_OPTION_cdrom:
4865 drive_add(optarg, CDROM_ALIAS);
4866 break;
4867 case QEMU_OPTION_boot:
4868 boot_devices = optarg;
4869 /* We just do some generic consistency checks */
4871 /* Could easily be extended to 64 devices if needed */
4872 const char *p;
4874 boot_devices_bitmap = 0;
4875 for (p = boot_devices; *p != '\0'; p++) {
4876 /* Allowed boot devices are:
4877 * a b : floppy disk drives
4878 * c ... f : IDE disk drives
4879 * g ... m : machine implementation dependant drives
4880 * n ... p : network devices
4881 * It's up to each machine implementation to check
4882 * if the given boot devices match the actual hardware
4883 * implementation and firmware features.
4885 if (*p < 'a' || *p > 'q') {
4886 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4887 exit(1);
4889 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4890 fprintf(stderr,
4891 "Boot device '%c' was given twice\n",*p);
4892 exit(1);
4894 boot_devices_bitmap |= 1 << (*p - 'a');
4897 break;
4898 case QEMU_OPTION_fda:
4899 case QEMU_OPTION_fdb:
4900 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4901 break;
4902 #ifdef TARGET_I386
4903 case QEMU_OPTION_no_fd_bootchk:
4904 fd_bootchk = 0;
4905 break;
4906 #endif
4907 case QEMU_OPTION_net:
4908 if (nb_net_clients >= MAX_NET_CLIENTS) {
4909 fprintf(stderr, "qemu: too many network clients\n");
4910 exit(1);
4912 net_clients[nb_net_clients] = optarg;
4913 nb_net_clients++;
4914 break;
4915 #ifdef CONFIG_SLIRP
4916 case QEMU_OPTION_tftp:
4917 tftp_prefix = optarg;
4918 break;
4919 case QEMU_OPTION_bootp:
4920 bootp_filename = optarg;
4921 break;
4922 #ifndef _WIN32
4923 case QEMU_OPTION_smb:
4924 net_slirp_smb(optarg);
4925 break;
4926 #endif
4927 case QEMU_OPTION_redir:
4928 net_slirp_redir(optarg);
4929 break;
4930 #endif
4931 case QEMU_OPTION_bt:
4932 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4933 fprintf(stderr, "qemu: too many bluetooth options\n");
4934 exit(1);
4936 bt_opts[nb_bt_opts++] = optarg;
4937 break;
4938 #ifdef HAS_AUDIO
4939 case QEMU_OPTION_audio_help:
4940 AUD_help ();
4941 exit (0);
4942 break;
4943 case QEMU_OPTION_soundhw:
4944 select_soundhw (optarg);
4945 break;
4946 #endif
4947 case QEMU_OPTION_h:
4948 help(0);
4949 break;
4950 case QEMU_OPTION_m: {
4951 uint64_t value;
4952 char *ptr;
4954 value = strtoul(optarg, &ptr, 10);
4955 switch (*ptr) {
4956 case 0: case 'M': case 'm':
4957 value <<= 20;
4958 break;
4959 case 'G': case 'g':
4960 value <<= 30;
4961 break;
4962 default:
4963 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4964 exit(1);
4967 /* On 32-bit hosts, QEMU is limited by virtual address space */
4968 if (value > (2047 << 20)
4969 #ifndef USE_KQEMU
4970 && HOST_LONG_BITS == 32
4971 #endif
4973 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4974 exit(1);
4976 if (value != (uint64_t)(ram_addr_t)value) {
4977 fprintf(stderr, "qemu: ram size too large\n");
4978 exit(1);
4980 ram_size = value;
4981 break;
4983 case QEMU_OPTION_d:
4985 int mask;
4986 const CPULogItem *item;
4988 mask = cpu_str_to_log_mask(optarg);
4989 if (!mask) {
4990 printf("Log items (comma separated):\n");
4991 for(item = cpu_log_items; item->mask != 0; item++) {
4992 printf("%-10s %s\n", item->name, item->help);
4994 exit(1);
4996 cpu_set_log(mask);
4998 break;
4999 #ifdef CONFIG_GDBSTUB
5000 case QEMU_OPTION_s:
5001 use_gdbstub = 1;
5002 break;
5003 case QEMU_OPTION_p:
5004 gdbstub_port = optarg;
5005 break;
5006 #endif
5007 case QEMU_OPTION_L:
5008 bios_dir = optarg;
5009 break;
5010 case QEMU_OPTION_bios:
5011 bios_name = optarg;
5012 break;
5013 case QEMU_OPTION_S:
5014 autostart = 0;
5015 break;
5016 case QEMU_OPTION_k:
5017 keyboard_layout = optarg;
5018 break;
5019 case QEMU_OPTION_localtime:
5020 rtc_utc = 0;
5021 break;
5022 case QEMU_OPTION_vga:
5023 select_vgahw (optarg);
5024 break;
5025 case QEMU_OPTION_g:
5027 const char *p;
5028 int w, h, depth;
5029 p = optarg;
5030 w = strtol(p, (char **)&p, 10);
5031 if (w <= 0) {
5032 graphic_error:
5033 fprintf(stderr, "qemu: invalid resolution or depth\n");
5034 exit(1);
5036 if (*p != 'x')
5037 goto graphic_error;
5038 p++;
5039 h = strtol(p, (char **)&p, 10);
5040 if (h <= 0)
5041 goto graphic_error;
5042 if (*p == 'x') {
5043 p++;
5044 depth = strtol(p, (char **)&p, 10);
5045 if (depth != 8 && depth != 15 && depth != 16 &&
5046 depth != 24 && depth != 32)
5047 goto graphic_error;
5048 } else if (*p == '\0') {
5049 depth = graphic_depth;
5050 } else {
5051 goto graphic_error;
5054 graphic_width = w;
5055 graphic_height = h;
5056 graphic_depth = depth;
5058 break;
5059 case QEMU_OPTION_echr:
5061 char *r;
5062 term_escape_char = strtol(optarg, &r, 0);
5063 if (r == optarg)
5064 printf("Bad argument to echr\n");
5065 break;
5067 case QEMU_OPTION_monitor:
5068 monitor_device = optarg;
5069 break;
5070 case QEMU_OPTION_serial:
5071 if (serial_device_index >= MAX_SERIAL_PORTS) {
5072 fprintf(stderr, "qemu: too many serial ports\n");
5073 exit(1);
5075 serial_devices[serial_device_index] = optarg;
5076 serial_device_index++;
5077 break;
5078 case QEMU_OPTION_virtiocon:
5079 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5080 fprintf(stderr, "qemu: too many virtio consoles\n");
5081 exit(1);
5083 virtio_consoles[virtio_console_index] = optarg;
5084 virtio_console_index++;
5085 break;
5086 case QEMU_OPTION_parallel:
5087 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5088 fprintf(stderr, "qemu: too many parallel ports\n");
5089 exit(1);
5091 parallel_devices[parallel_device_index] = optarg;
5092 parallel_device_index++;
5093 break;
5094 case QEMU_OPTION_loadvm:
5095 loadvm = optarg;
5096 break;
5097 case QEMU_OPTION_full_screen:
5098 full_screen = 1;
5099 break;
5100 #ifdef CONFIG_SDL
5101 case QEMU_OPTION_no_frame:
5102 no_frame = 1;
5103 break;
5104 case QEMU_OPTION_alt_grab:
5105 alt_grab = 1;
5106 break;
5107 case QEMU_OPTION_no_quit:
5108 no_quit = 1;
5109 break;
5110 case QEMU_OPTION_sdl:
5111 sdl = 1;
5112 break;
5113 #endif
5114 case QEMU_OPTION_pidfile:
5115 pid_file = optarg;
5116 break;
5117 #ifdef TARGET_I386
5118 case QEMU_OPTION_win2k_hack:
5119 win2k_install_hack = 1;
5120 break;
5121 case QEMU_OPTION_rtc_td_hack:
5122 rtc_td_hack = 1;
5123 break;
5124 #endif
5125 #ifdef USE_KQEMU
5126 case QEMU_OPTION_no_kqemu:
5127 kqemu_allowed = 0;
5128 break;
5129 case QEMU_OPTION_kernel_kqemu:
5130 kqemu_allowed = 2;
5131 break;
5132 #endif
5133 #ifdef CONFIG_KVM
5134 case QEMU_OPTION_enable_kvm:
5135 kvm_allowed = 1;
5136 #ifdef USE_KQEMU
5137 kqemu_allowed = 0;
5138 #endif
5139 break;
5140 #endif
5141 case QEMU_OPTION_usb:
5142 usb_enabled = 1;
5143 break;
5144 case QEMU_OPTION_usbdevice:
5145 usb_enabled = 1;
5146 if (usb_devices_index >= MAX_USB_CMDLINE) {
5147 fprintf(stderr, "Too many USB devices\n");
5148 exit(1);
5150 usb_devices[usb_devices_index] = optarg;
5151 usb_devices_index++;
5152 break;
5153 case QEMU_OPTION_smp:
5154 smp_cpus = atoi(optarg);
5155 if (smp_cpus < 1) {
5156 fprintf(stderr, "Invalid number of CPUs\n");
5157 exit(1);
5159 break;
5160 case QEMU_OPTION_vnc:
5161 vnc_display = optarg;
5162 break;
5163 case QEMU_OPTION_no_acpi:
5164 acpi_enabled = 0;
5165 break;
5166 case QEMU_OPTION_no_hpet:
5167 no_hpet = 1;
5168 break;
5169 case QEMU_OPTION_no_reboot:
5170 no_reboot = 1;
5171 break;
5172 case QEMU_OPTION_no_shutdown:
5173 no_shutdown = 1;
5174 break;
5175 case QEMU_OPTION_show_cursor:
5176 cursor_hide = 0;
5177 break;
5178 case QEMU_OPTION_uuid:
5179 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5180 fprintf(stderr, "Fail to parse UUID string."
5181 " Wrong format.\n");
5182 exit(1);
5184 break;
5185 case QEMU_OPTION_daemonize:
5186 daemonize = 1;
5187 break;
5188 case QEMU_OPTION_option_rom:
5189 if (nb_option_roms >= MAX_OPTION_ROMS) {
5190 fprintf(stderr, "Too many option ROMs\n");
5191 exit(1);
5193 option_rom[nb_option_roms] = optarg;
5194 nb_option_roms++;
5195 break;
5196 case QEMU_OPTION_semihosting:
5197 semihosting_enabled = 1;
5198 break;
5199 case QEMU_OPTION_name:
5200 qemu_name = optarg;
5201 break;
5202 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5203 case QEMU_OPTION_prom_env:
5204 if (nb_prom_envs >= MAX_PROM_ENVS) {
5205 fprintf(stderr, "Too many prom variables\n");
5206 exit(1);
5208 prom_envs[nb_prom_envs] = optarg;
5209 nb_prom_envs++;
5210 break;
5211 #endif
5212 #ifdef TARGET_ARM
5213 case QEMU_OPTION_old_param:
5214 old_param = 1;
5215 break;
5216 #endif
5217 case QEMU_OPTION_clock:
5218 configure_alarms(optarg);
5219 break;
5220 case QEMU_OPTION_startdate:
5222 struct tm tm;
5223 time_t rtc_start_date;
5224 if (!strcmp(optarg, "now")) {
5225 rtc_date_offset = -1;
5226 } else {
5227 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5228 &tm.tm_year,
5229 &tm.tm_mon,
5230 &tm.tm_mday,
5231 &tm.tm_hour,
5232 &tm.tm_min,
5233 &tm.tm_sec) == 6) {
5234 /* OK */
5235 } else if (sscanf(optarg, "%d-%d-%d",
5236 &tm.tm_year,
5237 &tm.tm_mon,
5238 &tm.tm_mday) == 3) {
5239 tm.tm_hour = 0;
5240 tm.tm_min = 0;
5241 tm.tm_sec = 0;
5242 } else {
5243 goto date_fail;
5245 tm.tm_year -= 1900;
5246 tm.tm_mon--;
5247 rtc_start_date = mktimegm(&tm);
5248 if (rtc_start_date == -1) {
5249 date_fail:
5250 fprintf(stderr, "Invalid date format. Valid format are:\n"
5251 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5252 exit(1);
5254 rtc_date_offset = time(NULL) - rtc_start_date;
5257 break;
5258 case QEMU_OPTION_tb_size:
5259 tb_size = strtol(optarg, NULL, 0);
5260 if (tb_size < 0)
5261 tb_size = 0;
5262 break;
5263 case QEMU_OPTION_icount:
5264 use_icount = 1;
5265 if (strcmp(optarg, "auto") == 0) {
5266 icount_time_shift = -1;
5267 } else {
5268 icount_time_shift = strtol(optarg, NULL, 0);
5270 break;
5271 case QEMU_OPTION_incoming:
5272 incoming = optarg;
5273 break;
5278 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5279 if (kvm_allowed && kqemu_allowed) {
5280 fprintf(stderr,
5281 "You can not enable both KVM and kqemu at the same time\n");
5282 exit(1);
5284 #endif
5286 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5287 if (smp_cpus > machine->max_cpus) {
5288 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5289 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5290 machine->max_cpus);
5291 exit(1);
5294 if (nographic) {
5295 if (serial_device_index == 0)
5296 serial_devices[0] = "stdio";
5297 if (parallel_device_index == 0)
5298 parallel_devices[0] = "null";
5299 if (strncmp(monitor_device, "vc", 2) == 0)
5300 monitor_device = "stdio";
5301 if (virtio_console_index == 0)
5302 virtio_consoles[0] = "null";
5305 #ifndef _WIN32
5306 if (daemonize) {
5307 pid_t pid;
5309 if (pipe(fds) == -1)
5310 exit(1);
5312 pid = fork();
5313 if (pid > 0) {
5314 uint8_t status;
5315 ssize_t len;
5317 close(fds[1]);
5319 again:
5320 len = read(fds[0], &status, 1);
5321 if (len == -1 && (errno == EINTR))
5322 goto again;
5324 if (len != 1)
5325 exit(1);
5326 else if (status == 1) {
5327 fprintf(stderr, "Could not acquire pidfile\n");
5328 exit(1);
5329 } else
5330 exit(0);
5331 } else if (pid < 0)
5332 exit(1);
5334 setsid();
5336 pid = fork();
5337 if (pid > 0)
5338 exit(0);
5339 else if (pid < 0)
5340 exit(1);
5342 umask(027);
5344 signal(SIGTSTP, SIG_IGN);
5345 signal(SIGTTOU, SIG_IGN);
5346 signal(SIGTTIN, SIG_IGN);
5348 #endif
5350 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5351 if (daemonize) {
5352 uint8_t status = 1;
5353 write(fds[1], &status, 1);
5354 } else
5355 fprintf(stderr, "Could not acquire pid file\n");
5356 exit(1);
5359 #ifdef USE_KQEMU
5360 if (smp_cpus > 1)
5361 kqemu_allowed = 0;
5362 #endif
5363 linux_boot = (kernel_filename != NULL);
5364 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5366 if (!linux_boot && net_boot == 0 &&
5367 !machine->nodisk_ok && nb_drives_opt == 0)
5368 help(1);
5370 if (!linux_boot && *kernel_cmdline != '\0') {
5371 fprintf(stderr, "-append only allowed with -kernel option\n");
5372 exit(1);
5375 if (!linux_boot && initrd_filename != NULL) {
5376 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5377 exit(1);
5380 /* boot to floppy or the default cd if no hard disk defined yet */
5381 if (!boot_devices[0]) {
5382 boot_devices = "cad";
5384 setvbuf(stdout, NULL, _IOLBF, 0);
5386 init_timers();
5387 if (init_timer_alarm() < 0) {
5388 fprintf(stderr, "could not initialize alarm timer\n");
5389 exit(1);
5391 if (use_icount && icount_time_shift < 0) {
5392 use_icount = 2;
5393 /* 125MIPS seems a reasonable initial guess at the guest speed.
5394 It will be corrected fairly quickly anyway. */
5395 icount_time_shift = 3;
5396 init_icount_adjust();
5399 #ifdef _WIN32
5400 socket_init();
5401 #endif
5403 /* init network clients */
5404 if (nb_net_clients == 0) {
5405 /* if no clients, we use a default config */
5406 net_clients[nb_net_clients++] = "nic";
5407 #ifdef CONFIG_SLIRP
5408 net_clients[nb_net_clients++] = "user";
5409 #endif
5412 for(i = 0;i < nb_net_clients; i++) {
5413 if (net_client_parse(net_clients[i]) < 0)
5414 exit(1);
5416 net_client_check();
5418 #ifdef TARGET_I386
5419 /* XXX: this should be moved in the PC machine instantiation code */
5420 if (net_boot != 0) {
5421 int netroms = 0;
5422 for (i = 0; i < nb_nics && i < 4; i++) {
5423 const char *model = nd_table[i].model;
5424 char buf[1024];
5425 if (net_boot & (1 << i)) {
5426 if (model == NULL)
5427 model = "ne2k_pci";
5428 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5429 if (get_image_size(buf) > 0) {
5430 if (nb_option_roms >= MAX_OPTION_ROMS) {
5431 fprintf(stderr, "Too many option ROMs\n");
5432 exit(1);
5434 option_rom[nb_option_roms] = strdup(buf);
5435 nb_option_roms++;
5436 netroms++;
5440 if (netroms == 0) {
5441 fprintf(stderr, "No valid PXE rom found for network device\n");
5442 exit(1);
5445 #endif
5447 /* init the bluetooth world */
5448 for (i = 0; i < nb_bt_opts; i++)
5449 if (bt_parse(bt_opts[i]))
5450 exit(1);
5452 /* init the memory */
5453 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5455 if (machine->ram_require & RAMSIZE_FIXED) {
5456 if (ram_size > 0) {
5457 if (ram_size < phys_ram_size) {
5458 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5459 machine->name, (unsigned long long) phys_ram_size);
5460 exit(-1);
5463 phys_ram_size = ram_size;
5464 } else
5465 ram_size = phys_ram_size;
5466 } else {
5467 if (ram_size == 0)
5468 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5470 phys_ram_size += ram_size;
5473 phys_ram_base = qemu_vmalloc(phys_ram_size);
5474 if (!phys_ram_base) {
5475 fprintf(stderr, "Could not allocate physical memory\n");
5476 exit(1);
5479 /* init the dynamic translator */
5480 cpu_exec_init_all(tb_size * 1024 * 1024);
5482 bdrv_init();
5484 /* we always create the cdrom drive, even if no disk is there */
5486 if (nb_drives_opt < MAX_DRIVES)
5487 drive_add(NULL, CDROM_ALIAS);
5489 /* we always create at least one floppy */
5491 if (nb_drives_opt < MAX_DRIVES)
5492 drive_add(NULL, FD_ALIAS, 0);
5494 /* we always create one sd slot, even if no card is in it */
5496 if (nb_drives_opt < MAX_DRIVES)
5497 drive_add(NULL, SD_ALIAS);
5499 /* open the virtual block devices */
5501 for(i = 0; i < nb_drives_opt; i++)
5502 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5503 exit(1);
5505 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5506 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5508 #ifndef _WIN32
5509 /* must be after terminal init, SDL library changes signal handlers */
5510 termsig_setup();
5511 #endif
5513 /* Maintain compatibility with multiple stdio monitors */
5514 if (!strcmp(monitor_device,"stdio")) {
5515 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5516 const char *devname = serial_devices[i];
5517 if (devname && !strcmp(devname,"mon:stdio")) {
5518 monitor_device = NULL;
5519 break;
5520 } else if (devname && !strcmp(devname,"stdio")) {
5521 monitor_device = NULL;
5522 serial_devices[i] = "mon:stdio";
5523 break;
5528 if (kvm_enabled()) {
5529 int ret;
5531 ret = kvm_init(smp_cpus);
5532 if (ret < 0) {
5533 fprintf(stderr, "failed to initialize KVM\n");
5534 exit(1);
5538 if (monitor_device) {
5539 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5540 if (!monitor_hd) {
5541 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5542 exit(1);
5546 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5547 const char *devname = serial_devices[i];
5548 if (devname && strcmp(devname, "none")) {
5549 char label[32];
5550 snprintf(label, sizeof(label), "serial%d", i);
5551 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5552 if (!serial_hds[i]) {
5553 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5554 devname);
5555 exit(1);
5560 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5561 const char *devname = parallel_devices[i];
5562 if (devname && strcmp(devname, "none")) {
5563 char label[32];
5564 snprintf(label, sizeof(label), "parallel%d", i);
5565 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5566 if (!parallel_hds[i]) {
5567 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5568 devname);
5569 exit(1);
5574 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5575 const char *devname = virtio_consoles[i];
5576 if (devname && strcmp(devname, "none")) {
5577 char label[32];
5578 snprintf(label, sizeof(label), "virtcon%d", i);
5579 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5580 if (!virtcon_hds[i]) {
5581 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5582 devname);
5583 exit(1);
5588 machine->init(ram_size, vga_ram_size, boot_devices,
5589 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5591 current_machine = machine;
5593 /* Set KVM's vcpu state to qemu's initial CPUState. */
5594 if (kvm_enabled()) {
5595 int ret;
5597 ret = kvm_sync_vcpus();
5598 if (ret < 0) {
5599 fprintf(stderr, "failed to initialize vcpus\n");
5600 exit(1);
5604 /* init USB devices */
5605 if (usb_enabled) {
5606 for(i = 0; i < usb_devices_index; i++) {
5607 if (usb_device_add(usb_devices[i]) < 0) {
5608 fprintf(stderr, "Warning: could not add USB device %s\n",
5609 usb_devices[i]);
5614 if (!display_state)
5615 dumb_display_init();
5616 /* just use the first displaystate for the moment */
5617 ds = display_state;
5618 /* terminal init */
5619 if (nographic) {
5620 if (curses) {
5621 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5622 exit(1);
5624 } else {
5625 #if defined(CONFIG_CURSES)
5626 if (curses) {
5627 /* At the moment curses cannot be used with other displays */
5628 curses_display_init(ds, full_screen);
5629 } else
5630 #endif
5632 if (vnc_display != NULL) {
5633 vnc_display_init(ds);
5634 if (vnc_display_open(ds, vnc_display) < 0)
5635 exit(1);
5637 #if defined(CONFIG_SDL)
5638 if (sdl || !vnc_display)
5639 sdl_display_init(ds, full_screen, no_frame);
5640 #elif defined(CONFIG_COCOA)
5641 if (sdl || !vnc_display)
5642 cocoa_display_init(ds, full_screen);
5643 #endif
5646 dpy_resize(ds);
5648 dcl = ds->listeners;
5649 while (dcl != NULL) {
5650 if (dcl->dpy_refresh != NULL) {
5651 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5652 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5654 dcl = dcl->next;
5657 if (nographic || (vnc_display && !sdl)) {
5658 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5659 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5662 text_consoles_set_display(display_state);
5664 if (monitor_device && monitor_hd)
5665 monitor_init(monitor_hd, !nographic);
5667 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5668 const char *devname = serial_devices[i];
5669 if (devname && strcmp(devname, "none")) {
5670 char label[32];
5671 snprintf(label, sizeof(label), "serial%d", i);
5672 if (strstart(devname, "vc", 0))
5673 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5677 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5678 const char *devname = parallel_devices[i];
5679 if (devname && strcmp(devname, "none")) {
5680 char label[32];
5681 snprintf(label, sizeof(label), "parallel%d", i);
5682 if (strstart(devname, "vc", 0))
5683 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5687 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5688 const char *devname = virtio_consoles[i];
5689 if (virtcon_hds[i] && devname) {
5690 char label[32];
5691 snprintf(label, sizeof(label), "virtcon%d", i);
5692 if (strstart(devname, "vc", 0))
5693 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5697 #ifdef CONFIG_GDBSTUB
5698 if (use_gdbstub) {
5699 /* XXX: use standard host:port notation and modify options
5700 accordingly. */
5701 if (gdbserver_start(gdbstub_port) < 0) {
5702 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5703 gdbstub_port);
5704 exit(1);
5707 #endif
5709 if (loadvm)
5710 do_loadvm(loadvm);
5712 if (incoming) {
5713 autostart = 0; /* fixme how to deal with -daemonize */
5714 qemu_start_incoming_migration(incoming);
5718 /* XXX: simplify init */
5719 read_passwords();
5720 if (autostart) {
5721 vm_start();
5725 if (daemonize) {
5726 uint8_t status = 0;
5727 ssize_t len;
5728 int fd;
5730 again1:
5731 len = write(fds[1], &status, 1);
5732 if (len == -1 && (errno == EINTR))
5733 goto again1;
5735 if (len != 1)
5736 exit(1);
5738 chdir("/");
5739 TFR(fd = open("/dev/null", O_RDWR));
5740 if (fd == -1)
5741 exit(1);
5743 dup2(fd, 0);
5744 dup2(fd, 1);
5745 dup2(fd, 2);
5747 close(fd);
5750 main_loop();
5751 quit_timers();
5752 net_cleanup();
5754 return 0;