Kill redundant declarion of perror()
[qemu-kvm/fedora.git] / vl.c
blobe44c95e7d7ac15ab973b34566c295afe07c75089
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "hw/device-assignment.h"
43 #include "migration.h"
44 #include "kvm.h"
45 #include "balloon.h"
46 #include "qemu-kvm.h"
48 #include <unistd.h>
49 #include <fcntl.h>
50 #include <signal.h>
51 #include <time.h>
52 #include <errno.h>
53 #include <sys/time.h>
54 #include <zlib.h>
56 #ifndef _WIN32
57 #include <sys/times.h>
58 #include <sys/wait.h>
59 #include <termios.h>
60 #include <sys/mman.h>
61 #include <sys/ioctl.h>
62 #include <sys/resource.h>
63 #include <sys/socket.h>
64 #include <netinet/in.h>
65 #include <net/if.h>
66 #if defined(__NetBSD__)
67 #include <net/if_tap.h>
68 #endif
69 #ifdef __linux__
70 #include <linux/if_tun.h>
71 #endif
72 #include <arpa/inet.h>
73 #include <dirent.h>
74 #include <netdb.h>
75 #include <sys/select.h>
76 #ifdef _BSD
77 #include <sys/stat.h>
78 #ifdef __FreeBSD__
79 #include <libutil.h>
80 #else
81 #include <util.h>
82 #endif
83 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
84 #include <freebsd/stdlib.h>
85 #else
86 #ifdef __linux__
87 #include <pty.h>
88 #include <malloc.h>
89 #include <linux/rtc.h>
91 /* For the benefit of older linux systems which don't supply it,
92 we use a local copy of hpet.h. */
93 /* #include <linux/hpet.h> */
94 #include "hpet.h"
96 #include <linux/ppdev.h>
97 #include <linux/parport.h>
98 #endif
99 #ifdef __sun__
100 #include <sys/stat.h>
101 #include <sys/ethernet.h>
102 #include <sys/sockio.h>
103 #include <netinet/arp.h>
104 #include <netinet/in.h>
105 #include <netinet/in_systm.h>
106 #include <netinet/ip.h>
107 #include <netinet/ip_icmp.h> // must come after ip.h
108 #include <netinet/udp.h>
109 #include <netinet/tcp.h>
110 #include <net/if.h>
111 #include <syslog.h>
112 #include <stropts.h>
113 #endif
114 #endif
115 #endif
117 #include "qemu_socket.h"
119 #if defined(CONFIG_SLIRP)
120 #include "libslirp.h"
121 #endif
123 #if defined(__OpenBSD__)
124 #include <util.h>
125 #endif
127 #if defined(CONFIG_VDE)
128 #include <libvdeplug.h>
129 #endif
131 #ifdef _WIN32
132 #include <malloc.h>
133 #include <sys/timeb.h>
134 #include <mmsystem.h>
135 #define getopt_long_only getopt_long
136 #define memalign(align, size) malloc(size)
137 #endif
139 #ifdef CONFIG_SDL
140 #ifdef __APPLE__
141 #include <SDL/SDL.h>
142 #endif
143 #endif /* CONFIG_SDL */
145 #ifdef CONFIG_COCOA
146 #undef main
147 #define main qemu_main
148 #endif /* CONFIG_COCOA */
150 #include "disas.h"
152 #include "exec-all.h"
154 #include "qemu-kvm.h"
156 //#define DEBUG_UNUSED_IOPORT
157 //#define DEBUG_IOPORT
158 //#define DEBUG_NET
159 //#define DEBUG_SLIRP
161 #ifdef TARGET_PPC
162 #define DEFAULT_RAM_SIZE 144
163 #else
164 #define DEFAULT_RAM_SIZE 128
165 #endif
167 /* Max number of USB devices that can be specified on the commandline. */
168 #define MAX_USB_CMDLINE 8
170 /* Max number of bluetooth switches on the commandline. */
171 #define MAX_BT_CMDLINE 10
173 /* XXX: use a two level table to limit memory usage */
174 #define MAX_IOPORTS 65536
176 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
177 const char *bios_name = NULL;
178 static void *ioport_opaque[MAX_IOPORTS];
179 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
180 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
181 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
182 to store the VM snapshots */
183 DriveInfo drives_table[MAX_DRIVES+1];
184 int nb_drives;
185 int extboot_drive = -1;
186 static int vga_ram_size;
187 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
188 DisplayState display_state;
189 int nographic;
190 static int curses;
191 const char* keyboard_layout = NULL;
192 int64_t ticks_per_sec;
193 ram_addr_t ram_size;
194 int nb_nics;
195 NICInfo nd_table[MAX_NICS];
196 int vm_running;
197 static int rtc_utc = 1;
198 static int rtc_date_offset = -1; /* -1 means no change */
199 int cirrus_vga_enabled = 1;
200 int vmsvga_enabled = 0;
201 #ifdef TARGET_SPARC
202 int graphic_width = 1024;
203 int graphic_height = 768;
204 int graphic_depth = 8;
205 #else
206 int graphic_width = 800;
207 int graphic_height = 600;
208 int graphic_depth = 15;
209 #endif
210 static int full_screen = 0;
211 #ifdef CONFIG_SDL
212 static int no_frame = 0;
213 #endif
214 int no_quit = 0;
215 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217 #ifdef TARGET_I386
218 int win2k_install_hack = 0;
219 #endif
220 int usb_enabled = 0;
221 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
222 int assigned_devices_index;
223 int smp_cpus = 1;
224 const char *vnc_display;
225 int acpi_enabled = 1;
226 int no_hpet = 0;
227 int fd_bootchk = 1;
228 int no_reboot = 0;
229 int no_shutdown = 0;
230 int cursor_hide = 1;
231 int graphic_rotate = 0;
232 int daemonize = 0;
233 const char *incoming;
234 const char *option_rom[MAX_OPTION_ROMS];
235 int nb_option_roms;
236 int semihosting_enabled = 0;
237 int time_drift_fix = 0;
238 unsigned int kvm_shadow_memory = 0;
239 const char *mem_path = NULL;
240 int hpagesize = 0;
241 const char *cpu_vendor_string;
242 #ifdef TARGET_ARM
243 int old_param = 0;
244 #endif
245 const char *qemu_name;
246 int alt_grab = 0;
247 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
248 unsigned int nb_prom_envs = 0;
249 const char *prom_envs[MAX_PROM_ENVS];
250 #endif
251 int nb_drives_opt;
252 const char *nvram = NULL;
253 struct drive_opt drives_opt[MAX_DRIVES];
255 static CPUState *cur_cpu;
256 static CPUState *next_cpu;
257 static int event_pending = 1;
258 /* Conversion factor from emulated instructions to virtual clock ticks. */
259 static int icount_time_shift;
260 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
261 #define MAX_ICOUNT_SHIFT 10
262 /* Compensate for varying guest execution speed. */
263 static int64_t qemu_icount_bias;
264 static QEMUTimer *icount_rt_timer;
265 static QEMUTimer *icount_vm_timer;
267 uint8_t qemu_uuid[16];
269 /* KVM runs the main loop in a separate thread. If we update one of the lists
270 * that are polled before or after select(), we need to make sure to break out
271 * of the select() to ensure the new item is serviced.
273 static void main_loop_break(void)
275 if (kvm_enabled())
276 qemu_kvm_notify_work();
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 #ifdef DEBUG_IOPORT
433 if (loglevel & CPU_LOG_IOPORT)
434 fprintf(logfile, "outb: %04x %02x\n", addr, val);
435 #endif
436 ioport_write(0, addr, val);
437 #ifdef USE_KQEMU
438 if (env)
439 env->last_io_time = cpu_get_time_fast();
440 #endif
443 void cpu_outw(CPUState *env, int addr, int val)
445 #ifdef DEBUG_IOPORT
446 if (loglevel & CPU_LOG_IOPORT)
447 fprintf(logfile, "outw: %04x %04x\n", addr, val);
448 #endif
449 ioport_write(1, addr, val);
450 #ifdef USE_KQEMU
451 if (env)
452 env->last_io_time = cpu_get_time_fast();
453 #endif
456 void cpu_outl(CPUState *env, int addr, int val)
458 #ifdef DEBUG_IOPORT
459 if (loglevel & CPU_LOG_IOPORT)
460 fprintf(logfile, "outl: %04x %08x\n", addr, val);
461 #endif
462 ioport_write(2, addr, val);
463 #ifdef USE_KQEMU
464 if (env)
465 env->last_io_time = cpu_get_time_fast();
466 #endif
469 int cpu_inb(CPUState *env, int addr)
471 int val;
472 val = ioport_read(0, addr);
473 #ifdef DEBUG_IOPORT
474 if (loglevel & CPU_LOG_IOPORT)
475 fprintf(logfile, "inb : %04x %02x\n", addr, val);
476 #endif
477 #ifdef USE_KQEMU
478 if (env)
479 env->last_io_time = cpu_get_time_fast();
480 #endif
481 return val;
484 int cpu_inw(CPUState *env, int addr)
486 int val;
487 val = ioport_read(1, addr);
488 #ifdef DEBUG_IOPORT
489 if (loglevel & CPU_LOG_IOPORT)
490 fprintf(logfile, "inw : %04x %04x\n", addr, val);
491 #endif
492 #ifdef USE_KQEMU
493 if (env)
494 env->last_io_time = cpu_get_time_fast();
495 #endif
496 return val;
499 int cpu_inl(CPUState *env, int addr)
501 int val;
502 val = ioport_read(2, addr);
503 #ifdef DEBUG_IOPORT
504 if (loglevel & CPU_LOG_IOPORT)
505 fprintf(logfile, "inl : %04x %08x\n", addr, val);
506 #endif
507 #ifdef USE_KQEMU
508 if (env)
509 env->last_io_time = cpu_get_time_fast();
510 #endif
511 return val;
514 /***********************************************************/
515 void hw_error(const char *fmt, ...)
517 va_list ap;
518 CPUState *env;
520 va_start(ap, fmt);
521 fprintf(stderr, "qemu: hardware error: ");
522 vfprintf(stderr, fmt, ap);
523 fprintf(stderr, "\n");
524 for(env = first_cpu; env != NULL; env = env->next_cpu) {
525 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
526 #ifdef TARGET_I386
527 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
528 #else
529 cpu_dump_state(env, stderr, fprintf, 0);
530 #endif
532 va_end(ap);
533 abort();
536 /***************/
537 /* ballooning */
539 static QEMUBalloonEvent *qemu_balloon_event;
540 void *qemu_balloon_event_opaque;
542 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
544 qemu_balloon_event = func;
545 qemu_balloon_event_opaque = opaque;
548 void qemu_balloon(ram_addr_t target)
550 if (qemu_balloon_event)
551 qemu_balloon_event(qemu_balloon_event_opaque, target);
554 ram_addr_t qemu_balloon_status(void)
556 if (qemu_balloon_event)
557 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
558 return 0;
561 /***********************************************************/
562 /* keyboard/mouse */
564 static QEMUPutKBDEvent *qemu_put_kbd_event;
565 static void *qemu_put_kbd_event_opaque;
566 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
567 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
569 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
571 qemu_put_kbd_event_opaque = opaque;
572 qemu_put_kbd_event = func;
575 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
576 void *opaque, int absolute,
577 const char *name)
579 QEMUPutMouseEntry *s, *cursor;
581 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
582 if (!s)
583 return NULL;
585 s->qemu_put_mouse_event = func;
586 s->qemu_put_mouse_event_opaque = opaque;
587 s->qemu_put_mouse_event_absolute = absolute;
588 s->qemu_put_mouse_event_name = qemu_strdup(name);
589 s->next = NULL;
591 if (!qemu_put_mouse_event_head) {
592 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
593 return s;
596 cursor = qemu_put_mouse_event_head;
597 while (cursor->next != NULL)
598 cursor = cursor->next;
600 cursor->next = s;
601 qemu_put_mouse_event_current = s;
603 return s;
606 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
608 QEMUPutMouseEntry *prev = NULL, *cursor;
610 if (!qemu_put_mouse_event_head || entry == NULL)
611 return;
613 cursor = qemu_put_mouse_event_head;
614 while (cursor != NULL && cursor != entry) {
615 prev = cursor;
616 cursor = cursor->next;
619 if (cursor == NULL) // does not exist or list empty
620 return;
621 else if (prev == NULL) { // entry is head
622 qemu_put_mouse_event_head = cursor->next;
623 if (qemu_put_mouse_event_current == entry)
624 qemu_put_mouse_event_current = cursor->next;
625 qemu_free(entry->qemu_put_mouse_event_name);
626 qemu_free(entry);
627 return;
630 prev->next = entry->next;
632 if (qemu_put_mouse_event_current == entry)
633 qemu_put_mouse_event_current = prev;
635 qemu_free(entry->qemu_put_mouse_event_name);
636 qemu_free(entry);
639 void kbd_put_keycode(int keycode)
641 if (qemu_put_kbd_event) {
642 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
646 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
648 QEMUPutMouseEvent *mouse_event;
649 void *mouse_event_opaque;
650 int width;
652 if (!qemu_put_mouse_event_current) {
653 return;
656 mouse_event =
657 qemu_put_mouse_event_current->qemu_put_mouse_event;
658 mouse_event_opaque =
659 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
661 if (mouse_event) {
662 if (graphic_rotate) {
663 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
664 width = 0x7fff;
665 else
666 width = graphic_width - 1;
667 mouse_event(mouse_event_opaque,
668 width - dy, dx, dz, buttons_state);
669 } else
670 mouse_event(mouse_event_opaque,
671 dx, dy, dz, buttons_state);
675 int kbd_mouse_is_absolute(void)
677 if (!qemu_put_mouse_event_current)
678 return 0;
680 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
683 void do_info_mice(void)
685 QEMUPutMouseEntry *cursor;
686 int index = 0;
688 if (!qemu_put_mouse_event_head) {
689 term_printf("No mouse devices connected\n");
690 return;
693 term_printf("Mouse devices available:\n");
694 cursor = qemu_put_mouse_event_head;
695 while (cursor != NULL) {
696 term_printf("%c Mouse #%d: %s\n",
697 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
698 index, cursor->qemu_put_mouse_event_name);
699 index++;
700 cursor = cursor->next;
704 void do_mouse_set(int index)
706 QEMUPutMouseEntry *cursor;
707 int i = 0;
709 if (!qemu_put_mouse_event_head) {
710 term_printf("No mouse devices connected\n");
711 return;
714 cursor = qemu_put_mouse_event_head;
715 while (cursor != NULL && index != i) {
716 i++;
717 cursor = cursor->next;
720 if (cursor != NULL)
721 qemu_put_mouse_event_current = cursor;
722 else
723 term_printf("Mouse at given index not found\n");
726 /* compute with 96 bit intermediate result: (a*b)/c */
727 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
729 union {
730 uint64_t ll;
731 struct {
732 #ifdef WORDS_BIGENDIAN
733 uint32_t high, low;
734 #else
735 uint32_t low, high;
736 #endif
737 } l;
738 } u, res;
739 uint64_t rl, rh;
741 u.ll = a;
742 rl = (uint64_t)u.l.low * (uint64_t)b;
743 rh = (uint64_t)u.l.high * (uint64_t)b;
744 rh += (rl >> 32);
745 res.l.high = rh / c;
746 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
747 return res.ll;
750 /***********************************************************/
751 /* real time host monotonic timer */
753 #define QEMU_TIMER_BASE 1000000000LL
755 #ifdef WIN32
757 static int64_t clock_freq;
759 static void init_get_clock(void)
761 LARGE_INTEGER freq;
762 int ret;
763 ret = QueryPerformanceFrequency(&freq);
764 if (ret == 0) {
765 fprintf(stderr, "Could not calibrate ticks\n");
766 exit(1);
768 clock_freq = freq.QuadPart;
771 static int64_t get_clock(void)
773 LARGE_INTEGER ti;
774 QueryPerformanceCounter(&ti);
775 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
778 #else
780 static int use_rt_clock;
782 static void init_get_clock(void)
784 use_rt_clock = 0;
785 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
787 struct timespec ts;
788 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
789 use_rt_clock = 1;
792 #endif
795 static int64_t get_clock(void)
797 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
798 if (use_rt_clock) {
799 struct timespec ts;
800 clock_gettime(CLOCK_MONOTONIC, &ts);
801 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
802 } else
803 #endif
805 /* XXX: using gettimeofday leads to problems if the date
806 changes, so it should be avoided. */
807 struct timeval tv;
808 gettimeofday(&tv, NULL);
809 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
812 #endif
814 /* Return the virtual CPU time, based on the instruction counter. */
815 static int64_t cpu_get_icount(void)
817 int64_t icount;
818 CPUState *env = cpu_single_env;;
819 icount = qemu_icount;
820 if (env) {
821 if (!can_do_io(env))
822 fprintf(stderr, "Bad clock read\n");
823 icount -= (env->icount_decr.u16.low + env->icount_extra);
825 return qemu_icount_bias + (icount << icount_time_shift);
828 /***********************************************************/
829 /* guest cycle counter */
831 static int64_t cpu_ticks_prev;
832 static int64_t cpu_ticks_offset;
833 static int64_t cpu_clock_offset;
834 static int cpu_ticks_enabled;
836 /* return the host CPU cycle counter and handle stop/restart */
837 int64_t cpu_get_ticks(void)
839 if (use_icount) {
840 return cpu_get_icount();
842 if (!cpu_ticks_enabled) {
843 return cpu_ticks_offset;
844 } else {
845 int64_t ticks;
846 ticks = cpu_get_real_ticks();
847 if (cpu_ticks_prev > ticks) {
848 /* Note: non increasing ticks may happen if the host uses
849 software suspend */
850 cpu_ticks_offset += cpu_ticks_prev - ticks;
852 cpu_ticks_prev = ticks;
853 return ticks + cpu_ticks_offset;
857 /* return the host CPU monotonic timer and handle stop/restart */
858 static int64_t cpu_get_clock(void)
860 int64_t ti;
861 if (!cpu_ticks_enabled) {
862 return cpu_clock_offset;
863 } else {
864 ti = get_clock();
865 return ti + cpu_clock_offset;
869 /* enable cpu_get_ticks() */
870 void cpu_enable_ticks(void)
872 if (!cpu_ticks_enabled) {
873 cpu_ticks_offset -= cpu_get_real_ticks();
874 cpu_clock_offset -= get_clock();
875 cpu_ticks_enabled = 1;
879 /* disable cpu_get_ticks() : the clock is stopped. You must not call
880 cpu_get_ticks() after that. */
881 void cpu_disable_ticks(void)
883 if (cpu_ticks_enabled) {
884 cpu_ticks_offset = cpu_get_ticks();
885 cpu_clock_offset = cpu_get_clock();
886 cpu_ticks_enabled = 0;
890 /***********************************************************/
891 /* timers */
893 #define QEMU_TIMER_REALTIME 0
894 #define QEMU_TIMER_VIRTUAL 1
896 struct QEMUClock {
897 int type;
898 /* XXX: add frequency */
901 struct QEMUTimer {
902 QEMUClock *clock;
903 int64_t expire_time;
904 QEMUTimerCB *cb;
905 void *opaque;
906 struct QEMUTimer *next;
909 struct qemu_alarm_timer {
910 char const *name;
911 unsigned int flags;
913 int (*start)(struct qemu_alarm_timer *t);
914 void (*stop)(struct qemu_alarm_timer *t);
915 void (*rearm)(struct qemu_alarm_timer *t);
916 void *priv;
919 #define ALARM_FLAG_DYNTICKS 0x1
920 #define ALARM_FLAG_EXPIRED 0x2
922 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
924 return t->flags & ALARM_FLAG_DYNTICKS;
927 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
929 if (!alarm_has_dynticks(t))
930 return;
932 t->rearm(t);
935 /* TODO: MIN_TIMER_REARM_US should be optimized */
936 #define MIN_TIMER_REARM_US 250
938 static struct qemu_alarm_timer *alarm_timer;
939 #ifndef _WIN32
940 static int alarm_timer_rfd, alarm_timer_wfd;
941 #endif
943 #ifdef _WIN32
945 struct qemu_alarm_win32 {
946 MMRESULT timerId;
947 HANDLE host_alarm;
948 unsigned int period;
949 } alarm_win32_data = {0, NULL, -1};
951 static int win32_start_timer(struct qemu_alarm_timer *t);
952 static void win32_stop_timer(struct qemu_alarm_timer *t);
953 static void win32_rearm_timer(struct qemu_alarm_timer *t);
955 #else
957 static int unix_start_timer(struct qemu_alarm_timer *t);
958 static void unix_stop_timer(struct qemu_alarm_timer *t);
960 #ifdef __linux__
962 static int dynticks_start_timer(struct qemu_alarm_timer *t);
963 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
964 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
966 static int hpet_start_timer(struct qemu_alarm_timer *t);
967 static void hpet_stop_timer(struct qemu_alarm_timer *t);
969 static int rtc_start_timer(struct qemu_alarm_timer *t);
970 static void rtc_stop_timer(struct qemu_alarm_timer *t);
972 #endif /* __linux__ */
974 #endif /* _WIN32 */
976 /* Correlation between real and virtual time is always going to be
977 fairly approximate, so ignore small variation.
978 When the guest is idle real and virtual time will be aligned in
979 the IO wait loop. */
980 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
982 static void icount_adjust(void)
984 int64_t cur_time;
985 int64_t cur_icount;
986 int64_t delta;
987 static int64_t last_delta;
988 /* If the VM is not running, then do nothing. */
989 if (!vm_running)
990 return;
992 cur_time = cpu_get_clock();
993 cur_icount = qemu_get_clock(vm_clock);
994 delta = cur_icount - cur_time;
995 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
996 if (delta > 0
997 && last_delta + ICOUNT_WOBBLE < delta * 2
998 && icount_time_shift > 0) {
999 /* The guest is getting too far ahead. Slow time down. */
1000 icount_time_shift--;
1002 if (delta < 0
1003 && last_delta - ICOUNT_WOBBLE > delta * 2
1004 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1005 /* The guest is getting too far behind. Speed time up. */
1006 icount_time_shift++;
1008 last_delta = delta;
1009 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1012 static void icount_adjust_rt(void * opaque)
1014 qemu_mod_timer(icount_rt_timer,
1015 qemu_get_clock(rt_clock) + 1000);
1016 icount_adjust();
1019 static void icount_adjust_vm(void * opaque)
1021 qemu_mod_timer(icount_vm_timer,
1022 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1023 icount_adjust();
1026 static void init_icount_adjust(void)
1028 /* Have both realtime and virtual time triggers for speed adjustment.
1029 The realtime trigger catches emulated time passing too slowly,
1030 the virtual time trigger catches emulated time passing too fast.
1031 Realtime triggers occur even when idle, so use them less frequently
1032 than VM triggers. */
1033 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1034 qemu_mod_timer(icount_rt_timer,
1035 qemu_get_clock(rt_clock) + 1000);
1036 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1037 qemu_mod_timer(icount_vm_timer,
1038 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1041 static struct qemu_alarm_timer alarm_timers[] = {
1042 #ifndef _WIN32
1043 #ifdef __linux__
1044 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1045 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1046 /* HPET - if available - is preferred */
1047 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1048 /* ...otherwise try RTC */
1049 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1050 #endif
1051 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1052 #else
1053 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1054 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1055 {"win32", 0, win32_start_timer,
1056 win32_stop_timer, NULL, &alarm_win32_data},
1057 #endif
1058 {NULL, }
1061 static void show_available_alarms(void)
1063 int i;
1065 printf("Available alarm timers, in order of precedence:\n");
1066 for (i = 0; alarm_timers[i].name; i++)
1067 printf("%s\n", alarm_timers[i].name);
1070 static void configure_alarms(char const *opt)
1072 int i;
1073 int cur = 0;
1074 int count = ARRAY_SIZE(alarm_timers) - 1;
1075 char *arg;
1076 char *name;
1077 struct qemu_alarm_timer tmp;
1079 if (!strcmp(opt, "?")) {
1080 show_available_alarms();
1081 exit(0);
1084 arg = strdup(opt);
1086 /* Reorder the array */
1087 name = strtok(arg, ",");
1088 while (name) {
1089 for (i = 0; i < count && alarm_timers[i].name; i++) {
1090 if (!strcmp(alarm_timers[i].name, name))
1091 break;
1094 if (i == count) {
1095 fprintf(stderr, "Unknown clock %s\n", name);
1096 goto next;
1099 if (i < cur)
1100 /* Ignore */
1101 goto next;
1103 /* Swap */
1104 tmp = alarm_timers[i];
1105 alarm_timers[i] = alarm_timers[cur];
1106 alarm_timers[cur] = tmp;
1108 cur++;
1109 next:
1110 name = strtok(NULL, ",");
1113 free(arg);
1115 if (cur) {
1116 /* Disable remaining timers */
1117 for (i = cur; i < count; i++)
1118 alarm_timers[i].name = NULL;
1119 } else {
1120 show_available_alarms();
1121 exit(1);
1125 QEMUClock *rt_clock;
1126 QEMUClock *vm_clock;
1128 static QEMUTimer *active_timers[2];
1130 static QEMUClock *qemu_new_clock(int type)
1132 QEMUClock *clock;
1133 clock = qemu_mallocz(sizeof(QEMUClock));
1134 if (!clock)
1135 return NULL;
1136 clock->type = type;
1137 return clock;
1140 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1142 QEMUTimer *ts;
1144 ts = qemu_mallocz(sizeof(QEMUTimer));
1145 ts->clock = clock;
1146 ts->cb = cb;
1147 ts->opaque = opaque;
1148 return ts;
1151 void qemu_free_timer(QEMUTimer *ts)
1153 qemu_free(ts);
1156 /* stop a timer, but do not dealloc it */
1157 void qemu_del_timer(QEMUTimer *ts)
1159 QEMUTimer **pt, *t;
1161 /* NOTE: this code must be signal safe because
1162 qemu_timer_expired() can be called from a signal. */
1163 pt = &active_timers[ts->clock->type];
1164 for(;;) {
1165 t = *pt;
1166 if (!t)
1167 break;
1168 if (t == ts) {
1169 *pt = t->next;
1170 break;
1172 pt = &t->next;
1176 /* modify the current timer so that it will be fired when current_time
1177 >= expire_time. The corresponding callback will be called. */
1178 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1180 QEMUTimer **pt, *t;
1182 qemu_del_timer(ts);
1184 /* add the timer in the sorted list */
1185 /* NOTE: this code must be signal safe because
1186 qemu_timer_expired() can be called from a signal. */
1187 pt = &active_timers[ts->clock->type];
1188 for(;;) {
1189 t = *pt;
1190 if (!t)
1191 break;
1192 if (t->expire_time > expire_time)
1193 break;
1194 pt = &t->next;
1196 ts->expire_time = expire_time;
1197 ts->next = *pt;
1198 *pt = ts;
1200 /* Rearm if necessary */
1201 if (pt == &active_timers[ts->clock->type]) {
1202 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1203 qemu_rearm_alarm_timer(alarm_timer);
1205 /* Interrupt execution to force deadline recalculation. */
1206 if (use_icount && cpu_single_env) {
1207 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1212 int qemu_timer_pending(QEMUTimer *ts)
1214 QEMUTimer *t;
1215 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1216 if (t == ts)
1217 return 1;
1219 return 0;
1222 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1224 if (!timer_head)
1225 return 0;
1226 return (timer_head->expire_time <= current_time);
1229 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1231 QEMUTimer *ts;
1233 for(;;) {
1234 ts = *ptimer_head;
1235 if (!ts || ts->expire_time > current_time)
1236 break;
1237 /* remove timer from the list before calling the callback */
1238 *ptimer_head = ts->next;
1239 ts->next = NULL;
1241 /* run the callback (the timer list can be modified) */
1242 ts->cb(ts->opaque);
1246 int64_t qemu_get_clock(QEMUClock *clock)
1248 switch(clock->type) {
1249 case QEMU_TIMER_REALTIME:
1250 return get_clock() / 1000000;
1251 default:
1252 case QEMU_TIMER_VIRTUAL:
1253 if (use_icount) {
1254 return cpu_get_icount();
1255 } else {
1256 return cpu_get_clock();
1261 static void init_timers(void)
1263 init_get_clock();
1264 ticks_per_sec = QEMU_TIMER_BASE;
1265 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1266 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1269 /* save a timer */
1270 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1272 uint64_t expire_time;
1274 if (qemu_timer_pending(ts)) {
1275 expire_time = ts->expire_time;
1276 } else {
1277 expire_time = -1;
1279 qemu_put_be64(f, expire_time);
1282 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1284 uint64_t expire_time;
1286 expire_time = qemu_get_be64(f);
1287 if (expire_time != -1) {
1288 qemu_mod_timer(ts, expire_time);
1289 } else {
1290 qemu_del_timer(ts);
1294 static void timer_save(QEMUFile *f, void *opaque)
1296 if (cpu_ticks_enabled) {
1297 hw_error("cannot save state if virtual timers are running");
1299 qemu_put_be64(f, cpu_ticks_offset);
1300 qemu_put_be64(f, ticks_per_sec);
1301 qemu_put_be64(f, cpu_clock_offset);
1304 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1306 if (version_id != 1 && version_id != 2)
1307 return -EINVAL;
1308 if (cpu_ticks_enabled) {
1309 return -EINVAL;
1311 cpu_ticks_offset=qemu_get_be64(f);
1312 ticks_per_sec=qemu_get_be64(f);
1313 if (version_id == 2) {
1314 cpu_clock_offset=qemu_get_be64(f);
1316 return 0;
1319 #ifdef _WIN32
1320 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1321 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1322 #else
1323 static void host_alarm_handler(int host_signum)
1324 #endif
1326 #if 0
1327 #define DISP_FREQ 1000
1329 static int64_t delta_min = INT64_MAX;
1330 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1331 static int count;
1332 ti = qemu_get_clock(vm_clock);
1333 if (last_clock != 0) {
1334 delta = ti - last_clock;
1335 if (delta < delta_min)
1336 delta_min = delta;
1337 if (delta > delta_max)
1338 delta_max = delta;
1339 delta_cum += delta;
1340 if (++count == DISP_FREQ) {
1341 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1342 muldiv64(delta_min, 1000000, ticks_per_sec),
1343 muldiv64(delta_max, 1000000, ticks_per_sec),
1344 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1345 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1346 count = 0;
1347 delta_min = INT64_MAX;
1348 delta_max = 0;
1349 delta_cum = 0;
1352 last_clock = ti;
1354 #endif
1355 if (1 ||
1356 alarm_has_dynticks(alarm_timer) ||
1357 (!use_icount &&
1358 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1359 qemu_get_clock(vm_clock))) ||
1360 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1361 qemu_get_clock(rt_clock))) {
1362 CPUState *env = next_cpu;
1364 #ifdef _WIN32
1365 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1366 SetEvent(data->host_alarm);
1367 #else
1368 static const char byte = 0;
1369 write(alarm_timer_wfd, &byte, sizeof(byte));
1370 #endif
1371 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1373 if (env) {
1374 /* stop the currently executing cpu because a timer occured */
1375 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1376 #ifdef USE_KQEMU
1377 if (env->kqemu_enabled) {
1378 kqemu_cpu_interrupt(env);
1380 #endif
1382 event_pending = 1;
1386 static int64_t qemu_next_deadline(void)
1388 int64_t delta;
1390 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1391 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1392 qemu_get_clock(vm_clock);
1393 } else {
1394 /* To avoid problems with overflow limit this to 2^32. */
1395 delta = INT32_MAX;
1398 if (delta < 0)
1399 delta = 0;
1401 return delta;
1404 #if defined(__linux__) || defined(_WIN32)
1405 static uint64_t qemu_next_deadline_dyntick(void)
1407 int64_t delta;
1408 int64_t rtdelta;
1410 if (use_icount)
1411 delta = INT32_MAX;
1412 else
1413 delta = (qemu_next_deadline() + 999) / 1000;
1415 if (active_timers[QEMU_TIMER_REALTIME]) {
1416 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1417 qemu_get_clock(rt_clock))*1000;
1418 if (rtdelta < delta)
1419 delta = rtdelta;
1422 if (delta < MIN_TIMER_REARM_US)
1423 delta = MIN_TIMER_REARM_US;
1425 return delta;
1427 #endif
1429 #ifndef _WIN32
1431 /* Sets a specific flag */
1432 static int fcntl_setfl(int fd, int flag)
1434 int flags;
1436 flags = fcntl(fd, F_GETFL);
1437 if (flags == -1)
1438 return -errno;
1440 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1441 return -errno;
1443 return 0;
1446 #if defined(__linux__)
1448 #define RTC_FREQ 1024
1450 static void enable_sigio_timer(int fd)
1452 struct sigaction act;
1454 /* timer signal */
1455 sigfillset(&act.sa_mask);
1456 act.sa_flags = 0;
1457 act.sa_handler = host_alarm_handler;
1459 sigaction(SIGIO, &act, NULL);
1460 fcntl_setfl(fd, O_ASYNC);
1461 fcntl(fd, F_SETOWN, getpid());
1464 static int hpet_start_timer(struct qemu_alarm_timer *t)
1466 struct hpet_info info;
1467 int r, fd;
1469 fd = open("/dev/hpet", O_RDONLY);
1470 if (fd < 0)
1471 return -1;
1473 /* Set frequency */
1474 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1475 if (r < 0) {
1476 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1477 "error, but for better emulation accuracy type:\n"
1478 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1479 goto fail;
1482 /* Check capabilities */
1483 r = ioctl(fd, HPET_INFO, &info);
1484 if (r < 0)
1485 goto fail;
1487 /* Enable periodic mode */
1488 r = ioctl(fd, HPET_EPI, 0);
1489 if (info.hi_flags && (r < 0))
1490 goto fail;
1492 /* Enable interrupt */
1493 r = ioctl(fd, HPET_IE_ON, 0);
1494 if (r < 0)
1495 goto fail;
1497 enable_sigio_timer(fd);
1498 t->priv = (void *)(long)fd;
1500 return 0;
1501 fail:
1502 close(fd);
1503 return -1;
1506 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1508 int fd = (long)t->priv;
1510 close(fd);
1513 static int rtc_start_timer(struct qemu_alarm_timer *t)
1515 int rtc_fd;
1516 unsigned long current_rtc_freq = 0;
1518 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1519 if (rtc_fd < 0)
1520 return -1;
1521 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1522 if (current_rtc_freq != RTC_FREQ &&
1523 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1524 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1525 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1526 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1527 goto fail;
1529 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1530 fail:
1531 close(rtc_fd);
1532 return -1;
1535 enable_sigio_timer(rtc_fd);
1537 t->priv = (void *)(long)rtc_fd;
1539 return 0;
1542 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1544 int rtc_fd = (long)t->priv;
1546 close(rtc_fd);
1549 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1551 struct sigevent ev;
1552 timer_t host_timer;
1553 struct sigaction act;
1555 sigfillset(&act.sa_mask);
1556 act.sa_flags = 0;
1557 act.sa_handler = host_alarm_handler;
1559 sigaction(SIGALRM, &act, NULL);
1561 ev.sigev_value.sival_int = 0;
1562 ev.sigev_notify = SIGEV_SIGNAL;
1563 ev.sigev_signo = SIGALRM;
1565 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1566 perror("timer_create");
1568 /* disable dynticks */
1569 fprintf(stderr, "Dynamic Ticks disabled\n");
1571 return -1;
1574 t->priv = (void *)(long)host_timer;
1576 return 0;
1579 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1581 timer_t host_timer = (timer_t)(long)t->priv;
1583 timer_delete(host_timer);
1586 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1588 timer_t host_timer = (timer_t)(long)t->priv;
1589 struct itimerspec timeout;
1590 int64_t nearest_delta_us = INT64_MAX;
1591 int64_t current_us;
1593 if (!active_timers[QEMU_TIMER_REALTIME] &&
1594 !active_timers[QEMU_TIMER_VIRTUAL])
1595 return;
1597 nearest_delta_us = qemu_next_deadline_dyntick();
1599 /* check whether a timer is already running */
1600 if (timer_gettime(host_timer, &timeout)) {
1601 perror("gettime");
1602 fprintf(stderr, "Internal timer error: aborting\n");
1603 exit(1);
1605 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1606 if (current_us && current_us <= nearest_delta_us)
1607 return;
1609 timeout.it_interval.tv_sec = 0;
1610 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1611 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1612 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1613 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1614 perror("settime");
1615 fprintf(stderr, "Internal timer error: aborting\n");
1616 exit(1);
1620 #endif /* defined(__linux__) */
1622 static int unix_start_timer(struct qemu_alarm_timer *t)
1624 struct sigaction act;
1625 struct itimerval itv;
1626 int err;
1628 /* timer signal */
1629 sigfillset(&act.sa_mask);
1630 act.sa_flags = 0;
1631 act.sa_handler = host_alarm_handler;
1633 sigaction(SIGALRM, &act, NULL);
1635 itv.it_interval.tv_sec = 0;
1636 /* for i386 kernel 2.6 to get 1 ms */
1637 itv.it_interval.tv_usec = 999;
1638 itv.it_value.tv_sec = 0;
1639 itv.it_value.tv_usec = 10 * 1000;
1641 err = setitimer(ITIMER_REAL, &itv, NULL);
1642 if (err)
1643 return -1;
1645 return 0;
1648 static void unix_stop_timer(struct qemu_alarm_timer *t)
1650 struct itimerval itv;
1652 memset(&itv, 0, sizeof(itv));
1653 setitimer(ITIMER_REAL, &itv, NULL);
1656 #endif /* !defined(_WIN32) */
1658 static void try_to_rearm_timer(void *opaque)
1660 struct qemu_alarm_timer *t = opaque;
1661 #ifndef _WIN32
1662 ssize_t len;
1664 /* Drain the notify pipe */
1665 do {
1666 char buffer[512];
1667 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1668 } while ((len == -1 && errno == EINTR) || len > 0);
1669 #endif
1671 if (t->flags & ALARM_FLAG_EXPIRED) {
1672 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1673 qemu_rearm_alarm_timer(alarm_timer);
1677 #ifdef _WIN32
1679 static int win32_start_timer(struct qemu_alarm_timer *t)
1681 TIMECAPS tc;
1682 struct qemu_alarm_win32 *data = t->priv;
1683 UINT flags;
1685 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1686 if (!data->host_alarm) {
1687 perror("Failed CreateEvent");
1688 return -1;
1691 memset(&tc, 0, sizeof(tc));
1692 timeGetDevCaps(&tc, sizeof(tc));
1694 if (data->period < tc.wPeriodMin)
1695 data->period = tc.wPeriodMin;
1697 timeBeginPeriod(data->period);
1699 flags = TIME_CALLBACK_FUNCTION;
1700 if (alarm_has_dynticks(t))
1701 flags |= TIME_ONESHOT;
1702 else
1703 flags |= TIME_PERIODIC;
1705 data->timerId = timeSetEvent(1, // interval (ms)
1706 data->period, // resolution
1707 host_alarm_handler, // function
1708 (DWORD)t, // parameter
1709 flags);
1711 if (!data->timerId) {
1712 perror("Failed to initialize win32 alarm timer");
1714 timeEndPeriod(data->period);
1715 CloseHandle(data->host_alarm);
1716 return -1;
1719 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1721 return 0;
1724 static void win32_stop_timer(struct qemu_alarm_timer *t)
1726 struct qemu_alarm_win32 *data = t->priv;
1728 timeKillEvent(data->timerId);
1729 timeEndPeriod(data->period);
1731 CloseHandle(data->host_alarm);
1734 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1736 struct qemu_alarm_win32 *data = t->priv;
1737 uint64_t nearest_delta_us;
1739 if (!active_timers[QEMU_TIMER_REALTIME] &&
1740 !active_timers[QEMU_TIMER_VIRTUAL])
1741 return;
1743 nearest_delta_us = qemu_next_deadline_dyntick();
1744 nearest_delta_us /= 1000;
1746 timeKillEvent(data->timerId);
1748 data->timerId = timeSetEvent(1,
1749 data->period,
1750 host_alarm_handler,
1751 (DWORD)t,
1752 TIME_ONESHOT | TIME_PERIODIC);
1754 if (!data->timerId) {
1755 perror("Failed to re-arm win32 alarm timer");
1757 timeEndPeriod(data->period);
1758 CloseHandle(data->host_alarm);
1759 exit(1);
1763 #endif /* _WIN32 */
1765 static int init_timer_alarm(void)
1767 struct qemu_alarm_timer *t = NULL;
1768 int i, err = -1;
1770 #ifndef _WIN32
1771 int fds[2];
1773 err = pipe(fds);
1774 if (err == -1)
1775 return -errno;
1777 err = fcntl_setfl(fds[0], O_NONBLOCK);
1778 if (err < 0)
1779 goto fail;
1781 err = fcntl_setfl(fds[1], O_NONBLOCK);
1782 if (err < 0)
1783 goto fail;
1785 alarm_timer_rfd = fds[0];
1786 alarm_timer_wfd = fds[1];
1787 #endif
1789 for (i = 0; alarm_timers[i].name; i++) {
1790 t = &alarm_timers[i];
1792 err = t->start(t);
1793 if (!err)
1794 break;
1797 if (err) {
1798 err = -ENOENT;
1799 goto fail;
1802 #ifndef _WIN32
1803 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1804 try_to_rearm_timer, NULL, t);
1805 #endif
1807 alarm_timer = t;
1809 return 0;
1811 fail:
1812 #ifndef _WIN32
1813 close(fds[0]);
1814 close(fds[1]);
1815 #endif
1816 return err;
1819 static void quit_timers(void)
1821 alarm_timer->stop(alarm_timer);
1822 alarm_timer = NULL;
1825 /***********************************************************/
1826 /* host time/date access */
1827 void qemu_get_timedate(struct tm *tm, int offset)
1829 time_t ti;
1830 struct tm *ret;
1832 time(&ti);
1833 ti += offset;
1834 if (rtc_date_offset == -1) {
1835 if (rtc_utc)
1836 ret = gmtime(&ti);
1837 else
1838 ret = localtime(&ti);
1839 } else {
1840 ti -= rtc_date_offset;
1841 ret = gmtime(&ti);
1844 memcpy(tm, ret, sizeof(struct tm));
1847 int qemu_timedate_diff(struct tm *tm)
1849 time_t seconds;
1851 if (rtc_date_offset == -1)
1852 if (rtc_utc)
1853 seconds = mktimegm(tm);
1854 else
1855 seconds = mktime(tm);
1856 else
1857 seconds = mktimegm(tm) + rtc_date_offset;
1859 return seconds - time(NULL);
1862 #ifdef _WIN32
1863 static void socket_cleanup(void)
1865 WSACleanup();
1868 static int socket_init(void)
1870 WSADATA Data;
1871 int ret, err;
1873 ret = WSAStartup(MAKEWORD(2,2), &Data);
1874 if (ret != 0) {
1875 err = WSAGetLastError();
1876 fprintf(stderr, "WSAStartup: %d\n", err);
1877 return -1;
1879 atexit(socket_cleanup);
1880 return 0;
1882 #endif
1884 const char *get_opt_name(char *buf, int buf_size, const char *p)
1886 char *q;
1888 q = buf;
1889 while (*p != '\0' && *p != '=') {
1890 if (q && (q - buf) < buf_size - 1)
1891 *q++ = *p;
1892 p++;
1894 if (q)
1895 *q = '\0';
1897 return p;
1900 const char *get_opt_value(char *buf, int buf_size, const char *p)
1902 char *q;
1904 q = buf;
1905 while (*p != '\0') {
1906 if (*p == ',') {
1907 if (*(p + 1) != ',')
1908 break;
1909 p++;
1911 if (q && (q - buf) < buf_size - 1)
1912 *q++ = *p;
1913 p++;
1915 if (q)
1916 *q = '\0';
1918 return p;
1921 int get_param_value(char *buf, int buf_size,
1922 const char *tag, const char *str)
1924 const char *p;
1925 char option[128];
1927 p = str;
1928 for(;;) {
1929 p = get_opt_name(option, sizeof(option), p);
1930 if (*p != '=')
1931 break;
1932 p++;
1933 if (!strcmp(tag, option)) {
1934 (void)get_opt_value(buf, buf_size, p);
1935 return strlen(buf);
1936 } else {
1937 p = get_opt_value(NULL, 0, p);
1939 if (*p != ',')
1940 break;
1941 p++;
1943 return 0;
1946 int check_params(char *buf, int buf_size,
1947 const char * const *params, const char *str)
1949 const char *p;
1950 int i;
1952 p = str;
1953 for(;;) {
1954 p = get_opt_name(buf, buf_size, p);
1955 if (*p != '=')
1956 return -1;
1957 p++;
1958 for(i = 0; params[i] != NULL; i++)
1959 if (!strcmp(params[i], buf))
1960 break;
1961 if (params[i] == NULL)
1962 return -1;
1963 p = get_opt_value(NULL, 0, p);
1964 if (*p != ',')
1965 break;
1966 p++;
1968 return 0;
1971 /***********************************************************/
1972 /* Bluetooth support */
1973 static int nb_hcis;
1974 static int cur_hci;
1975 static struct HCIInfo *hci_table[MAX_NICS];
1977 static struct bt_vlan_s {
1978 struct bt_scatternet_s net;
1979 int id;
1980 struct bt_vlan_s *next;
1981 } *first_bt_vlan;
1983 /* find or alloc a new bluetooth "VLAN" */
1984 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1986 struct bt_vlan_s **pvlan, *vlan;
1987 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1988 if (vlan->id == id)
1989 return &vlan->net;
1991 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1992 vlan->id = id;
1993 pvlan = &first_bt_vlan;
1994 while (*pvlan != NULL)
1995 pvlan = &(*pvlan)->next;
1996 *pvlan = vlan;
1997 return &vlan->net;
2000 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2004 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2006 return -ENOTSUP;
2009 static struct HCIInfo null_hci = {
2010 .cmd_send = null_hci_send,
2011 .sco_send = null_hci_send,
2012 .acl_send = null_hci_send,
2013 .bdaddr_set = null_hci_addr_set,
2016 struct HCIInfo *qemu_next_hci(void)
2018 if (cur_hci == nb_hcis)
2019 return &null_hci;
2021 return hci_table[cur_hci++];
2024 static struct HCIInfo *hci_init(const char *str)
2026 char *endp;
2027 struct bt_scatternet_s *vlan = 0;
2029 if (!strcmp(str, "null"))
2030 /* null */
2031 return &null_hci;
2032 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2033 /* host[:hciN] */
2034 return bt_host_hci(str[4] ? str + 5 : "hci0");
2035 else if (!strncmp(str, "hci", 3)) {
2036 /* hci[,vlan=n] */
2037 if (str[3]) {
2038 if (!strncmp(str + 3, ",vlan=", 6)) {
2039 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2040 if (*endp)
2041 vlan = 0;
2043 } else
2044 vlan = qemu_find_bt_vlan(0);
2045 if (vlan)
2046 return bt_new_hci(vlan);
2049 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2051 return 0;
2054 static int bt_hci_parse(const char *str)
2056 struct HCIInfo *hci;
2057 bdaddr_t bdaddr;
2059 if (nb_hcis >= MAX_NICS) {
2060 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2061 return -1;
2064 hci = hci_init(str);
2065 if (!hci)
2066 return -1;
2068 bdaddr.b[0] = 0x52;
2069 bdaddr.b[1] = 0x54;
2070 bdaddr.b[2] = 0x00;
2071 bdaddr.b[3] = 0x12;
2072 bdaddr.b[4] = 0x34;
2073 bdaddr.b[5] = 0x56 + nb_hcis;
2074 hci->bdaddr_set(hci, bdaddr.b);
2076 hci_table[nb_hcis++] = hci;
2078 return 0;
2081 static void bt_vhci_add(int vlan_id)
2083 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2085 if (!vlan->slave)
2086 fprintf(stderr, "qemu: warning: adding a VHCI to "
2087 "an empty scatternet %i\n", vlan_id);
2089 bt_vhci_init(bt_new_hci(vlan));
2092 static struct bt_device_s *bt_device_add(const char *opt)
2094 struct bt_scatternet_s *vlan;
2095 int vlan_id = 0;
2096 char *endp = strstr(opt, ",vlan=");
2097 int len = (endp ? endp - opt : strlen(opt)) + 1;
2098 char devname[10];
2100 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2102 if (endp) {
2103 vlan_id = strtol(endp + 6, &endp, 0);
2104 if (*endp) {
2105 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2106 return 0;
2110 vlan = qemu_find_bt_vlan(vlan_id);
2112 if (!vlan->slave)
2113 fprintf(stderr, "qemu: warning: adding a slave device to "
2114 "an empty scatternet %i\n", vlan_id);
2116 if (!strcmp(devname, "keyboard"))
2117 return bt_keyboard_init(vlan);
2119 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2120 return 0;
2123 static int bt_parse(const char *opt)
2125 const char *endp, *p;
2126 int vlan;
2128 if (strstart(opt, "hci", &endp)) {
2129 if (!*endp || *endp == ',') {
2130 if (*endp)
2131 if (!strstart(endp, ",vlan=", 0))
2132 opt = endp + 1;
2134 return bt_hci_parse(opt);
2136 } else if (strstart(opt, "vhci", &endp)) {
2137 if (!*endp || *endp == ',') {
2138 if (*endp) {
2139 if (strstart(endp, ",vlan=", &p)) {
2140 vlan = strtol(p, (char **) &endp, 0);
2141 if (*endp) {
2142 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2143 return 1;
2145 } else {
2146 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2147 return 1;
2149 } else
2150 vlan = 0;
2152 bt_vhci_add(vlan);
2153 return 0;
2155 } else if (strstart(opt, "device:", &endp))
2156 return !bt_device_add(endp);
2158 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2159 return 1;
2162 /***********************************************************/
2163 /* QEMU Block devices */
2165 #define HD_ALIAS "index=%d,media=disk"
2166 #ifdef TARGET_PPC
2167 #define CDROM_ALIAS "index=1,media=cdrom"
2168 #else
2169 #define CDROM_ALIAS "index=2,media=cdrom"
2170 #endif
2171 #define FD_ALIAS "index=%d,if=floppy"
2172 #define PFLASH_ALIAS "if=pflash"
2173 #define MTD_ALIAS "if=mtd"
2174 #define SD_ALIAS "index=0,if=sd"
2176 static int drive_opt_get_free_idx(void)
2178 int index;
2180 for (index = 0; index < MAX_DRIVES; index++)
2181 if (!drives_opt[index].used) {
2182 drives_opt[index].used = 1;
2183 return index;
2186 return -1;
2189 static int drive_get_free_idx(void)
2191 int index;
2193 for (index = 0; index < MAX_DRIVES; index++)
2194 if (!drives_table[index].used) {
2195 drives_table[index].used = 1;
2196 return index;
2199 return -1;
2202 int drive_add(const char *file, const char *fmt, ...)
2204 va_list ap;
2205 int index = drive_opt_get_free_idx();
2207 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2208 fprintf(stderr, "qemu: too many drives\n");
2209 return -1;
2212 drives_opt[index].file = file;
2213 va_start(ap, fmt);
2214 vsnprintf(drives_opt[index].opt,
2215 sizeof(drives_opt[0].opt), fmt, ap);
2216 va_end(ap);
2218 nb_drives_opt++;
2219 return index;
2222 void drive_remove(int index)
2224 drives_opt[index].used = 0;
2225 nb_drives_opt--;
2228 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2230 int index;
2232 /* seek interface, bus and unit */
2234 for (index = 0; index < MAX_DRIVES; index++)
2235 if (drives_table[index].type == type &&
2236 drives_table[index].bus == bus &&
2237 drives_table[index].unit == unit &&
2238 drives_table[index].used)
2239 return index;
2241 return -1;
2244 int drive_get_max_bus(BlockInterfaceType type)
2246 int max_bus;
2247 int index;
2249 max_bus = -1;
2250 for (index = 0; index < nb_drives; index++) {
2251 if(drives_table[index].type == type &&
2252 drives_table[index].bus > max_bus)
2253 max_bus = drives_table[index].bus;
2255 return max_bus;
2258 const char *drive_get_serial(BlockDriverState *bdrv)
2260 int index;
2262 for (index = 0; index < nb_drives; index++)
2263 if (drives_table[index].bdrv == bdrv)
2264 return drives_table[index].serial;
2266 return "\0";
2269 static void bdrv_format_print(void *opaque, const char *name)
2271 fprintf(stderr, " %s", name);
2274 void drive_uninit(BlockDriverState *bdrv)
2276 int i;
2278 for (i = 0; i < MAX_DRIVES; i++)
2279 if (drives_table[i].bdrv == bdrv) {
2280 drives_table[i].bdrv = NULL;
2281 drives_table[i].used = 0;
2282 drive_remove(drives_table[i].drive_opt_idx);
2283 nb_drives--;
2284 break;
2288 int drive_init(struct drive_opt *arg, int snapshot,
2289 QEMUMachine *machine)
2291 char buf[128];
2292 char file[1024];
2293 char devname[128];
2294 char serial[21];
2295 const char *mediastr = "";
2296 BlockInterfaceType type;
2297 enum { MEDIA_DISK, MEDIA_CDROM } media;
2298 int bus_id, unit_id;
2299 int cyls, heads, secs, translation;
2300 BlockDriverState *bdrv;
2301 BlockDriver *drv = NULL;
2302 int max_devs;
2303 int index;
2304 int cache;
2305 int bdrv_flags;
2306 int drives_table_idx;
2307 char *str = arg->opt;
2308 static const char * const params[] = { "bus", "unit", "if", "index",
2309 "cyls", "heads", "secs", "trans",
2310 "media", "snapshot", "file",
2311 "cache", "format", "serial",
2312 "boot", NULL };
2314 if (check_params(buf, sizeof(buf), params, str) < 0) {
2315 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2316 buf, str);
2317 return -1;
2320 file[0] = 0;
2321 cyls = heads = secs = 0;
2322 bus_id = 0;
2323 unit_id = -1;
2324 translation = BIOS_ATA_TRANSLATION_AUTO;
2325 index = -1;
2326 cache = 3;
2328 if (machine->use_scsi) {
2329 type = IF_SCSI;
2330 max_devs = MAX_SCSI_DEVS;
2331 pstrcpy(devname, sizeof(devname), "scsi");
2332 } else {
2333 type = IF_IDE;
2334 max_devs = MAX_IDE_DEVS;
2335 pstrcpy(devname, sizeof(devname), "ide");
2337 media = MEDIA_DISK;
2339 /* extract parameters */
2341 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2342 bus_id = strtol(buf, NULL, 0);
2343 if (bus_id < 0) {
2344 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2345 return -1;
2349 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2350 unit_id = strtol(buf, NULL, 0);
2351 if (unit_id < 0) {
2352 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2353 return -1;
2357 if (get_param_value(buf, sizeof(buf), "if", str)) {
2358 pstrcpy(devname, sizeof(devname), buf);
2359 if (!strcmp(buf, "ide")) {
2360 type = IF_IDE;
2361 max_devs = MAX_IDE_DEVS;
2362 } else if (!strcmp(buf, "scsi")) {
2363 type = IF_SCSI;
2364 max_devs = MAX_SCSI_DEVS;
2365 } else if (!strcmp(buf, "floppy")) {
2366 type = IF_FLOPPY;
2367 max_devs = 0;
2368 } else if (!strcmp(buf, "pflash")) {
2369 type = IF_PFLASH;
2370 max_devs = 0;
2371 } else if (!strcmp(buf, "mtd")) {
2372 type = IF_MTD;
2373 max_devs = 0;
2374 } else if (!strcmp(buf, "sd")) {
2375 type = IF_SD;
2376 max_devs = 0;
2377 } else if (!strcmp(buf, "virtio")) {
2378 type = IF_VIRTIO;
2379 max_devs = 0;
2380 } else {
2381 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2382 return -1;
2386 if (get_param_value(buf, sizeof(buf), "index", str)) {
2387 index = strtol(buf, NULL, 0);
2388 if (index < 0) {
2389 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2390 return -1;
2394 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2395 cyls = strtol(buf, NULL, 0);
2398 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2399 heads = strtol(buf, NULL, 0);
2402 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2403 secs = strtol(buf, NULL, 0);
2406 if (cyls || heads || secs) {
2407 if (cyls < 1 || cyls > 16383) {
2408 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2409 return -1;
2411 if (heads < 1 || heads > 16) {
2412 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2413 return -1;
2415 if (secs < 1 || secs > 63) {
2416 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2417 return -1;
2421 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2422 if (!cyls) {
2423 fprintf(stderr,
2424 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2425 str);
2426 return -1;
2428 if (!strcmp(buf, "none"))
2429 translation = BIOS_ATA_TRANSLATION_NONE;
2430 else if (!strcmp(buf, "lba"))
2431 translation = BIOS_ATA_TRANSLATION_LBA;
2432 else if (!strcmp(buf, "auto"))
2433 translation = BIOS_ATA_TRANSLATION_AUTO;
2434 else {
2435 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2436 return -1;
2440 if (get_param_value(buf, sizeof(buf), "media", str)) {
2441 if (!strcmp(buf, "disk")) {
2442 media = MEDIA_DISK;
2443 } else if (!strcmp(buf, "cdrom")) {
2444 if (cyls || secs || heads) {
2445 fprintf(stderr,
2446 "qemu: '%s' invalid physical CHS format\n", str);
2447 return -1;
2449 media = MEDIA_CDROM;
2450 } else {
2451 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2452 return -1;
2456 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2457 if (!strcmp(buf, "on"))
2458 snapshot = 1;
2459 else if (!strcmp(buf, "off"))
2460 snapshot = 0;
2461 else {
2462 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2463 return -1;
2467 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2468 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2469 cache = 0;
2470 else if (!strcmp(buf, "writethrough"))
2471 cache = 1;
2472 else if (!strcmp(buf, "writeback"))
2473 cache = 2;
2474 else {
2475 fprintf(stderr, "qemu: invalid cache option\n");
2476 return -1;
2480 if (get_param_value(buf, sizeof(buf), "format", str)) {
2481 if (strcmp(buf, "?") == 0) {
2482 fprintf(stderr, "qemu: Supported formats:");
2483 bdrv_iterate_format(bdrv_format_print, NULL);
2484 fprintf(stderr, "\n");
2485 return -1;
2487 drv = bdrv_find_format(buf);
2488 if (!drv) {
2489 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2490 return -1;
2494 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2495 if (!strcmp(buf, "on")) {
2496 if (extboot_drive != -1) {
2497 fprintf(stderr, "qemu: two bootable drives specified\n");
2498 return -1;
2500 extboot_drive = nb_drives;
2501 } else if (strcmp(buf, "off")) {
2502 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2503 return -1;
2507 if (arg->file == NULL)
2508 get_param_value(file, sizeof(file), "file", str);
2509 else
2510 pstrcpy(file, sizeof(file), arg->file);
2512 if (!get_param_value(serial, sizeof(serial), "serial", str))
2513 memset(serial, 0, sizeof(serial));
2515 /* compute bus and unit according index */
2517 if (index != -1) {
2518 if (bus_id != 0 || unit_id != -1) {
2519 fprintf(stderr,
2520 "qemu: '%s' index cannot be used with bus and unit\n", str);
2521 return -1;
2523 if (max_devs == 0)
2525 unit_id = index;
2526 bus_id = 0;
2527 } else {
2528 unit_id = index % max_devs;
2529 bus_id = index / max_devs;
2533 /* if user doesn't specify a unit_id,
2534 * try to find the first free
2537 if (unit_id == -1) {
2538 unit_id = 0;
2539 while (drive_get_index(type, bus_id, unit_id) != -1) {
2540 unit_id++;
2541 if (max_devs && unit_id >= max_devs) {
2542 unit_id -= max_devs;
2543 bus_id++;
2548 /* check unit id */
2550 if (max_devs && unit_id >= max_devs) {
2551 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2552 str, unit_id, max_devs - 1);
2553 return -1;
2557 * ignore multiple definitions
2560 if (drive_get_index(type, bus_id, unit_id) != -1)
2561 return -2;
2563 /* init */
2565 if (type == IF_IDE || type == IF_SCSI)
2566 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2567 if (max_devs)
2568 snprintf(buf, sizeof(buf), "%s%i%s%i",
2569 devname, bus_id, mediastr, unit_id);
2570 else
2571 snprintf(buf, sizeof(buf), "%s%s%i",
2572 devname, mediastr, unit_id);
2573 bdrv = bdrv_new(buf);
2574 drives_table_idx = drive_get_free_idx();
2575 drives_table[drives_table_idx].bdrv = bdrv;
2576 drives_table[drives_table_idx].type = type;
2577 drives_table[drives_table_idx].bus = bus_id;
2578 drives_table[drives_table_idx].unit = unit_id;
2579 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2580 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2581 nb_drives++;
2583 switch(type) {
2584 case IF_IDE:
2585 case IF_SCSI:
2586 switch(media) {
2587 case MEDIA_DISK:
2588 if (cyls != 0) {
2589 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2590 bdrv_set_translation_hint(bdrv, translation);
2592 break;
2593 case MEDIA_CDROM:
2594 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2595 break;
2597 break;
2598 case IF_SD:
2599 /* FIXME: This isn't really a floppy, but it's a reasonable
2600 approximation. */
2601 case IF_FLOPPY:
2602 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2603 break;
2604 case IF_PFLASH:
2605 case IF_MTD:
2606 case IF_VIRTIO:
2607 break;
2609 if (!file[0])
2610 return -2;
2611 bdrv_flags = 0;
2612 if (snapshot) {
2613 bdrv_flags |= BDRV_O_SNAPSHOT;
2614 cache = 2; /* always use write-back with snapshot */
2616 if (cache == 0) /* no caching */
2617 bdrv_flags |= BDRV_O_NOCACHE;
2618 else if (cache == 2) /* write-back */
2619 bdrv_flags |= BDRV_O_CACHE_WB;
2620 else if (cache == 3) /* not specified */
2621 bdrv_flags |= BDRV_O_CACHE_DEF;
2622 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2623 fprintf(stderr, "qemu: could not open disk image %s\n",
2624 file);
2625 return -1;
2627 return drives_table_idx;
2630 /***********************************************************/
2631 /* USB devices */
2633 static USBPort *used_usb_ports;
2634 static USBPort *free_usb_ports;
2636 /* ??? Maybe change this to register a hub to keep track of the topology. */
2637 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2638 usb_attachfn attach)
2640 port->opaque = opaque;
2641 port->index = index;
2642 port->attach = attach;
2643 port->next = free_usb_ports;
2644 free_usb_ports = port;
2647 int usb_device_add_dev(USBDevice *dev)
2649 USBPort *port;
2651 /* Find a USB port to add the device to. */
2652 port = free_usb_ports;
2653 if (!port->next) {
2654 USBDevice *hub;
2656 /* Create a new hub and chain it on. */
2657 free_usb_ports = NULL;
2658 port->next = used_usb_ports;
2659 used_usb_ports = port;
2661 hub = usb_hub_init(VM_USB_HUB_SIZE);
2662 usb_attach(port, hub);
2663 port = free_usb_ports;
2666 free_usb_ports = port->next;
2667 port->next = used_usb_ports;
2668 used_usb_ports = port;
2669 usb_attach(port, dev);
2670 return 0;
2673 static int usb_device_add(const char *devname)
2675 const char *p;
2676 USBDevice *dev;
2678 if (!free_usb_ports)
2679 return -1;
2681 if (strstart(devname, "host:", &p)) {
2682 dev = usb_host_device_open(p);
2683 } else if (!strcmp(devname, "mouse")) {
2684 dev = usb_mouse_init();
2685 } else if (!strcmp(devname, "tablet")) {
2686 dev = usb_tablet_init();
2687 } else if (!strcmp(devname, "keyboard")) {
2688 dev = usb_keyboard_init();
2689 } else if (strstart(devname, "disk:", &p)) {
2690 dev = usb_msd_init(p);
2691 } else if (!strcmp(devname, "wacom-tablet")) {
2692 dev = usb_wacom_init();
2693 } else if (strstart(devname, "serial:", &p)) {
2694 dev = usb_serial_init(p);
2695 #ifdef CONFIG_BRLAPI
2696 } else if (!strcmp(devname, "braille")) {
2697 dev = usb_baum_init();
2698 #endif
2699 } else if (strstart(devname, "net:", &p)) {
2700 int nic = nb_nics;
2702 if (net_client_init("nic", p) < 0)
2703 return -1;
2704 nd_table[nic].model = "usb";
2705 dev = usb_net_init(&nd_table[nic]);
2706 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2707 dev = usb_bt_init(devname[2] ? hci_init(p) :
2708 bt_new_hci(qemu_find_bt_vlan(0)));
2709 } else {
2710 return -1;
2712 if (!dev)
2713 return -1;
2715 return usb_device_add_dev(dev);
2718 int usb_device_del_addr(int bus_num, int addr)
2720 USBPort *port;
2721 USBPort **lastp;
2722 USBDevice *dev;
2724 if (!used_usb_ports)
2725 return -1;
2727 if (bus_num != 0)
2728 return -1;
2730 lastp = &used_usb_ports;
2731 port = used_usb_ports;
2732 while (port && port->dev->addr != addr) {
2733 lastp = &port->next;
2734 port = port->next;
2737 if (!port)
2738 return -1;
2740 dev = port->dev;
2741 *lastp = port->next;
2742 usb_attach(port, NULL);
2743 dev->handle_destroy(dev);
2744 port->next = free_usb_ports;
2745 free_usb_ports = port;
2746 return 0;
2749 static int usb_device_del(const char *devname)
2751 int bus_num, addr;
2752 const char *p;
2754 if (strstart(devname, "host:", &p))
2755 return usb_host_device_close(p);
2757 if (!used_usb_ports)
2758 return -1;
2760 p = strchr(devname, '.');
2761 if (!p)
2762 return -1;
2763 bus_num = strtoul(devname, NULL, 0);
2764 addr = strtoul(p + 1, NULL, 0);
2766 return usb_device_del_addr(bus_num, addr);
2769 void do_usb_add(const char *devname)
2771 usb_device_add(devname);
2774 void do_usb_del(const char *devname)
2776 usb_device_del(devname);
2779 void usb_info(void)
2781 USBDevice *dev;
2782 USBPort *port;
2783 const char *speed_str;
2785 if (!usb_enabled) {
2786 term_printf("USB support not enabled\n");
2787 return;
2790 for (port = used_usb_ports; port; port = port->next) {
2791 dev = port->dev;
2792 if (!dev)
2793 continue;
2794 switch(dev->speed) {
2795 case USB_SPEED_LOW:
2796 speed_str = "1.5";
2797 break;
2798 case USB_SPEED_FULL:
2799 speed_str = "12";
2800 break;
2801 case USB_SPEED_HIGH:
2802 speed_str = "480";
2803 break;
2804 default:
2805 speed_str = "?";
2806 break;
2808 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2809 0, dev->addr, speed_str, dev->devname);
2813 /***********************************************************/
2814 /* PCMCIA/Cardbus */
2816 static struct pcmcia_socket_entry_s {
2817 struct pcmcia_socket_s *socket;
2818 struct pcmcia_socket_entry_s *next;
2819 } *pcmcia_sockets = 0;
2821 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2823 struct pcmcia_socket_entry_s *entry;
2825 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2826 entry->socket = socket;
2827 entry->next = pcmcia_sockets;
2828 pcmcia_sockets = entry;
2831 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2833 struct pcmcia_socket_entry_s *entry, **ptr;
2835 ptr = &pcmcia_sockets;
2836 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2837 if (entry->socket == socket) {
2838 *ptr = entry->next;
2839 qemu_free(entry);
2843 void pcmcia_info(void)
2845 struct pcmcia_socket_entry_s *iter;
2846 if (!pcmcia_sockets)
2847 term_printf("No PCMCIA sockets\n");
2849 for (iter = pcmcia_sockets; iter; iter = iter->next)
2850 term_printf("%s: %s\n", iter->socket->slot_string,
2851 iter->socket->attached ? iter->socket->card_string :
2852 "Empty");
2855 /***********************************************************/
2856 /* dumb display */
2858 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2862 static void dumb_resize(DisplayState *ds, int w, int h)
2866 static void dumb_display_init(DisplayState *ds)
2868 ds->data = NULL;
2869 ds->linesize = 0;
2870 ds->depth = 0;
2871 ds->dpy_update = dumb_update;
2872 ds->dpy_resize = dumb_resize;
2873 ds->dpy_refresh = NULL;
2874 ds->gui_timer_interval = 0;
2875 ds->idle = 1;
2878 /***********************************************************/
2879 /* I/O handling */
2881 #define MAX_IO_HANDLERS 64
2883 typedef struct IOHandlerRecord {
2884 int fd;
2885 IOCanRWHandler *fd_read_poll;
2886 IOHandler *fd_read;
2887 IOHandler *fd_write;
2888 int deleted;
2889 void *opaque;
2890 /* temporary data */
2891 struct pollfd *ufd;
2892 struct IOHandlerRecord *next;
2893 } IOHandlerRecord;
2895 static IOHandlerRecord *first_io_handler;
2897 /* XXX: fd_read_poll should be suppressed, but an API change is
2898 necessary in the character devices to suppress fd_can_read(). */
2899 int qemu_set_fd_handler2(int fd,
2900 IOCanRWHandler *fd_read_poll,
2901 IOHandler *fd_read,
2902 IOHandler *fd_write,
2903 void *opaque)
2905 IOHandlerRecord **pioh, *ioh;
2907 if (!fd_read && !fd_write) {
2908 pioh = &first_io_handler;
2909 for(;;) {
2910 ioh = *pioh;
2911 if (ioh == NULL)
2912 break;
2913 if (ioh->fd == fd) {
2914 ioh->deleted = 1;
2915 break;
2917 pioh = &ioh->next;
2919 } else {
2920 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2921 if (ioh->fd == fd)
2922 goto found;
2924 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2925 if (!ioh)
2926 return -1;
2927 ioh->next = first_io_handler;
2928 first_io_handler = ioh;
2929 found:
2930 ioh->fd = fd;
2931 ioh->fd_read_poll = fd_read_poll;
2932 ioh->fd_read = fd_read;
2933 ioh->fd_write = fd_write;
2934 ioh->opaque = opaque;
2935 ioh->deleted = 0;
2937 main_loop_break();
2938 return 0;
2941 int qemu_set_fd_handler(int fd,
2942 IOHandler *fd_read,
2943 IOHandler *fd_write,
2944 void *opaque)
2946 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2949 #ifdef _WIN32
2950 /***********************************************************/
2951 /* Polling handling */
2953 typedef struct PollingEntry {
2954 PollingFunc *func;
2955 void *opaque;
2956 struct PollingEntry *next;
2957 } PollingEntry;
2959 static PollingEntry *first_polling_entry;
2961 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2963 PollingEntry **ppe, *pe;
2964 pe = qemu_mallocz(sizeof(PollingEntry));
2965 if (!pe)
2966 return -1;
2967 pe->func = func;
2968 pe->opaque = opaque;
2969 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2970 *ppe = pe;
2971 return 0;
2974 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2976 PollingEntry **ppe, *pe;
2977 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2978 pe = *ppe;
2979 if (pe->func == func && pe->opaque == opaque) {
2980 *ppe = pe->next;
2981 qemu_free(pe);
2982 break;
2987 /***********************************************************/
2988 /* Wait objects support */
2989 typedef struct WaitObjects {
2990 int num;
2991 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2992 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2993 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2994 } WaitObjects;
2996 static WaitObjects wait_objects = {0};
2998 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3000 WaitObjects *w = &wait_objects;
3002 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3003 return -1;
3004 w->events[w->num] = handle;
3005 w->func[w->num] = func;
3006 w->opaque[w->num] = opaque;
3007 w->num++;
3008 return 0;
3011 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3013 int i, found;
3014 WaitObjects *w = &wait_objects;
3016 found = 0;
3017 for (i = 0; i < w->num; i++) {
3018 if (w->events[i] == handle)
3019 found = 1;
3020 if (found) {
3021 w->events[i] = w->events[i + 1];
3022 w->func[i] = w->func[i + 1];
3023 w->opaque[i] = w->opaque[i + 1];
3026 if (found)
3027 w->num--;
3029 #endif
3031 /***********************************************************/
3032 /* ram save/restore */
3034 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3036 int v;
3038 v = qemu_get_byte(f);
3039 switch(v) {
3040 case 0:
3041 if (qemu_get_buffer(f, buf, len) != len)
3042 return -EIO;
3043 break;
3044 case 1:
3045 v = qemu_get_byte(f);
3046 memset(buf, v, len);
3047 break;
3048 default:
3049 return -EINVAL;
3052 if (qemu_file_has_error(f))
3053 return -EIO;
3055 return 0;
3058 static int ram_load_v1(QEMUFile *f, void *opaque)
3060 int ret;
3061 ram_addr_t i;
3063 if (qemu_get_be32(f) != phys_ram_size)
3064 return -EINVAL;
3065 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3066 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3067 continue;
3068 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3069 if (ret)
3070 return ret;
3072 return 0;
3075 #define BDRV_HASH_BLOCK_SIZE 1024
3076 #define IOBUF_SIZE 4096
3077 #define RAM_CBLOCK_MAGIC 0xfabe
3079 typedef struct RamDecompressState {
3080 z_stream zstream;
3081 QEMUFile *f;
3082 uint8_t buf[IOBUF_SIZE];
3083 } RamDecompressState;
3085 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3087 int ret;
3088 memset(s, 0, sizeof(*s));
3089 s->f = f;
3090 ret = inflateInit(&s->zstream);
3091 if (ret != Z_OK)
3092 return -1;
3093 return 0;
3096 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3098 int ret, clen;
3100 s->zstream.avail_out = len;
3101 s->zstream.next_out = buf;
3102 while (s->zstream.avail_out > 0) {
3103 if (s->zstream.avail_in == 0) {
3104 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3105 return -1;
3106 clen = qemu_get_be16(s->f);
3107 if (clen > IOBUF_SIZE)
3108 return -1;
3109 qemu_get_buffer(s->f, s->buf, clen);
3110 s->zstream.avail_in = clen;
3111 s->zstream.next_in = s->buf;
3113 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3114 if (ret != Z_OK && ret != Z_STREAM_END) {
3115 return -1;
3118 return 0;
3121 static void ram_decompress_close(RamDecompressState *s)
3123 inflateEnd(&s->zstream);
3126 #define RAM_SAVE_FLAG_FULL 0x01
3127 #define RAM_SAVE_FLAG_COMPRESS 0x02
3128 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3129 #define RAM_SAVE_FLAG_PAGE 0x08
3130 #define RAM_SAVE_FLAG_EOS 0x10
3132 static int is_dup_page(uint8_t *page, uint8_t ch)
3134 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3135 uint32_t *array = (uint32_t *)page;
3136 int i;
3138 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3139 if (array[i] != val)
3140 return 0;
3143 return 1;
3146 static int ram_save_block(QEMUFile *f)
3148 static ram_addr_t current_addr = 0;
3149 ram_addr_t saved_addr = current_addr;
3150 ram_addr_t addr = 0;
3151 int found = 0;
3153 while (addr < phys_ram_size) {
3154 if (kvm_enabled() && current_addr == 0)
3155 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3156 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3157 uint8_t ch;
3159 cpu_physical_memory_reset_dirty(current_addr,
3160 current_addr + TARGET_PAGE_SIZE,
3161 MIGRATION_DIRTY_FLAG);
3163 ch = *(phys_ram_base + current_addr);
3165 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3166 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3167 qemu_put_byte(f, ch);
3168 } else {
3169 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3170 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3173 found = 1;
3174 break;
3176 addr += TARGET_PAGE_SIZE;
3177 current_addr = (saved_addr + addr) % phys_ram_size;
3180 return found;
3183 static ram_addr_t ram_save_threshold = 10;
3185 static ram_addr_t ram_save_remaining(void)
3187 ram_addr_t addr;
3188 ram_addr_t count = 0;
3190 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3191 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3192 count++;
3195 return count;
3198 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3200 ram_addr_t addr;
3202 if (stage == 1) {
3203 /* Make sure all dirty bits are set */
3204 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3205 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3206 cpu_physical_memory_set_dirty(addr);
3209 /* Enable dirty memory tracking */
3210 cpu_physical_memory_set_dirty_tracking(1);
3212 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3215 while (!qemu_file_rate_limit(f)) {
3216 int ret;
3218 ret = ram_save_block(f);
3219 if (ret == 0) /* no more blocks */
3220 break;
3223 /* try transferring iterative blocks of memory */
3225 if (stage == 3) {
3226 cpu_physical_memory_set_dirty_tracking(0);
3228 /* flush all remaining blocks regardless of rate limiting */
3229 while (ram_save_block(f) != 0);
3232 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3234 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3237 static int ram_load_dead(QEMUFile *f, void *opaque)
3239 RamDecompressState s1, *s = &s1;
3240 uint8_t buf[10];
3241 ram_addr_t i;
3243 if (ram_decompress_open(s, f) < 0)
3244 return -EINVAL;
3245 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3246 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3247 continue;
3248 if (ram_decompress_buf(s, buf, 1) < 0) {
3249 fprintf(stderr, "Error while reading ram block header\n");
3250 goto error;
3252 if (buf[0] == 0) {
3253 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3254 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3255 goto error;
3257 } else {
3258 error:
3259 printf("Error block header\n");
3260 return -EINVAL;
3263 ram_decompress_close(s);
3265 return 0;
3268 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3270 ram_addr_t addr;
3271 int flags;
3273 if (version_id == 1)
3274 return ram_load_v1(f, opaque);
3276 if (version_id == 2) {
3277 if (qemu_get_be32(f) != phys_ram_size)
3278 return -EINVAL;
3279 return ram_load_dead(f, opaque);
3282 if (version_id != 3)
3283 return -EINVAL;
3285 do {
3286 addr = qemu_get_be64(f);
3288 flags = addr & ~TARGET_PAGE_MASK;
3289 addr &= TARGET_PAGE_MASK;
3291 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3292 if (addr != phys_ram_size)
3293 return -EINVAL;
3296 if (flags & RAM_SAVE_FLAG_FULL) {
3297 if (ram_load_dead(f, opaque) < 0)
3298 return -EINVAL;
3301 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3302 uint8_t ch = qemu_get_byte(f);
3303 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3304 } else if (flags & RAM_SAVE_FLAG_PAGE)
3305 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3306 } while (!(flags & RAM_SAVE_FLAG_EOS));
3308 return 0;
3311 /***********************************************************/
3312 /* bottom halves (can be seen as timers which expire ASAP) */
3314 struct QEMUBH {
3315 QEMUBHFunc *cb;
3316 void *opaque;
3317 int scheduled;
3318 int idle;
3319 int deleted;
3320 QEMUBH *next;
3323 static QEMUBH *first_bh = NULL;
3325 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3327 QEMUBH *bh;
3328 bh = qemu_mallocz(sizeof(QEMUBH));
3329 if (!bh)
3330 return NULL;
3331 bh->cb = cb;
3332 bh->opaque = opaque;
3333 bh->next = first_bh;
3334 first_bh = bh;
3335 return bh;
3338 int qemu_bh_poll(void)
3340 QEMUBH *bh, **bhp;
3341 int ret;
3343 ret = 0;
3344 for (bh = first_bh; bh; bh = bh->next) {
3345 if (!bh->deleted && bh->scheduled) {
3346 bh->scheduled = 0;
3347 if (!bh->idle)
3348 ret = 1;
3349 bh->idle = 0;
3350 bh->cb(bh->opaque);
3354 /* remove deleted bhs */
3355 bhp = &first_bh;
3356 while (*bhp) {
3357 bh = *bhp;
3358 if (bh->deleted) {
3359 *bhp = bh->next;
3360 qemu_free(bh);
3361 } else
3362 bhp = &bh->next;
3365 return ret;
3368 void qemu_bh_schedule_idle(QEMUBH *bh)
3370 if (bh->scheduled)
3371 return;
3372 bh->scheduled = 1;
3373 bh->idle = 1;
3376 void qemu_bh_schedule(QEMUBH *bh)
3378 CPUState *env = cpu_single_env;
3379 if (bh->scheduled)
3380 return;
3381 bh->scheduled = 1;
3382 bh->idle = 0;
3383 /* stop the currently executing CPU to execute the BH ASAP */
3384 if (env) {
3385 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3387 main_loop_break();
3390 void qemu_bh_cancel(QEMUBH *bh)
3392 bh->scheduled = 0;
3395 void qemu_bh_delete(QEMUBH *bh)
3397 bh->scheduled = 0;
3398 bh->deleted = 1;
3401 static void qemu_bh_update_timeout(int *timeout)
3403 QEMUBH *bh;
3405 for (bh = first_bh; bh; bh = bh->next) {
3406 if (!bh->deleted && bh->scheduled) {
3407 if (bh->idle) {
3408 /* idle bottom halves will be polled at least
3409 * every 10ms */
3410 *timeout = MIN(10, *timeout);
3411 } else {
3412 /* non-idle bottom halves will be executed
3413 * immediately */
3414 *timeout = 0;
3415 break;
3421 /***********************************************************/
3422 /* machine registration */
3424 static QEMUMachine *first_machine = NULL;
3425 QEMUMachine *current_machine = NULL;
3427 int qemu_register_machine(QEMUMachine *m)
3429 QEMUMachine **pm;
3430 pm = &first_machine;
3431 while (*pm != NULL)
3432 pm = &(*pm)->next;
3433 m->next = NULL;
3434 *pm = m;
3435 return 0;
3438 static QEMUMachine *find_machine(const char *name)
3440 QEMUMachine *m;
3442 for(m = first_machine; m != NULL; m = m->next) {
3443 if (!strcmp(m->name, name))
3444 return m;
3446 return NULL;
3449 /***********************************************************/
3450 /* main execution loop */
3452 static void gui_update(void *opaque)
3454 DisplayState *ds = opaque;
3455 ds->dpy_refresh(ds);
3456 qemu_mod_timer(ds->gui_timer,
3457 (ds->gui_timer_interval ?
3458 ds->gui_timer_interval :
3459 GUI_REFRESH_INTERVAL)
3460 + qemu_get_clock(rt_clock));
3463 struct vm_change_state_entry {
3464 VMChangeStateHandler *cb;
3465 void *opaque;
3466 LIST_ENTRY (vm_change_state_entry) entries;
3469 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3471 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3472 void *opaque)
3474 VMChangeStateEntry *e;
3476 e = qemu_mallocz(sizeof (*e));
3477 if (!e)
3478 return NULL;
3480 e->cb = cb;
3481 e->opaque = opaque;
3482 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3483 return e;
3486 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3488 LIST_REMOVE (e, entries);
3489 qemu_free (e);
3492 static void vm_state_notify(int running)
3494 VMChangeStateEntry *e;
3496 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3497 e->cb(e->opaque, running);
3501 /* XXX: support several handlers */
3502 static VMStopHandler *vm_stop_cb;
3503 static void *vm_stop_opaque;
3505 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3507 vm_stop_cb = cb;
3508 vm_stop_opaque = opaque;
3509 return 0;
3512 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3514 vm_stop_cb = NULL;
3517 void vm_start(void)
3519 if (!vm_running) {
3520 cpu_enable_ticks();
3521 vm_running = 1;
3522 vm_state_notify(1);
3523 qemu_rearm_alarm_timer(alarm_timer);
3527 void vm_stop(int reason)
3529 if (vm_running) {
3530 cpu_disable_ticks();
3531 vm_running = 0;
3532 if (reason != 0) {
3533 if (vm_stop_cb) {
3534 vm_stop_cb(vm_stop_opaque, reason);
3537 vm_state_notify(0);
3541 /* reset/shutdown handler */
3543 typedef struct QEMUResetEntry {
3544 QEMUResetHandler *func;
3545 void *opaque;
3546 struct QEMUResetEntry *next;
3547 } QEMUResetEntry;
3549 static QEMUResetEntry *first_reset_entry;
3550 static int reset_requested;
3551 static int shutdown_requested;
3552 static int powerdown_requested;
3554 int qemu_shutdown_requested(void)
3556 int r = shutdown_requested;
3557 shutdown_requested = 0;
3558 return r;
3561 int qemu_reset_requested(void)
3563 int r = reset_requested;
3564 reset_requested = 0;
3565 return r;
3568 int qemu_powerdown_requested(void)
3570 int r = powerdown_requested;
3571 powerdown_requested = 0;
3572 return r;
3575 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3577 QEMUResetEntry **pre, *re;
3579 pre = &first_reset_entry;
3580 while (*pre != NULL)
3581 pre = &(*pre)->next;
3582 re = qemu_mallocz(sizeof(QEMUResetEntry));
3583 re->func = func;
3584 re->opaque = opaque;
3585 re->next = NULL;
3586 *pre = re;
3589 void qemu_system_reset(void)
3591 QEMUResetEntry *re;
3593 /* reset all devices */
3594 for(re = first_reset_entry; re != NULL; re = re->next) {
3595 re->func(re->opaque);
3599 void qemu_system_reset_request(void)
3601 if (no_reboot) {
3602 shutdown_requested = 1;
3603 } else {
3604 reset_requested = 1;
3607 if (cpu_single_env) {
3608 qemu_kvm_cpu_stop(cpu_single_env);
3609 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3611 main_loop_break();
3614 void qemu_system_shutdown_request(void)
3616 shutdown_requested = 1;
3617 if (cpu_single_env)
3618 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3621 void qemu_system_powerdown_request(void)
3623 powerdown_requested = 1;
3624 if (cpu_single_env)
3625 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3628 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3629 struct timeval *tv)
3631 int ret;
3633 /* KVM holds a mutex while QEMU code is running, we need hooks to
3634 release the mutex whenever QEMU code sleeps. */
3636 kvm_sleep_begin();
3638 ret = select(max_fd, rfds, wfds, xfds, tv);
3640 kvm_sleep_end();
3642 return ret;
3645 #ifdef _WIN32
3646 static void host_main_loop_wait(int *timeout)
3648 int ret, ret2, i;
3649 PollingEntry *pe;
3652 /* XXX: need to suppress polling by better using win32 events */
3653 ret = 0;
3654 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3655 ret |= pe->func(pe->opaque);
3657 if (ret == 0) {
3658 int err;
3659 WaitObjects *w = &wait_objects;
3661 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3662 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3663 if (w->func[ret - WAIT_OBJECT_0])
3664 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3666 /* Check for additional signaled events */
3667 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3669 /* Check if event is signaled */
3670 ret2 = WaitForSingleObject(w->events[i], 0);
3671 if(ret2 == WAIT_OBJECT_0) {
3672 if (w->func[i])
3673 w->func[i](w->opaque[i]);
3674 } else if (ret2 == WAIT_TIMEOUT) {
3675 } else {
3676 err = GetLastError();
3677 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3680 } else if (ret == WAIT_TIMEOUT) {
3681 } else {
3682 err = GetLastError();
3683 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3687 *timeout = 0;
3689 #else
3690 static void host_main_loop_wait(int *timeout)
3693 #endif
3695 void main_loop_wait(int timeout)
3697 IOHandlerRecord *ioh;
3698 fd_set rfds, wfds, xfds;
3699 int ret, nfds;
3700 struct timeval tv;
3702 qemu_bh_update_timeout(&timeout);
3704 host_main_loop_wait(&timeout);
3706 /* poll any events */
3707 /* XXX: separate device handlers from system ones */
3708 nfds = -1;
3709 FD_ZERO(&rfds);
3710 FD_ZERO(&wfds);
3711 FD_ZERO(&xfds);
3712 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3713 if (ioh->deleted)
3714 continue;
3715 if (ioh->fd_read &&
3716 (!ioh->fd_read_poll ||
3717 ioh->fd_read_poll(ioh->opaque) != 0)) {
3718 FD_SET(ioh->fd, &rfds);
3719 if (ioh->fd > nfds)
3720 nfds = ioh->fd;
3722 if (ioh->fd_write) {
3723 FD_SET(ioh->fd, &wfds);
3724 if (ioh->fd > nfds)
3725 nfds = ioh->fd;
3729 tv.tv_sec = timeout / 1000;
3730 tv.tv_usec = (timeout % 1000) * 1000;
3732 #if defined(CONFIG_SLIRP)
3733 if (slirp_is_inited()) {
3734 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3736 #endif
3737 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3738 if (ret > 0) {
3739 IOHandlerRecord **pioh;
3741 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3742 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3743 ioh->fd_read(ioh->opaque);
3744 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3745 FD_CLR(ioh->fd, &rfds);
3747 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3748 ioh->fd_write(ioh->opaque);
3752 /* remove deleted IO handlers */
3753 pioh = &first_io_handler;
3754 while (*pioh) {
3755 ioh = *pioh;
3756 if (ioh->deleted) {
3757 *pioh = ioh->next;
3758 qemu_free(ioh);
3759 } else
3760 pioh = &ioh->next;
3763 #if defined(CONFIG_SLIRP)
3764 if (slirp_is_inited()) {
3765 if (ret < 0) {
3766 FD_ZERO(&rfds);
3767 FD_ZERO(&wfds);
3768 FD_ZERO(&xfds);
3770 slirp_select_poll(&rfds, &wfds, &xfds);
3772 #endif
3774 /* vm time timers */
3775 if (vm_running && (!cur_cpu
3776 || 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;
3799 if (kvm_enabled()) {
3800 kvm_main_loop();
3801 cpu_disable_ticks();
3802 return 0;
3805 cur_cpu = first_cpu;
3806 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3807 for(;;) {
3808 if (vm_running) {
3810 for(;;) {
3811 /* get next cpu */
3812 env = next_cpu;
3813 #ifdef CONFIG_PROFILER
3814 ti = profile_getclock();
3815 #endif
3816 if (use_icount) {
3817 int64_t count;
3818 int decr;
3819 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3820 env->icount_decr.u16.low = 0;
3821 env->icount_extra = 0;
3822 count = qemu_next_deadline();
3823 count = (count + (1 << icount_time_shift) - 1)
3824 >> icount_time_shift;
3825 qemu_icount += count;
3826 decr = (count > 0xffff) ? 0xffff : count;
3827 count -= decr;
3828 env->icount_decr.u16.low = decr;
3829 env->icount_extra = count;
3831 ret = cpu_exec(env);
3832 #ifdef CONFIG_PROFILER
3833 qemu_time += profile_getclock() - ti;
3834 #endif
3835 if (use_icount) {
3836 /* Fold pending instructions back into the
3837 instruction counter, and clear the interrupt flag. */
3838 qemu_icount -= (env->icount_decr.u16.low
3839 + env->icount_extra);
3840 env->icount_decr.u32 = 0;
3841 env->icount_extra = 0;
3843 next_cpu = env->next_cpu ?: first_cpu;
3844 if (event_pending && likely(ret != EXCP_DEBUG)) {
3845 ret = EXCP_INTERRUPT;
3846 event_pending = 0;
3847 break;
3849 if (ret == EXCP_HLT) {
3850 /* Give the next CPU a chance to run. */
3851 cur_cpu = env;
3852 continue;
3854 if (ret != EXCP_HALTED)
3855 break;
3856 /* all CPUs are halted ? */
3857 if (env == cur_cpu)
3858 break;
3860 cur_cpu = env;
3862 if (shutdown_requested) {
3863 ret = EXCP_INTERRUPT;
3864 if (no_shutdown) {
3865 vm_stop(0);
3866 no_shutdown = 0;
3868 else
3869 break;
3871 if (reset_requested) {
3872 reset_requested = 0;
3873 qemu_system_reset();
3874 if (kvm_enabled())
3875 kvm_load_registers(env);
3876 ret = EXCP_INTERRUPT;
3878 if (powerdown_requested) {
3879 powerdown_requested = 0;
3880 qemu_system_powerdown();
3881 ret = EXCP_INTERRUPT;
3883 #ifdef CONFIG_GDBSTUB
3884 if (unlikely(ret == EXCP_DEBUG)) {
3885 gdb_set_stop_cpu(cur_cpu);
3886 vm_stop(EXCP_DEBUG);
3888 #endif
3889 /* If all cpus are halted then wait until the next IRQ */
3890 /* XXX: use timeout computed from timers */
3891 if (ret == EXCP_HALTED) {
3892 if (use_icount) {
3893 int64_t add;
3894 int64_t delta;
3895 /* Advance virtual time to the next event. */
3896 if (use_icount == 1) {
3897 /* When not using an adaptive execution frequency
3898 we tend to get badly out of sync with real time,
3899 so just delay for a reasonable amount of time. */
3900 delta = 0;
3901 } else {
3902 delta = cpu_get_icount() - cpu_get_clock();
3904 if (delta > 0) {
3905 /* If virtual time is ahead of real time then just
3906 wait for IO. */
3907 timeout = (delta / 1000000) + 1;
3908 } else {
3909 /* Wait for either IO to occur or the next
3910 timer event. */
3911 add = qemu_next_deadline();
3912 /* We advance the timer before checking for IO.
3913 Limit the amount we advance so that early IO
3914 activity won't get the guest too far ahead. */
3915 if (add > 10000000)
3916 add = 10000000;
3917 delta += add;
3918 add = (add + (1 << icount_time_shift) - 1)
3919 >> icount_time_shift;
3920 qemu_icount += add;
3921 timeout = delta / 1000000;
3922 if (timeout < 0)
3923 timeout = 0;
3925 } else {
3926 timeout = 5000;
3928 } else {
3929 timeout = 0;
3931 } else {
3932 if (shutdown_requested) {
3933 ret = EXCP_INTERRUPT;
3934 break;
3936 timeout = 5000;
3938 #ifdef CONFIG_PROFILER
3939 ti = profile_getclock();
3940 #endif
3941 main_loop_wait(timeout);
3942 #ifdef CONFIG_PROFILER
3943 dev_time += profile_getclock() - ti;
3944 #endif
3946 cpu_disable_ticks();
3947 return ret;
3950 static void help(int exitcode)
3952 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
3953 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3954 "usage: %s [options] [disk_image]\n"
3955 "\n"
3956 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3957 "\n"
3958 "Standard options:\n"
3959 "-M machine select emulated machine (-M ? for list)\n"
3960 "-cpu cpu select CPU (-cpu ? for list)\n"
3961 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3962 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3963 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3964 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3965 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3966 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3967 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3968 " [,boot=on|off]\n"
3969 " use 'file' as a drive image\n"
3970 "-mtdblock file use 'file' as on-board Flash memory image\n"
3971 "-sd file use 'file' as SecureDigital card image\n"
3972 "-pflash file use 'file' as a parallel flash image\n"
3973 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3974 "-snapshot write to temporary files instead of disk image files\n"
3975 #ifdef CONFIG_SDL
3976 "-no-frame open SDL window without a frame and window decorations\n"
3977 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3978 "-no-quit disable SDL window close capability\n"
3979 #endif
3980 #ifdef TARGET_I386
3981 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
3982 #endif
3983 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3984 "-smp n set the number of CPUs to 'n' [default=1]\n"
3985 "-nographic disable graphical output and redirect serial I/Os to console\n"
3986 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
3987 #ifndef _WIN32
3988 "-k language use keyboard layout (for example \"fr\" for French)\n"
3989 #endif
3990 #ifdef HAS_AUDIO
3991 "-audio-help print list of audio drivers and their options\n"
3992 "-soundhw c1,... enable audio support\n"
3993 " and only specified sound cards (comma separated list)\n"
3994 " use -soundhw ? to get the list of supported cards\n"
3995 " use -soundhw all to enable all of them\n"
3996 #endif
3997 "-vga [std|cirrus|vmware]\n"
3998 " select video card type\n"
3999 "-localtime set the real time clock to local time [default=utc]\n"
4000 "-full-screen start in full screen\n"
4001 #ifdef TARGET_I386
4002 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4003 #endif
4004 "-usb enable the USB driver (will be the default soon)\n"
4005 "-usbdevice name add the host or guest USB device 'name'\n"
4006 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4007 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4008 #endif
4009 #ifdef TARGET_IA64
4010 "-nvram file use 'file' to save or load nvram image\n"
4011 #endif
4012 "-name string set the name of the guest\n"
4013 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4014 "\n"
4015 "Network options:\n"
4016 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
4017 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4018 #ifdef CONFIG_SLIRP
4019 "-net user[,vlan=n][,name=str][,hostname=host]\n"
4020 " connect the user mode network stack to VLAN 'n' and send\n"
4021 " hostname 'host' to DHCP clients\n"
4022 #endif
4023 #ifdef _WIN32
4024 "-net tap[,vlan=n][,name=str],ifname=name\n"
4025 " connect the host TAP network interface to VLAN 'n'\n"
4026 #else
4027 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4028 " connect the host TAP network interface to VLAN 'n' and use the\n"
4029 " network scripts 'file' (default=%s)\n"
4030 " and 'dfile' (default=%s);\n"
4031 " use '[down]script=no' to disable script execution;\n"
4032 " use 'fd=h' to connect to an already opened TAP interface\n"
4033 #endif
4034 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4035 " connect the vlan 'n' to another VLAN using a socket connection\n"
4036 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4037 " connect the vlan 'n' to multicast maddr and port\n"
4038 #ifdef CONFIG_VDE
4039 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4040 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4041 " on host and listening for incoming connections on 'socketpath'.\n"
4042 " Use group 'groupname' and mode 'octalmode' to change default\n"
4043 " ownership and permissions for communication port.\n"
4044 #endif
4045 "-net none use it alone to have zero network devices; if no -net option\n"
4046 " is provided, the default is '-net nic -net user'\n"
4047 "\n"
4048 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
4049 "-bt hci,host[:id]\n"
4050 " Use host's HCI with the given name\n"
4051 "-bt hci[,vlan=n]\n"
4052 " Emulate a standard HCI in virtual scatternet 'n'\n"
4053 "-bt vhci[,vlan=n]\n"
4054 " Add host computer to virtual scatternet 'n' using VHCI\n"
4055 "-bt device:dev[,vlan=n]\n"
4056 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
4057 "\n"
4058 #ifdef CONFIG_SLIRP
4059 "-tftp dir allow tftp access to files in dir [-net user]\n"
4060 "-bootp file advertise file in BOOTP replies\n"
4061 #ifndef _WIN32
4062 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4063 #endif
4064 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4065 " redirect TCP or UDP connections from host to guest [-net user]\n"
4066 #endif
4067 "\n"
4068 "Linux boot specific:\n"
4069 "-kernel bzImage use 'bzImage' as kernel image\n"
4070 "-append cmdline use 'cmdline' as kernel command line\n"
4071 "-initrd file use 'file' as initial ram disk\n"
4072 "\n"
4073 "Debug/Expert options:\n"
4074 "-monitor dev redirect the monitor to char device 'dev'\n"
4075 "-serial dev redirect the serial port to char device 'dev'\n"
4076 "-parallel dev redirect the parallel port to char device 'dev'\n"
4077 "-pidfile file Write PID to 'file'\n"
4078 "-S freeze CPU at startup (use 'c' to start execution)\n"
4079 "-s wait gdb connection to port\n"
4080 "-p port set gdb connection port [default=%s]\n"
4081 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4082 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4083 " translation (t=none or lba) (usually qemu can guess them)\n"
4084 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4085 #ifdef USE_KQEMU
4086 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4087 "-no-kqemu disable KQEMU kernel module usage\n"
4088 #endif
4089 #ifdef CONFIG_KVM
4090 "-enable-kvm enable KVM full virtualization support\n"
4091 #endif
4092 #ifdef USE_KVM
4093 #ifndef NO_CPU_EMULATION
4094 "-no-kvm disable KVM hardware virtualization\n"
4095 #endif
4096 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4097 "-no-kvm-pit disable KVM kernel mode PIT\n"
4098 "-no-kvm-pit-reinjection disable KVM kernel mode PIT interrupt reinjection\n"
4099 "-enable-nesting enable support for running a VM inside the VM (AMD only)\n"
4100 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4101 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4102 " expose a PCI device to the guest OS.\n"
4103 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4104 " 'string' is used in log output.\n"
4105 #endif
4106 #endif
4107 #ifdef TARGET_I386
4108 "-no-acpi disable ACPI\n"
4109 "-no-hpet disable HPET\n"
4110 #endif
4111 #ifdef CONFIG_CURSES
4112 "-curses use a curses/ncurses interface instead of SDL\n"
4113 #endif
4114 "-no-reboot exit instead of rebooting\n"
4115 "-no-shutdown stop before shutdown\n"
4116 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
4117 "-vnc display start a VNC server on display\n"
4118 #ifndef _WIN32
4119 "-daemonize daemonize QEMU after initializing\n"
4120 #endif
4121 "-tdf inject timer interrupts that got lost\n"
4122 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4123 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
4124 "-option-rom rom load a file, rom, into the option ROM space\n"
4125 #ifdef TARGET_SPARC
4126 "-prom-env variable=value set OpenBIOS nvram variables\n"
4127 #endif
4128 "-clock force the use of the given methods for timer alarm.\n"
4129 " To see what timers are available use -clock ?\n"
4130 "-startdate select initial date of the clock\n"
4131 "-icount [N|auto]\n"
4132 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4133 "\n"
4134 "During emulation, the following keys are useful:\n"
4135 "ctrl-alt-f toggle full screen\n"
4136 "ctrl-alt-n switch to virtual console 'n'\n"
4137 "ctrl-alt toggle mouse and keyboard grab\n"
4138 "\n"
4139 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4141 "qemu",
4142 DEFAULT_RAM_SIZE,
4143 #ifndef _WIN32
4144 DEFAULT_NETWORK_SCRIPT,
4145 DEFAULT_NETWORK_DOWN_SCRIPT,
4146 #endif
4147 DEFAULT_GDBSTUB_PORT,
4148 "/tmp/qemu.log");
4149 exit(exitcode);
4152 #define HAS_ARG 0x0001
4154 enum {
4155 QEMU_OPTION_h,
4157 QEMU_OPTION_M,
4158 QEMU_OPTION_cpu,
4159 QEMU_OPTION_fda,
4160 QEMU_OPTION_fdb,
4161 QEMU_OPTION_hda,
4162 QEMU_OPTION_hdb,
4163 QEMU_OPTION_hdc,
4164 QEMU_OPTION_hdd,
4165 QEMU_OPTION_drive,
4166 QEMU_OPTION_cdrom,
4167 QEMU_OPTION_mtdblock,
4168 QEMU_OPTION_sd,
4169 QEMU_OPTION_pflash,
4170 QEMU_OPTION_boot,
4171 QEMU_OPTION_snapshot,
4172 #ifdef TARGET_I386
4173 QEMU_OPTION_no_fd_bootchk,
4174 #endif
4175 QEMU_OPTION_m,
4176 QEMU_OPTION_nographic,
4177 QEMU_OPTION_portrait,
4178 #ifdef HAS_AUDIO
4179 QEMU_OPTION_audio_help,
4180 QEMU_OPTION_soundhw,
4181 #endif
4183 QEMU_OPTION_net,
4184 QEMU_OPTION_tftp,
4185 QEMU_OPTION_bootp,
4186 QEMU_OPTION_smb,
4187 QEMU_OPTION_redir,
4188 QEMU_OPTION_bt,
4190 QEMU_OPTION_kernel,
4191 QEMU_OPTION_append,
4192 QEMU_OPTION_initrd,
4194 QEMU_OPTION_S,
4195 QEMU_OPTION_s,
4196 QEMU_OPTION_p,
4197 QEMU_OPTION_d,
4198 QEMU_OPTION_hdachs,
4199 QEMU_OPTION_L,
4200 QEMU_OPTION_bios,
4201 QEMU_OPTION_k,
4202 QEMU_OPTION_localtime,
4203 QEMU_OPTION_g,
4204 QEMU_OPTION_vga,
4205 QEMU_OPTION_echr,
4206 QEMU_OPTION_monitor,
4207 QEMU_OPTION_serial,
4208 QEMU_OPTION_parallel,
4209 QEMU_OPTION_loadvm,
4210 QEMU_OPTION_full_screen,
4211 QEMU_OPTION_no_frame,
4212 QEMU_OPTION_alt_grab,
4213 QEMU_OPTION_no_quit,
4214 QEMU_OPTION_pidfile,
4215 QEMU_OPTION_no_kqemu,
4216 QEMU_OPTION_kernel_kqemu,
4217 QEMU_OPTION_enable_kvm,
4218 QEMU_OPTION_enable_nesting,
4219 QEMU_OPTION_win2k_hack,
4220 QEMU_OPTION_usb,
4221 QEMU_OPTION_usbdevice,
4222 QEMU_OPTION_smp,
4223 QEMU_OPTION_vnc,
4224 QEMU_OPTION_no_acpi,
4225 QEMU_OPTION_no_hpet,
4226 QEMU_OPTION_curses,
4227 QEMU_OPTION_no_kvm,
4228 QEMU_OPTION_no_kvm_irqchip,
4229 QEMU_OPTION_no_kvm_pit,
4230 QEMU_OPTION_no_kvm_pit_reinjection,
4231 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4232 QEMU_OPTION_pcidevice,
4233 #endif
4234 QEMU_OPTION_no_reboot,
4235 QEMU_OPTION_no_shutdown,
4236 QEMU_OPTION_show_cursor,
4237 QEMU_OPTION_daemonize,
4238 QEMU_OPTION_option_rom,
4239 QEMU_OPTION_semihosting,
4240 QEMU_OPTION_cpu_vendor,
4241 QEMU_OPTION_name,
4242 QEMU_OPTION_nvram,
4243 QEMU_OPTION_prom_env,
4244 QEMU_OPTION_old_param,
4245 QEMU_OPTION_clock,
4246 QEMU_OPTION_startdate,
4247 QEMU_OPTION_tb_size,
4248 QEMU_OPTION_icount,
4249 QEMU_OPTION_uuid,
4250 QEMU_OPTION_incoming,
4251 QEMU_OPTION_tdf,
4252 QEMU_OPTION_kvm_shadow_memory,
4253 QEMU_OPTION_mempath,
4256 typedef struct QEMUOption {
4257 const char *name;
4258 int flags;
4259 int index;
4260 } QEMUOption;
4262 static const QEMUOption qemu_options[] = {
4263 { "h", 0, QEMU_OPTION_h },
4264 { "help", 0, QEMU_OPTION_h },
4266 { "M", HAS_ARG, QEMU_OPTION_M },
4267 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4268 { "fda", HAS_ARG, QEMU_OPTION_fda },
4269 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4270 { "hda", HAS_ARG, QEMU_OPTION_hda },
4271 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4272 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4273 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4274 { "drive", HAS_ARG, QEMU_OPTION_drive },
4275 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4276 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4277 { "sd", HAS_ARG, QEMU_OPTION_sd },
4278 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4279 { "boot", HAS_ARG, QEMU_OPTION_boot },
4280 { "snapshot", 0, QEMU_OPTION_snapshot },
4281 #ifdef TARGET_I386
4282 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4283 #endif
4284 { "m", HAS_ARG, QEMU_OPTION_m },
4285 { "nographic", 0, QEMU_OPTION_nographic },
4286 { "portrait", 0, QEMU_OPTION_portrait },
4287 { "k", HAS_ARG, QEMU_OPTION_k },
4288 #ifdef HAS_AUDIO
4289 { "audio-help", 0, QEMU_OPTION_audio_help },
4290 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4291 #endif
4293 { "net", HAS_ARG, QEMU_OPTION_net},
4294 #ifdef CONFIG_SLIRP
4295 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4296 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4297 #ifndef _WIN32
4298 { "smb", HAS_ARG, QEMU_OPTION_smb },
4299 #endif
4300 { "redir", HAS_ARG, QEMU_OPTION_redir },
4301 #endif
4302 { "bt", HAS_ARG, QEMU_OPTION_bt },
4304 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4305 { "append", HAS_ARG, QEMU_OPTION_append },
4306 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4308 { "S", 0, QEMU_OPTION_S },
4309 { "s", 0, QEMU_OPTION_s },
4310 { "p", HAS_ARG, QEMU_OPTION_p },
4311 { "d", HAS_ARG, QEMU_OPTION_d },
4312 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4313 { "L", HAS_ARG, QEMU_OPTION_L },
4314 { "bios", HAS_ARG, QEMU_OPTION_bios },
4315 #ifdef USE_KQEMU
4316 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4317 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4318 #endif
4319 #ifdef CONFIG_KVM
4320 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4321 #endif
4322 #ifdef USE_KVM
4323 #ifndef NO_CPU_EMULATION
4324 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4325 #endif
4326 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4327 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4328 { "no-kvm-pit-reinjection", 0, QEMU_OPTION_no_kvm_pit_reinjection },
4329 { "enable-nesting", 0, QEMU_OPTION_enable_nesting },
4330 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4331 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4332 #endif
4333 #endif
4334 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4335 { "g", 1, QEMU_OPTION_g },
4336 #endif
4337 { "localtime", 0, QEMU_OPTION_localtime },
4338 { "vga", HAS_ARG, QEMU_OPTION_vga },
4339 { "echr", HAS_ARG, QEMU_OPTION_echr },
4340 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4341 { "serial", HAS_ARG, QEMU_OPTION_serial },
4342 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4343 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4344 { "incoming", 1, QEMU_OPTION_incoming },
4345 { "full-screen", 0, QEMU_OPTION_full_screen },
4346 #ifdef CONFIG_SDL
4347 { "no-frame", 0, QEMU_OPTION_no_frame },
4348 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4349 { "no-quit", 0, QEMU_OPTION_no_quit },
4350 #endif
4351 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4352 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4353 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4354 { "smp", HAS_ARG, QEMU_OPTION_smp },
4355 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4356 #ifdef CONFIG_CURSES
4357 { "curses", 0, QEMU_OPTION_curses },
4358 #endif
4359 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4361 /* temporary options */
4362 { "usb", 0, QEMU_OPTION_usb },
4363 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4364 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4365 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4366 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4367 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4368 { "daemonize", 0, QEMU_OPTION_daemonize },
4369 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4370 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4371 { "semihosting", 0, QEMU_OPTION_semihosting },
4372 #endif
4373 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4374 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4375 { "name", HAS_ARG, QEMU_OPTION_name },
4376 { "nvram", HAS_ARG, QEMU_OPTION_nvram },
4377 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4378 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4379 #endif
4380 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4381 #if defined(TARGET_ARM)
4382 { "old-param", 0, QEMU_OPTION_old_param },
4383 #endif
4384 { "clock", HAS_ARG, QEMU_OPTION_clock },
4385 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4386 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4387 { "icount", HAS_ARG, QEMU_OPTION_icount },
4388 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4389 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4390 { NULL },
4393 /* password input */
4395 int qemu_key_check(BlockDriverState *bs, const char *name)
4397 char password[256];
4398 int i;
4400 if (!bdrv_is_encrypted(bs))
4401 return 0;
4403 term_printf("%s is encrypted.\n", name);
4404 for(i = 0; i < 3; i++) {
4405 monitor_readline("Password: ", 1, password, sizeof(password));
4406 if (bdrv_set_key(bs, password) == 0)
4407 return 0;
4408 term_printf("invalid password\n");
4410 return -EPERM;
4413 static BlockDriverState *get_bdrv(int index)
4415 if (index > nb_drives)
4416 return NULL;
4417 return drives_table[index].bdrv;
4420 static void read_passwords(void)
4422 BlockDriverState *bs;
4423 int i;
4425 for(i = 0; i < 6; i++) {
4426 bs = get_bdrv(i);
4427 if (bs)
4428 qemu_key_check(bs, bdrv_get_device_name(bs));
4432 #ifdef HAS_AUDIO
4433 struct soundhw soundhw[] = {
4434 #ifdef HAS_AUDIO_CHOICE
4435 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4437 "pcspk",
4438 "PC speaker",
4441 { .init_isa = pcspk_audio_init }
4443 #endif
4445 #ifdef CONFIG_SB16
4447 "sb16",
4448 "Creative Sound Blaster 16",
4451 { .init_isa = SB16_init }
4453 #endif
4455 #ifdef CONFIG_CS4231A
4457 "cs4231a",
4458 "CS4231A",
4461 { .init_isa = cs4231a_init }
4463 #endif
4465 #ifdef CONFIG_ADLIB
4467 "adlib",
4468 #ifdef HAS_YMF262
4469 "Yamaha YMF262 (OPL3)",
4470 #else
4471 "Yamaha YM3812 (OPL2)",
4472 #endif
4475 { .init_isa = Adlib_init }
4477 #endif
4479 #ifdef CONFIG_GUS
4481 "gus",
4482 "Gravis Ultrasound GF1",
4485 { .init_isa = GUS_init }
4487 #endif
4489 #ifdef CONFIG_AC97
4491 "ac97",
4492 "Intel 82801AA AC97 Audio",
4495 { .init_pci = ac97_init }
4497 #endif
4499 #ifdef CONFIG_ES1370
4501 "es1370",
4502 "ENSONIQ AudioPCI ES1370",
4505 { .init_pci = es1370_init }
4507 #endif
4509 #endif /* HAS_AUDIO_CHOICE */
4511 { NULL, NULL, 0, 0, { NULL } }
4514 static void select_soundhw (const char *optarg)
4516 struct soundhw *c;
4518 if (*optarg == '?') {
4519 show_valid_cards:
4521 printf ("Valid sound card names (comma separated):\n");
4522 for (c = soundhw; c->name; ++c) {
4523 printf ("%-11s %s\n", c->name, c->descr);
4525 printf ("\n-soundhw all will enable all of the above\n");
4526 exit (*optarg != '?');
4528 else {
4529 size_t l;
4530 const char *p;
4531 char *e;
4532 int bad_card = 0;
4534 if (!strcmp (optarg, "all")) {
4535 for (c = soundhw; c->name; ++c) {
4536 c->enabled = 1;
4538 return;
4541 p = optarg;
4542 while (*p) {
4543 e = strchr (p, ',');
4544 l = !e ? strlen (p) : (size_t) (e - p);
4546 for (c = soundhw; c->name; ++c) {
4547 if (!strncmp (c->name, p, l)) {
4548 c->enabled = 1;
4549 break;
4553 if (!c->name) {
4554 if (l > 80) {
4555 fprintf (stderr,
4556 "Unknown sound card name (too big to show)\n");
4558 else {
4559 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4560 (int) l, p);
4562 bad_card = 1;
4564 p += l + (e != NULL);
4567 if (bad_card)
4568 goto show_valid_cards;
4571 #endif
4573 static void select_vgahw (const char *p)
4575 const char *opts;
4577 if (strstart(p, "std", &opts)) {
4578 cirrus_vga_enabled = 0;
4579 vmsvga_enabled = 0;
4580 } else if (strstart(p, "cirrus", &opts)) {
4581 cirrus_vga_enabled = 1;
4582 vmsvga_enabled = 0;
4583 } else if (strstart(p, "vmware", &opts)) {
4584 cirrus_vga_enabled = 0;
4585 vmsvga_enabled = 1;
4586 } else {
4587 invalid_vga:
4588 fprintf(stderr, "Unknown vga type: %s\n", p);
4589 exit(1);
4591 while (*opts) {
4592 const char *nextopt;
4594 if (strstart(opts, ",retrace=", &nextopt)) {
4595 opts = nextopt;
4596 if (strstart(opts, "dumb", &nextopt))
4597 vga_retrace_method = VGA_RETRACE_DUMB;
4598 else if (strstart(opts, "precise", &nextopt))
4599 vga_retrace_method = VGA_RETRACE_PRECISE;
4600 else goto invalid_vga;
4601 } else goto invalid_vga;
4602 opts = nextopt;
4606 #ifdef _WIN32
4607 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4609 exit(STATUS_CONTROL_C_EXIT);
4610 return TRUE;
4612 #endif
4614 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4616 int ret;
4618 if(strlen(str) != 36)
4619 return -1;
4621 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4622 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4623 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4625 if(ret != 16)
4626 return -1;
4628 return 0;
4631 #define MAX_NET_CLIENTS 32
4633 static int saved_argc;
4634 static char **saved_argv;
4636 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4638 *argc = saved_argc;
4639 *argv = saved_argv;
4640 *opt_daemonize = daemonize;
4641 *opt_incoming = incoming;
4645 static int gethugepagesize(void)
4647 int ret, fd;
4648 char buf[4096];
4649 const char *needle = "Hugepagesize:";
4650 char *size;
4651 unsigned long hugepagesize;
4653 fd = open("/proc/meminfo", O_RDONLY);
4654 if (fd < 0) {
4655 perror("open");
4656 exit(0);
4659 ret = read(fd, buf, sizeof(buf));
4660 if (ret < 0) {
4661 perror("read");
4662 exit(0);
4665 size = strstr(buf, needle);
4666 if (!size)
4667 return 0;
4668 size += strlen(needle);
4669 hugepagesize = strtol(size, NULL, 0);
4670 return hugepagesize;
4673 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4675 char *filename;
4676 void *area;
4677 int fd;
4679 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4680 return NULL;
4682 hpagesize = gethugepagesize() * 1024;
4683 if (!hpagesize)
4684 return NULL;
4686 fd = mkstemp(filename);
4687 if (fd < 0) {
4688 perror("mkstemp");
4689 free(filename);
4690 return NULL;
4692 unlink(filename);
4693 free(filename);
4695 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4698 * ftruncate is not supported by hugetlbfs in older
4699 * hosts, so don't bother checking for errors.
4700 * If anything goes wrong with it under other filesystems,
4701 * mmap will fail.
4703 ftruncate(fd, memory);
4705 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4706 if (area == MAP_FAILED) {
4707 perror("mmap");
4708 close(fd);
4709 return NULL;
4712 *len = memory;
4713 return area;
4716 static void *qemu_alloc_physram(unsigned long memory)
4718 void *area = NULL;
4719 unsigned long map_len = memory;
4721 #ifdef USE_KVM
4722 if (mem_path)
4723 area = alloc_mem_area(memory, &map_len, mem_path);
4724 #endif
4725 if (!area)
4726 area = qemu_vmalloc(memory);
4727 #ifdef USE_KVM
4728 if (kvm_setup_guest_memory(area, map_len))
4729 area = NULL;
4730 #endif
4731 return area;
4734 #ifndef _WIN32
4736 static void termsig_handler(int signal)
4738 qemu_system_shutdown_request();
4741 static void termsig_setup(void)
4743 struct sigaction act;
4745 memset(&act, 0, sizeof(act));
4746 act.sa_handler = termsig_handler;
4747 sigaction(SIGINT, &act, NULL);
4748 sigaction(SIGHUP, &act, NULL);
4749 sigaction(SIGTERM, &act, NULL);
4752 #endif
4754 int main(int argc, char **argv, char **envp)
4756 #ifdef CONFIG_GDBSTUB
4757 int use_gdbstub;
4758 const char *gdbstub_port;
4759 #endif
4760 uint32_t boot_devices_bitmap = 0;
4761 int i;
4762 int snapshot, linux_boot, net_boot;
4763 const char *initrd_filename;
4764 const char *kernel_filename, *kernel_cmdline;
4765 const char *boot_devices = "";
4766 DisplayState *ds = &display_state;
4767 int cyls, heads, secs, translation;
4768 const char *net_clients[MAX_NET_CLIENTS];
4769 int nb_net_clients;
4770 const char *bt_opts[MAX_BT_CMDLINE];
4771 int nb_bt_opts;
4772 int hda_index;
4773 int optind;
4774 const char *r, *optarg;
4775 CharDriverState *monitor_hd;
4776 const char *monitor_device;
4777 const char *serial_devices[MAX_SERIAL_PORTS];
4778 int serial_device_index;
4779 const char *parallel_devices[MAX_PARALLEL_PORTS];
4780 int parallel_device_index;
4781 const char *loadvm = NULL;
4782 QEMUMachine *machine;
4783 const char *cpu_model;
4784 const char *usb_devices[MAX_USB_CMDLINE];
4785 int usb_devices_index;
4786 int fds[2];
4787 int tb_size;
4788 const char *pid_file = NULL;
4789 int autostart;
4790 const char *incoming = NULL;
4792 qemu_cache_utils_init(envp);
4794 LIST_INIT (&vm_change_state_head);
4795 #ifndef _WIN32
4797 struct sigaction act;
4798 sigfillset(&act.sa_mask);
4799 act.sa_flags = 0;
4800 act.sa_handler = SIG_IGN;
4801 sigaction(SIGPIPE, &act, NULL);
4803 #else
4804 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4805 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4806 QEMU to run on a single CPU */
4808 HANDLE h;
4809 DWORD mask, smask;
4810 int i;
4811 h = GetCurrentProcess();
4812 if (GetProcessAffinityMask(h, &mask, &smask)) {
4813 for(i = 0; i < 32; i++) {
4814 if (mask & (1 << i))
4815 break;
4817 if (i != 32) {
4818 mask = 1 << i;
4819 SetProcessAffinityMask(h, mask);
4823 #endif
4825 register_machines();
4826 machine = first_machine;
4827 cpu_model = NULL;
4828 initrd_filename = NULL;
4829 ram_size = 0;
4830 vga_ram_size = VGA_RAM_SIZE;
4831 #ifdef CONFIG_GDBSTUB
4832 use_gdbstub = 0;
4833 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4834 #endif
4835 snapshot = 0;
4836 nographic = 0;
4837 curses = 0;
4838 kernel_filename = NULL;
4839 kernel_cmdline = "";
4840 cyls = heads = secs = 0;
4841 translation = BIOS_ATA_TRANSLATION_AUTO;
4842 monitor_device = "vc";
4844 serial_devices[0] = "vc:80Cx24C";
4845 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4846 serial_devices[i] = NULL;
4847 serial_device_index = 0;
4849 parallel_devices[0] = "vc:640x480";
4850 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4851 parallel_devices[i] = NULL;
4852 parallel_device_index = 0;
4854 usb_devices_index = 0;
4855 assigned_devices_index = 0;
4857 nb_net_clients = 0;
4858 nb_bt_opts = 0;
4859 nb_drives = 0;
4860 nb_drives_opt = 0;
4861 hda_index = -1;
4863 nb_nics = 0;
4865 tb_size = 0;
4866 autostart= 1;
4868 optind = 1;
4869 for(;;) {
4870 if (optind >= argc)
4871 break;
4872 r = argv[optind];
4873 if (r[0] != '-') {
4874 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4875 } else {
4876 const QEMUOption *popt;
4878 optind++;
4879 /* Treat --foo the same as -foo. */
4880 if (r[1] == '-')
4881 r++;
4882 popt = qemu_options;
4883 for(;;) {
4884 if (!popt->name) {
4885 fprintf(stderr, "%s: invalid option -- '%s'\n",
4886 argv[0], r);
4887 exit(1);
4889 if (!strcmp(popt->name, r + 1))
4890 break;
4891 popt++;
4893 if (popt->flags & HAS_ARG) {
4894 if (optind >= argc) {
4895 fprintf(stderr, "%s: option '%s' requires an argument\n",
4896 argv[0], r);
4897 exit(1);
4899 optarg = argv[optind++];
4900 } else {
4901 optarg = NULL;
4904 switch(popt->index) {
4905 case QEMU_OPTION_M:
4906 machine = find_machine(optarg);
4907 if (!machine) {
4908 QEMUMachine *m;
4909 printf("Supported machines are:\n");
4910 for(m = first_machine; m != NULL; m = m->next) {
4911 printf("%-10s %s%s\n",
4912 m->name, m->desc,
4913 m == first_machine ? " (default)" : "");
4915 exit(*optarg != '?');
4917 break;
4918 case QEMU_OPTION_cpu:
4919 /* hw initialization will check this */
4920 if (*optarg == '?') {
4921 /* XXX: implement xxx_cpu_list for targets that still miss it */
4922 #if defined(cpu_list)
4923 cpu_list(stdout, &fprintf);
4924 #endif
4925 exit(0);
4926 } else {
4927 cpu_model = optarg;
4929 break;
4930 case QEMU_OPTION_initrd:
4931 initrd_filename = optarg;
4932 break;
4933 case QEMU_OPTION_hda:
4934 if (cyls == 0)
4935 hda_index = drive_add(optarg, HD_ALIAS, 0);
4936 else
4937 hda_index = drive_add(optarg, HD_ALIAS
4938 ",cyls=%d,heads=%d,secs=%d%s",
4939 0, cyls, heads, secs,
4940 translation == BIOS_ATA_TRANSLATION_LBA ?
4941 ",trans=lba" :
4942 translation == BIOS_ATA_TRANSLATION_NONE ?
4943 ",trans=none" : "");
4944 break;
4945 case QEMU_OPTION_hdb:
4946 case QEMU_OPTION_hdc:
4947 case QEMU_OPTION_hdd:
4948 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4949 break;
4950 case QEMU_OPTION_drive:
4951 drive_add(NULL, "%s", optarg);
4952 break;
4953 case QEMU_OPTION_mtdblock:
4954 drive_add(optarg, MTD_ALIAS);
4955 break;
4956 case QEMU_OPTION_sd:
4957 drive_add(optarg, SD_ALIAS);
4958 break;
4959 case QEMU_OPTION_pflash:
4960 drive_add(optarg, PFLASH_ALIAS);
4961 break;
4962 case QEMU_OPTION_snapshot:
4963 snapshot = 1;
4964 break;
4965 case QEMU_OPTION_hdachs:
4967 const char *p;
4968 p = optarg;
4969 cyls = strtol(p, (char **)&p, 0);
4970 if (cyls < 1 || cyls > 16383)
4971 goto chs_fail;
4972 if (*p != ',')
4973 goto chs_fail;
4974 p++;
4975 heads = strtol(p, (char **)&p, 0);
4976 if (heads < 1 || heads > 16)
4977 goto chs_fail;
4978 if (*p != ',')
4979 goto chs_fail;
4980 p++;
4981 secs = strtol(p, (char **)&p, 0);
4982 if (secs < 1 || secs > 63)
4983 goto chs_fail;
4984 if (*p == ',') {
4985 p++;
4986 if (!strcmp(p, "none"))
4987 translation = BIOS_ATA_TRANSLATION_NONE;
4988 else if (!strcmp(p, "lba"))
4989 translation = BIOS_ATA_TRANSLATION_LBA;
4990 else if (!strcmp(p, "auto"))
4991 translation = BIOS_ATA_TRANSLATION_AUTO;
4992 else
4993 goto chs_fail;
4994 } else if (*p != '\0') {
4995 chs_fail:
4996 fprintf(stderr, "qemu: invalid physical CHS format\n");
4997 exit(1);
4999 if (hda_index != -1)
5000 snprintf(drives_opt[hda_index].opt,
5001 sizeof(drives_opt[hda_index].opt),
5002 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5003 0, cyls, heads, secs,
5004 translation == BIOS_ATA_TRANSLATION_LBA ?
5005 ",trans=lba" :
5006 translation == BIOS_ATA_TRANSLATION_NONE ?
5007 ",trans=none" : "");
5009 break;
5010 case QEMU_OPTION_nographic:
5011 nographic = 1;
5012 break;
5013 #ifdef CONFIG_CURSES
5014 case QEMU_OPTION_curses:
5015 curses = 1;
5016 break;
5017 #endif
5018 case QEMU_OPTION_portrait:
5019 graphic_rotate = 1;
5020 break;
5021 case QEMU_OPTION_kernel:
5022 kernel_filename = optarg;
5023 break;
5024 case QEMU_OPTION_append:
5025 kernel_cmdline = optarg;
5026 break;
5027 case QEMU_OPTION_cdrom:
5028 drive_add(optarg, CDROM_ALIAS);
5029 break;
5030 case QEMU_OPTION_boot:
5031 boot_devices = optarg;
5032 /* We just do some generic consistency checks */
5034 /* Could easily be extended to 64 devices if needed */
5035 const char *p;
5037 boot_devices_bitmap = 0;
5038 for (p = boot_devices; *p != '\0'; p++) {
5039 /* Allowed boot devices are:
5040 * a b : floppy disk drives
5041 * c ... f : IDE disk drives
5042 * g ... m : machine implementation dependant drives
5043 * n ... p : network devices
5044 * It's up to each machine implementation to check
5045 * if the given boot devices match the actual hardware
5046 * implementation and firmware features.
5048 if (*p < 'a' || *p > 'q') {
5049 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5050 exit(1);
5052 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5053 fprintf(stderr,
5054 "Boot device '%c' was given twice\n",*p);
5055 exit(1);
5057 boot_devices_bitmap |= 1 << (*p - 'a');
5060 break;
5061 case QEMU_OPTION_fda:
5062 case QEMU_OPTION_fdb:
5063 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5064 break;
5065 #ifdef TARGET_I386
5066 case QEMU_OPTION_no_fd_bootchk:
5067 fd_bootchk = 0;
5068 break;
5069 #endif
5070 case QEMU_OPTION_net:
5071 if (nb_net_clients >= MAX_NET_CLIENTS) {
5072 fprintf(stderr, "qemu: too many network clients\n");
5073 exit(1);
5075 net_clients[nb_net_clients] = optarg;
5076 nb_net_clients++;
5077 break;
5078 #ifdef CONFIG_SLIRP
5079 case QEMU_OPTION_tftp:
5080 tftp_prefix = optarg;
5081 break;
5082 case QEMU_OPTION_bootp:
5083 bootp_filename = optarg;
5084 break;
5085 #ifndef _WIN32
5086 case QEMU_OPTION_smb:
5087 net_slirp_smb(optarg);
5088 break;
5089 #endif
5090 case QEMU_OPTION_redir:
5091 net_slirp_redir(optarg);
5092 break;
5093 #endif
5094 case QEMU_OPTION_bt:
5095 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5096 fprintf(stderr, "qemu: too many bluetooth options\n");
5097 exit(1);
5099 bt_opts[nb_bt_opts++] = optarg;
5100 break;
5101 #ifdef HAS_AUDIO
5102 case QEMU_OPTION_audio_help:
5103 AUD_help ();
5104 exit (0);
5105 break;
5106 case QEMU_OPTION_soundhw:
5107 select_soundhw (optarg);
5108 break;
5109 #endif
5110 case QEMU_OPTION_h:
5111 help(0);
5112 break;
5113 case QEMU_OPTION_m: {
5114 uint64_t value;
5115 char *ptr;
5117 value = strtoul(optarg, &ptr, 10);
5118 switch (*ptr) {
5119 case 0: case 'M': case 'm':
5120 value <<= 20;
5121 break;
5122 case 'G': case 'g':
5123 value <<= 30;
5124 break;
5125 default:
5126 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5127 exit(1);
5130 /* On 32-bit hosts, QEMU is limited by virtual address space */
5131 if (value > (2047 << 20)
5132 #ifndef USE_KQEMU
5133 && HOST_LONG_BITS == 32
5134 #endif
5136 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5137 exit(1);
5139 if (value != (uint64_t)(ram_addr_t)value) {
5140 fprintf(stderr, "qemu: ram size too large\n");
5141 exit(1);
5143 ram_size = value;
5144 break;
5146 case QEMU_OPTION_d:
5148 int mask;
5149 const CPULogItem *item;
5151 mask = cpu_str_to_log_mask(optarg);
5152 if (!mask) {
5153 printf("Log items (comma separated):\n");
5154 for(item = cpu_log_items; item->mask != 0; item++) {
5155 printf("%-10s %s\n", item->name, item->help);
5157 exit(1);
5159 cpu_set_log(mask);
5161 break;
5162 #ifdef CONFIG_GDBSTUB
5163 case QEMU_OPTION_s:
5164 use_gdbstub = 1;
5165 break;
5166 case QEMU_OPTION_p:
5167 gdbstub_port = optarg;
5168 break;
5169 #endif
5170 case QEMU_OPTION_L:
5171 bios_dir = optarg;
5172 break;
5173 case QEMU_OPTION_bios:
5174 bios_name = optarg;
5175 break;
5176 case QEMU_OPTION_S:
5177 autostart = 0;
5178 break;
5179 case QEMU_OPTION_k:
5180 keyboard_layout = optarg;
5181 break;
5182 case QEMU_OPTION_localtime:
5183 rtc_utc = 0;
5184 break;
5185 case QEMU_OPTION_vga:
5186 select_vgahw (optarg);
5187 break;
5188 case QEMU_OPTION_g:
5190 const char *p;
5191 int w, h, depth;
5192 p = optarg;
5193 w = strtol(p, (char **)&p, 10);
5194 if (w <= 0) {
5195 graphic_error:
5196 fprintf(stderr, "qemu: invalid resolution or depth\n");
5197 exit(1);
5199 if (*p != 'x')
5200 goto graphic_error;
5201 p++;
5202 h = strtol(p, (char **)&p, 10);
5203 if (h <= 0)
5204 goto graphic_error;
5205 if (*p == 'x') {
5206 p++;
5207 depth = strtol(p, (char **)&p, 10);
5208 if (depth != 8 && depth != 15 && depth != 16 &&
5209 depth != 24 && depth != 32)
5210 goto graphic_error;
5211 } else if (*p == '\0') {
5212 depth = graphic_depth;
5213 } else {
5214 goto graphic_error;
5217 graphic_width = w;
5218 graphic_height = h;
5219 graphic_depth = depth;
5221 break;
5222 case QEMU_OPTION_echr:
5224 char *r;
5225 term_escape_char = strtol(optarg, &r, 0);
5226 if (r == optarg)
5227 printf("Bad argument to echr\n");
5228 break;
5230 case QEMU_OPTION_monitor:
5231 monitor_device = optarg;
5232 break;
5233 case QEMU_OPTION_serial:
5234 if (serial_device_index >= MAX_SERIAL_PORTS) {
5235 fprintf(stderr, "qemu: too many serial ports\n");
5236 exit(1);
5238 serial_devices[serial_device_index] = optarg;
5239 serial_device_index++;
5240 break;
5241 case QEMU_OPTION_parallel:
5242 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5243 fprintf(stderr, "qemu: too many parallel ports\n");
5244 exit(1);
5246 parallel_devices[parallel_device_index] = optarg;
5247 parallel_device_index++;
5248 break;
5249 case QEMU_OPTION_loadvm:
5250 loadvm = optarg;
5251 break;
5252 case QEMU_OPTION_full_screen:
5253 full_screen = 1;
5254 break;
5255 #ifdef CONFIG_SDL
5256 case QEMU_OPTION_no_frame:
5257 no_frame = 1;
5258 break;
5259 case QEMU_OPTION_alt_grab:
5260 alt_grab = 1;
5261 break;
5262 case QEMU_OPTION_no_quit:
5263 no_quit = 1;
5264 break;
5265 #endif
5266 case QEMU_OPTION_pidfile:
5267 pid_file = optarg;
5268 break;
5269 #ifdef TARGET_I386
5270 case QEMU_OPTION_win2k_hack:
5271 win2k_install_hack = 1;
5272 break;
5273 #endif
5274 #ifdef USE_KQEMU
5275 case QEMU_OPTION_no_kqemu:
5276 kqemu_allowed = 0;
5277 break;
5278 case QEMU_OPTION_kernel_kqemu:
5279 kqemu_allowed = 2;
5280 break;
5281 #endif
5282 #ifdef CONFIG_KVM
5283 case QEMU_OPTION_enable_kvm:
5284 kvm_allowed = 1;
5285 #ifdef USE_KQEMU
5286 kqemu_allowed = 0;
5287 #endif
5288 break;
5289 #endif
5290 #ifdef USE_KVM
5291 case QEMU_OPTION_no_kvm:
5292 kvm_allowed = 0;
5293 break;
5294 case QEMU_OPTION_no_kvm_irqchip: {
5295 kvm_irqchip = 0;
5296 kvm_pit = 0;
5297 break;
5299 case QEMU_OPTION_no_kvm_pit: {
5300 kvm_pit = 0;
5301 break;
5303 case QEMU_OPTION_no_kvm_pit_reinjection: {
5304 kvm_pit_reinject = 0;
5305 break;
5307 case QEMU_OPTION_enable_nesting: {
5308 kvm_nested = 1;
5309 break;
5311 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5312 case QEMU_OPTION_pcidevice:
5313 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5314 fprintf(stderr, "Too many assigned devices\n");
5315 exit(1);
5317 assigned_devices[assigned_devices_index] = optarg;
5318 assigned_devices_index++;
5319 break;
5320 #endif
5321 #endif
5322 case QEMU_OPTION_usb:
5323 usb_enabled = 1;
5324 break;
5325 case QEMU_OPTION_usbdevice:
5326 usb_enabled = 1;
5327 if (usb_devices_index >= MAX_USB_CMDLINE) {
5328 fprintf(stderr, "Too many USB devices\n");
5329 exit(1);
5331 usb_devices[usb_devices_index] = optarg;
5332 usb_devices_index++;
5333 break;
5334 case QEMU_OPTION_smp:
5335 smp_cpus = atoi(optarg);
5336 if (smp_cpus < 1) {
5337 fprintf(stderr, "Invalid number of CPUs\n");
5338 exit(1);
5340 break;
5341 case QEMU_OPTION_vnc:
5342 vnc_display = optarg;
5343 break;
5344 case QEMU_OPTION_no_acpi:
5345 acpi_enabled = 0;
5346 break;
5347 case QEMU_OPTION_no_hpet:
5348 no_hpet = 1;
5349 break;
5350 case QEMU_OPTION_no_reboot:
5351 no_reboot = 1;
5352 break;
5353 case QEMU_OPTION_no_shutdown:
5354 no_shutdown = 1;
5355 break;
5356 case QEMU_OPTION_show_cursor:
5357 cursor_hide = 0;
5358 break;
5359 case QEMU_OPTION_uuid:
5360 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5361 fprintf(stderr, "Fail to parse UUID string."
5362 " Wrong format.\n");
5363 exit(1);
5365 break;
5366 case QEMU_OPTION_daemonize:
5367 daemonize = 1;
5368 break;
5369 case QEMU_OPTION_option_rom:
5370 if (nb_option_roms >= MAX_OPTION_ROMS) {
5371 fprintf(stderr, "Too many option ROMs\n");
5372 exit(1);
5374 option_rom[nb_option_roms] = optarg;
5375 nb_option_roms++;
5376 break;
5377 case QEMU_OPTION_semihosting:
5378 semihosting_enabled = 1;
5379 break;
5380 case QEMU_OPTION_tdf:
5381 time_drift_fix = 1;
5382 break;
5383 case QEMU_OPTION_kvm_shadow_memory:
5384 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5385 break;
5386 case QEMU_OPTION_mempath:
5387 mem_path = optarg;
5388 break;
5389 case QEMU_OPTION_name:
5390 qemu_name = optarg;
5391 break;
5392 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5393 case QEMU_OPTION_prom_env:
5394 if (nb_prom_envs >= MAX_PROM_ENVS) {
5395 fprintf(stderr, "Too many prom variables\n");
5396 exit(1);
5398 prom_envs[nb_prom_envs] = optarg;
5399 nb_prom_envs++;
5400 break;
5401 #endif
5402 case QEMU_OPTION_cpu_vendor:
5403 cpu_vendor_string = optarg;
5404 break;
5405 #ifdef TARGET_ARM
5406 case QEMU_OPTION_old_param:
5407 old_param = 1;
5408 break;
5409 #endif
5410 case QEMU_OPTION_clock:
5411 configure_alarms(optarg);
5412 break;
5413 case QEMU_OPTION_startdate:
5415 struct tm tm;
5416 time_t rtc_start_date;
5417 if (!strcmp(optarg, "now")) {
5418 rtc_date_offset = -1;
5419 } else {
5420 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5421 &tm.tm_year,
5422 &tm.tm_mon,
5423 &tm.tm_mday,
5424 &tm.tm_hour,
5425 &tm.tm_min,
5426 &tm.tm_sec) == 6) {
5427 /* OK */
5428 } else if (sscanf(optarg, "%d-%d-%d",
5429 &tm.tm_year,
5430 &tm.tm_mon,
5431 &tm.tm_mday) == 3) {
5432 tm.tm_hour = 0;
5433 tm.tm_min = 0;
5434 tm.tm_sec = 0;
5435 } else {
5436 goto date_fail;
5438 tm.tm_year -= 1900;
5439 tm.tm_mon--;
5440 rtc_start_date = mktimegm(&tm);
5441 if (rtc_start_date == -1) {
5442 date_fail:
5443 fprintf(stderr, "Invalid date format. Valid format are:\n"
5444 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5445 exit(1);
5447 rtc_date_offset = time(NULL) - rtc_start_date;
5450 break;
5451 case QEMU_OPTION_tb_size:
5452 tb_size = strtol(optarg, NULL, 0);
5453 if (tb_size < 0)
5454 tb_size = 0;
5455 break;
5456 case QEMU_OPTION_icount:
5457 use_icount = 1;
5458 if (strcmp(optarg, "auto") == 0) {
5459 icount_time_shift = -1;
5460 } else {
5461 icount_time_shift = strtol(optarg, NULL, 0);
5463 break;
5464 case QEMU_OPTION_incoming:
5465 incoming = optarg;
5466 break;
5467 case QEMU_OPTION_nvram:
5468 nvram = optarg;
5469 break;
5474 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5475 if (kvm_allowed && kqemu_allowed) {
5476 fprintf(stderr,
5477 "You can not enable both KVM and kqemu at the same time\n");
5478 exit(1);
5480 #endif
5482 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5483 if (smp_cpus > machine->max_cpus) {
5484 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5485 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5486 machine->max_cpus);
5487 exit(1);
5490 if (nographic) {
5491 if (serial_device_index == 0)
5492 serial_devices[0] = "stdio";
5493 if (parallel_device_index == 0)
5494 parallel_devices[0] = "null";
5495 if (strncmp(monitor_device, "vc", 2) == 0)
5496 monitor_device = "stdio";
5499 #ifndef _WIN32
5500 if (daemonize) {
5501 pid_t pid;
5503 if (pipe(fds) == -1)
5504 exit(1);
5506 pid = fork();
5507 if (pid > 0) {
5508 uint8_t status;
5509 ssize_t len;
5511 close(fds[1]);
5513 again:
5514 len = read(fds[0], &status, 1);
5515 if (len == -1 && (errno == EINTR))
5516 goto again;
5518 if (len != 1)
5519 exit(1);
5520 else if (status == 1) {
5521 fprintf(stderr, "Could not acquire pidfile\n");
5522 exit(1);
5523 } else
5524 exit(0);
5525 } else if (pid < 0)
5526 exit(1);
5528 setsid();
5530 pid = fork();
5531 if (pid > 0)
5532 exit(0);
5533 else if (pid < 0)
5534 exit(1);
5536 umask(027);
5538 signal(SIGTSTP, SIG_IGN);
5539 signal(SIGTTOU, SIG_IGN);
5540 signal(SIGTTIN, SIG_IGN);
5542 #endif
5544 #if USE_KVM
5545 if (kvm_enabled()) {
5546 if (kvm_qemu_init() < 0) {
5547 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5548 #ifdef NO_CPU_EMULATION
5549 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5550 exit(1);
5551 #endif
5552 kvm_allowed = 0;
5555 #endif
5557 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5558 if (daemonize) {
5559 uint8_t status = 1;
5560 write(fds[1], &status, 1);
5561 } else
5562 fprintf(stderr, "Could not acquire pid file\n");
5563 exit(1);
5566 #ifdef USE_KQEMU
5567 if (smp_cpus > 1)
5568 kqemu_allowed = 0;
5569 #endif
5570 linux_boot = (kernel_filename != NULL);
5571 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5573 if (!linux_boot && net_boot == 0 &&
5574 !machine->nodisk_ok && nb_drives_opt == 0)
5575 help(1);
5577 if (!linux_boot && *kernel_cmdline != '\0') {
5578 fprintf(stderr, "-append only allowed with -kernel option\n");
5579 exit(1);
5582 if (!linux_boot && initrd_filename != NULL) {
5583 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5584 exit(1);
5587 /* boot to floppy or the default cd if no hard disk defined yet */
5588 if (!boot_devices[0]) {
5589 boot_devices = "cad";
5591 setvbuf(stdout, NULL, _IOLBF, 0);
5593 init_timers();
5594 if (init_timer_alarm() < 0) {
5595 fprintf(stderr, "could not initialize alarm timer\n");
5596 exit(1);
5598 if (use_icount && icount_time_shift < 0) {
5599 use_icount = 2;
5600 /* 125MIPS seems a reasonable initial guess at the guest speed.
5601 It will be corrected fairly quickly anyway. */
5602 icount_time_shift = 3;
5603 init_icount_adjust();
5606 #ifdef _WIN32
5607 socket_init();
5608 #endif
5610 /* init network clients */
5611 if (nb_net_clients == 0) {
5612 /* if no clients, we use a default config */
5613 net_clients[nb_net_clients++] = "nic";
5614 #ifdef CONFIG_SLIRP
5615 net_clients[nb_net_clients++] = "user";
5616 #endif
5619 for(i = 0;i < nb_net_clients; i++) {
5620 if (net_client_parse(net_clients[i]) < 0)
5621 exit(1);
5623 net_client_check();
5625 #ifdef TARGET_I386
5626 /* XXX: this should be moved in the PC machine instantiation code */
5627 if (net_boot != 0) {
5628 int netroms = 0;
5629 for (i = 0; i < nb_nics && i < 4; i++) {
5630 const char *model = nd_table[i].model;
5631 char buf[1024];
5632 if (net_boot & (1 << i)) {
5633 if (model == NULL)
5634 model = "rtl8139";
5635 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5636 if (get_image_size(buf) > 0) {
5637 if (nb_option_roms >= MAX_OPTION_ROMS) {
5638 fprintf(stderr, "Too many option ROMs\n");
5639 exit(1);
5641 option_rom[nb_option_roms] = strdup(buf);
5642 nb_option_roms++;
5643 netroms++;
5647 if (netroms == 0) {
5648 fprintf(stderr, "No valid PXE rom found for network device\n");
5649 exit(1);
5652 #endif
5654 /* init the bluetooth world */
5655 for (i = 0; i < nb_bt_opts; i++)
5656 if (bt_parse(bt_opts[i]))
5657 exit(1);
5659 /* init the memory */
5660 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5662 if (machine->ram_require & RAMSIZE_FIXED) {
5663 if (ram_size > 0) {
5664 if (ram_size < phys_ram_size) {
5665 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5666 machine->name, (unsigned long long) phys_ram_size);
5667 exit(-1);
5670 phys_ram_size = ram_size;
5671 } else
5672 ram_size = phys_ram_size;
5673 } else {
5674 if (ram_size == 0)
5675 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5677 phys_ram_size += ram_size;
5680 /* Initialize kvm */
5681 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5682 #define KVM_EXTRA_PAGES 3
5683 #else
5684 #define KVM_EXTRA_PAGES 0
5685 #endif
5686 if (kvm_enabled()) {
5687 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5688 if (kvm_qemu_create_context() < 0) {
5689 fprintf(stderr, "Could not create KVM context\n");
5690 exit(1);
5694 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5695 if (!phys_ram_base) {
5696 fprintf(stderr, "Could not allocate physical memory\n");
5697 exit(1);
5700 /* init the dynamic translator */
5701 cpu_exec_init_all(tb_size * 1024 * 1024);
5703 bdrv_init();
5705 /* we always create the cdrom drive, even if no disk is there */
5707 if (nb_drives_opt < MAX_DRIVES)
5708 drive_add(NULL, CDROM_ALIAS);
5710 /* we always create at least one floppy */
5712 if (nb_drives_opt < MAX_DRIVES)
5713 drive_add(NULL, FD_ALIAS, 0);
5715 /* we always create one sd slot, even if no card is in it */
5717 if (nb_drives_opt < MAX_DRIVES)
5718 drive_add(NULL, SD_ALIAS);
5720 /* open the virtual block devices
5721 * note that migration with device
5722 * hot add/remove is broken.
5724 for(i = 0; i < nb_drives_opt; i++)
5725 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5726 exit(1);
5728 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5729 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5731 /* terminal init */
5732 memset(&display_state, 0, sizeof(display_state));
5733 if (nographic) {
5734 if (curses) {
5735 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5736 exit(1);
5738 /* nearly nothing to do */
5739 dumb_display_init(ds);
5740 } else if (vnc_display != NULL) {
5741 vnc_display_init(ds);
5742 if (vnc_display_open(ds, vnc_display) < 0)
5743 exit(1);
5744 } else
5745 #if defined(CONFIG_CURSES)
5746 if (curses) {
5747 curses_display_init(ds, full_screen);
5748 } else
5749 #endif
5751 #if defined(CONFIG_SDL)
5752 sdl_display_init(ds, full_screen, no_frame);
5753 #elif defined(CONFIG_COCOA)
5754 cocoa_display_init(ds, full_screen);
5755 #else
5756 dumb_display_init(ds);
5757 #endif
5760 #ifndef _WIN32
5761 /* must be after terminal init, SDL library changes signal handlers */
5762 termsig_setup();
5763 #endif
5765 /* Maintain compatibility with multiple stdio monitors */
5766 if (!strcmp(monitor_device,"stdio")) {
5767 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5768 const char *devname = serial_devices[i];
5769 if (devname && !strcmp(devname,"mon:stdio")) {
5770 monitor_device = NULL;
5771 break;
5772 } else if (devname && !strcmp(devname,"stdio")) {
5773 monitor_device = NULL;
5774 serial_devices[i] = "mon:stdio";
5775 break;
5779 if (monitor_device) {
5780 monitor_hd = qemu_chr_open("monitor", monitor_device);
5781 if (!monitor_hd) {
5782 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5783 exit(1);
5785 monitor_init(monitor_hd, !nographic);
5788 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5789 const char *devname = serial_devices[i];
5790 if (devname && strcmp(devname, "none")) {
5791 char label[32];
5792 snprintf(label, sizeof(label), "serial%d", i);
5793 serial_hds[i] = qemu_chr_open(label, devname);
5794 if (!serial_hds[i]) {
5795 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5796 devname);
5797 exit(1);
5799 if (strstart(devname, "vc", 0))
5800 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5804 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5805 const char *devname = parallel_devices[i];
5806 if (devname && strcmp(devname, "none")) {
5807 char label[32];
5808 snprintf(label, sizeof(label), "parallel%d", i);
5809 parallel_hds[i] = qemu_chr_open(label, devname);
5810 if (!parallel_hds[i]) {
5811 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5812 devname);
5813 exit(1);
5815 if (strstart(devname, "vc", 0))
5816 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5820 if (kvm_enabled())
5821 kvm_init_ap();
5823 #ifdef KVM_UPSTREAM
5824 if (kvm_enabled()) {
5825 int ret;
5827 ret = kvm_init(smp_cpus);
5828 if (ret < 0) {
5829 fprintf(stderr, "failed to initialize KVM\n");
5830 exit(1);
5833 #endif
5835 machine->init(ram_size, vga_ram_size, boot_devices, ds,
5836 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5838 current_machine = machine;
5840 /* Set KVM's vcpu state to qemu's initial CPUState. */
5841 if (kvm_enabled()) {
5842 int ret;
5844 ret = kvm_sync_vcpus();
5845 if (ret < 0) {
5846 fprintf(stderr, "failed to initialize vcpus\n");
5847 exit(1);
5851 /* init USB devices */
5852 if (usb_enabled) {
5853 for(i = 0; i < usb_devices_index; i++) {
5854 if (usb_device_add(usb_devices[i]) < 0) {
5855 fprintf(stderr, "Warning: could not add USB device %s\n",
5856 usb_devices[i]);
5861 if (display_state.dpy_refresh) {
5862 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5863 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5866 #ifdef CONFIG_GDBSTUB
5867 if (use_gdbstub) {
5868 /* XXX: use standard host:port notation and modify options
5869 accordingly. */
5870 if (gdbserver_start(gdbstub_port) < 0) {
5871 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5872 gdbstub_port);
5873 exit(1);
5876 #endif
5878 if (loadvm)
5879 do_loadvm(loadvm);
5881 if (incoming) {
5882 autostart = 0; /* fixme how to deal with -daemonize */
5883 qemu_start_incoming_migration(incoming);
5887 /* XXX: simplify init */
5888 read_passwords();
5889 if (autostart) {
5890 vm_start();
5894 if (daemonize) {
5895 uint8_t status = 0;
5896 ssize_t len;
5897 int fd;
5899 again1:
5900 len = write(fds[1], &status, 1);
5901 if (len == -1 && (errno == EINTR))
5902 goto again1;
5904 if (len != 1)
5905 exit(1);
5907 chdir("/");
5908 TFR(fd = open("/dev/null", O_RDWR));
5909 if (fd == -1)
5910 exit(1);
5912 dup2(fd, 0);
5913 dup2(fd, 1);
5914 dup2(fd, 2);
5916 close(fd);
5919 main_loop();
5920 quit_timers();
5921 net_cleanup();
5923 return 0;