kvm: testsuite: Fix warnings
[qemu-kvm/fedora.git] / vl.c
blobcde1a32f9c05451c295dcd025fbfd34c24657f84
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "hw/device-assignment.h"
43 #include "migration.h"
44 #include "kvm.h"
45 #include "balloon.h"
46 #include "qemu-kvm.h"
48 #include <unistd.h>
49 #include <fcntl.h>
50 #include <signal.h>
51 #include <time.h>
52 #include <errno.h>
53 #include <sys/time.h>
54 #include <zlib.h>
56 #ifndef _WIN32
57 #include <sys/times.h>
58 #include <sys/wait.h>
59 #include <termios.h>
60 #include <sys/mman.h>
61 #include <sys/ioctl.h>
62 #include <sys/resource.h>
63 #include <sys/socket.h>
64 #include <netinet/in.h>
65 #include <net/if.h>
66 #if defined(__NetBSD__)
67 #include <net/if_tap.h>
68 #endif
69 #ifdef __linux__
70 #include <linux/if_tun.h>
71 #endif
72 #include <arpa/inet.h>
73 #include <dirent.h>
74 #include <netdb.h>
75 #include <sys/select.h>
76 #ifdef _BSD
77 #include <sys/stat.h>
78 #ifdef __FreeBSD__
79 #include <libutil.h>
80 #else
81 #include <util.h>
82 #endif
83 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
84 #include <freebsd/stdlib.h>
85 #else
86 #ifdef __linux__
87 #include <pty.h>
88 #include <malloc.h>
89 #include <linux/rtc.h>
91 /* For the benefit of older linux systems which don't supply it,
92 we use a local copy of hpet.h. */
93 /* #include <linux/hpet.h> */
94 #include "hpet.h"
96 #include <linux/ppdev.h>
97 #include <linux/parport.h>
98 #endif
99 #ifdef __sun__
100 #include <sys/stat.h>
101 #include <sys/ethernet.h>
102 #include <sys/sockio.h>
103 #include <netinet/arp.h>
104 #include <netinet/in.h>
105 #include <netinet/in_systm.h>
106 #include <netinet/ip.h>
107 #include <netinet/ip_icmp.h> // must come after ip.h
108 #include <netinet/udp.h>
109 #include <netinet/tcp.h>
110 #include <net/if.h>
111 #include <syslog.h>
112 #include <stropts.h>
113 #endif
114 #endif
115 #endif
117 #include "qemu_socket.h"
119 #if defined(CONFIG_SLIRP)
120 #include "libslirp.h"
121 #endif
123 #if defined(__OpenBSD__)
124 #include <util.h>
125 #endif
127 #if defined(CONFIG_VDE)
128 #include <libvdeplug.h>
129 #endif
131 #ifdef _WIN32
132 #include <malloc.h>
133 #include <sys/timeb.h>
134 #include <mmsystem.h>
135 #define getopt_long_only getopt_long
136 #define memalign(align, size) malloc(size)
137 #endif
139 #ifdef CONFIG_SDL
140 #ifdef __APPLE__
141 #include <SDL/SDL.h>
142 #endif
143 #endif /* CONFIG_SDL */
145 #ifdef CONFIG_COCOA
146 #undef main
147 #define main qemu_main
148 #endif /* CONFIG_COCOA */
150 #include "disas.h"
152 #include "exec-all.h"
154 #include "qemu-kvm.h"
156 //#define DEBUG_UNUSED_IOPORT
157 //#define DEBUG_IOPORT
158 //#define DEBUG_NET
159 //#define DEBUG_SLIRP
162 #ifdef DEBUG_IOPORT
163 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
164 #else
165 # define LOG_IOPORT(...) do { } while (0)
166 #endif
168 #define DEFAULT_RAM_SIZE 128
170 /* Max number of USB devices that can be specified on the commandline. */
171 #define MAX_USB_CMDLINE 8
173 /* Max number of bluetooth switches on the commandline. */
174 #define MAX_BT_CMDLINE 10
176 /* XXX: use a two level table to limit memory usage */
177 #define MAX_IOPORTS 65536
179 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
180 const char *bios_name = NULL;
181 static void *ioport_opaque[MAX_IOPORTS];
182 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
183 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
184 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
185 to store the VM snapshots */
186 DriveInfo drives_table[MAX_DRIVES+1];
187 int nb_drives;
188 int extboot_drive = -1;
189 static int vga_ram_size;
190 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
191 static DisplayState *display_state;
192 int nographic;
193 static int curses;
194 static int sdl;
195 const char* keyboard_layout = NULL;
196 int64_t ticks_per_sec;
197 ram_addr_t ram_size;
198 int nb_nics;
199 NICInfo nd_table[MAX_NICS];
200 int vm_running;
201 static int rtc_utc = 1;
202 static int rtc_date_offset = -1; /* -1 means no change */
203 int cirrus_vga_enabled = 1;
204 int std_vga_enabled = 0;
205 int vmsvga_enabled = 0;
206 #ifdef TARGET_SPARC
207 int graphic_width = 1024;
208 int graphic_height = 768;
209 int graphic_depth = 8;
210 #else
211 int graphic_width = 800;
212 int graphic_height = 600;
213 int graphic_depth = 15;
214 #endif
215 static int full_screen = 0;
216 #ifdef CONFIG_SDL
217 static int no_frame = 0;
218 #endif
219 int no_quit = 0;
220 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
221 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
222 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
223 #ifdef TARGET_I386
224 int win2k_install_hack = 0;
225 int rtc_td_hack = 0;
226 #endif
227 int usb_enabled = 0;
228 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
229 int assigned_devices_index;
230 int smp_cpus = 1;
231 const char *vnc_display;
232 int acpi_enabled = 1;
233 int no_hpet = 0;
234 int fd_bootchk = 1;
235 int no_reboot = 0;
236 int no_shutdown = 0;
237 int cursor_hide = 1;
238 int graphic_rotate = 0;
239 int daemonize = 0;
240 const char *incoming;
241 const char *option_rom[MAX_OPTION_ROMS];
242 int nb_option_roms;
243 int semihosting_enabled = 0;
244 int time_drift_fix = 0;
245 unsigned int kvm_shadow_memory = 0;
246 const char *mem_path = NULL;
247 #ifdef MAP_POPULATE
248 int mem_prealloc = 1; /* force preallocation of physical target memory */
249 #endif
250 int hpagesize = 0;
251 const char *cpu_vendor_string;
252 #ifdef TARGET_ARM
253 int old_param = 0;
254 #endif
255 const char *qemu_name;
256 int alt_grab = 0;
257 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
258 unsigned int nb_prom_envs = 0;
259 const char *prom_envs[MAX_PROM_ENVS];
260 #endif
261 int nb_drives_opt;
262 const char *nvram = NULL;
263 struct drive_opt drives_opt[MAX_DRIVES];
265 static CPUState *cur_cpu;
266 static CPUState *next_cpu;
267 static int event_pending = 1;
268 /* Conversion factor from emulated instructions to virtual clock ticks. */
269 static int icount_time_shift;
270 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
271 #define MAX_ICOUNT_SHIFT 10
272 /* Compensate for varying guest execution speed. */
273 static int64_t qemu_icount_bias;
274 static QEMUTimer *icount_rt_timer;
275 static QEMUTimer *icount_vm_timer;
276 static QEMUTimer *nographic_timer;
278 uint8_t qemu_uuid[16];
280 /* KVM runs the main loop in a separate thread. If we update one of the lists
281 * that are polled before or after select(), we need to make sure to break out
282 * of the select() to ensure the new item is serviced.
284 static void main_loop_break(void)
286 if (kvm_enabled())
287 qemu_kvm_notify_work();
290 /***********************************************************/
291 /* x86 ISA bus support */
293 target_phys_addr_t isa_mem_base = 0;
294 PicState2 *isa_pic;
296 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
297 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
299 static uint32_t ioport_read(int index, uint32_t address)
301 static IOPortReadFunc *default_func[3] = {
302 default_ioport_readb,
303 default_ioport_readw,
304 default_ioport_readl
306 IOPortReadFunc *func = ioport_read_table[index][address];
307 if (!func)
308 func = default_func[index];
309 return func(ioport_opaque[address], address);
312 static void ioport_write(int index, uint32_t address, uint32_t data)
314 static IOPortWriteFunc *default_func[3] = {
315 default_ioport_writeb,
316 default_ioport_writew,
317 default_ioport_writel
319 IOPortWriteFunc *func = ioport_write_table[index][address];
320 if (!func)
321 func = default_func[index];
322 func(ioport_opaque[address], address, data);
325 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
327 #ifdef DEBUG_UNUSED_IOPORT
328 fprintf(stderr, "unused inb: port=0x%04x\n", address);
329 #endif
330 return 0xff;
333 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
335 #ifdef DEBUG_UNUSED_IOPORT
336 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
337 #endif
340 /* default is to make two byte accesses */
341 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
343 uint32_t data;
344 data = ioport_read(0, address);
345 address = (address + 1) & (MAX_IOPORTS - 1);
346 data |= ioport_read(0, address) << 8;
347 return data;
350 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
352 ioport_write(0, address, data & 0xff);
353 address = (address + 1) & (MAX_IOPORTS - 1);
354 ioport_write(0, address, (data >> 8) & 0xff);
357 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
359 #ifdef DEBUG_UNUSED_IOPORT
360 fprintf(stderr, "unused inl: port=0x%04x\n", address);
361 #endif
362 return 0xffffffff;
365 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
367 #ifdef DEBUG_UNUSED_IOPORT
368 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
369 #endif
372 /* size is the word size in byte */
373 int register_ioport_read(int start, int length, int size,
374 IOPortReadFunc *func, void *opaque)
376 int i, bsize;
378 if (size == 1) {
379 bsize = 0;
380 } else if (size == 2) {
381 bsize = 1;
382 } else if (size == 4) {
383 bsize = 2;
384 } else {
385 hw_error("register_ioport_read: invalid size");
386 return -1;
388 for(i = start; i < start + length; i += size) {
389 ioport_read_table[bsize][i] = func;
390 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
391 hw_error("register_ioport_read: invalid opaque");
392 ioport_opaque[i] = opaque;
394 return 0;
397 /* size is the word size in byte */
398 int register_ioport_write(int start, int length, int size,
399 IOPortWriteFunc *func, void *opaque)
401 int i, bsize;
403 if (size == 1) {
404 bsize = 0;
405 } else if (size == 2) {
406 bsize = 1;
407 } else if (size == 4) {
408 bsize = 2;
409 } else {
410 hw_error("register_ioport_write: invalid size");
411 return -1;
413 for(i = start; i < start + length; i += size) {
414 ioport_write_table[bsize][i] = func;
415 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
416 hw_error("register_ioport_write: invalid opaque");
417 ioport_opaque[i] = opaque;
419 return 0;
422 void isa_unassign_ioport(int start, int length)
424 int i;
426 for(i = start; i < start + length; i++) {
427 ioport_read_table[0][i] = default_ioport_readb;
428 ioport_read_table[1][i] = default_ioport_readw;
429 ioport_read_table[2][i] = default_ioport_readl;
431 ioport_write_table[0][i] = default_ioport_writeb;
432 ioport_write_table[1][i] = default_ioport_writew;
433 ioport_write_table[2][i] = default_ioport_writel;
435 ioport_opaque[i] = NULL;
439 /***********************************************************/
441 void cpu_outb(CPUState *env, int addr, int val)
443 LOG_IOPORT("outb: %04x %02x\n", addr, val);
444 ioport_write(0, addr, val);
445 #ifdef USE_KQEMU
446 if (env)
447 env->last_io_time = cpu_get_time_fast();
448 #endif
451 void cpu_outw(CPUState *env, int addr, int val)
453 LOG_IOPORT("outw: %04x %04x\n", addr, val);
454 ioport_write(1, addr, val);
455 #ifdef USE_KQEMU
456 if (env)
457 env->last_io_time = cpu_get_time_fast();
458 #endif
461 void cpu_outl(CPUState *env, int addr, int val)
463 LOG_IOPORT("outl: %04x %08x\n", addr, val);
464 ioport_write(2, addr, val);
465 #ifdef USE_KQEMU
466 if (env)
467 env->last_io_time = cpu_get_time_fast();
468 #endif
471 int cpu_inb(CPUState *env, int addr)
473 int val;
474 val = ioport_read(0, addr);
475 LOG_IOPORT("inb : %04x %02x\n", addr, val);
476 #ifdef USE_KQEMU
477 if (env)
478 env->last_io_time = cpu_get_time_fast();
479 #endif
480 return val;
483 int cpu_inw(CPUState *env, int addr)
485 int val;
486 val = ioport_read(1, addr);
487 LOG_IOPORT("inw : %04x %04x\n", addr, val);
488 #ifdef USE_KQEMU
489 if (env)
490 env->last_io_time = cpu_get_time_fast();
491 #endif
492 return val;
495 int cpu_inl(CPUState *env, int addr)
497 int val;
498 val = ioport_read(2, addr);
499 LOG_IOPORT("inl : %04x %08x\n", addr, val);
500 #ifdef USE_KQEMU
501 if (env)
502 env->last_io_time = cpu_get_time_fast();
503 #endif
504 return val;
507 /***********************************************************/
508 void hw_error(const char *fmt, ...)
510 va_list ap;
511 CPUState *env;
513 va_start(ap, fmt);
514 fprintf(stderr, "qemu: hardware error: ");
515 vfprintf(stderr, fmt, ap);
516 fprintf(stderr, "\n");
517 for(env = first_cpu; env != NULL; env = env->next_cpu) {
518 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
519 #ifdef TARGET_I386
520 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
521 #else
522 cpu_dump_state(env, stderr, fprintf, 0);
523 #endif
525 va_end(ap);
526 abort();
529 /***************/
530 /* ballooning */
532 static QEMUBalloonEvent *qemu_balloon_event;
533 void *qemu_balloon_event_opaque;
535 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
537 qemu_balloon_event = func;
538 qemu_balloon_event_opaque = opaque;
541 void qemu_balloon(ram_addr_t target)
543 if (qemu_balloon_event)
544 qemu_balloon_event(qemu_balloon_event_opaque, target);
547 ram_addr_t qemu_balloon_status(void)
549 if (qemu_balloon_event)
550 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
551 return 0;
554 /***********************************************************/
555 /* keyboard/mouse */
557 static QEMUPutKBDEvent *qemu_put_kbd_event;
558 static void *qemu_put_kbd_event_opaque;
559 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
560 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
562 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
564 qemu_put_kbd_event_opaque = opaque;
565 qemu_put_kbd_event = func;
568 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
569 void *opaque, int absolute,
570 const char *name)
572 QEMUPutMouseEntry *s, *cursor;
574 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
576 s->qemu_put_mouse_event = func;
577 s->qemu_put_mouse_event_opaque = opaque;
578 s->qemu_put_mouse_event_absolute = absolute;
579 s->qemu_put_mouse_event_name = qemu_strdup(name);
580 s->next = NULL;
582 if (!qemu_put_mouse_event_head) {
583 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
584 return s;
587 cursor = qemu_put_mouse_event_head;
588 while (cursor->next != NULL)
589 cursor = cursor->next;
591 cursor->next = s;
592 qemu_put_mouse_event_current = s;
594 return s;
597 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
599 QEMUPutMouseEntry *prev = NULL, *cursor;
601 if (!qemu_put_mouse_event_head || entry == NULL)
602 return;
604 cursor = qemu_put_mouse_event_head;
605 while (cursor != NULL && cursor != entry) {
606 prev = cursor;
607 cursor = cursor->next;
610 if (cursor == NULL) // does not exist or list empty
611 return;
612 else if (prev == NULL) { // entry is head
613 qemu_put_mouse_event_head = cursor->next;
614 if (qemu_put_mouse_event_current == entry)
615 qemu_put_mouse_event_current = cursor->next;
616 qemu_free(entry->qemu_put_mouse_event_name);
617 qemu_free(entry);
618 return;
621 prev->next = entry->next;
623 if (qemu_put_mouse_event_current == entry)
624 qemu_put_mouse_event_current = prev;
626 qemu_free(entry->qemu_put_mouse_event_name);
627 qemu_free(entry);
630 void kbd_put_keycode(int keycode)
632 if (qemu_put_kbd_event) {
633 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
637 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
639 QEMUPutMouseEvent *mouse_event;
640 void *mouse_event_opaque;
641 int width;
643 if (!qemu_put_mouse_event_current) {
644 return;
647 mouse_event =
648 qemu_put_mouse_event_current->qemu_put_mouse_event;
649 mouse_event_opaque =
650 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
652 if (mouse_event) {
653 if (graphic_rotate) {
654 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
655 width = 0x7fff;
656 else
657 width = graphic_width - 1;
658 mouse_event(mouse_event_opaque,
659 width - dy, dx, dz, buttons_state);
660 } else
661 mouse_event(mouse_event_opaque,
662 dx, dy, dz, buttons_state);
666 int kbd_mouse_is_absolute(void)
668 if (!qemu_put_mouse_event_current)
669 return 0;
671 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
674 void do_info_mice(void)
676 QEMUPutMouseEntry *cursor;
677 int index = 0;
679 if (!qemu_put_mouse_event_head) {
680 term_printf("No mouse devices connected\n");
681 return;
684 term_printf("Mouse devices available:\n");
685 cursor = qemu_put_mouse_event_head;
686 while (cursor != NULL) {
687 term_printf("%c Mouse #%d: %s\n",
688 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
689 index, cursor->qemu_put_mouse_event_name);
690 index++;
691 cursor = cursor->next;
695 void do_mouse_set(int index)
697 QEMUPutMouseEntry *cursor;
698 int i = 0;
700 if (!qemu_put_mouse_event_head) {
701 term_printf("No mouse devices connected\n");
702 return;
705 cursor = qemu_put_mouse_event_head;
706 while (cursor != NULL && index != i) {
707 i++;
708 cursor = cursor->next;
711 if (cursor != NULL)
712 qemu_put_mouse_event_current = cursor;
713 else
714 term_printf("Mouse at given index not found\n");
717 /* compute with 96 bit intermediate result: (a*b)/c */
718 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
720 union {
721 uint64_t ll;
722 struct {
723 #ifdef WORDS_BIGENDIAN
724 uint32_t high, low;
725 #else
726 uint32_t low, high;
727 #endif
728 } l;
729 } u, res;
730 uint64_t rl, rh;
732 u.ll = a;
733 rl = (uint64_t)u.l.low * (uint64_t)b;
734 rh = (uint64_t)u.l.high * (uint64_t)b;
735 rh += (rl >> 32);
736 res.l.high = rh / c;
737 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
738 return res.ll;
741 /***********************************************************/
742 /* real time host monotonic timer */
744 #define QEMU_TIMER_BASE 1000000000LL
746 #ifdef WIN32
748 static int64_t clock_freq;
750 static void init_get_clock(void)
752 LARGE_INTEGER freq;
753 int ret;
754 ret = QueryPerformanceFrequency(&freq);
755 if (ret == 0) {
756 fprintf(stderr, "Could not calibrate ticks\n");
757 exit(1);
759 clock_freq = freq.QuadPart;
762 static int64_t get_clock(void)
764 LARGE_INTEGER ti;
765 QueryPerformanceCounter(&ti);
766 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
769 #else
771 static int use_rt_clock;
773 static void init_get_clock(void)
775 use_rt_clock = 0;
776 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
778 struct timespec ts;
779 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
780 use_rt_clock = 1;
783 #endif
786 static int64_t get_clock(void)
788 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
789 if (use_rt_clock) {
790 struct timespec ts;
791 clock_gettime(CLOCK_MONOTONIC, &ts);
792 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
793 } else
794 #endif
796 /* XXX: using gettimeofday leads to problems if the date
797 changes, so it should be avoided. */
798 struct timeval tv;
799 gettimeofday(&tv, NULL);
800 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
803 #endif
805 /* Return the virtual CPU time, based on the instruction counter. */
806 static int64_t cpu_get_icount(void)
808 int64_t icount;
809 CPUState *env = cpu_single_env;;
810 icount = qemu_icount;
811 if (env) {
812 if (!can_do_io(env))
813 fprintf(stderr, "Bad clock read\n");
814 icount -= (env->icount_decr.u16.low + env->icount_extra);
816 return qemu_icount_bias + (icount << icount_time_shift);
819 /***********************************************************/
820 /* guest cycle counter */
822 static int64_t cpu_ticks_prev;
823 static int64_t cpu_ticks_offset;
824 static int64_t cpu_clock_offset;
825 static int cpu_ticks_enabled;
827 /* return the host CPU cycle counter and handle stop/restart */
828 int64_t cpu_get_ticks(void)
830 if (use_icount) {
831 return cpu_get_icount();
833 if (!cpu_ticks_enabled) {
834 return cpu_ticks_offset;
835 } else {
836 int64_t ticks;
837 ticks = cpu_get_real_ticks();
838 if (cpu_ticks_prev > ticks) {
839 /* Note: non increasing ticks may happen if the host uses
840 software suspend */
841 cpu_ticks_offset += cpu_ticks_prev - ticks;
843 cpu_ticks_prev = ticks;
844 return ticks + cpu_ticks_offset;
848 /* return the host CPU monotonic timer and handle stop/restart */
849 static int64_t cpu_get_clock(void)
851 int64_t ti;
852 if (!cpu_ticks_enabled) {
853 return cpu_clock_offset;
854 } else {
855 ti = get_clock();
856 return ti + cpu_clock_offset;
860 /* enable cpu_get_ticks() */
861 void cpu_enable_ticks(void)
863 if (!cpu_ticks_enabled) {
864 cpu_ticks_offset -= cpu_get_real_ticks();
865 cpu_clock_offset -= get_clock();
866 cpu_ticks_enabled = 1;
870 /* disable cpu_get_ticks() : the clock is stopped. You must not call
871 cpu_get_ticks() after that. */
872 void cpu_disable_ticks(void)
874 if (cpu_ticks_enabled) {
875 cpu_ticks_offset = cpu_get_ticks();
876 cpu_clock_offset = cpu_get_clock();
877 cpu_ticks_enabled = 0;
881 /***********************************************************/
882 /* timers */
884 #define QEMU_TIMER_REALTIME 0
885 #define QEMU_TIMER_VIRTUAL 1
887 struct QEMUClock {
888 int type;
889 /* XXX: add frequency */
892 struct QEMUTimer {
893 QEMUClock *clock;
894 int64_t expire_time;
895 QEMUTimerCB *cb;
896 void *opaque;
897 struct QEMUTimer *next;
900 struct qemu_alarm_timer {
901 char const *name;
902 unsigned int flags;
904 int (*start)(struct qemu_alarm_timer *t);
905 void (*stop)(struct qemu_alarm_timer *t);
906 void (*rearm)(struct qemu_alarm_timer *t);
907 void *priv;
910 #define ALARM_FLAG_DYNTICKS 0x1
911 #define ALARM_FLAG_EXPIRED 0x2
913 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
915 return t->flags & ALARM_FLAG_DYNTICKS;
918 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
920 if (!alarm_has_dynticks(t))
921 return;
923 t->rearm(t);
926 /* TODO: MIN_TIMER_REARM_US should be optimized */
927 #define MIN_TIMER_REARM_US 250
929 static struct qemu_alarm_timer *alarm_timer;
930 #ifndef _WIN32
931 static int alarm_timer_rfd, alarm_timer_wfd;
932 #endif
934 #ifdef _WIN32
936 struct qemu_alarm_win32 {
937 MMRESULT timerId;
938 HANDLE host_alarm;
939 unsigned int period;
940 } alarm_win32_data = {0, NULL, -1};
942 static int win32_start_timer(struct qemu_alarm_timer *t);
943 static void win32_stop_timer(struct qemu_alarm_timer *t);
944 static void win32_rearm_timer(struct qemu_alarm_timer *t);
946 #else
948 static int unix_start_timer(struct qemu_alarm_timer *t);
949 static void unix_stop_timer(struct qemu_alarm_timer *t);
951 #ifdef __linux__
953 static int dynticks_start_timer(struct qemu_alarm_timer *t);
954 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
955 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
957 static int hpet_start_timer(struct qemu_alarm_timer *t);
958 static void hpet_stop_timer(struct qemu_alarm_timer *t);
960 static int rtc_start_timer(struct qemu_alarm_timer *t);
961 static void rtc_stop_timer(struct qemu_alarm_timer *t);
963 #endif /* __linux__ */
965 #endif /* _WIN32 */
967 /* Correlation between real and virtual time is always going to be
968 fairly approximate, so ignore small variation.
969 When the guest is idle real and virtual time will be aligned in
970 the IO wait loop. */
971 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
973 static void icount_adjust(void)
975 int64_t cur_time;
976 int64_t cur_icount;
977 int64_t delta;
978 static int64_t last_delta;
979 /* If the VM is not running, then do nothing. */
980 if (!vm_running)
981 return;
983 cur_time = cpu_get_clock();
984 cur_icount = qemu_get_clock(vm_clock);
985 delta = cur_icount - cur_time;
986 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
987 if (delta > 0
988 && last_delta + ICOUNT_WOBBLE < delta * 2
989 && icount_time_shift > 0) {
990 /* The guest is getting too far ahead. Slow time down. */
991 icount_time_shift--;
993 if (delta < 0
994 && last_delta - ICOUNT_WOBBLE > delta * 2
995 && icount_time_shift < MAX_ICOUNT_SHIFT) {
996 /* The guest is getting too far behind. Speed time up. */
997 icount_time_shift++;
999 last_delta = delta;
1000 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1003 static void icount_adjust_rt(void * opaque)
1005 qemu_mod_timer(icount_rt_timer,
1006 qemu_get_clock(rt_clock) + 1000);
1007 icount_adjust();
1010 static void icount_adjust_vm(void * opaque)
1012 qemu_mod_timer(icount_vm_timer,
1013 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1014 icount_adjust();
1017 static void init_icount_adjust(void)
1019 /* Have both realtime and virtual time triggers for speed adjustment.
1020 The realtime trigger catches emulated time passing too slowly,
1021 the virtual time trigger catches emulated time passing too fast.
1022 Realtime triggers occur even when idle, so use them less frequently
1023 than VM triggers. */
1024 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1025 qemu_mod_timer(icount_rt_timer,
1026 qemu_get_clock(rt_clock) + 1000);
1027 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1028 qemu_mod_timer(icount_vm_timer,
1029 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1032 static struct qemu_alarm_timer alarm_timers[] = {
1033 #ifndef _WIN32
1034 #ifdef __linux__
1035 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1036 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1037 /* HPET - if available - is preferred */
1038 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1039 /* ...otherwise try RTC */
1040 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1041 #endif
1042 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1043 #else
1044 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1045 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1046 {"win32", 0, win32_start_timer,
1047 win32_stop_timer, NULL, &alarm_win32_data},
1048 #endif
1049 {NULL, }
1052 static void show_available_alarms(void)
1054 int i;
1056 printf("Available alarm timers, in order of precedence:\n");
1057 for (i = 0; alarm_timers[i].name; i++)
1058 printf("%s\n", alarm_timers[i].name);
1061 static void configure_alarms(char const *opt)
1063 int i;
1064 int cur = 0;
1065 int count = ARRAY_SIZE(alarm_timers) - 1;
1066 char *arg;
1067 char *name;
1068 struct qemu_alarm_timer tmp;
1070 if (!strcmp(opt, "?")) {
1071 show_available_alarms();
1072 exit(0);
1075 arg = strdup(opt);
1077 /* Reorder the array */
1078 name = strtok(arg, ",");
1079 while (name) {
1080 for (i = 0; i < count && alarm_timers[i].name; i++) {
1081 if (!strcmp(alarm_timers[i].name, name))
1082 break;
1085 if (i == count) {
1086 fprintf(stderr, "Unknown clock %s\n", name);
1087 goto next;
1090 if (i < cur)
1091 /* Ignore */
1092 goto next;
1094 /* Swap */
1095 tmp = alarm_timers[i];
1096 alarm_timers[i] = alarm_timers[cur];
1097 alarm_timers[cur] = tmp;
1099 cur++;
1100 next:
1101 name = strtok(NULL, ",");
1104 free(arg);
1106 if (cur) {
1107 /* Disable remaining timers */
1108 for (i = cur; i < count; i++)
1109 alarm_timers[i].name = NULL;
1110 } else {
1111 show_available_alarms();
1112 exit(1);
1116 QEMUClock *rt_clock;
1117 QEMUClock *vm_clock;
1119 static QEMUTimer *active_timers[2];
1121 static QEMUClock *qemu_new_clock(int type)
1123 QEMUClock *clock;
1124 clock = qemu_mallocz(sizeof(QEMUClock));
1125 clock->type = type;
1126 return clock;
1129 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1131 QEMUTimer *ts;
1133 ts = qemu_mallocz(sizeof(QEMUTimer));
1134 ts->clock = clock;
1135 ts->cb = cb;
1136 ts->opaque = opaque;
1137 return ts;
1140 void qemu_free_timer(QEMUTimer *ts)
1142 qemu_free(ts);
1145 /* stop a timer, but do not dealloc it */
1146 void qemu_del_timer(QEMUTimer *ts)
1148 QEMUTimer **pt, *t;
1150 /* NOTE: this code must be signal safe because
1151 qemu_timer_expired() can be called from a signal. */
1152 pt = &active_timers[ts->clock->type];
1153 for(;;) {
1154 t = *pt;
1155 if (!t)
1156 break;
1157 if (t == ts) {
1158 *pt = t->next;
1159 break;
1161 pt = &t->next;
1165 /* modify the current timer so that it will be fired when current_time
1166 >= expire_time. The corresponding callback will be called. */
1167 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1169 QEMUTimer **pt, *t;
1171 qemu_del_timer(ts);
1173 /* add the timer in the sorted list */
1174 /* NOTE: this code must be signal safe because
1175 qemu_timer_expired() can be called from a signal. */
1176 pt = &active_timers[ts->clock->type];
1177 for(;;) {
1178 t = *pt;
1179 if (!t)
1180 break;
1181 if (t->expire_time > expire_time)
1182 break;
1183 pt = &t->next;
1185 ts->expire_time = expire_time;
1186 ts->next = *pt;
1187 *pt = ts;
1189 /* Rearm if necessary */
1190 if (pt == &active_timers[ts->clock->type]) {
1191 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1192 qemu_rearm_alarm_timer(alarm_timer);
1194 /* Interrupt execution to force deadline recalculation. */
1195 if (use_icount && cpu_single_env) {
1196 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1201 int qemu_timer_pending(QEMUTimer *ts)
1203 QEMUTimer *t;
1204 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1205 if (t == ts)
1206 return 1;
1208 return 0;
1211 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1213 if (!timer_head)
1214 return 0;
1215 return (timer_head->expire_time <= current_time);
1218 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1220 QEMUTimer *ts;
1222 for(;;) {
1223 ts = *ptimer_head;
1224 if (!ts || ts->expire_time > current_time)
1225 break;
1226 /* remove timer from the list before calling the callback */
1227 *ptimer_head = ts->next;
1228 ts->next = NULL;
1230 /* run the callback (the timer list can be modified) */
1231 ts->cb(ts->opaque);
1235 int64_t qemu_get_clock(QEMUClock *clock)
1237 switch(clock->type) {
1238 case QEMU_TIMER_REALTIME:
1239 return get_clock() / 1000000;
1240 default:
1241 case QEMU_TIMER_VIRTUAL:
1242 if (use_icount) {
1243 return cpu_get_icount();
1244 } else {
1245 return cpu_get_clock();
1250 static void init_timers(void)
1252 init_get_clock();
1253 ticks_per_sec = QEMU_TIMER_BASE;
1254 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1255 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1258 /* save a timer */
1259 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1261 uint64_t expire_time;
1263 if (qemu_timer_pending(ts)) {
1264 expire_time = ts->expire_time;
1265 } else {
1266 expire_time = -1;
1268 qemu_put_be64(f, expire_time);
1271 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1273 uint64_t expire_time;
1275 expire_time = qemu_get_be64(f);
1276 if (expire_time != -1) {
1277 qemu_mod_timer(ts, expire_time);
1278 } else {
1279 qemu_del_timer(ts);
1283 static void timer_save(QEMUFile *f, void *opaque)
1285 if (cpu_ticks_enabled) {
1286 hw_error("cannot save state if virtual timers are running");
1288 qemu_put_be64(f, cpu_ticks_offset);
1289 qemu_put_be64(f, ticks_per_sec);
1290 qemu_put_be64(f, cpu_clock_offset);
1293 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1295 if (version_id != 1 && version_id != 2)
1296 return -EINVAL;
1297 if (cpu_ticks_enabled) {
1298 return -EINVAL;
1300 cpu_ticks_offset=qemu_get_be64(f);
1301 ticks_per_sec=qemu_get_be64(f);
1302 if (version_id == 2) {
1303 cpu_clock_offset=qemu_get_be64(f);
1305 return 0;
1308 #ifdef _WIN32
1309 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1310 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1311 #else
1312 static void host_alarm_handler(int host_signum)
1313 #endif
1315 #if 0
1316 #define DISP_FREQ 1000
1318 static int64_t delta_min = INT64_MAX;
1319 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1320 static int count;
1321 ti = qemu_get_clock(vm_clock);
1322 if (last_clock != 0) {
1323 delta = ti - last_clock;
1324 if (delta < delta_min)
1325 delta_min = delta;
1326 if (delta > delta_max)
1327 delta_max = delta;
1328 delta_cum += delta;
1329 if (++count == DISP_FREQ) {
1330 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1331 muldiv64(delta_min, 1000000, ticks_per_sec),
1332 muldiv64(delta_max, 1000000, ticks_per_sec),
1333 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1334 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1335 count = 0;
1336 delta_min = INT64_MAX;
1337 delta_max = 0;
1338 delta_cum = 0;
1341 last_clock = ti;
1343 #endif
1344 if (1 ||
1345 alarm_has_dynticks(alarm_timer) ||
1346 (!use_icount &&
1347 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1348 qemu_get_clock(vm_clock))) ||
1349 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1350 qemu_get_clock(rt_clock))) {
1351 CPUState *env = next_cpu;
1353 #ifdef _WIN32
1354 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1355 SetEvent(data->host_alarm);
1356 #else
1357 static const char byte = 0;
1358 write(alarm_timer_wfd, &byte, sizeof(byte));
1359 #endif
1360 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1362 if (env) {
1363 /* stop the currently executing cpu because a timer occured */
1364 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1365 #ifdef USE_KQEMU
1366 if (env->kqemu_enabled) {
1367 kqemu_cpu_interrupt(env);
1369 #endif
1371 event_pending = 1;
1375 static int64_t qemu_next_deadline(void)
1377 int64_t delta;
1379 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1380 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1381 qemu_get_clock(vm_clock);
1382 } else {
1383 /* To avoid problems with overflow limit this to 2^32. */
1384 delta = INT32_MAX;
1387 if (delta < 0)
1388 delta = 0;
1390 return delta;
1393 #if defined(__linux__) || defined(_WIN32)
1394 static uint64_t qemu_next_deadline_dyntick(void)
1396 int64_t delta;
1397 int64_t rtdelta;
1399 if (use_icount)
1400 delta = INT32_MAX;
1401 else
1402 delta = (qemu_next_deadline() + 999) / 1000;
1404 if (active_timers[QEMU_TIMER_REALTIME]) {
1405 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1406 qemu_get_clock(rt_clock))*1000;
1407 if (rtdelta < delta)
1408 delta = rtdelta;
1411 if (delta < MIN_TIMER_REARM_US)
1412 delta = MIN_TIMER_REARM_US;
1414 return delta;
1416 #endif
1418 #ifndef _WIN32
1420 /* Sets a specific flag */
1421 static int fcntl_setfl(int fd, int flag)
1423 int flags;
1425 flags = fcntl(fd, F_GETFL);
1426 if (flags == -1)
1427 return -errno;
1429 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1430 return -errno;
1432 return 0;
1435 #if defined(__linux__)
1437 #define RTC_FREQ 1024
1439 static void enable_sigio_timer(int fd)
1441 struct sigaction act;
1443 /* timer signal */
1444 sigfillset(&act.sa_mask);
1445 act.sa_flags = 0;
1446 act.sa_handler = host_alarm_handler;
1448 sigaction(SIGIO, &act, NULL);
1449 fcntl_setfl(fd, O_ASYNC);
1450 fcntl(fd, F_SETOWN, getpid());
1453 static int hpet_start_timer(struct qemu_alarm_timer *t)
1455 struct hpet_info info;
1456 int r, fd;
1458 fd = open("/dev/hpet", O_RDONLY);
1459 if (fd < 0)
1460 return -1;
1462 /* Set frequency */
1463 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1464 if (r < 0) {
1465 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1466 "error, but for better emulation accuracy type:\n"
1467 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1468 goto fail;
1471 /* Check capabilities */
1472 r = ioctl(fd, HPET_INFO, &info);
1473 if (r < 0)
1474 goto fail;
1476 /* Enable periodic mode */
1477 r = ioctl(fd, HPET_EPI, 0);
1478 if (info.hi_flags && (r < 0))
1479 goto fail;
1481 /* Enable interrupt */
1482 r = ioctl(fd, HPET_IE_ON, 0);
1483 if (r < 0)
1484 goto fail;
1486 enable_sigio_timer(fd);
1487 t->priv = (void *)(long)fd;
1489 return 0;
1490 fail:
1491 close(fd);
1492 return -1;
1495 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1497 int fd = (long)t->priv;
1499 close(fd);
1502 static int rtc_start_timer(struct qemu_alarm_timer *t)
1504 int rtc_fd;
1505 unsigned long current_rtc_freq = 0;
1507 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1508 if (rtc_fd < 0)
1509 return -1;
1510 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1511 if (current_rtc_freq != RTC_FREQ &&
1512 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1513 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1514 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1515 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1516 goto fail;
1518 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1519 fail:
1520 close(rtc_fd);
1521 return -1;
1524 enable_sigio_timer(rtc_fd);
1526 t->priv = (void *)(long)rtc_fd;
1528 return 0;
1531 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1533 int rtc_fd = (long)t->priv;
1535 close(rtc_fd);
1538 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1540 struct sigevent ev;
1541 timer_t host_timer;
1542 struct sigaction act;
1544 sigfillset(&act.sa_mask);
1545 act.sa_flags = 0;
1546 act.sa_handler = host_alarm_handler;
1548 sigaction(SIGALRM, &act, NULL);
1550 ev.sigev_value.sival_int = 0;
1551 ev.sigev_notify = SIGEV_SIGNAL;
1552 ev.sigev_signo = SIGALRM;
1554 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1555 perror("timer_create");
1557 /* disable dynticks */
1558 fprintf(stderr, "Dynamic Ticks disabled\n");
1560 return -1;
1563 t->priv = (void *)(long)host_timer;
1565 return 0;
1568 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1570 timer_t host_timer = (timer_t)(long)t->priv;
1572 timer_delete(host_timer);
1575 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1577 timer_t host_timer = (timer_t)(long)t->priv;
1578 struct itimerspec timeout;
1579 int64_t nearest_delta_us = INT64_MAX;
1580 int64_t current_us;
1582 if (!active_timers[QEMU_TIMER_REALTIME] &&
1583 !active_timers[QEMU_TIMER_VIRTUAL])
1584 return;
1586 nearest_delta_us = qemu_next_deadline_dyntick();
1588 /* check whether a timer is already running */
1589 if (timer_gettime(host_timer, &timeout)) {
1590 perror("gettime");
1591 fprintf(stderr, "Internal timer error: aborting\n");
1592 exit(1);
1594 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1595 if (current_us && current_us <= nearest_delta_us)
1596 return;
1598 timeout.it_interval.tv_sec = 0;
1599 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1600 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1601 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1602 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1603 perror("settime");
1604 fprintf(stderr, "Internal timer error: aborting\n");
1605 exit(1);
1609 #endif /* defined(__linux__) */
1611 static int unix_start_timer(struct qemu_alarm_timer *t)
1613 struct sigaction act;
1614 struct itimerval itv;
1615 int err;
1617 /* timer signal */
1618 sigfillset(&act.sa_mask);
1619 act.sa_flags = 0;
1620 act.sa_handler = host_alarm_handler;
1622 sigaction(SIGALRM, &act, NULL);
1624 itv.it_interval.tv_sec = 0;
1625 /* for i386 kernel 2.6 to get 1 ms */
1626 itv.it_interval.tv_usec = 999;
1627 itv.it_value.tv_sec = 0;
1628 itv.it_value.tv_usec = 10 * 1000;
1630 err = setitimer(ITIMER_REAL, &itv, NULL);
1631 if (err)
1632 return -1;
1634 return 0;
1637 static void unix_stop_timer(struct qemu_alarm_timer *t)
1639 struct itimerval itv;
1641 memset(&itv, 0, sizeof(itv));
1642 setitimer(ITIMER_REAL, &itv, NULL);
1645 #endif /* !defined(_WIN32) */
1647 static void try_to_rearm_timer(void *opaque)
1649 struct qemu_alarm_timer *t = opaque;
1650 #ifndef _WIN32
1651 ssize_t len;
1653 /* Drain the notify pipe */
1654 do {
1655 char buffer[512];
1656 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1657 } while ((len == -1 && errno == EINTR) || len > 0);
1658 #endif
1660 if (t->flags & ALARM_FLAG_EXPIRED) {
1661 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1662 qemu_rearm_alarm_timer(alarm_timer);
1666 #ifdef _WIN32
1668 static int win32_start_timer(struct qemu_alarm_timer *t)
1670 TIMECAPS tc;
1671 struct qemu_alarm_win32 *data = t->priv;
1672 UINT flags;
1674 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1675 if (!data->host_alarm) {
1676 perror("Failed CreateEvent");
1677 return -1;
1680 memset(&tc, 0, sizeof(tc));
1681 timeGetDevCaps(&tc, sizeof(tc));
1683 if (data->period < tc.wPeriodMin)
1684 data->period = tc.wPeriodMin;
1686 timeBeginPeriod(data->period);
1688 flags = TIME_CALLBACK_FUNCTION;
1689 if (alarm_has_dynticks(t))
1690 flags |= TIME_ONESHOT;
1691 else
1692 flags |= TIME_PERIODIC;
1694 data->timerId = timeSetEvent(1, // interval (ms)
1695 data->period, // resolution
1696 host_alarm_handler, // function
1697 (DWORD)t, // parameter
1698 flags);
1700 if (!data->timerId) {
1701 perror("Failed to initialize win32 alarm timer");
1703 timeEndPeriod(data->period);
1704 CloseHandle(data->host_alarm);
1705 return -1;
1708 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1710 return 0;
1713 static void win32_stop_timer(struct qemu_alarm_timer *t)
1715 struct qemu_alarm_win32 *data = t->priv;
1717 timeKillEvent(data->timerId);
1718 timeEndPeriod(data->period);
1720 CloseHandle(data->host_alarm);
1723 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1725 struct qemu_alarm_win32 *data = t->priv;
1726 uint64_t nearest_delta_us;
1728 if (!active_timers[QEMU_TIMER_REALTIME] &&
1729 !active_timers[QEMU_TIMER_VIRTUAL])
1730 return;
1732 nearest_delta_us = qemu_next_deadline_dyntick();
1733 nearest_delta_us /= 1000;
1735 timeKillEvent(data->timerId);
1737 data->timerId = timeSetEvent(1,
1738 data->period,
1739 host_alarm_handler,
1740 (DWORD)t,
1741 TIME_ONESHOT | TIME_PERIODIC);
1743 if (!data->timerId) {
1744 perror("Failed to re-arm win32 alarm timer");
1746 timeEndPeriod(data->period);
1747 CloseHandle(data->host_alarm);
1748 exit(1);
1752 #endif /* _WIN32 */
1754 static int init_timer_alarm(void)
1756 struct qemu_alarm_timer *t = NULL;
1757 int i, err = -1;
1759 #ifndef _WIN32
1760 int fds[2];
1762 err = pipe(fds);
1763 if (err == -1)
1764 return -errno;
1766 err = fcntl_setfl(fds[0], O_NONBLOCK);
1767 if (err < 0)
1768 goto fail;
1770 err = fcntl_setfl(fds[1], O_NONBLOCK);
1771 if (err < 0)
1772 goto fail;
1774 alarm_timer_rfd = fds[0];
1775 alarm_timer_wfd = fds[1];
1776 #endif
1778 for (i = 0; alarm_timers[i].name; i++) {
1779 t = &alarm_timers[i];
1781 err = t->start(t);
1782 if (!err)
1783 break;
1786 if (err) {
1787 err = -ENOENT;
1788 goto fail;
1791 #ifndef _WIN32
1792 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1793 try_to_rearm_timer, NULL, t);
1794 #endif
1796 alarm_timer = t;
1798 return 0;
1800 fail:
1801 #ifndef _WIN32
1802 close(fds[0]);
1803 close(fds[1]);
1804 #endif
1805 return err;
1808 static void quit_timers(void)
1810 alarm_timer->stop(alarm_timer);
1811 alarm_timer = NULL;
1814 /***********************************************************/
1815 /* host time/date access */
1816 void qemu_get_timedate(struct tm *tm, int offset)
1818 time_t ti;
1819 struct tm *ret;
1821 time(&ti);
1822 ti += offset;
1823 if (rtc_date_offset == -1) {
1824 if (rtc_utc)
1825 ret = gmtime(&ti);
1826 else
1827 ret = localtime(&ti);
1828 } else {
1829 ti -= rtc_date_offset;
1830 ret = gmtime(&ti);
1833 memcpy(tm, ret, sizeof(struct tm));
1836 int qemu_timedate_diff(struct tm *tm)
1838 time_t seconds;
1840 if (rtc_date_offset == -1)
1841 if (rtc_utc)
1842 seconds = mktimegm(tm);
1843 else
1844 seconds = mktime(tm);
1845 else
1846 seconds = mktimegm(tm) + rtc_date_offset;
1848 return seconds - time(NULL);
1851 #ifdef _WIN32
1852 static void socket_cleanup(void)
1854 WSACleanup();
1857 static int socket_init(void)
1859 WSADATA Data;
1860 int ret, err;
1862 ret = WSAStartup(MAKEWORD(2,2), &Data);
1863 if (ret != 0) {
1864 err = WSAGetLastError();
1865 fprintf(stderr, "WSAStartup: %d\n", err);
1866 return -1;
1868 atexit(socket_cleanup);
1869 return 0;
1871 #endif
1873 const char *get_opt_name(char *buf, int buf_size, const char *p)
1875 char *q;
1877 q = buf;
1878 while (*p != '\0' && *p != '=') {
1879 if (q && (q - buf) < buf_size - 1)
1880 *q++ = *p;
1881 p++;
1883 if (q)
1884 *q = '\0';
1886 return p;
1889 const char *get_opt_value(char *buf, int buf_size, const char *p)
1891 char *q;
1893 q = buf;
1894 while (*p != '\0') {
1895 if (*p == ',') {
1896 if (*(p + 1) != ',')
1897 break;
1898 p++;
1900 if (q && (q - buf) < buf_size - 1)
1901 *q++ = *p;
1902 p++;
1904 if (q)
1905 *q = '\0';
1907 return p;
1910 int get_param_value(char *buf, int buf_size,
1911 const char *tag, const char *str)
1913 const char *p;
1914 char option[128];
1916 p = str;
1917 for(;;) {
1918 p = get_opt_name(option, sizeof(option), p);
1919 if (*p != '=')
1920 break;
1921 p++;
1922 if (!strcmp(tag, option)) {
1923 (void)get_opt_value(buf, buf_size, p);
1924 return strlen(buf);
1925 } else {
1926 p = get_opt_value(NULL, 0, p);
1928 if (*p != ',')
1929 break;
1930 p++;
1932 return 0;
1935 int check_params(char *buf, int buf_size,
1936 const char * const *params, const char *str)
1938 const char *p;
1939 int i;
1941 p = str;
1942 for(;;) {
1943 p = get_opt_name(buf, buf_size, p);
1944 if (*p != '=')
1945 return -1;
1946 p++;
1947 for(i = 0; params[i] != NULL; i++)
1948 if (!strcmp(params[i], buf))
1949 break;
1950 if (params[i] == NULL)
1951 return -1;
1952 p = get_opt_value(NULL, 0, p);
1953 if (*p != ',')
1954 break;
1955 p++;
1957 return 0;
1960 /***********************************************************/
1961 /* Bluetooth support */
1962 static int nb_hcis;
1963 static int cur_hci;
1964 static struct HCIInfo *hci_table[MAX_NICS];
1966 static struct bt_vlan_s {
1967 struct bt_scatternet_s net;
1968 int id;
1969 struct bt_vlan_s *next;
1970 } *first_bt_vlan;
1972 /* find or alloc a new bluetooth "VLAN" */
1973 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1975 struct bt_vlan_s **pvlan, *vlan;
1976 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1977 if (vlan->id == id)
1978 return &vlan->net;
1980 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1981 vlan->id = id;
1982 pvlan = &first_bt_vlan;
1983 while (*pvlan != NULL)
1984 pvlan = &(*pvlan)->next;
1985 *pvlan = vlan;
1986 return &vlan->net;
1989 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1993 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1995 return -ENOTSUP;
1998 static struct HCIInfo null_hci = {
1999 .cmd_send = null_hci_send,
2000 .sco_send = null_hci_send,
2001 .acl_send = null_hci_send,
2002 .bdaddr_set = null_hci_addr_set,
2005 struct HCIInfo *qemu_next_hci(void)
2007 if (cur_hci == nb_hcis)
2008 return &null_hci;
2010 return hci_table[cur_hci++];
2013 static struct HCIInfo *hci_init(const char *str)
2015 char *endp;
2016 struct bt_scatternet_s *vlan = 0;
2018 if (!strcmp(str, "null"))
2019 /* null */
2020 return &null_hci;
2021 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2022 /* host[:hciN] */
2023 return bt_host_hci(str[4] ? str + 5 : "hci0");
2024 else if (!strncmp(str, "hci", 3)) {
2025 /* hci[,vlan=n] */
2026 if (str[3]) {
2027 if (!strncmp(str + 3, ",vlan=", 6)) {
2028 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2029 if (*endp)
2030 vlan = 0;
2032 } else
2033 vlan = qemu_find_bt_vlan(0);
2034 if (vlan)
2035 return bt_new_hci(vlan);
2038 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2040 return 0;
2043 static int bt_hci_parse(const char *str)
2045 struct HCIInfo *hci;
2046 bdaddr_t bdaddr;
2048 if (nb_hcis >= MAX_NICS) {
2049 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2050 return -1;
2053 hci = hci_init(str);
2054 if (!hci)
2055 return -1;
2057 bdaddr.b[0] = 0x52;
2058 bdaddr.b[1] = 0x54;
2059 bdaddr.b[2] = 0x00;
2060 bdaddr.b[3] = 0x12;
2061 bdaddr.b[4] = 0x34;
2062 bdaddr.b[5] = 0x56 + nb_hcis;
2063 hci->bdaddr_set(hci, bdaddr.b);
2065 hci_table[nb_hcis++] = hci;
2067 return 0;
2070 static void bt_vhci_add(int vlan_id)
2072 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2074 if (!vlan->slave)
2075 fprintf(stderr, "qemu: warning: adding a VHCI to "
2076 "an empty scatternet %i\n", vlan_id);
2078 bt_vhci_init(bt_new_hci(vlan));
2081 static struct bt_device_s *bt_device_add(const char *opt)
2083 struct bt_scatternet_s *vlan;
2084 int vlan_id = 0;
2085 char *endp = strstr(opt, ",vlan=");
2086 int len = (endp ? endp - opt : strlen(opt)) + 1;
2087 char devname[10];
2089 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2091 if (endp) {
2092 vlan_id = strtol(endp + 6, &endp, 0);
2093 if (*endp) {
2094 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2095 return 0;
2099 vlan = qemu_find_bt_vlan(vlan_id);
2101 if (!vlan->slave)
2102 fprintf(stderr, "qemu: warning: adding a slave device to "
2103 "an empty scatternet %i\n", vlan_id);
2105 if (!strcmp(devname, "keyboard"))
2106 return bt_keyboard_init(vlan);
2108 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2109 return 0;
2112 static int bt_parse(const char *opt)
2114 const char *endp, *p;
2115 int vlan;
2117 if (strstart(opt, "hci", &endp)) {
2118 if (!*endp || *endp == ',') {
2119 if (*endp)
2120 if (!strstart(endp, ",vlan=", 0))
2121 opt = endp + 1;
2123 return bt_hci_parse(opt);
2125 } else if (strstart(opt, "vhci", &endp)) {
2126 if (!*endp || *endp == ',') {
2127 if (*endp) {
2128 if (strstart(endp, ",vlan=", &p)) {
2129 vlan = strtol(p, (char **) &endp, 0);
2130 if (*endp) {
2131 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2132 return 1;
2134 } else {
2135 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2136 return 1;
2138 } else
2139 vlan = 0;
2141 bt_vhci_add(vlan);
2142 return 0;
2144 } else if (strstart(opt, "device:", &endp))
2145 return !bt_device_add(endp);
2147 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2148 return 1;
2151 /***********************************************************/
2152 /* QEMU Block devices */
2154 #define HD_ALIAS "index=%d,media=disk"
2155 #ifdef TARGET_PPC
2156 #define CDROM_ALIAS "index=1,media=cdrom"
2157 #else
2158 #define CDROM_ALIAS "index=2,media=cdrom"
2159 #endif
2160 #define FD_ALIAS "index=%d,if=floppy"
2161 #define PFLASH_ALIAS "if=pflash"
2162 #define MTD_ALIAS "if=mtd"
2163 #define SD_ALIAS "index=0,if=sd"
2165 static int drive_opt_get_free_idx(void)
2167 int index;
2169 for (index = 0; index < MAX_DRIVES; index++)
2170 if (!drives_opt[index].used) {
2171 drives_opt[index].used = 1;
2172 return index;
2175 return -1;
2178 static int drive_get_free_idx(void)
2180 int index;
2182 for (index = 0; index < MAX_DRIVES; index++)
2183 if (!drives_table[index].used) {
2184 drives_table[index].used = 1;
2185 return index;
2188 return -1;
2191 int drive_add(const char *file, const char *fmt, ...)
2193 va_list ap;
2194 int index = drive_opt_get_free_idx();
2196 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2197 fprintf(stderr, "qemu: too many drives\n");
2198 return -1;
2201 drives_opt[index].file = file;
2202 va_start(ap, fmt);
2203 vsnprintf(drives_opt[index].opt,
2204 sizeof(drives_opt[0].opt), fmt, ap);
2205 va_end(ap);
2207 nb_drives_opt++;
2208 return index;
2211 void drive_remove(int index)
2213 drives_opt[index].used = 0;
2214 nb_drives_opt--;
2217 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2219 int index;
2221 /* seek interface, bus and unit */
2223 for (index = 0; index < MAX_DRIVES; index++)
2224 if (drives_table[index].type == type &&
2225 drives_table[index].bus == bus &&
2226 drives_table[index].unit == unit &&
2227 drives_table[index].used)
2228 return index;
2230 return -1;
2233 int drive_get_max_bus(BlockInterfaceType type)
2235 int max_bus;
2236 int index;
2238 max_bus = -1;
2239 for (index = 0; index < nb_drives; index++) {
2240 if(drives_table[index].type == type &&
2241 drives_table[index].bus > max_bus)
2242 max_bus = drives_table[index].bus;
2244 return max_bus;
2247 const char *drive_get_serial(BlockDriverState *bdrv)
2249 int index;
2251 for (index = 0; index < nb_drives; index++)
2252 if (drives_table[index].bdrv == bdrv)
2253 return drives_table[index].serial;
2255 return "\0";
2258 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2260 int index;
2262 for (index = 0; index < nb_drives; index++)
2263 if (drives_table[index].bdrv == bdrv)
2264 return drives_table[index].onerror;
2266 return BLOCK_ERR_REPORT;
2269 static void bdrv_format_print(void *opaque, const char *name)
2271 fprintf(stderr, " %s", name);
2274 void drive_uninit(BlockDriverState *bdrv)
2276 int i;
2278 for (i = 0; i < MAX_DRIVES; i++)
2279 if (drives_table[i].bdrv == bdrv) {
2280 drives_table[i].bdrv = NULL;
2281 drives_table[i].used = 0;
2282 drive_remove(drives_table[i].drive_opt_idx);
2283 nb_drives--;
2284 break;
2288 int drive_init(struct drive_opt *arg, int snapshot,
2289 QEMUMachine *machine)
2291 char buf[128];
2292 char file[1024];
2293 char devname[128];
2294 char serial[21];
2295 const char *mediastr = "";
2296 BlockInterfaceType type;
2297 enum { MEDIA_DISK, MEDIA_CDROM } media;
2298 int bus_id, unit_id;
2299 int cyls, heads, secs, translation;
2300 BlockDriverState *bdrv;
2301 BlockDriver *drv = NULL;
2302 int max_devs;
2303 int index;
2304 int cache;
2305 int bdrv_flags, onerror;
2306 int drives_table_idx;
2307 char *str = arg->opt;
2308 static const char * const params[] = { "bus", "unit", "if", "index",
2309 "cyls", "heads", "secs", "trans",
2310 "media", "snapshot", "file",
2311 "cache", "format", "serial", "werror",
2312 "boot", NULL };
2314 if (check_params(buf, sizeof(buf), params, str) < 0) {
2315 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2316 buf, str);
2317 return -1;
2320 file[0] = 0;
2321 cyls = heads = secs = 0;
2322 bus_id = 0;
2323 unit_id = -1;
2324 translation = BIOS_ATA_TRANSLATION_AUTO;
2325 index = -1;
2326 cache = 3;
2328 if (machine->use_scsi) {
2329 type = IF_SCSI;
2330 max_devs = MAX_SCSI_DEVS;
2331 pstrcpy(devname, sizeof(devname), "scsi");
2332 } else {
2333 type = IF_IDE;
2334 max_devs = MAX_IDE_DEVS;
2335 pstrcpy(devname, sizeof(devname), "ide");
2337 media = MEDIA_DISK;
2339 /* extract parameters */
2341 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2342 bus_id = strtol(buf, NULL, 0);
2343 if (bus_id < 0) {
2344 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2345 return -1;
2349 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2350 unit_id = strtol(buf, NULL, 0);
2351 if (unit_id < 0) {
2352 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2353 return -1;
2357 if (get_param_value(buf, sizeof(buf), "if", str)) {
2358 pstrcpy(devname, sizeof(devname), buf);
2359 if (!strcmp(buf, "ide")) {
2360 type = IF_IDE;
2361 max_devs = MAX_IDE_DEVS;
2362 } else if (!strcmp(buf, "scsi")) {
2363 type = IF_SCSI;
2364 max_devs = MAX_SCSI_DEVS;
2365 } else if (!strcmp(buf, "floppy")) {
2366 type = IF_FLOPPY;
2367 max_devs = 0;
2368 } else if (!strcmp(buf, "pflash")) {
2369 type = IF_PFLASH;
2370 max_devs = 0;
2371 } else if (!strcmp(buf, "mtd")) {
2372 type = IF_MTD;
2373 max_devs = 0;
2374 } else if (!strcmp(buf, "sd")) {
2375 type = IF_SD;
2376 max_devs = 0;
2377 } else if (!strcmp(buf, "virtio")) {
2378 type = IF_VIRTIO;
2379 max_devs = 0;
2380 } else {
2381 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2382 return -1;
2386 if (get_param_value(buf, sizeof(buf), "index", str)) {
2387 index = strtol(buf, NULL, 0);
2388 if (index < 0) {
2389 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2390 return -1;
2394 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2395 cyls = strtol(buf, NULL, 0);
2398 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2399 heads = strtol(buf, NULL, 0);
2402 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2403 secs = strtol(buf, NULL, 0);
2406 if (cyls || heads || secs) {
2407 if (cyls < 1 || cyls > 16383) {
2408 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2409 return -1;
2411 if (heads < 1 || heads > 16) {
2412 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2413 return -1;
2415 if (secs < 1 || secs > 63) {
2416 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2417 return -1;
2421 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2422 if (!cyls) {
2423 fprintf(stderr,
2424 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2425 str);
2426 return -1;
2428 if (!strcmp(buf, "none"))
2429 translation = BIOS_ATA_TRANSLATION_NONE;
2430 else if (!strcmp(buf, "lba"))
2431 translation = BIOS_ATA_TRANSLATION_LBA;
2432 else if (!strcmp(buf, "auto"))
2433 translation = BIOS_ATA_TRANSLATION_AUTO;
2434 else {
2435 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2436 return -1;
2440 if (get_param_value(buf, sizeof(buf), "media", str)) {
2441 if (!strcmp(buf, "disk")) {
2442 media = MEDIA_DISK;
2443 } else if (!strcmp(buf, "cdrom")) {
2444 if (cyls || secs || heads) {
2445 fprintf(stderr,
2446 "qemu: '%s' invalid physical CHS format\n", str);
2447 return -1;
2449 media = MEDIA_CDROM;
2450 } else {
2451 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2452 return -1;
2456 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2457 if (!strcmp(buf, "on"))
2458 snapshot = 1;
2459 else if (!strcmp(buf, "off"))
2460 snapshot = 0;
2461 else {
2462 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2463 return -1;
2467 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2468 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2469 cache = 0;
2470 else if (!strcmp(buf, "writethrough"))
2471 cache = 1;
2472 else if (!strcmp(buf, "writeback"))
2473 cache = 2;
2474 else {
2475 fprintf(stderr, "qemu: invalid cache option\n");
2476 return -1;
2480 if (get_param_value(buf, sizeof(buf), "format", str)) {
2481 if (strcmp(buf, "?") == 0) {
2482 fprintf(stderr, "qemu: Supported formats:");
2483 bdrv_iterate_format(bdrv_format_print, NULL);
2484 fprintf(stderr, "\n");
2485 return -1;
2487 drv = bdrv_find_format(buf);
2488 if (!drv) {
2489 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2490 return -1;
2494 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2495 if (!strcmp(buf, "on")) {
2496 if (extboot_drive != -1) {
2497 fprintf(stderr, "qemu: two bootable drives specified\n");
2498 return -1;
2500 extboot_drive = nb_drives;
2501 } else if (strcmp(buf, "off")) {
2502 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2503 return -1;
2507 if (arg->file == NULL)
2508 get_param_value(file, sizeof(file), "file", str);
2509 else
2510 pstrcpy(file, sizeof(file), arg->file);
2512 if (!get_param_value(serial, sizeof(serial), "serial", str))
2513 memset(serial, 0, sizeof(serial));
2515 onerror = BLOCK_ERR_REPORT;
2516 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2517 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2518 fprintf(stderr, "werror is no supported by this format\n");
2519 return -1;
2521 if (!strcmp(buf, "ignore"))
2522 onerror = BLOCK_ERR_IGNORE;
2523 else if (!strcmp(buf, "enospc"))
2524 onerror = BLOCK_ERR_STOP_ENOSPC;
2525 else if (!strcmp(buf, "stop"))
2526 onerror = BLOCK_ERR_STOP_ANY;
2527 else if (!strcmp(buf, "report"))
2528 onerror = BLOCK_ERR_REPORT;
2529 else {
2530 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2531 return -1;
2535 /* compute bus and unit according index */
2537 if (index != -1) {
2538 if (bus_id != 0 || unit_id != -1) {
2539 fprintf(stderr,
2540 "qemu: '%s' index cannot be used with bus and unit\n", str);
2541 return -1;
2543 if (max_devs == 0)
2545 unit_id = index;
2546 bus_id = 0;
2547 } else {
2548 unit_id = index % max_devs;
2549 bus_id = index / max_devs;
2553 /* if user doesn't specify a unit_id,
2554 * try to find the first free
2557 if (unit_id == -1) {
2558 unit_id = 0;
2559 while (drive_get_index(type, bus_id, unit_id) != -1) {
2560 unit_id++;
2561 if (max_devs && unit_id >= max_devs) {
2562 unit_id -= max_devs;
2563 bus_id++;
2568 /* check unit id */
2570 if (max_devs && unit_id >= max_devs) {
2571 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2572 str, unit_id, max_devs - 1);
2573 return -1;
2577 * ignore multiple definitions
2580 if (drive_get_index(type, bus_id, unit_id) != -1)
2581 return -2;
2583 /* init */
2585 if (type == IF_IDE || type == IF_SCSI)
2586 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2587 if (max_devs)
2588 snprintf(buf, sizeof(buf), "%s%i%s%i",
2589 devname, bus_id, mediastr, unit_id);
2590 else
2591 snprintf(buf, sizeof(buf), "%s%s%i",
2592 devname, mediastr, unit_id);
2593 bdrv = bdrv_new(buf);
2594 drives_table_idx = drive_get_free_idx();
2595 drives_table[drives_table_idx].bdrv = bdrv;
2596 drives_table[drives_table_idx].type = type;
2597 drives_table[drives_table_idx].bus = bus_id;
2598 drives_table[drives_table_idx].unit = unit_id;
2599 drives_table[drives_table_idx].onerror = onerror;
2600 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2601 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2602 nb_drives++;
2604 switch(type) {
2605 case IF_IDE:
2606 case IF_SCSI:
2607 switch(media) {
2608 case MEDIA_DISK:
2609 if (cyls != 0) {
2610 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2611 bdrv_set_translation_hint(bdrv, translation);
2613 break;
2614 case MEDIA_CDROM:
2615 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2616 break;
2618 break;
2619 case IF_SD:
2620 /* FIXME: This isn't really a floppy, but it's a reasonable
2621 approximation. */
2622 case IF_FLOPPY:
2623 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2624 break;
2625 case IF_PFLASH:
2626 case IF_MTD:
2627 case IF_VIRTIO:
2628 break;
2630 if (!file[0])
2631 return -2;
2632 bdrv_flags = 0;
2633 if (snapshot) {
2634 bdrv_flags |= BDRV_O_SNAPSHOT;
2635 cache = 2; /* always use write-back with snapshot */
2637 if (cache == 0) /* no caching */
2638 bdrv_flags |= BDRV_O_NOCACHE;
2639 else if (cache == 2) /* write-back */
2640 bdrv_flags |= BDRV_O_CACHE_WB;
2641 else if (cache == 3) /* not specified */
2642 bdrv_flags |= BDRV_O_CACHE_DEF;
2643 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2644 fprintf(stderr, "qemu: could not open disk image %s\n",
2645 file);
2646 return -1;
2648 return drives_table_idx;
2651 /***********************************************************/
2652 /* USB devices */
2654 static USBPort *used_usb_ports;
2655 static USBPort *free_usb_ports;
2657 /* ??? Maybe change this to register a hub to keep track of the topology. */
2658 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2659 usb_attachfn attach)
2661 port->opaque = opaque;
2662 port->index = index;
2663 port->attach = attach;
2664 port->next = free_usb_ports;
2665 free_usb_ports = port;
2668 int usb_device_add_dev(USBDevice *dev)
2670 USBPort *port;
2672 /* Find a USB port to add the device to. */
2673 port = free_usb_ports;
2674 if (!port->next) {
2675 USBDevice *hub;
2677 /* Create a new hub and chain it on. */
2678 free_usb_ports = NULL;
2679 port->next = used_usb_ports;
2680 used_usb_ports = port;
2682 hub = usb_hub_init(VM_USB_HUB_SIZE);
2683 usb_attach(port, hub);
2684 port = free_usb_ports;
2687 free_usb_ports = port->next;
2688 port->next = used_usb_ports;
2689 used_usb_ports = port;
2690 usb_attach(port, dev);
2691 return 0;
2694 static int usb_device_add(const char *devname)
2696 const char *p;
2697 USBDevice *dev;
2699 if (!free_usb_ports)
2700 return -1;
2702 if (strstart(devname, "host:", &p)) {
2703 dev = usb_host_device_open(p);
2704 } else if (!strcmp(devname, "mouse")) {
2705 dev = usb_mouse_init();
2706 } else if (!strcmp(devname, "tablet")) {
2707 dev = usb_tablet_init();
2708 } else if (!strcmp(devname, "keyboard")) {
2709 dev = usb_keyboard_init();
2710 } else if (strstart(devname, "disk:", &p)) {
2711 dev = usb_msd_init(p);
2712 } else if (!strcmp(devname, "wacom-tablet")) {
2713 dev = usb_wacom_init();
2714 } else if (strstart(devname, "serial:", &p)) {
2715 dev = usb_serial_init(p);
2716 #ifdef CONFIG_BRLAPI
2717 } else if (!strcmp(devname, "braille")) {
2718 dev = usb_baum_init();
2719 #endif
2720 } else if (strstart(devname, "net:", &p)) {
2721 int nic = nb_nics;
2723 if (net_client_init("nic", p) < 0)
2724 return -1;
2725 nd_table[nic].model = "usb";
2726 dev = usb_net_init(&nd_table[nic]);
2727 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2728 dev = usb_bt_init(devname[2] ? hci_init(p) :
2729 bt_new_hci(qemu_find_bt_vlan(0)));
2730 } else {
2731 return -1;
2733 if (!dev)
2734 return -1;
2736 return usb_device_add_dev(dev);
2739 int usb_device_del_addr(int bus_num, int addr)
2741 USBPort *port;
2742 USBPort **lastp;
2743 USBDevice *dev;
2745 if (!used_usb_ports)
2746 return -1;
2748 if (bus_num != 0)
2749 return -1;
2751 lastp = &used_usb_ports;
2752 port = used_usb_ports;
2753 while (port && port->dev->addr != addr) {
2754 lastp = &port->next;
2755 port = port->next;
2758 if (!port)
2759 return -1;
2761 dev = port->dev;
2762 *lastp = port->next;
2763 usb_attach(port, NULL);
2764 dev->handle_destroy(dev);
2765 port->next = free_usb_ports;
2766 free_usb_ports = port;
2767 return 0;
2770 static int usb_device_del(const char *devname)
2772 int bus_num, addr;
2773 const char *p;
2775 if (strstart(devname, "host:", &p))
2776 return usb_host_device_close(p);
2778 if (!used_usb_ports)
2779 return -1;
2781 p = strchr(devname, '.');
2782 if (!p)
2783 return -1;
2784 bus_num = strtoul(devname, NULL, 0);
2785 addr = strtoul(p + 1, NULL, 0);
2787 return usb_device_del_addr(bus_num, addr);
2790 void do_usb_add(const char *devname)
2792 usb_device_add(devname);
2795 void do_usb_del(const char *devname)
2797 usb_device_del(devname);
2800 void usb_info(void)
2802 USBDevice *dev;
2803 USBPort *port;
2804 const char *speed_str;
2806 if (!usb_enabled) {
2807 term_printf("USB support not enabled\n");
2808 return;
2811 for (port = used_usb_ports; port; port = port->next) {
2812 dev = port->dev;
2813 if (!dev)
2814 continue;
2815 switch(dev->speed) {
2816 case USB_SPEED_LOW:
2817 speed_str = "1.5";
2818 break;
2819 case USB_SPEED_FULL:
2820 speed_str = "12";
2821 break;
2822 case USB_SPEED_HIGH:
2823 speed_str = "480";
2824 break;
2825 default:
2826 speed_str = "?";
2827 break;
2829 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2830 0, dev->addr, speed_str, dev->devname);
2834 /***********************************************************/
2835 /* PCMCIA/Cardbus */
2837 static struct pcmcia_socket_entry_s {
2838 struct pcmcia_socket_s *socket;
2839 struct pcmcia_socket_entry_s *next;
2840 } *pcmcia_sockets = 0;
2842 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2844 struct pcmcia_socket_entry_s *entry;
2846 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2847 entry->socket = socket;
2848 entry->next = pcmcia_sockets;
2849 pcmcia_sockets = entry;
2852 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2854 struct pcmcia_socket_entry_s *entry, **ptr;
2856 ptr = &pcmcia_sockets;
2857 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2858 if (entry->socket == socket) {
2859 *ptr = entry->next;
2860 qemu_free(entry);
2864 void pcmcia_info(void)
2866 struct pcmcia_socket_entry_s *iter;
2867 if (!pcmcia_sockets)
2868 term_printf("No PCMCIA sockets\n");
2870 for (iter = pcmcia_sockets; iter; iter = iter->next)
2871 term_printf("%s: %s\n", iter->socket->slot_string,
2872 iter->socket->attached ? iter->socket->card_string :
2873 "Empty");
2876 /***********************************************************/
2877 /* register display */
2879 void register_displaystate(DisplayState *ds)
2881 DisplayState **s;
2882 s = &display_state;
2883 while (*s != NULL)
2884 s = &(*s)->next;
2885 ds->next = NULL;
2886 *s = ds;
2889 DisplayState *get_displaystate(void)
2891 return display_state;
2894 /* dumb display */
2896 static void dumb_display_init(void)
2898 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2899 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2900 register_displaystate(ds);
2903 /***********************************************************/
2904 /* I/O handling */
2906 #define MAX_IO_HANDLERS 64
2908 typedef struct IOHandlerRecord {
2909 int fd;
2910 IOCanRWHandler *fd_read_poll;
2911 IOHandler *fd_read;
2912 IOHandler *fd_write;
2913 int deleted;
2914 void *opaque;
2915 /* temporary data */
2916 struct pollfd *ufd;
2917 struct IOHandlerRecord *next;
2918 } IOHandlerRecord;
2920 static IOHandlerRecord *first_io_handler;
2922 /* XXX: fd_read_poll should be suppressed, but an API change is
2923 necessary in the character devices to suppress fd_can_read(). */
2924 int qemu_set_fd_handler2(int fd,
2925 IOCanRWHandler *fd_read_poll,
2926 IOHandler *fd_read,
2927 IOHandler *fd_write,
2928 void *opaque)
2930 IOHandlerRecord **pioh, *ioh;
2932 if (!fd_read && !fd_write) {
2933 pioh = &first_io_handler;
2934 for(;;) {
2935 ioh = *pioh;
2936 if (ioh == NULL)
2937 break;
2938 if (ioh->fd == fd) {
2939 ioh->deleted = 1;
2940 break;
2942 pioh = &ioh->next;
2944 } else {
2945 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2946 if (ioh->fd == fd)
2947 goto found;
2949 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2950 ioh->next = first_io_handler;
2951 first_io_handler = ioh;
2952 found:
2953 ioh->fd = fd;
2954 ioh->fd_read_poll = fd_read_poll;
2955 ioh->fd_read = fd_read;
2956 ioh->fd_write = fd_write;
2957 ioh->opaque = opaque;
2958 ioh->deleted = 0;
2960 main_loop_break();
2961 return 0;
2964 int qemu_set_fd_handler(int fd,
2965 IOHandler *fd_read,
2966 IOHandler *fd_write,
2967 void *opaque)
2969 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2972 #ifdef _WIN32
2973 /***********************************************************/
2974 /* Polling handling */
2976 typedef struct PollingEntry {
2977 PollingFunc *func;
2978 void *opaque;
2979 struct PollingEntry *next;
2980 } PollingEntry;
2982 static PollingEntry *first_polling_entry;
2984 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2986 PollingEntry **ppe, *pe;
2987 pe = qemu_mallocz(sizeof(PollingEntry));
2988 pe->func = func;
2989 pe->opaque = opaque;
2990 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2991 *ppe = pe;
2992 return 0;
2995 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2997 PollingEntry **ppe, *pe;
2998 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2999 pe = *ppe;
3000 if (pe->func == func && pe->opaque == opaque) {
3001 *ppe = pe->next;
3002 qemu_free(pe);
3003 break;
3008 /***********************************************************/
3009 /* Wait objects support */
3010 typedef struct WaitObjects {
3011 int num;
3012 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3013 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3014 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3015 } WaitObjects;
3017 static WaitObjects wait_objects = {0};
3019 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3021 WaitObjects *w = &wait_objects;
3023 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3024 return -1;
3025 w->events[w->num] = handle;
3026 w->func[w->num] = func;
3027 w->opaque[w->num] = opaque;
3028 w->num++;
3029 return 0;
3032 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3034 int i, found;
3035 WaitObjects *w = &wait_objects;
3037 found = 0;
3038 for (i = 0; i < w->num; i++) {
3039 if (w->events[i] == handle)
3040 found = 1;
3041 if (found) {
3042 w->events[i] = w->events[i + 1];
3043 w->func[i] = w->func[i + 1];
3044 w->opaque[i] = w->opaque[i + 1];
3047 if (found)
3048 w->num--;
3050 #endif
3052 /***********************************************************/
3053 /* ram save/restore */
3055 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3057 int v;
3059 v = qemu_get_byte(f);
3060 switch(v) {
3061 case 0:
3062 if (qemu_get_buffer(f, buf, len) != len)
3063 return -EIO;
3064 break;
3065 case 1:
3066 v = qemu_get_byte(f);
3067 memset(buf, v, len);
3068 break;
3069 default:
3070 return -EINVAL;
3073 if (qemu_file_has_error(f))
3074 return -EIO;
3076 return 0;
3079 static int ram_load_v1(QEMUFile *f, void *opaque)
3081 int ret;
3082 ram_addr_t i;
3084 if (qemu_get_be32(f) != phys_ram_size)
3085 return -EINVAL;
3086 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3087 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3088 continue;
3089 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3090 if (ret)
3091 return ret;
3093 return 0;
3096 #define BDRV_HASH_BLOCK_SIZE 1024
3097 #define IOBUF_SIZE 4096
3098 #define RAM_CBLOCK_MAGIC 0xfabe
3100 typedef struct RamDecompressState {
3101 z_stream zstream;
3102 QEMUFile *f;
3103 uint8_t buf[IOBUF_SIZE];
3104 } RamDecompressState;
3106 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3108 int ret;
3109 memset(s, 0, sizeof(*s));
3110 s->f = f;
3111 ret = inflateInit(&s->zstream);
3112 if (ret != Z_OK)
3113 return -1;
3114 return 0;
3117 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3119 int ret, clen;
3121 s->zstream.avail_out = len;
3122 s->zstream.next_out = buf;
3123 while (s->zstream.avail_out > 0) {
3124 if (s->zstream.avail_in == 0) {
3125 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3126 return -1;
3127 clen = qemu_get_be16(s->f);
3128 if (clen > IOBUF_SIZE)
3129 return -1;
3130 qemu_get_buffer(s->f, s->buf, clen);
3131 s->zstream.avail_in = clen;
3132 s->zstream.next_in = s->buf;
3134 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3135 if (ret != Z_OK && ret != Z_STREAM_END) {
3136 return -1;
3139 return 0;
3142 static void ram_decompress_close(RamDecompressState *s)
3144 inflateEnd(&s->zstream);
3147 #define RAM_SAVE_FLAG_FULL 0x01
3148 #define RAM_SAVE_FLAG_COMPRESS 0x02
3149 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3150 #define RAM_SAVE_FLAG_PAGE 0x08
3151 #define RAM_SAVE_FLAG_EOS 0x10
3153 static int is_dup_page(uint8_t *page, uint8_t ch)
3155 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3156 uint32_t *array = (uint32_t *)page;
3157 int i;
3159 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3160 if (array[i] != val)
3161 return 0;
3164 return 1;
3167 static int ram_save_block(QEMUFile *f)
3169 static ram_addr_t current_addr = 0;
3170 ram_addr_t saved_addr = current_addr;
3171 ram_addr_t addr = 0;
3172 int found = 0;
3174 while (addr < phys_ram_size) {
3175 if (kvm_enabled() && current_addr == 0)
3176 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3177 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3178 uint8_t ch;
3180 cpu_physical_memory_reset_dirty(current_addr,
3181 current_addr + TARGET_PAGE_SIZE,
3182 MIGRATION_DIRTY_FLAG);
3184 ch = *(phys_ram_base + current_addr);
3186 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3187 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3188 qemu_put_byte(f, ch);
3189 } else {
3190 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3191 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3194 found = 1;
3195 break;
3197 addr += TARGET_PAGE_SIZE;
3198 current_addr = (saved_addr + addr) % phys_ram_size;
3201 return found;
3204 static ram_addr_t ram_save_threshold = 10;
3206 static ram_addr_t ram_save_remaining(void)
3208 ram_addr_t addr;
3209 ram_addr_t count = 0;
3211 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3212 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3213 count++;
3216 return count;
3219 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3221 ram_addr_t addr;
3223 if (stage == 1) {
3224 /* Make sure all dirty bits are set */
3225 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3226 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3227 cpu_physical_memory_set_dirty(addr);
3230 /* Enable dirty memory tracking */
3231 cpu_physical_memory_set_dirty_tracking(1);
3233 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3236 while (!qemu_file_rate_limit(f)) {
3237 int ret;
3239 ret = ram_save_block(f);
3240 if (ret == 0) /* no more blocks */
3241 break;
3244 /* try transferring iterative blocks of memory */
3246 if (stage == 3) {
3247 cpu_physical_memory_set_dirty_tracking(0);
3249 /* flush all remaining blocks regardless of rate limiting */
3250 while (ram_save_block(f) != 0);
3253 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3255 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3258 static int ram_load_dead(QEMUFile *f, void *opaque)
3260 RamDecompressState s1, *s = &s1;
3261 uint8_t buf[10];
3262 ram_addr_t i;
3264 if (ram_decompress_open(s, f) < 0)
3265 return -EINVAL;
3266 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3267 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3268 continue;
3269 if (ram_decompress_buf(s, buf, 1) < 0) {
3270 fprintf(stderr, "Error while reading ram block header\n");
3271 goto error;
3273 if (buf[0] == 0) {
3274 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3275 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3276 goto error;
3278 } else {
3279 error:
3280 printf("Error block header\n");
3281 return -EINVAL;
3284 ram_decompress_close(s);
3286 return 0;
3289 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3291 ram_addr_t addr;
3292 int flags;
3294 if (version_id == 1)
3295 return ram_load_v1(f, opaque);
3297 if (version_id == 2) {
3298 if (qemu_get_be32(f) != phys_ram_size)
3299 return -EINVAL;
3300 return ram_load_dead(f, opaque);
3303 if (version_id != 3)
3304 return -EINVAL;
3306 do {
3307 addr = qemu_get_be64(f);
3309 flags = addr & ~TARGET_PAGE_MASK;
3310 addr &= TARGET_PAGE_MASK;
3312 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3313 if (addr != phys_ram_size)
3314 return -EINVAL;
3317 if (flags & RAM_SAVE_FLAG_FULL) {
3318 if (ram_load_dead(f, opaque) < 0)
3319 return -EINVAL;
3322 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3323 uint8_t ch = qemu_get_byte(f);
3324 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3325 } else if (flags & RAM_SAVE_FLAG_PAGE)
3326 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3327 } while (!(flags & RAM_SAVE_FLAG_EOS));
3329 return 0;
3332 /***********************************************************/
3333 /* bottom halves (can be seen as timers which expire ASAP) */
3335 struct QEMUBH {
3336 QEMUBHFunc *cb;
3337 void *opaque;
3338 int scheduled;
3339 int idle;
3340 int deleted;
3341 QEMUBH *next;
3344 static QEMUBH *first_bh = NULL;
3346 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3348 QEMUBH *bh;
3349 bh = qemu_mallocz(sizeof(QEMUBH));
3350 bh->cb = cb;
3351 bh->opaque = opaque;
3352 bh->next = first_bh;
3353 first_bh = bh;
3354 return bh;
3357 int qemu_bh_poll(void)
3359 QEMUBH *bh, **bhp;
3360 int ret;
3362 ret = 0;
3363 for (bh = first_bh; bh; bh = bh->next) {
3364 if (!bh->deleted && bh->scheduled) {
3365 bh->scheduled = 0;
3366 if (!bh->idle)
3367 ret = 1;
3368 bh->idle = 0;
3369 bh->cb(bh->opaque);
3373 /* remove deleted bhs */
3374 bhp = &first_bh;
3375 while (*bhp) {
3376 bh = *bhp;
3377 if (bh->deleted) {
3378 *bhp = bh->next;
3379 qemu_free(bh);
3380 } else
3381 bhp = &bh->next;
3384 return ret;
3387 void qemu_bh_schedule_idle(QEMUBH *bh)
3389 if (bh->scheduled)
3390 return;
3391 bh->scheduled = 1;
3392 bh->idle = 1;
3395 void qemu_bh_schedule(QEMUBH *bh)
3397 CPUState *env = cpu_single_env;
3398 if (bh->scheduled)
3399 return;
3400 bh->scheduled = 1;
3401 bh->idle = 0;
3402 /* stop the currently executing CPU to execute the BH ASAP */
3403 if (env) {
3404 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3406 main_loop_break();
3409 void qemu_bh_cancel(QEMUBH *bh)
3411 bh->scheduled = 0;
3414 void qemu_bh_delete(QEMUBH *bh)
3416 bh->scheduled = 0;
3417 bh->deleted = 1;
3420 static void qemu_bh_update_timeout(int *timeout)
3422 QEMUBH *bh;
3424 for (bh = first_bh; bh; bh = bh->next) {
3425 if (!bh->deleted && bh->scheduled) {
3426 if (bh->idle) {
3427 /* idle bottom halves will be polled at least
3428 * every 10ms */
3429 *timeout = MIN(10, *timeout);
3430 } else {
3431 /* non-idle bottom halves will be executed
3432 * immediately */
3433 *timeout = 0;
3434 break;
3440 /***********************************************************/
3441 /* machine registration */
3443 static QEMUMachine *first_machine = NULL;
3444 QEMUMachine *current_machine = NULL;
3446 int qemu_register_machine(QEMUMachine *m)
3448 QEMUMachine **pm;
3449 pm = &first_machine;
3450 while (*pm != NULL)
3451 pm = &(*pm)->next;
3452 m->next = NULL;
3453 *pm = m;
3454 return 0;
3457 static QEMUMachine *find_machine(const char *name)
3459 QEMUMachine *m;
3461 for(m = first_machine; m != NULL; m = m->next) {
3462 if (!strcmp(m->name, name))
3463 return m;
3465 return NULL;
3468 /***********************************************************/
3469 /* main execution loop */
3471 static void gui_update(void *opaque)
3473 uint64_t interval = GUI_REFRESH_INTERVAL;
3474 DisplayState *ds = opaque;
3475 DisplayChangeListener *dcl = ds->listeners;
3477 dpy_refresh(ds);
3479 while (dcl != NULL) {
3480 if (dcl->gui_timer_interval &&
3481 dcl->gui_timer_interval < interval)
3482 interval = dcl->gui_timer_interval;
3483 dcl = dcl->next;
3485 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3488 static void nographic_update(void *opaque)
3490 uint64_t interval = GUI_REFRESH_INTERVAL;
3492 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3495 struct vm_change_state_entry {
3496 VMChangeStateHandler *cb;
3497 void *opaque;
3498 LIST_ENTRY (vm_change_state_entry) entries;
3501 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3503 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3504 void *opaque)
3506 VMChangeStateEntry *e;
3508 e = qemu_mallocz(sizeof (*e));
3510 e->cb = cb;
3511 e->opaque = opaque;
3512 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3513 return e;
3516 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3518 LIST_REMOVE (e, entries);
3519 qemu_free (e);
3522 static void vm_state_notify(int running, int reason)
3524 VMChangeStateEntry *e;
3526 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3527 e->cb(e->opaque, running, reason);
3531 void vm_start(void)
3533 if (!vm_running) {
3534 cpu_enable_ticks();
3535 vm_running = 1;
3536 vm_state_notify(1, 0);
3537 qemu_rearm_alarm_timer(alarm_timer);
3541 void vm_stop(int reason)
3543 if (vm_running) {
3544 cpu_disable_ticks();
3545 vm_running = 0;
3546 vm_state_notify(0, reason);
3550 /* reset/shutdown handler */
3552 typedef struct QEMUResetEntry {
3553 QEMUResetHandler *func;
3554 void *opaque;
3555 struct QEMUResetEntry *next;
3556 } QEMUResetEntry;
3558 static QEMUResetEntry *first_reset_entry;
3559 static int reset_requested;
3560 static int shutdown_requested;
3561 static int powerdown_requested;
3563 int qemu_shutdown_requested(void)
3565 int r = shutdown_requested;
3566 shutdown_requested = 0;
3567 return r;
3570 int qemu_reset_requested(void)
3572 int r = reset_requested;
3573 reset_requested = 0;
3574 return r;
3577 int qemu_powerdown_requested(void)
3579 int r = powerdown_requested;
3580 powerdown_requested = 0;
3581 return r;
3584 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3586 QEMUResetEntry **pre, *re;
3588 pre = &first_reset_entry;
3589 while (*pre != NULL)
3590 pre = &(*pre)->next;
3591 re = qemu_mallocz(sizeof(QEMUResetEntry));
3592 re->func = func;
3593 re->opaque = opaque;
3594 re->next = NULL;
3595 *pre = re;
3598 void qemu_system_reset(void)
3600 QEMUResetEntry *re;
3602 /* reset all devices */
3603 for(re = first_reset_entry; re != NULL; re = re->next) {
3604 re->func(re->opaque);
3608 void qemu_system_reset_request(void)
3610 if (no_reboot) {
3611 shutdown_requested = 1;
3612 } else {
3613 reset_requested = 1;
3616 if (cpu_single_env) {
3617 qemu_kvm_cpu_stop(cpu_single_env);
3618 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3620 main_loop_break();
3623 void qemu_system_shutdown_request(void)
3625 shutdown_requested = 1;
3626 if (cpu_single_env)
3627 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3630 void qemu_system_powerdown_request(void)
3632 powerdown_requested = 1;
3633 if (cpu_single_env)
3634 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3637 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3638 struct timeval *tv)
3640 int ret;
3642 /* KVM holds a mutex while QEMU code is running, we need hooks to
3643 release the mutex whenever QEMU code sleeps. */
3645 kvm_sleep_begin();
3647 ret = select(max_fd, rfds, wfds, xfds, tv);
3649 kvm_sleep_end();
3651 return ret;
3654 #ifdef _WIN32
3655 static void host_main_loop_wait(int *timeout)
3657 int ret, ret2, i;
3658 PollingEntry *pe;
3661 /* XXX: need to suppress polling by better using win32 events */
3662 ret = 0;
3663 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3664 ret |= pe->func(pe->opaque);
3666 if (ret == 0) {
3667 int err;
3668 WaitObjects *w = &wait_objects;
3670 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3671 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3672 if (w->func[ret - WAIT_OBJECT_0])
3673 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3675 /* Check for additional signaled events */
3676 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3678 /* Check if event is signaled */
3679 ret2 = WaitForSingleObject(w->events[i], 0);
3680 if(ret2 == WAIT_OBJECT_0) {
3681 if (w->func[i])
3682 w->func[i](w->opaque[i]);
3683 } else if (ret2 == WAIT_TIMEOUT) {
3684 } else {
3685 err = GetLastError();
3686 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3689 } else if (ret == WAIT_TIMEOUT) {
3690 } else {
3691 err = GetLastError();
3692 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3696 *timeout = 0;
3698 #else
3699 static void host_main_loop_wait(int *timeout)
3702 #endif
3704 void main_loop_wait(int timeout)
3706 IOHandlerRecord *ioh;
3707 fd_set rfds, wfds, xfds;
3708 int ret, nfds;
3709 struct timeval tv;
3711 qemu_bh_update_timeout(&timeout);
3713 host_main_loop_wait(&timeout);
3715 /* poll any events */
3716 /* XXX: separate device handlers from system ones */
3717 nfds = -1;
3718 FD_ZERO(&rfds);
3719 FD_ZERO(&wfds);
3720 FD_ZERO(&xfds);
3721 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3722 if (ioh->deleted)
3723 continue;
3724 if (ioh->fd_read &&
3725 (!ioh->fd_read_poll ||
3726 ioh->fd_read_poll(ioh->opaque) != 0)) {
3727 FD_SET(ioh->fd, &rfds);
3728 if (ioh->fd > nfds)
3729 nfds = ioh->fd;
3731 if (ioh->fd_write) {
3732 FD_SET(ioh->fd, &wfds);
3733 if (ioh->fd > nfds)
3734 nfds = ioh->fd;
3738 tv.tv_sec = timeout / 1000;
3739 tv.tv_usec = (timeout % 1000) * 1000;
3741 #if defined(CONFIG_SLIRP)
3742 if (slirp_is_inited()) {
3743 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3745 #endif
3746 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3747 if (ret > 0) {
3748 IOHandlerRecord **pioh;
3750 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3751 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3752 ioh->fd_read(ioh->opaque);
3753 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3754 FD_CLR(ioh->fd, &rfds);
3756 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3757 ioh->fd_write(ioh->opaque);
3761 /* remove deleted IO handlers */
3762 pioh = &first_io_handler;
3763 while (*pioh) {
3764 ioh = *pioh;
3765 if (ioh->deleted) {
3766 *pioh = ioh->next;
3767 qemu_free(ioh);
3768 } else
3769 pioh = &ioh->next;
3772 #if defined(CONFIG_SLIRP)
3773 if (slirp_is_inited()) {
3774 if (ret < 0) {
3775 FD_ZERO(&rfds);
3776 FD_ZERO(&wfds);
3777 FD_ZERO(&xfds);
3779 slirp_select_poll(&rfds, &wfds, &xfds);
3781 #endif
3783 /* vm time timers */
3784 if (vm_running && (!cur_cpu
3785 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3786 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3787 qemu_get_clock(vm_clock));
3789 /* real time timers */
3790 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3791 qemu_get_clock(rt_clock));
3793 /* Check bottom-halves last in case any of the earlier events triggered
3794 them. */
3795 qemu_bh_poll();
3799 static int main_loop(void)
3801 int ret, timeout;
3802 #ifdef CONFIG_PROFILER
3803 int64_t ti;
3804 #endif
3805 CPUState *env;
3808 if (kvm_enabled()) {
3809 kvm_main_loop();
3810 cpu_disable_ticks();
3811 return 0;
3814 cur_cpu = first_cpu;
3815 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3816 for(;;) {
3817 if (vm_running) {
3819 for(;;) {
3820 /* get next cpu */
3821 env = next_cpu;
3822 #ifdef CONFIG_PROFILER
3823 ti = profile_getclock();
3824 #endif
3825 if (use_icount) {
3826 int64_t count;
3827 int decr;
3828 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3829 env->icount_decr.u16.low = 0;
3830 env->icount_extra = 0;
3831 count = qemu_next_deadline();
3832 count = (count + (1 << icount_time_shift) - 1)
3833 >> icount_time_shift;
3834 qemu_icount += count;
3835 decr = (count > 0xffff) ? 0xffff : count;
3836 count -= decr;
3837 env->icount_decr.u16.low = decr;
3838 env->icount_extra = count;
3840 ret = cpu_exec(env);
3841 #ifdef CONFIG_PROFILER
3842 qemu_time += profile_getclock() - ti;
3843 #endif
3844 if (use_icount) {
3845 /* Fold pending instructions back into the
3846 instruction counter, and clear the interrupt flag. */
3847 qemu_icount -= (env->icount_decr.u16.low
3848 + env->icount_extra);
3849 env->icount_decr.u32 = 0;
3850 env->icount_extra = 0;
3852 next_cpu = env->next_cpu ?: first_cpu;
3853 if (event_pending && likely(ret != EXCP_DEBUG)) {
3854 ret = EXCP_INTERRUPT;
3855 event_pending = 0;
3856 break;
3858 if (ret == EXCP_HLT) {
3859 /* Give the next CPU a chance to run. */
3860 cur_cpu = env;
3861 continue;
3863 if (ret != EXCP_HALTED)
3864 break;
3865 /* all CPUs are halted ? */
3866 if (env == cur_cpu)
3867 break;
3869 cur_cpu = env;
3871 if (shutdown_requested) {
3872 ret = EXCP_INTERRUPT;
3873 if (no_shutdown) {
3874 vm_stop(0);
3875 no_shutdown = 0;
3877 else
3878 break;
3880 if (reset_requested) {
3881 reset_requested = 0;
3882 qemu_system_reset();
3883 if (kvm_enabled())
3884 kvm_load_registers(env);
3885 ret = EXCP_INTERRUPT;
3887 if (powerdown_requested) {
3888 powerdown_requested = 0;
3889 qemu_system_powerdown();
3890 ret = EXCP_INTERRUPT;
3892 #ifdef CONFIG_GDBSTUB
3893 if (unlikely(ret == EXCP_DEBUG)) {
3894 gdb_set_stop_cpu(cur_cpu);
3895 vm_stop(EXCP_DEBUG);
3897 #endif
3898 /* If all cpus are halted then wait until the next IRQ */
3899 /* XXX: use timeout computed from timers */
3900 if (ret == EXCP_HALTED) {
3901 if (use_icount) {
3902 int64_t add;
3903 int64_t delta;
3904 /* Advance virtual time to the next event. */
3905 if (use_icount == 1) {
3906 /* When not using an adaptive execution frequency
3907 we tend to get badly out of sync with real time,
3908 so just delay for a reasonable amount of time. */
3909 delta = 0;
3910 } else {
3911 delta = cpu_get_icount() - cpu_get_clock();
3913 if (delta > 0) {
3914 /* If virtual time is ahead of real time then just
3915 wait for IO. */
3916 timeout = (delta / 1000000) + 1;
3917 } else {
3918 /* Wait for either IO to occur or the next
3919 timer event. */
3920 add = qemu_next_deadline();
3921 /* We advance the timer before checking for IO.
3922 Limit the amount we advance so that early IO
3923 activity won't get the guest too far ahead. */
3924 if (add > 10000000)
3925 add = 10000000;
3926 delta += add;
3927 add = (add + (1 << icount_time_shift) - 1)
3928 >> icount_time_shift;
3929 qemu_icount += add;
3930 timeout = delta / 1000000;
3931 if (timeout < 0)
3932 timeout = 0;
3934 } else {
3935 timeout = 5000;
3937 } else {
3938 timeout = 0;
3940 } else {
3941 if (shutdown_requested) {
3942 ret = EXCP_INTERRUPT;
3943 break;
3945 timeout = 5000;
3947 #ifdef CONFIG_PROFILER
3948 ti = profile_getclock();
3949 #endif
3950 main_loop_wait(timeout);
3951 #ifdef CONFIG_PROFILER
3952 dev_time += profile_getclock() - ti;
3953 #endif
3955 cpu_disable_ticks();
3956 return ret;
3959 static void help(int exitcode)
3961 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3962 and qemu-doc.texi */
3963 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
3964 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3965 "usage: %s [options] [disk_image]\n"
3966 "\n"
3967 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3968 "\n"
3969 "Standard options:\n"
3970 "-h or -help display this help and exit\n"
3971 "-M machine select emulated machine (-M ? for list)\n"
3972 "-cpu cpu select CPU (-cpu ? for list)\n"
3973 "-smp n set the number of CPUs to 'n' [default=1]\n"
3974 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3975 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3976 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3977 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3978 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3979 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3980 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3981 " [,boot=on|off]\n"
3982 " use 'file' as a drive image\n"
3983 "-mtdblock file use 'file' as on-board Flash memory image\n"
3984 "-sd file use 'file' as SecureDigital card image\n"
3985 "-pflash file use 'file' as a parallel flash image\n"
3986 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3987 "-snapshot write to temporary files instead of disk image files\n"
3988 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3989 #ifndef _WIN32
3990 "-k language use keyboard layout (for example \"fr\" for French)\n"
3991 #endif
3992 #ifdef HAS_AUDIO
3993 "-audio-help print list of audio drivers and their options\n"
3994 "-soundhw c1,... enable audio support\n"
3995 " and only specified sound cards (comma separated list)\n"
3996 " use -soundhw ? to get the list of supported cards\n"
3997 " use -soundhw all to enable all of them\n"
3998 #endif
3999 "-usb enable the USB driver (will be the default soon)\n"
4000 "-usbdevice name add the host or guest USB device 'name'\n"
4001 "-name string set the name of the guest\n"
4002 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
4003 " specify machine UUID\n"
4004 "\n"
4005 "Display options:\n"
4006 "-nographic disable graphical output and redirect serial I/Os to console\n"
4007 #ifdef CONFIG_CURSES
4008 "-curses use a curses/ncurses interface instead of SDL\n"
4009 #endif
4010 #ifdef CONFIG_SDL
4011 "-no-frame open SDL window without a frame and window decorations\n"
4012 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4013 "-no-quit disable SDL window close capability\n"
4014 "-sdl enable SDL\n"
4015 #endif
4016 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4017 "-vga [std|cirrus|vmware|none]\n"
4018 " select video card type\n"
4019 "-full-screen start in full screen\n"
4020 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4021 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4022 #endif
4023 "-vnc display start a VNC server on display\n"
4024 #ifdef TARGET_IA64
4025 "-nvram file use 'file' to save or load nvram image\n"
4026 #endif
4027 "-name string set the name of the guest\n"
4028 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4029 "\n"
4030 "Network options:\n"
4031 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
4032 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4033 #ifdef CONFIG_SLIRP
4034 "-net user[,vlan=n][,name=str][,hostname=host]\n"
4035 " connect the user mode network stack to VLAN 'n' and send\n"
4036 " hostname 'host' to DHCP clients\n"
4037 #endif
4038 #ifdef _WIN32
4039 "-net tap[,vlan=n][,name=str],ifname=name\n"
4040 " connect the host TAP network interface to VLAN 'n'\n"
4041 #else
4042 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4043 " connect the host TAP network interface to VLAN 'n' and use the\n"
4044 " network scripts 'file' (default=%s)\n"
4045 " and 'dfile' (default=%s);\n"
4046 " use '[down]script=no' to disable script execution;\n"
4047 " use 'fd=h' to connect to an already opened TAP interface\n"
4048 #endif
4049 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4050 " connect the vlan 'n' to another VLAN using a socket connection\n"
4051 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4052 " connect the vlan 'n' to multicast maddr and port\n"
4053 #ifdef CONFIG_VDE
4054 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4055 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4056 " on host and listening for incoming connections on 'socketpath'.\n"
4057 " Use group 'groupname' and mode 'octalmode' to change default\n"
4058 " ownership and permissions for communication port.\n"
4059 #endif
4060 "-net none use it alone to have zero network devices; if no -net option\n"
4061 " is provided, the default is '-net nic -net user'\n"
4062 #ifdef CONFIG_SLIRP
4063 "-tftp dir allow tftp access to files in dir [-net user]\n"
4064 "-bootp file advertise file in BOOTP replies\n"
4065 #ifndef _WIN32
4066 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4067 #endif
4068 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4069 " redirect TCP or UDP connections from host to guest [-net user]\n"
4070 #endif
4071 "\n"
4072 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4073 "-bt hci,host[:id]\n"
4074 " use host's HCI with the given name\n"
4075 "-bt hci[,vlan=n]\n"
4076 " emulate a standard HCI in virtual scatternet 'n'\n"
4077 "-bt vhci[,vlan=n]\n"
4078 " add host computer to virtual scatternet 'n' using VHCI\n"
4079 "-bt device:dev[,vlan=n]\n"
4080 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4081 "\n"
4082 #ifdef TARGET_I386
4083 "\n"
4084 "i386 target only:\n"
4085 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4086 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4087 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4088 "-no-acpi disable ACPI\n"
4089 "-no-hpet disable HPET\n"
4090 #endif
4091 "Linux boot specific:\n"
4092 "-kernel bzImage use 'bzImage' as kernel image\n"
4093 "-append cmdline use 'cmdline' as kernel command line\n"
4094 "-initrd file use 'file' as initial ram disk\n"
4095 "\n"
4096 "Debug/Expert options:\n"
4097 "-serial dev redirect the serial port to char device 'dev'\n"
4098 "-parallel dev redirect the parallel port to char device 'dev'\n"
4099 "-monitor dev redirect the monitor to char device 'dev'\n"
4100 "-pidfile file write PID to 'file'\n"
4101 "-S freeze CPU at startup (use 'c' to start execution)\n"
4102 "-s wait gdb connection to port\n"
4103 "-p port set gdb connection port [default=%s]\n"
4104 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4105 "-hdachs c,h,s[,t]\n"
4106 " force hard disk 0 physical geometry and the optional BIOS\n"
4107 " translation (t=none or lba) (usually qemu can guess them)\n"
4108 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4109 "-bios file set the filename for the BIOS\n"
4110 #ifdef USE_KQEMU
4111 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4112 "-no-kqemu disable KQEMU kernel module usage\n"
4113 #endif
4114 #ifdef CONFIG_KVM
4115 "-enable-kvm enable KVM full virtualization support\n"
4116 #endif
4117 #ifdef USE_KVM
4118 #ifndef NO_CPU_EMULATION
4119 "-no-kvm disable KVM hardware virtualization\n"
4120 #endif
4121 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4122 "-no-kvm-pit disable KVM kernel mode PIT\n"
4123 "-no-kvm-pit-reinjection disable KVM kernel mode PIT interrupt reinjection\n"
4124 "-enable-nesting enable support for running a VM inside the VM (AMD only)\n"
4125 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4126 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4127 " expose a PCI device to the guest OS.\n"
4128 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4129 " 'string' is used in log output.\n"
4130 #endif
4131 #endif
4132 "-no-reboot exit instead of rebooting\n"
4133 "-no-shutdown stop before shutdown\n"
4134 "-loadvm [tag|id]\n"
4135 " start right away with a saved state (loadvm in monitor)\n"
4136 #ifndef _WIN32
4137 "-daemonize daemonize QEMU after initializing\n"
4138 #endif
4139 "-tdf inject timer interrupts that got lost\n"
4140 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4141 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also\n"
4142 " enables allocation of guest memory with huge pages\n"
4143 #ifdef MAP_POPULATE
4144 "-mem-prealloc toggles preallocation of -mem-path backed physical memory\n"
4145 " at startup. Default is enabled.\n"
4146 #endif
4147 "-option-rom rom load a file, rom, into the option ROM space\n"
4148 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4149 "-prom-env variable=value\n"
4150 " set OpenBIOS nvram variables\n"
4151 #endif
4152 "-clock force the use of the given methods for timer alarm.\n"
4153 " To see what timers are available use -clock ?\n"
4154 "-localtime set the real time clock to local time [default=utc]\n"
4155 "-startdate select initial date of the clock\n"
4156 "-icount [N|auto]\n"
4157 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4158 "-echr chr set terminal escape character instead of ctrl-a\n"
4159 "-virtioconsole c\n"
4160 " set virtio console\n"
4161 "-show-cursor show cursor\n"
4162 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4163 "-semihosting semihosting mode\n"
4164 #endif
4165 #if defined(TARGET_ARM)
4166 "-old-param old param mode\n"
4167 #endif
4168 "-tb-size n set TB size\n"
4169 "-incoming p prepare for incoming migration, listen on port p\n"
4170 "\n"
4171 "During emulation, the following keys are useful:\n"
4172 "ctrl-alt-f toggle full screen\n"
4173 "ctrl-alt-n switch to virtual console 'n'\n"
4174 "ctrl-alt toggle mouse and keyboard grab\n"
4175 "\n"
4176 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4178 "qemu",
4179 DEFAULT_RAM_SIZE,
4180 #ifndef _WIN32
4181 DEFAULT_NETWORK_SCRIPT,
4182 DEFAULT_NETWORK_DOWN_SCRIPT,
4183 #endif
4184 DEFAULT_GDBSTUB_PORT,
4185 "/tmp/qemu.log");
4186 exit(exitcode);
4189 #define HAS_ARG 0x0001
4191 enum {
4192 /* Please keep in synch with help, qemu_options[] and
4193 qemu-doc.texi */
4194 /* Standard options: */
4195 QEMU_OPTION_h,
4196 QEMU_OPTION_M,
4197 QEMU_OPTION_cpu,
4198 QEMU_OPTION_smp,
4199 QEMU_OPTION_fda,
4200 QEMU_OPTION_fdb,
4201 QEMU_OPTION_hda,
4202 QEMU_OPTION_hdb,
4203 QEMU_OPTION_hdc,
4204 QEMU_OPTION_hdd,
4205 QEMU_OPTION_cdrom,
4206 QEMU_OPTION_drive,
4207 QEMU_OPTION_mtdblock,
4208 QEMU_OPTION_sd,
4209 QEMU_OPTION_pflash,
4210 QEMU_OPTION_boot,
4211 QEMU_OPTION_snapshot,
4212 QEMU_OPTION_m,
4213 QEMU_OPTION_k,
4214 QEMU_OPTION_audio_help,
4215 QEMU_OPTION_soundhw,
4216 QEMU_OPTION_usb,
4217 QEMU_OPTION_usbdevice,
4218 QEMU_OPTION_name,
4219 QEMU_OPTION_uuid,
4221 /* Display options: */
4222 QEMU_OPTION_nographic,
4223 QEMU_OPTION_curses,
4224 QEMU_OPTION_no_frame,
4225 QEMU_OPTION_alt_grab,
4226 QEMU_OPTION_no_quit,
4227 QEMU_OPTION_sdl,
4228 QEMU_OPTION_portrait,
4229 QEMU_OPTION_vga,
4230 QEMU_OPTION_full_screen,
4231 QEMU_OPTION_g,
4232 QEMU_OPTION_vnc,
4234 /* Network options: */
4235 QEMU_OPTION_net,
4236 QEMU_OPTION_tftp,
4237 QEMU_OPTION_bootp,
4238 QEMU_OPTION_smb,
4239 QEMU_OPTION_redir,
4240 QEMU_OPTION_bt,
4242 /* i386 target only: */
4243 QEMU_OPTION_win2k_hack,
4244 QEMU_OPTION_rtc_td_hack,
4245 QEMU_OPTION_no_fd_bootchk,
4246 QEMU_OPTION_no_acpi,
4247 QEMU_OPTION_no_hpet,
4249 /* Linux boot specific: */
4250 QEMU_OPTION_kernel,
4251 QEMU_OPTION_append,
4252 QEMU_OPTION_initrd,
4254 /* Debug/Expert options: */
4255 QEMU_OPTION_serial,
4256 QEMU_OPTION_parallel,
4257 QEMU_OPTION_monitor,
4258 QEMU_OPTION_pidfile,
4259 QEMU_OPTION_S,
4260 QEMU_OPTION_s,
4261 QEMU_OPTION_p,
4262 QEMU_OPTION_d,
4263 QEMU_OPTION_hdachs,
4264 QEMU_OPTION_L,
4265 QEMU_OPTION_bios,
4266 QEMU_OPTION_kernel_kqemu,
4267 QEMU_OPTION_no_kqemu,
4268 QEMU_OPTION_enable_kvm,
4269 QEMU_OPTION_enable_nesting,
4270 QEMU_OPTION_no_kvm,
4271 QEMU_OPTION_no_kvm_irqchip,
4272 QEMU_OPTION_no_kvm_pit,
4273 QEMU_OPTION_no_kvm_pit_reinjection,
4274 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4275 QEMU_OPTION_pcidevice,
4276 #endif
4277 QEMU_OPTION_no_reboot,
4278 QEMU_OPTION_no_shutdown,
4279 QEMU_OPTION_loadvm,
4280 QEMU_OPTION_daemonize,
4281 QEMU_OPTION_option_rom,
4282 QEMU_OPTION_cpu_vendor,
4283 QEMU_OPTION_nvram,
4284 QEMU_OPTION_prom_env,
4285 QEMU_OPTION_clock,
4286 QEMU_OPTION_localtime,
4287 QEMU_OPTION_startdate,
4288 QEMU_OPTION_icount,
4289 QEMU_OPTION_echr,
4290 QEMU_OPTION_virtiocon,
4291 QEMU_OPTION_show_cursor,
4292 QEMU_OPTION_semihosting,
4293 QEMU_OPTION_old_param,
4294 QEMU_OPTION_tb_size,
4295 QEMU_OPTION_incoming,
4296 QEMU_OPTION_tdf,
4297 QEMU_OPTION_kvm_shadow_memory,
4298 QEMU_OPTION_mempath,
4299 #ifdef MAP_POPULATE
4300 QEMU_OPTION_mem_prealloc,
4301 #endif
4304 typedef struct QEMUOption {
4305 const char *name;
4306 int flags;
4307 int index;
4308 } QEMUOption;
4310 static const QEMUOption qemu_options[] = {
4311 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4312 qemu-doc.texi */
4313 /* Standard options: */
4314 { "h", 0, QEMU_OPTION_h },
4315 { "help", 0, QEMU_OPTION_h },
4316 { "M", HAS_ARG, QEMU_OPTION_M },
4317 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4318 { "smp", HAS_ARG, QEMU_OPTION_smp },
4319 { "fda", HAS_ARG, QEMU_OPTION_fda },
4320 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4321 { "hda", HAS_ARG, QEMU_OPTION_hda },
4322 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4323 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4324 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4325 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4326 { "drive", HAS_ARG, QEMU_OPTION_drive },
4327 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4328 { "sd", HAS_ARG, QEMU_OPTION_sd },
4329 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4330 { "boot", HAS_ARG, QEMU_OPTION_boot },
4331 { "snapshot", 0, QEMU_OPTION_snapshot },
4332 { "m", HAS_ARG, QEMU_OPTION_m },
4333 #ifndef _WIN32
4334 { "k", HAS_ARG, QEMU_OPTION_k },
4335 #endif
4336 #ifdef HAS_AUDIO
4337 { "audio-help", 0, QEMU_OPTION_audio_help },
4338 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4339 #endif
4340 { "usb", 0, QEMU_OPTION_usb },
4341 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4342 { "name", HAS_ARG, QEMU_OPTION_name },
4343 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4345 /* Display options: */
4346 { "nographic", 0, QEMU_OPTION_nographic },
4347 #ifdef CONFIG_CURSES
4348 { "curses", 0, QEMU_OPTION_curses },
4349 #endif
4350 #ifdef CONFIG_SDL
4351 { "no-frame", 0, QEMU_OPTION_no_frame },
4352 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4353 { "no-quit", 0, QEMU_OPTION_no_quit },
4354 { "sdl", 0, QEMU_OPTION_sdl },
4355 #endif
4356 { "portrait", 0, QEMU_OPTION_portrait },
4357 { "vga", HAS_ARG, QEMU_OPTION_vga },
4358 { "full-screen", 0, QEMU_OPTION_full_screen },
4359 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4360 { "g", 1, QEMU_OPTION_g },
4361 #endif
4362 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4364 /* Network options: */
4365 { "net", HAS_ARG, QEMU_OPTION_net},
4366 #ifdef CONFIG_SLIRP
4367 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4368 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4369 #ifndef _WIN32
4370 { "smb", HAS_ARG, QEMU_OPTION_smb },
4371 #endif
4372 { "redir", HAS_ARG, QEMU_OPTION_redir },
4373 #endif
4374 { "bt", HAS_ARG, QEMU_OPTION_bt },
4375 #ifdef TARGET_I386
4376 /* i386 target only: */
4377 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4378 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4379 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4380 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4381 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4382 #endif
4384 /* Linux boot specific: */
4385 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4386 { "append", HAS_ARG, QEMU_OPTION_append },
4387 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4389 /* Debug/Expert options: */
4390 { "serial", HAS_ARG, QEMU_OPTION_serial },
4391 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4392 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4393 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4394 { "S", 0, QEMU_OPTION_S },
4395 { "s", 0, QEMU_OPTION_s },
4396 { "p", HAS_ARG, QEMU_OPTION_p },
4397 { "d", HAS_ARG, QEMU_OPTION_d },
4398 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4399 { "L", HAS_ARG, QEMU_OPTION_L },
4400 { "bios", HAS_ARG, QEMU_OPTION_bios },
4401 #ifdef USE_KQEMU
4402 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4403 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4404 #endif
4405 #ifdef CONFIG_KVM
4406 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4407 #endif
4408 #ifdef USE_KVM
4409 #ifndef NO_CPU_EMULATION
4410 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4411 #endif
4412 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4413 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4414 { "no-kvm-pit-reinjection", 0, QEMU_OPTION_no_kvm_pit_reinjection },
4415 { "enable-nesting", 0, QEMU_OPTION_enable_nesting },
4416 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4417 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4418 #endif
4419 #endif
4420 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4421 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4422 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4423 { "daemonize", 0, QEMU_OPTION_daemonize },
4424 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4425 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4426 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4427 #endif
4428 { "clock", HAS_ARG, QEMU_OPTION_clock },
4429 { "localtime", 0, QEMU_OPTION_localtime },
4430 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4431 { "icount", HAS_ARG, QEMU_OPTION_icount },
4432 { "echr", HAS_ARG, QEMU_OPTION_echr },
4433 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4434 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4435 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4436 { "semihosting", 0, QEMU_OPTION_semihosting },
4437 #endif
4438 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4439 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4440 { "nvram", HAS_ARG, QEMU_OPTION_nvram },
4441 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4442 #if defined(TARGET_ARM)
4443 { "old-param", 0, QEMU_OPTION_old_param },
4444 #endif
4445 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4446 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4447 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4448 #ifdef MAP_POPULATE
4449 { "mem-prealloc", 0, QEMU_OPTION_mem_prealloc },
4450 #endif
4451 { NULL },
4454 /* password input */
4456 int qemu_key_check(BlockDriverState *bs, const char *name)
4458 char password[256];
4459 int i;
4461 if (!bdrv_is_encrypted(bs))
4462 return 0;
4464 term_printf("%s is encrypted.\n", name);
4465 for(i = 0; i < 3; i++) {
4466 monitor_readline("Password: ", 1, password, sizeof(password));
4467 if (bdrv_set_key(bs, password) == 0)
4468 return 0;
4469 term_printf("invalid password\n");
4471 return -EPERM;
4474 static BlockDriverState *get_bdrv(int index)
4476 if (index > nb_drives)
4477 return NULL;
4478 return drives_table[index].bdrv;
4481 static void read_passwords(void)
4483 BlockDriverState *bs;
4484 int i;
4486 for(i = 0; i < 6; i++) {
4487 bs = get_bdrv(i);
4488 if (bs)
4489 qemu_key_check(bs, bdrv_get_device_name(bs));
4493 #ifdef HAS_AUDIO
4494 struct soundhw soundhw[] = {
4495 #ifdef HAS_AUDIO_CHOICE
4496 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4498 "pcspk",
4499 "PC speaker",
4502 { .init_isa = pcspk_audio_init }
4504 #endif
4506 #ifdef CONFIG_SB16
4508 "sb16",
4509 "Creative Sound Blaster 16",
4512 { .init_isa = SB16_init }
4514 #endif
4516 #ifdef CONFIG_CS4231A
4518 "cs4231a",
4519 "CS4231A",
4522 { .init_isa = cs4231a_init }
4524 #endif
4526 #ifdef CONFIG_ADLIB
4528 "adlib",
4529 #ifdef HAS_YMF262
4530 "Yamaha YMF262 (OPL3)",
4531 #else
4532 "Yamaha YM3812 (OPL2)",
4533 #endif
4536 { .init_isa = Adlib_init }
4538 #endif
4540 #ifdef CONFIG_GUS
4542 "gus",
4543 "Gravis Ultrasound GF1",
4546 { .init_isa = GUS_init }
4548 #endif
4550 #ifdef CONFIG_AC97
4552 "ac97",
4553 "Intel 82801AA AC97 Audio",
4556 { .init_pci = ac97_init }
4558 #endif
4560 #ifdef CONFIG_ES1370
4562 "es1370",
4563 "ENSONIQ AudioPCI ES1370",
4566 { .init_pci = es1370_init }
4568 #endif
4570 #endif /* HAS_AUDIO_CHOICE */
4572 { NULL, NULL, 0, 0, { NULL } }
4575 static void select_soundhw (const char *optarg)
4577 struct soundhw *c;
4579 if (*optarg == '?') {
4580 show_valid_cards:
4582 printf ("Valid sound card names (comma separated):\n");
4583 for (c = soundhw; c->name; ++c) {
4584 printf ("%-11s %s\n", c->name, c->descr);
4586 printf ("\n-soundhw all will enable all of the above\n");
4587 exit (*optarg != '?');
4589 else {
4590 size_t l;
4591 const char *p;
4592 char *e;
4593 int bad_card = 0;
4595 if (!strcmp (optarg, "all")) {
4596 for (c = soundhw; c->name; ++c) {
4597 c->enabled = 1;
4599 return;
4602 p = optarg;
4603 while (*p) {
4604 e = strchr (p, ',');
4605 l = !e ? strlen (p) : (size_t) (e - p);
4607 for (c = soundhw; c->name; ++c) {
4608 if (!strncmp (c->name, p, l)) {
4609 c->enabled = 1;
4610 break;
4614 if (!c->name) {
4615 if (l > 80) {
4616 fprintf (stderr,
4617 "Unknown sound card name (too big to show)\n");
4619 else {
4620 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4621 (int) l, p);
4623 bad_card = 1;
4625 p += l + (e != NULL);
4628 if (bad_card)
4629 goto show_valid_cards;
4632 #endif
4634 static void select_vgahw (const char *p)
4636 const char *opts;
4638 if (strstart(p, "std", &opts)) {
4639 std_vga_enabled = 1;
4640 cirrus_vga_enabled = 0;
4641 vmsvga_enabled = 0;
4642 } else if (strstart(p, "cirrus", &opts)) {
4643 cirrus_vga_enabled = 1;
4644 std_vga_enabled = 0;
4645 vmsvga_enabled = 0;
4646 } else if (strstart(p, "vmware", &opts)) {
4647 cirrus_vga_enabled = 0;
4648 std_vga_enabled = 0;
4649 vmsvga_enabled = 1;
4650 } else if (strstart(p, "none", &opts)) {
4651 cirrus_vga_enabled = 0;
4652 std_vga_enabled = 0;
4653 vmsvga_enabled = 0;
4654 } else {
4655 invalid_vga:
4656 fprintf(stderr, "Unknown vga type: %s\n", p);
4657 exit(1);
4659 while (*opts) {
4660 const char *nextopt;
4662 if (strstart(opts, ",retrace=", &nextopt)) {
4663 opts = nextopt;
4664 if (strstart(opts, "dumb", &nextopt))
4665 vga_retrace_method = VGA_RETRACE_DUMB;
4666 else if (strstart(opts, "precise", &nextopt))
4667 vga_retrace_method = VGA_RETRACE_PRECISE;
4668 else goto invalid_vga;
4669 } else goto invalid_vga;
4670 opts = nextopt;
4674 #ifdef _WIN32
4675 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4677 exit(STATUS_CONTROL_C_EXIT);
4678 return TRUE;
4680 #endif
4682 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4684 int ret;
4686 if(strlen(str) != 36)
4687 return -1;
4689 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4690 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4691 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4693 if(ret != 16)
4694 return -1;
4696 return 0;
4699 #define MAX_NET_CLIENTS 32
4701 static int saved_argc;
4702 static char **saved_argv;
4704 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4706 *argc = saved_argc;
4707 *argv = saved_argv;
4708 *opt_daemonize = daemonize;
4709 *opt_incoming = incoming;
4713 static int gethugepagesize(void)
4715 int ret, fd;
4716 char buf[4096];
4717 const char *needle = "Hugepagesize:";
4718 char *size;
4719 unsigned long hugepagesize;
4721 fd = open("/proc/meminfo", O_RDONLY);
4722 if (fd < 0) {
4723 perror("open");
4724 exit(0);
4727 ret = read(fd, buf, sizeof(buf));
4728 if (ret < 0) {
4729 perror("read");
4730 exit(0);
4733 size = strstr(buf, needle);
4734 if (!size)
4735 return 0;
4736 size += strlen(needle);
4737 hugepagesize = strtol(size, NULL, 0);
4738 return hugepagesize;
4741 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4743 char *filename;
4744 void *area;
4745 int fd;
4746 #ifdef MAP_POPULATE
4747 int flags;
4748 #endif
4750 if (!kvm_has_sync_mmu()) {
4751 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4752 return NULL;
4755 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4756 return NULL;
4758 hpagesize = gethugepagesize() * 1024;
4759 if (!hpagesize)
4760 return NULL;
4762 fd = mkstemp(filename);
4763 if (fd < 0) {
4764 perror("mkstemp");
4765 free(filename);
4766 return NULL;
4768 unlink(filename);
4769 free(filename);
4771 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4774 * ftruncate is not supported by hugetlbfs in older
4775 * hosts, so don't bother checking for errors.
4776 * If anything goes wrong with it under other filesystems,
4777 * mmap will fail.
4779 ftruncate(fd, memory);
4781 #ifdef MAP_POPULATE
4782 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4783 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4784 * to sidestep this quirk.
4786 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4787 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4788 #else
4789 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4790 #endif
4791 if (area == MAP_FAILED) {
4792 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4793 close(fd);
4794 return (NULL);
4796 *len = memory;
4797 return area;
4800 static void *qemu_alloc_physram(unsigned long memory)
4802 void *area = NULL;
4803 unsigned long map_len = memory;
4805 #ifdef USE_KVM
4806 if (mem_path)
4807 area = alloc_mem_area(memory, &map_len, mem_path);
4808 #endif
4809 if (!area)
4810 area = qemu_vmalloc(memory);
4811 #ifdef USE_KVM
4812 if (kvm_setup_guest_memory(area, map_len))
4813 area = NULL;
4814 #endif
4815 return area;
4818 #ifndef _WIN32
4820 static void termsig_handler(int signal)
4822 qemu_system_shutdown_request();
4825 static void termsig_setup(void)
4827 struct sigaction act;
4829 memset(&act, 0, sizeof(act));
4830 act.sa_handler = termsig_handler;
4831 sigaction(SIGINT, &act, NULL);
4832 sigaction(SIGHUP, &act, NULL);
4833 sigaction(SIGTERM, &act, NULL);
4836 #endif
4838 int main(int argc, char **argv, char **envp)
4840 #ifdef CONFIG_GDBSTUB
4841 int use_gdbstub;
4842 const char *gdbstub_port;
4843 #endif
4844 uint32_t boot_devices_bitmap = 0;
4845 int i;
4846 int snapshot, linux_boot, net_boot;
4847 const char *initrd_filename;
4848 const char *kernel_filename, *kernel_cmdline;
4849 const char *boot_devices = "";
4850 DisplayState *ds;
4851 DisplayChangeListener *dcl;
4852 int cyls, heads, secs, translation;
4853 const char *net_clients[MAX_NET_CLIENTS];
4854 int nb_net_clients;
4855 const char *bt_opts[MAX_BT_CMDLINE];
4856 int nb_bt_opts;
4857 int hda_index;
4858 int optind;
4859 const char *r, *optarg;
4860 CharDriverState *monitor_hd = NULL;
4861 const char *monitor_device;
4862 const char *serial_devices[MAX_SERIAL_PORTS];
4863 int serial_device_index;
4864 const char *parallel_devices[MAX_PARALLEL_PORTS];
4865 int parallel_device_index;
4866 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4867 int virtio_console_index;
4868 const char *loadvm = NULL;
4869 QEMUMachine *machine;
4870 const char *cpu_model;
4871 const char *usb_devices[MAX_USB_CMDLINE];
4872 int usb_devices_index;
4873 int fds[2];
4874 int tb_size;
4875 const char *pid_file = NULL;
4876 int autostart;
4877 const char *incoming = NULL;
4879 qemu_cache_utils_init(envp);
4881 LIST_INIT (&vm_change_state_head);
4882 #ifndef _WIN32
4884 struct sigaction act;
4885 sigfillset(&act.sa_mask);
4886 act.sa_flags = 0;
4887 act.sa_handler = SIG_IGN;
4888 sigaction(SIGPIPE, &act, NULL);
4890 #else
4891 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4892 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4893 QEMU to run on a single CPU */
4895 HANDLE h;
4896 DWORD mask, smask;
4897 int i;
4898 h = GetCurrentProcess();
4899 if (GetProcessAffinityMask(h, &mask, &smask)) {
4900 for(i = 0; i < 32; i++) {
4901 if (mask & (1 << i))
4902 break;
4904 if (i != 32) {
4905 mask = 1 << i;
4906 SetProcessAffinityMask(h, mask);
4910 #endif
4912 register_machines();
4913 machine = first_machine;
4914 cpu_model = NULL;
4915 initrd_filename = NULL;
4916 ram_size = 0;
4917 vga_ram_size = VGA_RAM_SIZE;
4918 #ifdef CONFIG_GDBSTUB
4919 use_gdbstub = 0;
4920 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4921 #endif
4922 snapshot = 0;
4923 nographic = 0;
4924 curses = 0;
4925 kernel_filename = NULL;
4926 kernel_cmdline = "";
4927 cyls = heads = secs = 0;
4928 translation = BIOS_ATA_TRANSLATION_AUTO;
4929 monitor_device = "vc";
4931 serial_devices[0] = "vc:80Cx24C";
4932 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4933 serial_devices[i] = NULL;
4934 serial_device_index = 0;
4936 parallel_devices[0] = "vc:640x480";
4937 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4938 parallel_devices[i] = NULL;
4939 parallel_device_index = 0;
4941 virtio_consoles[0] = "vc:80Cx24C";
4942 for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4943 virtio_consoles[i] = NULL;
4944 virtio_console_index = 0;
4946 usb_devices_index = 0;
4947 assigned_devices_index = 0;
4949 nb_net_clients = 0;
4950 nb_bt_opts = 0;
4951 nb_drives = 0;
4952 nb_drives_opt = 0;
4953 hda_index = -1;
4955 nb_nics = 0;
4957 tb_size = 0;
4958 autostart= 1;
4960 optind = 1;
4961 for(;;) {
4962 if (optind >= argc)
4963 break;
4964 r = argv[optind];
4965 if (r[0] != '-') {
4966 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4967 } else {
4968 const QEMUOption *popt;
4970 optind++;
4971 /* Treat --foo the same as -foo. */
4972 if (r[1] == '-')
4973 r++;
4974 popt = qemu_options;
4975 for(;;) {
4976 if (!popt->name) {
4977 fprintf(stderr, "%s: invalid option -- '%s'\n",
4978 argv[0], r);
4979 exit(1);
4981 if (!strcmp(popt->name, r + 1))
4982 break;
4983 popt++;
4985 if (popt->flags & HAS_ARG) {
4986 if (optind >= argc) {
4987 fprintf(stderr, "%s: option '%s' requires an argument\n",
4988 argv[0], r);
4989 exit(1);
4991 optarg = argv[optind++];
4992 } else {
4993 optarg = NULL;
4996 switch(popt->index) {
4997 case QEMU_OPTION_M:
4998 machine = find_machine(optarg);
4999 if (!machine) {
5000 QEMUMachine *m;
5001 printf("Supported machines are:\n");
5002 for(m = first_machine; m != NULL; m = m->next) {
5003 printf("%-10s %s%s\n",
5004 m->name, m->desc,
5005 m == first_machine ? " (default)" : "");
5007 exit(*optarg != '?');
5009 break;
5010 case QEMU_OPTION_cpu:
5011 /* hw initialization will check this */
5012 if (*optarg == '?') {
5013 /* XXX: implement xxx_cpu_list for targets that still miss it */
5014 #if defined(cpu_list)
5015 cpu_list(stdout, &fprintf);
5016 #endif
5017 exit(0);
5018 } else {
5019 cpu_model = optarg;
5021 break;
5022 case QEMU_OPTION_initrd:
5023 initrd_filename = optarg;
5024 break;
5025 case QEMU_OPTION_hda:
5026 if (cyls == 0)
5027 hda_index = drive_add(optarg, HD_ALIAS, 0);
5028 else
5029 hda_index = drive_add(optarg, HD_ALIAS
5030 ",cyls=%d,heads=%d,secs=%d%s",
5031 0, cyls, heads, secs,
5032 translation == BIOS_ATA_TRANSLATION_LBA ?
5033 ",trans=lba" :
5034 translation == BIOS_ATA_TRANSLATION_NONE ?
5035 ",trans=none" : "");
5036 break;
5037 case QEMU_OPTION_hdb:
5038 case QEMU_OPTION_hdc:
5039 case QEMU_OPTION_hdd:
5040 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5041 break;
5042 case QEMU_OPTION_drive:
5043 drive_add(NULL, "%s", optarg);
5044 break;
5045 case QEMU_OPTION_mtdblock:
5046 drive_add(optarg, MTD_ALIAS);
5047 break;
5048 case QEMU_OPTION_sd:
5049 drive_add(optarg, SD_ALIAS);
5050 break;
5051 case QEMU_OPTION_pflash:
5052 drive_add(optarg, PFLASH_ALIAS);
5053 break;
5054 case QEMU_OPTION_snapshot:
5055 snapshot = 1;
5056 break;
5057 case QEMU_OPTION_hdachs:
5059 const char *p;
5060 p = optarg;
5061 cyls = strtol(p, (char **)&p, 0);
5062 if (cyls < 1 || cyls > 16383)
5063 goto chs_fail;
5064 if (*p != ',')
5065 goto chs_fail;
5066 p++;
5067 heads = strtol(p, (char **)&p, 0);
5068 if (heads < 1 || heads > 16)
5069 goto chs_fail;
5070 if (*p != ',')
5071 goto chs_fail;
5072 p++;
5073 secs = strtol(p, (char **)&p, 0);
5074 if (secs < 1 || secs > 63)
5075 goto chs_fail;
5076 if (*p == ',') {
5077 p++;
5078 if (!strcmp(p, "none"))
5079 translation = BIOS_ATA_TRANSLATION_NONE;
5080 else if (!strcmp(p, "lba"))
5081 translation = BIOS_ATA_TRANSLATION_LBA;
5082 else if (!strcmp(p, "auto"))
5083 translation = BIOS_ATA_TRANSLATION_AUTO;
5084 else
5085 goto chs_fail;
5086 } else if (*p != '\0') {
5087 chs_fail:
5088 fprintf(stderr, "qemu: invalid physical CHS format\n");
5089 exit(1);
5091 if (hda_index != -1)
5092 snprintf(drives_opt[hda_index].opt,
5093 sizeof(drives_opt[hda_index].opt),
5094 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5095 0, cyls, heads, secs,
5096 translation == BIOS_ATA_TRANSLATION_LBA ?
5097 ",trans=lba" :
5098 translation == BIOS_ATA_TRANSLATION_NONE ?
5099 ",trans=none" : "");
5101 break;
5102 case QEMU_OPTION_nographic:
5103 nographic = 1;
5104 break;
5105 #ifdef CONFIG_CURSES
5106 case QEMU_OPTION_curses:
5107 curses = 1;
5108 break;
5109 #endif
5110 case QEMU_OPTION_portrait:
5111 graphic_rotate = 1;
5112 break;
5113 case QEMU_OPTION_kernel:
5114 kernel_filename = optarg;
5115 break;
5116 case QEMU_OPTION_append:
5117 kernel_cmdline = optarg;
5118 break;
5119 case QEMU_OPTION_cdrom:
5120 drive_add(optarg, CDROM_ALIAS);
5121 break;
5122 case QEMU_OPTION_boot:
5123 boot_devices = optarg;
5124 /* We just do some generic consistency checks */
5126 /* Could easily be extended to 64 devices if needed */
5127 const char *p;
5129 boot_devices_bitmap = 0;
5130 for (p = boot_devices; *p != '\0'; p++) {
5131 /* Allowed boot devices are:
5132 * a b : floppy disk drives
5133 * c ... f : IDE disk drives
5134 * g ... m : machine implementation dependant drives
5135 * n ... p : network devices
5136 * It's up to each machine implementation to check
5137 * if the given boot devices match the actual hardware
5138 * implementation and firmware features.
5140 if (*p < 'a' || *p > 'q') {
5141 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5142 exit(1);
5144 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5145 fprintf(stderr,
5146 "Boot device '%c' was given twice\n",*p);
5147 exit(1);
5149 boot_devices_bitmap |= 1 << (*p - 'a');
5152 break;
5153 case QEMU_OPTION_fda:
5154 case QEMU_OPTION_fdb:
5155 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5156 break;
5157 #ifdef TARGET_I386
5158 case QEMU_OPTION_no_fd_bootchk:
5159 fd_bootchk = 0;
5160 break;
5161 #endif
5162 case QEMU_OPTION_net:
5163 if (nb_net_clients >= MAX_NET_CLIENTS) {
5164 fprintf(stderr, "qemu: too many network clients\n");
5165 exit(1);
5167 net_clients[nb_net_clients] = optarg;
5168 nb_net_clients++;
5169 break;
5170 #ifdef CONFIG_SLIRP
5171 case QEMU_OPTION_tftp:
5172 tftp_prefix = optarg;
5173 break;
5174 case QEMU_OPTION_bootp:
5175 bootp_filename = optarg;
5176 break;
5177 #ifndef _WIN32
5178 case QEMU_OPTION_smb:
5179 net_slirp_smb(optarg);
5180 break;
5181 #endif
5182 case QEMU_OPTION_redir:
5183 net_slirp_redir(optarg);
5184 break;
5185 #endif
5186 case QEMU_OPTION_bt:
5187 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5188 fprintf(stderr, "qemu: too many bluetooth options\n");
5189 exit(1);
5191 bt_opts[nb_bt_opts++] = optarg;
5192 break;
5193 #ifdef HAS_AUDIO
5194 case QEMU_OPTION_audio_help:
5195 AUD_help ();
5196 exit (0);
5197 break;
5198 case QEMU_OPTION_soundhw:
5199 select_soundhw (optarg);
5200 break;
5201 #endif
5202 case QEMU_OPTION_h:
5203 help(0);
5204 break;
5205 case QEMU_OPTION_m: {
5206 uint64_t value;
5207 char *ptr;
5209 value = strtoul(optarg, &ptr, 10);
5210 switch (*ptr) {
5211 case 0: case 'M': case 'm':
5212 value <<= 20;
5213 break;
5214 case 'G': case 'g':
5215 value <<= 30;
5216 break;
5217 default:
5218 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5219 exit(1);
5222 /* On 32-bit hosts, QEMU is limited by virtual address space */
5223 if (value > (2047 << 20)
5224 #ifndef USE_KQEMU
5225 && HOST_LONG_BITS == 32
5226 #endif
5228 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5229 exit(1);
5231 if (value != (uint64_t)(ram_addr_t)value) {
5232 fprintf(stderr, "qemu: ram size too large\n");
5233 exit(1);
5235 ram_size = value;
5236 break;
5238 case QEMU_OPTION_d:
5240 int mask;
5241 const CPULogItem *item;
5243 mask = cpu_str_to_log_mask(optarg);
5244 if (!mask) {
5245 printf("Log items (comma separated):\n");
5246 for(item = cpu_log_items; item->mask != 0; item++) {
5247 printf("%-10s %s\n", item->name, item->help);
5249 exit(1);
5251 cpu_set_log(mask);
5253 break;
5254 #ifdef CONFIG_GDBSTUB
5255 case QEMU_OPTION_s:
5256 use_gdbstub = 1;
5257 break;
5258 case QEMU_OPTION_p:
5259 gdbstub_port = optarg;
5260 break;
5261 #endif
5262 case QEMU_OPTION_L:
5263 bios_dir = optarg;
5264 break;
5265 case QEMU_OPTION_bios:
5266 bios_name = optarg;
5267 break;
5268 case QEMU_OPTION_S:
5269 autostart = 0;
5270 break;
5271 case QEMU_OPTION_k:
5272 keyboard_layout = optarg;
5273 break;
5274 case QEMU_OPTION_localtime:
5275 rtc_utc = 0;
5276 break;
5277 case QEMU_OPTION_vga:
5278 select_vgahw (optarg);
5279 break;
5280 case QEMU_OPTION_g:
5282 const char *p;
5283 int w, h, depth;
5284 p = optarg;
5285 w = strtol(p, (char **)&p, 10);
5286 if (w <= 0) {
5287 graphic_error:
5288 fprintf(stderr, "qemu: invalid resolution or depth\n");
5289 exit(1);
5291 if (*p != 'x')
5292 goto graphic_error;
5293 p++;
5294 h = strtol(p, (char **)&p, 10);
5295 if (h <= 0)
5296 goto graphic_error;
5297 if (*p == 'x') {
5298 p++;
5299 depth = strtol(p, (char **)&p, 10);
5300 if (depth != 8 && depth != 15 && depth != 16 &&
5301 depth != 24 && depth != 32)
5302 goto graphic_error;
5303 } else if (*p == '\0') {
5304 depth = graphic_depth;
5305 } else {
5306 goto graphic_error;
5309 graphic_width = w;
5310 graphic_height = h;
5311 graphic_depth = depth;
5313 break;
5314 case QEMU_OPTION_echr:
5316 char *r;
5317 term_escape_char = strtol(optarg, &r, 0);
5318 if (r == optarg)
5319 printf("Bad argument to echr\n");
5320 break;
5322 case QEMU_OPTION_monitor:
5323 monitor_device = optarg;
5324 break;
5325 case QEMU_OPTION_serial:
5326 if (serial_device_index >= MAX_SERIAL_PORTS) {
5327 fprintf(stderr, "qemu: too many serial ports\n");
5328 exit(1);
5330 serial_devices[serial_device_index] = optarg;
5331 serial_device_index++;
5332 break;
5333 case QEMU_OPTION_virtiocon:
5334 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5335 fprintf(stderr, "qemu: too many virtio consoles\n");
5336 exit(1);
5338 virtio_consoles[virtio_console_index] = optarg;
5339 virtio_console_index++;
5340 break;
5341 case QEMU_OPTION_parallel:
5342 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5343 fprintf(stderr, "qemu: too many parallel ports\n");
5344 exit(1);
5346 parallel_devices[parallel_device_index] = optarg;
5347 parallel_device_index++;
5348 break;
5349 case QEMU_OPTION_loadvm:
5350 loadvm = optarg;
5351 break;
5352 case QEMU_OPTION_full_screen:
5353 full_screen = 1;
5354 break;
5355 #ifdef CONFIG_SDL
5356 case QEMU_OPTION_no_frame:
5357 no_frame = 1;
5358 break;
5359 case QEMU_OPTION_alt_grab:
5360 alt_grab = 1;
5361 break;
5362 case QEMU_OPTION_no_quit:
5363 no_quit = 1;
5364 break;
5365 case QEMU_OPTION_sdl:
5366 sdl = 1;
5367 break;
5368 #endif
5369 case QEMU_OPTION_pidfile:
5370 pid_file = optarg;
5371 break;
5372 #ifdef TARGET_I386
5373 case QEMU_OPTION_win2k_hack:
5374 win2k_install_hack = 1;
5375 break;
5376 case QEMU_OPTION_rtc_td_hack:
5377 rtc_td_hack = 1;
5378 break;
5379 #endif
5380 #ifdef USE_KQEMU
5381 case QEMU_OPTION_no_kqemu:
5382 kqemu_allowed = 0;
5383 break;
5384 case QEMU_OPTION_kernel_kqemu:
5385 kqemu_allowed = 2;
5386 break;
5387 #endif
5388 #ifdef CONFIG_KVM
5389 case QEMU_OPTION_enable_kvm:
5390 kvm_allowed = 1;
5391 #ifdef USE_KQEMU
5392 kqemu_allowed = 0;
5393 #endif
5394 break;
5395 #endif
5396 #ifdef USE_KVM
5397 case QEMU_OPTION_no_kvm:
5398 kvm_allowed = 0;
5399 break;
5400 case QEMU_OPTION_no_kvm_irqchip: {
5401 kvm_irqchip = 0;
5402 kvm_pit = 0;
5403 break;
5405 case QEMU_OPTION_no_kvm_pit: {
5406 kvm_pit = 0;
5407 break;
5409 case QEMU_OPTION_no_kvm_pit_reinjection: {
5410 kvm_pit_reinject = 0;
5411 break;
5413 case QEMU_OPTION_enable_nesting: {
5414 kvm_nested = 1;
5415 break;
5417 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5418 case QEMU_OPTION_pcidevice:
5419 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5420 fprintf(stderr, "Too many assigned devices\n");
5421 exit(1);
5423 assigned_devices[assigned_devices_index] = optarg;
5424 assigned_devices_index++;
5425 break;
5426 #endif
5427 #endif
5428 case QEMU_OPTION_usb:
5429 usb_enabled = 1;
5430 break;
5431 case QEMU_OPTION_usbdevice:
5432 usb_enabled = 1;
5433 if (usb_devices_index >= MAX_USB_CMDLINE) {
5434 fprintf(stderr, "Too many USB devices\n");
5435 exit(1);
5437 usb_devices[usb_devices_index] = optarg;
5438 usb_devices_index++;
5439 break;
5440 case QEMU_OPTION_smp:
5441 smp_cpus = atoi(optarg);
5442 if (smp_cpus < 1) {
5443 fprintf(stderr, "Invalid number of CPUs\n");
5444 exit(1);
5446 break;
5447 case QEMU_OPTION_vnc:
5448 vnc_display = optarg;
5449 break;
5450 case QEMU_OPTION_no_acpi:
5451 acpi_enabled = 0;
5452 break;
5453 case QEMU_OPTION_no_hpet:
5454 no_hpet = 1;
5455 break;
5456 case QEMU_OPTION_no_reboot:
5457 no_reboot = 1;
5458 break;
5459 case QEMU_OPTION_no_shutdown:
5460 no_shutdown = 1;
5461 break;
5462 case QEMU_OPTION_show_cursor:
5463 cursor_hide = 0;
5464 break;
5465 case QEMU_OPTION_uuid:
5466 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5467 fprintf(stderr, "Fail to parse UUID string."
5468 " Wrong format.\n");
5469 exit(1);
5471 break;
5472 case QEMU_OPTION_daemonize:
5473 daemonize = 1;
5474 break;
5475 case QEMU_OPTION_option_rom:
5476 if (nb_option_roms >= MAX_OPTION_ROMS) {
5477 fprintf(stderr, "Too many option ROMs\n");
5478 exit(1);
5480 option_rom[nb_option_roms] = optarg;
5481 nb_option_roms++;
5482 break;
5483 case QEMU_OPTION_semihosting:
5484 semihosting_enabled = 1;
5485 break;
5486 case QEMU_OPTION_tdf:
5487 time_drift_fix = 1;
5488 break;
5489 case QEMU_OPTION_kvm_shadow_memory:
5490 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5491 break;
5492 case QEMU_OPTION_mempath:
5493 mem_path = optarg;
5494 break;
5495 #ifdef MAP_POPULATE
5496 case QEMU_OPTION_mem_prealloc:
5497 mem_prealloc = !mem_prealloc;
5498 break;
5499 #endif
5500 case QEMU_OPTION_name:
5501 qemu_name = optarg;
5502 break;
5503 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5504 case QEMU_OPTION_prom_env:
5505 if (nb_prom_envs >= MAX_PROM_ENVS) {
5506 fprintf(stderr, "Too many prom variables\n");
5507 exit(1);
5509 prom_envs[nb_prom_envs] = optarg;
5510 nb_prom_envs++;
5511 break;
5512 #endif
5513 case QEMU_OPTION_cpu_vendor:
5514 cpu_vendor_string = optarg;
5515 break;
5516 #ifdef TARGET_ARM
5517 case QEMU_OPTION_old_param:
5518 old_param = 1;
5519 break;
5520 #endif
5521 case QEMU_OPTION_clock:
5522 configure_alarms(optarg);
5523 break;
5524 case QEMU_OPTION_startdate:
5526 struct tm tm;
5527 time_t rtc_start_date;
5528 if (!strcmp(optarg, "now")) {
5529 rtc_date_offset = -1;
5530 } else {
5531 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5532 &tm.tm_year,
5533 &tm.tm_mon,
5534 &tm.tm_mday,
5535 &tm.tm_hour,
5536 &tm.tm_min,
5537 &tm.tm_sec) == 6) {
5538 /* OK */
5539 } else if (sscanf(optarg, "%d-%d-%d",
5540 &tm.tm_year,
5541 &tm.tm_mon,
5542 &tm.tm_mday) == 3) {
5543 tm.tm_hour = 0;
5544 tm.tm_min = 0;
5545 tm.tm_sec = 0;
5546 } else {
5547 goto date_fail;
5549 tm.tm_year -= 1900;
5550 tm.tm_mon--;
5551 rtc_start_date = mktimegm(&tm);
5552 if (rtc_start_date == -1) {
5553 date_fail:
5554 fprintf(stderr, "Invalid date format. Valid format are:\n"
5555 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5556 exit(1);
5558 rtc_date_offset = time(NULL) - rtc_start_date;
5561 break;
5562 case QEMU_OPTION_tb_size:
5563 tb_size = strtol(optarg, NULL, 0);
5564 if (tb_size < 0)
5565 tb_size = 0;
5566 break;
5567 case QEMU_OPTION_icount:
5568 use_icount = 1;
5569 if (strcmp(optarg, "auto") == 0) {
5570 icount_time_shift = -1;
5571 } else {
5572 icount_time_shift = strtol(optarg, NULL, 0);
5574 break;
5575 case QEMU_OPTION_incoming:
5576 incoming = optarg;
5577 break;
5578 case QEMU_OPTION_nvram:
5579 nvram = optarg;
5580 break;
5585 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5586 if (kvm_allowed && kqemu_allowed) {
5587 fprintf(stderr,
5588 "You can not enable both KVM and kqemu at the same time\n");
5589 exit(1);
5591 #endif
5593 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5594 if (smp_cpus > machine->max_cpus) {
5595 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5596 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5597 machine->max_cpus);
5598 exit(1);
5601 if (nographic) {
5602 if (serial_device_index == 0)
5603 serial_devices[0] = "stdio";
5604 if (parallel_device_index == 0)
5605 parallel_devices[0] = "null";
5606 if (strncmp(monitor_device, "vc", 2) == 0)
5607 monitor_device = "stdio";
5608 if (virtio_console_index == 0)
5609 virtio_consoles[0] = "null";
5612 #ifndef _WIN32
5613 if (daemonize) {
5614 pid_t pid;
5616 if (pipe(fds) == -1)
5617 exit(1);
5619 pid = fork();
5620 if (pid > 0) {
5621 uint8_t status;
5622 ssize_t len;
5624 close(fds[1]);
5626 again:
5627 len = read(fds[0], &status, 1);
5628 if (len == -1 && (errno == EINTR))
5629 goto again;
5631 if (len != 1)
5632 exit(1);
5633 else if (status == 1) {
5634 fprintf(stderr, "Could not acquire pidfile\n");
5635 exit(1);
5636 } else
5637 exit(0);
5638 } else if (pid < 0)
5639 exit(1);
5641 setsid();
5643 pid = fork();
5644 if (pid > 0)
5645 exit(0);
5646 else if (pid < 0)
5647 exit(1);
5649 umask(027);
5651 signal(SIGTSTP, SIG_IGN);
5652 signal(SIGTTOU, SIG_IGN);
5653 signal(SIGTTIN, SIG_IGN);
5655 #endif
5657 #if USE_KVM
5658 if (kvm_enabled()) {
5659 if (kvm_qemu_init() < 0) {
5660 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5661 #ifdef NO_CPU_EMULATION
5662 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5663 exit(1);
5664 #endif
5665 kvm_allowed = 0;
5668 #endif
5670 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5671 if (daemonize) {
5672 uint8_t status = 1;
5673 write(fds[1], &status, 1);
5674 } else
5675 fprintf(stderr, "Could not acquire pid file\n");
5676 exit(1);
5679 #ifdef USE_KQEMU
5680 if (smp_cpus > 1)
5681 kqemu_allowed = 0;
5682 #endif
5683 linux_boot = (kernel_filename != NULL);
5684 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5686 if (!linux_boot && net_boot == 0 &&
5687 !machine->nodisk_ok && nb_drives_opt == 0)
5688 help(1);
5690 if (!linux_boot && *kernel_cmdline != '\0') {
5691 fprintf(stderr, "-append only allowed with -kernel option\n");
5692 exit(1);
5695 if (!linux_boot && initrd_filename != NULL) {
5696 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5697 exit(1);
5700 /* boot to floppy or the default cd if no hard disk defined yet */
5701 if (!boot_devices[0]) {
5702 boot_devices = "cad";
5704 setvbuf(stdout, NULL, _IOLBF, 0);
5706 init_timers();
5707 if (init_timer_alarm() < 0) {
5708 fprintf(stderr, "could not initialize alarm timer\n");
5709 exit(1);
5711 if (use_icount && icount_time_shift < 0) {
5712 use_icount = 2;
5713 /* 125MIPS seems a reasonable initial guess at the guest speed.
5714 It will be corrected fairly quickly anyway. */
5715 icount_time_shift = 3;
5716 init_icount_adjust();
5719 #ifdef _WIN32
5720 socket_init();
5721 #endif
5723 /* init network clients */
5724 if (nb_net_clients == 0) {
5725 /* if no clients, we use a default config */
5726 net_clients[nb_net_clients++] = "nic";
5727 #ifdef CONFIG_SLIRP
5728 net_clients[nb_net_clients++] = "user";
5729 #endif
5732 for(i = 0;i < nb_net_clients; i++) {
5733 if (net_client_parse(net_clients[i]) < 0)
5734 exit(1);
5736 net_client_check();
5738 #ifdef TARGET_I386
5739 /* XXX: this should be moved in the PC machine instantiation code */
5740 if (net_boot != 0) {
5741 int netroms = 0;
5742 for (i = 0; i < nb_nics && i < 4; i++) {
5743 const char *model = nd_table[i].model;
5744 char buf[1024];
5745 if (net_boot & (1 << i)) {
5746 if (model == NULL)
5747 model = "rtl8139";
5748 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5749 if (get_image_size(buf) > 0) {
5750 if (nb_option_roms >= MAX_OPTION_ROMS) {
5751 fprintf(stderr, "Too many option ROMs\n");
5752 exit(1);
5754 option_rom[nb_option_roms] = strdup(buf);
5755 nb_option_roms++;
5756 netroms++;
5760 if (netroms == 0) {
5761 fprintf(stderr, "No valid PXE rom found for network device\n");
5762 exit(1);
5765 #endif
5767 /* init the bluetooth world */
5768 for (i = 0; i < nb_bt_opts; i++)
5769 if (bt_parse(bt_opts[i]))
5770 exit(1);
5772 /* init the memory */
5773 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5775 if (machine->ram_require & RAMSIZE_FIXED) {
5776 if (ram_size > 0) {
5777 if (ram_size < phys_ram_size) {
5778 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5779 machine->name, (unsigned long long) phys_ram_size);
5780 exit(-1);
5783 phys_ram_size = ram_size;
5784 } else
5785 ram_size = phys_ram_size;
5786 } else {
5787 if (ram_size == 0)
5788 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5790 phys_ram_size += ram_size;
5793 /* Initialize kvm */
5794 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5795 #define KVM_EXTRA_PAGES 3
5796 #else
5797 #define KVM_EXTRA_PAGES 0
5798 #endif
5799 if (kvm_enabled()) {
5800 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5801 if (kvm_qemu_create_context() < 0) {
5802 fprintf(stderr, "Could not create KVM context\n");
5803 exit(1);
5807 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5808 if (!phys_ram_base) {
5809 fprintf(stderr, "Could not allocate physical memory\n");
5810 exit(1);
5813 /* init the dynamic translator */
5814 cpu_exec_init_all(tb_size * 1024 * 1024);
5816 bdrv_init();
5818 /* we always create the cdrom drive, even if no disk is there */
5820 if (nb_drives_opt < MAX_DRIVES)
5821 drive_add(NULL, CDROM_ALIAS);
5823 /* we always create at least one floppy */
5825 if (nb_drives_opt < MAX_DRIVES)
5826 drive_add(NULL, FD_ALIAS, 0);
5828 /* we always create one sd slot, even if no card is in it */
5830 if (nb_drives_opt < MAX_DRIVES)
5831 drive_add(NULL, SD_ALIAS);
5833 /* open the virtual block devices
5834 * note that migration with device
5835 * hot add/remove is broken.
5837 for(i = 0; i < nb_drives_opt; i++)
5838 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5839 exit(1);
5841 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5842 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5844 #ifndef _WIN32
5845 /* must be after terminal init, SDL library changes signal handlers */
5846 termsig_setup();
5847 #endif
5849 /* Maintain compatibility with multiple stdio monitors */
5850 if (!strcmp(monitor_device,"stdio")) {
5851 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5852 const char *devname = serial_devices[i];
5853 if (devname && !strcmp(devname,"mon:stdio")) {
5854 monitor_device = NULL;
5855 break;
5856 } else if (devname && !strcmp(devname,"stdio")) {
5857 monitor_device = NULL;
5858 serial_devices[i] = "mon:stdio";
5859 break;
5864 #ifdef KVM_UPSTREAM
5865 if (kvm_enabled()) {
5866 int ret;
5868 ret = kvm_init(smp_cpus);
5869 if (ret < 0) {
5870 fprintf(stderr, "failed to initialize KVM\n");
5871 exit(1);
5874 #endif
5876 if (monitor_device) {
5877 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5878 if (!monitor_hd) {
5879 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5880 exit(1);
5884 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5885 const char *devname = serial_devices[i];
5886 if (devname && strcmp(devname, "none")) {
5887 char label[32];
5888 snprintf(label, sizeof(label), "serial%d", i);
5889 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5890 if (!serial_hds[i]) {
5891 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5892 devname);
5893 exit(1);
5898 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5899 const char *devname = parallel_devices[i];
5900 if (devname && strcmp(devname, "none")) {
5901 char label[32];
5902 snprintf(label, sizeof(label), "parallel%d", i);
5903 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5904 if (!parallel_hds[i]) {
5905 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5906 devname);
5907 exit(1);
5912 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5913 const char *devname = virtio_consoles[i];
5914 if (devname && strcmp(devname, "none")) {
5915 char label[32];
5916 snprintf(label, sizeof(label), "virtcon%d", i);
5917 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5918 if (!virtcon_hds[i]) {
5919 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5920 devname);
5921 exit(1);
5926 if (kvm_enabled())
5927 kvm_init_ap();
5929 machine->init(ram_size, vga_ram_size, boot_devices,
5930 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5932 current_machine = machine;
5934 /* Set KVM's vcpu state to qemu's initial CPUState. */
5935 if (kvm_enabled()) {
5936 int ret;
5938 ret = kvm_sync_vcpus();
5939 if (ret < 0) {
5940 fprintf(stderr, "failed to initialize vcpus\n");
5941 exit(1);
5945 /* init USB devices */
5946 if (usb_enabled) {
5947 for(i = 0; i < usb_devices_index; i++) {
5948 if (usb_device_add(usb_devices[i]) < 0) {
5949 fprintf(stderr, "Warning: could not add USB device %s\n",
5950 usb_devices[i]);
5955 if (!display_state)
5956 dumb_display_init();
5957 /* just use the first displaystate for the moment */
5958 ds = display_state;
5959 /* terminal init */
5960 if (nographic) {
5961 if (curses) {
5962 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5963 exit(1);
5965 } else {
5966 #if defined(CONFIG_CURSES)
5967 if (curses) {
5968 /* At the moment curses cannot be used with other displays */
5969 curses_display_init(ds, full_screen);
5970 } else
5971 #endif
5973 if (vnc_display != NULL) {
5974 vnc_display_init(ds);
5975 if (vnc_display_open(ds, vnc_display) < 0)
5976 exit(1);
5978 #if defined(CONFIG_SDL)
5979 if (sdl || !vnc_display)
5980 sdl_display_init(ds, full_screen, no_frame);
5981 #elif defined(CONFIG_COCOA)
5982 if (sdl || !vnc_display)
5983 cocoa_display_init(ds, full_screen);
5984 #endif
5987 dpy_resize(ds);
5989 dcl = ds->listeners;
5990 while (dcl != NULL) {
5991 if (dcl->dpy_refresh != NULL) {
5992 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5993 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5995 dcl = dcl->next;
5998 if (nographic || (vnc_display && !sdl)) {
5999 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6000 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6003 text_consoles_set_display(display_state);
6005 if (monitor_device && monitor_hd)
6006 monitor_init(monitor_hd, !nographic);
6008 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6009 const char *devname = serial_devices[i];
6010 if (devname && strcmp(devname, "none")) {
6011 char label[32];
6012 snprintf(label, sizeof(label), "serial%d", i);
6013 if (strstart(devname, "vc", 0))
6014 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6018 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6019 const char *devname = parallel_devices[i];
6020 if (devname && strcmp(devname, "none")) {
6021 char label[32];
6022 snprintf(label, sizeof(label), "parallel%d", i);
6023 if (strstart(devname, "vc", 0))
6024 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6028 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6029 const char *devname = virtio_consoles[i];
6030 if (virtcon_hds[i] && devname) {
6031 char label[32];
6032 snprintf(label, sizeof(label), "virtcon%d", i);
6033 if (strstart(devname, "vc", 0))
6034 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6038 #ifdef CONFIG_GDBSTUB
6039 if (use_gdbstub) {
6040 /* XXX: use standard host:port notation and modify options
6041 accordingly. */
6042 if (gdbserver_start(gdbstub_port) < 0) {
6043 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6044 gdbstub_port);
6045 exit(1);
6048 #endif
6050 if (loadvm)
6051 do_loadvm(loadvm);
6053 if (incoming) {
6054 autostart = 0; /* fixme how to deal with -daemonize */
6055 qemu_start_incoming_migration(incoming);
6059 /* XXX: simplify init */
6060 read_passwords();
6061 if (autostart) {
6062 vm_start();
6066 if (daemonize) {
6067 uint8_t status = 0;
6068 ssize_t len;
6069 int fd;
6071 again1:
6072 len = write(fds[1], &status, 1);
6073 if (len == -1 && (errno == EINTR))
6074 goto again1;
6076 if (len != 1)
6077 exit(1);
6079 chdir("/");
6080 TFR(fd = open("/dev/null", O_RDWR));
6081 if (fd == -1)
6082 exit(1);
6084 dup2(fd, 0);
6085 dup2(fd, 1);
6086 dup2(fd, 2);
6088 close(fd);
6091 main_loop();
6092 quit_timers();
6093 net_cleanup();
6095 return 0;