Fix kvm ppc vcpu initialization
[qemu-kvm/fedora.git] / vl.c
blob4721fddb9f43ab9d15c927dbd3ea089f4cd3f803
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 "block.h"
40 #include "audio/audio.h"
41 #include "hw/device-assignment.h"
42 #include "migration.h"
43 #include "kvm.h"
44 #include "balloon.h"
45 #include "qemu-kvm.h"
47 #include <unistd.h>
48 #include <fcntl.h>
49 #include <signal.h>
50 #include <time.h>
51 #include <errno.h>
52 #include <sys/time.h>
53 #include <zlib.h>
55 #ifndef _WIN32
56 #include <sys/times.h>
57 #include <sys/wait.h>
58 #include <termios.h>
59 #include <sys/mman.h>
60 #include <sys/ioctl.h>
61 #include <sys/resource.h>
62 #include <sys/socket.h>
63 #include <netinet/in.h>
64 #include <net/if.h>
65 #if defined(__NetBSD__)
66 #include <net/if_tap.h>
67 #endif
68 #ifdef __linux__
69 #include <linux/if_tun.h>
70 #endif
71 #include <arpa/inet.h>
72 #include <dirent.h>
73 #include <netdb.h>
74 #include <sys/select.h>
75 #ifdef _BSD
76 #include <sys/stat.h>
77 #ifdef __FreeBSD__
78 #include <libutil.h>
79 #else
80 #include <util.h>
81 #endif
82 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
83 #include <freebsd/stdlib.h>
84 #else
85 #ifdef __linux__
86 #include <pty.h>
87 #include <malloc.h>
88 #include <linux/rtc.h>
90 /* For the benefit of older linux systems which don't supply it,
91 we use a local copy of hpet.h. */
92 /* #include <linux/hpet.h> */
93 #include "hpet.h"
95 #include <linux/ppdev.h>
96 #include <linux/parport.h>
97 #endif
98 #ifdef __sun__
99 #include <sys/stat.h>
100 #include <sys/ethernet.h>
101 #include <sys/sockio.h>
102 #include <netinet/arp.h>
103 #include <netinet/in.h>
104 #include <netinet/in_systm.h>
105 #include <netinet/ip.h>
106 #include <netinet/ip_icmp.h> // must come after ip.h
107 #include <netinet/udp.h>
108 #include <netinet/tcp.h>
109 #include <net/if.h>
110 #include <syslog.h>
111 #include <stropts.h>
112 #endif
113 #endif
114 #endif
116 #include "qemu_socket.h"
118 #if defined(CONFIG_SLIRP)
119 #include "libslirp.h"
120 #endif
122 #if defined(__OpenBSD__)
123 #include <util.h>
124 #endif
126 #if defined(CONFIG_VDE)
127 #include <libvdeplug.h>
128 #endif
130 #ifdef _WIN32
131 #include <malloc.h>
132 #include <sys/timeb.h>
133 #include <mmsystem.h>
134 #define getopt_long_only getopt_long
135 #define memalign(align, size) malloc(size)
136 #endif
138 #ifdef CONFIG_SDL
139 #ifdef __APPLE__
140 #include <SDL/SDL.h>
141 #endif
142 #endif /* CONFIG_SDL */
144 #ifdef CONFIG_COCOA
145 #undef main
146 #define main qemu_main
147 #endif /* CONFIG_COCOA */
149 #include "disas.h"
151 #include "exec-all.h"
153 #include "qemu-kvm.h"
155 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
156 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
157 #ifdef __sun__
158 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
159 #else
160 #define SMBD_COMMAND "/usr/sbin/smbd"
161 #endif
163 //#define DEBUG_UNUSED_IOPORT
164 //#define DEBUG_IOPORT
165 //#define DEBUG_NET
166 //#define DEBUG_SLIRP
168 #ifdef TARGET_PPC
169 #define DEFAULT_RAM_SIZE 144
170 #else
171 #define DEFAULT_RAM_SIZE 128
172 #endif
174 /* Max number of USB devices that can be specified on the commandline. */
175 #define MAX_USB_CMDLINE 8
177 /* Max number of bluetooth switches on the commandline. */
178 #define MAX_BT_CMDLINE 10
180 /* XXX: use a two level table to limit memory usage */
181 #define MAX_IOPORTS 65536
183 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
184 const char *bios_name = NULL;
185 static void *ioport_opaque[MAX_IOPORTS];
186 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
187 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
188 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
189 to store the VM snapshots */
190 DriveInfo drives_table[MAX_DRIVES+1];
191 int nb_drives;
192 int extboot_drive = -1;
193 /* point to the block driver where the snapshots are managed */
194 static BlockDriverState *bs_snapshots;
195 static int vga_ram_size;
196 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
197 DisplayState display_state;
198 int nographic;
199 static int curses;
200 const char* keyboard_layout = NULL;
201 int64_t ticks_per_sec;
202 ram_addr_t ram_size;
203 int nb_nics;
204 NICInfo nd_table[MAX_NICS];
205 int vm_running;
206 static int rtc_utc = 1;
207 static int rtc_date_offset = -1; /* -1 means no change */
208 int cirrus_vga_enabled = 1;
209 int vmsvga_enabled = 0;
210 #ifdef TARGET_SPARC
211 int graphic_width = 1024;
212 int graphic_height = 768;
213 int graphic_depth = 8;
214 #else
215 int graphic_width = 800;
216 int graphic_height = 600;
217 int graphic_depth = 15;
218 #endif
219 static int full_screen = 0;
220 static int no_frame = 0;
221 int no_quit = 0;
222 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
223 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
224 #ifdef TARGET_I386
225 int win2k_install_hack = 0;
226 #endif
227 int usb_enabled = 0;
228 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
229 int assigned_devices_index;
230 int smp_cpus = 1;
231 const char *vnc_display;
232 int acpi_enabled = 1;
233 int fd_bootchk = 1;
234 int no_reboot = 0;
235 int no_shutdown = 0;
236 int cursor_hide = 1;
237 int graphic_rotate = 0;
238 int daemonize = 0;
239 const char *incoming;
240 const char *option_rom[MAX_OPTION_ROMS];
241 int nb_option_roms;
242 int semihosting_enabled = 0;
243 int time_drift_fix = 0;
244 unsigned int kvm_shadow_memory = 0;
245 const char *mem_path = NULL;
246 int hpagesize = 0;
247 const char *cpu_vendor_string;
248 #ifdef TARGET_ARM
249 int old_param = 0;
250 #endif
251 const char *qemu_name;
252 int alt_grab = 0;
253 #ifdef TARGET_SPARC
254 unsigned int nb_prom_envs = 0;
255 const char *prom_envs[MAX_PROM_ENVS];
256 #endif
257 int nb_drives_opt;
258 struct drive_opt drives_opt[MAX_DRIVES];
260 static CPUState *cur_cpu;
261 static CPUState *next_cpu;
262 static int event_pending = 1;
263 /* Conversion factor from emulated instructions to virtual clock ticks. */
264 static int icount_time_shift;
265 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
266 #define MAX_ICOUNT_SHIFT 10
267 /* Compensate for varying guest execution speed. */
268 static int64_t qemu_icount_bias;
269 static QEMUTimer *icount_rt_timer;
270 static QEMUTimer *icount_vm_timer;
272 uint8_t qemu_uuid[16];
274 /* KVM runs the main loop in a separate thread. If we update one of the lists
275 * that are polled before or after select(), we need to make sure to break out
276 * of the select() to ensure the new item is serviced.
278 static void main_loop_break(void)
280 if (kvm_enabled())
281 qemu_kvm_notify_work();
284 /***********************************************************/
285 /* x86 ISA bus support */
287 target_phys_addr_t isa_mem_base = 0;
288 PicState2 *isa_pic;
290 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
291 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
293 static uint32_t ioport_read(int index, uint32_t address)
295 static IOPortReadFunc *default_func[3] = {
296 default_ioport_readb,
297 default_ioport_readw,
298 default_ioport_readl
300 IOPortReadFunc *func = ioport_read_table[index][address];
301 if (!func)
302 func = default_func[index];
303 return func(ioport_opaque[address], address);
306 static void ioport_write(int index, uint32_t address, uint32_t data)
308 static IOPortWriteFunc *default_func[3] = {
309 default_ioport_writeb,
310 default_ioport_writew,
311 default_ioport_writel
313 IOPortWriteFunc *func = ioport_write_table[index][address];
314 if (!func)
315 func = default_func[index];
316 func(ioport_opaque[address], address, data);
319 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
321 #ifdef DEBUG_UNUSED_IOPORT
322 fprintf(stderr, "unused inb: port=0x%04x\n", address);
323 #endif
324 return 0xff;
327 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
329 #ifdef DEBUG_UNUSED_IOPORT
330 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
331 #endif
334 /* default is to make two byte accesses */
335 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
337 uint32_t data;
338 data = ioport_read(0, address);
339 address = (address + 1) & (MAX_IOPORTS - 1);
340 data |= ioport_read(0, address) << 8;
341 return data;
344 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
346 ioport_write(0, address, data & 0xff);
347 address = (address + 1) & (MAX_IOPORTS - 1);
348 ioport_write(0, address, (data >> 8) & 0xff);
351 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
353 #ifdef DEBUG_UNUSED_IOPORT
354 fprintf(stderr, "unused inl: port=0x%04x\n", address);
355 #endif
356 return 0xffffffff;
359 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
361 #ifdef DEBUG_UNUSED_IOPORT
362 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
363 #endif
366 /* size is the word size in byte */
367 int register_ioport_read(int start, int length, int size,
368 IOPortReadFunc *func, void *opaque)
370 int i, bsize;
372 if (size == 1) {
373 bsize = 0;
374 } else if (size == 2) {
375 bsize = 1;
376 } else if (size == 4) {
377 bsize = 2;
378 } else {
379 hw_error("register_ioport_read: invalid size");
380 return -1;
382 for(i = start; i < start + length; i += size) {
383 ioport_read_table[bsize][i] = func;
384 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
385 hw_error("register_ioport_read: invalid opaque");
386 ioport_opaque[i] = opaque;
388 return 0;
391 /* size is the word size in byte */
392 int register_ioport_write(int start, int length, int size,
393 IOPortWriteFunc *func, void *opaque)
395 int i, bsize;
397 if (size == 1) {
398 bsize = 0;
399 } else if (size == 2) {
400 bsize = 1;
401 } else if (size == 4) {
402 bsize = 2;
403 } else {
404 hw_error("register_ioport_write: invalid size");
405 return -1;
407 for(i = start; i < start + length; i += size) {
408 ioport_write_table[bsize][i] = func;
409 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
410 hw_error("register_ioport_write: invalid opaque");
411 ioport_opaque[i] = opaque;
413 return 0;
416 void isa_unassign_ioport(int start, int length)
418 int i;
420 for(i = start; i < start + length; i++) {
421 ioport_read_table[0][i] = default_ioport_readb;
422 ioport_read_table[1][i] = default_ioport_readw;
423 ioport_read_table[2][i] = default_ioport_readl;
425 ioport_write_table[0][i] = default_ioport_writeb;
426 ioport_write_table[1][i] = default_ioport_writew;
427 ioport_write_table[2][i] = default_ioport_writel;
429 ioport_opaque[i] = NULL;
433 /***********************************************************/
435 void cpu_outb(CPUState *env, int addr, int val)
437 #ifdef DEBUG_IOPORT
438 if (loglevel & CPU_LOG_IOPORT)
439 fprintf(logfile, "outb: %04x %02x\n", addr, val);
440 #endif
441 ioport_write(0, addr, val);
442 #ifdef USE_KQEMU
443 if (env)
444 env->last_io_time = cpu_get_time_fast();
445 #endif
448 void cpu_outw(CPUState *env, int addr, int val)
450 #ifdef DEBUG_IOPORT
451 if (loglevel & CPU_LOG_IOPORT)
452 fprintf(logfile, "outw: %04x %04x\n", addr, val);
453 #endif
454 ioport_write(1, addr, val);
455 #ifdef USE_KQEMU
456 if (env)
457 env->last_io_time = cpu_get_time_fast();
458 #endif
461 void cpu_outl(CPUState *env, int addr, int val)
463 #ifdef DEBUG_IOPORT
464 if (loglevel & CPU_LOG_IOPORT)
465 fprintf(logfile, "outl: %04x %08x\n", addr, val);
466 #endif
467 ioport_write(2, addr, val);
468 #ifdef USE_KQEMU
469 if (env)
470 env->last_io_time = cpu_get_time_fast();
471 #endif
474 int cpu_inb(CPUState *env, int addr)
476 int val;
477 val = ioport_read(0, addr);
478 #ifdef DEBUG_IOPORT
479 if (loglevel & CPU_LOG_IOPORT)
480 fprintf(logfile, "inb : %04x %02x\n", addr, val);
481 #endif
482 #ifdef USE_KQEMU
483 if (env)
484 env->last_io_time = cpu_get_time_fast();
485 #endif
486 return val;
489 int cpu_inw(CPUState *env, int addr)
491 int val;
492 val = ioport_read(1, addr);
493 #ifdef DEBUG_IOPORT
494 if (loglevel & CPU_LOG_IOPORT)
495 fprintf(logfile, "inw : %04x %04x\n", addr, val);
496 #endif
497 #ifdef USE_KQEMU
498 if (env)
499 env->last_io_time = cpu_get_time_fast();
500 #endif
501 return val;
504 int cpu_inl(CPUState *env, int addr)
506 int val;
507 val = ioport_read(2, addr);
508 #ifdef DEBUG_IOPORT
509 if (loglevel & CPU_LOG_IOPORT)
510 fprintf(logfile, "inl : %04x %08x\n", addr, val);
511 #endif
512 #ifdef USE_KQEMU
513 if (env)
514 env->last_io_time = cpu_get_time_fast();
515 #endif
516 return val;
519 /***********************************************************/
520 void hw_error(const char *fmt, ...)
522 va_list ap;
523 CPUState *env;
525 va_start(ap, fmt);
526 fprintf(stderr, "qemu: hardware error: ");
527 vfprintf(stderr, fmt, ap);
528 fprintf(stderr, "\n");
529 for(env = first_cpu; env != NULL; env = env->next_cpu) {
530 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
531 #ifdef TARGET_I386
532 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
533 #else
534 cpu_dump_state(env, stderr, fprintf, 0);
535 #endif
537 va_end(ap);
538 abort();
541 /***************/
542 /* ballooning */
544 static QEMUBalloonEvent *qemu_balloon_event;
545 void *qemu_balloon_event_opaque;
547 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
549 qemu_balloon_event = func;
550 qemu_balloon_event_opaque = opaque;
553 void qemu_balloon(ram_addr_t target)
555 if (qemu_balloon_event)
556 qemu_balloon_event(qemu_balloon_event_opaque, target);
559 ram_addr_t qemu_balloon_status(void)
561 if (qemu_balloon_event)
562 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
563 return 0;
566 /***********************************************************/
567 /* keyboard/mouse */
569 static QEMUPutKBDEvent *qemu_put_kbd_event;
570 static void *qemu_put_kbd_event_opaque;
571 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
572 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
574 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
576 qemu_put_kbd_event_opaque = opaque;
577 qemu_put_kbd_event = func;
580 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
581 void *opaque, int absolute,
582 const char *name)
584 QEMUPutMouseEntry *s, *cursor;
586 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
587 if (!s)
588 return NULL;
590 s->qemu_put_mouse_event = func;
591 s->qemu_put_mouse_event_opaque = opaque;
592 s->qemu_put_mouse_event_absolute = absolute;
593 s->qemu_put_mouse_event_name = qemu_strdup(name);
594 s->next = NULL;
596 if (!qemu_put_mouse_event_head) {
597 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
598 return s;
601 cursor = qemu_put_mouse_event_head;
602 while (cursor->next != NULL)
603 cursor = cursor->next;
605 cursor->next = s;
606 qemu_put_mouse_event_current = s;
608 return s;
611 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
613 QEMUPutMouseEntry *prev = NULL, *cursor;
615 if (!qemu_put_mouse_event_head || entry == NULL)
616 return;
618 cursor = qemu_put_mouse_event_head;
619 while (cursor != NULL && cursor != entry) {
620 prev = cursor;
621 cursor = cursor->next;
624 if (cursor == NULL) // does not exist or list empty
625 return;
626 else if (prev == NULL) { // entry is head
627 qemu_put_mouse_event_head = cursor->next;
628 if (qemu_put_mouse_event_current == entry)
629 qemu_put_mouse_event_current = cursor->next;
630 qemu_free(entry->qemu_put_mouse_event_name);
631 qemu_free(entry);
632 return;
635 prev->next = entry->next;
637 if (qemu_put_mouse_event_current == entry)
638 qemu_put_mouse_event_current = prev;
640 qemu_free(entry->qemu_put_mouse_event_name);
641 qemu_free(entry);
644 void kbd_put_keycode(int keycode)
646 if (qemu_put_kbd_event) {
647 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
651 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
653 QEMUPutMouseEvent *mouse_event;
654 void *mouse_event_opaque;
655 int width;
657 if (!qemu_put_mouse_event_current) {
658 return;
661 mouse_event =
662 qemu_put_mouse_event_current->qemu_put_mouse_event;
663 mouse_event_opaque =
664 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
666 if (mouse_event) {
667 if (graphic_rotate) {
668 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
669 width = 0x7fff;
670 else
671 width = graphic_width - 1;
672 mouse_event(mouse_event_opaque,
673 width - dy, dx, dz, buttons_state);
674 } else
675 mouse_event(mouse_event_opaque,
676 dx, dy, dz, buttons_state);
680 int kbd_mouse_is_absolute(void)
682 if (!qemu_put_mouse_event_current)
683 return 0;
685 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
688 void do_info_mice(void)
690 QEMUPutMouseEntry *cursor;
691 int index = 0;
693 if (!qemu_put_mouse_event_head) {
694 term_printf("No mouse devices connected\n");
695 return;
698 term_printf("Mouse devices available:\n");
699 cursor = qemu_put_mouse_event_head;
700 while (cursor != NULL) {
701 term_printf("%c Mouse #%d: %s\n",
702 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
703 index, cursor->qemu_put_mouse_event_name);
704 index++;
705 cursor = cursor->next;
709 void do_mouse_set(int index)
711 QEMUPutMouseEntry *cursor;
712 int i = 0;
714 if (!qemu_put_mouse_event_head) {
715 term_printf("No mouse devices connected\n");
716 return;
719 cursor = qemu_put_mouse_event_head;
720 while (cursor != NULL && index != i) {
721 i++;
722 cursor = cursor->next;
725 if (cursor != NULL)
726 qemu_put_mouse_event_current = cursor;
727 else
728 term_printf("Mouse at given index not found\n");
731 /* compute with 96 bit intermediate result: (a*b)/c */
732 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
734 union {
735 uint64_t ll;
736 struct {
737 #ifdef WORDS_BIGENDIAN
738 uint32_t high, low;
739 #else
740 uint32_t low, high;
741 #endif
742 } l;
743 } u, res;
744 uint64_t rl, rh;
746 u.ll = a;
747 rl = (uint64_t)u.l.low * (uint64_t)b;
748 rh = (uint64_t)u.l.high * (uint64_t)b;
749 rh += (rl >> 32);
750 res.l.high = rh / c;
751 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
752 return res.ll;
755 /***********************************************************/
756 /* real time host monotonic timer */
758 #define QEMU_TIMER_BASE 1000000000LL
760 #ifdef WIN32
762 static int64_t clock_freq;
764 static void init_get_clock(void)
766 LARGE_INTEGER freq;
767 int ret;
768 ret = QueryPerformanceFrequency(&freq);
769 if (ret == 0) {
770 fprintf(stderr, "Could not calibrate ticks\n");
771 exit(1);
773 clock_freq = freq.QuadPart;
776 static int64_t get_clock(void)
778 LARGE_INTEGER ti;
779 QueryPerformanceCounter(&ti);
780 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
783 #else
785 static int use_rt_clock;
787 static void init_get_clock(void)
789 use_rt_clock = 0;
790 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
792 struct timespec ts;
793 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
794 use_rt_clock = 1;
797 #endif
800 static int64_t get_clock(void)
802 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
803 if (use_rt_clock) {
804 struct timespec ts;
805 clock_gettime(CLOCK_MONOTONIC, &ts);
806 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
807 } else
808 #endif
810 /* XXX: using gettimeofday leads to problems if the date
811 changes, so it should be avoided. */
812 struct timeval tv;
813 gettimeofday(&tv, NULL);
814 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
817 #endif
819 /* Return the virtual CPU time, based on the instruction counter. */
820 static int64_t cpu_get_icount(void)
822 int64_t icount;
823 CPUState *env = cpu_single_env;;
824 icount = qemu_icount;
825 if (env) {
826 if (!can_do_io(env))
827 fprintf(stderr, "Bad clock read\n");
828 icount -= (env->icount_decr.u16.low + env->icount_extra);
830 return qemu_icount_bias + (icount << icount_time_shift);
833 /***********************************************************/
834 /* guest cycle counter */
836 static int64_t cpu_ticks_prev;
837 static int64_t cpu_ticks_offset;
838 static int64_t cpu_clock_offset;
839 static int cpu_ticks_enabled;
841 /* return the host CPU cycle counter and handle stop/restart */
842 int64_t cpu_get_ticks(void)
844 if (use_icount) {
845 return cpu_get_icount();
847 if (!cpu_ticks_enabled) {
848 return cpu_ticks_offset;
849 } else {
850 int64_t ticks;
851 ticks = cpu_get_real_ticks();
852 if (cpu_ticks_prev > ticks) {
853 /* Note: non increasing ticks may happen if the host uses
854 software suspend */
855 cpu_ticks_offset += cpu_ticks_prev - ticks;
857 cpu_ticks_prev = ticks;
858 return ticks + cpu_ticks_offset;
862 /* return the host CPU monotonic timer and handle stop/restart */
863 static int64_t cpu_get_clock(void)
865 int64_t ti;
866 if (!cpu_ticks_enabled) {
867 return cpu_clock_offset;
868 } else {
869 ti = get_clock();
870 return ti + cpu_clock_offset;
874 /* enable cpu_get_ticks() */
875 void cpu_enable_ticks(void)
877 if (!cpu_ticks_enabled) {
878 cpu_ticks_offset -= cpu_get_real_ticks();
879 cpu_clock_offset -= get_clock();
880 cpu_ticks_enabled = 1;
884 /* disable cpu_get_ticks() : the clock is stopped. You must not call
885 cpu_get_ticks() after that. */
886 void cpu_disable_ticks(void)
888 if (cpu_ticks_enabled) {
889 cpu_ticks_offset = cpu_get_ticks();
890 cpu_clock_offset = cpu_get_clock();
891 cpu_ticks_enabled = 0;
895 /***********************************************************/
896 /* timers */
898 #define QEMU_TIMER_REALTIME 0
899 #define QEMU_TIMER_VIRTUAL 1
901 struct QEMUClock {
902 int type;
903 /* XXX: add frequency */
906 struct QEMUTimer {
907 QEMUClock *clock;
908 int64_t expire_time;
909 QEMUTimerCB *cb;
910 void *opaque;
911 struct QEMUTimer *next;
914 struct qemu_alarm_timer {
915 char const *name;
916 unsigned int flags;
918 int (*start)(struct qemu_alarm_timer *t);
919 void (*stop)(struct qemu_alarm_timer *t);
920 void (*rearm)(struct qemu_alarm_timer *t);
921 void *priv;
924 #define ALARM_FLAG_DYNTICKS 0x1
925 #define ALARM_FLAG_EXPIRED 0x2
927 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
929 return t->flags & ALARM_FLAG_DYNTICKS;
932 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
934 if (!alarm_has_dynticks(t))
935 return;
937 t->rearm(t);
940 /* TODO: MIN_TIMER_REARM_US should be optimized */
941 #define MIN_TIMER_REARM_US 250
943 static struct qemu_alarm_timer *alarm_timer;
944 #ifndef _WIN32
945 static int alarm_timer_rfd, alarm_timer_wfd;
946 #endif
948 #ifdef _WIN32
950 struct qemu_alarm_win32 {
951 MMRESULT timerId;
952 HANDLE host_alarm;
953 unsigned int period;
954 } alarm_win32_data = {0, NULL, -1};
956 static int win32_start_timer(struct qemu_alarm_timer *t);
957 static void win32_stop_timer(struct qemu_alarm_timer *t);
958 static void win32_rearm_timer(struct qemu_alarm_timer *t);
960 #else
962 static int unix_start_timer(struct qemu_alarm_timer *t);
963 static void unix_stop_timer(struct qemu_alarm_timer *t);
965 #ifdef __linux__
967 static int dynticks_start_timer(struct qemu_alarm_timer *t);
968 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
969 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
971 static int hpet_start_timer(struct qemu_alarm_timer *t);
972 static void hpet_stop_timer(struct qemu_alarm_timer *t);
974 static int rtc_start_timer(struct qemu_alarm_timer *t);
975 static void rtc_stop_timer(struct qemu_alarm_timer *t);
977 #endif /* __linux__ */
979 #endif /* _WIN32 */
981 /* Correlation between real and virtual time is always going to be
982 fairly approximate, so ignore small variation.
983 When the guest is idle real and virtual time will be aligned in
984 the IO wait loop. */
985 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
987 static void icount_adjust(void)
989 int64_t cur_time;
990 int64_t cur_icount;
991 int64_t delta;
992 static int64_t last_delta;
993 /* If the VM is not running, then do nothing. */
994 if (!vm_running)
995 return;
997 cur_time = cpu_get_clock();
998 cur_icount = qemu_get_clock(vm_clock);
999 delta = cur_icount - cur_time;
1000 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1001 if (delta > 0
1002 && last_delta + ICOUNT_WOBBLE < delta * 2
1003 && icount_time_shift > 0) {
1004 /* The guest is getting too far ahead. Slow time down. */
1005 icount_time_shift--;
1007 if (delta < 0
1008 && last_delta - ICOUNT_WOBBLE > delta * 2
1009 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1010 /* The guest is getting too far behind. Speed time up. */
1011 icount_time_shift++;
1013 last_delta = delta;
1014 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1017 static void icount_adjust_rt(void * opaque)
1019 qemu_mod_timer(icount_rt_timer,
1020 qemu_get_clock(rt_clock) + 1000);
1021 icount_adjust();
1024 static void icount_adjust_vm(void * opaque)
1026 qemu_mod_timer(icount_vm_timer,
1027 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1028 icount_adjust();
1031 static void init_icount_adjust(void)
1033 /* Have both realtime and virtual time triggers for speed adjustment.
1034 The realtime trigger catches emulated time passing too slowly,
1035 the virtual time trigger catches emulated time passing too fast.
1036 Realtime triggers occur even when idle, so use them less frequently
1037 than VM triggers. */
1038 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1039 qemu_mod_timer(icount_rt_timer,
1040 qemu_get_clock(rt_clock) + 1000);
1041 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1042 qemu_mod_timer(icount_vm_timer,
1043 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1046 static struct qemu_alarm_timer alarm_timers[] = {
1047 #ifndef _WIN32
1048 #ifdef __linux__
1049 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1050 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1051 /* HPET - if available - is preferred */
1052 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1053 /* ...otherwise try RTC */
1054 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1055 #endif
1056 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1057 #else
1058 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1059 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1060 {"win32", 0, win32_start_timer,
1061 win32_stop_timer, NULL, &alarm_win32_data},
1062 #endif
1063 {NULL, }
1066 static void show_available_alarms(void)
1068 int i;
1070 printf("Available alarm timers, in order of precedence:\n");
1071 for (i = 0; alarm_timers[i].name; i++)
1072 printf("%s\n", alarm_timers[i].name);
1075 static void configure_alarms(char const *opt)
1077 int i;
1078 int cur = 0;
1079 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1080 char *arg;
1081 char *name;
1082 struct qemu_alarm_timer tmp;
1084 if (!strcmp(opt, "?")) {
1085 show_available_alarms();
1086 exit(0);
1089 arg = strdup(opt);
1091 /* Reorder the array */
1092 name = strtok(arg, ",");
1093 while (name) {
1094 for (i = 0; i < count && alarm_timers[i].name; i++) {
1095 if (!strcmp(alarm_timers[i].name, name))
1096 break;
1099 if (i == count) {
1100 fprintf(stderr, "Unknown clock %s\n", name);
1101 goto next;
1104 if (i < cur)
1105 /* Ignore */
1106 goto next;
1108 /* Swap */
1109 tmp = alarm_timers[i];
1110 alarm_timers[i] = alarm_timers[cur];
1111 alarm_timers[cur] = tmp;
1113 cur++;
1114 next:
1115 name = strtok(NULL, ",");
1118 free(arg);
1120 if (cur) {
1121 /* Disable remaining timers */
1122 for (i = cur; i < count; i++)
1123 alarm_timers[i].name = NULL;
1124 } else {
1125 show_available_alarms();
1126 exit(1);
1130 QEMUClock *rt_clock;
1131 QEMUClock *vm_clock;
1133 static QEMUTimer *active_timers[2];
1135 static QEMUClock *qemu_new_clock(int type)
1137 QEMUClock *clock;
1138 clock = qemu_mallocz(sizeof(QEMUClock));
1139 if (!clock)
1140 return NULL;
1141 clock->type = type;
1142 return clock;
1145 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1147 QEMUTimer *ts;
1149 ts = qemu_mallocz(sizeof(QEMUTimer));
1150 ts->clock = clock;
1151 ts->cb = cb;
1152 ts->opaque = opaque;
1153 return ts;
1156 void qemu_free_timer(QEMUTimer *ts)
1158 qemu_free(ts);
1161 /* stop a timer, but do not dealloc it */
1162 void qemu_del_timer(QEMUTimer *ts)
1164 QEMUTimer **pt, *t;
1166 /* NOTE: this code must be signal safe because
1167 qemu_timer_expired() can be called from a signal. */
1168 pt = &active_timers[ts->clock->type];
1169 for(;;) {
1170 t = *pt;
1171 if (!t)
1172 break;
1173 if (t == ts) {
1174 *pt = t->next;
1175 break;
1177 pt = &t->next;
1181 /* modify the current timer so that it will be fired when current_time
1182 >= expire_time. The corresponding callback will be called. */
1183 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1185 QEMUTimer **pt, *t;
1187 qemu_del_timer(ts);
1189 /* add the timer in the sorted list */
1190 /* NOTE: this code must be signal safe because
1191 qemu_timer_expired() can be called from a signal. */
1192 pt = &active_timers[ts->clock->type];
1193 for(;;) {
1194 t = *pt;
1195 if (!t)
1196 break;
1197 if (t->expire_time > expire_time)
1198 break;
1199 pt = &t->next;
1201 ts->expire_time = expire_time;
1202 ts->next = *pt;
1203 *pt = ts;
1205 /* Rearm if necessary */
1206 if (pt == &active_timers[ts->clock->type]) {
1207 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1208 qemu_rearm_alarm_timer(alarm_timer);
1210 /* Interrupt execution to force deadline recalculation. */
1211 if (use_icount && cpu_single_env) {
1212 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1217 int qemu_timer_pending(QEMUTimer *ts)
1219 QEMUTimer *t;
1220 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1221 if (t == ts)
1222 return 1;
1224 return 0;
1227 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1229 if (!timer_head)
1230 return 0;
1231 return (timer_head->expire_time <= current_time);
1234 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1236 QEMUTimer *ts;
1238 for(;;) {
1239 ts = *ptimer_head;
1240 if (!ts || ts->expire_time > current_time)
1241 break;
1242 /* remove timer from the list before calling the callback */
1243 *ptimer_head = ts->next;
1244 ts->next = NULL;
1246 /* run the callback (the timer list can be modified) */
1247 ts->cb(ts->opaque);
1251 int64_t qemu_get_clock(QEMUClock *clock)
1253 switch(clock->type) {
1254 case QEMU_TIMER_REALTIME:
1255 return get_clock() / 1000000;
1256 default:
1257 case QEMU_TIMER_VIRTUAL:
1258 if (use_icount) {
1259 return cpu_get_icount();
1260 } else {
1261 return cpu_get_clock();
1266 static void init_timers(void)
1268 init_get_clock();
1269 ticks_per_sec = QEMU_TIMER_BASE;
1270 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1271 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1274 /* save a timer */
1275 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1277 uint64_t expire_time;
1279 if (qemu_timer_pending(ts)) {
1280 expire_time = ts->expire_time;
1281 } else {
1282 expire_time = -1;
1284 qemu_put_be64(f, expire_time);
1287 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1289 uint64_t expire_time;
1291 expire_time = qemu_get_be64(f);
1292 if (expire_time != -1) {
1293 qemu_mod_timer(ts, expire_time);
1294 } else {
1295 qemu_del_timer(ts);
1299 static void timer_save(QEMUFile *f, void *opaque)
1301 if (cpu_ticks_enabled) {
1302 hw_error("cannot save state if virtual timers are running");
1304 qemu_put_be64(f, cpu_ticks_offset);
1305 qemu_put_be64(f, ticks_per_sec);
1306 qemu_put_be64(f, cpu_clock_offset);
1309 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1311 if (version_id != 1 && version_id != 2)
1312 return -EINVAL;
1313 if (cpu_ticks_enabled) {
1314 return -EINVAL;
1316 cpu_ticks_offset=qemu_get_be64(f);
1317 ticks_per_sec=qemu_get_be64(f);
1318 if (version_id == 2) {
1319 cpu_clock_offset=qemu_get_be64(f);
1321 return 0;
1324 #ifdef _WIN32
1325 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1326 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1327 #else
1328 static void host_alarm_handler(int host_signum)
1329 #endif
1331 #if 0
1332 #define DISP_FREQ 1000
1334 static int64_t delta_min = INT64_MAX;
1335 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1336 static int count;
1337 ti = qemu_get_clock(vm_clock);
1338 if (last_clock != 0) {
1339 delta = ti - last_clock;
1340 if (delta < delta_min)
1341 delta_min = delta;
1342 if (delta > delta_max)
1343 delta_max = delta;
1344 delta_cum += delta;
1345 if (++count == DISP_FREQ) {
1346 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1347 muldiv64(delta_min, 1000000, ticks_per_sec),
1348 muldiv64(delta_max, 1000000, ticks_per_sec),
1349 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1350 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1351 count = 0;
1352 delta_min = INT64_MAX;
1353 delta_max = 0;
1354 delta_cum = 0;
1357 last_clock = ti;
1359 #endif
1360 if (1 ||
1361 alarm_has_dynticks(alarm_timer) ||
1362 (!use_icount &&
1363 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1364 qemu_get_clock(vm_clock))) ||
1365 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1366 qemu_get_clock(rt_clock))) {
1367 CPUState *env = next_cpu;
1369 #ifdef _WIN32
1370 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1371 SetEvent(data->host_alarm);
1372 #else
1373 static const char byte = 0;
1374 write(alarm_timer_wfd, &byte, sizeof(byte));
1375 #endif
1376 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1378 if (env) {
1379 /* stop the currently executing cpu because a timer occured */
1380 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1381 #ifdef USE_KQEMU
1382 if (env->kqemu_enabled) {
1383 kqemu_cpu_interrupt(env);
1385 #endif
1387 event_pending = 1;
1391 static int64_t qemu_next_deadline(void)
1393 int64_t delta;
1395 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1396 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1397 qemu_get_clock(vm_clock);
1398 } else {
1399 /* To avoid problems with overflow limit this to 2^32. */
1400 delta = INT32_MAX;
1403 if (delta < 0)
1404 delta = 0;
1406 return delta;
1409 #if defined(__linux__) || defined(_WIN32)
1410 static uint64_t qemu_next_deadline_dyntick(void)
1412 int64_t delta;
1413 int64_t rtdelta;
1415 if (use_icount)
1416 delta = INT32_MAX;
1417 else
1418 delta = (qemu_next_deadline() + 999) / 1000;
1420 if (active_timers[QEMU_TIMER_REALTIME]) {
1421 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1422 qemu_get_clock(rt_clock))*1000;
1423 if (rtdelta < delta)
1424 delta = rtdelta;
1427 if (delta < MIN_TIMER_REARM_US)
1428 delta = MIN_TIMER_REARM_US;
1430 return delta;
1432 #endif
1434 #ifndef _WIN32
1436 /* Sets a specific flag */
1437 static int fcntl_setfl(int fd, int flag)
1439 int flags;
1441 flags = fcntl(fd, F_GETFL);
1442 if (flags == -1)
1443 return -errno;
1445 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1446 return -errno;
1448 return 0;
1451 #if defined(__linux__)
1453 #define RTC_FREQ 1024
1455 static void enable_sigio_timer(int fd)
1457 struct sigaction act;
1459 /* timer signal */
1460 sigfillset(&act.sa_mask);
1461 act.sa_flags = 0;
1462 act.sa_handler = host_alarm_handler;
1464 sigaction(SIGIO, &act, NULL);
1465 fcntl_setfl(fd, O_ASYNC);
1466 fcntl(fd, F_SETOWN, getpid());
1469 static int hpet_start_timer(struct qemu_alarm_timer *t)
1471 struct hpet_info info;
1472 int r, fd;
1474 fd = open("/dev/hpet", O_RDONLY);
1475 if (fd < 0)
1476 return -1;
1478 /* Set frequency */
1479 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1480 if (r < 0) {
1481 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1482 "error, but for better emulation accuracy type:\n"
1483 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1484 goto fail;
1487 /* Check capabilities */
1488 r = ioctl(fd, HPET_INFO, &info);
1489 if (r < 0)
1490 goto fail;
1492 /* Enable periodic mode */
1493 r = ioctl(fd, HPET_EPI, 0);
1494 if (info.hi_flags && (r < 0))
1495 goto fail;
1497 /* Enable interrupt */
1498 r = ioctl(fd, HPET_IE_ON, 0);
1499 if (r < 0)
1500 goto fail;
1502 enable_sigio_timer(fd);
1503 t->priv = (void *)(long)fd;
1505 return 0;
1506 fail:
1507 close(fd);
1508 return -1;
1511 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1513 int fd = (long)t->priv;
1515 close(fd);
1518 static int rtc_start_timer(struct qemu_alarm_timer *t)
1520 int rtc_fd;
1521 unsigned long current_rtc_freq = 0;
1523 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1524 if (rtc_fd < 0)
1525 return -1;
1526 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1527 if (current_rtc_freq != RTC_FREQ &&
1528 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1529 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1530 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1531 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1532 goto fail;
1534 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1535 fail:
1536 close(rtc_fd);
1537 return -1;
1540 enable_sigio_timer(rtc_fd);
1542 t->priv = (void *)(long)rtc_fd;
1544 return 0;
1547 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1549 int rtc_fd = (long)t->priv;
1551 close(rtc_fd);
1554 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1556 struct sigevent ev;
1557 timer_t host_timer;
1558 struct sigaction act;
1560 sigfillset(&act.sa_mask);
1561 act.sa_flags = 0;
1562 act.sa_handler = host_alarm_handler;
1564 sigaction(SIGALRM, &act, NULL);
1566 ev.sigev_value.sival_int = 0;
1567 ev.sigev_notify = SIGEV_SIGNAL;
1568 ev.sigev_signo = SIGALRM;
1570 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1571 perror("timer_create");
1573 /* disable dynticks */
1574 fprintf(stderr, "Dynamic Ticks disabled\n");
1576 return -1;
1579 t->priv = (void *)host_timer;
1581 return 0;
1584 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1586 timer_t host_timer = (timer_t)t->priv;
1588 timer_delete(host_timer);
1591 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1593 timer_t host_timer = (timer_t)t->priv;
1594 struct itimerspec timeout;
1595 int64_t nearest_delta_us = INT64_MAX;
1596 int64_t current_us;
1598 if (!active_timers[QEMU_TIMER_REALTIME] &&
1599 !active_timers[QEMU_TIMER_VIRTUAL])
1600 return;
1602 nearest_delta_us = qemu_next_deadline_dyntick();
1604 /* check whether a timer is already running */
1605 if (timer_gettime(host_timer, &timeout)) {
1606 perror("gettime");
1607 fprintf(stderr, "Internal timer error: aborting\n");
1608 exit(1);
1610 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1611 if (current_us && current_us <= nearest_delta_us)
1612 return;
1614 timeout.it_interval.tv_sec = 0;
1615 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1616 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1617 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1618 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1619 perror("settime");
1620 fprintf(stderr, "Internal timer error: aborting\n");
1621 exit(1);
1625 #endif /* defined(__linux__) */
1627 static int unix_start_timer(struct qemu_alarm_timer *t)
1629 struct sigaction act;
1630 struct itimerval itv;
1631 int err;
1633 /* timer signal */
1634 sigfillset(&act.sa_mask);
1635 act.sa_flags = 0;
1636 act.sa_handler = host_alarm_handler;
1638 sigaction(SIGALRM, &act, NULL);
1640 itv.it_interval.tv_sec = 0;
1641 /* for i386 kernel 2.6 to get 1 ms */
1642 itv.it_interval.tv_usec = 999;
1643 itv.it_value.tv_sec = 0;
1644 itv.it_value.tv_usec = 10 * 1000;
1646 err = setitimer(ITIMER_REAL, &itv, NULL);
1647 if (err)
1648 return -1;
1650 return 0;
1653 static void unix_stop_timer(struct qemu_alarm_timer *t)
1655 struct itimerval itv;
1657 memset(&itv, 0, sizeof(itv));
1658 setitimer(ITIMER_REAL, &itv, NULL);
1661 #endif /* !defined(_WIN32) */
1663 static void try_to_rearm_timer(void *opaque)
1665 struct qemu_alarm_timer *t = opaque;
1666 #ifndef _WIN32
1667 ssize_t len;
1669 /* Drain the notify pipe */
1670 do {
1671 char buffer[512];
1672 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1673 } while ((len == -1 && errno == EINTR) || len > 0);
1674 #endif
1676 /* vm time timers */
1677 if (vm_running && likely(!(cur_cpu && (cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
1678 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
1679 qemu_get_clock(vm_clock));
1681 /* real time timers */
1682 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
1683 qemu_get_clock(rt_clock));
1685 if (t->flags & ALARM_FLAG_EXPIRED) {
1686 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1687 qemu_rearm_alarm_timer(alarm_timer);
1691 #ifdef _WIN32
1693 static int win32_start_timer(struct qemu_alarm_timer *t)
1695 TIMECAPS tc;
1696 struct qemu_alarm_win32 *data = t->priv;
1697 UINT flags;
1699 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1700 if (!data->host_alarm) {
1701 perror("Failed CreateEvent");
1702 return -1;
1705 memset(&tc, 0, sizeof(tc));
1706 timeGetDevCaps(&tc, sizeof(tc));
1708 if (data->period < tc.wPeriodMin)
1709 data->period = tc.wPeriodMin;
1711 timeBeginPeriod(data->period);
1713 flags = TIME_CALLBACK_FUNCTION;
1714 if (alarm_has_dynticks(t))
1715 flags |= TIME_ONESHOT;
1716 else
1717 flags |= TIME_PERIODIC;
1719 data->timerId = timeSetEvent(1, // interval (ms)
1720 data->period, // resolution
1721 host_alarm_handler, // function
1722 (DWORD)t, // parameter
1723 flags);
1725 if (!data->timerId) {
1726 perror("Failed to initialize win32 alarm timer");
1728 timeEndPeriod(data->period);
1729 CloseHandle(data->host_alarm);
1730 return -1;
1733 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1735 return 0;
1738 static void win32_stop_timer(struct qemu_alarm_timer *t)
1740 struct qemu_alarm_win32 *data = t->priv;
1742 timeKillEvent(data->timerId);
1743 timeEndPeriod(data->period);
1745 CloseHandle(data->host_alarm);
1748 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1750 struct qemu_alarm_win32 *data = t->priv;
1751 uint64_t nearest_delta_us;
1753 if (!active_timers[QEMU_TIMER_REALTIME] &&
1754 !active_timers[QEMU_TIMER_VIRTUAL])
1755 return;
1757 nearest_delta_us = qemu_next_deadline_dyntick();
1758 nearest_delta_us /= 1000;
1760 timeKillEvent(data->timerId);
1762 data->timerId = timeSetEvent(1,
1763 data->period,
1764 host_alarm_handler,
1765 (DWORD)t,
1766 TIME_ONESHOT | TIME_PERIODIC);
1768 if (!data->timerId) {
1769 perror("Failed to re-arm win32 alarm timer");
1771 timeEndPeriod(data->period);
1772 CloseHandle(data->host_alarm);
1773 exit(1);
1777 #endif /* _WIN32 */
1779 static int init_timer_alarm(void)
1781 struct qemu_alarm_timer *t = NULL;
1782 int i, err = -1;
1784 #ifndef _WIN32
1785 int fds[2];
1787 err = pipe(fds);
1788 if (err == -1)
1789 return -errno;
1791 err = fcntl_setfl(fds[0], O_NONBLOCK);
1792 if (err < 0)
1793 goto fail;
1795 err = fcntl_setfl(fds[1], O_NONBLOCK);
1796 if (err < 0)
1797 goto fail;
1799 alarm_timer_rfd = fds[0];
1800 alarm_timer_wfd = fds[1];
1801 #endif
1803 for (i = 0; alarm_timers[i].name; i++) {
1804 t = &alarm_timers[i];
1806 err = t->start(t);
1807 if (!err)
1808 break;
1811 if (err) {
1812 err = -ENOENT;
1813 goto fail;
1816 #ifndef _WIN32
1817 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1818 try_to_rearm_timer, NULL, t);
1819 #endif
1821 alarm_timer = t;
1823 return 0;
1825 fail:
1826 #ifndef _WIN32
1827 close(fds[0]);
1828 close(fds[1]);
1829 #endif
1830 return err;
1833 static void quit_timers(void)
1835 alarm_timer->stop(alarm_timer);
1836 alarm_timer = NULL;
1839 /***********************************************************/
1840 /* host time/date access */
1841 void qemu_get_timedate(struct tm *tm, int offset)
1843 time_t ti;
1844 struct tm *ret;
1846 time(&ti);
1847 ti += offset;
1848 if (rtc_date_offset == -1) {
1849 if (rtc_utc)
1850 ret = gmtime(&ti);
1851 else
1852 ret = localtime(&ti);
1853 } else {
1854 ti -= rtc_date_offset;
1855 ret = gmtime(&ti);
1858 memcpy(tm, ret, sizeof(struct tm));
1861 int qemu_timedate_diff(struct tm *tm)
1863 time_t seconds;
1865 if (rtc_date_offset == -1)
1866 if (rtc_utc)
1867 seconds = mktimegm(tm);
1868 else
1869 seconds = mktime(tm);
1870 else
1871 seconds = mktimegm(tm) + rtc_date_offset;
1873 return seconds - time(NULL);
1876 #ifdef _WIN32
1877 static void socket_cleanup(void)
1879 WSACleanup();
1882 static int socket_init(void)
1884 WSADATA Data;
1885 int ret, err;
1887 ret = WSAStartup(MAKEWORD(2,2), &Data);
1888 if (ret != 0) {
1889 err = WSAGetLastError();
1890 fprintf(stderr, "WSAStartup: %d\n", err);
1891 return -1;
1893 atexit(socket_cleanup);
1894 return 0;
1896 #endif
1898 const char *get_opt_name(char *buf, int buf_size, const char *p)
1900 char *q;
1902 q = buf;
1903 while (*p != '\0' && *p != '=') {
1904 if (q && (q - buf) < buf_size - 1)
1905 *q++ = *p;
1906 p++;
1908 if (q)
1909 *q = '\0';
1911 return p;
1914 const char *get_opt_value(char *buf, int buf_size, const char *p)
1916 char *q;
1918 q = buf;
1919 while (*p != '\0') {
1920 if (*p == ',') {
1921 if (*(p + 1) != ',')
1922 break;
1923 p++;
1925 if (q && (q - buf) < buf_size - 1)
1926 *q++ = *p;
1927 p++;
1929 if (q)
1930 *q = '\0';
1932 return p;
1935 int get_param_value(char *buf, int buf_size,
1936 const char *tag, const char *str)
1938 const char *p;
1939 char option[128];
1941 p = str;
1942 for(;;) {
1943 p = get_opt_name(option, sizeof(option), p);
1944 if (*p != '=')
1945 break;
1946 p++;
1947 if (!strcmp(tag, option)) {
1948 (void)get_opt_value(buf, buf_size, p);
1949 return strlen(buf);
1950 } else {
1951 p = get_opt_value(NULL, 0, p);
1953 if (*p != ',')
1954 break;
1955 p++;
1957 return 0;
1960 int check_params(char *buf, int buf_size,
1961 const char * const *params, const char *str)
1963 const char *p;
1964 int i;
1966 p = str;
1967 for(;;) {
1968 p = get_opt_name(buf, buf_size, p);
1969 if (*p != '=')
1970 return -1;
1971 p++;
1972 for(i = 0; params[i] != NULL; i++)
1973 if (!strcmp(params[i], buf))
1974 break;
1975 if (params[i] == NULL)
1976 return -1;
1977 p = get_opt_value(NULL, 0, p);
1978 if (*p != ',')
1979 break;
1980 p++;
1982 return 0;
1985 /***********************************************************/
1986 /* Bluetooth support */
1987 static int nb_hcis;
1988 static int cur_hci;
1989 static struct HCIInfo *hci_table[MAX_NICS];
1991 static struct bt_vlan_s {
1992 struct bt_scatternet_s net;
1993 int id;
1994 struct bt_vlan_s *next;
1995 } *first_bt_vlan;
1997 /* find or alloc a new bluetooth "VLAN" */
1998 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
2000 struct bt_vlan_s **pvlan, *vlan;
2001 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
2002 if (vlan->id == id)
2003 return &vlan->net;
2005 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
2006 vlan->id = id;
2007 pvlan = &first_bt_vlan;
2008 while (*pvlan != NULL)
2009 pvlan = &(*pvlan)->next;
2010 *pvlan = vlan;
2011 return &vlan->net;
2014 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2018 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2020 return -ENOTSUP;
2023 static struct HCIInfo null_hci = {
2024 .cmd_send = null_hci_send,
2025 .sco_send = null_hci_send,
2026 .acl_send = null_hci_send,
2027 .bdaddr_set = null_hci_addr_set,
2030 struct HCIInfo *qemu_next_hci(void)
2032 if (cur_hci == nb_hcis)
2033 return &null_hci;
2035 return hci_table[cur_hci++];
2038 static struct HCIInfo *hci_init(const char *str)
2040 char *endp;
2041 struct bt_scatternet_s *vlan = 0;
2043 if (!strcmp(str, "null"))
2044 /* null */
2045 return &null_hci;
2046 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2047 /* host[:hciN] */
2048 return bt_host_hci(str[4] ? str + 5 : "hci0");
2049 else if (!strncmp(str, "hci", 3)) {
2050 /* hci[,vlan=n] */
2051 if (str[3]) {
2052 if (!strncmp(str + 3, ",vlan=", 6)) {
2053 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2054 if (*endp)
2055 vlan = 0;
2057 } else
2058 vlan = qemu_find_bt_vlan(0);
2059 if (vlan)
2060 return bt_new_hci(vlan);
2063 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2065 return 0;
2068 static int bt_hci_parse(const char *str)
2070 struct HCIInfo *hci;
2071 bdaddr_t bdaddr;
2073 if (nb_hcis >= MAX_NICS) {
2074 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2075 return -1;
2078 hci = hci_init(str);
2079 if (!hci)
2080 return -1;
2082 bdaddr.b[0] = 0x52;
2083 bdaddr.b[1] = 0x54;
2084 bdaddr.b[2] = 0x00;
2085 bdaddr.b[3] = 0x12;
2086 bdaddr.b[4] = 0x34;
2087 bdaddr.b[5] = 0x56 + nb_hcis;
2088 hci->bdaddr_set(hci, bdaddr.b);
2090 hci_table[nb_hcis++] = hci;
2092 return 0;
2095 static void bt_vhci_add(int vlan_id)
2097 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2099 if (!vlan->slave)
2100 fprintf(stderr, "qemu: warning: adding a VHCI to "
2101 "an empty scatternet %i\n", vlan_id);
2103 bt_vhci_init(bt_new_hci(vlan));
2106 static struct bt_device_s *bt_device_add(const char *opt)
2108 struct bt_scatternet_s *vlan;
2109 int vlan_id = 0;
2110 char *endp = strstr(opt, ",vlan=");
2111 int len = (endp ? endp - opt : strlen(opt)) + 1;
2112 char devname[10];
2114 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2116 if (endp) {
2117 vlan_id = strtol(endp + 6, &endp, 0);
2118 if (*endp) {
2119 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2120 return 0;
2124 vlan = qemu_find_bt_vlan(vlan_id);
2126 if (!vlan->slave)
2127 fprintf(stderr, "qemu: warning: adding a slave device to "
2128 "an empty scatternet %i\n", vlan_id);
2130 if (!strcmp(devname, "keyboard"))
2131 return bt_keyboard_init(vlan);
2133 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2134 return 0;
2137 static int bt_parse(const char *opt)
2139 const char *endp, *p;
2140 int vlan;
2142 if (strstart(opt, "hci", &endp)) {
2143 if (!*endp || *endp == ',') {
2144 if (*endp)
2145 if (!strstart(endp, ",vlan=", 0))
2146 opt = endp + 1;
2148 return bt_hci_parse(opt);
2150 } else if (strstart(opt, "vhci", &endp)) {
2151 if (!*endp || *endp == ',') {
2152 if (*endp) {
2153 if (strstart(endp, ",vlan=", &p)) {
2154 vlan = strtol(p, (char **) &endp, 0);
2155 if (*endp) {
2156 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2157 return 1;
2159 } else {
2160 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2161 return 1;
2163 } else
2164 vlan = 0;
2166 bt_vhci_add(vlan);
2167 return 0;
2169 } else if (strstart(opt, "device:", &endp))
2170 return !bt_device_add(endp);
2172 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2173 return 1;
2176 /***********************************************************/
2177 /* QEMU Block devices */
2179 #define HD_ALIAS "index=%d,media=disk"
2180 #ifdef TARGET_PPC
2181 #define CDROM_ALIAS "index=1,media=cdrom"
2182 #else
2183 #define CDROM_ALIAS "index=2,media=cdrom"
2184 #endif
2185 #define FD_ALIAS "index=%d,if=floppy"
2186 #define PFLASH_ALIAS "if=pflash"
2187 #define MTD_ALIAS "if=mtd"
2188 #define SD_ALIAS "index=0,if=sd"
2190 static int drive_opt_get_free_idx(void)
2192 int index;
2194 for (index = 0; index < MAX_DRIVES; index++)
2195 if (!drives_opt[index].used) {
2196 drives_opt[index].used = 1;
2197 return index;
2200 return -1;
2203 static int drive_get_free_idx(void)
2205 int index;
2207 for (index = 0; index < MAX_DRIVES; index++)
2208 if (!drives_table[index].used) {
2209 drives_table[index].used = 1;
2210 return index;
2213 return -1;
2216 int drive_add(const char *file, const char *fmt, ...)
2218 va_list ap;
2219 int index = drive_opt_get_free_idx();
2221 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2222 fprintf(stderr, "qemu: too many drives\n");
2223 return -1;
2226 drives_opt[index].file = file;
2227 va_start(ap, fmt);
2228 vsnprintf(drives_opt[index].opt,
2229 sizeof(drives_opt[0].opt), fmt, ap);
2230 va_end(ap);
2232 nb_drives_opt++;
2233 return index;
2236 void drive_remove(int index)
2238 drives_opt[index].used = 0;
2239 nb_drives_opt--;
2242 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2244 int index;
2246 /* seek interface, bus and unit */
2248 for (index = 0; index < MAX_DRIVES; index++)
2249 if (drives_table[index].type == type &&
2250 drives_table[index].bus == bus &&
2251 drives_table[index].unit == unit &&
2252 drives_table[index].used)
2253 return index;
2255 return -1;
2258 int drive_get_max_bus(BlockInterfaceType type)
2260 int max_bus;
2261 int index;
2263 max_bus = -1;
2264 for (index = 0; index < nb_drives; index++) {
2265 if(drives_table[index].type == type &&
2266 drives_table[index].bus > max_bus)
2267 max_bus = drives_table[index].bus;
2269 return max_bus;
2272 static void bdrv_format_print(void *opaque, const char *name)
2274 fprintf(stderr, " %s", name);
2277 void drive_uninit(BlockDriverState *bdrv)
2279 int i;
2281 for (i = 0; i < MAX_DRIVES; i++)
2282 if (drives_table[i].bdrv == bdrv) {
2283 drives_table[i].bdrv = NULL;
2284 drives_table[i].used = 0;
2285 drive_remove(drives_table[i].drive_opt_idx);
2286 nb_drives--;
2287 break;
2291 int drive_init(struct drive_opt *arg, int snapshot,
2292 QEMUMachine *machine)
2294 char buf[128];
2295 char file[1024];
2296 char devname[128];
2297 const char *mediastr = "";
2298 BlockInterfaceType type;
2299 enum { MEDIA_DISK, MEDIA_CDROM } media;
2300 int bus_id, unit_id;
2301 int cyls, heads, secs, translation;
2302 BlockDriverState *bdrv;
2303 BlockDriver *drv = NULL;
2304 int max_devs;
2305 int index;
2306 int cache;
2307 int bdrv_flags;
2308 int drives_table_idx;
2309 char *str = arg->opt;
2310 static const char * const params[] = { "bus", "unit", "if", "index",
2311 "cyls", "heads", "secs", "trans",
2312 "media", "snapshot", "file",
2313 "cache", "format", "boot", NULL };
2315 if (check_params(buf, sizeof(buf), params, str) < 0) {
2316 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2317 buf, str);
2318 return -1;
2321 file[0] = 0;
2322 cyls = heads = secs = 0;
2323 bus_id = 0;
2324 unit_id = -1;
2325 translation = BIOS_ATA_TRANSLATION_AUTO;
2326 index = -1;
2327 cache = 1;
2329 if (machine->use_scsi) {
2330 type = IF_SCSI;
2331 max_devs = MAX_SCSI_DEVS;
2332 pstrcpy(devname, sizeof(devname), "scsi");
2333 } else {
2334 type = IF_IDE;
2335 max_devs = MAX_IDE_DEVS;
2336 pstrcpy(devname, sizeof(devname), "ide");
2338 media = MEDIA_DISK;
2340 /* extract parameters */
2342 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2343 bus_id = strtol(buf, NULL, 0);
2344 if (bus_id < 0) {
2345 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2346 return -1;
2350 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2351 unit_id = strtol(buf, NULL, 0);
2352 if (unit_id < 0) {
2353 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2354 return -1;
2358 if (get_param_value(buf, sizeof(buf), "if", str)) {
2359 pstrcpy(devname, sizeof(devname), buf);
2360 if (!strcmp(buf, "ide")) {
2361 type = IF_IDE;
2362 max_devs = MAX_IDE_DEVS;
2363 } else if (!strcmp(buf, "scsi")) {
2364 type = IF_SCSI;
2365 max_devs = MAX_SCSI_DEVS;
2366 } else if (!strcmp(buf, "floppy")) {
2367 type = IF_FLOPPY;
2368 max_devs = 0;
2369 } else if (!strcmp(buf, "pflash")) {
2370 type = IF_PFLASH;
2371 max_devs = 0;
2372 } else if (!strcmp(buf, "mtd")) {
2373 type = IF_MTD;
2374 max_devs = 0;
2375 } else if (!strcmp(buf, "sd")) {
2376 type = IF_SD;
2377 max_devs = 0;
2378 } else if (!strcmp(buf, "virtio")) {
2379 type = IF_VIRTIO;
2380 max_devs = 0;
2381 } else {
2382 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2383 return -1;
2387 if (get_param_value(buf, sizeof(buf), "index", str)) {
2388 index = strtol(buf, NULL, 0);
2389 if (index < 0) {
2390 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2391 return -1;
2395 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2396 cyls = strtol(buf, NULL, 0);
2399 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2400 heads = strtol(buf, NULL, 0);
2403 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2404 secs = strtol(buf, NULL, 0);
2407 if (cyls || heads || secs) {
2408 if (cyls < 1 || cyls > 16383) {
2409 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2410 return -1;
2412 if (heads < 1 || heads > 16) {
2413 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2414 return -1;
2416 if (secs < 1 || secs > 63) {
2417 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2418 return -1;
2422 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2423 if (!cyls) {
2424 fprintf(stderr,
2425 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2426 str);
2427 return -1;
2429 if (!strcmp(buf, "none"))
2430 translation = BIOS_ATA_TRANSLATION_NONE;
2431 else if (!strcmp(buf, "lba"))
2432 translation = BIOS_ATA_TRANSLATION_LBA;
2433 else if (!strcmp(buf, "auto"))
2434 translation = BIOS_ATA_TRANSLATION_AUTO;
2435 else {
2436 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2437 return -1;
2441 if (get_param_value(buf, sizeof(buf), "media", str)) {
2442 if (!strcmp(buf, "disk")) {
2443 media = MEDIA_DISK;
2444 } else if (!strcmp(buf, "cdrom")) {
2445 if (cyls || secs || heads) {
2446 fprintf(stderr,
2447 "qemu: '%s' invalid physical CHS format\n", str);
2448 return -1;
2450 media = MEDIA_CDROM;
2451 } else {
2452 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2453 return -1;
2457 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2458 if (!strcmp(buf, "on"))
2459 snapshot = 1;
2460 else if (!strcmp(buf, "off"))
2461 snapshot = 0;
2462 else {
2463 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2464 return -1;
2468 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2469 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2470 cache = 0;
2471 else if (!strcmp(buf, "writethrough"))
2472 cache = 1;
2473 else if (!strcmp(buf, "writeback"))
2474 cache = 2;
2475 else {
2476 fprintf(stderr, "qemu: invalid cache option\n");
2477 return -1;
2481 if (get_param_value(buf, sizeof(buf), "format", str)) {
2482 if (strcmp(buf, "?") == 0) {
2483 fprintf(stderr, "qemu: Supported formats:");
2484 bdrv_iterate_format(bdrv_format_print, NULL);
2485 fprintf(stderr, "\n");
2486 return -1;
2488 drv = bdrv_find_format(buf);
2489 if (!drv) {
2490 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2491 return -1;
2495 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2496 if (!strcmp(buf, "on")) {
2497 if (extboot_drive != -1) {
2498 fprintf(stderr, "qemu: two bootable drives specified\n");
2499 return -1;
2501 extboot_drive = nb_drives;
2502 } else if (strcmp(buf, "off")) {
2503 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2504 return -1;
2508 if (arg->file == NULL)
2509 get_param_value(file, sizeof(file), "file", str);
2510 else
2511 pstrcpy(file, sizeof(file), arg->file);
2513 /* compute bus and unit according index */
2515 if (index != -1) {
2516 if (bus_id != 0 || unit_id != -1) {
2517 fprintf(stderr,
2518 "qemu: '%s' index cannot be used with bus and unit\n", str);
2519 return -1;
2521 if (max_devs == 0)
2523 unit_id = index;
2524 bus_id = 0;
2525 } else {
2526 unit_id = index % max_devs;
2527 bus_id = index / max_devs;
2531 /* if user doesn't specify a unit_id,
2532 * try to find the first free
2535 if (unit_id == -1) {
2536 unit_id = 0;
2537 while (drive_get_index(type, bus_id, unit_id) != -1) {
2538 unit_id++;
2539 if (max_devs && unit_id >= max_devs) {
2540 unit_id -= max_devs;
2541 bus_id++;
2546 /* check unit id */
2548 if (max_devs && unit_id >= max_devs) {
2549 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2550 str, unit_id, max_devs - 1);
2551 return -1;
2555 * ignore multiple definitions
2558 if (drive_get_index(type, bus_id, unit_id) != -1)
2559 return -2;
2561 /* init */
2563 if (type == IF_IDE || type == IF_SCSI)
2564 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2565 if (max_devs)
2566 snprintf(buf, sizeof(buf), "%s%i%s%i",
2567 devname, bus_id, mediastr, unit_id);
2568 else
2569 snprintf(buf, sizeof(buf), "%s%s%i",
2570 devname, mediastr, unit_id);
2571 bdrv = bdrv_new(buf);
2572 drives_table_idx = drive_get_free_idx();
2573 drives_table[drives_table_idx].bdrv = bdrv;
2574 drives_table[drives_table_idx].type = type;
2575 drives_table[drives_table_idx].bus = bus_id;
2576 drives_table[drives_table_idx].unit = unit_id;
2577 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2578 nb_drives++;
2580 switch(type) {
2581 case IF_IDE:
2582 case IF_SCSI:
2583 switch(media) {
2584 case MEDIA_DISK:
2585 if (cyls != 0) {
2586 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2587 bdrv_set_translation_hint(bdrv, translation);
2589 break;
2590 case MEDIA_CDROM:
2591 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2592 break;
2594 break;
2595 case IF_SD:
2596 /* FIXME: This isn't really a floppy, but it's a reasonable
2597 approximation. */
2598 case IF_FLOPPY:
2599 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2600 break;
2601 case IF_PFLASH:
2602 case IF_MTD:
2603 case IF_VIRTIO:
2604 break;
2606 if (!file[0])
2607 return -2;
2608 bdrv_flags = 0;
2609 if (snapshot) {
2610 bdrv_flags |= BDRV_O_SNAPSHOT;
2611 cache = 2; /* always use write-back with snapshot */
2613 if (cache == 0) /* no caching */
2614 bdrv_flags |= BDRV_O_NOCACHE;
2615 else if (cache == 2) /* write-back */
2616 bdrv_flags |= BDRV_O_CACHE_WB;
2617 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2618 fprintf(stderr, "qemu: could not open disk image %s\n",
2619 file);
2620 return -1;
2622 return drives_table_idx;
2625 /***********************************************************/
2626 /* USB devices */
2628 static USBPort *used_usb_ports;
2629 static USBPort *free_usb_ports;
2631 /* ??? Maybe change this to register a hub to keep track of the topology. */
2632 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2633 usb_attachfn attach)
2635 port->opaque = opaque;
2636 port->index = index;
2637 port->attach = attach;
2638 port->next = free_usb_ports;
2639 free_usb_ports = port;
2642 int usb_device_add_dev(USBDevice *dev)
2644 USBPort *port;
2646 /* Find a USB port to add the device to. */
2647 port = free_usb_ports;
2648 if (!port->next) {
2649 USBDevice *hub;
2651 /* Create a new hub and chain it on. */
2652 free_usb_ports = NULL;
2653 port->next = used_usb_ports;
2654 used_usb_ports = port;
2656 hub = usb_hub_init(VM_USB_HUB_SIZE);
2657 usb_attach(port, hub);
2658 port = free_usb_ports;
2661 free_usb_ports = port->next;
2662 port->next = used_usb_ports;
2663 used_usb_ports = port;
2664 usb_attach(port, dev);
2665 return 0;
2668 static int usb_device_add(const char *devname)
2670 const char *p;
2671 USBDevice *dev;
2673 if (!free_usb_ports)
2674 return -1;
2676 if (strstart(devname, "host:", &p)) {
2677 dev = usb_host_device_open(p);
2678 } else if (!strcmp(devname, "mouse")) {
2679 dev = usb_mouse_init();
2680 } else if (!strcmp(devname, "tablet")) {
2681 dev = usb_tablet_init();
2682 } else if (!strcmp(devname, "keyboard")) {
2683 dev = usb_keyboard_init();
2684 } else if (strstart(devname, "disk:", &p)) {
2685 dev = usb_msd_init(p);
2686 } else if (!strcmp(devname, "wacom-tablet")) {
2687 dev = usb_wacom_init();
2688 } else if (strstart(devname, "serial:", &p)) {
2689 dev = usb_serial_init(p);
2690 #ifdef CONFIG_BRLAPI
2691 } else if (!strcmp(devname, "braille")) {
2692 dev = usb_baum_init();
2693 #endif
2694 } else if (strstart(devname, "net:", &p)) {
2695 int nic = nb_nics;
2697 if (net_client_init("nic", p) < 0)
2698 return -1;
2699 nd_table[nic].model = "usb";
2700 dev = usb_net_init(&nd_table[nic]);
2701 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2702 dev = usb_bt_init(devname[2] ? hci_init(p) :
2703 bt_new_hci(qemu_find_bt_vlan(0)));
2704 } else {
2705 return -1;
2707 if (!dev)
2708 return -1;
2710 return usb_device_add_dev(dev);
2713 int usb_device_del_addr(int bus_num, int addr)
2715 USBPort *port;
2716 USBPort **lastp;
2717 USBDevice *dev;
2719 if (!used_usb_ports)
2720 return -1;
2722 if (bus_num != 0)
2723 return -1;
2725 lastp = &used_usb_ports;
2726 port = used_usb_ports;
2727 while (port && port->dev->addr != addr) {
2728 lastp = &port->next;
2729 port = port->next;
2732 if (!port)
2733 return -1;
2735 dev = port->dev;
2736 *lastp = port->next;
2737 usb_attach(port, NULL);
2738 dev->handle_destroy(dev);
2739 port->next = free_usb_ports;
2740 free_usb_ports = port;
2741 return 0;
2744 static int usb_device_del(const char *devname)
2746 int bus_num, addr;
2747 const char *p;
2749 if (strstart(devname, "host:", &p))
2750 return usb_host_device_close(p);
2752 if (!used_usb_ports)
2753 return -1;
2755 p = strchr(devname, '.');
2756 if (!p)
2757 return -1;
2758 bus_num = strtoul(devname, NULL, 0);
2759 addr = strtoul(p + 1, NULL, 0);
2761 return usb_device_del_addr(bus_num, addr);
2764 void do_usb_add(const char *devname)
2766 usb_device_add(devname);
2769 void do_usb_del(const char *devname)
2771 usb_device_del(devname);
2774 void usb_info(void)
2776 USBDevice *dev;
2777 USBPort *port;
2778 const char *speed_str;
2780 if (!usb_enabled) {
2781 term_printf("USB support not enabled\n");
2782 return;
2785 for (port = used_usb_ports; port; port = port->next) {
2786 dev = port->dev;
2787 if (!dev)
2788 continue;
2789 switch(dev->speed) {
2790 case USB_SPEED_LOW:
2791 speed_str = "1.5";
2792 break;
2793 case USB_SPEED_FULL:
2794 speed_str = "12";
2795 break;
2796 case USB_SPEED_HIGH:
2797 speed_str = "480";
2798 break;
2799 default:
2800 speed_str = "?";
2801 break;
2803 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2804 0, dev->addr, speed_str, dev->devname);
2808 /***********************************************************/
2809 /* PCMCIA/Cardbus */
2811 static struct pcmcia_socket_entry_s {
2812 struct pcmcia_socket_s *socket;
2813 struct pcmcia_socket_entry_s *next;
2814 } *pcmcia_sockets = 0;
2816 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2818 struct pcmcia_socket_entry_s *entry;
2820 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2821 entry->socket = socket;
2822 entry->next = pcmcia_sockets;
2823 pcmcia_sockets = entry;
2826 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2828 struct pcmcia_socket_entry_s *entry, **ptr;
2830 ptr = &pcmcia_sockets;
2831 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2832 if (entry->socket == socket) {
2833 *ptr = entry->next;
2834 qemu_free(entry);
2838 void pcmcia_info(void)
2840 struct pcmcia_socket_entry_s *iter;
2841 if (!pcmcia_sockets)
2842 term_printf("No PCMCIA sockets\n");
2844 for (iter = pcmcia_sockets; iter; iter = iter->next)
2845 term_printf("%s: %s\n", iter->socket->slot_string,
2846 iter->socket->attached ? iter->socket->card_string :
2847 "Empty");
2850 /***********************************************************/
2851 /* dumb display */
2853 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2857 static void dumb_resize(DisplayState *ds, int w, int h)
2861 static void dumb_display_init(DisplayState *ds)
2863 ds->data = NULL;
2864 ds->linesize = 0;
2865 ds->depth = 0;
2866 ds->dpy_update = dumb_update;
2867 ds->dpy_resize = dumb_resize;
2868 ds->dpy_refresh = NULL;
2869 ds->gui_timer_interval = 0;
2870 ds->idle = 1;
2873 /***********************************************************/
2874 /* I/O handling */
2876 #define MAX_IO_HANDLERS 64
2878 typedef struct IOHandlerRecord {
2879 int fd;
2880 IOCanRWHandler *fd_read_poll;
2881 IOHandler *fd_read;
2882 IOHandler *fd_write;
2883 int deleted;
2884 void *opaque;
2885 /* temporary data */
2886 struct pollfd *ufd;
2887 struct IOHandlerRecord *next;
2888 } IOHandlerRecord;
2890 static IOHandlerRecord *first_io_handler;
2892 /* XXX: fd_read_poll should be suppressed, but an API change is
2893 necessary in the character devices to suppress fd_can_read(). */
2894 int qemu_set_fd_handler2(int fd,
2895 IOCanRWHandler *fd_read_poll,
2896 IOHandler *fd_read,
2897 IOHandler *fd_write,
2898 void *opaque)
2900 IOHandlerRecord **pioh, *ioh;
2902 if (!fd_read && !fd_write) {
2903 pioh = &first_io_handler;
2904 for(;;) {
2905 ioh = *pioh;
2906 if (ioh == NULL)
2907 break;
2908 if (ioh->fd == fd) {
2909 ioh->deleted = 1;
2910 break;
2912 pioh = &ioh->next;
2914 } else {
2915 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2916 if (ioh->fd == fd)
2917 goto found;
2919 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2920 if (!ioh)
2921 return -1;
2922 ioh->next = first_io_handler;
2923 first_io_handler = ioh;
2924 found:
2925 ioh->fd = fd;
2926 ioh->fd_read_poll = fd_read_poll;
2927 ioh->fd_read = fd_read;
2928 ioh->fd_write = fd_write;
2929 ioh->opaque = opaque;
2930 ioh->deleted = 0;
2932 main_loop_break();
2933 return 0;
2936 int qemu_set_fd_handler(int fd,
2937 IOHandler *fd_read,
2938 IOHandler *fd_write,
2939 void *opaque)
2941 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2944 #ifdef _WIN32
2945 /***********************************************************/
2946 /* Polling handling */
2948 typedef struct PollingEntry {
2949 PollingFunc *func;
2950 void *opaque;
2951 struct PollingEntry *next;
2952 } PollingEntry;
2954 static PollingEntry *first_polling_entry;
2956 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2958 PollingEntry **ppe, *pe;
2959 pe = qemu_mallocz(sizeof(PollingEntry));
2960 if (!pe)
2961 return -1;
2962 pe->func = func;
2963 pe->opaque = opaque;
2964 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2965 *ppe = pe;
2966 return 0;
2969 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2971 PollingEntry **ppe, *pe;
2972 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2973 pe = *ppe;
2974 if (pe->func == func && pe->opaque == opaque) {
2975 *ppe = pe->next;
2976 qemu_free(pe);
2977 break;
2982 /***********************************************************/
2983 /* Wait objects support */
2984 typedef struct WaitObjects {
2985 int num;
2986 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2987 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2988 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2989 } WaitObjects;
2991 static WaitObjects wait_objects = {0};
2993 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2995 WaitObjects *w = &wait_objects;
2997 if (w->num >= MAXIMUM_WAIT_OBJECTS)
2998 return -1;
2999 w->events[w->num] = handle;
3000 w->func[w->num] = func;
3001 w->opaque[w->num] = opaque;
3002 w->num++;
3003 return 0;
3006 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3008 int i, found;
3009 WaitObjects *w = &wait_objects;
3011 found = 0;
3012 for (i = 0; i < w->num; i++) {
3013 if (w->events[i] == handle)
3014 found = 1;
3015 if (found) {
3016 w->events[i] = w->events[i + 1];
3017 w->func[i] = w->func[i + 1];
3018 w->opaque[i] = w->opaque[i + 1];
3021 if (found)
3022 w->num--;
3024 #endif
3026 #define SELF_ANNOUNCE_ROUNDS 5
3027 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
3028 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
3029 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
3031 static int announce_self_create(uint8_t *buf,
3032 uint8_t *mac_addr)
3034 uint32_t magic = EXPERIMENTAL_MAGIC;
3035 uint16_t proto = htons(ETH_P_EXPERIMENTAL);
3037 /* FIXME: should we send a different packet (arp/rarp/ping)? */
3039 memset(buf, 0xff, 6); /* h_dst */
3040 memcpy(buf + 6, mac_addr, 6); /* h_src */
3041 memcpy(buf + 12, &proto, 2); /* h_proto */
3042 memcpy(buf + 14, &magic, 4); /* magic */
3044 return 18; /* len */
3047 void qemu_announce_self(void)
3049 int i, j, len;
3050 VLANState *vlan;
3051 VLANClientState *vc;
3052 uint8_t buf[256];
3054 for (i = 0; i < nb_nics; i++) {
3055 len = announce_self_create(buf, nd_table[i].macaddr);
3056 vlan = nd_table[i].vlan;
3057 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3058 for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
3059 vc->fd_read(vc->opaque, buf, len);
3064 /***********************************************************/
3065 /* savevm/loadvm support */
3067 #define IO_BUF_SIZE 32768
3069 struct QEMUFile {
3070 QEMUFilePutBufferFunc *put_buffer;
3071 QEMUFileGetBufferFunc *get_buffer;
3072 QEMUFileCloseFunc *close;
3073 QEMUFileRateLimit *rate_limit;
3074 void *opaque;
3075 int is_write;
3077 int64_t buf_offset; /* start of buffer when writing, end of buffer
3078 when reading */
3079 int buf_index;
3080 int buf_size; /* 0 when writing */
3081 uint8_t buf[IO_BUF_SIZE];
3083 int has_error;
3086 typedef struct QEMUFileSocket
3088 int fd;
3089 QEMUFile *file;
3090 } QEMUFileSocket;
3092 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
3094 QEMUFileSocket *s = opaque;
3095 ssize_t len;
3097 do {
3098 len = recv(s->fd, buf, size, 0);
3099 } while (len == -1 && socket_error() == EINTR);
3101 if (len == -1)
3102 len = -socket_error();
3104 return len;
3107 static int socket_close(void *opaque)
3109 QEMUFileSocket *s = opaque;
3110 qemu_free(s);
3111 return 0;
3114 QEMUFile *qemu_fopen_socket(int fd)
3116 QEMUFileSocket *s = qemu_mallocz(sizeof(QEMUFileSocket));
3118 if (s == NULL)
3119 return NULL;
3121 s->fd = fd;
3122 s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, socket_close, NULL);
3123 return s->file;
3126 typedef struct QEMUFileStdio
3128 FILE *outfile;
3129 } QEMUFileStdio;
3131 static int file_put_buffer(void *opaque, const uint8_t *buf,
3132 int64_t pos, int size)
3134 QEMUFileStdio *s = opaque;
3135 fseek(s->outfile, pos, SEEK_SET);
3136 fwrite(buf, 1, size, s->outfile);
3137 return size;
3140 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
3142 QEMUFileStdio *s = opaque;
3143 fseek(s->outfile, pos, SEEK_SET);
3144 return fread(buf, 1, size, s->outfile);
3147 static int file_close(void *opaque)
3149 QEMUFileStdio *s = opaque;
3150 fclose(s->outfile);
3151 qemu_free(s);
3152 return 0;
3155 QEMUFile *qemu_fopen(const char *filename, const char *mode)
3157 QEMUFileStdio *s;
3159 s = qemu_mallocz(sizeof(QEMUFileStdio));
3160 if (!s)
3161 return NULL;
3163 s->outfile = fopen(filename, mode);
3164 if (!s->outfile)
3165 goto fail;
3167 if (!strcmp(mode, "wb"))
3168 return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
3169 else if (!strcmp(mode, "rb"))
3170 return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
3172 fail:
3173 if (s->outfile)
3174 fclose(s->outfile);
3175 qemu_free(s);
3176 return NULL;
3179 typedef struct QEMUFileBdrv
3181 BlockDriverState *bs;
3182 int64_t base_offset;
3183 } QEMUFileBdrv;
3185 static int bdrv_put_buffer(void *opaque, const uint8_t *buf,
3186 int64_t pos, int size)
3188 QEMUFileBdrv *s = opaque;
3189 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
3190 return size;
3193 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
3195 QEMUFileBdrv *s = opaque;
3196 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
3199 static int bdrv_fclose(void *opaque)
3201 QEMUFileBdrv *s = opaque;
3202 qemu_free(s);
3203 return 0;
3206 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
3208 QEMUFileBdrv *s;
3210 s = qemu_mallocz(sizeof(QEMUFileBdrv));
3211 if (!s)
3212 return NULL;
3214 s->bs = bs;
3215 s->base_offset = offset;
3217 if (is_writable)
3218 return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
3220 return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
3223 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
3224 QEMUFileGetBufferFunc *get_buffer,
3225 QEMUFileCloseFunc *close,
3226 QEMUFileRateLimit *rate_limit)
3228 QEMUFile *f;
3230 f = qemu_mallocz(sizeof(QEMUFile));
3231 if (!f)
3232 return NULL;
3234 f->opaque = opaque;
3235 f->put_buffer = put_buffer;
3236 f->get_buffer = get_buffer;
3237 f->close = close;
3238 f->rate_limit = rate_limit;
3239 f->is_write = 0;
3241 return f;
3244 int qemu_file_has_error(QEMUFile *f)
3246 return f->has_error;
3249 void qemu_fflush(QEMUFile *f)
3251 if (!f->put_buffer)
3252 return;
3254 if (f->is_write && f->buf_index > 0) {
3255 int len;
3257 len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
3258 if (len > 0)
3259 f->buf_offset += f->buf_index;
3260 else
3261 f->has_error = 1;
3262 f->buf_index = 0;
3266 static void qemu_fill_buffer(QEMUFile *f)
3268 int len;
3270 if (!f->get_buffer)
3271 return;
3273 if (f->is_write)
3274 abort();
3276 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
3277 if (len > 0) {
3278 f->buf_index = 0;
3279 f->buf_size = len;
3280 f->buf_offset += len;
3281 } else if (len != -EAGAIN)
3282 f->has_error = 1;
3285 int qemu_fclose(QEMUFile *f)
3287 int ret = 0;
3288 qemu_fflush(f);
3289 if (f->close)
3290 ret = f->close(f->opaque);
3291 qemu_free(f);
3292 return ret;
3295 void qemu_file_put_notify(QEMUFile *f)
3297 f->put_buffer(f->opaque, NULL, 0, 0);
3300 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3302 int l;
3304 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3305 fprintf(stderr,
3306 "Attempted to write to buffer while read buffer is not empty\n");
3307 abort();
3310 while (!f->has_error && size > 0) {
3311 l = IO_BUF_SIZE - f->buf_index;
3312 if (l > size)
3313 l = size;
3314 memcpy(f->buf + f->buf_index, buf, l);
3315 f->is_write = 1;
3316 f->buf_index += l;
3317 buf += l;
3318 size -= l;
3319 if (f->buf_index >= IO_BUF_SIZE)
3320 qemu_fflush(f);
3324 void qemu_put_byte(QEMUFile *f, int v)
3326 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
3327 fprintf(stderr,
3328 "Attempted to write to buffer while read buffer is not empty\n");
3329 abort();
3332 f->buf[f->buf_index++] = v;
3333 f->is_write = 1;
3334 if (f->buf_index >= IO_BUF_SIZE)
3335 qemu_fflush(f);
3338 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
3340 int size, l;
3342 if (f->is_write)
3343 abort();
3345 size = size1;
3346 while (size > 0) {
3347 l = f->buf_size - f->buf_index;
3348 if (l == 0) {
3349 qemu_fill_buffer(f);
3350 l = f->buf_size - f->buf_index;
3351 if (l == 0)
3352 break;
3354 if (l > size)
3355 l = size;
3356 memcpy(buf, f->buf + f->buf_index, l);
3357 f->buf_index += l;
3358 buf += l;
3359 size -= l;
3361 return size1 - size;
3364 int qemu_get_byte(QEMUFile *f)
3366 if (f->is_write)
3367 abort();
3369 if (f->buf_index >= f->buf_size) {
3370 qemu_fill_buffer(f);
3371 if (f->buf_index >= f->buf_size)
3372 return 0;
3374 return f->buf[f->buf_index++];
3377 int64_t qemu_ftell(QEMUFile *f)
3379 return f->buf_offset - f->buf_size + f->buf_index;
3382 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3384 if (whence == SEEK_SET) {
3385 /* nothing to do */
3386 } else if (whence == SEEK_CUR) {
3387 pos += qemu_ftell(f);
3388 } else {
3389 /* SEEK_END not supported */
3390 return -1;
3392 if (f->put_buffer) {
3393 qemu_fflush(f);
3394 f->buf_offset = pos;
3395 } else {
3396 f->buf_offset = pos;
3397 f->buf_index = 0;
3398 f->buf_size = 0;
3400 return pos;
3403 int qemu_file_rate_limit(QEMUFile *f)
3405 if (f->rate_limit)
3406 return f->rate_limit(f->opaque);
3408 return 0;
3411 void qemu_put_be16(QEMUFile *f, unsigned int v)
3413 qemu_put_byte(f, v >> 8);
3414 qemu_put_byte(f, v);
3417 void qemu_put_be32(QEMUFile *f, unsigned int v)
3419 qemu_put_byte(f, v >> 24);
3420 qemu_put_byte(f, v >> 16);
3421 qemu_put_byte(f, v >> 8);
3422 qemu_put_byte(f, v);
3425 void qemu_put_be64(QEMUFile *f, uint64_t v)
3427 qemu_put_be32(f, v >> 32);
3428 qemu_put_be32(f, v);
3431 unsigned int qemu_get_be16(QEMUFile *f)
3433 unsigned int v;
3434 v = qemu_get_byte(f) << 8;
3435 v |= qemu_get_byte(f);
3436 return v;
3439 unsigned int qemu_get_be32(QEMUFile *f)
3441 unsigned int v;
3442 v = qemu_get_byte(f) << 24;
3443 v |= qemu_get_byte(f) << 16;
3444 v |= qemu_get_byte(f) << 8;
3445 v |= qemu_get_byte(f);
3446 return v;
3449 uint64_t qemu_get_be64(QEMUFile *f)
3451 uint64_t v;
3452 v = (uint64_t)qemu_get_be32(f) << 32;
3453 v |= qemu_get_be32(f);
3454 return v;
3457 typedef struct SaveStateEntry {
3458 char idstr[256];
3459 int instance_id;
3460 int version_id;
3461 int section_id;
3462 SaveLiveStateHandler *save_live_state;
3463 SaveStateHandler *save_state;
3464 LoadStateHandler *load_state;
3465 void *opaque;
3466 struct SaveStateEntry *next;
3467 } SaveStateEntry;
3469 static SaveStateEntry *first_se;
3471 /* TODO: Individual devices generally have very little idea about the rest
3472 of the system, so instance_id should be removed/replaced.
3473 Meanwhile pass -1 as instance_id if you do not already have a clearly
3474 distinguishing id for all instances of your device class. */
3475 int register_savevm_live(const char *idstr,
3476 int instance_id,
3477 int version_id,
3478 SaveLiveStateHandler *save_live_state,
3479 SaveStateHandler *save_state,
3480 LoadStateHandler *load_state,
3481 void *opaque)
3483 SaveStateEntry *se, **pse;
3484 static int global_section_id;
3486 se = qemu_malloc(sizeof(SaveStateEntry));
3487 if (!se)
3488 return -1;
3489 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3490 se->instance_id = (instance_id == -1) ? 0 : instance_id;
3491 se->version_id = version_id;
3492 se->section_id = global_section_id++;
3493 se->save_live_state = save_live_state;
3494 se->save_state = save_state;
3495 se->load_state = load_state;
3496 se->opaque = opaque;
3497 se->next = NULL;
3499 /* add at the end of list */
3500 pse = &first_se;
3501 while (*pse != NULL) {
3502 if (instance_id == -1
3503 && strcmp(se->idstr, (*pse)->idstr) == 0
3504 && se->instance_id <= (*pse)->instance_id)
3505 se->instance_id = (*pse)->instance_id + 1;
3506 pse = &(*pse)->next;
3508 *pse = se;
3509 return 0;
3512 int register_savevm(const char *idstr,
3513 int instance_id,
3514 int version_id,
3515 SaveStateHandler *save_state,
3516 LoadStateHandler *load_state,
3517 void *opaque)
3519 return register_savevm_live(idstr, instance_id, version_id,
3520 NULL, save_state, load_state, opaque);
3523 #define QEMU_VM_FILE_MAGIC 0x5145564d
3524 #define QEMU_VM_FILE_VERSION_COMPAT 0x00000002
3525 #define QEMU_VM_FILE_VERSION 0x00000003
3527 #define QEMU_VM_EOF 0x00
3528 #define QEMU_VM_SECTION_START 0x01
3529 #define QEMU_VM_SECTION_PART 0x02
3530 #define QEMU_VM_SECTION_END 0x03
3531 #define QEMU_VM_SECTION_FULL 0x04
3533 int qemu_savevm_state_begin(QEMUFile *f)
3535 SaveStateEntry *se;
3537 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3538 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3540 for (se = first_se; se != NULL; se = se->next) {
3541 int len;
3543 if (se->save_live_state == NULL)
3544 continue;
3546 /* Section type */
3547 qemu_put_byte(f, QEMU_VM_SECTION_START);
3548 qemu_put_be32(f, se->section_id);
3550 /* ID string */
3551 len = strlen(se->idstr);
3552 qemu_put_byte(f, len);
3553 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3555 qemu_put_be32(f, se->instance_id);
3556 qemu_put_be32(f, se->version_id);
3558 se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
3561 if (qemu_file_has_error(f))
3562 return -EIO;
3564 return 0;
3567 int qemu_savevm_state_iterate(QEMUFile *f)
3569 SaveStateEntry *se;
3570 int ret = 1;
3572 for (se = first_se; se != NULL; se = se->next) {
3573 if (se->save_live_state == NULL)
3574 continue;
3576 /* Section type */
3577 qemu_put_byte(f, QEMU_VM_SECTION_PART);
3578 qemu_put_be32(f, se->section_id);
3580 ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
3583 if (ret)
3584 return 1;
3586 if (qemu_file_has_error(f))
3587 return -EIO;
3589 return 0;
3592 int qemu_savevm_state_complete(QEMUFile *f)
3594 SaveStateEntry *se;
3596 for (se = first_se; se != NULL; se = se->next) {
3597 if (se->save_live_state == NULL)
3598 continue;
3600 /* Section type */
3601 qemu_put_byte(f, QEMU_VM_SECTION_END);
3602 qemu_put_be32(f, se->section_id);
3604 se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
3607 for(se = first_se; se != NULL; se = se->next) {
3608 int len;
3610 if (se->save_state == NULL)
3611 continue;
3613 /* Section type */
3614 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
3615 qemu_put_be32(f, se->section_id);
3617 /* ID string */
3618 len = strlen(se->idstr);
3619 qemu_put_byte(f, len);
3620 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3622 qemu_put_be32(f, se->instance_id);
3623 qemu_put_be32(f, se->version_id);
3625 se->save_state(f, se->opaque);
3628 qemu_put_byte(f, QEMU_VM_EOF);
3630 if (qemu_file_has_error(f))
3631 return -EIO;
3633 return 0;
3636 int qemu_savevm_state(QEMUFile *f)
3638 int saved_vm_running;
3639 int ret;
3641 saved_vm_running = vm_running;
3642 vm_stop(0);
3644 bdrv_flush_all();
3646 ret = qemu_savevm_state_begin(f);
3647 if (ret < 0)
3648 goto out;
3650 do {
3651 ret = qemu_savevm_state_iterate(f);
3652 if (ret < 0)
3653 goto out;
3654 } while (ret == 0);
3656 ret = qemu_savevm_state_complete(f);
3658 out:
3659 if (qemu_file_has_error(f))
3660 ret = -EIO;
3662 if (!ret && saved_vm_running)
3663 vm_start();
3665 return ret;
3668 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3670 SaveStateEntry *se;
3672 for(se = first_se; se != NULL; se = se->next) {
3673 if (!strcmp(se->idstr, idstr) &&
3674 instance_id == se->instance_id)
3675 return se;
3677 return NULL;
3680 typedef struct LoadStateEntry {
3681 SaveStateEntry *se;
3682 int section_id;
3683 int version_id;
3684 struct LoadStateEntry *next;
3685 } LoadStateEntry;
3687 static int qemu_loadvm_state_v2(QEMUFile *f)
3689 SaveStateEntry *se;
3690 int len, ret, instance_id, record_len, version_id;
3691 int64_t total_len, end_pos, cur_pos;
3692 char idstr[256];
3694 total_len = qemu_get_be64(f);
3695 end_pos = total_len + qemu_ftell(f);
3696 for(;;) {
3697 if (qemu_ftell(f) >= end_pos)
3698 break;
3699 len = qemu_get_byte(f);
3700 qemu_get_buffer(f, (uint8_t *)idstr, len);
3701 idstr[len] = '\0';
3702 instance_id = qemu_get_be32(f);
3703 version_id = qemu_get_be32(f);
3704 record_len = qemu_get_be32(f);
3705 cur_pos = qemu_ftell(f);
3706 se = find_se(idstr, instance_id);
3707 if (!se) {
3708 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3709 instance_id, idstr);
3710 } else {
3711 ret = se->load_state(f, se->opaque, version_id);
3712 if (ret < 0) {
3713 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3714 instance_id, idstr);
3715 goto the_end;
3718 /* always seek to exact end of record */
3719 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3721 ret = 0;
3722 the_end:
3723 return ret;
3726 int qemu_loadvm_state(QEMUFile *f)
3728 LoadStateEntry *first_le = NULL;
3729 uint8_t section_type;
3730 unsigned int v;
3731 int ret;
3733 v = qemu_get_be32(f);
3734 if (v != QEMU_VM_FILE_MAGIC)
3735 return -EINVAL;
3737 v = qemu_get_be32(f);
3738 if (v == QEMU_VM_FILE_VERSION_COMPAT)
3739 return qemu_loadvm_state_v2(f);
3740 if (v != QEMU_VM_FILE_VERSION)
3741 return -ENOTSUP;
3743 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
3744 uint32_t instance_id, version_id, section_id;
3745 LoadStateEntry *le;
3746 SaveStateEntry *se;
3747 char idstr[257];
3748 int len;
3750 switch (section_type) {
3751 case QEMU_VM_SECTION_START:
3752 case QEMU_VM_SECTION_FULL:
3753 /* Read section start */
3754 section_id = qemu_get_be32(f);
3755 len = qemu_get_byte(f);
3756 qemu_get_buffer(f, (uint8_t *)idstr, len);
3757 idstr[len] = 0;
3758 instance_id = qemu_get_be32(f);
3759 version_id = qemu_get_be32(f);
3761 /* Find savevm section */
3762 se = find_se(idstr, instance_id);
3763 if (se == NULL) {
3764 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
3765 ret = -EINVAL;
3766 goto out;
3769 /* Validate version */
3770 if (version_id > se->version_id) {
3771 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
3772 version_id, idstr, se->version_id);
3773 ret = -EINVAL;
3774 goto out;
3777 /* Add entry */
3778 le = qemu_mallocz(sizeof(*le));
3779 if (le == NULL) {
3780 ret = -ENOMEM;
3781 goto out;
3784 le->se = se;
3785 le->section_id = section_id;
3786 le->version_id = version_id;
3787 le->next = first_le;
3788 first_le = le;
3790 le->se->load_state(f, le->se->opaque, le->version_id);
3791 break;
3792 case QEMU_VM_SECTION_PART:
3793 case QEMU_VM_SECTION_END:
3794 section_id = qemu_get_be32(f);
3796 for (le = first_le; le && le->section_id != section_id; le = le->next);
3797 if (le == NULL) {
3798 fprintf(stderr, "Unknown savevm section %d\n", section_id);
3799 ret = -EINVAL;
3800 goto out;
3803 le->se->load_state(f, le->se->opaque, le->version_id);
3804 break;
3805 default:
3806 fprintf(stderr, "Unknown savevm section type %d\n", section_type);
3807 ret = -EINVAL;
3808 goto out;
3812 ret = 0;
3814 out:
3815 while (first_le) {
3816 LoadStateEntry *le = first_le;
3817 first_le = first_le->next;
3818 qemu_free(le);
3821 if (qemu_file_has_error(f))
3822 ret = -EIO;
3824 return ret;
3827 /* device can contain snapshots */
3828 static int bdrv_can_snapshot(BlockDriverState *bs)
3830 return (bs &&
3831 !bdrv_is_removable(bs) &&
3832 !bdrv_is_read_only(bs));
3835 /* device must be snapshots in order to have a reliable snapshot */
3836 static int bdrv_has_snapshot(BlockDriverState *bs)
3838 return (bs &&
3839 !bdrv_is_removable(bs) &&
3840 !bdrv_is_read_only(bs));
3843 static BlockDriverState *get_bs_snapshots(void)
3845 BlockDriverState *bs;
3846 int i;
3848 if (bs_snapshots)
3849 return bs_snapshots;
3850 for(i = 0; i <= nb_drives; i++) {
3851 bs = drives_table[i].bdrv;
3852 if (bdrv_can_snapshot(bs))
3853 goto ok;
3855 return NULL;
3857 bs_snapshots = bs;
3858 return bs;
3861 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
3862 const char *name)
3864 QEMUSnapshotInfo *sn_tab, *sn;
3865 int nb_sns, i, ret;
3867 ret = -ENOENT;
3868 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3869 if (nb_sns < 0)
3870 return ret;
3871 for(i = 0; i < nb_sns; i++) {
3872 sn = &sn_tab[i];
3873 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
3874 *sn_info = *sn;
3875 ret = 0;
3876 break;
3879 qemu_free(sn_tab);
3880 return ret;
3883 void do_savevm(const char *name)
3885 BlockDriverState *bs, *bs1;
3886 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
3887 int must_delete, ret, i;
3888 BlockDriverInfo bdi1, *bdi = &bdi1;
3889 QEMUFile *f;
3890 int saved_vm_running;
3891 #ifdef _WIN32
3892 struct _timeb tb;
3893 #else
3894 struct timeval tv;
3895 #endif
3897 bs = get_bs_snapshots();
3898 if (!bs) {
3899 term_printf("No block device can accept snapshots\n");
3900 return;
3903 /* ??? Should this occur after vm_stop? */
3904 qemu_aio_flush();
3906 saved_vm_running = vm_running;
3907 vm_stop(0);
3909 must_delete = 0;
3910 if (name) {
3911 ret = bdrv_snapshot_find(bs, old_sn, name);
3912 if (ret >= 0) {
3913 must_delete = 1;
3916 memset(sn, 0, sizeof(*sn));
3917 if (must_delete) {
3918 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
3919 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
3920 } else {
3921 if (name)
3922 pstrcpy(sn->name, sizeof(sn->name), name);
3925 /* fill auxiliary fields */
3926 #ifdef _WIN32
3927 _ftime(&tb);
3928 sn->date_sec = tb.time;
3929 sn->date_nsec = tb.millitm * 1000000;
3930 #else
3931 gettimeofday(&tv, NULL);
3932 sn->date_sec = tv.tv_sec;
3933 sn->date_nsec = tv.tv_usec * 1000;
3934 #endif
3935 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
3937 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3938 term_printf("Device %s does not support VM state snapshots\n",
3939 bdrv_get_device_name(bs));
3940 goto the_end;
3943 /* save the VM state */
3944 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
3945 if (!f) {
3946 term_printf("Could not open VM state file\n");
3947 goto the_end;
3949 ret = qemu_savevm_state(f);
3950 sn->vm_state_size = qemu_ftell(f);
3951 qemu_fclose(f);
3952 if (ret < 0) {
3953 term_printf("Error %d while writing VM\n", ret);
3954 goto the_end;
3957 /* create the snapshots */
3959 for(i = 0; i < nb_drives; i++) {
3960 bs1 = drives_table[i].bdrv;
3961 if (bdrv_has_snapshot(bs1)) {
3962 if (must_delete) {
3963 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
3964 if (ret < 0) {
3965 term_printf("Error while deleting snapshot on '%s'\n",
3966 bdrv_get_device_name(bs1));
3969 ret = bdrv_snapshot_create(bs1, sn);
3970 if (ret < 0) {
3971 term_printf("Error while creating snapshot on '%s'\n",
3972 bdrv_get_device_name(bs1));
3977 the_end:
3978 if (saved_vm_running)
3979 vm_start();
3982 void do_loadvm(const char *name)
3984 BlockDriverState *bs, *bs1;
3985 BlockDriverInfo bdi1, *bdi = &bdi1;
3986 QEMUFile *f;
3987 int i, ret;
3988 int saved_vm_running;
3990 bs = get_bs_snapshots();
3991 if (!bs) {
3992 term_printf("No block device supports snapshots\n");
3993 return;
3996 /* Flush all IO requests so they don't interfere with the new state. */
3997 qemu_aio_flush();
3999 saved_vm_running = vm_running;
4000 vm_stop(0);
4002 for(i = 0; i <= nb_drives; i++) {
4003 bs1 = drives_table[i].bdrv;
4004 if (bdrv_has_snapshot(bs1)) {
4005 ret = bdrv_snapshot_goto(bs1, name);
4006 if (ret < 0) {
4007 if (bs != bs1)
4008 term_printf("Warning: ");
4009 switch(ret) {
4010 case -ENOTSUP:
4011 term_printf("Snapshots not supported on device '%s'\n",
4012 bdrv_get_device_name(bs1));
4013 break;
4014 case -ENOENT:
4015 term_printf("Could not find snapshot '%s' on device '%s'\n",
4016 name, bdrv_get_device_name(bs1));
4017 break;
4018 default:
4019 term_printf("Error %d while activating snapshot on '%s'\n",
4020 ret, bdrv_get_device_name(bs1));
4021 break;
4023 /* fatal on snapshot block device */
4024 if (bs == bs1)
4025 goto the_end;
4030 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4031 term_printf("Device %s does not support VM state snapshots\n",
4032 bdrv_get_device_name(bs));
4033 return;
4036 /* restore the VM state */
4037 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4038 if (!f) {
4039 term_printf("Could not open VM state file\n");
4040 goto the_end;
4042 ret = qemu_loadvm_state(f);
4043 qemu_fclose(f);
4044 if (ret < 0) {
4045 term_printf("Error %d while loading VM state\n", ret);
4047 the_end:
4048 if (saved_vm_running)
4049 vm_start();
4052 void do_delvm(const char *name)
4054 BlockDriverState *bs, *bs1;
4055 int i, ret;
4057 bs = get_bs_snapshots();
4058 if (!bs) {
4059 term_printf("No block device supports snapshots\n");
4060 return;
4063 for(i = 0; i <= nb_drives; i++) {
4064 bs1 = drives_table[i].bdrv;
4065 if (bdrv_has_snapshot(bs1)) {
4066 ret = bdrv_snapshot_delete(bs1, name);
4067 if (ret < 0) {
4068 if (ret == -ENOTSUP)
4069 term_printf("Snapshots not supported on device '%s'\n",
4070 bdrv_get_device_name(bs1));
4071 else
4072 term_printf("Error %d while deleting snapshot on '%s'\n",
4073 ret, bdrv_get_device_name(bs1));
4079 void do_info_snapshots(void)
4081 BlockDriverState *bs, *bs1;
4082 QEMUSnapshotInfo *sn_tab, *sn;
4083 int nb_sns, i;
4084 char buf[256];
4086 bs = get_bs_snapshots();
4087 if (!bs) {
4088 term_printf("No available block device supports snapshots\n");
4089 return;
4091 term_printf("Snapshot devices:");
4092 for(i = 0; i <= nb_drives; i++) {
4093 bs1 = drives_table[i].bdrv;
4094 if (bdrv_has_snapshot(bs1)) {
4095 if (bs == bs1)
4096 term_printf(" %s", bdrv_get_device_name(bs1));
4099 term_printf("\n");
4101 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4102 if (nb_sns < 0) {
4103 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4104 return;
4106 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4107 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4108 for(i = 0; i < nb_sns; i++) {
4109 sn = &sn_tab[i];
4110 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4112 qemu_free(sn_tab);
4115 /***********************************************************/
4116 /* ram save/restore */
4118 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4120 int v;
4122 v = qemu_get_byte(f);
4123 switch(v) {
4124 case 0:
4125 if (qemu_get_buffer(f, buf, len) != len)
4126 return -EIO;
4127 break;
4128 case 1:
4129 v = qemu_get_byte(f);
4130 memset(buf, v, len);
4131 break;
4132 default:
4133 return -EINVAL;
4136 if (qemu_file_has_error(f))
4137 return -EIO;
4139 return 0;
4142 static int ram_load_v1(QEMUFile *f, void *opaque)
4144 int ret;
4145 ram_addr_t i;
4147 if (qemu_get_be32(f) != phys_ram_size)
4148 return -EINVAL;
4149 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4150 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
4151 continue;
4152 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4153 if (ret)
4154 return ret;
4156 return 0;
4159 #define BDRV_HASH_BLOCK_SIZE 1024
4160 #define IOBUF_SIZE 4096
4161 #define RAM_CBLOCK_MAGIC 0xfabe
4163 typedef struct RamDecompressState {
4164 z_stream zstream;
4165 QEMUFile *f;
4166 uint8_t buf[IOBUF_SIZE];
4167 } RamDecompressState;
4169 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
4171 int ret;
4172 memset(s, 0, sizeof(*s));
4173 s->f = f;
4174 ret = inflateInit(&s->zstream);
4175 if (ret != Z_OK)
4176 return -1;
4177 return 0;
4180 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
4182 int ret, clen;
4184 s->zstream.avail_out = len;
4185 s->zstream.next_out = buf;
4186 while (s->zstream.avail_out > 0) {
4187 if (s->zstream.avail_in == 0) {
4188 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
4189 return -1;
4190 clen = qemu_get_be16(s->f);
4191 if (clen > IOBUF_SIZE)
4192 return -1;
4193 qemu_get_buffer(s->f, s->buf, clen);
4194 s->zstream.avail_in = clen;
4195 s->zstream.next_in = s->buf;
4197 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
4198 if (ret != Z_OK && ret != Z_STREAM_END) {
4199 return -1;
4202 return 0;
4205 static void ram_decompress_close(RamDecompressState *s)
4207 inflateEnd(&s->zstream);
4210 #define RAM_SAVE_FLAG_FULL 0x01
4211 #define RAM_SAVE_FLAG_COMPRESS 0x02
4212 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
4213 #define RAM_SAVE_FLAG_PAGE 0x08
4214 #define RAM_SAVE_FLAG_EOS 0x10
4216 static int is_dup_page(uint8_t *page, uint8_t ch)
4218 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
4219 uint32_t *array = (uint32_t *)page;
4220 int i;
4222 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
4223 if (array[i] != val)
4224 return 0;
4227 return 1;
4230 static int ram_save_block(QEMUFile *f)
4232 static ram_addr_t current_addr = 0;
4233 ram_addr_t saved_addr = current_addr;
4234 ram_addr_t addr = 0;
4235 int found = 0;
4237 while (addr < phys_ram_size) {
4238 if (kvm_enabled() && current_addr == 0)
4239 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
4240 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
4241 uint8_t ch;
4243 cpu_physical_memory_reset_dirty(current_addr,
4244 current_addr + TARGET_PAGE_SIZE,
4245 MIGRATION_DIRTY_FLAG);
4247 ch = *(phys_ram_base + current_addr);
4249 if (is_dup_page(phys_ram_base + current_addr, ch)) {
4250 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
4251 qemu_put_byte(f, ch);
4252 } else {
4253 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
4254 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
4257 found = 1;
4258 break;
4260 addr += TARGET_PAGE_SIZE;
4261 current_addr = (saved_addr + addr) % phys_ram_size;
4264 return found;
4267 static ram_addr_t ram_save_threshold = 10;
4269 static ram_addr_t ram_save_remaining(void)
4271 ram_addr_t addr;
4272 ram_addr_t count = 0;
4274 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4275 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4276 count++;
4279 return count;
4282 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
4284 ram_addr_t addr;
4286 if (stage == 1) {
4287 /* Make sure all dirty bits are set */
4288 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
4289 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
4290 cpu_physical_memory_set_dirty(addr);
4293 /* Enable dirty memory tracking */
4294 cpu_physical_memory_set_dirty_tracking(1);
4296 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
4299 while (!qemu_file_rate_limit(f)) {
4300 int ret;
4302 ret = ram_save_block(f);
4303 if (ret == 0) /* no more blocks */
4304 break;
4307 /* try transferring iterative blocks of memory */
4309 if (stage == 3) {
4310 cpu_physical_memory_set_dirty_tracking(0);
4312 /* flush all remaining blocks regardless of rate limiting */
4313 while (ram_save_block(f) != 0);
4316 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
4318 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
4321 static int ram_load_dead(QEMUFile *f, void *opaque)
4323 RamDecompressState s1, *s = &s1;
4324 uint8_t buf[10];
4325 ram_addr_t i;
4327 if (ram_decompress_open(s, f) < 0)
4328 return -EINVAL;
4329 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
4330 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
4331 continue;
4332 if (ram_decompress_buf(s, buf, 1) < 0) {
4333 fprintf(stderr, "Error while reading ram block header\n");
4334 goto error;
4336 if (buf[0] == 0) {
4337 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
4338 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
4339 goto error;
4341 } else {
4342 error:
4343 printf("Error block header\n");
4344 return -EINVAL;
4347 ram_decompress_close(s);
4349 return 0;
4352 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4354 ram_addr_t addr;
4355 int flags;
4357 if (version_id == 1)
4358 return ram_load_v1(f, opaque);
4360 if (version_id == 2) {
4361 if (qemu_get_be32(f) != phys_ram_size)
4362 return -EINVAL;
4363 return ram_load_dead(f, opaque);
4366 if (version_id != 3)
4367 return -EINVAL;
4369 do {
4370 addr = qemu_get_be64(f);
4372 flags = addr & ~TARGET_PAGE_MASK;
4373 addr &= TARGET_PAGE_MASK;
4375 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
4376 if (addr != phys_ram_size)
4377 return -EINVAL;
4380 if (flags & RAM_SAVE_FLAG_FULL) {
4381 if (ram_load_dead(f, opaque) < 0)
4382 return -EINVAL;
4385 if (flags & RAM_SAVE_FLAG_COMPRESS) {
4386 uint8_t ch = qemu_get_byte(f);
4387 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
4388 } else if (flags & RAM_SAVE_FLAG_PAGE)
4389 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
4390 } while (!(flags & RAM_SAVE_FLAG_EOS));
4392 return 0;
4395 /***********************************************************/
4396 /* bottom halves (can be seen as timers which expire ASAP) */
4398 struct QEMUBH {
4399 QEMUBHFunc *cb;
4400 void *opaque;
4401 int scheduled;
4402 int idle;
4403 int deleted;
4404 QEMUBH *next;
4407 static QEMUBH *first_bh = NULL;
4409 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
4411 QEMUBH *bh;
4412 bh = qemu_mallocz(sizeof(QEMUBH));
4413 if (!bh)
4414 return NULL;
4415 bh->cb = cb;
4416 bh->opaque = opaque;
4417 bh->next = first_bh;
4418 first_bh = bh;
4419 return bh;
4422 int qemu_bh_poll(void)
4424 QEMUBH *bh, **bhp;
4425 int ret;
4427 ret = 0;
4428 for (bh = first_bh; bh; bh = bh->next) {
4429 if (!bh->deleted && bh->scheduled) {
4430 bh->scheduled = 0;
4431 if (!bh->idle)
4432 ret = 1;
4433 bh->idle = 0;
4434 bh->cb(bh->opaque);
4438 /* remove deleted bhs */
4439 bhp = &first_bh;
4440 while (*bhp) {
4441 bh = *bhp;
4442 if (bh->deleted) {
4443 *bhp = bh->next;
4444 qemu_free(bh);
4445 } else
4446 bhp = &bh->next;
4449 return ret;
4452 void qemu_bh_schedule_idle(QEMUBH *bh)
4454 if (bh->scheduled)
4455 return;
4456 bh->scheduled = 1;
4457 bh->idle = 1;
4460 void qemu_bh_schedule(QEMUBH *bh)
4462 CPUState *env = cpu_single_env;
4463 if (bh->scheduled)
4464 return;
4465 bh->scheduled = 1;
4466 bh->idle = 0;
4467 /* stop the currently executing CPU to execute the BH ASAP */
4468 if (env) {
4469 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4471 main_loop_break();
4474 void qemu_bh_cancel(QEMUBH *bh)
4476 bh->scheduled = 0;
4479 void qemu_bh_delete(QEMUBH *bh)
4481 bh->scheduled = 0;
4482 bh->deleted = 1;
4485 static void qemu_bh_update_timeout(int *timeout)
4487 QEMUBH *bh;
4489 for (bh = first_bh; bh; bh = bh->next) {
4490 if (!bh->deleted && bh->scheduled) {
4491 if (bh->idle) {
4492 /* idle bottom halves will be polled at least
4493 * every 10ms */
4494 *timeout = MIN(10, *timeout);
4495 } else {
4496 /* non-idle bottom halves will be executed
4497 * immediately */
4498 *timeout = 0;
4499 break;
4505 /***********************************************************/
4506 /* machine registration */
4508 static QEMUMachine *first_machine = NULL;
4509 QEMUMachine *current_machine = NULL;
4511 int qemu_register_machine(QEMUMachine *m)
4513 QEMUMachine **pm;
4514 pm = &first_machine;
4515 while (*pm != NULL)
4516 pm = &(*pm)->next;
4517 m->next = NULL;
4518 *pm = m;
4519 return 0;
4522 static QEMUMachine *find_machine(const char *name)
4524 QEMUMachine *m;
4526 for(m = first_machine; m != NULL; m = m->next) {
4527 if (!strcmp(m->name, name))
4528 return m;
4530 return NULL;
4533 /***********************************************************/
4534 /* main execution loop */
4536 static void gui_update(void *opaque)
4538 DisplayState *ds = opaque;
4539 ds->dpy_refresh(ds);
4540 qemu_mod_timer(ds->gui_timer,
4541 (ds->gui_timer_interval ?
4542 ds->gui_timer_interval :
4543 GUI_REFRESH_INTERVAL)
4544 + qemu_get_clock(rt_clock));
4547 struct vm_change_state_entry {
4548 VMChangeStateHandler *cb;
4549 void *opaque;
4550 LIST_ENTRY (vm_change_state_entry) entries;
4553 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4555 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4556 void *opaque)
4558 VMChangeStateEntry *e;
4560 e = qemu_mallocz(sizeof (*e));
4561 if (!e)
4562 return NULL;
4564 e->cb = cb;
4565 e->opaque = opaque;
4566 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4567 return e;
4570 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4572 LIST_REMOVE (e, entries);
4573 qemu_free (e);
4576 static void vm_state_notify(int running)
4578 VMChangeStateEntry *e;
4580 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4581 e->cb(e->opaque, running);
4585 /* XXX: support several handlers */
4586 static VMStopHandler *vm_stop_cb;
4587 static void *vm_stop_opaque;
4589 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4591 vm_stop_cb = cb;
4592 vm_stop_opaque = opaque;
4593 return 0;
4596 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4598 vm_stop_cb = NULL;
4601 void vm_start(void)
4603 if (!vm_running) {
4604 cpu_enable_ticks();
4605 vm_running = 1;
4606 vm_state_notify(1);
4607 qemu_rearm_alarm_timer(alarm_timer);
4611 void vm_stop(int reason)
4613 if (vm_running) {
4614 cpu_disable_ticks();
4615 vm_running = 0;
4616 if (reason != 0) {
4617 if (vm_stop_cb) {
4618 vm_stop_cb(vm_stop_opaque, reason);
4621 vm_state_notify(0);
4625 /* reset/shutdown handler */
4627 typedef struct QEMUResetEntry {
4628 QEMUResetHandler *func;
4629 void *opaque;
4630 struct QEMUResetEntry *next;
4631 } QEMUResetEntry;
4633 static QEMUResetEntry *first_reset_entry;
4634 static int reset_requested;
4635 static int shutdown_requested;
4636 static int powerdown_requested;
4638 int qemu_shutdown_requested(void)
4640 int r = shutdown_requested;
4641 shutdown_requested = 0;
4642 return r;
4645 int qemu_reset_requested(void)
4647 int r = reset_requested;
4648 reset_requested = 0;
4649 return r;
4652 int qemu_powerdown_requested(void)
4654 int r = powerdown_requested;
4655 powerdown_requested = 0;
4656 return r;
4659 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4661 QEMUResetEntry **pre, *re;
4663 pre = &first_reset_entry;
4664 while (*pre != NULL)
4665 pre = &(*pre)->next;
4666 re = qemu_mallocz(sizeof(QEMUResetEntry));
4667 re->func = func;
4668 re->opaque = opaque;
4669 re->next = NULL;
4670 *pre = re;
4673 void qemu_system_reset(void)
4675 QEMUResetEntry *re;
4677 /* reset all devices */
4678 for(re = first_reset_entry; re != NULL; re = re->next) {
4679 re->func(re->opaque);
4683 void qemu_system_reset_request(void)
4685 if (no_reboot) {
4686 shutdown_requested = 1;
4687 } else {
4688 reset_requested = 1;
4690 if (cpu_single_env)
4691 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4692 main_loop_break();
4695 void qemu_system_shutdown_request(void)
4697 shutdown_requested = 1;
4698 if (cpu_single_env)
4699 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4702 void qemu_system_powerdown_request(void)
4704 powerdown_requested = 1;
4705 if (cpu_single_env)
4706 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4709 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
4710 struct timeval *tv)
4712 int ret;
4714 /* KVM holds a mutex while QEMU code is running, we need hooks to
4715 release the mutex whenever QEMU code sleeps. */
4717 kvm_sleep_begin();
4719 ret = select(max_fd, rfds, wfds, xfds, tv);
4721 kvm_sleep_end();
4723 return ret;
4726 #ifdef _WIN32
4727 void host_main_loop_wait(int *timeout)
4729 int ret, ret2, i;
4730 PollingEntry *pe;
4733 /* XXX: need to suppress polling by better using win32 events */
4734 ret = 0;
4735 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4736 ret |= pe->func(pe->opaque);
4738 if (ret == 0) {
4739 int err;
4740 WaitObjects *w = &wait_objects;
4742 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4743 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4744 if (w->func[ret - WAIT_OBJECT_0])
4745 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4747 /* Check for additional signaled events */
4748 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4750 /* Check if event is signaled */
4751 ret2 = WaitForSingleObject(w->events[i], 0);
4752 if(ret2 == WAIT_OBJECT_0) {
4753 if (w->func[i])
4754 w->func[i](w->opaque[i]);
4755 } else if (ret2 == WAIT_TIMEOUT) {
4756 } else {
4757 err = GetLastError();
4758 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4761 } else if (ret == WAIT_TIMEOUT) {
4762 } else {
4763 err = GetLastError();
4764 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4768 *timeout = 0;
4770 #else
4771 void host_main_loop_wait(int *timeout)
4774 #endif
4776 void main_loop_wait(int timeout)
4778 IOHandlerRecord *ioh;
4779 fd_set rfds, wfds, xfds;
4780 int ret, nfds;
4781 struct timeval tv;
4783 qemu_bh_update_timeout(&timeout);
4785 host_main_loop_wait(&timeout);
4787 /* poll any events */
4788 /* XXX: separate device handlers from system ones */
4789 nfds = -1;
4790 FD_ZERO(&rfds);
4791 FD_ZERO(&wfds);
4792 FD_ZERO(&xfds);
4793 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4794 if (ioh->deleted)
4795 continue;
4796 if (ioh->fd_read &&
4797 (!ioh->fd_read_poll ||
4798 ioh->fd_read_poll(ioh->opaque) != 0)) {
4799 FD_SET(ioh->fd, &rfds);
4800 if (ioh->fd > nfds)
4801 nfds = ioh->fd;
4803 if (ioh->fd_write) {
4804 FD_SET(ioh->fd, &wfds);
4805 if (ioh->fd > nfds)
4806 nfds = ioh->fd;
4810 tv.tv_sec = timeout / 1000;
4811 tv.tv_usec = (timeout % 1000) * 1000;
4813 #if defined(CONFIG_SLIRP)
4814 if (slirp_is_inited()) {
4815 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4817 #endif
4818 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4819 if (ret > 0) {
4820 IOHandlerRecord **pioh;
4822 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4823 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4824 ioh->fd_read(ioh->opaque);
4825 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4826 FD_CLR(ioh->fd, &rfds);
4828 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4829 ioh->fd_write(ioh->opaque);
4833 /* remove deleted IO handlers */
4834 pioh = &first_io_handler;
4835 while (*pioh) {
4836 ioh = *pioh;
4837 if (ioh->deleted) {
4838 *pioh = ioh->next;
4839 qemu_free(ioh);
4840 } else
4841 pioh = &ioh->next;
4844 #if defined(CONFIG_SLIRP)
4845 if (slirp_is_inited()) {
4846 if (ret < 0) {
4847 FD_ZERO(&rfds);
4848 FD_ZERO(&wfds);
4849 FD_ZERO(&xfds);
4851 slirp_select_poll(&rfds, &wfds, &xfds);
4853 #endif
4855 /* Check bottom-halves last in case any of the earlier events triggered
4856 them. */
4857 qemu_bh_poll();
4861 static int main_loop(void)
4863 int ret, timeout;
4864 #ifdef CONFIG_PROFILER
4865 int64_t ti;
4866 #endif
4867 CPUState *env;
4870 if (kvm_enabled()) {
4871 kvm_main_loop();
4872 cpu_disable_ticks();
4873 return 0;
4876 cur_cpu = first_cpu;
4877 next_cpu = cur_cpu->next_cpu ?: first_cpu;
4878 for(;;) {
4879 if (vm_running) {
4881 for(;;) {
4882 /* get next cpu */
4883 env = next_cpu;
4884 #ifdef CONFIG_PROFILER
4885 ti = profile_getclock();
4886 #endif
4887 if (use_icount) {
4888 int64_t count;
4889 int decr;
4890 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4891 env->icount_decr.u16.low = 0;
4892 env->icount_extra = 0;
4893 count = qemu_next_deadline();
4894 count = (count + (1 << icount_time_shift) - 1)
4895 >> icount_time_shift;
4896 qemu_icount += count;
4897 decr = (count > 0xffff) ? 0xffff : count;
4898 count -= decr;
4899 env->icount_decr.u16.low = decr;
4900 env->icount_extra = count;
4902 ret = cpu_exec(env);
4903 #ifdef CONFIG_PROFILER
4904 qemu_time += profile_getclock() - ti;
4905 #endif
4906 if (use_icount) {
4907 /* Fold pending instructions back into the
4908 instruction counter, and clear the interrupt flag. */
4909 qemu_icount -= (env->icount_decr.u16.low
4910 + env->icount_extra);
4911 env->icount_decr.u32 = 0;
4912 env->icount_extra = 0;
4914 next_cpu = env->next_cpu ?: first_cpu;
4915 if (event_pending && likely(ret != EXCP_DEBUG)) {
4916 ret = EXCP_INTERRUPT;
4917 event_pending = 0;
4918 break;
4920 if (ret == EXCP_HLT) {
4921 /* Give the next CPU a chance to run. */
4922 cur_cpu = env;
4923 continue;
4925 if (ret != EXCP_HALTED)
4926 break;
4927 /* all CPUs are halted ? */
4928 if (env == cur_cpu)
4929 break;
4931 cur_cpu = env;
4933 if (shutdown_requested) {
4934 ret = EXCP_INTERRUPT;
4935 if (no_shutdown) {
4936 vm_stop(0);
4937 no_shutdown = 0;
4939 else
4940 break;
4942 if (reset_requested) {
4943 reset_requested = 0;
4944 qemu_system_reset();
4945 if (kvm_enabled())
4946 kvm_load_registers(env);
4947 ret = EXCP_INTERRUPT;
4949 if (powerdown_requested) {
4950 powerdown_requested = 0;
4951 qemu_system_powerdown();
4952 ret = EXCP_INTERRUPT;
4954 if (unlikely(ret == EXCP_DEBUG)) {
4955 vm_stop(EXCP_DEBUG);
4957 /* If all cpus are halted then wait until the next IRQ */
4958 /* XXX: use timeout computed from timers */
4959 if (ret == EXCP_HALTED) {
4960 if (use_icount) {
4961 int64_t add;
4962 int64_t delta;
4963 /* Advance virtual time to the next event. */
4964 if (use_icount == 1) {
4965 /* When not using an adaptive execution frequency
4966 we tend to get badly out of sync with real time,
4967 so just delay for a reasonable amount of time. */
4968 delta = 0;
4969 } else {
4970 delta = cpu_get_icount() - cpu_get_clock();
4972 if (delta > 0) {
4973 /* If virtual time is ahead of real time then just
4974 wait for IO. */
4975 timeout = (delta / 1000000) + 1;
4976 } else {
4977 /* Wait for either IO to occur or the next
4978 timer event. */
4979 add = qemu_next_deadline();
4980 /* We advance the timer before checking for IO.
4981 Limit the amount we advance so that early IO
4982 activity won't get the guest too far ahead. */
4983 if (add > 10000000)
4984 add = 10000000;
4985 delta += add;
4986 add = (add + (1 << icount_time_shift) - 1)
4987 >> icount_time_shift;
4988 qemu_icount += add;
4989 timeout = delta / 1000000;
4990 if (timeout < 0)
4991 timeout = 0;
4993 } else {
4994 timeout = 5000;
4996 } else {
4997 timeout = 0;
4999 } else {
5000 if (shutdown_requested) {
5001 ret = EXCP_INTERRUPT;
5002 break;
5004 timeout = 5000;
5006 #ifdef CONFIG_PROFILER
5007 ti = profile_getclock();
5008 #endif
5009 main_loop_wait(timeout);
5010 #ifdef CONFIG_PROFILER
5011 dev_time += profile_getclock() - ti;
5012 #endif
5014 cpu_disable_ticks();
5015 return ret;
5018 static void help(int exitcode)
5020 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
5021 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
5022 "usage: %s [options] [disk_image]\n"
5023 "\n"
5024 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5025 "\n"
5026 "Standard options:\n"
5027 "-M machine select emulated machine (-M ? for list)\n"
5028 "-cpu cpu select CPU (-cpu ? for list)\n"
5029 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5030 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5031 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5032 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5033 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
5034 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
5035 " [,cache=writethrough|writeback|none][,format=f]\n"
5036 " [,boot=on|off]\n"
5037 " use 'file' as a drive image\n"
5038 "-mtdblock file use 'file' as on-board Flash memory image\n"
5039 "-sd file use 'file' as SecureDigital card image\n"
5040 "-pflash file use 'file' as a parallel flash image\n"
5041 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
5042 "-snapshot write to temporary files instead of disk image files\n"
5043 #ifdef CONFIG_SDL
5044 "-no-frame open SDL window without a frame and window decorations\n"
5045 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
5046 "-no-quit disable SDL window close capability\n"
5047 #endif
5048 #ifdef TARGET_I386
5049 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5050 #endif
5051 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5052 "-smp n set the number of CPUs to 'n' [default=1]\n"
5053 "-nographic disable graphical output and redirect serial I/Os to console\n"
5054 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
5055 #ifndef _WIN32
5056 "-k language use keyboard layout (for example \"fr\" for French)\n"
5057 #endif
5058 #ifdef HAS_AUDIO
5059 "-audio-help print list of audio drivers and their options\n"
5060 "-soundhw c1,... enable audio support\n"
5061 " and only specified sound cards (comma separated list)\n"
5062 " use -soundhw ? to get the list of supported cards\n"
5063 " use -soundhw all to enable all of them\n"
5064 #endif
5065 "-vga [std|cirrus|vmware]\n"
5066 " select video card type\n"
5067 "-localtime set the real time clock to local time [default=utc]\n"
5068 "-full-screen start in full screen\n"
5069 #ifdef TARGET_I386
5070 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5071 #endif
5072 "-usb enable the USB driver (will be the default soon)\n"
5073 "-usbdevice name add the host or guest USB device 'name'\n"
5074 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5075 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5076 #endif
5077 "-name string set the name of the guest\n"
5078 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
5079 "\n"
5080 "Network options:\n"
5081 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5082 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5083 #ifdef CONFIG_SLIRP
5084 "-net user[,vlan=n][,hostname=host]\n"
5085 " connect the user mode network stack to VLAN 'n' and send\n"
5086 " hostname 'host' to DHCP clients\n"
5087 #endif
5088 #ifdef _WIN32
5089 "-net tap[,vlan=n],ifname=name\n"
5090 " connect the host TAP network interface to VLAN 'n'\n"
5091 #else
5092 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
5093 " connect the host TAP network interface to VLAN 'n' and use the\n"
5094 " network scripts 'file' (default=%s)\n"
5095 " and 'dfile' (default=%s);\n"
5096 " use '[down]script=no' to disable script execution;\n"
5097 " use 'fd=h' to connect to an already opened TAP interface\n"
5098 #endif
5099 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5100 " connect the vlan 'n' to another VLAN using a socket connection\n"
5101 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5102 " connect the vlan 'n' to multicast maddr and port\n"
5103 #ifdef CONFIG_VDE
5104 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
5105 " connect the vlan 'n' to port 'n' of a vde switch running\n"
5106 " on host and listening for incoming connections on 'socketpath'.\n"
5107 " Use group 'groupname' and mode 'octalmode' to change default\n"
5108 " ownership and permissions for communication port.\n"
5109 #endif
5110 "-net none use it alone to have zero network devices; if no -net option\n"
5111 " is provided, the default is '-net nic -net user'\n"
5112 "\n"
5113 "-bt hci,null Dumb bluetooth HCI - doesn't respond to commands\n"
5114 "-bt hci,host[:id]\n"
5115 " Use host's HCI with the given name\n"
5116 "-bt hci[,vlan=n]\n"
5117 " Emulate a standard HCI in virtual scatternet 'n'\n"
5118 "-bt vhci[,vlan=n]\n"
5119 " Add host computer to virtual scatternet 'n' using VHCI\n"
5120 "-bt device:dev[,vlan=n]\n"
5121 " Emulate a bluetooth device 'dev' in scatternet 'n'\n"
5122 "\n"
5123 #ifdef CONFIG_SLIRP
5124 "-tftp dir allow tftp access to files in dir [-net user]\n"
5125 "-bootp file advertise file in BOOTP replies\n"
5126 #ifndef _WIN32
5127 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5128 #endif
5129 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5130 " redirect TCP or UDP connections from host to guest [-net user]\n"
5131 #endif
5132 "\n"
5133 "Linux boot specific:\n"
5134 "-kernel bzImage use 'bzImage' as kernel image\n"
5135 "-append cmdline use 'cmdline' as kernel command line\n"
5136 "-initrd file use 'file' as initial ram disk\n"
5137 "\n"
5138 "Debug/Expert options:\n"
5139 "-monitor dev redirect the monitor to char device 'dev'\n"
5140 "-serial dev redirect the serial port to char device 'dev'\n"
5141 "-parallel dev redirect the parallel port to char device 'dev'\n"
5142 "-pidfile file Write PID to 'file'\n"
5143 "-S freeze CPU at startup (use 'c' to start execution)\n"
5144 "-s wait gdb connection to port\n"
5145 "-p port set gdb connection port [default=%s]\n"
5146 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5147 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5148 " translation (t=none or lba) (usually qemu can guess them)\n"
5149 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
5150 #ifdef USE_KQEMU
5151 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5152 "-no-kqemu disable KQEMU kernel module usage\n"
5153 #endif
5154 #ifdef CONFIG_KVM
5155 "-enable-kvm enable KVM full virtualization support\n"
5156 #endif
5157 #ifdef USE_KVM
5158 #ifndef NO_CPU_EMULATION
5159 "-no-kvm disable KVM hardware virtualization\n"
5160 #endif
5161 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
5162 "-no-kvm-pit disable KVM kernel mode PIT\n"
5163 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5164 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
5165 " expose a PCI device to the guest OS.\n"
5166 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
5167 " 'string' is used in log output.\n"
5168 #endif
5169 #endif
5170 #ifdef TARGET_I386
5171 "-no-acpi disable ACPI\n"
5172 #endif
5173 #ifdef CONFIG_CURSES
5174 "-curses use a curses/ncurses interface instead of SDL\n"
5175 #endif
5176 "-no-reboot exit instead of rebooting\n"
5177 "-no-shutdown stop before shutdown\n"
5178 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
5179 "-vnc display start a VNC server on display\n"
5180 #ifndef _WIN32
5181 "-daemonize daemonize QEMU after initializing\n"
5182 #endif
5183 "-tdf inject timer interrupts that got lost\n"
5184 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
5185 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
5186 "-option-rom rom load a file, rom, into the option ROM space\n"
5187 #ifdef TARGET_SPARC
5188 "-prom-env variable=value set OpenBIOS nvram variables\n"
5189 #endif
5190 "-clock force the use of the given methods for timer alarm.\n"
5191 " To see what timers are available use -clock ?\n"
5192 "-startdate select initial date of the clock\n"
5193 "-icount [N|auto]\n"
5194 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
5195 "\n"
5196 "During emulation, the following keys are useful:\n"
5197 "ctrl-alt-f toggle full screen\n"
5198 "ctrl-alt-n switch to virtual console 'n'\n"
5199 "ctrl-alt toggle mouse and keyboard grab\n"
5200 "\n"
5201 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5203 "qemu",
5204 DEFAULT_RAM_SIZE,
5205 #ifndef _WIN32
5206 DEFAULT_NETWORK_SCRIPT,
5207 DEFAULT_NETWORK_DOWN_SCRIPT,
5208 #endif
5209 DEFAULT_GDBSTUB_PORT,
5210 "/tmp/qemu.log");
5211 exit(exitcode);
5214 #define HAS_ARG 0x0001
5216 enum {
5217 QEMU_OPTION_h,
5219 QEMU_OPTION_M,
5220 QEMU_OPTION_cpu,
5221 QEMU_OPTION_fda,
5222 QEMU_OPTION_fdb,
5223 QEMU_OPTION_hda,
5224 QEMU_OPTION_hdb,
5225 QEMU_OPTION_hdc,
5226 QEMU_OPTION_hdd,
5227 QEMU_OPTION_drive,
5228 QEMU_OPTION_cdrom,
5229 QEMU_OPTION_mtdblock,
5230 QEMU_OPTION_sd,
5231 QEMU_OPTION_pflash,
5232 QEMU_OPTION_boot,
5233 QEMU_OPTION_snapshot,
5234 #ifdef TARGET_I386
5235 QEMU_OPTION_no_fd_bootchk,
5236 #endif
5237 QEMU_OPTION_m,
5238 QEMU_OPTION_nographic,
5239 QEMU_OPTION_portrait,
5240 #ifdef HAS_AUDIO
5241 QEMU_OPTION_audio_help,
5242 QEMU_OPTION_soundhw,
5243 #endif
5245 QEMU_OPTION_net,
5246 QEMU_OPTION_tftp,
5247 QEMU_OPTION_bootp,
5248 QEMU_OPTION_smb,
5249 QEMU_OPTION_redir,
5250 QEMU_OPTION_bt,
5252 QEMU_OPTION_kernel,
5253 QEMU_OPTION_append,
5254 QEMU_OPTION_initrd,
5256 QEMU_OPTION_S,
5257 QEMU_OPTION_s,
5258 QEMU_OPTION_p,
5259 QEMU_OPTION_d,
5260 QEMU_OPTION_hdachs,
5261 QEMU_OPTION_L,
5262 QEMU_OPTION_bios,
5263 QEMU_OPTION_k,
5264 QEMU_OPTION_localtime,
5265 QEMU_OPTION_g,
5266 QEMU_OPTION_vga,
5267 QEMU_OPTION_echr,
5268 QEMU_OPTION_monitor,
5269 QEMU_OPTION_serial,
5270 QEMU_OPTION_parallel,
5271 QEMU_OPTION_loadvm,
5272 QEMU_OPTION_full_screen,
5273 QEMU_OPTION_no_frame,
5274 QEMU_OPTION_alt_grab,
5275 QEMU_OPTION_no_quit,
5276 QEMU_OPTION_pidfile,
5277 QEMU_OPTION_no_kqemu,
5278 QEMU_OPTION_kernel_kqemu,
5279 QEMU_OPTION_enable_kvm,
5280 QEMU_OPTION_win2k_hack,
5281 QEMU_OPTION_usb,
5282 QEMU_OPTION_usbdevice,
5283 QEMU_OPTION_smp,
5284 QEMU_OPTION_vnc,
5285 QEMU_OPTION_no_acpi,
5286 QEMU_OPTION_curses,
5287 QEMU_OPTION_no_kvm,
5288 QEMU_OPTION_no_kvm_irqchip,
5289 QEMU_OPTION_no_kvm_pit,
5290 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5291 QEMU_OPTION_pcidevice,
5292 #endif
5293 QEMU_OPTION_no_reboot,
5294 QEMU_OPTION_no_shutdown,
5295 QEMU_OPTION_show_cursor,
5296 QEMU_OPTION_daemonize,
5297 QEMU_OPTION_option_rom,
5298 QEMU_OPTION_semihosting,
5299 QEMU_OPTION_cpu_vendor,
5300 QEMU_OPTION_name,
5301 QEMU_OPTION_prom_env,
5302 QEMU_OPTION_old_param,
5303 QEMU_OPTION_clock,
5304 QEMU_OPTION_startdate,
5305 QEMU_OPTION_tb_size,
5306 QEMU_OPTION_icount,
5307 QEMU_OPTION_uuid,
5308 QEMU_OPTION_incoming,
5309 QEMU_OPTION_tdf,
5310 QEMU_OPTION_kvm_shadow_memory,
5311 QEMU_OPTION_mempath,
5314 typedef struct QEMUOption {
5315 const char *name;
5316 int flags;
5317 int index;
5318 } QEMUOption;
5320 static const QEMUOption qemu_options[] = {
5321 { "h", 0, QEMU_OPTION_h },
5322 { "help", 0, QEMU_OPTION_h },
5324 { "M", HAS_ARG, QEMU_OPTION_M },
5325 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
5326 { "fda", HAS_ARG, QEMU_OPTION_fda },
5327 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5328 { "hda", HAS_ARG, QEMU_OPTION_hda },
5329 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5330 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5331 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5332 { "drive", HAS_ARG, QEMU_OPTION_drive },
5333 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5334 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
5335 { "sd", HAS_ARG, QEMU_OPTION_sd },
5336 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
5337 { "boot", HAS_ARG, QEMU_OPTION_boot },
5338 { "snapshot", 0, QEMU_OPTION_snapshot },
5339 #ifdef TARGET_I386
5340 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5341 #endif
5342 { "m", HAS_ARG, QEMU_OPTION_m },
5343 { "nographic", 0, QEMU_OPTION_nographic },
5344 { "portrait", 0, QEMU_OPTION_portrait },
5345 { "k", HAS_ARG, QEMU_OPTION_k },
5346 #ifdef HAS_AUDIO
5347 { "audio-help", 0, QEMU_OPTION_audio_help },
5348 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5349 #endif
5351 { "net", HAS_ARG, QEMU_OPTION_net},
5352 #ifdef CONFIG_SLIRP
5353 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5354 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
5355 #ifndef _WIN32
5356 { "smb", HAS_ARG, QEMU_OPTION_smb },
5357 #endif
5358 { "redir", HAS_ARG, QEMU_OPTION_redir },
5359 #endif
5360 { "bt", HAS_ARG, QEMU_OPTION_bt },
5362 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5363 { "append", HAS_ARG, QEMU_OPTION_append },
5364 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5366 { "S", 0, QEMU_OPTION_S },
5367 { "s", 0, QEMU_OPTION_s },
5368 { "p", HAS_ARG, QEMU_OPTION_p },
5369 { "d", HAS_ARG, QEMU_OPTION_d },
5370 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5371 { "L", HAS_ARG, QEMU_OPTION_L },
5372 { "bios", HAS_ARG, QEMU_OPTION_bios },
5373 #ifdef USE_KQEMU
5374 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5375 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5376 #endif
5377 #ifdef CONFIG_KVM
5378 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
5379 #endif
5380 #ifdef USE_KVM
5381 #ifndef NO_CPU_EMULATION
5382 { "no-kvm", 0, QEMU_OPTION_no_kvm },
5383 #endif
5384 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
5385 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
5386 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5387 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
5388 #endif
5389 #endif
5390 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5391 { "g", 1, QEMU_OPTION_g },
5392 #endif
5393 { "localtime", 0, QEMU_OPTION_localtime },
5394 { "vga", HAS_ARG, QEMU_OPTION_vga },
5395 { "echr", HAS_ARG, QEMU_OPTION_echr },
5396 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
5397 { "serial", HAS_ARG, QEMU_OPTION_serial },
5398 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
5399 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5400 { "incoming", 1, QEMU_OPTION_incoming },
5401 { "full-screen", 0, QEMU_OPTION_full_screen },
5402 #ifdef CONFIG_SDL
5403 { "no-frame", 0, QEMU_OPTION_no_frame },
5404 { "alt-grab", 0, QEMU_OPTION_alt_grab },
5405 { "no-quit", 0, QEMU_OPTION_no_quit },
5406 #endif
5407 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5408 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5409 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5410 { "smp", HAS_ARG, QEMU_OPTION_smp },
5411 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5412 #ifdef CONFIG_CURSES
5413 { "curses", 0, QEMU_OPTION_curses },
5414 #endif
5415 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
5417 /* temporary options */
5418 { "usb", 0, QEMU_OPTION_usb },
5419 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5420 { "no-reboot", 0, QEMU_OPTION_no_reboot },
5421 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
5422 { "show-cursor", 0, QEMU_OPTION_show_cursor },
5423 { "daemonize", 0, QEMU_OPTION_daemonize },
5424 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
5425 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5426 { "semihosting", 0, QEMU_OPTION_semihosting },
5427 #endif
5428 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
5429 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
5430 { "name", HAS_ARG, QEMU_OPTION_name },
5431 #if defined(TARGET_SPARC)
5432 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
5433 #endif
5434 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
5435 #if defined(TARGET_ARM)
5436 { "old-param", 0, QEMU_OPTION_old_param },
5437 #endif
5438 { "clock", HAS_ARG, QEMU_OPTION_clock },
5439 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
5440 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
5441 { "icount", HAS_ARG, QEMU_OPTION_icount },
5442 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
5443 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
5444 { NULL },
5447 /* password input */
5449 int qemu_key_check(BlockDriverState *bs, const char *name)
5451 char password[256];
5452 int i;
5454 if (!bdrv_is_encrypted(bs))
5455 return 0;
5457 term_printf("%s is encrypted.\n", name);
5458 for(i = 0; i < 3; i++) {
5459 monitor_readline("Password: ", 1, password, sizeof(password));
5460 if (bdrv_set_key(bs, password) == 0)
5461 return 0;
5462 term_printf("invalid password\n");
5464 return -EPERM;
5467 static BlockDriverState *get_bdrv(int index)
5469 if (index > nb_drives)
5470 return NULL;
5471 return drives_table[index].bdrv;
5474 static void read_passwords(void)
5476 BlockDriverState *bs;
5477 int i;
5479 for(i = 0; i < 6; i++) {
5480 bs = get_bdrv(i);
5481 if (bs)
5482 qemu_key_check(bs, bdrv_get_device_name(bs));
5486 #ifdef HAS_AUDIO
5487 struct soundhw soundhw[] = {
5488 #ifdef HAS_AUDIO_CHOICE
5489 #if defined(TARGET_I386) || defined(TARGET_MIPS)
5491 "pcspk",
5492 "PC speaker",
5495 { .init_isa = pcspk_audio_init }
5497 #endif
5499 "sb16",
5500 "Creative Sound Blaster 16",
5503 { .init_isa = SB16_init }
5506 #ifdef CONFIG_CS4231A
5508 "cs4231a",
5509 "CS4231A",
5512 { .init_isa = cs4231a_init }
5514 #endif
5516 #ifdef CONFIG_ADLIB
5518 "adlib",
5519 #ifdef HAS_YMF262
5520 "Yamaha YMF262 (OPL3)",
5521 #else
5522 "Yamaha YM3812 (OPL2)",
5523 #endif
5526 { .init_isa = Adlib_init }
5528 #endif
5530 #ifdef CONFIG_GUS
5532 "gus",
5533 "Gravis Ultrasound GF1",
5536 { .init_isa = GUS_init }
5538 #endif
5540 #ifdef CONFIG_AC97
5542 "ac97",
5543 "Intel 82801AA AC97 Audio",
5546 { .init_pci = ac97_init }
5548 #endif
5551 "es1370",
5552 "ENSONIQ AudioPCI ES1370",
5555 { .init_pci = es1370_init }
5557 #endif
5559 { NULL, NULL, 0, 0, { NULL } }
5562 static void select_soundhw (const char *optarg)
5564 struct soundhw *c;
5566 if (*optarg == '?') {
5567 show_valid_cards:
5569 printf ("Valid sound card names (comma separated):\n");
5570 for (c = soundhw; c->name; ++c) {
5571 printf ("%-11s %s\n", c->name, c->descr);
5573 printf ("\n-soundhw all will enable all of the above\n");
5574 exit (*optarg != '?');
5576 else {
5577 size_t l;
5578 const char *p;
5579 char *e;
5580 int bad_card = 0;
5582 if (!strcmp (optarg, "all")) {
5583 for (c = soundhw; c->name; ++c) {
5584 c->enabled = 1;
5586 return;
5589 p = optarg;
5590 while (*p) {
5591 e = strchr (p, ',');
5592 l = !e ? strlen (p) : (size_t) (e - p);
5594 for (c = soundhw; c->name; ++c) {
5595 if (!strncmp (c->name, p, l)) {
5596 c->enabled = 1;
5597 break;
5601 if (!c->name) {
5602 if (l > 80) {
5603 fprintf (stderr,
5604 "Unknown sound card name (too big to show)\n");
5606 else {
5607 fprintf (stderr, "Unknown sound card name `%.*s'\n",
5608 (int) l, p);
5610 bad_card = 1;
5612 p += l + (e != NULL);
5615 if (bad_card)
5616 goto show_valid_cards;
5619 #endif
5621 static void select_vgahw (const char *p)
5623 const char *opts;
5625 if (strstart(p, "std", &opts)) {
5626 cirrus_vga_enabled = 0;
5627 vmsvga_enabled = 0;
5628 } else if (strstart(p, "cirrus", &opts)) {
5629 cirrus_vga_enabled = 1;
5630 vmsvga_enabled = 0;
5631 } else if (strstart(p, "vmware", &opts)) {
5632 cirrus_vga_enabled = 0;
5633 vmsvga_enabled = 1;
5634 } else {
5635 invalid_vga:
5636 fprintf(stderr, "Unknown vga type: %s\n", p);
5637 exit(1);
5639 while (*opts) {
5640 const char *nextopt;
5642 if (strstart(opts, ",retrace=", &nextopt)) {
5643 opts = nextopt;
5644 if (strstart(opts, "dumb", &nextopt))
5645 vga_retrace_method = VGA_RETRACE_DUMB;
5646 else if (strstart(opts, "precise", &nextopt))
5647 vga_retrace_method = VGA_RETRACE_PRECISE;
5648 else goto invalid_vga;
5649 } else goto invalid_vga;
5650 opts = nextopt;
5654 #ifdef _WIN32
5655 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5657 exit(STATUS_CONTROL_C_EXIT);
5658 return TRUE;
5660 #endif
5662 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
5664 int ret;
5666 if(strlen(str) != 36)
5667 return -1;
5669 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
5670 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
5671 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
5673 if(ret != 16)
5674 return -1;
5676 return 0;
5679 #define MAX_NET_CLIENTS 32
5681 static int saved_argc;
5682 static char **saved_argv;
5684 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
5686 *argc = saved_argc;
5687 *argv = saved_argv;
5688 *opt_daemonize = daemonize;
5689 *opt_incoming = incoming;
5693 static int gethugepagesize(void)
5695 int ret, fd;
5696 char buf[4096];
5697 char *needle = "Hugepagesize:";
5698 char *size;
5699 unsigned long hugepagesize;
5701 fd = open("/proc/meminfo", O_RDONLY);
5702 if (fd < 0) {
5703 perror("open");
5704 exit(0);
5707 ret = read(fd, buf, sizeof(buf));
5708 if (ret < 0) {
5709 perror("read");
5710 exit(0);
5713 size = strstr(buf, needle);
5714 if (!size)
5715 return 0;
5716 size += strlen(needle);
5717 hugepagesize = strtol(size, NULL, 0);
5718 return hugepagesize;
5721 void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
5723 char *filename;
5724 void *area;
5725 int fd;
5727 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
5728 return NULL;
5730 hpagesize = gethugepagesize() * 1024;
5731 if (!hpagesize)
5732 return NULL;
5734 fd = mkstemp(filename);
5735 if (fd < 0) {
5736 perror("mkstemp");
5737 free(filename);
5738 return NULL;
5740 unlink(filename);
5741 free(filename);
5743 memory = (memory+hpagesize-1) & ~(hpagesize-1);
5746 * ftruncate is not supported by hugetlbfs in older
5747 * hosts, so don't bother checking for errors.
5748 * If anything goes wrong with it under other filesystems,
5749 * mmap will fail.
5751 ftruncate(fd, memory);
5753 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
5754 if (area == MAP_FAILED) {
5755 perror("mmap");
5756 close(fd);
5757 return NULL;
5760 *len = memory;
5761 return area;
5764 void *qemu_alloc_physram(unsigned long memory)
5766 void *area = NULL;
5767 unsigned long map_len = memory;
5769 #ifdef USE_KVM
5770 if (mem_path)
5771 area = alloc_mem_area(memory, &map_len, mem_path);
5772 #endif
5773 if (!area)
5774 area = qemu_vmalloc(memory);
5775 #ifdef USE_KVM
5776 if (kvm_setup_guest_memory(area, map_len))
5777 area = NULL;
5778 #endif
5779 return area;
5782 #ifndef _WIN32
5784 static void termsig_handler(int signal)
5786 qemu_system_shutdown_request();
5789 static void termsig_setup(void)
5791 struct sigaction act;
5793 memset(&act, 0, sizeof(act));
5794 act.sa_handler = termsig_handler;
5795 sigaction(SIGINT, &act, NULL);
5796 sigaction(SIGHUP, &act, NULL);
5797 sigaction(SIGTERM, &act, NULL);
5800 #endif
5802 int main(int argc, char **argv)
5804 #ifdef CONFIG_GDBSTUB
5805 int use_gdbstub;
5806 const char *gdbstub_port;
5807 #endif
5808 uint32_t boot_devices_bitmap = 0;
5809 int i;
5810 int snapshot, linux_boot, net_boot;
5811 const char *initrd_filename;
5812 const char *kernel_filename, *kernel_cmdline;
5813 const char *boot_devices = "";
5814 DisplayState *ds = &display_state;
5815 int cyls, heads, secs, translation;
5816 const char *net_clients[MAX_NET_CLIENTS];
5817 int nb_net_clients;
5818 const char *bt_opts[MAX_BT_CMDLINE];
5819 int nb_bt_opts;
5820 int hda_index;
5821 int optind;
5822 const char *r, *optarg;
5823 CharDriverState *monitor_hd;
5824 const char *monitor_device;
5825 const char *serial_devices[MAX_SERIAL_PORTS];
5826 int serial_device_index;
5827 const char *parallel_devices[MAX_PARALLEL_PORTS];
5828 int parallel_device_index;
5829 const char *loadvm = NULL;
5830 QEMUMachine *machine;
5831 const char *cpu_model;
5832 const char *usb_devices[MAX_USB_CMDLINE];
5833 int usb_devices_index;
5834 int fds[2];
5835 int tb_size;
5836 const char *pid_file = NULL;
5837 int autostart;
5838 const char *incoming = NULL;
5840 LIST_INIT (&vm_change_state_head);
5841 #ifndef _WIN32
5843 struct sigaction act;
5844 sigfillset(&act.sa_mask);
5845 act.sa_flags = 0;
5846 act.sa_handler = SIG_IGN;
5847 sigaction(SIGPIPE, &act, NULL);
5849 #else
5850 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5851 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5852 QEMU to run on a single CPU */
5854 HANDLE h;
5855 DWORD mask, smask;
5856 int i;
5857 h = GetCurrentProcess();
5858 if (GetProcessAffinityMask(h, &mask, &smask)) {
5859 for(i = 0; i < 32; i++) {
5860 if (mask & (1 << i))
5861 break;
5863 if (i != 32) {
5864 mask = 1 << i;
5865 SetProcessAffinityMask(h, mask);
5869 #endif
5871 register_machines();
5872 machine = first_machine;
5873 cpu_model = NULL;
5874 initrd_filename = NULL;
5875 ram_size = 0;
5876 vga_ram_size = VGA_RAM_SIZE;
5877 #ifdef CONFIG_GDBSTUB
5878 use_gdbstub = 0;
5879 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5880 #endif
5881 snapshot = 0;
5882 nographic = 0;
5883 curses = 0;
5884 kernel_filename = NULL;
5885 kernel_cmdline = "";
5886 cyls = heads = secs = 0;
5887 translation = BIOS_ATA_TRANSLATION_AUTO;
5888 monitor_device = "vc";
5890 serial_devices[0] = "vc:80Cx24C";
5891 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5892 serial_devices[i] = NULL;
5893 serial_device_index = 0;
5895 parallel_devices[0] = "vc:640x480";
5896 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5897 parallel_devices[i] = NULL;
5898 parallel_device_index = 0;
5900 usb_devices_index = 0;
5901 assigned_devices_index = 0;
5903 nb_net_clients = 0;
5904 nb_bt_opts = 0;
5905 nb_drives = 0;
5906 nb_drives_opt = 0;
5907 hda_index = -1;
5909 nb_nics = 0;
5911 tb_size = 0;
5912 autostart= 1;
5914 optind = 1;
5915 for(;;) {
5916 if (optind >= argc)
5917 break;
5918 r = argv[optind];
5919 if (r[0] != '-') {
5920 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5921 } else {
5922 const QEMUOption *popt;
5924 optind++;
5925 /* Treat --foo the same as -foo. */
5926 if (r[1] == '-')
5927 r++;
5928 popt = qemu_options;
5929 for(;;) {
5930 if (!popt->name) {
5931 fprintf(stderr, "%s: invalid option -- '%s'\n",
5932 argv[0], r);
5933 exit(1);
5935 if (!strcmp(popt->name, r + 1))
5936 break;
5937 popt++;
5939 if (popt->flags & HAS_ARG) {
5940 if (optind >= argc) {
5941 fprintf(stderr, "%s: option '%s' requires an argument\n",
5942 argv[0], r);
5943 exit(1);
5945 optarg = argv[optind++];
5946 } else {
5947 optarg = NULL;
5950 switch(popt->index) {
5951 case QEMU_OPTION_M:
5952 machine = find_machine(optarg);
5953 if (!machine) {
5954 QEMUMachine *m;
5955 printf("Supported machines are:\n");
5956 for(m = first_machine; m != NULL; m = m->next) {
5957 printf("%-10s %s%s\n",
5958 m->name, m->desc,
5959 m == first_machine ? " (default)" : "");
5961 exit(*optarg != '?');
5963 break;
5964 case QEMU_OPTION_cpu:
5965 /* hw initialization will check this */
5966 if (*optarg == '?') {
5967 /* XXX: implement xxx_cpu_list for targets that still miss it */
5968 #if defined(cpu_list)
5969 cpu_list(stdout, &fprintf);
5970 #endif
5971 exit(0);
5972 } else {
5973 cpu_model = optarg;
5975 break;
5976 case QEMU_OPTION_initrd:
5977 initrd_filename = optarg;
5978 break;
5979 case QEMU_OPTION_hda:
5980 if (cyls == 0)
5981 hda_index = drive_add(optarg, HD_ALIAS, 0);
5982 else
5983 hda_index = drive_add(optarg, HD_ALIAS
5984 ",cyls=%d,heads=%d,secs=%d%s",
5985 0, cyls, heads, secs,
5986 translation == BIOS_ATA_TRANSLATION_LBA ?
5987 ",trans=lba" :
5988 translation == BIOS_ATA_TRANSLATION_NONE ?
5989 ",trans=none" : "");
5990 break;
5991 case QEMU_OPTION_hdb:
5992 case QEMU_OPTION_hdc:
5993 case QEMU_OPTION_hdd:
5994 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5995 break;
5996 case QEMU_OPTION_drive:
5997 drive_add(NULL, "%s", optarg);
5998 break;
5999 case QEMU_OPTION_mtdblock:
6000 drive_add(optarg, MTD_ALIAS);
6001 break;
6002 case QEMU_OPTION_sd:
6003 drive_add(optarg, SD_ALIAS);
6004 break;
6005 case QEMU_OPTION_pflash:
6006 drive_add(optarg, PFLASH_ALIAS);
6007 break;
6008 case QEMU_OPTION_snapshot:
6009 snapshot = 1;
6010 break;
6011 case QEMU_OPTION_hdachs:
6013 const char *p;
6014 p = optarg;
6015 cyls = strtol(p, (char **)&p, 0);
6016 if (cyls < 1 || cyls > 16383)
6017 goto chs_fail;
6018 if (*p != ',')
6019 goto chs_fail;
6020 p++;
6021 heads = strtol(p, (char **)&p, 0);
6022 if (heads < 1 || heads > 16)
6023 goto chs_fail;
6024 if (*p != ',')
6025 goto chs_fail;
6026 p++;
6027 secs = strtol(p, (char **)&p, 0);
6028 if (secs < 1 || secs > 63)
6029 goto chs_fail;
6030 if (*p == ',') {
6031 p++;
6032 if (!strcmp(p, "none"))
6033 translation = BIOS_ATA_TRANSLATION_NONE;
6034 else if (!strcmp(p, "lba"))
6035 translation = BIOS_ATA_TRANSLATION_LBA;
6036 else if (!strcmp(p, "auto"))
6037 translation = BIOS_ATA_TRANSLATION_AUTO;
6038 else
6039 goto chs_fail;
6040 } else if (*p != '\0') {
6041 chs_fail:
6042 fprintf(stderr, "qemu: invalid physical CHS format\n");
6043 exit(1);
6045 if (hda_index != -1)
6046 snprintf(drives_opt[hda_index].opt,
6047 sizeof(drives_opt[hda_index].opt),
6048 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
6049 0, cyls, heads, secs,
6050 translation == BIOS_ATA_TRANSLATION_LBA ?
6051 ",trans=lba" :
6052 translation == BIOS_ATA_TRANSLATION_NONE ?
6053 ",trans=none" : "");
6055 break;
6056 case QEMU_OPTION_nographic:
6057 nographic = 1;
6058 break;
6059 #ifdef CONFIG_CURSES
6060 case QEMU_OPTION_curses:
6061 curses = 1;
6062 break;
6063 #endif
6064 case QEMU_OPTION_portrait:
6065 graphic_rotate = 1;
6066 break;
6067 case QEMU_OPTION_kernel:
6068 kernel_filename = optarg;
6069 break;
6070 case QEMU_OPTION_append:
6071 kernel_cmdline = optarg;
6072 break;
6073 case QEMU_OPTION_cdrom:
6074 drive_add(optarg, CDROM_ALIAS);
6075 break;
6076 case QEMU_OPTION_boot:
6077 boot_devices = optarg;
6078 /* We just do some generic consistency checks */
6080 /* Could easily be extended to 64 devices if needed */
6081 const char *p;
6083 boot_devices_bitmap = 0;
6084 for (p = boot_devices; *p != '\0'; p++) {
6085 /* Allowed boot devices are:
6086 * a b : floppy disk drives
6087 * c ... f : IDE disk drives
6088 * g ... m : machine implementation dependant drives
6089 * n ... p : network devices
6090 * It's up to each machine implementation to check
6091 * if the given boot devices match the actual hardware
6092 * implementation and firmware features.
6094 if (*p < 'a' || *p > 'q') {
6095 fprintf(stderr, "Invalid boot device '%c'\n", *p);
6096 exit(1);
6098 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
6099 fprintf(stderr,
6100 "Boot device '%c' was given twice\n",*p);
6101 exit(1);
6103 boot_devices_bitmap |= 1 << (*p - 'a');
6106 break;
6107 case QEMU_OPTION_fda:
6108 case QEMU_OPTION_fdb:
6109 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
6110 break;
6111 #ifdef TARGET_I386
6112 case QEMU_OPTION_no_fd_bootchk:
6113 fd_bootchk = 0;
6114 break;
6115 #endif
6116 case QEMU_OPTION_net:
6117 if (nb_net_clients >= MAX_NET_CLIENTS) {
6118 fprintf(stderr, "qemu: too many network clients\n");
6119 exit(1);
6121 net_clients[nb_net_clients] = optarg;
6122 nb_net_clients++;
6123 break;
6124 #ifdef CONFIG_SLIRP
6125 case QEMU_OPTION_tftp:
6126 tftp_prefix = optarg;
6127 break;
6128 case QEMU_OPTION_bootp:
6129 bootp_filename = optarg;
6130 break;
6131 #ifndef _WIN32
6132 case QEMU_OPTION_smb:
6133 net_slirp_smb(optarg);
6134 break;
6135 #endif
6136 case QEMU_OPTION_redir:
6137 net_slirp_redir(optarg);
6138 break;
6139 #endif
6140 case QEMU_OPTION_bt:
6141 if (nb_bt_opts >= MAX_BT_CMDLINE) {
6142 fprintf(stderr, "qemu: too many bluetooth options\n");
6143 exit(1);
6145 bt_opts[nb_bt_opts++] = optarg;
6146 break;
6147 #ifdef HAS_AUDIO
6148 case QEMU_OPTION_audio_help:
6149 AUD_help ();
6150 exit (0);
6151 break;
6152 case QEMU_OPTION_soundhw:
6153 select_soundhw (optarg);
6154 break;
6155 #endif
6156 case QEMU_OPTION_h:
6157 help(0);
6158 break;
6159 case QEMU_OPTION_m: {
6160 uint64_t value;
6161 char *ptr;
6163 value = strtoul(optarg, &ptr, 10);
6164 switch (*ptr) {
6165 case 0: case 'M': case 'm':
6166 value <<= 20;
6167 break;
6168 case 'G': case 'g':
6169 value <<= 30;
6170 break;
6171 default:
6172 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
6173 exit(1);
6176 /* On 32-bit hosts, QEMU is limited by virtual address space */
6177 if (value > (2047 << 20)
6178 #ifndef USE_KQEMU
6179 && HOST_LONG_BITS == 32
6180 #endif
6182 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
6183 exit(1);
6185 if (value != (uint64_t)(ram_addr_t)value) {
6186 fprintf(stderr, "qemu: ram size too large\n");
6187 exit(1);
6189 ram_size = value;
6190 break;
6192 case QEMU_OPTION_d:
6194 int mask;
6195 const CPULogItem *item;
6197 mask = cpu_str_to_log_mask(optarg);
6198 if (!mask) {
6199 printf("Log items (comma separated):\n");
6200 for(item = cpu_log_items; item->mask != 0; item++) {
6201 printf("%-10s %s\n", item->name, item->help);
6203 exit(1);
6205 cpu_set_log(mask);
6207 break;
6208 #ifdef CONFIG_GDBSTUB
6209 case QEMU_OPTION_s:
6210 use_gdbstub = 1;
6211 break;
6212 case QEMU_OPTION_p:
6213 gdbstub_port = optarg;
6214 break;
6215 #endif
6216 case QEMU_OPTION_L:
6217 bios_dir = optarg;
6218 break;
6219 case QEMU_OPTION_bios:
6220 bios_name = optarg;
6221 break;
6222 case QEMU_OPTION_S:
6223 autostart = 0;
6224 break;
6225 case QEMU_OPTION_k:
6226 keyboard_layout = optarg;
6227 break;
6228 case QEMU_OPTION_localtime:
6229 rtc_utc = 0;
6230 break;
6231 case QEMU_OPTION_vga:
6232 select_vgahw (optarg);
6233 break;
6234 case QEMU_OPTION_g:
6236 const char *p;
6237 int w, h, depth;
6238 p = optarg;
6239 w = strtol(p, (char **)&p, 10);
6240 if (w <= 0) {
6241 graphic_error:
6242 fprintf(stderr, "qemu: invalid resolution or depth\n");
6243 exit(1);
6245 if (*p != 'x')
6246 goto graphic_error;
6247 p++;
6248 h = strtol(p, (char **)&p, 10);
6249 if (h <= 0)
6250 goto graphic_error;
6251 if (*p == 'x') {
6252 p++;
6253 depth = strtol(p, (char **)&p, 10);
6254 if (depth != 8 && depth != 15 && depth != 16 &&
6255 depth != 24 && depth != 32)
6256 goto graphic_error;
6257 } else if (*p == '\0') {
6258 depth = graphic_depth;
6259 } else {
6260 goto graphic_error;
6263 graphic_width = w;
6264 graphic_height = h;
6265 graphic_depth = depth;
6267 break;
6268 case QEMU_OPTION_echr:
6270 char *r;
6271 term_escape_char = strtol(optarg, &r, 0);
6272 if (r == optarg)
6273 printf("Bad argument to echr\n");
6274 break;
6276 case QEMU_OPTION_monitor:
6277 monitor_device = optarg;
6278 break;
6279 case QEMU_OPTION_serial:
6280 if (serial_device_index >= MAX_SERIAL_PORTS) {
6281 fprintf(stderr, "qemu: too many serial ports\n");
6282 exit(1);
6284 serial_devices[serial_device_index] = optarg;
6285 serial_device_index++;
6286 break;
6287 case QEMU_OPTION_parallel:
6288 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6289 fprintf(stderr, "qemu: too many parallel ports\n");
6290 exit(1);
6292 parallel_devices[parallel_device_index] = optarg;
6293 parallel_device_index++;
6294 break;
6295 case QEMU_OPTION_loadvm:
6296 loadvm = optarg;
6297 break;
6298 case QEMU_OPTION_full_screen:
6299 full_screen = 1;
6300 break;
6301 #ifdef CONFIG_SDL
6302 case QEMU_OPTION_no_frame:
6303 no_frame = 1;
6304 break;
6305 case QEMU_OPTION_alt_grab:
6306 alt_grab = 1;
6307 break;
6308 case QEMU_OPTION_no_quit:
6309 no_quit = 1;
6310 break;
6311 #endif
6312 case QEMU_OPTION_pidfile:
6313 pid_file = optarg;
6314 break;
6315 #ifdef TARGET_I386
6316 case QEMU_OPTION_win2k_hack:
6317 win2k_install_hack = 1;
6318 break;
6319 #endif
6320 #ifdef USE_KQEMU
6321 case QEMU_OPTION_no_kqemu:
6322 kqemu_allowed = 0;
6323 break;
6324 case QEMU_OPTION_kernel_kqemu:
6325 kqemu_allowed = 2;
6326 break;
6327 #endif
6328 #ifdef CONFIG_KVM
6329 case QEMU_OPTION_enable_kvm:
6330 kvm_allowed = 1;
6331 #ifdef USE_KQEMU
6332 kqemu_allowed = 0;
6333 #endif
6334 break;
6335 #endif
6336 #ifdef USE_KVM
6337 case QEMU_OPTION_no_kvm:
6338 kvm_allowed = 0;
6339 break;
6340 case QEMU_OPTION_no_kvm_irqchip: {
6341 extern int kvm_irqchip, kvm_pit;
6342 kvm_irqchip = 0;
6343 kvm_pit = 0;
6344 break;
6346 case QEMU_OPTION_no_kvm_pit: {
6347 extern int kvm_pit;
6348 kvm_pit = 0;
6349 break;
6351 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
6352 case QEMU_OPTION_pcidevice:
6353 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
6354 fprintf(stderr, "Too many assigned devices\n");
6355 exit(1);
6357 assigned_devices[assigned_devices_index] = optarg;
6358 assigned_devices_index++;
6359 break;
6360 #endif
6361 #endif
6362 case QEMU_OPTION_usb:
6363 usb_enabled = 1;
6364 break;
6365 case QEMU_OPTION_usbdevice:
6366 usb_enabled = 1;
6367 if (usb_devices_index >= MAX_USB_CMDLINE) {
6368 fprintf(stderr, "Too many USB devices\n");
6369 exit(1);
6371 usb_devices[usb_devices_index] = optarg;
6372 usb_devices_index++;
6373 break;
6374 case QEMU_OPTION_smp:
6375 smp_cpus = atoi(optarg);
6376 if (smp_cpus < 1) {
6377 fprintf(stderr, "Invalid number of CPUs\n");
6378 exit(1);
6380 break;
6381 case QEMU_OPTION_vnc:
6382 vnc_display = optarg;
6383 break;
6384 case QEMU_OPTION_no_acpi:
6385 acpi_enabled = 0;
6386 break;
6387 case QEMU_OPTION_no_reboot:
6388 no_reboot = 1;
6389 break;
6390 case QEMU_OPTION_no_shutdown:
6391 no_shutdown = 1;
6392 break;
6393 case QEMU_OPTION_show_cursor:
6394 cursor_hide = 0;
6395 break;
6396 case QEMU_OPTION_uuid:
6397 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
6398 fprintf(stderr, "Fail to parse UUID string."
6399 " Wrong format.\n");
6400 exit(1);
6402 break;
6403 case QEMU_OPTION_daemonize:
6404 daemonize = 1;
6405 break;
6406 case QEMU_OPTION_option_rom:
6407 if (nb_option_roms >= MAX_OPTION_ROMS) {
6408 fprintf(stderr, "Too many option ROMs\n");
6409 exit(1);
6411 option_rom[nb_option_roms] = optarg;
6412 nb_option_roms++;
6413 break;
6414 case QEMU_OPTION_semihosting:
6415 semihosting_enabled = 1;
6416 break;
6417 case QEMU_OPTION_tdf:
6418 time_drift_fix = 1;
6419 break;
6420 case QEMU_OPTION_kvm_shadow_memory:
6421 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
6422 break;
6423 case QEMU_OPTION_mempath:
6424 mem_path = optarg;
6425 break;
6426 case QEMU_OPTION_name:
6427 qemu_name = optarg;
6428 break;
6429 #ifdef TARGET_SPARC
6430 case QEMU_OPTION_prom_env:
6431 if (nb_prom_envs >= MAX_PROM_ENVS) {
6432 fprintf(stderr, "Too many prom variables\n");
6433 exit(1);
6435 prom_envs[nb_prom_envs] = optarg;
6436 nb_prom_envs++;
6437 break;
6438 #endif
6439 case QEMU_OPTION_cpu_vendor:
6440 cpu_vendor_string = optarg;
6441 break;
6442 #ifdef TARGET_ARM
6443 case QEMU_OPTION_old_param:
6444 old_param = 1;
6445 break;
6446 #endif
6447 case QEMU_OPTION_clock:
6448 configure_alarms(optarg);
6449 break;
6450 case QEMU_OPTION_startdate:
6452 struct tm tm;
6453 time_t rtc_start_date;
6454 if (!strcmp(optarg, "now")) {
6455 rtc_date_offset = -1;
6456 } else {
6457 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
6458 &tm.tm_year,
6459 &tm.tm_mon,
6460 &tm.tm_mday,
6461 &tm.tm_hour,
6462 &tm.tm_min,
6463 &tm.tm_sec) == 6) {
6464 /* OK */
6465 } else if (sscanf(optarg, "%d-%d-%d",
6466 &tm.tm_year,
6467 &tm.tm_mon,
6468 &tm.tm_mday) == 3) {
6469 tm.tm_hour = 0;
6470 tm.tm_min = 0;
6471 tm.tm_sec = 0;
6472 } else {
6473 goto date_fail;
6475 tm.tm_year -= 1900;
6476 tm.tm_mon--;
6477 rtc_start_date = mktimegm(&tm);
6478 if (rtc_start_date == -1) {
6479 date_fail:
6480 fprintf(stderr, "Invalid date format. Valid format are:\n"
6481 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
6482 exit(1);
6484 rtc_date_offset = time(NULL) - rtc_start_date;
6487 break;
6488 case QEMU_OPTION_tb_size:
6489 tb_size = strtol(optarg, NULL, 0);
6490 if (tb_size < 0)
6491 tb_size = 0;
6492 break;
6493 case QEMU_OPTION_icount:
6494 use_icount = 1;
6495 if (strcmp(optarg, "auto") == 0) {
6496 icount_time_shift = -1;
6497 } else {
6498 icount_time_shift = strtol(optarg, NULL, 0);
6500 break;
6501 case QEMU_OPTION_incoming:
6502 incoming = optarg;
6503 break;
6508 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
6509 if (kvm_allowed && kqemu_allowed) {
6510 fprintf(stderr,
6511 "You can not enable both KVM and kqemu at the same time\n");
6512 exit(1);
6514 #endif
6516 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
6517 if (smp_cpus > machine->max_cpus) {
6518 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
6519 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
6520 machine->max_cpus);
6521 exit(1);
6524 if (nographic) {
6525 if (serial_device_index == 0)
6526 serial_devices[0] = "stdio";
6527 if (parallel_device_index == 0)
6528 parallel_devices[0] = "null";
6529 if (strncmp(monitor_device, "vc", 2) == 0)
6530 monitor_device = "stdio";
6533 #ifndef _WIN32
6534 if (daemonize) {
6535 pid_t pid;
6537 if (pipe(fds) == -1)
6538 exit(1);
6540 pid = fork();
6541 if (pid > 0) {
6542 uint8_t status;
6543 ssize_t len;
6545 close(fds[1]);
6547 again:
6548 len = read(fds[0], &status, 1);
6549 if (len == -1 && (errno == EINTR))
6550 goto again;
6552 if (len != 1)
6553 exit(1);
6554 else if (status == 1) {
6555 fprintf(stderr, "Could not acquire pidfile\n");
6556 exit(1);
6557 } else
6558 exit(0);
6559 } else if (pid < 0)
6560 exit(1);
6562 setsid();
6564 pid = fork();
6565 if (pid > 0)
6566 exit(0);
6567 else if (pid < 0)
6568 exit(1);
6570 umask(027);
6572 signal(SIGTSTP, SIG_IGN);
6573 signal(SIGTTOU, SIG_IGN);
6574 signal(SIGTTIN, SIG_IGN);
6576 #endif
6578 #if USE_KVM
6579 if (kvm_enabled()) {
6580 if (kvm_qemu_init() < 0) {
6581 extern int kvm_allowed;
6582 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
6583 #ifdef NO_CPU_EMULATION
6584 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
6585 exit(1);
6586 #endif
6587 kvm_allowed = 0;
6590 #endif
6592 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
6593 if (daemonize) {
6594 uint8_t status = 1;
6595 write(fds[1], &status, 1);
6596 } else
6597 fprintf(stderr, "Could not acquire pid file\n");
6598 exit(1);
6601 #ifdef USE_KQEMU
6602 if (smp_cpus > 1)
6603 kqemu_allowed = 0;
6604 #endif
6605 linux_boot = (kernel_filename != NULL);
6606 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6608 if (!linux_boot && net_boot == 0 &&
6609 !machine->nodisk_ok && nb_drives_opt == 0)
6610 help(1);
6612 if (!linux_boot && *kernel_cmdline != '\0') {
6613 fprintf(stderr, "-append only allowed with -kernel option\n");
6614 exit(1);
6617 if (!linux_boot && initrd_filename != NULL) {
6618 fprintf(stderr, "-initrd only allowed with -kernel option\n");
6619 exit(1);
6622 /* boot to floppy or the default cd if no hard disk defined yet */
6623 if (!boot_devices[0]) {
6624 boot_devices = "cad";
6626 setvbuf(stdout, NULL, _IOLBF, 0);
6628 init_timers();
6629 if (init_timer_alarm() < 0) {
6630 fprintf(stderr, "could not initialize alarm timer\n");
6631 exit(1);
6633 if (use_icount && icount_time_shift < 0) {
6634 use_icount = 2;
6635 /* 125MIPS seems a reasonable initial guess at the guest speed.
6636 It will be corrected fairly quickly anyway. */
6637 icount_time_shift = 3;
6638 init_icount_adjust();
6641 #ifdef _WIN32
6642 socket_init();
6643 #endif
6645 /* init network clients */
6646 if (nb_net_clients == 0) {
6647 /* if no clients, we use a default config */
6648 net_clients[nb_net_clients++] = "nic";
6649 #ifdef CONFIG_SLIRP
6650 net_clients[nb_net_clients++] = "user";
6651 #endif
6654 for(i = 0;i < nb_net_clients; i++) {
6655 if (net_client_parse(net_clients[i]) < 0)
6656 exit(1);
6658 net_client_check();
6660 #ifdef TARGET_I386
6661 /* XXX: this should be moved in the PC machine instantiation code */
6662 if (net_boot != 0) {
6663 int netroms = 0;
6664 for (i = 0; i < nb_nics && i < 4; i++) {
6665 const char *model = nd_table[i].model;
6666 char buf[1024];
6667 if (net_boot & (1 << i)) {
6668 if (model == NULL)
6669 model = "rtl8139";
6670 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
6671 if (get_image_size(buf) > 0) {
6672 if (nb_option_roms >= MAX_OPTION_ROMS) {
6673 fprintf(stderr, "Too many option ROMs\n");
6674 exit(1);
6676 option_rom[nb_option_roms] = strdup(buf);
6677 nb_option_roms++;
6678 netroms++;
6682 if (netroms == 0) {
6683 fprintf(stderr, "No valid PXE rom found for network device\n");
6684 exit(1);
6687 #endif
6689 /* init the bluetooth world */
6690 for (i = 0; i < nb_bt_opts; i++)
6691 if (bt_parse(bt_opts[i]))
6692 exit(1);
6694 /* init the memory */
6695 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
6697 if (machine->ram_require & RAMSIZE_FIXED) {
6698 if (ram_size > 0) {
6699 if (ram_size < phys_ram_size) {
6700 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
6701 machine->name, (unsigned long long) phys_ram_size);
6702 exit(-1);
6705 phys_ram_size = ram_size;
6706 } else
6707 ram_size = phys_ram_size;
6708 } else {
6709 if (ram_size == 0)
6710 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6712 phys_ram_size += ram_size;
6715 /* Initialize kvm */
6716 #if defined(TARGET_I386) || defined(TARGET_X86_64)
6717 #define KVM_EXTRA_PAGES 3
6718 #else
6719 #define KVM_EXTRA_PAGES 0
6720 #endif
6721 if (kvm_enabled()) {
6722 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
6723 if (kvm_qemu_create_context() < 0) {
6724 fprintf(stderr, "Could not create KVM context\n");
6725 exit(1);
6729 phys_ram_base = qemu_alloc_physram(phys_ram_size);
6730 if (!phys_ram_base) {
6731 fprintf(stderr, "Could not allocate physical memory\n");
6732 exit(1);
6735 /* init the dynamic translator */
6736 cpu_exec_init_all(tb_size * 1024 * 1024);
6738 bdrv_init();
6740 /* we always create the cdrom drive, even if no disk is there */
6742 if (nb_drives_opt < MAX_DRIVES)
6743 drive_add(NULL, CDROM_ALIAS);
6745 /* we always create at least one floppy */
6747 if (nb_drives_opt < MAX_DRIVES)
6748 drive_add(NULL, FD_ALIAS, 0);
6750 /* we always create one sd slot, even if no card is in it */
6752 if (nb_drives_opt < MAX_DRIVES)
6753 drive_add(NULL, SD_ALIAS);
6755 /* open the virtual block devices
6756 * note that migration with device
6757 * hot add/remove is broken.
6759 for(i = 0; i < nb_drives_opt; i++)
6760 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6761 exit(1);
6763 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6764 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6766 /* terminal init */
6767 memset(&display_state, 0, sizeof(display_state));
6768 if (nographic) {
6769 if (curses) {
6770 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
6771 exit(1);
6773 /* nearly nothing to do */
6774 dumb_display_init(ds);
6775 } else if (vnc_display != NULL) {
6776 vnc_display_init(ds);
6777 if (vnc_display_open(ds, vnc_display) < 0)
6778 exit(1);
6779 } else
6780 #if defined(CONFIG_CURSES)
6781 if (curses) {
6782 curses_display_init(ds, full_screen);
6783 } else
6784 #endif
6786 #if defined(CONFIG_SDL)
6787 sdl_display_init(ds, full_screen, no_frame);
6788 #elif defined(CONFIG_COCOA)
6789 cocoa_display_init(ds, full_screen);
6790 #else
6791 dumb_display_init(ds);
6792 #endif
6795 #ifndef _WIN32
6796 /* must be after terminal init, SDL library changes signal handlers */
6797 termsig_setup();
6798 #endif
6800 /* Maintain compatibility with multiple stdio monitors */
6801 if (!strcmp(monitor_device,"stdio")) {
6802 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6803 const char *devname = serial_devices[i];
6804 if (devname && !strcmp(devname,"mon:stdio")) {
6805 monitor_device = NULL;
6806 break;
6807 } else if (devname && !strcmp(devname,"stdio")) {
6808 monitor_device = NULL;
6809 serial_devices[i] = "mon:stdio";
6810 break;
6814 if (monitor_device) {
6815 monitor_hd = qemu_chr_open("monitor", monitor_device);
6816 if (!monitor_hd) {
6817 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6818 exit(1);
6820 monitor_init(monitor_hd, !nographic);
6823 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6824 const char *devname = serial_devices[i];
6825 if (devname && strcmp(devname, "none")) {
6826 char label[32];
6827 snprintf(label, sizeof(label), "serial%d", i);
6828 serial_hds[i] = qemu_chr_open(label, devname);
6829 if (!serial_hds[i]) {
6830 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6831 devname);
6832 exit(1);
6834 if (strstart(devname, "vc", 0))
6835 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6839 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6840 const char *devname = parallel_devices[i];
6841 if (devname && strcmp(devname, "none")) {
6842 char label[32];
6843 snprintf(label, sizeof(label), "parallel%d", i);
6844 parallel_hds[i] = qemu_chr_open(label, devname);
6845 if (!parallel_hds[i]) {
6846 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6847 devname);
6848 exit(1);
6850 if (strstart(devname, "vc", 0))
6851 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6855 if (kvm_enabled())
6856 kvm_init_ap();
6858 #ifdef KVM_UPSTREAM
6859 if (kvm_enabled()) {
6860 int ret;
6862 ret = kvm_init(smp_cpus);
6863 if (ret < 0) {
6864 fprintf(stderr, "failed to initialize KVM\n");
6865 exit(1);
6868 #endif
6870 machine->init(ram_size, vga_ram_size, boot_devices, ds,
6871 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6873 current_machine = machine;
6875 /* init USB devices */
6876 if (usb_enabled) {
6877 for(i = 0; i < usb_devices_index; i++) {
6878 if (usb_device_add(usb_devices[i]) < 0) {
6879 fprintf(stderr, "Warning: could not add USB device %s\n",
6880 usb_devices[i]);
6885 if (display_state.dpy_refresh) {
6886 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
6887 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
6890 #ifdef CONFIG_GDBSTUB
6891 if (use_gdbstub) {
6892 /* XXX: use standard host:port notation and modify options
6893 accordingly. */
6894 if (gdbserver_start(gdbstub_port) < 0) {
6895 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6896 gdbstub_port);
6897 exit(1);
6900 #endif
6902 if (loadvm)
6903 do_loadvm(loadvm);
6905 if (incoming) {
6906 autostart = 0; /* fixme how to deal with -daemonize */
6907 qemu_start_incoming_migration(incoming);
6911 /* XXX: simplify init */
6912 read_passwords();
6913 if (autostart) {
6914 vm_start();
6918 if (daemonize) {
6919 uint8_t status = 0;
6920 ssize_t len;
6921 int fd;
6923 again1:
6924 len = write(fds[1], &status, 1);
6925 if (len == -1 && (errno == EINTR))
6926 goto again1;
6928 if (len != 1)
6929 exit(1);
6931 chdir("/");
6932 TFR(fd = open("/dev/null", O_RDWR));
6933 if (fd == -1)
6934 exit(1);
6936 dup2(fd, 0);
6937 dup2(fd, 1);
6938 dup2(fd, 2);
6940 close(fd);
6943 main_loop();
6944 quit_timers();
6945 net_cleanup();
6947 return 0;