clean build: Fix remaining m68k warnings
[qemu/mini2440/sniper_sniper_test.git] / vl.c
blobc15f9ac09902bbcc6beab0f84ca20af24f4b9df3
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_exit(cpu_single_env);
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_exit(env);
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 #define CDROM_ALIAS "index=2,media=cdrom"
2143 #define FD_ALIAS "index=%d,if=floppy"
2144 #define PFLASH_ALIAS "if=pflash"
2145 #define MTD_ALIAS "if=mtd"
2146 #define SD_ALIAS "index=0,if=sd"
2148 static int drive_opt_get_free_idx(void)
2150 int index;
2152 for (index = 0; index < MAX_DRIVES; index++)
2153 if (!drives_opt[index].used) {
2154 drives_opt[index].used = 1;
2155 return index;
2158 return -1;
2161 static int drive_get_free_idx(void)
2163 int index;
2165 for (index = 0; index < MAX_DRIVES; index++)
2166 if (!drives_table[index].used) {
2167 drives_table[index].used = 1;
2168 return index;
2171 return -1;
2174 int drive_add(const char *file, const char *fmt, ...)
2176 va_list ap;
2177 int index = drive_opt_get_free_idx();
2179 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2180 fprintf(stderr, "qemu: too many drives\n");
2181 return -1;
2184 drives_opt[index].file = file;
2185 va_start(ap, fmt);
2186 vsnprintf(drives_opt[index].opt,
2187 sizeof(drives_opt[0].opt), fmt, ap);
2188 va_end(ap);
2190 nb_drives_opt++;
2191 return index;
2194 void drive_remove(int index)
2196 drives_opt[index].used = 0;
2197 nb_drives_opt--;
2200 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2202 int index;
2204 /* seek interface, bus and unit */
2206 for (index = 0; index < MAX_DRIVES; index++)
2207 if (drives_table[index].type == type &&
2208 drives_table[index].bus == bus &&
2209 drives_table[index].unit == unit &&
2210 drives_table[index].used)
2211 return index;
2213 return -1;
2216 int drive_get_max_bus(BlockInterfaceType type)
2218 int max_bus;
2219 int index;
2221 max_bus = -1;
2222 for (index = 0; index < nb_drives; index++) {
2223 if(drives_table[index].type == type &&
2224 drives_table[index].bus > max_bus)
2225 max_bus = drives_table[index].bus;
2227 return max_bus;
2230 const char *drive_get_serial(BlockDriverState *bdrv)
2232 int index;
2234 for (index = 0; index < nb_drives; index++)
2235 if (drives_table[index].bdrv == bdrv)
2236 return drives_table[index].serial;
2238 return "\0";
2241 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2243 int index;
2245 for (index = 0; index < nb_drives; index++)
2246 if (drives_table[index].bdrv == bdrv)
2247 return drives_table[index].onerror;
2249 return BLOCK_ERR_STOP_ENOSPC;
2252 static void bdrv_format_print(void *opaque, const char *name)
2254 fprintf(stderr, " %s", name);
2257 void drive_uninit(BlockDriverState *bdrv)
2259 int i;
2261 for (i = 0; i < MAX_DRIVES; i++)
2262 if (drives_table[i].bdrv == bdrv) {
2263 drives_table[i].bdrv = NULL;
2264 drives_table[i].used = 0;
2265 drive_remove(drives_table[i].drive_opt_idx);
2266 nb_drives--;
2267 break;
2271 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2273 char buf[128];
2274 char file[1024];
2275 char devname[128];
2276 char serial[21];
2277 const char *mediastr = "";
2278 BlockInterfaceType type;
2279 enum { MEDIA_DISK, MEDIA_CDROM } media;
2280 int bus_id, unit_id;
2281 int cyls, heads, secs, translation;
2282 BlockDriverState *bdrv;
2283 BlockDriver *drv = NULL;
2284 QEMUMachine *machine = opaque;
2285 int max_devs;
2286 int index;
2287 int cache;
2288 int bdrv_flags, onerror;
2289 int drives_table_idx;
2290 char *str = arg->opt;
2291 static const char * const params[] = { "bus", "unit", "if", "index",
2292 "cyls", "heads", "secs", "trans",
2293 "media", "snapshot", "file",
2294 "cache", "format", "serial", "werror",
2295 NULL };
2297 if (check_params(buf, sizeof(buf), params, str) < 0) {
2298 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2299 buf, str);
2300 return -1;
2303 file[0] = 0;
2304 cyls = heads = secs = 0;
2305 bus_id = 0;
2306 unit_id = -1;
2307 translation = BIOS_ATA_TRANSLATION_AUTO;
2308 index = -1;
2309 cache = 3;
2311 if (machine->use_scsi) {
2312 type = IF_SCSI;
2313 max_devs = MAX_SCSI_DEVS;
2314 pstrcpy(devname, sizeof(devname), "scsi");
2315 } else {
2316 type = IF_IDE;
2317 max_devs = MAX_IDE_DEVS;
2318 pstrcpy(devname, sizeof(devname), "ide");
2320 media = MEDIA_DISK;
2322 /* extract parameters */
2324 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2325 bus_id = strtol(buf, NULL, 0);
2326 if (bus_id < 0) {
2327 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2328 return -1;
2332 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2333 unit_id = strtol(buf, NULL, 0);
2334 if (unit_id < 0) {
2335 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2336 return -1;
2340 if (get_param_value(buf, sizeof(buf), "if", str)) {
2341 pstrcpy(devname, sizeof(devname), buf);
2342 if (!strcmp(buf, "ide")) {
2343 type = IF_IDE;
2344 max_devs = MAX_IDE_DEVS;
2345 } else if (!strcmp(buf, "scsi")) {
2346 type = IF_SCSI;
2347 max_devs = MAX_SCSI_DEVS;
2348 } else if (!strcmp(buf, "floppy")) {
2349 type = IF_FLOPPY;
2350 max_devs = 0;
2351 } else if (!strcmp(buf, "pflash")) {
2352 type = IF_PFLASH;
2353 max_devs = 0;
2354 } else if (!strcmp(buf, "mtd")) {
2355 type = IF_MTD;
2356 max_devs = 0;
2357 } else if (!strcmp(buf, "sd")) {
2358 type = IF_SD;
2359 max_devs = 0;
2360 } else if (!strcmp(buf, "virtio")) {
2361 type = IF_VIRTIO;
2362 max_devs = 0;
2363 } else {
2364 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2365 return -1;
2369 if (get_param_value(buf, sizeof(buf), "index", str)) {
2370 index = strtol(buf, NULL, 0);
2371 if (index < 0) {
2372 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2373 return -1;
2377 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2378 cyls = strtol(buf, NULL, 0);
2381 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2382 heads = strtol(buf, NULL, 0);
2385 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2386 secs = strtol(buf, NULL, 0);
2389 if (cyls || heads || secs) {
2390 if (cyls < 1 || cyls > 16383) {
2391 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2392 return -1;
2394 if (heads < 1 || heads > 16) {
2395 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2396 return -1;
2398 if (secs < 1 || secs > 63) {
2399 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2400 return -1;
2404 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2405 if (!cyls) {
2406 fprintf(stderr,
2407 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2408 str);
2409 return -1;
2411 if (!strcmp(buf, "none"))
2412 translation = BIOS_ATA_TRANSLATION_NONE;
2413 else if (!strcmp(buf, "lba"))
2414 translation = BIOS_ATA_TRANSLATION_LBA;
2415 else if (!strcmp(buf, "auto"))
2416 translation = BIOS_ATA_TRANSLATION_AUTO;
2417 else {
2418 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2419 return -1;
2423 if (get_param_value(buf, sizeof(buf), "media", str)) {
2424 if (!strcmp(buf, "disk")) {
2425 media = MEDIA_DISK;
2426 } else if (!strcmp(buf, "cdrom")) {
2427 if (cyls || secs || heads) {
2428 fprintf(stderr,
2429 "qemu: '%s' invalid physical CHS format\n", str);
2430 return -1;
2432 media = MEDIA_CDROM;
2433 } else {
2434 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2435 return -1;
2439 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2440 if (!strcmp(buf, "on"))
2441 snapshot = 1;
2442 else if (!strcmp(buf, "off"))
2443 snapshot = 0;
2444 else {
2445 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2446 return -1;
2450 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2451 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2452 cache = 0;
2453 else if (!strcmp(buf, "writethrough"))
2454 cache = 1;
2455 else if (!strcmp(buf, "writeback"))
2456 cache = 2;
2457 else {
2458 fprintf(stderr, "qemu: invalid cache option\n");
2459 return -1;
2463 if (get_param_value(buf, sizeof(buf), "format", str)) {
2464 if (strcmp(buf, "?") == 0) {
2465 fprintf(stderr, "qemu: Supported formats:");
2466 bdrv_iterate_format(bdrv_format_print, NULL);
2467 fprintf(stderr, "\n");
2468 return -1;
2470 drv = bdrv_find_format(buf);
2471 if (!drv) {
2472 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2473 return -1;
2477 if (arg->file == NULL)
2478 get_param_value(file, sizeof(file), "file", str);
2479 else
2480 pstrcpy(file, sizeof(file), arg->file);
2482 if (!get_param_value(serial, sizeof(serial), "serial", str))
2483 memset(serial, 0, sizeof(serial));
2485 onerror = BLOCK_ERR_STOP_ENOSPC;
2486 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2487 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2488 fprintf(stderr, "werror is no supported by this format\n");
2489 return -1;
2491 if (!strcmp(buf, "ignore"))
2492 onerror = BLOCK_ERR_IGNORE;
2493 else if (!strcmp(buf, "enospc"))
2494 onerror = BLOCK_ERR_STOP_ENOSPC;
2495 else if (!strcmp(buf, "stop"))
2496 onerror = BLOCK_ERR_STOP_ANY;
2497 else if (!strcmp(buf, "report"))
2498 onerror = BLOCK_ERR_REPORT;
2499 else {
2500 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2501 return -1;
2505 /* compute bus and unit according index */
2507 if (index != -1) {
2508 if (bus_id != 0 || unit_id != -1) {
2509 fprintf(stderr,
2510 "qemu: '%s' index cannot be used with bus and unit\n", str);
2511 return -1;
2513 if (max_devs == 0)
2515 unit_id = index;
2516 bus_id = 0;
2517 } else {
2518 unit_id = index % max_devs;
2519 bus_id = index / max_devs;
2523 /* if user doesn't specify a unit_id,
2524 * try to find the first free
2527 if (unit_id == -1) {
2528 unit_id = 0;
2529 while (drive_get_index(type, bus_id, unit_id) != -1) {
2530 unit_id++;
2531 if (max_devs && unit_id >= max_devs) {
2532 unit_id -= max_devs;
2533 bus_id++;
2538 /* check unit id */
2540 if (max_devs && unit_id >= max_devs) {
2541 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2542 str, unit_id, max_devs - 1);
2543 return -1;
2547 * ignore multiple definitions
2550 if (drive_get_index(type, bus_id, unit_id) != -1)
2551 return -2;
2553 /* init */
2555 if (type == IF_IDE || type == IF_SCSI)
2556 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2557 if (max_devs)
2558 snprintf(buf, sizeof(buf), "%s%i%s%i",
2559 devname, bus_id, mediastr, unit_id);
2560 else
2561 snprintf(buf, sizeof(buf), "%s%s%i",
2562 devname, mediastr, unit_id);
2563 bdrv = bdrv_new(buf);
2564 drives_table_idx = drive_get_free_idx();
2565 drives_table[drives_table_idx].bdrv = bdrv;
2566 drives_table[drives_table_idx].type = type;
2567 drives_table[drives_table_idx].bus = bus_id;
2568 drives_table[drives_table_idx].unit = unit_id;
2569 drives_table[drives_table_idx].onerror = onerror;
2570 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2571 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2572 nb_drives++;
2574 switch(type) {
2575 case IF_IDE:
2576 case IF_SCSI:
2577 switch(media) {
2578 case MEDIA_DISK:
2579 if (cyls != 0) {
2580 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2581 bdrv_set_translation_hint(bdrv, translation);
2583 break;
2584 case MEDIA_CDROM:
2585 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2586 break;
2588 break;
2589 case IF_SD:
2590 /* FIXME: This isn't really a floppy, but it's a reasonable
2591 approximation. */
2592 case IF_FLOPPY:
2593 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2594 break;
2595 case IF_PFLASH:
2596 case IF_MTD:
2597 case IF_VIRTIO:
2598 break;
2600 if (!file[0])
2601 return -2;
2602 bdrv_flags = 0;
2603 if (snapshot) {
2604 bdrv_flags |= BDRV_O_SNAPSHOT;
2605 cache = 2; /* always use write-back with snapshot */
2607 if (cache == 0) /* no caching */
2608 bdrv_flags |= BDRV_O_NOCACHE;
2609 else if (cache == 2) /* write-back */
2610 bdrv_flags |= BDRV_O_CACHE_WB;
2611 else if (cache == 3) /* not specified */
2612 bdrv_flags |= BDRV_O_CACHE_DEF;
2613 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2614 fprintf(stderr, "qemu: could not open disk image %s\n",
2615 file);
2616 return -1;
2618 if (bdrv_key_required(bdrv))
2619 autostart = 0;
2620 return drives_table_idx;
2623 /***********************************************************/
2624 /* USB devices */
2626 static USBPort *used_usb_ports;
2627 static USBPort *free_usb_ports;
2629 /* ??? Maybe change this to register a hub to keep track of the topology. */
2630 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2631 usb_attachfn attach)
2633 port->opaque = opaque;
2634 port->index = index;
2635 port->attach = attach;
2636 port->next = free_usb_ports;
2637 free_usb_ports = port;
2640 int usb_device_add_dev(USBDevice *dev)
2642 USBPort *port;
2644 /* Find a USB port to add the device to. */
2645 port = free_usb_ports;
2646 if (!port->next) {
2647 USBDevice *hub;
2649 /* Create a new hub and chain it on. */
2650 free_usb_ports = NULL;
2651 port->next = used_usb_ports;
2652 used_usb_ports = port;
2654 hub = usb_hub_init(VM_USB_HUB_SIZE);
2655 usb_attach(port, hub);
2656 port = free_usb_ports;
2659 free_usb_ports = port->next;
2660 port->next = used_usb_ports;
2661 used_usb_ports = port;
2662 usb_attach(port, dev);
2663 return 0;
2666 static void usb_msd_password_cb(void *opaque, int err)
2668 USBDevice *dev = opaque;
2670 if (!err)
2671 usb_device_add_dev(dev);
2672 else
2673 dev->handle_destroy(dev);
2676 static int usb_device_add(const char *devname, int is_hotplug)
2678 const char *p;
2679 USBDevice *dev;
2681 if (!free_usb_ports)
2682 return -1;
2684 if (strstart(devname, "host:", &p)) {
2685 dev = usb_host_device_open(p);
2686 } else if (!strcmp(devname, "mouse")) {
2687 dev = usb_mouse_init();
2688 } else if (!strcmp(devname, "tablet")) {
2689 dev = usb_tablet_init();
2690 } else if (!strcmp(devname, "keyboard")) {
2691 dev = usb_keyboard_init();
2692 } else if (strstart(devname, "disk:", &p)) {
2693 BlockDriverState *bs;
2695 dev = usb_msd_init(p);
2696 if (!dev)
2697 return -1;
2698 bs = usb_msd_get_bdrv(dev);
2699 if (bdrv_key_required(bs)) {
2700 autostart = 0;
2701 if (is_hotplug) {
2702 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2703 dev);
2704 return 0;
2707 } else if (!strcmp(devname, "wacom-tablet")) {
2708 dev = usb_wacom_init();
2709 } else if (strstart(devname, "serial:", &p)) {
2710 dev = usb_serial_init(p);
2711 #ifdef CONFIG_BRLAPI
2712 } else if (!strcmp(devname, "braille")) {
2713 dev = usb_baum_init();
2714 #endif
2715 } else if (strstart(devname, "net:", &p)) {
2716 int nic = nb_nics;
2718 if (net_client_init("nic", p) < 0)
2719 return -1;
2720 nd_table[nic].model = "usb";
2721 dev = usb_net_init(&nd_table[nic]);
2722 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2723 dev = usb_bt_init(devname[2] ? hci_init(p) :
2724 bt_new_hci(qemu_find_bt_vlan(0)));
2725 } else {
2726 return -1;
2728 if (!dev)
2729 return -1;
2731 return usb_device_add_dev(dev);
2734 int usb_device_del_addr(int bus_num, int addr)
2736 USBPort *port;
2737 USBPort **lastp;
2738 USBDevice *dev;
2740 if (!used_usb_ports)
2741 return -1;
2743 if (bus_num != 0)
2744 return -1;
2746 lastp = &used_usb_ports;
2747 port = used_usb_ports;
2748 while (port && port->dev->addr != addr) {
2749 lastp = &port->next;
2750 port = port->next;
2753 if (!port)
2754 return -1;
2756 dev = port->dev;
2757 *lastp = port->next;
2758 usb_attach(port, NULL);
2759 dev->handle_destroy(dev);
2760 port->next = free_usb_ports;
2761 free_usb_ports = port;
2762 return 0;
2765 static int usb_device_del(const char *devname)
2767 int bus_num, addr;
2768 const char *p;
2770 if (strstart(devname, "host:", &p))
2771 return usb_host_device_close(p);
2773 if (!used_usb_ports)
2774 return -1;
2776 p = strchr(devname, '.');
2777 if (!p)
2778 return -1;
2779 bus_num = strtoul(devname, NULL, 0);
2780 addr = strtoul(p + 1, NULL, 0);
2782 return usb_device_del_addr(bus_num, addr);
2785 void do_usb_add(Monitor *mon, const char *devname)
2787 usb_device_add(devname, 1);
2790 void do_usb_del(Monitor *mon, const char *devname)
2792 usb_device_del(devname);
2795 void usb_info(Monitor *mon)
2797 USBDevice *dev;
2798 USBPort *port;
2799 const char *speed_str;
2801 if (!usb_enabled) {
2802 monitor_printf(mon, "USB support not enabled\n");
2803 return;
2806 for (port = used_usb_ports; port; port = port->next) {
2807 dev = port->dev;
2808 if (!dev)
2809 continue;
2810 switch(dev->speed) {
2811 case USB_SPEED_LOW:
2812 speed_str = "1.5";
2813 break;
2814 case USB_SPEED_FULL:
2815 speed_str = "12";
2816 break;
2817 case USB_SPEED_HIGH:
2818 speed_str = "480";
2819 break;
2820 default:
2821 speed_str = "?";
2822 break;
2824 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2825 0, dev->addr, speed_str, dev->devname);
2829 /***********************************************************/
2830 /* PCMCIA/Cardbus */
2832 static struct pcmcia_socket_entry_s {
2833 struct pcmcia_socket_s *socket;
2834 struct pcmcia_socket_entry_s *next;
2835 } *pcmcia_sockets = 0;
2837 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2839 struct pcmcia_socket_entry_s *entry;
2841 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2842 entry->socket = socket;
2843 entry->next = pcmcia_sockets;
2844 pcmcia_sockets = entry;
2847 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2849 struct pcmcia_socket_entry_s *entry, **ptr;
2851 ptr = &pcmcia_sockets;
2852 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2853 if (entry->socket == socket) {
2854 *ptr = entry->next;
2855 qemu_free(entry);
2859 void pcmcia_info(Monitor *mon)
2861 struct pcmcia_socket_entry_s *iter;
2863 if (!pcmcia_sockets)
2864 monitor_printf(mon, "No PCMCIA sockets\n");
2866 for (iter = pcmcia_sockets; iter; iter = iter->next)
2867 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2868 iter->socket->attached ? iter->socket->card_string :
2869 "Empty");
2872 /***********************************************************/
2873 /* register display */
2875 void register_displaystate(DisplayState *ds)
2877 DisplayState **s;
2878 s = &display_state;
2879 while (*s != NULL)
2880 s = &(*s)->next;
2881 ds->next = NULL;
2882 *s = ds;
2885 DisplayState *get_displaystate(void)
2887 return display_state;
2890 /* dumb display */
2892 static void dumb_display_init(void)
2894 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2895 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2896 register_displaystate(ds);
2899 /***********************************************************/
2900 /* I/O handling */
2902 #define MAX_IO_HANDLERS 64
2904 typedef struct IOHandlerRecord {
2905 int fd;
2906 IOCanRWHandler *fd_read_poll;
2907 IOHandler *fd_read;
2908 IOHandler *fd_write;
2909 int deleted;
2910 void *opaque;
2911 /* temporary data */
2912 struct pollfd *ufd;
2913 struct IOHandlerRecord *next;
2914 } IOHandlerRecord;
2916 static IOHandlerRecord *first_io_handler;
2918 /* XXX: fd_read_poll should be suppressed, but an API change is
2919 necessary in the character devices to suppress fd_can_read(). */
2920 int qemu_set_fd_handler2(int fd,
2921 IOCanRWHandler *fd_read_poll,
2922 IOHandler *fd_read,
2923 IOHandler *fd_write,
2924 void *opaque)
2926 IOHandlerRecord **pioh, *ioh;
2928 if (!fd_read && !fd_write) {
2929 pioh = &first_io_handler;
2930 for(;;) {
2931 ioh = *pioh;
2932 if (ioh == NULL)
2933 break;
2934 if (ioh->fd == fd) {
2935 ioh->deleted = 1;
2936 break;
2938 pioh = &ioh->next;
2940 } else {
2941 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2942 if (ioh->fd == fd)
2943 goto found;
2945 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2946 ioh->next = first_io_handler;
2947 first_io_handler = ioh;
2948 found:
2949 ioh->fd = fd;
2950 ioh->fd_read_poll = fd_read_poll;
2951 ioh->fd_read = fd_read;
2952 ioh->fd_write = fd_write;
2953 ioh->opaque = opaque;
2954 ioh->deleted = 0;
2956 return 0;
2959 int qemu_set_fd_handler(int fd,
2960 IOHandler *fd_read,
2961 IOHandler *fd_write,
2962 void *opaque)
2964 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2967 #ifdef _WIN32
2968 /***********************************************************/
2969 /* Polling handling */
2971 typedef struct PollingEntry {
2972 PollingFunc *func;
2973 void *opaque;
2974 struct PollingEntry *next;
2975 } PollingEntry;
2977 static PollingEntry *first_polling_entry;
2979 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2981 PollingEntry **ppe, *pe;
2982 pe = qemu_mallocz(sizeof(PollingEntry));
2983 pe->func = func;
2984 pe->opaque = opaque;
2985 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2986 *ppe = pe;
2987 return 0;
2990 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2992 PollingEntry **ppe, *pe;
2993 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2994 pe = *ppe;
2995 if (pe->func == func && pe->opaque == opaque) {
2996 *ppe = pe->next;
2997 qemu_free(pe);
2998 break;
3003 /***********************************************************/
3004 /* Wait objects support */
3005 typedef struct WaitObjects {
3006 int num;
3007 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3008 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3009 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3010 } WaitObjects;
3012 static WaitObjects wait_objects = {0};
3014 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3016 WaitObjects *w = &wait_objects;
3018 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3019 return -1;
3020 w->events[w->num] = handle;
3021 w->func[w->num] = func;
3022 w->opaque[w->num] = opaque;
3023 w->num++;
3024 return 0;
3027 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3029 int i, found;
3030 WaitObjects *w = &wait_objects;
3032 found = 0;
3033 for (i = 0; i < w->num; i++) {
3034 if (w->events[i] == handle)
3035 found = 1;
3036 if (found) {
3037 w->events[i] = w->events[i + 1];
3038 w->func[i] = w->func[i + 1];
3039 w->opaque[i] = w->opaque[i + 1];
3042 if (found)
3043 w->num--;
3045 #endif
3047 /***********************************************************/
3048 /* ram save/restore */
3050 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3052 int v;
3054 v = qemu_get_byte(f);
3055 switch(v) {
3056 case 0:
3057 if (qemu_get_buffer(f, buf, len) != len)
3058 return -EIO;
3059 break;
3060 case 1:
3061 v = qemu_get_byte(f);
3062 memset(buf, v, len);
3063 break;
3064 default:
3065 return -EINVAL;
3068 if (qemu_file_has_error(f))
3069 return -EIO;
3071 return 0;
3074 static int ram_load_v1(QEMUFile *f, void *opaque)
3076 int ret;
3077 ram_addr_t i;
3079 if (qemu_get_be32(f) != phys_ram_size)
3080 return -EINVAL;
3081 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3082 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3083 if (ret)
3084 return ret;
3086 return 0;
3089 #define BDRV_HASH_BLOCK_SIZE 1024
3090 #define IOBUF_SIZE 4096
3091 #define RAM_CBLOCK_MAGIC 0xfabe
3093 typedef struct RamDecompressState {
3094 z_stream zstream;
3095 QEMUFile *f;
3096 uint8_t buf[IOBUF_SIZE];
3097 } RamDecompressState;
3099 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3101 int ret;
3102 memset(s, 0, sizeof(*s));
3103 s->f = f;
3104 ret = inflateInit(&s->zstream);
3105 if (ret != Z_OK)
3106 return -1;
3107 return 0;
3110 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3112 int ret, clen;
3114 s->zstream.avail_out = len;
3115 s->zstream.next_out = buf;
3116 while (s->zstream.avail_out > 0) {
3117 if (s->zstream.avail_in == 0) {
3118 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3119 return -1;
3120 clen = qemu_get_be16(s->f);
3121 if (clen > IOBUF_SIZE)
3122 return -1;
3123 qemu_get_buffer(s->f, s->buf, clen);
3124 s->zstream.avail_in = clen;
3125 s->zstream.next_in = s->buf;
3127 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3128 if (ret != Z_OK && ret != Z_STREAM_END) {
3129 return -1;
3132 return 0;
3135 static void ram_decompress_close(RamDecompressState *s)
3137 inflateEnd(&s->zstream);
3140 #define RAM_SAVE_FLAG_FULL 0x01
3141 #define RAM_SAVE_FLAG_COMPRESS 0x02
3142 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3143 #define RAM_SAVE_FLAG_PAGE 0x08
3144 #define RAM_SAVE_FLAG_EOS 0x10
3146 static int is_dup_page(uint8_t *page, uint8_t ch)
3148 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3149 uint32_t *array = (uint32_t *)page;
3150 int i;
3152 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3153 if (array[i] != val)
3154 return 0;
3157 return 1;
3160 static int ram_save_block(QEMUFile *f)
3162 static ram_addr_t current_addr = 0;
3163 ram_addr_t saved_addr = current_addr;
3164 ram_addr_t addr = 0;
3165 int found = 0;
3167 while (addr < phys_ram_size) {
3168 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3169 uint8_t ch;
3171 cpu_physical_memory_reset_dirty(current_addr,
3172 current_addr + TARGET_PAGE_SIZE,
3173 MIGRATION_DIRTY_FLAG);
3175 ch = *(phys_ram_base + current_addr);
3177 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3178 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3179 qemu_put_byte(f, ch);
3180 } else {
3181 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3182 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3185 found = 1;
3186 break;
3188 addr += TARGET_PAGE_SIZE;
3189 current_addr = (saved_addr + addr) % phys_ram_size;
3192 return found;
3195 static ram_addr_t ram_save_threshold = 10;
3197 static ram_addr_t ram_save_remaining(void)
3199 ram_addr_t addr;
3200 ram_addr_t count = 0;
3202 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3203 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3204 count++;
3207 return count;
3210 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3212 ram_addr_t addr;
3214 if (stage == 1) {
3215 /* Make sure all dirty bits are set */
3216 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3217 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3218 cpu_physical_memory_set_dirty(addr);
3221 /* Enable dirty memory tracking */
3222 cpu_physical_memory_set_dirty_tracking(1);
3224 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3227 while (!qemu_file_rate_limit(f)) {
3228 int ret;
3230 ret = ram_save_block(f);
3231 if (ret == 0) /* no more blocks */
3232 break;
3235 /* try transferring iterative blocks of memory */
3237 if (stage == 3) {
3238 cpu_physical_memory_set_dirty_tracking(0);
3240 /* flush all remaining blocks regardless of rate limiting */
3241 while (ram_save_block(f) != 0);
3244 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3246 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3249 static int ram_load_dead(QEMUFile *f, void *opaque)
3251 RamDecompressState s1, *s = &s1;
3252 uint8_t buf[10];
3253 ram_addr_t i;
3255 if (ram_decompress_open(s, f) < 0)
3256 return -EINVAL;
3257 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3258 if (ram_decompress_buf(s, buf, 1) < 0) {
3259 fprintf(stderr, "Error while reading ram block header\n");
3260 goto error;
3262 if (buf[0] == 0) {
3263 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3264 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3265 goto error;
3267 } else {
3268 error:
3269 printf("Error block header\n");
3270 return -EINVAL;
3273 ram_decompress_close(s);
3275 return 0;
3278 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3280 ram_addr_t addr;
3281 int flags;
3283 if (version_id == 1)
3284 return ram_load_v1(f, opaque);
3286 if (version_id == 2) {
3287 if (qemu_get_be32(f) != phys_ram_size)
3288 return -EINVAL;
3289 return ram_load_dead(f, opaque);
3292 if (version_id != 3)
3293 return -EINVAL;
3295 do {
3296 addr = qemu_get_be64(f);
3298 flags = addr & ~TARGET_PAGE_MASK;
3299 addr &= TARGET_PAGE_MASK;
3301 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3302 if (addr != phys_ram_size)
3303 return -EINVAL;
3306 if (flags & RAM_SAVE_FLAG_FULL) {
3307 if (ram_load_dead(f, opaque) < 0)
3308 return -EINVAL;
3311 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3312 uint8_t ch = qemu_get_byte(f);
3313 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3314 } else if (flags & RAM_SAVE_FLAG_PAGE)
3315 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3316 } while (!(flags & RAM_SAVE_FLAG_EOS));
3318 return 0;
3321 void qemu_service_io(void)
3323 CPUState *env = cpu_single_env;
3324 if (env) {
3325 cpu_exit(env);
3326 #ifdef USE_KQEMU
3327 if (env->kqemu_enabled) {
3328 kqemu_cpu_interrupt(env);
3330 #endif
3334 /***********************************************************/
3335 /* bottom halves (can be seen as timers which expire ASAP) */
3337 struct QEMUBH {
3338 QEMUBHFunc *cb;
3339 void *opaque;
3340 int scheduled;
3341 int idle;
3342 int deleted;
3343 QEMUBH *next;
3346 static QEMUBH *first_bh = NULL;
3348 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3350 QEMUBH *bh;
3351 bh = qemu_mallocz(sizeof(QEMUBH));
3352 bh->cb = cb;
3353 bh->opaque = opaque;
3354 bh->next = first_bh;
3355 first_bh = bh;
3356 return bh;
3359 int qemu_bh_poll(void)
3361 QEMUBH *bh, **bhp;
3362 int ret;
3364 ret = 0;
3365 for (bh = first_bh; bh; bh = bh->next) {
3366 if (!bh->deleted && bh->scheduled) {
3367 bh->scheduled = 0;
3368 if (!bh->idle)
3369 ret = 1;
3370 bh->idle = 0;
3371 bh->cb(bh->opaque);
3375 /* remove deleted bhs */
3376 bhp = &first_bh;
3377 while (*bhp) {
3378 bh = *bhp;
3379 if (bh->deleted) {
3380 *bhp = bh->next;
3381 qemu_free(bh);
3382 } else
3383 bhp = &bh->next;
3386 return ret;
3389 void qemu_bh_schedule_idle(QEMUBH *bh)
3391 if (bh->scheduled)
3392 return;
3393 bh->scheduled = 1;
3394 bh->idle = 1;
3397 void qemu_bh_schedule(QEMUBH *bh)
3399 CPUState *env = cpu_single_env;
3400 if (bh->scheduled)
3401 return;
3402 bh->scheduled = 1;
3403 bh->idle = 0;
3404 /* stop the currently executing CPU to execute the BH ASAP */
3405 if (env) {
3406 cpu_exit(env);
3410 void qemu_bh_cancel(QEMUBH *bh)
3412 bh->scheduled = 0;
3415 void qemu_bh_delete(QEMUBH *bh)
3417 bh->scheduled = 0;
3418 bh->deleted = 1;
3421 static void qemu_bh_update_timeout(int *timeout)
3423 QEMUBH *bh;
3425 for (bh = first_bh; bh; bh = bh->next) {
3426 if (!bh->deleted && bh->scheduled) {
3427 if (bh->idle) {
3428 /* idle bottom halves will be polled at least
3429 * every 10ms */
3430 *timeout = MIN(10, *timeout);
3431 } else {
3432 /* non-idle bottom halves will be executed
3433 * immediately */
3434 *timeout = 0;
3435 break;
3441 /***********************************************************/
3442 /* machine registration */
3444 static QEMUMachine *first_machine = NULL;
3445 QEMUMachine *current_machine = NULL;
3447 int qemu_register_machine(QEMUMachine *m)
3449 QEMUMachine **pm;
3450 pm = &first_machine;
3451 while (*pm != NULL)
3452 pm = &(*pm)->next;
3453 m->next = NULL;
3454 *pm = m;
3455 return 0;
3458 static QEMUMachine *find_machine(const char *name)
3460 QEMUMachine *m;
3462 for(m = first_machine; m != NULL; m = m->next) {
3463 if (!strcmp(m->name, name))
3464 return m;
3466 return NULL;
3469 /***********************************************************/
3470 /* main execution loop */
3472 static void gui_update(void *opaque)
3474 uint64_t interval = GUI_REFRESH_INTERVAL;
3475 DisplayState *ds = opaque;
3476 DisplayChangeListener *dcl = ds->listeners;
3478 dpy_refresh(ds);
3480 while (dcl != NULL) {
3481 if (dcl->gui_timer_interval &&
3482 dcl->gui_timer_interval < interval)
3483 interval = dcl->gui_timer_interval;
3484 dcl = dcl->next;
3486 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3489 static void nographic_update(void *opaque)
3491 uint64_t interval = GUI_REFRESH_INTERVAL;
3493 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3496 struct vm_change_state_entry {
3497 VMChangeStateHandler *cb;
3498 void *opaque;
3499 LIST_ENTRY (vm_change_state_entry) entries;
3502 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3504 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3505 void *opaque)
3507 VMChangeStateEntry *e;
3509 e = qemu_mallocz(sizeof (*e));
3511 e->cb = cb;
3512 e->opaque = opaque;
3513 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3514 return e;
3517 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3519 LIST_REMOVE (e, entries);
3520 qemu_free (e);
3523 static void vm_state_notify(int running, int reason)
3525 VMChangeStateEntry *e;
3527 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3528 e->cb(e->opaque, running, reason);
3532 void vm_start(void)
3534 if (!vm_running) {
3535 cpu_enable_ticks();
3536 vm_running = 1;
3537 vm_state_notify(1, 0);
3538 qemu_rearm_alarm_timer(alarm_timer);
3542 void vm_stop(int reason)
3544 if (vm_running) {
3545 cpu_disable_ticks();
3546 vm_running = 0;
3547 vm_state_notify(0, reason);
3551 /* reset/shutdown handler */
3553 typedef struct QEMUResetEntry {
3554 QEMUResetHandler *func;
3555 void *opaque;
3556 struct QEMUResetEntry *next;
3557 } QEMUResetEntry;
3559 static QEMUResetEntry *first_reset_entry;
3560 static int reset_requested;
3561 static int shutdown_requested;
3562 static int powerdown_requested;
3564 int qemu_shutdown_requested(void)
3566 int r = shutdown_requested;
3567 shutdown_requested = 0;
3568 return r;
3571 int qemu_reset_requested(void)
3573 int r = reset_requested;
3574 reset_requested = 0;
3575 return r;
3578 int qemu_powerdown_requested(void)
3580 int r = powerdown_requested;
3581 powerdown_requested = 0;
3582 return r;
3585 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3587 QEMUResetEntry **pre, *re;
3589 pre = &first_reset_entry;
3590 while (*pre != NULL)
3591 pre = &(*pre)->next;
3592 re = qemu_mallocz(sizeof(QEMUResetEntry));
3593 re->func = func;
3594 re->opaque = opaque;
3595 re->next = NULL;
3596 *pre = re;
3599 void qemu_system_reset(void)
3601 QEMUResetEntry *re;
3603 /* reset all devices */
3604 for(re = first_reset_entry; re != NULL; re = re->next) {
3605 re->func(re->opaque);
3609 void qemu_system_reset_request(void)
3611 if (no_reboot) {
3612 shutdown_requested = 1;
3613 } else {
3614 reset_requested = 1;
3616 if (cpu_single_env)
3617 cpu_exit(cpu_single_env);
3620 void qemu_system_shutdown_request(void)
3622 shutdown_requested = 1;
3623 if (cpu_single_env)
3624 cpu_exit(cpu_single_env);
3627 void qemu_system_powerdown_request(void)
3629 powerdown_requested = 1;
3630 if (cpu_single_env)
3631 cpu_exit(cpu_single_env);
3634 #ifdef _WIN32
3635 static void host_main_loop_wait(int *timeout)
3637 int ret, ret2, i;
3638 PollingEntry *pe;
3641 /* XXX: need to suppress polling by better using win32 events */
3642 ret = 0;
3643 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3644 ret |= pe->func(pe->opaque);
3646 if (ret == 0) {
3647 int err;
3648 WaitObjects *w = &wait_objects;
3650 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3651 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3652 if (w->func[ret - WAIT_OBJECT_0])
3653 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3655 /* Check for additional signaled events */
3656 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3658 /* Check if event is signaled */
3659 ret2 = WaitForSingleObject(w->events[i], 0);
3660 if(ret2 == WAIT_OBJECT_0) {
3661 if (w->func[i])
3662 w->func[i](w->opaque[i]);
3663 } else if (ret2 == WAIT_TIMEOUT) {
3664 } else {
3665 err = GetLastError();
3666 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3669 } else if (ret == WAIT_TIMEOUT) {
3670 } else {
3671 err = GetLastError();
3672 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3676 *timeout = 0;
3678 #else
3679 static void host_main_loop_wait(int *timeout)
3682 #endif
3684 void main_loop_wait(int timeout)
3686 IOHandlerRecord *ioh;
3687 fd_set rfds, wfds, xfds;
3688 int ret, nfds;
3689 struct timeval tv;
3691 qemu_bh_update_timeout(&timeout);
3693 host_main_loop_wait(&timeout);
3695 /* poll any events */
3696 /* XXX: separate device handlers from system ones */
3697 nfds = -1;
3698 FD_ZERO(&rfds);
3699 FD_ZERO(&wfds);
3700 FD_ZERO(&xfds);
3701 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3702 if (ioh->deleted)
3703 continue;
3704 if (ioh->fd_read &&
3705 (!ioh->fd_read_poll ||
3706 ioh->fd_read_poll(ioh->opaque) != 0)) {
3707 FD_SET(ioh->fd, &rfds);
3708 if (ioh->fd > nfds)
3709 nfds = ioh->fd;
3711 if (ioh->fd_write) {
3712 FD_SET(ioh->fd, &wfds);
3713 if (ioh->fd > nfds)
3714 nfds = ioh->fd;
3718 tv.tv_sec = timeout / 1000;
3719 tv.tv_usec = (timeout % 1000) * 1000;
3721 #if defined(CONFIG_SLIRP)
3722 if (slirp_is_inited()) {
3723 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3725 #endif
3726 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3727 if (ret > 0) {
3728 IOHandlerRecord **pioh;
3730 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3731 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3732 ioh->fd_read(ioh->opaque);
3734 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3735 ioh->fd_write(ioh->opaque);
3739 /* remove deleted IO handlers */
3740 pioh = &first_io_handler;
3741 while (*pioh) {
3742 ioh = *pioh;
3743 if (ioh->deleted) {
3744 *pioh = ioh->next;
3745 qemu_free(ioh);
3746 } else
3747 pioh = &ioh->next;
3750 #if defined(CONFIG_SLIRP)
3751 if (slirp_is_inited()) {
3752 if (ret < 0) {
3753 FD_ZERO(&rfds);
3754 FD_ZERO(&wfds);
3755 FD_ZERO(&xfds);
3757 slirp_select_poll(&rfds, &wfds, &xfds);
3759 #endif
3761 /* vm time timers */
3762 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3763 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3764 qemu_get_clock(vm_clock));
3766 /* real time timers */
3767 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3768 qemu_get_clock(rt_clock));
3770 /* Check bottom-halves last in case any of the earlier events triggered
3771 them. */
3772 qemu_bh_poll();
3776 static int main_loop(void)
3778 int ret, timeout;
3779 #ifdef CONFIG_PROFILER
3780 int64_t ti;
3781 #endif
3782 CPUState *env;
3784 cur_cpu = first_cpu;
3785 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3786 for(;;) {
3787 if (vm_running) {
3789 for(;;) {
3790 /* get next cpu */
3791 env = next_cpu;
3792 #ifdef CONFIG_PROFILER
3793 ti = profile_getclock();
3794 #endif
3795 if (use_icount) {
3796 int64_t count;
3797 int decr;
3798 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3799 env->icount_decr.u16.low = 0;
3800 env->icount_extra = 0;
3801 count = qemu_next_deadline();
3802 count = (count + (1 << icount_time_shift) - 1)
3803 >> icount_time_shift;
3804 qemu_icount += count;
3805 decr = (count > 0xffff) ? 0xffff : count;
3806 count -= decr;
3807 env->icount_decr.u16.low = decr;
3808 env->icount_extra = count;
3810 ret = cpu_exec(env);
3811 #ifdef CONFIG_PROFILER
3812 qemu_time += profile_getclock() - ti;
3813 #endif
3814 if (use_icount) {
3815 /* Fold pending instructions back into the
3816 instruction counter, and clear the interrupt flag. */
3817 qemu_icount -= (env->icount_decr.u16.low
3818 + env->icount_extra);
3819 env->icount_decr.u32 = 0;
3820 env->icount_extra = 0;
3822 next_cpu = env->next_cpu ?: first_cpu;
3823 if (event_pending && likely(ret != EXCP_DEBUG)) {
3824 ret = EXCP_INTERRUPT;
3825 event_pending = 0;
3826 break;
3828 if (ret == EXCP_HLT) {
3829 /* Give the next CPU a chance to run. */
3830 cur_cpu = env;
3831 continue;
3833 if (ret != EXCP_HALTED)
3834 break;
3835 /* all CPUs are halted ? */
3836 if (env == cur_cpu)
3837 break;
3839 cur_cpu = env;
3841 if (shutdown_requested) {
3842 ret = EXCP_INTERRUPT;
3843 if (no_shutdown) {
3844 vm_stop(0);
3845 no_shutdown = 0;
3847 else
3848 break;
3850 if (reset_requested) {
3851 reset_requested = 0;
3852 qemu_system_reset();
3853 ret = EXCP_INTERRUPT;
3855 if (powerdown_requested) {
3856 powerdown_requested = 0;
3857 qemu_system_powerdown();
3858 ret = EXCP_INTERRUPT;
3860 if (unlikely(ret == EXCP_DEBUG)) {
3861 gdb_set_stop_cpu(cur_cpu);
3862 vm_stop(EXCP_DEBUG);
3864 /* If all cpus are halted then wait until the next IRQ */
3865 /* XXX: use timeout computed from timers */
3866 if (ret == EXCP_HALTED) {
3867 if (use_icount) {
3868 int64_t add;
3869 int64_t delta;
3870 /* Advance virtual time to the next event. */
3871 if (use_icount == 1) {
3872 /* When not using an adaptive execution frequency
3873 we tend to get badly out of sync with real time,
3874 so just delay for a reasonable amount of time. */
3875 delta = 0;
3876 } else {
3877 delta = cpu_get_icount() - cpu_get_clock();
3879 if (delta > 0) {
3880 /* If virtual time is ahead of real time then just
3881 wait for IO. */
3882 timeout = (delta / 1000000) + 1;
3883 } else {
3884 /* Wait for either IO to occur or the next
3885 timer event. */
3886 add = qemu_next_deadline();
3887 /* We advance the timer before checking for IO.
3888 Limit the amount we advance so that early IO
3889 activity won't get the guest too far ahead. */
3890 if (add > 10000000)
3891 add = 10000000;
3892 delta += add;
3893 add = (add + (1 << icount_time_shift) - 1)
3894 >> icount_time_shift;
3895 qemu_icount += add;
3896 timeout = delta / 1000000;
3897 if (timeout < 0)
3898 timeout = 0;
3900 } else {
3901 timeout = 5000;
3903 } else {
3904 timeout = 0;
3906 } else {
3907 if (shutdown_requested) {
3908 ret = EXCP_INTERRUPT;
3909 break;
3911 timeout = 5000;
3913 #ifdef CONFIG_PROFILER
3914 ti = profile_getclock();
3915 #endif
3916 main_loop_wait(timeout);
3917 #ifdef CONFIG_PROFILER
3918 dev_time += profile_getclock() - ti;
3919 #endif
3921 cpu_disable_ticks();
3922 return ret;
3925 static void help(int exitcode)
3927 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3928 and qemu-doc.texi */
3929 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3930 "usage: %s [options] [disk_image]\n"
3931 "\n"
3932 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3933 "\n"
3934 "Standard options:\n"
3935 "-h or -help display this help and exit\n"
3936 "-M machine select emulated machine (-M ? for list)\n"
3937 "-cpu cpu select CPU (-cpu ? for list)\n"
3938 "-smp n set the number of CPUs to 'n' [default=1]\n"
3939 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3940 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3941 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3942 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3943 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3944 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3945 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3946 " use 'file' as a drive image\n"
3947 "-mtdblock file use 'file' as on-board Flash memory image\n"
3948 "-sd file use 'file' as SecureDigital card image\n"
3949 "-pflash file use 'file' as a parallel flash image\n"
3950 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3951 "-snapshot write to temporary files instead of disk image files\n"
3952 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3953 #ifndef _WIN32
3954 "-k language use keyboard layout (for example \"fr\" for French)\n"
3955 #endif
3956 #ifdef HAS_AUDIO
3957 "-audio-help print list of audio drivers and their options\n"
3958 "-soundhw c1,... enable audio support\n"
3959 " and only specified sound cards (comma separated list)\n"
3960 " use -soundhw ? to get the list of supported cards\n"
3961 " use -soundhw all to enable all of them\n"
3962 #endif
3963 "-usb enable the USB driver (will be the default soon)\n"
3964 "-usbdevice name add the host or guest USB device 'name'\n"
3965 "-name string set the name of the guest\n"
3966 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3967 " specify machine UUID\n"
3968 "\n"
3969 "Display options:\n"
3970 "-nographic disable graphical output and redirect serial I/Os to console\n"
3971 #ifdef CONFIG_CURSES
3972 "-curses use a curses/ncurses interface instead of SDL\n"
3973 #endif
3974 #ifdef CONFIG_SDL
3975 "-no-frame open SDL window without a frame and window decorations\n"
3976 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3977 "-no-quit disable SDL window close capability\n"
3978 "-sdl enable SDL\n"
3979 #endif
3980 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3981 "-vga [std|cirrus|vmware|none]\n"
3982 " select video card type\n"
3983 "-full-screen start in full screen\n"
3984 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3985 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3986 #endif
3987 "-vnc display start a VNC server on display\n"
3988 "\n"
3989 "Network options:\n"
3990 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3991 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3992 #ifdef CONFIG_SLIRP
3993 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3994 " connect the user mode network stack to VLAN 'n' and send\n"
3995 " hostname 'host' to DHCP clients\n"
3996 #endif
3997 #ifdef _WIN32
3998 "-net tap[,vlan=n][,name=str],ifname=name\n"
3999 " connect the host TAP network interface to VLAN 'n'\n"
4000 #else
4001 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4002 " connect the host TAP network interface to VLAN 'n' and use the\n"
4003 " network scripts 'file' (default=%s)\n"
4004 " and 'dfile' (default=%s);\n"
4005 " use '[down]script=no' to disable script execution;\n"
4006 " use 'fd=h' to connect to an already opened TAP interface\n"
4007 #endif
4008 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4009 " connect the vlan 'n' to another VLAN using a socket connection\n"
4010 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4011 " connect the vlan 'n' to multicast maddr and port\n"
4012 #ifdef CONFIG_VDE
4013 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4014 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4015 " on host and listening for incoming connections on 'socketpath'.\n"
4016 " Use group 'groupname' and mode 'octalmode' to change default\n"
4017 " ownership and permissions for communication port.\n"
4018 #endif
4019 "-net none use it alone to have zero network devices; if no -net option\n"
4020 " is provided, the default is '-net nic -net user'\n"
4021 #ifdef CONFIG_SLIRP
4022 "-tftp dir allow tftp access to files in dir [-net user]\n"
4023 "-bootp file advertise file in BOOTP replies\n"
4024 #ifndef _WIN32
4025 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4026 #endif
4027 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4028 " redirect TCP or UDP connections from host to guest [-net user]\n"
4029 #endif
4030 "\n"
4031 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4032 "-bt hci,host[:id]\n"
4033 " use host's HCI with the given name\n"
4034 "-bt hci[,vlan=n]\n"
4035 " emulate a standard HCI in virtual scatternet 'n'\n"
4036 "-bt vhci[,vlan=n]\n"
4037 " add host computer to virtual scatternet 'n' using VHCI\n"
4038 "-bt device:dev[,vlan=n]\n"
4039 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4040 "\n"
4041 #ifdef TARGET_I386
4042 "\n"
4043 "i386 target only:\n"
4044 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4045 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4046 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4047 "-no-acpi disable ACPI\n"
4048 "-no-hpet disable HPET\n"
4049 "-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"
4050 " ACPI table description\n"
4051 #endif
4052 "Linux boot specific:\n"
4053 "-kernel bzImage use 'bzImage' as kernel image\n"
4054 "-append cmdline use 'cmdline' as kernel command line\n"
4055 "-initrd file use 'file' as initial ram disk\n"
4056 "\n"
4057 "Debug/Expert options:\n"
4058 "-serial dev redirect the serial port to char device 'dev'\n"
4059 "-parallel dev redirect the parallel port to char device 'dev'\n"
4060 "-monitor dev redirect the monitor to char device 'dev'\n"
4061 "-pidfile file write PID to 'file'\n"
4062 "-S freeze CPU at startup (use 'c' to start execution)\n"
4063 "-s wait gdb connection to port\n"
4064 "-p port set gdb connection port [default=%s]\n"
4065 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4066 "-hdachs c,h,s[,t]\n"
4067 " force hard disk 0 physical geometry and the optional BIOS\n"
4068 " translation (t=none or lba) (usually qemu can guess them)\n"
4069 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4070 "-bios file set the filename for the BIOS\n"
4071 #ifdef USE_KQEMU
4072 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4073 "-no-kqemu disable KQEMU kernel module usage\n"
4074 #endif
4075 #ifdef CONFIG_KVM
4076 "-enable-kvm enable KVM full virtualization support\n"
4077 #endif
4078 "-no-reboot exit instead of rebooting\n"
4079 "-no-shutdown stop before shutdown\n"
4080 "-loadvm [tag|id]\n"
4081 " start right away with a saved state (loadvm in monitor)\n"
4082 #ifndef _WIN32
4083 "-daemonize daemonize QEMU after initializing\n"
4084 #endif
4085 "-option-rom rom load a file, rom, into the option ROM space\n"
4086 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4087 "-prom-env variable=value\n"
4088 " set OpenBIOS nvram variables\n"
4089 #endif
4090 "-clock force the use of the given methods for timer alarm.\n"
4091 " To see what timers are available use -clock ?\n"
4092 "-localtime set the real time clock to local time [default=utc]\n"
4093 "-startdate select initial date of the clock\n"
4094 "-icount [N|auto]\n"
4095 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4096 "-echr chr set terminal escape character instead of ctrl-a\n"
4097 "-virtioconsole c\n"
4098 " set virtio console\n"
4099 "-show-cursor show cursor\n"
4100 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4101 "-semihosting semihosting mode\n"
4102 #endif
4103 #if defined(TARGET_ARM)
4104 "-old-param old param mode\n"
4105 #endif
4106 "-tb-size n set TB size\n"
4107 "-incoming p prepare for incoming migration, listen on port p\n"
4108 #ifndef _WIN32
4109 "-chroot dir Chroot to dir just before starting the VM.\n"
4110 "-runas user Change to user id user just before starting the VM.\n"
4111 #endif
4112 "\n"
4113 "During emulation, the following keys are useful:\n"
4114 "ctrl-alt-f toggle full screen\n"
4115 "ctrl-alt-n switch to virtual console 'n'\n"
4116 "ctrl-alt toggle mouse and keyboard grab\n"
4117 "\n"
4118 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4120 "qemu",
4121 DEFAULT_RAM_SIZE,
4122 #ifndef _WIN32
4123 DEFAULT_NETWORK_SCRIPT,
4124 DEFAULT_NETWORK_DOWN_SCRIPT,
4125 #endif
4126 DEFAULT_GDBSTUB_PORT,
4127 "/tmp/qemu.log");
4128 exit(exitcode);
4131 #define HAS_ARG 0x0001
4133 enum {
4134 /* Please keep in synch with help, qemu_options[] and
4135 qemu-doc.texi */
4136 /* Standard options: */
4137 QEMU_OPTION_h,
4138 QEMU_OPTION_M,
4139 QEMU_OPTION_cpu,
4140 QEMU_OPTION_smp,
4141 QEMU_OPTION_fda,
4142 QEMU_OPTION_fdb,
4143 QEMU_OPTION_hda,
4144 QEMU_OPTION_hdb,
4145 QEMU_OPTION_hdc,
4146 QEMU_OPTION_hdd,
4147 QEMU_OPTION_cdrom,
4148 QEMU_OPTION_drive,
4149 QEMU_OPTION_mtdblock,
4150 QEMU_OPTION_sd,
4151 QEMU_OPTION_pflash,
4152 QEMU_OPTION_boot,
4153 QEMU_OPTION_snapshot,
4154 QEMU_OPTION_m,
4155 QEMU_OPTION_k,
4156 QEMU_OPTION_audio_help,
4157 QEMU_OPTION_soundhw,
4158 QEMU_OPTION_usb,
4159 QEMU_OPTION_usbdevice,
4160 QEMU_OPTION_name,
4161 QEMU_OPTION_uuid,
4163 /* Display options: */
4164 QEMU_OPTION_nographic,
4165 QEMU_OPTION_curses,
4166 QEMU_OPTION_no_frame,
4167 QEMU_OPTION_alt_grab,
4168 QEMU_OPTION_no_quit,
4169 QEMU_OPTION_sdl,
4170 QEMU_OPTION_portrait,
4171 QEMU_OPTION_vga,
4172 QEMU_OPTION_full_screen,
4173 QEMU_OPTION_g,
4174 QEMU_OPTION_vnc,
4176 /* Network options: */
4177 QEMU_OPTION_net,
4178 QEMU_OPTION_tftp,
4179 QEMU_OPTION_bootp,
4180 QEMU_OPTION_smb,
4181 QEMU_OPTION_redir,
4182 QEMU_OPTION_bt,
4184 /* i386 target only: */
4185 QEMU_OPTION_win2k_hack,
4186 QEMU_OPTION_rtc_td_hack,
4187 QEMU_OPTION_no_fd_bootchk,
4188 QEMU_OPTION_no_acpi,
4189 QEMU_OPTION_no_hpet,
4190 QEMU_OPTION_acpitable,
4192 /* Linux boot specific: */
4193 QEMU_OPTION_kernel,
4194 QEMU_OPTION_append,
4195 QEMU_OPTION_initrd,
4197 /* Debug/Expert options: */
4198 QEMU_OPTION_serial,
4199 QEMU_OPTION_parallel,
4200 QEMU_OPTION_monitor,
4201 QEMU_OPTION_pidfile,
4202 QEMU_OPTION_S,
4203 QEMU_OPTION_s,
4204 QEMU_OPTION_p,
4205 QEMU_OPTION_d,
4206 QEMU_OPTION_hdachs,
4207 QEMU_OPTION_L,
4208 QEMU_OPTION_bios,
4209 QEMU_OPTION_kernel_kqemu,
4210 QEMU_OPTION_no_kqemu,
4211 QEMU_OPTION_enable_kvm,
4212 QEMU_OPTION_no_reboot,
4213 QEMU_OPTION_no_shutdown,
4214 QEMU_OPTION_loadvm,
4215 QEMU_OPTION_daemonize,
4216 QEMU_OPTION_option_rom,
4217 QEMU_OPTION_prom_env,
4218 QEMU_OPTION_clock,
4219 QEMU_OPTION_localtime,
4220 QEMU_OPTION_startdate,
4221 QEMU_OPTION_icount,
4222 QEMU_OPTION_echr,
4223 QEMU_OPTION_virtiocon,
4224 QEMU_OPTION_show_cursor,
4225 QEMU_OPTION_semihosting,
4226 QEMU_OPTION_old_param,
4227 QEMU_OPTION_tb_size,
4228 QEMU_OPTION_incoming,
4229 QEMU_OPTION_chroot,
4230 QEMU_OPTION_runas,
4233 typedef struct QEMUOption {
4234 const char *name;
4235 int flags;
4236 int index;
4237 } QEMUOption;
4239 static const QEMUOption qemu_options[] = {
4240 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4241 qemu-doc.texi */
4242 /* Standard options: */
4243 { "h", 0, QEMU_OPTION_h },
4244 { "help", 0, QEMU_OPTION_h },
4245 { "M", HAS_ARG, QEMU_OPTION_M },
4246 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4247 { "smp", HAS_ARG, QEMU_OPTION_smp },
4248 { "fda", HAS_ARG, QEMU_OPTION_fda },
4249 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4250 { "hda", HAS_ARG, QEMU_OPTION_hda },
4251 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4252 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4253 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4254 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4255 { "drive", HAS_ARG, QEMU_OPTION_drive },
4256 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4257 { "sd", HAS_ARG, QEMU_OPTION_sd },
4258 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4259 { "boot", HAS_ARG, QEMU_OPTION_boot },
4260 { "snapshot", 0, QEMU_OPTION_snapshot },
4261 { "m", HAS_ARG, QEMU_OPTION_m },
4262 #ifndef _WIN32
4263 { "k", HAS_ARG, QEMU_OPTION_k },
4264 #endif
4265 #ifdef HAS_AUDIO
4266 { "audio-help", 0, QEMU_OPTION_audio_help },
4267 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4268 #endif
4269 { "usb", 0, QEMU_OPTION_usb },
4270 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4271 { "name", HAS_ARG, QEMU_OPTION_name },
4272 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4274 /* Display options: */
4275 { "nographic", 0, QEMU_OPTION_nographic },
4276 #ifdef CONFIG_CURSES
4277 { "curses", 0, QEMU_OPTION_curses },
4278 #endif
4279 #ifdef CONFIG_SDL
4280 { "no-frame", 0, QEMU_OPTION_no_frame },
4281 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4282 { "no-quit", 0, QEMU_OPTION_no_quit },
4283 { "sdl", 0, QEMU_OPTION_sdl },
4284 #endif
4285 { "portrait", 0, QEMU_OPTION_portrait },
4286 { "vga", HAS_ARG, QEMU_OPTION_vga },
4287 { "full-screen", 0, QEMU_OPTION_full_screen },
4288 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4289 { "g", 1, QEMU_OPTION_g },
4290 #endif
4291 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4293 /* Network options: */
4294 { "net", HAS_ARG, QEMU_OPTION_net},
4295 #ifdef CONFIG_SLIRP
4296 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4297 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4298 #ifndef _WIN32
4299 { "smb", HAS_ARG, QEMU_OPTION_smb },
4300 #endif
4301 { "redir", HAS_ARG, QEMU_OPTION_redir },
4302 #endif
4303 { "bt", HAS_ARG, QEMU_OPTION_bt },
4304 #ifdef TARGET_I386
4305 /* i386 target only: */
4306 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4307 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4308 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4309 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4310 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4311 { "acpitable", HAS_ARG, QEMU_OPTION_acpitable },
4312 #endif
4314 /* Linux boot specific: */
4315 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4316 { "append", HAS_ARG, QEMU_OPTION_append },
4317 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4319 /* Debug/Expert options: */
4320 { "serial", HAS_ARG, QEMU_OPTION_serial },
4321 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4322 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4323 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4324 { "S", 0, QEMU_OPTION_S },
4325 { "s", 0, QEMU_OPTION_s },
4326 { "p", HAS_ARG, QEMU_OPTION_p },
4327 { "d", HAS_ARG, QEMU_OPTION_d },
4328 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4329 { "L", HAS_ARG, QEMU_OPTION_L },
4330 { "bios", HAS_ARG, QEMU_OPTION_bios },
4331 #ifdef USE_KQEMU
4332 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4333 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4334 #endif
4335 #ifdef CONFIG_KVM
4336 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4337 #endif
4338 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4339 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4340 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4341 { "daemonize", 0, QEMU_OPTION_daemonize },
4342 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4343 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4344 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4345 #endif
4346 { "clock", HAS_ARG, QEMU_OPTION_clock },
4347 { "localtime", 0, QEMU_OPTION_localtime },
4348 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4349 { "icount", HAS_ARG, QEMU_OPTION_icount },
4350 { "echr", HAS_ARG, QEMU_OPTION_echr },
4351 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4352 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4353 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4354 { "semihosting", 0, QEMU_OPTION_semihosting },
4355 #endif
4356 #if defined(TARGET_ARM)
4357 { "old-param", 0, QEMU_OPTION_old_param },
4358 #endif
4359 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4360 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4361 { "chroot", HAS_ARG, QEMU_OPTION_chroot },
4362 { "runas", HAS_ARG, QEMU_OPTION_runas },
4363 { NULL },
4366 #ifdef HAS_AUDIO
4367 struct soundhw soundhw[] = {
4368 #ifdef HAS_AUDIO_CHOICE
4369 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4371 "pcspk",
4372 "PC speaker",
4375 { .init_isa = pcspk_audio_init }
4377 #endif
4379 #ifdef CONFIG_SB16
4381 "sb16",
4382 "Creative Sound Blaster 16",
4385 { .init_isa = SB16_init }
4387 #endif
4389 #ifdef CONFIG_CS4231A
4391 "cs4231a",
4392 "CS4231A",
4395 { .init_isa = cs4231a_init }
4397 #endif
4399 #ifdef CONFIG_ADLIB
4401 "adlib",
4402 #ifdef HAS_YMF262
4403 "Yamaha YMF262 (OPL3)",
4404 #else
4405 "Yamaha YM3812 (OPL2)",
4406 #endif
4409 { .init_isa = Adlib_init }
4411 #endif
4413 #ifdef CONFIG_GUS
4415 "gus",
4416 "Gravis Ultrasound GF1",
4419 { .init_isa = GUS_init }
4421 #endif
4423 #ifdef CONFIG_AC97
4425 "ac97",
4426 "Intel 82801AA AC97 Audio",
4429 { .init_pci = ac97_init }
4431 #endif
4433 #ifdef CONFIG_ES1370
4435 "es1370",
4436 "ENSONIQ AudioPCI ES1370",
4439 { .init_pci = es1370_init }
4441 #endif
4443 #endif /* HAS_AUDIO_CHOICE */
4445 { NULL, NULL, 0, 0, { NULL } }
4448 static void select_soundhw (const char *optarg)
4450 struct soundhw *c;
4452 if (*optarg == '?') {
4453 show_valid_cards:
4455 printf ("Valid sound card names (comma separated):\n");
4456 for (c = soundhw; c->name; ++c) {
4457 printf ("%-11s %s\n", c->name, c->descr);
4459 printf ("\n-soundhw all will enable all of the above\n");
4460 exit (*optarg != '?');
4462 else {
4463 size_t l;
4464 const char *p;
4465 char *e;
4466 int bad_card = 0;
4468 if (!strcmp (optarg, "all")) {
4469 for (c = soundhw; c->name; ++c) {
4470 c->enabled = 1;
4472 return;
4475 p = optarg;
4476 while (*p) {
4477 e = strchr (p, ',');
4478 l = !e ? strlen (p) : (size_t) (e - p);
4480 for (c = soundhw; c->name; ++c) {
4481 if (!strncmp (c->name, p, l)) {
4482 c->enabled = 1;
4483 break;
4487 if (!c->name) {
4488 if (l > 80) {
4489 fprintf (stderr,
4490 "Unknown sound card name (too big to show)\n");
4492 else {
4493 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4494 (int) l, p);
4496 bad_card = 1;
4498 p += l + (e != NULL);
4501 if (bad_card)
4502 goto show_valid_cards;
4505 #endif
4507 static void select_vgahw (const char *p)
4509 const char *opts;
4511 if (strstart(p, "std", &opts)) {
4512 std_vga_enabled = 1;
4513 cirrus_vga_enabled = 0;
4514 vmsvga_enabled = 0;
4515 } else if (strstart(p, "cirrus", &opts)) {
4516 cirrus_vga_enabled = 1;
4517 std_vga_enabled = 0;
4518 vmsvga_enabled = 0;
4519 } else if (strstart(p, "vmware", &opts)) {
4520 cirrus_vga_enabled = 0;
4521 std_vga_enabled = 0;
4522 vmsvga_enabled = 1;
4523 } else if (strstart(p, "none", &opts)) {
4524 cirrus_vga_enabled = 0;
4525 std_vga_enabled = 0;
4526 vmsvga_enabled = 0;
4527 } else {
4528 invalid_vga:
4529 fprintf(stderr, "Unknown vga type: %s\n", p);
4530 exit(1);
4532 while (*opts) {
4533 const char *nextopt;
4535 if (strstart(opts, ",retrace=", &nextopt)) {
4536 opts = nextopt;
4537 if (strstart(opts, "dumb", &nextopt))
4538 vga_retrace_method = VGA_RETRACE_DUMB;
4539 else if (strstart(opts, "precise", &nextopt))
4540 vga_retrace_method = VGA_RETRACE_PRECISE;
4541 else goto invalid_vga;
4542 } else goto invalid_vga;
4543 opts = nextopt;
4547 #ifdef _WIN32
4548 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4550 exit(STATUS_CONTROL_C_EXIT);
4551 return TRUE;
4553 #endif
4555 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4557 int ret;
4559 if(strlen(str) != 36)
4560 return -1;
4562 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4563 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4564 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4566 if(ret != 16)
4567 return -1;
4569 return 0;
4572 #define MAX_NET_CLIENTS 32
4574 #ifndef _WIN32
4576 static void termsig_handler(int signal)
4578 qemu_system_shutdown_request();
4581 static void termsig_setup(void)
4583 struct sigaction act;
4585 memset(&act, 0, sizeof(act));
4586 act.sa_handler = termsig_handler;
4587 sigaction(SIGINT, &act, NULL);
4588 sigaction(SIGHUP, &act, NULL);
4589 sigaction(SIGTERM, &act, NULL);
4592 #endif
4594 int main(int argc, char **argv, char **envp)
4596 #ifdef CONFIG_GDBSTUB
4597 int use_gdbstub;
4598 const char *gdbstub_port;
4599 #endif
4600 uint32_t boot_devices_bitmap = 0;
4601 int i;
4602 int snapshot, linux_boot, net_boot;
4603 const char *initrd_filename;
4604 const char *kernel_filename, *kernel_cmdline;
4605 const char *boot_devices = "";
4606 DisplayState *ds;
4607 DisplayChangeListener *dcl;
4608 int cyls, heads, secs, translation;
4609 const char *net_clients[MAX_NET_CLIENTS];
4610 int nb_net_clients;
4611 const char *bt_opts[MAX_BT_CMDLINE];
4612 int nb_bt_opts;
4613 int hda_index;
4614 int optind;
4615 const char *r, *optarg;
4616 CharDriverState *monitor_hd = NULL;
4617 const char *monitor_device;
4618 const char *serial_devices[MAX_SERIAL_PORTS];
4619 int serial_device_index;
4620 const char *parallel_devices[MAX_PARALLEL_PORTS];
4621 int parallel_device_index;
4622 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4623 int virtio_console_index;
4624 const char *loadvm = NULL;
4625 QEMUMachine *machine;
4626 const char *cpu_model;
4627 const char *usb_devices[MAX_USB_CMDLINE];
4628 int usb_devices_index;
4629 int fds[2];
4630 int tb_size;
4631 const char *pid_file = NULL;
4632 const char *incoming = NULL;
4633 int fd = 0;
4634 struct passwd *pwd = NULL;
4635 const char *chroot_dir = NULL;
4636 const char *run_as = NULL;
4638 qemu_cache_utils_init(envp);
4640 LIST_INIT (&vm_change_state_head);
4641 #ifndef _WIN32
4643 struct sigaction act;
4644 sigfillset(&act.sa_mask);
4645 act.sa_flags = 0;
4646 act.sa_handler = SIG_IGN;
4647 sigaction(SIGPIPE, &act, NULL);
4649 #else
4650 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4651 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4652 QEMU to run on a single CPU */
4654 HANDLE h;
4655 DWORD mask, smask;
4656 int i;
4657 h = GetCurrentProcess();
4658 if (GetProcessAffinityMask(h, &mask, &smask)) {
4659 for(i = 0; i < 32; i++) {
4660 if (mask & (1 << i))
4661 break;
4663 if (i != 32) {
4664 mask = 1 << i;
4665 SetProcessAffinityMask(h, mask);
4669 #endif
4671 register_machines();
4672 machine = first_machine;
4673 cpu_model = NULL;
4674 initrd_filename = NULL;
4675 ram_size = 0;
4676 vga_ram_size = VGA_RAM_SIZE;
4677 #ifdef CONFIG_GDBSTUB
4678 use_gdbstub = 0;
4679 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4680 #endif
4681 snapshot = 0;
4682 nographic = 0;
4683 curses = 0;
4684 kernel_filename = NULL;
4685 kernel_cmdline = "";
4686 cyls = heads = secs = 0;
4687 translation = BIOS_ATA_TRANSLATION_AUTO;
4688 monitor_device = "vc:80Cx24C";
4690 serial_devices[0] = "vc:80Cx24C";
4691 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4692 serial_devices[i] = NULL;
4693 serial_device_index = 0;
4695 parallel_devices[0] = "vc:80Cx24C";
4696 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4697 parallel_devices[i] = NULL;
4698 parallel_device_index = 0;
4700 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4701 virtio_consoles[i] = NULL;
4702 virtio_console_index = 0;
4704 usb_devices_index = 0;
4706 nb_net_clients = 0;
4707 nb_bt_opts = 0;
4708 nb_drives = 0;
4709 nb_drives_opt = 0;
4710 hda_index = -1;
4712 nb_nics = 0;
4714 tb_size = 0;
4715 autostart= 1;
4717 optind = 1;
4718 for(;;) {
4719 if (optind >= argc)
4720 break;
4721 r = argv[optind];
4722 if (r[0] != '-') {
4723 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4724 } else {
4725 const QEMUOption *popt;
4727 optind++;
4728 /* Treat --foo the same as -foo. */
4729 if (r[1] == '-')
4730 r++;
4731 popt = qemu_options;
4732 for(;;) {
4733 if (!popt->name) {
4734 fprintf(stderr, "%s: invalid option -- '%s'\n",
4735 argv[0], r);
4736 exit(1);
4738 if (!strcmp(popt->name, r + 1))
4739 break;
4740 popt++;
4742 if (popt->flags & HAS_ARG) {
4743 if (optind >= argc) {
4744 fprintf(stderr, "%s: option '%s' requires an argument\n",
4745 argv[0], r);
4746 exit(1);
4748 optarg = argv[optind++];
4749 } else {
4750 optarg = NULL;
4753 switch(popt->index) {
4754 case QEMU_OPTION_M:
4755 machine = find_machine(optarg);
4756 if (!machine) {
4757 QEMUMachine *m;
4758 printf("Supported machines are:\n");
4759 for(m = first_machine; m != NULL; m = m->next) {
4760 printf("%-10s %s%s\n",
4761 m->name, m->desc,
4762 m == first_machine ? " (default)" : "");
4764 exit(*optarg != '?');
4766 break;
4767 case QEMU_OPTION_cpu:
4768 /* hw initialization will check this */
4769 if (*optarg == '?') {
4770 /* XXX: implement xxx_cpu_list for targets that still miss it */
4771 #if defined(cpu_list)
4772 cpu_list(stdout, &fprintf);
4773 #endif
4774 exit(0);
4775 } else {
4776 cpu_model = optarg;
4778 break;
4779 case QEMU_OPTION_initrd:
4780 initrd_filename = optarg;
4781 break;
4782 case QEMU_OPTION_hda:
4783 if (cyls == 0)
4784 hda_index = drive_add(optarg, HD_ALIAS, 0);
4785 else
4786 hda_index = drive_add(optarg, HD_ALIAS
4787 ",cyls=%d,heads=%d,secs=%d%s",
4788 0, cyls, heads, secs,
4789 translation == BIOS_ATA_TRANSLATION_LBA ?
4790 ",trans=lba" :
4791 translation == BIOS_ATA_TRANSLATION_NONE ?
4792 ",trans=none" : "");
4793 break;
4794 case QEMU_OPTION_hdb:
4795 case QEMU_OPTION_hdc:
4796 case QEMU_OPTION_hdd:
4797 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4798 break;
4799 case QEMU_OPTION_drive:
4800 drive_add(NULL, "%s", optarg);
4801 break;
4802 case QEMU_OPTION_mtdblock:
4803 drive_add(optarg, MTD_ALIAS);
4804 break;
4805 case QEMU_OPTION_sd:
4806 drive_add(optarg, SD_ALIAS);
4807 break;
4808 case QEMU_OPTION_pflash:
4809 drive_add(optarg, PFLASH_ALIAS);
4810 break;
4811 case QEMU_OPTION_snapshot:
4812 snapshot = 1;
4813 break;
4814 case QEMU_OPTION_hdachs:
4816 const char *p;
4817 p = optarg;
4818 cyls = strtol(p, (char **)&p, 0);
4819 if (cyls < 1 || cyls > 16383)
4820 goto chs_fail;
4821 if (*p != ',')
4822 goto chs_fail;
4823 p++;
4824 heads = strtol(p, (char **)&p, 0);
4825 if (heads < 1 || heads > 16)
4826 goto chs_fail;
4827 if (*p != ',')
4828 goto chs_fail;
4829 p++;
4830 secs = strtol(p, (char **)&p, 0);
4831 if (secs < 1 || secs > 63)
4832 goto chs_fail;
4833 if (*p == ',') {
4834 p++;
4835 if (!strcmp(p, "none"))
4836 translation = BIOS_ATA_TRANSLATION_NONE;
4837 else if (!strcmp(p, "lba"))
4838 translation = BIOS_ATA_TRANSLATION_LBA;
4839 else if (!strcmp(p, "auto"))
4840 translation = BIOS_ATA_TRANSLATION_AUTO;
4841 else
4842 goto chs_fail;
4843 } else if (*p != '\0') {
4844 chs_fail:
4845 fprintf(stderr, "qemu: invalid physical CHS format\n");
4846 exit(1);
4848 if (hda_index != -1)
4849 snprintf(drives_opt[hda_index].opt,
4850 sizeof(drives_opt[hda_index].opt),
4851 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4852 0, cyls, heads, secs,
4853 translation == BIOS_ATA_TRANSLATION_LBA ?
4854 ",trans=lba" :
4855 translation == BIOS_ATA_TRANSLATION_NONE ?
4856 ",trans=none" : "");
4858 break;
4859 case QEMU_OPTION_nographic:
4860 nographic = 1;
4861 break;
4862 #ifdef CONFIG_CURSES
4863 case QEMU_OPTION_curses:
4864 curses = 1;
4865 break;
4866 #endif
4867 case QEMU_OPTION_portrait:
4868 graphic_rotate = 1;
4869 break;
4870 case QEMU_OPTION_kernel:
4871 kernel_filename = optarg;
4872 break;
4873 case QEMU_OPTION_append:
4874 kernel_cmdline = optarg;
4875 break;
4876 case QEMU_OPTION_cdrom:
4877 drive_add(optarg, CDROM_ALIAS);
4878 break;
4879 case QEMU_OPTION_boot:
4880 boot_devices = optarg;
4881 /* We just do some generic consistency checks */
4883 /* Could easily be extended to 64 devices if needed */
4884 const char *p;
4886 boot_devices_bitmap = 0;
4887 for (p = boot_devices; *p != '\0'; p++) {
4888 /* Allowed boot devices are:
4889 * a b : floppy disk drives
4890 * c ... f : IDE disk drives
4891 * g ... m : machine implementation dependant drives
4892 * n ... p : network devices
4893 * It's up to each machine implementation to check
4894 * if the given boot devices match the actual hardware
4895 * implementation and firmware features.
4897 if (*p < 'a' || *p > 'q') {
4898 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4899 exit(1);
4901 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4902 fprintf(stderr,
4903 "Boot device '%c' was given twice\n",*p);
4904 exit(1);
4906 boot_devices_bitmap |= 1 << (*p - 'a');
4909 break;
4910 case QEMU_OPTION_fda:
4911 case QEMU_OPTION_fdb:
4912 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4913 break;
4914 #ifdef TARGET_I386
4915 case QEMU_OPTION_no_fd_bootchk:
4916 fd_bootchk = 0;
4917 break;
4918 #endif
4919 case QEMU_OPTION_net:
4920 if (nb_net_clients >= MAX_NET_CLIENTS) {
4921 fprintf(stderr, "qemu: too many network clients\n");
4922 exit(1);
4924 net_clients[nb_net_clients] = optarg;
4925 nb_net_clients++;
4926 break;
4927 #ifdef CONFIG_SLIRP
4928 case QEMU_OPTION_tftp:
4929 tftp_prefix = optarg;
4930 break;
4931 case QEMU_OPTION_bootp:
4932 bootp_filename = optarg;
4933 break;
4934 #ifndef _WIN32
4935 case QEMU_OPTION_smb:
4936 net_slirp_smb(optarg);
4937 break;
4938 #endif
4939 case QEMU_OPTION_redir:
4940 net_slirp_redir(optarg);
4941 break;
4942 #endif
4943 case QEMU_OPTION_bt:
4944 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4945 fprintf(stderr, "qemu: too many bluetooth options\n");
4946 exit(1);
4948 bt_opts[nb_bt_opts++] = optarg;
4949 break;
4950 #ifdef HAS_AUDIO
4951 case QEMU_OPTION_audio_help:
4952 AUD_help ();
4953 exit (0);
4954 break;
4955 case QEMU_OPTION_soundhw:
4956 select_soundhw (optarg);
4957 break;
4958 #endif
4959 case QEMU_OPTION_h:
4960 help(0);
4961 break;
4962 case QEMU_OPTION_m: {
4963 uint64_t value;
4964 char *ptr;
4966 value = strtoul(optarg, &ptr, 10);
4967 switch (*ptr) {
4968 case 0: case 'M': case 'm':
4969 value <<= 20;
4970 break;
4971 case 'G': case 'g':
4972 value <<= 30;
4973 break;
4974 default:
4975 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4976 exit(1);
4979 /* On 32-bit hosts, QEMU is limited by virtual address space */
4980 if (value > (2047 << 20)
4981 #ifndef USE_KQEMU
4982 && HOST_LONG_BITS == 32
4983 #endif
4985 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4986 exit(1);
4988 if (value != (uint64_t)(ram_addr_t)value) {
4989 fprintf(stderr, "qemu: ram size too large\n");
4990 exit(1);
4992 ram_size = value;
4993 break;
4995 case QEMU_OPTION_d:
4997 int mask;
4998 const CPULogItem *item;
5000 mask = cpu_str_to_log_mask(optarg);
5001 if (!mask) {
5002 printf("Log items (comma separated):\n");
5003 for(item = cpu_log_items; item->mask != 0; item++) {
5004 printf("%-10s %s\n", item->name, item->help);
5006 exit(1);
5008 cpu_set_log(mask);
5010 break;
5011 #ifdef CONFIG_GDBSTUB
5012 case QEMU_OPTION_s:
5013 use_gdbstub = 1;
5014 break;
5015 case QEMU_OPTION_p:
5016 gdbstub_port = optarg;
5017 break;
5018 #endif
5019 case QEMU_OPTION_L:
5020 bios_dir = optarg;
5021 break;
5022 case QEMU_OPTION_bios:
5023 bios_name = optarg;
5024 break;
5025 case QEMU_OPTION_S:
5026 autostart = 0;
5027 break;
5028 case QEMU_OPTION_k:
5029 keyboard_layout = optarg;
5030 break;
5031 case QEMU_OPTION_localtime:
5032 rtc_utc = 0;
5033 break;
5034 case QEMU_OPTION_vga:
5035 select_vgahw (optarg);
5036 break;
5037 case QEMU_OPTION_g:
5039 const char *p;
5040 int w, h, depth;
5041 p = optarg;
5042 w = strtol(p, (char **)&p, 10);
5043 if (w <= 0) {
5044 graphic_error:
5045 fprintf(stderr, "qemu: invalid resolution or depth\n");
5046 exit(1);
5048 if (*p != 'x')
5049 goto graphic_error;
5050 p++;
5051 h = strtol(p, (char **)&p, 10);
5052 if (h <= 0)
5053 goto graphic_error;
5054 if (*p == 'x') {
5055 p++;
5056 depth = strtol(p, (char **)&p, 10);
5057 if (depth != 8 && depth != 15 && depth != 16 &&
5058 depth != 24 && depth != 32)
5059 goto graphic_error;
5060 } else if (*p == '\0') {
5061 depth = graphic_depth;
5062 } else {
5063 goto graphic_error;
5066 graphic_width = w;
5067 graphic_height = h;
5068 graphic_depth = depth;
5070 break;
5071 case QEMU_OPTION_echr:
5073 char *r;
5074 term_escape_char = strtol(optarg, &r, 0);
5075 if (r == optarg)
5076 printf("Bad argument to echr\n");
5077 break;
5079 case QEMU_OPTION_monitor:
5080 monitor_device = optarg;
5081 break;
5082 case QEMU_OPTION_serial:
5083 if (serial_device_index >= MAX_SERIAL_PORTS) {
5084 fprintf(stderr, "qemu: too many serial ports\n");
5085 exit(1);
5087 serial_devices[serial_device_index] = optarg;
5088 serial_device_index++;
5089 break;
5090 case QEMU_OPTION_virtiocon:
5091 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5092 fprintf(stderr, "qemu: too many virtio consoles\n");
5093 exit(1);
5095 virtio_consoles[virtio_console_index] = optarg;
5096 virtio_console_index++;
5097 break;
5098 case QEMU_OPTION_parallel:
5099 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5100 fprintf(stderr, "qemu: too many parallel ports\n");
5101 exit(1);
5103 parallel_devices[parallel_device_index] = optarg;
5104 parallel_device_index++;
5105 break;
5106 case QEMU_OPTION_loadvm:
5107 loadvm = optarg;
5108 break;
5109 case QEMU_OPTION_full_screen:
5110 full_screen = 1;
5111 break;
5112 #ifdef CONFIG_SDL
5113 case QEMU_OPTION_no_frame:
5114 no_frame = 1;
5115 break;
5116 case QEMU_OPTION_alt_grab:
5117 alt_grab = 1;
5118 break;
5119 case QEMU_OPTION_no_quit:
5120 no_quit = 1;
5121 break;
5122 case QEMU_OPTION_sdl:
5123 sdl = 1;
5124 break;
5125 #endif
5126 case QEMU_OPTION_pidfile:
5127 pid_file = optarg;
5128 break;
5129 #ifdef TARGET_I386
5130 case QEMU_OPTION_win2k_hack:
5131 win2k_install_hack = 1;
5132 break;
5133 case QEMU_OPTION_rtc_td_hack:
5134 rtc_td_hack = 1;
5135 break;
5136 case QEMU_OPTION_acpitable:
5137 if(acpi_table_add(optarg) < 0) {
5138 fprintf(stderr, "Wrong acpi table provided\n");
5139 exit(1);
5141 break;
5142 #endif
5143 #ifdef USE_KQEMU
5144 case QEMU_OPTION_no_kqemu:
5145 kqemu_allowed = 0;
5146 break;
5147 case QEMU_OPTION_kernel_kqemu:
5148 kqemu_allowed = 2;
5149 break;
5150 #endif
5151 #ifdef CONFIG_KVM
5152 case QEMU_OPTION_enable_kvm:
5153 kvm_allowed = 1;
5154 #ifdef USE_KQEMU
5155 kqemu_allowed = 0;
5156 #endif
5157 break;
5158 #endif
5159 case QEMU_OPTION_usb:
5160 usb_enabled = 1;
5161 break;
5162 case QEMU_OPTION_usbdevice:
5163 usb_enabled = 1;
5164 if (usb_devices_index >= MAX_USB_CMDLINE) {
5165 fprintf(stderr, "Too many USB devices\n");
5166 exit(1);
5168 usb_devices[usb_devices_index] = optarg;
5169 usb_devices_index++;
5170 break;
5171 case QEMU_OPTION_smp:
5172 smp_cpus = atoi(optarg);
5173 if (smp_cpus < 1) {
5174 fprintf(stderr, "Invalid number of CPUs\n");
5175 exit(1);
5177 break;
5178 case QEMU_OPTION_vnc:
5179 vnc_display = optarg;
5180 break;
5181 case QEMU_OPTION_no_acpi:
5182 acpi_enabled = 0;
5183 break;
5184 case QEMU_OPTION_no_hpet:
5185 no_hpet = 1;
5186 break;
5187 case QEMU_OPTION_no_reboot:
5188 no_reboot = 1;
5189 break;
5190 case QEMU_OPTION_no_shutdown:
5191 no_shutdown = 1;
5192 break;
5193 case QEMU_OPTION_show_cursor:
5194 cursor_hide = 0;
5195 break;
5196 case QEMU_OPTION_uuid:
5197 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5198 fprintf(stderr, "Fail to parse UUID string."
5199 " Wrong format.\n");
5200 exit(1);
5202 break;
5203 case QEMU_OPTION_daemonize:
5204 daemonize = 1;
5205 break;
5206 case QEMU_OPTION_option_rom:
5207 if (nb_option_roms >= MAX_OPTION_ROMS) {
5208 fprintf(stderr, "Too many option ROMs\n");
5209 exit(1);
5211 option_rom[nb_option_roms] = optarg;
5212 nb_option_roms++;
5213 break;
5214 case QEMU_OPTION_semihosting:
5215 semihosting_enabled = 1;
5216 break;
5217 case QEMU_OPTION_name:
5218 qemu_name = optarg;
5219 break;
5220 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5221 case QEMU_OPTION_prom_env:
5222 if (nb_prom_envs >= MAX_PROM_ENVS) {
5223 fprintf(stderr, "Too many prom variables\n");
5224 exit(1);
5226 prom_envs[nb_prom_envs] = optarg;
5227 nb_prom_envs++;
5228 break;
5229 #endif
5230 #ifdef TARGET_ARM
5231 case QEMU_OPTION_old_param:
5232 old_param = 1;
5233 break;
5234 #endif
5235 case QEMU_OPTION_clock:
5236 configure_alarms(optarg);
5237 break;
5238 case QEMU_OPTION_startdate:
5240 struct tm tm;
5241 time_t rtc_start_date;
5242 if (!strcmp(optarg, "now")) {
5243 rtc_date_offset = -1;
5244 } else {
5245 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5246 &tm.tm_year,
5247 &tm.tm_mon,
5248 &tm.tm_mday,
5249 &tm.tm_hour,
5250 &tm.tm_min,
5251 &tm.tm_sec) == 6) {
5252 /* OK */
5253 } else if (sscanf(optarg, "%d-%d-%d",
5254 &tm.tm_year,
5255 &tm.tm_mon,
5256 &tm.tm_mday) == 3) {
5257 tm.tm_hour = 0;
5258 tm.tm_min = 0;
5259 tm.tm_sec = 0;
5260 } else {
5261 goto date_fail;
5263 tm.tm_year -= 1900;
5264 tm.tm_mon--;
5265 rtc_start_date = mktimegm(&tm);
5266 if (rtc_start_date == -1) {
5267 date_fail:
5268 fprintf(stderr, "Invalid date format. Valid format are:\n"
5269 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5270 exit(1);
5272 rtc_date_offset = time(NULL) - rtc_start_date;
5275 break;
5276 case QEMU_OPTION_tb_size:
5277 tb_size = strtol(optarg, NULL, 0);
5278 if (tb_size < 0)
5279 tb_size = 0;
5280 break;
5281 case QEMU_OPTION_icount:
5282 use_icount = 1;
5283 if (strcmp(optarg, "auto") == 0) {
5284 icount_time_shift = -1;
5285 } else {
5286 icount_time_shift = strtol(optarg, NULL, 0);
5288 break;
5289 case QEMU_OPTION_incoming:
5290 incoming = optarg;
5291 break;
5292 case QEMU_OPTION_chroot:
5293 chroot_dir = optarg;
5294 break;
5295 case QEMU_OPTION_runas:
5296 run_as = optarg;
5297 break;
5302 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5303 if (kvm_allowed && kqemu_allowed) {
5304 fprintf(stderr,
5305 "You can not enable both KVM and kqemu at the same time\n");
5306 exit(1);
5308 #endif
5310 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5311 if (smp_cpus > machine->max_cpus) {
5312 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5313 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5314 machine->max_cpus);
5315 exit(1);
5318 if (nographic) {
5319 if (serial_device_index == 0)
5320 serial_devices[0] = "stdio";
5321 if (parallel_device_index == 0)
5322 parallel_devices[0] = "null";
5323 if (strncmp(monitor_device, "vc", 2) == 0)
5324 monitor_device = "stdio";
5327 #ifndef _WIN32
5328 if (daemonize) {
5329 pid_t pid;
5331 if (pipe(fds) == -1)
5332 exit(1);
5334 pid = fork();
5335 if (pid > 0) {
5336 uint8_t status;
5337 ssize_t len;
5339 close(fds[1]);
5341 again:
5342 len = read(fds[0], &status, 1);
5343 if (len == -1 && (errno == EINTR))
5344 goto again;
5346 if (len != 1)
5347 exit(1);
5348 else if (status == 1) {
5349 fprintf(stderr, "Could not acquire pidfile\n");
5350 exit(1);
5351 } else
5352 exit(0);
5353 } else if (pid < 0)
5354 exit(1);
5356 setsid();
5358 pid = fork();
5359 if (pid > 0)
5360 exit(0);
5361 else if (pid < 0)
5362 exit(1);
5364 umask(027);
5366 signal(SIGTSTP, SIG_IGN);
5367 signal(SIGTTOU, SIG_IGN);
5368 signal(SIGTTIN, SIG_IGN);
5370 #endif
5372 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5373 if (daemonize) {
5374 uint8_t status = 1;
5375 write(fds[1], &status, 1);
5376 } else
5377 fprintf(stderr, "Could not acquire pid file\n");
5378 exit(1);
5381 #ifdef USE_KQEMU
5382 if (smp_cpus > 1)
5383 kqemu_allowed = 0;
5384 #endif
5385 linux_boot = (kernel_filename != NULL);
5386 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5388 if (!linux_boot && net_boot == 0 &&
5389 !machine->nodisk_ok && nb_drives_opt == 0)
5390 help(1);
5392 if (!linux_boot && *kernel_cmdline != '\0') {
5393 fprintf(stderr, "-append only allowed with -kernel option\n");
5394 exit(1);
5397 if (!linux_boot && initrd_filename != NULL) {
5398 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5399 exit(1);
5402 /* boot to floppy or the default cd if no hard disk defined yet */
5403 if (!boot_devices[0]) {
5404 boot_devices = "cad";
5406 setvbuf(stdout, NULL, _IOLBF, 0);
5408 init_timers();
5409 if (init_timer_alarm() < 0) {
5410 fprintf(stderr, "could not initialize alarm timer\n");
5411 exit(1);
5413 if (use_icount && icount_time_shift < 0) {
5414 use_icount = 2;
5415 /* 125MIPS seems a reasonable initial guess at the guest speed.
5416 It will be corrected fairly quickly anyway. */
5417 icount_time_shift = 3;
5418 init_icount_adjust();
5421 #ifdef _WIN32
5422 socket_init();
5423 #endif
5425 /* init network clients */
5426 if (nb_net_clients == 0) {
5427 /* if no clients, we use a default config */
5428 net_clients[nb_net_clients++] = "nic";
5429 #ifdef CONFIG_SLIRP
5430 net_clients[nb_net_clients++] = "user";
5431 #endif
5434 for(i = 0;i < nb_net_clients; i++) {
5435 if (net_client_parse(net_clients[i]) < 0)
5436 exit(1);
5438 net_client_check();
5440 #ifdef TARGET_I386
5441 /* XXX: this should be moved in the PC machine instantiation code */
5442 if (net_boot != 0) {
5443 int netroms = 0;
5444 for (i = 0; i < nb_nics && i < 4; i++) {
5445 const char *model = nd_table[i].model;
5446 char buf[1024];
5447 if (net_boot & (1 << i)) {
5448 if (model == NULL)
5449 model = "ne2k_pci";
5450 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5451 if (get_image_size(buf) > 0) {
5452 if (nb_option_roms >= MAX_OPTION_ROMS) {
5453 fprintf(stderr, "Too many option ROMs\n");
5454 exit(1);
5456 option_rom[nb_option_roms] = strdup(buf);
5457 nb_option_roms++;
5458 netroms++;
5462 if (netroms == 0) {
5463 fprintf(stderr, "No valid PXE rom found for network device\n");
5464 exit(1);
5467 #endif
5469 /* init the bluetooth world */
5470 for (i = 0; i < nb_bt_opts; i++)
5471 if (bt_parse(bt_opts[i]))
5472 exit(1);
5474 /* init the memory */
5475 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5477 if (machine->ram_require & RAMSIZE_FIXED) {
5478 if (ram_size > 0) {
5479 if (ram_size < phys_ram_size) {
5480 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5481 machine->name, (unsigned long long) phys_ram_size);
5482 exit(-1);
5485 phys_ram_size = ram_size;
5486 } else
5487 ram_size = phys_ram_size;
5488 } else {
5489 if (ram_size == 0)
5490 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5492 phys_ram_size += ram_size;
5495 phys_ram_base = qemu_vmalloc(phys_ram_size);
5496 if (!phys_ram_base) {
5497 fprintf(stderr, "Could not allocate physical memory\n");
5498 exit(1);
5501 /* init the dynamic translator */
5502 cpu_exec_init_all(tb_size * 1024 * 1024);
5504 bdrv_init();
5506 /* we always create the cdrom drive, even if no disk is there */
5508 if (nb_drives_opt < MAX_DRIVES)
5509 drive_add(NULL, CDROM_ALIAS);
5511 /* we always create at least one floppy */
5513 if (nb_drives_opt < MAX_DRIVES)
5514 drive_add(NULL, FD_ALIAS, 0);
5516 /* we always create one sd slot, even if no card is in it */
5518 if (nb_drives_opt < MAX_DRIVES)
5519 drive_add(NULL, SD_ALIAS);
5521 /* open the virtual block devices */
5523 for(i = 0; i < nb_drives_opt; i++)
5524 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5525 exit(1);
5527 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5528 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5530 #ifndef _WIN32
5531 /* must be after terminal init, SDL library changes signal handlers */
5532 termsig_setup();
5533 #endif
5535 /* Maintain compatibility with multiple stdio monitors */
5536 if (!strcmp(monitor_device,"stdio")) {
5537 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5538 const char *devname = serial_devices[i];
5539 if (devname && !strcmp(devname,"mon:stdio")) {
5540 monitor_device = NULL;
5541 break;
5542 } else if (devname && !strcmp(devname,"stdio")) {
5543 monitor_device = NULL;
5544 serial_devices[i] = "mon:stdio";
5545 break;
5550 if (kvm_enabled()) {
5551 int ret;
5553 ret = kvm_init(smp_cpus);
5554 if (ret < 0) {
5555 fprintf(stderr, "failed to initialize KVM\n");
5556 exit(1);
5560 if (monitor_device) {
5561 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5562 if (!monitor_hd) {
5563 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5564 exit(1);
5568 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5569 const char *devname = serial_devices[i];
5570 if (devname && strcmp(devname, "none")) {
5571 char label[32];
5572 snprintf(label, sizeof(label), "serial%d", i);
5573 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5574 if (!serial_hds[i]) {
5575 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5576 devname);
5577 exit(1);
5582 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5583 const char *devname = parallel_devices[i];
5584 if (devname && strcmp(devname, "none")) {
5585 char label[32];
5586 snprintf(label, sizeof(label), "parallel%d", i);
5587 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5588 if (!parallel_hds[i]) {
5589 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5590 devname);
5591 exit(1);
5596 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5597 const char *devname = virtio_consoles[i];
5598 if (devname && strcmp(devname, "none")) {
5599 char label[32];
5600 snprintf(label, sizeof(label), "virtcon%d", i);
5601 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5602 if (!virtcon_hds[i]) {
5603 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5604 devname);
5605 exit(1);
5610 machine->init(ram_size, vga_ram_size, boot_devices,
5611 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5613 current_machine = machine;
5615 /* Set KVM's vcpu state to qemu's initial CPUState. */
5616 if (kvm_enabled()) {
5617 int ret;
5619 ret = kvm_sync_vcpus();
5620 if (ret < 0) {
5621 fprintf(stderr, "failed to initialize vcpus\n");
5622 exit(1);
5626 /* init USB devices */
5627 if (usb_enabled) {
5628 for(i = 0; i < usb_devices_index; i++) {
5629 if (usb_device_add(usb_devices[i], 0) < 0) {
5630 fprintf(stderr, "Warning: could not add USB device %s\n",
5631 usb_devices[i]);
5636 if (!display_state)
5637 dumb_display_init();
5638 /* just use the first displaystate for the moment */
5639 ds = display_state;
5640 /* terminal init */
5641 if (nographic) {
5642 if (curses) {
5643 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5644 exit(1);
5646 } else {
5647 #if defined(CONFIG_CURSES)
5648 if (curses) {
5649 /* At the moment curses cannot be used with other displays */
5650 curses_display_init(ds, full_screen);
5651 } else
5652 #endif
5654 if (vnc_display != NULL) {
5655 vnc_display_init(ds);
5656 if (vnc_display_open(ds, vnc_display) < 0)
5657 exit(1);
5659 #if defined(CONFIG_SDL)
5660 if (sdl || !vnc_display)
5661 sdl_display_init(ds, full_screen, no_frame);
5662 #elif defined(CONFIG_COCOA)
5663 if (sdl || !vnc_display)
5664 cocoa_display_init(ds, full_screen);
5665 #endif
5668 dpy_resize(ds);
5670 dcl = ds->listeners;
5671 while (dcl != NULL) {
5672 if (dcl->dpy_refresh != NULL) {
5673 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5674 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5676 dcl = dcl->next;
5679 if (nographic || (vnc_display && !sdl)) {
5680 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5681 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5684 text_consoles_set_display(display_state);
5685 qemu_chr_initial_reset();
5687 if (monitor_device && monitor_hd)
5688 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5690 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5691 const char *devname = serial_devices[i];
5692 if (devname && strcmp(devname, "none")) {
5693 char label[32];
5694 snprintf(label, sizeof(label), "serial%d", i);
5695 if (strstart(devname, "vc", 0))
5696 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5700 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5701 const char *devname = parallel_devices[i];
5702 if (devname && strcmp(devname, "none")) {
5703 char label[32];
5704 snprintf(label, sizeof(label), "parallel%d", i);
5705 if (strstart(devname, "vc", 0))
5706 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5710 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5711 const char *devname = virtio_consoles[i];
5712 if (virtcon_hds[i] && devname) {
5713 char label[32];
5714 snprintf(label, sizeof(label), "virtcon%d", i);
5715 if (strstart(devname, "vc", 0))
5716 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5720 #ifdef CONFIG_GDBSTUB
5721 if (use_gdbstub) {
5722 /* XXX: use standard host:port notation and modify options
5723 accordingly. */
5724 if (gdbserver_start(gdbstub_port) < 0) {
5725 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5726 gdbstub_port);
5727 exit(1);
5730 #endif
5732 if (loadvm)
5733 do_loadvm(cur_mon, loadvm);
5735 if (incoming) {
5736 autostart = 0; /* fixme how to deal with -daemonize */
5737 qemu_start_incoming_migration(incoming);
5740 if (autostart)
5741 vm_start();
5743 if (daemonize) {
5744 uint8_t status = 0;
5745 ssize_t len;
5747 again1:
5748 len = write(fds[1], &status, 1);
5749 if (len == -1 && (errno == EINTR))
5750 goto again1;
5752 if (len != 1)
5753 exit(1);
5755 chdir("/");
5756 TFR(fd = open("/dev/null", O_RDWR));
5757 if (fd == -1)
5758 exit(1);
5761 #ifndef _WIN32
5762 if (run_as) {
5763 pwd = getpwnam(run_as);
5764 if (!pwd) {
5765 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5766 exit(1);
5770 if (chroot_dir) {
5771 if (chroot(chroot_dir) < 0) {
5772 fprintf(stderr, "chroot failed\n");
5773 exit(1);
5775 chdir("/");
5778 if (run_as) {
5779 if (setgid(pwd->pw_gid) < 0) {
5780 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5781 exit(1);
5783 if (setuid(pwd->pw_uid) < 0) {
5784 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5785 exit(1);
5787 if (setuid(0) != -1) {
5788 fprintf(stderr, "Dropping privileges failed\n");
5789 exit(1);
5792 #endif
5794 if (daemonize) {
5795 dup2(fd, 0);
5796 dup2(fd, 1);
5797 dup2(fd, 2);
5799 close(fd);
5802 main_loop();
5803 quit_timers();
5804 net_cleanup();
5806 return 0;