Fix mfcr on ppc64-softmmu
[qemu/mini2440/sniper_sniper_test.git] / vl.c
blob62a9194614a6ea6766d4ae30fec36140dd30cd06
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 <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for _BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <pwd.h>
37 #include <sys/times.h>
38 #include <sys/wait.h>
39 #include <termios.h>
40 #include <sys/mman.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <net/if.h>
46 #if defined(__NetBSD__)
47 #include <net/if_tap.h>
48 #endif
49 #ifdef __linux__
50 #include <linux/if_tun.h>
51 #endif
52 #include <arpa/inet.h>
53 #include <dirent.h>
54 #include <netdb.h>
55 #include <sys/select.h>
56 #ifdef _BSD
57 #include <sys/stat.h>
58 #if defined(__FreeBSD__) || defined(__DragonFly__)
59 #include <libutil.h>
60 #else
61 #include <util.h>
62 #endif
63 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
64 #include <freebsd/stdlib.h>
65 #else
66 #ifdef __linux__
67 #include <pty.h>
68 #include <malloc.h>
69 #include <linux/rtc.h>
71 /* For the benefit of older linux systems which don't supply it,
72 we use a local copy of hpet.h. */
73 /* #include <linux/hpet.h> */
74 #include "hpet.h"
76 #include <linux/ppdev.h>
77 #include <linux/parport.h>
78 #endif
79 #ifdef __sun__
80 #include <sys/stat.h>
81 #include <sys/ethernet.h>
82 #include <sys/sockio.h>
83 #include <netinet/arp.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #include <netinet/ip_icmp.h> // must come after ip.h
88 #include <netinet/udp.h>
89 #include <netinet/tcp.h>
90 #include <net/if.h>
91 #include <syslog.h>
92 #include <stropts.h>
93 #endif
94 #endif
95 #endif
97 #if defined(__OpenBSD__)
98 #include <util.h>
99 #endif
101 #if defined(CONFIG_VDE)
102 #include <libvdeplug.h>
103 #endif
105 #ifdef _WIN32
106 #include <malloc.h>
107 #include <sys/timeb.h>
108 #include <mmsystem.h>
109 #define getopt_long_only getopt_long
110 #define memalign(align, size) malloc(size)
111 #endif
113 #ifdef CONFIG_SDL
114 #ifdef __APPLE__
115 #include <SDL/SDL.h>
116 int qemu_main(int argc, char **argv, char **envp);
117 int main(int argc, char **argv)
119 qemu_main(argc, argv, NULL);
121 #undef main
122 #define main qemu_main
123 #endif
124 #endif /* CONFIG_SDL */
126 #ifdef CONFIG_COCOA
127 #undef main
128 #define main qemu_main
129 #endif /* CONFIG_COCOA */
131 #include "hw/hw.h"
132 #include "hw/boards.h"
133 #include "hw/usb.h"
134 #include "hw/pcmcia.h"
135 #include "hw/pc.h"
136 #include "hw/audiodev.h"
137 #include "hw/isa.h"
138 #include "hw/baum.h"
139 #include "hw/bt.h"
140 #include "net.h"
141 #include "monitor.h"
142 #include "console.h"
143 #include "sysemu.h"
144 #include "gdbstub.h"
145 #include "qemu-timer.h"
146 #include "qemu-char.h"
147 #include "cache-utils.h"
148 #include "block.h"
149 #include "audio/audio.h"
150 #include "migration.h"
151 #include "kvm.h"
152 #include "balloon.h"
154 #include "disas.h"
156 #include "exec-all.h"
158 #include "qemu_socket.h"
160 #if defined(CONFIG_SLIRP)
161 #include "libslirp.h"
162 #endif
164 //#define DEBUG_UNUSED_IOPORT
165 //#define DEBUG_IOPORT
166 //#define DEBUG_NET
167 //#define DEBUG_SLIRP
170 #ifdef DEBUG_IOPORT
171 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
172 #else
173 # define LOG_IOPORT(...) do { } while (0)
174 #endif
176 #define DEFAULT_RAM_SIZE 128
178 /* Max number of USB devices that can be specified on the commandline. */
179 #define MAX_USB_CMDLINE 8
181 /* Max number of bluetooth switches on the commandline. */
182 #define MAX_BT_CMDLINE 10
184 /* XXX: use a two level table to limit memory usage */
185 #define MAX_IOPORTS 65536
187 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
188 const char *bios_name = NULL;
189 static void *ioport_opaque[MAX_IOPORTS];
190 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
191 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
192 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
193 to store the VM snapshots */
194 DriveInfo drives_table[MAX_DRIVES+1];
195 int nb_drives;
196 static int vga_ram_size;
197 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
198 static DisplayState *display_state;
199 int nographic;
200 static int curses;
201 static int sdl;
202 const char* keyboard_layout = NULL;
203 int64_t ticks_per_sec;
204 ram_addr_t ram_size;
205 int nb_nics;
206 NICInfo nd_table[MAX_NICS];
207 int vm_running;
208 static int autostart;
209 static int rtc_utc = 1;
210 static int rtc_date_offset = -1; /* -1 means no change */
211 int cirrus_vga_enabled = 1;
212 int std_vga_enabled = 0;
213 int vmsvga_enabled = 0;
214 #ifdef TARGET_SPARC
215 int graphic_width = 1024;
216 int graphic_height = 768;
217 int graphic_depth = 8;
218 #else
219 int graphic_width = 800;
220 int graphic_height = 600;
221 int graphic_depth = 15;
222 #endif
223 static int full_screen = 0;
224 #ifdef CONFIG_SDL
225 static int no_frame = 0;
226 #endif
227 int no_quit = 0;
228 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
229 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
230 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
231 #ifdef TARGET_I386
232 int win2k_install_hack = 0;
233 int rtc_td_hack = 0;
234 #endif
235 int usb_enabled = 0;
236 int smp_cpus = 1;
237 const char *vnc_display;
238 int acpi_enabled = 1;
239 int no_hpet = 0;
240 int fd_bootchk = 1;
241 int no_reboot = 0;
242 int no_shutdown = 0;
243 int cursor_hide = 1;
244 int graphic_rotate = 0;
245 int daemonize = 0;
246 const char *option_rom[MAX_OPTION_ROMS];
247 int nb_option_roms;
248 int semihosting_enabled = 0;
249 #ifdef TARGET_ARM
250 int old_param = 0;
251 #endif
252 const char *qemu_name;
253 int alt_grab = 0;
254 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
255 unsigned int nb_prom_envs = 0;
256 const char *prom_envs[MAX_PROM_ENVS];
257 #endif
258 int nb_drives_opt;
259 struct drive_opt drives_opt[MAX_DRIVES];
261 static CPUState *cur_cpu;
262 static CPUState *next_cpu;
263 static int event_pending = 1;
264 /* Conversion factor from emulated instructions to virtual clock ticks. */
265 static int icount_time_shift;
266 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
267 #define MAX_ICOUNT_SHIFT 10
268 /* Compensate for varying guest execution speed. */
269 static int64_t qemu_icount_bias;
270 static QEMUTimer *icount_rt_timer;
271 static QEMUTimer *icount_vm_timer;
272 static QEMUTimer *nographic_timer;
274 uint8_t qemu_uuid[16];
276 /***********************************************************/
277 /* x86 ISA bus support */
279 target_phys_addr_t isa_mem_base = 0;
280 PicState2 *isa_pic;
282 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
283 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
285 static uint32_t ioport_read(int index, uint32_t address)
287 static IOPortReadFunc *default_func[3] = {
288 default_ioport_readb,
289 default_ioport_readw,
290 default_ioport_readl
292 IOPortReadFunc *func = ioport_read_table[index][address];
293 if (!func)
294 func = default_func[index];
295 return func(ioport_opaque[address], address);
298 static void ioport_write(int index, uint32_t address, uint32_t data)
300 static IOPortWriteFunc *default_func[3] = {
301 default_ioport_writeb,
302 default_ioport_writew,
303 default_ioport_writel
305 IOPortWriteFunc *func = ioport_write_table[index][address];
306 if (!func)
307 func = default_func[index];
308 func(ioport_opaque[address], address, data);
311 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
313 #ifdef DEBUG_UNUSED_IOPORT
314 fprintf(stderr, "unused inb: port=0x%04x\n", address);
315 #endif
316 return 0xff;
319 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
321 #ifdef DEBUG_UNUSED_IOPORT
322 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
323 #endif
326 /* default is to make two byte accesses */
327 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
329 uint32_t data;
330 data = ioport_read(0, address);
331 address = (address + 1) & (MAX_IOPORTS - 1);
332 data |= ioport_read(0, address) << 8;
333 return data;
336 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
338 ioport_write(0, address, data & 0xff);
339 address = (address + 1) & (MAX_IOPORTS - 1);
340 ioport_write(0, address, (data >> 8) & 0xff);
343 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
345 #ifdef DEBUG_UNUSED_IOPORT
346 fprintf(stderr, "unused inl: port=0x%04x\n", address);
347 #endif
348 return 0xffffffff;
351 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
353 #ifdef DEBUG_UNUSED_IOPORT
354 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
355 #endif
358 /* size is the word size in byte */
359 int register_ioport_read(int start, int length, int size,
360 IOPortReadFunc *func, void *opaque)
362 int i, bsize;
364 if (size == 1) {
365 bsize = 0;
366 } else if (size == 2) {
367 bsize = 1;
368 } else if (size == 4) {
369 bsize = 2;
370 } else {
371 hw_error("register_ioport_read: invalid size");
372 return -1;
374 for(i = start; i < start + length; i += size) {
375 ioport_read_table[bsize][i] = func;
376 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
377 hw_error("register_ioport_read: invalid opaque");
378 ioport_opaque[i] = opaque;
380 return 0;
383 /* size is the word size in byte */
384 int register_ioport_write(int start, int length, int size,
385 IOPortWriteFunc *func, void *opaque)
387 int i, bsize;
389 if (size == 1) {
390 bsize = 0;
391 } else if (size == 2) {
392 bsize = 1;
393 } else if (size == 4) {
394 bsize = 2;
395 } else {
396 hw_error("register_ioport_write: invalid size");
397 return -1;
399 for(i = start; i < start + length; i += size) {
400 ioport_write_table[bsize][i] = func;
401 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
402 hw_error("register_ioport_write: invalid opaque");
403 ioport_opaque[i] = opaque;
405 return 0;
408 void isa_unassign_ioport(int start, int length)
410 int i;
412 for(i = start; i < start + length; i++) {
413 ioport_read_table[0][i] = default_ioport_readb;
414 ioport_read_table[1][i] = default_ioport_readw;
415 ioport_read_table[2][i] = default_ioport_readl;
417 ioport_write_table[0][i] = default_ioport_writeb;
418 ioport_write_table[1][i] = default_ioport_writew;
419 ioport_write_table[2][i] = default_ioport_writel;
421 ioport_opaque[i] = NULL;
425 /***********************************************************/
427 void cpu_outb(CPUState *env, int addr, int val)
429 LOG_IOPORT("outb: %04x %02x\n", addr, val);
430 ioport_write(0, addr, val);
431 #ifdef USE_KQEMU
432 if (env)
433 env->last_io_time = cpu_get_time_fast();
434 #endif
437 void cpu_outw(CPUState *env, int addr, int val)
439 LOG_IOPORT("outw: %04x %04x\n", addr, val);
440 ioport_write(1, addr, val);
441 #ifdef USE_KQEMU
442 if (env)
443 env->last_io_time = cpu_get_time_fast();
444 #endif
447 void cpu_outl(CPUState *env, int addr, int val)
449 LOG_IOPORT("outl: %04x %08x\n", addr, val);
450 ioport_write(2, addr, val);
451 #ifdef USE_KQEMU
452 if (env)
453 env->last_io_time = cpu_get_time_fast();
454 #endif
457 int cpu_inb(CPUState *env, int addr)
459 int val;
460 val = ioport_read(0, addr);
461 LOG_IOPORT("inb : %04x %02x\n", addr, val);
462 #ifdef USE_KQEMU
463 if (env)
464 env->last_io_time = cpu_get_time_fast();
465 #endif
466 return val;
469 int cpu_inw(CPUState *env, int addr)
471 int val;
472 val = ioport_read(1, addr);
473 LOG_IOPORT("inw : %04x %04x\n", addr, val);
474 #ifdef USE_KQEMU
475 if (env)
476 env->last_io_time = cpu_get_time_fast();
477 #endif
478 return val;
481 int cpu_inl(CPUState *env, int addr)
483 int val;
484 val = ioport_read(2, addr);
485 LOG_IOPORT("inl : %04x %08x\n", addr, val);
486 #ifdef USE_KQEMU
487 if (env)
488 env->last_io_time = cpu_get_time_fast();
489 #endif
490 return val;
493 /***********************************************************/
494 void hw_error(const char *fmt, ...)
496 va_list ap;
497 CPUState *env;
499 va_start(ap, fmt);
500 fprintf(stderr, "qemu: hardware error: ");
501 vfprintf(stderr, fmt, ap);
502 fprintf(stderr, "\n");
503 for(env = first_cpu; env != NULL; env = env->next_cpu) {
504 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
505 #ifdef TARGET_I386
506 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
507 #else
508 cpu_dump_state(env, stderr, fprintf, 0);
509 #endif
511 va_end(ap);
512 abort();
515 /***************/
516 /* ballooning */
518 static QEMUBalloonEvent *qemu_balloon_event;
519 void *qemu_balloon_event_opaque;
521 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
523 qemu_balloon_event = func;
524 qemu_balloon_event_opaque = opaque;
527 void qemu_balloon(ram_addr_t target)
529 if (qemu_balloon_event)
530 qemu_balloon_event(qemu_balloon_event_opaque, target);
533 ram_addr_t qemu_balloon_status(void)
535 if (qemu_balloon_event)
536 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
537 return 0;
540 /***********************************************************/
541 /* keyboard/mouse */
543 static QEMUPutKBDEvent *qemu_put_kbd_event;
544 static void *qemu_put_kbd_event_opaque;
545 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
546 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
548 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
550 qemu_put_kbd_event_opaque = opaque;
551 qemu_put_kbd_event = func;
554 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
555 void *opaque, int absolute,
556 const char *name)
558 QEMUPutMouseEntry *s, *cursor;
560 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
562 s->qemu_put_mouse_event = func;
563 s->qemu_put_mouse_event_opaque = opaque;
564 s->qemu_put_mouse_event_absolute = absolute;
565 s->qemu_put_mouse_event_name = qemu_strdup(name);
566 s->next = NULL;
568 if (!qemu_put_mouse_event_head) {
569 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
570 return s;
573 cursor = qemu_put_mouse_event_head;
574 while (cursor->next != NULL)
575 cursor = cursor->next;
577 cursor->next = s;
578 qemu_put_mouse_event_current = s;
580 return s;
583 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
585 QEMUPutMouseEntry *prev = NULL, *cursor;
587 if (!qemu_put_mouse_event_head || entry == NULL)
588 return;
590 cursor = qemu_put_mouse_event_head;
591 while (cursor != NULL && cursor != entry) {
592 prev = cursor;
593 cursor = cursor->next;
596 if (cursor == NULL) // does not exist or list empty
597 return;
598 else if (prev == NULL) { // entry is head
599 qemu_put_mouse_event_head = cursor->next;
600 if (qemu_put_mouse_event_current == entry)
601 qemu_put_mouse_event_current = cursor->next;
602 qemu_free(entry->qemu_put_mouse_event_name);
603 qemu_free(entry);
604 return;
607 prev->next = entry->next;
609 if (qemu_put_mouse_event_current == entry)
610 qemu_put_mouse_event_current = prev;
612 qemu_free(entry->qemu_put_mouse_event_name);
613 qemu_free(entry);
616 void kbd_put_keycode(int keycode)
618 if (qemu_put_kbd_event) {
619 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
623 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
625 QEMUPutMouseEvent *mouse_event;
626 void *mouse_event_opaque;
627 int width;
629 if (!qemu_put_mouse_event_current) {
630 return;
633 mouse_event =
634 qemu_put_mouse_event_current->qemu_put_mouse_event;
635 mouse_event_opaque =
636 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
638 if (mouse_event) {
639 if (graphic_rotate) {
640 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
641 width = 0x7fff;
642 else
643 width = graphic_width - 1;
644 mouse_event(mouse_event_opaque,
645 width - dy, dx, dz, buttons_state);
646 } else
647 mouse_event(mouse_event_opaque,
648 dx, dy, dz, buttons_state);
652 int kbd_mouse_is_absolute(void)
654 if (!qemu_put_mouse_event_current)
655 return 0;
657 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
660 void do_info_mice(Monitor *mon)
662 QEMUPutMouseEntry *cursor;
663 int index = 0;
665 if (!qemu_put_mouse_event_head) {
666 monitor_printf(mon, "No mouse devices connected\n");
667 return;
670 monitor_printf(mon, "Mouse devices available:\n");
671 cursor = qemu_put_mouse_event_head;
672 while (cursor != NULL) {
673 monitor_printf(mon, "%c Mouse #%d: %s\n",
674 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
675 index, cursor->qemu_put_mouse_event_name);
676 index++;
677 cursor = cursor->next;
681 void do_mouse_set(Monitor *mon, int index)
683 QEMUPutMouseEntry *cursor;
684 int i = 0;
686 if (!qemu_put_mouse_event_head) {
687 monitor_printf(mon, "No mouse devices connected\n");
688 return;
691 cursor = qemu_put_mouse_event_head;
692 while (cursor != NULL && index != i) {
693 i++;
694 cursor = cursor->next;
697 if (cursor != NULL)
698 qemu_put_mouse_event_current = cursor;
699 else
700 monitor_printf(mon, "Mouse at given index not found\n");
703 /* compute with 96 bit intermediate result: (a*b)/c */
704 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
706 union {
707 uint64_t ll;
708 struct {
709 #ifdef WORDS_BIGENDIAN
710 uint32_t high, low;
711 #else
712 uint32_t low, high;
713 #endif
714 } l;
715 } u, res;
716 uint64_t rl, rh;
718 u.ll = a;
719 rl = (uint64_t)u.l.low * (uint64_t)b;
720 rh = (uint64_t)u.l.high * (uint64_t)b;
721 rh += (rl >> 32);
722 res.l.high = rh / c;
723 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
724 return res.ll;
727 /***********************************************************/
728 /* real time host monotonic timer */
730 #define QEMU_TIMER_BASE 1000000000LL
732 #ifdef WIN32
734 static int64_t clock_freq;
736 static void init_get_clock(void)
738 LARGE_INTEGER freq;
739 int ret;
740 ret = QueryPerformanceFrequency(&freq);
741 if (ret == 0) {
742 fprintf(stderr, "Could not calibrate ticks\n");
743 exit(1);
745 clock_freq = freq.QuadPart;
748 static int64_t get_clock(void)
750 LARGE_INTEGER ti;
751 QueryPerformanceCounter(&ti);
752 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
755 #else
757 static int use_rt_clock;
759 static void init_get_clock(void)
761 use_rt_clock = 0;
762 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
763 || defined(__DragonFly__)
765 struct timespec ts;
766 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
767 use_rt_clock = 1;
770 #endif
773 static int64_t get_clock(void)
775 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
776 || defined(__DragonFly__)
777 if (use_rt_clock) {
778 struct timespec ts;
779 clock_gettime(CLOCK_MONOTONIC, &ts);
780 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
781 } else
782 #endif
784 /* XXX: using gettimeofday leads to problems if the date
785 changes, so it should be avoided. */
786 struct timeval tv;
787 gettimeofday(&tv, NULL);
788 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
791 #endif
793 /* Return the virtual CPU time, based on the instruction counter. */
794 static int64_t cpu_get_icount(void)
796 int64_t icount;
797 CPUState *env = cpu_single_env;;
798 icount = qemu_icount;
799 if (env) {
800 if (!can_do_io(env))
801 fprintf(stderr, "Bad clock read\n");
802 icount -= (env->icount_decr.u16.low + env->icount_extra);
804 return qemu_icount_bias + (icount << icount_time_shift);
807 /***********************************************************/
808 /* guest cycle counter */
810 static int64_t cpu_ticks_prev;
811 static int64_t cpu_ticks_offset;
812 static int64_t cpu_clock_offset;
813 static int cpu_ticks_enabled;
815 /* return the host CPU cycle counter and handle stop/restart */
816 int64_t cpu_get_ticks(void)
818 if (use_icount) {
819 return cpu_get_icount();
821 if (!cpu_ticks_enabled) {
822 return cpu_ticks_offset;
823 } else {
824 int64_t ticks;
825 ticks = cpu_get_real_ticks();
826 if (cpu_ticks_prev > ticks) {
827 /* Note: non increasing ticks may happen if the host uses
828 software suspend */
829 cpu_ticks_offset += cpu_ticks_prev - ticks;
831 cpu_ticks_prev = ticks;
832 return ticks + cpu_ticks_offset;
836 /* return the host CPU monotonic timer and handle stop/restart */
837 static int64_t cpu_get_clock(void)
839 int64_t ti;
840 if (!cpu_ticks_enabled) {
841 return cpu_clock_offset;
842 } else {
843 ti = get_clock();
844 return ti + cpu_clock_offset;
848 /* enable cpu_get_ticks() */
849 void cpu_enable_ticks(void)
851 if (!cpu_ticks_enabled) {
852 cpu_ticks_offset -= cpu_get_real_ticks();
853 cpu_clock_offset -= get_clock();
854 cpu_ticks_enabled = 1;
858 /* disable cpu_get_ticks() : the clock is stopped. You must not call
859 cpu_get_ticks() after that. */
860 void cpu_disable_ticks(void)
862 if (cpu_ticks_enabled) {
863 cpu_ticks_offset = cpu_get_ticks();
864 cpu_clock_offset = cpu_get_clock();
865 cpu_ticks_enabled = 0;
869 /***********************************************************/
870 /* timers */
872 #define QEMU_TIMER_REALTIME 0
873 #define QEMU_TIMER_VIRTUAL 1
875 struct QEMUClock {
876 int type;
877 /* XXX: add frequency */
880 struct QEMUTimer {
881 QEMUClock *clock;
882 int64_t expire_time;
883 QEMUTimerCB *cb;
884 void *opaque;
885 struct QEMUTimer *next;
888 struct qemu_alarm_timer {
889 char const *name;
890 unsigned int flags;
892 int (*start)(struct qemu_alarm_timer *t);
893 void (*stop)(struct qemu_alarm_timer *t);
894 void (*rearm)(struct qemu_alarm_timer *t);
895 void *priv;
898 #define ALARM_FLAG_DYNTICKS 0x1
899 #define ALARM_FLAG_EXPIRED 0x2
901 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
903 return t->flags & ALARM_FLAG_DYNTICKS;
906 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
908 if (!alarm_has_dynticks(t))
909 return;
911 t->rearm(t);
914 /* TODO: MIN_TIMER_REARM_US should be optimized */
915 #define MIN_TIMER_REARM_US 250
917 static struct qemu_alarm_timer *alarm_timer;
918 #ifndef _WIN32
919 static int alarm_timer_rfd, alarm_timer_wfd;
920 #endif
922 #ifdef _WIN32
924 struct qemu_alarm_win32 {
925 MMRESULT timerId;
926 HANDLE host_alarm;
927 unsigned int period;
928 } alarm_win32_data = {0, NULL, -1};
930 static int win32_start_timer(struct qemu_alarm_timer *t);
931 static void win32_stop_timer(struct qemu_alarm_timer *t);
932 static void win32_rearm_timer(struct qemu_alarm_timer *t);
934 #else
936 static int unix_start_timer(struct qemu_alarm_timer *t);
937 static void unix_stop_timer(struct qemu_alarm_timer *t);
939 #ifdef __linux__
941 static int dynticks_start_timer(struct qemu_alarm_timer *t);
942 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
943 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
945 static int hpet_start_timer(struct qemu_alarm_timer *t);
946 static void hpet_stop_timer(struct qemu_alarm_timer *t);
948 static int rtc_start_timer(struct qemu_alarm_timer *t);
949 static void rtc_stop_timer(struct qemu_alarm_timer *t);
951 #endif /* __linux__ */
953 #endif /* _WIN32 */
955 /* Correlation between real and virtual time is always going to be
956 fairly approximate, so ignore small variation.
957 When the guest is idle real and virtual time will be aligned in
958 the IO wait loop. */
959 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
961 static void icount_adjust(void)
963 int64_t cur_time;
964 int64_t cur_icount;
965 int64_t delta;
966 static int64_t last_delta;
967 /* If the VM is not running, then do nothing. */
968 if (!vm_running)
969 return;
971 cur_time = cpu_get_clock();
972 cur_icount = qemu_get_clock(vm_clock);
973 delta = cur_icount - cur_time;
974 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
975 if (delta > 0
976 && last_delta + ICOUNT_WOBBLE < delta * 2
977 && icount_time_shift > 0) {
978 /* The guest is getting too far ahead. Slow time down. */
979 icount_time_shift--;
981 if (delta < 0
982 && last_delta - ICOUNT_WOBBLE > delta * 2
983 && icount_time_shift < MAX_ICOUNT_SHIFT) {
984 /* The guest is getting too far behind. Speed time up. */
985 icount_time_shift++;
987 last_delta = delta;
988 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
991 static void icount_adjust_rt(void * opaque)
993 qemu_mod_timer(icount_rt_timer,
994 qemu_get_clock(rt_clock) + 1000);
995 icount_adjust();
998 static void icount_adjust_vm(void * opaque)
1000 qemu_mod_timer(icount_vm_timer,
1001 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1002 icount_adjust();
1005 static void init_icount_adjust(void)
1007 /* Have both realtime and virtual time triggers for speed adjustment.
1008 The realtime trigger catches emulated time passing too slowly,
1009 the virtual time trigger catches emulated time passing too fast.
1010 Realtime triggers occur even when idle, so use them less frequently
1011 than VM triggers. */
1012 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1013 qemu_mod_timer(icount_rt_timer,
1014 qemu_get_clock(rt_clock) + 1000);
1015 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1016 qemu_mod_timer(icount_vm_timer,
1017 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1020 static struct qemu_alarm_timer alarm_timers[] = {
1021 #ifndef _WIN32
1022 #ifdef __linux__
1023 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1024 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1025 /* HPET - if available - is preferred */
1026 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1027 /* ...otherwise try RTC */
1028 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1029 #endif
1030 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1031 #else
1032 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1033 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1034 {"win32", 0, win32_start_timer,
1035 win32_stop_timer, NULL, &alarm_win32_data},
1036 #endif
1037 {NULL, }
1040 static void show_available_alarms(void)
1042 int i;
1044 printf("Available alarm timers, in order of precedence:\n");
1045 for (i = 0; alarm_timers[i].name; i++)
1046 printf("%s\n", alarm_timers[i].name);
1049 static void configure_alarms(char const *opt)
1051 int i;
1052 int cur = 0;
1053 int count = ARRAY_SIZE(alarm_timers) - 1;
1054 char *arg;
1055 char *name;
1056 struct qemu_alarm_timer tmp;
1058 if (!strcmp(opt, "?")) {
1059 show_available_alarms();
1060 exit(0);
1063 arg = strdup(opt);
1065 /* Reorder the array */
1066 name = strtok(arg, ",");
1067 while (name) {
1068 for (i = 0; i < count && alarm_timers[i].name; i++) {
1069 if (!strcmp(alarm_timers[i].name, name))
1070 break;
1073 if (i == count) {
1074 fprintf(stderr, "Unknown clock %s\n", name);
1075 goto next;
1078 if (i < cur)
1079 /* Ignore */
1080 goto next;
1082 /* Swap */
1083 tmp = alarm_timers[i];
1084 alarm_timers[i] = alarm_timers[cur];
1085 alarm_timers[cur] = tmp;
1087 cur++;
1088 next:
1089 name = strtok(NULL, ",");
1092 free(arg);
1094 if (cur) {
1095 /* Disable remaining timers */
1096 for (i = cur; i < count; i++)
1097 alarm_timers[i].name = NULL;
1098 } else {
1099 show_available_alarms();
1100 exit(1);
1104 QEMUClock *rt_clock;
1105 QEMUClock *vm_clock;
1107 static QEMUTimer *active_timers[2];
1109 static QEMUClock *qemu_new_clock(int type)
1111 QEMUClock *clock;
1112 clock = qemu_mallocz(sizeof(QEMUClock));
1113 clock->type = type;
1114 return clock;
1117 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1119 QEMUTimer *ts;
1121 ts = qemu_mallocz(sizeof(QEMUTimer));
1122 ts->clock = clock;
1123 ts->cb = cb;
1124 ts->opaque = opaque;
1125 return ts;
1128 void qemu_free_timer(QEMUTimer *ts)
1130 qemu_free(ts);
1133 /* stop a timer, but do not dealloc it */
1134 void qemu_del_timer(QEMUTimer *ts)
1136 QEMUTimer **pt, *t;
1138 /* NOTE: this code must be signal safe because
1139 qemu_timer_expired() can be called from a signal. */
1140 pt = &active_timers[ts->clock->type];
1141 for(;;) {
1142 t = *pt;
1143 if (!t)
1144 break;
1145 if (t == ts) {
1146 *pt = t->next;
1147 break;
1149 pt = &t->next;
1153 /* modify the current timer so that it will be fired when current_time
1154 >= expire_time. The corresponding callback will be called. */
1155 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1157 QEMUTimer **pt, *t;
1159 qemu_del_timer(ts);
1161 /* add the timer in the sorted list */
1162 /* NOTE: this code must be signal safe because
1163 qemu_timer_expired() can be called from a signal. */
1164 pt = &active_timers[ts->clock->type];
1165 for(;;) {
1166 t = *pt;
1167 if (!t)
1168 break;
1169 if (t->expire_time > expire_time)
1170 break;
1171 pt = &t->next;
1173 ts->expire_time = expire_time;
1174 ts->next = *pt;
1175 *pt = ts;
1177 /* Rearm if necessary */
1178 if (pt == &active_timers[ts->clock->type]) {
1179 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1180 qemu_rearm_alarm_timer(alarm_timer);
1182 /* Interrupt execution to force deadline recalculation. */
1183 if (use_icount && cpu_single_env) {
1184 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1189 int qemu_timer_pending(QEMUTimer *ts)
1191 QEMUTimer *t;
1192 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1193 if (t == ts)
1194 return 1;
1196 return 0;
1199 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1201 if (!timer_head)
1202 return 0;
1203 return (timer_head->expire_time <= current_time);
1206 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1208 QEMUTimer *ts;
1210 for(;;) {
1211 ts = *ptimer_head;
1212 if (!ts || ts->expire_time > current_time)
1213 break;
1214 /* remove timer from the list before calling the callback */
1215 *ptimer_head = ts->next;
1216 ts->next = NULL;
1218 /* run the callback (the timer list can be modified) */
1219 ts->cb(ts->opaque);
1223 int64_t qemu_get_clock(QEMUClock *clock)
1225 switch(clock->type) {
1226 case QEMU_TIMER_REALTIME:
1227 return get_clock() / 1000000;
1228 default:
1229 case QEMU_TIMER_VIRTUAL:
1230 if (use_icount) {
1231 return cpu_get_icount();
1232 } else {
1233 return cpu_get_clock();
1238 static void init_timers(void)
1240 init_get_clock();
1241 ticks_per_sec = QEMU_TIMER_BASE;
1242 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1243 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1246 /* save a timer */
1247 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1249 uint64_t expire_time;
1251 if (qemu_timer_pending(ts)) {
1252 expire_time = ts->expire_time;
1253 } else {
1254 expire_time = -1;
1256 qemu_put_be64(f, expire_time);
1259 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1261 uint64_t expire_time;
1263 expire_time = qemu_get_be64(f);
1264 if (expire_time != -1) {
1265 qemu_mod_timer(ts, expire_time);
1266 } else {
1267 qemu_del_timer(ts);
1271 static void timer_save(QEMUFile *f, void *opaque)
1273 if (cpu_ticks_enabled) {
1274 hw_error("cannot save state if virtual timers are running");
1276 qemu_put_be64(f, cpu_ticks_offset);
1277 qemu_put_be64(f, ticks_per_sec);
1278 qemu_put_be64(f, cpu_clock_offset);
1281 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1283 if (version_id != 1 && version_id != 2)
1284 return -EINVAL;
1285 if (cpu_ticks_enabled) {
1286 return -EINVAL;
1288 cpu_ticks_offset=qemu_get_be64(f);
1289 ticks_per_sec=qemu_get_be64(f);
1290 if (version_id == 2) {
1291 cpu_clock_offset=qemu_get_be64(f);
1293 return 0;
1296 #ifdef _WIN32
1297 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1298 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1299 #else
1300 static void host_alarm_handler(int host_signum)
1301 #endif
1303 #if 0
1304 #define DISP_FREQ 1000
1306 static int64_t delta_min = INT64_MAX;
1307 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1308 static int count;
1309 ti = qemu_get_clock(vm_clock);
1310 if (last_clock != 0) {
1311 delta = ti - last_clock;
1312 if (delta < delta_min)
1313 delta_min = delta;
1314 if (delta > delta_max)
1315 delta_max = delta;
1316 delta_cum += delta;
1317 if (++count == DISP_FREQ) {
1318 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1319 muldiv64(delta_min, 1000000, ticks_per_sec),
1320 muldiv64(delta_max, 1000000, ticks_per_sec),
1321 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1322 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1323 count = 0;
1324 delta_min = INT64_MAX;
1325 delta_max = 0;
1326 delta_cum = 0;
1329 last_clock = ti;
1331 #endif
1332 if (alarm_has_dynticks(alarm_timer) ||
1333 (!use_icount &&
1334 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1335 qemu_get_clock(vm_clock))) ||
1336 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1337 qemu_get_clock(rt_clock))) {
1338 CPUState *env = next_cpu;
1340 #ifdef _WIN32
1341 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1342 SetEvent(data->host_alarm);
1343 #else
1344 static const char byte = 0;
1345 write(alarm_timer_wfd, &byte, sizeof(byte));
1346 #endif
1347 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1349 if (env) {
1350 /* stop the currently executing cpu because a timer occured */
1351 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1352 #ifdef USE_KQEMU
1353 if (env->kqemu_enabled) {
1354 kqemu_cpu_interrupt(env);
1356 #endif
1358 event_pending = 1;
1362 static int64_t qemu_next_deadline(void)
1364 int64_t delta;
1366 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1367 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1368 qemu_get_clock(vm_clock);
1369 } else {
1370 /* To avoid problems with overflow limit this to 2^32. */
1371 delta = INT32_MAX;
1374 if (delta < 0)
1375 delta = 0;
1377 return delta;
1380 #if defined(__linux__) || defined(_WIN32)
1381 static uint64_t qemu_next_deadline_dyntick(void)
1383 int64_t delta;
1384 int64_t rtdelta;
1386 if (use_icount)
1387 delta = INT32_MAX;
1388 else
1389 delta = (qemu_next_deadline() + 999) / 1000;
1391 if (active_timers[QEMU_TIMER_REALTIME]) {
1392 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1393 qemu_get_clock(rt_clock))*1000;
1394 if (rtdelta < delta)
1395 delta = rtdelta;
1398 if (delta < MIN_TIMER_REARM_US)
1399 delta = MIN_TIMER_REARM_US;
1401 return delta;
1403 #endif
1405 #ifndef _WIN32
1407 /* Sets a specific flag */
1408 static int fcntl_setfl(int fd, int flag)
1410 int flags;
1412 flags = fcntl(fd, F_GETFL);
1413 if (flags == -1)
1414 return -errno;
1416 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1417 return -errno;
1419 return 0;
1422 #if defined(__linux__)
1424 #define RTC_FREQ 1024
1426 static void enable_sigio_timer(int fd)
1428 struct sigaction act;
1430 /* timer signal */
1431 sigfillset(&act.sa_mask);
1432 act.sa_flags = 0;
1433 act.sa_handler = host_alarm_handler;
1435 sigaction(SIGIO, &act, NULL);
1436 fcntl_setfl(fd, O_ASYNC);
1437 fcntl(fd, F_SETOWN, getpid());
1440 static int hpet_start_timer(struct qemu_alarm_timer *t)
1442 struct hpet_info info;
1443 int r, fd;
1445 fd = open("/dev/hpet", O_RDONLY);
1446 if (fd < 0)
1447 return -1;
1449 /* Set frequency */
1450 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1451 if (r < 0) {
1452 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1453 "error, but for better emulation accuracy type:\n"
1454 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1455 goto fail;
1458 /* Check capabilities */
1459 r = ioctl(fd, HPET_INFO, &info);
1460 if (r < 0)
1461 goto fail;
1463 /* Enable periodic mode */
1464 r = ioctl(fd, HPET_EPI, 0);
1465 if (info.hi_flags && (r < 0))
1466 goto fail;
1468 /* Enable interrupt */
1469 r = ioctl(fd, HPET_IE_ON, 0);
1470 if (r < 0)
1471 goto fail;
1473 enable_sigio_timer(fd);
1474 t->priv = (void *)(long)fd;
1476 return 0;
1477 fail:
1478 close(fd);
1479 return -1;
1482 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1484 int fd = (long)t->priv;
1486 close(fd);
1489 static int rtc_start_timer(struct qemu_alarm_timer *t)
1491 int rtc_fd;
1492 unsigned long current_rtc_freq = 0;
1494 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1495 if (rtc_fd < 0)
1496 return -1;
1497 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1498 if (current_rtc_freq != RTC_FREQ &&
1499 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1500 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1501 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1502 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1503 goto fail;
1505 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1506 fail:
1507 close(rtc_fd);
1508 return -1;
1511 enable_sigio_timer(rtc_fd);
1513 t->priv = (void *)(long)rtc_fd;
1515 return 0;
1518 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1520 int rtc_fd = (long)t->priv;
1522 close(rtc_fd);
1525 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1527 struct sigevent ev;
1528 timer_t host_timer;
1529 struct sigaction act;
1531 sigfillset(&act.sa_mask);
1532 act.sa_flags = 0;
1533 act.sa_handler = host_alarm_handler;
1535 sigaction(SIGALRM, &act, NULL);
1537 ev.sigev_value.sival_int = 0;
1538 ev.sigev_notify = SIGEV_SIGNAL;
1539 ev.sigev_signo = SIGALRM;
1541 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1542 perror("timer_create");
1544 /* disable dynticks */
1545 fprintf(stderr, "Dynamic Ticks disabled\n");
1547 return -1;
1550 t->priv = (void *)(long)host_timer;
1552 return 0;
1555 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1557 timer_t host_timer = (timer_t)(long)t->priv;
1559 timer_delete(host_timer);
1562 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1564 timer_t host_timer = (timer_t)(long)t->priv;
1565 struct itimerspec timeout;
1566 int64_t nearest_delta_us = INT64_MAX;
1567 int64_t current_us;
1569 if (!active_timers[QEMU_TIMER_REALTIME] &&
1570 !active_timers[QEMU_TIMER_VIRTUAL])
1571 return;
1573 nearest_delta_us = qemu_next_deadline_dyntick();
1575 /* check whether a timer is already running */
1576 if (timer_gettime(host_timer, &timeout)) {
1577 perror("gettime");
1578 fprintf(stderr, "Internal timer error: aborting\n");
1579 exit(1);
1581 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1582 if (current_us && current_us <= nearest_delta_us)
1583 return;
1585 timeout.it_interval.tv_sec = 0;
1586 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1587 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1588 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1589 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1590 perror("settime");
1591 fprintf(stderr, "Internal timer error: aborting\n");
1592 exit(1);
1596 #endif /* defined(__linux__) */
1598 static int unix_start_timer(struct qemu_alarm_timer *t)
1600 struct sigaction act;
1601 struct itimerval itv;
1602 int err;
1604 /* timer signal */
1605 sigfillset(&act.sa_mask);
1606 act.sa_flags = 0;
1607 act.sa_handler = host_alarm_handler;
1609 sigaction(SIGALRM, &act, NULL);
1611 itv.it_interval.tv_sec = 0;
1612 /* for i386 kernel 2.6 to get 1 ms */
1613 itv.it_interval.tv_usec = 999;
1614 itv.it_value.tv_sec = 0;
1615 itv.it_value.tv_usec = 10 * 1000;
1617 err = setitimer(ITIMER_REAL, &itv, NULL);
1618 if (err)
1619 return -1;
1621 return 0;
1624 static void unix_stop_timer(struct qemu_alarm_timer *t)
1626 struct itimerval itv;
1628 memset(&itv, 0, sizeof(itv));
1629 setitimer(ITIMER_REAL, &itv, NULL);
1632 #endif /* !defined(_WIN32) */
1634 static void try_to_rearm_timer(void *opaque)
1636 struct qemu_alarm_timer *t = opaque;
1637 #ifndef _WIN32
1638 ssize_t len;
1640 /* Drain the notify pipe */
1641 do {
1642 char buffer[512];
1643 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1644 } while ((len == -1 && errno == EINTR) || len > 0);
1645 #endif
1647 if (t->flags & ALARM_FLAG_EXPIRED) {
1648 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1649 qemu_rearm_alarm_timer(alarm_timer);
1653 #ifdef _WIN32
1655 static int win32_start_timer(struct qemu_alarm_timer *t)
1657 TIMECAPS tc;
1658 struct qemu_alarm_win32 *data = t->priv;
1659 UINT flags;
1661 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1662 if (!data->host_alarm) {
1663 perror("Failed CreateEvent");
1664 return -1;
1667 memset(&tc, 0, sizeof(tc));
1668 timeGetDevCaps(&tc, sizeof(tc));
1670 if (data->period < tc.wPeriodMin)
1671 data->period = tc.wPeriodMin;
1673 timeBeginPeriod(data->period);
1675 flags = TIME_CALLBACK_FUNCTION;
1676 if (alarm_has_dynticks(t))
1677 flags |= TIME_ONESHOT;
1678 else
1679 flags |= TIME_PERIODIC;
1681 data->timerId = timeSetEvent(1, // interval (ms)
1682 data->period, // resolution
1683 host_alarm_handler, // function
1684 (DWORD)t, // parameter
1685 flags);
1687 if (!data->timerId) {
1688 perror("Failed to initialize win32 alarm timer");
1690 timeEndPeriod(data->period);
1691 CloseHandle(data->host_alarm);
1692 return -1;
1695 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1697 return 0;
1700 static void win32_stop_timer(struct qemu_alarm_timer *t)
1702 struct qemu_alarm_win32 *data = t->priv;
1704 timeKillEvent(data->timerId);
1705 timeEndPeriod(data->period);
1707 CloseHandle(data->host_alarm);
1710 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1712 struct qemu_alarm_win32 *data = t->priv;
1713 uint64_t nearest_delta_us;
1715 if (!active_timers[QEMU_TIMER_REALTIME] &&
1716 !active_timers[QEMU_TIMER_VIRTUAL])
1717 return;
1719 nearest_delta_us = qemu_next_deadline_dyntick();
1720 nearest_delta_us /= 1000;
1722 timeKillEvent(data->timerId);
1724 data->timerId = timeSetEvent(1,
1725 data->period,
1726 host_alarm_handler,
1727 (DWORD)t,
1728 TIME_ONESHOT | TIME_PERIODIC);
1730 if (!data->timerId) {
1731 perror("Failed to re-arm win32 alarm timer");
1733 timeEndPeriod(data->period);
1734 CloseHandle(data->host_alarm);
1735 exit(1);
1739 #endif /* _WIN32 */
1741 static int init_timer_alarm(void)
1743 struct qemu_alarm_timer *t = NULL;
1744 int i, err = -1;
1746 #ifndef _WIN32
1747 int fds[2];
1749 err = pipe(fds);
1750 if (err == -1)
1751 return -errno;
1753 err = fcntl_setfl(fds[0], O_NONBLOCK);
1754 if (err < 0)
1755 goto fail;
1757 err = fcntl_setfl(fds[1], O_NONBLOCK);
1758 if (err < 0)
1759 goto fail;
1761 alarm_timer_rfd = fds[0];
1762 alarm_timer_wfd = fds[1];
1763 #endif
1765 for (i = 0; alarm_timers[i].name; i++) {
1766 t = &alarm_timers[i];
1768 err = t->start(t);
1769 if (!err)
1770 break;
1773 if (err) {
1774 err = -ENOENT;
1775 goto fail;
1778 #ifndef _WIN32
1779 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1780 try_to_rearm_timer, NULL, t);
1781 #endif
1783 alarm_timer = t;
1785 return 0;
1787 fail:
1788 #ifndef _WIN32
1789 close(fds[0]);
1790 close(fds[1]);
1791 #endif
1792 return err;
1795 static void quit_timers(void)
1797 alarm_timer->stop(alarm_timer);
1798 alarm_timer = NULL;
1801 /***********************************************************/
1802 /* host time/date access */
1803 void qemu_get_timedate(struct tm *tm, int offset)
1805 time_t ti;
1806 struct tm *ret;
1808 time(&ti);
1809 ti += offset;
1810 if (rtc_date_offset == -1) {
1811 if (rtc_utc)
1812 ret = gmtime(&ti);
1813 else
1814 ret = localtime(&ti);
1815 } else {
1816 ti -= rtc_date_offset;
1817 ret = gmtime(&ti);
1820 memcpy(tm, ret, sizeof(struct tm));
1823 int qemu_timedate_diff(struct tm *tm)
1825 time_t seconds;
1827 if (rtc_date_offset == -1)
1828 if (rtc_utc)
1829 seconds = mktimegm(tm);
1830 else
1831 seconds = mktime(tm);
1832 else
1833 seconds = mktimegm(tm) + rtc_date_offset;
1835 return seconds - time(NULL);
1838 #ifdef _WIN32
1839 static void socket_cleanup(void)
1841 WSACleanup();
1844 static int socket_init(void)
1846 WSADATA Data;
1847 int ret, err;
1849 ret = WSAStartup(MAKEWORD(2,2), &Data);
1850 if (ret != 0) {
1851 err = WSAGetLastError();
1852 fprintf(stderr, "WSAStartup: %d\n", err);
1853 return -1;
1855 atexit(socket_cleanup);
1856 return 0;
1858 #endif
1860 const char *get_opt_name(char *buf, int buf_size, const char *p)
1862 char *q;
1864 q = buf;
1865 while (*p != '\0' && *p != '=') {
1866 if (q && (q - buf) < buf_size - 1)
1867 *q++ = *p;
1868 p++;
1870 if (q)
1871 *q = '\0';
1873 return p;
1876 const char *get_opt_value(char *buf, int buf_size, const char *p)
1878 char *q;
1880 q = buf;
1881 while (*p != '\0') {
1882 if (*p == ',') {
1883 if (*(p + 1) != ',')
1884 break;
1885 p++;
1887 if (q && (q - buf) < buf_size - 1)
1888 *q++ = *p;
1889 p++;
1891 if (q)
1892 *q = '\0';
1894 return p;
1897 int get_param_value(char *buf, int buf_size,
1898 const char *tag, const char *str)
1900 const char *p;
1901 char option[128];
1903 p = str;
1904 for(;;) {
1905 p = get_opt_name(option, sizeof(option), p);
1906 if (*p != '=')
1907 break;
1908 p++;
1909 if (!strcmp(tag, option)) {
1910 (void)get_opt_value(buf, buf_size, p);
1911 return strlen(buf);
1912 } else {
1913 p = get_opt_value(NULL, 0, p);
1915 if (*p != ',')
1916 break;
1917 p++;
1919 return 0;
1922 int check_params(char *buf, int buf_size,
1923 const char * const *params, const char *str)
1925 const char *p;
1926 int i;
1928 p = str;
1929 for(;;) {
1930 p = get_opt_name(buf, buf_size, p);
1931 if (*p != '=')
1932 return -1;
1933 p++;
1934 for(i = 0; params[i] != NULL; i++)
1935 if (!strcmp(params[i], buf))
1936 break;
1937 if (params[i] == NULL)
1938 return -1;
1939 p = get_opt_value(NULL, 0, p);
1940 if (*p != ',')
1941 break;
1942 p++;
1944 return 0;
1947 /***********************************************************/
1948 /* Bluetooth support */
1949 static int nb_hcis;
1950 static int cur_hci;
1951 static struct HCIInfo *hci_table[MAX_NICS];
1953 static struct bt_vlan_s {
1954 struct bt_scatternet_s net;
1955 int id;
1956 struct bt_vlan_s *next;
1957 } *first_bt_vlan;
1959 /* find or alloc a new bluetooth "VLAN" */
1960 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1962 struct bt_vlan_s **pvlan, *vlan;
1963 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1964 if (vlan->id == id)
1965 return &vlan->net;
1967 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1968 vlan->id = id;
1969 pvlan = &first_bt_vlan;
1970 while (*pvlan != NULL)
1971 pvlan = &(*pvlan)->next;
1972 *pvlan = vlan;
1973 return &vlan->net;
1976 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1980 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1982 return -ENOTSUP;
1985 static struct HCIInfo null_hci = {
1986 .cmd_send = null_hci_send,
1987 .sco_send = null_hci_send,
1988 .acl_send = null_hci_send,
1989 .bdaddr_set = null_hci_addr_set,
1992 struct HCIInfo *qemu_next_hci(void)
1994 if (cur_hci == nb_hcis)
1995 return &null_hci;
1997 return hci_table[cur_hci++];
2000 static struct HCIInfo *hci_init(const char *str)
2002 char *endp;
2003 struct bt_scatternet_s *vlan = 0;
2005 if (!strcmp(str, "null"))
2006 /* null */
2007 return &null_hci;
2008 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2009 /* host[:hciN] */
2010 return bt_host_hci(str[4] ? str + 5 : "hci0");
2011 else if (!strncmp(str, "hci", 3)) {
2012 /* hci[,vlan=n] */
2013 if (str[3]) {
2014 if (!strncmp(str + 3, ",vlan=", 6)) {
2015 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2016 if (*endp)
2017 vlan = 0;
2019 } else
2020 vlan = qemu_find_bt_vlan(0);
2021 if (vlan)
2022 return bt_new_hci(vlan);
2025 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2027 return 0;
2030 static int bt_hci_parse(const char *str)
2032 struct HCIInfo *hci;
2033 bdaddr_t bdaddr;
2035 if (nb_hcis >= MAX_NICS) {
2036 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2037 return -1;
2040 hci = hci_init(str);
2041 if (!hci)
2042 return -1;
2044 bdaddr.b[0] = 0x52;
2045 bdaddr.b[1] = 0x54;
2046 bdaddr.b[2] = 0x00;
2047 bdaddr.b[3] = 0x12;
2048 bdaddr.b[4] = 0x34;
2049 bdaddr.b[5] = 0x56 + nb_hcis;
2050 hci->bdaddr_set(hci, bdaddr.b);
2052 hci_table[nb_hcis++] = hci;
2054 return 0;
2057 static void bt_vhci_add(int vlan_id)
2059 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2061 if (!vlan->slave)
2062 fprintf(stderr, "qemu: warning: adding a VHCI to "
2063 "an empty scatternet %i\n", vlan_id);
2065 bt_vhci_init(bt_new_hci(vlan));
2068 static struct bt_device_s *bt_device_add(const char *opt)
2070 struct bt_scatternet_s *vlan;
2071 int vlan_id = 0;
2072 char *endp = strstr(opt, ",vlan=");
2073 int len = (endp ? endp - opt : strlen(opt)) + 1;
2074 char devname[10];
2076 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2078 if (endp) {
2079 vlan_id = strtol(endp + 6, &endp, 0);
2080 if (*endp) {
2081 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2082 return 0;
2086 vlan = qemu_find_bt_vlan(vlan_id);
2088 if (!vlan->slave)
2089 fprintf(stderr, "qemu: warning: adding a slave device to "
2090 "an empty scatternet %i\n", vlan_id);
2092 if (!strcmp(devname, "keyboard"))
2093 return bt_keyboard_init(vlan);
2095 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2096 return 0;
2099 static int bt_parse(const char *opt)
2101 const char *endp, *p;
2102 int vlan;
2104 if (strstart(opt, "hci", &endp)) {
2105 if (!*endp || *endp == ',') {
2106 if (*endp)
2107 if (!strstart(endp, ",vlan=", 0))
2108 opt = endp + 1;
2110 return bt_hci_parse(opt);
2112 } else if (strstart(opt, "vhci", &endp)) {
2113 if (!*endp || *endp == ',') {
2114 if (*endp) {
2115 if (strstart(endp, ",vlan=", &p)) {
2116 vlan = strtol(p, (char **) &endp, 0);
2117 if (*endp) {
2118 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2119 return 1;
2121 } else {
2122 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2123 return 1;
2125 } else
2126 vlan = 0;
2128 bt_vhci_add(vlan);
2129 return 0;
2131 } else if (strstart(opt, "device:", &endp))
2132 return !bt_device_add(endp);
2134 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2135 return 1;
2138 /***********************************************************/
2139 /* QEMU Block devices */
2141 #define HD_ALIAS "index=%d,media=disk"
2142 #ifdef TARGET_PPC
2143 #define CDROM_ALIAS "index=1,media=cdrom"
2144 #else
2145 #define CDROM_ALIAS "index=2,media=cdrom"
2146 #endif
2147 #define FD_ALIAS "index=%d,if=floppy"
2148 #define PFLASH_ALIAS "if=pflash"
2149 #define MTD_ALIAS "if=mtd"
2150 #define SD_ALIAS "index=0,if=sd"
2152 static int drive_opt_get_free_idx(void)
2154 int index;
2156 for (index = 0; index < MAX_DRIVES; index++)
2157 if (!drives_opt[index].used) {
2158 drives_opt[index].used = 1;
2159 return index;
2162 return -1;
2165 static int drive_get_free_idx(void)
2167 int index;
2169 for (index = 0; index < MAX_DRIVES; index++)
2170 if (!drives_table[index].used) {
2171 drives_table[index].used = 1;
2172 return index;
2175 return -1;
2178 int drive_add(const char *file, const char *fmt, ...)
2180 va_list ap;
2181 int index = drive_opt_get_free_idx();
2183 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2184 fprintf(stderr, "qemu: too many drives\n");
2185 return -1;
2188 drives_opt[index].file = file;
2189 va_start(ap, fmt);
2190 vsnprintf(drives_opt[index].opt,
2191 sizeof(drives_opt[0].opt), fmt, ap);
2192 va_end(ap);
2194 nb_drives_opt++;
2195 return index;
2198 void drive_remove(int index)
2200 drives_opt[index].used = 0;
2201 nb_drives_opt--;
2204 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2206 int index;
2208 /* seek interface, bus and unit */
2210 for (index = 0; index < MAX_DRIVES; index++)
2211 if (drives_table[index].type == type &&
2212 drives_table[index].bus == bus &&
2213 drives_table[index].unit == unit &&
2214 drives_table[index].used)
2215 return index;
2217 return -1;
2220 int drive_get_max_bus(BlockInterfaceType type)
2222 int max_bus;
2223 int index;
2225 max_bus = -1;
2226 for (index = 0; index < nb_drives; index++) {
2227 if(drives_table[index].type == type &&
2228 drives_table[index].bus > max_bus)
2229 max_bus = drives_table[index].bus;
2231 return max_bus;
2234 const char *drive_get_serial(BlockDriverState *bdrv)
2236 int index;
2238 for (index = 0; index < nb_drives; index++)
2239 if (drives_table[index].bdrv == bdrv)
2240 return drives_table[index].serial;
2242 return "\0";
2245 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2247 int index;
2249 for (index = 0; index < nb_drives; index++)
2250 if (drives_table[index].bdrv == bdrv)
2251 return drives_table[index].onerror;
2253 return BLOCK_ERR_STOP_ENOSPC;
2256 static void bdrv_format_print(void *opaque, const char *name)
2258 fprintf(stderr, " %s", name);
2261 void drive_uninit(BlockDriverState *bdrv)
2263 int i;
2265 for (i = 0; i < MAX_DRIVES; i++)
2266 if (drives_table[i].bdrv == bdrv) {
2267 drives_table[i].bdrv = NULL;
2268 drives_table[i].used = 0;
2269 drive_remove(drives_table[i].drive_opt_idx);
2270 nb_drives--;
2271 break;
2275 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2277 char buf[128];
2278 char file[1024];
2279 char devname[128];
2280 char serial[21];
2281 const char *mediastr = "";
2282 BlockInterfaceType type;
2283 enum { MEDIA_DISK, MEDIA_CDROM } media;
2284 int bus_id, unit_id;
2285 int cyls, heads, secs, translation;
2286 BlockDriverState *bdrv;
2287 BlockDriver *drv = NULL;
2288 QEMUMachine *machine = opaque;
2289 int max_devs;
2290 int index;
2291 int cache;
2292 int bdrv_flags, onerror;
2293 int drives_table_idx;
2294 char *str = arg->opt;
2295 static const char * const params[] = { "bus", "unit", "if", "index",
2296 "cyls", "heads", "secs", "trans",
2297 "media", "snapshot", "file",
2298 "cache", "format", "serial", "werror",
2299 NULL };
2301 if (check_params(buf, sizeof(buf), params, str) < 0) {
2302 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2303 buf, str);
2304 return -1;
2307 file[0] = 0;
2308 cyls = heads = secs = 0;
2309 bus_id = 0;
2310 unit_id = -1;
2311 translation = BIOS_ATA_TRANSLATION_AUTO;
2312 index = -1;
2313 cache = 3;
2315 if (machine->use_scsi) {
2316 type = IF_SCSI;
2317 max_devs = MAX_SCSI_DEVS;
2318 pstrcpy(devname, sizeof(devname), "scsi");
2319 } else {
2320 type = IF_IDE;
2321 max_devs = MAX_IDE_DEVS;
2322 pstrcpy(devname, sizeof(devname), "ide");
2324 media = MEDIA_DISK;
2326 /* extract parameters */
2328 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2329 bus_id = strtol(buf, NULL, 0);
2330 if (bus_id < 0) {
2331 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2332 return -1;
2336 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2337 unit_id = strtol(buf, NULL, 0);
2338 if (unit_id < 0) {
2339 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2340 return -1;
2344 if (get_param_value(buf, sizeof(buf), "if", str)) {
2345 pstrcpy(devname, sizeof(devname), buf);
2346 if (!strcmp(buf, "ide")) {
2347 type = IF_IDE;
2348 max_devs = MAX_IDE_DEVS;
2349 } else if (!strcmp(buf, "scsi")) {
2350 type = IF_SCSI;
2351 max_devs = MAX_SCSI_DEVS;
2352 } else if (!strcmp(buf, "floppy")) {
2353 type = IF_FLOPPY;
2354 max_devs = 0;
2355 } else if (!strcmp(buf, "pflash")) {
2356 type = IF_PFLASH;
2357 max_devs = 0;
2358 } else if (!strcmp(buf, "mtd")) {
2359 type = IF_MTD;
2360 max_devs = 0;
2361 } else if (!strcmp(buf, "sd")) {
2362 type = IF_SD;
2363 max_devs = 0;
2364 } else if (!strcmp(buf, "virtio")) {
2365 type = IF_VIRTIO;
2366 max_devs = 0;
2367 } else {
2368 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2369 return -1;
2373 if (get_param_value(buf, sizeof(buf), "index", str)) {
2374 index = strtol(buf, NULL, 0);
2375 if (index < 0) {
2376 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2377 return -1;
2381 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2382 cyls = strtol(buf, NULL, 0);
2385 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2386 heads = strtol(buf, NULL, 0);
2389 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2390 secs = strtol(buf, NULL, 0);
2393 if (cyls || heads || secs) {
2394 if (cyls < 1 || cyls > 16383) {
2395 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2396 return -1;
2398 if (heads < 1 || heads > 16) {
2399 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2400 return -1;
2402 if (secs < 1 || secs > 63) {
2403 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2404 return -1;
2408 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2409 if (!cyls) {
2410 fprintf(stderr,
2411 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2412 str);
2413 return -1;
2415 if (!strcmp(buf, "none"))
2416 translation = BIOS_ATA_TRANSLATION_NONE;
2417 else if (!strcmp(buf, "lba"))
2418 translation = BIOS_ATA_TRANSLATION_LBA;
2419 else if (!strcmp(buf, "auto"))
2420 translation = BIOS_ATA_TRANSLATION_AUTO;
2421 else {
2422 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2423 return -1;
2427 if (get_param_value(buf, sizeof(buf), "media", str)) {
2428 if (!strcmp(buf, "disk")) {
2429 media = MEDIA_DISK;
2430 } else if (!strcmp(buf, "cdrom")) {
2431 if (cyls || secs || heads) {
2432 fprintf(stderr,
2433 "qemu: '%s' invalid physical CHS format\n", str);
2434 return -1;
2436 media = MEDIA_CDROM;
2437 } else {
2438 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2439 return -1;
2443 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2444 if (!strcmp(buf, "on"))
2445 snapshot = 1;
2446 else if (!strcmp(buf, "off"))
2447 snapshot = 0;
2448 else {
2449 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2450 return -1;
2454 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2455 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2456 cache = 0;
2457 else if (!strcmp(buf, "writethrough"))
2458 cache = 1;
2459 else if (!strcmp(buf, "writeback"))
2460 cache = 2;
2461 else {
2462 fprintf(stderr, "qemu: invalid cache option\n");
2463 return -1;
2467 if (get_param_value(buf, sizeof(buf), "format", str)) {
2468 if (strcmp(buf, "?") == 0) {
2469 fprintf(stderr, "qemu: Supported formats:");
2470 bdrv_iterate_format(bdrv_format_print, NULL);
2471 fprintf(stderr, "\n");
2472 return -1;
2474 drv = bdrv_find_format(buf);
2475 if (!drv) {
2476 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2477 return -1;
2481 if (arg->file == NULL)
2482 get_param_value(file, sizeof(file), "file", str);
2483 else
2484 pstrcpy(file, sizeof(file), arg->file);
2486 if (!get_param_value(serial, sizeof(serial), "serial", str))
2487 memset(serial, 0, sizeof(serial));
2489 onerror = BLOCK_ERR_STOP_ENOSPC;
2490 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2491 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2492 fprintf(stderr, "werror is no supported by this format\n");
2493 return -1;
2495 if (!strcmp(buf, "ignore"))
2496 onerror = BLOCK_ERR_IGNORE;
2497 else if (!strcmp(buf, "enospc"))
2498 onerror = BLOCK_ERR_STOP_ENOSPC;
2499 else if (!strcmp(buf, "stop"))
2500 onerror = BLOCK_ERR_STOP_ANY;
2501 else if (!strcmp(buf, "report"))
2502 onerror = BLOCK_ERR_REPORT;
2503 else {
2504 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2505 return -1;
2509 /* compute bus and unit according index */
2511 if (index != -1) {
2512 if (bus_id != 0 || unit_id != -1) {
2513 fprintf(stderr,
2514 "qemu: '%s' index cannot be used with bus and unit\n", str);
2515 return -1;
2517 if (max_devs == 0)
2519 unit_id = index;
2520 bus_id = 0;
2521 } else {
2522 unit_id = index % max_devs;
2523 bus_id = index / max_devs;
2527 /* if user doesn't specify a unit_id,
2528 * try to find the first free
2531 if (unit_id == -1) {
2532 unit_id = 0;
2533 while (drive_get_index(type, bus_id, unit_id) != -1) {
2534 unit_id++;
2535 if (max_devs && unit_id >= max_devs) {
2536 unit_id -= max_devs;
2537 bus_id++;
2542 /* check unit id */
2544 if (max_devs && unit_id >= max_devs) {
2545 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2546 str, unit_id, max_devs - 1);
2547 return -1;
2551 * ignore multiple definitions
2554 if (drive_get_index(type, bus_id, unit_id) != -1)
2555 return -2;
2557 /* init */
2559 if (type == IF_IDE || type == IF_SCSI)
2560 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2561 if (max_devs)
2562 snprintf(buf, sizeof(buf), "%s%i%s%i",
2563 devname, bus_id, mediastr, unit_id);
2564 else
2565 snprintf(buf, sizeof(buf), "%s%s%i",
2566 devname, mediastr, unit_id);
2567 bdrv = bdrv_new(buf);
2568 drives_table_idx = drive_get_free_idx();
2569 drives_table[drives_table_idx].bdrv = bdrv;
2570 drives_table[drives_table_idx].type = type;
2571 drives_table[drives_table_idx].bus = bus_id;
2572 drives_table[drives_table_idx].unit = unit_id;
2573 drives_table[drives_table_idx].onerror = onerror;
2574 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2575 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2576 nb_drives++;
2578 switch(type) {
2579 case IF_IDE:
2580 case IF_SCSI:
2581 switch(media) {
2582 case MEDIA_DISK:
2583 if (cyls != 0) {
2584 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2585 bdrv_set_translation_hint(bdrv, translation);
2587 break;
2588 case MEDIA_CDROM:
2589 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2590 break;
2592 break;
2593 case IF_SD:
2594 /* FIXME: This isn't really a floppy, but it's a reasonable
2595 approximation. */
2596 case IF_FLOPPY:
2597 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2598 break;
2599 case IF_PFLASH:
2600 case IF_MTD:
2601 case IF_VIRTIO:
2602 break;
2604 if (!file[0])
2605 return -2;
2606 bdrv_flags = 0;
2607 if (snapshot) {
2608 bdrv_flags |= BDRV_O_SNAPSHOT;
2609 cache = 2; /* always use write-back with snapshot */
2611 if (cache == 0) /* no caching */
2612 bdrv_flags |= BDRV_O_NOCACHE;
2613 else if (cache == 2) /* write-back */
2614 bdrv_flags |= BDRV_O_CACHE_WB;
2615 else if (cache == 3) /* not specified */
2616 bdrv_flags |= BDRV_O_CACHE_DEF;
2617 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2618 fprintf(stderr, "qemu: could not open disk image %s\n",
2619 file);
2620 return -1;
2622 if (bdrv_key_required(bdrv))
2623 autostart = 0;
2624 return drives_table_idx;
2627 /***********************************************************/
2628 /* USB devices */
2630 static USBPort *used_usb_ports;
2631 static USBPort *free_usb_ports;
2633 /* ??? Maybe change this to register a hub to keep track of the topology. */
2634 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2635 usb_attachfn attach)
2637 port->opaque = opaque;
2638 port->index = index;
2639 port->attach = attach;
2640 port->next = free_usb_ports;
2641 free_usb_ports = port;
2644 int usb_device_add_dev(USBDevice *dev)
2646 USBPort *port;
2648 /* Find a USB port to add the device to. */
2649 port = free_usb_ports;
2650 if (!port->next) {
2651 USBDevice *hub;
2653 /* Create a new hub and chain it on. */
2654 free_usb_ports = NULL;
2655 port->next = used_usb_ports;
2656 used_usb_ports = port;
2658 hub = usb_hub_init(VM_USB_HUB_SIZE);
2659 usb_attach(port, hub);
2660 port = free_usb_ports;
2663 free_usb_ports = port->next;
2664 port->next = used_usb_ports;
2665 used_usb_ports = port;
2666 usb_attach(port, dev);
2667 return 0;
2670 static void usb_msd_password_cb(void *opaque, int err)
2672 USBDevice *dev = opaque;
2674 if (!err)
2675 usb_device_add_dev(dev);
2676 else
2677 dev->handle_destroy(dev);
2680 static int usb_device_add(const char *devname, int is_hotplug)
2682 const char *p;
2683 USBDevice *dev;
2685 if (!free_usb_ports)
2686 return -1;
2688 if (strstart(devname, "host:", &p)) {
2689 dev = usb_host_device_open(p);
2690 } else if (!strcmp(devname, "mouse")) {
2691 dev = usb_mouse_init();
2692 } else if (!strcmp(devname, "tablet")) {
2693 dev = usb_tablet_init();
2694 } else if (!strcmp(devname, "keyboard")) {
2695 dev = usb_keyboard_init();
2696 } else if (strstart(devname, "disk:", &p)) {
2697 BlockDriverState *bs;
2699 dev = usb_msd_init(p);
2700 if (!dev)
2701 return -1;
2702 bs = usb_msd_get_bdrv(dev);
2703 if (bdrv_key_required(bs)) {
2704 autostart = 0;
2705 if (is_hotplug) {
2706 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2707 dev);
2708 return 0;
2711 } else if (!strcmp(devname, "wacom-tablet")) {
2712 dev = usb_wacom_init();
2713 } else if (strstart(devname, "serial:", &p)) {
2714 dev = usb_serial_init(p);
2715 #ifdef CONFIG_BRLAPI
2716 } else if (!strcmp(devname, "braille")) {
2717 dev = usb_baum_init();
2718 #endif
2719 } else if (strstart(devname, "net:", &p)) {
2720 int nic = nb_nics;
2722 if (net_client_init("nic", p) < 0)
2723 return -1;
2724 nd_table[nic].model = "usb";
2725 dev = usb_net_init(&nd_table[nic]);
2726 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2727 dev = usb_bt_init(devname[2] ? hci_init(p) :
2728 bt_new_hci(qemu_find_bt_vlan(0)));
2729 } else {
2730 return -1;
2732 if (!dev)
2733 return -1;
2735 return usb_device_add_dev(dev);
2738 int usb_device_del_addr(int bus_num, int addr)
2740 USBPort *port;
2741 USBPort **lastp;
2742 USBDevice *dev;
2744 if (!used_usb_ports)
2745 return -1;
2747 if (bus_num != 0)
2748 return -1;
2750 lastp = &used_usb_ports;
2751 port = used_usb_ports;
2752 while (port && port->dev->addr != addr) {
2753 lastp = &port->next;
2754 port = port->next;
2757 if (!port)
2758 return -1;
2760 dev = port->dev;
2761 *lastp = port->next;
2762 usb_attach(port, NULL);
2763 dev->handle_destroy(dev);
2764 port->next = free_usb_ports;
2765 free_usb_ports = port;
2766 return 0;
2769 static int usb_device_del(const char *devname)
2771 int bus_num, addr;
2772 const char *p;
2774 if (strstart(devname, "host:", &p))
2775 return usb_host_device_close(p);
2777 if (!used_usb_ports)
2778 return -1;
2780 p = strchr(devname, '.');
2781 if (!p)
2782 return -1;
2783 bus_num = strtoul(devname, NULL, 0);
2784 addr = strtoul(p + 1, NULL, 0);
2786 return usb_device_del_addr(bus_num, addr);
2789 void do_usb_add(Monitor *mon, const char *devname)
2791 usb_device_add(devname, 1);
2794 void do_usb_del(Monitor *mon, const char *devname)
2796 usb_device_del(devname);
2799 void usb_info(Monitor *mon)
2801 USBDevice *dev;
2802 USBPort *port;
2803 const char *speed_str;
2805 if (!usb_enabled) {
2806 monitor_printf(mon, "USB support not enabled\n");
2807 return;
2810 for (port = used_usb_ports; port; port = port->next) {
2811 dev = port->dev;
2812 if (!dev)
2813 continue;
2814 switch(dev->speed) {
2815 case USB_SPEED_LOW:
2816 speed_str = "1.5";
2817 break;
2818 case USB_SPEED_FULL:
2819 speed_str = "12";
2820 break;
2821 case USB_SPEED_HIGH:
2822 speed_str = "480";
2823 break;
2824 default:
2825 speed_str = "?";
2826 break;
2828 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2829 0, dev->addr, speed_str, dev->devname);
2833 /***********************************************************/
2834 /* PCMCIA/Cardbus */
2836 static struct pcmcia_socket_entry_s {
2837 struct pcmcia_socket_s *socket;
2838 struct pcmcia_socket_entry_s *next;
2839 } *pcmcia_sockets = 0;
2841 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2843 struct pcmcia_socket_entry_s *entry;
2845 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2846 entry->socket = socket;
2847 entry->next = pcmcia_sockets;
2848 pcmcia_sockets = entry;
2851 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2853 struct pcmcia_socket_entry_s *entry, **ptr;
2855 ptr = &pcmcia_sockets;
2856 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2857 if (entry->socket == socket) {
2858 *ptr = entry->next;
2859 qemu_free(entry);
2863 void pcmcia_info(Monitor *mon)
2865 struct pcmcia_socket_entry_s *iter;
2867 if (!pcmcia_sockets)
2868 monitor_printf(mon, "No PCMCIA sockets\n");
2870 for (iter = pcmcia_sockets; iter; iter = iter->next)
2871 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2872 iter->socket->attached ? iter->socket->card_string :
2873 "Empty");
2876 /***********************************************************/
2877 /* register display */
2879 void register_displaystate(DisplayState *ds)
2881 DisplayState **s;
2882 s = &display_state;
2883 while (*s != NULL)
2884 s = &(*s)->next;
2885 ds->next = NULL;
2886 *s = ds;
2889 DisplayState *get_displaystate(void)
2891 return display_state;
2894 /* dumb display */
2896 static void dumb_display_init(void)
2898 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2899 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2900 register_displaystate(ds);
2903 /***********************************************************/
2904 /* I/O handling */
2906 #define MAX_IO_HANDLERS 64
2908 typedef struct IOHandlerRecord {
2909 int fd;
2910 IOCanRWHandler *fd_read_poll;
2911 IOHandler *fd_read;
2912 IOHandler *fd_write;
2913 int deleted;
2914 void *opaque;
2915 /* temporary data */
2916 struct pollfd *ufd;
2917 struct IOHandlerRecord *next;
2918 } IOHandlerRecord;
2920 static IOHandlerRecord *first_io_handler;
2922 /* XXX: fd_read_poll should be suppressed, but an API change is
2923 necessary in the character devices to suppress fd_can_read(). */
2924 int qemu_set_fd_handler2(int fd,
2925 IOCanRWHandler *fd_read_poll,
2926 IOHandler *fd_read,
2927 IOHandler *fd_write,
2928 void *opaque)
2930 IOHandlerRecord **pioh, *ioh;
2932 if (!fd_read && !fd_write) {
2933 pioh = &first_io_handler;
2934 for(;;) {
2935 ioh = *pioh;
2936 if (ioh == NULL)
2937 break;
2938 if (ioh->fd == fd) {
2939 ioh->deleted = 1;
2940 break;
2942 pioh = &ioh->next;
2944 } else {
2945 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2946 if (ioh->fd == fd)
2947 goto found;
2949 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2950 ioh->next = first_io_handler;
2951 first_io_handler = ioh;
2952 found:
2953 ioh->fd = fd;
2954 ioh->fd_read_poll = fd_read_poll;
2955 ioh->fd_read = fd_read;
2956 ioh->fd_write = fd_write;
2957 ioh->opaque = opaque;
2958 ioh->deleted = 0;
2960 return 0;
2963 int qemu_set_fd_handler(int fd,
2964 IOHandler *fd_read,
2965 IOHandler *fd_write,
2966 void *opaque)
2968 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2971 #ifdef _WIN32
2972 /***********************************************************/
2973 /* Polling handling */
2975 typedef struct PollingEntry {
2976 PollingFunc *func;
2977 void *opaque;
2978 struct PollingEntry *next;
2979 } PollingEntry;
2981 static PollingEntry *first_polling_entry;
2983 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2985 PollingEntry **ppe, *pe;
2986 pe = qemu_mallocz(sizeof(PollingEntry));
2987 pe->func = func;
2988 pe->opaque = opaque;
2989 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2990 *ppe = pe;
2991 return 0;
2994 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2996 PollingEntry **ppe, *pe;
2997 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2998 pe = *ppe;
2999 if (pe->func == func && pe->opaque == opaque) {
3000 *ppe = pe->next;
3001 qemu_free(pe);
3002 break;
3007 /***********************************************************/
3008 /* Wait objects support */
3009 typedef struct WaitObjects {
3010 int num;
3011 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3012 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3013 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3014 } WaitObjects;
3016 static WaitObjects wait_objects = {0};
3018 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3020 WaitObjects *w = &wait_objects;
3022 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3023 return -1;
3024 w->events[w->num] = handle;
3025 w->func[w->num] = func;
3026 w->opaque[w->num] = opaque;
3027 w->num++;
3028 return 0;
3031 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3033 int i, found;
3034 WaitObjects *w = &wait_objects;
3036 found = 0;
3037 for (i = 0; i < w->num; i++) {
3038 if (w->events[i] == handle)
3039 found = 1;
3040 if (found) {
3041 w->events[i] = w->events[i + 1];
3042 w->func[i] = w->func[i + 1];
3043 w->opaque[i] = w->opaque[i + 1];
3046 if (found)
3047 w->num--;
3049 #endif
3051 /***********************************************************/
3052 /* ram save/restore */
3054 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3056 int v;
3058 v = qemu_get_byte(f);
3059 switch(v) {
3060 case 0:
3061 if (qemu_get_buffer(f, buf, len) != len)
3062 return -EIO;
3063 break;
3064 case 1:
3065 v = qemu_get_byte(f);
3066 memset(buf, v, len);
3067 break;
3068 default:
3069 return -EINVAL;
3072 if (qemu_file_has_error(f))
3073 return -EIO;
3075 return 0;
3078 static int ram_load_v1(QEMUFile *f, void *opaque)
3080 int ret;
3081 ram_addr_t i;
3083 if (qemu_get_be32(f) != phys_ram_size)
3084 return -EINVAL;
3085 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3086 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3087 if (ret)
3088 return ret;
3090 return 0;
3093 #define BDRV_HASH_BLOCK_SIZE 1024
3094 #define IOBUF_SIZE 4096
3095 #define RAM_CBLOCK_MAGIC 0xfabe
3097 typedef struct RamDecompressState {
3098 z_stream zstream;
3099 QEMUFile *f;
3100 uint8_t buf[IOBUF_SIZE];
3101 } RamDecompressState;
3103 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3105 int ret;
3106 memset(s, 0, sizeof(*s));
3107 s->f = f;
3108 ret = inflateInit(&s->zstream);
3109 if (ret != Z_OK)
3110 return -1;
3111 return 0;
3114 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3116 int ret, clen;
3118 s->zstream.avail_out = len;
3119 s->zstream.next_out = buf;
3120 while (s->zstream.avail_out > 0) {
3121 if (s->zstream.avail_in == 0) {
3122 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3123 return -1;
3124 clen = qemu_get_be16(s->f);
3125 if (clen > IOBUF_SIZE)
3126 return -1;
3127 qemu_get_buffer(s->f, s->buf, clen);
3128 s->zstream.avail_in = clen;
3129 s->zstream.next_in = s->buf;
3131 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3132 if (ret != Z_OK && ret != Z_STREAM_END) {
3133 return -1;
3136 return 0;
3139 static void ram_decompress_close(RamDecompressState *s)
3141 inflateEnd(&s->zstream);
3144 #define RAM_SAVE_FLAG_FULL 0x01
3145 #define RAM_SAVE_FLAG_COMPRESS 0x02
3146 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3147 #define RAM_SAVE_FLAG_PAGE 0x08
3148 #define RAM_SAVE_FLAG_EOS 0x10
3150 static int is_dup_page(uint8_t *page, uint8_t ch)
3152 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3153 uint32_t *array = (uint32_t *)page;
3154 int i;
3156 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3157 if (array[i] != val)
3158 return 0;
3161 return 1;
3164 static int ram_save_block(QEMUFile *f)
3166 static ram_addr_t current_addr = 0;
3167 ram_addr_t saved_addr = current_addr;
3168 ram_addr_t addr = 0;
3169 int found = 0;
3171 while (addr < phys_ram_size) {
3172 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3173 uint8_t ch;
3175 cpu_physical_memory_reset_dirty(current_addr,
3176 current_addr + TARGET_PAGE_SIZE,
3177 MIGRATION_DIRTY_FLAG);
3179 ch = *(phys_ram_base + current_addr);
3181 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3182 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3183 qemu_put_byte(f, ch);
3184 } else {
3185 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3186 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3189 found = 1;
3190 break;
3192 addr += TARGET_PAGE_SIZE;
3193 current_addr = (saved_addr + addr) % phys_ram_size;
3196 return found;
3199 static ram_addr_t ram_save_threshold = 10;
3201 static ram_addr_t ram_save_remaining(void)
3203 ram_addr_t addr;
3204 ram_addr_t count = 0;
3206 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3207 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3208 count++;
3211 return count;
3214 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3216 ram_addr_t addr;
3218 if (stage == 1) {
3219 /* Make sure all dirty bits are set */
3220 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3221 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3222 cpu_physical_memory_set_dirty(addr);
3225 /* Enable dirty memory tracking */
3226 cpu_physical_memory_set_dirty_tracking(1);
3228 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3231 while (!qemu_file_rate_limit(f)) {
3232 int ret;
3234 ret = ram_save_block(f);
3235 if (ret == 0) /* no more blocks */
3236 break;
3239 /* try transferring iterative blocks of memory */
3241 if (stage == 3) {
3242 cpu_physical_memory_set_dirty_tracking(0);
3244 /* flush all remaining blocks regardless of rate limiting */
3245 while (ram_save_block(f) != 0);
3248 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3250 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3253 static int ram_load_dead(QEMUFile *f, void *opaque)
3255 RamDecompressState s1, *s = &s1;
3256 uint8_t buf[10];
3257 ram_addr_t i;
3259 if (ram_decompress_open(s, f) < 0)
3260 return -EINVAL;
3261 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3262 if (ram_decompress_buf(s, buf, 1) < 0) {
3263 fprintf(stderr, "Error while reading ram block header\n");
3264 goto error;
3266 if (buf[0] == 0) {
3267 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3268 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3269 goto error;
3271 } else {
3272 error:
3273 printf("Error block header\n");
3274 return -EINVAL;
3277 ram_decompress_close(s);
3279 return 0;
3282 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3284 ram_addr_t addr;
3285 int flags;
3287 if (version_id == 1)
3288 return ram_load_v1(f, opaque);
3290 if (version_id == 2) {
3291 if (qemu_get_be32(f) != phys_ram_size)
3292 return -EINVAL;
3293 return ram_load_dead(f, opaque);
3296 if (version_id != 3)
3297 return -EINVAL;
3299 do {
3300 addr = qemu_get_be64(f);
3302 flags = addr & ~TARGET_PAGE_MASK;
3303 addr &= TARGET_PAGE_MASK;
3305 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3306 if (addr != phys_ram_size)
3307 return -EINVAL;
3310 if (flags & RAM_SAVE_FLAG_FULL) {
3311 if (ram_load_dead(f, opaque) < 0)
3312 return -EINVAL;
3315 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3316 uint8_t ch = qemu_get_byte(f);
3317 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3318 } else if (flags & RAM_SAVE_FLAG_PAGE)
3319 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3320 } while (!(flags & RAM_SAVE_FLAG_EOS));
3322 return 0;
3325 void qemu_service_io(void)
3327 CPUState *env = cpu_single_env;
3328 if (env) {
3329 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3330 #ifdef USE_KQEMU
3331 if (env->kqemu_enabled) {
3332 kqemu_cpu_interrupt(env);
3334 #endif
3338 /***********************************************************/
3339 /* bottom halves (can be seen as timers which expire ASAP) */
3341 struct QEMUBH {
3342 QEMUBHFunc *cb;
3343 void *opaque;
3344 int scheduled;
3345 int idle;
3346 int deleted;
3347 QEMUBH *next;
3350 static QEMUBH *first_bh = NULL;
3352 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3354 QEMUBH *bh;
3355 bh = qemu_mallocz(sizeof(QEMUBH));
3356 bh->cb = cb;
3357 bh->opaque = opaque;
3358 bh->next = first_bh;
3359 first_bh = bh;
3360 return bh;
3363 int qemu_bh_poll(void)
3365 QEMUBH *bh, **bhp;
3366 int ret;
3368 ret = 0;
3369 for (bh = first_bh; bh; bh = bh->next) {
3370 if (!bh->deleted && bh->scheduled) {
3371 bh->scheduled = 0;
3372 if (!bh->idle)
3373 ret = 1;
3374 bh->idle = 0;
3375 bh->cb(bh->opaque);
3379 /* remove deleted bhs */
3380 bhp = &first_bh;
3381 while (*bhp) {
3382 bh = *bhp;
3383 if (bh->deleted) {
3384 *bhp = bh->next;
3385 qemu_free(bh);
3386 } else
3387 bhp = &bh->next;
3390 return ret;
3393 void qemu_bh_schedule_idle(QEMUBH *bh)
3395 if (bh->scheduled)
3396 return;
3397 bh->scheduled = 1;
3398 bh->idle = 1;
3401 void qemu_bh_schedule(QEMUBH *bh)
3403 CPUState *env = cpu_single_env;
3404 if (bh->scheduled)
3405 return;
3406 bh->scheduled = 1;
3407 bh->idle = 0;
3408 /* stop the currently executing CPU to execute the BH ASAP */
3409 if (env) {
3410 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3414 void qemu_bh_cancel(QEMUBH *bh)
3416 bh->scheduled = 0;
3419 void qemu_bh_delete(QEMUBH *bh)
3421 bh->scheduled = 0;
3422 bh->deleted = 1;
3425 static void qemu_bh_update_timeout(int *timeout)
3427 QEMUBH *bh;
3429 for (bh = first_bh; bh; bh = bh->next) {
3430 if (!bh->deleted && bh->scheduled) {
3431 if (bh->idle) {
3432 /* idle bottom halves will be polled at least
3433 * every 10ms */
3434 *timeout = MIN(10, *timeout);
3435 } else {
3436 /* non-idle bottom halves will be executed
3437 * immediately */
3438 *timeout = 0;
3439 break;
3445 /***********************************************************/
3446 /* machine registration */
3448 static QEMUMachine *first_machine = NULL;
3449 QEMUMachine *current_machine = NULL;
3451 int qemu_register_machine(QEMUMachine *m)
3453 QEMUMachine **pm;
3454 pm = &first_machine;
3455 while (*pm != NULL)
3456 pm = &(*pm)->next;
3457 m->next = NULL;
3458 *pm = m;
3459 return 0;
3462 static QEMUMachine *find_machine(const char *name)
3464 QEMUMachine *m;
3466 for(m = first_machine; m != NULL; m = m->next) {
3467 if (!strcmp(m->name, name))
3468 return m;
3470 return NULL;
3473 /***********************************************************/
3474 /* main execution loop */
3476 static void gui_update(void *opaque)
3478 uint64_t interval = GUI_REFRESH_INTERVAL;
3479 DisplayState *ds = opaque;
3480 DisplayChangeListener *dcl = ds->listeners;
3482 dpy_refresh(ds);
3484 while (dcl != NULL) {
3485 if (dcl->gui_timer_interval &&
3486 dcl->gui_timer_interval < interval)
3487 interval = dcl->gui_timer_interval;
3488 dcl = dcl->next;
3490 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3493 static void nographic_update(void *opaque)
3495 uint64_t interval = GUI_REFRESH_INTERVAL;
3497 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3500 struct vm_change_state_entry {
3501 VMChangeStateHandler *cb;
3502 void *opaque;
3503 LIST_ENTRY (vm_change_state_entry) entries;
3506 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3508 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3509 void *opaque)
3511 VMChangeStateEntry *e;
3513 e = qemu_mallocz(sizeof (*e));
3515 e->cb = cb;
3516 e->opaque = opaque;
3517 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3518 return e;
3521 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3523 LIST_REMOVE (e, entries);
3524 qemu_free (e);
3527 static void vm_state_notify(int running, int reason)
3529 VMChangeStateEntry *e;
3531 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3532 e->cb(e->opaque, running, reason);
3536 void vm_start(void)
3538 if (!vm_running) {
3539 cpu_enable_ticks();
3540 vm_running = 1;
3541 vm_state_notify(1, 0);
3542 qemu_rearm_alarm_timer(alarm_timer);
3546 void vm_stop(int reason)
3548 if (vm_running) {
3549 cpu_disable_ticks();
3550 vm_running = 0;
3551 vm_state_notify(0, reason);
3555 /* reset/shutdown handler */
3557 typedef struct QEMUResetEntry {
3558 QEMUResetHandler *func;
3559 void *opaque;
3560 struct QEMUResetEntry *next;
3561 } QEMUResetEntry;
3563 static QEMUResetEntry *first_reset_entry;
3564 static int reset_requested;
3565 static int shutdown_requested;
3566 static int powerdown_requested;
3568 int qemu_shutdown_requested(void)
3570 int r = shutdown_requested;
3571 shutdown_requested = 0;
3572 return r;
3575 int qemu_reset_requested(void)
3577 int r = reset_requested;
3578 reset_requested = 0;
3579 return r;
3582 int qemu_powerdown_requested(void)
3584 int r = powerdown_requested;
3585 powerdown_requested = 0;
3586 return r;
3589 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3591 QEMUResetEntry **pre, *re;
3593 pre = &first_reset_entry;
3594 while (*pre != NULL)
3595 pre = &(*pre)->next;
3596 re = qemu_mallocz(sizeof(QEMUResetEntry));
3597 re->func = func;
3598 re->opaque = opaque;
3599 re->next = NULL;
3600 *pre = re;
3603 void qemu_system_reset(void)
3605 QEMUResetEntry *re;
3607 /* reset all devices */
3608 for(re = first_reset_entry; re != NULL; re = re->next) {
3609 re->func(re->opaque);
3613 void qemu_system_reset_request(void)
3615 if (no_reboot) {
3616 shutdown_requested = 1;
3617 } else {
3618 reset_requested = 1;
3620 if (cpu_single_env)
3621 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3624 void qemu_system_shutdown_request(void)
3626 shutdown_requested = 1;
3627 if (cpu_single_env)
3628 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3631 void qemu_system_powerdown_request(void)
3633 powerdown_requested = 1;
3634 if (cpu_single_env)
3635 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3638 #ifdef _WIN32
3639 static void host_main_loop_wait(int *timeout)
3641 int ret, ret2, i;
3642 PollingEntry *pe;
3645 /* XXX: need to suppress polling by better using win32 events */
3646 ret = 0;
3647 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3648 ret |= pe->func(pe->opaque);
3650 if (ret == 0) {
3651 int err;
3652 WaitObjects *w = &wait_objects;
3654 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3655 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3656 if (w->func[ret - WAIT_OBJECT_0])
3657 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3659 /* Check for additional signaled events */
3660 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3662 /* Check if event is signaled */
3663 ret2 = WaitForSingleObject(w->events[i], 0);
3664 if(ret2 == WAIT_OBJECT_0) {
3665 if (w->func[i])
3666 w->func[i](w->opaque[i]);
3667 } else if (ret2 == WAIT_TIMEOUT) {
3668 } else {
3669 err = GetLastError();
3670 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3673 } else if (ret == WAIT_TIMEOUT) {
3674 } else {
3675 err = GetLastError();
3676 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3680 *timeout = 0;
3682 #else
3683 static void host_main_loop_wait(int *timeout)
3686 #endif
3688 void main_loop_wait(int timeout)
3690 IOHandlerRecord *ioh;
3691 fd_set rfds, wfds, xfds;
3692 int ret, nfds;
3693 struct timeval tv;
3695 qemu_bh_update_timeout(&timeout);
3697 host_main_loop_wait(&timeout);
3699 /* poll any events */
3700 /* XXX: separate device handlers from system ones */
3701 nfds = -1;
3702 FD_ZERO(&rfds);
3703 FD_ZERO(&wfds);
3704 FD_ZERO(&xfds);
3705 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3706 if (ioh->deleted)
3707 continue;
3708 if (ioh->fd_read &&
3709 (!ioh->fd_read_poll ||
3710 ioh->fd_read_poll(ioh->opaque) != 0)) {
3711 FD_SET(ioh->fd, &rfds);
3712 if (ioh->fd > nfds)
3713 nfds = ioh->fd;
3715 if (ioh->fd_write) {
3716 FD_SET(ioh->fd, &wfds);
3717 if (ioh->fd > nfds)
3718 nfds = ioh->fd;
3722 tv.tv_sec = timeout / 1000;
3723 tv.tv_usec = (timeout % 1000) * 1000;
3725 #if defined(CONFIG_SLIRP)
3726 if (slirp_is_inited()) {
3727 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3729 #endif
3730 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3731 if (ret > 0) {
3732 IOHandlerRecord **pioh;
3734 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3735 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3736 ioh->fd_read(ioh->opaque);
3738 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3739 ioh->fd_write(ioh->opaque);
3743 /* remove deleted IO handlers */
3744 pioh = &first_io_handler;
3745 while (*pioh) {
3746 ioh = *pioh;
3747 if (ioh->deleted) {
3748 *pioh = ioh->next;
3749 qemu_free(ioh);
3750 } else
3751 pioh = &ioh->next;
3754 #if defined(CONFIG_SLIRP)
3755 if (slirp_is_inited()) {
3756 if (ret < 0) {
3757 FD_ZERO(&rfds);
3758 FD_ZERO(&wfds);
3759 FD_ZERO(&xfds);
3761 slirp_select_poll(&rfds, &wfds, &xfds);
3763 #endif
3765 /* vm time timers */
3766 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3767 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3768 qemu_get_clock(vm_clock));
3770 /* real time timers */
3771 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3772 qemu_get_clock(rt_clock));
3774 /* Check bottom-halves last in case any of the earlier events triggered
3775 them. */
3776 qemu_bh_poll();
3780 static int main_loop(void)
3782 int ret, timeout;
3783 #ifdef CONFIG_PROFILER
3784 int64_t ti;
3785 #endif
3786 CPUState *env;
3788 cur_cpu = first_cpu;
3789 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3790 for(;;) {
3791 if (vm_running) {
3793 for(;;) {
3794 /* get next cpu */
3795 env = next_cpu;
3796 #ifdef CONFIG_PROFILER
3797 ti = profile_getclock();
3798 #endif
3799 if (use_icount) {
3800 int64_t count;
3801 int decr;
3802 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3803 env->icount_decr.u16.low = 0;
3804 env->icount_extra = 0;
3805 count = qemu_next_deadline();
3806 count = (count + (1 << icount_time_shift) - 1)
3807 >> icount_time_shift;
3808 qemu_icount += count;
3809 decr = (count > 0xffff) ? 0xffff : count;
3810 count -= decr;
3811 env->icount_decr.u16.low = decr;
3812 env->icount_extra = count;
3814 ret = cpu_exec(env);
3815 #ifdef CONFIG_PROFILER
3816 qemu_time += profile_getclock() - ti;
3817 #endif
3818 if (use_icount) {
3819 /* Fold pending instructions back into the
3820 instruction counter, and clear the interrupt flag. */
3821 qemu_icount -= (env->icount_decr.u16.low
3822 + env->icount_extra);
3823 env->icount_decr.u32 = 0;
3824 env->icount_extra = 0;
3826 next_cpu = env->next_cpu ?: first_cpu;
3827 if (event_pending && likely(ret != EXCP_DEBUG)) {
3828 ret = EXCP_INTERRUPT;
3829 event_pending = 0;
3830 break;
3832 if (ret == EXCP_HLT) {
3833 /* Give the next CPU a chance to run. */
3834 cur_cpu = env;
3835 continue;
3837 if (ret != EXCP_HALTED)
3838 break;
3839 /* all CPUs are halted ? */
3840 if (env == cur_cpu)
3841 break;
3843 cur_cpu = env;
3845 if (shutdown_requested) {
3846 ret = EXCP_INTERRUPT;
3847 if (no_shutdown) {
3848 vm_stop(0);
3849 no_shutdown = 0;
3851 else
3852 break;
3854 if (reset_requested) {
3855 reset_requested = 0;
3856 qemu_system_reset();
3857 ret = EXCP_INTERRUPT;
3859 if (powerdown_requested) {
3860 powerdown_requested = 0;
3861 qemu_system_powerdown();
3862 ret = EXCP_INTERRUPT;
3864 if (unlikely(ret == EXCP_DEBUG)) {
3865 gdb_set_stop_cpu(cur_cpu);
3866 vm_stop(EXCP_DEBUG);
3868 /* If all cpus are halted then wait until the next IRQ */
3869 /* XXX: use timeout computed from timers */
3870 if (ret == EXCP_HALTED) {
3871 if (use_icount) {
3872 int64_t add;
3873 int64_t delta;
3874 /* Advance virtual time to the next event. */
3875 if (use_icount == 1) {
3876 /* When not using an adaptive execution frequency
3877 we tend to get badly out of sync with real time,
3878 so just delay for a reasonable amount of time. */
3879 delta = 0;
3880 } else {
3881 delta = cpu_get_icount() - cpu_get_clock();
3883 if (delta > 0) {
3884 /* If virtual time is ahead of real time then just
3885 wait for IO. */
3886 timeout = (delta / 1000000) + 1;
3887 } else {
3888 /* Wait for either IO to occur or the next
3889 timer event. */
3890 add = qemu_next_deadline();
3891 /* We advance the timer before checking for IO.
3892 Limit the amount we advance so that early IO
3893 activity won't get the guest too far ahead. */
3894 if (add > 10000000)
3895 add = 10000000;
3896 delta += add;
3897 add = (add + (1 << icount_time_shift) - 1)
3898 >> icount_time_shift;
3899 qemu_icount += add;
3900 timeout = delta / 1000000;
3901 if (timeout < 0)
3902 timeout = 0;
3904 } else {
3905 timeout = 5000;
3907 } else {
3908 timeout = 0;
3910 } else {
3911 if (shutdown_requested) {
3912 ret = EXCP_INTERRUPT;
3913 break;
3915 timeout = 5000;
3917 #ifdef CONFIG_PROFILER
3918 ti = profile_getclock();
3919 #endif
3920 main_loop_wait(timeout);
3921 #ifdef CONFIG_PROFILER
3922 dev_time += profile_getclock() - ti;
3923 #endif
3925 cpu_disable_ticks();
3926 return ret;
3929 static void help(int exitcode)
3931 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3932 and qemu-doc.texi */
3933 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3934 "usage: %s [options] [disk_image]\n"
3935 "\n"
3936 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3937 "\n"
3938 "Standard options:\n"
3939 "-h or -help display this help and exit\n"
3940 "-M machine select emulated machine (-M ? for list)\n"
3941 "-cpu cpu select CPU (-cpu ? for list)\n"
3942 "-smp n set the number of CPUs to 'n' [default=1]\n"
3943 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3944 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3945 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3946 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3947 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3948 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3949 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3950 " use 'file' as a drive image\n"
3951 "-mtdblock file use 'file' as on-board Flash memory image\n"
3952 "-sd file use 'file' as SecureDigital card image\n"
3953 "-pflash file use 'file' as a parallel flash image\n"
3954 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3955 "-snapshot write to temporary files instead of disk image files\n"
3956 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3957 #ifndef _WIN32
3958 "-k language use keyboard layout (for example \"fr\" for French)\n"
3959 #endif
3960 #ifdef HAS_AUDIO
3961 "-audio-help print list of audio drivers and their options\n"
3962 "-soundhw c1,... enable audio support\n"
3963 " and only specified sound cards (comma separated list)\n"
3964 " use -soundhw ? to get the list of supported cards\n"
3965 " use -soundhw all to enable all of them\n"
3966 #endif
3967 "-usb enable the USB driver (will be the default soon)\n"
3968 "-usbdevice name add the host or guest USB device 'name'\n"
3969 "-name string set the name of the guest\n"
3970 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3971 " specify machine UUID\n"
3972 "\n"
3973 "Display options:\n"
3974 "-nographic disable graphical output and redirect serial I/Os to console\n"
3975 #ifdef CONFIG_CURSES
3976 "-curses use a curses/ncurses interface instead of SDL\n"
3977 #endif
3978 #ifdef CONFIG_SDL
3979 "-no-frame open SDL window without a frame and window decorations\n"
3980 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3981 "-no-quit disable SDL window close capability\n"
3982 "-sdl enable SDL\n"
3983 #endif
3984 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3985 "-vga [std|cirrus|vmware|none]\n"
3986 " select video card type\n"
3987 "-full-screen start in full screen\n"
3988 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3989 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3990 #endif
3991 "-vnc display start a VNC server on display\n"
3992 "\n"
3993 "Network options:\n"
3994 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3995 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3996 #ifdef CONFIG_SLIRP
3997 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3998 " connect the user mode network stack to VLAN 'n' and send\n"
3999 " hostname 'host' to DHCP clients\n"
4000 #endif
4001 #ifdef _WIN32
4002 "-net tap[,vlan=n][,name=str],ifname=name\n"
4003 " connect the host TAP network interface to VLAN 'n'\n"
4004 #else
4005 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4006 " connect the host TAP network interface to VLAN 'n' and use the\n"
4007 " network scripts 'file' (default=%s)\n"
4008 " and 'dfile' (default=%s);\n"
4009 " use '[down]script=no' to disable script execution;\n"
4010 " use 'fd=h' to connect to an already opened TAP interface\n"
4011 #endif
4012 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4013 " connect the vlan 'n' to another VLAN using a socket connection\n"
4014 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4015 " connect the vlan 'n' to multicast maddr and port\n"
4016 #ifdef CONFIG_VDE
4017 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4018 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4019 " on host and listening for incoming connections on 'socketpath'.\n"
4020 " Use group 'groupname' and mode 'octalmode' to change default\n"
4021 " ownership and permissions for communication port.\n"
4022 #endif
4023 "-net none use it alone to have zero network devices; if no -net option\n"
4024 " is provided, the default is '-net nic -net user'\n"
4025 #ifdef CONFIG_SLIRP
4026 "-tftp dir allow tftp access to files in dir [-net user]\n"
4027 "-bootp file advertise file in BOOTP replies\n"
4028 #ifndef _WIN32
4029 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4030 #endif
4031 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4032 " redirect TCP or UDP connections from host to guest [-net user]\n"
4033 #endif
4034 "\n"
4035 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4036 "-bt hci,host[:id]\n"
4037 " use host's HCI with the given name\n"
4038 "-bt hci[,vlan=n]\n"
4039 " emulate a standard HCI in virtual scatternet 'n'\n"
4040 "-bt vhci[,vlan=n]\n"
4041 " add host computer to virtual scatternet 'n' using VHCI\n"
4042 "-bt device:dev[,vlan=n]\n"
4043 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4044 "\n"
4045 #ifdef TARGET_I386
4046 "\n"
4047 "i386 target only:\n"
4048 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4049 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4050 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4051 "-no-acpi disable ACPI\n"
4052 "-no-hpet disable HPET\n"
4053 "-acpitable [sig=str][,rev=n][,oem_id=str][,oem_table_id=str][,oem_rev=n][,asl_compiler_id=str][,asl_compiler_rev=n][,data=file1[:file2]...]\n"
4054 " ACPI table description\n"
4055 #endif
4056 "Linux boot specific:\n"
4057 "-kernel bzImage use 'bzImage' as kernel image\n"
4058 "-append cmdline use 'cmdline' as kernel command line\n"
4059 "-initrd file use 'file' as initial ram disk\n"
4060 "\n"
4061 "Debug/Expert options:\n"
4062 "-serial dev redirect the serial port to char device 'dev'\n"
4063 "-parallel dev redirect the parallel port to char device 'dev'\n"
4064 "-monitor dev redirect the monitor to char device 'dev'\n"
4065 "-pidfile file write PID to 'file'\n"
4066 "-S freeze CPU at startup (use 'c' to start execution)\n"
4067 "-s wait gdb connection to port\n"
4068 "-p port set gdb connection port [default=%s]\n"
4069 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4070 "-hdachs c,h,s[,t]\n"
4071 " force hard disk 0 physical geometry and the optional BIOS\n"
4072 " translation (t=none or lba) (usually qemu can guess them)\n"
4073 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4074 "-bios file set the filename for the BIOS\n"
4075 #ifdef USE_KQEMU
4076 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4077 "-no-kqemu disable KQEMU kernel module usage\n"
4078 #endif
4079 #ifdef CONFIG_KVM
4080 "-enable-kvm enable KVM full virtualization support\n"
4081 #endif
4082 "-no-reboot exit instead of rebooting\n"
4083 "-no-shutdown stop before shutdown\n"
4084 "-loadvm [tag|id]\n"
4085 " start right away with a saved state (loadvm in monitor)\n"
4086 #ifndef _WIN32
4087 "-daemonize daemonize QEMU after initializing\n"
4088 #endif
4089 "-option-rom rom load a file, rom, into the option ROM space\n"
4090 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4091 "-prom-env variable=value\n"
4092 " set OpenBIOS nvram variables\n"
4093 #endif
4094 "-clock force the use of the given methods for timer alarm.\n"
4095 " To see what timers are available use -clock ?\n"
4096 "-localtime set the real time clock to local time [default=utc]\n"
4097 "-startdate select initial date of the clock\n"
4098 "-icount [N|auto]\n"
4099 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4100 "-echr chr set terminal escape character instead of ctrl-a\n"
4101 "-virtioconsole c\n"
4102 " set virtio console\n"
4103 "-show-cursor show cursor\n"
4104 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4105 "-semihosting semihosting mode\n"
4106 #endif
4107 #if defined(TARGET_ARM)
4108 "-old-param old param mode\n"
4109 #endif
4110 "-tb-size n set TB size\n"
4111 "-incoming p prepare for incoming migration, listen on port p\n"
4112 #ifndef _WIN32
4113 "-chroot dir Chroot to dir just before starting the VM.\n"
4114 "-runas user Change to user id user just before starting the VM.\n"
4115 #endif
4116 "\n"
4117 "During emulation, the following keys are useful:\n"
4118 "ctrl-alt-f toggle full screen\n"
4119 "ctrl-alt-n switch to virtual console 'n'\n"
4120 "ctrl-alt toggle mouse and keyboard grab\n"
4121 "\n"
4122 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4124 "qemu",
4125 DEFAULT_RAM_SIZE,
4126 #ifndef _WIN32
4127 DEFAULT_NETWORK_SCRIPT,
4128 DEFAULT_NETWORK_DOWN_SCRIPT,
4129 #endif
4130 DEFAULT_GDBSTUB_PORT,
4131 "/tmp/qemu.log");
4132 exit(exitcode);
4135 #define HAS_ARG 0x0001
4137 enum {
4138 /* Please keep in synch with help, qemu_options[] and
4139 qemu-doc.texi */
4140 /* Standard options: */
4141 QEMU_OPTION_h,
4142 QEMU_OPTION_M,
4143 QEMU_OPTION_cpu,
4144 QEMU_OPTION_smp,
4145 QEMU_OPTION_fda,
4146 QEMU_OPTION_fdb,
4147 QEMU_OPTION_hda,
4148 QEMU_OPTION_hdb,
4149 QEMU_OPTION_hdc,
4150 QEMU_OPTION_hdd,
4151 QEMU_OPTION_cdrom,
4152 QEMU_OPTION_drive,
4153 QEMU_OPTION_mtdblock,
4154 QEMU_OPTION_sd,
4155 QEMU_OPTION_pflash,
4156 QEMU_OPTION_boot,
4157 QEMU_OPTION_snapshot,
4158 QEMU_OPTION_m,
4159 QEMU_OPTION_k,
4160 QEMU_OPTION_audio_help,
4161 QEMU_OPTION_soundhw,
4162 QEMU_OPTION_usb,
4163 QEMU_OPTION_usbdevice,
4164 QEMU_OPTION_name,
4165 QEMU_OPTION_uuid,
4167 /* Display options: */
4168 QEMU_OPTION_nographic,
4169 QEMU_OPTION_curses,
4170 QEMU_OPTION_no_frame,
4171 QEMU_OPTION_alt_grab,
4172 QEMU_OPTION_no_quit,
4173 QEMU_OPTION_sdl,
4174 QEMU_OPTION_portrait,
4175 QEMU_OPTION_vga,
4176 QEMU_OPTION_full_screen,
4177 QEMU_OPTION_g,
4178 QEMU_OPTION_vnc,
4180 /* Network options: */
4181 QEMU_OPTION_net,
4182 QEMU_OPTION_tftp,
4183 QEMU_OPTION_bootp,
4184 QEMU_OPTION_smb,
4185 QEMU_OPTION_redir,
4186 QEMU_OPTION_bt,
4188 /* i386 target only: */
4189 QEMU_OPTION_win2k_hack,
4190 QEMU_OPTION_rtc_td_hack,
4191 QEMU_OPTION_no_fd_bootchk,
4192 QEMU_OPTION_no_acpi,
4193 QEMU_OPTION_no_hpet,
4194 QEMU_OPTION_acpitable,
4196 /* Linux boot specific: */
4197 QEMU_OPTION_kernel,
4198 QEMU_OPTION_append,
4199 QEMU_OPTION_initrd,
4201 /* Debug/Expert options: */
4202 QEMU_OPTION_serial,
4203 QEMU_OPTION_parallel,
4204 QEMU_OPTION_monitor,
4205 QEMU_OPTION_pidfile,
4206 QEMU_OPTION_S,
4207 QEMU_OPTION_s,
4208 QEMU_OPTION_p,
4209 QEMU_OPTION_d,
4210 QEMU_OPTION_hdachs,
4211 QEMU_OPTION_L,
4212 QEMU_OPTION_bios,
4213 QEMU_OPTION_kernel_kqemu,
4214 QEMU_OPTION_no_kqemu,
4215 QEMU_OPTION_enable_kvm,
4216 QEMU_OPTION_no_reboot,
4217 QEMU_OPTION_no_shutdown,
4218 QEMU_OPTION_loadvm,
4219 QEMU_OPTION_daemonize,
4220 QEMU_OPTION_option_rom,
4221 QEMU_OPTION_prom_env,
4222 QEMU_OPTION_clock,
4223 QEMU_OPTION_localtime,
4224 QEMU_OPTION_startdate,
4225 QEMU_OPTION_icount,
4226 QEMU_OPTION_echr,
4227 QEMU_OPTION_virtiocon,
4228 QEMU_OPTION_show_cursor,
4229 QEMU_OPTION_semihosting,
4230 QEMU_OPTION_old_param,
4231 QEMU_OPTION_tb_size,
4232 QEMU_OPTION_incoming,
4233 QEMU_OPTION_chroot,
4234 QEMU_OPTION_runas,
4237 typedef struct QEMUOption {
4238 const char *name;
4239 int flags;
4240 int index;
4241 } QEMUOption;
4243 static const QEMUOption qemu_options[] = {
4244 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4245 qemu-doc.texi */
4246 /* Standard options: */
4247 { "h", 0, QEMU_OPTION_h },
4248 { "help", 0, QEMU_OPTION_h },
4249 { "M", HAS_ARG, QEMU_OPTION_M },
4250 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4251 { "smp", HAS_ARG, QEMU_OPTION_smp },
4252 { "fda", HAS_ARG, QEMU_OPTION_fda },
4253 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4254 { "hda", HAS_ARG, QEMU_OPTION_hda },
4255 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4256 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4257 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4258 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4259 { "drive", HAS_ARG, QEMU_OPTION_drive },
4260 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4261 { "sd", HAS_ARG, QEMU_OPTION_sd },
4262 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4263 { "boot", HAS_ARG, QEMU_OPTION_boot },
4264 { "snapshot", 0, QEMU_OPTION_snapshot },
4265 { "m", HAS_ARG, QEMU_OPTION_m },
4266 #ifndef _WIN32
4267 { "k", HAS_ARG, QEMU_OPTION_k },
4268 #endif
4269 #ifdef HAS_AUDIO
4270 { "audio-help", 0, QEMU_OPTION_audio_help },
4271 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4272 #endif
4273 { "usb", 0, QEMU_OPTION_usb },
4274 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4275 { "name", HAS_ARG, QEMU_OPTION_name },
4276 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4278 /* Display options: */
4279 { "nographic", 0, QEMU_OPTION_nographic },
4280 #ifdef CONFIG_CURSES
4281 { "curses", 0, QEMU_OPTION_curses },
4282 #endif
4283 #ifdef CONFIG_SDL
4284 { "no-frame", 0, QEMU_OPTION_no_frame },
4285 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4286 { "no-quit", 0, QEMU_OPTION_no_quit },
4287 { "sdl", 0, QEMU_OPTION_sdl },
4288 #endif
4289 { "portrait", 0, QEMU_OPTION_portrait },
4290 { "vga", HAS_ARG, QEMU_OPTION_vga },
4291 { "full-screen", 0, QEMU_OPTION_full_screen },
4292 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4293 { "g", 1, QEMU_OPTION_g },
4294 #endif
4295 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4297 /* Network options: */
4298 { "net", HAS_ARG, QEMU_OPTION_net},
4299 #ifdef CONFIG_SLIRP
4300 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4301 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4302 #ifndef _WIN32
4303 { "smb", HAS_ARG, QEMU_OPTION_smb },
4304 #endif
4305 { "redir", HAS_ARG, QEMU_OPTION_redir },
4306 #endif
4307 { "bt", HAS_ARG, QEMU_OPTION_bt },
4308 #ifdef TARGET_I386
4309 /* i386 target only: */
4310 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4311 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4312 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4313 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4314 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4315 { "acpitable", HAS_ARG, QEMU_OPTION_acpitable },
4316 #endif
4318 /* Linux boot specific: */
4319 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4320 { "append", HAS_ARG, QEMU_OPTION_append },
4321 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4323 /* Debug/Expert options: */
4324 { "serial", HAS_ARG, QEMU_OPTION_serial },
4325 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4326 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4327 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4328 { "S", 0, QEMU_OPTION_S },
4329 { "s", 0, QEMU_OPTION_s },
4330 { "p", HAS_ARG, QEMU_OPTION_p },
4331 { "d", HAS_ARG, QEMU_OPTION_d },
4332 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4333 { "L", HAS_ARG, QEMU_OPTION_L },
4334 { "bios", HAS_ARG, QEMU_OPTION_bios },
4335 #ifdef USE_KQEMU
4336 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4337 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4338 #endif
4339 #ifdef CONFIG_KVM
4340 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4341 #endif
4342 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4343 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4344 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4345 { "daemonize", 0, QEMU_OPTION_daemonize },
4346 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4347 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4348 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4349 #endif
4350 { "clock", HAS_ARG, QEMU_OPTION_clock },
4351 { "localtime", 0, QEMU_OPTION_localtime },
4352 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4353 { "icount", HAS_ARG, QEMU_OPTION_icount },
4354 { "echr", HAS_ARG, QEMU_OPTION_echr },
4355 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4356 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4357 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4358 { "semihosting", 0, QEMU_OPTION_semihosting },
4359 #endif
4360 #if defined(TARGET_ARM)
4361 { "old-param", 0, QEMU_OPTION_old_param },
4362 #endif
4363 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4364 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4365 { "chroot", HAS_ARG, QEMU_OPTION_chroot },
4366 { "runas", HAS_ARG, QEMU_OPTION_runas },
4367 { NULL },
4370 #ifdef HAS_AUDIO
4371 struct soundhw soundhw[] = {
4372 #ifdef HAS_AUDIO_CHOICE
4373 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4375 "pcspk",
4376 "PC speaker",
4379 { .init_isa = pcspk_audio_init }
4381 #endif
4383 #ifdef CONFIG_SB16
4385 "sb16",
4386 "Creative Sound Blaster 16",
4389 { .init_isa = SB16_init }
4391 #endif
4393 #ifdef CONFIG_CS4231A
4395 "cs4231a",
4396 "CS4231A",
4399 { .init_isa = cs4231a_init }
4401 #endif
4403 #ifdef CONFIG_ADLIB
4405 "adlib",
4406 #ifdef HAS_YMF262
4407 "Yamaha YMF262 (OPL3)",
4408 #else
4409 "Yamaha YM3812 (OPL2)",
4410 #endif
4413 { .init_isa = Adlib_init }
4415 #endif
4417 #ifdef CONFIG_GUS
4419 "gus",
4420 "Gravis Ultrasound GF1",
4423 { .init_isa = GUS_init }
4425 #endif
4427 #ifdef CONFIG_AC97
4429 "ac97",
4430 "Intel 82801AA AC97 Audio",
4433 { .init_pci = ac97_init }
4435 #endif
4437 #ifdef CONFIG_ES1370
4439 "es1370",
4440 "ENSONIQ AudioPCI ES1370",
4443 { .init_pci = es1370_init }
4445 #endif
4447 #endif /* HAS_AUDIO_CHOICE */
4449 { NULL, NULL, 0, 0, { NULL } }
4452 static void select_soundhw (const char *optarg)
4454 struct soundhw *c;
4456 if (*optarg == '?') {
4457 show_valid_cards:
4459 printf ("Valid sound card names (comma separated):\n");
4460 for (c = soundhw; c->name; ++c) {
4461 printf ("%-11s %s\n", c->name, c->descr);
4463 printf ("\n-soundhw all will enable all of the above\n");
4464 exit (*optarg != '?');
4466 else {
4467 size_t l;
4468 const char *p;
4469 char *e;
4470 int bad_card = 0;
4472 if (!strcmp (optarg, "all")) {
4473 for (c = soundhw; c->name; ++c) {
4474 c->enabled = 1;
4476 return;
4479 p = optarg;
4480 while (*p) {
4481 e = strchr (p, ',');
4482 l = !e ? strlen (p) : (size_t) (e - p);
4484 for (c = soundhw; c->name; ++c) {
4485 if (!strncmp (c->name, p, l)) {
4486 c->enabled = 1;
4487 break;
4491 if (!c->name) {
4492 if (l > 80) {
4493 fprintf (stderr,
4494 "Unknown sound card name (too big to show)\n");
4496 else {
4497 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4498 (int) l, p);
4500 bad_card = 1;
4502 p += l + (e != NULL);
4505 if (bad_card)
4506 goto show_valid_cards;
4509 #endif
4511 static void select_vgahw (const char *p)
4513 const char *opts;
4515 if (strstart(p, "std", &opts)) {
4516 std_vga_enabled = 1;
4517 cirrus_vga_enabled = 0;
4518 vmsvga_enabled = 0;
4519 } else if (strstart(p, "cirrus", &opts)) {
4520 cirrus_vga_enabled = 1;
4521 std_vga_enabled = 0;
4522 vmsvga_enabled = 0;
4523 } else if (strstart(p, "vmware", &opts)) {
4524 cirrus_vga_enabled = 0;
4525 std_vga_enabled = 0;
4526 vmsvga_enabled = 1;
4527 } else if (strstart(p, "none", &opts)) {
4528 cirrus_vga_enabled = 0;
4529 std_vga_enabled = 0;
4530 vmsvga_enabled = 0;
4531 } else {
4532 invalid_vga:
4533 fprintf(stderr, "Unknown vga type: %s\n", p);
4534 exit(1);
4536 while (*opts) {
4537 const char *nextopt;
4539 if (strstart(opts, ",retrace=", &nextopt)) {
4540 opts = nextopt;
4541 if (strstart(opts, "dumb", &nextopt))
4542 vga_retrace_method = VGA_RETRACE_DUMB;
4543 else if (strstart(opts, "precise", &nextopt))
4544 vga_retrace_method = VGA_RETRACE_PRECISE;
4545 else goto invalid_vga;
4546 } else goto invalid_vga;
4547 opts = nextopt;
4551 #ifdef _WIN32
4552 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4554 exit(STATUS_CONTROL_C_EXIT);
4555 return TRUE;
4557 #endif
4559 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4561 int ret;
4563 if(strlen(str) != 36)
4564 return -1;
4566 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4567 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4568 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4570 if(ret != 16)
4571 return -1;
4573 return 0;
4576 #define MAX_NET_CLIENTS 32
4578 #ifndef _WIN32
4580 static void termsig_handler(int signal)
4582 qemu_system_shutdown_request();
4585 static void termsig_setup(void)
4587 struct sigaction act;
4589 memset(&act, 0, sizeof(act));
4590 act.sa_handler = termsig_handler;
4591 sigaction(SIGINT, &act, NULL);
4592 sigaction(SIGHUP, &act, NULL);
4593 sigaction(SIGTERM, &act, NULL);
4596 #endif
4598 int main(int argc, char **argv, char **envp)
4600 #ifdef CONFIG_GDBSTUB
4601 int use_gdbstub;
4602 const char *gdbstub_port;
4603 #endif
4604 uint32_t boot_devices_bitmap = 0;
4605 int i;
4606 int snapshot, linux_boot, net_boot;
4607 const char *initrd_filename;
4608 const char *kernel_filename, *kernel_cmdline;
4609 const char *boot_devices = "";
4610 DisplayState *ds;
4611 DisplayChangeListener *dcl;
4612 int cyls, heads, secs, translation;
4613 const char *net_clients[MAX_NET_CLIENTS];
4614 int nb_net_clients;
4615 const char *bt_opts[MAX_BT_CMDLINE];
4616 int nb_bt_opts;
4617 int hda_index;
4618 int optind;
4619 const char *r, *optarg;
4620 CharDriverState *monitor_hd = NULL;
4621 const char *monitor_device;
4622 const char *serial_devices[MAX_SERIAL_PORTS];
4623 int serial_device_index;
4624 const char *parallel_devices[MAX_PARALLEL_PORTS];
4625 int parallel_device_index;
4626 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4627 int virtio_console_index;
4628 const char *loadvm = NULL;
4629 QEMUMachine *machine;
4630 const char *cpu_model;
4631 const char *usb_devices[MAX_USB_CMDLINE];
4632 int usb_devices_index;
4633 int fds[2];
4634 int tb_size;
4635 const char *pid_file = NULL;
4636 const char *incoming = NULL;
4637 int fd = 0;
4638 struct passwd *pwd = NULL;
4639 const char *chroot_dir = NULL;
4640 const char *run_as = NULL;
4642 qemu_cache_utils_init(envp);
4644 LIST_INIT (&vm_change_state_head);
4645 #ifndef _WIN32
4647 struct sigaction act;
4648 sigfillset(&act.sa_mask);
4649 act.sa_flags = 0;
4650 act.sa_handler = SIG_IGN;
4651 sigaction(SIGPIPE, &act, NULL);
4653 #else
4654 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4655 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4656 QEMU to run on a single CPU */
4658 HANDLE h;
4659 DWORD mask, smask;
4660 int i;
4661 h = GetCurrentProcess();
4662 if (GetProcessAffinityMask(h, &mask, &smask)) {
4663 for(i = 0; i < 32; i++) {
4664 if (mask & (1 << i))
4665 break;
4667 if (i != 32) {
4668 mask = 1 << i;
4669 SetProcessAffinityMask(h, mask);
4673 #endif
4675 register_machines();
4676 machine = first_machine;
4677 cpu_model = NULL;
4678 initrd_filename = NULL;
4679 ram_size = 0;
4680 vga_ram_size = VGA_RAM_SIZE;
4681 #ifdef CONFIG_GDBSTUB
4682 use_gdbstub = 0;
4683 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4684 #endif
4685 snapshot = 0;
4686 nographic = 0;
4687 curses = 0;
4688 kernel_filename = NULL;
4689 kernel_cmdline = "";
4690 cyls = heads = secs = 0;
4691 translation = BIOS_ATA_TRANSLATION_AUTO;
4692 monitor_device = "vc:80Cx24C";
4694 serial_devices[0] = "vc:80Cx24C";
4695 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4696 serial_devices[i] = NULL;
4697 serial_device_index = 0;
4699 parallel_devices[0] = "vc:80Cx24C";
4700 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4701 parallel_devices[i] = NULL;
4702 parallel_device_index = 0;
4704 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4705 virtio_consoles[i] = NULL;
4706 virtio_console_index = 0;
4708 usb_devices_index = 0;
4710 nb_net_clients = 0;
4711 nb_bt_opts = 0;
4712 nb_drives = 0;
4713 nb_drives_opt = 0;
4714 hda_index = -1;
4716 nb_nics = 0;
4718 tb_size = 0;
4719 autostart= 1;
4721 optind = 1;
4722 for(;;) {
4723 if (optind >= argc)
4724 break;
4725 r = argv[optind];
4726 if (r[0] != '-') {
4727 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4728 } else {
4729 const QEMUOption *popt;
4731 optind++;
4732 /* Treat --foo the same as -foo. */
4733 if (r[1] == '-')
4734 r++;
4735 popt = qemu_options;
4736 for(;;) {
4737 if (!popt->name) {
4738 fprintf(stderr, "%s: invalid option -- '%s'\n",
4739 argv[0], r);
4740 exit(1);
4742 if (!strcmp(popt->name, r + 1))
4743 break;
4744 popt++;
4746 if (popt->flags & HAS_ARG) {
4747 if (optind >= argc) {
4748 fprintf(stderr, "%s: option '%s' requires an argument\n",
4749 argv[0], r);
4750 exit(1);
4752 optarg = argv[optind++];
4753 } else {
4754 optarg = NULL;
4757 switch(popt->index) {
4758 case QEMU_OPTION_M:
4759 machine = find_machine(optarg);
4760 if (!machine) {
4761 QEMUMachine *m;
4762 printf("Supported machines are:\n");
4763 for(m = first_machine; m != NULL; m = m->next) {
4764 printf("%-10s %s%s\n",
4765 m->name, m->desc,
4766 m == first_machine ? " (default)" : "");
4768 exit(*optarg != '?');
4770 break;
4771 case QEMU_OPTION_cpu:
4772 /* hw initialization will check this */
4773 if (*optarg == '?') {
4774 /* XXX: implement xxx_cpu_list for targets that still miss it */
4775 #if defined(cpu_list)
4776 cpu_list(stdout, &fprintf);
4777 #endif
4778 exit(0);
4779 } else {
4780 cpu_model = optarg;
4782 break;
4783 case QEMU_OPTION_initrd:
4784 initrd_filename = optarg;
4785 break;
4786 case QEMU_OPTION_hda:
4787 if (cyls == 0)
4788 hda_index = drive_add(optarg, HD_ALIAS, 0);
4789 else
4790 hda_index = drive_add(optarg, HD_ALIAS
4791 ",cyls=%d,heads=%d,secs=%d%s",
4792 0, cyls, heads, secs,
4793 translation == BIOS_ATA_TRANSLATION_LBA ?
4794 ",trans=lba" :
4795 translation == BIOS_ATA_TRANSLATION_NONE ?
4796 ",trans=none" : "");
4797 break;
4798 case QEMU_OPTION_hdb:
4799 case QEMU_OPTION_hdc:
4800 case QEMU_OPTION_hdd:
4801 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4802 break;
4803 case QEMU_OPTION_drive:
4804 drive_add(NULL, "%s", optarg);
4805 break;
4806 case QEMU_OPTION_mtdblock:
4807 drive_add(optarg, MTD_ALIAS);
4808 break;
4809 case QEMU_OPTION_sd:
4810 drive_add(optarg, SD_ALIAS);
4811 break;
4812 case QEMU_OPTION_pflash:
4813 drive_add(optarg, PFLASH_ALIAS);
4814 break;
4815 case QEMU_OPTION_snapshot:
4816 snapshot = 1;
4817 break;
4818 case QEMU_OPTION_hdachs:
4820 const char *p;
4821 p = optarg;
4822 cyls = strtol(p, (char **)&p, 0);
4823 if (cyls < 1 || cyls > 16383)
4824 goto chs_fail;
4825 if (*p != ',')
4826 goto chs_fail;
4827 p++;
4828 heads = strtol(p, (char **)&p, 0);
4829 if (heads < 1 || heads > 16)
4830 goto chs_fail;
4831 if (*p != ',')
4832 goto chs_fail;
4833 p++;
4834 secs = strtol(p, (char **)&p, 0);
4835 if (secs < 1 || secs > 63)
4836 goto chs_fail;
4837 if (*p == ',') {
4838 p++;
4839 if (!strcmp(p, "none"))
4840 translation = BIOS_ATA_TRANSLATION_NONE;
4841 else if (!strcmp(p, "lba"))
4842 translation = BIOS_ATA_TRANSLATION_LBA;
4843 else if (!strcmp(p, "auto"))
4844 translation = BIOS_ATA_TRANSLATION_AUTO;
4845 else
4846 goto chs_fail;
4847 } else if (*p != '\0') {
4848 chs_fail:
4849 fprintf(stderr, "qemu: invalid physical CHS format\n");
4850 exit(1);
4852 if (hda_index != -1)
4853 snprintf(drives_opt[hda_index].opt,
4854 sizeof(drives_opt[hda_index].opt),
4855 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4856 0, cyls, heads, secs,
4857 translation == BIOS_ATA_TRANSLATION_LBA ?
4858 ",trans=lba" :
4859 translation == BIOS_ATA_TRANSLATION_NONE ?
4860 ",trans=none" : "");
4862 break;
4863 case QEMU_OPTION_nographic:
4864 nographic = 1;
4865 break;
4866 #ifdef CONFIG_CURSES
4867 case QEMU_OPTION_curses:
4868 curses = 1;
4869 break;
4870 #endif
4871 case QEMU_OPTION_portrait:
4872 graphic_rotate = 1;
4873 break;
4874 case QEMU_OPTION_kernel:
4875 kernel_filename = optarg;
4876 break;
4877 case QEMU_OPTION_append:
4878 kernel_cmdline = optarg;
4879 break;
4880 case QEMU_OPTION_cdrom:
4881 drive_add(optarg, CDROM_ALIAS);
4882 break;
4883 case QEMU_OPTION_boot:
4884 boot_devices = optarg;
4885 /* We just do some generic consistency checks */
4887 /* Could easily be extended to 64 devices if needed */
4888 const char *p;
4890 boot_devices_bitmap = 0;
4891 for (p = boot_devices; *p != '\0'; p++) {
4892 /* Allowed boot devices are:
4893 * a b : floppy disk drives
4894 * c ... f : IDE disk drives
4895 * g ... m : machine implementation dependant drives
4896 * n ... p : network devices
4897 * It's up to each machine implementation to check
4898 * if the given boot devices match the actual hardware
4899 * implementation and firmware features.
4901 if (*p < 'a' || *p > 'q') {
4902 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4903 exit(1);
4905 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4906 fprintf(stderr,
4907 "Boot device '%c' was given twice\n",*p);
4908 exit(1);
4910 boot_devices_bitmap |= 1 << (*p - 'a');
4913 break;
4914 case QEMU_OPTION_fda:
4915 case QEMU_OPTION_fdb:
4916 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4917 break;
4918 #ifdef TARGET_I386
4919 case QEMU_OPTION_no_fd_bootchk:
4920 fd_bootchk = 0;
4921 break;
4922 #endif
4923 case QEMU_OPTION_net:
4924 if (nb_net_clients >= MAX_NET_CLIENTS) {
4925 fprintf(stderr, "qemu: too many network clients\n");
4926 exit(1);
4928 net_clients[nb_net_clients] = optarg;
4929 nb_net_clients++;
4930 break;
4931 #ifdef CONFIG_SLIRP
4932 case QEMU_OPTION_tftp:
4933 tftp_prefix = optarg;
4934 break;
4935 case QEMU_OPTION_bootp:
4936 bootp_filename = optarg;
4937 break;
4938 #ifndef _WIN32
4939 case QEMU_OPTION_smb:
4940 net_slirp_smb(optarg);
4941 break;
4942 #endif
4943 case QEMU_OPTION_redir:
4944 net_slirp_redir(optarg);
4945 break;
4946 #endif
4947 case QEMU_OPTION_bt:
4948 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4949 fprintf(stderr, "qemu: too many bluetooth options\n");
4950 exit(1);
4952 bt_opts[nb_bt_opts++] = optarg;
4953 break;
4954 #ifdef HAS_AUDIO
4955 case QEMU_OPTION_audio_help:
4956 AUD_help ();
4957 exit (0);
4958 break;
4959 case QEMU_OPTION_soundhw:
4960 select_soundhw (optarg);
4961 break;
4962 #endif
4963 case QEMU_OPTION_h:
4964 help(0);
4965 break;
4966 case QEMU_OPTION_m: {
4967 uint64_t value;
4968 char *ptr;
4970 value = strtoul(optarg, &ptr, 10);
4971 switch (*ptr) {
4972 case 0: case 'M': case 'm':
4973 value <<= 20;
4974 break;
4975 case 'G': case 'g':
4976 value <<= 30;
4977 break;
4978 default:
4979 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4980 exit(1);
4983 /* On 32-bit hosts, QEMU is limited by virtual address space */
4984 if (value > (2047 << 20)
4985 #ifndef USE_KQEMU
4986 && HOST_LONG_BITS == 32
4987 #endif
4989 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4990 exit(1);
4992 if (value != (uint64_t)(ram_addr_t)value) {
4993 fprintf(stderr, "qemu: ram size too large\n");
4994 exit(1);
4996 ram_size = value;
4997 break;
4999 case QEMU_OPTION_d:
5001 int mask;
5002 const CPULogItem *item;
5004 mask = cpu_str_to_log_mask(optarg);
5005 if (!mask) {
5006 printf("Log items (comma separated):\n");
5007 for(item = cpu_log_items; item->mask != 0; item++) {
5008 printf("%-10s %s\n", item->name, item->help);
5010 exit(1);
5012 cpu_set_log(mask);
5014 break;
5015 #ifdef CONFIG_GDBSTUB
5016 case QEMU_OPTION_s:
5017 use_gdbstub = 1;
5018 break;
5019 case QEMU_OPTION_p:
5020 gdbstub_port = optarg;
5021 break;
5022 #endif
5023 case QEMU_OPTION_L:
5024 bios_dir = optarg;
5025 break;
5026 case QEMU_OPTION_bios:
5027 bios_name = optarg;
5028 break;
5029 case QEMU_OPTION_S:
5030 autostart = 0;
5031 break;
5032 case QEMU_OPTION_k:
5033 keyboard_layout = optarg;
5034 break;
5035 case QEMU_OPTION_localtime:
5036 rtc_utc = 0;
5037 break;
5038 case QEMU_OPTION_vga:
5039 select_vgahw (optarg);
5040 break;
5041 case QEMU_OPTION_g:
5043 const char *p;
5044 int w, h, depth;
5045 p = optarg;
5046 w = strtol(p, (char **)&p, 10);
5047 if (w <= 0) {
5048 graphic_error:
5049 fprintf(stderr, "qemu: invalid resolution or depth\n");
5050 exit(1);
5052 if (*p != 'x')
5053 goto graphic_error;
5054 p++;
5055 h = strtol(p, (char **)&p, 10);
5056 if (h <= 0)
5057 goto graphic_error;
5058 if (*p == 'x') {
5059 p++;
5060 depth = strtol(p, (char **)&p, 10);
5061 if (depth != 8 && depth != 15 && depth != 16 &&
5062 depth != 24 && depth != 32)
5063 goto graphic_error;
5064 } else if (*p == '\0') {
5065 depth = graphic_depth;
5066 } else {
5067 goto graphic_error;
5070 graphic_width = w;
5071 graphic_height = h;
5072 graphic_depth = depth;
5074 break;
5075 case QEMU_OPTION_echr:
5077 char *r;
5078 term_escape_char = strtol(optarg, &r, 0);
5079 if (r == optarg)
5080 printf("Bad argument to echr\n");
5081 break;
5083 case QEMU_OPTION_monitor:
5084 monitor_device = optarg;
5085 break;
5086 case QEMU_OPTION_serial:
5087 if (serial_device_index >= MAX_SERIAL_PORTS) {
5088 fprintf(stderr, "qemu: too many serial ports\n");
5089 exit(1);
5091 serial_devices[serial_device_index] = optarg;
5092 serial_device_index++;
5093 break;
5094 case QEMU_OPTION_virtiocon:
5095 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5096 fprintf(stderr, "qemu: too many virtio consoles\n");
5097 exit(1);
5099 virtio_consoles[virtio_console_index] = optarg;
5100 virtio_console_index++;
5101 break;
5102 case QEMU_OPTION_parallel:
5103 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5104 fprintf(stderr, "qemu: too many parallel ports\n");
5105 exit(1);
5107 parallel_devices[parallel_device_index] = optarg;
5108 parallel_device_index++;
5109 break;
5110 case QEMU_OPTION_loadvm:
5111 loadvm = optarg;
5112 break;
5113 case QEMU_OPTION_full_screen:
5114 full_screen = 1;
5115 break;
5116 #ifdef CONFIG_SDL
5117 case QEMU_OPTION_no_frame:
5118 no_frame = 1;
5119 break;
5120 case QEMU_OPTION_alt_grab:
5121 alt_grab = 1;
5122 break;
5123 case QEMU_OPTION_no_quit:
5124 no_quit = 1;
5125 break;
5126 case QEMU_OPTION_sdl:
5127 sdl = 1;
5128 break;
5129 #endif
5130 case QEMU_OPTION_pidfile:
5131 pid_file = optarg;
5132 break;
5133 #ifdef TARGET_I386
5134 case QEMU_OPTION_win2k_hack:
5135 win2k_install_hack = 1;
5136 break;
5137 case QEMU_OPTION_rtc_td_hack:
5138 rtc_td_hack = 1;
5139 break;
5140 case QEMU_OPTION_acpitable:
5141 if(acpi_table_add(optarg) < 0) {
5142 fprintf(stderr, "Wrong acpi table provided\n");
5143 exit(1);
5145 break;
5146 #endif
5147 #ifdef USE_KQEMU
5148 case QEMU_OPTION_no_kqemu:
5149 kqemu_allowed = 0;
5150 break;
5151 case QEMU_OPTION_kernel_kqemu:
5152 kqemu_allowed = 2;
5153 break;
5154 #endif
5155 #ifdef CONFIG_KVM
5156 case QEMU_OPTION_enable_kvm:
5157 kvm_allowed = 1;
5158 #ifdef USE_KQEMU
5159 kqemu_allowed = 0;
5160 #endif
5161 break;
5162 #endif
5163 case QEMU_OPTION_usb:
5164 usb_enabled = 1;
5165 break;
5166 case QEMU_OPTION_usbdevice:
5167 usb_enabled = 1;
5168 if (usb_devices_index >= MAX_USB_CMDLINE) {
5169 fprintf(stderr, "Too many USB devices\n");
5170 exit(1);
5172 usb_devices[usb_devices_index] = optarg;
5173 usb_devices_index++;
5174 break;
5175 case QEMU_OPTION_smp:
5176 smp_cpus = atoi(optarg);
5177 if (smp_cpus < 1) {
5178 fprintf(stderr, "Invalid number of CPUs\n");
5179 exit(1);
5181 break;
5182 case QEMU_OPTION_vnc:
5183 vnc_display = optarg;
5184 break;
5185 case QEMU_OPTION_no_acpi:
5186 acpi_enabled = 0;
5187 break;
5188 case QEMU_OPTION_no_hpet:
5189 no_hpet = 1;
5190 break;
5191 case QEMU_OPTION_no_reboot:
5192 no_reboot = 1;
5193 break;
5194 case QEMU_OPTION_no_shutdown:
5195 no_shutdown = 1;
5196 break;
5197 case QEMU_OPTION_show_cursor:
5198 cursor_hide = 0;
5199 break;
5200 case QEMU_OPTION_uuid:
5201 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5202 fprintf(stderr, "Fail to parse UUID string."
5203 " Wrong format.\n");
5204 exit(1);
5206 break;
5207 case QEMU_OPTION_daemonize:
5208 daemonize = 1;
5209 break;
5210 case QEMU_OPTION_option_rom:
5211 if (nb_option_roms >= MAX_OPTION_ROMS) {
5212 fprintf(stderr, "Too many option ROMs\n");
5213 exit(1);
5215 option_rom[nb_option_roms] = optarg;
5216 nb_option_roms++;
5217 break;
5218 case QEMU_OPTION_semihosting:
5219 semihosting_enabled = 1;
5220 break;
5221 case QEMU_OPTION_name:
5222 qemu_name = optarg;
5223 break;
5224 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5225 case QEMU_OPTION_prom_env:
5226 if (nb_prom_envs >= MAX_PROM_ENVS) {
5227 fprintf(stderr, "Too many prom variables\n");
5228 exit(1);
5230 prom_envs[nb_prom_envs] = optarg;
5231 nb_prom_envs++;
5232 break;
5233 #endif
5234 #ifdef TARGET_ARM
5235 case QEMU_OPTION_old_param:
5236 old_param = 1;
5237 break;
5238 #endif
5239 case QEMU_OPTION_clock:
5240 configure_alarms(optarg);
5241 break;
5242 case QEMU_OPTION_startdate:
5244 struct tm tm;
5245 time_t rtc_start_date;
5246 if (!strcmp(optarg, "now")) {
5247 rtc_date_offset = -1;
5248 } else {
5249 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5250 &tm.tm_year,
5251 &tm.tm_mon,
5252 &tm.tm_mday,
5253 &tm.tm_hour,
5254 &tm.tm_min,
5255 &tm.tm_sec) == 6) {
5256 /* OK */
5257 } else if (sscanf(optarg, "%d-%d-%d",
5258 &tm.tm_year,
5259 &tm.tm_mon,
5260 &tm.tm_mday) == 3) {
5261 tm.tm_hour = 0;
5262 tm.tm_min = 0;
5263 tm.tm_sec = 0;
5264 } else {
5265 goto date_fail;
5267 tm.tm_year -= 1900;
5268 tm.tm_mon--;
5269 rtc_start_date = mktimegm(&tm);
5270 if (rtc_start_date == -1) {
5271 date_fail:
5272 fprintf(stderr, "Invalid date format. Valid format are:\n"
5273 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5274 exit(1);
5276 rtc_date_offset = time(NULL) - rtc_start_date;
5279 break;
5280 case QEMU_OPTION_tb_size:
5281 tb_size = strtol(optarg, NULL, 0);
5282 if (tb_size < 0)
5283 tb_size = 0;
5284 break;
5285 case QEMU_OPTION_icount:
5286 use_icount = 1;
5287 if (strcmp(optarg, "auto") == 0) {
5288 icount_time_shift = -1;
5289 } else {
5290 icount_time_shift = strtol(optarg, NULL, 0);
5292 break;
5293 case QEMU_OPTION_incoming:
5294 incoming = optarg;
5295 break;
5296 case QEMU_OPTION_chroot:
5297 chroot_dir = optarg;
5298 break;
5299 case QEMU_OPTION_runas:
5300 run_as = optarg;
5301 break;
5306 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5307 if (kvm_allowed && kqemu_allowed) {
5308 fprintf(stderr,
5309 "You can not enable both KVM and kqemu at the same time\n");
5310 exit(1);
5312 #endif
5314 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5315 if (smp_cpus > machine->max_cpus) {
5316 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5317 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5318 machine->max_cpus);
5319 exit(1);
5322 if (nographic) {
5323 if (serial_device_index == 0)
5324 serial_devices[0] = "stdio";
5325 if (parallel_device_index == 0)
5326 parallel_devices[0] = "null";
5327 if (strncmp(monitor_device, "vc", 2) == 0)
5328 monitor_device = "stdio";
5331 #ifndef _WIN32
5332 if (daemonize) {
5333 pid_t pid;
5335 if (pipe(fds) == -1)
5336 exit(1);
5338 pid = fork();
5339 if (pid > 0) {
5340 uint8_t status;
5341 ssize_t len;
5343 close(fds[1]);
5345 again:
5346 len = read(fds[0], &status, 1);
5347 if (len == -1 && (errno == EINTR))
5348 goto again;
5350 if (len != 1)
5351 exit(1);
5352 else if (status == 1) {
5353 fprintf(stderr, "Could not acquire pidfile\n");
5354 exit(1);
5355 } else
5356 exit(0);
5357 } else if (pid < 0)
5358 exit(1);
5360 setsid();
5362 pid = fork();
5363 if (pid > 0)
5364 exit(0);
5365 else if (pid < 0)
5366 exit(1);
5368 umask(027);
5370 signal(SIGTSTP, SIG_IGN);
5371 signal(SIGTTOU, SIG_IGN);
5372 signal(SIGTTIN, SIG_IGN);
5374 #endif
5376 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5377 if (daemonize) {
5378 uint8_t status = 1;
5379 write(fds[1], &status, 1);
5380 } else
5381 fprintf(stderr, "Could not acquire pid file\n");
5382 exit(1);
5385 #ifdef USE_KQEMU
5386 if (smp_cpus > 1)
5387 kqemu_allowed = 0;
5388 #endif
5389 linux_boot = (kernel_filename != NULL);
5390 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5392 if (!linux_boot && net_boot == 0 &&
5393 !machine->nodisk_ok && nb_drives_opt == 0)
5394 help(1);
5396 if (!linux_boot && *kernel_cmdline != '\0') {
5397 fprintf(stderr, "-append only allowed with -kernel option\n");
5398 exit(1);
5401 if (!linux_boot && initrd_filename != NULL) {
5402 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5403 exit(1);
5406 /* boot to floppy or the default cd if no hard disk defined yet */
5407 if (!boot_devices[0]) {
5408 boot_devices = "cad";
5410 setvbuf(stdout, NULL, _IOLBF, 0);
5412 init_timers();
5413 if (init_timer_alarm() < 0) {
5414 fprintf(stderr, "could not initialize alarm timer\n");
5415 exit(1);
5417 if (use_icount && icount_time_shift < 0) {
5418 use_icount = 2;
5419 /* 125MIPS seems a reasonable initial guess at the guest speed.
5420 It will be corrected fairly quickly anyway. */
5421 icount_time_shift = 3;
5422 init_icount_adjust();
5425 #ifdef _WIN32
5426 socket_init();
5427 #endif
5429 /* init network clients */
5430 if (nb_net_clients == 0) {
5431 /* if no clients, we use a default config */
5432 net_clients[nb_net_clients++] = "nic";
5433 #ifdef CONFIG_SLIRP
5434 net_clients[nb_net_clients++] = "user";
5435 #endif
5438 for(i = 0;i < nb_net_clients; i++) {
5439 if (net_client_parse(net_clients[i]) < 0)
5440 exit(1);
5442 net_client_check();
5444 #ifdef TARGET_I386
5445 /* XXX: this should be moved in the PC machine instantiation code */
5446 if (net_boot != 0) {
5447 int netroms = 0;
5448 for (i = 0; i < nb_nics && i < 4; i++) {
5449 const char *model = nd_table[i].model;
5450 char buf[1024];
5451 if (net_boot & (1 << i)) {
5452 if (model == NULL)
5453 model = "ne2k_pci";
5454 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5455 if (get_image_size(buf) > 0) {
5456 if (nb_option_roms >= MAX_OPTION_ROMS) {
5457 fprintf(stderr, "Too many option ROMs\n");
5458 exit(1);
5460 option_rom[nb_option_roms] = strdup(buf);
5461 nb_option_roms++;
5462 netroms++;
5466 if (netroms == 0) {
5467 fprintf(stderr, "No valid PXE rom found for network device\n");
5468 exit(1);
5471 #endif
5473 /* init the bluetooth world */
5474 for (i = 0; i < nb_bt_opts; i++)
5475 if (bt_parse(bt_opts[i]))
5476 exit(1);
5478 /* init the memory */
5479 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5481 if (machine->ram_require & RAMSIZE_FIXED) {
5482 if (ram_size > 0) {
5483 if (ram_size < phys_ram_size) {
5484 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5485 machine->name, (unsigned long long) phys_ram_size);
5486 exit(-1);
5489 phys_ram_size = ram_size;
5490 } else
5491 ram_size = phys_ram_size;
5492 } else {
5493 if (ram_size == 0)
5494 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5496 phys_ram_size += ram_size;
5499 phys_ram_base = qemu_vmalloc(phys_ram_size);
5500 if (!phys_ram_base) {
5501 fprintf(stderr, "Could not allocate physical memory\n");
5502 exit(1);
5505 /* init the dynamic translator */
5506 cpu_exec_init_all(tb_size * 1024 * 1024);
5508 bdrv_init();
5510 /* we always create the cdrom drive, even if no disk is there */
5512 if (nb_drives_opt < MAX_DRIVES)
5513 drive_add(NULL, CDROM_ALIAS);
5515 /* we always create at least one floppy */
5517 if (nb_drives_opt < MAX_DRIVES)
5518 drive_add(NULL, FD_ALIAS, 0);
5520 /* we always create one sd slot, even if no card is in it */
5522 if (nb_drives_opt < MAX_DRIVES)
5523 drive_add(NULL, SD_ALIAS);
5525 /* open the virtual block devices */
5527 for(i = 0; i < nb_drives_opt; i++)
5528 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5529 exit(1);
5531 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5532 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5534 #ifndef _WIN32
5535 /* must be after terminal init, SDL library changes signal handlers */
5536 termsig_setup();
5537 #endif
5539 /* Maintain compatibility with multiple stdio monitors */
5540 if (!strcmp(monitor_device,"stdio")) {
5541 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5542 const char *devname = serial_devices[i];
5543 if (devname && !strcmp(devname,"mon:stdio")) {
5544 monitor_device = NULL;
5545 break;
5546 } else if (devname && !strcmp(devname,"stdio")) {
5547 monitor_device = NULL;
5548 serial_devices[i] = "mon:stdio";
5549 break;
5554 if (kvm_enabled()) {
5555 int ret;
5557 ret = kvm_init(smp_cpus);
5558 if (ret < 0) {
5559 fprintf(stderr, "failed to initialize KVM\n");
5560 exit(1);
5564 if (monitor_device) {
5565 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5566 if (!monitor_hd) {
5567 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5568 exit(1);
5572 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5573 const char *devname = serial_devices[i];
5574 if (devname && strcmp(devname, "none")) {
5575 char label[32];
5576 snprintf(label, sizeof(label), "serial%d", i);
5577 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5578 if (!serial_hds[i]) {
5579 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5580 devname);
5581 exit(1);
5586 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5587 const char *devname = parallel_devices[i];
5588 if (devname && strcmp(devname, "none")) {
5589 char label[32];
5590 snprintf(label, sizeof(label), "parallel%d", i);
5591 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5592 if (!parallel_hds[i]) {
5593 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5594 devname);
5595 exit(1);
5600 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5601 const char *devname = virtio_consoles[i];
5602 if (devname && strcmp(devname, "none")) {
5603 char label[32];
5604 snprintf(label, sizeof(label), "virtcon%d", i);
5605 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5606 if (!virtcon_hds[i]) {
5607 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5608 devname);
5609 exit(1);
5614 machine->init(ram_size, vga_ram_size, boot_devices,
5615 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5617 current_machine = machine;
5619 /* Set KVM's vcpu state to qemu's initial CPUState. */
5620 if (kvm_enabled()) {
5621 int ret;
5623 ret = kvm_sync_vcpus();
5624 if (ret < 0) {
5625 fprintf(stderr, "failed to initialize vcpus\n");
5626 exit(1);
5630 /* init USB devices */
5631 if (usb_enabled) {
5632 for(i = 0; i < usb_devices_index; i++) {
5633 if (usb_device_add(usb_devices[i], 0) < 0) {
5634 fprintf(stderr, "Warning: could not add USB device %s\n",
5635 usb_devices[i]);
5640 if (!display_state)
5641 dumb_display_init();
5642 /* just use the first displaystate for the moment */
5643 ds = display_state;
5644 /* terminal init */
5645 if (nographic) {
5646 if (curses) {
5647 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5648 exit(1);
5650 } else {
5651 #if defined(CONFIG_CURSES)
5652 if (curses) {
5653 /* At the moment curses cannot be used with other displays */
5654 curses_display_init(ds, full_screen);
5655 } else
5656 #endif
5658 if (vnc_display != NULL) {
5659 vnc_display_init(ds);
5660 if (vnc_display_open(ds, vnc_display) < 0)
5661 exit(1);
5663 #if defined(CONFIG_SDL)
5664 if (sdl || !vnc_display)
5665 sdl_display_init(ds, full_screen, no_frame);
5666 #elif defined(CONFIG_COCOA)
5667 if (sdl || !vnc_display)
5668 cocoa_display_init(ds, full_screen);
5669 #endif
5672 dpy_resize(ds);
5674 dcl = ds->listeners;
5675 while (dcl != NULL) {
5676 if (dcl->dpy_refresh != NULL) {
5677 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5678 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5680 dcl = dcl->next;
5683 if (nographic || (vnc_display && !sdl)) {
5684 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5685 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5688 text_consoles_set_display(display_state);
5689 qemu_chr_initial_reset();
5691 if (monitor_device && monitor_hd)
5692 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5694 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5695 const char *devname = serial_devices[i];
5696 if (devname && strcmp(devname, "none")) {
5697 char label[32];
5698 snprintf(label, sizeof(label), "serial%d", i);
5699 if (strstart(devname, "vc", 0))
5700 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5704 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5705 const char *devname = parallel_devices[i];
5706 if (devname && strcmp(devname, "none")) {
5707 char label[32];
5708 snprintf(label, sizeof(label), "parallel%d", i);
5709 if (strstart(devname, "vc", 0))
5710 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5714 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5715 const char *devname = virtio_consoles[i];
5716 if (virtcon_hds[i] && devname) {
5717 char label[32];
5718 snprintf(label, sizeof(label), "virtcon%d", i);
5719 if (strstart(devname, "vc", 0))
5720 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5724 #ifdef CONFIG_GDBSTUB
5725 if (use_gdbstub) {
5726 /* XXX: use standard host:port notation and modify options
5727 accordingly. */
5728 if (gdbserver_start(gdbstub_port) < 0) {
5729 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5730 gdbstub_port);
5731 exit(1);
5734 #endif
5736 if (loadvm)
5737 do_loadvm(cur_mon, loadvm);
5739 if (incoming) {
5740 autostart = 0; /* fixme how to deal with -daemonize */
5741 qemu_start_incoming_migration(incoming);
5744 if (autostart)
5745 vm_start();
5747 if (daemonize) {
5748 uint8_t status = 0;
5749 ssize_t len;
5751 again1:
5752 len = write(fds[1], &status, 1);
5753 if (len == -1 && (errno == EINTR))
5754 goto again1;
5756 if (len != 1)
5757 exit(1);
5759 chdir("/");
5760 TFR(fd = open("/dev/null", O_RDWR));
5761 if (fd == -1)
5762 exit(1);
5765 #ifndef _WIN32
5766 if (run_as) {
5767 pwd = getpwnam(run_as);
5768 if (!pwd) {
5769 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5770 exit(1);
5774 if (chroot_dir) {
5775 if (chroot(chroot_dir) < 0) {
5776 fprintf(stderr, "chroot failed\n");
5777 exit(1);
5779 chdir("/");
5782 if (run_as) {
5783 if (setgid(pwd->pw_gid) < 0) {
5784 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5785 exit(1);
5787 if (setuid(pwd->pw_uid) < 0) {
5788 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5789 exit(1);
5791 if (setuid(0) != -1) {
5792 fprintf(stderr, "Dropping privileges failed\n");
5793 exit(1);
5796 #endif
5798 if (daemonize) {
5799 dup2(fd, 0);
5800 dup2(fd, 1);
5801 dup2(fd, 2);
5803 close(fd);
5806 main_loop();
5807 quit_timers();
5808 net_cleanup();
5810 return 0;