[MINI2440] Disable useless debug trace
[qemu/mini2440/sniper_sniper_test.git] / vl.c
blobb7417008ad35d4fa45b5c46025f0327502942fbb
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 HOST_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 HOST_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 <windows.h>
107 #include <malloc.h>
108 #include <sys/timeb.h>
109 #include <mmsystem.h>
110 #define getopt_long_only getopt_long
111 #define memalign(align, size) malloc(size)
112 #endif
114 #ifdef CONFIG_SDL
115 #ifdef __APPLE__
116 #include <SDL/SDL.h>
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 qemu_main(argc, argv, NULL);
122 #undef main
123 #define main qemu_main
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "hw/hw.h"
133 #include "hw/boards.h"
134 #include "hw/usb.h"
135 #include "hw/pcmcia.h"
136 #include "hw/pc.h"
137 #include "hw/audiodev.h"
138 #include "hw/isa.h"
139 #include "hw/baum.h"
140 #include "hw/bt.h"
141 #include "net.h"
142 #include "monitor.h"
143 #include "console.h"
144 #include "sysemu.h"
145 #include "gdbstub.h"
146 #include "qemu-timer.h"
147 #include "qemu-char.h"
148 #include "cache-utils.h"
149 #include "block.h"
150 #include "audio/audio.h"
151 #include "migration.h"
152 #include "kvm.h"
153 #include "balloon.h"
155 #include "disas.h"
157 #include "exec-all.h"
159 #include "qemu_socket.h"
161 #if defined(CONFIG_SLIRP)
162 #include "libslirp.h"
163 #endif
165 //#define DEBUG_UNUSED_IOPORT
166 //#define DEBUG_IOPORT
167 //#define DEBUG_NET
168 //#define DEBUG_SLIRP
171 #ifdef DEBUG_IOPORT
172 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
173 #else
174 # define LOG_IOPORT(...) do { } while (0)
175 #endif
177 #define DEFAULT_RAM_SIZE 128
179 /* Max number of USB devices that can be specified on the commandline. */
180 #define MAX_USB_CMDLINE 8
182 /* Max number of bluetooth switches on the commandline. */
183 #define MAX_BT_CMDLINE 10
185 /* XXX: use a two level table to limit memory usage */
186 #define MAX_IOPORTS 65536
188 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
189 const char *bios_name = NULL;
190 static void *ioport_opaque[MAX_IOPORTS];
191 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
192 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
193 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
194 to store the VM snapshots */
195 DriveInfo drives_table[MAX_DRIVES+1];
196 int nb_drives;
197 static int vga_ram_size;
198 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
199 static DisplayState *display_state;
200 int nographic;
201 static int curses;
202 static int sdl;
203 const char* keyboard_layout = NULL;
204 int64_t ticks_per_sec;
205 ram_addr_t ram_size;
206 int nb_nics;
207 NICInfo nd_table[MAX_NICS];
208 int vm_running;
209 static int autostart;
210 static int rtc_utc = 1;
211 static int rtc_date_offset = -1; /* -1 means no change */
212 int cirrus_vga_enabled = 1;
213 int std_vga_enabled = 0;
214 int vmsvga_enabled = 0;
215 #ifdef TARGET_SPARC
216 int graphic_width = 1024;
217 int graphic_height = 768;
218 int graphic_depth = 8;
219 #else
220 int graphic_width = 800;
221 int graphic_height = 600;
222 int graphic_depth = 15;
223 #endif
224 static int full_screen = 0;
225 #ifdef CONFIG_SDL
226 static int no_frame = 0;
227 #endif
228 int no_quit = 0;
229 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
230 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
231 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
232 #ifdef TARGET_I386
233 int win2k_install_hack = 0;
234 int rtc_td_hack = 0;
235 #endif
236 int usb_enabled = 0;
237 int smp_cpus = 1;
238 const char *vnc_display;
239 int acpi_enabled = 1;
240 int no_hpet = 0;
241 int fd_bootchk = 1;
242 int no_reboot = 0;
243 int no_shutdown = 0;
244 int cursor_hide = 1;
245 int graphic_rotate = 0;
246 int daemonize = 0;
247 const char *option_rom[MAX_OPTION_ROMS];
248 int nb_option_roms;
249 int semihosting_enabled = 0;
250 #ifdef TARGET_ARM
251 int old_param = 0;
252 #endif
253 const char *qemu_name;
254 int alt_grab = 0;
255 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
256 unsigned int nb_prom_envs = 0;
257 const char *prom_envs[MAX_PROM_ENVS];
258 #endif
259 int nb_drives_opt;
260 struct drive_opt drives_opt[MAX_DRIVES];
262 static CPUState *cur_cpu;
263 static CPUState *next_cpu;
264 static int event_pending = 1;
265 /* Conversion factor from emulated instructions to virtual clock ticks. */
266 static int icount_time_shift;
267 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
268 #define MAX_ICOUNT_SHIFT 10
269 /* Compensate for varying guest execution speed. */
270 static int64_t qemu_icount_bias;
271 static QEMUTimer *icount_rt_timer;
272 static QEMUTimer *icount_vm_timer;
273 static QEMUTimer *nographic_timer;
275 uint8_t qemu_uuid[16];
277 /***********************************************************/
278 /* x86 ISA bus support */
280 target_phys_addr_t isa_mem_base = 0;
281 PicState2 *isa_pic;
283 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
284 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
286 static uint32_t ioport_read(int index, uint32_t address)
288 static IOPortReadFunc *default_func[3] = {
289 default_ioport_readb,
290 default_ioport_readw,
291 default_ioport_readl
293 IOPortReadFunc *func = ioport_read_table[index][address];
294 if (!func)
295 func = default_func[index];
296 return func(ioport_opaque[address], address);
299 static void ioport_write(int index, uint32_t address, uint32_t data)
301 static IOPortWriteFunc *default_func[3] = {
302 default_ioport_writeb,
303 default_ioport_writew,
304 default_ioport_writel
306 IOPortWriteFunc *func = ioport_write_table[index][address];
307 if (!func)
308 func = default_func[index];
309 func(ioport_opaque[address], address, data);
312 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
314 #ifdef DEBUG_UNUSED_IOPORT
315 fprintf(stderr, "unused inb: port=0x%04x\n", address);
316 #endif
317 return 0xff;
320 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
322 #ifdef DEBUG_UNUSED_IOPORT
323 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
324 #endif
327 /* default is to make two byte accesses */
328 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
330 uint32_t data;
331 data = ioport_read(0, address);
332 address = (address + 1) & (MAX_IOPORTS - 1);
333 data |= ioport_read(0, address) << 8;
334 return data;
337 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
339 ioport_write(0, address, data & 0xff);
340 address = (address + 1) & (MAX_IOPORTS - 1);
341 ioport_write(0, address, (data >> 8) & 0xff);
344 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
346 #ifdef DEBUG_UNUSED_IOPORT
347 fprintf(stderr, "unused inl: port=0x%04x\n", address);
348 #endif
349 return 0xffffffff;
352 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
354 #ifdef DEBUG_UNUSED_IOPORT
355 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
356 #endif
359 /* size is the word size in byte */
360 int register_ioport_read(int start, int length, int size,
361 IOPortReadFunc *func, void *opaque)
363 int i, bsize;
365 if (size == 1) {
366 bsize = 0;
367 } else if (size == 2) {
368 bsize = 1;
369 } else if (size == 4) {
370 bsize = 2;
371 } else {
372 hw_error("register_ioport_read: invalid size");
373 return -1;
375 for(i = start; i < start + length; i += size) {
376 ioport_read_table[bsize][i] = func;
377 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
378 hw_error("register_ioport_read: invalid opaque");
379 ioport_opaque[i] = opaque;
381 return 0;
384 /* size is the word size in byte */
385 int register_ioport_write(int start, int length, int size,
386 IOPortWriteFunc *func, void *opaque)
388 int i, bsize;
390 if (size == 1) {
391 bsize = 0;
392 } else if (size == 2) {
393 bsize = 1;
394 } else if (size == 4) {
395 bsize = 2;
396 } else {
397 hw_error("register_ioport_write: invalid size");
398 return -1;
400 for(i = start; i < start + length; i += size) {
401 ioport_write_table[bsize][i] = func;
402 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
403 hw_error("register_ioport_write: invalid opaque");
404 ioport_opaque[i] = opaque;
406 return 0;
409 void isa_unassign_ioport(int start, int length)
411 int i;
413 for(i = start; i < start + length; i++) {
414 ioport_read_table[0][i] = default_ioport_readb;
415 ioport_read_table[1][i] = default_ioport_readw;
416 ioport_read_table[2][i] = default_ioport_readl;
418 ioport_write_table[0][i] = default_ioport_writeb;
419 ioport_write_table[1][i] = default_ioport_writew;
420 ioport_write_table[2][i] = default_ioport_writel;
422 ioport_opaque[i] = NULL;
426 /***********************************************************/
428 void cpu_outb(CPUState *env, int addr, int val)
430 LOG_IOPORT("outb: %04x %02x\n", addr, val);
431 ioport_write(0, addr, val);
432 #ifdef USE_KQEMU
433 if (env)
434 env->last_io_time = cpu_get_time_fast();
435 #endif
438 void cpu_outw(CPUState *env, int addr, int val)
440 LOG_IOPORT("outw: %04x %04x\n", addr, val);
441 ioport_write(1, addr, val);
442 #ifdef USE_KQEMU
443 if (env)
444 env->last_io_time = cpu_get_time_fast();
445 #endif
448 void cpu_outl(CPUState *env, int addr, int val)
450 LOG_IOPORT("outl: %04x %08x\n", addr, val);
451 ioport_write(2, addr, val);
452 #ifdef USE_KQEMU
453 if (env)
454 env->last_io_time = cpu_get_time_fast();
455 #endif
458 int cpu_inb(CPUState *env, int addr)
460 int val;
461 val = ioport_read(0, addr);
462 LOG_IOPORT("inb : %04x %02x\n", addr, val);
463 #ifdef USE_KQEMU
464 if (env)
465 env->last_io_time = cpu_get_time_fast();
466 #endif
467 return val;
470 int cpu_inw(CPUState *env, int addr)
472 int val;
473 val = ioport_read(1, addr);
474 LOG_IOPORT("inw : %04x %04x\n", addr, val);
475 #ifdef USE_KQEMU
476 if (env)
477 env->last_io_time = cpu_get_time_fast();
478 #endif
479 return val;
482 int cpu_inl(CPUState *env, int addr)
484 int val;
485 val = ioport_read(2, addr);
486 LOG_IOPORT("inl : %04x %08x\n", addr, val);
487 #ifdef USE_KQEMU
488 if (env)
489 env->last_io_time = cpu_get_time_fast();
490 #endif
491 return val;
494 /***********************************************************/
495 void hw_error(const char *fmt, ...)
497 va_list ap;
498 CPUState *env;
500 va_start(ap, fmt);
501 fprintf(stderr, "qemu: hardware error: ");
502 vfprintf(stderr, fmt, ap);
503 fprintf(stderr, "\n");
504 for(env = first_cpu; env != NULL; env = env->next_cpu) {
505 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
506 #ifdef TARGET_I386
507 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
508 #else
509 cpu_dump_state(env, stderr, fprintf, 0);
510 #endif
512 va_end(ap);
513 abort();
516 /***************/
517 /* ballooning */
519 static QEMUBalloonEvent *qemu_balloon_event;
520 void *qemu_balloon_event_opaque;
522 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
524 qemu_balloon_event = func;
525 qemu_balloon_event_opaque = opaque;
528 void qemu_balloon(ram_addr_t target)
530 if (qemu_balloon_event)
531 qemu_balloon_event(qemu_balloon_event_opaque, target);
534 ram_addr_t qemu_balloon_status(void)
536 if (qemu_balloon_event)
537 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
538 return 0;
541 /***********************************************************/
542 /* keyboard/mouse */
544 static QEMUPutKBDEvent *qemu_put_kbd_event;
545 static void *qemu_put_kbd_event_opaque;
546 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
547 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
549 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
551 qemu_put_kbd_event_opaque = opaque;
552 qemu_put_kbd_event = func;
555 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
556 void *opaque, int absolute,
557 const char *name)
559 QEMUPutMouseEntry *s, *cursor;
561 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
563 s->qemu_put_mouse_event = func;
564 s->qemu_put_mouse_event_opaque = opaque;
565 s->qemu_put_mouse_event_absolute = absolute;
566 s->qemu_put_mouse_event_name = qemu_strdup(name);
567 s->next = NULL;
569 if (!qemu_put_mouse_event_head) {
570 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
571 return s;
574 cursor = qemu_put_mouse_event_head;
575 while (cursor->next != NULL)
576 cursor = cursor->next;
578 cursor->next = s;
579 qemu_put_mouse_event_current = s;
581 return s;
584 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
586 QEMUPutMouseEntry *prev = NULL, *cursor;
588 if (!qemu_put_mouse_event_head || entry == NULL)
589 return;
591 cursor = qemu_put_mouse_event_head;
592 while (cursor != NULL && cursor != entry) {
593 prev = cursor;
594 cursor = cursor->next;
597 if (cursor == NULL) // does not exist or list empty
598 return;
599 else if (prev == NULL) { // entry is head
600 qemu_put_mouse_event_head = cursor->next;
601 if (qemu_put_mouse_event_current == entry)
602 qemu_put_mouse_event_current = cursor->next;
603 qemu_free(entry->qemu_put_mouse_event_name);
604 qemu_free(entry);
605 return;
608 prev->next = entry->next;
610 if (qemu_put_mouse_event_current == entry)
611 qemu_put_mouse_event_current = prev;
613 qemu_free(entry->qemu_put_mouse_event_name);
614 qemu_free(entry);
617 void kbd_put_keycode(int keycode)
619 if (qemu_put_kbd_event) {
620 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
624 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
626 QEMUPutMouseEvent *mouse_event;
627 void *mouse_event_opaque;
628 int width;
630 if (!qemu_put_mouse_event_current) {
631 return;
634 mouse_event =
635 qemu_put_mouse_event_current->qemu_put_mouse_event;
636 mouse_event_opaque =
637 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
639 if (mouse_event) {
640 if (graphic_rotate) {
641 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
642 width = 0x7fff;
643 else
644 width = graphic_width - 1;
645 mouse_event(mouse_event_opaque,
646 width - dy, dx, dz, buttons_state);
647 } else
648 mouse_event(mouse_event_opaque,
649 dx, dy, dz, buttons_state);
653 int kbd_mouse_is_absolute(void)
655 if (!qemu_put_mouse_event_current)
656 return 0;
658 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
661 void do_info_mice(Monitor *mon)
663 QEMUPutMouseEntry *cursor;
664 int index = 0;
666 if (!qemu_put_mouse_event_head) {
667 monitor_printf(mon, "No mouse devices connected\n");
668 return;
671 monitor_printf(mon, "Mouse devices available:\n");
672 cursor = qemu_put_mouse_event_head;
673 while (cursor != NULL) {
674 monitor_printf(mon, "%c Mouse #%d: %s\n",
675 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
676 index, cursor->qemu_put_mouse_event_name);
677 index++;
678 cursor = cursor->next;
682 void do_mouse_set(Monitor *mon, int index)
684 QEMUPutMouseEntry *cursor;
685 int i = 0;
687 if (!qemu_put_mouse_event_head) {
688 monitor_printf(mon, "No mouse devices connected\n");
689 return;
692 cursor = qemu_put_mouse_event_head;
693 while (cursor != NULL && index != i) {
694 i++;
695 cursor = cursor->next;
698 if (cursor != NULL)
699 qemu_put_mouse_event_current = cursor;
700 else
701 monitor_printf(mon, "Mouse at given index not found\n");
704 /* compute with 96 bit intermediate result: (a*b)/c */
705 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
707 union {
708 uint64_t ll;
709 struct {
710 #ifdef WORDS_BIGENDIAN
711 uint32_t high, low;
712 #else
713 uint32_t low, high;
714 #endif
715 } l;
716 } u, res;
717 uint64_t rl, rh;
719 u.ll = a;
720 rl = (uint64_t)u.l.low * (uint64_t)b;
721 rh = (uint64_t)u.l.high * (uint64_t)b;
722 rh += (rl >> 32);
723 res.l.high = rh / c;
724 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
725 return res.ll;
728 /***********************************************************/
729 /* real time host monotonic timer */
731 #define QEMU_TIMER_BASE 1000000000LL
733 #ifdef WIN32
735 static int64_t clock_freq;
737 static void init_get_clock(void)
739 LARGE_INTEGER freq;
740 int ret;
741 ret = QueryPerformanceFrequency(&freq);
742 if (ret == 0) {
743 fprintf(stderr, "Could not calibrate ticks\n");
744 exit(1);
746 clock_freq = freq.QuadPart;
749 static int64_t get_clock(void)
751 LARGE_INTEGER ti;
752 QueryPerformanceCounter(&ti);
753 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
756 #else
758 static int use_rt_clock;
760 static void init_get_clock(void)
762 use_rt_clock = 0;
763 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
764 || defined(__DragonFly__)
766 struct timespec ts;
767 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
768 use_rt_clock = 1;
771 #endif
774 static int64_t get_clock(void)
776 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
777 || defined(__DragonFly__)
778 if (use_rt_clock) {
779 struct timespec ts;
780 clock_gettime(CLOCK_MONOTONIC, &ts);
781 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
782 } else
783 #endif
785 /* XXX: using gettimeofday leads to problems if the date
786 changes, so it should be avoided. */
787 struct timeval tv;
788 gettimeofday(&tv, NULL);
789 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
792 #endif
794 /* Return the virtual CPU time, based on the instruction counter. */
795 static int64_t cpu_get_icount(void)
797 int64_t icount;
798 CPUState *env = cpu_single_env;;
799 icount = qemu_icount;
800 if (env) {
801 if (!can_do_io(env))
802 fprintf(stderr, "Bad clock read\n");
803 icount -= (env->icount_decr.u16.low + env->icount_extra);
805 return qemu_icount_bias + (icount << icount_time_shift);
808 /***********************************************************/
809 /* guest cycle counter */
811 static int64_t cpu_ticks_prev;
812 static int64_t cpu_ticks_offset;
813 static int64_t cpu_clock_offset;
814 static int cpu_ticks_enabled;
816 /* return the host CPU cycle counter and handle stop/restart */
817 int64_t cpu_get_ticks(void)
819 if (use_icount) {
820 return cpu_get_icount();
822 if (!cpu_ticks_enabled) {
823 return cpu_ticks_offset;
824 } else {
825 int64_t ticks;
826 ticks = cpu_get_real_ticks();
827 if (cpu_ticks_prev > ticks) {
828 /* Note: non increasing ticks may happen if the host uses
829 software suspend */
830 cpu_ticks_offset += cpu_ticks_prev - ticks;
832 cpu_ticks_prev = ticks;
833 return ticks + cpu_ticks_offset;
837 /* return the host CPU monotonic timer and handle stop/restart */
838 static int64_t cpu_get_clock(void)
840 int64_t ti;
841 if (!cpu_ticks_enabled) {
842 return cpu_clock_offset;
843 } else {
844 ti = get_clock();
845 return ti + cpu_clock_offset;
849 /* enable cpu_get_ticks() */
850 void cpu_enable_ticks(void)
852 if (!cpu_ticks_enabled) {
853 cpu_ticks_offset -= cpu_get_real_ticks();
854 cpu_clock_offset -= get_clock();
855 cpu_ticks_enabled = 1;
859 /* disable cpu_get_ticks() : the clock is stopped. You must not call
860 cpu_get_ticks() after that. */
861 void cpu_disable_ticks(void)
863 if (cpu_ticks_enabled) {
864 cpu_ticks_offset = cpu_get_ticks();
865 cpu_clock_offset = cpu_get_clock();
866 cpu_ticks_enabled = 0;
870 /***********************************************************/
871 /* timers */
873 #define QEMU_TIMER_REALTIME 0
874 #define QEMU_TIMER_VIRTUAL 1
876 struct QEMUClock {
877 int type;
878 /* XXX: add frequency */
881 struct QEMUTimer {
882 QEMUClock *clock;
883 int64_t expire_time;
884 QEMUTimerCB *cb;
885 void *opaque;
886 struct QEMUTimer *next;
889 struct qemu_alarm_timer {
890 char const *name;
891 unsigned int flags;
893 int (*start)(struct qemu_alarm_timer *t);
894 void (*stop)(struct qemu_alarm_timer *t);
895 void (*rearm)(struct qemu_alarm_timer *t);
896 void *priv;
899 #define ALARM_FLAG_DYNTICKS 0x1
900 #define ALARM_FLAG_EXPIRED 0x2
902 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
904 return t->flags & ALARM_FLAG_DYNTICKS;
907 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
909 if (!alarm_has_dynticks(t))
910 return;
912 t->rearm(t);
915 /* TODO: MIN_TIMER_REARM_US should be optimized */
916 #define MIN_TIMER_REARM_US 250
918 static struct qemu_alarm_timer *alarm_timer;
919 #ifndef _WIN32
920 static int alarm_timer_rfd, alarm_timer_wfd;
921 #endif
923 #ifdef _WIN32
925 struct qemu_alarm_win32 {
926 MMRESULT timerId;
927 HANDLE host_alarm;
928 unsigned int period;
929 } alarm_win32_data = {0, NULL, -1};
931 static int win32_start_timer(struct qemu_alarm_timer *t);
932 static void win32_stop_timer(struct qemu_alarm_timer *t);
933 static void win32_rearm_timer(struct qemu_alarm_timer *t);
935 #else
937 static int unix_start_timer(struct qemu_alarm_timer *t);
938 static void unix_stop_timer(struct qemu_alarm_timer *t);
940 #ifdef __linux__
942 static int dynticks_start_timer(struct qemu_alarm_timer *t);
943 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
944 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
946 static int hpet_start_timer(struct qemu_alarm_timer *t);
947 static void hpet_stop_timer(struct qemu_alarm_timer *t);
949 static int rtc_start_timer(struct qemu_alarm_timer *t);
950 static void rtc_stop_timer(struct qemu_alarm_timer *t);
952 #endif /* __linux__ */
954 #endif /* _WIN32 */
956 /* Correlation between real and virtual time is always going to be
957 fairly approximate, so ignore small variation.
958 When the guest is idle real and virtual time will be aligned in
959 the IO wait loop. */
960 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
962 static void icount_adjust(void)
964 int64_t cur_time;
965 int64_t cur_icount;
966 int64_t delta;
967 static int64_t last_delta;
968 /* If the VM is not running, then do nothing. */
969 if (!vm_running)
970 return;
972 cur_time = cpu_get_clock();
973 cur_icount = qemu_get_clock(vm_clock);
974 delta = cur_icount - cur_time;
975 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
976 if (delta > 0
977 && last_delta + ICOUNT_WOBBLE < delta * 2
978 && icount_time_shift > 0) {
979 /* The guest is getting too far ahead. Slow time down. */
980 icount_time_shift--;
982 if (delta < 0
983 && last_delta - ICOUNT_WOBBLE > delta * 2
984 && icount_time_shift < MAX_ICOUNT_SHIFT) {
985 /* The guest is getting too far behind. Speed time up. */
986 icount_time_shift++;
988 last_delta = delta;
989 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
992 static void icount_adjust_rt(void * opaque)
994 qemu_mod_timer(icount_rt_timer,
995 qemu_get_clock(rt_clock) + 1000);
996 icount_adjust();
999 static void icount_adjust_vm(void * opaque)
1001 qemu_mod_timer(icount_vm_timer,
1002 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1003 icount_adjust();
1006 static void init_icount_adjust(void)
1008 /* Have both realtime and virtual time triggers for speed adjustment.
1009 The realtime trigger catches emulated time passing too slowly,
1010 the virtual time trigger catches emulated time passing too fast.
1011 Realtime triggers occur even when idle, so use them less frequently
1012 than VM triggers. */
1013 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1014 qemu_mod_timer(icount_rt_timer,
1015 qemu_get_clock(rt_clock) + 1000);
1016 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1017 qemu_mod_timer(icount_vm_timer,
1018 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1021 static struct qemu_alarm_timer alarm_timers[] = {
1022 #ifndef _WIN32
1023 #ifdef __linux__
1024 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1025 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1026 /* HPET - if available - is preferred */
1027 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1028 /* ...otherwise try RTC */
1029 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1030 #endif
1031 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1032 #else
1033 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1034 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1035 {"win32", 0, win32_start_timer,
1036 win32_stop_timer, NULL, &alarm_win32_data},
1037 #endif
1038 {NULL, }
1041 static void show_available_alarms(void)
1043 int i;
1045 printf("Available alarm timers, in order of precedence:\n");
1046 for (i = 0; alarm_timers[i].name; i++)
1047 printf("%s\n", alarm_timers[i].name);
1050 static void configure_alarms(char const *opt)
1052 int i;
1053 int cur = 0;
1054 int count = ARRAY_SIZE(alarm_timers) - 1;
1055 char *arg;
1056 char *name;
1057 struct qemu_alarm_timer tmp;
1059 if (!strcmp(opt, "?")) {
1060 show_available_alarms();
1061 exit(0);
1064 arg = strdup(opt);
1066 /* Reorder the array */
1067 name = strtok(arg, ",");
1068 while (name) {
1069 for (i = 0; i < count && alarm_timers[i].name; i++) {
1070 if (!strcmp(alarm_timers[i].name, name))
1071 break;
1074 if (i == count) {
1075 fprintf(stderr, "Unknown clock %s\n", name);
1076 goto next;
1079 if (i < cur)
1080 /* Ignore */
1081 goto next;
1083 /* Swap */
1084 tmp = alarm_timers[i];
1085 alarm_timers[i] = alarm_timers[cur];
1086 alarm_timers[cur] = tmp;
1088 cur++;
1089 next:
1090 name = strtok(NULL, ",");
1093 free(arg);
1095 if (cur) {
1096 /* Disable remaining timers */
1097 for (i = cur; i < count; i++)
1098 alarm_timers[i].name = NULL;
1099 } else {
1100 show_available_alarms();
1101 exit(1);
1105 QEMUClock *rt_clock;
1106 QEMUClock *vm_clock;
1108 static QEMUTimer *active_timers[2];
1110 static QEMUClock *qemu_new_clock(int type)
1112 QEMUClock *clock;
1113 clock = qemu_mallocz(sizeof(QEMUClock));
1114 clock->type = type;
1115 return clock;
1118 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1120 QEMUTimer *ts;
1122 ts = qemu_mallocz(sizeof(QEMUTimer));
1123 ts->clock = clock;
1124 ts->cb = cb;
1125 ts->opaque = opaque;
1126 return ts;
1129 void qemu_free_timer(QEMUTimer *ts)
1131 qemu_free(ts);
1134 /* stop a timer, but do not dealloc it */
1135 void qemu_del_timer(QEMUTimer *ts)
1137 QEMUTimer **pt, *t;
1139 /* NOTE: this code must be signal safe because
1140 qemu_timer_expired() can be called from a signal. */
1141 pt = &active_timers[ts->clock->type];
1142 for(;;) {
1143 t = *pt;
1144 if (!t)
1145 break;
1146 if (t == ts) {
1147 *pt = t->next;
1148 break;
1150 pt = &t->next;
1154 /* modify the current timer so that it will be fired when current_time
1155 >= expire_time. The corresponding callback will be called. */
1156 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1158 QEMUTimer **pt, *t;
1160 qemu_del_timer(ts);
1162 /* add the timer in the sorted list */
1163 /* NOTE: this code must be signal safe because
1164 qemu_timer_expired() can be called from a signal. */
1165 pt = &active_timers[ts->clock->type];
1166 for(;;) {
1167 t = *pt;
1168 if (!t)
1169 break;
1170 if (t->expire_time > expire_time)
1171 break;
1172 pt = &t->next;
1174 ts->expire_time = expire_time;
1175 ts->next = *pt;
1176 *pt = ts;
1178 /* Rearm if necessary */
1179 if (pt == &active_timers[ts->clock->type]) {
1180 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1181 qemu_rearm_alarm_timer(alarm_timer);
1183 /* Interrupt execution to force deadline recalculation. */
1184 if (use_icount && cpu_single_env) {
1185 cpu_exit(cpu_single_env);
1190 int qemu_timer_pending(QEMUTimer *ts)
1192 QEMUTimer *t;
1193 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1194 if (t == ts)
1195 return 1;
1197 return 0;
1200 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1202 if (!timer_head)
1203 return 0;
1204 return (timer_head->expire_time <= current_time);
1207 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1209 QEMUTimer *ts;
1211 for(;;) {
1212 ts = *ptimer_head;
1213 if (!ts || ts->expire_time > current_time)
1214 break;
1215 /* remove timer from the list before calling the callback */
1216 *ptimer_head = ts->next;
1217 ts->next = NULL;
1219 /* run the callback (the timer list can be modified) */
1220 ts->cb(ts->opaque);
1224 int64_t qemu_get_clock(QEMUClock *clock)
1226 switch(clock->type) {
1227 case QEMU_TIMER_REALTIME:
1228 return get_clock() / 1000000;
1229 default:
1230 case QEMU_TIMER_VIRTUAL:
1231 if (use_icount) {
1232 return cpu_get_icount();
1233 } else {
1234 return cpu_get_clock();
1239 static void init_timers(void)
1241 init_get_clock();
1242 ticks_per_sec = QEMU_TIMER_BASE;
1243 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1244 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1247 /* save a timer */
1248 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1250 uint64_t expire_time;
1252 if (qemu_timer_pending(ts)) {
1253 expire_time = ts->expire_time;
1254 } else {
1255 expire_time = -1;
1257 qemu_put_be64(f, expire_time);
1260 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1262 uint64_t expire_time;
1264 expire_time = qemu_get_be64(f);
1265 if (expire_time != -1) {
1266 qemu_mod_timer(ts, expire_time);
1267 } else {
1268 qemu_del_timer(ts);
1272 static void timer_save(QEMUFile *f, void *opaque)
1274 if (cpu_ticks_enabled) {
1275 hw_error("cannot save state if virtual timers are running");
1277 qemu_put_be64(f, cpu_ticks_offset);
1278 qemu_put_be64(f, ticks_per_sec);
1279 qemu_put_be64(f, cpu_clock_offset);
1282 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1284 if (version_id != 1 && version_id != 2)
1285 return -EINVAL;
1286 if (cpu_ticks_enabled) {
1287 return -EINVAL;
1289 cpu_ticks_offset=qemu_get_be64(f);
1290 ticks_per_sec=qemu_get_be64(f);
1291 if (version_id == 2) {
1292 cpu_clock_offset=qemu_get_be64(f);
1294 return 0;
1297 #ifdef _WIN32
1298 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1299 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1300 #else
1301 static void host_alarm_handler(int host_signum)
1302 #endif
1304 #if 0
1305 #define DISP_FREQ 1000
1307 static int64_t delta_min = INT64_MAX;
1308 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1309 static int count;
1310 ti = qemu_get_clock(vm_clock);
1311 if (last_clock != 0) {
1312 delta = ti - last_clock;
1313 if (delta < delta_min)
1314 delta_min = delta;
1315 if (delta > delta_max)
1316 delta_max = delta;
1317 delta_cum += delta;
1318 if (++count == DISP_FREQ) {
1319 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1320 muldiv64(delta_min, 1000000, ticks_per_sec),
1321 muldiv64(delta_max, 1000000, ticks_per_sec),
1322 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1323 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1324 count = 0;
1325 delta_min = INT64_MAX;
1326 delta_max = 0;
1327 delta_cum = 0;
1330 last_clock = ti;
1332 #endif
1333 if (alarm_has_dynticks(alarm_timer) ||
1334 (!use_icount &&
1335 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1336 qemu_get_clock(vm_clock))) ||
1337 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1338 qemu_get_clock(rt_clock))) {
1339 CPUState *env = next_cpu;
1341 #ifdef _WIN32
1342 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1343 SetEvent(data->host_alarm);
1344 #else
1345 static const char byte = 0;
1346 write(alarm_timer_wfd, &byte, sizeof(byte));
1347 #endif
1348 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1350 if (env) {
1351 /* stop the currently executing cpu because a timer occured */
1352 cpu_exit(env);
1353 #ifdef USE_KQEMU
1354 if (env->kqemu_enabled) {
1355 kqemu_cpu_interrupt(env);
1357 #endif
1359 event_pending = 1;
1363 static int64_t qemu_next_deadline(void)
1365 int64_t delta;
1367 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1368 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1369 qemu_get_clock(vm_clock);
1370 } else {
1371 /* To avoid problems with overflow limit this to 2^32. */
1372 delta = INT32_MAX;
1375 if (delta < 0)
1376 delta = 0;
1378 return delta;
1381 #if defined(__linux__) || defined(_WIN32)
1382 static uint64_t qemu_next_deadline_dyntick(void)
1384 int64_t delta;
1385 int64_t rtdelta;
1387 if (use_icount)
1388 delta = INT32_MAX;
1389 else
1390 delta = (qemu_next_deadline() + 999) / 1000;
1392 if (active_timers[QEMU_TIMER_REALTIME]) {
1393 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1394 qemu_get_clock(rt_clock))*1000;
1395 if (rtdelta < delta)
1396 delta = rtdelta;
1399 if (delta < MIN_TIMER_REARM_US)
1400 delta = MIN_TIMER_REARM_US;
1402 return delta;
1404 #endif
1406 #ifndef _WIN32
1408 /* Sets a specific flag */
1409 static int fcntl_setfl(int fd, int flag)
1411 int flags;
1413 flags = fcntl(fd, F_GETFL);
1414 if (flags == -1)
1415 return -errno;
1417 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1418 return -errno;
1420 return 0;
1423 #if defined(__linux__)
1425 #define RTC_FREQ 1024
1427 static void enable_sigio_timer(int fd)
1429 struct sigaction act;
1431 /* timer signal */
1432 sigfillset(&act.sa_mask);
1433 act.sa_flags = 0;
1434 act.sa_handler = host_alarm_handler;
1436 sigaction(SIGIO, &act, NULL);
1437 fcntl_setfl(fd, O_ASYNC);
1438 fcntl(fd, F_SETOWN, getpid());
1441 static int hpet_start_timer(struct qemu_alarm_timer *t)
1443 struct hpet_info info;
1444 int r, fd;
1446 fd = open("/dev/hpet", O_RDONLY);
1447 if (fd < 0)
1448 return -1;
1450 /* Set frequency */
1451 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1452 if (r < 0) {
1453 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1454 "error, but for better emulation accuracy type:\n"
1455 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1456 goto fail;
1459 /* Check capabilities */
1460 r = ioctl(fd, HPET_INFO, &info);
1461 if (r < 0)
1462 goto fail;
1464 /* Enable periodic mode */
1465 r = ioctl(fd, HPET_EPI, 0);
1466 if (info.hi_flags && (r < 0))
1467 goto fail;
1469 /* Enable interrupt */
1470 r = ioctl(fd, HPET_IE_ON, 0);
1471 if (r < 0)
1472 goto fail;
1474 enable_sigio_timer(fd);
1475 t->priv = (void *)(long)fd;
1477 return 0;
1478 fail:
1479 close(fd);
1480 return -1;
1483 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1485 int fd = (long)t->priv;
1487 close(fd);
1490 static int rtc_start_timer(struct qemu_alarm_timer *t)
1492 int rtc_fd;
1493 unsigned long current_rtc_freq = 0;
1495 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1496 if (rtc_fd < 0)
1497 return -1;
1498 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1499 if (current_rtc_freq != RTC_FREQ &&
1500 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1501 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1502 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1503 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1504 goto fail;
1506 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1507 fail:
1508 close(rtc_fd);
1509 return -1;
1512 enable_sigio_timer(rtc_fd);
1514 t->priv = (void *)(long)rtc_fd;
1516 return 0;
1519 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1521 int rtc_fd = (long)t->priv;
1523 close(rtc_fd);
1526 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1528 struct sigevent ev;
1529 timer_t host_timer;
1530 struct sigaction act;
1532 sigfillset(&act.sa_mask);
1533 act.sa_flags = 0;
1534 act.sa_handler = host_alarm_handler;
1536 sigaction(SIGALRM, &act, NULL);
1538 ev.sigev_value.sival_int = 0;
1539 ev.sigev_notify = SIGEV_SIGNAL;
1540 ev.sigev_signo = SIGALRM;
1542 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1543 perror("timer_create");
1545 /* disable dynticks */
1546 fprintf(stderr, "Dynamic Ticks disabled\n");
1548 return -1;
1551 t->priv = (void *)(long)host_timer;
1553 return 0;
1556 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1558 timer_t host_timer = (timer_t)(long)t->priv;
1560 timer_delete(host_timer);
1563 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1565 timer_t host_timer = (timer_t)(long)t->priv;
1566 struct itimerspec timeout;
1567 int64_t nearest_delta_us = INT64_MAX;
1568 int64_t current_us;
1570 if (!active_timers[QEMU_TIMER_REALTIME] &&
1571 !active_timers[QEMU_TIMER_VIRTUAL])
1572 return;
1574 nearest_delta_us = qemu_next_deadline_dyntick();
1576 /* check whether a timer is already running */
1577 if (timer_gettime(host_timer, &timeout)) {
1578 perror("gettime");
1579 fprintf(stderr, "Internal timer error: aborting\n");
1580 exit(1);
1582 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1583 if (current_us && current_us <= nearest_delta_us)
1584 return;
1586 timeout.it_interval.tv_sec = 0;
1587 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1588 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1589 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1590 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1591 perror("settime");
1592 fprintf(stderr, "Internal timer error: aborting\n");
1593 exit(1);
1597 #endif /* defined(__linux__) */
1599 static int unix_start_timer(struct qemu_alarm_timer *t)
1601 struct sigaction act;
1602 struct itimerval itv;
1603 int err;
1605 /* timer signal */
1606 sigfillset(&act.sa_mask);
1607 act.sa_flags = 0;
1608 act.sa_handler = host_alarm_handler;
1610 sigaction(SIGALRM, &act, NULL);
1612 itv.it_interval.tv_sec = 0;
1613 /* for i386 kernel 2.6 to get 1 ms */
1614 itv.it_interval.tv_usec = 999;
1615 itv.it_value.tv_sec = 0;
1616 itv.it_value.tv_usec = 10 * 1000;
1618 err = setitimer(ITIMER_REAL, &itv, NULL);
1619 if (err)
1620 return -1;
1622 return 0;
1625 static void unix_stop_timer(struct qemu_alarm_timer *t)
1627 struct itimerval itv;
1629 memset(&itv, 0, sizeof(itv));
1630 setitimer(ITIMER_REAL, &itv, NULL);
1633 #endif /* !defined(_WIN32) */
1635 static void try_to_rearm_timer(void *opaque)
1637 struct qemu_alarm_timer *t = opaque;
1638 #ifndef _WIN32
1639 ssize_t len;
1641 /* Drain the notify pipe */
1642 do {
1643 char buffer[512];
1644 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1645 } while ((len == -1 && errno == EINTR) || len > 0);
1646 #endif
1648 if (t->flags & ALARM_FLAG_EXPIRED) {
1649 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1650 qemu_rearm_alarm_timer(alarm_timer);
1654 #ifdef _WIN32
1656 static int win32_start_timer(struct qemu_alarm_timer *t)
1658 TIMECAPS tc;
1659 struct qemu_alarm_win32 *data = t->priv;
1660 UINT flags;
1662 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1663 if (!data->host_alarm) {
1664 perror("Failed CreateEvent");
1665 return -1;
1668 memset(&tc, 0, sizeof(tc));
1669 timeGetDevCaps(&tc, sizeof(tc));
1671 if (data->period < tc.wPeriodMin)
1672 data->period = tc.wPeriodMin;
1674 timeBeginPeriod(data->period);
1676 flags = TIME_CALLBACK_FUNCTION;
1677 if (alarm_has_dynticks(t))
1678 flags |= TIME_ONESHOT;
1679 else
1680 flags |= TIME_PERIODIC;
1682 data->timerId = timeSetEvent(1, // interval (ms)
1683 data->period, // resolution
1684 host_alarm_handler, // function
1685 (DWORD)t, // parameter
1686 flags);
1688 if (!data->timerId) {
1689 perror("Failed to initialize win32 alarm timer");
1691 timeEndPeriod(data->period);
1692 CloseHandle(data->host_alarm);
1693 return -1;
1696 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1698 return 0;
1701 static void win32_stop_timer(struct qemu_alarm_timer *t)
1703 struct qemu_alarm_win32 *data = t->priv;
1705 timeKillEvent(data->timerId);
1706 timeEndPeriod(data->period);
1708 CloseHandle(data->host_alarm);
1711 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1713 struct qemu_alarm_win32 *data = t->priv;
1714 uint64_t nearest_delta_us;
1716 if (!active_timers[QEMU_TIMER_REALTIME] &&
1717 !active_timers[QEMU_TIMER_VIRTUAL])
1718 return;
1720 nearest_delta_us = qemu_next_deadline_dyntick();
1721 nearest_delta_us /= 1000;
1723 timeKillEvent(data->timerId);
1725 data->timerId = timeSetEvent(1,
1726 data->period,
1727 host_alarm_handler,
1728 (DWORD)t,
1729 TIME_ONESHOT | TIME_PERIODIC);
1731 if (!data->timerId) {
1732 perror("Failed to re-arm win32 alarm timer");
1734 timeEndPeriod(data->period);
1735 CloseHandle(data->host_alarm);
1736 exit(1);
1740 #endif /* _WIN32 */
1742 static int init_timer_alarm(void)
1744 struct qemu_alarm_timer *t = NULL;
1745 int i, err = -1;
1747 #ifndef _WIN32
1748 int fds[2];
1750 err = pipe(fds);
1751 if (err == -1)
1752 return -errno;
1754 err = fcntl_setfl(fds[0], O_NONBLOCK);
1755 if (err < 0)
1756 goto fail;
1758 err = fcntl_setfl(fds[1], O_NONBLOCK);
1759 if (err < 0)
1760 goto fail;
1762 alarm_timer_rfd = fds[0];
1763 alarm_timer_wfd = fds[1];
1764 #endif
1766 for (i = 0; alarm_timers[i].name; i++) {
1767 t = &alarm_timers[i];
1769 err = t->start(t);
1770 if (!err)
1771 break;
1774 if (err) {
1775 err = -ENOENT;
1776 goto fail;
1779 #ifndef _WIN32
1780 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1781 try_to_rearm_timer, NULL, t);
1782 #endif
1784 alarm_timer = t;
1786 return 0;
1788 fail:
1789 #ifndef _WIN32
1790 close(fds[0]);
1791 close(fds[1]);
1792 #endif
1793 return err;
1796 static void quit_timers(void)
1798 alarm_timer->stop(alarm_timer);
1799 alarm_timer = NULL;
1802 /***********************************************************/
1803 /* host time/date access */
1804 void qemu_get_timedate(struct tm *tm, int offset)
1806 time_t ti;
1807 struct tm *ret;
1809 time(&ti);
1810 ti += offset;
1811 if (rtc_date_offset == -1) {
1812 if (rtc_utc)
1813 ret = gmtime(&ti);
1814 else
1815 ret = localtime(&ti);
1816 } else {
1817 ti -= rtc_date_offset;
1818 ret = gmtime(&ti);
1821 memcpy(tm, ret, sizeof(struct tm));
1824 int qemu_timedate_diff(struct tm *tm)
1826 time_t seconds;
1828 if (rtc_date_offset == -1)
1829 if (rtc_utc)
1830 seconds = mktimegm(tm);
1831 else
1832 seconds = mktime(tm);
1833 else
1834 seconds = mktimegm(tm) + rtc_date_offset;
1836 return seconds - time(NULL);
1839 #ifdef _WIN32
1840 static void socket_cleanup(void)
1842 WSACleanup();
1845 static int socket_init(void)
1847 WSADATA Data;
1848 int ret, err;
1850 ret = WSAStartup(MAKEWORD(2,2), &Data);
1851 if (ret != 0) {
1852 err = WSAGetLastError();
1853 fprintf(stderr, "WSAStartup: %d\n", err);
1854 return -1;
1856 atexit(socket_cleanup);
1857 return 0;
1859 #endif
1861 const char *get_opt_name(char *buf, int buf_size, const char *p)
1863 char *q;
1865 q = buf;
1866 while (*p != '\0' && *p != '=') {
1867 if (q && (q - buf) < buf_size - 1)
1868 *q++ = *p;
1869 p++;
1871 if (q)
1872 *q = '\0';
1874 return p;
1877 const char *get_opt_value(char *buf, int buf_size, const char *p)
1879 char *q;
1881 q = buf;
1882 while (*p != '\0') {
1883 if (*p == ',') {
1884 if (*(p + 1) != ',')
1885 break;
1886 p++;
1888 if (q && (q - buf) < buf_size - 1)
1889 *q++ = *p;
1890 p++;
1892 if (q)
1893 *q = '\0';
1895 return p;
1898 int get_param_value(char *buf, int buf_size,
1899 const char *tag, const char *str)
1901 const char *p;
1902 char option[128];
1904 p = str;
1905 for(;;) {
1906 p = get_opt_name(option, sizeof(option), p);
1907 if (*p != '=')
1908 break;
1909 p++;
1910 if (!strcmp(tag, option)) {
1911 (void)get_opt_value(buf, buf_size, p);
1912 return strlen(buf);
1913 } else {
1914 p = get_opt_value(NULL, 0, p);
1916 if (*p != ',')
1917 break;
1918 p++;
1920 return 0;
1923 int check_params(char *buf, int buf_size,
1924 const char * const *params, const char *str)
1926 const char *p;
1927 int i;
1929 p = str;
1930 for(;;) {
1931 p = get_opt_name(buf, buf_size, p);
1932 if (*p != '=')
1933 return -1;
1934 p++;
1935 for(i = 0; params[i] != NULL; i++)
1936 if (!strcmp(params[i], buf))
1937 break;
1938 if (params[i] == NULL)
1939 return -1;
1940 p = get_opt_value(NULL, 0, p);
1941 if (*p != ',')
1942 break;
1943 p++;
1945 return 0;
1948 /***********************************************************/
1949 /* Bluetooth support */
1950 static int nb_hcis;
1951 static int cur_hci;
1952 static struct HCIInfo *hci_table[MAX_NICS];
1954 static struct bt_vlan_s {
1955 struct bt_scatternet_s net;
1956 int id;
1957 struct bt_vlan_s *next;
1958 } *first_bt_vlan;
1960 /* find or alloc a new bluetooth "VLAN" */
1961 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1963 struct bt_vlan_s **pvlan, *vlan;
1964 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1965 if (vlan->id == id)
1966 return &vlan->net;
1968 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1969 vlan->id = id;
1970 pvlan = &first_bt_vlan;
1971 while (*pvlan != NULL)
1972 pvlan = &(*pvlan)->next;
1973 *pvlan = vlan;
1974 return &vlan->net;
1977 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1981 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1983 return -ENOTSUP;
1986 static struct HCIInfo null_hci = {
1987 .cmd_send = null_hci_send,
1988 .sco_send = null_hci_send,
1989 .acl_send = null_hci_send,
1990 .bdaddr_set = null_hci_addr_set,
1993 struct HCIInfo *qemu_next_hci(void)
1995 if (cur_hci == nb_hcis)
1996 return &null_hci;
1998 return hci_table[cur_hci++];
2001 static struct HCIInfo *hci_init(const char *str)
2003 char *endp;
2004 struct bt_scatternet_s *vlan = 0;
2006 if (!strcmp(str, "null"))
2007 /* null */
2008 return &null_hci;
2009 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2010 /* host[:hciN] */
2011 return bt_host_hci(str[4] ? str + 5 : "hci0");
2012 else if (!strncmp(str, "hci", 3)) {
2013 /* hci[,vlan=n] */
2014 if (str[3]) {
2015 if (!strncmp(str + 3, ",vlan=", 6)) {
2016 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2017 if (*endp)
2018 vlan = 0;
2020 } else
2021 vlan = qemu_find_bt_vlan(0);
2022 if (vlan)
2023 return bt_new_hci(vlan);
2026 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2028 return 0;
2031 static int bt_hci_parse(const char *str)
2033 struct HCIInfo *hci;
2034 bdaddr_t bdaddr;
2036 if (nb_hcis >= MAX_NICS) {
2037 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2038 return -1;
2041 hci = hci_init(str);
2042 if (!hci)
2043 return -1;
2045 bdaddr.b[0] = 0x52;
2046 bdaddr.b[1] = 0x54;
2047 bdaddr.b[2] = 0x00;
2048 bdaddr.b[3] = 0x12;
2049 bdaddr.b[4] = 0x34;
2050 bdaddr.b[5] = 0x56 + nb_hcis;
2051 hci->bdaddr_set(hci, bdaddr.b);
2053 hci_table[nb_hcis++] = hci;
2055 return 0;
2058 static void bt_vhci_add(int vlan_id)
2060 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2062 if (!vlan->slave)
2063 fprintf(stderr, "qemu: warning: adding a VHCI to "
2064 "an empty scatternet %i\n", vlan_id);
2066 bt_vhci_init(bt_new_hci(vlan));
2069 static struct bt_device_s *bt_device_add(const char *opt)
2071 struct bt_scatternet_s *vlan;
2072 int vlan_id = 0;
2073 char *endp = strstr(opt, ",vlan=");
2074 int len = (endp ? endp - opt : strlen(opt)) + 1;
2075 char devname[10];
2077 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2079 if (endp) {
2080 vlan_id = strtol(endp + 6, &endp, 0);
2081 if (*endp) {
2082 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2083 return 0;
2087 vlan = qemu_find_bt_vlan(vlan_id);
2089 if (!vlan->slave)
2090 fprintf(stderr, "qemu: warning: adding a slave device to "
2091 "an empty scatternet %i\n", vlan_id);
2093 if (!strcmp(devname, "keyboard"))
2094 return bt_keyboard_init(vlan);
2096 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2097 return 0;
2100 static int bt_parse(const char *opt)
2102 const char *endp, *p;
2103 int vlan;
2105 if (strstart(opt, "hci", &endp)) {
2106 if (!*endp || *endp == ',') {
2107 if (*endp)
2108 if (!strstart(endp, ",vlan=", 0))
2109 opt = endp + 1;
2111 return bt_hci_parse(opt);
2113 } else if (strstart(opt, "vhci", &endp)) {
2114 if (!*endp || *endp == ',') {
2115 if (*endp) {
2116 if (strstart(endp, ",vlan=", &p)) {
2117 vlan = strtol(p, (char **) &endp, 0);
2118 if (*endp) {
2119 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2120 return 1;
2122 } else {
2123 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2124 return 1;
2126 } else
2127 vlan = 0;
2129 bt_vhci_add(vlan);
2130 return 0;
2132 } else if (strstart(opt, "device:", &endp))
2133 return !bt_device_add(endp);
2135 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2136 return 1;
2139 /***********************************************************/
2140 /* QEMU Block devices */
2142 #define HD_ALIAS "index=%d,media=disk"
2143 #define CDROM_ALIAS "index=2,media=cdrom"
2144 #define FD_ALIAS "index=%d,if=floppy"
2145 #define PFLASH_ALIAS "if=pflash"
2146 #define MTD_ALIAS "if=mtd"
2147 #define SD_ALIAS "index=0,if=sd"
2149 static int drive_opt_get_free_idx(void)
2151 int index;
2153 for (index = 0; index < MAX_DRIVES; index++)
2154 if (!drives_opt[index].used) {
2155 drives_opt[index].used = 1;
2156 return index;
2159 return -1;
2162 static int drive_get_free_idx(void)
2164 int index;
2166 for (index = 0; index < MAX_DRIVES; index++)
2167 if (!drives_table[index].used) {
2168 drives_table[index].used = 1;
2169 return index;
2172 return -1;
2175 int drive_add(const char *file, const char *fmt, ...)
2177 va_list ap;
2178 int index = drive_opt_get_free_idx();
2180 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2181 fprintf(stderr, "qemu: too many drives\n");
2182 return -1;
2185 drives_opt[index].file = file;
2186 va_start(ap, fmt);
2187 vsnprintf(drives_opt[index].opt,
2188 sizeof(drives_opt[0].opt), fmt, ap);
2189 va_end(ap);
2191 nb_drives_opt++;
2192 return index;
2195 void drive_remove(int index)
2197 drives_opt[index].used = 0;
2198 nb_drives_opt--;
2201 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2203 int index;
2205 /* seek interface, bus and unit */
2207 for (index = 0; index < MAX_DRIVES; index++)
2208 if (drives_table[index].type == type &&
2209 drives_table[index].bus == bus &&
2210 drives_table[index].unit == unit &&
2211 drives_table[index].used)
2212 return index;
2214 return -1;
2217 int drive_get_max_bus(BlockInterfaceType type)
2219 int max_bus;
2220 int index;
2222 max_bus = -1;
2223 for (index = 0; index < nb_drives; index++) {
2224 if(drives_table[index].type == type &&
2225 drives_table[index].bus > max_bus)
2226 max_bus = drives_table[index].bus;
2228 return max_bus;
2231 const char *drive_get_serial(BlockDriverState *bdrv)
2233 int index;
2235 for (index = 0; index < nb_drives; index++)
2236 if (drives_table[index].bdrv == bdrv)
2237 return drives_table[index].serial;
2239 return "\0";
2242 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2244 int index;
2246 for (index = 0; index < nb_drives; index++)
2247 if (drives_table[index].bdrv == bdrv)
2248 return drives_table[index].onerror;
2250 return BLOCK_ERR_STOP_ENOSPC;
2253 static void bdrv_format_print(void *opaque, const char *name)
2255 fprintf(stderr, " %s", name);
2258 void drive_uninit(BlockDriverState *bdrv)
2260 int i;
2262 for (i = 0; i < MAX_DRIVES; i++)
2263 if (drives_table[i].bdrv == bdrv) {
2264 drives_table[i].bdrv = NULL;
2265 drives_table[i].used = 0;
2266 drive_remove(drives_table[i].drive_opt_idx);
2267 nb_drives--;
2268 break;
2272 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2274 char buf[128];
2275 char file[1024];
2276 char devname[128];
2277 char serial[21];
2278 const char *mediastr = "";
2279 BlockInterfaceType type;
2280 enum { MEDIA_DISK, MEDIA_CDROM } media;
2281 int bus_id, unit_id;
2282 int cyls, heads, secs, translation;
2283 BlockDriverState *bdrv;
2284 BlockDriver *drv = NULL;
2285 QEMUMachine *machine = opaque;
2286 int max_devs;
2287 int index;
2288 int cache;
2289 int bdrv_flags, onerror;
2290 int drives_table_idx;
2291 char *str = arg->opt;
2292 static const char * const params[] = { "bus", "unit", "if", "index",
2293 "cyls", "heads", "secs", "trans",
2294 "media", "snapshot", "file",
2295 "cache", "format", "serial", "werror",
2296 NULL };
2298 if (check_params(buf, sizeof(buf), params, str) < 0) {
2299 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2300 buf, str);
2301 return -1;
2304 file[0] = 0;
2305 cyls = heads = secs = 0;
2306 bus_id = 0;
2307 unit_id = -1;
2308 translation = BIOS_ATA_TRANSLATION_AUTO;
2309 index = -1;
2310 cache = 3;
2312 if (machine->use_scsi) {
2313 type = IF_SCSI;
2314 max_devs = MAX_SCSI_DEVS;
2315 pstrcpy(devname, sizeof(devname), "scsi");
2316 } else {
2317 type = IF_IDE;
2318 max_devs = MAX_IDE_DEVS;
2319 pstrcpy(devname, sizeof(devname), "ide");
2321 media = MEDIA_DISK;
2323 /* extract parameters */
2325 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2326 bus_id = strtol(buf, NULL, 0);
2327 if (bus_id < 0) {
2328 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2329 return -1;
2333 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2334 unit_id = strtol(buf, NULL, 0);
2335 if (unit_id < 0) {
2336 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2337 return -1;
2341 if (get_param_value(buf, sizeof(buf), "if", str)) {
2342 pstrcpy(devname, sizeof(devname), buf);
2343 if (!strcmp(buf, "ide")) {
2344 type = IF_IDE;
2345 max_devs = MAX_IDE_DEVS;
2346 } else if (!strcmp(buf, "scsi")) {
2347 type = IF_SCSI;
2348 max_devs = MAX_SCSI_DEVS;
2349 } else if (!strcmp(buf, "floppy")) {
2350 type = IF_FLOPPY;
2351 max_devs = 0;
2352 } else if (!strcmp(buf, "pflash")) {
2353 type = IF_PFLASH;
2354 max_devs = 0;
2355 } else if (!strcmp(buf, "mtd")) {
2356 type = IF_MTD;
2357 max_devs = 0;
2358 } else if (!strcmp(buf, "sd")) {
2359 type = IF_SD;
2360 max_devs = 0;
2361 } else if (!strcmp(buf, "virtio")) {
2362 type = IF_VIRTIO;
2363 max_devs = 0;
2364 } else {
2365 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2366 return -1;
2370 if (get_param_value(buf, sizeof(buf), "index", str)) {
2371 index = strtol(buf, NULL, 0);
2372 if (index < 0) {
2373 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2374 return -1;
2378 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2379 cyls = strtol(buf, NULL, 0);
2382 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2383 heads = strtol(buf, NULL, 0);
2386 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2387 secs = strtol(buf, NULL, 0);
2390 if (cyls || heads || secs) {
2391 if (cyls < 1 || cyls > 16383) {
2392 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2393 return -1;
2395 if (heads < 1 || heads > 16) {
2396 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2397 return -1;
2399 if (secs < 1 || secs > 63) {
2400 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2401 return -1;
2405 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2406 if (!cyls) {
2407 fprintf(stderr,
2408 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2409 str);
2410 return -1;
2412 if (!strcmp(buf, "none"))
2413 translation = BIOS_ATA_TRANSLATION_NONE;
2414 else if (!strcmp(buf, "lba"))
2415 translation = BIOS_ATA_TRANSLATION_LBA;
2416 else if (!strcmp(buf, "auto"))
2417 translation = BIOS_ATA_TRANSLATION_AUTO;
2418 else {
2419 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2420 return -1;
2424 if (get_param_value(buf, sizeof(buf), "media", str)) {
2425 if (!strcmp(buf, "disk")) {
2426 media = MEDIA_DISK;
2427 } else if (!strcmp(buf, "cdrom")) {
2428 if (cyls || secs || heads) {
2429 fprintf(stderr,
2430 "qemu: '%s' invalid physical CHS format\n", str);
2431 return -1;
2433 media = MEDIA_CDROM;
2434 } else {
2435 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2436 return -1;
2440 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2441 if (!strcmp(buf, "on"))
2442 snapshot = 1;
2443 else if (!strcmp(buf, "off"))
2444 snapshot = 0;
2445 else {
2446 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2447 return -1;
2451 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2452 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2453 cache = 0;
2454 else if (!strcmp(buf, "writethrough"))
2455 cache = 1;
2456 else if (!strcmp(buf, "writeback"))
2457 cache = 2;
2458 else {
2459 fprintf(stderr, "qemu: invalid cache option\n");
2460 return -1;
2464 if (get_param_value(buf, sizeof(buf), "format", str)) {
2465 if (strcmp(buf, "?") == 0) {
2466 fprintf(stderr, "qemu: Supported formats:");
2467 bdrv_iterate_format(bdrv_format_print, NULL);
2468 fprintf(stderr, "\n");
2469 return -1;
2471 drv = bdrv_find_format(buf);
2472 if (!drv) {
2473 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2474 return -1;
2478 if (arg->file == NULL)
2479 get_param_value(file, sizeof(file), "file", str);
2480 else
2481 pstrcpy(file, sizeof(file), arg->file);
2483 if (!get_param_value(serial, sizeof(serial), "serial", str))
2484 memset(serial, 0, sizeof(serial));
2486 onerror = BLOCK_ERR_STOP_ENOSPC;
2487 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2488 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2489 fprintf(stderr, "werror is no supported by this format\n");
2490 return -1;
2492 if (!strcmp(buf, "ignore"))
2493 onerror = BLOCK_ERR_IGNORE;
2494 else if (!strcmp(buf, "enospc"))
2495 onerror = BLOCK_ERR_STOP_ENOSPC;
2496 else if (!strcmp(buf, "stop"))
2497 onerror = BLOCK_ERR_STOP_ANY;
2498 else if (!strcmp(buf, "report"))
2499 onerror = BLOCK_ERR_REPORT;
2500 else {
2501 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2502 return -1;
2506 /* compute bus and unit according index */
2508 if (index != -1) {
2509 if (bus_id != 0 || unit_id != -1) {
2510 fprintf(stderr,
2511 "qemu: '%s' index cannot be used with bus and unit\n", str);
2512 return -1;
2514 if (max_devs == 0)
2516 unit_id = index;
2517 bus_id = 0;
2518 } else {
2519 unit_id = index % max_devs;
2520 bus_id = index / max_devs;
2524 /* if user doesn't specify a unit_id,
2525 * try to find the first free
2528 if (unit_id == -1) {
2529 unit_id = 0;
2530 while (drive_get_index(type, bus_id, unit_id) != -1) {
2531 unit_id++;
2532 if (max_devs && unit_id >= max_devs) {
2533 unit_id -= max_devs;
2534 bus_id++;
2539 /* check unit id */
2541 if (max_devs && unit_id >= max_devs) {
2542 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2543 str, unit_id, max_devs - 1);
2544 return -1;
2548 * ignore multiple definitions
2551 if (drive_get_index(type, bus_id, unit_id) != -1)
2552 return -2;
2554 /* init */
2556 if (type == IF_IDE || type == IF_SCSI)
2557 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2558 if (max_devs)
2559 snprintf(buf, sizeof(buf), "%s%i%s%i",
2560 devname, bus_id, mediastr, unit_id);
2561 else
2562 snprintf(buf, sizeof(buf), "%s%s%i",
2563 devname, mediastr, unit_id);
2564 bdrv = bdrv_new(buf);
2565 drives_table_idx = drive_get_free_idx();
2566 drives_table[drives_table_idx].bdrv = bdrv;
2567 drives_table[drives_table_idx].type = type;
2568 drives_table[drives_table_idx].bus = bus_id;
2569 drives_table[drives_table_idx].unit = unit_id;
2570 drives_table[drives_table_idx].onerror = onerror;
2571 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2572 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2573 nb_drives++;
2575 switch(type) {
2576 case IF_IDE:
2577 case IF_SCSI:
2578 switch(media) {
2579 case MEDIA_DISK:
2580 if (cyls != 0) {
2581 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2582 bdrv_set_translation_hint(bdrv, translation);
2584 break;
2585 case MEDIA_CDROM:
2586 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2587 break;
2589 break;
2590 case IF_SD:
2591 /* FIXME: This isn't really a floppy, but it's a reasonable
2592 approximation. */
2593 case IF_FLOPPY:
2594 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2595 break;
2596 case IF_PFLASH:
2597 case IF_MTD:
2598 case IF_VIRTIO:
2599 break;
2601 if (!file[0])
2602 return -2;
2603 bdrv_flags = 0;
2604 if (snapshot) {
2605 bdrv_flags |= BDRV_O_SNAPSHOT;
2606 cache = 2; /* always use write-back with snapshot */
2608 if (cache == 0) /* no caching */
2609 bdrv_flags |= BDRV_O_NOCACHE;
2610 else if (cache == 2) /* write-back */
2611 bdrv_flags |= BDRV_O_CACHE_WB;
2612 else if (cache == 3) /* not specified */
2613 bdrv_flags |= BDRV_O_CACHE_DEF;
2614 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2615 fprintf(stderr, "qemu: could not open disk image %s\n",
2616 file);
2617 return -1;
2619 if (bdrv_key_required(bdrv))
2620 autostart = 0;
2621 return drives_table_idx;
2624 /***********************************************************/
2625 /* USB devices */
2627 static USBPort *used_usb_ports;
2628 static USBPort *free_usb_ports;
2630 /* ??? Maybe change this to register a hub to keep track of the topology. */
2631 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2632 usb_attachfn attach)
2634 port->opaque = opaque;
2635 port->index = index;
2636 port->attach = attach;
2637 port->next = free_usb_ports;
2638 free_usb_ports = port;
2641 int usb_device_add_dev(USBDevice *dev)
2643 USBPort *port;
2645 /* Find a USB port to add the device to. */
2646 port = free_usb_ports;
2647 if (!port->next) {
2648 USBDevice *hub;
2650 /* Create a new hub and chain it on. */
2651 free_usb_ports = NULL;
2652 port->next = used_usb_ports;
2653 used_usb_ports = port;
2655 hub = usb_hub_init(VM_USB_HUB_SIZE);
2656 usb_attach(port, hub);
2657 port = free_usb_ports;
2660 free_usb_ports = port->next;
2661 port->next = used_usb_ports;
2662 used_usb_ports = port;
2663 usb_attach(port, dev);
2664 return 0;
2667 static void usb_msd_password_cb(void *opaque, int err)
2669 USBDevice *dev = opaque;
2671 if (!err)
2672 usb_device_add_dev(dev);
2673 else
2674 dev->handle_destroy(dev);
2677 static int usb_device_add(const char *devname, int is_hotplug)
2679 const char *p;
2680 USBDevice *dev;
2682 if (!free_usb_ports)
2683 return -1;
2685 if (strstart(devname, "host:", &p)) {
2686 dev = usb_host_device_open(p);
2687 } else if (!strcmp(devname, "mouse")) {
2688 dev = usb_mouse_init();
2689 } else if (!strcmp(devname, "tablet")) {
2690 dev = usb_tablet_init();
2691 } else if (!strcmp(devname, "keyboard")) {
2692 dev = usb_keyboard_init();
2693 } else if (strstart(devname, "disk:", &p)) {
2694 BlockDriverState *bs;
2696 dev = usb_msd_init(p);
2697 if (!dev)
2698 return -1;
2699 bs = usb_msd_get_bdrv(dev);
2700 if (bdrv_key_required(bs)) {
2701 autostart = 0;
2702 if (is_hotplug) {
2703 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2704 dev);
2705 return 0;
2708 } else if (!strcmp(devname, "wacom-tablet")) {
2709 dev = usb_wacom_init();
2710 } else if (strstart(devname, "serial:", &p)) {
2711 dev = usb_serial_init(p);
2712 #ifdef CONFIG_BRLAPI
2713 } else if (!strcmp(devname, "braille")) {
2714 dev = usb_baum_init();
2715 #endif
2716 } else if (strstart(devname, "net:", &p)) {
2717 int nic = nb_nics;
2719 if (net_client_init("nic", p) < 0)
2720 return -1;
2721 nd_table[nic].model = "usb";
2722 dev = usb_net_init(&nd_table[nic]);
2723 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2724 dev = usb_bt_init(devname[2] ? hci_init(p) :
2725 bt_new_hci(qemu_find_bt_vlan(0)));
2726 } else {
2727 return -1;
2729 if (!dev)
2730 return -1;
2732 return usb_device_add_dev(dev);
2735 int usb_device_del_addr(int bus_num, int addr)
2737 USBPort *port;
2738 USBPort **lastp;
2739 USBDevice *dev;
2741 if (!used_usb_ports)
2742 return -1;
2744 if (bus_num != 0)
2745 return -1;
2747 lastp = &used_usb_ports;
2748 port = used_usb_ports;
2749 while (port && port->dev->addr != addr) {
2750 lastp = &port->next;
2751 port = port->next;
2754 if (!port)
2755 return -1;
2757 dev = port->dev;
2758 *lastp = port->next;
2759 usb_attach(port, NULL);
2760 dev->handle_destroy(dev);
2761 port->next = free_usb_ports;
2762 free_usb_ports = port;
2763 return 0;
2766 static int usb_device_del(const char *devname)
2768 int bus_num, addr;
2769 const char *p;
2771 if (strstart(devname, "host:", &p))
2772 return usb_host_device_close(p);
2774 if (!used_usb_ports)
2775 return -1;
2777 p = strchr(devname, '.');
2778 if (!p)
2779 return -1;
2780 bus_num = strtoul(devname, NULL, 0);
2781 addr = strtoul(p + 1, NULL, 0);
2783 return usb_device_del_addr(bus_num, addr);
2786 void do_usb_add(Monitor *mon, const char *devname)
2788 usb_device_add(devname, 1);
2791 void do_usb_del(Monitor *mon, const char *devname)
2793 usb_device_del(devname);
2796 void usb_info(Monitor *mon)
2798 USBDevice *dev;
2799 USBPort *port;
2800 const char *speed_str;
2802 if (!usb_enabled) {
2803 monitor_printf(mon, "USB support not enabled\n");
2804 return;
2807 for (port = used_usb_ports; port; port = port->next) {
2808 dev = port->dev;
2809 if (!dev)
2810 continue;
2811 switch(dev->speed) {
2812 case USB_SPEED_LOW:
2813 speed_str = "1.5";
2814 break;
2815 case USB_SPEED_FULL:
2816 speed_str = "12";
2817 break;
2818 case USB_SPEED_HIGH:
2819 speed_str = "480";
2820 break;
2821 default:
2822 speed_str = "?";
2823 break;
2825 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2826 0, dev->addr, speed_str, dev->devname);
2830 /***********************************************************/
2831 /* PCMCIA/Cardbus */
2833 static struct pcmcia_socket_entry_s {
2834 struct pcmcia_socket_s *socket;
2835 struct pcmcia_socket_entry_s *next;
2836 } *pcmcia_sockets = 0;
2838 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2840 struct pcmcia_socket_entry_s *entry;
2842 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2843 entry->socket = socket;
2844 entry->next = pcmcia_sockets;
2845 pcmcia_sockets = entry;
2848 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2850 struct pcmcia_socket_entry_s *entry, **ptr;
2852 ptr = &pcmcia_sockets;
2853 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2854 if (entry->socket == socket) {
2855 *ptr = entry->next;
2856 qemu_free(entry);
2860 void pcmcia_info(Monitor *mon)
2862 struct pcmcia_socket_entry_s *iter;
2864 if (!pcmcia_sockets)
2865 monitor_printf(mon, "No PCMCIA sockets\n");
2867 for (iter = pcmcia_sockets; iter; iter = iter->next)
2868 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2869 iter->socket->attached ? iter->socket->card_string :
2870 "Empty");
2873 /***********************************************************/
2874 /* register display */
2876 void register_displaystate(DisplayState *ds)
2878 DisplayState **s;
2879 s = &display_state;
2880 while (*s != NULL)
2881 s = &(*s)->next;
2882 ds->next = NULL;
2883 *s = ds;
2886 DisplayState *get_displaystate(void)
2888 return display_state;
2891 /* dumb display */
2893 static void dumb_display_init(void)
2895 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2896 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2897 register_displaystate(ds);
2900 /***********************************************************/
2901 /* I/O handling */
2903 #define MAX_IO_HANDLERS 64
2905 typedef struct IOHandlerRecord {
2906 int fd;
2907 IOCanRWHandler *fd_read_poll;
2908 IOHandler *fd_read;
2909 IOHandler *fd_write;
2910 int deleted;
2911 void *opaque;
2912 /* temporary data */
2913 struct pollfd *ufd;
2914 struct IOHandlerRecord *next;
2915 } IOHandlerRecord;
2917 static IOHandlerRecord *first_io_handler;
2919 /* XXX: fd_read_poll should be suppressed, but an API change is
2920 necessary in the character devices to suppress fd_can_read(). */
2921 int qemu_set_fd_handler2(int fd,
2922 IOCanRWHandler *fd_read_poll,
2923 IOHandler *fd_read,
2924 IOHandler *fd_write,
2925 void *opaque)
2927 IOHandlerRecord **pioh, *ioh;
2929 if (!fd_read && !fd_write) {
2930 pioh = &first_io_handler;
2931 for(;;) {
2932 ioh = *pioh;
2933 if (ioh == NULL)
2934 break;
2935 if (ioh->fd == fd) {
2936 ioh->deleted = 1;
2937 break;
2939 pioh = &ioh->next;
2941 } else {
2942 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2943 if (ioh->fd == fd)
2944 goto found;
2946 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2947 ioh->next = first_io_handler;
2948 first_io_handler = ioh;
2949 found:
2950 ioh->fd = fd;
2951 ioh->fd_read_poll = fd_read_poll;
2952 ioh->fd_read = fd_read;
2953 ioh->fd_write = fd_write;
2954 ioh->opaque = opaque;
2955 ioh->deleted = 0;
2957 return 0;
2960 int qemu_set_fd_handler(int fd,
2961 IOHandler *fd_read,
2962 IOHandler *fd_write,
2963 void *opaque)
2965 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2968 #ifdef _WIN32
2969 /***********************************************************/
2970 /* Polling handling */
2972 typedef struct PollingEntry {
2973 PollingFunc *func;
2974 void *opaque;
2975 struct PollingEntry *next;
2976 } PollingEntry;
2978 static PollingEntry *first_polling_entry;
2980 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2982 PollingEntry **ppe, *pe;
2983 pe = qemu_mallocz(sizeof(PollingEntry));
2984 pe->func = func;
2985 pe->opaque = opaque;
2986 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2987 *ppe = pe;
2988 return 0;
2991 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2993 PollingEntry **ppe, *pe;
2994 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2995 pe = *ppe;
2996 if (pe->func == func && pe->opaque == opaque) {
2997 *ppe = pe->next;
2998 qemu_free(pe);
2999 break;
3004 /***********************************************************/
3005 /* Wait objects support */
3006 typedef struct WaitObjects {
3007 int num;
3008 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3009 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3010 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3011 } WaitObjects;
3013 static WaitObjects wait_objects = {0};
3015 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3017 WaitObjects *w = &wait_objects;
3019 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3020 return -1;
3021 w->events[w->num] = handle;
3022 w->func[w->num] = func;
3023 w->opaque[w->num] = opaque;
3024 w->num++;
3025 return 0;
3028 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3030 int i, found;
3031 WaitObjects *w = &wait_objects;
3033 found = 0;
3034 for (i = 0; i < w->num; i++) {
3035 if (w->events[i] == handle)
3036 found = 1;
3037 if (found) {
3038 w->events[i] = w->events[i + 1];
3039 w->func[i] = w->func[i + 1];
3040 w->opaque[i] = w->opaque[i + 1];
3043 if (found)
3044 w->num--;
3046 #endif
3048 /***********************************************************/
3049 /* ram save/restore */
3051 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3053 int v;
3055 v = qemu_get_byte(f);
3056 switch(v) {
3057 case 0:
3058 if (qemu_get_buffer(f, buf, len) != len)
3059 return -EIO;
3060 break;
3061 case 1:
3062 v = qemu_get_byte(f);
3063 memset(buf, v, len);
3064 break;
3065 default:
3066 return -EINVAL;
3069 if (qemu_file_has_error(f))
3070 return -EIO;
3072 return 0;
3075 static int ram_load_v1(QEMUFile *f, void *opaque)
3077 int ret;
3078 ram_addr_t i;
3080 if (qemu_get_be32(f) != phys_ram_size)
3081 return -EINVAL;
3082 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3083 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3084 if (ret)
3085 return ret;
3087 return 0;
3090 #define BDRV_HASH_BLOCK_SIZE 1024
3091 #define IOBUF_SIZE 4096
3092 #define RAM_CBLOCK_MAGIC 0xfabe
3094 typedef struct RamDecompressState {
3095 z_stream zstream;
3096 QEMUFile *f;
3097 uint8_t buf[IOBUF_SIZE];
3098 } RamDecompressState;
3100 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3102 int ret;
3103 memset(s, 0, sizeof(*s));
3104 s->f = f;
3105 ret = inflateInit(&s->zstream);
3106 if (ret != Z_OK)
3107 return -1;
3108 return 0;
3111 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3113 int ret, clen;
3115 s->zstream.avail_out = len;
3116 s->zstream.next_out = buf;
3117 while (s->zstream.avail_out > 0) {
3118 if (s->zstream.avail_in == 0) {
3119 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3120 return -1;
3121 clen = qemu_get_be16(s->f);
3122 if (clen > IOBUF_SIZE)
3123 return -1;
3124 qemu_get_buffer(s->f, s->buf, clen);
3125 s->zstream.avail_in = clen;
3126 s->zstream.next_in = s->buf;
3128 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3129 if (ret != Z_OK && ret != Z_STREAM_END) {
3130 return -1;
3133 return 0;
3136 static void ram_decompress_close(RamDecompressState *s)
3138 inflateEnd(&s->zstream);
3141 #define RAM_SAVE_FLAG_FULL 0x01
3142 #define RAM_SAVE_FLAG_COMPRESS 0x02
3143 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3144 #define RAM_SAVE_FLAG_PAGE 0x08
3145 #define RAM_SAVE_FLAG_EOS 0x10
3147 static int is_dup_page(uint8_t *page, uint8_t ch)
3149 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3150 uint32_t *array = (uint32_t *)page;
3151 int i;
3153 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3154 if (array[i] != val)
3155 return 0;
3158 return 1;
3161 static int ram_save_block(QEMUFile *f)
3163 static ram_addr_t current_addr = 0;
3164 ram_addr_t saved_addr = current_addr;
3165 ram_addr_t addr = 0;
3166 int found = 0;
3168 while (addr < phys_ram_size) {
3169 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3170 uint8_t ch;
3172 cpu_physical_memory_reset_dirty(current_addr,
3173 current_addr + TARGET_PAGE_SIZE,
3174 MIGRATION_DIRTY_FLAG);
3176 ch = *(phys_ram_base + current_addr);
3178 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3179 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3180 qemu_put_byte(f, ch);
3181 } else {
3182 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3183 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3186 found = 1;
3187 break;
3189 addr += TARGET_PAGE_SIZE;
3190 current_addr = (saved_addr + addr) % phys_ram_size;
3193 return found;
3196 static ram_addr_t ram_save_threshold = 10;
3198 static ram_addr_t ram_save_remaining(void)
3200 ram_addr_t addr;
3201 ram_addr_t count = 0;
3203 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3204 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3205 count++;
3208 return count;
3211 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3213 ram_addr_t addr;
3215 if (stage == 1) {
3216 /* Make sure all dirty bits are set */
3217 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3218 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3219 cpu_physical_memory_set_dirty(addr);
3222 /* Enable dirty memory tracking */
3223 cpu_physical_memory_set_dirty_tracking(1);
3225 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3228 while (!qemu_file_rate_limit(f)) {
3229 int ret;
3231 ret = ram_save_block(f);
3232 if (ret == 0) /* no more blocks */
3233 break;
3236 /* try transferring iterative blocks of memory */
3238 if (stage == 3) {
3239 cpu_physical_memory_set_dirty_tracking(0);
3241 /* flush all remaining blocks regardless of rate limiting */
3242 while (ram_save_block(f) != 0);
3245 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3247 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3250 static int ram_load_dead(QEMUFile *f, void *opaque)
3252 RamDecompressState s1, *s = &s1;
3253 uint8_t buf[10];
3254 ram_addr_t i;
3256 if (ram_decompress_open(s, f) < 0)
3257 return -EINVAL;
3258 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3259 if (ram_decompress_buf(s, buf, 1) < 0) {
3260 fprintf(stderr, "Error while reading ram block header\n");
3261 goto error;
3263 if (buf[0] == 0) {
3264 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3265 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3266 goto error;
3268 } else {
3269 error:
3270 printf("Error block header\n");
3271 return -EINVAL;
3274 ram_decompress_close(s);
3276 return 0;
3279 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3281 ram_addr_t addr;
3282 int flags;
3284 if (version_id == 1)
3285 return ram_load_v1(f, opaque);
3287 if (version_id == 2) {
3288 if (qemu_get_be32(f) != phys_ram_size)
3289 return -EINVAL;
3290 return ram_load_dead(f, opaque);
3293 if (version_id != 3)
3294 return -EINVAL;
3296 do {
3297 addr = qemu_get_be64(f);
3299 flags = addr & ~TARGET_PAGE_MASK;
3300 addr &= TARGET_PAGE_MASK;
3302 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3303 if (addr != phys_ram_size)
3304 return -EINVAL;
3307 if (flags & RAM_SAVE_FLAG_FULL) {
3308 if (ram_load_dead(f, opaque) < 0)
3309 return -EINVAL;
3312 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3313 uint8_t ch = qemu_get_byte(f);
3314 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3315 } else if (flags & RAM_SAVE_FLAG_PAGE)
3316 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3317 } while (!(flags & RAM_SAVE_FLAG_EOS));
3319 return 0;
3322 void qemu_service_io(void)
3324 CPUState *env = cpu_single_env;
3325 if (env) {
3326 cpu_exit(env);
3327 #ifdef USE_KQEMU
3328 if (env->kqemu_enabled) {
3329 kqemu_cpu_interrupt(env);
3331 #endif
3335 /***********************************************************/
3336 /* bottom halves (can be seen as timers which expire ASAP) */
3338 struct QEMUBH {
3339 QEMUBHFunc *cb;
3340 void *opaque;
3341 int scheduled;
3342 int idle;
3343 int deleted;
3344 QEMUBH *next;
3347 static QEMUBH *first_bh = NULL;
3349 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3351 QEMUBH *bh;
3352 bh = qemu_mallocz(sizeof(QEMUBH));
3353 bh->cb = cb;
3354 bh->opaque = opaque;
3355 bh->next = first_bh;
3356 first_bh = bh;
3357 return bh;
3360 int qemu_bh_poll(void)
3362 QEMUBH *bh, **bhp;
3363 int ret;
3365 ret = 0;
3366 for (bh = first_bh; bh; bh = bh->next) {
3367 if (!bh->deleted && bh->scheduled) {
3368 bh->scheduled = 0;
3369 if (!bh->idle)
3370 ret = 1;
3371 bh->idle = 0;
3372 bh->cb(bh->opaque);
3376 /* remove deleted bhs */
3377 bhp = &first_bh;
3378 while (*bhp) {
3379 bh = *bhp;
3380 if (bh->deleted) {
3381 *bhp = bh->next;
3382 qemu_free(bh);
3383 } else
3384 bhp = &bh->next;
3387 return ret;
3390 void qemu_bh_schedule_idle(QEMUBH *bh)
3392 if (bh->scheduled)
3393 return;
3394 bh->scheduled = 1;
3395 bh->idle = 1;
3398 void qemu_bh_schedule(QEMUBH *bh)
3400 CPUState *env = cpu_single_env;
3401 if (bh->scheduled)
3402 return;
3403 bh->scheduled = 1;
3404 bh->idle = 0;
3405 /* stop the currently executing CPU to execute the BH ASAP */
3406 if (env) {
3407 cpu_exit(env);
3411 void qemu_bh_cancel(QEMUBH *bh)
3413 bh->scheduled = 0;
3416 void qemu_bh_delete(QEMUBH *bh)
3418 bh->scheduled = 0;
3419 bh->deleted = 1;
3422 static void qemu_bh_update_timeout(int *timeout)
3424 QEMUBH *bh;
3426 for (bh = first_bh; bh; bh = bh->next) {
3427 if (!bh->deleted && bh->scheduled) {
3428 if (bh->idle) {
3429 /* idle bottom halves will be polled at least
3430 * every 10ms */
3431 *timeout = MIN(10, *timeout);
3432 } else {
3433 /* non-idle bottom halves will be executed
3434 * immediately */
3435 *timeout = 0;
3436 break;
3442 /***********************************************************/
3443 /* machine registration */
3445 static QEMUMachine *first_machine = NULL;
3446 QEMUMachine *current_machine = NULL;
3448 int qemu_register_machine(QEMUMachine *m)
3450 QEMUMachine **pm;
3451 pm = &first_machine;
3452 while (*pm != NULL)
3453 pm = &(*pm)->next;
3454 m->next = NULL;
3455 *pm = m;
3456 return 0;
3459 static QEMUMachine *find_machine(const char *name)
3461 QEMUMachine *m;
3463 for(m = first_machine; m != NULL; m = m->next) {
3464 if (!strcmp(m->name, name))
3465 return m;
3467 return NULL;
3470 /***********************************************************/
3471 /* main execution loop */
3473 static void gui_update(void *opaque)
3475 uint64_t interval = GUI_REFRESH_INTERVAL;
3476 DisplayState *ds = opaque;
3477 DisplayChangeListener *dcl = ds->listeners;
3479 dpy_refresh(ds);
3481 while (dcl != NULL) {
3482 if (dcl->gui_timer_interval &&
3483 dcl->gui_timer_interval < interval)
3484 interval = dcl->gui_timer_interval;
3485 dcl = dcl->next;
3487 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3490 static void nographic_update(void *opaque)
3492 uint64_t interval = GUI_REFRESH_INTERVAL;
3494 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3497 struct vm_change_state_entry {
3498 VMChangeStateHandler *cb;
3499 void *opaque;
3500 LIST_ENTRY (vm_change_state_entry) entries;
3503 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3505 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3506 void *opaque)
3508 VMChangeStateEntry *e;
3510 e = qemu_mallocz(sizeof (*e));
3512 e->cb = cb;
3513 e->opaque = opaque;
3514 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3515 return e;
3518 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3520 LIST_REMOVE (e, entries);
3521 qemu_free (e);
3524 static void vm_state_notify(int running, int reason)
3526 VMChangeStateEntry *e;
3528 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3529 e->cb(e->opaque, running, reason);
3533 void vm_start(void)
3535 if (!vm_running) {
3536 cpu_enable_ticks();
3537 vm_running = 1;
3538 vm_state_notify(1, 0);
3539 qemu_rearm_alarm_timer(alarm_timer);
3543 void vm_stop(int reason)
3545 if (vm_running) {
3546 cpu_disable_ticks();
3547 vm_running = 0;
3548 vm_state_notify(0, reason);
3552 /* reset/shutdown handler */
3554 typedef struct QEMUResetEntry {
3555 QEMUResetHandler *func;
3556 void *opaque;
3557 struct QEMUResetEntry *next;
3558 } QEMUResetEntry;
3560 static QEMUResetEntry *first_reset_entry;
3561 static int reset_requested;
3562 static int shutdown_requested;
3563 static int powerdown_requested;
3565 int qemu_shutdown_requested(void)
3567 int r = shutdown_requested;
3568 shutdown_requested = 0;
3569 return r;
3572 int qemu_reset_requested(void)
3574 int r = reset_requested;
3575 reset_requested = 0;
3576 return r;
3579 int qemu_powerdown_requested(void)
3581 int r = powerdown_requested;
3582 powerdown_requested = 0;
3583 return r;
3586 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3588 QEMUResetEntry **pre, *re;
3590 pre = &first_reset_entry;
3591 while (*pre != NULL)
3592 pre = &(*pre)->next;
3593 re = qemu_mallocz(sizeof(QEMUResetEntry));
3594 re->func = func;
3595 re->opaque = opaque;
3596 re->next = NULL;
3597 *pre = re;
3600 void qemu_system_reset(void)
3602 QEMUResetEntry *re;
3604 /* reset all devices */
3605 for(re = first_reset_entry; re != NULL; re = re->next) {
3606 re->func(re->opaque);
3610 void qemu_system_reset_request(void)
3612 if (no_reboot) {
3613 shutdown_requested = 1;
3614 } else {
3615 reset_requested = 1;
3617 if (cpu_single_env)
3618 cpu_exit(cpu_single_env);
3621 void qemu_system_shutdown_request(void)
3623 shutdown_requested = 1;
3624 if (cpu_single_env)
3625 cpu_exit(cpu_single_env);
3628 void qemu_system_powerdown_request(void)
3630 powerdown_requested = 1;
3631 if (cpu_single_env)
3632 cpu_exit(cpu_single_env);
3635 #ifdef _WIN32
3636 static void host_main_loop_wait(int *timeout)
3638 int ret, ret2, i;
3639 PollingEntry *pe;
3642 /* XXX: need to suppress polling by better using win32 events */
3643 ret = 0;
3644 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3645 ret |= pe->func(pe->opaque);
3647 if (ret == 0) {
3648 int err;
3649 WaitObjects *w = &wait_objects;
3651 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3652 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3653 if (w->func[ret - WAIT_OBJECT_0])
3654 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3656 /* Check for additional signaled events */
3657 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3659 /* Check if event is signaled */
3660 ret2 = WaitForSingleObject(w->events[i], 0);
3661 if(ret2 == WAIT_OBJECT_0) {
3662 if (w->func[i])
3663 w->func[i](w->opaque[i]);
3664 } else if (ret2 == WAIT_TIMEOUT) {
3665 } else {
3666 err = GetLastError();
3667 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3670 } else if (ret == WAIT_TIMEOUT) {
3671 } else {
3672 err = GetLastError();
3673 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3677 *timeout = 0;
3679 #else
3680 static void host_main_loop_wait(int *timeout)
3683 #endif
3685 void main_loop_wait(int timeout)
3687 IOHandlerRecord *ioh;
3688 fd_set rfds, wfds, xfds;
3689 int ret, nfds;
3690 struct timeval tv;
3692 qemu_bh_update_timeout(&timeout);
3694 host_main_loop_wait(&timeout);
3696 /* poll any events */
3697 /* XXX: separate device handlers from system ones */
3698 nfds = -1;
3699 FD_ZERO(&rfds);
3700 FD_ZERO(&wfds);
3701 FD_ZERO(&xfds);
3702 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3703 if (ioh->deleted)
3704 continue;
3705 if (ioh->fd_read &&
3706 (!ioh->fd_read_poll ||
3707 ioh->fd_read_poll(ioh->opaque) != 0)) {
3708 FD_SET(ioh->fd, &rfds);
3709 if (ioh->fd > nfds)
3710 nfds = ioh->fd;
3712 if (ioh->fd_write) {
3713 FD_SET(ioh->fd, &wfds);
3714 if (ioh->fd > nfds)
3715 nfds = ioh->fd;
3719 tv.tv_sec = timeout / 1000;
3720 tv.tv_usec = (timeout % 1000) * 1000;
3722 #if defined(CONFIG_SLIRP)
3723 if (slirp_is_inited()) {
3724 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3726 #endif
3727 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3728 if (ret > 0) {
3729 IOHandlerRecord **pioh;
3731 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3732 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3733 ioh->fd_read(ioh->opaque);
3735 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3736 ioh->fd_write(ioh->opaque);
3740 /* remove deleted IO handlers */
3741 pioh = &first_io_handler;
3742 while (*pioh) {
3743 ioh = *pioh;
3744 if (ioh->deleted) {
3745 *pioh = ioh->next;
3746 qemu_free(ioh);
3747 } else
3748 pioh = &ioh->next;
3751 #if defined(CONFIG_SLIRP)
3752 if (slirp_is_inited()) {
3753 if (ret < 0) {
3754 FD_ZERO(&rfds);
3755 FD_ZERO(&wfds);
3756 FD_ZERO(&xfds);
3758 slirp_select_poll(&rfds, &wfds, &xfds);
3760 #endif
3762 /* vm time timers */
3763 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3764 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3765 qemu_get_clock(vm_clock));
3767 /* real time timers */
3768 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3769 qemu_get_clock(rt_clock));
3771 /* Check bottom-halves last in case any of the earlier events triggered
3772 them. */
3773 qemu_bh_poll();
3777 static int main_loop(void)
3779 int ret, timeout;
3780 #ifdef CONFIG_PROFILER
3781 int64_t ti;
3782 #endif
3783 CPUState *env;
3785 cur_cpu = first_cpu;
3786 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3787 for(;;) {
3788 if (vm_running) {
3790 for(;;) {
3791 /* get next cpu */
3792 env = next_cpu;
3793 #ifdef CONFIG_PROFILER
3794 ti = profile_getclock();
3795 #endif
3796 if (use_icount) {
3797 int64_t count;
3798 int decr;
3799 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3800 env->icount_decr.u16.low = 0;
3801 env->icount_extra = 0;
3802 count = qemu_next_deadline();
3803 count = (count + (1 << icount_time_shift) - 1)
3804 >> icount_time_shift;
3805 qemu_icount += count;
3806 decr = (count > 0xffff) ? 0xffff : count;
3807 count -= decr;
3808 env->icount_decr.u16.low = decr;
3809 env->icount_extra = count;
3811 ret = cpu_exec(env);
3812 #ifdef CONFIG_PROFILER
3813 qemu_time += profile_getclock() - ti;
3814 #endif
3815 if (use_icount) {
3816 /* Fold pending instructions back into the
3817 instruction counter, and clear the interrupt flag. */
3818 qemu_icount -= (env->icount_decr.u16.low
3819 + env->icount_extra);
3820 env->icount_decr.u32 = 0;
3821 env->icount_extra = 0;
3823 next_cpu = env->next_cpu ?: first_cpu;
3824 if (event_pending && likely(ret != EXCP_DEBUG)) {
3825 ret = EXCP_INTERRUPT;
3826 event_pending = 0;
3827 break;
3829 if (ret == EXCP_HLT) {
3830 /* Give the next CPU a chance to run. */
3831 cur_cpu = env;
3832 continue;
3834 if (ret != EXCP_HALTED)
3835 break;
3836 /* all CPUs are halted ? */
3837 if (env == cur_cpu)
3838 break;
3840 cur_cpu = env;
3842 if (shutdown_requested) {
3843 ret = EXCP_INTERRUPT;
3844 if (no_shutdown) {
3845 vm_stop(0);
3846 no_shutdown = 0;
3848 else
3849 break;
3851 if (reset_requested) {
3852 reset_requested = 0;
3853 qemu_system_reset();
3854 ret = EXCP_INTERRUPT;
3856 if (powerdown_requested) {
3857 powerdown_requested = 0;
3858 qemu_system_powerdown();
3859 ret = EXCP_INTERRUPT;
3861 if (unlikely(ret == EXCP_DEBUG)) {
3862 gdb_set_stop_cpu(cur_cpu);
3863 vm_stop(EXCP_DEBUG);
3865 /* If all cpus are halted then wait until the next IRQ */
3866 /* XXX: use timeout computed from timers */
3867 if (ret == EXCP_HALTED) {
3868 if (use_icount) {
3869 int64_t add;
3870 int64_t delta;
3871 /* Advance virtual time to the next event. */
3872 if (use_icount == 1) {
3873 /* When not using an adaptive execution frequency
3874 we tend to get badly out of sync with real time,
3875 so just delay for a reasonable amount of time. */
3876 delta = 0;
3877 } else {
3878 delta = cpu_get_icount() - cpu_get_clock();
3880 if (delta > 0) {
3881 /* If virtual time is ahead of real time then just
3882 wait for IO. */
3883 timeout = (delta / 1000000) + 1;
3884 } else {
3885 /* Wait for either IO to occur or the next
3886 timer event. */
3887 add = qemu_next_deadline();
3888 /* We advance the timer before checking for IO.
3889 Limit the amount we advance so that early IO
3890 activity won't get the guest too far ahead. */
3891 if (add > 10000000)
3892 add = 10000000;
3893 delta += add;
3894 add = (add + (1 << icount_time_shift) - 1)
3895 >> icount_time_shift;
3896 qemu_icount += add;
3897 timeout = delta / 1000000;
3898 if (timeout < 0)
3899 timeout = 0;
3901 } else {
3902 timeout = 5000;
3904 } else {
3905 timeout = 0;
3907 } else {
3908 if (shutdown_requested) {
3909 ret = EXCP_INTERRUPT;
3910 break;
3912 timeout = 5000;
3914 #ifdef CONFIG_PROFILER
3915 ti = profile_getclock();
3916 #endif
3917 main_loop_wait(timeout);
3918 #ifdef CONFIG_PROFILER
3919 dev_time += profile_getclock() - ti;
3920 #endif
3922 cpu_disable_ticks();
3923 return ret;
3926 static void help(int exitcode)
3928 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3929 and qemu-doc.texi */
3930 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3931 "usage: %s [options] [disk_image]\n"
3932 "\n"
3933 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3934 "\n"
3935 "Standard options:\n"
3936 "-h or -help display this help and exit\n"
3937 "-M machine select emulated machine (-M ? for list)\n"
3938 "-cpu cpu select CPU (-cpu ? for list)\n"
3939 "-smp n set the number of CPUs to 'n' [default=1]\n"
3940 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3941 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3942 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3943 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3944 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3945 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3946 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3947 " use 'file' as a drive image\n"
3948 "-mtdblock file use 'file' as on-board Flash memory image\n"
3949 "-sd file use 'file' as SecureDigital card image\n"
3950 "-pflash file use 'file' as a parallel flash image\n"
3951 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3952 "-snapshot write to temporary files instead of disk image files\n"
3953 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3954 #ifndef _WIN32
3955 "-k language use keyboard layout (for example \"fr\" for French)\n"
3956 #endif
3957 #ifdef HAS_AUDIO
3958 "-audio-help print list of audio drivers and their options\n"
3959 "-soundhw c1,... enable audio support\n"
3960 " and only specified sound cards (comma separated list)\n"
3961 " use -soundhw ? to get the list of supported cards\n"
3962 " use -soundhw all to enable all of them\n"
3963 #endif
3964 "-usb enable the USB driver (will be the default soon)\n"
3965 "-usbdevice name add the host or guest USB device 'name'\n"
3966 "-name string set the name of the guest\n"
3967 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
3968 " specify machine UUID\n"
3969 "\n"
3970 "Display options:\n"
3971 "-nographic disable graphical output and redirect serial I/Os to console\n"
3972 #ifdef CONFIG_CURSES
3973 "-curses use a curses/ncurses interface instead of SDL\n"
3974 #endif
3975 #ifdef CONFIG_SDL
3976 "-no-frame open SDL window without a frame and window decorations\n"
3977 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3978 "-no-quit disable SDL window close capability\n"
3979 "-sdl enable SDL\n"
3980 #endif
3981 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3982 "-vga [std|cirrus|vmware|none]\n"
3983 " select video card type\n"
3984 "-full-screen start in full screen\n"
3985 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3986 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3987 #endif
3988 "-vnc display start a VNC server on display\n"
3989 "\n"
3990 "Network options:\n"
3991 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3992 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3993 #ifdef CONFIG_SLIRP
3994 "-net user[,vlan=n][,name=str][,hostname=host]\n"
3995 " connect the user mode network stack to VLAN 'n' and send\n"
3996 " hostname 'host' to DHCP clients\n"
3997 #endif
3998 #ifdef _WIN32
3999 "-net tap[,vlan=n][,name=str],ifname=name\n"
4000 " connect the host TAP network interface to VLAN 'n'\n"
4001 #else
4002 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4003 " connect the host TAP network interface to VLAN 'n' and use the\n"
4004 " network scripts 'file' (default=%s)\n"
4005 " and 'dfile' (default=%s);\n"
4006 " use '[down]script=no' to disable script execution;\n"
4007 " use 'fd=h' to connect to an already opened TAP interface\n"
4008 #endif
4009 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4010 " connect the vlan 'n' to another VLAN using a socket connection\n"
4011 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4012 " connect the vlan 'n' to multicast maddr and port\n"
4013 #ifdef CONFIG_VDE
4014 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4015 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4016 " on host and listening for incoming connections on 'socketpath'.\n"
4017 " Use group 'groupname' and mode 'octalmode' to change default\n"
4018 " ownership and permissions for communication port.\n"
4019 #endif
4020 "-net none use it alone to have zero network devices; if no -net option\n"
4021 " is provided, the default is '-net nic -net user'\n"
4022 #ifdef CONFIG_SLIRP
4023 "-tftp dir allow tftp access to files in dir [-net user]\n"
4024 "-bootp file advertise file in BOOTP replies\n"
4025 #ifndef _WIN32
4026 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4027 #endif
4028 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4029 " redirect TCP or UDP connections from host to guest [-net user]\n"
4030 #endif
4031 "\n"
4032 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4033 "-bt hci,host[:id]\n"
4034 " use host's HCI with the given name\n"
4035 "-bt hci[,vlan=n]\n"
4036 " emulate a standard HCI in virtual scatternet 'n'\n"
4037 "-bt vhci[,vlan=n]\n"
4038 " add host computer to virtual scatternet 'n' using VHCI\n"
4039 "-bt device:dev[,vlan=n]\n"
4040 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4041 "\n"
4042 #ifdef TARGET_I386
4043 "\n"
4044 "i386 target only:\n"
4045 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4046 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4047 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4048 "-no-acpi disable ACPI\n"
4049 "-no-hpet disable HPET\n"
4050 "-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"
4051 " ACPI table description\n"
4052 #endif
4053 "Linux boot specific:\n"
4054 "-kernel bzImage use 'bzImage' as kernel image\n"
4055 "-append cmdline use 'cmdline' as kernel command line\n"
4056 "-initrd file use 'file' as initial ram disk\n"
4057 "\n"
4058 "Debug/Expert options:\n"
4059 "-serial dev redirect the serial port to char device 'dev'\n"
4060 "-parallel dev redirect the parallel port to char device 'dev'\n"
4061 "-monitor dev redirect the monitor to char device 'dev'\n"
4062 "-pidfile file write PID to 'file'\n"
4063 "-S freeze CPU at startup (use 'c' to start execution)\n"
4064 "-s wait gdb connection to port\n"
4065 "-p port set gdb connection port [default=%s]\n"
4066 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4067 "-hdachs c,h,s[,t]\n"
4068 " force hard disk 0 physical geometry and the optional BIOS\n"
4069 " translation (t=none or lba) (usually qemu can guess them)\n"
4070 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4071 "-bios file set the filename for the BIOS\n"
4072 #ifdef USE_KQEMU
4073 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4074 "-no-kqemu disable KQEMU kernel module usage\n"
4075 #endif
4076 #ifdef CONFIG_KVM
4077 "-enable-kvm enable KVM full virtualization support\n"
4078 #endif
4079 "-no-reboot exit instead of rebooting\n"
4080 "-no-shutdown stop before shutdown\n"
4081 "-loadvm [tag|id]\n"
4082 " start right away with a saved state (loadvm in monitor)\n"
4083 #ifndef _WIN32
4084 "-daemonize daemonize QEMU after initializing\n"
4085 #endif
4086 "-option-rom rom load a file, rom, into the option ROM space\n"
4087 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4088 "-prom-env variable=value\n"
4089 " set OpenBIOS nvram variables\n"
4090 #endif
4091 "-clock force the use of the given methods for timer alarm.\n"
4092 " To see what timers are available use -clock ?\n"
4093 "-localtime set the real time clock to local time [default=utc]\n"
4094 "-startdate select initial date of the clock\n"
4095 "-icount [N|auto]\n"
4096 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4097 "-echr chr set terminal escape character instead of ctrl-a\n"
4098 "-virtioconsole c\n"
4099 " set virtio console\n"
4100 "-show-cursor show cursor\n"
4101 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4102 "-semihosting semihosting mode\n"
4103 #endif
4104 #if defined(TARGET_ARM)
4105 "-old-param old param mode\n"
4106 #endif
4107 "-tb-size n set TB size\n"
4108 "-incoming p prepare for incoming migration, listen on port p\n"
4109 #ifndef _WIN32
4110 "-chroot dir Chroot to dir just before starting the VM.\n"
4111 "-runas user Change to user id user just before starting the VM.\n"
4112 #endif
4113 "\n"
4114 "During emulation, the following keys are useful:\n"
4115 "ctrl-alt-f toggle full screen\n"
4116 "ctrl-alt-n switch to virtual console 'n'\n"
4117 "ctrl-alt toggle mouse and keyboard grab\n"
4118 "\n"
4119 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4121 "qemu",
4122 DEFAULT_RAM_SIZE,
4123 #ifndef _WIN32
4124 DEFAULT_NETWORK_SCRIPT,
4125 DEFAULT_NETWORK_DOWN_SCRIPT,
4126 #endif
4127 DEFAULT_GDBSTUB_PORT,
4128 "/tmp/qemu.log");
4129 exit(exitcode);
4132 #define HAS_ARG 0x0001
4134 enum {
4135 /* Please keep in synch with help, qemu_options[] and
4136 qemu-doc.texi */
4137 /* Standard options: */
4138 QEMU_OPTION_h,
4139 QEMU_OPTION_M,
4140 QEMU_OPTION_cpu,
4141 QEMU_OPTION_smp,
4142 QEMU_OPTION_fda,
4143 QEMU_OPTION_fdb,
4144 QEMU_OPTION_hda,
4145 QEMU_OPTION_hdb,
4146 QEMU_OPTION_hdc,
4147 QEMU_OPTION_hdd,
4148 QEMU_OPTION_cdrom,
4149 QEMU_OPTION_drive,
4150 QEMU_OPTION_mtdblock,
4151 QEMU_OPTION_sd,
4152 QEMU_OPTION_pflash,
4153 QEMU_OPTION_boot,
4154 QEMU_OPTION_snapshot,
4155 QEMU_OPTION_m,
4156 QEMU_OPTION_k,
4157 QEMU_OPTION_audio_help,
4158 QEMU_OPTION_soundhw,
4159 QEMU_OPTION_usb,
4160 QEMU_OPTION_usbdevice,
4161 QEMU_OPTION_name,
4162 QEMU_OPTION_uuid,
4164 /* Display options: */
4165 QEMU_OPTION_nographic,
4166 QEMU_OPTION_curses,
4167 QEMU_OPTION_no_frame,
4168 QEMU_OPTION_alt_grab,
4169 QEMU_OPTION_no_quit,
4170 QEMU_OPTION_sdl,
4171 QEMU_OPTION_portrait,
4172 QEMU_OPTION_vga,
4173 QEMU_OPTION_full_screen,
4174 QEMU_OPTION_g,
4175 QEMU_OPTION_vnc,
4177 /* Network options: */
4178 QEMU_OPTION_net,
4179 QEMU_OPTION_tftp,
4180 QEMU_OPTION_bootp,
4181 QEMU_OPTION_smb,
4182 QEMU_OPTION_redir,
4183 QEMU_OPTION_bt,
4185 /* i386 target only: */
4186 QEMU_OPTION_win2k_hack,
4187 QEMU_OPTION_rtc_td_hack,
4188 QEMU_OPTION_no_fd_bootchk,
4189 QEMU_OPTION_no_acpi,
4190 QEMU_OPTION_no_hpet,
4191 QEMU_OPTION_acpitable,
4193 /* Linux boot specific: */
4194 QEMU_OPTION_kernel,
4195 QEMU_OPTION_append,
4196 QEMU_OPTION_initrd,
4198 /* Debug/Expert options: */
4199 QEMU_OPTION_serial,
4200 QEMU_OPTION_parallel,
4201 QEMU_OPTION_monitor,
4202 QEMU_OPTION_pidfile,
4203 QEMU_OPTION_S,
4204 QEMU_OPTION_s,
4205 QEMU_OPTION_p,
4206 QEMU_OPTION_d,
4207 QEMU_OPTION_hdachs,
4208 QEMU_OPTION_L,
4209 QEMU_OPTION_bios,
4210 QEMU_OPTION_kernel_kqemu,
4211 QEMU_OPTION_no_kqemu,
4212 QEMU_OPTION_enable_kvm,
4213 QEMU_OPTION_no_reboot,
4214 QEMU_OPTION_no_shutdown,
4215 QEMU_OPTION_loadvm,
4216 QEMU_OPTION_daemonize,
4217 QEMU_OPTION_option_rom,
4218 QEMU_OPTION_prom_env,
4219 QEMU_OPTION_clock,
4220 QEMU_OPTION_localtime,
4221 QEMU_OPTION_startdate,
4222 QEMU_OPTION_icount,
4223 QEMU_OPTION_echr,
4224 QEMU_OPTION_virtiocon,
4225 QEMU_OPTION_show_cursor,
4226 QEMU_OPTION_semihosting,
4227 QEMU_OPTION_old_param,
4228 QEMU_OPTION_tb_size,
4229 QEMU_OPTION_incoming,
4230 QEMU_OPTION_chroot,
4231 QEMU_OPTION_runas,
4234 typedef struct QEMUOption {
4235 const char *name;
4236 int flags;
4237 int index;
4238 } QEMUOption;
4240 static const QEMUOption qemu_options[] = {
4241 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4242 qemu-doc.texi */
4243 /* Standard options: */
4244 { "h", 0, QEMU_OPTION_h },
4245 { "help", 0, QEMU_OPTION_h },
4246 { "M", HAS_ARG, QEMU_OPTION_M },
4247 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4248 { "smp", HAS_ARG, QEMU_OPTION_smp },
4249 { "fda", HAS_ARG, QEMU_OPTION_fda },
4250 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4251 { "hda", HAS_ARG, QEMU_OPTION_hda },
4252 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4253 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4254 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4255 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4256 { "drive", HAS_ARG, QEMU_OPTION_drive },
4257 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4258 { "sd", HAS_ARG, QEMU_OPTION_sd },
4259 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4260 { "boot", HAS_ARG, QEMU_OPTION_boot },
4261 { "snapshot", 0, QEMU_OPTION_snapshot },
4262 { "m", HAS_ARG, QEMU_OPTION_m },
4263 #ifndef _WIN32
4264 { "k", HAS_ARG, QEMU_OPTION_k },
4265 #endif
4266 #ifdef HAS_AUDIO
4267 { "audio-help", 0, QEMU_OPTION_audio_help },
4268 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4269 #endif
4270 { "usb", 0, QEMU_OPTION_usb },
4271 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4272 { "name", HAS_ARG, QEMU_OPTION_name },
4273 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4275 /* Display options: */
4276 { "nographic", 0, QEMU_OPTION_nographic },
4277 #ifdef CONFIG_CURSES
4278 { "curses", 0, QEMU_OPTION_curses },
4279 #endif
4280 #ifdef CONFIG_SDL
4281 { "no-frame", 0, QEMU_OPTION_no_frame },
4282 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4283 { "no-quit", 0, QEMU_OPTION_no_quit },
4284 { "sdl", 0, QEMU_OPTION_sdl },
4285 #endif
4286 { "portrait", 0, QEMU_OPTION_portrait },
4287 { "vga", HAS_ARG, QEMU_OPTION_vga },
4288 { "full-screen", 0, QEMU_OPTION_full_screen },
4289 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4290 { "g", 1, QEMU_OPTION_g },
4291 #endif
4292 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4294 /* Network options: */
4295 { "net", HAS_ARG, QEMU_OPTION_net},
4296 #ifdef CONFIG_SLIRP
4297 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4298 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4299 #ifndef _WIN32
4300 { "smb", HAS_ARG, QEMU_OPTION_smb },
4301 #endif
4302 { "redir", HAS_ARG, QEMU_OPTION_redir },
4303 #endif
4304 { "bt", HAS_ARG, QEMU_OPTION_bt },
4305 #ifdef TARGET_I386
4306 /* i386 target only: */
4307 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4308 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4309 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4310 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4311 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4312 { "acpitable", HAS_ARG, QEMU_OPTION_acpitable },
4313 #endif
4315 /* Linux boot specific: */
4316 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4317 { "append", HAS_ARG, QEMU_OPTION_append },
4318 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4320 /* Debug/Expert options: */
4321 { "serial", HAS_ARG, QEMU_OPTION_serial },
4322 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4323 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4324 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4325 { "S", 0, QEMU_OPTION_S },
4326 { "s", 0, QEMU_OPTION_s },
4327 { "p", HAS_ARG, QEMU_OPTION_p },
4328 { "d", HAS_ARG, QEMU_OPTION_d },
4329 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4330 { "L", HAS_ARG, QEMU_OPTION_L },
4331 { "bios", HAS_ARG, QEMU_OPTION_bios },
4332 #ifdef USE_KQEMU
4333 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4334 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4335 #endif
4336 #ifdef CONFIG_KVM
4337 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4338 #endif
4339 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4340 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4341 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4342 { "daemonize", 0, QEMU_OPTION_daemonize },
4343 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4344 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4345 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4346 #endif
4347 { "clock", HAS_ARG, QEMU_OPTION_clock },
4348 { "localtime", 0, QEMU_OPTION_localtime },
4349 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4350 { "icount", HAS_ARG, QEMU_OPTION_icount },
4351 { "echr", HAS_ARG, QEMU_OPTION_echr },
4352 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4353 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4354 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4355 { "semihosting", 0, QEMU_OPTION_semihosting },
4356 #endif
4357 #if defined(TARGET_ARM)
4358 { "old-param", 0, QEMU_OPTION_old_param },
4359 #endif
4360 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4361 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4362 { "chroot", HAS_ARG, QEMU_OPTION_chroot },
4363 { "runas", HAS_ARG, QEMU_OPTION_runas },
4364 { NULL },
4367 #ifdef HAS_AUDIO
4368 struct soundhw soundhw[] = {
4369 #ifdef HAS_AUDIO_CHOICE
4370 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4372 "pcspk",
4373 "PC speaker",
4376 { .init_isa = pcspk_audio_init }
4378 #endif
4380 #ifdef CONFIG_SB16
4382 "sb16",
4383 "Creative Sound Blaster 16",
4386 { .init_isa = SB16_init }
4388 #endif
4390 #ifdef CONFIG_CS4231A
4392 "cs4231a",
4393 "CS4231A",
4396 { .init_isa = cs4231a_init }
4398 #endif
4400 #ifdef CONFIG_ADLIB
4402 "adlib",
4403 #ifdef HAS_YMF262
4404 "Yamaha YMF262 (OPL3)",
4405 #else
4406 "Yamaha YM3812 (OPL2)",
4407 #endif
4410 { .init_isa = Adlib_init }
4412 #endif
4414 #ifdef CONFIG_GUS
4416 "gus",
4417 "Gravis Ultrasound GF1",
4420 { .init_isa = GUS_init }
4422 #endif
4424 #ifdef CONFIG_AC97
4426 "ac97",
4427 "Intel 82801AA AC97 Audio",
4430 { .init_pci = ac97_init }
4432 #endif
4434 #ifdef CONFIG_ES1370
4436 "es1370",
4437 "ENSONIQ AudioPCI ES1370",
4440 { .init_pci = es1370_init }
4442 #endif
4444 #endif /* HAS_AUDIO_CHOICE */
4446 { NULL, NULL, 0, 0, { NULL } }
4449 static void select_soundhw (const char *optarg)
4451 struct soundhw *c;
4453 if (*optarg == '?') {
4454 show_valid_cards:
4456 printf ("Valid sound card names (comma separated):\n");
4457 for (c = soundhw; c->name; ++c) {
4458 printf ("%-11s %s\n", c->name, c->descr);
4460 printf ("\n-soundhw all will enable all of the above\n");
4461 exit (*optarg != '?');
4463 else {
4464 size_t l;
4465 const char *p;
4466 char *e;
4467 int bad_card = 0;
4469 if (!strcmp (optarg, "all")) {
4470 for (c = soundhw; c->name; ++c) {
4471 c->enabled = 1;
4473 return;
4476 p = optarg;
4477 while (*p) {
4478 e = strchr (p, ',');
4479 l = !e ? strlen (p) : (size_t) (e - p);
4481 for (c = soundhw; c->name; ++c) {
4482 if (!strncmp (c->name, p, l)) {
4483 c->enabled = 1;
4484 break;
4488 if (!c->name) {
4489 if (l > 80) {
4490 fprintf (stderr,
4491 "Unknown sound card name (too big to show)\n");
4493 else {
4494 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4495 (int) l, p);
4497 bad_card = 1;
4499 p += l + (e != NULL);
4502 if (bad_card)
4503 goto show_valid_cards;
4506 #endif
4508 static void select_vgahw (const char *p)
4510 const char *opts;
4512 if (strstart(p, "std", &opts)) {
4513 std_vga_enabled = 1;
4514 cirrus_vga_enabled = 0;
4515 vmsvga_enabled = 0;
4516 } else if (strstart(p, "cirrus", &opts)) {
4517 cirrus_vga_enabled = 1;
4518 std_vga_enabled = 0;
4519 vmsvga_enabled = 0;
4520 } else if (strstart(p, "vmware", &opts)) {
4521 cirrus_vga_enabled = 0;
4522 std_vga_enabled = 0;
4523 vmsvga_enabled = 1;
4524 } else if (strstart(p, "none", &opts)) {
4525 cirrus_vga_enabled = 0;
4526 std_vga_enabled = 0;
4527 vmsvga_enabled = 0;
4528 } else {
4529 invalid_vga:
4530 fprintf(stderr, "Unknown vga type: %s\n", p);
4531 exit(1);
4533 while (*opts) {
4534 const char *nextopt;
4536 if (strstart(opts, ",retrace=", &nextopt)) {
4537 opts = nextopt;
4538 if (strstart(opts, "dumb", &nextopt))
4539 vga_retrace_method = VGA_RETRACE_DUMB;
4540 else if (strstart(opts, "precise", &nextopt))
4541 vga_retrace_method = VGA_RETRACE_PRECISE;
4542 else goto invalid_vga;
4543 } else goto invalid_vga;
4544 opts = nextopt;
4548 #ifdef _WIN32
4549 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4551 exit(STATUS_CONTROL_C_EXIT);
4552 return TRUE;
4554 #endif
4556 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4558 int ret;
4560 if(strlen(str) != 36)
4561 return -1;
4563 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4564 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4565 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4567 if(ret != 16)
4568 return -1;
4570 return 0;
4573 #define MAX_NET_CLIENTS 32
4575 #ifndef _WIN32
4577 static void termsig_handler(int signal)
4579 qemu_system_shutdown_request();
4582 static void termsig_setup(void)
4584 struct sigaction act;
4586 memset(&act, 0, sizeof(act));
4587 act.sa_handler = termsig_handler;
4588 sigaction(SIGINT, &act, NULL);
4589 sigaction(SIGHUP, &act, NULL);
4590 sigaction(SIGTERM, &act, NULL);
4593 #endif
4595 int main(int argc, char **argv, char **envp)
4597 #ifdef CONFIG_GDBSTUB
4598 int use_gdbstub;
4599 const char *gdbstub_port;
4600 #endif
4601 uint32_t boot_devices_bitmap = 0;
4602 int i;
4603 int snapshot, linux_boot, net_boot;
4604 const char *initrd_filename;
4605 const char *kernel_filename, *kernel_cmdline;
4606 const char *boot_devices = "";
4607 DisplayState *ds;
4608 DisplayChangeListener *dcl;
4609 int cyls, heads, secs, translation;
4610 const char *net_clients[MAX_NET_CLIENTS];
4611 int nb_net_clients;
4612 const char *bt_opts[MAX_BT_CMDLINE];
4613 int nb_bt_opts;
4614 int hda_index;
4615 int optind;
4616 const char *r, *optarg;
4617 CharDriverState *monitor_hd = NULL;
4618 const char *monitor_device;
4619 const char *serial_devices[MAX_SERIAL_PORTS];
4620 int serial_device_index;
4621 const char *parallel_devices[MAX_PARALLEL_PORTS];
4622 int parallel_device_index;
4623 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4624 int virtio_console_index;
4625 const char *loadvm = NULL;
4626 QEMUMachine *machine;
4627 const char *cpu_model;
4628 const char *usb_devices[MAX_USB_CMDLINE];
4629 int usb_devices_index;
4630 int fds[2];
4631 int tb_size;
4632 const char *pid_file = NULL;
4633 const char *incoming = NULL;
4634 int fd = 0;
4635 struct passwd *pwd = NULL;
4636 const char *chroot_dir = NULL;
4637 const char *run_as = NULL;
4639 qemu_cache_utils_init(envp);
4641 LIST_INIT (&vm_change_state_head);
4642 #ifndef _WIN32
4644 struct sigaction act;
4645 sigfillset(&act.sa_mask);
4646 act.sa_flags = 0;
4647 act.sa_handler = SIG_IGN;
4648 sigaction(SIGPIPE, &act, NULL);
4650 #else
4651 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4652 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4653 QEMU to run on a single CPU */
4655 HANDLE h;
4656 DWORD mask, smask;
4657 int i;
4658 h = GetCurrentProcess();
4659 if (GetProcessAffinityMask(h, &mask, &smask)) {
4660 for(i = 0; i < 32; i++) {
4661 if (mask & (1 << i))
4662 break;
4664 if (i != 32) {
4665 mask = 1 << i;
4666 SetProcessAffinityMask(h, mask);
4670 #endif
4672 register_machines();
4673 machine = first_machine;
4674 cpu_model = NULL;
4675 initrd_filename = NULL;
4676 ram_size = 0;
4677 vga_ram_size = VGA_RAM_SIZE;
4678 #ifdef CONFIG_GDBSTUB
4679 use_gdbstub = 0;
4680 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4681 #endif
4682 snapshot = 0;
4683 nographic = 0;
4684 curses = 0;
4685 kernel_filename = NULL;
4686 kernel_cmdline = "";
4687 cyls = heads = secs = 0;
4688 translation = BIOS_ATA_TRANSLATION_AUTO;
4689 monitor_device = "vc:80Cx24C";
4691 serial_devices[0] = "vc:80Cx24C";
4692 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4693 serial_devices[i] = NULL;
4694 serial_device_index = 0;
4696 parallel_devices[0] = "vc:80Cx24C";
4697 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4698 parallel_devices[i] = NULL;
4699 parallel_device_index = 0;
4701 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4702 virtio_consoles[i] = NULL;
4703 virtio_console_index = 0;
4705 usb_devices_index = 0;
4707 nb_net_clients = 0;
4708 nb_bt_opts = 0;
4709 nb_drives = 0;
4710 nb_drives_opt = 0;
4711 hda_index = -1;
4713 nb_nics = 0;
4715 tb_size = 0;
4716 autostart= 1;
4718 optind = 1;
4719 for(;;) {
4720 if (optind >= argc)
4721 break;
4722 r = argv[optind];
4723 if (r[0] != '-') {
4724 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4725 } else {
4726 const QEMUOption *popt;
4728 optind++;
4729 /* Treat --foo the same as -foo. */
4730 if (r[1] == '-')
4731 r++;
4732 popt = qemu_options;
4733 for(;;) {
4734 if (!popt->name) {
4735 fprintf(stderr, "%s: invalid option -- '%s'\n",
4736 argv[0], r);
4737 exit(1);
4739 if (!strcmp(popt->name, r + 1))
4740 break;
4741 popt++;
4743 if (popt->flags & HAS_ARG) {
4744 if (optind >= argc) {
4745 fprintf(stderr, "%s: option '%s' requires an argument\n",
4746 argv[0], r);
4747 exit(1);
4749 optarg = argv[optind++];
4750 } else {
4751 optarg = NULL;
4754 switch(popt->index) {
4755 case QEMU_OPTION_M:
4756 machine = find_machine(optarg);
4757 if (!machine) {
4758 QEMUMachine *m;
4759 printf("Supported machines are:\n");
4760 for(m = first_machine; m != NULL; m = m->next) {
4761 printf("%-10s %s%s\n",
4762 m->name, m->desc,
4763 m == first_machine ? " (default)" : "");
4765 exit(*optarg != '?');
4767 break;
4768 case QEMU_OPTION_cpu:
4769 /* hw initialization will check this */
4770 if (*optarg == '?') {
4771 /* XXX: implement xxx_cpu_list for targets that still miss it */
4772 #if defined(cpu_list)
4773 cpu_list(stdout, &fprintf);
4774 #endif
4775 exit(0);
4776 } else {
4777 cpu_model = optarg;
4779 break;
4780 case QEMU_OPTION_initrd:
4781 initrd_filename = optarg;
4782 break;
4783 case QEMU_OPTION_hda:
4784 if (cyls == 0)
4785 hda_index = drive_add(optarg, HD_ALIAS, 0);
4786 else
4787 hda_index = drive_add(optarg, HD_ALIAS
4788 ",cyls=%d,heads=%d,secs=%d%s",
4789 0, cyls, heads, secs,
4790 translation == BIOS_ATA_TRANSLATION_LBA ?
4791 ",trans=lba" :
4792 translation == BIOS_ATA_TRANSLATION_NONE ?
4793 ",trans=none" : "");
4794 break;
4795 case QEMU_OPTION_hdb:
4796 case QEMU_OPTION_hdc:
4797 case QEMU_OPTION_hdd:
4798 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4799 break;
4800 case QEMU_OPTION_drive:
4801 drive_add(NULL, "%s", optarg);
4802 break;
4803 case QEMU_OPTION_mtdblock:
4804 drive_add(optarg, MTD_ALIAS);
4805 break;
4806 case QEMU_OPTION_sd:
4807 drive_add(optarg, SD_ALIAS);
4808 break;
4809 case QEMU_OPTION_pflash:
4810 drive_add(optarg, PFLASH_ALIAS);
4811 break;
4812 case QEMU_OPTION_snapshot:
4813 snapshot = 1;
4814 break;
4815 case QEMU_OPTION_hdachs:
4817 const char *p;
4818 p = optarg;
4819 cyls = strtol(p, (char **)&p, 0);
4820 if (cyls < 1 || cyls > 16383)
4821 goto chs_fail;
4822 if (*p != ',')
4823 goto chs_fail;
4824 p++;
4825 heads = strtol(p, (char **)&p, 0);
4826 if (heads < 1 || heads > 16)
4827 goto chs_fail;
4828 if (*p != ',')
4829 goto chs_fail;
4830 p++;
4831 secs = strtol(p, (char **)&p, 0);
4832 if (secs < 1 || secs > 63)
4833 goto chs_fail;
4834 if (*p == ',') {
4835 p++;
4836 if (!strcmp(p, "none"))
4837 translation = BIOS_ATA_TRANSLATION_NONE;
4838 else if (!strcmp(p, "lba"))
4839 translation = BIOS_ATA_TRANSLATION_LBA;
4840 else if (!strcmp(p, "auto"))
4841 translation = BIOS_ATA_TRANSLATION_AUTO;
4842 else
4843 goto chs_fail;
4844 } else if (*p != '\0') {
4845 chs_fail:
4846 fprintf(stderr, "qemu: invalid physical CHS format\n");
4847 exit(1);
4849 if (hda_index != -1)
4850 snprintf(drives_opt[hda_index].opt,
4851 sizeof(drives_opt[hda_index].opt),
4852 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4853 0, cyls, heads, secs,
4854 translation == BIOS_ATA_TRANSLATION_LBA ?
4855 ",trans=lba" :
4856 translation == BIOS_ATA_TRANSLATION_NONE ?
4857 ",trans=none" : "");
4859 break;
4860 case QEMU_OPTION_nographic:
4861 nographic = 1;
4862 break;
4863 #ifdef CONFIG_CURSES
4864 case QEMU_OPTION_curses:
4865 curses = 1;
4866 break;
4867 #endif
4868 case QEMU_OPTION_portrait:
4869 graphic_rotate = 1;
4870 break;
4871 case QEMU_OPTION_kernel:
4872 kernel_filename = optarg;
4873 break;
4874 case QEMU_OPTION_append:
4875 kernel_cmdline = optarg;
4876 break;
4877 case QEMU_OPTION_cdrom:
4878 drive_add(optarg, CDROM_ALIAS);
4879 break;
4880 case QEMU_OPTION_boot:
4881 boot_devices = optarg;
4882 /* We just do some generic consistency checks */
4884 /* Could easily be extended to 64 devices if needed */
4885 const char *p;
4887 boot_devices_bitmap = 0;
4888 for (p = boot_devices; *p != '\0'; p++) {
4889 /* Allowed boot devices are:
4890 * a b : floppy disk drives
4891 * c ... f : IDE disk drives
4892 * g ... m : machine implementation dependant drives
4893 * n ... p : network devices
4894 * It's up to each machine implementation to check
4895 * if the given boot devices match the actual hardware
4896 * implementation and firmware features.
4898 if (*p < 'a' || *p > 'q') {
4899 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4900 exit(1);
4902 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4903 fprintf(stderr,
4904 "Boot device '%c' was given twice\n",*p);
4905 exit(1);
4907 boot_devices_bitmap |= 1 << (*p - 'a');
4910 break;
4911 case QEMU_OPTION_fda:
4912 case QEMU_OPTION_fdb:
4913 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4914 break;
4915 #ifdef TARGET_I386
4916 case QEMU_OPTION_no_fd_bootchk:
4917 fd_bootchk = 0;
4918 break;
4919 #endif
4920 case QEMU_OPTION_net:
4921 if (nb_net_clients >= MAX_NET_CLIENTS) {
4922 fprintf(stderr, "qemu: too many network clients\n");
4923 exit(1);
4925 net_clients[nb_net_clients] = optarg;
4926 nb_net_clients++;
4927 break;
4928 #ifdef CONFIG_SLIRP
4929 case QEMU_OPTION_tftp:
4930 tftp_prefix = optarg;
4931 break;
4932 case QEMU_OPTION_bootp:
4933 bootp_filename = optarg;
4934 break;
4935 #ifndef _WIN32
4936 case QEMU_OPTION_smb:
4937 net_slirp_smb(optarg);
4938 break;
4939 #endif
4940 case QEMU_OPTION_redir:
4941 net_slirp_redir(optarg);
4942 break;
4943 #endif
4944 case QEMU_OPTION_bt:
4945 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4946 fprintf(stderr, "qemu: too many bluetooth options\n");
4947 exit(1);
4949 bt_opts[nb_bt_opts++] = optarg;
4950 break;
4951 #ifdef HAS_AUDIO
4952 case QEMU_OPTION_audio_help:
4953 AUD_help ();
4954 exit (0);
4955 break;
4956 case QEMU_OPTION_soundhw:
4957 select_soundhw (optarg);
4958 break;
4959 #endif
4960 case QEMU_OPTION_h:
4961 help(0);
4962 break;
4963 case QEMU_OPTION_m: {
4964 uint64_t value;
4965 char *ptr;
4967 value = strtoul(optarg, &ptr, 10);
4968 switch (*ptr) {
4969 case 0: case 'M': case 'm':
4970 value <<= 20;
4971 break;
4972 case 'G': case 'g':
4973 value <<= 30;
4974 break;
4975 default:
4976 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4977 exit(1);
4980 /* On 32-bit hosts, QEMU is limited by virtual address space */
4981 if (value > (2047 << 20)
4982 #ifndef USE_KQEMU
4983 && HOST_LONG_BITS == 32
4984 #endif
4986 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4987 exit(1);
4989 if (value != (uint64_t)(ram_addr_t)value) {
4990 fprintf(stderr, "qemu: ram size too large\n");
4991 exit(1);
4993 ram_size = value;
4994 break;
4996 case QEMU_OPTION_d:
4998 int mask;
4999 const CPULogItem *item;
5001 mask = cpu_str_to_log_mask(optarg);
5002 if (!mask) {
5003 printf("Log items (comma separated):\n");
5004 for(item = cpu_log_items; item->mask != 0; item++) {
5005 printf("%-10s %s\n", item->name, item->help);
5007 exit(1);
5009 cpu_set_log(mask);
5011 break;
5012 #ifdef CONFIG_GDBSTUB
5013 case QEMU_OPTION_s:
5014 use_gdbstub = 1;
5015 break;
5016 case QEMU_OPTION_p:
5017 gdbstub_port = optarg;
5018 break;
5019 #endif
5020 case QEMU_OPTION_L:
5021 bios_dir = optarg;
5022 break;
5023 case QEMU_OPTION_bios:
5024 bios_name = optarg;
5025 break;
5026 case QEMU_OPTION_S:
5027 autostart = 0;
5028 break;
5029 case QEMU_OPTION_k:
5030 keyboard_layout = optarg;
5031 break;
5032 case QEMU_OPTION_localtime:
5033 rtc_utc = 0;
5034 break;
5035 case QEMU_OPTION_vga:
5036 select_vgahw (optarg);
5037 break;
5038 case QEMU_OPTION_g:
5040 const char *p;
5041 int w, h, depth;
5042 p = optarg;
5043 w = strtol(p, (char **)&p, 10);
5044 if (w <= 0) {
5045 graphic_error:
5046 fprintf(stderr, "qemu: invalid resolution or depth\n");
5047 exit(1);
5049 if (*p != 'x')
5050 goto graphic_error;
5051 p++;
5052 h = strtol(p, (char **)&p, 10);
5053 if (h <= 0)
5054 goto graphic_error;
5055 if (*p == 'x') {
5056 p++;
5057 depth = strtol(p, (char **)&p, 10);
5058 if (depth != 8 && depth != 15 && depth != 16 &&
5059 depth != 24 && depth != 32)
5060 goto graphic_error;
5061 } else if (*p == '\0') {
5062 depth = graphic_depth;
5063 } else {
5064 goto graphic_error;
5067 graphic_width = w;
5068 graphic_height = h;
5069 graphic_depth = depth;
5071 break;
5072 case QEMU_OPTION_echr:
5074 char *r;
5075 term_escape_char = strtol(optarg, &r, 0);
5076 if (r == optarg)
5077 printf("Bad argument to echr\n");
5078 break;
5080 case QEMU_OPTION_monitor:
5081 monitor_device = optarg;
5082 break;
5083 case QEMU_OPTION_serial:
5084 if (serial_device_index >= MAX_SERIAL_PORTS) {
5085 fprintf(stderr, "qemu: too many serial ports\n");
5086 exit(1);
5088 serial_devices[serial_device_index] = optarg;
5089 serial_device_index++;
5090 break;
5091 case QEMU_OPTION_virtiocon:
5092 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5093 fprintf(stderr, "qemu: too many virtio consoles\n");
5094 exit(1);
5096 virtio_consoles[virtio_console_index] = optarg;
5097 virtio_console_index++;
5098 break;
5099 case QEMU_OPTION_parallel:
5100 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5101 fprintf(stderr, "qemu: too many parallel ports\n");
5102 exit(1);
5104 parallel_devices[parallel_device_index] = optarg;
5105 parallel_device_index++;
5106 break;
5107 case QEMU_OPTION_loadvm:
5108 loadvm = optarg;
5109 break;
5110 case QEMU_OPTION_full_screen:
5111 full_screen = 1;
5112 break;
5113 #ifdef CONFIG_SDL
5114 case QEMU_OPTION_no_frame:
5115 no_frame = 1;
5116 break;
5117 case QEMU_OPTION_alt_grab:
5118 alt_grab = 1;
5119 break;
5120 case QEMU_OPTION_no_quit:
5121 no_quit = 1;
5122 break;
5123 case QEMU_OPTION_sdl:
5124 sdl = 1;
5125 break;
5126 #endif
5127 case QEMU_OPTION_pidfile:
5128 pid_file = optarg;
5129 break;
5130 #ifdef TARGET_I386
5131 case QEMU_OPTION_win2k_hack:
5132 win2k_install_hack = 1;
5133 break;
5134 case QEMU_OPTION_rtc_td_hack:
5135 rtc_td_hack = 1;
5136 break;
5137 case QEMU_OPTION_acpitable:
5138 if(acpi_table_add(optarg) < 0) {
5139 fprintf(stderr, "Wrong acpi table provided\n");
5140 exit(1);
5142 break;
5143 #endif
5144 #ifdef USE_KQEMU
5145 case QEMU_OPTION_no_kqemu:
5146 kqemu_allowed = 0;
5147 break;
5148 case QEMU_OPTION_kernel_kqemu:
5149 kqemu_allowed = 2;
5150 break;
5151 #endif
5152 #ifdef CONFIG_KVM
5153 case QEMU_OPTION_enable_kvm:
5154 kvm_allowed = 1;
5155 #ifdef USE_KQEMU
5156 kqemu_allowed = 0;
5157 #endif
5158 break;
5159 #endif
5160 case QEMU_OPTION_usb:
5161 usb_enabled = 1;
5162 break;
5163 case QEMU_OPTION_usbdevice:
5164 usb_enabled = 1;
5165 if (usb_devices_index >= MAX_USB_CMDLINE) {
5166 fprintf(stderr, "Too many USB devices\n");
5167 exit(1);
5169 usb_devices[usb_devices_index] = optarg;
5170 usb_devices_index++;
5171 break;
5172 case QEMU_OPTION_smp:
5173 smp_cpus = atoi(optarg);
5174 if (smp_cpus < 1) {
5175 fprintf(stderr, "Invalid number of CPUs\n");
5176 exit(1);
5178 break;
5179 case QEMU_OPTION_vnc:
5180 vnc_display = optarg;
5181 break;
5182 case QEMU_OPTION_no_acpi:
5183 acpi_enabled = 0;
5184 break;
5185 case QEMU_OPTION_no_hpet:
5186 no_hpet = 1;
5187 break;
5188 case QEMU_OPTION_no_reboot:
5189 no_reboot = 1;
5190 break;
5191 case QEMU_OPTION_no_shutdown:
5192 no_shutdown = 1;
5193 break;
5194 case QEMU_OPTION_show_cursor:
5195 cursor_hide = 0;
5196 break;
5197 case QEMU_OPTION_uuid:
5198 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5199 fprintf(stderr, "Fail to parse UUID string."
5200 " Wrong format.\n");
5201 exit(1);
5203 break;
5204 case QEMU_OPTION_daemonize:
5205 daemonize = 1;
5206 break;
5207 case QEMU_OPTION_option_rom:
5208 if (nb_option_roms >= MAX_OPTION_ROMS) {
5209 fprintf(stderr, "Too many option ROMs\n");
5210 exit(1);
5212 option_rom[nb_option_roms] = optarg;
5213 nb_option_roms++;
5214 break;
5215 case QEMU_OPTION_semihosting:
5216 semihosting_enabled = 1;
5217 break;
5218 case QEMU_OPTION_name:
5219 qemu_name = optarg;
5220 break;
5221 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5222 case QEMU_OPTION_prom_env:
5223 if (nb_prom_envs >= MAX_PROM_ENVS) {
5224 fprintf(stderr, "Too many prom variables\n");
5225 exit(1);
5227 prom_envs[nb_prom_envs] = optarg;
5228 nb_prom_envs++;
5229 break;
5230 #endif
5231 #ifdef TARGET_ARM
5232 case QEMU_OPTION_old_param:
5233 old_param = 1;
5234 break;
5235 #endif
5236 case QEMU_OPTION_clock:
5237 configure_alarms(optarg);
5238 break;
5239 case QEMU_OPTION_startdate:
5241 struct tm tm;
5242 time_t rtc_start_date;
5243 if (!strcmp(optarg, "now")) {
5244 rtc_date_offset = -1;
5245 } else {
5246 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5247 &tm.tm_year,
5248 &tm.tm_mon,
5249 &tm.tm_mday,
5250 &tm.tm_hour,
5251 &tm.tm_min,
5252 &tm.tm_sec) == 6) {
5253 /* OK */
5254 } else if (sscanf(optarg, "%d-%d-%d",
5255 &tm.tm_year,
5256 &tm.tm_mon,
5257 &tm.tm_mday) == 3) {
5258 tm.tm_hour = 0;
5259 tm.tm_min = 0;
5260 tm.tm_sec = 0;
5261 } else {
5262 goto date_fail;
5264 tm.tm_year -= 1900;
5265 tm.tm_mon--;
5266 rtc_start_date = mktimegm(&tm);
5267 if (rtc_start_date == -1) {
5268 date_fail:
5269 fprintf(stderr, "Invalid date format. Valid format are:\n"
5270 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5271 exit(1);
5273 rtc_date_offset = time(NULL) - rtc_start_date;
5276 break;
5277 case QEMU_OPTION_tb_size:
5278 tb_size = strtol(optarg, NULL, 0);
5279 if (tb_size < 0)
5280 tb_size = 0;
5281 break;
5282 case QEMU_OPTION_icount:
5283 use_icount = 1;
5284 if (strcmp(optarg, "auto") == 0) {
5285 icount_time_shift = -1;
5286 } else {
5287 icount_time_shift = strtol(optarg, NULL, 0);
5289 break;
5290 case QEMU_OPTION_incoming:
5291 incoming = optarg;
5292 break;
5293 case QEMU_OPTION_chroot:
5294 chroot_dir = optarg;
5295 break;
5296 case QEMU_OPTION_runas:
5297 run_as = optarg;
5298 break;
5303 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5304 if (kvm_allowed && kqemu_allowed) {
5305 fprintf(stderr,
5306 "You can not enable both KVM and kqemu at the same time\n");
5307 exit(1);
5309 #endif
5311 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5312 if (smp_cpus > machine->max_cpus) {
5313 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5314 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5315 machine->max_cpus);
5316 exit(1);
5319 if (nographic) {
5320 if (serial_device_index == 0)
5321 serial_devices[0] = "stdio";
5322 if (parallel_device_index == 0)
5323 parallel_devices[0] = "null";
5324 if (strncmp(monitor_device, "vc", 2) == 0)
5325 monitor_device = "stdio";
5328 #ifndef _WIN32
5329 if (daemonize) {
5330 pid_t pid;
5332 if (pipe(fds) == -1)
5333 exit(1);
5335 pid = fork();
5336 if (pid > 0) {
5337 uint8_t status;
5338 ssize_t len;
5340 close(fds[1]);
5342 again:
5343 len = read(fds[0], &status, 1);
5344 if (len == -1 && (errno == EINTR))
5345 goto again;
5347 if (len != 1)
5348 exit(1);
5349 else if (status == 1) {
5350 fprintf(stderr, "Could not acquire pidfile\n");
5351 exit(1);
5352 } else
5353 exit(0);
5354 } else if (pid < 0)
5355 exit(1);
5357 setsid();
5359 pid = fork();
5360 if (pid > 0)
5361 exit(0);
5362 else if (pid < 0)
5363 exit(1);
5365 umask(027);
5367 signal(SIGTSTP, SIG_IGN);
5368 signal(SIGTTOU, SIG_IGN);
5369 signal(SIGTTIN, SIG_IGN);
5371 #endif
5373 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5374 if (daemonize) {
5375 uint8_t status = 1;
5376 write(fds[1], &status, 1);
5377 } else
5378 fprintf(stderr, "Could not acquire pid file\n");
5379 exit(1);
5382 #ifdef USE_KQEMU
5383 if (smp_cpus > 1)
5384 kqemu_allowed = 0;
5385 #endif
5386 linux_boot = (kernel_filename != NULL);
5387 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5389 if (!linux_boot && net_boot == 0 &&
5390 !machine->nodisk_ok && nb_drives_opt == 0)
5391 help(1);
5393 if (!linux_boot && *kernel_cmdline != '\0') {
5394 fprintf(stderr, "-append only allowed with -kernel option\n");
5395 exit(1);
5398 if (!linux_boot && initrd_filename != NULL) {
5399 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5400 exit(1);
5403 /* boot to floppy or the default cd if no hard disk defined yet */
5404 if (!boot_devices[0]) {
5405 boot_devices = "cad";
5407 setvbuf(stdout, NULL, _IOLBF, 0);
5409 init_timers();
5410 if (init_timer_alarm() < 0) {
5411 fprintf(stderr, "could not initialize alarm timer\n");
5412 exit(1);
5414 if (use_icount && icount_time_shift < 0) {
5415 use_icount = 2;
5416 /* 125MIPS seems a reasonable initial guess at the guest speed.
5417 It will be corrected fairly quickly anyway. */
5418 icount_time_shift = 3;
5419 init_icount_adjust();
5422 #ifdef _WIN32
5423 socket_init();
5424 #endif
5426 /* init network clients */
5427 if (nb_net_clients == 0) {
5428 /* if no clients, we use a default config */
5429 net_clients[nb_net_clients++] = "nic";
5430 #ifdef CONFIG_SLIRP
5431 net_clients[nb_net_clients++] = "user";
5432 #endif
5435 for(i = 0;i < nb_net_clients; i++) {
5436 if (net_client_parse(net_clients[i]) < 0)
5437 exit(1);
5439 net_client_check();
5441 #ifdef TARGET_I386
5442 /* XXX: this should be moved in the PC machine instantiation code */
5443 if (net_boot != 0) {
5444 int netroms = 0;
5445 for (i = 0; i < nb_nics && i < 4; i++) {
5446 const char *model = nd_table[i].model;
5447 char buf[1024];
5448 if (net_boot & (1 << i)) {
5449 if (model == NULL)
5450 model = "ne2k_pci";
5451 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5452 if (get_image_size(buf) > 0) {
5453 if (nb_option_roms >= MAX_OPTION_ROMS) {
5454 fprintf(stderr, "Too many option ROMs\n");
5455 exit(1);
5457 option_rom[nb_option_roms] = strdup(buf);
5458 nb_option_roms++;
5459 netroms++;
5463 if (netroms == 0) {
5464 fprintf(stderr, "No valid PXE rom found for network device\n");
5465 exit(1);
5468 #endif
5470 /* init the bluetooth world */
5471 for (i = 0; i < nb_bt_opts; i++)
5472 if (bt_parse(bt_opts[i]))
5473 exit(1);
5475 /* init the memory */
5476 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5478 if (machine->ram_require & RAMSIZE_FIXED) {
5479 if (ram_size > 0) {
5480 if (ram_size < phys_ram_size) {
5481 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5482 machine->name, (unsigned long long) phys_ram_size);
5483 exit(-1);
5486 phys_ram_size = ram_size;
5487 } else
5488 ram_size = phys_ram_size;
5489 } else {
5490 if (ram_size == 0)
5491 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5493 phys_ram_size += ram_size;
5496 phys_ram_base = qemu_vmalloc(phys_ram_size);
5497 if (!phys_ram_base) {
5498 fprintf(stderr, "Could not allocate physical memory\n");
5499 exit(1);
5502 /* init the dynamic translator */
5503 cpu_exec_init_all(tb_size * 1024 * 1024);
5505 bdrv_init();
5507 /* we always create the cdrom drive, even if no disk is there */
5509 if (nb_drives_opt < MAX_DRIVES)
5510 drive_add(NULL, CDROM_ALIAS);
5512 /* we always create at least one floppy */
5514 if (nb_drives_opt < MAX_DRIVES)
5515 drive_add(NULL, FD_ALIAS, 0);
5517 /* we always create one sd slot, even if no card is in it */
5519 if (nb_drives_opt < MAX_DRIVES)
5520 drive_add(NULL, SD_ALIAS);
5522 /* open the virtual block devices */
5524 for(i = 0; i < nb_drives_opt; i++)
5525 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5526 exit(1);
5528 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5529 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5531 #ifndef _WIN32
5532 /* must be after terminal init, SDL library changes signal handlers */
5533 termsig_setup();
5534 #endif
5536 /* Maintain compatibility with multiple stdio monitors */
5537 if (!strcmp(monitor_device,"stdio")) {
5538 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5539 const char *devname = serial_devices[i];
5540 if (devname && !strcmp(devname,"mon:stdio")) {
5541 monitor_device = NULL;
5542 break;
5543 } else if (devname && !strcmp(devname,"stdio")) {
5544 monitor_device = NULL;
5545 serial_devices[i] = "mon:stdio";
5546 break;
5551 if (kvm_enabled()) {
5552 int ret;
5554 ret = kvm_init(smp_cpus);
5555 if (ret < 0) {
5556 fprintf(stderr, "failed to initialize KVM\n");
5557 exit(1);
5561 if (monitor_device) {
5562 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5563 if (!monitor_hd) {
5564 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5565 exit(1);
5569 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5570 const char *devname = serial_devices[i];
5571 if (devname && strcmp(devname, "none")) {
5572 char label[32];
5573 snprintf(label, sizeof(label), "serial%d", i);
5574 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5575 if (!serial_hds[i]) {
5576 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5577 devname);
5578 exit(1);
5583 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5584 const char *devname = parallel_devices[i];
5585 if (devname && strcmp(devname, "none")) {
5586 char label[32];
5587 snprintf(label, sizeof(label), "parallel%d", i);
5588 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5589 if (!parallel_hds[i]) {
5590 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5591 devname);
5592 exit(1);
5597 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5598 const char *devname = virtio_consoles[i];
5599 if (devname && strcmp(devname, "none")) {
5600 char label[32];
5601 snprintf(label, sizeof(label), "virtcon%d", i);
5602 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5603 if (!virtcon_hds[i]) {
5604 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5605 devname);
5606 exit(1);
5611 machine->init(ram_size, vga_ram_size, boot_devices,
5612 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5614 current_machine = machine;
5616 /* Set KVM's vcpu state to qemu's initial CPUState. */
5617 if (kvm_enabled()) {
5618 int ret;
5620 ret = kvm_sync_vcpus();
5621 if (ret < 0) {
5622 fprintf(stderr, "failed to initialize vcpus\n");
5623 exit(1);
5627 /* init USB devices */
5628 if (usb_enabled) {
5629 for(i = 0; i < usb_devices_index; i++) {
5630 if (usb_device_add(usb_devices[i], 0) < 0) {
5631 fprintf(stderr, "Warning: could not add USB device %s\n",
5632 usb_devices[i]);
5637 if (!display_state)
5638 dumb_display_init();
5639 /* just use the first displaystate for the moment */
5640 ds = display_state;
5641 /* terminal init */
5642 if (nographic) {
5643 if (curses) {
5644 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5645 exit(1);
5647 } else {
5648 #if defined(CONFIG_CURSES)
5649 if (curses) {
5650 /* At the moment curses cannot be used with other displays */
5651 curses_display_init(ds, full_screen);
5652 } else
5653 #endif
5655 if (vnc_display != NULL) {
5656 vnc_display_init(ds);
5657 if (vnc_display_open(ds, vnc_display) < 0)
5658 exit(1);
5660 #if defined(CONFIG_SDL)
5661 if (sdl || !vnc_display)
5662 sdl_display_init(ds, full_screen, no_frame);
5663 #elif defined(CONFIG_COCOA)
5664 if (sdl || !vnc_display)
5665 cocoa_display_init(ds, full_screen);
5666 #endif
5669 dpy_resize(ds);
5671 dcl = ds->listeners;
5672 while (dcl != NULL) {
5673 if (dcl->dpy_refresh != NULL) {
5674 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5675 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5677 dcl = dcl->next;
5680 if (nographic || (vnc_display && !sdl)) {
5681 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5682 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5685 text_consoles_set_display(display_state);
5686 qemu_chr_initial_reset();
5688 if (monitor_device && monitor_hd)
5689 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5691 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5692 const char *devname = serial_devices[i];
5693 if (devname && strcmp(devname, "none")) {
5694 char label[32];
5695 snprintf(label, sizeof(label), "serial%d", i);
5696 if (strstart(devname, "vc", 0))
5697 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5701 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5702 const char *devname = parallel_devices[i];
5703 if (devname && strcmp(devname, "none")) {
5704 char label[32];
5705 snprintf(label, sizeof(label), "parallel%d", i);
5706 if (strstart(devname, "vc", 0))
5707 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5711 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5712 const char *devname = virtio_consoles[i];
5713 if (virtcon_hds[i] && devname) {
5714 char label[32];
5715 snprintf(label, sizeof(label), "virtcon%d", i);
5716 if (strstart(devname, "vc", 0))
5717 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5721 #ifdef CONFIG_GDBSTUB
5722 if (use_gdbstub) {
5723 /* XXX: use standard host:port notation and modify options
5724 accordingly. */
5725 if (gdbserver_start(gdbstub_port) < 0) {
5726 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5727 gdbstub_port);
5728 exit(1);
5731 #endif
5733 if (loadvm)
5734 do_loadvm(cur_mon, loadvm);
5736 if (incoming) {
5737 autostart = 0; /* fixme how to deal with -daemonize */
5738 qemu_start_incoming_migration(incoming);
5741 if (autostart)
5742 vm_start();
5744 if (daemonize) {
5745 uint8_t status = 0;
5746 ssize_t len;
5748 again1:
5749 len = write(fds[1], &status, 1);
5750 if (len == -1 && (errno == EINTR))
5751 goto again1;
5753 if (len != 1)
5754 exit(1);
5756 chdir("/");
5757 TFR(fd = open("/dev/null", O_RDWR));
5758 if (fd == -1)
5759 exit(1);
5762 #ifndef _WIN32
5763 if (run_as) {
5764 pwd = getpwnam(run_as);
5765 if (!pwd) {
5766 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5767 exit(1);
5771 if (chroot_dir) {
5772 if (chroot(chroot_dir) < 0) {
5773 fprintf(stderr, "chroot failed\n");
5774 exit(1);
5776 chdir("/");
5779 if (run_as) {
5780 if (setgid(pwd->pw_gid) < 0) {
5781 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5782 exit(1);
5784 if (setuid(pwd->pw_uid) < 0) {
5785 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5786 exit(1);
5788 if (setuid(0) != -1) {
5789 fprintf(stderr, "Dropping privileges failed\n");
5790 exit(1);
5793 #endif
5795 if (daemonize) {
5796 dup2(fd, 0);
5797 dup2(fd, 1);
5798 dup2(fd, 2);
5800 close(fd);
5803 main_loop();
5804 quit_timers();
5805 net_cleanup();
5807 return 0;