Add host_device support to qemu-img. (Nolan Leake)
[qemu-kvm/fedora.git] / vl.c
blob5e6c621f2d5d25b4376daff28d291a11e2ee789a
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 "bt-host.h"
142 #include "net.h"
143 #include "monitor.h"
144 #include "console.h"
145 #include "sysemu.h"
146 #include "gdbstub.h"
147 #include "qemu-timer.h"
148 #include "qemu-char.h"
149 #include "cache-utils.h"
150 #include "block.h"
151 #include "dma.h"
152 #include "audio/audio.h"
153 #include "migration.h"
154 #include "kvm.h"
155 #include "balloon.h"
157 #include "disas.h"
159 #include "exec-all.h"
161 #include "qemu_socket.h"
163 #if defined(CONFIG_SLIRP)
164 #include "libslirp.h"
165 #endif
167 //#define DEBUG_UNUSED_IOPORT
168 //#define DEBUG_IOPORT
169 //#define DEBUG_NET
170 //#define DEBUG_SLIRP
173 #ifdef DEBUG_IOPORT
174 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
175 #else
176 # define LOG_IOPORT(...) do { } while (0)
177 #endif
179 #define DEFAULT_RAM_SIZE 128
181 /* Max number of USB devices that can be specified on the commandline. */
182 #define MAX_USB_CMDLINE 8
184 /* Max number of bluetooth switches on the commandline. */
185 #define MAX_BT_CMDLINE 10
187 /* XXX: use a two level table to limit memory usage */
188 #define MAX_IOPORTS 65536
190 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
191 const char *bios_name = NULL;
192 static void *ioport_opaque[MAX_IOPORTS];
193 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
194 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
195 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
196 to store the VM snapshots */
197 DriveInfo drives_table[MAX_DRIVES+1];
198 int nb_drives;
199 static int vga_ram_size;
200 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
201 static DisplayState *display_state;
202 int nographic;
203 static int curses;
204 static int sdl;
205 const char* keyboard_layout = NULL;
206 int64_t ticks_per_sec;
207 ram_addr_t ram_size;
208 int nb_nics;
209 NICInfo nd_table[MAX_NICS];
210 int vm_running;
211 static int autostart;
212 static int rtc_utc = 1;
213 static int rtc_date_offset = -1; /* -1 means no change */
214 int cirrus_vga_enabled = 1;
215 int std_vga_enabled = 0;
216 int vmsvga_enabled = 0;
217 #ifdef TARGET_SPARC
218 int graphic_width = 1024;
219 int graphic_height = 768;
220 int graphic_depth = 8;
221 #else
222 int graphic_width = 800;
223 int graphic_height = 600;
224 int graphic_depth = 15;
225 #endif
226 static int full_screen = 0;
227 #ifdef CONFIG_SDL
228 static int no_frame = 0;
229 #endif
230 int no_quit = 0;
231 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
232 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
233 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
234 #ifdef TARGET_I386
235 int win2k_install_hack = 0;
236 int rtc_td_hack = 0;
237 #endif
238 int usb_enabled = 0;
239 int smp_cpus = 1;
240 const char *vnc_display;
241 int acpi_enabled = 1;
242 int no_hpet = 0;
243 int fd_bootchk = 1;
244 int no_reboot = 0;
245 int no_shutdown = 0;
246 int cursor_hide = 1;
247 int graphic_rotate = 0;
248 int daemonize = 0;
249 const char *option_rom[MAX_OPTION_ROMS];
250 int nb_option_roms;
251 int semihosting_enabled = 0;
252 #ifdef TARGET_ARM
253 int old_param = 0;
254 #endif
255 const char *qemu_name;
256 int alt_grab = 0;
257 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
258 unsigned int nb_prom_envs = 0;
259 const char *prom_envs[MAX_PROM_ENVS];
260 #endif
261 int nb_drives_opt;
262 struct drive_opt drives_opt[MAX_DRIVES];
264 static CPUState *cur_cpu;
265 static CPUState *next_cpu;
266 static int event_pending = 1;
267 /* Conversion factor from emulated instructions to virtual clock ticks. */
268 static int icount_time_shift;
269 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
270 #define MAX_ICOUNT_SHIFT 10
271 /* Compensate for varying guest execution speed. */
272 static int64_t qemu_icount_bias;
273 static QEMUTimer *icount_rt_timer;
274 static QEMUTimer *icount_vm_timer;
275 static QEMUTimer *nographic_timer;
277 uint8_t qemu_uuid[16];
279 /***********************************************************/
280 /* x86 ISA bus support */
282 target_phys_addr_t isa_mem_base = 0;
283 PicState2 *isa_pic;
285 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
286 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
288 static uint32_t ioport_read(int index, uint32_t address)
290 static IOPortReadFunc *default_func[3] = {
291 default_ioport_readb,
292 default_ioport_readw,
293 default_ioport_readl
295 IOPortReadFunc *func = ioport_read_table[index][address];
296 if (!func)
297 func = default_func[index];
298 return func(ioport_opaque[address], address);
301 static void ioport_write(int index, uint32_t address, uint32_t data)
303 static IOPortWriteFunc *default_func[3] = {
304 default_ioport_writeb,
305 default_ioport_writew,
306 default_ioport_writel
308 IOPortWriteFunc *func = ioport_write_table[index][address];
309 if (!func)
310 func = default_func[index];
311 func(ioport_opaque[address], address, data);
314 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
316 #ifdef DEBUG_UNUSED_IOPORT
317 fprintf(stderr, "unused inb: port=0x%04x\n", address);
318 #endif
319 return 0xff;
322 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
324 #ifdef DEBUG_UNUSED_IOPORT
325 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
326 #endif
329 /* default is to make two byte accesses */
330 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
332 uint32_t data;
333 data = ioport_read(0, address);
334 address = (address + 1) & (MAX_IOPORTS - 1);
335 data |= ioport_read(0, address) << 8;
336 return data;
339 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
341 ioport_write(0, address, data & 0xff);
342 address = (address + 1) & (MAX_IOPORTS - 1);
343 ioport_write(0, address, (data >> 8) & 0xff);
346 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
348 #ifdef DEBUG_UNUSED_IOPORT
349 fprintf(stderr, "unused inl: port=0x%04x\n", address);
350 #endif
351 return 0xffffffff;
354 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
356 #ifdef DEBUG_UNUSED_IOPORT
357 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
358 #endif
361 /* size is the word size in byte */
362 int register_ioport_read(int start, int length, int size,
363 IOPortReadFunc *func, void *opaque)
365 int i, bsize;
367 if (size == 1) {
368 bsize = 0;
369 } else if (size == 2) {
370 bsize = 1;
371 } else if (size == 4) {
372 bsize = 2;
373 } else {
374 hw_error("register_ioport_read: invalid size");
375 return -1;
377 for(i = start; i < start + length; i += size) {
378 ioport_read_table[bsize][i] = func;
379 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
380 hw_error("register_ioport_read: invalid opaque");
381 ioport_opaque[i] = opaque;
383 return 0;
386 /* size is the word size in byte */
387 int register_ioport_write(int start, int length, int size,
388 IOPortWriteFunc *func, void *opaque)
390 int i, bsize;
392 if (size == 1) {
393 bsize = 0;
394 } else if (size == 2) {
395 bsize = 1;
396 } else if (size == 4) {
397 bsize = 2;
398 } else {
399 hw_error("register_ioport_write: invalid size");
400 return -1;
402 for(i = start; i < start + length; i += size) {
403 ioport_write_table[bsize][i] = func;
404 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
405 hw_error("register_ioport_write: invalid opaque");
406 ioport_opaque[i] = opaque;
408 return 0;
411 void isa_unassign_ioport(int start, int length)
413 int i;
415 for(i = start; i < start + length; i++) {
416 ioport_read_table[0][i] = default_ioport_readb;
417 ioport_read_table[1][i] = default_ioport_readw;
418 ioport_read_table[2][i] = default_ioport_readl;
420 ioport_write_table[0][i] = default_ioport_writeb;
421 ioport_write_table[1][i] = default_ioport_writew;
422 ioport_write_table[2][i] = default_ioport_writel;
424 ioport_opaque[i] = NULL;
428 /***********************************************************/
430 void cpu_outb(CPUState *env, int addr, int val)
432 LOG_IOPORT("outb: %04x %02x\n", addr, val);
433 ioport_write(0, addr, val);
434 #ifdef USE_KQEMU
435 if (env)
436 env->last_io_time = cpu_get_time_fast();
437 #endif
440 void cpu_outw(CPUState *env, int addr, int val)
442 LOG_IOPORT("outw: %04x %04x\n", addr, val);
443 ioport_write(1, addr, val);
444 #ifdef USE_KQEMU
445 if (env)
446 env->last_io_time = cpu_get_time_fast();
447 #endif
450 void cpu_outl(CPUState *env, int addr, int val)
452 LOG_IOPORT("outl: %04x %08x\n", addr, val);
453 ioport_write(2, addr, val);
454 #ifdef USE_KQEMU
455 if (env)
456 env->last_io_time = cpu_get_time_fast();
457 #endif
460 int cpu_inb(CPUState *env, int addr)
462 int val;
463 val = ioport_read(0, addr);
464 LOG_IOPORT("inb : %04x %02x\n", addr, val);
465 #ifdef USE_KQEMU
466 if (env)
467 env->last_io_time = cpu_get_time_fast();
468 #endif
469 return val;
472 int cpu_inw(CPUState *env, int addr)
474 int val;
475 val = ioport_read(1, addr);
476 LOG_IOPORT("inw : %04x %04x\n", addr, val);
477 #ifdef USE_KQEMU
478 if (env)
479 env->last_io_time = cpu_get_time_fast();
480 #endif
481 return val;
484 int cpu_inl(CPUState *env, int addr)
486 int val;
487 val = ioport_read(2, addr);
488 LOG_IOPORT("inl : %04x %08x\n", addr, val);
489 #ifdef USE_KQEMU
490 if (env)
491 env->last_io_time = cpu_get_time_fast();
492 #endif
493 return val;
496 /***********************************************************/
497 void hw_error(const char *fmt, ...)
499 va_list ap;
500 CPUState *env;
502 va_start(ap, fmt);
503 fprintf(stderr, "qemu: hardware error: ");
504 vfprintf(stderr, fmt, ap);
505 fprintf(stderr, "\n");
506 for(env = first_cpu; env != NULL; env = env->next_cpu) {
507 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
508 #ifdef TARGET_I386
509 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
510 #else
511 cpu_dump_state(env, stderr, fprintf, 0);
512 #endif
514 va_end(ap);
515 abort();
518 /***************/
519 /* ballooning */
521 static QEMUBalloonEvent *qemu_balloon_event;
522 void *qemu_balloon_event_opaque;
524 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
526 qemu_balloon_event = func;
527 qemu_balloon_event_opaque = opaque;
530 void qemu_balloon(ram_addr_t target)
532 if (qemu_balloon_event)
533 qemu_balloon_event(qemu_balloon_event_opaque, target);
536 ram_addr_t qemu_balloon_status(void)
538 if (qemu_balloon_event)
539 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
540 return 0;
543 /***********************************************************/
544 /* keyboard/mouse */
546 static QEMUPutKBDEvent *qemu_put_kbd_event;
547 static void *qemu_put_kbd_event_opaque;
548 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
549 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
551 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
553 qemu_put_kbd_event_opaque = opaque;
554 qemu_put_kbd_event = func;
557 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
558 void *opaque, int absolute,
559 const char *name)
561 QEMUPutMouseEntry *s, *cursor;
563 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
565 s->qemu_put_mouse_event = func;
566 s->qemu_put_mouse_event_opaque = opaque;
567 s->qemu_put_mouse_event_absolute = absolute;
568 s->qemu_put_mouse_event_name = qemu_strdup(name);
569 s->next = NULL;
571 if (!qemu_put_mouse_event_head) {
572 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
573 return s;
576 cursor = qemu_put_mouse_event_head;
577 while (cursor->next != NULL)
578 cursor = cursor->next;
580 cursor->next = s;
581 qemu_put_mouse_event_current = s;
583 return s;
586 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
588 QEMUPutMouseEntry *prev = NULL, *cursor;
590 if (!qemu_put_mouse_event_head || entry == NULL)
591 return;
593 cursor = qemu_put_mouse_event_head;
594 while (cursor != NULL && cursor != entry) {
595 prev = cursor;
596 cursor = cursor->next;
599 if (cursor == NULL) // does not exist or list empty
600 return;
601 else if (prev == NULL) { // entry is head
602 qemu_put_mouse_event_head = cursor->next;
603 if (qemu_put_mouse_event_current == entry)
604 qemu_put_mouse_event_current = cursor->next;
605 qemu_free(entry->qemu_put_mouse_event_name);
606 qemu_free(entry);
607 return;
610 prev->next = entry->next;
612 if (qemu_put_mouse_event_current == entry)
613 qemu_put_mouse_event_current = prev;
615 qemu_free(entry->qemu_put_mouse_event_name);
616 qemu_free(entry);
619 void kbd_put_keycode(int keycode)
621 if (qemu_put_kbd_event) {
622 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
626 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
628 QEMUPutMouseEvent *mouse_event;
629 void *mouse_event_opaque;
630 int width;
632 if (!qemu_put_mouse_event_current) {
633 return;
636 mouse_event =
637 qemu_put_mouse_event_current->qemu_put_mouse_event;
638 mouse_event_opaque =
639 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
641 if (mouse_event) {
642 if (graphic_rotate) {
643 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
644 width = 0x7fff;
645 else
646 width = graphic_width - 1;
647 mouse_event(mouse_event_opaque,
648 width - dy, dx, dz, buttons_state);
649 } else
650 mouse_event(mouse_event_opaque,
651 dx, dy, dz, buttons_state);
655 int kbd_mouse_is_absolute(void)
657 if (!qemu_put_mouse_event_current)
658 return 0;
660 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
663 void do_info_mice(Monitor *mon)
665 QEMUPutMouseEntry *cursor;
666 int index = 0;
668 if (!qemu_put_mouse_event_head) {
669 monitor_printf(mon, "No mouse devices connected\n");
670 return;
673 monitor_printf(mon, "Mouse devices available:\n");
674 cursor = qemu_put_mouse_event_head;
675 while (cursor != NULL) {
676 monitor_printf(mon, "%c Mouse #%d: %s\n",
677 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
678 index, cursor->qemu_put_mouse_event_name);
679 index++;
680 cursor = cursor->next;
684 void do_mouse_set(Monitor *mon, int index)
686 QEMUPutMouseEntry *cursor;
687 int i = 0;
689 if (!qemu_put_mouse_event_head) {
690 monitor_printf(mon, "No mouse devices connected\n");
691 return;
694 cursor = qemu_put_mouse_event_head;
695 while (cursor != NULL && index != i) {
696 i++;
697 cursor = cursor->next;
700 if (cursor != NULL)
701 qemu_put_mouse_event_current = cursor;
702 else
703 monitor_printf(mon, "Mouse at given index not found\n");
706 /* compute with 96 bit intermediate result: (a*b)/c */
707 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
709 union {
710 uint64_t ll;
711 struct {
712 #ifdef WORDS_BIGENDIAN
713 uint32_t high, low;
714 #else
715 uint32_t low, high;
716 #endif
717 } l;
718 } u, res;
719 uint64_t rl, rh;
721 u.ll = a;
722 rl = (uint64_t)u.l.low * (uint64_t)b;
723 rh = (uint64_t)u.l.high * (uint64_t)b;
724 rh += (rl >> 32);
725 res.l.high = rh / c;
726 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
727 return res.ll;
730 /***********************************************************/
731 /* real time host monotonic timer */
733 #define QEMU_TIMER_BASE 1000000000LL
735 #ifdef WIN32
737 static int64_t clock_freq;
739 static void init_get_clock(void)
741 LARGE_INTEGER freq;
742 int ret;
743 ret = QueryPerformanceFrequency(&freq);
744 if (ret == 0) {
745 fprintf(stderr, "Could not calibrate ticks\n");
746 exit(1);
748 clock_freq = freq.QuadPart;
751 static int64_t get_clock(void)
753 LARGE_INTEGER ti;
754 QueryPerformanceCounter(&ti);
755 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
758 #else
760 static int use_rt_clock;
762 static void init_get_clock(void)
764 use_rt_clock = 0;
765 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
766 || defined(__DragonFly__)
768 struct timespec ts;
769 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
770 use_rt_clock = 1;
773 #endif
776 static int64_t get_clock(void)
778 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
779 || defined(__DragonFly__)
780 if (use_rt_clock) {
781 struct timespec ts;
782 clock_gettime(CLOCK_MONOTONIC, &ts);
783 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
784 } else
785 #endif
787 /* XXX: using gettimeofday leads to problems if the date
788 changes, so it should be avoided. */
789 struct timeval tv;
790 gettimeofday(&tv, NULL);
791 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
794 #endif
796 /* Return the virtual CPU time, based on the instruction counter. */
797 static int64_t cpu_get_icount(void)
799 int64_t icount;
800 CPUState *env = cpu_single_env;;
801 icount = qemu_icount;
802 if (env) {
803 if (!can_do_io(env))
804 fprintf(stderr, "Bad clock read\n");
805 icount -= (env->icount_decr.u16.low + env->icount_extra);
807 return qemu_icount_bias + (icount << icount_time_shift);
810 /***********************************************************/
811 /* guest cycle counter */
813 static int64_t cpu_ticks_prev;
814 static int64_t cpu_ticks_offset;
815 static int64_t cpu_clock_offset;
816 static int cpu_ticks_enabled;
818 /* return the host CPU cycle counter and handle stop/restart */
819 int64_t cpu_get_ticks(void)
821 if (use_icount) {
822 return cpu_get_icount();
824 if (!cpu_ticks_enabled) {
825 return cpu_ticks_offset;
826 } else {
827 int64_t ticks;
828 ticks = cpu_get_real_ticks();
829 if (cpu_ticks_prev > ticks) {
830 /* Note: non increasing ticks may happen if the host uses
831 software suspend */
832 cpu_ticks_offset += cpu_ticks_prev - ticks;
834 cpu_ticks_prev = ticks;
835 return ticks + cpu_ticks_offset;
839 /* return the host CPU monotonic timer and handle stop/restart */
840 static int64_t cpu_get_clock(void)
842 int64_t ti;
843 if (!cpu_ticks_enabled) {
844 return cpu_clock_offset;
845 } else {
846 ti = get_clock();
847 return ti + cpu_clock_offset;
851 /* enable cpu_get_ticks() */
852 void cpu_enable_ticks(void)
854 if (!cpu_ticks_enabled) {
855 cpu_ticks_offset -= cpu_get_real_ticks();
856 cpu_clock_offset -= get_clock();
857 cpu_ticks_enabled = 1;
861 /* disable cpu_get_ticks() : the clock is stopped. You must not call
862 cpu_get_ticks() after that. */
863 void cpu_disable_ticks(void)
865 if (cpu_ticks_enabled) {
866 cpu_ticks_offset = cpu_get_ticks();
867 cpu_clock_offset = cpu_get_clock();
868 cpu_ticks_enabled = 0;
872 /***********************************************************/
873 /* timers */
875 #define QEMU_TIMER_REALTIME 0
876 #define QEMU_TIMER_VIRTUAL 1
878 struct QEMUClock {
879 int type;
880 /* XXX: add frequency */
883 struct QEMUTimer {
884 QEMUClock *clock;
885 int64_t expire_time;
886 QEMUTimerCB *cb;
887 void *opaque;
888 struct QEMUTimer *next;
891 struct qemu_alarm_timer {
892 char const *name;
893 unsigned int flags;
895 int (*start)(struct qemu_alarm_timer *t);
896 void (*stop)(struct qemu_alarm_timer *t);
897 void (*rearm)(struct qemu_alarm_timer *t);
898 void *priv;
901 #define ALARM_FLAG_DYNTICKS 0x1
902 #define ALARM_FLAG_EXPIRED 0x2
904 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
906 return t->flags & ALARM_FLAG_DYNTICKS;
909 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
911 if (!alarm_has_dynticks(t))
912 return;
914 t->rearm(t);
917 /* TODO: MIN_TIMER_REARM_US should be optimized */
918 #define MIN_TIMER_REARM_US 250
920 static struct qemu_alarm_timer *alarm_timer;
921 #ifndef _WIN32
922 static int alarm_timer_rfd, alarm_timer_wfd;
923 #endif
925 #ifdef _WIN32
927 struct qemu_alarm_win32 {
928 MMRESULT timerId;
929 HANDLE host_alarm;
930 unsigned int period;
931 } alarm_win32_data = {0, NULL, -1};
933 static int win32_start_timer(struct qemu_alarm_timer *t);
934 static void win32_stop_timer(struct qemu_alarm_timer *t);
935 static void win32_rearm_timer(struct qemu_alarm_timer *t);
937 #else
939 static int unix_start_timer(struct qemu_alarm_timer *t);
940 static void unix_stop_timer(struct qemu_alarm_timer *t);
942 #ifdef __linux__
944 static int dynticks_start_timer(struct qemu_alarm_timer *t);
945 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
946 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
948 static int hpet_start_timer(struct qemu_alarm_timer *t);
949 static void hpet_stop_timer(struct qemu_alarm_timer *t);
951 static int rtc_start_timer(struct qemu_alarm_timer *t);
952 static void rtc_stop_timer(struct qemu_alarm_timer *t);
954 #endif /* __linux__ */
956 #endif /* _WIN32 */
958 /* Correlation between real and virtual time is always going to be
959 fairly approximate, so ignore small variation.
960 When the guest is idle real and virtual time will be aligned in
961 the IO wait loop. */
962 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
964 static void icount_adjust(void)
966 int64_t cur_time;
967 int64_t cur_icount;
968 int64_t delta;
969 static int64_t last_delta;
970 /* If the VM is not running, then do nothing. */
971 if (!vm_running)
972 return;
974 cur_time = cpu_get_clock();
975 cur_icount = qemu_get_clock(vm_clock);
976 delta = cur_icount - cur_time;
977 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
978 if (delta > 0
979 && last_delta + ICOUNT_WOBBLE < delta * 2
980 && icount_time_shift > 0) {
981 /* The guest is getting too far ahead. Slow time down. */
982 icount_time_shift--;
984 if (delta < 0
985 && last_delta - ICOUNT_WOBBLE > delta * 2
986 && icount_time_shift < MAX_ICOUNT_SHIFT) {
987 /* The guest is getting too far behind. Speed time up. */
988 icount_time_shift++;
990 last_delta = delta;
991 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
994 static void icount_adjust_rt(void * opaque)
996 qemu_mod_timer(icount_rt_timer,
997 qemu_get_clock(rt_clock) + 1000);
998 icount_adjust();
1001 static void icount_adjust_vm(void * opaque)
1003 qemu_mod_timer(icount_vm_timer,
1004 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1005 icount_adjust();
1008 static void init_icount_adjust(void)
1010 /* Have both realtime and virtual time triggers for speed adjustment.
1011 The realtime trigger catches emulated time passing too slowly,
1012 the virtual time trigger catches emulated time passing too fast.
1013 Realtime triggers occur even when idle, so use them less frequently
1014 than VM triggers. */
1015 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1016 qemu_mod_timer(icount_rt_timer,
1017 qemu_get_clock(rt_clock) + 1000);
1018 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1019 qemu_mod_timer(icount_vm_timer,
1020 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1023 static struct qemu_alarm_timer alarm_timers[] = {
1024 #ifndef _WIN32
1025 #ifdef __linux__
1026 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1027 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1028 /* HPET - if available - is preferred */
1029 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1030 /* ...otherwise try RTC */
1031 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1032 #endif
1033 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1034 #else
1035 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1036 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1037 {"win32", 0, win32_start_timer,
1038 win32_stop_timer, NULL, &alarm_win32_data},
1039 #endif
1040 {NULL, }
1043 static void show_available_alarms(void)
1045 int i;
1047 printf("Available alarm timers, in order of precedence:\n");
1048 for (i = 0; alarm_timers[i].name; i++)
1049 printf("%s\n", alarm_timers[i].name);
1052 static void configure_alarms(char const *opt)
1054 int i;
1055 int cur = 0;
1056 int count = ARRAY_SIZE(alarm_timers) - 1;
1057 char *arg;
1058 char *name;
1059 struct qemu_alarm_timer tmp;
1061 if (!strcmp(opt, "?")) {
1062 show_available_alarms();
1063 exit(0);
1066 arg = strdup(opt);
1068 /* Reorder the array */
1069 name = strtok(arg, ",");
1070 while (name) {
1071 for (i = 0; i < count && alarm_timers[i].name; i++) {
1072 if (!strcmp(alarm_timers[i].name, name))
1073 break;
1076 if (i == count) {
1077 fprintf(stderr, "Unknown clock %s\n", name);
1078 goto next;
1081 if (i < cur)
1082 /* Ignore */
1083 goto next;
1085 /* Swap */
1086 tmp = alarm_timers[i];
1087 alarm_timers[i] = alarm_timers[cur];
1088 alarm_timers[cur] = tmp;
1090 cur++;
1091 next:
1092 name = strtok(NULL, ",");
1095 free(arg);
1097 if (cur) {
1098 /* Disable remaining timers */
1099 for (i = cur; i < count; i++)
1100 alarm_timers[i].name = NULL;
1101 } else {
1102 show_available_alarms();
1103 exit(1);
1107 QEMUClock *rt_clock;
1108 QEMUClock *vm_clock;
1110 static QEMUTimer *active_timers[2];
1112 static QEMUClock *qemu_new_clock(int type)
1114 QEMUClock *clock;
1115 clock = qemu_mallocz(sizeof(QEMUClock));
1116 clock->type = type;
1117 return clock;
1120 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1122 QEMUTimer *ts;
1124 ts = qemu_mallocz(sizeof(QEMUTimer));
1125 ts->clock = clock;
1126 ts->cb = cb;
1127 ts->opaque = opaque;
1128 return ts;
1131 void qemu_free_timer(QEMUTimer *ts)
1133 qemu_free(ts);
1136 /* stop a timer, but do not dealloc it */
1137 void qemu_del_timer(QEMUTimer *ts)
1139 QEMUTimer **pt, *t;
1141 /* NOTE: this code must be signal safe because
1142 qemu_timer_expired() can be called from a signal. */
1143 pt = &active_timers[ts->clock->type];
1144 for(;;) {
1145 t = *pt;
1146 if (!t)
1147 break;
1148 if (t == ts) {
1149 *pt = t->next;
1150 break;
1152 pt = &t->next;
1156 /* modify the current timer so that it will be fired when current_time
1157 >= expire_time. The corresponding callback will be called. */
1158 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1160 QEMUTimer **pt, *t;
1162 qemu_del_timer(ts);
1164 /* add the timer in the sorted list */
1165 /* NOTE: this code must be signal safe because
1166 qemu_timer_expired() can be called from a signal. */
1167 pt = &active_timers[ts->clock->type];
1168 for(;;) {
1169 t = *pt;
1170 if (!t)
1171 break;
1172 if (t->expire_time > expire_time)
1173 break;
1174 pt = &t->next;
1176 ts->expire_time = expire_time;
1177 ts->next = *pt;
1178 *pt = ts;
1180 /* Rearm if necessary */
1181 if (pt == &active_timers[ts->clock->type]) {
1182 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1183 qemu_rearm_alarm_timer(alarm_timer);
1185 /* Interrupt execution to force deadline recalculation. */
1186 if (use_icount && cpu_single_env) {
1187 cpu_exit(cpu_single_env);
1192 int qemu_timer_pending(QEMUTimer *ts)
1194 QEMUTimer *t;
1195 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1196 if (t == ts)
1197 return 1;
1199 return 0;
1202 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1204 if (!timer_head)
1205 return 0;
1206 return (timer_head->expire_time <= current_time);
1209 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1211 QEMUTimer *ts;
1213 for(;;) {
1214 ts = *ptimer_head;
1215 if (!ts || ts->expire_time > current_time)
1216 break;
1217 /* remove timer from the list before calling the callback */
1218 *ptimer_head = ts->next;
1219 ts->next = NULL;
1221 /* run the callback (the timer list can be modified) */
1222 ts->cb(ts->opaque);
1226 int64_t qemu_get_clock(QEMUClock *clock)
1228 switch(clock->type) {
1229 case QEMU_TIMER_REALTIME:
1230 return get_clock() / 1000000;
1231 default:
1232 case QEMU_TIMER_VIRTUAL:
1233 if (use_icount) {
1234 return cpu_get_icount();
1235 } else {
1236 return cpu_get_clock();
1241 static void init_timers(void)
1243 init_get_clock();
1244 ticks_per_sec = QEMU_TIMER_BASE;
1245 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1246 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1249 /* save a timer */
1250 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1252 uint64_t expire_time;
1254 if (qemu_timer_pending(ts)) {
1255 expire_time = ts->expire_time;
1256 } else {
1257 expire_time = -1;
1259 qemu_put_be64(f, expire_time);
1262 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1264 uint64_t expire_time;
1266 expire_time = qemu_get_be64(f);
1267 if (expire_time != -1) {
1268 qemu_mod_timer(ts, expire_time);
1269 } else {
1270 qemu_del_timer(ts);
1274 static void timer_save(QEMUFile *f, void *opaque)
1276 if (cpu_ticks_enabled) {
1277 hw_error("cannot save state if virtual timers are running");
1279 qemu_put_be64(f, cpu_ticks_offset);
1280 qemu_put_be64(f, ticks_per_sec);
1281 qemu_put_be64(f, cpu_clock_offset);
1284 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1286 if (version_id != 1 && version_id != 2)
1287 return -EINVAL;
1288 if (cpu_ticks_enabled) {
1289 return -EINVAL;
1291 cpu_ticks_offset=qemu_get_be64(f);
1292 ticks_per_sec=qemu_get_be64(f);
1293 if (version_id == 2) {
1294 cpu_clock_offset=qemu_get_be64(f);
1296 return 0;
1299 #ifdef _WIN32
1300 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1301 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1302 #else
1303 static void host_alarm_handler(int host_signum)
1304 #endif
1306 #if 0
1307 #define DISP_FREQ 1000
1309 static int64_t delta_min = INT64_MAX;
1310 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1311 static int count;
1312 ti = qemu_get_clock(vm_clock);
1313 if (last_clock != 0) {
1314 delta = ti - last_clock;
1315 if (delta < delta_min)
1316 delta_min = delta;
1317 if (delta > delta_max)
1318 delta_max = delta;
1319 delta_cum += delta;
1320 if (++count == DISP_FREQ) {
1321 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1322 muldiv64(delta_min, 1000000, ticks_per_sec),
1323 muldiv64(delta_max, 1000000, ticks_per_sec),
1324 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1325 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1326 count = 0;
1327 delta_min = INT64_MAX;
1328 delta_max = 0;
1329 delta_cum = 0;
1332 last_clock = ti;
1334 #endif
1335 if (alarm_has_dynticks(alarm_timer) ||
1336 (!use_icount &&
1337 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1338 qemu_get_clock(vm_clock))) ||
1339 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1340 qemu_get_clock(rt_clock))) {
1341 CPUState *env = next_cpu;
1343 #ifdef _WIN32
1344 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1345 SetEvent(data->host_alarm);
1346 #else
1347 static const char byte = 0;
1348 write(alarm_timer_wfd, &byte, sizeof(byte));
1349 #endif
1350 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1352 if (env) {
1353 /* stop the currently executing cpu because a timer occured */
1354 cpu_exit(env);
1355 #ifdef USE_KQEMU
1356 if (env->kqemu_enabled) {
1357 kqemu_cpu_interrupt(env);
1359 #endif
1361 event_pending = 1;
1365 static int64_t qemu_next_deadline(void)
1367 int64_t delta;
1369 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1370 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1371 qemu_get_clock(vm_clock);
1372 } else {
1373 /* To avoid problems with overflow limit this to 2^32. */
1374 delta = INT32_MAX;
1377 if (delta < 0)
1378 delta = 0;
1380 return delta;
1383 #if defined(__linux__) || defined(_WIN32)
1384 static uint64_t qemu_next_deadline_dyntick(void)
1386 int64_t delta;
1387 int64_t rtdelta;
1389 if (use_icount)
1390 delta = INT32_MAX;
1391 else
1392 delta = (qemu_next_deadline() + 999) / 1000;
1394 if (active_timers[QEMU_TIMER_REALTIME]) {
1395 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1396 qemu_get_clock(rt_clock))*1000;
1397 if (rtdelta < delta)
1398 delta = rtdelta;
1401 if (delta < MIN_TIMER_REARM_US)
1402 delta = MIN_TIMER_REARM_US;
1404 return delta;
1406 #endif
1408 #ifndef _WIN32
1410 /* Sets a specific flag */
1411 static int fcntl_setfl(int fd, int flag)
1413 int flags;
1415 flags = fcntl(fd, F_GETFL);
1416 if (flags == -1)
1417 return -errno;
1419 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1420 return -errno;
1422 return 0;
1425 #if defined(__linux__)
1427 #define RTC_FREQ 1024
1429 static void enable_sigio_timer(int fd)
1431 struct sigaction act;
1433 /* timer signal */
1434 sigfillset(&act.sa_mask);
1435 act.sa_flags = 0;
1436 act.sa_handler = host_alarm_handler;
1438 sigaction(SIGIO, &act, NULL);
1439 fcntl_setfl(fd, O_ASYNC);
1440 fcntl(fd, F_SETOWN, getpid());
1443 static int hpet_start_timer(struct qemu_alarm_timer *t)
1445 struct hpet_info info;
1446 int r, fd;
1448 fd = open("/dev/hpet", O_RDONLY);
1449 if (fd < 0)
1450 return -1;
1452 /* Set frequency */
1453 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1454 if (r < 0) {
1455 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1456 "error, but for better emulation accuracy type:\n"
1457 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1458 goto fail;
1461 /* Check capabilities */
1462 r = ioctl(fd, HPET_INFO, &info);
1463 if (r < 0)
1464 goto fail;
1466 /* Enable periodic mode */
1467 r = ioctl(fd, HPET_EPI, 0);
1468 if (info.hi_flags && (r < 0))
1469 goto fail;
1471 /* Enable interrupt */
1472 r = ioctl(fd, HPET_IE_ON, 0);
1473 if (r < 0)
1474 goto fail;
1476 enable_sigio_timer(fd);
1477 t->priv = (void *)(long)fd;
1479 return 0;
1480 fail:
1481 close(fd);
1482 return -1;
1485 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1487 int fd = (long)t->priv;
1489 close(fd);
1492 static int rtc_start_timer(struct qemu_alarm_timer *t)
1494 int rtc_fd;
1495 unsigned long current_rtc_freq = 0;
1497 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1498 if (rtc_fd < 0)
1499 return -1;
1500 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1501 if (current_rtc_freq != RTC_FREQ &&
1502 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1503 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1504 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1505 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1506 goto fail;
1508 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1509 fail:
1510 close(rtc_fd);
1511 return -1;
1514 enable_sigio_timer(rtc_fd);
1516 t->priv = (void *)(long)rtc_fd;
1518 return 0;
1521 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1523 int rtc_fd = (long)t->priv;
1525 close(rtc_fd);
1528 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1530 struct sigevent ev;
1531 timer_t host_timer;
1532 struct sigaction act;
1534 sigfillset(&act.sa_mask);
1535 act.sa_flags = 0;
1536 act.sa_handler = host_alarm_handler;
1538 sigaction(SIGALRM, &act, NULL);
1540 ev.sigev_value.sival_int = 0;
1541 ev.sigev_notify = SIGEV_SIGNAL;
1542 ev.sigev_signo = SIGALRM;
1544 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1545 perror("timer_create");
1547 /* disable dynticks */
1548 fprintf(stderr, "Dynamic Ticks disabled\n");
1550 return -1;
1553 t->priv = (void *)(long)host_timer;
1555 return 0;
1558 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1560 timer_t host_timer = (timer_t)(long)t->priv;
1562 timer_delete(host_timer);
1565 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1567 timer_t host_timer = (timer_t)(long)t->priv;
1568 struct itimerspec timeout;
1569 int64_t nearest_delta_us = INT64_MAX;
1570 int64_t current_us;
1572 if (!active_timers[QEMU_TIMER_REALTIME] &&
1573 !active_timers[QEMU_TIMER_VIRTUAL])
1574 return;
1576 nearest_delta_us = qemu_next_deadline_dyntick();
1578 /* check whether a timer is already running */
1579 if (timer_gettime(host_timer, &timeout)) {
1580 perror("gettime");
1581 fprintf(stderr, "Internal timer error: aborting\n");
1582 exit(1);
1584 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1585 if (current_us && current_us <= nearest_delta_us)
1586 return;
1588 timeout.it_interval.tv_sec = 0;
1589 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1590 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1591 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1592 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1593 perror("settime");
1594 fprintf(stderr, "Internal timer error: aborting\n");
1595 exit(1);
1599 #endif /* defined(__linux__) */
1601 static int unix_start_timer(struct qemu_alarm_timer *t)
1603 struct sigaction act;
1604 struct itimerval itv;
1605 int err;
1607 /* timer signal */
1608 sigfillset(&act.sa_mask);
1609 act.sa_flags = 0;
1610 act.sa_handler = host_alarm_handler;
1612 sigaction(SIGALRM, &act, NULL);
1614 itv.it_interval.tv_sec = 0;
1615 /* for i386 kernel 2.6 to get 1 ms */
1616 itv.it_interval.tv_usec = 999;
1617 itv.it_value.tv_sec = 0;
1618 itv.it_value.tv_usec = 10 * 1000;
1620 err = setitimer(ITIMER_REAL, &itv, NULL);
1621 if (err)
1622 return -1;
1624 return 0;
1627 static void unix_stop_timer(struct qemu_alarm_timer *t)
1629 struct itimerval itv;
1631 memset(&itv, 0, sizeof(itv));
1632 setitimer(ITIMER_REAL, &itv, NULL);
1635 #endif /* !defined(_WIN32) */
1637 static void try_to_rearm_timer(void *opaque)
1639 struct qemu_alarm_timer *t = opaque;
1640 #ifndef _WIN32
1641 ssize_t len;
1643 /* Drain the notify pipe */
1644 do {
1645 char buffer[512];
1646 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1647 } while ((len == -1 && errno == EINTR) || len > 0);
1648 #endif
1650 if (t->flags & ALARM_FLAG_EXPIRED) {
1651 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1652 qemu_rearm_alarm_timer(alarm_timer);
1656 #ifdef _WIN32
1658 static int win32_start_timer(struct qemu_alarm_timer *t)
1660 TIMECAPS tc;
1661 struct qemu_alarm_win32 *data = t->priv;
1662 UINT flags;
1664 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1665 if (!data->host_alarm) {
1666 perror("Failed CreateEvent");
1667 return -1;
1670 memset(&tc, 0, sizeof(tc));
1671 timeGetDevCaps(&tc, sizeof(tc));
1673 if (data->period < tc.wPeriodMin)
1674 data->period = tc.wPeriodMin;
1676 timeBeginPeriod(data->period);
1678 flags = TIME_CALLBACK_FUNCTION;
1679 if (alarm_has_dynticks(t))
1680 flags |= TIME_ONESHOT;
1681 else
1682 flags |= TIME_PERIODIC;
1684 data->timerId = timeSetEvent(1, // interval (ms)
1685 data->period, // resolution
1686 host_alarm_handler, // function
1687 (DWORD)t, // parameter
1688 flags);
1690 if (!data->timerId) {
1691 perror("Failed to initialize win32 alarm timer");
1693 timeEndPeriod(data->period);
1694 CloseHandle(data->host_alarm);
1695 return -1;
1698 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1700 return 0;
1703 static void win32_stop_timer(struct qemu_alarm_timer *t)
1705 struct qemu_alarm_win32 *data = t->priv;
1707 timeKillEvent(data->timerId);
1708 timeEndPeriod(data->period);
1710 CloseHandle(data->host_alarm);
1713 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1715 struct qemu_alarm_win32 *data = t->priv;
1716 uint64_t nearest_delta_us;
1718 if (!active_timers[QEMU_TIMER_REALTIME] &&
1719 !active_timers[QEMU_TIMER_VIRTUAL])
1720 return;
1722 nearest_delta_us = qemu_next_deadline_dyntick();
1723 nearest_delta_us /= 1000;
1725 timeKillEvent(data->timerId);
1727 data->timerId = timeSetEvent(1,
1728 data->period,
1729 host_alarm_handler,
1730 (DWORD)t,
1731 TIME_ONESHOT | TIME_PERIODIC);
1733 if (!data->timerId) {
1734 perror("Failed to re-arm win32 alarm timer");
1736 timeEndPeriod(data->period);
1737 CloseHandle(data->host_alarm);
1738 exit(1);
1742 #endif /* _WIN32 */
1744 static int init_timer_alarm(void)
1746 struct qemu_alarm_timer *t = NULL;
1747 int i, err = -1;
1749 #ifndef _WIN32
1750 int fds[2];
1752 err = pipe(fds);
1753 if (err == -1)
1754 return -errno;
1756 err = fcntl_setfl(fds[0], O_NONBLOCK);
1757 if (err < 0)
1758 goto fail;
1760 err = fcntl_setfl(fds[1], O_NONBLOCK);
1761 if (err < 0)
1762 goto fail;
1764 alarm_timer_rfd = fds[0];
1765 alarm_timer_wfd = fds[1];
1766 #endif
1768 for (i = 0; alarm_timers[i].name; i++) {
1769 t = &alarm_timers[i];
1771 err = t->start(t);
1772 if (!err)
1773 break;
1776 if (err) {
1777 err = -ENOENT;
1778 goto fail;
1781 #ifndef _WIN32
1782 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1783 try_to_rearm_timer, NULL, t);
1784 #endif
1786 alarm_timer = t;
1788 return 0;
1790 fail:
1791 #ifndef _WIN32
1792 close(fds[0]);
1793 close(fds[1]);
1794 #endif
1795 return err;
1798 static void quit_timers(void)
1800 alarm_timer->stop(alarm_timer);
1801 alarm_timer = NULL;
1804 /***********************************************************/
1805 /* host time/date access */
1806 void qemu_get_timedate(struct tm *tm, int offset)
1808 time_t ti;
1809 struct tm *ret;
1811 time(&ti);
1812 ti += offset;
1813 if (rtc_date_offset == -1) {
1814 if (rtc_utc)
1815 ret = gmtime(&ti);
1816 else
1817 ret = localtime(&ti);
1818 } else {
1819 ti -= rtc_date_offset;
1820 ret = gmtime(&ti);
1823 memcpy(tm, ret, sizeof(struct tm));
1826 int qemu_timedate_diff(struct tm *tm)
1828 time_t seconds;
1830 if (rtc_date_offset == -1)
1831 if (rtc_utc)
1832 seconds = mktimegm(tm);
1833 else
1834 seconds = mktime(tm);
1835 else
1836 seconds = mktimegm(tm) + rtc_date_offset;
1838 return seconds - time(NULL);
1841 #ifdef _WIN32
1842 static void socket_cleanup(void)
1844 WSACleanup();
1847 static int socket_init(void)
1849 WSADATA Data;
1850 int ret, err;
1852 ret = WSAStartup(MAKEWORD(2,2), &Data);
1853 if (ret != 0) {
1854 err = WSAGetLastError();
1855 fprintf(stderr, "WSAStartup: %d\n", err);
1856 return -1;
1858 atexit(socket_cleanup);
1859 return 0;
1861 #endif
1863 const char *get_opt_name(char *buf, int buf_size, const char *p)
1865 char *q;
1867 q = buf;
1868 while (*p != '\0' && *p != '=') {
1869 if (q && (q - buf) < buf_size - 1)
1870 *q++ = *p;
1871 p++;
1873 if (q)
1874 *q = '\0';
1876 return p;
1879 const char *get_opt_value(char *buf, int buf_size, const char *p)
1881 char *q;
1883 q = buf;
1884 while (*p != '\0') {
1885 if (*p == ',') {
1886 if (*(p + 1) != ',')
1887 break;
1888 p++;
1890 if (q && (q - buf) < buf_size - 1)
1891 *q++ = *p;
1892 p++;
1894 if (q)
1895 *q = '\0';
1897 return p;
1900 int get_param_value(char *buf, int buf_size,
1901 const char *tag, const char *str)
1903 const char *p;
1904 char option[128];
1906 p = str;
1907 for(;;) {
1908 p = get_opt_name(option, sizeof(option), p);
1909 if (*p != '=')
1910 break;
1911 p++;
1912 if (!strcmp(tag, option)) {
1913 (void)get_opt_value(buf, buf_size, p);
1914 return strlen(buf);
1915 } else {
1916 p = get_opt_value(NULL, 0, p);
1918 if (*p != ',')
1919 break;
1920 p++;
1922 return 0;
1925 int check_params(char *buf, int buf_size,
1926 const char * const *params, const char *str)
1928 const char *p;
1929 int i;
1931 p = str;
1932 for(;;) {
1933 p = get_opt_name(buf, buf_size, p);
1934 if (*p != '=')
1935 return -1;
1936 p++;
1937 for(i = 0; params[i] != NULL; i++)
1938 if (!strcmp(params[i], buf))
1939 break;
1940 if (params[i] == NULL)
1941 return -1;
1942 p = get_opt_value(NULL, 0, p);
1943 if (*p != ',')
1944 break;
1945 p++;
1947 return 0;
1950 /***********************************************************/
1951 /* Bluetooth support */
1952 static int nb_hcis;
1953 static int cur_hci;
1954 static struct HCIInfo *hci_table[MAX_NICS];
1956 static struct bt_vlan_s {
1957 struct bt_scatternet_s net;
1958 int id;
1959 struct bt_vlan_s *next;
1960 } *first_bt_vlan;
1962 /* find or alloc a new bluetooth "VLAN" */
1963 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1965 struct bt_vlan_s **pvlan, *vlan;
1966 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1967 if (vlan->id == id)
1968 return &vlan->net;
1970 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1971 vlan->id = id;
1972 pvlan = &first_bt_vlan;
1973 while (*pvlan != NULL)
1974 pvlan = &(*pvlan)->next;
1975 *pvlan = vlan;
1976 return &vlan->net;
1979 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1983 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1985 return -ENOTSUP;
1988 static struct HCIInfo null_hci = {
1989 .cmd_send = null_hci_send,
1990 .sco_send = null_hci_send,
1991 .acl_send = null_hci_send,
1992 .bdaddr_set = null_hci_addr_set,
1995 struct HCIInfo *qemu_next_hci(void)
1997 if (cur_hci == nb_hcis)
1998 return &null_hci;
2000 return hci_table[cur_hci++];
2003 static struct HCIInfo *hci_init(const char *str)
2005 char *endp;
2006 struct bt_scatternet_s *vlan = 0;
2008 if (!strcmp(str, "null"))
2009 /* null */
2010 return &null_hci;
2011 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2012 /* host[:hciN] */
2013 return bt_host_hci(str[4] ? str + 5 : "hci0");
2014 else if (!strncmp(str, "hci", 3)) {
2015 /* hci[,vlan=n] */
2016 if (str[3]) {
2017 if (!strncmp(str + 3, ",vlan=", 6)) {
2018 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2019 if (*endp)
2020 vlan = 0;
2022 } else
2023 vlan = qemu_find_bt_vlan(0);
2024 if (vlan)
2025 return bt_new_hci(vlan);
2028 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2030 return 0;
2033 static int bt_hci_parse(const char *str)
2035 struct HCIInfo *hci;
2036 bdaddr_t bdaddr;
2038 if (nb_hcis >= MAX_NICS) {
2039 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2040 return -1;
2043 hci = hci_init(str);
2044 if (!hci)
2045 return -1;
2047 bdaddr.b[0] = 0x52;
2048 bdaddr.b[1] = 0x54;
2049 bdaddr.b[2] = 0x00;
2050 bdaddr.b[3] = 0x12;
2051 bdaddr.b[4] = 0x34;
2052 bdaddr.b[5] = 0x56 + nb_hcis;
2053 hci->bdaddr_set(hci, bdaddr.b);
2055 hci_table[nb_hcis++] = hci;
2057 return 0;
2060 static void bt_vhci_add(int vlan_id)
2062 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2064 if (!vlan->slave)
2065 fprintf(stderr, "qemu: warning: adding a VHCI to "
2066 "an empty scatternet %i\n", vlan_id);
2068 bt_vhci_init(bt_new_hci(vlan));
2071 static struct bt_device_s *bt_device_add(const char *opt)
2073 struct bt_scatternet_s *vlan;
2074 int vlan_id = 0;
2075 char *endp = strstr(opt, ",vlan=");
2076 int len = (endp ? endp - opt : strlen(opt)) + 1;
2077 char devname[10];
2079 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2081 if (endp) {
2082 vlan_id = strtol(endp + 6, &endp, 0);
2083 if (*endp) {
2084 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2085 return 0;
2089 vlan = qemu_find_bt_vlan(vlan_id);
2091 if (!vlan->slave)
2092 fprintf(stderr, "qemu: warning: adding a slave device to "
2093 "an empty scatternet %i\n", vlan_id);
2095 if (!strcmp(devname, "keyboard"))
2096 return bt_keyboard_init(vlan);
2098 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2099 return 0;
2102 static int bt_parse(const char *opt)
2104 const char *endp, *p;
2105 int vlan;
2107 if (strstart(opt, "hci", &endp)) {
2108 if (!*endp || *endp == ',') {
2109 if (*endp)
2110 if (!strstart(endp, ",vlan=", 0))
2111 opt = endp + 1;
2113 return bt_hci_parse(opt);
2115 } else if (strstart(opt, "vhci", &endp)) {
2116 if (!*endp || *endp == ',') {
2117 if (*endp) {
2118 if (strstart(endp, ",vlan=", &p)) {
2119 vlan = strtol(p, (char **) &endp, 0);
2120 if (*endp) {
2121 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2122 return 1;
2124 } else {
2125 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2126 return 1;
2128 } else
2129 vlan = 0;
2131 bt_vhci_add(vlan);
2132 return 0;
2134 } else if (strstart(opt, "device:", &endp))
2135 return !bt_device_add(endp);
2137 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2138 return 1;
2141 /***********************************************************/
2142 /* QEMU Block devices */
2144 #define HD_ALIAS "index=%d,media=disk"
2145 #define CDROM_ALIAS "index=2,media=cdrom"
2146 #define FD_ALIAS "index=%d,if=floppy"
2147 #define PFLASH_ALIAS "if=pflash"
2148 #define MTD_ALIAS "if=mtd"
2149 #define SD_ALIAS "index=0,if=sd"
2151 static int drive_opt_get_free_idx(void)
2153 int index;
2155 for (index = 0; index < MAX_DRIVES; index++)
2156 if (!drives_opt[index].used) {
2157 drives_opt[index].used = 1;
2158 return index;
2161 return -1;
2164 static int drive_get_free_idx(void)
2166 int index;
2168 for (index = 0; index < MAX_DRIVES; index++)
2169 if (!drives_table[index].used) {
2170 drives_table[index].used = 1;
2171 return index;
2174 return -1;
2177 int drive_add(const char *file, const char *fmt, ...)
2179 va_list ap;
2180 int index = drive_opt_get_free_idx();
2182 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2183 fprintf(stderr, "qemu: too many drives\n");
2184 return -1;
2187 drives_opt[index].file = file;
2188 va_start(ap, fmt);
2189 vsnprintf(drives_opt[index].opt,
2190 sizeof(drives_opt[0].opt), fmt, ap);
2191 va_end(ap);
2193 nb_drives_opt++;
2194 return index;
2197 void drive_remove(int index)
2199 drives_opt[index].used = 0;
2200 nb_drives_opt--;
2203 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2205 int index;
2207 /* seek interface, bus and unit */
2209 for (index = 0; index < MAX_DRIVES; index++)
2210 if (drives_table[index].type == type &&
2211 drives_table[index].bus == bus &&
2212 drives_table[index].unit == unit &&
2213 drives_table[index].used)
2214 return index;
2216 return -1;
2219 int drive_get_max_bus(BlockInterfaceType type)
2221 int max_bus;
2222 int index;
2224 max_bus = -1;
2225 for (index = 0; index < nb_drives; index++) {
2226 if(drives_table[index].type == type &&
2227 drives_table[index].bus > max_bus)
2228 max_bus = drives_table[index].bus;
2230 return max_bus;
2233 const char *drive_get_serial(BlockDriverState *bdrv)
2235 int index;
2237 for (index = 0; index < nb_drives; index++)
2238 if (drives_table[index].bdrv == bdrv)
2239 return drives_table[index].serial;
2241 return "\0";
2244 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2246 int index;
2248 for (index = 0; index < nb_drives; index++)
2249 if (drives_table[index].bdrv == bdrv)
2250 return drives_table[index].onerror;
2252 return BLOCK_ERR_STOP_ENOSPC;
2255 static void bdrv_format_print(void *opaque, const char *name)
2257 fprintf(stderr, " %s", name);
2260 void drive_uninit(BlockDriverState *bdrv)
2262 int i;
2264 for (i = 0; i < MAX_DRIVES; i++)
2265 if (drives_table[i].bdrv == bdrv) {
2266 drives_table[i].bdrv = NULL;
2267 drives_table[i].used = 0;
2268 drive_remove(drives_table[i].drive_opt_idx);
2269 nb_drives--;
2270 break;
2274 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2276 char buf[128];
2277 char file[1024];
2278 char devname[128];
2279 char serial[21];
2280 const char *mediastr = "";
2281 BlockInterfaceType type;
2282 enum { MEDIA_DISK, MEDIA_CDROM } media;
2283 int bus_id, unit_id;
2284 int cyls, heads, secs, translation;
2285 BlockDriverState *bdrv;
2286 BlockDriver *drv = NULL;
2287 QEMUMachine *machine = opaque;
2288 int max_devs;
2289 int index;
2290 int cache;
2291 int bdrv_flags, onerror;
2292 int drives_table_idx;
2293 char *str = arg->opt;
2294 static const char * const params[] = { "bus", "unit", "if", "index",
2295 "cyls", "heads", "secs", "trans",
2296 "media", "snapshot", "file",
2297 "cache", "format", "serial", "werror",
2298 NULL };
2300 if (check_params(buf, sizeof(buf), params, str) < 0) {
2301 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2302 buf, str);
2303 return -1;
2306 file[0] = 0;
2307 cyls = heads = secs = 0;
2308 bus_id = 0;
2309 unit_id = -1;
2310 translation = BIOS_ATA_TRANSLATION_AUTO;
2311 index = -1;
2312 cache = 3;
2314 if (machine->use_scsi) {
2315 type = IF_SCSI;
2316 max_devs = MAX_SCSI_DEVS;
2317 pstrcpy(devname, sizeof(devname), "scsi");
2318 } else {
2319 type = IF_IDE;
2320 max_devs = MAX_IDE_DEVS;
2321 pstrcpy(devname, sizeof(devname), "ide");
2323 media = MEDIA_DISK;
2325 /* extract parameters */
2327 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2328 bus_id = strtol(buf, NULL, 0);
2329 if (bus_id < 0) {
2330 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2331 return -1;
2335 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2336 unit_id = strtol(buf, NULL, 0);
2337 if (unit_id < 0) {
2338 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2339 return -1;
2343 if (get_param_value(buf, sizeof(buf), "if", str)) {
2344 pstrcpy(devname, sizeof(devname), buf);
2345 if (!strcmp(buf, "ide")) {
2346 type = IF_IDE;
2347 max_devs = MAX_IDE_DEVS;
2348 } else if (!strcmp(buf, "scsi")) {
2349 type = IF_SCSI;
2350 max_devs = MAX_SCSI_DEVS;
2351 } else if (!strcmp(buf, "floppy")) {
2352 type = IF_FLOPPY;
2353 max_devs = 0;
2354 } else if (!strcmp(buf, "pflash")) {
2355 type = IF_PFLASH;
2356 max_devs = 0;
2357 } else if (!strcmp(buf, "mtd")) {
2358 type = IF_MTD;
2359 max_devs = 0;
2360 } else if (!strcmp(buf, "sd")) {
2361 type = IF_SD;
2362 max_devs = 0;
2363 } else if (!strcmp(buf, "virtio")) {
2364 type = IF_VIRTIO;
2365 max_devs = 0;
2366 } else {
2367 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2368 return -1;
2372 if (get_param_value(buf, sizeof(buf), "index", str)) {
2373 index = strtol(buf, NULL, 0);
2374 if (index < 0) {
2375 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2376 return -1;
2380 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2381 cyls = strtol(buf, NULL, 0);
2384 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2385 heads = strtol(buf, NULL, 0);
2388 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2389 secs = strtol(buf, NULL, 0);
2392 if (cyls || heads || secs) {
2393 if (cyls < 1 || cyls > 16383) {
2394 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2395 return -1;
2397 if (heads < 1 || heads > 16) {
2398 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2399 return -1;
2401 if (secs < 1 || secs > 63) {
2402 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2403 return -1;
2407 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2408 if (!cyls) {
2409 fprintf(stderr,
2410 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2411 str);
2412 return -1;
2414 if (!strcmp(buf, "none"))
2415 translation = BIOS_ATA_TRANSLATION_NONE;
2416 else if (!strcmp(buf, "lba"))
2417 translation = BIOS_ATA_TRANSLATION_LBA;
2418 else if (!strcmp(buf, "auto"))
2419 translation = BIOS_ATA_TRANSLATION_AUTO;
2420 else {
2421 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2422 return -1;
2426 if (get_param_value(buf, sizeof(buf), "media", str)) {
2427 if (!strcmp(buf, "disk")) {
2428 media = MEDIA_DISK;
2429 } else if (!strcmp(buf, "cdrom")) {
2430 if (cyls || secs || heads) {
2431 fprintf(stderr,
2432 "qemu: '%s' invalid physical CHS format\n", str);
2433 return -1;
2435 media = MEDIA_CDROM;
2436 } else {
2437 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2438 return -1;
2442 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2443 if (!strcmp(buf, "on"))
2444 snapshot = 1;
2445 else if (!strcmp(buf, "off"))
2446 snapshot = 0;
2447 else {
2448 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2449 return -1;
2453 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2454 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2455 cache = 0;
2456 else if (!strcmp(buf, "writethrough"))
2457 cache = 1;
2458 else if (!strcmp(buf, "writeback"))
2459 cache = 2;
2460 else {
2461 fprintf(stderr, "qemu: invalid cache option\n");
2462 return -1;
2466 if (get_param_value(buf, sizeof(buf), "format", str)) {
2467 if (strcmp(buf, "?") == 0) {
2468 fprintf(stderr, "qemu: Supported formats:");
2469 bdrv_iterate_format(bdrv_format_print, NULL);
2470 fprintf(stderr, "\n");
2471 return -1;
2473 drv = bdrv_find_format(buf);
2474 if (!drv) {
2475 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2476 return -1;
2480 if (arg->file == NULL)
2481 get_param_value(file, sizeof(file), "file", str);
2482 else
2483 pstrcpy(file, sizeof(file), arg->file);
2485 if (!get_param_value(serial, sizeof(serial), "serial", str))
2486 memset(serial, 0, sizeof(serial));
2488 onerror = BLOCK_ERR_STOP_ENOSPC;
2489 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2490 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2491 fprintf(stderr, "werror is no supported by this format\n");
2492 return -1;
2494 if (!strcmp(buf, "ignore"))
2495 onerror = BLOCK_ERR_IGNORE;
2496 else if (!strcmp(buf, "enospc"))
2497 onerror = BLOCK_ERR_STOP_ENOSPC;
2498 else if (!strcmp(buf, "stop"))
2499 onerror = BLOCK_ERR_STOP_ANY;
2500 else if (!strcmp(buf, "report"))
2501 onerror = BLOCK_ERR_REPORT;
2502 else {
2503 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2504 return -1;
2508 /* compute bus and unit according index */
2510 if (index != -1) {
2511 if (bus_id != 0 || unit_id != -1) {
2512 fprintf(stderr,
2513 "qemu: '%s' index cannot be used with bus and unit\n", str);
2514 return -1;
2516 if (max_devs == 0)
2518 unit_id = index;
2519 bus_id = 0;
2520 } else {
2521 unit_id = index % max_devs;
2522 bus_id = index / max_devs;
2526 /* if user doesn't specify a unit_id,
2527 * try to find the first free
2530 if (unit_id == -1) {
2531 unit_id = 0;
2532 while (drive_get_index(type, bus_id, unit_id) != -1) {
2533 unit_id++;
2534 if (max_devs && unit_id >= max_devs) {
2535 unit_id -= max_devs;
2536 bus_id++;
2541 /* check unit id */
2543 if (max_devs && unit_id >= max_devs) {
2544 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2545 str, unit_id, max_devs - 1);
2546 return -1;
2550 * ignore multiple definitions
2553 if (drive_get_index(type, bus_id, unit_id) != -1)
2554 return -2;
2556 /* init */
2558 if (type == IF_IDE || type == IF_SCSI)
2559 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2560 if (max_devs)
2561 snprintf(buf, sizeof(buf), "%s%i%s%i",
2562 devname, bus_id, mediastr, unit_id);
2563 else
2564 snprintf(buf, sizeof(buf), "%s%s%i",
2565 devname, mediastr, unit_id);
2566 bdrv = bdrv_new(buf);
2567 drives_table_idx = drive_get_free_idx();
2568 drives_table[drives_table_idx].bdrv = bdrv;
2569 drives_table[drives_table_idx].type = type;
2570 drives_table[drives_table_idx].bus = bus_id;
2571 drives_table[drives_table_idx].unit = unit_id;
2572 drives_table[drives_table_idx].onerror = onerror;
2573 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2574 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2575 nb_drives++;
2577 switch(type) {
2578 case IF_IDE:
2579 case IF_SCSI:
2580 switch(media) {
2581 case MEDIA_DISK:
2582 if (cyls != 0) {
2583 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2584 bdrv_set_translation_hint(bdrv, translation);
2586 break;
2587 case MEDIA_CDROM:
2588 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2589 break;
2591 break;
2592 case IF_SD:
2593 /* FIXME: This isn't really a floppy, but it's a reasonable
2594 approximation. */
2595 case IF_FLOPPY:
2596 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2597 break;
2598 case IF_PFLASH:
2599 case IF_MTD:
2600 case IF_VIRTIO:
2601 break;
2603 if (!file[0])
2604 return -2;
2605 bdrv_flags = 0;
2606 if (snapshot) {
2607 bdrv_flags |= BDRV_O_SNAPSHOT;
2608 cache = 2; /* always use write-back with snapshot */
2610 if (cache == 0) /* no caching */
2611 bdrv_flags |= BDRV_O_NOCACHE;
2612 else if (cache == 2) /* write-back */
2613 bdrv_flags |= BDRV_O_CACHE_WB;
2614 else if (cache == 3) /* not specified */
2615 bdrv_flags |= BDRV_O_CACHE_DEF;
2616 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2617 fprintf(stderr, "qemu: could not open disk image %s\n",
2618 file);
2619 return -1;
2621 if (bdrv_key_required(bdrv))
2622 autostart = 0;
2623 return drives_table_idx;
2626 /***********************************************************/
2627 /* USB devices */
2629 static USBPort *used_usb_ports;
2630 static USBPort *free_usb_ports;
2632 /* ??? Maybe change this to register a hub to keep track of the topology. */
2633 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2634 usb_attachfn attach)
2636 port->opaque = opaque;
2637 port->index = index;
2638 port->attach = attach;
2639 port->next = free_usb_ports;
2640 free_usb_ports = port;
2643 int usb_device_add_dev(USBDevice *dev)
2645 USBPort *port;
2647 /* Find a USB port to add the device to. */
2648 port = free_usb_ports;
2649 if (!port->next) {
2650 USBDevice *hub;
2652 /* Create a new hub and chain it on. */
2653 free_usb_ports = NULL;
2654 port->next = used_usb_ports;
2655 used_usb_ports = port;
2657 hub = usb_hub_init(VM_USB_HUB_SIZE);
2658 usb_attach(port, hub);
2659 port = free_usb_ports;
2662 free_usb_ports = port->next;
2663 port->next = used_usb_ports;
2664 used_usb_ports = port;
2665 usb_attach(port, dev);
2666 return 0;
2669 static void usb_msd_password_cb(void *opaque, int err)
2671 USBDevice *dev = opaque;
2673 if (!err)
2674 usb_device_add_dev(dev);
2675 else
2676 dev->handle_destroy(dev);
2679 static int usb_device_add(const char *devname, int is_hotplug)
2681 const char *p;
2682 USBDevice *dev;
2684 if (!free_usb_ports)
2685 return -1;
2687 if (strstart(devname, "host:", &p)) {
2688 dev = usb_host_device_open(p);
2689 } else if (!strcmp(devname, "mouse")) {
2690 dev = usb_mouse_init();
2691 } else if (!strcmp(devname, "tablet")) {
2692 dev = usb_tablet_init();
2693 } else if (!strcmp(devname, "keyboard")) {
2694 dev = usb_keyboard_init();
2695 } else if (strstart(devname, "disk:", &p)) {
2696 BlockDriverState *bs;
2698 dev = usb_msd_init(p);
2699 if (!dev)
2700 return -1;
2701 bs = usb_msd_get_bdrv(dev);
2702 if (bdrv_key_required(bs)) {
2703 autostart = 0;
2704 if (is_hotplug) {
2705 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2706 dev);
2707 return 0;
2710 } else if (!strcmp(devname, "wacom-tablet")) {
2711 dev = usb_wacom_init();
2712 } else if (strstart(devname, "serial:", &p)) {
2713 dev = usb_serial_init(p);
2714 #ifdef CONFIG_BRLAPI
2715 } else if (!strcmp(devname, "braille")) {
2716 dev = usb_baum_init();
2717 #endif
2718 } else if (strstart(devname, "net:", &p)) {
2719 int nic = nb_nics;
2721 if (net_client_init("nic", p) < 0)
2722 return -1;
2723 nd_table[nic].model = "usb";
2724 dev = usb_net_init(&nd_table[nic]);
2725 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2726 dev = usb_bt_init(devname[2] ? hci_init(p) :
2727 bt_new_hci(qemu_find_bt_vlan(0)));
2728 } else {
2729 return -1;
2731 if (!dev)
2732 return -1;
2734 return usb_device_add_dev(dev);
2737 int usb_device_del_addr(int bus_num, int addr)
2739 USBPort *port;
2740 USBPort **lastp;
2741 USBDevice *dev;
2743 if (!used_usb_ports)
2744 return -1;
2746 if (bus_num != 0)
2747 return -1;
2749 lastp = &used_usb_ports;
2750 port = used_usb_ports;
2751 while (port && port->dev->addr != addr) {
2752 lastp = &port->next;
2753 port = port->next;
2756 if (!port)
2757 return -1;
2759 dev = port->dev;
2760 *lastp = port->next;
2761 usb_attach(port, NULL);
2762 dev->handle_destroy(dev);
2763 port->next = free_usb_ports;
2764 free_usb_ports = port;
2765 return 0;
2768 static int usb_device_del(const char *devname)
2770 int bus_num, addr;
2771 const char *p;
2773 if (strstart(devname, "host:", &p))
2774 return usb_host_device_close(p);
2776 if (!used_usb_ports)
2777 return -1;
2779 p = strchr(devname, '.');
2780 if (!p)
2781 return -1;
2782 bus_num = strtoul(devname, NULL, 0);
2783 addr = strtoul(p + 1, NULL, 0);
2785 return usb_device_del_addr(bus_num, addr);
2788 void do_usb_add(Monitor *mon, const char *devname)
2790 usb_device_add(devname, 1);
2793 void do_usb_del(Monitor *mon, const char *devname)
2795 usb_device_del(devname);
2798 void usb_info(Monitor *mon)
2800 USBDevice *dev;
2801 USBPort *port;
2802 const char *speed_str;
2804 if (!usb_enabled) {
2805 monitor_printf(mon, "USB support not enabled\n");
2806 return;
2809 for (port = used_usb_ports; port; port = port->next) {
2810 dev = port->dev;
2811 if (!dev)
2812 continue;
2813 switch(dev->speed) {
2814 case USB_SPEED_LOW:
2815 speed_str = "1.5";
2816 break;
2817 case USB_SPEED_FULL:
2818 speed_str = "12";
2819 break;
2820 case USB_SPEED_HIGH:
2821 speed_str = "480";
2822 break;
2823 default:
2824 speed_str = "?";
2825 break;
2827 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2828 0, dev->addr, speed_str, dev->devname);
2832 /***********************************************************/
2833 /* PCMCIA/Cardbus */
2835 static struct pcmcia_socket_entry_s {
2836 struct pcmcia_socket_s *socket;
2837 struct pcmcia_socket_entry_s *next;
2838 } *pcmcia_sockets = 0;
2840 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2842 struct pcmcia_socket_entry_s *entry;
2844 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2845 entry->socket = socket;
2846 entry->next = pcmcia_sockets;
2847 pcmcia_sockets = entry;
2850 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2852 struct pcmcia_socket_entry_s *entry, **ptr;
2854 ptr = &pcmcia_sockets;
2855 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2856 if (entry->socket == socket) {
2857 *ptr = entry->next;
2858 qemu_free(entry);
2862 void pcmcia_info(Monitor *mon)
2864 struct pcmcia_socket_entry_s *iter;
2866 if (!pcmcia_sockets)
2867 monitor_printf(mon, "No PCMCIA sockets\n");
2869 for (iter = pcmcia_sockets; iter; iter = iter->next)
2870 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2871 iter->socket->attached ? iter->socket->card_string :
2872 "Empty");
2875 /***********************************************************/
2876 /* register display */
2878 struct DisplayAllocator default_allocator = {
2879 defaultallocator_create_displaysurface,
2880 defaultallocator_resize_displaysurface,
2881 defaultallocator_free_displaysurface
2884 void register_displaystate(DisplayState *ds)
2886 DisplayState **s;
2887 s = &display_state;
2888 while (*s != NULL)
2889 s = &(*s)->next;
2890 ds->next = NULL;
2891 *s = ds;
2894 DisplayState *get_displaystate(void)
2896 return display_state;
2899 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2901 if(ds->allocator == &default_allocator) ds->allocator = da;
2902 return ds->allocator;
2905 /* dumb display */
2907 static void dumb_display_init(void)
2909 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2910 ds->allocator = &default_allocator;
2911 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2912 register_displaystate(ds);
2915 /***********************************************************/
2916 /* I/O handling */
2918 typedef struct IOHandlerRecord {
2919 int fd;
2920 IOCanRWHandler *fd_read_poll;
2921 IOHandler *fd_read;
2922 IOHandler *fd_write;
2923 int deleted;
2924 void *opaque;
2925 /* temporary data */
2926 struct pollfd *ufd;
2927 struct IOHandlerRecord *next;
2928 } IOHandlerRecord;
2930 static IOHandlerRecord *first_io_handler;
2932 /* XXX: fd_read_poll should be suppressed, but an API change is
2933 necessary in the character devices to suppress fd_can_read(). */
2934 int qemu_set_fd_handler2(int fd,
2935 IOCanRWHandler *fd_read_poll,
2936 IOHandler *fd_read,
2937 IOHandler *fd_write,
2938 void *opaque)
2940 IOHandlerRecord **pioh, *ioh;
2942 if (!fd_read && !fd_write) {
2943 pioh = &first_io_handler;
2944 for(;;) {
2945 ioh = *pioh;
2946 if (ioh == NULL)
2947 break;
2948 if (ioh->fd == fd) {
2949 ioh->deleted = 1;
2950 break;
2952 pioh = &ioh->next;
2954 } else {
2955 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2956 if (ioh->fd == fd)
2957 goto found;
2959 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2960 ioh->next = first_io_handler;
2961 first_io_handler = ioh;
2962 found:
2963 ioh->fd = fd;
2964 ioh->fd_read_poll = fd_read_poll;
2965 ioh->fd_read = fd_read;
2966 ioh->fd_write = fd_write;
2967 ioh->opaque = opaque;
2968 ioh->deleted = 0;
2970 return 0;
2973 int qemu_set_fd_handler(int fd,
2974 IOHandler *fd_read,
2975 IOHandler *fd_write,
2976 void *opaque)
2978 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2981 #ifdef _WIN32
2982 /***********************************************************/
2983 /* Polling handling */
2985 typedef struct PollingEntry {
2986 PollingFunc *func;
2987 void *opaque;
2988 struct PollingEntry *next;
2989 } PollingEntry;
2991 static PollingEntry *first_polling_entry;
2993 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2995 PollingEntry **ppe, *pe;
2996 pe = qemu_mallocz(sizeof(PollingEntry));
2997 pe->func = func;
2998 pe->opaque = opaque;
2999 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3000 *ppe = pe;
3001 return 0;
3004 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3006 PollingEntry **ppe, *pe;
3007 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3008 pe = *ppe;
3009 if (pe->func == func && pe->opaque == opaque) {
3010 *ppe = pe->next;
3011 qemu_free(pe);
3012 break;
3017 /***********************************************************/
3018 /* Wait objects support */
3019 typedef struct WaitObjects {
3020 int num;
3021 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3022 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3023 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3024 } WaitObjects;
3026 static WaitObjects wait_objects = {0};
3028 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3030 WaitObjects *w = &wait_objects;
3032 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3033 return -1;
3034 w->events[w->num] = handle;
3035 w->func[w->num] = func;
3036 w->opaque[w->num] = opaque;
3037 w->num++;
3038 return 0;
3041 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3043 int i, found;
3044 WaitObjects *w = &wait_objects;
3046 found = 0;
3047 for (i = 0; i < w->num; i++) {
3048 if (w->events[i] == handle)
3049 found = 1;
3050 if (found) {
3051 w->events[i] = w->events[i + 1];
3052 w->func[i] = w->func[i + 1];
3053 w->opaque[i] = w->opaque[i + 1];
3056 if (found)
3057 w->num--;
3059 #endif
3061 /***********************************************************/
3062 /* ram save/restore */
3064 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3066 int v;
3068 v = qemu_get_byte(f);
3069 switch(v) {
3070 case 0:
3071 if (qemu_get_buffer(f, buf, len) != len)
3072 return -EIO;
3073 break;
3074 case 1:
3075 v = qemu_get_byte(f);
3076 memset(buf, v, len);
3077 break;
3078 default:
3079 return -EINVAL;
3082 if (qemu_file_has_error(f))
3083 return -EIO;
3085 return 0;
3088 static int ram_load_v1(QEMUFile *f, void *opaque)
3090 int ret;
3091 ram_addr_t i;
3093 if (qemu_get_be32(f) != phys_ram_size)
3094 return -EINVAL;
3095 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3096 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3097 if (ret)
3098 return ret;
3100 return 0;
3103 #define BDRV_HASH_BLOCK_SIZE 1024
3104 #define IOBUF_SIZE 4096
3105 #define RAM_CBLOCK_MAGIC 0xfabe
3107 typedef struct RamDecompressState {
3108 z_stream zstream;
3109 QEMUFile *f;
3110 uint8_t buf[IOBUF_SIZE];
3111 } RamDecompressState;
3113 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3115 int ret;
3116 memset(s, 0, sizeof(*s));
3117 s->f = f;
3118 ret = inflateInit(&s->zstream);
3119 if (ret != Z_OK)
3120 return -1;
3121 return 0;
3124 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3126 int ret, clen;
3128 s->zstream.avail_out = len;
3129 s->zstream.next_out = buf;
3130 while (s->zstream.avail_out > 0) {
3131 if (s->zstream.avail_in == 0) {
3132 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3133 return -1;
3134 clen = qemu_get_be16(s->f);
3135 if (clen > IOBUF_SIZE)
3136 return -1;
3137 qemu_get_buffer(s->f, s->buf, clen);
3138 s->zstream.avail_in = clen;
3139 s->zstream.next_in = s->buf;
3141 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3142 if (ret != Z_OK && ret != Z_STREAM_END) {
3143 return -1;
3146 return 0;
3149 static void ram_decompress_close(RamDecompressState *s)
3151 inflateEnd(&s->zstream);
3154 #define RAM_SAVE_FLAG_FULL 0x01
3155 #define RAM_SAVE_FLAG_COMPRESS 0x02
3156 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3157 #define RAM_SAVE_FLAG_PAGE 0x08
3158 #define RAM_SAVE_FLAG_EOS 0x10
3160 static int is_dup_page(uint8_t *page, uint8_t ch)
3162 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3163 uint32_t *array = (uint32_t *)page;
3164 int i;
3166 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3167 if (array[i] != val)
3168 return 0;
3171 return 1;
3174 static int ram_save_block(QEMUFile *f)
3176 static ram_addr_t current_addr = 0;
3177 ram_addr_t saved_addr = current_addr;
3178 ram_addr_t addr = 0;
3179 int found = 0;
3181 while (addr < phys_ram_size) {
3182 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3183 uint8_t ch;
3185 cpu_physical_memory_reset_dirty(current_addr,
3186 current_addr + TARGET_PAGE_SIZE,
3187 MIGRATION_DIRTY_FLAG);
3189 ch = *(phys_ram_base + current_addr);
3191 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3192 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3193 qemu_put_byte(f, ch);
3194 } else {
3195 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3196 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3199 found = 1;
3200 break;
3202 addr += TARGET_PAGE_SIZE;
3203 current_addr = (saved_addr + addr) % phys_ram_size;
3206 return found;
3209 static ram_addr_t ram_save_threshold = 10;
3211 static ram_addr_t ram_save_remaining(void)
3213 ram_addr_t addr;
3214 ram_addr_t count = 0;
3216 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3217 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3218 count++;
3221 return count;
3224 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3226 ram_addr_t addr;
3228 if (stage == 1) {
3229 /* Make sure all dirty bits are set */
3230 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3231 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3232 cpu_physical_memory_set_dirty(addr);
3235 /* Enable dirty memory tracking */
3236 cpu_physical_memory_set_dirty_tracking(1);
3238 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3241 while (!qemu_file_rate_limit(f)) {
3242 int ret;
3244 ret = ram_save_block(f);
3245 if (ret == 0) /* no more blocks */
3246 break;
3249 /* try transferring iterative blocks of memory */
3251 if (stage == 3) {
3252 cpu_physical_memory_set_dirty_tracking(0);
3254 /* flush all remaining blocks regardless of rate limiting */
3255 while (ram_save_block(f) != 0);
3258 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3260 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3263 static int ram_load_dead(QEMUFile *f, void *opaque)
3265 RamDecompressState s1, *s = &s1;
3266 uint8_t buf[10];
3267 ram_addr_t i;
3269 if (ram_decompress_open(s, f) < 0)
3270 return -EINVAL;
3271 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3272 if (ram_decompress_buf(s, buf, 1) < 0) {
3273 fprintf(stderr, "Error while reading ram block header\n");
3274 goto error;
3276 if (buf[0] == 0) {
3277 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3278 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3279 goto error;
3281 } else {
3282 error:
3283 printf("Error block header\n");
3284 return -EINVAL;
3287 ram_decompress_close(s);
3289 return 0;
3292 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3294 ram_addr_t addr;
3295 int flags;
3297 if (version_id == 1)
3298 return ram_load_v1(f, opaque);
3300 if (version_id == 2) {
3301 if (qemu_get_be32(f) != phys_ram_size)
3302 return -EINVAL;
3303 return ram_load_dead(f, opaque);
3306 if (version_id != 3)
3307 return -EINVAL;
3309 do {
3310 addr = qemu_get_be64(f);
3312 flags = addr & ~TARGET_PAGE_MASK;
3313 addr &= TARGET_PAGE_MASK;
3315 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3316 if (addr != phys_ram_size)
3317 return -EINVAL;
3320 if (flags & RAM_SAVE_FLAG_FULL) {
3321 if (ram_load_dead(f, opaque) < 0)
3322 return -EINVAL;
3325 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3326 uint8_t ch = qemu_get_byte(f);
3327 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3328 } else if (flags & RAM_SAVE_FLAG_PAGE)
3329 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3330 } while (!(flags & RAM_SAVE_FLAG_EOS));
3332 return 0;
3335 void qemu_service_io(void)
3337 CPUState *env = cpu_single_env;
3338 if (env) {
3339 cpu_exit(env);
3340 #ifdef USE_KQEMU
3341 if (env->kqemu_enabled) {
3342 kqemu_cpu_interrupt(env);
3344 #endif
3348 /***********************************************************/
3349 /* bottom halves (can be seen as timers which expire ASAP) */
3351 struct QEMUBH {
3352 QEMUBHFunc *cb;
3353 void *opaque;
3354 int scheduled;
3355 int idle;
3356 int deleted;
3357 QEMUBH *next;
3360 static QEMUBH *first_bh = NULL;
3362 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3364 QEMUBH *bh;
3365 bh = qemu_mallocz(sizeof(QEMUBH));
3366 bh->cb = cb;
3367 bh->opaque = opaque;
3368 bh->next = first_bh;
3369 first_bh = bh;
3370 return bh;
3373 int qemu_bh_poll(void)
3375 QEMUBH *bh, **bhp;
3376 int ret;
3378 ret = 0;
3379 for (bh = first_bh; bh; bh = bh->next) {
3380 if (!bh->deleted && bh->scheduled) {
3381 bh->scheduled = 0;
3382 if (!bh->idle)
3383 ret = 1;
3384 bh->idle = 0;
3385 bh->cb(bh->opaque);
3389 /* remove deleted bhs */
3390 bhp = &first_bh;
3391 while (*bhp) {
3392 bh = *bhp;
3393 if (bh->deleted) {
3394 *bhp = bh->next;
3395 qemu_free(bh);
3396 } else
3397 bhp = &bh->next;
3400 return ret;
3403 void qemu_bh_schedule_idle(QEMUBH *bh)
3405 if (bh->scheduled)
3406 return;
3407 bh->scheduled = 1;
3408 bh->idle = 1;
3411 void qemu_bh_schedule(QEMUBH *bh)
3413 CPUState *env = cpu_single_env;
3414 if (bh->scheduled)
3415 return;
3416 bh->scheduled = 1;
3417 bh->idle = 0;
3418 /* stop the currently executing CPU to execute the BH ASAP */
3419 if (env) {
3420 cpu_exit(env);
3424 void qemu_bh_cancel(QEMUBH *bh)
3426 bh->scheduled = 0;
3429 void qemu_bh_delete(QEMUBH *bh)
3431 bh->scheduled = 0;
3432 bh->deleted = 1;
3435 static void qemu_bh_update_timeout(int *timeout)
3437 QEMUBH *bh;
3439 for (bh = first_bh; bh; bh = bh->next) {
3440 if (!bh->deleted && bh->scheduled) {
3441 if (bh->idle) {
3442 /* idle bottom halves will be polled at least
3443 * every 10ms */
3444 *timeout = MIN(10, *timeout);
3445 } else {
3446 /* non-idle bottom halves will be executed
3447 * immediately */
3448 *timeout = 0;
3449 break;
3455 /***********************************************************/
3456 /* machine registration */
3458 static QEMUMachine *first_machine = NULL;
3459 QEMUMachine *current_machine = NULL;
3461 int qemu_register_machine(QEMUMachine *m)
3463 QEMUMachine **pm;
3464 pm = &first_machine;
3465 while (*pm != NULL)
3466 pm = &(*pm)->next;
3467 m->next = NULL;
3468 *pm = m;
3469 return 0;
3472 static QEMUMachine *find_machine(const char *name)
3474 QEMUMachine *m;
3476 for(m = first_machine; m != NULL; m = m->next) {
3477 if (!strcmp(m->name, name))
3478 return m;
3480 return NULL;
3483 /***********************************************************/
3484 /* main execution loop */
3486 static void gui_update(void *opaque)
3488 uint64_t interval = GUI_REFRESH_INTERVAL;
3489 DisplayState *ds = opaque;
3490 DisplayChangeListener *dcl = ds->listeners;
3492 dpy_refresh(ds);
3494 while (dcl != NULL) {
3495 if (dcl->gui_timer_interval &&
3496 dcl->gui_timer_interval < interval)
3497 interval = dcl->gui_timer_interval;
3498 dcl = dcl->next;
3500 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3503 static void nographic_update(void *opaque)
3505 uint64_t interval = GUI_REFRESH_INTERVAL;
3507 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3510 struct vm_change_state_entry {
3511 VMChangeStateHandler *cb;
3512 void *opaque;
3513 LIST_ENTRY (vm_change_state_entry) entries;
3516 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3518 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3519 void *opaque)
3521 VMChangeStateEntry *e;
3523 e = qemu_mallocz(sizeof (*e));
3525 e->cb = cb;
3526 e->opaque = opaque;
3527 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3528 return e;
3531 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3533 LIST_REMOVE (e, entries);
3534 qemu_free (e);
3537 static void vm_state_notify(int running, int reason)
3539 VMChangeStateEntry *e;
3541 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3542 e->cb(e->opaque, running, reason);
3546 void vm_start(void)
3548 if (!vm_running) {
3549 cpu_enable_ticks();
3550 vm_running = 1;
3551 vm_state_notify(1, 0);
3552 qemu_rearm_alarm_timer(alarm_timer);
3556 void vm_stop(int reason)
3558 if (vm_running) {
3559 cpu_disable_ticks();
3560 vm_running = 0;
3561 vm_state_notify(0, reason);
3565 /* reset/shutdown handler */
3567 typedef struct QEMUResetEntry {
3568 QEMUResetHandler *func;
3569 void *opaque;
3570 struct QEMUResetEntry *next;
3571 } QEMUResetEntry;
3573 static QEMUResetEntry *first_reset_entry;
3574 static int reset_requested;
3575 static int shutdown_requested;
3576 static int powerdown_requested;
3578 int qemu_shutdown_requested(void)
3580 int r = shutdown_requested;
3581 shutdown_requested = 0;
3582 return r;
3585 int qemu_reset_requested(void)
3587 int r = reset_requested;
3588 reset_requested = 0;
3589 return r;
3592 int qemu_powerdown_requested(void)
3594 int r = powerdown_requested;
3595 powerdown_requested = 0;
3596 return r;
3599 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3601 QEMUResetEntry **pre, *re;
3603 pre = &first_reset_entry;
3604 while (*pre != NULL)
3605 pre = &(*pre)->next;
3606 re = qemu_mallocz(sizeof(QEMUResetEntry));
3607 re->func = func;
3608 re->opaque = opaque;
3609 re->next = NULL;
3610 *pre = re;
3613 void qemu_system_reset(void)
3615 QEMUResetEntry *re;
3617 /* reset all devices */
3618 for(re = first_reset_entry; re != NULL; re = re->next) {
3619 re->func(re->opaque);
3623 void qemu_system_reset_request(void)
3625 if (no_reboot) {
3626 shutdown_requested = 1;
3627 } else {
3628 reset_requested = 1;
3630 if (cpu_single_env)
3631 cpu_exit(cpu_single_env);
3634 void qemu_system_shutdown_request(void)
3636 shutdown_requested = 1;
3637 if (cpu_single_env)
3638 cpu_exit(cpu_single_env);
3641 void qemu_system_powerdown_request(void)
3643 powerdown_requested = 1;
3644 if (cpu_single_env)
3645 cpu_exit(cpu_single_env);
3648 #ifdef _WIN32
3649 static void host_main_loop_wait(int *timeout)
3651 int ret, ret2, i;
3652 PollingEntry *pe;
3655 /* XXX: need to suppress polling by better using win32 events */
3656 ret = 0;
3657 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3658 ret |= pe->func(pe->opaque);
3660 if (ret == 0) {
3661 int err;
3662 WaitObjects *w = &wait_objects;
3664 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3665 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3666 if (w->func[ret - WAIT_OBJECT_0])
3667 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3669 /* Check for additional signaled events */
3670 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3672 /* Check if event is signaled */
3673 ret2 = WaitForSingleObject(w->events[i], 0);
3674 if(ret2 == WAIT_OBJECT_0) {
3675 if (w->func[i])
3676 w->func[i](w->opaque[i]);
3677 } else if (ret2 == WAIT_TIMEOUT) {
3678 } else {
3679 err = GetLastError();
3680 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3683 } else if (ret == WAIT_TIMEOUT) {
3684 } else {
3685 err = GetLastError();
3686 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3690 *timeout = 0;
3692 #else
3693 static void host_main_loop_wait(int *timeout)
3696 #endif
3698 void main_loop_wait(int timeout)
3700 IOHandlerRecord *ioh;
3701 fd_set rfds, wfds, xfds;
3702 int ret, nfds;
3703 struct timeval tv;
3705 qemu_bh_update_timeout(&timeout);
3707 host_main_loop_wait(&timeout);
3709 /* poll any events */
3710 /* XXX: separate device handlers from system ones */
3711 nfds = -1;
3712 FD_ZERO(&rfds);
3713 FD_ZERO(&wfds);
3714 FD_ZERO(&xfds);
3715 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3716 if (ioh->deleted)
3717 continue;
3718 if (ioh->fd_read &&
3719 (!ioh->fd_read_poll ||
3720 ioh->fd_read_poll(ioh->opaque) != 0)) {
3721 FD_SET(ioh->fd, &rfds);
3722 if (ioh->fd > nfds)
3723 nfds = ioh->fd;
3725 if (ioh->fd_write) {
3726 FD_SET(ioh->fd, &wfds);
3727 if (ioh->fd > nfds)
3728 nfds = ioh->fd;
3732 tv.tv_sec = timeout / 1000;
3733 tv.tv_usec = (timeout % 1000) * 1000;
3735 #if defined(CONFIG_SLIRP)
3736 if (slirp_is_inited()) {
3737 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3739 #endif
3740 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3741 if (ret > 0) {
3742 IOHandlerRecord **pioh;
3744 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3745 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3746 ioh->fd_read(ioh->opaque);
3748 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3749 ioh->fd_write(ioh->opaque);
3753 /* remove deleted IO handlers */
3754 pioh = &first_io_handler;
3755 while (*pioh) {
3756 ioh = *pioh;
3757 if (ioh->deleted) {
3758 *pioh = ioh->next;
3759 qemu_free(ioh);
3760 } else
3761 pioh = &ioh->next;
3764 #if defined(CONFIG_SLIRP)
3765 if (slirp_is_inited()) {
3766 if (ret < 0) {
3767 FD_ZERO(&rfds);
3768 FD_ZERO(&wfds);
3769 FD_ZERO(&xfds);
3771 slirp_select_poll(&rfds, &wfds, &xfds);
3773 #endif
3775 /* vm time timers */
3776 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3777 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3778 qemu_get_clock(vm_clock));
3780 /* real time timers */
3781 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3782 qemu_get_clock(rt_clock));
3784 /* Check bottom-halves last in case any of the earlier events triggered
3785 them. */
3786 qemu_bh_poll();
3790 static int main_loop(void)
3792 int ret, timeout;
3793 #ifdef CONFIG_PROFILER
3794 int64_t ti;
3795 #endif
3796 CPUState *env;
3798 cur_cpu = first_cpu;
3799 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3800 for(;;) {
3801 if (vm_running) {
3803 for(;;) {
3804 /* get next cpu */
3805 env = next_cpu;
3806 #ifdef CONFIG_PROFILER
3807 ti = profile_getclock();
3808 #endif
3809 if (use_icount) {
3810 int64_t count;
3811 int decr;
3812 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3813 env->icount_decr.u16.low = 0;
3814 env->icount_extra = 0;
3815 count = qemu_next_deadline();
3816 count = (count + (1 << icount_time_shift) - 1)
3817 >> icount_time_shift;
3818 qemu_icount += count;
3819 decr = (count > 0xffff) ? 0xffff : count;
3820 count -= decr;
3821 env->icount_decr.u16.low = decr;
3822 env->icount_extra = count;
3824 ret = cpu_exec(env);
3825 #ifdef CONFIG_PROFILER
3826 qemu_time += profile_getclock() - ti;
3827 #endif
3828 if (use_icount) {
3829 /* Fold pending instructions back into the
3830 instruction counter, and clear the interrupt flag. */
3831 qemu_icount -= (env->icount_decr.u16.low
3832 + env->icount_extra);
3833 env->icount_decr.u32 = 0;
3834 env->icount_extra = 0;
3836 next_cpu = env->next_cpu ?: first_cpu;
3837 if (event_pending && likely(ret != EXCP_DEBUG)) {
3838 ret = EXCP_INTERRUPT;
3839 event_pending = 0;
3840 break;
3842 if (ret == EXCP_HLT) {
3843 /* Give the next CPU a chance to run. */
3844 cur_cpu = env;
3845 continue;
3847 if (ret != EXCP_HALTED)
3848 break;
3849 /* all CPUs are halted ? */
3850 if (env == cur_cpu)
3851 break;
3853 cur_cpu = env;
3855 if (shutdown_requested) {
3856 ret = EXCP_INTERRUPT;
3857 if (no_shutdown) {
3858 vm_stop(0);
3859 no_shutdown = 0;
3861 else
3862 break;
3864 if (reset_requested) {
3865 reset_requested = 0;
3866 qemu_system_reset();
3867 ret = EXCP_INTERRUPT;
3869 if (powerdown_requested) {
3870 powerdown_requested = 0;
3871 qemu_system_powerdown();
3872 ret = EXCP_INTERRUPT;
3874 if (unlikely(ret == EXCP_DEBUG)) {
3875 gdb_set_stop_cpu(cur_cpu);
3876 vm_stop(EXCP_DEBUG);
3878 /* If all cpus are halted then wait until the next IRQ */
3879 /* XXX: use timeout computed from timers */
3880 if (ret == EXCP_HALTED) {
3881 if (use_icount) {
3882 int64_t add;
3883 int64_t delta;
3884 /* Advance virtual time to the next event. */
3885 if (use_icount == 1) {
3886 /* When not using an adaptive execution frequency
3887 we tend to get badly out of sync with real time,
3888 so just delay for a reasonable amount of time. */
3889 delta = 0;
3890 } else {
3891 delta = cpu_get_icount() - cpu_get_clock();
3893 if (delta > 0) {
3894 /* If virtual time is ahead of real time then just
3895 wait for IO. */
3896 timeout = (delta / 1000000) + 1;
3897 } else {
3898 /* Wait for either IO to occur or the next
3899 timer event. */
3900 add = qemu_next_deadline();
3901 /* We advance the timer before checking for IO.
3902 Limit the amount we advance so that early IO
3903 activity won't get the guest too far ahead. */
3904 if (add > 10000000)
3905 add = 10000000;
3906 delta += add;
3907 add = (add + (1 << icount_time_shift) - 1)
3908 >> icount_time_shift;
3909 qemu_icount += add;
3910 timeout = delta / 1000000;
3911 if (timeout < 0)
3912 timeout = 0;
3914 } else {
3915 timeout = 5000;
3917 } else {
3918 timeout = 0;
3920 } else {
3921 if (shutdown_requested) {
3922 ret = EXCP_INTERRUPT;
3923 break;
3925 timeout = 5000;
3927 #ifdef CONFIG_PROFILER
3928 ti = profile_getclock();
3929 #endif
3930 main_loop_wait(timeout);
3931 #ifdef CONFIG_PROFILER
3932 dev_time += profile_getclock() - ti;
3933 #endif
3935 cpu_disable_ticks();
3936 return ret;
3939 static void help(int exitcode)
3941 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3942 "usage: %s [options] [disk_image]\n"
3943 "\n"
3944 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3945 "\n"
3946 #define DEF(option, opt_arg, opt_enum, opt_help) \
3947 opt_help
3948 #define DEFHEADING(text) stringify(text) "\n"
3949 #include "qemu-options.h"
3950 #undef DEF
3951 #undef DEFHEADING
3952 #undef GEN_DOCS
3953 "\n"
3954 "During emulation, the following keys are useful:\n"
3955 "ctrl-alt-f toggle full screen\n"
3956 "ctrl-alt-n switch to virtual console 'n'\n"
3957 "ctrl-alt toggle mouse and keyboard grab\n"
3958 "\n"
3959 "When using -nographic, press 'ctrl-a h' to get some help.\n"
3961 "qemu",
3962 DEFAULT_RAM_SIZE,
3963 #ifndef _WIN32
3964 DEFAULT_NETWORK_SCRIPT,
3965 DEFAULT_NETWORK_DOWN_SCRIPT,
3966 #endif
3967 DEFAULT_GDBSTUB_PORT,
3968 "/tmp/qemu.log");
3969 exit(exitcode);
3972 #define HAS_ARG 0x0001
3974 enum {
3975 #define DEF(option, opt_arg, opt_enum, opt_help) \
3976 opt_enum,
3977 #define DEFHEADING(text)
3978 #include "qemu-options.h"
3979 #undef DEF
3980 #undef DEFHEADING
3981 #undef GEN_DOCS
3984 typedef struct QEMUOption {
3985 const char *name;
3986 int flags;
3987 int index;
3988 } QEMUOption;
3990 static const QEMUOption qemu_options[] = {
3991 { "h", 0, QEMU_OPTION_h },
3992 #define DEF(option, opt_arg, opt_enum, opt_help) \
3993 { option, opt_arg, opt_enum },
3994 #define DEFHEADING(text)
3995 #include "qemu-options.h"
3996 #undef DEF
3997 #undef DEFHEADING
3998 #undef GEN_DOCS
3999 { NULL },
4002 #ifdef HAS_AUDIO
4003 struct soundhw soundhw[] = {
4004 #ifdef HAS_AUDIO_CHOICE
4005 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4007 "pcspk",
4008 "PC speaker",
4011 { .init_isa = pcspk_audio_init }
4013 #endif
4015 #ifdef CONFIG_SB16
4017 "sb16",
4018 "Creative Sound Blaster 16",
4021 { .init_isa = SB16_init }
4023 #endif
4025 #ifdef CONFIG_CS4231A
4027 "cs4231a",
4028 "CS4231A",
4031 { .init_isa = cs4231a_init }
4033 #endif
4035 #ifdef CONFIG_ADLIB
4037 "adlib",
4038 #ifdef HAS_YMF262
4039 "Yamaha YMF262 (OPL3)",
4040 #else
4041 "Yamaha YM3812 (OPL2)",
4042 #endif
4045 { .init_isa = Adlib_init }
4047 #endif
4049 #ifdef CONFIG_GUS
4051 "gus",
4052 "Gravis Ultrasound GF1",
4055 { .init_isa = GUS_init }
4057 #endif
4059 #ifdef CONFIG_AC97
4061 "ac97",
4062 "Intel 82801AA AC97 Audio",
4065 { .init_pci = ac97_init }
4067 #endif
4069 #ifdef CONFIG_ES1370
4071 "es1370",
4072 "ENSONIQ AudioPCI ES1370",
4075 { .init_pci = es1370_init }
4077 #endif
4079 #endif /* HAS_AUDIO_CHOICE */
4081 { NULL, NULL, 0, 0, { NULL } }
4084 static void select_soundhw (const char *optarg)
4086 struct soundhw *c;
4088 if (*optarg == '?') {
4089 show_valid_cards:
4091 printf ("Valid sound card names (comma separated):\n");
4092 for (c = soundhw; c->name; ++c) {
4093 printf ("%-11s %s\n", c->name, c->descr);
4095 printf ("\n-soundhw all will enable all of the above\n");
4096 exit (*optarg != '?');
4098 else {
4099 size_t l;
4100 const char *p;
4101 char *e;
4102 int bad_card = 0;
4104 if (!strcmp (optarg, "all")) {
4105 for (c = soundhw; c->name; ++c) {
4106 c->enabled = 1;
4108 return;
4111 p = optarg;
4112 while (*p) {
4113 e = strchr (p, ',');
4114 l = !e ? strlen (p) : (size_t) (e - p);
4116 for (c = soundhw; c->name; ++c) {
4117 if (!strncmp (c->name, p, l)) {
4118 c->enabled = 1;
4119 break;
4123 if (!c->name) {
4124 if (l > 80) {
4125 fprintf (stderr,
4126 "Unknown sound card name (too big to show)\n");
4128 else {
4129 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4130 (int) l, p);
4132 bad_card = 1;
4134 p += l + (e != NULL);
4137 if (bad_card)
4138 goto show_valid_cards;
4141 #endif
4143 static void select_vgahw (const char *p)
4145 const char *opts;
4147 if (strstart(p, "std", &opts)) {
4148 std_vga_enabled = 1;
4149 cirrus_vga_enabled = 0;
4150 vmsvga_enabled = 0;
4151 } else if (strstart(p, "cirrus", &opts)) {
4152 cirrus_vga_enabled = 1;
4153 std_vga_enabled = 0;
4154 vmsvga_enabled = 0;
4155 } else if (strstart(p, "vmware", &opts)) {
4156 cirrus_vga_enabled = 0;
4157 std_vga_enabled = 0;
4158 vmsvga_enabled = 1;
4159 } else if (strstart(p, "none", &opts)) {
4160 cirrus_vga_enabled = 0;
4161 std_vga_enabled = 0;
4162 vmsvga_enabled = 0;
4163 } else {
4164 invalid_vga:
4165 fprintf(stderr, "Unknown vga type: %s\n", p);
4166 exit(1);
4168 while (*opts) {
4169 const char *nextopt;
4171 if (strstart(opts, ",retrace=", &nextopt)) {
4172 opts = nextopt;
4173 if (strstart(opts, "dumb", &nextopt))
4174 vga_retrace_method = VGA_RETRACE_DUMB;
4175 else if (strstart(opts, "precise", &nextopt))
4176 vga_retrace_method = VGA_RETRACE_PRECISE;
4177 else goto invalid_vga;
4178 } else goto invalid_vga;
4179 opts = nextopt;
4183 #ifdef _WIN32
4184 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4186 exit(STATUS_CONTROL_C_EXIT);
4187 return TRUE;
4189 #endif
4191 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4193 int ret;
4195 if(strlen(str) != 36)
4196 return -1;
4198 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4199 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4200 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4202 if(ret != 16)
4203 return -1;
4205 return 0;
4208 #define MAX_NET_CLIENTS 32
4210 #ifndef _WIN32
4212 static void termsig_handler(int signal)
4214 qemu_system_shutdown_request();
4217 static void termsig_setup(void)
4219 struct sigaction act;
4221 memset(&act, 0, sizeof(act));
4222 act.sa_handler = termsig_handler;
4223 sigaction(SIGINT, &act, NULL);
4224 sigaction(SIGHUP, &act, NULL);
4225 sigaction(SIGTERM, &act, NULL);
4228 #endif
4230 int main(int argc, char **argv, char **envp)
4232 #ifdef CONFIG_GDBSTUB
4233 int use_gdbstub;
4234 const char *gdbstub_port;
4235 #endif
4236 uint32_t boot_devices_bitmap = 0;
4237 int i;
4238 int snapshot, linux_boot, net_boot;
4239 const char *initrd_filename;
4240 const char *kernel_filename, *kernel_cmdline;
4241 const char *boot_devices = "";
4242 DisplayState *ds;
4243 DisplayChangeListener *dcl;
4244 int cyls, heads, secs, translation;
4245 const char *net_clients[MAX_NET_CLIENTS];
4246 int nb_net_clients;
4247 const char *bt_opts[MAX_BT_CMDLINE];
4248 int nb_bt_opts;
4249 int hda_index;
4250 int optind;
4251 const char *r, *optarg;
4252 CharDriverState *monitor_hd = NULL;
4253 const char *monitor_device;
4254 const char *serial_devices[MAX_SERIAL_PORTS];
4255 int serial_device_index;
4256 const char *parallel_devices[MAX_PARALLEL_PORTS];
4257 int parallel_device_index;
4258 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4259 int virtio_console_index;
4260 const char *loadvm = NULL;
4261 QEMUMachine *machine;
4262 const char *cpu_model;
4263 const char *usb_devices[MAX_USB_CMDLINE];
4264 int usb_devices_index;
4265 int fds[2];
4266 int tb_size;
4267 const char *pid_file = NULL;
4268 const char *incoming = NULL;
4269 int fd = 0;
4270 struct passwd *pwd = NULL;
4271 const char *chroot_dir = NULL;
4272 const char *run_as = NULL;
4274 qemu_cache_utils_init(envp);
4276 LIST_INIT (&vm_change_state_head);
4277 #ifndef _WIN32
4279 struct sigaction act;
4280 sigfillset(&act.sa_mask);
4281 act.sa_flags = 0;
4282 act.sa_handler = SIG_IGN;
4283 sigaction(SIGPIPE, &act, NULL);
4285 #else
4286 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4287 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4288 QEMU to run on a single CPU */
4290 HANDLE h;
4291 DWORD mask, smask;
4292 int i;
4293 h = GetCurrentProcess();
4294 if (GetProcessAffinityMask(h, &mask, &smask)) {
4295 for(i = 0; i < 32; i++) {
4296 if (mask & (1 << i))
4297 break;
4299 if (i != 32) {
4300 mask = 1 << i;
4301 SetProcessAffinityMask(h, mask);
4305 #endif
4307 register_machines();
4308 machine = first_machine;
4309 cpu_model = NULL;
4310 initrd_filename = NULL;
4311 ram_size = 0;
4312 vga_ram_size = VGA_RAM_SIZE;
4313 #ifdef CONFIG_GDBSTUB
4314 use_gdbstub = 0;
4315 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4316 #endif
4317 snapshot = 0;
4318 nographic = 0;
4319 curses = 0;
4320 kernel_filename = NULL;
4321 kernel_cmdline = "";
4322 cyls = heads = secs = 0;
4323 translation = BIOS_ATA_TRANSLATION_AUTO;
4324 monitor_device = "vc:80Cx24C";
4326 serial_devices[0] = "vc:80Cx24C";
4327 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4328 serial_devices[i] = NULL;
4329 serial_device_index = 0;
4331 parallel_devices[0] = "vc:80Cx24C";
4332 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4333 parallel_devices[i] = NULL;
4334 parallel_device_index = 0;
4336 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4337 virtio_consoles[i] = NULL;
4338 virtio_console_index = 0;
4340 usb_devices_index = 0;
4342 nb_net_clients = 0;
4343 nb_bt_opts = 0;
4344 nb_drives = 0;
4345 nb_drives_opt = 0;
4346 hda_index = -1;
4348 nb_nics = 0;
4350 tb_size = 0;
4351 autostart= 1;
4353 optind = 1;
4354 for(;;) {
4355 if (optind >= argc)
4356 break;
4357 r = argv[optind];
4358 if (r[0] != '-') {
4359 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4360 } else {
4361 const QEMUOption *popt;
4363 optind++;
4364 /* Treat --foo the same as -foo. */
4365 if (r[1] == '-')
4366 r++;
4367 popt = qemu_options;
4368 for(;;) {
4369 if (!popt->name) {
4370 fprintf(stderr, "%s: invalid option -- '%s'\n",
4371 argv[0], r);
4372 exit(1);
4374 if (!strcmp(popt->name, r + 1))
4375 break;
4376 popt++;
4378 if (popt->flags & HAS_ARG) {
4379 if (optind >= argc) {
4380 fprintf(stderr, "%s: option '%s' requires an argument\n",
4381 argv[0], r);
4382 exit(1);
4384 optarg = argv[optind++];
4385 } else {
4386 optarg = NULL;
4389 switch(popt->index) {
4390 case QEMU_OPTION_M:
4391 machine = find_machine(optarg);
4392 if (!machine) {
4393 QEMUMachine *m;
4394 printf("Supported machines are:\n");
4395 for(m = first_machine; m != NULL; m = m->next) {
4396 printf("%-10s %s%s\n",
4397 m->name, m->desc,
4398 m == first_machine ? " (default)" : "");
4400 exit(*optarg != '?');
4402 break;
4403 case QEMU_OPTION_cpu:
4404 /* hw initialization will check this */
4405 if (*optarg == '?') {
4406 /* XXX: implement xxx_cpu_list for targets that still miss it */
4407 #if defined(cpu_list)
4408 cpu_list(stdout, &fprintf);
4409 #endif
4410 exit(0);
4411 } else {
4412 cpu_model = optarg;
4414 break;
4415 case QEMU_OPTION_initrd:
4416 initrd_filename = optarg;
4417 break;
4418 case QEMU_OPTION_hda:
4419 if (cyls == 0)
4420 hda_index = drive_add(optarg, HD_ALIAS, 0);
4421 else
4422 hda_index = drive_add(optarg, HD_ALIAS
4423 ",cyls=%d,heads=%d,secs=%d%s",
4424 0, cyls, heads, secs,
4425 translation == BIOS_ATA_TRANSLATION_LBA ?
4426 ",trans=lba" :
4427 translation == BIOS_ATA_TRANSLATION_NONE ?
4428 ",trans=none" : "");
4429 break;
4430 case QEMU_OPTION_hdb:
4431 case QEMU_OPTION_hdc:
4432 case QEMU_OPTION_hdd:
4433 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4434 break;
4435 case QEMU_OPTION_drive:
4436 drive_add(NULL, "%s", optarg);
4437 break;
4438 case QEMU_OPTION_mtdblock:
4439 drive_add(optarg, MTD_ALIAS);
4440 break;
4441 case QEMU_OPTION_sd:
4442 drive_add(optarg, SD_ALIAS);
4443 break;
4444 case QEMU_OPTION_pflash:
4445 drive_add(optarg, PFLASH_ALIAS);
4446 break;
4447 case QEMU_OPTION_snapshot:
4448 snapshot = 1;
4449 break;
4450 case QEMU_OPTION_hdachs:
4452 const char *p;
4453 p = optarg;
4454 cyls = strtol(p, (char **)&p, 0);
4455 if (cyls < 1 || cyls > 16383)
4456 goto chs_fail;
4457 if (*p != ',')
4458 goto chs_fail;
4459 p++;
4460 heads = strtol(p, (char **)&p, 0);
4461 if (heads < 1 || heads > 16)
4462 goto chs_fail;
4463 if (*p != ',')
4464 goto chs_fail;
4465 p++;
4466 secs = strtol(p, (char **)&p, 0);
4467 if (secs < 1 || secs > 63)
4468 goto chs_fail;
4469 if (*p == ',') {
4470 p++;
4471 if (!strcmp(p, "none"))
4472 translation = BIOS_ATA_TRANSLATION_NONE;
4473 else if (!strcmp(p, "lba"))
4474 translation = BIOS_ATA_TRANSLATION_LBA;
4475 else if (!strcmp(p, "auto"))
4476 translation = BIOS_ATA_TRANSLATION_AUTO;
4477 else
4478 goto chs_fail;
4479 } else if (*p != '\0') {
4480 chs_fail:
4481 fprintf(stderr, "qemu: invalid physical CHS format\n");
4482 exit(1);
4484 if (hda_index != -1)
4485 snprintf(drives_opt[hda_index].opt,
4486 sizeof(drives_opt[hda_index].opt),
4487 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4488 0, cyls, heads, secs,
4489 translation == BIOS_ATA_TRANSLATION_LBA ?
4490 ",trans=lba" :
4491 translation == BIOS_ATA_TRANSLATION_NONE ?
4492 ",trans=none" : "");
4494 break;
4495 case QEMU_OPTION_nographic:
4496 nographic = 1;
4497 break;
4498 #ifdef CONFIG_CURSES
4499 case QEMU_OPTION_curses:
4500 curses = 1;
4501 break;
4502 #endif
4503 case QEMU_OPTION_portrait:
4504 graphic_rotate = 1;
4505 break;
4506 case QEMU_OPTION_kernel:
4507 kernel_filename = optarg;
4508 break;
4509 case QEMU_OPTION_append:
4510 kernel_cmdline = optarg;
4511 break;
4512 case QEMU_OPTION_cdrom:
4513 drive_add(optarg, CDROM_ALIAS);
4514 break;
4515 case QEMU_OPTION_boot:
4516 boot_devices = optarg;
4517 /* We just do some generic consistency checks */
4519 /* Could easily be extended to 64 devices if needed */
4520 const char *p;
4522 boot_devices_bitmap = 0;
4523 for (p = boot_devices; *p != '\0'; p++) {
4524 /* Allowed boot devices are:
4525 * a b : floppy disk drives
4526 * c ... f : IDE disk drives
4527 * g ... m : machine implementation dependant drives
4528 * n ... p : network devices
4529 * It's up to each machine implementation to check
4530 * if the given boot devices match the actual hardware
4531 * implementation and firmware features.
4533 if (*p < 'a' || *p > 'q') {
4534 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4535 exit(1);
4537 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4538 fprintf(stderr,
4539 "Boot device '%c' was given twice\n",*p);
4540 exit(1);
4542 boot_devices_bitmap |= 1 << (*p - 'a');
4545 break;
4546 case QEMU_OPTION_fda:
4547 case QEMU_OPTION_fdb:
4548 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4549 break;
4550 #ifdef TARGET_I386
4551 case QEMU_OPTION_no_fd_bootchk:
4552 fd_bootchk = 0;
4553 break;
4554 #endif
4555 case QEMU_OPTION_net:
4556 if (nb_net_clients >= MAX_NET_CLIENTS) {
4557 fprintf(stderr, "qemu: too many network clients\n");
4558 exit(1);
4560 net_clients[nb_net_clients] = optarg;
4561 nb_net_clients++;
4562 break;
4563 #ifdef CONFIG_SLIRP
4564 case QEMU_OPTION_tftp:
4565 tftp_prefix = optarg;
4566 break;
4567 case QEMU_OPTION_bootp:
4568 bootp_filename = optarg;
4569 break;
4570 #ifndef _WIN32
4571 case QEMU_OPTION_smb:
4572 net_slirp_smb(optarg);
4573 break;
4574 #endif
4575 case QEMU_OPTION_redir:
4576 net_slirp_redir(optarg);
4577 break;
4578 #endif
4579 case QEMU_OPTION_bt:
4580 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4581 fprintf(stderr, "qemu: too many bluetooth options\n");
4582 exit(1);
4584 bt_opts[nb_bt_opts++] = optarg;
4585 break;
4586 #ifdef HAS_AUDIO
4587 case QEMU_OPTION_audio_help:
4588 AUD_help ();
4589 exit (0);
4590 break;
4591 case QEMU_OPTION_soundhw:
4592 select_soundhw (optarg);
4593 break;
4594 #endif
4595 case QEMU_OPTION_h:
4596 help(0);
4597 break;
4598 case QEMU_OPTION_m: {
4599 uint64_t value;
4600 char *ptr;
4602 value = strtoul(optarg, &ptr, 10);
4603 switch (*ptr) {
4604 case 0: case 'M': case 'm':
4605 value <<= 20;
4606 break;
4607 case 'G': case 'g':
4608 value <<= 30;
4609 break;
4610 default:
4611 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4612 exit(1);
4615 /* On 32-bit hosts, QEMU is limited by virtual address space */
4616 if (value > (2047 << 20)
4617 #ifndef USE_KQEMU
4618 && HOST_LONG_BITS == 32
4619 #endif
4621 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4622 exit(1);
4624 if (value != (uint64_t)(ram_addr_t)value) {
4625 fprintf(stderr, "qemu: ram size too large\n");
4626 exit(1);
4628 ram_size = value;
4629 break;
4631 case QEMU_OPTION_d:
4633 int mask;
4634 const CPULogItem *item;
4636 mask = cpu_str_to_log_mask(optarg);
4637 if (!mask) {
4638 printf("Log items (comma separated):\n");
4639 for(item = cpu_log_items; item->mask != 0; item++) {
4640 printf("%-10s %s\n", item->name, item->help);
4642 exit(1);
4644 cpu_set_log(mask);
4646 break;
4647 #ifdef CONFIG_GDBSTUB
4648 case QEMU_OPTION_s:
4649 use_gdbstub = 1;
4650 break;
4651 case QEMU_OPTION_p:
4652 gdbstub_port = optarg;
4653 break;
4654 #endif
4655 case QEMU_OPTION_L:
4656 bios_dir = optarg;
4657 break;
4658 case QEMU_OPTION_bios:
4659 bios_name = optarg;
4660 break;
4661 case QEMU_OPTION_S:
4662 autostart = 0;
4663 break;
4664 #ifndef _WIN32
4665 case QEMU_OPTION_k:
4666 keyboard_layout = optarg;
4667 break;
4668 #endif
4669 case QEMU_OPTION_localtime:
4670 rtc_utc = 0;
4671 break;
4672 case QEMU_OPTION_vga:
4673 select_vgahw (optarg);
4674 break;
4675 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4676 case QEMU_OPTION_g:
4678 const char *p;
4679 int w, h, depth;
4680 p = optarg;
4681 w = strtol(p, (char **)&p, 10);
4682 if (w <= 0) {
4683 graphic_error:
4684 fprintf(stderr, "qemu: invalid resolution or depth\n");
4685 exit(1);
4687 if (*p != 'x')
4688 goto graphic_error;
4689 p++;
4690 h = strtol(p, (char **)&p, 10);
4691 if (h <= 0)
4692 goto graphic_error;
4693 if (*p == 'x') {
4694 p++;
4695 depth = strtol(p, (char **)&p, 10);
4696 if (depth != 8 && depth != 15 && depth != 16 &&
4697 depth != 24 && depth != 32)
4698 goto graphic_error;
4699 } else if (*p == '\0') {
4700 depth = graphic_depth;
4701 } else {
4702 goto graphic_error;
4705 graphic_width = w;
4706 graphic_height = h;
4707 graphic_depth = depth;
4709 break;
4710 #endif
4711 case QEMU_OPTION_echr:
4713 char *r;
4714 term_escape_char = strtol(optarg, &r, 0);
4715 if (r == optarg)
4716 printf("Bad argument to echr\n");
4717 break;
4719 case QEMU_OPTION_monitor:
4720 monitor_device = optarg;
4721 break;
4722 case QEMU_OPTION_serial:
4723 if (serial_device_index >= MAX_SERIAL_PORTS) {
4724 fprintf(stderr, "qemu: too many serial ports\n");
4725 exit(1);
4727 serial_devices[serial_device_index] = optarg;
4728 serial_device_index++;
4729 break;
4730 case QEMU_OPTION_virtiocon:
4731 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4732 fprintf(stderr, "qemu: too many virtio consoles\n");
4733 exit(1);
4735 virtio_consoles[virtio_console_index] = optarg;
4736 virtio_console_index++;
4737 break;
4738 case QEMU_OPTION_parallel:
4739 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4740 fprintf(stderr, "qemu: too many parallel ports\n");
4741 exit(1);
4743 parallel_devices[parallel_device_index] = optarg;
4744 parallel_device_index++;
4745 break;
4746 case QEMU_OPTION_loadvm:
4747 loadvm = optarg;
4748 break;
4749 case QEMU_OPTION_full_screen:
4750 full_screen = 1;
4751 break;
4752 #ifdef CONFIG_SDL
4753 case QEMU_OPTION_no_frame:
4754 no_frame = 1;
4755 break;
4756 case QEMU_OPTION_alt_grab:
4757 alt_grab = 1;
4758 break;
4759 case QEMU_OPTION_no_quit:
4760 no_quit = 1;
4761 break;
4762 case QEMU_OPTION_sdl:
4763 sdl = 1;
4764 break;
4765 #endif
4766 case QEMU_OPTION_pidfile:
4767 pid_file = optarg;
4768 break;
4769 #ifdef TARGET_I386
4770 case QEMU_OPTION_win2k_hack:
4771 win2k_install_hack = 1;
4772 break;
4773 case QEMU_OPTION_rtc_td_hack:
4774 rtc_td_hack = 1;
4775 break;
4776 case QEMU_OPTION_acpitable:
4777 if(acpi_table_add(optarg) < 0) {
4778 fprintf(stderr, "Wrong acpi table provided\n");
4779 exit(1);
4781 break;
4782 #endif
4783 #ifdef USE_KQEMU
4784 case QEMU_OPTION_no_kqemu:
4785 kqemu_allowed = 0;
4786 break;
4787 case QEMU_OPTION_kernel_kqemu:
4788 kqemu_allowed = 2;
4789 break;
4790 #endif
4791 #ifdef CONFIG_KVM
4792 case QEMU_OPTION_enable_kvm:
4793 kvm_allowed = 1;
4794 #ifdef USE_KQEMU
4795 kqemu_allowed = 0;
4796 #endif
4797 break;
4798 #endif
4799 case QEMU_OPTION_usb:
4800 usb_enabled = 1;
4801 break;
4802 case QEMU_OPTION_usbdevice:
4803 usb_enabled = 1;
4804 if (usb_devices_index >= MAX_USB_CMDLINE) {
4805 fprintf(stderr, "Too many USB devices\n");
4806 exit(1);
4808 usb_devices[usb_devices_index] = optarg;
4809 usb_devices_index++;
4810 break;
4811 case QEMU_OPTION_smp:
4812 smp_cpus = atoi(optarg);
4813 if (smp_cpus < 1) {
4814 fprintf(stderr, "Invalid number of CPUs\n");
4815 exit(1);
4817 break;
4818 case QEMU_OPTION_vnc:
4819 vnc_display = optarg;
4820 break;
4821 #ifdef TARGET_I386
4822 case QEMU_OPTION_no_acpi:
4823 acpi_enabled = 0;
4824 break;
4825 case QEMU_OPTION_no_hpet:
4826 no_hpet = 1;
4827 break;
4828 #endif
4829 case QEMU_OPTION_no_reboot:
4830 no_reboot = 1;
4831 break;
4832 case QEMU_OPTION_no_shutdown:
4833 no_shutdown = 1;
4834 break;
4835 case QEMU_OPTION_show_cursor:
4836 cursor_hide = 0;
4837 break;
4838 case QEMU_OPTION_uuid:
4839 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4840 fprintf(stderr, "Fail to parse UUID string."
4841 " Wrong format.\n");
4842 exit(1);
4844 break;
4845 #ifndef _WIN32
4846 case QEMU_OPTION_daemonize:
4847 daemonize = 1;
4848 break;
4849 #endif
4850 case QEMU_OPTION_option_rom:
4851 if (nb_option_roms >= MAX_OPTION_ROMS) {
4852 fprintf(stderr, "Too many option ROMs\n");
4853 exit(1);
4855 option_rom[nb_option_roms] = optarg;
4856 nb_option_roms++;
4857 break;
4858 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4859 case QEMU_OPTION_semihosting:
4860 semihosting_enabled = 1;
4861 break;
4862 #endif
4863 case QEMU_OPTION_name:
4864 qemu_name = optarg;
4865 break;
4866 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4867 case QEMU_OPTION_prom_env:
4868 if (nb_prom_envs >= MAX_PROM_ENVS) {
4869 fprintf(stderr, "Too many prom variables\n");
4870 exit(1);
4872 prom_envs[nb_prom_envs] = optarg;
4873 nb_prom_envs++;
4874 break;
4875 #endif
4876 #ifdef TARGET_ARM
4877 case QEMU_OPTION_old_param:
4878 old_param = 1;
4879 break;
4880 #endif
4881 case QEMU_OPTION_clock:
4882 configure_alarms(optarg);
4883 break;
4884 case QEMU_OPTION_startdate:
4886 struct tm tm;
4887 time_t rtc_start_date;
4888 if (!strcmp(optarg, "now")) {
4889 rtc_date_offset = -1;
4890 } else {
4891 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
4892 &tm.tm_year,
4893 &tm.tm_mon,
4894 &tm.tm_mday,
4895 &tm.tm_hour,
4896 &tm.tm_min,
4897 &tm.tm_sec) == 6) {
4898 /* OK */
4899 } else if (sscanf(optarg, "%d-%d-%d",
4900 &tm.tm_year,
4901 &tm.tm_mon,
4902 &tm.tm_mday) == 3) {
4903 tm.tm_hour = 0;
4904 tm.tm_min = 0;
4905 tm.tm_sec = 0;
4906 } else {
4907 goto date_fail;
4909 tm.tm_year -= 1900;
4910 tm.tm_mon--;
4911 rtc_start_date = mktimegm(&tm);
4912 if (rtc_start_date == -1) {
4913 date_fail:
4914 fprintf(stderr, "Invalid date format. Valid format are:\n"
4915 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
4916 exit(1);
4918 rtc_date_offset = time(NULL) - rtc_start_date;
4921 break;
4922 case QEMU_OPTION_tb_size:
4923 tb_size = strtol(optarg, NULL, 0);
4924 if (tb_size < 0)
4925 tb_size = 0;
4926 break;
4927 case QEMU_OPTION_icount:
4928 use_icount = 1;
4929 if (strcmp(optarg, "auto") == 0) {
4930 icount_time_shift = -1;
4931 } else {
4932 icount_time_shift = strtol(optarg, NULL, 0);
4934 break;
4935 case QEMU_OPTION_incoming:
4936 incoming = optarg;
4937 break;
4938 #ifndef _WIN32
4939 case QEMU_OPTION_chroot:
4940 chroot_dir = optarg;
4941 break;
4942 case QEMU_OPTION_runas:
4943 run_as = optarg;
4944 break;
4945 #endif
4950 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
4951 if (kvm_allowed && kqemu_allowed) {
4952 fprintf(stderr,
4953 "You can not enable both KVM and kqemu at the same time\n");
4954 exit(1);
4956 #endif
4958 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4959 if (smp_cpus > machine->max_cpus) {
4960 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4961 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
4962 machine->max_cpus);
4963 exit(1);
4966 if (nographic) {
4967 if (serial_device_index == 0)
4968 serial_devices[0] = "stdio";
4969 if (parallel_device_index == 0)
4970 parallel_devices[0] = "null";
4971 if (strncmp(monitor_device, "vc", 2) == 0)
4972 monitor_device = "stdio";
4975 #ifndef _WIN32
4976 if (daemonize) {
4977 pid_t pid;
4979 if (pipe(fds) == -1)
4980 exit(1);
4982 pid = fork();
4983 if (pid > 0) {
4984 uint8_t status;
4985 ssize_t len;
4987 close(fds[1]);
4989 again:
4990 len = read(fds[0], &status, 1);
4991 if (len == -1 && (errno == EINTR))
4992 goto again;
4994 if (len != 1)
4995 exit(1);
4996 else if (status == 1) {
4997 fprintf(stderr, "Could not acquire pidfile\n");
4998 exit(1);
4999 } else
5000 exit(0);
5001 } else if (pid < 0)
5002 exit(1);
5004 setsid();
5006 pid = fork();
5007 if (pid > 0)
5008 exit(0);
5009 else if (pid < 0)
5010 exit(1);
5012 umask(027);
5014 signal(SIGTSTP, SIG_IGN);
5015 signal(SIGTTOU, SIG_IGN);
5016 signal(SIGTTIN, SIG_IGN);
5018 #endif
5020 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5021 if (daemonize) {
5022 uint8_t status = 1;
5023 write(fds[1], &status, 1);
5024 } else
5025 fprintf(stderr, "Could not acquire pid file\n");
5026 exit(1);
5029 #ifdef USE_KQEMU
5030 if (smp_cpus > 1)
5031 kqemu_allowed = 0;
5032 #endif
5033 linux_boot = (kernel_filename != NULL);
5034 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5036 if (!linux_boot && *kernel_cmdline != '\0') {
5037 fprintf(stderr, "-append only allowed with -kernel option\n");
5038 exit(1);
5041 if (!linux_boot && initrd_filename != NULL) {
5042 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5043 exit(1);
5046 /* boot to floppy or the default cd if no hard disk defined yet */
5047 if (!boot_devices[0]) {
5048 boot_devices = "cad";
5050 setvbuf(stdout, NULL, _IOLBF, 0);
5052 init_timers();
5053 if (init_timer_alarm() < 0) {
5054 fprintf(stderr, "could not initialize alarm timer\n");
5055 exit(1);
5057 if (use_icount && icount_time_shift < 0) {
5058 use_icount = 2;
5059 /* 125MIPS seems a reasonable initial guess at the guest speed.
5060 It will be corrected fairly quickly anyway. */
5061 icount_time_shift = 3;
5062 init_icount_adjust();
5065 #ifdef _WIN32
5066 socket_init();
5067 #endif
5069 /* init network clients */
5070 if (nb_net_clients == 0) {
5071 /* if no clients, we use a default config */
5072 net_clients[nb_net_clients++] = "nic";
5073 #ifdef CONFIG_SLIRP
5074 net_clients[nb_net_clients++] = "user";
5075 #endif
5078 for(i = 0;i < nb_net_clients; i++) {
5079 if (net_client_parse(net_clients[i]) < 0)
5080 exit(1);
5082 net_client_check();
5084 #ifdef TARGET_I386
5085 /* XXX: this should be moved in the PC machine instantiation code */
5086 if (net_boot != 0) {
5087 int netroms = 0;
5088 for (i = 0; i < nb_nics && i < 4; i++) {
5089 const char *model = nd_table[i].model;
5090 char buf[1024];
5091 if (net_boot & (1 << i)) {
5092 if (model == NULL)
5093 model = "ne2k_pci";
5094 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5095 if (get_image_size(buf) > 0) {
5096 if (nb_option_roms >= MAX_OPTION_ROMS) {
5097 fprintf(stderr, "Too many option ROMs\n");
5098 exit(1);
5100 option_rom[nb_option_roms] = strdup(buf);
5101 nb_option_roms++;
5102 netroms++;
5106 if (netroms == 0) {
5107 fprintf(stderr, "No valid PXE rom found for network device\n");
5108 exit(1);
5111 #endif
5113 /* init the bluetooth world */
5114 for (i = 0; i < nb_bt_opts; i++)
5115 if (bt_parse(bt_opts[i]))
5116 exit(1);
5118 /* init the memory */
5119 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5121 if (machine->ram_require & RAMSIZE_FIXED) {
5122 if (ram_size > 0) {
5123 if (ram_size < phys_ram_size) {
5124 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5125 machine->name, (unsigned long long) phys_ram_size);
5126 exit(-1);
5129 phys_ram_size = ram_size;
5130 } else
5131 ram_size = phys_ram_size;
5132 } else {
5133 if (ram_size == 0)
5134 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5136 phys_ram_size += ram_size;
5139 phys_ram_base = qemu_vmalloc(phys_ram_size);
5140 if (!phys_ram_base) {
5141 fprintf(stderr, "Could not allocate physical memory\n");
5142 exit(1);
5145 /* init the dynamic translator */
5146 cpu_exec_init_all(tb_size * 1024 * 1024);
5148 bdrv_init();
5149 dma_helper_init();
5151 /* we always create the cdrom drive, even if no disk is there */
5153 if (nb_drives_opt < MAX_DRIVES)
5154 drive_add(NULL, CDROM_ALIAS);
5156 /* we always create at least one floppy */
5158 if (nb_drives_opt < MAX_DRIVES)
5159 drive_add(NULL, FD_ALIAS, 0);
5161 /* we always create one sd slot, even if no card is in it */
5163 if (nb_drives_opt < MAX_DRIVES)
5164 drive_add(NULL, SD_ALIAS);
5166 /* open the virtual block devices */
5168 for(i = 0; i < nb_drives_opt; i++)
5169 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5170 exit(1);
5172 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5173 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5175 #ifndef _WIN32
5176 /* must be after terminal init, SDL library changes signal handlers */
5177 termsig_setup();
5178 #endif
5180 /* Maintain compatibility with multiple stdio monitors */
5181 if (!strcmp(monitor_device,"stdio")) {
5182 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5183 const char *devname = serial_devices[i];
5184 if (devname && !strcmp(devname,"mon:stdio")) {
5185 monitor_device = NULL;
5186 break;
5187 } else if (devname && !strcmp(devname,"stdio")) {
5188 monitor_device = NULL;
5189 serial_devices[i] = "mon:stdio";
5190 break;
5195 if (kvm_enabled()) {
5196 int ret;
5198 ret = kvm_init(smp_cpus);
5199 if (ret < 0) {
5200 fprintf(stderr, "failed to initialize KVM\n");
5201 exit(1);
5205 if (monitor_device) {
5206 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5207 if (!monitor_hd) {
5208 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5209 exit(1);
5213 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5214 const char *devname = serial_devices[i];
5215 if (devname && strcmp(devname, "none")) {
5216 char label[32];
5217 snprintf(label, sizeof(label), "serial%d", i);
5218 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5219 if (!serial_hds[i]) {
5220 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5221 devname);
5222 exit(1);
5227 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5228 const char *devname = parallel_devices[i];
5229 if (devname && strcmp(devname, "none")) {
5230 char label[32];
5231 snprintf(label, sizeof(label), "parallel%d", i);
5232 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5233 if (!parallel_hds[i]) {
5234 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5235 devname);
5236 exit(1);
5241 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5242 const char *devname = virtio_consoles[i];
5243 if (devname && strcmp(devname, "none")) {
5244 char label[32];
5245 snprintf(label, sizeof(label), "virtcon%d", i);
5246 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5247 if (!virtcon_hds[i]) {
5248 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5249 devname);
5250 exit(1);
5255 machine->init(ram_size, vga_ram_size, boot_devices,
5256 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5258 current_machine = machine;
5260 /* Set KVM's vcpu state to qemu's initial CPUState. */
5261 if (kvm_enabled()) {
5262 int ret;
5264 ret = kvm_sync_vcpus();
5265 if (ret < 0) {
5266 fprintf(stderr, "failed to initialize vcpus\n");
5267 exit(1);
5271 /* init USB devices */
5272 if (usb_enabled) {
5273 for(i = 0; i < usb_devices_index; i++) {
5274 if (usb_device_add(usb_devices[i], 0) < 0) {
5275 fprintf(stderr, "Warning: could not add USB device %s\n",
5276 usb_devices[i]);
5281 if (!display_state)
5282 dumb_display_init();
5283 /* just use the first displaystate for the moment */
5284 ds = display_state;
5285 /* terminal init */
5286 if (nographic) {
5287 if (curses) {
5288 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5289 exit(1);
5291 } else {
5292 #if defined(CONFIG_CURSES)
5293 if (curses) {
5294 /* At the moment curses cannot be used with other displays */
5295 curses_display_init(ds, full_screen);
5296 } else
5297 #endif
5299 if (vnc_display != NULL) {
5300 vnc_display_init(ds);
5301 if (vnc_display_open(ds, vnc_display) < 0)
5302 exit(1);
5304 #if defined(CONFIG_SDL)
5305 if (sdl || !vnc_display)
5306 sdl_display_init(ds, full_screen, no_frame);
5307 #elif defined(CONFIG_COCOA)
5308 if (sdl || !vnc_display)
5309 cocoa_display_init(ds, full_screen);
5310 #endif
5313 dpy_resize(ds);
5315 dcl = ds->listeners;
5316 while (dcl != NULL) {
5317 if (dcl->dpy_refresh != NULL) {
5318 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5319 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5321 dcl = dcl->next;
5324 if (nographic || (vnc_display && !sdl)) {
5325 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5326 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5329 text_consoles_set_display(display_state);
5330 qemu_chr_initial_reset();
5332 if (monitor_device && monitor_hd)
5333 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5335 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5336 const char *devname = serial_devices[i];
5337 if (devname && strcmp(devname, "none")) {
5338 char label[32];
5339 snprintf(label, sizeof(label), "serial%d", i);
5340 if (strstart(devname, "vc", 0))
5341 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5345 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5346 const char *devname = parallel_devices[i];
5347 if (devname && strcmp(devname, "none")) {
5348 char label[32];
5349 snprintf(label, sizeof(label), "parallel%d", i);
5350 if (strstart(devname, "vc", 0))
5351 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5355 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5356 const char *devname = virtio_consoles[i];
5357 if (virtcon_hds[i] && devname) {
5358 char label[32];
5359 snprintf(label, sizeof(label), "virtcon%d", i);
5360 if (strstart(devname, "vc", 0))
5361 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5365 #ifdef CONFIG_GDBSTUB
5366 if (use_gdbstub) {
5367 /* XXX: use standard host:port notation and modify options
5368 accordingly. */
5369 if (gdbserver_start(gdbstub_port) < 0) {
5370 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5371 gdbstub_port);
5372 exit(1);
5375 #endif
5377 if (loadvm)
5378 do_loadvm(cur_mon, loadvm);
5380 if (incoming) {
5381 autostart = 0; /* fixme how to deal with -daemonize */
5382 qemu_start_incoming_migration(incoming);
5385 if (autostart)
5386 vm_start();
5388 if (daemonize) {
5389 uint8_t status = 0;
5390 ssize_t len;
5392 again1:
5393 len = write(fds[1], &status, 1);
5394 if (len == -1 && (errno == EINTR))
5395 goto again1;
5397 if (len != 1)
5398 exit(1);
5400 chdir("/");
5401 TFR(fd = open("/dev/null", O_RDWR));
5402 if (fd == -1)
5403 exit(1);
5406 #ifndef _WIN32
5407 if (run_as) {
5408 pwd = getpwnam(run_as);
5409 if (!pwd) {
5410 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5411 exit(1);
5415 if (chroot_dir) {
5416 if (chroot(chroot_dir) < 0) {
5417 fprintf(stderr, "chroot failed\n");
5418 exit(1);
5420 chdir("/");
5423 if (run_as) {
5424 if (setgid(pwd->pw_gid) < 0) {
5425 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5426 exit(1);
5428 if (setuid(pwd->pw_uid) < 0) {
5429 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5430 exit(1);
5432 if (setuid(0) != -1) {
5433 fprintf(stderr, "Dropping privileges failed\n");
5434 exit(1);
5437 #endif
5439 if (daemonize) {
5440 dup2(fd, 0);
5441 dup2(fd, 1);
5442 dup2(fd, 2);
5444 close(fd);
5447 main_loop();
5448 quit_timers();
5449 net_cleanup();
5451 return 0;