Include qemu-kvm.h unconditionally
[qemu-kvm/fedora.git] / vl.c
blobbbd7aa3862c6fb3fee86c8eb427b407dec11983f
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "hw/device-assignment.h"
43 #include "migration.h"
44 #include "kvm.h"
45 #include "balloon.h"
46 #include "qemu-kvm.h"
48 #include <unistd.h>
49 #include <fcntl.h>
50 #include <signal.h>
51 #include <time.h>
52 #include <errno.h>
53 #include <sys/time.h>
54 #include <zlib.h>
56 #ifndef _WIN32
57 #include <sys/times.h>
58 #include <sys/wait.h>
59 #include <termios.h>
60 #include <sys/mman.h>
61 #include <sys/ioctl.h>
62 #include <sys/resource.h>
63 #include <sys/socket.h>
64 #include <netinet/in.h>
65 #include <net/if.h>
66 #if defined(__NetBSD__)
67 #include <net/if_tap.h>
68 #endif
69 #ifdef __linux__
70 #include <linux/if_tun.h>
71 #endif
72 #include <arpa/inet.h>
73 #include <dirent.h>
74 #include <netdb.h>
75 #include <sys/select.h>
76 #ifdef _BSD
77 #include <sys/stat.h>
78 #ifdef __FreeBSD__
79 #include <libutil.h>
80 #else
81 #include <util.h>
82 #endif
83 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
84 #include <freebsd/stdlib.h>
85 #else
86 #ifdef __linux__
87 #include <pty.h>
88 #include <malloc.h>
89 #include <linux/rtc.h>
91 /* For the benefit of older linux systems which don't supply it,
92 we use a local copy of hpet.h. */
93 /* #include <linux/hpet.h> */
94 #include "hpet.h"
96 #include <linux/ppdev.h>
97 #include <linux/parport.h>
98 #endif
99 #ifdef __sun__
100 #include <sys/stat.h>
101 #include <sys/ethernet.h>
102 #include <sys/sockio.h>
103 #include <netinet/arp.h>
104 #include <netinet/in.h>
105 #include <netinet/in_systm.h>
106 #include <netinet/ip.h>
107 #include <netinet/ip_icmp.h> // must come after ip.h
108 #include <netinet/udp.h>
109 #include <netinet/tcp.h>
110 #include <net/if.h>
111 #include <syslog.h>
112 #include <stropts.h>
113 #endif
114 #endif
115 #endif
117 #include "qemu_socket.h"
119 #if defined(CONFIG_SLIRP)
120 #include "libslirp.h"
121 #endif
123 #if defined(__OpenBSD__)
124 #include <util.h>
125 #endif
127 #if defined(CONFIG_VDE)
128 #include <libvdeplug.h>
129 #endif
131 #ifdef _WIN32
132 #include <malloc.h>
133 #include <sys/timeb.h>
134 #include <mmsystem.h>
135 #define getopt_long_only getopt_long
136 #define memalign(align, size) malloc(size)
137 #endif
139 #ifdef CONFIG_SDL
140 #ifdef __APPLE__
141 #include <SDL/SDL.h>
142 int qemu_main(int argc, char **argv, char **envp);
143 int main(int argc, char **argv)
145 qemu_main(argc, argv, NULL);
147 #undef main
148 #define main qemu_main
149 #endif
150 #endif /* CONFIG_SDL */
152 #ifdef CONFIG_COCOA
153 #undef main
154 #define main qemu_main
155 #endif /* CONFIG_COCOA */
157 #include "disas.h"
159 #include "exec-all.h"
161 #include "qemu-kvm.h"
163 //#define DEBUG_UNUSED_IOPORT
164 //#define DEBUG_IOPORT
165 //#define DEBUG_NET
166 //#define DEBUG_SLIRP
169 #ifdef DEBUG_IOPORT
170 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
171 #else
172 # define LOG_IOPORT(...) do { } while (0)
173 #endif
175 #define DEFAULT_RAM_SIZE 128
177 /* Max number of USB devices that can be specified on the commandline. */
178 #define MAX_USB_CMDLINE 8
180 /* Max number of bluetooth switches on the commandline. */
181 #define MAX_BT_CMDLINE 10
183 /* XXX: use a two level table to limit memory usage */
184 #define MAX_IOPORTS 65536
186 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
187 const char *bios_name = NULL;
188 static void *ioport_opaque[MAX_IOPORTS];
189 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
190 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
191 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
192 to store the VM snapshots */
193 DriveInfo drives_table[MAX_DRIVES+1];
194 int nb_drives;
195 int extboot_drive = -1;
196 static int vga_ram_size;
197 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
198 static DisplayState *display_state;
199 int nographic;
200 static int curses;
201 static int sdl;
202 const char* keyboard_layout = NULL;
203 int64_t ticks_per_sec;
204 ram_addr_t ram_size;
205 int nb_nics;
206 NICInfo nd_table[MAX_NICS];
207 int vm_running;
208 static int rtc_utc = 1;
209 static int rtc_date_offset = -1; /* -1 means no change */
210 int cirrus_vga_enabled = 1;
211 int std_vga_enabled = 0;
212 int vmsvga_enabled = 0;
213 #ifdef TARGET_SPARC
214 int graphic_width = 1024;
215 int graphic_height = 768;
216 int graphic_depth = 8;
217 #else
218 int graphic_width = 800;
219 int graphic_height = 600;
220 int graphic_depth = 15;
221 #endif
222 static int full_screen = 0;
223 #ifdef CONFIG_SDL
224 static int no_frame = 0;
225 #endif
226 int no_quit = 0;
227 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
228 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
229 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
230 #ifdef TARGET_I386
231 int win2k_install_hack = 0;
232 int rtc_td_hack = 0;
233 #endif
234 int usb_enabled = 0;
235 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
236 int assigned_devices_index;
237 int smp_cpus = 1;
238 const char *vnc_display;
239 int acpi_enabled = 1;
240 int no_hpet = 0;
241 int fd_bootchk = 1;
242 int no_reboot = 0;
243 int no_shutdown = 0;
244 int cursor_hide = 1;
245 int graphic_rotate = 0;
246 int daemonize = 0;
247 const char *incoming;
248 const char *option_rom[MAX_OPTION_ROMS];
249 int nb_option_roms;
250 int semihosting_enabled = 0;
251 int time_drift_fix = 0;
252 unsigned int kvm_shadow_memory = 0;
253 const char *mem_path = NULL;
254 #ifdef MAP_POPULATE
255 int mem_prealloc = 1; /* force preallocation of physical target memory */
256 #endif
257 int hpagesize = 0;
258 const char *cpu_vendor_string;
259 #ifdef TARGET_ARM
260 int old_param = 0;
261 #endif
262 const char *qemu_name;
263 int alt_grab = 0;
264 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
265 unsigned int nb_prom_envs = 0;
266 const char *prom_envs[MAX_PROM_ENVS];
267 #endif
268 int nb_drives_opt;
269 const char *nvram = NULL;
270 struct drive_opt drives_opt[MAX_DRIVES];
272 static CPUState *cur_cpu;
273 static CPUState *next_cpu;
274 static int event_pending = 1;
275 /* Conversion factor from emulated instructions to virtual clock ticks. */
276 static int icount_time_shift;
277 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
278 #define MAX_ICOUNT_SHIFT 10
279 /* Compensate for varying guest execution speed. */
280 static int64_t qemu_icount_bias;
281 static QEMUTimer *icount_rt_timer;
282 static QEMUTimer *icount_vm_timer;
283 static QEMUTimer *nographic_timer;
285 uint8_t qemu_uuid[16];
287 /* KVM runs the main loop in a separate thread. If we update one of the lists
288 * that are polled before or after select(), we need to make sure to break out
289 * of the select() to ensure the new item is serviced.
291 static void main_loop_break(void)
293 if (kvm_enabled())
294 qemu_kvm_notify_work();
297 /***********************************************************/
298 /* x86 ISA bus support */
300 target_phys_addr_t isa_mem_base = 0;
301 PicState2 *isa_pic;
303 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
304 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
306 static uint32_t ioport_read(int index, uint32_t address)
308 static IOPortReadFunc *default_func[3] = {
309 default_ioport_readb,
310 default_ioport_readw,
311 default_ioport_readl
313 IOPortReadFunc *func = ioport_read_table[index][address];
314 if (!func)
315 func = default_func[index];
316 return func(ioport_opaque[address], address);
319 static void ioport_write(int index, uint32_t address, uint32_t data)
321 static IOPortWriteFunc *default_func[3] = {
322 default_ioport_writeb,
323 default_ioport_writew,
324 default_ioport_writel
326 IOPortWriteFunc *func = ioport_write_table[index][address];
327 if (!func)
328 func = default_func[index];
329 func(ioport_opaque[address], address, data);
332 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
334 #ifdef DEBUG_UNUSED_IOPORT
335 fprintf(stderr, "unused inb: port=0x%04x\n", address);
336 #endif
337 return 0xff;
340 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
342 #ifdef DEBUG_UNUSED_IOPORT
343 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
344 #endif
347 /* default is to make two byte accesses */
348 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
350 uint32_t data;
351 data = ioport_read(0, address);
352 address = (address + 1) & (MAX_IOPORTS - 1);
353 data |= ioport_read(0, address) << 8;
354 return data;
357 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
359 ioport_write(0, address, data & 0xff);
360 address = (address + 1) & (MAX_IOPORTS - 1);
361 ioport_write(0, address, (data >> 8) & 0xff);
364 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
366 #ifdef DEBUG_UNUSED_IOPORT
367 fprintf(stderr, "unused inl: port=0x%04x\n", address);
368 #endif
369 return 0xffffffff;
372 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
374 #ifdef DEBUG_UNUSED_IOPORT
375 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
376 #endif
379 /* size is the word size in byte */
380 int register_ioport_read(int start, int length, int size,
381 IOPortReadFunc *func, void *opaque)
383 int i, bsize;
385 if (size == 1) {
386 bsize = 0;
387 } else if (size == 2) {
388 bsize = 1;
389 } else if (size == 4) {
390 bsize = 2;
391 } else {
392 hw_error("register_ioport_read: invalid size");
393 return -1;
395 for(i = start; i < start + length; i += size) {
396 ioport_read_table[bsize][i] = func;
397 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
398 hw_error("register_ioport_read: invalid opaque");
399 ioport_opaque[i] = opaque;
401 return 0;
404 /* size is the word size in byte */
405 int register_ioport_write(int start, int length, int size,
406 IOPortWriteFunc *func, void *opaque)
408 int i, bsize;
410 if (size == 1) {
411 bsize = 0;
412 } else if (size == 2) {
413 bsize = 1;
414 } else if (size == 4) {
415 bsize = 2;
416 } else {
417 hw_error("register_ioport_write: invalid size");
418 return -1;
420 for(i = start; i < start + length; i += size) {
421 ioport_write_table[bsize][i] = func;
422 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
423 hw_error("register_ioport_write: invalid opaque");
424 ioport_opaque[i] = opaque;
426 return 0;
429 void isa_unassign_ioport(int start, int length)
431 int i;
433 for(i = start; i < start + length; i++) {
434 ioport_read_table[0][i] = default_ioport_readb;
435 ioport_read_table[1][i] = default_ioport_readw;
436 ioport_read_table[2][i] = default_ioport_readl;
438 ioport_write_table[0][i] = default_ioport_writeb;
439 ioport_write_table[1][i] = default_ioport_writew;
440 ioport_write_table[2][i] = default_ioport_writel;
442 ioport_opaque[i] = NULL;
446 /***********************************************************/
448 void cpu_outb(CPUState *env, int addr, int val)
450 LOG_IOPORT("outb: %04x %02x\n", addr, val);
451 ioport_write(0, addr, val);
452 #ifdef USE_KQEMU
453 if (env)
454 env->last_io_time = cpu_get_time_fast();
455 #endif
458 void cpu_outw(CPUState *env, int addr, int val)
460 LOG_IOPORT("outw: %04x %04x\n", addr, val);
461 ioport_write(1, addr, val);
462 #ifdef USE_KQEMU
463 if (env)
464 env->last_io_time = cpu_get_time_fast();
465 #endif
468 void cpu_outl(CPUState *env, int addr, int val)
470 LOG_IOPORT("outl: %04x %08x\n", addr, val);
471 ioport_write(2, addr, val);
472 #ifdef USE_KQEMU
473 if (env)
474 env->last_io_time = cpu_get_time_fast();
475 #endif
478 int cpu_inb(CPUState *env, int addr)
480 int val;
481 val = ioport_read(0, addr);
482 LOG_IOPORT("inb : %04x %02x\n", addr, val);
483 #ifdef USE_KQEMU
484 if (env)
485 env->last_io_time = cpu_get_time_fast();
486 #endif
487 return val;
490 int cpu_inw(CPUState *env, int addr)
492 int val;
493 val = ioport_read(1, addr);
494 LOG_IOPORT("inw : %04x %04x\n", addr, val);
495 #ifdef USE_KQEMU
496 if (env)
497 env->last_io_time = cpu_get_time_fast();
498 #endif
499 return val;
502 int cpu_inl(CPUState *env, int addr)
504 int val;
505 val = ioport_read(2, addr);
506 LOG_IOPORT("inl : %04x %08x\n", addr, val);
507 #ifdef USE_KQEMU
508 if (env)
509 env->last_io_time = cpu_get_time_fast();
510 #endif
511 return val;
514 /***********************************************************/
515 void hw_error(const char *fmt, ...)
517 va_list ap;
518 CPUState *env;
520 va_start(ap, fmt);
521 fprintf(stderr, "qemu: hardware error: ");
522 vfprintf(stderr, fmt, ap);
523 fprintf(stderr, "\n");
524 for(env = first_cpu; env != NULL; env = env->next_cpu) {
525 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
526 #ifdef TARGET_I386
527 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
528 #else
529 cpu_dump_state(env, stderr, fprintf, 0);
530 #endif
532 va_end(ap);
533 abort();
536 /***************/
537 /* ballooning */
539 static QEMUBalloonEvent *qemu_balloon_event;
540 void *qemu_balloon_event_opaque;
542 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
544 qemu_balloon_event = func;
545 qemu_balloon_event_opaque = opaque;
548 void qemu_balloon(ram_addr_t target)
550 if (qemu_balloon_event)
551 qemu_balloon_event(qemu_balloon_event_opaque, target);
554 ram_addr_t qemu_balloon_status(void)
556 if (qemu_balloon_event)
557 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
558 return 0;
561 /***********************************************************/
562 /* keyboard/mouse */
564 static QEMUPutKBDEvent *qemu_put_kbd_event;
565 static void *qemu_put_kbd_event_opaque;
566 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
567 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
569 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
571 qemu_put_kbd_event_opaque = opaque;
572 qemu_put_kbd_event = func;
575 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
576 void *opaque, int absolute,
577 const char *name)
579 QEMUPutMouseEntry *s, *cursor;
581 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
583 s->qemu_put_mouse_event = func;
584 s->qemu_put_mouse_event_opaque = opaque;
585 s->qemu_put_mouse_event_absolute = absolute;
586 s->qemu_put_mouse_event_name = qemu_strdup(name);
587 s->next = NULL;
589 if (!qemu_put_mouse_event_head) {
590 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
591 return s;
594 cursor = qemu_put_mouse_event_head;
595 while (cursor->next != NULL)
596 cursor = cursor->next;
598 cursor->next = s;
599 qemu_put_mouse_event_current = s;
601 return s;
604 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
606 QEMUPutMouseEntry *prev = NULL, *cursor;
608 if (!qemu_put_mouse_event_head || entry == NULL)
609 return;
611 cursor = qemu_put_mouse_event_head;
612 while (cursor != NULL && cursor != entry) {
613 prev = cursor;
614 cursor = cursor->next;
617 if (cursor == NULL) // does not exist or list empty
618 return;
619 else if (prev == NULL) { // entry is head
620 qemu_put_mouse_event_head = cursor->next;
621 if (qemu_put_mouse_event_current == entry)
622 qemu_put_mouse_event_current = cursor->next;
623 qemu_free(entry->qemu_put_mouse_event_name);
624 qemu_free(entry);
625 return;
628 prev->next = entry->next;
630 if (qemu_put_mouse_event_current == entry)
631 qemu_put_mouse_event_current = prev;
633 qemu_free(entry->qemu_put_mouse_event_name);
634 qemu_free(entry);
637 void kbd_put_keycode(int keycode)
639 if (qemu_put_kbd_event) {
640 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
644 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
646 QEMUPutMouseEvent *mouse_event;
647 void *mouse_event_opaque;
648 int width;
650 if (!qemu_put_mouse_event_current) {
651 return;
654 mouse_event =
655 qemu_put_mouse_event_current->qemu_put_mouse_event;
656 mouse_event_opaque =
657 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
659 if (mouse_event) {
660 if (graphic_rotate) {
661 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
662 width = 0x7fff;
663 else
664 width = graphic_width - 1;
665 mouse_event(mouse_event_opaque,
666 width - dy, dx, dz, buttons_state);
667 } else
668 mouse_event(mouse_event_opaque,
669 dx, dy, dz, buttons_state);
673 int kbd_mouse_is_absolute(void)
675 if (!qemu_put_mouse_event_current)
676 return 0;
678 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
681 void do_info_mice(void)
683 QEMUPutMouseEntry *cursor;
684 int index = 0;
686 if (!qemu_put_mouse_event_head) {
687 term_printf("No mouse devices connected\n");
688 return;
691 term_printf("Mouse devices available:\n");
692 cursor = qemu_put_mouse_event_head;
693 while (cursor != NULL) {
694 term_printf("%c Mouse #%d: %s\n",
695 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
696 index, cursor->qemu_put_mouse_event_name);
697 index++;
698 cursor = cursor->next;
702 void do_mouse_set(int index)
704 QEMUPutMouseEntry *cursor;
705 int i = 0;
707 if (!qemu_put_mouse_event_head) {
708 term_printf("No mouse devices connected\n");
709 return;
712 cursor = qemu_put_mouse_event_head;
713 while (cursor != NULL && index != i) {
714 i++;
715 cursor = cursor->next;
718 if (cursor != NULL)
719 qemu_put_mouse_event_current = cursor;
720 else
721 term_printf("Mouse at given index not found\n");
724 /* compute with 96 bit intermediate result: (a*b)/c */
725 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
727 union {
728 uint64_t ll;
729 struct {
730 #ifdef WORDS_BIGENDIAN
731 uint32_t high, low;
732 #else
733 uint32_t low, high;
734 #endif
735 } l;
736 } u, res;
737 uint64_t rl, rh;
739 u.ll = a;
740 rl = (uint64_t)u.l.low * (uint64_t)b;
741 rh = (uint64_t)u.l.high * (uint64_t)b;
742 rh += (rl >> 32);
743 res.l.high = rh / c;
744 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
745 return res.ll;
748 /***********************************************************/
749 /* real time host monotonic timer */
751 #define QEMU_TIMER_BASE 1000000000LL
753 #ifdef WIN32
755 static int64_t clock_freq;
757 static void init_get_clock(void)
759 LARGE_INTEGER freq;
760 int ret;
761 ret = QueryPerformanceFrequency(&freq);
762 if (ret == 0) {
763 fprintf(stderr, "Could not calibrate ticks\n");
764 exit(1);
766 clock_freq = freq.QuadPart;
769 static int64_t get_clock(void)
771 LARGE_INTEGER ti;
772 QueryPerformanceCounter(&ti);
773 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
776 #else
778 static int use_rt_clock;
780 static void init_get_clock(void)
782 use_rt_clock = 0;
783 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
785 struct timespec ts;
786 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
787 use_rt_clock = 1;
790 #endif
793 static int64_t get_clock(void)
795 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
796 if (use_rt_clock) {
797 struct timespec ts;
798 clock_gettime(CLOCK_MONOTONIC, &ts);
799 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
800 } else
801 #endif
803 /* XXX: using gettimeofday leads to problems if the date
804 changes, so it should be avoided. */
805 struct timeval tv;
806 gettimeofday(&tv, NULL);
807 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
810 #endif
812 /* Return the virtual CPU time, based on the instruction counter. */
813 static int64_t cpu_get_icount(void)
815 int64_t icount;
816 CPUState *env = cpu_single_env;;
817 icount = qemu_icount;
818 if (env) {
819 if (!can_do_io(env))
820 fprintf(stderr, "Bad clock read\n");
821 icount -= (env->icount_decr.u16.low + env->icount_extra);
823 return qemu_icount_bias + (icount << icount_time_shift);
826 /***********************************************************/
827 /* guest cycle counter */
829 static int64_t cpu_ticks_prev;
830 static int64_t cpu_ticks_offset;
831 static int64_t cpu_clock_offset;
832 static int cpu_ticks_enabled;
834 /* return the host CPU cycle counter and handle stop/restart */
835 int64_t cpu_get_ticks(void)
837 if (use_icount) {
838 return cpu_get_icount();
840 if (!cpu_ticks_enabled) {
841 return cpu_ticks_offset;
842 } else {
843 int64_t ticks;
844 ticks = cpu_get_real_ticks();
845 if (cpu_ticks_prev > ticks) {
846 /* Note: non increasing ticks may happen if the host uses
847 software suspend */
848 cpu_ticks_offset += cpu_ticks_prev - ticks;
850 cpu_ticks_prev = ticks;
851 return ticks + cpu_ticks_offset;
855 /* return the host CPU monotonic timer and handle stop/restart */
856 static int64_t cpu_get_clock(void)
858 int64_t ti;
859 if (!cpu_ticks_enabled) {
860 return cpu_clock_offset;
861 } else {
862 ti = get_clock();
863 return ti + cpu_clock_offset;
867 /* enable cpu_get_ticks() */
868 void cpu_enable_ticks(void)
870 if (!cpu_ticks_enabled) {
871 cpu_ticks_offset -= cpu_get_real_ticks();
872 cpu_clock_offset -= get_clock();
873 cpu_ticks_enabled = 1;
877 /* disable cpu_get_ticks() : the clock is stopped. You must not call
878 cpu_get_ticks() after that. */
879 void cpu_disable_ticks(void)
881 if (cpu_ticks_enabled) {
882 cpu_ticks_offset = cpu_get_ticks();
883 cpu_clock_offset = cpu_get_clock();
884 cpu_ticks_enabled = 0;
888 /***********************************************************/
889 /* timers */
891 #define QEMU_TIMER_REALTIME 0
892 #define QEMU_TIMER_VIRTUAL 1
894 struct QEMUClock {
895 int type;
896 /* XXX: add frequency */
899 struct QEMUTimer {
900 QEMUClock *clock;
901 int64_t expire_time;
902 QEMUTimerCB *cb;
903 void *opaque;
904 struct QEMUTimer *next;
907 struct qemu_alarm_timer {
908 char const *name;
909 unsigned int flags;
911 int (*start)(struct qemu_alarm_timer *t);
912 void (*stop)(struct qemu_alarm_timer *t);
913 void (*rearm)(struct qemu_alarm_timer *t);
914 void *priv;
917 #define ALARM_FLAG_DYNTICKS 0x1
918 #define ALARM_FLAG_EXPIRED 0x2
920 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
922 return t->flags & ALARM_FLAG_DYNTICKS;
925 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
927 if (!alarm_has_dynticks(t))
928 return;
930 t->rearm(t);
933 /* TODO: MIN_TIMER_REARM_US should be optimized */
934 #define MIN_TIMER_REARM_US 250
936 static struct qemu_alarm_timer *alarm_timer;
937 #ifndef _WIN32
938 static int alarm_timer_rfd, alarm_timer_wfd;
939 #endif
941 #ifdef _WIN32
943 struct qemu_alarm_win32 {
944 MMRESULT timerId;
945 HANDLE host_alarm;
946 unsigned int period;
947 } alarm_win32_data = {0, NULL, -1};
949 static int win32_start_timer(struct qemu_alarm_timer *t);
950 static void win32_stop_timer(struct qemu_alarm_timer *t);
951 static void win32_rearm_timer(struct qemu_alarm_timer *t);
953 #else
955 static int unix_start_timer(struct qemu_alarm_timer *t);
956 static void unix_stop_timer(struct qemu_alarm_timer *t);
958 #ifdef __linux__
960 static int dynticks_start_timer(struct qemu_alarm_timer *t);
961 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
962 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
964 static int hpet_start_timer(struct qemu_alarm_timer *t);
965 static void hpet_stop_timer(struct qemu_alarm_timer *t);
967 static int rtc_start_timer(struct qemu_alarm_timer *t);
968 static void rtc_stop_timer(struct qemu_alarm_timer *t);
970 #endif /* __linux__ */
972 #endif /* _WIN32 */
974 /* Correlation between real and virtual time is always going to be
975 fairly approximate, so ignore small variation.
976 When the guest is idle real and virtual time will be aligned in
977 the IO wait loop. */
978 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
980 static void icount_adjust(void)
982 int64_t cur_time;
983 int64_t cur_icount;
984 int64_t delta;
985 static int64_t last_delta;
986 /* If the VM is not running, then do nothing. */
987 if (!vm_running)
988 return;
990 cur_time = cpu_get_clock();
991 cur_icount = qemu_get_clock(vm_clock);
992 delta = cur_icount - cur_time;
993 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
994 if (delta > 0
995 && last_delta + ICOUNT_WOBBLE < delta * 2
996 && icount_time_shift > 0) {
997 /* The guest is getting too far ahead. Slow time down. */
998 icount_time_shift--;
1000 if (delta < 0
1001 && last_delta - ICOUNT_WOBBLE > delta * 2
1002 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1003 /* The guest is getting too far behind. Speed time up. */
1004 icount_time_shift++;
1006 last_delta = delta;
1007 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1010 static void icount_adjust_rt(void * opaque)
1012 qemu_mod_timer(icount_rt_timer,
1013 qemu_get_clock(rt_clock) + 1000);
1014 icount_adjust();
1017 static void icount_adjust_vm(void * opaque)
1019 qemu_mod_timer(icount_vm_timer,
1020 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1021 icount_adjust();
1024 static void init_icount_adjust(void)
1026 /* Have both realtime and virtual time triggers for speed adjustment.
1027 The realtime trigger catches emulated time passing too slowly,
1028 the virtual time trigger catches emulated time passing too fast.
1029 Realtime triggers occur even when idle, so use them less frequently
1030 than VM triggers. */
1031 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1032 qemu_mod_timer(icount_rt_timer,
1033 qemu_get_clock(rt_clock) + 1000);
1034 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1035 qemu_mod_timer(icount_vm_timer,
1036 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1039 static struct qemu_alarm_timer alarm_timers[] = {
1040 #ifndef _WIN32
1041 #ifdef __linux__
1042 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1043 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1044 /* HPET - if available - is preferred */
1045 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1046 /* ...otherwise try RTC */
1047 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1048 #endif
1049 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1050 #else
1051 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1052 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1053 {"win32", 0, win32_start_timer,
1054 win32_stop_timer, NULL, &alarm_win32_data},
1055 #endif
1056 {NULL, }
1059 static void show_available_alarms(void)
1061 int i;
1063 printf("Available alarm timers, in order of precedence:\n");
1064 for (i = 0; alarm_timers[i].name; i++)
1065 printf("%s\n", alarm_timers[i].name);
1068 static void configure_alarms(char const *opt)
1070 int i;
1071 int cur = 0;
1072 int count = ARRAY_SIZE(alarm_timers) - 1;
1073 char *arg;
1074 char *name;
1075 struct qemu_alarm_timer tmp;
1077 if (!strcmp(opt, "?")) {
1078 show_available_alarms();
1079 exit(0);
1082 arg = strdup(opt);
1084 /* Reorder the array */
1085 name = strtok(arg, ",");
1086 while (name) {
1087 for (i = 0; i < count && alarm_timers[i].name; i++) {
1088 if (!strcmp(alarm_timers[i].name, name))
1089 break;
1092 if (i == count) {
1093 fprintf(stderr, "Unknown clock %s\n", name);
1094 goto next;
1097 if (i < cur)
1098 /* Ignore */
1099 goto next;
1101 /* Swap */
1102 tmp = alarm_timers[i];
1103 alarm_timers[i] = alarm_timers[cur];
1104 alarm_timers[cur] = tmp;
1106 cur++;
1107 next:
1108 name = strtok(NULL, ",");
1111 free(arg);
1113 if (cur) {
1114 /* Disable remaining timers */
1115 for (i = cur; i < count; i++)
1116 alarm_timers[i].name = NULL;
1117 } else {
1118 show_available_alarms();
1119 exit(1);
1123 QEMUClock *rt_clock;
1124 QEMUClock *vm_clock;
1126 static QEMUTimer *active_timers[2];
1128 static QEMUClock *qemu_new_clock(int type)
1130 QEMUClock *clock;
1131 clock = qemu_mallocz(sizeof(QEMUClock));
1132 clock->type = type;
1133 return clock;
1136 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1138 QEMUTimer *ts;
1140 ts = qemu_mallocz(sizeof(QEMUTimer));
1141 ts->clock = clock;
1142 ts->cb = cb;
1143 ts->opaque = opaque;
1144 return ts;
1147 void qemu_free_timer(QEMUTimer *ts)
1149 qemu_free(ts);
1152 /* stop a timer, but do not dealloc it */
1153 void qemu_del_timer(QEMUTimer *ts)
1155 QEMUTimer **pt, *t;
1157 /* NOTE: this code must be signal safe because
1158 qemu_timer_expired() can be called from a signal. */
1159 pt = &active_timers[ts->clock->type];
1160 for(;;) {
1161 t = *pt;
1162 if (!t)
1163 break;
1164 if (t == ts) {
1165 *pt = t->next;
1166 break;
1168 pt = &t->next;
1172 /* modify the current timer so that it will be fired when current_time
1173 >= expire_time. The corresponding callback will be called. */
1174 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1176 QEMUTimer **pt, *t;
1178 qemu_del_timer(ts);
1180 /* add the timer in the sorted list */
1181 /* NOTE: this code must be signal safe because
1182 qemu_timer_expired() can be called from a signal. */
1183 pt = &active_timers[ts->clock->type];
1184 for(;;) {
1185 t = *pt;
1186 if (!t)
1187 break;
1188 if (t->expire_time > expire_time)
1189 break;
1190 pt = &t->next;
1192 ts->expire_time = expire_time;
1193 ts->next = *pt;
1194 *pt = ts;
1196 /* Rearm if necessary */
1197 if (pt == &active_timers[ts->clock->type]) {
1198 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1199 qemu_rearm_alarm_timer(alarm_timer);
1201 /* Interrupt execution to force deadline recalculation. */
1202 if (use_icount && cpu_single_env) {
1203 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1208 int qemu_timer_pending(QEMUTimer *ts)
1210 QEMUTimer *t;
1211 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1212 if (t == ts)
1213 return 1;
1215 return 0;
1218 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1220 if (!timer_head)
1221 return 0;
1222 return (timer_head->expire_time <= current_time);
1225 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1227 QEMUTimer *ts;
1229 for(;;) {
1230 ts = *ptimer_head;
1231 if (!ts || ts->expire_time > current_time)
1232 break;
1233 /* remove timer from the list before calling the callback */
1234 *ptimer_head = ts->next;
1235 ts->next = NULL;
1237 /* run the callback (the timer list can be modified) */
1238 ts->cb(ts->opaque);
1242 int64_t qemu_get_clock(QEMUClock *clock)
1244 switch(clock->type) {
1245 case QEMU_TIMER_REALTIME:
1246 return get_clock() / 1000000;
1247 default:
1248 case QEMU_TIMER_VIRTUAL:
1249 if (use_icount) {
1250 return cpu_get_icount();
1251 } else {
1252 return cpu_get_clock();
1257 static void init_timers(void)
1259 init_get_clock();
1260 ticks_per_sec = QEMU_TIMER_BASE;
1261 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1262 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1265 /* save a timer */
1266 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1268 uint64_t expire_time;
1270 if (qemu_timer_pending(ts)) {
1271 expire_time = ts->expire_time;
1272 } else {
1273 expire_time = -1;
1275 qemu_put_be64(f, expire_time);
1278 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1280 uint64_t expire_time;
1282 expire_time = qemu_get_be64(f);
1283 if (expire_time != -1) {
1284 qemu_mod_timer(ts, expire_time);
1285 } else {
1286 qemu_del_timer(ts);
1290 static void timer_save(QEMUFile *f, void *opaque)
1292 if (cpu_ticks_enabled) {
1293 hw_error("cannot save state if virtual timers are running");
1295 qemu_put_be64(f, cpu_ticks_offset);
1296 qemu_put_be64(f, ticks_per_sec);
1297 qemu_put_be64(f, cpu_clock_offset);
1300 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1302 if (version_id != 1 && version_id != 2)
1303 return -EINVAL;
1304 if (cpu_ticks_enabled) {
1305 return -EINVAL;
1307 cpu_ticks_offset=qemu_get_be64(f);
1308 ticks_per_sec=qemu_get_be64(f);
1309 if (version_id == 2) {
1310 cpu_clock_offset=qemu_get_be64(f);
1312 return 0;
1315 #ifdef _WIN32
1316 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1317 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1318 #else
1319 static void host_alarm_handler(int host_signum)
1320 #endif
1322 #if 0
1323 #define DISP_FREQ 1000
1325 static int64_t delta_min = INT64_MAX;
1326 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1327 static int count;
1328 ti = qemu_get_clock(vm_clock);
1329 if (last_clock != 0) {
1330 delta = ti - last_clock;
1331 if (delta < delta_min)
1332 delta_min = delta;
1333 if (delta > delta_max)
1334 delta_max = delta;
1335 delta_cum += delta;
1336 if (++count == DISP_FREQ) {
1337 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1338 muldiv64(delta_min, 1000000, ticks_per_sec),
1339 muldiv64(delta_max, 1000000, ticks_per_sec),
1340 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1341 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1342 count = 0;
1343 delta_min = INT64_MAX;
1344 delta_max = 0;
1345 delta_cum = 0;
1348 last_clock = ti;
1350 #endif
1351 if (1 ||
1352 alarm_has_dynticks(alarm_timer) ||
1353 (!use_icount &&
1354 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1355 qemu_get_clock(vm_clock))) ||
1356 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1357 qemu_get_clock(rt_clock))) {
1358 CPUState *env = next_cpu;
1360 #ifdef _WIN32
1361 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1362 SetEvent(data->host_alarm);
1363 #else
1364 static const char byte = 0;
1365 write(alarm_timer_wfd, &byte, sizeof(byte));
1366 #endif
1367 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1369 if (env) {
1370 /* stop the currently executing cpu because a timer occured */
1371 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1372 #ifdef USE_KQEMU
1373 if (env->kqemu_enabled) {
1374 kqemu_cpu_interrupt(env);
1376 #endif
1378 event_pending = 1;
1382 static int64_t qemu_next_deadline(void)
1384 int64_t delta;
1386 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1387 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1388 qemu_get_clock(vm_clock);
1389 } else {
1390 /* To avoid problems with overflow limit this to 2^32. */
1391 delta = INT32_MAX;
1394 if (delta < 0)
1395 delta = 0;
1397 return delta;
1400 #if defined(__linux__) || defined(_WIN32)
1401 static uint64_t qemu_next_deadline_dyntick(void)
1403 int64_t delta;
1404 int64_t rtdelta;
1406 if (use_icount)
1407 delta = INT32_MAX;
1408 else
1409 delta = (qemu_next_deadline() + 999) / 1000;
1411 if (active_timers[QEMU_TIMER_REALTIME]) {
1412 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1413 qemu_get_clock(rt_clock))*1000;
1414 if (rtdelta < delta)
1415 delta = rtdelta;
1418 if (delta < MIN_TIMER_REARM_US)
1419 delta = MIN_TIMER_REARM_US;
1421 return delta;
1423 #endif
1425 #ifndef _WIN32
1427 /* Sets a specific flag */
1428 static int fcntl_setfl(int fd, int flag)
1430 int flags;
1432 flags = fcntl(fd, F_GETFL);
1433 if (flags == -1)
1434 return -errno;
1436 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1437 return -errno;
1439 return 0;
1442 #if defined(__linux__)
1444 #define RTC_FREQ 1024
1446 static void enable_sigio_timer(int fd)
1448 struct sigaction act;
1450 /* timer signal */
1451 sigfillset(&act.sa_mask);
1452 act.sa_flags = 0;
1453 act.sa_handler = host_alarm_handler;
1455 sigaction(SIGIO, &act, NULL);
1456 fcntl_setfl(fd, O_ASYNC);
1457 fcntl(fd, F_SETOWN, getpid());
1460 static int hpet_start_timer(struct qemu_alarm_timer *t)
1462 struct hpet_info info;
1463 int r, fd;
1465 fd = open("/dev/hpet", O_RDONLY);
1466 if (fd < 0)
1467 return -1;
1469 /* Set frequency */
1470 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1471 if (r < 0) {
1472 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1473 "error, but for better emulation accuracy type:\n"
1474 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1475 goto fail;
1478 /* Check capabilities */
1479 r = ioctl(fd, HPET_INFO, &info);
1480 if (r < 0)
1481 goto fail;
1483 /* Enable periodic mode */
1484 r = ioctl(fd, HPET_EPI, 0);
1485 if (info.hi_flags && (r < 0))
1486 goto fail;
1488 /* Enable interrupt */
1489 r = ioctl(fd, HPET_IE_ON, 0);
1490 if (r < 0)
1491 goto fail;
1493 enable_sigio_timer(fd);
1494 t->priv = (void *)(long)fd;
1496 return 0;
1497 fail:
1498 close(fd);
1499 return -1;
1502 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1504 int fd = (long)t->priv;
1506 close(fd);
1509 static int rtc_start_timer(struct qemu_alarm_timer *t)
1511 int rtc_fd;
1512 unsigned long current_rtc_freq = 0;
1514 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1515 if (rtc_fd < 0)
1516 return -1;
1517 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1518 if (current_rtc_freq != RTC_FREQ &&
1519 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1520 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1521 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1522 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1523 goto fail;
1525 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1526 fail:
1527 close(rtc_fd);
1528 return -1;
1531 enable_sigio_timer(rtc_fd);
1533 t->priv = (void *)(long)rtc_fd;
1535 return 0;
1538 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1540 int rtc_fd = (long)t->priv;
1542 close(rtc_fd);
1545 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1547 struct sigevent ev;
1548 timer_t host_timer;
1549 struct sigaction act;
1551 sigfillset(&act.sa_mask);
1552 act.sa_flags = 0;
1553 act.sa_handler = host_alarm_handler;
1555 sigaction(SIGALRM, &act, NULL);
1557 ev.sigev_value.sival_int = 0;
1558 ev.sigev_notify = SIGEV_SIGNAL;
1559 ev.sigev_signo = SIGALRM;
1561 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1562 perror("timer_create");
1564 /* disable dynticks */
1565 fprintf(stderr, "Dynamic Ticks disabled\n");
1567 return -1;
1570 t->priv = (void *)(long)host_timer;
1572 return 0;
1575 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1577 timer_t host_timer = (timer_t)(long)t->priv;
1579 timer_delete(host_timer);
1582 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1584 timer_t host_timer = (timer_t)(long)t->priv;
1585 struct itimerspec timeout;
1586 int64_t nearest_delta_us = INT64_MAX;
1587 int64_t current_us;
1589 if (!active_timers[QEMU_TIMER_REALTIME] &&
1590 !active_timers[QEMU_TIMER_VIRTUAL])
1591 return;
1593 nearest_delta_us = qemu_next_deadline_dyntick();
1595 /* check whether a timer is already running */
1596 if (timer_gettime(host_timer, &timeout)) {
1597 perror("gettime");
1598 fprintf(stderr, "Internal timer error: aborting\n");
1599 exit(1);
1601 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1602 if (current_us && current_us <= nearest_delta_us)
1603 return;
1605 timeout.it_interval.tv_sec = 0;
1606 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1607 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1608 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1609 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1610 perror("settime");
1611 fprintf(stderr, "Internal timer error: aborting\n");
1612 exit(1);
1616 #endif /* defined(__linux__) */
1618 static int unix_start_timer(struct qemu_alarm_timer *t)
1620 struct sigaction act;
1621 struct itimerval itv;
1622 int err;
1624 /* timer signal */
1625 sigfillset(&act.sa_mask);
1626 act.sa_flags = 0;
1627 act.sa_handler = host_alarm_handler;
1629 sigaction(SIGALRM, &act, NULL);
1631 itv.it_interval.tv_sec = 0;
1632 /* for i386 kernel 2.6 to get 1 ms */
1633 itv.it_interval.tv_usec = 999;
1634 itv.it_value.tv_sec = 0;
1635 itv.it_value.tv_usec = 10 * 1000;
1637 err = setitimer(ITIMER_REAL, &itv, NULL);
1638 if (err)
1639 return -1;
1641 return 0;
1644 static void unix_stop_timer(struct qemu_alarm_timer *t)
1646 struct itimerval itv;
1648 memset(&itv, 0, sizeof(itv));
1649 setitimer(ITIMER_REAL, &itv, NULL);
1652 #endif /* !defined(_WIN32) */
1654 static void try_to_rearm_timer(void *opaque)
1656 struct qemu_alarm_timer *t = opaque;
1657 #ifndef _WIN32
1658 ssize_t len;
1660 /* Drain the notify pipe */
1661 do {
1662 char buffer[512];
1663 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1664 } while ((len == -1 && errno == EINTR) || len > 0);
1665 #endif
1667 if (t->flags & ALARM_FLAG_EXPIRED) {
1668 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1669 qemu_rearm_alarm_timer(alarm_timer);
1673 #ifdef _WIN32
1675 static int win32_start_timer(struct qemu_alarm_timer *t)
1677 TIMECAPS tc;
1678 struct qemu_alarm_win32 *data = t->priv;
1679 UINT flags;
1681 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1682 if (!data->host_alarm) {
1683 perror("Failed CreateEvent");
1684 return -1;
1687 memset(&tc, 0, sizeof(tc));
1688 timeGetDevCaps(&tc, sizeof(tc));
1690 if (data->period < tc.wPeriodMin)
1691 data->period = tc.wPeriodMin;
1693 timeBeginPeriod(data->period);
1695 flags = TIME_CALLBACK_FUNCTION;
1696 if (alarm_has_dynticks(t))
1697 flags |= TIME_ONESHOT;
1698 else
1699 flags |= TIME_PERIODIC;
1701 data->timerId = timeSetEvent(1, // interval (ms)
1702 data->period, // resolution
1703 host_alarm_handler, // function
1704 (DWORD)t, // parameter
1705 flags);
1707 if (!data->timerId) {
1708 perror("Failed to initialize win32 alarm timer");
1710 timeEndPeriod(data->period);
1711 CloseHandle(data->host_alarm);
1712 return -1;
1715 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1717 return 0;
1720 static void win32_stop_timer(struct qemu_alarm_timer *t)
1722 struct qemu_alarm_win32 *data = t->priv;
1724 timeKillEvent(data->timerId);
1725 timeEndPeriod(data->period);
1727 CloseHandle(data->host_alarm);
1730 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1732 struct qemu_alarm_win32 *data = t->priv;
1733 uint64_t nearest_delta_us;
1735 if (!active_timers[QEMU_TIMER_REALTIME] &&
1736 !active_timers[QEMU_TIMER_VIRTUAL])
1737 return;
1739 nearest_delta_us = qemu_next_deadline_dyntick();
1740 nearest_delta_us /= 1000;
1742 timeKillEvent(data->timerId);
1744 data->timerId = timeSetEvent(1,
1745 data->period,
1746 host_alarm_handler,
1747 (DWORD)t,
1748 TIME_ONESHOT | TIME_PERIODIC);
1750 if (!data->timerId) {
1751 perror("Failed to re-arm win32 alarm timer");
1753 timeEndPeriod(data->period);
1754 CloseHandle(data->host_alarm);
1755 exit(1);
1759 #endif /* _WIN32 */
1761 static int init_timer_alarm(void)
1763 struct qemu_alarm_timer *t = NULL;
1764 int i, err = -1;
1766 #ifndef _WIN32
1767 int fds[2];
1769 err = pipe(fds);
1770 if (err == -1)
1771 return -errno;
1773 err = fcntl_setfl(fds[0], O_NONBLOCK);
1774 if (err < 0)
1775 goto fail;
1777 err = fcntl_setfl(fds[1], O_NONBLOCK);
1778 if (err < 0)
1779 goto fail;
1781 alarm_timer_rfd = fds[0];
1782 alarm_timer_wfd = fds[1];
1783 #endif
1785 for (i = 0; alarm_timers[i].name; i++) {
1786 t = &alarm_timers[i];
1788 err = t->start(t);
1789 if (!err)
1790 break;
1793 if (err) {
1794 err = -ENOENT;
1795 goto fail;
1798 #ifndef _WIN32
1799 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1800 try_to_rearm_timer, NULL, t);
1801 #endif
1803 alarm_timer = t;
1805 return 0;
1807 fail:
1808 #ifndef _WIN32
1809 close(fds[0]);
1810 close(fds[1]);
1811 #endif
1812 return err;
1815 static void quit_timers(void)
1817 alarm_timer->stop(alarm_timer);
1818 alarm_timer = NULL;
1821 /***********************************************************/
1822 /* host time/date access */
1823 void qemu_get_timedate(struct tm *tm, int offset)
1825 time_t ti;
1826 struct tm *ret;
1828 time(&ti);
1829 ti += offset;
1830 if (rtc_date_offset == -1) {
1831 if (rtc_utc)
1832 ret = gmtime(&ti);
1833 else
1834 ret = localtime(&ti);
1835 } else {
1836 ti -= rtc_date_offset;
1837 ret = gmtime(&ti);
1840 memcpy(tm, ret, sizeof(struct tm));
1843 int qemu_timedate_diff(struct tm *tm)
1845 time_t seconds;
1847 if (rtc_date_offset == -1)
1848 if (rtc_utc)
1849 seconds = mktimegm(tm);
1850 else
1851 seconds = mktime(tm);
1852 else
1853 seconds = mktimegm(tm) + rtc_date_offset;
1855 return seconds - time(NULL);
1858 #ifdef _WIN32
1859 static void socket_cleanup(void)
1861 WSACleanup();
1864 static int socket_init(void)
1866 WSADATA Data;
1867 int ret, err;
1869 ret = WSAStartup(MAKEWORD(2,2), &Data);
1870 if (ret != 0) {
1871 err = WSAGetLastError();
1872 fprintf(stderr, "WSAStartup: %d\n", err);
1873 return -1;
1875 atexit(socket_cleanup);
1876 return 0;
1878 #endif
1880 const char *get_opt_name(char *buf, int buf_size, const char *p)
1882 char *q;
1884 q = buf;
1885 while (*p != '\0' && *p != '=') {
1886 if (q && (q - buf) < buf_size - 1)
1887 *q++ = *p;
1888 p++;
1890 if (q)
1891 *q = '\0';
1893 return p;
1896 const char *get_opt_value(char *buf, int buf_size, const char *p)
1898 char *q;
1900 q = buf;
1901 while (*p != '\0') {
1902 if (*p == ',') {
1903 if (*(p + 1) != ',')
1904 break;
1905 p++;
1907 if (q && (q - buf) < buf_size - 1)
1908 *q++ = *p;
1909 p++;
1911 if (q)
1912 *q = '\0';
1914 return p;
1917 int get_param_value(char *buf, int buf_size,
1918 const char *tag, const char *str)
1920 const char *p;
1921 char option[128];
1923 p = str;
1924 for(;;) {
1925 p = get_opt_name(option, sizeof(option), p);
1926 if (*p != '=')
1927 break;
1928 p++;
1929 if (!strcmp(tag, option)) {
1930 (void)get_opt_value(buf, buf_size, p);
1931 return strlen(buf);
1932 } else {
1933 p = get_opt_value(NULL, 0, p);
1935 if (*p != ',')
1936 break;
1937 p++;
1939 return 0;
1942 int check_params(char *buf, int buf_size,
1943 const char * const *params, const char *str)
1945 const char *p;
1946 int i;
1948 p = str;
1949 for(;;) {
1950 p = get_opt_name(buf, buf_size, p);
1951 if (*p != '=')
1952 return -1;
1953 p++;
1954 for(i = 0; params[i] != NULL; i++)
1955 if (!strcmp(params[i], buf))
1956 break;
1957 if (params[i] == NULL)
1958 return -1;
1959 p = get_opt_value(NULL, 0, p);
1960 if (*p != ',')
1961 break;
1962 p++;
1964 return 0;
1967 /***********************************************************/
1968 /* Bluetooth support */
1969 static int nb_hcis;
1970 static int cur_hci;
1971 static struct HCIInfo *hci_table[MAX_NICS];
1973 static struct bt_vlan_s {
1974 struct bt_scatternet_s net;
1975 int id;
1976 struct bt_vlan_s *next;
1977 } *first_bt_vlan;
1979 /* find or alloc a new bluetooth "VLAN" */
1980 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1982 struct bt_vlan_s **pvlan, *vlan;
1983 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1984 if (vlan->id == id)
1985 return &vlan->net;
1987 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1988 vlan->id = id;
1989 pvlan = &first_bt_vlan;
1990 while (*pvlan != NULL)
1991 pvlan = &(*pvlan)->next;
1992 *pvlan = vlan;
1993 return &vlan->net;
1996 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2000 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2002 return -ENOTSUP;
2005 static struct HCIInfo null_hci = {
2006 .cmd_send = null_hci_send,
2007 .sco_send = null_hci_send,
2008 .acl_send = null_hci_send,
2009 .bdaddr_set = null_hci_addr_set,
2012 struct HCIInfo *qemu_next_hci(void)
2014 if (cur_hci == nb_hcis)
2015 return &null_hci;
2017 return hci_table[cur_hci++];
2020 static struct HCIInfo *hci_init(const char *str)
2022 char *endp;
2023 struct bt_scatternet_s *vlan = 0;
2025 if (!strcmp(str, "null"))
2026 /* null */
2027 return &null_hci;
2028 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2029 /* host[:hciN] */
2030 return bt_host_hci(str[4] ? str + 5 : "hci0");
2031 else if (!strncmp(str, "hci", 3)) {
2032 /* hci[,vlan=n] */
2033 if (str[3]) {
2034 if (!strncmp(str + 3, ",vlan=", 6)) {
2035 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2036 if (*endp)
2037 vlan = 0;
2039 } else
2040 vlan = qemu_find_bt_vlan(0);
2041 if (vlan)
2042 return bt_new_hci(vlan);
2045 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2047 return 0;
2050 static int bt_hci_parse(const char *str)
2052 struct HCIInfo *hci;
2053 bdaddr_t bdaddr;
2055 if (nb_hcis >= MAX_NICS) {
2056 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2057 return -1;
2060 hci = hci_init(str);
2061 if (!hci)
2062 return -1;
2064 bdaddr.b[0] = 0x52;
2065 bdaddr.b[1] = 0x54;
2066 bdaddr.b[2] = 0x00;
2067 bdaddr.b[3] = 0x12;
2068 bdaddr.b[4] = 0x34;
2069 bdaddr.b[5] = 0x56 + nb_hcis;
2070 hci->bdaddr_set(hci, bdaddr.b);
2072 hci_table[nb_hcis++] = hci;
2074 return 0;
2077 static void bt_vhci_add(int vlan_id)
2079 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2081 if (!vlan->slave)
2082 fprintf(stderr, "qemu: warning: adding a VHCI to "
2083 "an empty scatternet %i\n", vlan_id);
2085 bt_vhci_init(bt_new_hci(vlan));
2088 static struct bt_device_s *bt_device_add(const char *opt)
2090 struct bt_scatternet_s *vlan;
2091 int vlan_id = 0;
2092 char *endp = strstr(opt, ",vlan=");
2093 int len = (endp ? endp - opt : strlen(opt)) + 1;
2094 char devname[10];
2096 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2098 if (endp) {
2099 vlan_id = strtol(endp + 6, &endp, 0);
2100 if (*endp) {
2101 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2102 return 0;
2106 vlan = qemu_find_bt_vlan(vlan_id);
2108 if (!vlan->slave)
2109 fprintf(stderr, "qemu: warning: adding a slave device to "
2110 "an empty scatternet %i\n", vlan_id);
2112 if (!strcmp(devname, "keyboard"))
2113 return bt_keyboard_init(vlan);
2115 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2116 return 0;
2119 static int bt_parse(const char *opt)
2121 const char *endp, *p;
2122 int vlan;
2124 if (strstart(opt, "hci", &endp)) {
2125 if (!*endp || *endp == ',') {
2126 if (*endp)
2127 if (!strstart(endp, ",vlan=", 0))
2128 opt = endp + 1;
2130 return bt_hci_parse(opt);
2132 } else if (strstart(opt, "vhci", &endp)) {
2133 if (!*endp || *endp == ',') {
2134 if (*endp) {
2135 if (strstart(endp, ",vlan=", &p)) {
2136 vlan = strtol(p, (char **) &endp, 0);
2137 if (*endp) {
2138 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2139 return 1;
2141 } else {
2142 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2143 return 1;
2145 } else
2146 vlan = 0;
2148 bt_vhci_add(vlan);
2149 return 0;
2151 } else if (strstart(opt, "device:", &endp))
2152 return !bt_device_add(endp);
2154 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2155 return 1;
2158 /***********************************************************/
2159 /* QEMU Block devices */
2161 #define HD_ALIAS "index=%d,media=disk"
2162 #ifdef TARGET_PPC
2163 #define CDROM_ALIAS "index=1,media=cdrom"
2164 #else
2165 #define CDROM_ALIAS "index=2,media=cdrom"
2166 #endif
2167 #define FD_ALIAS "index=%d,if=floppy"
2168 #define PFLASH_ALIAS "if=pflash"
2169 #define MTD_ALIAS "if=mtd"
2170 #define SD_ALIAS "index=0,if=sd"
2172 static int drive_opt_get_free_idx(void)
2174 int index;
2176 for (index = 0; index < MAX_DRIVES; index++)
2177 if (!drives_opt[index].used) {
2178 drives_opt[index].used = 1;
2179 return index;
2182 return -1;
2185 static int drive_get_free_idx(void)
2187 int index;
2189 for (index = 0; index < MAX_DRIVES; index++)
2190 if (!drives_table[index].used) {
2191 drives_table[index].used = 1;
2192 return index;
2195 return -1;
2198 int drive_add(const char *file, const char *fmt, ...)
2200 va_list ap;
2201 int index = drive_opt_get_free_idx();
2203 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2204 fprintf(stderr, "qemu: too many drives\n");
2205 return -1;
2208 drives_opt[index].file = file;
2209 va_start(ap, fmt);
2210 vsnprintf(drives_opt[index].opt,
2211 sizeof(drives_opt[0].opt), fmt, ap);
2212 va_end(ap);
2214 nb_drives_opt++;
2215 return index;
2218 void drive_remove(int index)
2220 drives_opt[index].used = 0;
2221 nb_drives_opt--;
2224 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2226 int index;
2228 /* seek interface, bus and unit */
2230 for (index = 0; index < MAX_DRIVES; index++)
2231 if (drives_table[index].type == type &&
2232 drives_table[index].bus == bus &&
2233 drives_table[index].unit == unit &&
2234 drives_table[index].used)
2235 return index;
2237 return -1;
2240 int drive_get_max_bus(BlockInterfaceType type)
2242 int max_bus;
2243 int index;
2245 max_bus = -1;
2246 for (index = 0; index < nb_drives; index++) {
2247 if(drives_table[index].type == type &&
2248 drives_table[index].bus > max_bus)
2249 max_bus = drives_table[index].bus;
2251 return max_bus;
2254 const char *drive_get_serial(BlockDriverState *bdrv)
2256 int index;
2258 for (index = 0; index < nb_drives; index++)
2259 if (drives_table[index].bdrv == bdrv)
2260 return drives_table[index].serial;
2262 return "\0";
2265 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2267 int index;
2269 for (index = 0; index < nb_drives; index++)
2270 if (drives_table[index].bdrv == bdrv)
2271 return drives_table[index].onerror;
2273 return BLOCK_ERR_REPORT;
2276 static void bdrv_format_print(void *opaque, const char *name)
2278 fprintf(stderr, " %s", name);
2281 void drive_uninit(BlockDriverState *bdrv)
2283 int i;
2285 for (i = 0; i < MAX_DRIVES; i++)
2286 if (drives_table[i].bdrv == bdrv) {
2287 drives_table[i].bdrv = NULL;
2288 drives_table[i].used = 0;
2289 drive_remove(drives_table[i].drive_opt_idx);
2290 nb_drives--;
2291 break;
2295 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2297 char buf[128];
2298 char file[1024];
2299 char devname[128];
2300 char serial[21];
2301 const char *mediastr = "";
2302 BlockInterfaceType type;
2303 enum { MEDIA_DISK, MEDIA_CDROM } media;
2304 int bus_id, unit_id;
2305 int cyls, heads, secs, translation;
2306 BlockDriverState *bdrv;
2307 BlockDriver *drv = NULL;
2308 QEMUMachine *machine = opaque;
2309 int max_devs;
2310 int index;
2311 int cache;
2312 int bdrv_flags, onerror;
2313 int drives_table_idx;
2314 char *str = arg->opt;
2315 static const char * const params[] = { "bus", "unit", "if", "index",
2316 "cyls", "heads", "secs", "trans",
2317 "media", "snapshot", "file",
2318 "cache", "format", "serial", "werror",
2319 "boot", NULL };
2321 if (check_params(buf, sizeof(buf), params, str) < 0) {
2322 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2323 buf, str);
2324 return -1;
2327 file[0] = 0;
2328 cyls = heads = secs = 0;
2329 bus_id = 0;
2330 unit_id = -1;
2331 translation = BIOS_ATA_TRANSLATION_AUTO;
2332 index = -1;
2333 cache = 3;
2335 if (machine->use_scsi) {
2336 type = IF_SCSI;
2337 max_devs = MAX_SCSI_DEVS;
2338 pstrcpy(devname, sizeof(devname), "scsi");
2339 } else {
2340 type = IF_IDE;
2341 max_devs = MAX_IDE_DEVS;
2342 pstrcpy(devname, sizeof(devname), "ide");
2344 media = MEDIA_DISK;
2346 /* extract parameters */
2348 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2349 bus_id = strtol(buf, NULL, 0);
2350 if (bus_id < 0) {
2351 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2352 return -1;
2356 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2357 unit_id = strtol(buf, NULL, 0);
2358 if (unit_id < 0) {
2359 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2360 return -1;
2364 if (get_param_value(buf, sizeof(buf), "if", str)) {
2365 pstrcpy(devname, sizeof(devname), buf);
2366 if (!strcmp(buf, "ide")) {
2367 type = IF_IDE;
2368 max_devs = MAX_IDE_DEVS;
2369 } else if (!strcmp(buf, "scsi")) {
2370 type = IF_SCSI;
2371 max_devs = MAX_SCSI_DEVS;
2372 } else if (!strcmp(buf, "floppy")) {
2373 type = IF_FLOPPY;
2374 max_devs = 0;
2375 } else if (!strcmp(buf, "pflash")) {
2376 type = IF_PFLASH;
2377 max_devs = 0;
2378 } else if (!strcmp(buf, "mtd")) {
2379 type = IF_MTD;
2380 max_devs = 0;
2381 } else if (!strcmp(buf, "sd")) {
2382 type = IF_SD;
2383 max_devs = 0;
2384 } else if (!strcmp(buf, "virtio")) {
2385 type = IF_VIRTIO;
2386 max_devs = 0;
2387 } else {
2388 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2389 return -1;
2393 if (get_param_value(buf, sizeof(buf), "index", str)) {
2394 index = strtol(buf, NULL, 0);
2395 if (index < 0) {
2396 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2397 return -1;
2401 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2402 cyls = strtol(buf, NULL, 0);
2405 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2406 heads = strtol(buf, NULL, 0);
2409 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2410 secs = strtol(buf, NULL, 0);
2413 if (cyls || heads || secs) {
2414 if (cyls < 1 || cyls > 16383) {
2415 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2416 return -1;
2418 if (heads < 1 || heads > 16) {
2419 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2420 return -1;
2422 if (secs < 1 || secs > 63) {
2423 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2424 return -1;
2428 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2429 if (!cyls) {
2430 fprintf(stderr,
2431 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2432 str);
2433 return -1;
2435 if (!strcmp(buf, "none"))
2436 translation = BIOS_ATA_TRANSLATION_NONE;
2437 else if (!strcmp(buf, "lba"))
2438 translation = BIOS_ATA_TRANSLATION_LBA;
2439 else if (!strcmp(buf, "auto"))
2440 translation = BIOS_ATA_TRANSLATION_AUTO;
2441 else {
2442 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2443 return -1;
2447 if (get_param_value(buf, sizeof(buf), "media", str)) {
2448 if (!strcmp(buf, "disk")) {
2449 media = MEDIA_DISK;
2450 } else if (!strcmp(buf, "cdrom")) {
2451 if (cyls || secs || heads) {
2452 fprintf(stderr,
2453 "qemu: '%s' invalid physical CHS format\n", str);
2454 return -1;
2456 media = MEDIA_CDROM;
2457 } else {
2458 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2459 return -1;
2463 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2464 if (!strcmp(buf, "on"))
2465 snapshot = 1;
2466 else if (!strcmp(buf, "off"))
2467 snapshot = 0;
2468 else {
2469 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2470 return -1;
2474 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2475 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2476 cache = 0;
2477 else if (!strcmp(buf, "writethrough"))
2478 cache = 1;
2479 else if (!strcmp(buf, "writeback"))
2480 cache = 2;
2481 else {
2482 fprintf(stderr, "qemu: invalid cache option\n");
2483 return -1;
2487 if (get_param_value(buf, sizeof(buf), "format", str)) {
2488 if (strcmp(buf, "?") == 0) {
2489 fprintf(stderr, "qemu: Supported formats:");
2490 bdrv_iterate_format(bdrv_format_print, NULL);
2491 fprintf(stderr, "\n");
2492 return -1;
2494 drv = bdrv_find_format(buf);
2495 if (!drv) {
2496 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2497 return -1;
2501 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2502 if (!strcmp(buf, "on")) {
2503 if (extboot_drive != -1) {
2504 fprintf(stderr, "qemu: two bootable drives specified\n");
2505 return -1;
2507 extboot_drive = nb_drives;
2508 } else if (strcmp(buf, "off")) {
2509 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2510 return -1;
2514 if (arg->file == NULL)
2515 get_param_value(file, sizeof(file), "file", str);
2516 else
2517 pstrcpy(file, sizeof(file), arg->file);
2519 if (!get_param_value(serial, sizeof(serial), "serial", str))
2520 memset(serial, 0, sizeof(serial));
2522 onerror = BLOCK_ERR_REPORT;
2523 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2524 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2525 fprintf(stderr, "werror is no supported by this format\n");
2526 return -1;
2528 if (!strcmp(buf, "ignore"))
2529 onerror = BLOCK_ERR_IGNORE;
2530 else if (!strcmp(buf, "enospc"))
2531 onerror = BLOCK_ERR_STOP_ENOSPC;
2532 else if (!strcmp(buf, "stop"))
2533 onerror = BLOCK_ERR_STOP_ANY;
2534 else if (!strcmp(buf, "report"))
2535 onerror = BLOCK_ERR_REPORT;
2536 else {
2537 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2538 return -1;
2542 /* compute bus and unit according index */
2544 if (index != -1) {
2545 if (bus_id != 0 || unit_id != -1) {
2546 fprintf(stderr,
2547 "qemu: '%s' index cannot be used with bus and unit\n", str);
2548 return -1;
2550 if (max_devs == 0)
2552 unit_id = index;
2553 bus_id = 0;
2554 } else {
2555 unit_id = index % max_devs;
2556 bus_id = index / max_devs;
2560 /* if user doesn't specify a unit_id,
2561 * try to find the first free
2564 if (unit_id == -1) {
2565 unit_id = 0;
2566 while (drive_get_index(type, bus_id, unit_id) != -1) {
2567 unit_id++;
2568 if (max_devs && unit_id >= max_devs) {
2569 unit_id -= max_devs;
2570 bus_id++;
2575 /* check unit id */
2577 if (max_devs && unit_id >= max_devs) {
2578 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2579 str, unit_id, max_devs - 1);
2580 return -1;
2584 * ignore multiple definitions
2587 if (drive_get_index(type, bus_id, unit_id) != -1)
2588 return -2;
2590 /* init */
2592 if (type == IF_IDE || type == IF_SCSI)
2593 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2594 if (max_devs)
2595 snprintf(buf, sizeof(buf), "%s%i%s%i",
2596 devname, bus_id, mediastr, unit_id);
2597 else
2598 snprintf(buf, sizeof(buf), "%s%s%i",
2599 devname, mediastr, unit_id);
2600 bdrv = bdrv_new(buf);
2601 drives_table_idx = drive_get_free_idx();
2602 drives_table[drives_table_idx].bdrv = bdrv;
2603 drives_table[drives_table_idx].type = type;
2604 drives_table[drives_table_idx].bus = bus_id;
2605 drives_table[drives_table_idx].unit = unit_id;
2606 drives_table[drives_table_idx].onerror = onerror;
2607 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2608 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2609 nb_drives++;
2611 switch(type) {
2612 case IF_IDE:
2613 case IF_SCSI:
2614 switch(media) {
2615 case MEDIA_DISK:
2616 if (cyls != 0) {
2617 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2618 bdrv_set_translation_hint(bdrv, translation);
2620 break;
2621 case MEDIA_CDROM:
2622 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2623 break;
2625 break;
2626 case IF_SD:
2627 /* FIXME: This isn't really a floppy, but it's a reasonable
2628 approximation. */
2629 case IF_FLOPPY:
2630 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2631 break;
2632 case IF_PFLASH:
2633 case IF_MTD:
2634 case IF_VIRTIO:
2635 break;
2637 if (!file[0])
2638 return -2;
2639 bdrv_flags = 0;
2640 if (snapshot) {
2641 bdrv_flags |= BDRV_O_SNAPSHOT;
2642 cache = 2; /* always use write-back with snapshot */
2644 if (cache == 0) /* no caching */
2645 bdrv_flags |= BDRV_O_NOCACHE;
2646 else if (cache == 2) /* write-back */
2647 bdrv_flags |= BDRV_O_CACHE_WB;
2648 else if (cache == 3) /* not specified */
2649 bdrv_flags |= BDRV_O_CACHE_DEF;
2650 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2651 fprintf(stderr, "qemu: could not open disk image %s\n",
2652 file);
2653 return -1;
2655 return drives_table_idx;
2658 /***********************************************************/
2659 /* USB devices */
2661 static USBPort *used_usb_ports;
2662 static USBPort *free_usb_ports;
2664 /* ??? Maybe change this to register a hub to keep track of the topology. */
2665 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2666 usb_attachfn attach)
2668 port->opaque = opaque;
2669 port->index = index;
2670 port->attach = attach;
2671 port->next = free_usb_ports;
2672 free_usb_ports = port;
2675 int usb_device_add_dev(USBDevice *dev)
2677 USBPort *port;
2679 /* Find a USB port to add the device to. */
2680 port = free_usb_ports;
2681 if (!port->next) {
2682 USBDevice *hub;
2684 /* Create a new hub and chain it on. */
2685 free_usb_ports = NULL;
2686 port->next = used_usb_ports;
2687 used_usb_ports = port;
2689 hub = usb_hub_init(VM_USB_HUB_SIZE);
2690 usb_attach(port, hub);
2691 port = free_usb_ports;
2694 free_usb_ports = port->next;
2695 port->next = used_usb_ports;
2696 used_usb_ports = port;
2697 usb_attach(port, dev);
2698 return 0;
2701 static int usb_device_add(const char *devname)
2703 const char *p;
2704 USBDevice *dev;
2706 if (!free_usb_ports)
2707 return -1;
2709 if (strstart(devname, "host:", &p)) {
2710 dev = usb_host_device_open(p);
2711 } else if (!strcmp(devname, "mouse")) {
2712 dev = usb_mouse_init();
2713 } else if (!strcmp(devname, "tablet")) {
2714 dev = usb_tablet_init();
2715 } else if (!strcmp(devname, "keyboard")) {
2716 dev = usb_keyboard_init();
2717 } else if (strstart(devname, "disk:", &p)) {
2718 dev = usb_msd_init(p);
2719 } else if (!strcmp(devname, "wacom-tablet")) {
2720 dev = usb_wacom_init();
2721 } else if (strstart(devname, "serial:", &p)) {
2722 dev = usb_serial_init(p);
2723 #ifdef CONFIG_BRLAPI
2724 } else if (!strcmp(devname, "braille")) {
2725 dev = usb_baum_init();
2726 #endif
2727 } else if (strstart(devname, "net:", &p)) {
2728 int nic = nb_nics;
2730 if (net_client_init("nic", p) < 0)
2731 return -1;
2732 nd_table[nic].model = "usb";
2733 dev = usb_net_init(&nd_table[nic]);
2734 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2735 dev = usb_bt_init(devname[2] ? hci_init(p) :
2736 bt_new_hci(qemu_find_bt_vlan(0)));
2737 } else {
2738 return -1;
2740 if (!dev)
2741 return -1;
2743 return usb_device_add_dev(dev);
2746 int usb_device_del_addr(int bus_num, int addr)
2748 USBPort *port;
2749 USBPort **lastp;
2750 USBDevice *dev;
2752 if (!used_usb_ports)
2753 return -1;
2755 if (bus_num != 0)
2756 return -1;
2758 lastp = &used_usb_ports;
2759 port = used_usb_ports;
2760 while (port && port->dev->addr != addr) {
2761 lastp = &port->next;
2762 port = port->next;
2765 if (!port)
2766 return -1;
2768 dev = port->dev;
2769 *lastp = port->next;
2770 usb_attach(port, NULL);
2771 dev->handle_destroy(dev);
2772 port->next = free_usb_ports;
2773 free_usb_ports = port;
2774 return 0;
2777 static int usb_device_del(const char *devname)
2779 int bus_num, addr;
2780 const char *p;
2782 if (strstart(devname, "host:", &p))
2783 return usb_host_device_close(p);
2785 if (!used_usb_ports)
2786 return -1;
2788 p = strchr(devname, '.');
2789 if (!p)
2790 return -1;
2791 bus_num = strtoul(devname, NULL, 0);
2792 addr = strtoul(p + 1, NULL, 0);
2794 return usb_device_del_addr(bus_num, addr);
2797 void do_usb_add(const char *devname)
2799 usb_device_add(devname);
2802 void do_usb_del(const char *devname)
2804 usb_device_del(devname);
2807 void usb_info(void)
2809 USBDevice *dev;
2810 USBPort *port;
2811 const char *speed_str;
2813 if (!usb_enabled) {
2814 term_printf("USB support not enabled\n");
2815 return;
2818 for (port = used_usb_ports; port; port = port->next) {
2819 dev = port->dev;
2820 if (!dev)
2821 continue;
2822 switch(dev->speed) {
2823 case USB_SPEED_LOW:
2824 speed_str = "1.5";
2825 break;
2826 case USB_SPEED_FULL:
2827 speed_str = "12";
2828 break;
2829 case USB_SPEED_HIGH:
2830 speed_str = "480";
2831 break;
2832 default:
2833 speed_str = "?";
2834 break;
2836 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2837 0, dev->addr, speed_str, dev->devname);
2841 /***********************************************************/
2842 /* PCMCIA/Cardbus */
2844 static struct pcmcia_socket_entry_s {
2845 struct pcmcia_socket_s *socket;
2846 struct pcmcia_socket_entry_s *next;
2847 } *pcmcia_sockets = 0;
2849 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2851 struct pcmcia_socket_entry_s *entry;
2853 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2854 entry->socket = socket;
2855 entry->next = pcmcia_sockets;
2856 pcmcia_sockets = entry;
2859 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2861 struct pcmcia_socket_entry_s *entry, **ptr;
2863 ptr = &pcmcia_sockets;
2864 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2865 if (entry->socket == socket) {
2866 *ptr = entry->next;
2867 qemu_free(entry);
2871 void pcmcia_info(void)
2873 struct pcmcia_socket_entry_s *iter;
2874 if (!pcmcia_sockets)
2875 term_printf("No PCMCIA sockets\n");
2877 for (iter = pcmcia_sockets; iter; iter = iter->next)
2878 term_printf("%s: %s\n", iter->socket->slot_string,
2879 iter->socket->attached ? iter->socket->card_string :
2880 "Empty");
2883 /***********************************************************/
2884 /* register display */
2886 void register_displaystate(DisplayState *ds)
2888 DisplayState **s;
2889 s = &display_state;
2890 while (*s != NULL)
2891 s = &(*s)->next;
2892 ds->next = NULL;
2893 *s = ds;
2896 DisplayState *get_displaystate(void)
2898 return display_state;
2901 /* dumb display */
2903 static void dumb_display_init(void)
2905 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2906 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2907 register_displaystate(ds);
2910 /***********************************************************/
2911 /* I/O handling */
2913 #define MAX_IO_HANDLERS 64
2915 typedef struct IOHandlerRecord {
2916 int fd;
2917 IOCanRWHandler *fd_read_poll;
2918 IOHandler *fd_read;
2919 IOHandler *fd_write;
2920 int deleted;
2921 void *opaque;
2922 /* temporary data */
2923 struct pollfd *ufd;
2924 struct IOHandlerRecord *next;
2925 } IOHandlerRecord;
2927 static IOHandlerRecord *first_io_handler;
2929 /* XXX: fd_read_poll should be suppressed, but an API change is
2930 necessary in the character devices to suppress fd_can_read(). */
2931 int qemu_set_fd_handler2(int fd,
2932 IOCanRWHandler *fd_read_poll,
2933 IOHandler *fd_read,
2934 IOHandler *fd_write,
2935 void *opaque)
2937 IOHandlerRecord **pioh, *ioh;
2939 if (!fd_read && !fd_write) {
2940 pioh = &first_io_handler;
2941 for(;;) {
2942 ioh = *pioh;
2943 if (ioh == NULL)
2944 break;
2945 if (ioh->fd == fd) {
2946 ioh->deleted = 1;
2947 break;
2949 pioh = &ioh->next;
2951 } else {
2952 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2953 if (ioh->fd == fd)
2954 goto found;
2956 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2957 ioh->next = first_io_handler;
2958 first_io_handler = ioh;
2959 found:
2960 ioh->fd = fd;
2961 ioh->fd_read_poll = fd_read_poll;
2962 ioh->fd_read = fd_read;
2963 ioh->fd_write = fd_write;
2964 ioh->opaque = opaque;
2965 ioh->deleted = 0;
2967 main_loop_break();
2968 return 0;
2971 int qemu_set_fd_handler(int fd,
2972 IOHandler *fd_read,
2973 IOHandler *fd_write,
2974 void *opaque)
2976 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2979 #ifdef _WIN32
2980 /***********************************************************/
2981 /* Polling handling */
2983 typedef struct PollingEntry {
2984 PollingFunc *func;
2985 void *opaque;
2986 struct PollingEntry *next;
2987 } PollingEntry;
2989 static PollingEntry *first_polling_entry;
2991 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2993 PollingEntry **ppe, *pe;
2994 pe = qemu_mallocz(sizeof(PollingEntry));
2995 pe->func = func;
2996 pe->opaque = opaque;
2997 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2998 *ppe = pe;
2999 return 0;
3002 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3004 PollingEntry **ppe, *pe;
3005 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3006 pe = *ppe;
3007 if (pe->func == func && pe->opaque == opaque) {
3008 *ppe = pe->next;
3009 qemu_free(pe);
3010 break;
3015 /***********************************************************/
3016 /* Wait objects support */
3017 typedef struct WaitObjects {
3018 int num;
3019 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3020 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3021 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3022 } WaitObjects;
3024 static WaitObjects wait_objects = {0};
3026 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3028 WaitObjects *w = &wait_objects;
3030 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3031 return -1;
3032 w->events[w->num] = handle;
3033 w->func[w->num] = func;
3034 w->opaque[w->num] = opaque;
3035 w->num++;
3036 return 0;
3039 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3041 int i, found;
3042 WaitObjects *w = &wait_objects;
3044 found = 0;
3045 for (i = 0; i < w->num; i++) {
3046 if (w->events[i] == handle)
3047 found = 1;
3048 if (found) {
3049 w->events[i] = w->events[i + 1];
3050 w->func[i] = w->func[i + 1];
3051 w->opaque[i] = w->opaque[i + 1];
3054 if (found)
3055 w->num--;
3057 #endif
3059 /***********************************************************/
3060 /* ram save/restore */
3062 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3064 int v;
3066 v = qemu_get_byte(f);
3067 switch(v) {
3068 case 0:
3069 if (qemu_get_buffer(f, buf, len) != len)
3070 return -EIO;
3071 break;
3072 case 1:
3073 v = qemu_get_byte(f);
3074 memset(buf, v, len);
3075 break;
3076 default:
3077 return -EINVAL;
3080 if (qemu_file_has_error(f))
3081 return -EIO;
3083 return 0;
3086 static int ram_load_v1(QEMUFile *f, void *opaque)
3088 int ret;
3089 ram_addr_t i;
3091 if (qemu_get_be32(f) != phys_ram_size)
3092 return -EINVAL;
3093 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3094 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3095 continue;
3096 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3097 if (ret)
3098 return ret;
3100 return 0;
3103 #define BDRV_HASH_BLOCK_SIZE 1024
3104 #define IOBUF_SIZE 4096
3105 #define RAM_CBLOCK_MAGIC 0xfabe
3107 typedef struct RamDecompressState {
3108 z_stream zstream;
3109 QEMUFile *f;
3110 uint8_t buf[IOBUF_SIZE];
3111 } RamDecompressState;
3113 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3115 int ret;
3116 memset(s, 0, sizeof(*s));
3117 s->f = f;
3118 ret = inflateInit(&s->zstream);
3119 if (ret != Z_OK)
3120 return -1;
3121 return 0;
3124 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3126 int ret, clen;
3128 s->zstream.avail_out = len;
3129 s->zstream.next_out = buf;
3130 while (s->zstream.avail_out > 0) {
3131 if (s->zstream.avail_in == 0) {
3132 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3133 return -1;
3134 clen = qemu_get_be16(s->f);
3135 if (clen > IOBUF_SIZE)
3136 return -1;
3137 qemu_get_buffer(s->f, s->buf, clen);
3138 s->zstream.avail_in = clen;
3139 s->zstream.next_in = s->buf;
3141 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3142 if (ret != Z_OK && ret != Z_STREAM_END) {
3143 return -1;
3146 return 0;
3149 static void ram_decompress_close(RamDecompressState *s)
3151 inflateEnd(&s->zstream);
3154 #define RAM_SAVE_FLAG_FULL 0x01
3155 #define RAM_SAVE_FLAG_COMPRESS 0x02
3156 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3157 #define RAM_SAVE_FLAG_PAGE 0x08
3158 #define RAM_SAVE_FLAG_EOS 0x10
3160 static int is_dup_page(uint8_t *page, uint8_t ch)
3162 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3163 uint32_t *array = (uint32_t *)page;
3164 int i;
3166 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3167 if (array[i] != val)
3168 return 0;
3171 return 1;
3174 static int ram_save_block(QEMUFile *f)
3176 static ram_addr_t current_addr = 0;
3177 ram_addr_t saved_addr = current_addr;
3178 ram_addr_t addr = 0;
3179 int found = 0;
3181 while (addr < phys_ram_size) {
3182 if (kvm_enabled() && current_addr == 0)
3183 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3184 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3185 uint8_t ch;
3187 cpu_physical_memory_reset_dirty(current_addr,
3188 current_addr + TARGET_PAGE_SIZE,
3189 MIGRATION_DIRTY_FLAG);
3191 ch = *(phys_ram_base + current_addr);
3193 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3194 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3195 qemu_put_byte(f, ch);
3196 } else {
3197 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3198 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3201 found = 1;
3202 break;
3204 addr += TARGET_PAGE_SIZE;
3205 current_addr = (saved_addr + addr) % phys_ram_size;
3208 return found;
3211 static ram_addr_t ram_save_threshold = 10;
3213 static ram_addr_t ram_save_remaining(void)
3215 ram_addr_t addr;
3216 ram_addr_t count = 0;
3218 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3219 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3220 count++;
3223 return count;
3226 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3228 ram_addr_t addr;
3230 if (stage == 1) {
3231 /* Make sure all dirty bits are set */
3232 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3233 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3234 cpu_physical_memory_set_dirty(addr);
3237 /* Enable dirty memory tracking */
3238 cpu_physical_memory_set_dirty_tracking(1);
3240 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3243 while (!qemu_file_rate_limit(f)) {
3244 int ret;
3246 ret = ram_save_block(f);
3247 if (ret == 0) /* no more blocks */
3248 break;
3251 /* try transferring iterative blocks of memory */
3253 if (stage == 3) {
3254 cpu_physical_memory_set_dirty_tracking(0);
3256 /* flush all remaining blocks regardless of rate limiting */
3257 while (ram_save_block(f) != 0);
3260 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3262 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3265 static int ram_load_dead(QEMUFile *f, void *opaque)
3267 RamDecompressState s1, *s = &s1;
3268 uint8_t buf[10];
3269 ram_addr_t i;
3271 if (ram_decompress_open(s, f) < 0)
3272 return -EINVAL;
3273 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3274 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3275 continue;
3276 if (ram_decompress_buf(s, buf, 1) < 0) {
3277 fprintf(stderr, "Error while reading ram block header\n");
3278 goto error;
3280 if (buf[0] == 0) {
3281 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3282 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3283 goto error;
3285 } else {
3286 error:
3287 printf("Error block header\n");
3288 return -EINVAL;
3291 ram_decompress_close(s);
3293 return 0;
3296 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3298 ram_addr_t addr;
3299 int flags;
3301 if (version_id == 1)
3302 return ram_load_v1(f, opaque);
3304 if (version_id == 2) {
3305 if (qemu_get_be32(f) != phys_ram_size)
3306 return -EINVAL;
3307 return ram_load_dead(f, opaque);
3310 if (version_id != 3)
3311 return -EINVAL;
3313 do {
3314 addr = qemu_get_be64(f);
3316 flags = addr & ~TARGET_PAGE_MASK;
3317 addr &= TARGET_PAGE_MASK;
3319 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3320 if (addr != phys_ram_size)
3321 return -EINVAL;
3324 if (flags & RAM_SAVE_FLAG_FULL) {
3325 if (ram_load_dead(f, opaque) < 0)
3326 return -EINVAL;
3329 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3330 uint8_t ch = qemu_get_byte(f);
3331 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3332 } else if (flags & RAM_SAVE_FLAG_PAGE)
3333 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3334 } while (!(flags & RAM_SAVE_FLAG_EOS));
3336 return 0;
3339 /***********************************************************/
3340 /* bottom halves (can be seen as timers which expire ASAP) */
3342 struct QEMUBH {
3343 QEMUBHFunc *cb;
3344 void *opaque;
3345 int scheduled;
3346 int idle;
3347 int deleted;
3348 QEMUBH *next;
3351 static QEMUBH *first_bh = NULL;
3353 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3355 QEMUBH *bh;
3356 bh = qemu_mallocz(sizeof(QEMUBH));
3357 bh->cb = cb;
3358 bh->opaque = opaque;
3359 bh->next = first_bh;
3360 first_bh = bh;
3361 return bh;
3364 int qemu_bh_poll(void)
3366 QEMUBH *bh, **bhp;
3367 int ret;
3369 ret = 0;
3370 for (bh = first_bh; bh; bh = bh->next) {
3371 if (!bh->deleted && bh->scheduled) {
3372 bh->scheduled = 0;
3373 if (!bh->idle)
3374 ret = 1;
3375 bh->idle = 0;
3376 bh->cb(bh->opaque);
3380 /* remove deleted bhs */
3381 bhp = &first_bh;
3382 while (*bhp) {
3383 bh = *bhp;
3384 if (bh->deleted) {
3385 *bhp = bh->next;
3386 qemu_free(bh);
3387 } else
3388 bhp = &bh->next;
3391 return ret;
3394 void qemu_bh_schedule_idle(QEMUBH *bh)
3396 if (bh->scheduled)
3397 return;
3398 bh->scheduled = 1;
3399 bh->idle = 1;
3402 void qemu_bh_schedule(QEMUBH *bh)
3404 CPUState *env = cpu_single_env;
3405 if (bh->scheduled)
3406 return;
3407 bh->scheduled = 1;
3408 bh->idle = 0;
3409 /* stop the currently executing CPU to execute the BH ASAP */
3410 if (env) {
3411 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3413 main_loop_break();
3416 void qemu_bh_cancel(QEMUBH *bh)
3418 bh->scheduled = 0;
3421 void qemu_bh_delete(QEMUBH *bh)
3423 bh->scheduled = 0;
3424 bh->deleted = 1;
3427 static void qemu_bh_update_timeout(int *timeout)
3429 QEMUBH *bh;
3431 for (bh = first_bh; bh; bh = bh->next) {
3432 if (!bh->deleted && bh->scheduled) {
3433 if (bh->idle) {
3434 /* idle bottom halves will be polled at least
3435 * every 10ms */
3436 *timeout = MIN(10, *timeout);
3437 } else {
3438 /* non-idle bottom halves will be executed
3439 * immediately */
3440 *timeout = 0;
3441 break;
3447 /***********************************************************/
3448 /* machine registration */
3450 static QEMUMachine *first_machine = NULL;
3451 QEMUMachine *current_machine = NULL;
3453 int qemu_register_machine(QEMUMachine *m)
3455 QEMUMachine **pm;
3456 pm = &first_machine;
3457 while (*pm != NULL)
3458 pm = &(*pm)->next;
3459 m->next = NULL;
3460 *pm = m;
3461 return 0;
3464 static QEMUMachine *find_machine(const char *name)
3466 QEMUMachine *m;
3468 for(m = first_machine; m != NULL; m = m->next) {
3469 if (!strcmp(m->name, name))
3470 return m;
3472 return NULL;
3475 /***********************************************************/
3476 /* main execution loop */
3478 static void gui_update(void *opaque)
3480 uint64_t interval = GUI_REFRESH_INTERVAL;
3481 DisplayState *ds = opaque;
3482 DisplayChangeListener *dcl = ds->listeners;
3484 dpy_refresh(ds);
3486 while (dcl != NULL) {
3487 if (dcl->gui_timer_interval &&
3488 dcl->gui_timer_interval < interval)
3489 interval = dcl->gui_timer_interval;
3490 dcl = dcl->next;
3492 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3495 static void nographic_update(void *opaque)
3497 uint64_t interval = GUI_REFRESH_INTERVAL;
3499 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3502 struct vm_change_state_entry {
3503 VMChangeStateHandler *cb;
3504 void *opaque;
3505 LIST_ENTRY (vm_change_state_entry) entries;
3508 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3510 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3511 void *opaque)
3513 VMChangeStateEntry *e;
3515 e = qemu_mallocz(sizeof (*e));
3517 e->cb = cb;
3518 e->opaque = opaque;
3519 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3520 return e;
3523 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3525 LIST_REMOVE (e, entries);
3526 qemu_free (e);
3529 static void vm_state_notify(int running, int reason)
3531 VMChangeStateEntry *e;
3533 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3534 e->cb(e->opaque, running, reason);
3538 void vm_start(void)
3540 if (!vm_running) {
3541 cpu_enable_ticks();
3542 vm_running = 1;
3543 vm_state_notify(1, 0);
3544 qemu_rearm_alarm_timer(alarm_timer);
3548 void vm_stop(int reason)
3550 if (vm_running) {
3551 cpu_disable_ticks();
3552 vm_running = 0;
3553 vm_state_notify(0, reason);
3557 /* reset/shutdown handler */
3559 typedef struct QEMUResetEntry {
3560 QEMUResetHandler *func;
3561 void *opaque;
3562 struct QEMUResetEntry *next;
3563 } QEMUResetEntry;
3565 static QEMUResetEntry *first_reset_entry;
3566 static int reset_requested;
3567 static int shutdown_requested;
3568 static int powerdown_requested;
3570 int qemu_shutdown_requested(void)
3572 int r = shutdown_requested;
3573 shutdown_requested = 0;
3574 return r;
3577 int qemu_reset_requested(void)
3579 int r = reset_requested;
3580 reset_requested = 0;
3581 return r;
3584 int qemu_powerdown_requested(void)
3586 int r = powerdown_requested;
3587 powerdown_requested = 0;
3588 return r;
3591 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3593 QEMUResetEntry **pre, *re;
3595 pre = &first_reset_entry;
3596 while (*pre != NULL)
3597 pre = &(*pre)->next;
3598 re = qemu_mallocz(sizeof(QEMUResetEntry));
3599 re->func = func;
3600 re->opaque = opaque;
3601 re->next = NULL;
3602 *pre = re;
3605 void qemu_system_reset(void)
3607 QEMUResetEntry *re;
3609 /* reset all devices */
3610 for(re = first_reset_entry; re != NULL; re = re->next) {
3611 re->func(re->opaque);
3615 void qemu_system_reset_request(void)
3617 if (no_reboot) {
3618 shutdown_requested = 1;
3619 } else {
3620 reset_requested = 1;
3623 if (cpu_single_env) {
3624 qemu_kvm_cpu_stop(cpu_single_env);
3625 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3627 main_loop_break();
3630 void qemu_system_shutdown_request(void)
3632 shutdown_requested = 1;
3633 if (cpu_single_env)
3634 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3637 void qemu_system_powerdown_request(void)
3639 powerdown_requested = 1;
3640 if (cpu_single_env)
3641 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3644 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3645 struct timeval *tv)
3647 int ret;
3649 /* KVM holds a mutex while QEMU code is running, we need hooks to
3650 release the mutex whenever QEMU code sleeps. */
3652 kvm_sleep_begin();
3654 ret = select(max_fd, rfds, wfds, xfds, tv);
3656 kvm_sleep_end();
3658 return ret;
3661 #ifdef _WIN32
3662 static void host_main_loop_wait(int *timeout)
3664 int ret, ret2, i;
3665 PollingEntry *pe;
3668 /* XXX: need to suppress polling by better using win32 events */
3669 ret = 0;
3670 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3671 ret |= pe->func(pe->opaque);
3673 if (ret == 0) {
3674 int err;
3675 WaitObjects *w = &wait_objects;
3677 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3678 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3679 if (w->func[ret - WAIT_OBJECT_0])
3680 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3682 /* Check for additional signaled events */
3683 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3685 /* Check if event is signaled */
3686 ret2 = WaitForSingleObject(w->events[i], 0);
3687 if(ret2 == WAIT_OBJECT_0) {
3688 if (w->func[i])
3689 w->func[i](w->opaque[i]);
3690 } else if (ret2 == WAIT_TIMEOUT) {
3691 } else {
3692 err = GetLastError();
3693 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3696 } else if (ret == WAIT_TIMEOUT) {
3697 } else {
3698 err = GetLastError();
3699 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3703 *timeout = 0;
3705 #else
3706 static void host_main_loop_wait(int *timeout)
3709 #endif
3711 void main_loop_wait(int timeout)
3713 IOHandlerRecord *ioh;
3714 fd_set rfds, wfds, xfds;
3715 int ret, nfds;
3716 struct timeval tv;
3718 qemu_bh_update_timeout(&timeout);
3720 host_main_loop_wait(&timeout);
3722 /* poll any events */
3723 /* XXX: separate device handlers from system ones */
3724 nfds = -1;
3725 FD_ZERO(&rfds);
3726 FD_ZERO(&wfds);
3727 FD_ZERO(&xfds);
3728 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3729 if (ioh->deleted)
3730 continue;
3731 if (ioh->fd_read &&
3732 (!ioh->fd_read_poll ||
3733 ioh->fd_read_poll(ioh->opaque) != 0)) {
3734 FD_SET(ioh->fd, &rfds);
3735 if (ioh->fd > nfds)
3736 nfds = ioh->fd;
3738 if (ioh->fd_write) {
3739 FD_SET(ioh->fd, &wfds);
3740 if (ioh->fd > nfds)
3741 nfds = ioh->fd;
3745 tv.tv_sec = timeout / 1000;
3746 tv.tv_usec = (timeout % 1000) * 1000;
3748 #if defined(CONFIG_SLIRP)
3749 if (slirp_is_inited()) {
3750 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3752 #endif
3753 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3754 if (ret > 0) {
3755 IOHandlerRecord **pioh;
3757 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3758 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3759 ioh->fd_read(ioh->opaque);
3760 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3761 FD_CLR(ioh->fd, &rfds);
3763 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3764 ioh->fd_write(ioh->opaque);
3768 /* remove deleted IO handlers */
3769 pioh = &first_io_handler;
3770 while (*pioh) {
3771 ioh = *pioh;
3772 if (ioh->deleted) {
3773 *pioh = ioh->next;
3774 qemu_free(ioh);
3775 } else
3776 pioh = &ioh->next;
3779 #if defined(CONFIG_SLIRP)
3780 if (slirp_is_inited()) {
3781 if (ret < 0) {
3782 FD_ZERO(&rfds);
3783 FD_ZERO(&wfds);
3784 FD_ZERO(&xfds);
3786 slirp_select_poll(&rfds, &wfds, &xfds);
3788 #endif
3790 /* vm time timers */
3791 if (vm_running && (!cur_cpu
3792 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3793 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3794 qemu_get_clock(vm_clock));
3796 /* real time timers */
3797 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3798 qemu_get_clock(rt_clock));
3800 /* Check bottom-halves last in case any of the earlier events triggered
3801 them. */
3802 qemu_bh_poll();
3806 static int main_loop(void)
3808 int ret, timeout;
3809 #ifdef CONFIG_PROFILER
3810 int64_t ti;
3811 #endif
3812 CPUState *env;
3815 if (kvm_enabled()) {
3816 kvm_main_loop();
3817 cpu_disable_ticks();
3818 return 0;
3821 cur_cpu = first_cpu;
3822 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3823 for(;;) {
3824 if (vm_running) {
3826 for(;;) {
3827 /* get next cpu */
3828 env = next_cpu;
3829 #ifdef CONFIG_PROFILER
3830 ti = profile_getclock();
3831 #endif
3832 if (use_icount) {
3833 int64_t count;
3834 int decr;
3835 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3836 env->icount_decr.u16.low = 0;
3837 env->icount_extra = 0;
3838 count = qemu_next_deadline();
3839 count = (count + (1 << icount_time_shift) - 1)
3840 >> icount_time_shift;
3841 qemu_icount += count;
3842 decr = (count > 0xffff) ? 0xffff : count;
3843 count -= decr;
3844 env->icount_decr.u16.low = decr;
3845 env->icount_extra = count;
3847 ret = cpu_exec(env);
3848 #ifdef CONFIG_PROFILER
3849 qemu_time += profile_getclock() - ti;
3850 #endif
3851 if (use_icount) {
3852 /* Fold pending instructions back into the
3853 instruction counter, and clear the interrupt flag. */
3854 qemu_icount -= (env->icount_decr.u16.low
3855 + env->icount_extra);
3856 env->icount_decr.u32 = 0;
3857 env->icount_extra = 0;
3859 next_cpu = env->next_cpu ?: first_cpu;
3860 if (event_pending && likely(ret != EXCP_DEBUG)) {
3861 ret = EXCP_INTERRUPT;
3862 event_pending = 0;
3863 break;
3865 if (ret == EXCP_HLT) {
3866 /* Give the next CPU a chance to run. */
3867 cur_cpu = env;
3868 continue;
3870 if (ret != EXCP_HALTED)
3871 break;
3872 /* all CPUs are halted ? */
3873 if (env == cur_cpu)
3874 break;
3876 cur_cpu = env;
3878 if (shutdown_requested) {
3879 ret = EXCP_INTERRUPT;
3880 if (no_shutdown) {
3881 vm_stop(0);
3882 no_shutdown = 0;
3884 else
3885 break;
3887 if (reset_requested) {
3888 reset_requested = 0;
3889 qemu_system_reset();
3890 if (kvm_enabled())
3891 kvm_load_registers(env);
3892 ret = EXCP_INTERRUPT;
3894 if (powerdown_requested) {
3895 powerdown_requested = 0;
3896 qemu_system_powerdown();
3897 ret = EXCP_INTERRUPT;
3899 #ifdef CONFIG_GDBSTUB
3900 if (unlikely(ret == EXCP_DEBUG)) {
3901 gdb_set_stop_cpu(cur_cpu);
3902 vm_stop(EXCP_DEBUG);
3904 #endif
3905 /* If all cpus are halted then wait until the next IRQ */
3906 /* XXX: use timeout computed from timers */
3907 if (ret == EXCP_HALTED) {
3908 if (use_icount) {
3909 int64_t add;
3910 int64_t delta;
3911 /* Advance virtual time to the next event. */
3912 if (use_icount == 1) {
3913 /* When not using an adaptive execution frequency
3914 we tend to get badly out of sync with real time,
3915 so just delay for a reasonable amount of time. */
3916 delta = 0;
3917 } else {
3918 delta = cpu_get_icount() - cpu_get_clock();
3920 if (delta > 0) {
3921 /* If virtual time is ahead of real time then just
3922 wait for IO. */
3923 timeout = (delta / 1000000) + 1;
3924 } else {
3925 /* Wait for either IO to occur or the next
3926 timer event. */
3927 add = qemu_next_deadline();
3928 /* We advance the timer before checking for IO.
3929 Limit the amount we advance so that early IO
3930 activity won't get the guest too far ahead. */
3931 if (add > 10000000)
3932 add = 10000000;
3933 delta += add;
3934 add = (add + (1 << icount_time_shift) - 1)
3935 >> icount_time_shift;
3936 qemu_icount += add;
3937 timeout = delta / 1000000;
3938 if (timeout < 0)
3939 timeout = 0;
3941 } else {
3942 timeout = 5000;
3944 } else {
3945 timeout = 0;
3947 } else {
3948 if (shutdown_requested) {
3949 ret = EXCP_INTERRUPT;
3950 break;
3952 timeout = 5000;
3954 #ifdef CONFIG_PROFILER
3955 ti = profile_getclock();
3956 #endif
3957 main_loop_wait(timeout);
3958 #ifdef CONFIG_PROFILER
3959 dev_time += profile_getclock() - ti;
3960 #endif
3962 cpu_disable_ticks();
3963 return ret;
3966 static void help(int exitcode)
3968 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3969 and qemu-doc.texi */
3970 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
3971 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3972 "usage: %s [options] [disk_image]\n"
3973 "\n"
3974 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3975 "\n"
3976 "Standard options:\n"
3977 "-h or -help display this help and exit\n"
3978 "-M machine select emulated machine (-M ? for list)\n"
3979 "-cpu cpu select CPU (-cpu ? for list)\n"
3980 "-smp n set the number of CPUs to 'n' [default=1]\n"
3981 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3982 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3983 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3984 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3985 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3986 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3987 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3988 " [,boot=on|off]\n"
3989 " use 'file' as a drive image\n"
3990 "-mtdblock file use 'file' as on-board Flash memory image\n"
3991 "-sd file use 'file' as SecureDigital card image\n"
3992 "-pflash file use 'file' as a parallel flash image\n"
3993 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3994 "-snapshot write to temporary files instead of disk image files\n"
3995 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3996 #ifndef _WIN32
3997 "-k language use keyboard layout (for example \"fr\" for French)\n"
3998 #endif
3999 #ifdef HAS_AUDIO
4000 "-audio-help print list of audio drivers and their options\n"
4001 "-soundhw c1,... enable audio support\n"
4002 " and only specified sound cards (comma separated list)\n"
4003 " use -soundhw ? to get the list of supported cards\n"
4004 " use -soundhw all to enable all of them\n"
4005 #endif
4006 "-usb enable the USB driver (will be the default soon)\n"
4007 "-usbdevice name add the host or guest USB device 'name'\n"
4008 "-name string set the name of the guest\n"
4009 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
4010 " specify machine UUID\n"
4011 "\n"
4012 "Display options:\n"
4013 "-nographic disable graphical output and redirect serial I/Os to console\n"
4014 #ifdef CONFIG_CURSES
4015 "-curses use a curses/ncurses interface instead of SDL\n"
4016 #endif
4017 #ifdef CONFIG_SDL
4018 "-no-frame open SDL window without a frame and window decorations\n"
4019 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4020 "-no-quit disable SDL window close capability\n"
4021 "-sdl enable SDL\n"
4022 #endif
4023 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4024 "-vga [std|cirrus|vmware|none]\n"
4025 " select video card type\n"
4026 "-full-screen start in full screen\n"
4027 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4028 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4029 #endif
4030 "-vnc display start a VNC server on display\n"
4031 #ifdef TARGET_IA64
4032 "-nvram file use 'file' to save or load nvram image\n"
4033 #endif
4034 "-name string set the name of the guest\n"
4035 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4036 "\n"
4037 "Network options:\n"
4038 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
4039 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4040 #ifdef CONFIG_SLIRP
4041 "-net user[,vlan=n][,name=str][,hostname=host]\n"
4042 " connect the user mode network stack to VLAN 'n' and send\n"
4043 " hostname 'host' to DHCP clients\n"
4044 #endif
4045 #ifdef _WIN32
4046 "-net tap[,vlan=n][,name=str],ifname=name\n"
4047 " connect the host TAP network interface to VLAN 'n'\n"
4048 #else
4049 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4050 " connect the host TAP network interface to VLAN 'n' and use the\n"
4051 " network scripts 'file' (default=%s)\n"
4052 " and 'dfile' (default=%s);\n"
4053 " use '[down]script=no' to disable script execution;\n"
4054 " use 'fd=h' to connect to an already opened TAP interface\n"
4055 #endif
4056 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4057 " connect the vlan 'n' to another VLAN using a socket connection\n"
4058 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4059 " connect the vlan 'n' to multicast maddr and port\n"
4060 #ifdef CONFIG_VDE
4061 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4062 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4063 " on host and listening for incoming connections on 'socketpath'.\n"
4064 " Use group 'groupname' and mode 'octalmode' to change default\n"
4065 " ownership and permissions for communication port.\n"
4066 #endif
4067 "-net none use it alone to have zero network devices; if no -net option\n"
4068 " is provided, the default is '-net nic -net user'\n"
4069 #ifdef CONFIG_SLIRP
4070 "-tftp dir allow tftp access to files in dir [-net user]\n"
4071 "-bootp file advertise file in BOOTP replies\n"
4072 #ifndef _WIN32
4073 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4074 #endif
4075 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4076 " redirect TCP or UDP connections from host to guest [-net user]\n"
4077 #endif
4078 "\n"
4079 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4080 "-bt hci,host[:id]\n"
4081 " use host's HCI with the given name\n"
4082 "-bt hci[,vlan=n]\n"
4083 " emulate a standard HCI in virtual scatternet 'n'\n"
4084 "-bt vhci[,vlan=n]\n"
4085 " add host computer to virtual scatternet 'n' using VHCI\n"
4086 "-bt device:dev[,vlan=n]\n"
4087 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4088 "\n"
4089 #ifdef TARGET_I386
4090 "\n"
4091 "i386 target only:\n"
4092 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4093 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4094 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4095 "-no-acpi disable ACPI\n"
4096 "-no-hpet disable HPET\n"
4097 #endif
4098 "Linux boot specific:\n"
4099 "-kernel bzImage use 'bzImage' as kernel image\n"
4100 "-append cmdline use 'cmdline' as kernel command line\n"
4101 "-initrd file use 'file' as initial ram disk\n"
4102 "\n"
4103 "Debug/Expert options:\n"
4104 "-serial dev redirect the serial port to char device 'dev'\n"
4105 "-parallel dev redirect the parallel port to char device 'dev'\n"
4106 "-monitor dev redirect the monitor to char device 'dev'\n"
4107 "-pidfile file write PID to 'file'\n"
4108 "-S freeze CPU at startup (use 'c' to start execution)\n"
4109 "-s wait gdb connection to port\n"
4110 "-p port set gdb connection port [default=%s]\n"
4111 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4112 "-hdachs c,h,s[,t]\n"
4113 " force hard disk 0 physical geometry and the optional BIOS\n"
4114 " translation (t=none or lba) (usually qemu can guess them)\n"
4115 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4116 "-bios file set the filename for the BIOS\n"
4117 #ifdef USE_KQEMU
4118 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4119 "-no-kqemu disable KQEMU kernel module usage\n"
4120 #endif
4121 #ifdef CONFIG_KVM
4122 "-enable-kvm enable KVM full virtualization support\n"
4123 #endif
4124 #ifdef USE_KVM
4125 #ifndef NO_CPU_EMULATION
4126 "-no-kvm disable KVM hardware virtualization\n"
4127 #endif
4128 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4129 "-no-kvm-pit disable KVM kernel mode PIT\n"
4130 "-no-kvm-pit-reinjection disable KVM kernel mode PIT interrupt reinjection\n"
4131 "-enable-nesting enable support for running a VM inside the VM (AMD only)\n"
4132 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4133 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4134 " expose a PCI device to the guest OS.\n"
4135 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4136 " 'string' is used in log output.\n"
4137 #endif
4138 #endif
4139 "-no-reboot exit instead of rebooting\n"
4140 "-no-shutdown stop before shutdown\n"
4141 "-loadvm [tag|id]\n"
4142 " start right away with a saved state (loadvm in monitor)\n"
4143 #ifndef _WIN32
4144 "-daemonize daemonize QEMU after initializing\n"
4145 #endif
4146 "-tdf inject timer interrupts that got lost\n"
4147 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4148 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also\n"
4149 " enables allocation of guest memory with huge pages\n"
4150 #ifdef MAP_POPULATE
4151 "-mem-prealloc toggles preallocation of -mem-path backed physical memory\n"
4152 " at startup. Default is enabled.\n"
4153 #endif
4154 "-option-rom rom load a file, rom, into the option ROM space\n"
4155 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4156 "-prom-env variable=value\n"
4157 " set OpenBIOS nvram variables\n"
4158 #endif
4159 "-clock force the use of the given methods for timer alarm.\n"
4160 " To see what timers are available use -clock ?\n"
4161 "-localtime set the real time clock to local time [default=utc]\n"
4162 "-startdate select initial date of the clock\n"
4163 "-icount [N|auto]\n"
4164 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4165 "-echr chr set terminal escape character instead of ctrl-a\n"
4166 "-virtioconsole c\n"
4167 " set virtio console\n"
4168 "-show-cursor show cursor\n"
4169 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4170 "-semihosting semihosting mode\n"
4171 #endif
4172 #if defined(TARGET_ARM)
4173 "-old-param old param mode\n"
4174 #endif
4175 "-tb-size n set TB size\n"
4176 "-incoming p prepare for incoming migration, listen on port p\n"
4177 "\n"
4178 "During emulation, the following keys are useful:\n"
4179 "ctrl-alt-f toggle full screen\n"
4180 "ctrl-alt-n switch to virtual console 'n'\n"
4181 "ctrl-alt toggle mouse and keyboard grab\n"
4182 "\n"
4183 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4185 "qemu",
4186 DEFAULT_RAM_SIZE,
4187 #ifndef _WIN32
4188 DEFAULT_NETWORK_SCRIPT,
4189 DEFAULT_NETWORK_DOWN_SCRIPT,
4190 #endif
4191 DEFAULT_GDBSTUB_PORT,
4192 "/tmp/qemu.log");
4193 exit(exitcode);
4196 #define HAS_ARG 0x0001
4198 enum {
4199 /* Please keep in synch with help, qemu_options[] and
4200 qemu-doc.texi */
4201 /* Standard options: */
4202 QEMU_OPTION_h,
4203 QEMU_OPTION_M,
4204 QEMU_OPTION_cpu,
4205 QEMU_OPTION_smp,
4206 QEMU_OPTION_fda,
4207 QEMU_OPTION_fdb,
4208 QEMU_OPTION_hda,
4209 QEMU_OPTION_hdb,
4210 QEMU_OPTION_hdc,
4211 QEMU_OPTION_hdd,
4212 QEMU_OPTION_cdrom,
4213 QEMU_OPTION_drive,
4214 QEMU_OPTION_mtdblock,
4215 QEMU_OPTION_sd,
4216 QEMU_OPTION_pflash,
4217 QEMU_OPTION_boot,
4218 QEMU_OPTION_snapshot,
4219 QEMU_OPTION_m,
4220 QEMU_OPTION_k,
4221 QEMU_OPTION_audio_help,
4222 QEMU_OPTION_soundhw,
4223 QEMU_OPTION_usb,
4224 QEMU_OPTION_usbdevice,
4225 QEMU_OPTION_name,
4226 QEMU_OPTION_uuid,
4228 /* Display options: */
4229 QEMU_OPTION_nographic,
4230 QEMU_OPTION_curses,
4231 QEMU_OPTION_no_frame,
4232 QEMU_OPTION_alt_grab,
4233 QEMU_OPTION_no_quit,
4234 QEMU_OPTION_sdl,
4235 QEMU_OPTION_portrait,
4236 QEMU_OPTION_vga,
4237 QEMU_OPTION_full_screen,
4238 QEMU_OPTION_g,
4239 QEMU_OPTION_vnc,
4241 /* Network options: */
4242 QEMU_OPTION_net,
4243 QEMU_OPTION_tftp,
4244 QEMU_OPTION_bootp,
4245 QEMU_OPTION_smb,
4246 QEMU_OPTION_redir,
4247 QEMU_OPTION_bt,
4249 /* i386 target only: */
4250 QEMU_OPTION_win2k_hack,
4251 QEMU_OPTION_rtc_td_hack,
4252 QEMU_OPTION_no_fd_bootchk,
4253 QEMU_OPTION_no_acpi,
4254 QEMU_OPTION_no_hpet,
4256 /* Linux boot specific: */
4257 QEMU_OPTION_kernel,
4258 QEMU_OPTION_append,
4259 QEMU_OPTION_initrd,
4261 /* Debug/Expert options: */
4262 QEMU_OPTION_serial,
4263 QEMU_OPTION_parallel,
4264 QEMU_OPTION_monitor,
4265 QEMU_OPTION_pidfile,
4266 QEMU_OPTION_S,
4267 QEMU_OPTION_s,
4268 QEMU_OPTION_p,
4269 QEMU_OPTION_d,
4270 QEMU_OPTION_hdachs,
4271 QEMU_OPTION_L,
4272 QEMU_OPTION_bios,
4273 QEMU_OPTION_kernel_kqemu,
4274 QEMU_OPTION_no_kqemu,
4275 QEMU_OPTION_enable_kvm,
4276 QEMU_OPTION_enable_nesting,
4277 QEMU_OPTION_no_kvm,
4278 QEMU_OPTION_no_kvm_irqchip,
4279 QEMU_OPTION_no_kvm_pit,
4280 QEMU_OPTION_no_kvm_pit_reinjection,
4281 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4282 QEMU_OPTION_pcidevice,
4283 #endif
4284 QEMU_OPTION_no_reboot,
4285 QEMU_OPTION_no_shutdown,
4286 QEMU_OPTION_loadvm,
4287 QEMU_OPTION_daemonize,
4288 QEMU_OPTION_option_rom,
4289 QEMU_OPTION_cpu_vendor,
4290 QEMU_OPTION_nvram,
4291 QEMU_OPTION_prom_env,
4292 QEMU_OPTION_clock,
4293 QEMU_OPTION_localtime,
4294 QEMU_OPTION_startdate,
4295 QEMU_OPTION_icount,
4296 QEMU_OPTION_echr,
4297 QEMU_OPTION_virtiocon,
4298 QEMU_OPTION_show_cursor,
4299 QEMU_OPTION_semihosting,
4300 QEMU_OPTION_old_param,
4301 QEMU_OPTION_tb_size,
4302 QEMU_OPTION_incoming,
4303 QEMU_OPTION_tdf,
4304 QEMU_OPTION_kvm_shadow_memory,
4305 QEMU_OPTION_mempath,
4306 #ifdef MAP_POPULATE
4307 QEMU_OPTION_mem_prealloc,
4308 #endif
4311 typedef struct QEMUOption {
4312 const char *name;
4313 int flags;
4314 int index;
4315 } QEMUOption;
4317 static const QEMUOption qemu_options[] = {
4318 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4319 qemu-doc.texi */
4320 /* Standard options: */
4321 { "h", 0, QEMU_OPTION_h },
4322 { "help", 0, QEMU_OPTION_h },
4323 { "M", HAS_ARG, QEMU_OPTION_M },
4324 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4325 { "smp", HAS_ARG, QEMU_OPTION_smp },
4326 { "fda", HAS_ARG, QEMU_OPTION_fda },
4327 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4328 { "hda", HAS_ARG, QEMU_OPTION_hda },
4329 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4330 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4331 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4332 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4333 { "drive", HAS_ARG, QEMU_OPTION_drive },
4334 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4335 { "sd", HAS_ARG, QEMU_OPTION_sd },
4336 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4337 { "boot", HAS_ARG, QEMU_OPTION_boot },
4338 { "snapshot", 0, QEMU_OPTION_snapshot },
4339 { "m", HAS_ARG, QEMU_OPTION_m },
4340 #ifndef _WIN32
4341 { "k", HAS_ARG, QEMU_OPTION_k },
4342 #endif
4343 #ifdef HAS_AUDIO
4344 { "audio-help", 0, QEMU_OPTION_audio_help },
4345 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4346 #endif
4347 { "usb", 0, QEMU_OPTION_usb },
4348 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4349 { "name", HAS_ARG, QEMU_OPTION_name },
4350 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4352 /* Display options: */
4353 { "nographic", 0, QEMU_OPTION_nographic },
4354 #ifdef CONFIG_CURSES
4355 { "curses", 0, QEMU_OPTION_curses },
4356 #endif
4357 #ifdef CONFIG_SDL
4358 { "no-frame", 0, QEMU_OPTION_no_frame },
4359 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4360 { "no-quit", 0, QEMU_OPTION_no_quit },
4361 { "sdl", 0, QEMU_OPTION_sdl },
4362 #endif
4363 { "portrait", 0, QEMU_OPTION_portrait },
4364 { "vga", HAS_ARG, QEMU_OPTION_vga },
4365 { "full-screen", 0, QEMU_OPTION_full_screen },
4366 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4367 { "g", 1, QEMU_OPTION_g },
4368 #endif
4369 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4371 /* Network options: */
4372 { "net", HAS_ARG, QEMU_OPTION_net},
4373 #ifdef CONFIG_SLIRP
4374 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4375 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4376 #ifndef _WIN32
4377 { "smb", HAS_ARG, QEMU_OPTION_smb },
4378 #endif
4379 { "redir", HAS_ARG, QEMU_OPTION_redir },
4380 #endif
4381 { "bt", HAS_ARG, QEMU_OPTION_bt },
4382 #ifdef TARGET_I386
4383 /* i386 target only: */
4384 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4385 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4386 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4387 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4388 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4389 #endif
4391 /* Linux boot specific: */
4392 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4393 { "append", HAS_ARG, QEMU_OPTION_append },
4394 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4396 /* Debug/Expert options: */
4397 { "serial", HAS_ARG, QEMU_OPTION_serial },
4398 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4399 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4400 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4401 { "S", 0, QEMU_OPTION_S },
4402 { "s", 0, QEMU_OPTION_s },
4403 { "p", HAS_ARG, QEMU_OPTION_p },
4404 { "d", HAS_ARG, QEMU_OPTION_d },
4405 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4406 { "L", HAS_ARG, QEMU_OPTION_L },
4407 { "bios", HAS_ARG, QEMU_OPTION_bios },
4408 #ifdef USE_KQEMU
4409 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4410 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4411 #endif
4412 #ifdef CONFIG_KVM
4413 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4414 #endif
4415 #ifdef USE_KVM
4416 #ifndef NO_CPU_EMULATION
4417 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4418 #endif
4419 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4420 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4421 { "no-kvm-pit-reinjection", 0, QEMU_OPTION_no_kvm_pit_reinjection },
4422 { "enable-nesting", 0, QEMU_OPTION_enable_nesting },
4423 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4424 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4425 #endif
4426 #endif
4427 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4428 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4429 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4430 { "daemonize", 0, QEMU_OPTION_daemonize },
4431 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4432 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4433 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4434 #endif
4435 { "clock", HAS_ARG, QEMU_OPTION_clock },
4436 { "localtime", 0, QEMU_OPTION_localtime },
4437 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4438 { "icount", HAS_ARG, QEMU_OPTION_icount },
4439 { "echr", HAS_ARG, QEMU_OPTION_echr },
4440 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4441 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4442 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4443 { "semihosting", 0, QEMU_OPTION_semihosting },
4444 #endif
4445 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4446 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4447 { "nvram", HAS_ARG, QEMU_OPTION_nvram },
4448 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4449 #if defined(TARGET_ARM)
4450 { "old-param", 0, QEMU_OPTION_old_param },
4451 #endif
4452 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4453 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4454 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4455 #ifdef MAP_POPULATE
4456 { "mem-prealloc", 0, QEMU_OPTION_mem_prealloc },
4457 #endif
4458 { NULL },
4461 /* password input */
4463 int qemu_key_check(BlockDriverState *bs, const char *name)
4465 char password[256];
4466 int i;
4468 if (!bdrv_is_encrypted(bs))
4469 return 0;
4471 term_printf("%s is encrypted.\n", name);
4472 for(i = 0; i < 3; i++) {
4473 monitor_readline("Password: ", 1, password, sizeof(password));
4474 if (bdrv_set_key(bs, password) == 0)
4475 return 0;
4476 term_printf("invalid password\n");
4478 return -EPERM;
4481 static BlockDriverState *get_bdrv(int index)
4483 if (index > nb_drives)
4484 return NULL;
4485 return drives_table[index].bdrv;
4488 static void read_passwords(void)
4490 BlockDriverState *bs;
4491 int i;
4493 for(i = 0; i < 6; i++) {
4494 bs = get_bdrv(i);
4495 if (bs)
4496 qemu_key_check(bs, bdrv_get_device_name(bs));
4500 #ifdef HAS_AUDIO
4501 struct soundhw soundhw[] = {
4502 #ifdef HAS_AUDIO_CHOICE
4503 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4505 "pcspk",
4506 "PC speaker",
4509 { .init_isa = pcspk_audio_init }
4511 #endif
4513 #ifdef CONFIG_SB16
4515 "sb16",
4516 "Creative Sound Blaster 16",
4519 { .init_isa = SB16_init }
4521 #endif
4523 #ifdef CONFIG_CS4231A
4525 "cs4231a",
4526 "CS4231A",
4529 { .init_isa = cs4231a_init }
4531 #endif
4533 #ifdef CONFIG_ADLIB
4535 "adlib",
4536 #ifdef HAS_YMF262
4537 "Yamaha YMF262 (OPL3)",
4538 #else
4539 "Yamaha YM3812 (OPL2)",
4540 #endif
4543 { .init_isa = Adlib_init }
4545 #endif
4547 #ifdef CONFIG_GUS
4549 "gus",
4550 "Gravis Ultrasound GF1",
4553 { .init_isa = GUS_init }
4555 #endif
4557 #ifdef CONFIG_AC97
4559 "ac97",
4560 "Intel 82801AA AC97 Audio",
4563 { .init_pci = ac97_init }
4565 #endif
4567 #ifdef CONFIG_ES1370
4569 "es1370",
4570 "ENSONIQ AudioPCI ES1370",
4573 { .init_pci = es1370_init }
4575 #endif
4577 #endif /* HAS_AUDIO_CHOICE */
4579 { NULL, NULL, 0, 0, { NULL } }
4582 static void select_soundhw (const char *optarg)
4584 struct soundhw *c;
4586 if (*optarg == '?') {
4587 show_valid_cards:
4589 printf ("Valid sound card names (comma separated):\n");
4590 for (c = soundhw; c->name; ++c) {
4591 printf ("%-11s %s\n", c->name, c->descr);
4593 printf ("\n-soundhw all will enable all of the above\n");
4594 exit (*optarg != '?');
4596 else {
4597 size_t l;
4598 const char *p;
4599 char *e;
4600 int bad_card = 0;
4602 if (!strcmp (optarg, "all")) {
4603 for (c = soundhw; c->name; ++c) {
4604 c->enabled = 1;
4606 return;
4609 p = optarg;
4610 while (*p) {
4611 e = strchr (p, ',');
4612 l = !e ? strlen (p) : (size_t) (e - p);
4614 for (c = soundhw; c->name; ++c) {
4615 if (!strncmp (c->name, p, l)) {
4616 c->enabled = 1;
4617 break;
4621 if (!c->name) {
4622 if (l > 80) {
4623 fprintf (stderr,
4624 "Unknown sound card name (too big to show)\n");
4626 else {
4627 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4628 (int) l, p);
4630 bad_card = 1;
4632 p += l + (e != NULL);
4635 if (bad_card)
4636 goto show_valid_cards;
4639 #endif
4641 static void select_vgahw (const char *p)
4643 const char *opts;
4645 if (strstart(p, "std", &opts)) {
4646 std_vga_enabled = 1;
4647 cirrus_vga_enabled = 0;
4648 vmsvga_enabled = 0;
4649 } else if (strstart(p, "cirrus", &opts)) {
4650 cirrus_vga_enabled = 1;
4651 std_vga_enabled = 0;
4652 vmsvga_enabled = 0;
4653 } else if (strstart(p, "vmware", &opts)) {
4654 cirrus_vga_enabled = 0;
4655 std_vga_enabled = 0;
4656 vmsvga_enabled = 1;
4657 } else if (strstart(p, "none", &opts)) {
4658 cirrus_vga_enabled = 0;
4659 std_vga_enabled = 0;
4660 vmsvga_enabled = 0;
4661 } else {
4662 invalid_vga:
4663 fprintf(stderr, "Unknown vga type: %s\n", p);
4664 exit(1);
4666 while (*opts) {
4667 const char *nextopt;
4669 if (strstart(opts, ",retrace=", &nextopt)) {
4670 opts = nextopt;
4671 if (strstart(opts, "dumb", &nextopt))
4672 vga_retrace_method = VGA_RETRACE_DUMB;
4673 else if (strstart(opts, "precise", &nextopt))
4674 vga_retrace_method = VGA_RETRACE_PRECISE;
4675 else goto invalid_vga;
4676 } else goto invalid_vga;
4677 opts = nextopt;
4681 #ifdef _WIN32
4682 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4684 exit(STATUS_CONTROL_C_EXIT);
4685 return TRUE;
4687 #endif
4689 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4691 int ret;
4693 if(strlen(str) != 36)
4694 return -1;
4696 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4697 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4698 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4700 if(ret != 16)
4701 return -1;
4703 return 0;
4706 #define MAX_NET_CLIENTS 32
4708 static int saved_argc;
4709 static char **saved_argv;
4711 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4713 *argc = saved_argc;
4714 *argv = saved_argv;
4715 *opt_daemonize = daemonize;
4716 *opt_incoming = incoming;
4719 #ifdef USE_KVM
4720 static int gethugepagesize(void)
4722 int ret, fd;
4723 char buf[4096];
4724 const char *needle = "Hugepagesize:";
4725 char *size;
4726 unsigned long hugepagesize;
4728 fd = open("/proc/meminfo", O_RDONLY);
4729 if (fd < 0) {
4730 perror("open");
4731 exit(0);
4734 ret = read(fd, buf, sizeof(buf));
4735 if (ret < 0) {
4736 perror("read");
4737 exit(0);
4740 size = strstr(buf, needle);
4741 if (!size)
4742 return 0;
4743 size += strlen(needle);
4744 hugepagesize = strtol(size, NULL, 0);
4745 return hugepagesize;
4748 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4750 char *filename;
4751 void *area;
4752 int fd;
4753 #ifdef MAP_POPULATE
4754 int flags;
4755 #endif
4757 if (!kvm_has_sync_mmu()) {
4758 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4759 return NULL;
4762 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4763 return NULL;
4765 hpagesize = gethugepagesize() * 1024;
4766 if (!hpagesize)
4767 return NULL;
4769 fd = mkstemp(filename);
4770 if (fd < 0) {
4771 perror("mkstemp");
4772 free(filename);
4773 return NULL;
4775 unlink(filename);
4776 free(filename);
4778 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4781 * ftruncate is not supported by hugetlbfs in older
4782 * hosts, so don't bother checking for errors.
4783 * If anything goes wrong with it under other filesystems,
4784 * mmap will fail.
4786 ftruncate(fd, memory);
4788 #ifdef MAP_POPULATE
4789 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4790 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4791 * to sidestep this quirk.
4793 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4794 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4795 #else
4796 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4797 #endif
4798 if (area == MAP_FAILED) {
4799 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4800 close(fd);
4801 return (NULL);
4803 *len = memory;
4804 return area;
4806 #endif
4808 static void *qemu_alloc_physram(unsigned long memory)
4810 void *area = NULL;
4811 #ifdef USE_KVM
4812 unsigned long map_len = memory;
4814 if (mem_path)
4815 area = alloc_mem_area(memory, &map_len, mem_path);
4816 #endif
4817 if (!area)
4818 area = qemu_vmalloc(memory);
4819 #ifdef USE_KVM
4820 if (kvm_setup_guest_memory(area, map_len))
4821 area = NULL;
4822 #endif
4823 return area;
4826 #ifndef _WIN32
4828 static void termsig_handler(int signal)
4830 qemu_system_shutdown_request();
4833 static void termsig_setup(void)
4835 struct sigaction act;
4837 memset(&act, 0, sizeof(act));
4838 act.sa_handler = termsig_handler;
4839 sigaction(SIGINT, &act, NULL);
4840 sigaction(SIGHUP, &act, NULL);
4841 sigaction(SIGTERM, &act, NULL);
4844 #endif
4846 int main(int argc, char **argv, char **envp)
4848 #ifdef CONFIG_GDBSTUB
4849 int use_gdbstub;
4850 const char *gdbstub_port;
4851 #endif
4852 uint32_t boot_devices_bitmap = 0;
4853 int i;
4854 int snapshot, linux_boot, net_boot;
4855 const char *initrd_filename;
4856 const char *kernel_filename, *kernel_cmdline;
4857 const char *boot_devices = "";
4858 DisplayState *ds;
4859 DisplayChangeListener *dcl;
4860 int cyls, heads, secs, translation;
4861 const char *net_clients[MAX_NET_CLIENTS];
4862 int nb_net_clients;
4863 const char *bt_opts[MAX_BT_CMDLINE];
4864 int nb_bt_opts;
4865 int hda_index;
4866 int optind;
4867 const char *r, *optarg;
4868 CharDriverState *monitor_hd = NULL;
4869 const char *monitor_device;
4870 const char *serial_devices[MAX_SERIAL_PORTS];
4871 int serial_device_index;
4872 const char *parallel_devices[MAX_PARALLEL_PORTS];
4873 int parallel_device_index;
4874 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4875 int virtio_console_index;
4876 const char *loadvm = NULL;
4877 QEMUMachine *machine;
4878 const char *cpu_model;
4879 const char *usb_devices[MAX_USB_CMDLINE];
4880 int usb_devices_index;
4881 int fds[2];
4882 int tb_size;
4883 const char *pid_file = NULL;
4884 int autostart;
4885 const char *incoming = NULL;
4887 qemu_cache_utils_init(envp);
4889 LIST_INIT (&vm_change_state_head);
4890 #ifndef _WIN32
4892 struct sigaction act;
4893 sigfillset(&act.sa_mask);
4894 act.sa_flags = 0;
4895 act.sa_handler = SIG_IGN;
4896 sigaction(SIGPIPE, &act, NULL);
4898 #else
4899 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4900 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4901 QEMU to run on a single CPU */
4903 HANDLE h;
4904 DWORD mask, smask;
4905 int i;
4906 h = GetCurrentProcess();
4907 if (GetProcessAffinityMask(h, &mask, &smask)) {
4908 for(i = 0; i < 32; i++) {
4909 if (mask & (1 << i))
4910 break;
4912 if (i != 32) {
4913 mask = 1 << i;
4914 SetProcessAffinityMask(h, mask);
4918 #endif
4920 register_machines();
4921 machine = first_machine;
4922 cpu_model = NULL;
4923 initrd_filename = NULL;
4924 ram_size = 0;
4925 vga_ram_size = VGA_RAM_SIZE;
4926 #ifdef CONFIG_GDBSTUB
4927 use_gdbstub = 0;
4928 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4929 #endif
4930 snapshot = 0;
4931 nographic = 0;
4932 curses = 0;
4933 kernel_filename = NULL;
4934 kernel_cmdline = "";
4935 cyls = heads = secs = 0;
4936 translation = BIOS_ATA_TRANSLATION_AUTO;
4937 monitor_device = "vc";
4939 serial_devices[0] = "vc:80Cx24C";
4940 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4941 serial_devices[i] = NULL;
4942 serial_device_index = 0;
4944 parallel_devices[0] = "vc:640x480";
4945 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4946 parallel_devices[i] = NULL;
4947 parallel_device_index = 0;
4949 virtio_consoles[0] = "vc:80Cx24C";
4950 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4951 virtio_consoles[i] = NULL;
4952 virtio_console_index = 0;
4954 usb_devices_index = 0;
4955 assigned_devices_index = 0;
4957 nb_net_clients = 0;
4958 nb_bt_opts = 0;
4959 nb_drives = 0;
4960 nb_drives_opt = 0;
4961 hda_index = -1;
4963 nb_nics = 0;
4965 tb_size = 0;
4966 autostart= 1;
4968 optind = 1;
4969 for(;;) {
4970 if (optind >= argc)
4971 break;
4972 r = argv[optind];
4973 if (r[0] != '-') {
4974 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4975 } else {
4976 const QEMUOption *popt;
4978 optind++;
4979 /* Treat --foo the same as -foo. */
4980 if (r[1] == '-')
4981 r++;
4982 popt = qemu_options;
4983 for(;;) {
4984 if (!popt->name) {
4985 fprintf(stderr, "%s: invalid option -- '%s'\n",
4986 argv[0], r);
4987 exit(1);
4989 if (!strcmp(popt->name, r + 1))
4990 break;
4991 popt++;
4993 if (popt->flags & HAS_ARG) {
4994 if (optind >= argc) {
4995 fprintf(stderr, "%s: option '%s' requires an argument\n",
4996 argv[0], r);
4997 exit(1);
4999 optarg = argv[optind++];
5000 } else {
5001 optarg = NULL;
5004 switch(popt->index) {
5005 case QEMU_OPTION_M:
5006 machine = find_machine(optarg);
5007 if (!machine) {
5008 QEMUMachine *m;
5009 printf("Supported machines are:\n");
5010 for(m = first_machine; m != NULL; m = m->next) {
5011 printf("%-10s %s%s\n",
5012 m->name, m->desc,
5013 m == first_machine ? " (default)" : "");
5015 exit(*optarg != '?');
5017 break;
5018 case QEMU_OPTION_cpu:
5019 /* hw initialization will check this */
5020 if (*optarg == '?') {
5021 /* XXX: implement xxx_cpu_list for targets that still miss it */
5022 #if defined(cpu_list)
5023 cpu_list(stdout, &fprintf);
5024 #endif
5025 exit(0);
5026 } else {
5027 cpu_model = optarg;
5029 break;
5030 case QEMU_OPTION_initrd:
5031 initrd_filename = optarg;
5032 break;
5033 case QEMU_OPTION_hda:
5034 if (cyls == 0)
5035 hda_index = drive_add(optarg, HD_ALIAS, 0);
5036 else
5037 hda_index = drive_add(optarg, HD_ALIAS
5038 ",cyls=%d,heads=%d,secs=%d%s",
5039 0, cyls, heads, secs,
5040 translation == BIOS_ATA_TRANSLATION_LBA ?
5041 ",trans=lba" :
5042 translation == BIOS_ATA_TRANSLATION_NONE ?
5043 ",trans=none" : "");
5044 break;
5045 case QEMU_OPTION_hdb:
5046 case QEMU_OPTION_hdc:
5047 case QEMU_OPTION_hdd:
5048 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5049 break;
5050 case QEMU_OPTION_drive:
5051 drive_add(NULL, "%s", optarg);
5052 break;
5053 case QEMU_OPTION_mtdblock:
5054 drive_add(optarg, MTD_ALIAS);
5055 break;
5056 case QEMU_OPTION_sd:
5057 drive_add(optarg, SD_ALIAS);
5058 break;
5059 case QEMU_OPTION_pflash:
5060 drive_add(optarg, PFLASH_ALIAS);
5061 break;
5062 case QEMU_OPTION_snapshot:
5063 snapshot = 1;
5064 break;
5065 case QEMU_OPTION_hdachs:
5067 const char *p;
5068 p = optarg;
5069 cyls = strtol(p, (char **)&p, 0);
5070 if (cyls < 1 || cyls > 16383)
5071 goto chs_fail;
5072 if (*p != ',')
5073 goto chs_fail;
5074 p++;
5075 heads = strtol(p, (char **)&p, 0);
5076 if (heads < 1 || heads > 16)
5077 goto chs_fail;
5078 if (*p != ',')
5079 goto chs_fail;
5080 p++;
5081 secs = strtol(p, (char **)&p, 0);
5082 if (secs < 1 || secs > 63)
5083 goto chs_fail;
5084 if (*p == ',') {
5085 p++;
5086 if (!strcmp(p, "none"))
5087 translation = BIOS_ATA_TRANSLATION_NONE;
5088 else if (!strcmp(p, "lba"))
5089 translation = BIOS_ATA_TRANSLATION_LBA;
5090 else if (!strcmp(p, "auto"))
5091 translation = BIOS_ATA_TRANSLATION_AUTO;
5092 else
5093 goto chs_fail;
5094 } else if (*p != '\0') {
5095 chs_fail:
5096 fprintf(stderr, "qemu: invalid physical CHS format\n");
5097 exit(1);
5099 if (hda_index != -1)
5100 snprintf(drives_opt[hda_index].opt,
5101 sizeof(drives_opt[hda_index].opt),
5102 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5103 0, cyls, heads, secs,
5104 translation == BIOS_ATA_TRANSLATION_LBA ?
5105 ",trans=lba" :
5106 translation == BIOS_ATA_TRANSLATION_NONE ?
5107 ",trans=none" : "");
5109 break;
5110 case QEMU_OPTION_nographic:
5111 nographic = 1;
5112 break;
5113 #ifdef CONFIG_CURSES
5114 case QEMU_OPTION_curses:
5115 curses = 1;
5116 break;
5117 #endif
5118 case QEMU_OPTION_portrait:
5119 graphic_rotate = 1;
5120 break;
5121 case QEMU_OPTION_kernel:
5122 kernel_filename = optarg;
5123 break;
5124 case QEMU_OPTION_append:
5125 kernel_cmdline = optarg;
5126 break;
5127 case QEMU_OPTION_cdrom:
5128 drive_add(optarg, CDROM_ALIAS);
5129 break;
5130 case QEMU_OPTION_boot:
5131 boot_devices = optarg;
5132 /* We just do some generic consistency checks */
5134 /* Could easily be extended to 64 devices if needed */
5135 const char *p;
5137 boot_devices_bitmap = 0;
5138 for (p = boot_devices; *p != '\0'; p++) {
5139 /* Allowed boot devices are:
5140 * a b : floppy disk drives
5141 * c ... f : IDE disk drives
5142 * g ... m : machine implementation dependant drives
5143 * n ... p : network devices
5144 * It's up to each machine implementation to check
5145 * if the given boot devices match the actual hardware
5146 * implementation and firmware features.
5148 if (*p < 'a' || *p > 'q') {
5149 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5150 exit(1);
5152 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5153 fprintf(stderr,
5154 "Boot device '%c' was given twice\n",*p);
5155 exit(1);
5157 boot_devices_bitmap |= 1 << (*p - 'a');
5160 break;
5161 case QEMU_OPTION_fda:
5162 case QEMU_OPTION_fdb:
5163 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5164 break;
5165 #ifdef TARGET_I386
5166 case QEMU_OPTION_no_fd_bootchk:
5167 fd_bootchk = 0;
5168 break;
5169 #endif
5170 case QEMU_OPTION_net:
5171 if (nb_net_clients >= MAX_NET_CLIENTS) {
5172 fprintf(stderr, "qemu: too many network clients\n");
5173 exit(1);
5175 net_clients[nb_net_clients] = optarg;
5176 nb_net_clients++;
5177 break;
5178 #ifdef CONFIG_SLIRP
5179 case QEMU_OPTION_tftp:
5180 tftp_prefix = optarg;
5181 break;
5182 case QEMU_OPTION_bootp:
5183 bootp_filename = optarg;
5184 break;
5185 #ifndef _WIN32
5186 case QEMU_OPTION_smb:
5187 net_slirp_smb(optarg);
5188 break;
5189 #endif
5190 case QEMU_OPTION_redir:
5191 net_slirp_redir(optarg);
5192 break;
5193 #endif
5194 case QEMU_OPTION_bt:
5195 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5196 fprintf(stderr, "qemu: too many bluetooth options\n");
5197 exit(1);
5199 bt_opts[nb_bt_opts++] = optarg;
5200 break;
5201 #ifdef HAS_AUDIO
5202 case QEMU_OPTION_audio_help:
5203 AUD_help ();
5204 exit (0);
5205 break;
5206 case QEMU_OPTION_soundhw:
5207 select_soundhw (optarg);
5208 break;
5209 #endif
5210 case QEMU_OPTION_h:
5211 help(0);
5212 break;
5213 case QEMU_OPTION_m: {
5214 uint64_t value;
5215 char *ptr;
5217 value = strtoul(optarg, &ptr, 10);
5218 switch (*ptr) {
5219 case 0: case 'M': case 'm':
5220 value <<= 20;
5221 break;
5222 case 'G': case 'g':
5223 value <<= 30;
5224 break;
5225 default:
5226 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5227 exit(1);
5230 /* On 32-bit hosts, QEMU is limited by virtual address space */
5231 if (value > (2047 << 20)
5232 #ifndef USE_KQEMU
5233 && HOST_LONG_BITS == 32
5234 #endif
5236 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5237 exit(1);
5239 if (value != (uint64_t)(ram_addr_t)value) {
5240 fprintf(stderr, "qemu: ram size too large\n");
5241 exit(1);
5243 ram_size = value;
5244 break;
5246 case QEMU_OPTION_d:
5248 int mask;
5249 const CPULogItem *item;
5251 mask = cpu_str_to_log_mask(optarg);
5252 if (!mask) {
5253 printf("Log items (comma separated):\n");
5254 for(item = cpu_log_items; item->mask != 0; item++) {
5255 printf("%-10s %s\n", item->name, item->help);
5257 exit(1);
5259 cpu_set_log(mask);
5261 break;
5262 #ifdef CONFIG_GDBSTUB
5263 case QEMU_OPTION_s:
5264 use_gdbstub = 1;
5265 break;
5266 case QEMU_OPTION_p:
5267 gdbstub_port = optarg;
5268 break;
5269 #endif
5270 case QEMU_OPTION_L:
5271 bios_dir = optarg;
5272 break;
5273 case QEMU_OPTION_bios:
5274 bios_name = optarg;
5275 break;
5276 case QEMU_OPTION_S:
5277 autostart = 0;
5278 break;
5279 case QEMU_OPTION_k:
5280 keyboard_layout = optarg;
5281 break;
5282 case QEMU_OPTION_localtime:
5283 rtc_utc = 0;
5284 break;
5285 case QEMU_OPTION_vga:
5286 select_vgahw (optarg);
5287 break;
5288 case QEMU_OPTION_g:
5290 const char *p;
5291 int w, h, depth;
5292 p = optarg;
5293 w = strtol(p, (char **)&p, 10);
5294 if (w <= 0) {
5295 graphic_error:
5296 fprintf(stderr, "qemu: invalid resolution or depth\n");
5297 exit(1);
5299 if (*p != 'x')
5300 goto graphic_error;
5301 p++;
5302 h = strtol(p, (char **)&p, 10);
5303 if (h <= 0)
5304 goto graphic_error;
5305 if (*p == 'x') {
5306 p++;
5307 depth = strtol(p, (char **)&p, 10);
5308 if (depth != 8 && depth != 15 && depth != 16 &&
5309 depth != 24 && depth != 32)
5310 goto graphic_error;
5311 } else if (*p == '\0') {
5312 depth = graphic_depth;
5313 } else {
5314 goto graphic_error;
5317 graphic_width = w;
5318 graphic_height = h;
5319 graphic_depth = depth;
5321 break;
5322 case QEMU_OPTION_echr:
5324 char *r;
5325 term_escape_char = strtol(optarg, &r, 0);
5326 if (r == optarg)
5327 printf("Bad argument to echr\n");
5328 break;
5330 case QEMU_OPTION_monitor:
5331 monitor_device = optarg;
5332 break;
5333 case QEMU_OPTION_serial:
5334 if (serial_device_index >= MAX_SERIAL_PORTS) {
5335 fprintf(stderr, "qemu: too many serial ports\n");
5336 exit(1);
5338 serial_devices[serial_device_index] = optarg;
5339 serial_device_index++;
5340 break;
5341 case QEMU_OPTION_virtiocon:
5342 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5343 fprintf(stderr, "qemu: too many virtio consoles\n");
5344 exit(1);
5346 virtio_consoles[virtio_console_index] = optarg;
5347 virtio_console_index++;
5348 break;
5349 case QEMU_OPTION_parallel:
5350 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5351 fprintf(stderr, "qemu: too many parallel ports\n");
5352 exit(1);
5354 parallel_devices[parallel_device_index] = optarg;
5355 parallel_device_index++;
5356 break;
5357 case QEMU_OPTION_loadvm:
5358 loadvm = optarg;
5359 break;
5360 case QEMU_OPTION_full_screen:
5361 full_screen = 1;
5362 break;
5363 #ifdef CONFIG_SDL
5364 case QEMU_OPTION_no_frame:
5365 no_frame = 1;
5366 break;
5367 case QEMU_OPTION_alt_grab:
5368 alt_grab = 1;
5369 break;
5370 case QEMU_OPTION_no_quit:
5371 no_quit = 1;
5372 break;
5373 case QEMU_OPTION_sdl:
5374 sdl = 1;
5375 break;
5376 #endif
5377 case QEMU_OPTION_pidfile:
5378 pid_file = optarg;
5379 break;
5380 #ifdef TARGET_I386
5381 case QEMU_OPTION_win2k_hack:
5382 win2k_install_hack = 1;
5383 break;
5384 case QEMU_OPTION_rtc_td_hack:
5385 rtc_td_hack = 1;
5386 break;
5387 #endif
5388 #ifdef USE_KQEMU
5389 case QEMU_OPTION_no_kqemu:
5390 kqemu_allowed = 0;
5391 break;
5392 case QEMU_OPTION_kernel_kqemu:
5393 kqemu_allowed = 2;
5394 break;
5395 #endif
5396 #ifdef CONFIG_KVM
5397 case QEMU_OPTION_enable_kvm:
5398 kvm_allowed = 1;
5399 #ifdef USE_KQEMU
5400 kqemu_allowed = 0;
5401 #endif
5402 break;
5403 #endif
5404 #ifdef USE_KVM
5405 case QEMU_OPTION_no_kvm:
5406 kvm_allowed = 0;
5407 break;
5408 case QEMU_OPTION_no_kvm_irqchip: {
5409 kvm_irqchip = 0;
5410 kvm_pit = 0;
5411 break;
5413 case QEMU_OPTION_no_kvm_pit: {
5414 kvm_pit = 0;
5415 break;
5417 case QEMU_OPTION_no_kvm_pit_reinjection: {
5418 kvm_pit_reinject = 0;
5419 break;
5421 case QEMU_OPTION_enable_nesting: {
5422 kvm_nested = 1;
5423 break;
5425 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5426 case QEMU_OPTION_pcidevice:
5427 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5428 fprintf(stderr, "Too many assigned devices\n");
5429 exit(1);
5431 assigned_devices[assigned_devices_index] = optarg;
5432 assigned_devices_index++;
5433 break;
5434 #endif
5435 #endif
5436 case QEMU_OPTION_usb:
5437 usb_enabled = 1;
5438 break;
5439 case QEMU_OPTION_usbdevice:
5440 usb_enabled = 1;
5441 if (usb_devices_index >= MAX_USB_CMDLINE) {
5442 fprintf(stderr, "Too many USB devices\n");
5443 exit(1);
5445 usb_devices[usb_devices_index] = optarg;
5446 usb_devices_index++;
5447 break;
5448 case QEMU_OPTION_smp:
5449 smp_cpus = atoi(optarg);
5450 if (smp_cpus < 1) {
5451 fprintf(stderr, "Invalid number of CPUs\n");
5452 exit(1);
5454 break;
5455 case QEMU_OPTION_vnc:
5456 vnc_display = optarg;
5457 break;
5458 case QEMU_OPTION_no_acpi:
5459 acpi_enabled = 0;
5460 break;
5461 case QEMU_OPTION_no_hpet:
5462 no_hpet = 1;
5463 break;
5464 case QEMU_OPTION_no_reboot:
5465 no_reboot = 1;
5466 break;
5467 case QEMU_OPTION_no_shutdown:
5468 no_shutdown = 1;
5469 break;
5470 case QEMU_OPTION_show_cursor:
5471 cursor_hide = 0;
5472 break;
5473 case QEMU_OPTION_uuid:
5474 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5475 fprintf(stderr, "Fail to parse UUID string."
5476 " Wrong format.\n");
5477 exit(1);
5479 break;
5480 case QEMU_OPTION_daemonize:
5481 daemonize = 1;
5482 break;
5483 case QEMU_OPTION_option_rom:
5484 if (nb_option_roms >= MAX_OPTION_ROMS) {
5485 fprintf(stderr, "Too many option ROMs\n");
5486 exit(1);
5488 option_rom[nb_option_roms] = optarg;
5489 nb_option_roms++;
5490 break;
5491 case QEMU_OPTION_semihosting:
5492 semihosting_enabled = 1;
5493 break;
5494 case QEMU_OPTION_tdf:
5495 time_drift_fix = 1;
5496 break;
5497 case QEMU_OPTION_kvm_shadow_memory:
5498 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5499 break;
5500 case QEMU_OPTION_mempath:
5501 mem_path = optarg;
5502 break;
5503 #ifdef MAP_POPULATE
5504 case QEMU_OPTION_mem_prealloc:
5505 mem_prealloc = !mem_prealloc;
5506 break;
5507 #endif
5508 case QEMU_OPTION_name:
5509 qemu_name = optarg;
5510 break;
5511 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5512 case QEMU_OPTION_prom_env:
5513 if (nb_prom_envs >= MAX_PROM_ENVS) {
5514 fprintf(stderr, "Too many prom variables\n");
5515 exit(1);
5517 prom_envs[nb_prom_envs] = optarg;
5518 nb_prom_envs++;
5519 break;
5520 #endif
5521 case QEMU_OPTION_cpu_vendor:
5522 cpu_vendor_string = optarg;
5523 break;
5524 #ifdef TARGET_ARM
5525 case QEMU_OPTION_old_param:
5526 old_param = 1;
5527 break;
5528 #endif
5529 case QEMU_OPTION_clock:
5530 configure_alarms(optarg);
5531 break;
5532 case QEMU_OPTION_startdate:
5534 struct tm tm;
5535 time_t rtc_start_date;
5536 if (!strcmp(optarg, "now")) {
5537 rtc_date_offset = -1;
5538 } else {
5539 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5540 &tm.tm_year,
5541 &tm.tm_mon,
5542 &tm.tm_mday,
5543 &tm.tm_hour,
5544 &tm.tm_min,
5545 &tm.tm_sec) == 6) {
5546 /* OK */
5547 } else if (sscanf(optarg, "%d-%d-%d",
5548 &tm.tm_year,
5549 &tm.tm_mon,
5550 &tm.tm_mday) == 3) {
5551 tm.tm_hour = 0;
5552 tm.tm_min = 0;
5553 tm.tm_sec = 0;
5554 } else {
5555 goto date_fail;
5557 tm.tm_year -= 1900;
5558 tm.tm_mon--;
5559 rtc_start_date = mktimegm(&tm);
5560 if (rtc_start_date == -1) {
5561 date_fail:
5562 fprintf(stderr, "Invalid date format. Valid format are:\n"
5563 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5564 exit(1);
5566 rtc_date_offset = time(NULL) - rtc_start_date;
5569 break;
5570 case QEMU_OPTION_tb_size:
5571 tb_size = strtol(optarg, NULL, 0);
5572 if (tb_size < 0)
5573 tb_size = 0;
5574 break;
5575 case QEMU_OPTION_icount:
5576 use_icount = 1;
5577 if (strcmp(optarg, "auto") == 0) {
5578 icount_time_shift = -1;
5579 } else {
5580 icount_time_shift = strtol(optarg, NULL, 0);
5582 break;
5583 case QEMU_OPTION_incoming:
5584 incoming = optarg;
5585 break;
5586 case QEMU_OPTION_nvram:
5587 nvram = optarg;
5588 break;
5593 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5594 if (kvm_allowed && kqemu_allowed) {
5595 fprintf(stderr,
5596 "You can not enable both KVM and kqemu at the same time\n");
5597 exit(1);
5599 #endif
5601 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5602 if (smp_cpus > machine->max_cpus) {
5603 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5604 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5605 machine->max_cpus);
5606 exit(1);
5609 if (nographic) {
5610 if (serial_device_index == 0)
5611 serial_devices[0] = "stdio";
5612 if (parallel_device_index == 0)
5613 parallel_devices[0] = "null";
5614 if (strncmp(monitor_device, "vc", 2) == 0)
5615 monitor_device = "stdio";
5616 if (virtio_console_index == 0)
5617 virtio_consoles[0] = "null";
5620 #ifndef _WIN32
5621 if (daemonize) {
5622 pid_t pid;
5624 if (pipe(fds) == -1)
5625 exit(1);
5627 pid = fork();
5628 if (pid > 0) {
5629 uint8_t status;
5630 ssize_t len;
5632 close(fds[1]);
5634 again:
5635 len = read(fds[0], &status, 1);
5636 if (len == -1 && (errno == EINTR))
5637 goto again;
5639 if (len != 1)
5640 exit(1);
5641 else if (status == 1) {
5642 fprintf(stderr, "Could not acquire pidfile\n");
5643 exit(1);
5644 } else
5645 exit(0);
5646 } else if (pid < 0)
5647 exit(1);
5649 setsid();
5651 pid = fork();
5652 if (pid > 0)
5653 exit(0);
5654 else if (pid < 0)
5655 exit(1);
5657 umask(027);
5659 signal(SIGTSTP, SIG_IGN);
5660 signal(SIGTTOU, SIG_IGN);
5661 signal(SIGTTIN, SIG_IGN);
5663 #endif
5665 #ifdef USE_KVM
5666 if (kvm_enabled()) {
5667 if (kvm_qemu_init() < 0) {
5668 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5669 #ifdef NO_CPU_EMULATION
5670 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5671 exit(1);
5672 #endif
5673 kvm_allowed = 0;
5676 #endif
5678 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5679 if (daemonize) {
5680 uint8_t status = 1;
5681 write(fds[1], &status, 1);
5682 } else
5683 fprintf(stderr, "Could not acquire pid file\n");
5684 exit(1);
5687 #ifdef USE_KQEMU
5688 if (smp_cpus > 1)
5689 kqemu_allowed = 0;
5690 #endif
5691 linux_boot = (kernel_filename != NULL);
5692 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5694 if (!linux_boot && net_boot == 0 &&
5695 !machine->nodisk_ok && nb_drives_opt == 0)
5696 help(1);
5698 if (!linux_boot && *kernel_cmdline != '\0') {
5699 fprintf(stderr, "-append only allowed with -kernel option\n");
5700 exit(1);
5703 if (!linux_boot && initrd_filename != NULL) {
5704 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5705 exit(1);
5708 /* boot to floppy or the default cd if no hard disk defined yet */
5709 if (!boot_devices[0]) {
5710 boot_devices = "cad";
5712 setvbuf(stdout, NULL, _IOLBF, 0);
5714 init_timers();
5715 if (init_timer_alarm() < 0) {
5716 fprintf(stderr, "could not initialize alarm timer\n");
5717 exit(1);
5719 if (use_icount && icount_time_shift < 0) {
5720 use_icount = 2;
5721 /* 125MIPS seems a reasonable initial guess at the guest speed.
5722 It will be corrected fairly quickly anyway. */
5723 icount_time_shift = 3;
5724 init_icount_adjust();
5727 #ifdef _WIN32
5728 socket_init();
5729 #endif
5731 /* init network clients */
5732 if (nb_net_clients == 0) {
5733 /* if no clients, we use a default config */
5734 net_clients[nb_net_clients++] = "nic";
5735 #ifdef CONFIG_SLIRP
5736 net_clients[nb_net_clients++] = "user";
5737 #endif
5740 for(i = 0;i < nb_net_clients; i++) {
5741 if (net_client_parse(net_clients[i]) < 0)
5742 exit(1);
5744 net_client_check();
5746 #ifdef TARGET_I386
5747 /* XXX: this should be moved in the PC machine instantiation code */
5748 if (net_boot != 0) {
5749 int netroms = 0;
5750 for (i = 0; i < nb_nics && i < 4; i++) {
5751 const char *model = nd_table[i].model;
5752 char buf[1024];
5753 if (net_boot & (1 << i)) {
5754 if (model == NULL)
5755 model = "rtl8139";
5756 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5757 if (get_image_size(buf) > 0) {
5758 if (nb_option_roms >= MAX_OPTION_ROMS) {
5759 fprintf(stderr, "Too many option ROMs\n");
5760 exit(1);
5762 option_rom[nb_option_roms] = strdup(buf);
5763 nb_option_roms++;
5764 netroms++;
5768 if (netroms == 0) {
5769 fprintf(stderr, "No valid PXE rom found for network device\n");
5770 exit(1);
5773 #endif
5775 /* init the bluetooth world */
5776 for (i = 0; i < nb_bt_opts; i++)
5777 if (bt_parse(bt_opts[i]))
5778 exit(1);
5780 /* init the memory */
5781 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5783 if (machine->ram_require & RAMSIZE_FIXED) {
5784 if (ram_size > 0) {
5785 if (ram_size < phys_ram_size) {
5786 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5787 machine->name, (unsigned long long) phys_ram_size);
5788 exit(-1);
5791 phys_ram_size = ram_size;
5792 } else
5793 ram_size = phys_ram_size;
5794 } else {
5795 if (ram_size == 0)
5796 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5798 phys_ram_size += ram_size;
5801 /* Initialize kvm */
5802 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5803 #define KVM_EXTRA_PAGES 3
5804 #else
5805 #define KVM_EXTRA_PAGES 0
5806 #endif
5807 if (kvm_enabled()) {
5808 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5809 if (kvm_qemu_create_context() < 0) {
5810 fprintf(stderr, "Could not create KVM context\n");
5811 exit(1);
5815 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5816 if (!phys_ram_base) {
5817 fprintf(stderr, "Could not allocate physical memory\n");
5818 exit(1);
5821 /* init the dynamic translator */
5822 cpu_exec_init_all(tb_size * 1024 * 1024);
5824 bdrv_init();
5826 /* we always create the cdrom drive, even if no disk is there */
5828 if (nb_drives_opt < MAX_DRIVES)
5829 drive_add(NULL, CDROM_ALIAS);
5831 /* we always create at least one floppy */
5833 if (nb_drives_opt < MAX_DRIVES)
5834 drive_add(NULL, FD_ALIAS, 0);
5836 /* we always create one sd slot, even if no card is in it */
5838 if (nb_drives_opt < MAX_DRIVES)
5839 drive_add(NULL, SD_ALIAS);
5841 /* open the virtual block devices
5842 * note that migration with device
5843 * hot add/remove is broken.
5845 for(i = 0; i < nb_drives_opt; i++)
5846 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5847 exit(1);
5849 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5850 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5852 #ifndef _WIN32
5853 /* must be after terminal init, SDL library changes signal handlers */
5854 termsig_setup();
5855 #endif
5857 /* Maintain compatibility with multiple stdio monitors */
5858 if (!strcmp(monitor_device,"stdio")) {
5859 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5860 const char *devname = serial_devices[i];
5861 if (devname && !strcmp(devname,"mon:stdio")) {
5862 monitor_device = NULL;
5863 break;
5864 } else if (devname && !strcmp(devname,"stdio")) {
5865 monitor_device = NULL;
5866 serial_devices[i] = "mon:stdio";
5867 break;
5872 #ifdef KVM_UPSTREAM
5873 if (kvm_enabled()) {
5874 int ret;
5876 ret = kvm_init(smp_cpus);
5877 if (ret < 0) {
5878 fprintf(stderr, "failed to initialize KVM\n");
5879 exit(1);
5882 #endif
5884 if (monitor_device) {
5885 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5886 if (!monitor_hd) {
5887 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5888 exit(1);
5892 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5893 const char *devname = serial_devices[i];
5894 if (devname && strcmp(devname, "none")) {
5895 char label[32];
5896 snprintf(label, sizeof(label), "serial%d", i);
5897 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5898 if (!serial_hds[i]) {
5899 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5900 devname);
5901 exit(1);
5906 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5907 const char *devname = parallel_devices[i];
5908 if (devname && strcmp(devname, "none")) {
5909 char label[32];
5910 snprintf(label, sizeof(label), "parallel%d", i);
5911 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5912 if (!parallel_hds[i]) {
5913 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5914 devname);
5915 exit(1);
5920 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5921 const char *devname = virtio_consoles[i];
5922 if (devname && strcmp(devname, "none")) {
5923 char label[32];
5924 snprintf(label, sizeof(label), "virtcon%d", i);
5925 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5926 if (!virtcon_hds[i]) {
5927 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5928 devname);
5929 exit(1);
5934 if (kvm_enabled())
5935 kvm_init_ap();
5937 machine->init(ram_size, vga_ram_size, boot_devices,
5938 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5940 current_machine = machine;
5942 /* Set KVM's vcpu state to qemu's initial CPUState. */
5943 if (kvm_enabled()) {
5944 int ret;
5946 ret = kvm_sync_vcpus();
5947 if (ret < 0) {
5948 fprintf(stderr, "failed to initialize vcpus\n");
5949 exit(1);
5953 /* init USB devices */
5954 if (usb_enabled) {
5955 for(i = 0; i < usb_devices_index; i++) {
5956 if (usb_device_add(usb_devices[i]) < 0) {
5957 fprintf(stderr, "Warning: could not add USB device %s\n",
5958 usb_devices[i]);
5963 if (!display_state)
5964 dumb_display_init();
5965 /* just use the first displaystate for the moment */
5966 ds = display_state;
5967 /* terminal init */
5968 if (nographic) {
5969 if (curses) {
5970 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5971 exit(1);
5973 } else {
5974 #if defined(CONFIG_CURSES)
5975 if (curses) {
5976 /* At the moment curses cannot be used with other displays */
5977 curses_display_init(ds, full_screen);
5978 } else
5979 #endif
5981 if (vnc_display != NULL) {
5982 vnc_display_init(ds);
5983 if (vnc_display_open(ds, vnc_display) < 0)
5984 exit(1);
5986 #if defined(CONFIG_SDL)
5987 if (sdl || !vnc_display)
5988 sdl_display_init(ds, full_screen, no_frame);
5989 #elif defined(CONFIG_COCOA)
5990 if (sdl || !vnc_display)
5991 cocoa_display_init(ds, full_screen);
5992 #endif
5995 dpy_resize(ds);
5997 dcl = ds->listeners;
5998 while (dcl != NULL) {
5999 if (dcl->dpy_refresh != NULL) {
6000 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6001 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6003 dcl = dcl->next;
6006 if (nographic || (vnc_display && !sdl)) {
6007 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6008 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6011 text_consoles_set_display(display_state);
6013 if (monitor_device && monitor_hd)
6014 monitor_init(monitor_hd, !nographic);
6016 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6017 const char *devname = serial_devices[i];
6018 if (devname && strcmp(devname, "none")) {
6019 char label[32];
6020 snprintf(label, sizeof(label), "serial%d", i);
6021 if (strstart(devname, "vc", 0))
6022 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6026 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6027 const char *devname = parallel_devices[i];
6028 if (devname && strcmp(devname, "none")) {
6029 char label[32];
6030 snprintf(label, sizeof(label), "parallel%d", i);
6031 if (strstart(devname, "vc", 0))
6032 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6036 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6037 const char *devname = virtio_consoles[i];
6038 if (virtcon_hds[i] && devname) {
6039 char label[32];
6040 snprintf(label, sizeof(label), "virtcon%d", i);
6041 if (strstart(devname, "vc", 0))
6042 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6046 #ifdef CONFIG_GDBSTUB
6047 if (use_gdbstub) {
6048 /* XXX: use standard host:port notation and modify options
6049 accordingly. */
6050 if (gdbserver_start(gdbstub_port) < 0) {
6051 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6052 gdbstub_port);
6053 exit(1);
6056 #endif
6058 if (loadvm)
6059 do_loadvm(loadvm);
6061 if (incoming) {
6062 autostart = 0; /* fixme how to deal with -daemonize */
6063 qemu_start_incoming_migration(incoming);
6067 /* XXX: simplify init */
6068 read_passwords();
6069 if (autostart) {
6070 vm_start();
6074 if (daemonize) {
6075 uint8_t status = 0;
6076 ssize_t len;
6077 int fd;
6079 again1:
6080 len = write(fds[1], &status, 1);
6081 if (len == -1 && (errno == EINTR))
6082 goto again1;
6084 if (len != 1)
6085 exit(1);
6087 chdir("/");
6088 TFR(fd = open("/dev/null", O_RDWR));
6089 if (fd == -1)
6090 exit(1);
6092 dup2(fd, 0);
6093 dup2(fd, 1);
6094 dup2(fd, 2);
6096 close(fd);
6099 main_loop();
6100 quit_timers();
6101 net_cleanup();
6103 return 0;