Merge commit 'v0.10.3' into stable-0.10
[qemu-kvm/fedora.git] / vl.c
blob3cba8ed1e6fb4ccc8783b24965d9e60dad841432
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 <pwd.h>
58 #include <sys/times.h>
59 #include <sys/wait.h>
60 #include <termios.h>
61 #include <sys/mman.h>
62 #include <sys/ioctl.h>
63 #include <sys/resource.h>
64 #include <sys/socket.h>
65 #include <netinet/in.h>
66 #include <net/if.h>
67 #if defined(__NetBSD__)
68 #include <net/if_tap.h>
69 #endif
70 #ifdef __linux__
71 #include <linux/if_tun.h>
72 #endif
73 #include <arpa/inet.h>
74 #include <dirent.h>
75 #include <netdb.h>
76 #include <sys/select.h>
77 #ifdef _BSD
78 #include <sys/stat.h>
79 #ifdef __FreeBSD__
80 #include <libutil.h>
81 #else
82 #include <util.h>
83 #endif
84 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
85 #include <freebsd/stdlib.h>
86 #else
87 #ifdef __linux__
88 #include <pty.h>
89 #include <malloc.h>
90 #include <linux/rtc.h>
92 /* For the benefit of older linux systems which don't supply it,
93 we use a local copy of hpet.h. */
94 /* #include <linux/hpet.h> */
95 #include "hpet.h"
97 #include <linux/ppdev.h>
98 #include <linux/parport.h>
99 #endif
100 #ifdef __sun__
101 #include <sys/stat.h>
102 #include <sys/ethernet.h>
103 #include <sys/sockio.h>
104 #include <netinet/arp.h>
105 #include <netinet/in.h>
106 #include <netinet/in_systm.h>
107 #include <netinet/ip.h>
108 #include <netinet/ip_icmp.h> // must come after ip.h
109 #include <netinet/udp.h>
110 #include <netinet/tcp.h>
111 #include <net/if.h>
112 #include <syslog.h>
113 #include <stropts.h>
114 #endif
115 #endif
116 #endif
118 #include "qemu_socket.h"
120 #if defined(CONFIG_SLIRP)
121 #include "libslirp.h"
122 #endif
124 #if defined(__OpenBSD__)
125 #include <util.h>
126 #endif
128 #if defined(CONFIG_VDE)
129 #include <libvdeplug.h>
130 #endif
132 #ifdef _WIN32
133 #include <malloc.h>
134 #include <sys/timeb.h>
135 #include <mmsystem.h>
136 #define getopt_long_only getopt_long
137 #define memalign(align, size) malloc(size)
138 #endif
140 #ifdef CONFIG_SDL
141 #ifdef __APPLE__
142 #include <SDL/SDL.h>
143 int qemu_main(int argc, char **argv, char **envp);
144 int main(int argc, char **argv)
146 qemu_main(argc, argv, NULL);
148 #undef main
149 #define main qemu_main
150 #endif
151 #endif /* CONFIG_SDL */
153 #ifdef CONFIG_COCOA
154 #undef main
155 #define main qemu_main
156 #endif /* CONFIG_COCOA */
158 #include "disas.h"
160 #include "exec-all.h"
162 #include "qemu-kvm.h"
164 //#define DEBUG_UNUSED_IOPORT
165 //#define DEBUG_IOPORT
166 //#define DEBUG_NET
167 //#define DEBUG_SLIRP
170 #ifdef DEBUG_IOPORT
171 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
172 #else
173 # define LOG_IOPORT(...) do { } while (0)
174 #endif
176 #define DEFAULT_RAM_SIZE 128
178 /* Max number of USB devices that can be specified on the commandline. */
179 #define MAX_USB_CMDLINE 8
181 /* Max number of bluetooth switches on the commandline. */
182 #define MAX_BT_CMDLINE 10
184 /* XXX: use a two level table to limit memory usage */
185 #define MAX_IOPORTS 65536
187 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
188 const char *bios_name = NULL;
189 static void *ioport_opaque[MAX_IOPORTS];
190 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
191 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
192 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
193 to store the VM snapshots */
194 DriveInfo drives_table[MAX_DRIVES+1];
195 int nb_drives;
196 int extboot_drive = -1;
197 static int vga_ram_size;
198 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
199 static DisplayState *display_state;
200 int nographic;
201 static int curses;
202 static int sdl;
203 const char* keyboard_layout = NULL;
204 int64_t ticks_per_sec;
205 ram_addr_t ram_size;
206 int nb_nics;
207 NICInfo nd_table[MAX_NICS];
208 int vm_running;
209 static int autostart;
210 static int rtc_utc = 1;
211 static int rtc_date_offset = -1; /* -1 means no change */
212 int cirrus_vga_enabled = 1;
213 int std_vga_enabled = 0;
214 int vmsvga_enabled = 0;
215 #ifdef TARGET_SPARC
216 int graphic_width = 1024;
217 int graphic_height = 768;
218 int graphic_depth = 8;
219 #else
220 int graphic_width = 800;
221 int graphic_height = 600;
222 int graphic_depth = 15;
223 #endif
224 static int full_screen = 0;
225 #ifdef CONFIG_SDL
226 static int no_frame = 0;
227 #endif
228 int no_quit = 0;
229 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
230 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
231 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
232 #ifdef TARGET_I386
233 int win2k_install_hack = 0;
234 int rtc_td_hack = 0;
235 #endif
236 int usb_enabled = 0;
237 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
238 int assigned_devices_index;
239 int smp_cpus = 1;
240 const char *vnc_display;
241 int acpi_enabled = 1;
242 int no_hpet = 0;
243 int fd_bootchk = 1;
244 int no_reboot = 0;
245 int no_shutdown = 0;
246 int cursor_hide = 1;
247 int graphic_rotate = 0;
248 int daemonize = 0;
249 const char *incoming;
250 const char *option_rom[MAX_OPTION_ROMS];
251 int nb_option_roms;
252 int semihosting_enabled = 0;
253 int time_drift_fix = 0;
254 unsigned int kvm_shadow_memory = 0;
255 const char *mem_path = NULL;
256 #ifdef MAP_POPULATE
257 int mem_prealloc = 1; /* force preallocation of physical target memory */
258 #endif
259 int hpagesize = 0;
260 const char *cpu_vendor_string;
261 #ifdef TARGET_ARM
262 int old_param = 0;
263 #endif
264 const char *qemu_name;
265 int alt_grab = 0;
266 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
267 unsigned int nb_prom_envs = 0;
268 const char *prom_envs[MAX_PROM_ENVS];
269 #endif
270 int nb_drives_opt;
271 const char *nvram = NULL;
272 struct drive_opt drives_opt[MAX_DRIVES];
274 static CPUState *cur_cpu;
275 static CPUState *next_cpu;
276 static int event_pending = 1;
277 /* Conversion factor from emulated instructions to virtual clock ticks. */
278 static int icount_time_shift;
279 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
280 #define MAX_ICOUNT_SHIFT 10
281 /* Compensate for varying guest execution speed. */
282 static int64_t qemu_icount_bias;
283 static QEMUTimer *icount_rt_timer;
284 static QEMUTimer *icount_vm_timer;
285 static QEMUTimer *nographic_timer;
287 uint8_t qemu_uuid[16];
289 /* KVM runs the main loop in a separate thread. If we update one of the lists
290 * that are polled before or after select(), we need to make sure to break out
291 * of the select() to ensure the new item is serviced.
293 static void main_loop_break(void)
295 if (kvm_enabled())
296 qemu_kvm_notify_work();
299 /***********************************************************/
300 /* x86 ISA bus support */
302 target_phys_addr_t isa_mem_base = 0;
303 PicState2 *isa_pic;
305 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
306 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
308 static uint32_t ioport_read(int index, uint32_t address)
310 static IOPortReadFunc *default_func[3] = {
311 default_ioport_readb,
312 default_ioport_readw,
313 default_ioport_readl
315 IOPortReadFunc *func = ioport_read_table[index][address];
316 if (!func)
317 func = default_func[index];
318 return func(ioport_opaque[address], address);
321 static void ioport_write(int index, uint32_t address, uint32_t data)
323 static IOPortWriteFunc *default_func[3] = {
324 default_ioport_writeb,
325 default_ioport_writew,
326 default_ioport_writel
328 IOPortWriteFunc *func = ioport_write_table[index][address];
329 if (!func)
330 func = default_func[index];
331 func(ioport_opaque[address], address, data);
334 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
336 #ifdef DEBUG_UNUSED_IOPORT
337 fprintf(stderr, "unused inb: port=0x%04x\n", address);
338 #endif
339 return 0xff;
342 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
344 #ifdef DEBUG_UNUSED_IOPORT
345 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
346 #endif
349 /* default is to make two byte accesses */
350 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
352 uint32_t data;
353 data = ioport_read(0, address);
354 address = (address + 1) & (MAX_IOPORTS - 1);
355 data |= ioport_read(0, address) << 8;
356 return data;
359 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
361 ioport_write(0, address, data & 0xff);
362 address = (address + 1) & (MAX_IOPORTS - 1);
363 ioport_write(0, address, (data >> 8) & 0xff);
366 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
368 #ifdef DEBUG_UNUSED_IOPORT
369 fprintf(stderr, "unused inl: port=0x%04x\n", address);
370 #endif
371 return 0xffffffff;
374 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
376 #ifdef DEBUG_UNUSED_IOPORT
377 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
378 #endif
381 /* size is the word size in byte */
382 int register_ioport_read(int start, int length, int size,
383 IOPortReadFunc *func, void *opaque)
385 int i, bsize;
387 if (size == 1) {
388 bsize = 0;
389 } else if (size == 2) {
390 bsize = 1;
391 } else if (size == 4) {
392 bsize = 2;
393 } else {
394 hw_error("register_ioport_read: invalid size");
395 return -1;
397 for(i = start; i < start + length; i += size) {
398 ioport_read_table[bsize][i] = func;
399 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
400 hw_error("register_ioport_read: invalid opaque");
401 ioport_opaque[i] = opaque;
403 return 0;
406 /* size is the word size in byte */
407 int register_ioport_write(int start, int length, int size,
408 IOPortWriteFunc *func, void *opaque)
410 int i, bsize;
412 if (size == 1) {
413 bsize = 0;
414 } else if (size == 2) {
415 bsize = 1;
416 } else if (size == 4) {
417 bsize = 2;
418 } else {
419 hw_error("register_ioport_write: invalid size");
420 return -1;
422 for(i = start; i < start + length; i += size) {
423 ioport_write_table[bsize][i] = func;
424 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
425 hw_error("register_ioport_write: invalid opaque");
426 ioport_opaque[i] = opaque;
428 return 0;
431 void isa_unassign_ioport(int start, int length)
433 int i;
435 for(i = start; i < start + length; i++) {
436 ioport_read_table[0][i] = default_ioport_readb;
437 ioport_read_table[1][i] = default_ioport_readw;
438 ioport_read_table[2][i] = default_ioport_readl;
440 ioport_write_table[0][i] = default_ioport_writeb;
441 ioport_write_table[1][i] = default_ioport_writew;
442 ioport_write_table[2][i] = default_ioport_writel;
444 ioport_opaque[i] = NULL;
448 /***********************************************************/
450 void cpu_outb(CPUState *env, int addr, int val)
452 LOG_IOPORT("outb: %04x %02x\n", addr, val);
453 ioport_write(0, addr, val);
454 #ifdef USE_KQEMU
455 if (env)
456 env->last_io_time = cpu_get_time_fast();
457 #endif
460 void cpu_outw(CPUState *env, int addr, int val)
462 LOG_IOPORT("outw: %04x %04x\n", addr, val);
463 ioport_write(1, addr, val);
464 #ifdef USE_KQEMU
465 if (env)
466 env->last_io_time = cpu_get_time_fast();
467 #endif
470 void cpu_outl(CPUState *env, int addr, int val)
472 LOG_IOPORT("outl: %04x %08x\n", addr, val);
473 ioport_write(2, addr, val);
474 #ifdef USE_KQEMU
475 if (env)
476 env->last_io_time = cpu_get_time_fast();
477 #endif
480 int cpu_inb(CPUState *env, int addr)
482 int val;
483 val = ioport_read(0, addr);
484 LOG_IOPORT("inb : %04x %02x\n", addr, val);
485 #ifdef USE_KQEMU
486 if (env)
487 env->last_io_time = cpu_get_time_fast();
488 #endif
489 return val;
492 int cpu_inw(CPUState *env, int addr)
494 int val;
495 val = ioport_read(1, addr);
496 LOG_IOPORT("inw : %04x %04x\n", addr, val);
497 #ifdef USE_KQEMU
498 if (env)
499 env->last_io_time = cpu_get_time_fast();
500 #endif
501 return val;
504 int cpu_inl(CPUState *env, int addr)
506 int val;
507 val = ioport_read(2, addr);
508 LOG_IOPORT("inl : %04x %08x\n", addr, val);
509 #ifdef USE_KQEMU
510 if (env)
511 env->last_io_time = cpu_get_time_fast();
512 #endif
513 return val;
516 /***********************************************************/
517 void hw_error(const char *fmt, ...)
519 va_list ap;
520 CPUState *env;
522 va_start(ap, fmt);
523 fprintf(stderr, "qemu: hardware error: ");
524 vfprintf(stderr, fmt, ap);
525 fprintf(stderr, "\n");
526 for(env = first_cpu; env != NULL; env = env->next_cpu) {
527 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
528 #ifdef TARGET_I386
529 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
530 #else
531 cpu_dump_state(env, stderr, fprintf, 0);
532 #endif
534 va_end(ap);
535 abort();
538 /***************/
539 /* ballooning */
541 static QEMUBalloonEvent *qemu_balloon_event;
542 void *qemu_balloon_event_opaque;
544 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
546 qemu_balloon_event = func;
547 qemu_balloon_event_opaque = opaque;
550 void qemu_balloon(ram_addr_t target)
552 if (qemu_balloon_event)
553 qemu_balloon_event(qemu_balloon_event_opaque, target);
556 ram_addr_t qemu_balloon_status(void)
558 if (qemu_balloon_event)
559 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
560 return 0;
563 /***********************************************************/
564 /* keyboard/mouse */
566 static QEMUPutKBDEvent *qemu_put_kbd_event;
567 static void *qemu_put_kbd_event_opaque;
568 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
569 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
571 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
573 qemu_put_kbd_event_opaque = opaque;
574 qemu_put_kbd_event = func;
577 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
578 void *opaque, int absolute,
579 const char *name)
581 QEMUPutMouseEntry *s, *cursor;
583 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
585 s->qemu_put_mouse_event = func;
586 s->qemu_put_mouse_event_opaque = opaque;
587 s->qemu_put_mouse_event_absolute = absolute;
588 s->qemu_put_mouse_event_name = qemu_strdup(name);
589 s->next = NULL;
591 if (!qemu_put_mouse_event_head) {
592 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
593 return s;
596 cursor = qemu_put_mouse_event_head;
597 while (cursor->next != NULL)
598 cursor = cursor->next;
600 cursor->next = s;
601 qemu_put_mouse_event_current = s;
603 return s;
606 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
608 QEMUPutMouseEntry *prev = NULL, *cursor;
610 if (!qemu_put_mouse_event_head || entry == NULL)
611 return;
613 cursor = qemu_put_mouse_event_head;
614 while (cursor != NULL && cursor != entry) {
615 prev = cursor;
616 cursor = cursor->next;
619 if (cursor == NULL) // does not exist or list empty
620 return;
621 else if (prev == NULL) { // entry is head
622 qemu_put_mouse_event_head = cursor->next;
623 if (qemu_put_mouse_event_current == entry)
624 qemu_put_mouse_event_current = cursor->next;
625 qemu_free(entry->qemu_put_mouse_event_name);
626 qemu_free(entry);
627 return;
630 prev->next = entry->next;
632 if (qemu_put_mouse_event_current == entry)
633 qemu_put_mouse_event_current = prev;
635 qemu_free(entry->qemu_put_mouse_event_name);
636 qemu_free(entry);
639 void kbd_put_keycode(int keycode)
641 if (qemu_put_kbd_event) {
642 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
646 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
648 QEMUPutMouseEvent *mouse_event;
649 void *mouse_event_opaque;
650 int width;
652 if (!qemu_put_mouse_event_current) {
653 return;
656 mouse_event =
657 qemu_put_mouse_event_current->qemu_put_mouse_event;
658 mouse_event_opaque =
659 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
661 if (mouse_event) {
662 if (graphic_rotate) {
663 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
664 width = 0x7fff;
665 else
666 width = graphic_width - 1;
667 mouse_event(mouse_event_opaque,
668 width - dy, dx, dz, buttons_state);
669 } else
670 mouse_event(mouse_event_opaque,
671 dx, dy, dz, buttons_state);
675 int kbd_mouse_is_absolute(void)
677 if (!qemu_put_mouse_event_current)
678 return 0;
680 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
683 void do_info_mice(void)
685 QEMUPutMouseEntry *cursor;
686 int index = 0;
688 if (!qemu_put_mouse_event_head) {
689 term_printf("No mouse devices connected\n");
690 return;
693 term_printf("Mouse devices available:\n");
694 cursor = qemu_put_mouse_event_head;
695 while (cursor != NULL) {
696 term_printf("%c Mouse #%d: %s\n",
697 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
698 index, cursor->qemu_put_mouse_event_name);
699 index++;
700 cursor = cursor->next;
704 void do_mouse_set(int index)
706 QEMUPutMouseEntry *cursor;
707 int i = 0;
709 if (!qemu_put_mouse_event_head) {
710 term_printf("No mouse devices connected\n");
711 return;
714 cursor = qemu_put_mouse_event_head;
715 while (cursor != NULL && index != i) {
716 i++;
717 cursor = cursor->next;
720 if (cursor != NULL)
721 qemu_put_mouse_event_current = cursor;
722 else
723 term_printf("Mouse at given index not found\n");
726 /* compute with 96 bit intermediate result: (a*b)/c */
727 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
729 union {
730 uint64_t ll;
731 struct {
732 #ifdef WORDS_BIGENDIAN
733 uint32_t high, low;
734 #else
735 uint32_t low, high;
736 #endif
737 } l;
738 } u, res;
739 uint64_t rl, rh;
741 u.ll = a;
742 rl = (uint64_t)u.l.low * (uint64_t)b;
743 rh = (uint64_t)u.l.high * (uint64_t)b;
744 rh += (rl >> 32);
745 res.l.high = rh / c;
746 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
747 return res.ll;
750 /***********************************************************/
751 /* real time host monotonic timer */
753 #define QEMU_TIMER_BASE 1000000000LL
755 #ifdef WIN32
757 static int64_t clock_freq;
759 static void init_get_clock(void)
761 LARGE_INTEGER freq;
762 int ret;
763 ret = QueryPerformanceFrequency(&freq);
764 if (ret == 0) {
765 fprintf(stderr, "Could not calibrate ticks\n");
766 exit(1);
768 clock_freq = freq.QuadPart;
771 static int64_t get_clock(void)
773 LARGE_INTEGER ti;
774 QueryPerformanceCounter(&ti);
775 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
778 #else
780 static int use_rt_clock;
782 static void init_get_clock(void)
784 use_rt_clock = 0;
785 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
787 struct timespec ts;
788 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
789 use_rt_clock = 1;
792 #endif
795 static int64_t get_clock(void)
797 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
798 if (use_rt_clock) {
799 struct timespec ts;
800 clock_gettime(CLOCK_MONOTONIC, &ts);
801 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
802 } else
803 #endif
805 /* XXX: using gettimeofday leads to problems if the date
806 changes, so it should be avoided. */
807 struct timeval tv;
808 gettimeofday(&tv, NULL);
809 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
812 #endif
814 /* Return the virtual CPU time, based on the instruction counter. */
815 static int64_t cpu_get_icount(void)
817 int64_t icount;
818 CPUState *env = cpu_single_env;;
819 icount = qemu_icount;
820 if (env) {
821 if (!can_do_io(env))
822 fprintf(stderr, "Bad clock read\n");
823 icount -= (env->icount_decr.u16.low + env->icount_extra);
825 return qemu_icount_bias + (icount << icount_time_shift);
828 /***********************************************************/
829 /* guest cycle counter */
831 static int64_t cpu_ticks_prev;
832 static int64_t cpu_ticks_offset;
833 static int64_t cpu_clock_offset;
834 static int cpu_ticks_enabled;
836 /* return the host CPU cycle counter and handle stop/restart */
837 int64_t cpu_get_ticks(void)
839 if (use_icount) {
840 return cpu_get_icount();
842 if (!cpu_ticks_enabled) {
843 return cpu_ticks_offset;
844 } else {
845 int64_t ticks;
846 ticks = cpu_get_real_ticks();
847 if (cpu_ticks_prev > ticks) {
848 /* Note: non increasing ticks may happen if the host uses
849 software suspend */
850 cpu_ticks_offset += cpu_ticks_prev - ticks;
852 cpu_ticks_prev = ticks;
853 return ticks + cpu_ticks_offset;
857 /* return the host CPU monotonic timer and handle stop/restart */
858 static int64_t cpu_get_clock(void)
860 int64_t ti;
861 if (!cpu_ticks_enabled) {
862 return cpu_clock_offset;
863 } else {
864 ti = get_clock();
865 return ti + cpu_clock_offset;
869 /* enable cpu_get_ticks() */
870 void cpu_enable_ticks(void)
872 if (!cpu_ticks_enabled) {
873 cpu_ticks_offset -= cpu_get_real_ticks();
874 cpu_clock_offset -= get_clock();
875 cpu_ticks_enabled = 1;
879 /* disable cpu_get_ticks() : the clock is stopped. You must not call
880 cpu_get_ticks() after that. */
881 void cpu_disable_ticks(void)
883 if (cpu_ticks_enabled) {
884 cpu_ticks_offset = cpu_get_ticks();
885 cpu_clock_offset = cpu_get_clock();
886 cpu_ticks_enabled = 0;
890 /***********************************************************/
891 /* timers */
893 #define QEMU_TIMER_REALTIME 0
894 #define QEMU_TIMER_VIRTUAL 1
896 struct QEMUClock {
897 int type;
898 /* XXX: add frequency */
901 struct QEMUTimer {
902 QEMUClock *clock;
903 int64_t expire_time;
904 QEMUTimerCB *cb;
905 void *opaque;
906 struct QEMUTimer *next;
909 struct qemu_alarm_timer {
910 char const *name;
911 unsigned int flags;
913 int (*start)(struct qemu_alarm_timer *t);
914 void (*stop)(struct qemu_alarm_timer *t);
915 void (*rearm)(struct qemu_alarm_timer *t);
916 void *priv;
919 #define ALARM_FLAG_DYNTICKS 0x1
920 #define ALARM_FLAG_EXPIRED 0x2
922 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
924 return t->flags & ALARM_FLAG_DYNTICKS;
927 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
929 if (!alarm_has_dynticks(t))
930 return;
932 t->rearm(t);
935 /* TODO: MIN_TIMER_REARM_US should be optimized */
936 #define MIN_TIMER_REARM_US 250
938 static struct qemu_alarm_timer *alarm_timer;
939 #ifndef _WIN32
940 static int alarm_timer_rfd, alarm_timer_wfd;
941 #endif
943 #ifdef _WIN32
945 struct qemu_alarm_win32 {
946 MMRESULT timerId;
947 HANDLE host_alarm;
948 unsigned int period;
949 } alarm_win32_data = {0, NULL, -1};
951 static int win32_start_timer(struct qemu_alarm_timer *t);
952 static void win32_stop_timer(struct qemu_alarm_timer *t);
953 static void win32_rearm_timer(struct qemu_alarm_timer *t);
955 #else
957 static int unix_start_timer(struct qemu_alarm_timer *t);
958 static void unix_stop_timer(struct qemu_alarm_timer *t);
960 #ifdef __linux__
962 static int dynticks_start_timer(struct qemu_alarm_timer *t);
963 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
964 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
966 static int hpet_start_timer(struct qemu_alarm_timer *t);
967 static void hpet_stop_timer(struct qemu_alarm_timer *t);
969 static int rtc_start_timer(struct qemu_alarm_timer *t);
970 static void rtc_stop_timer(struct qemu_alarm_timer *t);
972 #endif /* __linux__ */
974 #endif /* _WIN32 */
976 /* Correlation between real and virtual time is always going to be
977 fairly approximate, so ignore small variation.
978 When the guest is idle real and virtual time will be aligned in
979 the IO wait loop. */
980 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
982 static void icount_adjust(void)
984 int64_t cur_time;
985 int64_t cur_icount;
986 int64_t delta;
987 static int64_t last_delta;
988 /* If the VM is not running, then do nothing. */
989 if (!vm_running)
990 return;
992 cur_time = cpu_get_clock();
993 cur_icount = qemu_get_clock(vm_clock);
994 delta = cur_icount - cur_time;
995 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
996 if (delta > 0
997 && last_delta + ICOUNT_WOBBLE < delta * 2
998 && icount_time_shift > 0) {
999 /* The guest is getting too far ahead. Slow time down. */
1000 icount_time_shift--;
1002 if (delta < 0
1003 && last_delta - ICOUNT_WOBBLE > delta * 2
1004 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1005 /* The guest is getting too far behind. Speed time up. */
1006 icount_time_shift++;
1008 last_delta = delta;
1009 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1012 static void icount_adjust_rt(void * opaque)
1014 qemu_mod_timer(icount_rt_timer,
1015 qemu_get_clock(rt_clock) + 1000);
1016 icount_adjust();
1019 static void icount_adjust_vm(void * opaque)
1021 qemu_mod_timer(icount_vm_timer,
1022 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1023 icount_adjust();
1026 static void init_icount_adjust(void)
1028 /* Have both realtime and virtual time triggers for speed adjustment.
1029 The realtime trigger catches emulated time passing too slowly,
1030 the virtual time trigger catches emulated time passing too fast.
1031 Realtime triggers occur even when idle, so use them less frequently
1032 than VM triggers. */
1033 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1034 qemu_mod_timer(icount_rt_timer,
1035 qemu_get_clock(rt_clock) + 1000);
1036 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1037 qemu_mod_timer(icount_vm_timer,
1038 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1041 static struct qemu_alarm_timer alarm_timers[] = {
1042 #ifndef _WIN32
1043 #ifdef __linux__
1044 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1045 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1046 /* HPET - if available - is preferred */
1047 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1048 /* ...otherwise try RTC */
1049 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1050 #endif
1051 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1052 #else
1053 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1054 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1055 {"win32", 0, win32_start_timer,
1056 win32_stop_timer, NULL, &alarm_win32_data},
1057 #endif
1058 {NULL, }
1061 static void show_available_alarms(void)
1063 int i;
1065 printf("Available alarm timers, in order of precedence:\n");
1066 for (i = 0; alarm_timers[i].name; i++)
1067 printf("%s\n", alarm_timers[i].name);
1070 static void configure_alarms(char const *opt)
1072 int i;
1073 int cur = 0;
1074 int count = ARRAY_SIZE(alarm_timers) - 1;
1075 char *arg;
1076 char *name;
1077 struct qemu_alarm_timer tmp;
1079 if (!strcmp(opt, "?")) {
1080 show_available_alarms();
1081 exit(0);
1084 arg = strdup(opt);
1086 /* Reorder the array */
1087 name = strtok(arg, ",");
1088 while (name) {
1089 for (i = 0; i < count && alarm_timers[i].name; i++) {
1090 if (!strcmp(alarm_timers[i].name, name))
1091 break;
1094 if (i == count) {
1095 fprintf(stderr, "Unknown clock %s\n", name);
1096 goto next;
1099 if (i < cur)
1100 /* Ignore */
1101 goto next;
1103 /* Swap */
1104 tmp = alarm_timers[i];
1105 alarm_timers[i] = alarm_timers[cur];
1106 alarm_timers[cur] = tmp;
1108 cur++;
1109 next:
1110 name = strtok(NULL, ",");
1113 free(arg);
1115 if (cur) {
1116 /* Disable remaining timers */
1117 for (i = cur; i < count; i++)
1118 alarm_timers[i].name = NULL;
1119 } else {
1120 show_available_alarms();
1121 exit(1);
1125 QEMUClock *rt_clock;
1126 QEMUClock *vm_clock;
1128 static QEMUTimer *active_timers[2];
1130 static QEMUClock *qemu_new_clock(int type)
1132 QEMUClock *clock;
1133 clock = qemu_mallocz(sizeof(QEMUClock));
1134 clock->type = type;
1135 return clock;
1138 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1140 QEMUTimer *ts;
1142 ts = qemu_mallocz(sizeof(QEMUTimer));
1143 ts->clock = clock;
1144 ts->cb = cb;
1145 ts->opaque = opaque;
1146 return ts;
1149 void qemu_free_timer(QEMUTimer *ts)
1151 qemu_free(ts);
1154 /* stop a timer, but do not dealloc it */
1155 void qemu_del_timer(QEMUTimer *ts)
1157 QEMUTimer **pt, *t;
1159 /* NOTE: this code must be signal safe because
1160 qemu_timer_expired() can be called from a signal. */
1161 pt = &active_timers[ts->clock->type];
1162 for(;;) {
1163 t = *pt;
1164 if (!t)
1165 break;
1166 if (t == ts) {
1167 *pt = t->next;
1168 break;
1170 pt = &t->next;
1174 /* modify the current timer so that it will be fired when current_time
1175 >= expire_time. The corresponding callback will be called. */
1176 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1178 QEMUTimer **pt, *t;
1180 qemu_del_timer(ts);
1182 /* add the timer in the sorted list */
1183 /* NOTE: this code must be signal safe because
1184 qemu_timer_expired() can be called from a signal. */
1185 pt = &active_timers[ts->clock->type];
1186 for(;;) {
1187 t = *pt;
1188 if (!t)
1189 break;
1190 if (t->expire_time > expire_time)
1191 break;
1192 pt = &t->next;
1194 ts->expire_time = expire_time;
1195 ts->next = *pt;
1196 *pt = ts;
1198 /* Rearm if necessary */
1199 if (pt == &active_timers[ts->clock->type]) {
1200 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1201 qemu_rearm_alarm_timer(alarm_timer);
1203 /* Interrupt execution to force deadline recalculation. */
1204 if (use_icount && cpu_single_env) {
1205 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1210 int qemu_timer_pending(QEMUTimer *ts)
1212 QEMUTimer *t;
1213 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1214 if (t == ts)
1215 return 1;
1217 return 0;
1220 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1222 if (!timer_head)
1223 return 0;
1224 return (timer_head->expire_time <= current_time);
1227 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1229 QEMUTimer *ts;
1231 for(;;) {
1232 ts = *ptimer_head;
1233 if (!ts || ts->expire_time > current_time)
1234 break;
1235 /* remove timer from the list before calling the callback */
1236 *ptimer_head = ts->next;
1237 ts->next = NULL;
1239 /* run the callback (the timer list can be modified) */
1240 ts->cb(ts->opaque);
1244 int64_t qemu_get_clock(QEMUClock *clock)
1246 switch(clock->type) {
1247 case QEMU_TIMER_REALTIME:
1248 return get_clock() / 1000000;
1249 default:
1250 case QEMU_TIMER_VIRTUAL:
1251 if (use_icount) {
1252 return cpu_get_icount();
1253 } else {
1254 return cpu_get_clock();
1259 static void init_timers(void)
1261 init_get_clock();
1262 ticks_per_sec = QEMU_TIMER_BASE;
1263 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1264 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1267 /* save a timer */
1268 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1270 uint64_t expire_time;
1272 if (qemu_timer_pending(ts)) {
1273 expire_time = ts->expire_time;
1274 } else {
1275 expire_time = -1;
1277 qemu_put_be64(f, expire_time);
1280 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1282 uint64_t expire_time;
1284 expire_time = qemu_get_be64(f);
1285 if (expire_time != -1) {
1286 qemu_mod_timer(ts, expire_time);
1287 } else {
1288 qemu_del_timer(ts);
1292 static void timer_save(QEMUFile *f, void *opaque)
1294 if (cpu_ticks_enabled) {
1295 hw_error("cannot save state if virtual timers are running");
1297 qemu_put_be64(f, cpu_ticks_offset);
1298 qemu_put_be64(f, ticks_per_sec);
1299 qemu_put_be64(f, cpu_clock_offset);
1302 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1304 if (version_id != 1 && version_id != 2)
1305 return -EINVAL;
1306 if (cpu_ticks_enabled) {
1307 return -EINVAL;
1309 cpu_ticks_offset=qemu_get_be64(f);
1310 ticks_per_sec=qemu_get_be64(f);
1311 if (version_id == 2) {
1312 cpu_clock_offset=qemu_get_be64(f);
1314 return 0;
1317 #ifdef _WIN32
1318 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1319 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1320 #else
1321 static void host_alarm_handler(int host_signum)
1322 #endif
1324 #if 0
1325 #define DISP_FREQ 1000
1327 static int64_t delta_min = INT64_MAX;
1328 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1329 static int count;
1330 ti = qemu_get_clock(vm_clock);
1331 if (last_clock != 0) {
1332 delta = ti - last_clock;
1333 if (delta < delta_min)
1334 delta_min = delta;
1335 if (delta > delta_max)
1336 delta_max = delta;
1337 delta_cum += delta;
1338 if (++count == DISP_FREQ) {
1339 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1340 muldiv64(delta_min, 1000000, ticks_per_sec),
1341 muldiv64(delta_max, 1000000, ticks_per_sec),
1342 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1343 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1344 count = 0;
1345 delta_min = INT64_MAX;
1346 delta_max = 0;
1347 delta_cum = 0;
1350 last_clock = ti;
1352 #endif
1353 if (1 ||
1354 alarm_has_dynticks(alarm_timer) ||
1355 (!use_icount &&
1356 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1357 qemu_get_clock(vm_clock))) ||
1358 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1359 qemu_get_clock(rt_clock))) {
1360 CPUState *env = next_cpu;
1362 #ifdef _WIN32
1363 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1364 SetEvent(data->host_alarm);
1365 #else
1366 static const char byte = 0;
1367 write(alarm_timer_wfd, &byte, sizeof(byte));
1368 #endif
1369 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1371 if (env) {
1372 /* stop the currently executing cpu because a timer occured */
1373 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1374 #ifdef USE_KQEMU
1375 if (env->kqemu_enabled) {
1376 kqemu_cpu_interrupt(env);
1378 #endif
1380 event_pending = 1;
1384 static int64_t qemu_next_deadline(void)
1386 int64_t delta;
1388 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1389 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1390 qemu_get_clock(vm_clock);
1391 } else {
1392 /* To avoid problems with overflow limit this to 2^32. */
1393 delta = INT32_MAX;
1396 if (delta < 0)
1397 delta = 0;
1399 return delta;
1402 #if defined(__linux__) || defined(_WIN32)
1403 static uint64_t qemu_next_deadline_dyntick(void)
1405 int64_t delta;
1406 int64_t rtdelta;
1408 if (use_icount)
1409 delta = INT32_MAX;
1410 else
1411 delta = (qemu_next_deadline() + 999) / 1000;
1413 if (active_timers[QEMU_TIMER_REALTIME]) {
1414 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1415 qemu_get_clock(rt_clock))*1000;
1416 if (rtdelta < delta)
1417 delta = rtdelta;
1420 if (delta < MIN_TIMER_REARM_US)
1421 delta = MIN_TIMER_REARM_US;
1423 return delta;
1425 #endif
1427 #ifndef _WIN32
1429 /* Sets a specific flag */
1430 static int fcntl_setfl(int fd, int flag)
1432 int flags;
1434 flags = fcntl(fd, F_GETFL);
1435 if (flags == -1)
1436 return -errno;
1438 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1439 return -errno;
1441 return 0;
1444 #if defined(__linux__)
1446 #define RTC_FREQ 1024
1448 static void enable_sigio_timer(int fd)
1450 struct sigaction act;
1452 /* timer signal */
1453 sigfillset(&act.sa_mask);
1454 act.sa_flags = 0;
1455 act.sa_handler = host_alarm_handler;
1457 sigaction(SIGIO, &act, NULL);
1458 fcntl_setfl(fd, O_ASYNC);
1459 fcntl(fd, F_SETOWN, getpid());
1462 static int hpet_start_timer(struct qemu_alarm_timer *t)
1464 struct hpet_info info;
1465 int r, fd;
1467 fd = open("/dev/hpet", O_RDONLY);
1468 if (fd < 0)
1469 return -1;
1471 /* Set frequency */
1472 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1473 if (r < 0) {
1474 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1475 "error, but for better emulation accuracy type:\n"
1476 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1477 goto fail;
1480 /* Check capabilities */
1481 r = ioctl(fd, HPET_INFO, &info);
1482 if (r < 0)
1483 goto fail;
1485 /* Enable periodic mode */
1486 r = ioctl(fd, HPET_EPI, 0);
1487 if (info.hi_flags && (r < 0))
1488 goto fail;
1490 /* Enable interrupt */
1491 r = ioctl(fd, HPET_IE_ON, 0);
1492 if (r < 0)
1493 goto fail;
1495 enable_sigio_timer(fd);
1496 t->priv = (void *)(long)fd;
1498 return 0;
1499 fail:
1500 close(fd);
1501 return -1;
1504 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1506 int fd = (long)t->priv;
1508 close(fd);
1511 static int rtc_start_timer(struct qemu_alarm_timer *t)
1513 int rtc_fd;
1514 unsigned long current_rtc_freq = 0;
1516 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1517 if (rtc_fd < 0)
1518 return -1;
1519 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1520 if (current_rtc_freq != RTC_FREQ &&
1521 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1522 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1523 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1524 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1525 goto fail;
1527 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1528 fail:
1529 close(rtc_fd);
1530 return -1;
1533 enable_sigio_timer(rtc_fd);
1535 t->priv = (void *)(long)rtc_fd;
1537 return 0;
1540 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1542 int rtc_fd = (long)t->priv;
1544 close(rtc_fd);
1547 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1549 struct sigevent ev;
1550 timer_t host_timer;
1551 struct sigaction act;
1553 sigfillset(&act.sa_mask);
1554 act.sa_flags = 0;
1555 act.sa_handler = host_alarm_handler;
1557 sigaction(SIGALRM, &act, NULL);
1559 ev.sigev_value.sival_int = 0;
1560 ev.sigev_notify = SIGEV_SIGNAL;
1561 ev.sigev_signo = SIGALRM;
1563 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1564 perror("timer_create");
1566 /* disable dynticks */
1567 fprintf(stderr, "Dynamic Ticks disabled\n");
1569 return -1;
1572 t->priv = (void *)(long)host_timer;
1574 return 0;
1577 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1579 timer_t host_timer = (timer_t)(long)t->priv;
1581 timer_delete(host_timer);
1584 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1586 timer_t host_timer = (timer_t)(long)t->priv;
1587 struct itimerspec timeout;
1588 int64_t nearest_delta_us = INT64_MAX;
1589 int64_t current_us;
1591 if (!active_timers[QEMU_TIMER_REALTIME] &&
1592 !active_timers[QEMU_TIMER_VIRTUAL])
1593 return;
1595 nearest_delta_us = qemu_next_deadline_dyntick();
1597 /* check whether a timer is already running */
1598 if (timer_gettime(host_timer, &timeout)) {
1599 perror("gettime");
1600 fprintf(stderr, "Internal timer error: aborting\n");
1601 exit(1);
1603 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1604 if (current_us && current_us <= nearest_delta_us)
1605 return;
1607 timeout.it_interval.tv_sec = 0;
1608 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1609 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1610 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1611 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1612 perror("settime");
1613 fprintf(stderr, "Internal timer error: aborting\n");
1614 exit(1);
1618 #endif /* defined(__linux__) */
1620 static int unix_start_timer(struct qemu_alarm_timer *t)
1622 struct sigaction act;
1623 struct itimerval itv;
1624 int err;
1626 /* timer signal */
1627 sigfillset(&act.sa_mask);
1628 act.sa_flags = 0;
1629 act.sa_handler = host_alarm_handler;
1631 sigaction(SIGALRM, &act, NULL);
1633 itv.it_interval.tv_sec = 0;
1634 /* for i386 kernel 2.6 to get 1 ms */
1635 itv.it_interval.tv_usec = 999;
1636 itv.it_value.tv_sec = 0;
1637 itv.it_value.tv_usec = 10 * 1000;
1639 err = setitimer(ITIMER_REAL, &itv, NULL);
1640 if (err)
1641 return -1;
1643 return 0;
1646 static void unix_stop_timer(struct qemu_alarm_timer *t)
1648 struct itimerval itv;
1650 memset(&itv, 0, sizeof(itv));
1651 setitimer(ITIMER_REAL, &itv, NULL);
1654 #endif /* !defined(_WIN32) */
1656 static void try_to_rearm_timer(void *opaque)
1658 struct qemu_alarm_timer *t = opaque;
1659 #ifndef _WIN32
1660 ssize_t len;
1662 /* Drain the notify pipe */
1663 do {
1664 char buffer[512];
1665 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1666 } while ((len == -1 && errno == EINTR) || len > 0);
1667 #endif
1669 if (t->flags & ALARM_FLAG_EXPIRED) {
1670 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1671 qemu_rearm_alarm_timer(alarm_timer);
1675 #ifdef _WIN32
1677 static int win32_start_timer(struct qemu_alarm_timer *t)
1679 TIMECAPS tc;
1680 struct qemu_alarm_win32 *data = t->priv;
1681 UINT flags;
1683 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1684 if (!data->host_alarm) {
1685 perror("Failed CreateEvent");
1686 return -1;
1689 memset(&tc, 0, sizeof(tc));
1690 timeGetDevCaps(&tc, sizeof(tc));
1692 if (data->period < tc.wPeriodMin)
1693 data->period = tc.wPeriodMin;
1695 timeBeginPeriod(data->period);
1697 flags = TIME_CALLBACK_FUNCTION;
1698 if (alarm_has_dynticks(t))
1699 flags |= TIME_ONESHOT;
1700 else
1701 flags |= TIME_PERIODIC;
1703 data->timerId = timeSetEvent(1, // interval (ms)
1704 data->period, // resolution
1705 host_alarm_handler, // function
1706 (DWORD)t, // parameter
1707 flags);
1709 if (!data->timerId) {
1710 perror("Failed to initialize win32 alarm timer");
1712 timeEndPeriod(data->period);
1713 CloseHandle(data->host_alarm);
1714 return -1;
1717 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1719 return 0;
1722 static void win32_stop_timer(struct qemu_alarm_timer *t)
1724 struct qemu_alarm_win32 *data = t->priv;
1726 timeKillEvent(data->timerId);
1727 timeEndPeriod(data->period);
1729 CloseHandle(data->host_alarm);
1732 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1734 struct qemu_alarm_win32 *data = t->priv;
1735 uint64_t nearest_delta_us;
1737 if (!active_timers[QEMU_TIMER_REALTIME] &&
1738 !active_timers[QEMU_TIMER_VIRTUAL])
1739 return;
1741 nearest_delta_us = qemu_next_deadline_dyntick();
1742 nearest_delta_us /= 1000;
1744 timeKillEvent(data->timerId);
1746 data->timerId = timeSetEvent(1,
1747 data->period,
1748 host_alarm_handler,
1749 (DWORD)t,
1750 TIME_ONESHOT | TIME_PERIODIC);
1752 if (!data->timerId) {
1753 perror("Failed to re-arm win32 alarm timer");
1755 timeEndPeriod(data->period);
1756 CloseHandle(data->host_alarm);
1757 exit(1);
1761 #endif /* _WIN32 */
1763 static int init_timer_alarm(void)
1765 struct qemu_alarm_timer *t = NULL;
1766 int i, err = -1;
1768 #ifndef _WIN32
1769 int fds[2];
1771 err = pipe(fds);
1772 if (err == -1)
1773 return -errno;
1775 err = fcntl_setfl(fds[0], O_NONBLOCK);
1776 if (err < 0)
1777 goto fail;
1779 err = fcntl_setfl(fds[1], O_NONBLOCK);
1780 if (err < 0)
1781 goto fail;
1783 alarm_timer_rfd = fds[0];
1784 alarm_timer_wfd = fds[1];
1785 #endif
1787 for (i = 0; alarm_timers[i].name; i++) {
1788 t = &alarm_timers[i];
1790 err = t->start(t);
1791 if (!err)
1792 break;
1795 if (err) {
1796 err = -ENOENT;
1797 goto fail;
1800 #ifndef _WIN32
1801 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1802 try_to_rearm_timer, NULL, t);
1803 #endif
1805 alarm_timer = t;
1807 return 0;
1809 fail:
1810 #ifndef _WIN32
1811 close(fds[0]);
1812 close(fds[1]);
1813 #endif
1814 return err;
1817 static void quit_timers(void)
1819 alarm_timer->stop(alarm_timer);
1820 alarm_timer = NULL;
1823 /***********************************************************/
1824 /* host time/date access */
1825 void qemu_get_timedate(struct tm *tm, int offset)
1827 time_t ti;
1828 struct tm *ret;
1830 time(&ti);
1831 ti += offset;
1832 if (rtc_date_offset == -1) {
1833 if (rtc_utc)
1834 ret = gmtime(&ti);
1835 else
1836 ret = localtime(&ti);
1837 } else {
1838 ti -= rtc_date_offset;
1839 ret = gmtime(&ti);
1842 memcpy(tm, ret, sizeof(struct tm));
1845 int qemu_timedate_diff(struct tm *tm)
1847 time_t seconds;
1849 if (rtc_date_offset == -1)
1850 if (rtc_utc)
1851 seconds = mktimegm(tm);
1852 else
1853 seconds = mktime(tm);
1854 else
1855 seconds = mktimegm(tm) + rtc_date_offset;
1857 return seconds - time(NULL);
1860 #ifdef _WIN32
1861 static void socket_cleanup(void)
1863 WSACleanup();
1866 static int socket_init(void)
1868 WSADATA Data;
1869 int ret, err;
1871 ret = WSAStartup(MAKEWORD(2,2), &Data);
1872 if (ret != 0) {
1873 err = WSAGetLastError();
1874 fprintf(stderr, "WSAStartup: %d\n", err);
1875 return -1;
1877 atexit(socket_cleanup);
1878 return 0;
1880 #endif
1882 const char *get_opt_name(char *buf, int buf_size, const char *p)
1884 char *q;
1886 q = buf;
1887 while (*p != '\0' && *p != '=') {
1888 if (q && (q - buf) < buf_size - 1)
1889 *q++ = *p;
1890 p++;
1892 if (q)
1893 *q = '\0';
1895 return p;
1898 const char *get_opt_value(char *buf, int buf_size, const char *p)
1900 char *q;
1902 q = buf;
1903 while (*p != '\0') {
1904 if (*p == ',') {
1905 if (*(p + 1) != ',')
1906 break;
1907 p++;
1909 if (q && (q - buf) < buf_size - 1)
1910 *q++ = *p;
1911 p++;
1913 if (q)
1914 *q = '\0';
1916 return p;
1919 int get_param_value(char *buf, int buf_size,
1920 const char *tag, const char *str)
1922 const char *p;
1923 char option[128];
1925 p = str;
1926 for(;;) {
1927 p = get_opt_name(option, sizeof(option), p);
1928 if (*p != '=')
1929 break;
1930 p++;
1931 if (!strcmp(tag, option)) {
1932 (void)get_opt_value(buf, buf_size, p);
1933 return strlen(buf);
1934 } else {
1935 p = get_opt_value(NULL, 0, p);
1937 if (*p != ',')
1938 break;
1939 p++;
1941 return 0;
1944 int check_params(char *buf, int buf_size,
1945 const char * const *params, const char *str)
1947 const char *p;
1948 int i;
1950 p = str;
1951 for(;;) {
1952 p = get_opt_name(buf, buf_size, p);
1953 if (*p != '=')
1954 return -1;
1955 p++;
1956 for(i = 0; params[i] != NULL; i++)
1957 if (!strcmp(params[i], buf))
1958 break;
1959 if (params[i] == NULL)
1960 return -1;
1961 p = get_opt_value(NULL, 0, p);
1962 if (*p != ',')
1963 break;
1964 p++;
1966 return 0;
1969 /***********************************************************/
1970 /* Bluetooth support */
1971 static int nb_hcis;
1972 static int cur_hci;
1973 static struct HCIInfo *hci_table[MAX_NICS];
1975 static struct bt_vlan_s {
1976 struct bt_scatternet_s net;
1977 int id;
1978 struct bt_vlan_s *next;
1979 } *first_bt_vlan;
1981 /* find or alloc a new bluetooth "VLAN" */
1982 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1984 struct bt_vlan_s **pvlan, *vlan;
1985 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1986 if (vlan->id == id)
1987 return &vlan->net;
1989 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1990 vlan->id = id;
1991 pvlan = &first_bt_vlan;
1992 while (*pvlan != NULL)
1993 pvlan = &(*pvlan)->next;
1994 *pvlan = vlan;
1995 return &vlan->net;
1998 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2002 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2004 return -ENOTSUP;
2007 static struct HCIInfo null_hci = {
2008 .cmd_send = null_hci_send,
2009 .sco_send = null_hci_send,
2010 .acl_send = null_hci_send,
2011 .bdaddr_set = null_hci_addr_set,
2014 struct HCIInfo *qemu_next_hci(void)
2016 if (cur_hci == nb_hcis)
2017 return &null_hci;
2019 return hci_table[cur_hci++];
2022 static struct HCIInfo *hci_init(const char *str)
2024 char *endp;
2025 struct bt_scatternet_s *vlan = 0;
2027 if (!strcmp(str, "null"))
2028 /* null */
2029 return &null_hci;
2030 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2031 /* host[:hciN] */
2032 return bt_host_hci(str[4] ? str + 5 : "hci0");
2033 else if (!strncmp(str, "hci", 3)) {
2034 /* hci[,vlan=n] */
2035 if (str[3]) {
2036 if (!strncmp(str + 3, ",vlan=", 6)) {
2037 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2038 if (*endp)
2039 vlan = 0;
2041 } else
2042 vlan = qemu_find_bt_vlan(0);
2043 if (vlan)
2044 return bt_new_hci(vlan);
2047 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2049 return 0;
2052 static int bt_hci_parse(const char *str)
2054 struct HCIInfo *hci;
2055 bdaddr_t bdaddr;
2057 if (nb_hcis >= MAX_NICS) {
2058 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2059 return -1;
2062 hci = hci_init(str);
2063 if (!hci)
2064 return -1;
2066 bdaddr.b[0] = 0x52;
2067 bdaddr.b[1] = 0x54;
2068 bdaddr.b[2] = 0x00;
2069 bdaddr.b[3] = 0x12;
2070 bdaddr.b[4] = 0x34;
2071 bdaddr.b[5] = 0x56 + nb_hcis;
2072 hci->bdaddr_set(hci, bdaddr.b);
2074 hci_table[nb_hcis++] = hci;
2076 return 0;
2079 static void bt_vhci_add(int vlan_id)
2081 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2083 if (!vlan->slave)
2084 fprintf(stderr, "qemu: warning: adding a VHCI to "
2085 "an empty scatternet %i\n", vlan_id);
2087 bt_vhci_init(bt_new_hci(vlan));
2090 static struct bt_device_s *bt_device_add(const char *opt)
2092 struct bt_scatternet_s *vlan;
2093 int vlan_id = 0;
2094 char *endp = strstr(opt, ",vlan=");
2095 int len = (endp ? endp - opt : strlen(opt)) + 1;
2096 char devname[10];
2098 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2100 if (endp) {
2101 vlan_id = strtol(endp + 6, &endp, 0);
2102 if (*endp) {
2103 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2104 return 0;
2108 vlan = qemu_find_bt_vlan(vlan_id);
2110 if (!vlan->slave)
2111 fprintf(stderr, "qemu: warning: adding a slave device to "
2112 "an empty scatternet %i\n", vlan_id);
2114 if (!strcmp(devname, "keyboard"))
2115 return bt_keyboard_init(vlan);
2117 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2118 return 0;
2121 static int bt_parse(const char *opt)
2123 const char *endp, *p;
2124 int vlan;
2126 if (strstart(opt, "hci", &endp)) {
2127 if (!*endp || *endp == ',') {
2128 if (*endp)
2129 if (!strstart(endp, ",vlan=", 0))
2130 opt = endp + 1;
2132 return bt_hci_parse(opt);
2134 } else if (strstart(opt, "vhci", &endp)) {
2135 if (!*endp || *endp == ',') {
2136 if (*endp) {
2137 if (strstart(endp, ",vlan=", &p)) {
2138 vlan = strtol(p, (char **) &endp, 0);
2139 if (*endp) {
2140 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2141 return 1;
2143 } else {
2144 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2145 return 1;
2147 } else
2148 vlan = 0;
2150 bt_vhci_add(vlan);
2151 return 0;
2153 } else if (strstart(opt, "device:", &endp))
2154 return !bt_device_add(endp);
2156 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2157 return 1;
2160 /***********************************************************/
2161 /* QEMU Block devices */
2163 #define HD_ALIAS "index=%d,media=disk"
2164 #ifdef TARGET_PPC
2165 #define CDROM_ALIAS "index=1,media=cdrom"
2166 #else
2167 #define CDROM_ALIAS "index=2,media=cdrom"
2168 #endif
2169 #define FD_ALIAS "index=%d,if=floppy"
2170 #define PFLASH_ALIAS "if=pflash"
2171 #define MTD_ALIAS "if=mtd"
2172 #define SD_ALIAS "index=0,if=sd"
2174 static int drive_opt_get_free_idx(void)
2176 int index;
2178 for (index = 0; index < MAX_DRIVES; index++)
2179 if (!drives_opt[index].used) {
2180 drives_opt[index].used = 1;
2181 return index;
2184 return -1;
2187 static int drive_get_free_idx(void)
2189 int index;
2191 for (index = 0; index < MAX_DRIVES; index++)
2192 if (!drives_table[index].used) {
2193 drives_table[index].used = 1;
2194 return index;
2197 return -1;
2200 int drive_add(const char *file, const char *fmt, ...)
2202 va_list ap;
2203 int index = drive_opt_get_free_idx();
2205 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2206 fprintf(stderr, "qemu: too many drives\n");
2207 return -1;
2210 drives_opt[index].file = file;
2211 va_start(ap, fmt);
2212 vsnprintf(drives_opt[index].opt,
2213 sizeof(drives_opt[0].opt), fmt, ap);
2214 va_end(ap);
2216 nb_drives_opt++;
2217 return index;
2220 void drive_remove(int index)
2222 drives_opt[index].used = 0;
2223 nb_drives_opt--;
2226 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2228 int index;
2230 /* seek interface, bus and unit */
2232 for (index = 0; index < MAX_DRIVES; index++)
2233 if (drives_table[index].type == type &&
2234 drives_table[index].bus == bus &&
2235 drives_table[index].unit == unit &&
2236 drives_table[index].used)
2237 return index;
2239 return -1;
2242 int drive_get_max_bus(BlockInterfaceType type)
2244 int max_bus;
2245 int index;
2247 max_bus = -1;
2248 for (index = 0; index < nb_drives; index++) {
2249 if(drives_table[index].type == type &&
2250 drives_table[index].bus > max_bus)
2251 max_bus = drives_table[index].bus;
2253 return max_bus;
2256 const char *drive_get_serial(BlockDriverState *bdrv)
2258 int index;
2260 for (index = 0; index < nb_drives; index++)
2261 if (drives_table[index].bdrv == bdrv)
2262 return drives_table[index].serial;
2264 return "\0";
2267 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2269 int index;
2271 for (index = 0; index < nb_drives; index++)
2272 if (drives_table[index].bdrv == bdrv)
2273 return drives_table[index].onerror;
2275 return BLOCK_ERR_STOP_ENOSPC;
2278 static void bdrv_format_print(void *opaque, const char *name)
2280 fprintf(stderr, " %s", name);
2283 void drive_uninit(BlockDriverState *bdrv)
2285 int i;
2287 for (i = 0; i < MAX_DRIVES; i++)
2288 if (drives_table[i].bdrv == bdrv) {
2289 drives_table[i].bdrv = NULL;
2290 drives_table[i].used = 0;
2291 drive_remove(drives_table[i].drive_opt_idx);
2292 nb_drives--;
2293 break;
2297 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2299 char buf[128];
2300 char file[1024];
2301 char devname[128];
2302 char serial[21];
2303 const char *mediastr = "";
2304 BlockInterfaceType type;
2305 enum { MEDIA_DISK, MEDIA_CDROM } media;
2306 int bus_id, unit_id;
2307 int cyls, heads, secs, translation;
2308 BlockDriverState *bdrv;
2309 BlockDriver *drv = NULL;
2310 QEMUMachine *machine = opaque;
2311 int max_devs;
2312 int index;
2313 int cache;
2314 int bdrv_flags, onerror;
2315 int drives_table_idx;
2316 char *str = arg->opt;
2317 static const char * const params[] = { "bus", "unit", "if", "index",
2318 "cyls", "heads", "secs", "trans",
2319 "media", "snapshot", "file",
2320 "cache", "format", "serial", "werror",
2321 "boot", NULL };
2323 if (check_params(buf, sizeof(buf), params, str) < 0) {
2324 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2325 buf, str);
2326 return -1;
2329 file[0] = 0;
2330 cyls = heads = secs = 0;
2331 bus_id = 0;
2332 unit_id = -1;
2333 translation = BIOS_ATA_TRANSLATION_AUTO;
2334 index = -1;
2335 cache = 3;
2337 if (machine->use_scsi) {
2338 type = IF_SCSI;
2339 max_devs = MAX_SCSI_DEVS;
2340 pstrcpy(devname, sizeof(devname), "scsi");
2341 } else {
2342 type = IF_IDE;
2343 max_devs = MAX_IDE_DEVS;
2344 pstrcpy(devname, sizeof(devname), "ide");
2346 media = MEDIA_DISK;
2348 /* extract parameters */
2350 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2351 bus_id = strtol(buf, NULL, 0);
2352 if (bus_id < 0) {
2353 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2354 return -1;
2358 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2359 unit_id = strtol(buf, NULL, 0);
2360 if (unit_id < 0) {
2361 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2362 return -1;
2366 if (get_param_value(buf, sizeof(buf), "if", str)) {
2367 pstrcpy(devname, sizeof(devname), buf);
2368 if (!strcmp(buf, "ide")) {
2369 type = IF_IDE;
2370 max_devs = MAX_IDE_DEVS;
2371 } else if (!strcmp(buf, "scsi")) {
2372 type = IF_SCSI;
2373 max_devs = MAX_SCSI_DEVS;
2374 } else if (!strcmp(buf, "floppy")) {
2375 type = IF_FLOPPY;
2376 max_devs = 0;
2377 } else if (!strcmp(buf, "pflash")) {
2378 type = IF_PFLASH;
2379 max_devs = 0;
2380 } else if (!strcmp(buf, "mtd")) {
2381 type = IF_MTD;
2382 max_devs = 0;
2383 } else if (!strcmp(buf, "sd")) {
2384 type = IF_SD;
2385 max_devs = 0;
2386 } else if (!strcmp(buf, "virtio")) {
2387 type = IF_VIRTIO;
2388 max_devs = 0;
2389 } else {
2390 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2391 return -1;
2395 if (get_param_value(buf, sizeof(buf), "index", str)) {
2396 index = strtol(buf, NULL, 0);
2397 if (index < 0) {
2398 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2399 return -1;
2403 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2404 cyls = strtol(buf, NULL, 0);
2407 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2408 heads = strtol(buf, NULL, 0);
2411 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2412 secs = strtol(buf, NULL, 0);
2415 if (cyls || heads || secs) {
2416 if (cyls < 1 || cyls > 16383) {
2417 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2418 return -1;
2420 if (heads < 1 || heads > 16) {
2421 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2422 return -1;
2424 if (secs < 1 || secs > 63) {
2425 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2426 return -1;
2430 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2431 if (!cyls) {
2432 fprintf(stderr,
2433 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2434 str);
2435 return -1;
2437 if (!strcmp(buf, "none"))
2438 translation = BIOS_ATA_TRANSLATION_NONE;
2439 else if (!strcmp(buf, "lba"))
2440 translation = BIOS_ATA_TRANSLATION_LBA;
2441 else if (!strcmp(buf, "auto"))
2442 translation = BIOS_ATA_TRANSLATION_AUTO;
2443 else {
2444 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2445 return -1;
2449 if (get_param_value(buf, sizeof(buf), "media", str)) {
2450 if (!strcmp(buf, "disk")) {
2451 media = MEDIA_DISK;
2452 } else if (!strcmp(buf, "cdrom")) {
2453 if (cyls || secs || heads) {
2454 fprintf(stderr,
2455 "qemu: '%s' invalid physical CHS format\n", str);
2456 return -1;
2458 media = MEDIA_CDROM;
2459 } else {
2460 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2461 return -1;
2465 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2466 if (!strcmp(buf, "on"))
2467 snapshot = 1;
2468 else if (!strcmp(buf, "off"))
2469 snapshot = 0;
2470 else {
2471 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2472 return -1;
2476 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2477 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2478 cache = 0;
2479 else if (!strcmp(buf, "writethrough"))
2480 cache = 1;
2481 else if (!strcmp(buf, "writeback"))
2482 cache = 2;
2483 else {
2484 fprintf(stderr, "qemu: invalid cache option\n");
2485 return -1;
2489 if (get_param_value(buf, sizeof(buf), "format", str)) {
2490 if (strcmp(buf, "?") == 0) {
2491 fprintf(stderr, "qemu: Supported formats:");
2492 bdrv_iterate_format(bdrv_format_print, NULL);
2493 fprintf(stderr, "\n");
2494 return -1;
2496 drv = bdrv_find_format(buf);
2497 if (!drv) {
2498 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2499 return -1;
2503 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2504 if (!strcmp(buf, "on")) {
2505 if (extboot_drive != -1) {
2506 fprintf(stderr, "qemu: two bootable drives specified\n");
2507 return -1;
2509 extboot_drive = nb_drives;
2510 } else if (strcmp(buf, "off")) {
2511 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2512 return -1;
2516 if (arg->file == NULL)
2517 get_param_value(file, sizeof(file), "file", str);
2518 else
2519 pstrcpy(file, sizeof(file), arg->file);
2521 if (!get_param_value(serial, sizeof(serial), "serial", str))
2522 memset(serial, 0, sizeof(serial));
2524 onerror = BLOCK_ERR_STOP_ENOSPC;
2525 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2526 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2527 fprintf(stderr, "werror is no supported by this format\n");
2528 return -1;
2530 if (!strcmp(buf, "ignore"))
2531 onerror = BLOCK_ERR_IGNORE;
2532 else if (!strcmp(buf, "enospc"))
2533 onerror = BLOCK_ERR_STOP_ENOSPC;
2534 else if (!strcmp(buf, "stop"))
2535 onerror = BLOCK_ERR_STOP_ANY;
2536 else if (!strcmp(buf, "report"))
2537 onerror = BLOCK_ERR_REPORT;
2538 else {
2539 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2540 return -1;
2544 /* compute bus and unit according index */
2546 if (index != -1) {
2547 if (bus_id != 0 || unit_id != -1) {
2548 fprintf(stderr,
2549 "qemu: '%s' index cannot be used with bus and unit\n", str);
2550 return -1;
2552 if (max_devs == 0)
2554 unit_id = index;
2555 bus_id = 0;
2556 } else {
2557 unit_id = index % max_devs;
2558 bus_id = index / max_devs;
2562 /* if user doesn't specify a unit_id,
2563 * try to find the first free
2566 if (unit_id == -1) {
2567 unit_id = 0;
2568 while (drive_get_index(type, bus_id, unit_id) != -1) {
2569 unit_id++;
2570 if (max_devs && unit_id >= max_devs) {
2571 unit_id -= max_devs;
2572 bus_id++;
2577 /* check unit id */
2579 if (max_devs && unit_id >= max_devs) {
2580 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2581 str, unit_id, max_devs - 1);
2582 return -1;
2586 * ignore multiple definitions
2589 if (drive_get_index(type, bus_id, unit_id) != -1)
2590 return -2;
2592 /* init */
2594 if (type == IF_IDE || type == IF_SCSI)
2595 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2596 if (max_devs)
2597 snprintf(buf, sizeof(buf), "%s%i%s%i",
2598 devname, bus_id, mediastr, unit_id);
2599 else
2600 snprintf(buf, sizeof(buf), "%s%s%i",
2601 devname, mediastr, unit_id);
2602 bdrv = bdrv_new(buf);
2603 drives_table_idx = drive_get_free_idx();
2604 drives_table[drives_table_idx].bdrv = bdrv;
2605 drives_table[drives_table_idx].type = type;
2606 drives_table[drives_table_idx].bus = bus_id;
2607 drives_table[drives_table_idx].unit = unit_id;
2608 drives_table[drives_table_idx].onerror = onerror;
2609 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2610 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2611 nb_drives++;
2613 switch(type) {
2614 case IF_IDE:
2615 case IF_SCSI:
2616 switch(media) {
2617 case MEDIA_DISK:
2618 if (cyls != 0) {
2619 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2620 bdrv_set_translation_hint(bdrv, translation);
2622 break;
2623 case MEDIA_CDROM:
2624 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2625 break;
2627 break;
2628 case IF_SD:
2629 /* FIXME: This isn't really a floppy, but it's a reasonable
2630 approximation. */
2631 case IF_FLOPPY:
2632 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2633 break;
2634 case IF_PFLASH:
2635 case IF_MTD:
2636 case IF_VIRTIO:
2637 break;
2639 if (!file[0])
2640 return -2;
2641 bdrv_flags = 0;
2642 if (snapshot) {
2643 bdrv_flags |= BDRV_O_SNAPSHOT;
2644 cache = 2; /* always use write-back with snapshot */
2646 if (cache == 0) /* no caching */
2647 bdrv_flags |= BDRV_O_NOCACHE;
2648 else if (cache == 2) /* write-back */
2649 bdrv_flags |= BDRV_O_CACHE_WB;
2650 else if (cache == 3) /* not specified */
2651 bdrv_flags |= BDRV_O_CACHE_DEF;
2652 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2653 fprintf(stderr, "qemu: could not open disk image %s\n",
2654 file);
2655 return -1;
2657 if (bdrv_key_required(bdrv))
2658 autostart = 0;
2659 return drives_table_idx;
2662 /***********************************************************/
2663 /* USB devices */
2665 static USBPort *used_usb_ports;
2666 static USBPort *free_usb_ports;
2668 /* ??? Maybe change this to register a hub to keep track of the topology. */
2669 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2670 usb_attachfn attach)
2672 port->opaque = opaque;
2673 port->index = index;
2674 port->attach = attach;
2675 port->next = free_usb_ports;
2676 free_usb_ports = port;
2679 int usb_device_add_dev(USBDevice *dev)
2681 USBPort *port;
2683 /* Find a USB port to add the device to. */
2684 port = free_usb_ports;
2685 if (!port->next) {
2686 USBDevice *hub;
2688 /* Create a new hub and chain it on. */
2689 free_usb_ports = NULL;
2690 port->next = used_usb_ports;
2691 used_usb_ports = port;
2693 hub = usb_hub_init(VM_USB_HUB_SIZE);
2694 usb_attach(port, hub);
2695 port = free_usb_ports;
2698 free_usb_ports = port->next;
2699 port->next = used_usb_ports;
2700 used_usb_ports = port;
2701 usb_attach(port, dev);
2702 return 0;
2705 static int usb_device_add(const char *devname, int is_hotplug)
2707 const char *p;
2708 USBDevice *dev;
2710 if (!free_usb_ports)
2711 return -1;
2713 if (strstart(devname, "host:", &p)) {
2714 dev = usb_host_device_open(p);
2715 } else if (!strcmp(devname, "mouse")) {
2716 dev = usb_mouse_init();
2717 } else if (!strcmp(devname, "tablet")) {
2718 dev = usb_tablet_init();
2719 } else if (!strcmp(devname, "keyboard")) {
2720 dev = usb_keyboard_init();
2721 } else if (strstart(devname, "disk:", &p)) {
2722 BlockDriverState *bs;
2724 dev = usb_msd_init(p, &bs);
2725 if (!dev)
2726 return -1;
2727 if (bdrv_key_required(bs)) {
2728 autostart = 0;
2729 if (is_hotplug && monitor_read_bdrv_key(bs) < 0) {
2730 dev->handle_destroy(dev);
2731 return -1;
2734 } else if (!strcmp(devname, "wacom-tablet")) {
2735 dev = usb_wacom_init();
2736 } else if (strstart(devname, "serial:", &p)) {
2737 dev = usb_serial_init(p);
2738 #ifdef CONFIG_BRLAPI
2739 } else if (!strcmp(devname, "braille")) {
2740 dev = usb_baum_init();
2741 #endif
2742 } else if (strstart(devname, "net:", &p)) {
2743 int nic = nb_nics;
2745 if (net_client_init("nic", p) < 0)
2746 return -1;
2747 nd_table[nic].model = "usb";
2748 dev = usb_net_init(&nd_table[nic]);
2749 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2750 dev = usb_bt_init(devname[2] ? hci_init(p) :
2751 bt_new_hci(qemu_find_bt_vlan(0)));
2752 } else {
2753 return -1;
2755 if (!dev)
2756 return -1;
2758 return usb_device_add_dev(dev);
2761 int usb_device_del_addr(int bus_num, int addr)
2763 USBPort *port;
2764 USBPort **lastp;
2765 USBDevice *dev;
2767 if (!used_usb_ports)
2768 return -1;
2770 if (bus_num != 0)
2771 return -1;
2773 lastp = &used_usb_ports;
2774 port = used_usb_ports;
2775 while (port && port->dev->addr != addr) {
2776 lastp = &port->next;
2777 port = port->next;
2780 if (!port)
2781 return -1;
2783 dev = port->dev;
2784 *lastp = port->next;
2785 usb_attach(port, NULL);
2786 dev->handle_destroy(dev);
2787 port->next = free_usb_ports;
2788 free_usb_ports = port;
2789 return 0;
2792 static int usb_device_del(const char *devname)
2794 int bus_num, addr;
2795 const char *p;
2797 if (strstart(devname, "host:", &p))
2798 return usb_host_device_close(p);
2800 if (!used_usb_ports)
2801 return -1;
2803 p = strchr(devname, '.');
2804 if (!p)
2805 return -1;
2806 bus_num = strtoul(devname, NULL, 0);
2807 addr = strtoul(p + 1, NULL, 0);
2809 return usb_device_del_addr(bus_num, addr);
2812 void do_usb_add(const char *devname)
2814 usb_device_add(devname, 1);
2817 void do_usb_del(const char *devname)
2819 usb_device_del(devname);
2822 void usb_info(void)
2824 USBDevice *dev;
2825 USBPort *port;
2826 const char *speed_str;
2828 if (!usb_enabled) {
2829 term_printf("USB support not enabled\n");
2830 return;
2833 for (port = used_usb_ports; port; port = port->next) {
2834 dev = port->dev;
2835 if (!dev)
2836 continue;
2837 switch(dev->speed) {
2838 case USB_SPEED_LOW:
2839 speed_str = "1.5";
2840 break;
2841 case USB_SPEED_FULL:
2842 speed_str = "12";
2843 break;
2844 case USB_SPEED_HIGH:
2845 speed_str = "480";
2846 break;
2847 default:
2848 speed_str = "?";
2849 break;
2851 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2852 0, dev->addr, speed_str, dev->devname);
2856 /***********************************************************/
2857 /* PCMCIA/Cardbus */
2859 static struct pcmcia_socket_entry_s {
2860 struct pcmcia_socket_s *socket;
2861 struct pcmcia_socket_entry_s *next;
2862 } *pcmcia_sockets = 0;
2864 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2866 struct pcmcia_socket_entry_s *entry;
2868 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2869 entry->socket = socket;
2870 entry->next = pcmcia_sockets;
2871 pcmcia_sockets = entry;
2874 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2876 struct pcmcia_socket_entry_s *entry, **ptr;
2878 ptr = &pcmcia_sockets;
2879 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2880 if (entry->socket == socket) {
2881 *ptr = entry->next;
2882 qemu_free(entry);
2886 void pcmcia_info(void)
2888 struct pcmcia_socket_entry_s *iter;
2889 if (!pcmcia_sockets)
2890 term_printf("No PCMCIA sockets\n");
2892 for (iter = pcmcia_sockets; iter; iter = iter->next)
2893 term_printf("%s: %s\n", iter->socket->slot_string,
2894 iter->socket->attached ? iter->socket->card_string :
2895 "Empty");
2898 /***********************************************************/
2899 /* register display */
2901 void register_displaystate(DisplayState *ds)
2903 DisplayState **s;
2904 s = &display_state;
2905 while (*s != NULL)
2906 s = &(*s)->next;
2907 ds->next = NULL;
2908 *s = ds;
2911 DisplayState *get_displaystate(void)
2913 return display_state;
2916 /* dumb display */
2918 static void dumb_display_init(void)
2920 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2921 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2922 register_displaystate(ds);
2925 /***********************************************************/
2926 /* I/O handling */
2928 #define MAX_IO_HANDLERS 64
2930 typedef struct IOHandlerRecord {
2931 int fd;
2932 IOCanRWHandler *fd_read_poll;
2933 IOHandler *fd_read;
2934 IOHandler *fd_write;
2935 int deleted;
2936 void *opaque;
2937 /* temporary data */
2938 struct pollfd *ufd;
2939 struct IOHandlerRecord *next;
2940 } IOHandlerRecord;
2942 static IOHandlerRecord *first_io_handler;
2944 /* XXX: fd_read_poll should be suppressed, but an API change is
2945 necessary in the character devices to suppress fd_can_read(). */
2946 int qemu_set_fd_handler2(int fd,
2947 IOCanRWHandler *fd_read_poll,
2948 IOHandler *fd_read,
2949 IOHandler *fd_write,
2950 void *opaque)
2952 IOHandlerRecord **pioh, *ioh;
2954 if (!fd_read && !fd_write) {
2955 pioh = &first_io_handler;
2956 for(;;) {
2957 ioh = *pioh;
2958 if (ioh == NULL)
2959 break;
2960 if (ioh->fd == fd) {
2961 ioh->deleted = 1;
2962 break;
2964 pioh = &ioh->next;
2966 } else {
2967 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2968 if (ioh->fd == fd)
2969 goto found;
2971 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2972 ioh->next = first_io_handler;
2973 first_io_handler = ioh;
2974 found:
2975 ioh->fd = fd;
2976 ioh->fd_read_poll = fd_read_poll;
2977 ioh->fd_read = fd_read;
2978 ioh->fd_write = fd_write;
2979 ioh->opaque = opaque;
2980 ioh->deleted = 0;
2982 main_loop_break();
2983 return 0;
2986 int qemu_set_fd_handler(int fd,
2987 IOHandler *fd_read,
2988 IOHandler *fd_write,
2989 void *opaque)
2991 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2994 #ifdef _WIN32
2995 /***********************************************************/
2996 /* Polling handling */
2998 typedef struct PollingEntry {
2999 PollingFunc *func;
3000 void *opaque;
3001 struct PollingEntry *next;
3002 } PollingEntry;
3004 static PollingEntry *first_polling_entry;
3006 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3008 PollingEntry **ppe, *pe;
3009 pe = qemu_mallocz(sizeof(PollingEntry));
3010 pe->func = func;
3011 pe->opaque = opaque;
3012 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3013 *ppe = pe;
3014 return 0;
3017 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3019 PollingEntry **ppe, *pe;
3020 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3021 pe = *ppe;
3022 if (pe->func == func && pe->opaque == opaque) {
3023 *ppe = pe->next;
3024 qemu_free(pe);
3025 break;
3030 /***********************************************************/
3031 /* Wait objects support */
3032 typedef struct WaitObjects {
3033 int num;
3034 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3035 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3036 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3037 } WaitObjects;
3039 static WaitObjects wait_objects = {0};
3041 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3043 WaitObjects *w = &wait_objects;
3045 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3046 return -1;
3047 w->events[w->num] = handle;
3048 w->func[w->num] = func;
3049 w->opaque[w->num] = opaque;
3050 w->num++;
3051 return 0;
3054 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3056 int i, found;
3057 WaitObjects *w = &wait_objects;
3059 found = 0;
3060 for (i = 0; i < w->num; i++) {
3061 if (w->events[i] == handle)
3062 found = 1;
3063 if (found) {
3064 w->events[i] = w->events[i + 1];
3065 w->func[i] = w->func[i + 1];
3066 w->opaque[i] = w->opaque[i + 1];
3069 if (found)
3070 w->num--;
3072 #endif
3074 /***********************************************************/
3075 /* ram save/restore */
3077 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3079 int v;
3081 v = qemu_get_byte(f);
3082 switch(v) {
3083 case 0:
3084 if (qemu_get_buffer(f, buf, len) != len)
3085 return -EIO;
3086 break;
3087 case 1:
3088 v = qemu_get_byte(f);
3089 memset(buf, v, len);
3090 break;
3091 default:
3092 return -EINVAL;
3095 if (qemu_file_has_error(f))
3096 return -EIO;
3098 return 0;
3101 static int ram_load_v1(QEMUFile *f, void *opaque)
3103 int ret;
3104 ram_addr_t i;
3106 if (qemu_get_be32(f) != phys_ram_size)
3107 return -EINVAL;
3108 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3109 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3110 continue;
3111 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3112 if (ret)
3113 return ret;
3115 return 0;
3118 #define BDRV_HASH_BLOCK_SIZE 1024
3119 #define IOBUF_SIZE 4096
3120 #define RAM_CBLOCK_MAGIC 0xfabe
3122 typedef struct RamDecompressState {
3123 z_stream zstream;
3124 QEMUFile *f;
3125 uint8_t buf[IOBUF_SIZE];
3126 } RamDecompressState;
3128 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3130 int ret;
3131 memset(s, 0, sizeof(*s));
3132 s->f = f;
3133 ret = inflateInit(&s->zstream);
3134 if (ret != Z_OK)
3135 return -1;
3136 return 0;
3139 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3141 int ret, clen;
3143 s->zstream.avail_out = len;
3144 s->zstream.next_out = buf;
3145 while (s->zstream.avail_out > 0) {
3146 if (s->zstream.avail_in == 0) {
3147 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3148 return -1;
3149 clen = qemu_get_be16(s->f);
3150 if (clen > IOBUF_SIZE)
3151 return -1;
3152 qemu_get_buffer(s->f, s->buf, clen);
3153 s->zstream.avail_in = clen;
3154 s->zstream.next_in = s->buf;
3156 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3157 if (ret != Z_OK && ret != Z_STREAM_END) {
3158 return -1;
3161 return 0;
3164 static void ram_decompress_close(RamDecompressState *s)
3166 inflateEnd(&s->zstream);
3169 #define RAM_SAVE_FLAG_FULL 0x01
3170 #define RAM_SAVE_FLAG_COMPRESS 0x02
3171 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3172 #define RAM_SAVE_FLAG_PAGE 0x08
3173 #define RAM_SAVE_FLAG_EOS 0x10
3175 static int is_dup_page(uint8_t *page, uint8_t ch)
3177 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3178 uint32_t *array = (uint32_t *)page;
3179 int i;
3181 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3182 if (array[i] != val)
3183 return 0;
3186 return 1;
3189 static int ram_save_block(QEMUFile *f)
3191 static ram_addr_t current_addr = 0;
3192 ram_addr_t saved_addr = current_addr;
3193 ram_addr_t addr = 0;
3194 int found = 0;
3196 while (addr < phys_ram_size) {
3197 if (kvm_enabled() && current_addr == 0)
3198 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3199 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3200 uint8_t ch;
3202 cpu_physical_memory_reset_dirty(current_addr,
3203 current_addr + TARGET_PAGE_SIZE,
3204 MIGRATION_DIRTY_FLAG);
3206 ch = *(phys_ram_base + current_addr);
3208 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3209 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3210 qemu_put_byte(f, ch);
3211 } else {
3212 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3213 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3216 found = 1;
3217 break;
3219 addr += TARGET_PAGE_SIZE;
3220 current_addr = (saved_addr + addr) % phys_ram_size;
3223 return found;
3226 static ram_addr_t ram_save_threshold = 10;
3228 static ram_addr_t ram_save_remaining(void)
3230 ram_addr_t addr;
3231 ram_addr_t count = 0;
3233 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3234 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3235 count++;
3238 return count;
3241 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3243 ram_addr_t addr;
3245 if (stage == 1) {
3246 /* Make sure all dirty bits are set */
3247 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3248 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3249 cpu_physical_memory_set_dirty(addr);
3252 /* Enable dirty memory tracking */
3253 cpu_physical_memory_set_dirty_tracking(1);
3255 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3258 while (!qemu_file_rate_limit(f)) {
3259 int ret;
3261 ret = ram_save_block(f);
3262 if (ret == 0) /* no more blocks */
3263 break;
3266 /* try transferring iterative blocks of memory */
3268 if (stage == 3) {
3270 /* flush all remaining blocks regardless of rate limiting */
3271 while (ram_save_block(f) != 0);
3272 cpu_physical_memory_set_dirty_tracking(0);
3275 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3277 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3280 static int ram_load_dead(QEMUFile *f, void *opaque)
3282 RamDecompressState s1, *s = &s1;
3283 uint8_t buf[10];
3284 ram_addr_t i;
3286 if (ram_decompress_open(s, f) < 0)
3287 return -EINVAL;
3288 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3289 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3290 continue;
3291 if (ram_decompress_buf(s, buf, 1) < 0) {
3292 fprintf(stderr, "Error while reading ram block header\n");
3293 goto error;
3295 if (buf[0] == 0) {
3296 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3297 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3298 goto error;
3300 } else {
3301 error:
3302 printf("Error block header\n");
3303 return -EINVAL;
3306 ram_decompress_close(s);
3308 return 0;
3311 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3313 ram_addr_t addr;
3314 int flags;
3316 if (version_id == 1)
3317 return ram_load_v1(f, opaque);
3319 if (version_id == 2) {
3320 if (qemu_get_be32(f) != phys_ram_size)
3321 return -EINVAL;
3322 return ram_load_dead(f, opaque);
3325 if (version_id != 3)
3326 return -EINVAL;
3328 do {
3329 addr = qemu_get_be64(f);
3331 flags = addr & ~TARGET_PAGE_MASK;
3332 addr &= TARGET_PAGE_MASK;
3334 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3335 if (addr != phys_ram_size)
3336 return -EINVAL;
3339 if (flags & RAM_SAVE_FLAG_FULL) {
3340 if (ram_load_dead(f, opaque) < 0)
3341 return -EINVAL;
3344 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3345 uint8_t ch = qemu_get_byte(f);
3346 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3347 } else if (flags & RAM_SAVE_FLAG_PAGE)
3348 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3349 } while (!(flags & RAM_SAVE_FLAG_EOS));
3351 return 0;
3354 /***********************************************************/
3355 /* bottom halves (can be seen as timers which expire ASAP) */
3357 struct QEMUBH {
3358 QEMUBHFunc *cb;
3359 void *opaque;
3360 int scheduled;
3361 int idle;
3362 int deleted;
3363 QEMUBH *next;
3366 static QEMUBH *first_bh = NULL;
3368 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3370 QEMUBH *bh;
3371 bh = qemu_mallocz(sizeof(QEMUBH));
3372 bh->cb = cb;
3373 bh->opaque = opaque;
3374 bh->next = first_bh;
3375 first_bh = bh;
3376 return bh;
3379 int qemu_bh_poll(void)
3381 QEMUBH *bh, **bhp;
3382 int ret;
3384 ret = 0;
3385 for (bh = first_bh; bh; bh = bh->next) {
3386 if (!bh->deleted && bh->scheduled) {
3387 bh->scheduled = 0;
3388 if (!bh->idle)
3389 ret = 1;
3390 bh->idle = 0;
3391 bh->cb(bh->opaque);
3395 /* remove deleted bhs */
3396 bhp = &first_bh;
3397 while (*bhp) {
3398 bh = *bhp;
3399 if (bh->deleted) {
3400 *bhp = bh->next;
3401 qemu_free(bh);
3402 } else
3403 bhp = &bh->next;
3406 return ret;
3409 void qemu_bh_schedule_idle(QEMUBH *bh)
3411 if (bh->scheduled)
3412 return;
3413 bh->scheduled = 1;
3414 bh->idle = 1;
3417 void qemu_bh_schedule(QEMUBH *bh)
3419 CPUState *env = cpu_single_env;
3420 if (bh->scheduled)
3421 return;
3422 bh->scheduled = 1;
3423 bh->idle = 0;
3424 /* stop the currently executing CPU to execute the BH ASAP */
3425 if (env) {
3426 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3428 main_loop_break();
3431 void qemu_bh_cancel(QEMUBH *bh)
3433 bh->scheduled = 0;
3436 void qemu_bh_delete(QEMUBH *bh)
3438 bh->scheduled = 0;
3439 bh->deleted = 1;
3442 static void qemu_bh_update_timeout(int *timeout)
3444 QEMUBH *bh;
3446 for (bh = first_bh; bh; bh = bh->next) {
3447 if (!bh->deleted && bh->scheduled) {
3448 if (bh->idle) {
3449 /* idle bottom halves will be polled at least
3450 * every 10ms */
3451 *timeout = MIN(10, *timeout);
3452 } else {
3453 /* non-idle bottom halves will be executed
3454 * immediately */
3455 *timeout = 0;
3456 break;
3462 /***********************************************************/
3463 /* machine registration */
3465 static QEMUMachine *first_machine = NULL;
3466 QEMUMachine *current_machine = NULL;
3468 int qemu_register_machine(QEMUMachine *m)
3470 QEMUMachine **pm;
3471 pm = &first_machine;
3472 while (*pm != NULL)
3473 pm = &(*pm)->next;
3474 m->next = NULL;
3475 *pm = m;
3476 return 0;
3479 static QEMUMachine *find_machine(const char *name)
3481 QEMUMachine *m;
3483 for(m = first_machine; m != NULL; m = m->next) {
3484 if (!strcmp(m->name, name))
3485 return m;
3487 return NULL;
3490 /***********************************************************/
3491 /* main execution loop */
3493 static void gui_update(void *opaque)
3495 uint64_t interval = GUI_REFRESH_INTERVAL;
3496 DisplayState *ds = opaque;
3497 DisplayChangeListener *dcl = ds->listeners;
3499 dpy_refresh(ds);
3501 while (dcl != NULL) {
3502 if (dcl->gui_timer_interval &&
3503 dcl->gui_timer_interval < interval)
3504 interval = dcl->gui_timer_interval;
3505 dcl = dcl->next;
3507 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3510 static void nographic_update(void *opaque)
3512 uint64_t interval = GUI_REFRESH_INTERVAL;
3514 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3517 struct vm_change_state_entry {
3518 VMChangeStateHandler *cb;
3519 void *opaque;
3520 LIST_ENTRY (vm_change_state_entry) entries;
3523 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3525 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3526 void *opaque)
3528 VMChangeStateEntry *e;
3530 e = qemu_mallocz(sizeof (*e));
3532 e->cb = cb;
3533 e->opaque = opaque;
3534 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3535 return e;
3538 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3540 LIST_REMOVE (e, entries);
3541 qemu_free (e);
3544 static void vm_state_notify(int running, int reason)
3546 VMChangeStateEntry *e;
3548 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3549 e->cb(e->opaque, running, reason);
3553 void vm_start(void)
3555 if (!vm_running) {
3556 cpu_enable_ticks();
3557 vm_running = 1;
3558 vm_state_notify(1, 0);
3559 qemu_rearm_alarm_timer(alarm_timer);
3563 void vm_stop(int reason)
3565 if (vm_running) {
3566 cpu_disable_ticks();
3567 vm_running = 0;
3568 vm_state_notify(0, reason);
3572 /* reset/shutdown handler */
3574 typedef struct QEMUResetEntry {
3575 QEMUResetHandler *func;
3576 void *opaque;
3577 struct QEMUResetEntry *next;
3578 } QEMUResetEntry;
3580 static QEMUResetEntry *first_reset_entry;
3581 static int reset_requested;
3582 static int shutdown_requested;
3583 static int powerdown_requested;
3585 int qemu_shutdown_requested(void)
3587 int r = shutdown_requested;
3588 shutdown_requested = 0;
3589 return r;
3592 int qemu_reset_requested(void)
3594 int r = reset_requested;
3595 reset_requested = 0;
3596 return r;
3599 int qemu_powerdown_requested(void)
3601 int r = powerdown_requested;
3602 powerdown_requested = 0;
3603 return r;
3606 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3608 QEMUResetEntry **pre, *re;
3610 pre = &first_reset_entry;
3611 while (*pre != NULL)
3612 pre = &(*pre)->next;
3613 re = qemu_mallocz(sizeof(QEMUResetEntry));
3614 re->func = func;
3615 re->opaque = opaque;
3616 re->next = NULL;
3617 *pre = re;
3620 void qemu_system_reset(void)
3622 QEMUResetEntry *re;
3624 /* reset all devices */
3625 for(re = first_reset_entry; re != NULL; re = re->next) {
3626 re->func(re->opaque);
3630 void qemu_system_reset_request(void)
3632 if (no_reboot) {
3633 shutdown_requested = 1;
3634 } else {
3635 reset_requested = 1;
3638 if (cpu_single_env) {
3639 qemu_kvm_cpu_stop(cpu_single_env);
3640 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3642 main_loop_break();
3645 void qemu_system_shutdown_request(void)
3647 shutdown_requested = 1;
3648 if (cpu_single_env)
3649 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3652 void qemu_system_powerdown_request(void)
3654 powerdown_requested = 1;
3655 if (cpu_single_env)
3656 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3659 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3660 struct timeval *tv)
3662 int ret;
3664 /* KVM holds a mutex while QEMU code is running, we need hooks to
3665 release the mutex whenever QEMU code sleeps. */
3667 kvm_sleep_begin();
3669 ret = select(max_fd, rfds, wfds, xfds, tv);
3671 kvm_sleep_end();
3673 return ret;
3676 #ifdef _WIN32
3677 static void host_main_loop_wait(int *timeout)
3679 int ret, ret2, i;
3680 PollingEntry *pe;
3683 /* XXX: need to suppress polling by better using win32 events */
3684 ret = 0;
3685 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3686 ret |= pe->func(pe->opaque);
3688 if (ret == 0) {
3689 int err;
3690 WaitObjects *w = &wait_objects;
3692 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3693 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3694 if (w->func[ret - WAIT_OBJECT_0])
3695 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3697 /* Check for additional signaled events */
3698 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3700 /* Check if event is signaled */
3701 ret2 = WaitForSingleObject(w->events[i], 0);
3702 if(ret2 == WAIT_OBJECT_0) {
3703 if (w->func[i])
3704 w->func[i](w->opaque[i]);
3705 } else if (ret2 == WAIT_TIMEOUT) {
3706 } else {
3707 err = GetLastError();
3708 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3711 } else if (ret == WAIT_TIMEOUT) {
3712 } else {
3713 err = GetLastError();
3714 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3718 *timeout = 0;
3720 #else
3721 static void host_main_loop_wait(int *timeout)
3724 #endif
3726 void main_loop_wait(int timeout)
3728 IOHandlerRecord *ioh;
3729 fd_set rfds, wfds, xfds;
3730 int ret, nfds;
3731 struct timeval tv;
3733 qemu_bh_update_timeout(&timeout);
3735 host_main_loop_wait(&timeout);
3737 /* poll any events */
3738 /* XXX: separate device handlers from system ones */
3739 nfds = -1;
3740 FD_ZERO(&rfds);
3741 FD_ZERO(&wfds);
3742 FD_ZERO(&xfds);
3743 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3744 if (ioh->deleted)
3745 continue;
3746 if (ioh->fd_read &&
3747 (!ioh->fd_read_poll ||
3748 ioh->fd_read_poll(ioh->opaque) != 0)) {
3749 FD_SET(ioh->fd, &rfds);
3750 if (ioh->fd > nfds)
3751 nfds = ioh->fd;
3753 if (ioh->fd_write) {
3754 FD_SET(ioh->fd, &wfds);
3755 if (ioh->fd > nfds)
3756 nfds = ioh->fd;
3760 tv.tv_sec = timeout / 1000;
3761 tv.tv_usec = (timeout % 1000) * 1000;
3763 #if defined(CONFIG_SLIRP)
3764 if (slirp_is_inited()) {
3765 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3767 #endif
3768 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3769 if (ret > 0) {
3770 IOHandlerRecord **pioh;
3772 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3773 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3774 ioh->fd_read(ioh->opaque);
3775 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3776 FD_CLR(ioh->fd, &rfds);
3778 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3779 ioh->fd_write(ioh->opaque);
3783 /* remove deleted IO handlers */
3784 pioh = &first_io_handler;
3785 while (*pioh) {
3786 ioh = *pioh;
3787 if (ioh->deleted) {
3788 *pioh = ioh->next;
3789 qemu_free(ioh);
3790 } else
3791 pioh = &ioh->next;
3794 #if defined(CONFIG_SLIRP)
3795 if (slirp_is_inited()) {
3796 if (ret < 0) {
3797 FD_ZERO(&rfds);
3798 FD_ZERO(&wfds);
3799 FD_ZERO(&xfds);
3801 slirp_select_poll(&rfds, &wfds, &xfds);
3803 #endif
3805 /* vm time timers */
3806 if (vm_running && (!cur_cpu
3807 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3808 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3809 qemu_get_clock(vm_clock));
3811 /* real time timers */
3812 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3813 qemu_get_clock(rt_clock));
3815 /* Check bottom-halves last in case any of the earlier events triggered
3816 them. */
3817 qemu_bh_poll();
3821 static int main_loop(void)
3823 int ret, timeout;
3824 #ifdef CONFIG_PROFILER
3825 int64_t ti;
3826 #endif
3827 CPUState *env;
3830 if (kvm_enabled()) {
3831 kvm_main_loop();
3832 cpu_disable_ticks();
3833 return 0;
3836 cur_cpu = first_cpu;
3837 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3838 for(;;) {
3839 if (vm_running) {
3841 for(;;) {
3842 /* get next cpu */
3843 env = next_cpu;
3844 #ifdef CONFIG_PROFILER
3845 ti = profile_getclock();
3846 #endif
3847 if (use_icount) {
3848 int64_t count;
3849 int decr;
3850 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3851 env->icount_decr.u16.low = 0;
3852 env->icount_extra = 0;
3853 count = qemu_next_deadline();
3854 count = (count + (1 << icount_time_shift) - 1)
3855 >> icount_time_shift;
3856 qemu_icount += count;
3857 decr = (count > 0xffff) ? 0xffff : count;
3858 count -= decr;
3859 env->icount_decr.u16.low = decr;
3860 env->icount_extra = count;
3862 ret = cpu_exec(env);
3863 #ifdef CONFIG_PROFILER
3864 qemu_time += profile_getclock() - ti;
3865 #endif
3866 if (use_icount) {
3867 /* Fold pending instructions back into the
3868 instruction counter, and clear the interrupt flag. */
3869 qemu_icount -= (env->icount_decr.u16.low
3870 + env->icount_extra);
3871 env->icount_decr.u32 = 0;
3872 env->icount_extra = 0;
3874 next_cpu = env->next_cpu ?: first_cpu;
3875 if (event_pending && likely(ret != EXCP_DEBUG)) {
3876 ret = EXCP_INTERRUPT;
3877 event_pending = 0;
3878 break;
3880 if (ret == EXCP_HLT) {
3881 /* Give the next CPU a chance to run. */
3882 cur_cpu = env;
3883 continue;
3885 if (ret != EXCP_HALTED)
3886 break;
3887 /* all CPUs are halted ? */
3888 if (env == cur_cpu)
3889 break;
3891 cur_cpu = env;
3893 if (shutdown_requested) {
3894 ret = EXCP_INTERRUPT;
3895 if (no_shutdown) {
3896 vm_stop(0);
3897 no_shutdown = 0;
3899 else
3900 break;
3902 if (reset_requested) {
3903 reset_requested = 0;
3904 qemu_system_reset();
3905 if (kvm_enabled())
3906 kvm_load_registers(env);
3907 ret = EXCP_INTERRUPT;
3909 if (powerdown_requested) {
3910 powerdown_requested = 0;
3911 qemu_system_powerdown();
3912 ret = EXCP_INTERRUPT;
3914 #ifdef CONFIG_GDBSTUB
3915 if (unlikely(ret == EXCP_DEBUG)) {
3916 gdb_set_stop_cpu(cur_cpu);
3917 vm_stop(EXCP_DEBUG);
3919 #endif
3920 /* If all cpus are halted then wait until the next IRQ */
3921 /* XXX: use timeout computed from timers */
3922 if (ret == EXCP_HALTED) {
3923 if (use_icount) {
3924 int64_t add;
3925 int64_t delta;
3926 /* Advance virtual time to the next event. */
3927 if (use_icount == 1) {
3928 /* When not using an adaptive execution frequency
3929 we tend to get badly out of sync with real time,
3930 so just delay for a reasonable amount of time. */
3931 delta = 0;
3932 } else {
3933 delta = cpu_get_icount() - cpu_get_clock();
3935 if (delta > 0) {
3936 /* If virtual time is ahead of real time then just
3937 wait for IO. */
3938 timeout = (delta / 1000000) + 1;
3939 } else {
3940 /* Wait for either IO to occur or the next
3941 timer event. */
3942 add = qemu_next_deadline();
3943 /* We advance the timer before checking for IO.
3944 Limit the amount we advance so that early IO
3945 activity won't get the guest too far ahead. */
3946 if (add > 10000000)
3947 add = 10000000;
3948 delta += add;
3949 add = (add + (1 << icount_time_shift) - 1)
3950 >> icount_time_shift;
3951 qemu_icount += add;
3952 timeout = delta / 1000000;
3953 if (timeout < 0)
3954 timeout = 0;
3956 } else {
3957 timeout = 5000;
3959 } else {
3960 timeout = 0;
3962 } else {
3963 if (shutdown_requested) {
3964 ret = EXCP_INTERRUPT;
3965 break;
3967 timeout = 5000;
3969 #ifdef CONFIG_PROFILER
3970 ti = profile_getclock();
3971 #endif
3972 main_loop_wait(timeout);
3973 #ifdef CONFIG_PROFILER
3974 dev_time += profile_getclock() - ti;
3975 #endif
3977 cpu_disable_ticks();
3978 return ret;
3981 static void help(int exitcode)
3983 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
3984 and qemu-doc.texi */
3985 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
3986 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3987 "usage: %s [options] [disk_image]\n"
3988 "\n"
3989 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3990 "\n"
3991 "Standard options:\n"
3992 "-h or -help display this help and exit\n"
3993 "-M machine select emulated machine (-M ? for list)\n"
3994 "-cpu cpu select CPU (-cpu ? for list)\n"
3995 "-smp n set the number of CPUs to 'n' [default=1]\n"
3996 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3997 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3998 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3999 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4000 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
4001 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
4002 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
4003 " [,boot=on|off]\n"
4004 " use 'file' as a drive image\n"
4005 "-mtdblock file use 'file' as on-board Flash memory image\n"
4006 "-sd file use 'file' as SecureDigital card image\n"
4007 "-pflash file use 'file' as a parallel flash image\n"
4008 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4009 "-snapshot write to temporary files instead of disk image files\n"
4010 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4011 #ifndef _WIN32
4012 "-k language use keyboard layout (for example \"fr\" for French)\n"
4013 #endif
4014 #ifdef HAS_AUDIO
4015 "-audio-help print list of audio drivers and their options\n"
4016 "-soundhw c1,... enable audio support\n"
4017 " and only specified sound cards (comma separated list)\n"
4018 " use -soundhw ? to get the list of supported cards\n"
4019 " use -soundhw all to enable all of them\n"
4020 #endif
4021 "-usb enable the USB driver (will be the default soon)\n"
4022 "-usbdevice name add the host or guest USB device 'name'\n"
4023 "-name string set the name of the guest\n"
4024 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
4025 " specify machine UUID\n"
4026 "\n"
4027 "Display options:\n"
4028 "-nographic disable graphical output and redirect serial I/Os to console\n"
4029 #ifdef CONFIG_CURSES
4030 "-curses use a curses/ncurses interface instead of SDL\n"
4031 #endif
4032 #ifdef CONFIG_SDL
4033 "-no-frame open SDL window without a frame and window decorations\n"
4034 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4035 "-no-quit disable SDL window close capability\n"
4036 "-sdl enable SDL\n"
4037 #endif
4038 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4039 "-vga [std|cirrus|vmware|none]\n"
4040 " select video card type\n"
4041 "-full-screen start in full screen\n"
4042 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4043 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4044 #endif
4045 "-vnc display start a VNC server on display\n"
4046 #ifdef TARGET_IA64
4047 "-nvram file use 'file' to save or load nvram image\n"
4048 #endif
4049 "-name string set the name of the guest\n"
4050 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4051 "\n"
4052 "Network options:\n"
4053 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
4054 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4055 #ifdef CONFIG_SLIRP
4056 "-net user[,vlan=n][,name=str][,hostname=host]\n"
4057 " connect the user mode network stack to VLAN 'n' and send\n"
4058 " hostname 'host' to DHCP clients\n"
4059 #endif
4060 #ifdef _WIN32
4061 "-net tap[,vlan=n][,name=str],ifname=name\n"
4062 " connect the host TAP network interface to VLAN 'n'\n"
4063 #else
4064 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4065 " connect the host TAP network interface to VLAN 'n' and use the\n"
4066 " network scripts 'file' (default=%s)\n"
4067 " and 'dfile' (default=%s);\n"
4068 " use '[down]script=no' to disable script execution;\n"
4069 " use 'fd=h' to connect to an already opened TAP interface\n"
4070 #endif
4071 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4072 " connect the vlan 'n' to another VLAN using a socket connection\n"
4073 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4074 " connect the vlan 'n' to multicast maddr and port\n"
4075 #ifdef CONFIG_VDE
4076 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4077 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4078 " on host and listening for incoming connections on 'socketpath'.\n"
4079 " Use group 'groupname' and mode 'octalmode' to change default\n"
4080 " ownership and permissions for communication port.\n"
4081 #endif
4082 "-net none use it alone to have zero network devices; if no -net option\n"
4083 " is provided, the default is '-net nic -net user'\n"
4084 #ifdef CONFIG_SLIRP
4085 "-tftp dir allow tftp access to files in dir [-net user]\n"
4086 "-bootp file advertise file in BOOTP replies\n"
4087 #ifndef _WIN32
4088 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4089 #endif
4090 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4091 " redirect TCP or UDP connections from host to guest [-net user]\n"
4092 #endif
4093 "\n"
4094 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4095 "-bt hci,host[:id]\n"
4096 " use host's HCI with the given name\n"
4097 "-bt hci[,vlan=n]\n"
4098 " emulate a standard HCI in virtual scatternet 'n'\n"
4099 "-bt vhci[,vlan=n]\n"
4100 " add host computer to virtual scatternet 'n' using VHCI\n"
4101 "-bt device:dev[,vlan=n]\n"
4102 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4103 "\n"
4104 #ifdef TARGET_I386
4105 "\n"
4106 "i386 target only:\n"
4107 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4108 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4109 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4110 "-no-acpi disable ACPI\n"
4111 "-no-hpet disable HPET\n"
4112 "-acpitable [sig=str][,rev=n][,oem_id=str][,oem_table_id=str][,oem_rev=n][,asl_compiler_id=str][,asl_compiler_rev=n][,data=file1[:file2]...]\n"
4113 " ACPI table description\n"
4114 #endif
4115 "Linux boot specific:\n"
4116 "-kernel bzImage use 'bzImage' as kernel image\n"
4117 "-append cmdline use 'cmdline' as kernel command line\n"
4118 "-initrd file use 'file' as initial ram disk\n"
4119 "\n"
4120 "Debug/Expert options:\n"
4121 "-serial dev redirect the serial port to char device 'dev'\n"
4122 "-parallel dev redirect the parallel port to char device 'dev'\n"
4123 "-monitor dev redirect the monitor to char device 'dev'\n"
4124 "-pidfile file write PID to 'file'\n"
4125 "-S freeze CPU at startup (use 'c' to start execution)\n"
4126 "-s wait gdb connection to port\n"
4127 "-p port set gdb connection port [default=%s]\n"
4128 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4129 "-hdachs c,h,s[,t]\n"
4130 " force hard disk 0 physical geometry and the optional BIOS\n"
4131 " translation (t=none or lba) (usually qemu can guess them)\n"
4132 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4133 "-bios file set the filename for the BIOS\n"
4134 #ifdef USE_KQEMU
4135 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4136 "-no-kqemu disable KQEMU kernel module usage\n"
4137 #endif
4138 #ifdef CONFIG_KVM
4139 "-enable-kvm enable KVM full virtualization support\n"
4140 #endif
4141 #ifdef USE_KVM
4142 #ifndef NO_CPU_EMULATION
4143 "-no-kvm disable KVM hardware virtualization\n"
4144 #endif
4145 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4146 "-no-kvm-pit disable KVM kernel mode PIT\n"
4147 "-no-kvm-pit-reinjection disable KVM kernel mode PIT interrupt reinjection\n"
4148 "-enable-nesting enable support for running a VM inside the VM (AMD only)\n"
4149 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4150 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4151 " expose a PCI device to the guest OS.\n"
4152 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4153 " 'string' is used in log output.\n"
4154 #endif
4155 #endif
4156 "-no-reboot exit instead of rebooting\n"
4157 "-no-shutdown stop before shutdown\n"
4158 "-loadvm [tag|id]\n"
4159 " start right away with a saved state (loadvm in monitor)\n"
4160 #ifndef _WIN32
4161 "-daemonize daemonize QEMU after initializing\n"
4162 #endif
4163 "-tdf inject timer interrupts that got lost\n"
4164 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4165 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also\n"
4166 " enables allocation of guest memory with huge pages\n"
4167 #ifdef MAP_POPULATE
4168 "-mem-prealloc toggles preallocation of -mem-path backed physical memory\n"
4169 " at startup. Default is enabled.\n"
4170 #endif
4171 "-option-rom rom load a file, rom, into the option ROM space\n"
4172 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4173 "-prom-env variable=value\n"
4174 " set OpenBIOS nvram variables\n"
4175 #endif
4176 "-clock force the use of the given methods for timer alarm.\n"
4177 " To see what timers are available use -clock ?\n"
4178 "-localtime set the real time clock to local time [default=utc]\n"
4179 "-startdate select initial date of the clock\n"
4180 "-icount [N|auto]\n"
4181 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4182 "-echr chr set terminal escape character instead of ctrl-a\n"
4183 "-virtioconsole c\n"
4184 " set virtio console\n"
4185 "-show-cursor show cursor\n"
4186 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4187 "-semihosting semihosting mode\n"
4188 #endif
4189 #if defined(TARGET_ARM)
4190 "-old-param old param mode\n"
4191 #endif
4192 "-tb-size n set TB size\n"
4193 "-incoming p prepare for incoming migration, listen on port p\n"
4194 #ifndef _WIN32
4195 "-chroot dir Chroot to dir just before starting the VM.\n"
4196 "-runas user Change to user id user just before starting the VM.\n"
4197 #endif
4198 "\n"
4199 "During emulation, the following keys are useful:\n"
4200 "ctrl-alt-f toggle full screen\n"
4201 "ctrl-alt-n switch to virtual console 'n'\n"
4202 "ctrl-alt toggle mouse and keyboard grab\n"
4203 "\n"
4204 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4206 "qemu",
4207 DEFAULT_RAM_SIZE,
4208 #ifndef _WIN32
4209 DEFAULT_NETWORK_SCRIPT,
4210 DEFAULT_NETWORK_DOWN_SCRIPT,
4211 #endif
4212 DEFAULT_GDBSTUB_PORT,
4213 "/tmp/qemu.log");
4214 exit(exitcode);
4217 #define HAS_ARG 0x0001
4219 enum {
4220 /* Please keep in synch with help, qemu_options[] and
4221 qemu-doc.texi */
4222 /* Standard options: */
4223 QEMU_OPTION_h,
4224 QEMU_OPTION_M,
4225 QEMU_OPTION_cpu,
4226 QEMU_OPTION_smp,
4227 QEMU_OPTION_fda,
4228 QEMU_OPTION_fdb,
4229 QEMU_OPTION_hda,
4230 QEMU_OPTION_hdb,
4231 QEMU_OPTION_hdc,
4232 QEMU_OPTION_hdd,
4233 QEMU_OPTION_cdrom,
4234 QEMU_OPTION_drive,
4235 QEMU_OPTION_mtdblock,
4236 QEMU_OPTION_sd,
4237 QEMU_OPTION_pflash,
4238 QEMU_OPTION_boot,
4239 QEMU_OPTION_snapshot,
4240 QEMU_OPTION_m,
4241 QEMU_OPTION_k,
4242 QEMU_OPTION_audio_help,
4243 QEMU_OPTION_soundhw,
4244 QEMU_OPTION_usb,
4245 QEMU_OPTION_usbdevice,
4246 QEMU_OPTION_name,
4247 QEMU_OPTION_uuid,
4249 /* Display options: */
4250 QEMU_OPTION_nographic,
4251 QEMU_OPTION_curses,
4252 QEMU_OPTION_no_frame,
4253 QEMU_OPTION_alt_grab,
4254 QEMU_OPTION_no_quit,
4255 QEMU_OPTION_sdl,
4256 QEMU_OPTION_portrait,
4257 QEMU_OPTION_vga,
4258 QEMU_OPTION_full_screen,
4259 QEMU_OPTION_g,
4260 QEMU_OPTION_vnc,
4262 /* Network options: */
4263 QEMU_OPTION_net,
4264 QEMU_OPTION_tftp,
4265 QEMU_OPTION_bootp,
4266 QEMU_OPTION_smb,
4267 QEMU_OPTION_redir,
4268 QEMU_OPTION_bt,
4270 /* i386 target only: */
4271 QEMU_OPTION_win2k_hack,
4272 QEMU_OPTION_rtc_td_hack,
4273 QEMU_OPTION_no_fd_bootchk,
4274 QEMU_OPTION_no_acpi,
4275 QEMU_OPTION_no_hpet,
4276 QEMU_OPTION_acpitable,
4278 /* Linux boot specific: */
4279 QEMU_OPTION_kernel,
4280 QEMU_OPTION_append,
4281 QEMU_OPTION_initrd,
4283 /* Debug/Expert options: */
4284 QEMU_OPTION_serial,
4285 QEMU_OPTION_parallel,
4286 QEMU_OPTION_monitor,
4287 QEMU_OPTION_pidfile,
4288 QEMU_OPTION_S,
4289 QEMU_OPTION_s,
4290 QEMU_OPTION_p,
4291 QEMU_OPTION_d,
4292 QEMU_OPTION_hdachs,
4293 QEMU_OPTION_L,
4294 QEMU_OPTION_bios,
4295 QEMU_OPTION_kernel_kqemu,
4296 QEMU_OPTION_no_kqemu,
4297 QEMU_OPTION_enable_kvm,
4298 QEMU_OPTION_enable_nesting,
4299 QEMU_OPTION_no_kvm,
4300 QEMU_OPTION_no_kvm_irqchip,
4301 QEMU_OPTION_no_kvm_pit,
4302 QEMU_OPTION_no_kvm_pit_reinjection,
4303 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4304 QEMU_OPTION_pcidevice,
4305 #endif
4306 QEMU_OPTION_no_reboot,
4307 QEMU_OPTION_no_shutdown,
4308 QEMU_OPTION_loadvm,
4309 QEMU_OPTION_daemonize,
4310 QEMU_OPTION_option_rom,
4311 QEMU_OPTION_cpu_vendor,
4312 QEMU_OPTION_nvram,
4313 QEMU_OPTION_prom_env,
4314 QEMU_OPTION_clock,
4315 QEMU_OPTION_localtime,
4316 QEMU_OPTION_startdate,
4317 QEMU_OPTION_icount,
4318 QEMU_OPTION_echr,
4319 QEMU_OPTION_virtiocon,
4320 QEMU_OPTION_show_cursor,
4321 QEMU_OPTION_semihosting,
4322 QEMU_OPTION_old_param,
4323 QEMU_OPTION_tb_size,
4324 QEMU_OPTION_incoming,
4325 QEMU_OPTION_chroot,
4326 QEMU_OPTION_runas,
4327 QEMU_OPTION_tdf,
4328 QEMU_OPTION_kvm_shadow_memory,
4329 QEMU_OPTION_mempath,
4330 #ifdef MAP_POPULATE
4331 QEMU_OPTION_mem_prealloc,
4332 #endif
4335 typedef struct QEMUOption {
4336 const char *name;
4337 int flags;
4338 int index;
4339 } QEMUOption;
4341 static const QEMUOption qemu_options[] = {
4342 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4343 qemu-doc.texi */
4344 /* Standard options: */
4345 { "h", 0, QEMU_OPTION_h },
4346 { "help", 0, QEMU_OPTION_h },
4347 { "M", HAS_ARG, QEMU_OPTION_M },
4348 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4349 { "smp", HAS_ARG, QEMU_OPTION_smp },
4350 { "fda", HAS_ARG, QEMU_OPTION_fda },
4351 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4352 { "hda", HAS_ARG, QEMU_OPTION_hda },
4353 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4354 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4355 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4356 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4357 { "drive", HAS_ARG, QEMU_OPTION_drive },
4358 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4359 { "sd", HAS_ARG, QEMU_OPTION_sd },
4360 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4361 { "boot", HAS_ARG, QEMU_OPTION_boot },
4362 { "snapshot", 0, QEMU_OPTION_snapshot },
4363 { "m", HAS_ARG, QEMU_OPTION_m },
4364 { "k", HAS_ARG, QEMU_OPTION_k },
4365 #ifdef HAS_AUDIO
4366 { "audio-help", 0, QEMU_OPTION_audio_help },
4367 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4368 #endif
4369 { "usb", 0, QEMU_OPTION_usb },
4370 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4371 { "name", HAS_ARG, QEMU_OPTION_name },
4372 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4374 /* Display options: */
4375 { "nographic", 0, QEMU_OPTION_nographic },
4376 #ifdef CONFIG_CURSES
4377 { "curses", 0, QEMU_OPTION_curses },
4378 #endif
4379 #ifdef CONFIG_SDL
4380 { "no-frame", 0, QEMU_OPTION_no_frame },
4381 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4382 { "no-quit", 0, QEMU_OPTION_no_quit },
4383 { "sdl", 0, QEMU_OPTION_sdl },
4384 #endif
4385 { "portrait", 0, QEMU_OPTION_portrait },
4386 { "vga", HAS_ARG, QEMU_OPTION_vga },
4387 { "full-screen", 0, QEMU_OPTION_full_screen },
4388 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4389 { "g", 1, QEMU_OPTION_g },
4390 #endif
4391 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4393 /* Network options: */
4394 { "net", HAS_ARG, QEMU_OPTION_net},
4395 #ifdef CONFIG_SLIRP
4396 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4397 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4398 #ifndef _WIN32
4399 { "smb", HAS_ARG, QEMU_OPTION_smb },
4400 #endif
4401 { "redir", HAS_ARG, QEMU_OPTION_redir },
4402 #endif
4403 { "bt", HAS_ARG, QEMU_OPTION_bt },
4404 #ifdef TARGET_I386
4405 /* i386 target only: */
4406 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4407 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4408 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4409 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4410 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4411 { "acpitable", HAS_ARG, QEMU_OPTION_acpitable },
4412 #endif
4414 /* Linux boot specific: */
4415 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4416 { "append", HAS_ARG, QEMU_OPTION_append },
4417 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4419 /* Debug/Expert options: */
4420 { "serial", HAS_ARG, QEMU_OPTION_serial },
4421 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4422 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4423 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4424 { "S", 0, QEMU_OPTION_S },
4425 { "s", 0, QEMU_OPTION_s },
4426 { "p", HAS_ARG, QEMU_OPTION_p },
4427 { "d", HAS_ARG, QEMU_OPTION_d },
4428 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4429 { "L", HAS_ARG, QEMU_OPTION_L },
4430 { "bios", HAS_ARG, QEMU_OPTION_bios },
4431 #ifdef USE_KQEMU
4432 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4433 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4434 #endif
4435 #ifdef CONFIG_KVM
4436 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4437 #endif
4438 #ifdef USE_KVM
4439 #ifndef NO_CPU_EMULATION
4440 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4441 #endif
4442 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4443 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4444 { "no-kvm-pit-reinjection", 0, QEMU_OPTION_no_kvm_pit_reinjection },
4445 { "enable-nesting", 0, QEMU_OPTION_enable_nesting },
4446 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4447 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4448 #endif
4449 #endif
4450 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4451 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4452 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4453 { "daemonize", 0, QEMU_OPTION_daemonize },
4454 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4455 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4456 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4457 #endif
4458 { "clock", HAS_ARG, QEMU_OPTION_clock },
4459 { "localtime", 0, QEMU_OPTION_localtime },
4460 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4461 { "icount", HAS_ARG, QEMU_OPTION_icount },
4462 { "echr", HAS_ARG, QEMU_OPTION_echr },
4463 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4464 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4465 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4466 { "semihosting", 0, QEMU_OPTION_semihosting },
4467 #endif
4468 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4469 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4470 { "nvram", HAS_ARG, QEMU_OPTION_nvram },
4471 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4472 #if defined(TARGET_ARM)
4473 { "old-param", 0, QEMU_OPTION_old_param },
4474 #endif
4475 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4476 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4477 { "chroot", HAS_ARG, QEMU_OPTION_chroot },
4478 { "runas", HAS_ARG, QEMU_OPTION_runas },
4479 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4480 #ifdef MAP_POPULATE
4481 { "mem-prealloc", 0, QEMU_OPTION_mem_prealloc },
4482 #endif
4483 { NULL },
4486 #ifdef HAS_AUDIO
4487 struct soundhw soundhw[] = {
4488 #ifdef HAS_AUDIO_CHOICE
4489 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4491 "pcspk",
4492 "PC speaker",
4495 { .init_isa = pcspk_audio_init }
4497 #endif
4499 #ifdef CONFIG_SB16
4501 "sb16",
4502 "Creative Sound Blaster 16",
4505 { .init_isa = SB16_init }
4507 #endif
4509 #ifdef CONFIG_CS4231A
4511 "cs4231a",
4512 "CS4231A",
4515 { .init_isa = cs4231a_init }
4517 #endif
4519 #ifdef CONFIG_ADLIB
4521 "adlib",
4522 #ifdef HAS_YMF262
4523 "Yamaha YMF262 (OPL3)",
4524 #else
4525 "Yamaha YM3812 (OPL2)",
4526 #endif
4529 { .init_isa = Adlib_init }
4531 #endif
4533 #ifdef CONFIG_GUS
4535 "gus",
4536 "Gravis Ultrasound GF1",
4539 { .init_isa = GUS_init }
4541 #endif
4543 #ifdef CONFIG_AC97
4545 "ac97",
4546 "Intel 82801AA AC97 Audio",
4549 { .init_pci = ac97_init }
4551 #endif
4553 #ifdef CONFIG_ES1370
4555 "es1370",
4556 "ENSONIQ AudioPCI ES1370",
4559 { .init_pci = es1370_init }
4561 #endif
4563 #endif /* HAS_AUDIO_CHOICE */
4565 { NULL, NULL, 0, 0, { NULL } }
4568 static void select_soundhw (const char *optarg)
4570 struct soundhw *c;
4572 if (*optarg == '?') {
4573 show_valid_cards:
4575 printf ("Valid sound card names (comma separated):\n");
4576 for (c = soundhw; c->name; ++c) {
4577 printf ("%-11s %s\n", c->name, c->descr);
4579 printf ("\n-soundhw all will enable all of the above\n");
4580 exit (*optarg != '?');
4582 else {
4583 size_t l;
4584 const char *p;
4585 char *e;
4586 int bad_card = 0;
4588 if (!strcmp (optarg, "all")) {
4589 for (c = soundhw; c->name; ++c) {
4590 c->enabled = 1;
4592 return;
4595 p = optarg;
4596 while (*p) {
4597 e = strchr (p, ',');
4598 l = !e ? strlen (p) : (size_t) (e - p);
4600 for (c = soundhw; c->name; ++c) {
4601 if (!strncmp (c->name, p, l)) {
4602 c->enabled = 1;
4603 break;
4607 if (!c->name) {
4608 if (l > 80) {
4609 fprintf (stderr,
4610 "Unknown sound card name (too big to show)\n");
4612 else {
4613 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4614 (int) l, p);
4616 bad_card = 1;
4618 p += l + (e != NULL);
4621 if (bad_card)
4622 goto show_valid_cards;
4625 #endif
4627 static void select_vgahw (const char *p)
4629 const char *opts;
4631 if (strstart(p, "std", &opts)) {
4632 std_vga_enabled = 1;
4633 cirrus_vga_enabled = 0;
4634 vmsvga_enabled = 0;
4635 } else if (strstart(p, "cirrus", &opts)) {
4636 cirrus_vga_enabled = 1;
4637 std_vga_enabled = 0;
4638 vmsvga_enabled = 0;
4639 } else if (strstart(p, "vmware", &opts)) {
4640 cirrus_vga_enabled = 0;
4641 std_vga_enabled = 0;
4642 vmsvga_enabled = 1;
4643 } else if (strstart(p, "none", &opts)) {
4644 cirrus_vga_enabled = 0;
4645 std_vga_enabled = 0;
4646 vmsvga_enabled = 0;
4647 } else {
4648 invalid_vga:
4649 fprintf(stderr, "Unknown vga type: %s\n", p);
4650 exit(1);
4652 while (*opts) {
4653 const char *nextopt;
4655 if (strstart(opts, ",retrace=", &nextopt)) {
4656 opts = nextopt;
4657 if (strstart(opts, "dumb", &nextopt))
4658 vga_retrace_method = VGA_RETRACE_DUMB;
4659 else if (strstart(opts, "precise", &nextopt))
4660 vga_retrace_method = VGA_RETRACE_PRECISE;
4661 else goto invalid_vga;
4662 } else goto invalid_vga;
4663 opts = nextopt;
4667 #ifdef _WIN32
4668 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4670 exit(STATUS_CONTROL_C_EXIT);
4671 return TRUE;
4673 #endif
4675 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4677 int ret;
4679 if(strlen(str) != 36)
4680 return -1;
4682 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4683 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4684 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4686 if(ret != 16)
4687 return -1;
4689 return 0;
4692 #define MAX_NET_CLIENTS 32
4694 static int saved_argc;
4695 static char **saved_argv;
4697 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4699 *argc = saved_argc;
4700 *argv = saved_argv;
4701 *opt_daemonize = daemonize;
4702 *opt_incoming = incoming;
4705 #ifdef USE_KVM
4706 static int gethugepagesize(void)
4708 int ret, fd;
4709 char buf[4096];
4710 const char *needle = "Hugepagesize:";
4711 char *size;
4712 unsigned long hugepagesize;
4714 fd = open("/proc/meminfo", O_RDONLY);
4715 if (fd < 0) {
4716 perror("open");
4717 exit(0);
4720 ret = read(fd, buf, sizeof(buf));
4721 if (ret < 0) {
4722 perror("read");
4723 exit(0);
4726 size = strstr(buf, needle);
4727 if (!size)
4728 return 0;
4729 size += strlen(needle);
4730 hugepagesize = strtol(size, NULL, 0);
4731 return hugepagesize;
4734 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4736 char *filename;
4737 void *area;
4738 int fd;
4739 #ifdef MAP_POPULATE
4740 int flags;
4741 #endif
4743 if (!kvm_has_sync_mmu()) {
4744 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4745 return NULL;
4748 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4749 return NULL;
4751 hpagesize = gethugepagesize() * 1024;
4752 if (!hpagesize)
4753 return NULL;
4755 fd = mkstemp(filename);
4756 if (fd < 0) {
4757 perror("mkstemp");
4758 free(filename);
4759 return NULL;
4761 unlink(filename);
4762 free(filename);
4764 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4767 * ftruncate is not supported by hugetlbfs in older
4768 * hosts, so don't bother checking for errors.
4769 * If anything goes wrong with it under other filesystems,
4770 * mmap will fail.
4772 ftruncate(fd, memory);
4774 #ifdef MAP_POPULATE
4775 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4776 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4777 * to sidestep this quirk.
4779 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4780 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4781 #else
4782 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4783 #endif
4784 if (area == MAP_FAILED) {
4785 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4786 close(fd);
4787 return (NULL);
4789 *len = memory;
4790 return area;
4792 #endif
4794 static void *qemu_alloc_physram(unsigned long memory)
4796 void *area = NULL;
4797 #ifdef USE_KVM
4798 unsigned long map_len = memory;
4800 if (mem_path)
4801 area = alloc_mem_area(memory, &map_len, mem_path);
4802 #endif
4803 if (!area)
4804 area = qemu_vmalloc(memory);
4805 #ifdef USE_KVM
4806 if (kvm_setup_guest_memory(area, map_len))
4807 area = NULL;
4808 #endif
4809 return area;
4812 #ifndef _WIN32
4814 static void termsig_handler(int signal)
4816 qemu_system_shutdown_request();
4819 static void termsig_setup(void)
4821 struct sigaction act;
4823 memset(&act, 0, sizeof(act));
4824 act.sa_handler = termsig_handler;
4825 sigaction(SIGINT, &act, NULL);
4826 sigaction(SIGHUP, &act, NULL);
4827 sigaction(SIGTERM, &act, NULL);
4830 #endif
4832 int main(int argc, char **argv, char **envp)
4834 #ifdef CONFIG_GDBSTUB
4835 int use_gdbstub;
4836 const char *gdbstub_port;
4837 #endif
4838 uint32_t boot_devices_bitmap = 0;
4839 int i;
4840 int snapshot, linux_boot, net_boot;
4841 const char *initrd_filename;
4842 const char *kernel_filename, *kernel_cmdline;
4843 const char *boot_devices = "";
4844 DisplayState *ds;
4845 DisplayChangeListener *dcl;
4846 int cyls, heads, secs, translation;
4847 const char *net_clients[MAX_NET_CLIENTS];
4848 int nb_net_clients;
4849 const char *bt_opts[MAX_BT_CMDLINE];
4850 int nb_bt_opts;
4851 int hda_index;
4852 int optind;
4853 const char *r, *optarg;
4854 CharDriverState *monitor_hd = NULL;
4855 const char *monitor_device;
4856 const char *serial_devices[MAX_SERIAL_PORTS];
4857 int serial_device_index;
4858 const char *parallel_devices[MAX_PARALLEL_PORTS];
4859 int parallel_device_index;
4860 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4861 int virtio_console_index;
4862 const char *loadvm = NULL;
4863 QEMUMachine *machine;
4864 const char *cpu_model;
4865 const char *usb_devices[MAX_USB_CMDLINE];
4866 int usb_devices_index;
4867 int fds[2];
4868 int tb_size;
4869 const char *pid_file = NULL;
4870 const char *incoming = NULL;
4871 int fd = 0;
4872 struct passwd *pwd = NULL;
4873 const char *chroot_dir = NULL;
4874 const char *run_as = NULL;
4876 qemu_cache_utils_init(envp);
4878 LIST_INIT (&vm_change_state_head);
4879 #ifndef _WIN32
4881 struct sigaction act;
4882 sigfillset(&act.sa_mask);
4883 act.sa_flags = 0;
4884 act.sa_handler = SIG_IGN;
4885 sigaction(SIGPIPE, &act, NULL);
4887 #else
4888 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4889 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4890 QEMU to run on a single CPU */
4892 HANDLE h;
4893 DWORD mask, smask;
4894 int i;
4895 h = GetCurrentProcess();
4896 if (GetProcessAffinityMask(h, &mask, &smask)) {
4897 for(i = 0; i < 32; i++) {
4898 if (mask & (1 << i))
4899 break;
4901 if (i != 32) {
4902 mask = 1 << i;
4903 SetProcessAffinityMask(h, mask);
4907 #endif
4909 register_machines();
4910 machine = first_machine;
4911 cpu_model = NULL;
4912 initrd_filename = NULL;
4913 ram_size = 0;
4914 vga_ram_size = VGA_RAM_SIZE;
4915 #ifdef CONFIG_GDBSTUB
4916 use_gdbstub = 0;
4917 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4918 #endif
4919 snapshot = 0;
4920 nographic = 0;
4921 curses = 0;
4922 kernel_filename = NULL;
4923 kernel_cmdline = "";
4924 cyls = heads = secs = 0;
4925 translation = BIOS_ATA_TRANSLATION_AUTO;
4926 monitor_device = "vc:80Cx24C";
4928 serial_devices[0] = "vc:80Cx24C";
4929 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4930 serial_devices[i] = NULL;
4931 serial_device_index = 0;
4933 parallel_devices[0] = "vc:80Cx24C";
4934 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4935 parallel_devices[i] = NULL;
4936 parallel_device_index = 0;
4938 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4939 virtio_consoles[i] = NULL;
4940 virtio_console_index = 0;
4942 usb_devices_index = 0;
4943 assigned_devices_index = 0;
4945 nb_net_clients = 0;
4946 nb_bt_opts = 0;
4947 nb_drives = 0;
4948 nb_drives_opt = 0;
4949 hda_index = -1;
4951 nb_nics = 0;
4953 tb_size = 0;
4954 autostart= 1;
4956 optind = 1;
4957 for(;;) {
4958 if (optind >= argc)
4959 break;
4960 r = argv[optind];
4961 if (r[0] != '-') {
4962 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4963 } else {
4964 const QEMUOption *popt;
4966 optind++;
4967 /* Treat --foo the same as -foo. */
4968 if (r[1] == '-')
4969 r++;
4970 popt = qemu_options;
4971 for(;;) {
4972 if (!popt->name) {
4973 fprintf(stderr, "%s: invalid option -- '%s'\n",
4974 argv[0], r);
4975 exit(1);
4977 if (!strcmp(popt->name, r + 1))
4978 break;
4979 popt++;
4981 if (popt->flags & HAS_ARG) {
4982 if (optind >= argc) {
4983 fprintf(stderr, "%s: option '%s' requires an argument\n",
4984 argv[0], r);
4985 exit(1);
4987 optarg = argv[optind++];
4988 } else {
4989 optarg = NULL;
4992 switch(popt->index) {
4993 case QEMU_OPTION_M:
4994 machine = find_machine(optarg);
4995 if (!machine) {
4996 QEMUMachine *m;
4997 printf("Supported machines are:\n");
4998 for(m = first_machine; m != NULL; m = m->next) {
4999 printf("%-10s %s%s\n",
5000 m->name, m->desc,
5001 m == first_machine ? " (default)" : "");
5003 exit(*optarg != '?');
5005 break;
5006 case QEMU_OPTION_cpu:
5007 /* hw initialization will check this */
5008 if (*optarg == '?') {
5009 /* XXX: implement xxx_cpu_list for targets that still miss it */
5010 #if defined(cpu_list)
5011 cpu_list(stdout, &fprintf);
5012 #endif
5013 exit(0);
5014 } else {
5015 cpu_model = optarg;
5017 break;
5018 case QEMU_OPTION_initrd:
5019 initrd_filename = optarg;
5020 break;
5021 case QEMU_OPTION_hda:
5022 if (cyls == 0)
5023 hda_index = drive_add(optarg, HD_ALIAS, 0);
5024 else
5025 hda_index = drive_add(optarg, HD_ALIAS
5026 ",cyls=%d,heads=%d,secs=%d%s",
5027 0, cyls, heads, secs,
5028 translation == BIOS_ATA_TRANSLATION_LBA ?
5029 ",trans=lba" :
5030 translation == BIOS_ATA_TRANSLATION_NONE ?
5031 ",trans=none" : "");
5032 break;
5033 case QEMU_OPTION_hdb:
5034 case QEMU_OPTION_hdc:
5035 case QEMU_OPTION_hdd:
5036 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5037 break;
5038 case QEMU_OPTION_drive:
5039 drive_add(NULL, "%s", optarg);
5040 break;
5041 case QEMU_OPTION_mtdblock:
5042 drive_add(optarg, MTD_ALIAS);
5043 break;
5044 case QEMU_OPTION_sd:
5045 drive_add(optarg, SD_ALIAS);
5046 break;
5047 case QEMU_OPTION_pflash:
5048 drive_add(optarg, PFLASH_ALIAS);
5049 break;
5050 case QEMU_OPTION_snapshot:
5051 snapshot = 1;
5052 break;
5053 case QEMU_OPTION_hdachs:
5055 const char *p;
5056 p = optarg;
5057 cyls = strtol(p, (char **)&p, 0);
5058 if (cyls < 1 || cyls > 16383)
5059 goto chs_fail;
5060 if (*p != ',')
5061 goto chs_fail;
5062 p++;
5063 heads = strtol(p, (char **)&p, 0);
5064 if (heads < 1 || heads > 16)
5065 goto chs_fail;
5066 if (*p != ',')
5067 goto chs_fail;
5068 p++;
5069 secs = strtol(p, (char **)&p, 0);
5070 if (secs < 1 || secs > 63)
5071 goto chs_fail;
5072 if (*p == ',') {
5073 p++;
5074 if (!strcmp(p, "none"))
5075 translation = BIOS_ATA_TRANSLATION_NONE;
5076 else if (!strcmp(p, "lba"))
5077 translation = BIOS_ATA_TRANSLATION_LBA;
5078 else if (!strcmp(p, "auto"))
5079 translation = BIOS_ATA_TRANSLATION_AUTO;
5080 else
5081 goto chs_fail;
5082 } else if (*p != '\0') {
5083 chs_fail:
5084 fprintf(stderr, "qemu: invalid physical CHS format\n");
5085 exit(1);
5087 if (hda_index != -1)
5088 snprintf(drives_opt[hda_index].opt,
5089 sizeof(drives_opt[hda_index].opt),
5090 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5091 0, cyls, heads, secs,
5092 translation == BIOS_ATA_TRANSLATION_LBA ?
5093 ",trans=lba" :
5094 translation == BIOS_ATA_TRANSLATION_NONE ?
5095 ",trans=none" : "");
5097 break;
5098 case QEMU_OPTION_nographic:
5099 nographic = 1;
5100 break;
5101 #ifdef CONFIG_CURSES
5102 case QEMU_OPTION_curses:
5103 curses = 1;
5104 break;
5105 #endif
5106 case QEMU_OPTION_portrait:
5107 graphic_rotate = 1;
5108 break;
5109 case QEMU_OPTION_kernel:
5110 kernel_filename = optarg;
5111 break;
5112 case QEMU_OPTION_append:
5113 kernel_cmdline = optarg;
5114 break;
5115 case QEMU_OPTION_cdrom:
5116 drive_add(optarg, CDROM_ALIAS);
5117 break;
5118 case QEMU_OPTION_boot:
5119 boot_devices = optarg;
5120 /* We just do some generic consistency checks */
5122 /* Could easily be extended to 64 devices if needed */
5123 const char *p;
5125 boot_devices_bitmap = 0;
5126 for (p = boot_devices; *p != '\0'; p++) {
5127 /* Allowed boot devices are:
5128 * a b : floppy disk drives
5129 * c ... f : IDE disk drives
5130 * g ... m : machine implementation dependant drives
5131 * n ... p : network devices
5132 * It's up to each machine implementation to check
5133 * if the given boot devices match the actual hardware
5134 * implementation and firmware features.
5136 if (*p < 'a' || *p > 'q') {
5137 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5138 exit(1);
5140 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5141 fprintf(stderr,
5142 "Boot device '%c' was given twice\n",*p);
5143 exit(1);
5145 boot_devices_bitmap |= 1 << (*p - 'a');
5148 break;
5149 case QEMU_OPTION_fda:
5150 case QEMU_OPTION_fdb:
5151 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5152 break;
5153 #ifdef TARGET_I386
5154 case QEMU_OPTION_no_fd_bootchk:
5155 fd_bootchk = 0;
5156 break;
5157 #endif
5158 case QEMU_OPTION_net:
5159 if (nb_net_clients >= MAX_NET_CLIENTS) {
5160 fprintf(stderr, "qemu: too many network clients\n");
5161 exit(1);
5163 net_clients[nb_net_clients] = optarg;
5164 nb_net_clients++;
5165 break;
5166 #ifdef CONFIG_SLIRP
5167 case QEMU_OPTION_tftp:
5168 tftp_prefix = optarg;
5169 break;
5170 case QEMU_OPTION_bootp:
5171 bootp_filename = optarg;
5172 break;
5173 #ifndef _WIN32
5174 case QEMU_OPTION_smb:
5175 net_slirp_smb(optarg);
5176 break;
5177 #endif
5178 case QEMU_OPTION_redir:
5179 net_slirp_redir(optarg);
5180 break;
5181 #endif
5182 case QEMU_OPTION_bt:
5183 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5184 fprintf(stderr, "qemu: too many bluetooth options\n");
5185 exit(1);
5187 bt_opts[nb_bt_opts++] = optarg;
5188 break;
5189 #ifdef HAS_AUDIO
5190 case QEMU_OPTION_audio_help:
5191 AUD_help ();
5192 exit (0);
5193 break;
5194 case QEMU_OPTION_soundhw:
5195 select_soundhw (optarg);
5196 break;
5197 #endif
5198 case QEMU_OPTION_h:
5199 help(0);
5200 break;
5201 case QEMU_OPTION_m: {
5202 uint64_t value;
5203 char *ptr;
5205 value = strtoul(optarg, &ptr, 10);
5206 switch (*ptr) {
5207 case 0: case 'M': case 'm':
5208 value <<= 20;
5209 break;
5210 case 'G': case 'g':
5211 value <<= 30;
5212 break;
5213 default:
5214 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5215 exit(1);
5218 /* On 32-bit hosts, QEMU is limited by virtual address space */
5219 if (value > (2047 << 20)
5220 #ifndef USE_KQEMU
5221 && HOST_LONG_BITS == 32
5222 #endif
5224 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5225 exit(1);
5227 if (value != (uint64_t)(ram_addr_t)value) {
5228 fprintf(stderr, "qemu: ram size too large\n");
5229 exit(1);
5231 ram_size = value;
5232 break;
5234 case QEMU_OPTION_d:
5236 int mask;
5237 const CPULogItem *item;
5239 mask = cpu_str_to_log_mask(optarg);
5240 if (!mask) {
5241 printf("Log items (comma separated):\n");
5242 for(item = cpu_log_items; item->mask != 0; item++) {
5243 printf("%-10s %s\n", item->name, item->help);
5245 exit(1);
5247 cpu_set_log(mask);
5249 break;
5250 #ifdef CONFIG_GDBSTUB
5251 case QEMU_OPTION_s:
5252 use_gdbstub = 1;
5253 break;
5254 case QEMU_OPTION_p:
5255 gdbstub_port = optarg;
5256 break;
5257 #endif
5258 case QEMU_OPTION_L:
5259 bios_dir = optarg;
5260 break;
5261 case QEMU_OPTION_bios:
5262 bios_name = optarg;
5263 break;
5264 case QEMU_OPTION_S:
5265 autostart = 0;
5266 break;
5267 case QEMU_OPTION_k:
5268 keyboard_layout = optarg;
5269 break;
5270 case QEMU_OPTION_localtime:
5271 rtc_utc = 0;
5272 break;
5273 case QEMU_OPTION_vga:
5274 select_vgahw (optarg);
5275 break;
5276 case QEMU_OPTION_g:
5278 const char *p;
5279 int w, h, depth;
5280 p = optarg;
5281 w = strtol(p, (char **)&p, 10);
5282 if (w <= 0) {
5283 graphic_error:
5284 fprintf(stderr, "qemu: invalid resolution or depth\n");
5285 exit(1);
5287 if (*p != 'x')
5288 goto graphic_error;
5289 p++;
5290 h = strtol(p, (char **)&p, 10);
5291 if (h <= 0)
5292 goto graphic_error;
5293 if (*p == 'x') {
5294 p++;
5295 depth = strtol(p, (char **)&p, 10);
5296 if (depth != 8 && depth != 15 && depth != 16 &&
5297 depth != 24 && depth != 32)
5298 goto graphic_error;
5299 } else if (*p == '\0') {
5300 depth = graphic_depth;
5301 } else {
5302 goto graphic_error;
5305 graphic_width = w;
5306 graphic_height = h;
5307 graphic_depth = depth;
5309 break;
5310 case QEMU_OPTION_echr:
5312 char *r;
5313 term_escape_char = strtol(optarg, &r, 0);
5314 if (r == optarg)
5315 printf("Bad argument to echr\n");
5316 break;
5318 case QEMU_OPTION_monitor:
5319 monitor_device = optarg;
5320 break;
5321 case QEMU_OPTION_serial:
5322 if (serial_device_index >= MAX_SERIAL_PORTS) {
5323 fprintf(stderr, "qemu: too many serial ports\n");
5324 exit(1);
5326 serial_devices[serial_device_index] = optarg;
5327 serial_device_index++;
5328 break;
5329 case QEMU_OPTION_virtiocon:
5330 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5331 fprintf(stderr, "qemu: too many virtio consoles\n");
5332 exit(1);
5334 virtio_consoles[virtio_console_index] = optarg;
5335 virtio_console_index++;
5336 break;
5337 case QEMU_OPTION_parallel:
5338 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5339 fprintf(stderr, "qemu: too many parallel ports\n");
5340 exit(1);
5342 parallel_devices[parallel_device_index] = optarg;
5343 parallel_device_index++;
5344 break;
5345 case QEMU_OPTION_loadvm:
5346 loadvm = optarg;
5347 break;
5348 case QEMU_OPTION_full_screen:
5349 full_screen = 1;
5350 break;
5351 #ifdef CONFIG_SDL
5352 case QEMU_OPTION_no_frame:
5353 no_frame = 1;
5354 break;
5355 case QEMU_OPTION_alt_grab:
5356 alt_grab = 1;
5357 break;
5358 case QEMU_OPTION_no_quit:
5359 no_quit = 1;
5360 break;
5361 case QEMU_OPTION_sdl:
5362 sdl = 1;
5363 break;
5364 #endif
5365 case QEMU_OPTION_pidfile:
5366 pid_file = optarg;
5367 break;
5368 #ifdef TARGET_I386
5369 case QEMU_OPTION_win2k_hack:
5370 win2k_install_hack = 1;
5371 break;
5372 case QEMU_OPTION_rtc_td_hack:
5373 rtc_td_hack = 1;
5374 break;
5375 case QEMU_OPTION_acpitable:
5376 if(acpi_table_add(optarg) < 0) {
5377 fprintf(stderr, "Wrong acpi table provided\n");
5378 exit(1);
5380 break;
5381 #endif
5382 #ifdef USE_KQEMU
5383 case QEMU_OPTION_no_kqemu:
5384 kqemu_allowed = 0;
5385 break;
5386 case QEMU_OPTION_kernel_kqemu:
5387 kqemu_allowed = 2;
5388 break;
5389 #endif
5390 #ifdef CONFIG_KVM
5391 case QEMU_OPTION_enable_kvm:
5392 kvm_allowed = 1;
5393 #ifdef USE_KQEMU
5394 kqemu_allowed = 0;
5395 #endif
5396 break;
5397 #endif
5398 #ifdef USE_KVM
5399 case QEMU_OPTION_no_kvm:
5400 kvm_allowed = 0;
5401 break;
5402 case QEMU_OPTION_no_kvm_irqchip: {
5403 kvm_irqchip = 0;
5404 kvm_pit = 0;
5405 break;
5407 case QEMU_OPTION_no_kvm_pit: {
5408 kvm_pit = 0;
5409 break;
5411 case QEMU_OPTION_no_kvm_pit_reinjection: {
5412 kvm_pit_reinject = 0;
5413 break;
5415 case QEMU_OPTION_enable_nesting: {
5416 kvm_nested = 1;
5417 break;
5419 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5420 case QEMU_OPTION_pcidevice:
5421 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5422 fprintf(stderr, "Too many assigned devices\n");
5423 exit(1);
5425 assigned_devices[assigned_devices_index] = optarg;
5426 assigned_devices_index++;
5427 break;
5428 #endif
5429 #endif
5430 case QEMU_OPTION_usb:
5431 usb_enabled = 1;
5432 break;
5433 case QEMU_OPTION_usbdevice:
5434 usb_enabled = 1;
5435 if (usb_devices_index >= MAX_USB_CMDLINE) {
5436 fprintf(stderr, "Too many USB devices\n");
5437 exit(1);
5439 usb_devices[usb_devices_index] = optarg;
5440 usb_devices_index++;
5441 break;
5442 case QEMU_OPTION_smp:
5443 smp_cpus = atoi(optarg);
5444 if (smp_cpus < 1) {
5445 fprintf(stderr, "Invalid number of CPUs\n");
5446 exit(1);
5448 break;
5449 case QEMU_OPTION_vnc:
5450 vnc_display = optarg;
5451 break;
5452 case QEMU_OPTION_no_acpi:
5453 acpi_enabled = 0;
5454 break;
5455 case QEMU_OPTION_no_hpet:
5456 no_hpet = 1;
5457 break;
5458 case QEMU_OPTION_no_reboot:
5459 no_reboot = 1;
5460 break;
5461 case QEMU_OPTION_no_shutdown:
5462 no_shutdown = 1;
5463 break;
5464 case QEMU_OPTION_show_cursor:
5465 cursor_hide = 0;
5466 break;
5467 case QEMU_OPTION_uuid:
5468 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5469 fprintf(stderr, "Fail to parse UUID string."
5470 " Wrong format.\n");
5471 exit(1);
5473 break;
5474 case QEMU_OPTION_daemonize:
5475 daemonize = 1;
5476 break;
5477 case QEMU_OPTION_option_rom:
5478 if (nb_option_roms >= MAX_OPTION_ROMS) {
5479 fprintf(stderr, "Too many option ROMs\n");
5480 exit(1);
5482 option_rom[nb_option_roms] = optarg;
5483 nb_option_roms++;
5484 break;
5485 case QEMU_OPTION_semihosting:
5486 semihosting_enabled = 1;
5487 break;
5488 case QEMU_OPTION_tdf:
5489 time_drift_fix = 1;
5490 break;
5491 case QEMU_OPTION_kvm_shadow_memory:
5492 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5493 break;
5494 case QEMU_OPTION_mempath:
5495 mem_path = optarg;
5496 break;
5497 #ifdef MAP_POPULATE
5498 case QEMU_OPTION_mem_prealloc:
5499 mem_prealloc = !mem_prealloc;
5500 break;
5501 #endif
5502 case QEMU_OPTION_name:
5503 qemu_name = optarg;
5504 break;
5505 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5506 case QEMU_OPTION_prom_env:
5507 if (nb_prom_envs >= MAX_PROM_ENVS) {
5508 fprintf(stderr, "Too many prom variables\n");
5509 exit(1);
5511 prom_envs[nb_prom_envs] = optarg;
5512 nb_prom_envs++;
5513 break;
5514 #endif
5515 case QEMU_OPTION_cpu_vendor:
5516 cpu_vendor_string = optarg;
5517 break;
5518 #ifdef TARGET_ARM
5519 case QEMU_OPTION_old_param:
5520 old_param = 1;
5521 break;
5522 #endif
5523 case QEMU_OPTION_clock:
5524 configure_alarms(optarg);
5525 break;
5526 case QEMU_OPTION_startdate:
5528 struct tm tm;
5529 time_t rtc_start_date;
5530 if (!strcmp(optarg, "now")) {
5531 rtc_date_offset = -1;
5532 } else {
5533 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5534 &tm.tm_year,
5535 &tm.tm_mon,
5536 &tm.tm_mday,
5537 &tm.tm_hour,
5538 &tm.tm_min,
5539 &tm.tm_sec) == 6) {
5540 /* OK */
5541 } else if (sscanf(optarg, "%d-%d-%d",
5542 &tm.tm_year,
5543 &tm.tm_mon,
5544 &tm.tm_mday) == 3) {
5545 tm.tm_hour = 0;
5546 tm.tm_min = 0;
5547 tm.tm_sec = 0;
5548 } else {
5549 goto date_fail;
5551 tm.tm_year -= 1900;
5552 tm.tm_mon--;
5553 rtc_start_date = mktimegm(&tm);
5554 if (rtc_start_date == -1) {
5555 date_fail:
5556 fprintf(stderr, "Invalid date format. Valid format are:\n"
5557 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5558 exit(1);
5560 rtc_date_offset = time(NULL) - rtc_start_date;
5563 break;
5564 case QEMU_OPTION_tb_size:
5565 tb_size = strtol(optarg, NULL, 0);
5566 if (tb_size < 0)
5567 tb_size = 0;
5568 break;
5569 case QEMU_OPTION_icount:
5570 use_icount = 1;
5571 if (strcmp(optarg, "auto") == 0) {
5572 icount_time_shift = -1;
5573 } else {
5574 icount_time_shift = strtol(optarg, NULL, 0);
5576 break;
5577 case QEMU_OPTION_incoming:
5578 incoming = optarg;
5579 break;
5580 case QEMU_OPTION_chroot:
5581 chroot_dir = optarg;
5582 break;
5583 case QEMU_OPTION_runas:
5584 run_as = optarg;
5585 case QEMU_OPTION_nvram:
5586 nvram = optarg;
5587 break;
5592 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5593 if (kvm_allowed && kqemu_allowed) {
5594 fprintf(stderr,
5595 "You can not enable both KVM and kqemu at the same time\n");
5596 exit(1);
5598 #endif
5600 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5601 if (smp_cpus > machine->max_cpus) {
5602 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5603 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5604 machine->max_cpus);
5605 exit(1);
5608 if (nographic) {
5609 if (serial_device_index == 0)
5610 serial_devices[0] = "stdio";
5611 if (parallel_device_index == 0)
5612 parallel_devices[0] = "null";
5613 if (strncmp(monitor_device, "vc", 2) == 0)
5614 monitor_device = "stdio";
5617 #ifndef _WIN32
5618 if (daemonize) {
5619 pid_t pid;
5621 if (pipe(fds) == -1)
5622 exit(1);
5624 pid = fork();
5625 if (pid > 0) {
5626 uint8_t status;
5627 ssize_t len;
5629 close(fds[1]);
5631 again:
5632 len = read(fds[0], &status, 1);
5633 if (len == -1 && (errno == EINTR))
5634 goto again;
5636 if (len != 1)
5637 exit(1);
5638 else if (status == 1) {
5639 fprintf(stderr, "Could not acquire pidfile\n");
5640 exit(1);
5641 } else
5642 exit(0);
5643 } else if (pid < 0)
5644 exit(1);
5646 setsid();
5648 pid = fork();
5649 if (pid > 0)
5650 exit(0);
5651 else if (pid < 0)
5652 exit(1);
5654 umask(027);
5656 signal(SIGTSTP, SIG_IGN);
5657 signal(SIGTTOU, SIG_IGN);
5658 signal(SIGTTIN, SIG_IGN);
5660 #endif
5662 #ifdef USE_KVM
5663 if (kvm_enabled()) {
5664 if (kvm_qemu_init() < 0) {
5665 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5666 #ifdef NO_CPU_EMULATION
5667 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5668 exit(1);
5669 #endif
5670 kvm_allowed = 0;
5673 #endif
5675 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5676 if (daemonize) {
5677 uint8_t status = 1;
5678 write(fds[1], &status, 1);
5679 } else
5680 fprintf(stderr, "Could not acquire pid file\n");
5681 exit(1);
5684 #ifdef USE_KQEMU
5685 if (smp_cpus > 1)
5686 kqemu_allowed = 0;
5687 #endif
5688 linux_boot = (kernel_filename != NULL);
5689 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5691 if (!linux_boot && net_boot == 0 &&
5692 !machine->nodisk_ok && nb_drives_opt == 0)
5693 help(1);
5695 if (!linux_boot && *kernel_cmdline != '\0') {
5696 fprintf(stderr, "-append only allowed with -kernel option\n");
5697 exit(1);
5700 if (!linux_boot && initrd_filename != NULL) {
5701 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5702 exit(1);
5705 /* boot to floppy or the default cd if no hard disk defined yet */
5706 if (!boot_devices[0]) {
5707 boot_devices = "cad";
5709 setvbuf(stdout, NULL, _IOLBF, 0);
5711 init_timers();
5712 if (init_timer_alarm() < 0) {
5713 fprintf(stderr, "could not initialize alarm timer\n");
5714 exit(1);
5716 if (use_icount && icount_time_shift < 0) {
5717 use_icount = 2;
5718 /* 125MIPS seems a reasonable initial guess at the guest speed.
5719 It will be corrected fairly quickly anyway. */
5720 icount_time_shift = 3;
5721 init_icount_adjust();
5724 #ifdef _WIN32
5725 socket_init();
5726 #endif
5728 /* init network clients */
5729 if (nb_net_clients == 0) {
5730 /* if no clients, we use a default config */
5731 net_clients[nb_net_clients++] = "nic";
5732 #ifdef CONFIG_SLIRP
5733 net_clients[nb_net_clients++] = "user";
5734 #endif
5737 for(i = 0;i < nb_net_clients; i++) {
5738 if (net_client_parse(net_clients[i]) < 0)
5739 exit(1);
5741 net_client_check();
5743 #ifdef TARGET_I386
5744 /* XXX: this should be moved in the PC machine instantiation code */
5745 if (net_boot != 0) {
5746 int netroms = 0;
5747 for (i = 0; i < nb_nics && i < 4; i++) {
5748 const char *model = nd_table[i].model;
5749 char buf[1024];
5750 if (net_boot & (1 << i)) {
5751 if (model == NULL)
5752 model = "rtl8139";
5753 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5754 if (get_image_size(buf) > 0) {
5755 if (nb_option_roms >= MAX_OPTION_ROMS) {
5756 fprintf(stderr, "Too many option ROMs\n");
5757 exit(1);
5759 option_rom[nb_option_roms] = strdup(buf);
5760 nb_option_roms++;
5761 netroms++;
5765 if (netroms == 0) {
5766 fprintf(stderr, "No valid PXE rom found for network device\n");
5767 exit(1);
5770 #endif
5772 /* init the bluetooth world */
5773 for (i = 0; i < nb_bt_opts; i++)
5774 if (bt_parse(bt_opts[i]))
5775 exit(1);
5777 /* init the memory */
5778 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5780 if (machine->ram_require & RAMSIZE_FIXED) {
5781 if (ram_size > 0) {
5782 if (ram_size < phys_ram_size) {
5783 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5784 machine->name, (unsigned long long) phys_ram_size);
5785 exit(-1);
5788 phys_ram_size = ram_size;
5789 } else
5790 ram_size = phys_ram_size;
5791 } else {
5792 if (ram_size == 0)
5793 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5795 phys_ram_size += ram_size;
5798 /* Initialize kvm */
5799 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5800 #define KVM_EXTRA_PAGES 3
5801 #else
5802 #define KVM_EXTRA_PAGES 0
5803 #endif
5804 if (kvm_enabled()) {
5805 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5806 if (kvm_qemu_create_context() < 0) {
5807 fprintf(stderr, "Could not create KVM context\n");
5808 exit(1);
5812 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5813 if (!phys_ram_base) {
5814 fprintf(stderr, "Could not allocate physical memory\n");
5815 exit(1);
5818 /* init the dynamic translator */
5819 cpu_exec_init_all(tb_size * 1024 * 1024);
5821 bdrv_init();
5822 dma_helper_init();
5824 /* we always create the cdrom drive, even if no disk is there */
5826 if (nb_drives_opt < MAX_DRIVES)
5827 drive_add(NULL, CDROM_ALIAS);
5829 /* we always create at least one floppy */
5831 if (nb_drives_opt < MAX_DRIVES)
5832 drive_add(NULL, FD_ALIAS, 0);
5834 /* we always create one sd slot, even if no card is in it */
5836 if (nb_drives_opt < MAX_DRIVES)
5837 drive_add(NULL, SD_ALIAS);
5839 /* open the virtual block devices
5840 * note that migration with device
5841 * hot add/remove is broken.
5843 for(i = 0; i < nb_drives_opt; i++)
5844 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5845 exit(1);
5847 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5848 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5850 #ifndef _WIN32
5851 /* must be after terminal init, SDL library changes signal handlers */
5852 termsig_setup();
5853 #endif
5855 /* Maintain compatibility with multiple stdio monitors */
5856 if (!strcmp(monitor_device,"stdio")) {
5857 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5858 const char *devname = serial_devices[i];
5859 if (devname && !strcmp(devname,"mon:stdio")) {
5860 monitor_device = NULL;
5861 break;
5862 } else if (devname && !strcmp(devname,"stdio")) {
5863 monitor_device = NULL;
5864 serial_devices[i] = "mon:stdio";
5865 break;
5870 #ifdef KVM_UPSTREAM
5871 if (kvm_enabled()) {
5872 int ret;
5874 ret = kvm_init(smp_cpus);
5875 if (ret < 0) {
5876 fprintf(stderr, "failed to initialize KVM\n");
5877 exit(1);
5880 #endif
5882 if (monitor_device) {
5883 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5884 if (!monitor_hd) {
5885 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5886 exit(1);
5890 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5891 const char *devname = serial_devices[i];
5892 if (devname && strcmp(devname, "none")) {
5893 char label[32];
5894 snprintf(label, sizeof(label), "serial%d", i);
5895 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5896 if (!serial_hds[i]) {
5897 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5898 devname);
5899 exit(1);
5904 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5905 const char *devname = parallel_devices[i];
5906 if (devname && strcmp(devname, "none")) {
5907 char label[32];
5908 snprintf(label, sizeof(label), "parallel%d", i);
5909 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5910 if (!parallel_hds[i]) {
5911 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5912 devname);
5913 exit(1);
5918 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5919 const char *devname = virtio_consoles[i];
5920 if (devname && strcmp(devname, "none")) {
5921 char label[32];
5922 snprintf(label, sizeof(label), "virtcon%d", i);
5923 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5924 if (!virtcon_hds[i]) {
5925 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5926 devname);
5927 exit(1);
5932 if (kvm_enabled())
5933 kvm_init_ap();
5935 machine->init(ram_size, vga_ram_size, boot_devices,
5936 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5938 current_machine = machine;
5940 /* Set KVM's vcpu state to qemu's initial CPUState. */
5941 if (kvm_enabled()) {
5942 int ret;
5944 ret = kvm_sync_vcpus();
5945 if (ret < 0) {
5946 fprintf(stderr, "failed to initialize vcpus\n");
5947 exit(1);
5951 /* init USB devices */
5952 if (usb_enabled) {
5953 for(i = 0; i < usb_devices_index; i++) {
5954 if (usb_device_add(usb_devices[i], 0) < 0) {
5955 fprintf(stderr, "Warning: could not add USB device %s\n",
5956 usb_devices[i]);
5961 if (!display_state)
5962 dumb_display_init();
5963 /* just use the first displaystate for the moment */
5964 ds = display_state;
5965 /* terminal init */
5966 if (nographic) {
5967 if (curses) {
5968 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5969 exit(1);
5971 } else {
5972 #if defined(CONFIG_CURSES)
5973 if (curses) {
5974 /* At the moment curses cannot be used with other displays */
5975 curses_display_init(ds, full_screen);
5976 } else
5977 #endif
5979 if (vnc_display != NULL) {
5980 vnc_display_init(ds);
5981 if (vnc_display_open(ds, vnc_display) < 0)
5982 exit(1);
5984 #if defined(CONFIG_SDL)
5985 if (sdl || !vnc_display)
5986 sdl_display_init(ds, full_screen, no_frame);
5987 #elif defined(CONFIG_COCOA)
5988 if (sdl || !vnc_display)
5989 cocoa_display_init(ds, full_screen);
5990 #endif
5993 dpy_resize(ds);
5995 dcl = ds->listeners;
5996 while (dcl != NULL) {
5997 if (dcl->dpy_refresh != NULL) {
5998 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5999 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6001 dcl = dcl->next;
6004 if (nographic || (vnc_display && !sdl)) {
6005 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6006 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6009 text_consoles_set_display(display_state);
6010 qemu_chr_initial_reset();
6012 if (monitor_device && monitor_hd)
6013 monitor_init(monitor_hd, !nographic);
6015 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6016 const char *devname = serial_devices[i];
6017 if (devname && strcmp(devname, "none")) {
6018 char label[32];
6019 snprintf(label, sizeof(label), "serial%d", i);
6020 if (strstart(devname, "vc", 0))
6021 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6025 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6026 const char *devname = parallel_devices[i];
6027 if (devname && strcmp(devname, "none")) {
6028 char label[32];
6029 snprintf(label, sizeof(label), "parallel%d", i);
6030 if (strstart(devname, "vc", 0))
6031 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6035 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6036 const char *devname = virtio_consoles[i];
6037 if (virtcon_hds[i] && devname) {
6038 char label[32];
6039 snprintf(label, sizeof(label), "virtcon%d", i);
6040 if (strstart(devname, "vc", 0))
6041 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6045 #ifdef CONFIG_GDBSTUB
6046 if (use_gdbstub) {
6047 /* XXX: use standard host:port notation and modify options
6048 accordingly. */
6049 if (gdbserver_start(gdbstub_port) < 0) {
6050 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6051 gdbstub_port);
6052 exit(1);
6055 #endif
6057 if (loadvm)
6058 do_loadvm(loadvm);
6060 if (incoming) {
6061 autostart = 0; /* fixme how to deal with -daemonize */
6062 qemu_start_incoming_migration(incoming);
6065 if (autostart)
6066 vm_start();
6068 if (daemonize) {
6069 uint8_t status = 0;
6070 ssize_t len;
6072 again1:
6073 len = write(fds[1], &status, 1);
6074 if (len == -1 && (errno == EINTR))
6075 goto again1;
6077 if (len != 1)
6078 exit(1);
6080 chdir("/");
6081 TFR(fd = open("/dev/null", O_RDWR));
6082 if (fd == -1)
6083 exit(1);
6086 #ifndef _WIN32
6087 if (run_as) {
6088 pwd = getpwnam(run_as);
6089 if (!pwd) {
6090 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6091 exit(1);
6095 if (chroot_dir) {
6096 if (chroot(chroot_dir) < 0) {
6097 fprintf(stderr, "chroot failed\n");
6098 exit(1);
6100 chdir("/");
6103 if (run_as) {
6104 if (setgid(pwd->pw_gid) < 0) {
6105 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6106 exit(1);
6108 if (setuid(pwd->pw_uid) < 0) {
6109 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6110 exit(1);
6112 if (setuid(0) != -1) {
6113 fprintf(stderr, "Dropping privileges failed\n");
6114 exit(1);
6117 #endif
6119 if (daemonize) {
6120 dup2(fd, 0);
6121 dup2(fd, 1);
6122 dup2(fd, 2);
6124 close(fd);
6127 main_loop();
6128 quit_timers();
6129 net_cleanup();
6131 return 0;