Disable the vnc CopyRect encoding
[qemu-kvm/fedora.git] / vl.c
blob0bfa3804ed02eb0a70ecb52977052076463cf8b1
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 <sys/vfs.h>
66 #include <netinet/in.h>
67 #include <net/if.h>
68 #if defined(__NetBSD__)
69 #include <net/if_tap.h>
70 #endif
71 #ifdef __linux__
72 #include <linux/if_tun.h>
73 #endif
74 #include <arpa/inet.h>
75 #include <dirent.h>
76 #include <netdb.h>
77 #include <sys/select.h>
78 #ifdef _BSD
79 #include <sys/stat.h>
80 #ifdef __FreeBSD__
81 #include <libutil.h>
82 #else
83 #include <util.h>
84 #endif
85 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
86 #include <freebsd/stdlib.h>
87 #else
88 #ifdef __linux__
89 #include <pty.h>
90 #include <malloc.h>
91 #include <linux/rtc.h>
93 /* For the benefit of older linux systems which don't supply it,
94 we use a local copy of hpet.h. */
95 /* #include <linux/hpet.h> */
96 #include "hpet.h"
98 #include <linux/ppdev.h>
99 #include <linux/parport.h>
100 #endif
101 #ifdef __sun__
102 #include <sys/stat.h>
103 #include <sys/ethernet.h>
104 #include <sys/sockio.h>
105 #include <netinet/arp.h>
106 #include <netinet/in.h>
107 #include <netinet/in_systm.h>
108 #include <netinet/ip.h>
109 #include <netinet/ip_icmp.h> // must come after ip.h
110 #include <netinet/udp.h>
111 #include <netinet/tcp.h>
112 #include <net/if.h>
113 #include <syslog.h>
114 #include <stropts.h>
115 #endif
116 #endif
117 #endif
119 #include "qemu_socket.h"
121 #if defined(CONFIG_SLIRP)
122 #include "libslirp.h"
123 #endif
125 #if defined(__OpenBSD__)
126 #include <util.h>
127 #endif
129 #if defined(CONFIG_VDE)
130 #include <libvdeplug.h>
131 #endif
133 #ifdef _WIN32
134 #include <malloc.h>
135 #include <sys/timeb.h>
136 #include <mmsystem.h>
137 #define getopt_long_only getopt_long
138 #define memalign(align, size) malloc(size)
139 #endif
141 #ifdef CONFIG_SDL
142 #ifdef __APPLE__
143 #include <SDL/SDL.h>
144 int qemu_main(int argc, char **argv, char **envp);
145 int main(int argc, char **argv)
147 qemu_main(argc, argv, NULL);
149 #undef main
150 #define main qemu_main
151 #endif
152 #endif /* CONFIG_SDL */
154 #ifdef CONFIG_COCOA
155 #undef main
156 #define main qemu_main
157 #endif /* CONFIG_COCOA */
159 #include "disas.h"
161 #include "exec-all.h"
163 #include "qemu-kvm.h"
165 //#define DEBUG_UNUSED_IOPORT
166 //#define DEBUG_IOPORT
167 //#define DEBUG_NET
168 //#define DEBUG_SLIRP
171 #ifdef DEBUG_IOPORT
172 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
173 #else
174 # define LOG_IOPORT(...) do { } while (0)
175 #endif
177 #define DEFAULT_RAM_SIZE 128
179 /* Max number of USB devices that can be specified on the commandline. */
180 #define MAX_USB_CMDLINE 8
182 /* Max number of bluetooth switches on the commandline. */
183 #define MAX_BT_CMDLINE 10
185 /* XXX: use a two level table to limit memory usage */
186 #define MAX_IOPORTS 65536
188 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
189 const char *bios_name = NULL;
190 static void *ioport_opaque[MAX_IOPORTS];
191 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
192 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
193 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
194 to store the VM snapshots */
195 DriveInfo drives_table[MAX_DRIVES+1];
196 int nb_drives;
197 int extboot_drive = -1;
198 static int vga_ram_size;
199 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
200 static DisplayState *display_state;
201 int nographic;
202 static int curses;
203 static int sdl;
204 const char* keyboard_layout = NULL;
205 int64_t ticks_per_sec;
206 ram_addr_t ram_size;
207 int nb_nics;
208 NICInfo nd_table[MAX_NICS];
209 int vm_running;
210 static int autostart;
211 static int rtc_utc = 1;
212 static int rtc_date_offset = -1; /* -1 means no change */
213 int cirrus_vga_enabled = 1;
214 int std_vga_enabled = 0;
215 int vmsvga_enabled = 0;
216 #ifdef TARGET_SPARC
217 int graphic_width = 1024;
218 int graphic_height = 768;
219 int graphic_depth = 8;
220 #else
221 int graphic_width = 800;
222 int graphic_height = 600;
223 int graphic_depth = 15;
224 #endif
225 static int full_screen = 0;
226 #ifdef CONFIG_SDL
227 static int no_frame = 0;
228 #endif
229 int no_quit = 0;
230 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
231 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
232 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
233 #ifdef TARGET_I386
234 int win2k_install_hack = 0;
235 int rtc_td_hack = 0;
236 #endif
237 int usb_enabled = 0;
238 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
239 int assigned_devices_index;
240 int smp_cpus = 1;
241 const char *vnc_display;
242 int acpi_enabled = 1;
243 int no_hpet = 0;
244 int fd_bootchk = 1;
245 int no_reboot = 0;
246 int no_shutdown = 0;
247 int cursor_hide = 1;
248 int graphic_rotate = 0;
249 int daemonize = 0;
250 const char *incoming;
251 const char *option_rom[MAX_OPTION_ROMS];
252 int nb_option_roms;
253 int semihosting_enabled = 0;
254 int time_drift_fix = 0;
255 unsigned int kvm_shadow_memory = 0;
256 const char *mem_path = NULL;
257 #ifdef MAP_POPULATE
258 int mem_prealloc = 1; /* force preallocation of physical target memory */
259 #endif
260 long hpagesize = 0;
261 const char *cpu_vendor_string;
262 #ifdef TARGET_ARM
263 int old_param = 0;
264 #endif
265 const char *qemu_name;
266 int alt_grab = 0;
267 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
268 unsigned int nb_prom_envs = 0;
269 const char *prom_envs[MAX_PROM_ENVS];
270 #endif
271 int nb_drives_opt;
272 const char *nvram = NULL;
273 struct drive_opt drives_opt[MAX_DRIVES];
275 static CPUState *cur_cpu;
276 static CPUState *next_cpu;
277 static int event_pending = 1;
278 /* Conversion factor from emulated instructions to virtual clock ticks. */
279 static int icount_time_shift;
280 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
281 #define MAX_ICOUNT_SHIFT 10
282 /* Compensate for varying guest execution speed. */
283 static int64_t qemu_icount_bias;
284 static QEMUTimer *icount_rt_timer;
285 static QEMUTimer *icount_vm_timer;
286 static QEMUTimer *nographic_timer;
288 uint8_t qemu_uuid[16];
290 /* KVM runs the main loop in a separate thread. If we update one of the lists
291 * that are polled before or after select(), we need to make sure to break out
292 * of the select() to ensure the new item is serviced.
294 static void main_loop_break(void)
296 if (kvm_enabled())
297 qemu_kvm_notify_work();
300 /***********************************************************/
301 /* x86 ISA bus support */
303 target_phys_addr_t isa_mem_base = 0;
304 PicState2 *isa_pic;
306 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
307 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
309 static uint32_t ioport_read(int index, uint32_t address)
311 static IOPortReadFunc *default_func[3] = {
312 default_ioport_readb,
313 default_ioport_readw,
314 default_ioport_readl
316 IOPortReadFunc *func = ioport_read_table[index][address];
317 if (!func)
318 func = default_func[index];
319 return func(ioport_opaque[address], address);
322 static void ioport_write(int index, uint32_t address, uint32_t data)
324 static IOPortWriteFunc *default_func[3] = {
325 default_ioport_writeb,
326 default_ioport_writew,
327 default_ioport_writel
329 IOPortWriteFunc *func = ioport_write_table[index][address];
330 if (!func)
331 func = default_func[index];
332 func(ioport_opaque[address], address, data);
335 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
337 #ifdef DEBUG_UNUSED_IOPORT
338 fprintf(stderr, "unused inb: port=0x%04x\n", address);
339 #endif
340 return 0xff;
343 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
345 #ifdef DEBUG_UNUSED_IOPORT
346 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
347 #endif
350 /* default is to make two byte accesses */
351 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
353 uint32_t data;
354 data = ioport_read(0, address);
355 address = (address + 1) & (MAX_IOPORTS - 1);
356 data |= ioport_read(0, address) << 8;
357 return data;
360 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
362 ioport_write(0, address, data & 0xff);
363 address = (address + 1) & (MAX_IOPORTS - 1);
364 ioport_write(0, address, (data >> 8) & 0xff);
367 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
369 #ifdef DEBUG_UNUSED_IOPORT
370 fprintf(stderr, "unused inl: port=0x%04x\n", address);
371 #endif
372 return 0xffffffff;
375 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
377 #ifdef DEBUG_UNUSED_IOPORT
378 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
379 #endif
382 /* size is the word size in byte */
383 int register_ioport_read(int start, int length, int size,
384 IOPortReadFunc *func, void *opaque)
386 int i, bsize;
388 if (size == 1) {
389 bsize = 0;
390 } else if (size == 2) {
391 bsize = 1;
392 } else if (size == 4) {
393 bsize = 2;
394 } else {
395 hw_error("register_ioport_read: invalid size");
396 return -1;
398 for(i = start; i < start + length; i += size) {
399 ioport_read_table[bsize][i] = func;
400 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
401 hw_error("register_ioport_read: invalid opaque");
402 ioport_opaque[i] = opaque;
404 return 0;
407 /* size is the word size in byte */
408 int register_ioport_write(int start, int length, int size,
409 IOPortWriteFunc *func, void *opaque)
411 int i, bsize;
413 if (size == 1) {
414 bsize = 0;
415 } else if (size == 2) {
416 bsize = 1;
417 } else if (size == 4) {
418 bsize = 2;
419 } else {
420 hw_error("register_ioport_write: invalid size");
421 return -1;
423 for(i = start; i < start + length; i += size) {
424 ioport_write_table[bsize][i] = func;
425 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
426 hw_error("register_ioport_write: invalid opaque");
427 ioport_opaque[i] = opaque;
429 return 0;
432 void isa_unassign_ioport(int start, int length)
434 int i;
436 for(i = start; i < start + length; i++) {
437 ioport_read_table[0][i] = default_ioport_readb;
438 ioport_read_table[1][i] = default_ioport_readw;
439 ioport_read_table[2][i] = default_ioport_readl;
441 ioport_write_table[0][i] = default_ioport_writeb;
442 ioport_write_table[1][i] = default_ioport_writew;
443 ioport_write_table[2][i] = default_ioport_writel;
445 ioport_opaque[i] = NULL;
449 /***********************************************************/
451 void cpu_outb(CPUState *env, int addr, int val)
453 LOG_IOPORT("outb: %04x %02x\n", addr, val);
454 ioport_write(0, addr, val);
455 #ifdef USE_KQEMU
456 if (env)
457 env->last_io_time = cpu_get_time_fast();
458 #endif
461 void cpu_outw(CPUState *env, int addr, int val)
463 LOG_IOPORT("outw: %04x %04x\n", addr, val);
464 ioport_write(1, addr, val);
465 #ifdef USE_KQEMU
466 if (env)
467 env->last_io_time = cpu_get_time_fast();
468 #endif
471 void cpu_outl(CPUState *env, int addr, int val)
473 LOG_IOPORT("outl: %04x %08x\n", addr, val);
474 ioport_write(2, addr, val);
475 #ifdef USE_KQEMU
476 if (env)
477 env->last_io_time = cpu_get_time_fast();
478 #endif
481 int cpu_inb(CPUState *env, int addr)
483 int val;
484 val = ioport_read(0, addr);
485 LOG_IOPORT("inb : %04x %02x\n", addr, val);
486 #ifdef USE_KQEMU
487 if (env)
488 env->last_io_time = cpu_get_time_fast();
489 #endif
490 return val;
493 int cpu_inw(CPUState *env, int addr)
495 int val;
496 val = ioport_read(1, addr);
497 LOG_IOPORT("inw : %04x %04x\n", addr, val);
498 #ifdef USE_KQEMU
499 if (env)
500 env->last_io_time = cpu_get_time_fast();
501 #endif
502 return val;
505 int cpu_inl(CPUState *env, int addr)
507 int val;
508 val = ioport_read(2, addr);
509 LOG_IOPORT("inl : %04x %08x\n", addr, val);
510 #ifdef USE_KQEMU
511 if (env)
512 env->last_io_time = cpu_get_time_fast();
513 #endif
514 return val;
517 /***********************************************************/
518 void hw_error(const char *fmt, ...)
520 va_list ap;
521 CPUState *env;
523 va_start(ap, fmt);
524 fprintf(stderr, "qemu: hardware error: ");
525 vfprintf(stderr, fmt, ap);
526 fprintf(stderr, "\n");
527 for(env = first_cpu; env != NULL; env = env->next_cpu) {
528 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
529 #ifdef TARGET_I386
530 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
531 #else
532 cpu_dump_state(env, stderr, fprintf, 0);
533 #endif
535 va_end(ap);
536 abort();
539 /***************/
540 /* ballooning */
542 static QEMUBalloonEvent *qemu_balloon_event;
543 void *qemu_balloon_event_opaque;
545 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
547 qemu_balloon_event = func;
548 qemu_balloon_event_opaque = opaque;
551 void qemu_balloon(ram_addr_t target)
553 if (qemu_balloon_event)
554 qemu_balloon_event(qemu_balloon_event_opaque, target);
557 ram_addr_t qemu_balloon_status(void)
559 if (qemu_balloon_event)
560 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
561 return 0;
564 /***********************************************************/
565 /* keyboard/mouse */
567 static QEMUPutKBDEvent *qemu_put_kbd_event;
568 static void *qemu_put_kbd_event_opaque;
569 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
570 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
572 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
574 qemu_put_kbd_event_opaque = opaque;
575 qemu_put_kbd_event = func;
578 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
579 void *opaque, int absolute,
580 const char *name)
582 QEMUPutMouseEntry *s, *cursor;
584 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
586 s->qemu_put_mouse_event = func;
587 s->qemu_put_mouse_event_opaque = opaque;
588 s->qemu_put_mouse_event_absolute = absolute;
589 s->qemu_put_mouse_event_name = qemu_strdup(name);
590 s->next = NULL;
592 if (!qemu_put_mouse_event_head) {
593 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
594 return s;
597 cursor = qemu_put_mouse_event_head;
598 while (cursor->next != NULL)
599 cursor = cursor->next;
601 cursor->next = s;
602 qemu_put_mouse_event_current = s;
604 return s;
607 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
609 QEMUPutMouseEntry *prev = NULL, *cursor;
611 if (!qemu_put_mouse_event_head || entry == NULL)
612 return;
614 cursor = qemu_put_mouse_event_head;
615 while (cursor != NULL && cursor != entry) {
616 prev = cursor;
617 cursor = cursor->next;
620 if (cursor == NULL) // does not exist or list empty
621 return;
622 else if (prev == NULL) { // entry is head
623 qemu_put_mouse_event_head = cursor->next;
624 if (qemu_put_mouse_event_current == entry)
625 qemu_put_mouse_event_current = cursor->next;
626 qemu_free(entry->qemu_put_mouse_event_name);
627 qemu_free(entry);
628 return;
631 prev->next = entry->next;
633 if (qemu_put_mouse_event_current == entry)
634 qemu_put_mouse_event_current = prev;
636 qemu_free(entry->qemu_put_mouse_event_name);
637 qemu_free(entry);
640 void kbd_put_keycode(int keycode)
642 if (qemu_put_kbd_event) {
643 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
647 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
649 QEMUPutMouseEvent *mouse_event;
650 void *mouse_event_opaque;
651 int width;
653 if (!qemu_put_mouse_event_current) {
654 return;
657 mouse_event =
658 qemu_put_mouse_event_current->qemu_put_mouse_event;
659 mouse_event_opaque =
660 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
662 if (mouse_event) {
663 if (graphic_rotate) {
664 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
665 width = 0x7fff;
666 else
667 width = graphic_width - 1;
668 mouse_event(mouse_event_opaque,
669 width - dy, dx, dz, buttons_state);
670 } else
671 mouse_event(mouse_event_opaque,
672 dx, dy, dz, buttons_state);
676 int kbd_mouse_is_absolute(void)
678 if (!qemu_put_mouse_event_current)
679 return 0;
681 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
684 void do_info_mice(void)
686 QEMUPutMouseEntry *cursor;
687 int index = 0;
689 if (!qemu_put_mouse_event_head) {
690 term_printf("No mouse devices connected\n");
691 return;
694 term_printf("Mouse devices available:\n");
695 cursor = qemu_put_mouse_event_head;
696 while (cursor != NULL) {
697 term_printf("%c Mouse #%d: %s\n",
698 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
699 index, cursor->qemu_put_mouse_event_name);
700 index++;
701 cursor = cursor->next;
705 void do_mouse_set(int index)
707 QEMUPutMouseEntry *cursor;
708 int i = 0;
710 if (!qemu_put_mouse_event_head) {
711 term_printf("No mouse devices connected\n");
712 return;
715 cursor = qemu_put_mouse_event_head;
716 while (cursor != NULL && index != i) {
717 i++;
718 cursor = cursor->next;
721 if (cursor != NULL)
722 qemu_put_mouse_event_current = cursor;
723 else
724 term_printf("Mouse at given index not found\n");
727 /* compute with 96 bit intermediate result: (a*b)/c */
728 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
730 union {
731 uint64_t ll;
732 struct {
733 #ifdef WORDS_BIGENDIAN
734 uint32_t high, low;
735 #else
736 uint32_t low, high;
737 #endif
738 } l;
739 } u, res;
740 uint64_t rl, rh;
742 u.ll = a;
743 rl = (uint64_t)u.l.low * (uint64_t)b;
744 rh = (uint64_t)u.l.high * (uint64_t)b;
745 rh += (rl >> 32);
746 res.l.high = rh / c;
747 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
748 return res.ll;
751 /***********************************************************/
752 /* real time host monotonic timer */
754 #define QEMU_TIMER_BASE 1000000000LL
756 #ifdef WIN32
758 static int64_t clock_freq;
760 static void init_get_clock(void)
762 LARGE_INTEGER freq;
763 int ret;
764 ret = QueryPerformanceFrequency(&freq);
765 if (ret == 0) {
766 fprintf(stderr, "Could not calibrate ticks\n");
767 exit(1);
769 clock_freq = freq.QuadPart;
772 static int64_t get_clock(void)
774 LARGE_INTEGER ti;
775 QueryPerformanceCounter(&ti);
776 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
779 #else
781 static int use_rt_clock;
783 static void init_get_clock(void)
785 use_rt_clock = 0;
786 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
788 struct timespec ts;
789 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
790 use_rt_clock = 1;
793 #endif
796 static int64_t get_clock(void)
798 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
799 if (use_rt_clock) {
800 struct timespec ts;
801 clock_gettime(CLOCK_MONOTONIC, &ts);
802 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
803 } else
804 #endif
806 /* XXX: using gettimeofday leads to problems if the date
807 changes, so it should be avoided. */
808 struct timeval tv;
809 gettimeofday(&tv, NULL);
810 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
813 #endif
815 /* Return the virtual CPU time, based on the instruction counter. */
816 static int64_t cpu_get_icount(void)
818 int64_t icount;
819 CPUState *env = cpu_single_env;;
820 icount = qemu_icount;
821 if (env) {
822 if (!can_do_io(env))
823 fprintf(stderr, "Bad clock read\n");
824 icount -= (env->icount_decr.u16.low + env->icount_extra);
826 return qemu_icount_bias + (icount << icount_time_shift);
829 /***********************************************************/
830 /* guest cycle counter */
832 static int64_t cpu_ticks_prev;
833 static int64_t cpu_ticks_offset;
834 static int64_t cpu_clock_offset;
835 static int cpu_ticks_enabled;
837 /* return the host CPU cycle counter and handle stop/restart */
838 int64_t cpu_get_ticks(void)
840 if (use_icount) {
841 return cpu_get_icount();
843 if (!cpu_ticks_enabled) {
844 return cpu_ticks_offset;
845 } else {
846 int64_t ticks;
847 ticks = cpu_get_real_ticks();
848 if (cpu_ticks_prev > ticks) {
849 /* Note: non increasing ticks may happen if the host uses
850 software suspend */
851 cpu_ticks_offset += cpu_ticks_prev - ticks;
853 cpu_ticks_prev = ticks;
854 return ticks + cpu_ticks_offset;
858 /* return the host CPU monotonic timer and handle stop/restart */
859 static int64_t cpu_get_clock(void)
861 int64_t ti;
862 if (!cpu_ticks_enabled) {
863 return cpu_clock_offset;
864 } else {
865 ti = get_clock();
866 return ti + cpu_clock_offset;
870 /* enable cpu_get_ticks() */
871 void cpu_enable_ticks(void)
873 if (!cpu_ticks_enabled) {
874 cpu_ticks_offset -= cpu_get_real_ticks();
875 cpu_clock_offset -= get_clock();
876 cpu_ticks_enabled = 1;
880 /* disable cpu_get_ticks() : the clock is stopped. You must not call
881 cpu_get_ticks() after that. */
882 void cpu_disable_ticks(void)
884 if (cpu_ticks_enabled) {
885 cpu_ticks_offset = cpu_get_ticks();
886 cpu_clock_offset = cpu_get_clock();
887 cpu_ticks_enabled = 0;
891 /***********************************************************/
892 /* timers */
894 #define QEMU_TIMER_REALTIME 0
895 #define QEMU_TIMER_VIRTUAL 1
897 struct QEMUClock {
898 int type;
899 /* XXX: add frequency */
902 struct QEMUTimer {
903 QEMUClock *clock;
904 int64_t expire_time;
905 QEMUTimerCB *cb;
906 void *opaque;
907 struct QEMUTimer *next;
910 struct qemu_alarm_timer {
911 char const *name;
912 unsigned int flags;
914 int (*start)(struct qemu_alarm_timer *t);
915 void (*stop)(struct qemu_alarm_timer *t);
916 void (*rearm)(struct qemu_alarm_timer *t);
917 void *priv;
920 #define ALARM_FLAG_DYNTICKS 0x1
921 #define ALARM_FLAG_EXPIRED 0x2
923 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
925 return t && (t->flags & ALARM_FLAG_DYNTICKS);
928 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
930 if (!alarm_has_dynticks(t))
931 return;
933 t->rearm(t);
936 /* TODO: MIN_TIMER_REARM_US should be optimized */
937 #define MIN_TIMER_REARM_US 250
939 static struct qemu_alarm_timer *alarm_timer;
940 #ifndef _WIN32
941 static int alarm_timer_rfd, alarm_timer_wfd;
942 #endif
944 #ifdef _WIN32
946 struct qemu_alarm_win32 {
947 MMRESULT timerId;
948 HANDLE host_alarm;
949 unsigned int period;
950 } alarm_win32_data = {0, NULL, -1};
952 static int win32_start_timer(struct qemu_alarm_timer *t);
953 static void win32_stop_timer(struct qemu_alarm_timer *t);
954 static void win32_rearm_timer(struct qemu_alarm_timer *t);
956 #else
958 static int unix_start_timer(struct qemu_alarm_timer *t);
959 static void unix_stop_timer(struct qemu_alarm_timer *t);
961 #ifdef __linux__
963 static int dynticks_start_timer(struct qemu_alarm_timer *t);
964 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
965 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
967 static int hpet_start_timer(struct qemu_alarm_timer *t);
968 static void hpet_stop_timer(struct qemu_alarm_timer *t);
970 static int rtc_start_timer(struct qemu_alarm_timer *t);
971 static void rtc_stop_timer(struct qemu_alarm_timer *t);
973 #endif /* __linux__ */
975 #endif /* _WIN32 */
977 /* Correlation between real and virtual time is always going to be
978 fairly approximate, so ignore small variation.
979 When the guest is idle real and virtual time will be aligned in
980 the IO wait loop. */
981 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
983 static void icount_adjust(void)
985 int64_t cur_time;
986 int64_t cur_icount;
987 int64_t delta;
988 static int64_t last_delta;
989 /* If the VM is not running, then do nothing. */
990 if (!vm_running)
991 return;
993 cur_time = cpu_get_clock();
994 cur_icount = qemu_get_clock(vm_clock);
995 delta = cur_icount - cur_time;
996 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
997 if (delta > 0
998 && last_delta + ICOUNT_WOBBLE < delta * 2
999 && icount_time_shift > 0) {
1000 /* The guest is getting too far ahead. Slow time down. */
1001 icount_time_shift--;
1003 if (delta < 0
1004 && last_delta - ICOUNT_WOBBLE > delta * 2
1005 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1006 /* The guest is getting too far behind. Speed time up. */
1007 icount_time_shift++;
1009 last_delta = delta;
1010 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1013 static void icount_adjust_rt(void * opaque)
1015 qemu_mod_timer(icount_rt_timer,
1016 qemu_get_clock(rt_clock) + 1000);
1017 icount_adjust();
1020 static void icount_adjust_vm(void * opaque)
1022 qemu_mod_timer(icount_vm_timer,
1023 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1024 icount_adjust();
1027 static void init_icount_adjust(void)
1029 /* Have both realtime and virtual time triggers for speed adjustment.
1030 The realtime trigger catches emulated time passing too slowly,
1031 the virtual time trigger catches emulated time passing too fast.
1032 Realtime triggers occur even when idle, so use them less frequently
1033 than VM triggers. */
1034 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1035 qemu_mod_timer(icount_rt_timer,
1036 qemu_get_clock(rt_clock) + 1000);
1037 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1038 qemu_mod_timer(icount_vm_timer,
1039 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1042 static struct qemu_alarm_timer alarm_timers[] = {
1043 #ifndef _WIN32
1044 #ifdef __linux__
1045 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1046 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1047 /* HPET - if available - is preferred */
1048 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1049 /* ...otherwise try RTC */
1050 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1051 #endif
1052 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1053 #else
1054 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1055 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1056 {"win32", 0, win32_start_timer,
1057 win32_stop_timer, NULL, &alarm_win32_data},
1058 #endif
1059 {NULL, }
1062 static void show_available_alarms(void)
1064 int i;
1066 printf("Available alarm timers, in order of precedence:\n");
1067 for (i = 0; alarm_timers[i].name; i++)
1068 printf("%s\n", alarm_timers[i].name);
1071 static void configure_alarms(char const *opt)
1073 int i;
1074 int cur = 0;
1075 int count = ARRAY_SIZE(alarm_timers) - 1;
1076 char *arg;
1077 char *name;
1078 struct qemu_alarm_timer tmp;
1080 if (!strcmp(opt, "?")) {
1081 show_available_alarms();
1082 exit(0);
1085 arg = strdup(opt);
1087 /* Reorder the array */
1088 name = strtok(arg, ",");
1089 while (name) {
1090 for (i = 0; i < count && alarm_timers[i].name; i++) {
1091 if (!strcmp(alarm_timers[i].name, name))
1092 break;
1095 if (i == count) {
1096 fprintf(stderr, "Unknown clock %s\n", name);
1097 goto next;
1100 if (i < cur)
1101 /* Ignore */
1102 goto next;
1104 /* Swap */
1105 tmp = alarm_timers[i];
1106 alarm_timers[i] = alarm_timers[cur];
1107 alarm_timers[cur] = tmp;
1109 cur++;
1110 next:
1111 name = strtok(NULL, ",");
1114 free(arg);
1116 if (cur) {
1117 /* Disable remaining timers */
1118 for (i = cur; i < count; i++)
1119 alarm_timers[i].name = NULL;
1120 } else {
1121 show_available_alarms();
1122 exit(1);
1126 QEMUClock *rt_clock;
1127 QEMUClock *vm_clock;
1129 static QEMUTimer *active_timers[2];
1131 static QEMUClock *qemu_new_clock(int type)
1133 QEMUClock *clock;
1134 clock = qemu_mallocz(sizeof(QEMUClock));
1135 clock->type = type;
1136 return clock;
1139 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1141 QEMUTimer *ts;
1143 ts = qemu_mallocz(sizeof(QEMUTimer));
1144 ts->clock = clock;
1145 ts->cb = cb;
1146 ts->opaque = opaque;
1147 return ts;
1150 void qemu_free_timer(QEMUTimer *ts)
1152 qemu_free(ts);
1155 /* stop a timer, but do not dealloc it */
1156 void qemu_del_timer(QEMUTimer *ts)
1158 QEMUTimer **pt, *t;
1160 /* NOTE: this code must be signal safe because
1161 qemu_timer_expired() can be called from a signal. */
1162 pt = &active_timers[ts->clock->type];
1163 for(;;) {
1164 t = *pt;
1165 if (!t)
1166 break;
1167 if (t == ts) {
1168 *pt = t->next;
1169 break;
1171 pt = &t->next;
1175 /* modify the current timer so that it will be fired when current_time
1176 >= expire_time. The corresponding callback will be called. */
1177 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1179 QEMUTimer **pt, *t;
1181 qemu_del_timer(ts);
1183 /* add the timer in the sorted list */
1184 /* NOTE: this code must be signal safe because
1185 qemu_timer_expired() can be called from a signal. */
1186 pt = &active_timers[ts->clock->type];
1187 for(;;) {
1188 t = *pt;
1189 if (!t)
1190 break;
1191 if (t->expire_time > expire_time)
1192 break;
1193 pt = &t->next;
1195 ts->expire_time = expire_time;
1196 ts->next = *pt;
1197 *pt = ts;
1199 /* Rearm if necessary */
1200 if (pt == &active_timers[ts->clock->type]) {
1201 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1202 qemu_rearm_alarm_timer(alarm_timer);
1204 /* Interrupt execution to force deadline recalculation. */
1205 if (use_icount && cpu_single_env) {
1206 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1211 int qemu_timer_pending(QEMUTimer *ts)
1213 QEMUTimer *t;
1214 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1215 if (t == ts)
1216 return 1;
1218 return 0;
1221 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1223 if (!timer_head)
1224 return 0;
1225 return (timer_head->expire_time <= current_time);
1228 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1230 QEMUTimer *ts;
1232 for(;;) {
1233 ts = *ptimer_head;
1234 if (!ts || ts->expire_time > current_time)
1235 break;
1236 /* remove timer from the list before calling the callback */
1237 *ptimer_head = ts->next;
1238 ts->next = NULL;
1240 /* run the callback (the timer list can be modified) */
1241 ts->cb(ts->opaque);
1245 int64_t qemu_get_clock(QEMUClock *clock)
1247 switch(clock->type) {
1248 case QEMU_TIMER_REALTIME:
1249 return get_clock() / 1000000;
1250 default:
1251 case QEMU_TIMER_VIRTUAL:
1252 if (use_icount) {
1253 return cpu_get_icount();
1254 } else {
1255 return cpu_get_clock();
1260 static void init_timers(void)
1262 init_get_clock();
1263 ticks_per_sec = QEMU_TIMER_BASE;
1264 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1265 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1268 /* save a timer */
1269 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1271 uint64_t expire_time;
1273 if (qemu_timer_pending(ts)) {
1274 expire_time = ts->expire_time;
1275 } else {
1276 expire_time = -1;
1278 qemu_put_be64(f, expire_time);
1281 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1283 uint64_t expire_time;
1285 expire_time = qemu_get_be64(f);
1286 if (expire_time != -1) {
1287 qemu_mod_timer(ts, expire_time);
1288 } else {
1289 qemu_del_timer(ts);
1293 static void timer_save(QEMUFile *f, void *opaque)
1295 if (cpu_ticks_enabled) {
1296 hw_error("cannot save state if virtual timers are running");
1298 qemu_put_be64(f, cpu_ticks_offset);
1299 qemu_put_be64(f, ticks_per_sec);
1300 qemu_put_be64(f, cpu_clock_offset);
1303 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1305 if (version_id != 1 && version_id != 2)
1306 return -EINVAL;
1307 if (cpu_ticks_enabled) {
1308 return -EINVAL;
1310 cpu_ticks_offset=qemu_get_be64(f);
1311 ticks_per_sec=qemu_get_be64(f);
1312 if (version_id == 2) {
1313 cpu_clock_offset=qemu_get_be64(f);
1315 return 0;
1318 #ifdef _WIN32
1319 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1320 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1321 #else
1322 static void host_alarm_handler(int host_signum)
1323 #endif
1325 #if 0
1326 #define DISP_FREQ 1000
1328 static int64_t delta_min = INT64_MAX;
1329 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1330 static int count;
1331 ti = qemu_get_clock(vm_clock);
1332 if (last_clock != 0) {
1333 delta = ti - last_clock;
1334 if (delta < delta_min)
1335 delta_min = delta;
1336 if (delta > delta_max)
1337 delta_max = delta;
1338 delta_cum += delta;
1339 if (++count == DISP_FREQ) {
1340 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1341 muldiv64(delta_min, 1000000, ticks_per_sec),
1342 muldiv64(delta_max, 1000000, ticks_per_sec),
1343 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1344 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1345 count = 0;
1346 delta_min = INT64_MAX;
1347 delta_max = 0;
1348 delta_cum = 0;
1351 last_clock = ti;
1353 #endif
1354 if (1 ||
1355 alarm_has_dynticks(alarm_timer) ||
1356 (!use_icount &&
1357 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1358 qemu_get_clock(vm_clock))) ||
1359 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1360 qemu_get_clock(rt_clock))) {
1361 CPUState *env = next_cpu;
1363 #ifdef _WIN32
1364 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1365 SetEvent(data->host_alarm);
1366 #else
1367 static const char byte = 0;
1368 write(alarm_timer_wfd, &byte, sizeof(byte));
1369 #endif
1370 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1372 if (env) {
1373 /* stop the currently executing cpu because a timer occured */
1374 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1375 #ifdef USE_KQEMU
1376 if (env->kqemu_enabled) {
1377 kqemu_cpu_interrupt(env);
1379 #endif
1381 event_pending = 1;
1385 static int64_t qemu_next_deadline(void)
1387 int64_t delta;
1389 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1390 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1391 qemu_get_clock(vm_clock);
1392 } else {
1393 /* To avoid problems with overflow limit this to 2^32. */
1394 delta = INT32_MAX;
1397 if (delta < 0)
1398 delta = 0;
1400 return delta;
1403 #if defined(__linux__) || defined(_WIN32)
1404 static uint64_t qemu_next_deadline_dyntick(void)
1406 int64_t delta;
1407 int64_t rtdelta;
1409 if (use_icount)
1410 delta = INT32_MAX;
1411 else
1412 delta = (qemu_next_deadline() + 999) / 1000;
1414 if (active_timers[QEMU_TIMER_REALTIME]) {
1415 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1416 qemu_get_clock(rt_clock))*1000;
1417 if (rtdelta < delta)
1418 delta = rtdelta;
1421 if (delta < MIN_TIMER_REARM_US)
1422 delta = MIN_TIMER_REARM_US;
1424 return delta;
1426 #endif
1428 #ifndef _WIN32
1430 /* Sets a specific flag */
1431 static int fcntl_setfl(int fd, int flag)
1433 int flags;
1435 flags = fcntl(fd, F_GETFL);
1436 if (flags == -1)
1437 return -errno;
1439 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1440 return -errno;
1442 return 0;
1445 #if defined(__linux__)
1447 #define RTC_FREQ 1024
1449 static void enable_sigio_timer(int fd)
1451 struct sigaction act;
1453 /* timer signal */
1454 sigfillset(&act.sa_mask);
1455 act.sa_flags = 0;
1456 act.sa_handler = host_alarm_handler;
1458 sigaction(SIGIO, &act, NULL);
1459 fcntl_setfl(fd, O_ASYNC);
1460 fcntl(fd, F_SETOWN, getpid());
1463 static int hpet_start_timer(struct qemu_alarm_timer *t)
1465 struct hpet_info info;
1466 int r, fd;
1468 fd = open("/dev/hpet", O_RDONLY);
1469 if (fd < 0)
1470 return -1;
1472 /* Set frequency */
1473 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1474 if (r < 0) {
1475 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1476 "error, but for better emulation accuracy type:\n"
1477 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1478 goto fail;
1481 /* Check capabilities */
1482 r = ioctl(fd, HPET_INFO, &info);
1483 if (r < 0)
1484 goto fail;
1486 /* Enable periodic mode */
1487 r = ioctl(fd, HPET_EPI, 0);
1488 if (info.hi_flags && (r < 0))
1489 goto fail;
1491 /* Enable interrupt */
1492 r = ioctl(fd, HPET_IE_ON, 0);
1493 if (r < 0)
1494 goto fail;
1496 enable_sigio_timer(fd);
1497 t->priv = (void *)(long)fd;
1499 return 0;
1500 fail:
1501 close(fd);
1502 return -1;
1505 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1507 int fd = (long)t->priv;
1509 close(fd);
1512 static int rtc_start_timer(struct qemu_alarm_timer *t)
1514 int rtc_fd;
1515 unsigned long current_rtc_freq = 0;
1517 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1518 if (rtc_fd < 0)
1519 return -1;
1520 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1521 if (current_rtc_freq != RTC_FREQ &&
1522 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1523 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1524 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1525 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1526 goto fail;
1528 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1529 fail:
1530 close(rtc_fd);
1531 return -1;
1534 enable_sigio_timer(rtc_fd);
1536 t->priv = (void *)(long)rtc_fd;
1538 return 0;
1541 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1543 int rtc_fd = (long)t->priv;
1545 close(rtc_fd);
1548 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1550 struct sigevent ev;
1551 timer_t host_timer;
1552 struct sigaction act;
1554 sigfillset(&act.sa_mask);
1555 act.sa_flags = 0;
1556 act.sa_handler = host_alarm_handler;
1558 sigaction(SIGALRM, &act, NULL);
1561 * Initialize ev struct to 0 to avoid valgrind complaining
1562 * about uninitialized data in timer_create call
1564 memset(&ev, 0, sizeof(ev));
1565 ev.sigev_value.sival_int = 0;
1566 ev.sigev_notify = SIGEV_SIGNAL;
1567 ev.sigev_signo = SIGALRM;
1569 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1570 perror("timer_create");
1572 /* disable dynticks */
1573 fprintf(stderr, "Dynamic Ticks disabled\n");
1575 return -1;
1578 t->priv = (void *)(long)host_timer;
1580 return 0;
1583 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1585 timer_t host_timer = (timer_t)(long)t->priv;
1587 timer_delete(host_timer);
1590 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1592 timer_t host_timer = (timer_t)(long)t->priv;
1593 struct itimerspec timeout;
1594 int64_t nearest_delta_us = INT64_MAX;
1595 int64_t current_us;
1597 if (!active_timers[QEMU_TIMER_REALTIME] &&
1598 !active_timers[QEMU_TIMER_VIRTUAL])
1599 return;
1601 nearest_delta_us = qemu_next_deadline_dyntick();
1603 /* check whether a timer is already running */
1604 if (timer_gettime(host_timer, &timeout)) {
1605 perror("gettime");
1606 fprintf(stderr, "Internal timer error: aborting\n");
1607 exit(1);
1609 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1610 if (current_us && current_us <= nearest_delta_us)
1611 return;
1613 timeout.it_interval.tv_sec = 0;
1614 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1615 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1616 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1617 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1618 perror("settime");
1619 fprintf(stderr, "Internal timer error: aborting\n");
1620 exit(1);
1624 #endif /* defined(__linux__) */
1626 static int unix_start_timer(struct qemu_alarm_timer *t)
1628 struct sigaction act;
1629 struct itimerval itv;
1630 int err;
1632 /* timer signal */
1633 sigfillset(&act.sa_mask);
1634 act.sa_flags = 0;
1635 act.sa_handler = host_alarm_handler;
1637 sigaction(SIGALRM, &act, NULL);
1639 itv.it_interval.tv_sec = 0;
1640 /* for i386 kernel 2.6 to get 1 ms */
1641 itv.it_interval.tv_usec = 999;
1642 itv.it_value.tv_sec = 0;
1643 itv.it_value.tv_usec = 10 * 1000;
1645 err = setitimer(ITIMER_REAL, &itv, NULL);
1646 if (err)
1647 return -1;
1649 return 0;
1652 static void unix_stop_timer(struct qemu_alarm_timer *t)
1654 struct itimerval itv;
1656 memset(&itv, 0, sizeof(itv));
1657 setitimer(ITIMER_REAL, &itv, NULL);
1660 #endif /* !defined(_WIN32) */
1662 static void try_to_rearm_timer(void *opaque)
1664 struct qemu_alarm_timer *t = opaque;
1665 #ifndef _WIN32
1666 ssize_t len;
1668 /* Drain the notify pipe */
1669 do {
1670 char buffer[512];
1671 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1672 } while ((len == -1 && errno == EINTR) || len > 0);
1673 #endif
1675 if (t->flags & ALARM_FLAG_EXPIRED) {
1676 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1677 qemu_rearm_alarm_timer(alarm_timer);
1681 #ifdef _WIN32
1683 static int win32_start_timer(struct qemu_alarm_timer *t)
1685 TIMECAPS tc;
1686 struct qemu_alarm_win32 *data = t->priv;
1687 UINT flags;
1689 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1690 if (!data->host_alarm) {
1691 perror("Failed CreateEvent");
1692 return -1;
1695 memset(&tc, 0, sizeof(tc));
1696 timeGetDevCaps(&tc, sizeof(tc));
1698 if (data->period < tc.wPeriodMin)
1699 data->period = tc.wPeriodMin;
1701 timeBeginPeriod(data->period);
1703 flags = TIME_CALLBACK_FUNCTION;
1704 if (alarm_has_dynticks(t))
1705 flags |= TIME_ONESHOT;
1706 else
1707 flags |= TIME_PERIODIC;
1709 data->timerId = timeSetEvent(1, // interval (ms)
1710 data->period, // resolution
1711 host_alarm_handler, // function
1712 (DWORD)t, // parameter
1713 flags);
1715 if (!data->timerId) {
1716 perror("Failed to initialize win32 alarm timer");
1718 timeEndPeriod(data->period);
1719 CloseHandle(data->host_alarm);
1720 return -1;
1723 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1725 return 0;
1728 static void win32_stop_timer(struct qemu_alarm_timer *t)
1730 struct qemu_alarm_win32 *data = t->priv;
1732 timeKillEvent(data->timerId);
1733 timeEndPeriod(data->period);
1735 CloseHandle(data->host_alarm);
1738 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1740 struct qemu_alarm_win32 *data = t->priv;
1741 uint64_t nearest_delta_us;
1743 if (!active_timers[QEMU_TIMER_REALTIME] &&
1744 !active_timers[QEMU_TIMER_VIRTUAL])
1745 return;
1747 nearest_delta_us = qemu_next_deadline_dyntick();
1748 nearest_delta_us /= 1000;
1750 timeKillEvent(data->timerId);
1752 data->timerId = timeSetEvent(1,
1753 data->period,
1754 host_alarm_handler,
1755 (DWORD)t,
1756 TIME_ONESHOT | TIME_PERIODIC);
1758 if (!data->timerId) {
1759 perror("Failed to re-arm win32 alarm timer");
1761 timeEndPeriod(data->period);
1762 CloseHandle(data->host_alarm);
1763 exit(1);
1767 #endif /* _WIN32 */
1769 static int init_timer_alarm(void)
1771 struct qemu_alarm_timer *t = NULL;
1772 int i, err = -1;
1774 #ifndef _WIN32
1775 int fds[2];
1777 err = pipe(fds);
1778 if (err == -1)
1779 return -errno;
1781 err = fcntl_setfl(fds[0], O_NONBLOCK);
1782 if (err < 0)
1783 goto fail;
1785 err = fcntl_setfl(fds[1], O_NONBLOCK);
1786 if (err < 0)
1787 goto fail;
1789 alarm_timer_rfd = fds[0];
1790 alarm_timer_wfd = fds[1];
1791 #endif
1793 for (i = 0; alarm_timers[i].name; i++) {
1794 t = &alarm_timers[i];
1796 err = t->start(t);
1797 if (!err)
1798 break;
1801 if (err) {
1802 err = -ENOENT;
1803 goto fail;
1806 #ifndef _WIN32
1807 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1808 try_to_rearm_timer, NULL, t);
1809 #endif
1811 alarm_timer = t;
1813 return 0;
1815 fail:
1816 #ifndef _WIN32
1817 close(fds[0]);
1818 close(fds[1]);
1819 #endif
1820 return err;
1823 static void quit_timers(void)
1825 alarm_timer->stop(alarm_timer);
1826 alarm_timer = NULL;
1829 /***********************************************************/
1830 /* host time/date access */
1831 void qemu_get_timedate(struct tm *tm, int offset)
1833 time_t ti;
1834 struct tm *ret;
1836 time(&ti);
1837 ti += offset;
1838 if (rtc_date_offset == -1) {
1839 if (rtc_utc)
1840 ret = gmtime(&ti);
1841 else
1842 ret = localtime(&ti);
1843 } else {
1844 ti -= rtc_date_offset;
1845 ret = gmtime(&ti);
1848 memcpy(tm, ret, sizeof(struct tm));
1851 int qemu_timedate_diff(struct tm *tm)
1853 time_t seconds;
1855 if (rtc_date_offset == -1)
1856 if (rtc_utc)
1857 seconds = mktimegm(tm);
1858 else
1859 seconds = mktime(tm);
1860 else
1861 seconds = mktimegm(tm) + rtc_date_offset;
1863 return seconds - time(NULL);
1866 #ifdef _WIN32
1867 static void socket_cleanup(void)
1869 WSACleanup();
1872 static int socket_init(void)
1874 WSADATA Data;
1875 int ret, err;
1877 ret = WSAStartup(MAKEWORD(2,2), &Data);
1878 if (ret != 0) {
1879 err = WSAGetLastError();
1880 fprintf(stderr, "WSAStartup: %d\n", err);
1881 return -1;
1883 atexit(socket_cleanup);
1884 return 0;
1886 #endif
1888 const char *get_opt_name(char *buf, int buf_size, const char *p)
1890 char *q;
1892 q = buf;
1893 while (*p != '\0' && *p != '=') {
1894 if (q && (q - buf) < buf_size - 1)
1895 *q++ = *p;
1896 p++;
1898 if (q)
1899 *q = '\0';
1901 return p;
1904 const char *get_opt_value(char *buf, int buf_size, const char *p)
1906 char *q;
1908 q = buf;
1909 while (*p != '\0') {
1910 if (*p == ',') {
1911 if (*(p + 1) != ',')
1912 break;
1913 p++;
1915 if (q && (q - buf) < buf_size - 1)
1916 *q++ = *p;
1917 p++;
1919 if (q)
1920 *q = '\0';
1922 return p;
1925 int get_param_value(char *buf, int buf_size,
1926 const char *tag, const char *str)
1928 const char *p;
1929 char option[128];
1931 p = str;
1932 for(;;) {
1933 p = get_opt_name(option, sizeof(option), p);
1934 if (*p != '=')
1935 break;
1936 p++;
1937 if (!strcmp(tag, option)) {
1938 (void)get_opt_value(buf, buf_size, p);
1939 return strlen(buf);
1940 } else {
1941 p = get_opt_value(NULL, 0, p);
1943 if (*p != ',')
1944 break;
1945 p++;
1947 return 0;
1950 int check_params(char *buf, int buf_size,
1951 const char * const *params, const char *str)
1953 const char *p;
1954 int i;
1956 p = str;
1957 for(;;) {
1958 p = get_opt_name(buf, buf_size, p);
1959 if (*p != '=')
1960 return -1;
1961 p++;
1962 for(i = 0; params[i] != NULL; i++)
1963 if (!strcmp(params[i], buf))
1964 break;
1965 if (params[i] == NULL)
1966 return -1;
1967 p = get_opt_value(NULL, 0, p);
1968 if (*p != ',')
1969 break;
1970 p++;
1972 return 0;
1975 /***********************************************************/
1976 /* Bluetooth support */
1977 static int nb_hcis;
1978 static int cur_hci;
1979 static struct HCIInfo *hci_table[MAX_NICS];
1981 static struct bt_vlan_s {
1982 struct bt_scatternet_s net;
1983 int id;
1984 struct bt_vlan_s *next;
1985 } *first_bt_vlan;
1987 /* find or alloc a new bluetooth "VLAN" */
1988 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1990 struct bt_vlan_s **pvlan, *vlan;
1991 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1992 if (vlan->id == id)
1993 return &vlan->net;
1995 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1996 vlan->id = id;
1997 pvlan = &first_bt_vlan;
1998 while (*pvlan != NULL)
1999 pvlan = &(*pvlan)->next;
2000 *pvlan = vlan;
2001 return &vlan->net;
2004 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2008 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2010 return -ENOTSUP;
2013 static struct HCIInfo null_hci = {
2014 .cmd_send = null_hci_send,
2015 .sco_send = null_hci_send,
2016 .acl_send = null_hci_send,
2017 .bdaddr_set = null_hci_addr_set,
2020 struct HCIInfo *qemu_next_hci(void)
2022 if (cur_hci == nb_hcis)
2023 return &null_hci;
2025 return hci_table[cur_hci++];
2028 static struct HCIInfo *hci_init(const char *str)
2030 char *endp;
2031 struct bt_scatternet_s *vlan = 0;
2033 if (!strcmp(str, "null"))
2034 /* null */
2035 return &null_hci;
2036 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2037 /* host[:hciN] */
2038 return bt_host_hci(str[4] ? str + 5 : "hci0");
2039 else if (!strncmp(str, "hci", 3)) {
2040 /* hci[,vlan=n] */
2041 if (str[3]) {
2042 if (!strncmp(str + 3, ",vlan=", 6)) {
2043 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2044 if (*endp)
2045 vlan = 0;
2047 } else
2048 vlan = qemu_find_bt_vlan(0);
2049 if (vlan)
2050 return bt_new_hci(vlan);
2053 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2055 return 0;
2058 static int bt_hci_parse(const char *str)
2060 struct HCIInfo *hci;
2061 bdaddr_t bdaddr;
2063 if (nb_hcis >= MAX_NICS) {
2064 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2065 return -1;
2068 hci = hci_init(str);
2069 if (!hci)
2070 return -1;
2072 bdaddr.b[0] = 0x52;
2073 bdaddr.b[1] = 0x54;
2074 bdaddr.b[2] = 0x00;
2075 bdaddr.b[3] = 0x12;
2076 bdaddr.b[4] = 0x34;
2077 bdaddr.b[5] = 0x56 + nb_hcis;
2078 hci->bdaddr_set(hci, bdaddr.b);
2080 hci_table[nb_hcis++] = hci;
2082 return 0;
2085 static void bt_vhci_add(int vlan_id)
2087 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2089 if (!vlan->slave)
2090 fprintf(stderr, "qemu: warning: adding a VHCI to "
2091 "an empty scatternet %i\n", vlan_id);
2093 bt_vhci_init(bt_new_hci(vlan));
2096 static struct bt_device_s *bt_device_add(const char *opt)
2098 struct bt_scatternet_s *vlan;
2099 int vlan_id = 0;
2100 char *endp = strstr(opt, ",vlan=");
2101 int len = (endp ? endp - opt : strlen(opt)) + 1;
2102 char devname[10];
2104 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2106 if (endp) {
2107 vlan_id = strtol(endp + 6, &endp, 0);
2108 if (*endp) {
2109 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2110 return 0;
2114 vlan = qemu_find_bt_vlan(vlan_id);
2116 if (!vlan->slave)
2117 fprintf(stderr, "qemu: warning: adding a slave device to "
2118 "an empty scatternet %i\n", vlan_id);
2120 if (!strcmp(devname, "keyboard"))
2121 return bt_keyboard_init(vlan);
2123 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2124 return 0;
2127 static int bt_parse(const char *opt)
2129 const char *endp, *p;
2130 int vlan;
2132 if (strstart(opt, "hci", &endp)) {
2133 if (!*endp || *endp == ',') {
2134 if (*endp)
2135 if (!strstart(endp, ",vlan=", 0))
2136 opt = endp + 1;
2138 return bt_hci_parse(opt);
2140 } else if (strstart(opt, "vhci", &endp)) {
2141 if (!*endp || *endp == ',') {
2142 if (*endp) {
2143 if (strstart(endp, ",vlan=", &p)) {
2144 vlan = strtol(p, (char **) &endp, 0);
2145 if (*endp) {
2146 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2147 return 1;
2149 } else {
2150 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2151 return 1;
2153 } else
2154 vlan = 0;
2156 bt_vhci_add(vlan);
2157 return 0;
2159 } else if (strstart(opt, "device:", &endp))
2160 return !bt_device_add(endp);
2162 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2163 return 1;
2166 /***********************************************************/
2167 /* QEMU Block devices */
2169 #define HD_ALIAS "index=%d,media=disk"
2170 #ifdef TARGET_PPC
2171 #define CDROM_ALIAS "index=1,media=cdrom"
2172 #else
2173 #define CDROM_ALIAS "index=2,media=cdrom"
2174 #endif
2175 #define FD_ALIAS "index=%d,if=floppy"
2176 #define PFLASH_ALIAS "if=pflash"
2177 #define MTD_ALIAS "if=mtd"
2178 #define SD_ALIAS "index=0,if=sd"
2180 static int drive_opt_get_free_idx(void)
2182 int index;
2184 for (index = 0; index < MAX_DRIVES; index++)
2185 if (!drives_opt[index].used) {
2186 drives_opt[index].used = 1;
2187 return index;
2190 return -1;
2193 static int drive_get_free_idx(void)
2195 int index;
2197 for (index = 0; index < MAX_DRIVES; index++)
2198 if (!drives_table[index].used) {
2199 drives_table[index].used = 1;
2200 return index;
2203 return -1;
2206 int drive_add(const char *file, const char *fmt, ...)
2208 va_list ap;
2209 int index = drive_opt_get_free_idx();
2211 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2212 fprintf(stderr, "qemu: too many drives\n");
2213 return -1;
2216 drives_opt[index].file = file;
2217 va_start(ap, fmt);
2218 vsnprintf(drives_opt[index].opt,
2219 sizeof(drives_opt[0].opt), fmt, ap);
2220 va_end(ap);
2222 nb_drives_opt++;
2223 return index;
2226 void drive_remove(int index)
2228 drives_opt[index].used = 0;
2229 nb_drives_opt--;
2232 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2234 int index;
2236 /* seek interface, bus and unit */
2238 for (index = 0; index < MAX_DRIVES; index++)
2239 if (drives_table[index].type == type &&
2240 drives_table[index].bus == bus &&
2241 drives_table[index].unit == unit &&
2242 drives_table[index].used)
2243 return index;
2245 return -1;
2248 int drive_get_max_bus(BlockInterfaceType type)
2250 int max_bus;
2251 int index;
2253 max_bus = -1;
2254 for (index = 0; index < nb_drives; index++) {
2255 if(drives_table[index].type == type &&
2256 drives_table[index].bus > max_bus)
2257 max_bus = drives_table[index].bus;
2259 return max_bus;
2262 const char *drive_get_serial(BlockDriverState *bdrv)
2264 int index;
2266 for (index = 0; index < nb_drives; index++)
2267 if (drives_table[index].bdrv == bdrv)
2268 return drives_table[index].serial;
2270 return "\0";
2273 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2275 int index;
2277 for (index = 0; index < nb_drives; index++)
2278 if (drives_table[index].bdrv == bdrv)
2279 return drives_table[index].onerror;
2281 return BLOCK_ERR_STOP_ENOSPC;
2284 static void bdrv_format_print(void *opaque, const char *name)
2286 fprintf(stderr, " %s", name);
2289 void drive_uninit(BlockDriverState *bdrv)
2291 int i;
2293 for (i = 0; i < MAX_DRIVES; i++)
2294 if (drives_table[i].bdrv == bdrv) {
2295 drives_table[i].bdrv = NULL;
2296 drives_table[i].used = 0;
2297 drive_remove(drives_table[i].drive_opt_idx);
2298 nb_drives--;
2299 break;
2303 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2305 char buf[128];
2306 char file[1024];
2307 char devname[128];
2308 char serial[21];
2309 const char *mediastr = "";
2310 BlockInterfaceType type;
2311 enum { MEDIA_DISK, MEDIA_CDROM } media;
2312 int bus_id, unit_id;
2313 int cyls, heads, secs, translation;
2314 BlockDriverState *bdrv;
2315 BlockDriver *drv = NULL;
2316 QEMUMachine *machine = opaque;
2317 int max_devs;
2318 int index;
2319 int cache;
2320 int bdrv_flags, onerror;
2321 int drives_table_idx;
2322 char *str = arg->opt;
2323 static const char * const params[] = { "bus", "unit", "if", "index",
2324 "cyls", "heads", "secs", "trans",
2325 "media", "snapshot", "file",
2326 "cache", "format", "serial", "werror",
2327 "boot", NULL };
2329 if (check_params(buf, sizeof(buf), params, str) < 0) {
2330 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2331 buf, str);
2332 return -1;
2335 file[0] = 0;
2336 cyls = heads = secs = 0;
2337 bus_id = 0;
2338 unit_id = -1;
2339 translation = BIOS_ATA_TRANSLATION_AUTO;
2340 index = -1;
2341 cache = 3;
2343 if (machine->use_scsi) {
2344 type = IF_SCSI;
2345 max_devs = MAX_SCSI_DEVS;
2346 pstrcpy(devname, sizeof(devname), "scsi");
2347 } else {
2348 type = IF_IDE;
2349 max_devs = MAX_IDE_DEVS;
2350 pstrcpy(devname, sizeof(devname), "ide");
2352 media = MEDIA_DISK;
2354 /* extract parameters */
2356 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2357 bus_id = strtol(buf, NULL, 0);
2358 if (bus_id < 0) {
2359 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2360 return -1;
2364 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2365 unit_id = strtol(buf, NULL, 0);
2366 if (unit_id < 0) {
2367 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2368 return -1;
2372 if (get_param_value(buf, sizeof(buf), "if", str)) {
2373 pstrcpy(devname, sizeof(devname), buf);
2374 if (!strcmp(buf, "ide")) {
2375 type = IF_IDE;
2376 max_devs = MAX_IDE_DEVS;
2377 } else if (!strcmp(buf, "scsi")) {
2378 type = IF_SCSI;
2379 max_devs = MAX_SCSI_DEVS;
2380 } else if (!strcmp(buf, "floppy")) {
2381 type = IF_FLOPPY;
2382 max_devs = 0;
2383 } else if (!strcmp(buf, "pflash")) {
2384 type = IF_PFLASH;
2385 max_devs = 0;
2386 } else if (!strcmp(buf, "mtd")) {
2387 type = IF_MTD;
2388 max_devs = 0;
2389 } else if (!strcmp(buf, "sd")) {
2390 type = IF_SD;
2391 max_devs = 0;
2392 } else if (!strcmp(buf, "virtio")) {
2393 type = IF_VIRTIO;
2394 max_devs = 0;
2395 } else {
2396 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2397 return -1;
2401 if (get_param_value(buf, sizeof(buf), "index", str)) {
2402 index = strtol(buf, NULL, 0);
2403 if (index < 0) {
2404 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2405 return -1;
2409 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2410 cyls = strtol(buf, NULL, 0);
2413 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2414 heads = strtol(buf, NULL, 0);
2417 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2418 secs = strtol(buf, NULL, 0);
2421 if (cyls || heads || secs) {
2422 if (cyls < 1 || cyls > 16383) {
2423 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2424 return -1;
2426 if (heads < 1 || heads > 16) {
2427 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2428 return -1;
2430 if (secs < 1 || secs > 63) {
2431 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2432 return -1;
2436 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2437 if (!cyls) {
2438 fprintf(stderr,
2439 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2440 str);
2441 return -1;
2443 if (!strcmp(buf, "none"))
2444 translation = BIOS_ATA_TRANSLATION_NONE;
2445 else if (!strcmp(buf, "lba"))
2446 translation = BIOS_ATA_TRANSLATION_LBA;
2447 else if (!strcmp(buf, "auto"))
2448 translation = BIOS_ATA_TRANSLATION_AUTO;
2449 else {
2450 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2451 return -1;
2455 if (get_param_value(buf, sizeof(buf), "media", str)) {
2456 if (!strcmp(buf, "disk")) {
2457 media = MEDIA_DISK;
2458 } else if (!strcmp(buf, "cdrom")) {
2459 if (cyls || secs || heads) {
2460 fprintf(stderr,
2461 "qemu: '%s' invalid physical CHS format\n", str);
2462 return -1;
2464 media = MEDIA_CDROM;
2465 } else {
2466 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2467 return -1;
2471 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2472 if (!strcmp(buf, "on"))
2473 snapshot = 1;
2474 else if (!strcmp(buf, "off"))
2475 snapshot = 0;
2476 else {
2477 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2478 return -1;
2482 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2483 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2484 cache = 0;
2485 else if (!strcmp(buf, "writethrough"))
2486 cache = 1;
2487 else if (!strcmp(buf, "writeback"))
2488 cache = 2;
2489 else {
2490 fprintf(stderr, "qemu: invalid cache option\n");
2491 return -1;
2495 if (get_param_value(buf, sizeof(buf), "format", str)) {
2496 if (strcmp(buf, "?") == 0) {
2497 fprintf(stderr, "qemu: Supported formats:");
2498 bdrv_iterate_format(bdrv_format_print, NULL);
2499 fprintf(stderr, "\n");
2500 return -1;
2502 drv = bdrv_find_format(buf);
2503 if (!drv) {
2504 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2505 return -1;
2509 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2510 if (!strcmp(buf, "on")) {
2511 if (extboot_drive != -1) {
2512 fprintf(stderr, "qemu: two bootable drives specified\n");
2513 return -1;
2515 extboot_drive = nb_drives;
2516 } else if (strcmp(buf, "off")) {
2517 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2518 return -1;
2522 if (arg->file == NULL)
2523 get_param_value(file, sizeof(file), "file", str);
2524 else
2525 pstrcpy(file, sizeof(file), arg->file);
2527 if (!get_param_value(serial, sizeof(serial), "serial", str))
2528 memset(serial, 0, sizeof(serial));
2530 onerror = BLOCK_ERR_STOP_ENOSPC;
2531 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2532 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2533 fprintf(stderr, "werror is no supported by this format\n");
2534 return -1;
2536 if (!strcmp(buf, "ignore"))
2537 onerror = BLOCK_ERR_IGNORE;
2538 else if (!strcmp(buf, "enospc"))
2539 onerror = BLOCK_ERR_STOP_ENOSPC;
2540 else if (!strcmp(buf, "stop"))
2541 onerror = BLOCK_ERR_STOP_ANY;
2542 else if (!strcmp(buf, "report"))
2543 onerror = BLOCK_ERR_REPORT;
2544 else {
2545 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2546 return -1;
2550 /* compute bus and unit according index */
2552 if (index != -1) {
2553 if (bus_id != 0 || unit_id != -1) {
2554 fprintf(stderr,
2555 "qemu: '%s' index cannot be used with bus and unit\n", str);
2556 return -1;
2558 if (max_devs == 0)
2560 unit_id = index;
2561 bus_id = 0;
2562 } else {
2563 unit_id = index % max_devs;
2564 bus_id = index / max_devs;
2568 /* if user doesn't specify a unit_id,
2569 * try to find the first free
2572 if (unit_id == -1) {
2573 unit_id = 0;
2574 while (drive_get_index(type, bus_id, unit_id) != -1) {
2575 unit_id++;
2576 if (max_devs && unit_id >= max_devs) {
2577 unit_id -= max_devs;
2578 bus_id++;
2583 /* check unit id */
2585 if (max_devs && unit_id >= max_devs) {
2586 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2587 str, unit_id, max_devs - 1);
2588 return -1;
2592 * ignore multiple definitions
2595 if (drive_get_index(type, bus_id, unit_id) != -1)
2596 return -2;
2598 /* init */
2600 if (type == IF_IDE || type == IF_SCSI)
2601 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2602 if (max_devs)
2603 snprintf(buf, sizeof(buf), "%s%i%s%i",
2604 devname, bus_id, mediastr, unit_id);
2605 else
2606 snprintf(buf, sizeof(buf), "%s%s%i",
2607 devname, mediastr, unit_id);
2608 bdrv = bdrv_new(buf);
2609 drives_table_idx = drive_get_free_idx();
2610 drives_table[drives_table_idx].bdrv = bdrv;
2611 drives_table[drives_table_idx].type = type;
2612 drives_table[drives_table_idx].bus = bus_id;
2613 drives_table[drives_table_idx].unit = unit_id;
2614 drives_table[drives_table_idx].onerror = onerror;
2615 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2616 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2617 nb_drives++;
2619 switch(type) {
2620 case IF_IDE:
2621 case IF_SCSI:
2622 switch(media) {
2623 case MEDIA_DISK:
2624 if (cyls != 0) {
2625 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2626 bdrv_set_translation_hint(bdrv, translation);
2628 break;
2629 case MEDIA_CDROM:
2630 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2631 break;
2633 break;
2634 case IF_SD:
2635 /* FIXME: This isn't really a floppy, but it's a reasonable
2636 approximation. */
2637 case IF_FLOPPY:
2638 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2639 break;
2640 case IF_PFLASH:
2641 case IF_MTD:
2642 case IF_VIRTIO:
2643 break;
2645 if (!file[0])
2646 return -2;
2647 bdrv_flags = 0;
2648 if (snapshot) {
2649 bdrv_flags |= BDRV_O_SNAPSHOT;
2650 cache = 2; /* always use write-back with snapshot */
2652 if (cache == 0) /* no caching */
2653 bdrv_flags |= BDRV_O_NOCACHE;
2654 else if (cache == 2) /* write-back */
2655 bdrv_flags |= BDRV_O_CACHE_WB;
2656 else if (cache == 3) /* not specified */
2657 bdrv_flags |= BDRV_O_CACHE_DEF;
2658 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2659 fprintf(stderr, "qemu: could not open disk image %s\n",
2660 file);
2661 return -1;
2663 if (bdrv_key_required(bdrv))
2664 autostart = 0;
2665 return drives_table_idx;
2668 /***********************************************************/
2669 /* USB devices */
2671 static USBPort *used_usb_ports;
2672 static USBPort *free_usb_ports;
2674 /* ??? Maybe change this to register a hub to keep track of the topology. */
2675 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2676 usb_attachfn attach)
2678 port->opaque = opaque;
2679 port->index = index;
2680 port->attach = attach;
2681 port->next = free_usb_ports;
2682 free_usb_ports = port;
2685 int usb_device_add_dev(USBDevice *dev)
2687 USBPort *port;
2689 /* Find a USB port to add the device to. */
2690 port = free_usb_ports;
2691 if (!port->next) {
2692 USBDevice *hub;
2694 /* Create a new hub and chain it on. */
2695 free_usb_ports = NULL;
2696 port->next = used_usb_ports;
2697 used_usb_ports = port;
2699 hub = usb_hub_init(VM_USB_HUB_SIZE);
2700 usb_attach(port, hub);
2701 port = free_usb_ports;
2704 free_usb_ports = port->next;
2705 port->next = used_usb_ports;
2706 used_usb_ports = port;
2707 usb_attach(port, dev);
2708 return 0;
2711 static int usb_device_add(const char *devname, int is_hotplug)
2713 const char *p;
2714 USBDevice *dev;
2716 if (!free_usb_ports)
2717 return -1;
2719 if (strstart(devname, "host:", &p)) {
2720 dev = usb_host_device_open(p);
2721 } else if (!strcmp(devname, "mouse")) {
2722 dev = usb_mouse_init();
2723 } else if (!strcmp(devname, "tablet")) {
2724 dev = usb_tablet_init();
2725 } else if (!strcmp(devname, "keyboard")) {
2726 dev = usb_keyboard_init();
2727 } else if (strstart(devname, "disk:", &p)) {
2728 BlockDriverState *bs;
2730 dev = usb_msd_init(p, &bs);
2731 if (!dev)
2732 return -1;
2733 if (bdrv_key_required(bs)) {
2734 autostart = 0;
2735 if (is_hotplug && monitor_read_bdrv_key(bs) < 0) {
2736 dev->handle_destroy(dev);
2737 return -1;
2740 } else if (!strcmp(devname, "wacom-tablet")) {
2741 dev = usb_wacom_init();
2742 } else if (strstart(devname, "serial:", &p)) {
2743 dev = usb_serial_init(p);
2744 #ifdef CONFIG_BRLAPI
2745 } else if (!strcmp(devname, "braille")) {
2746 dev = usb_baum_init();
2747 #endif
2748 } else if (strstart(devname, "net:", &p)) {
2749 int nic = nb_nics;
2751 if (net_client_init("nic", p) < 0)
2752 return -1;
2753 nd_table[nic].model = "usb";
2754 dev = usb_net_init(&nd_table[nic]);
2755 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2756 dev = usb_bt_init(devname[2] ? hci_init(p) :
2757 bt_new_hci(qemu_find_bt_vlan(0)));
2758 } else {
2759 return -1;
2761 if (!dev)
2762 return -1;
2764 return usb_device_add_dev(dev);
2767 int usb_device_del_addr(int bus_num, int addr)
2769 USBPort *port;
2770 USBPort **lastp;
2771 USBDevice *dev;
2773 if (!used_usb_ports)
2774 return -1;
2776 if (bus_num != 0)
2777 return -1;
2779 lastp = &used_usb_ports;
2780 port = used_usb_ports;
2781 while (port && port->dev->addr != addr) {
2782 lastp = &port->next;
2783 port = port->next;
2786 if (!port)
2787 return -1;
2789 dev = port->dev;
2790 *lastp = port->next;
2791 usb_attach(port, NULL);
2792 dev->handle_destroy(dev);
2793 port->next = free_usb_ports;
2794 free_usb_ports = port;
2795 return 0;
2798 static int usb_device_del(const char *devname)
2800 int bus_num, addr;
2801 const char *p;
2803 if (strstart(devname, "host:", &p))
2804 return usb_host_device_close(p);
2806 if (!used_usb_ports)
2807 return -1;
2809 p = strchr(devname, '.');
2810 if (!p)
2811 return -1;
2812 bus_num = strtoul(devname, NULL, 0);
2813 addr = strtoul(p + 1, NULL, 0);
2815 return usb_device_del_addr(bus_num, addr);
2818 void do_usb_add(const char *devname)
2820 usb_device_add(devname, 1);
2823 void do_usb_del(const char *devname)
2825 usb_device_del(devname);
2828 void usb_info(void)
2830 USBDevice *dev;
2831 USBPort *port;
2832 const char *speed_str;
2834 if (!usb_enabled) {
2835 term_printf("USB support not enabled\n");
2836 return;
2839 for (port = used_usb_ports; port; port = port->next) {
2840 dev = port->dev;
2841 if (!dev)
2842 continue;
2843 switch(dev->speed) {
2844 case USB_SPEED_LOW:
2845 speed_str = "1.5";
2846 break;
2847 case USB_SPEED_FULL:
2848 speed_str = "12";
2849 break;
2850 case USB_SPEED_HIGH:
2851 speed_str = "480";
2852 break;
2853 default:
2854 speed_str = "?";
2855 break;
2857 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2858 0, dev->addr, speed_str, dev->devname);
2862 /***********************************************************/
2863 /* PCMCIA/Cardbus */
2865 static struct pcmcia_socket_entry_s {
2866 struct pcmcia_socket_s *socket;
2867 struct pcmcia_socket_entry_s *next;
2868 } *pcmcia_sockets = 0;
2870 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2872 struct pcmcia_socket_entry_s *entry;
2874 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2875 entry->socket = socket;
2876 entry->next = pcmcia_sockets;
2877 pcmcia_sockets = entry;
2880 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2882 struct pcmcia_socket_entry_s *entry, **ptr;
2884 ptr = &pcmcia_sockets;
2885 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2886 if (entry->socket == socket) {
2887 *ptr = entry->next;
2888 qemu_free(entry);
2892 void pcmcia_info(void)
2894 struct pcmcia_socket_entry_s *iter;
2895 if (!pcmcia_sockets)
2896 term_printf("No PCMCIA sockets\n");
2898 for (iter = pcmcia_sockets; iter; iter = iter->next)
2899 term_printf("%s: %s\n", iter->socket->slot_string,
2900 iter->socket->attached ? iter->socket->card_string :
2901 "Empty");
2904 /***********************************************************/
2905 /* register display */
2907 void register_displaystate(DisplayState *ds)
2909 DisplayState **s;
2910 s = &display_state;
2911 while (*s != NULL)
2912 s = &(*s)->next;
2913 ds->next = NULL;
2914 *s = ds;
2917 DisplayState *get_displaystate(void)
2919 return display_state;
2922 /* dumb display */
2924 static void dumb_display_init(void)
2926 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2927 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2928 register_displaystate(ds);
2931 /***********************************************************/
2932 /* I/O handling */
2934 #define MAX_IO_HANDLERS 64
2936 typedef struct IOHandlerRecord {
2937 int fd;
2938 IOCanRWHandler *fd_read_poll;
2939 IOHandler *fd_read;
2940 IOHandler *fd_write;
2941 int deleted;
2942 void *opaque;
2943 /* temporary data */
2944 struct pollfd *ufd;
2945 struct IOHandlerRecord *next;
2946 } IOHandlerRecord;
2948 static IOHandlerRecord *first_io_handler;
2950 /* XXX: fd_read_poll should be suppressed, but an API change is
2951 necessary in the character devices to suppress fd_can_read(). */
2952 int qemu_set_fd_handler2(int fd,
2953 IOCanRWHandler *fd_read_poll,
2954 IOHandler *fd_read,
2955 IOHandler *fd_write,
2956 void *opaque)
2958 IOHandlerRecord **pioh, *ioh;
2960 if (!fd_read && !fd_write) {
2961 pioh = &first_io_handler;
2962 for(;;) {
2963 ioh = *pioh;
2964 if (ioh == NULL)
2965 break;
2966 if (ioh->fd == fd) {
2967 ioh->deleted = 1;
2968 break;
2970 pioh = &ioh->next;
2972 } else {
2973 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2974 if (ioh->fd == fd)
2975 goto found;
2977 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2978 ioh->next = first_io_handler;
2979 first_io_handler = ioh;
2980 found:
2981 ioh->fd = fd;
2982 ioh->fd_read_poll = fd_read_poll;
2983 ioh->fd_read = fd_read;
2984 ioh->fd_write = fd_write;
2985 ioh->opaque = opaque;
2986 ioh->deleted = 0;
2988 main_loop_break();
2989 return 0;
2992 int qemu_set_fd_handler(int fd,
2993 IOHandler *fd_read,
2994 IOHandler *fd_write,
2995 void *opaque)
2997 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3000 #ifdef _WIN32
3001 /***********************************************************/
3002 /* Polling handling */
3004 typedef struct PollingEntry {
3005 PollingFunc *func;
3006 void *opaque;
3007 struct PollingEntry *next;
3008 } PollingEntry;
3010 static PollingEntry *first_polling_entry;
3012 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3014 PollingEntry **ppe, *pe;
3015 pe = qemu_mallocz(sizeof(PollingEntry));
3016 pe->func = func;
3017 pe->opaque = opaque;
3018 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3019 *ppe = pe;
3020 return 0;
3023 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3025 PollingEntry **ppe, *pe;
3026 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3027 pe = *ppe;
3028 if (pe->func == func && pe->opaque == opaque) {
3029 *ppe = pe->next;
3030 qemu_free(pe);
3031 break;
3036 /***********************************************************/
3037 /* Wait objects support */
3038 typedef struct WaitObjects {
3039 int num;
3040 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3041 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3042 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3043 } WaitObjects;
3045 static WaitObjects wait_objects = {0};
3047 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3049 WaitObjects *w = &wait_objects;
3051 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3052 return -1;
3053 w->events[w->num] = handle;
3054 w->func[w->num] = func;
3055 w->opaque[w->num] = opaque;
3056 w->num++;
3057 return 0;
3060 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3062 int i, found;
3063 WaitObjects *w = &wait_objects;
3065 found = 0;
3066 for (i = 0; i < w->num; i++) {
3067 if (w->events[i] == handle)
3068 found = 1;
3069 if (found) {
3070 w->events[i] = w->events[i + 1];
3071 w->func[i] = w->func[i + 1];
3072 w->opaque[i] = w->opaque[i + 1];
3075 if (found)
3076 w->num--;
3078 #endif
3080 /***********************************************************/
3081 /* ram save/restore */
3083 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3085 int v;
3087 v = qemu_get_byte(f);
3088 switch(v) {
3089 case 0:
3090 if (qemu_get_buffer(f, buf, len) != len)
3091 return -EIO;
3092 break;
3093 case 1:
3094 v = qemu_get_byte(f);
3095 memset(buf, v, len);
3096 break;
3097 default:
3098 return -EINVAL;
3101 if (qemu_file_has_error(f))
3102 return -EIO;
3104 return 0;
3107 static int ram_load_v1(QEMUFile *f, void *opaque)
3109 int ret;
3110 ram_addr_t i;
3112 if (qemu_get_be32(f) != phys_ram_size)
3113 return -EINVAL;
3114 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3115 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3116 continue;
3117 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3118 if (ret)
3119 return ret;
3121 return 0;
3124 #define BDRV_HASH_BLOCK_SIZE 1024
3125 #define IOBUF_SIZE 4096
3126 #define RAM_CBLOCK_MAGIC 0xfabe
3128 typedef struct RamDecompressState {
3129 z_stream zstream;
3130 QEMUFile *f;
3131 uint8_t buf[IOBUF_SIZE];
3132 } RamDecompressState;
3134 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3136 int ret;
3137 memset(s, 0, sizeof(*s));
3138 s->f = f;
3139 ret = inflateInit(&s->zstream);
3140 if (ret != Z_OK)
3141 return -1;
3142 return 0;
3145 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3147 int ret, clen;
3149 s->zstream.avail_out = len;
3150 s->zstream.next_out = buf;
3151 while (s->zstream.avail_out > 0) {
3152 if (s->zstream.avail_in == 0) {
3153 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3154 return -1;
3155 clen = qemu_get_be16(s->f);
3156 if (clen > IOBUF_SIZE)
3157 return -1;
3158 qemu_get_buffer(s->f, s->buf, clen);
3159 s->zstream.avail_in = clen;
3160 s->zstream.next_in = s->buf;
3162 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3163 if (ret != Z_OK && ret != Z_STREAM_END) {
3164 return -1;
3167 return 0;
3170 static void ram_decompress_close(RamDecompressState *s)
3172 inflateEnd(&s->zstream);
3175 #define RAM_SAVE_FLAG_FULL 0x01
3176 #define RAM_SAVE_FLAG_COMPRESS 0x02
3177 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3178 #define RAM_SAVE_FLAG_PAGE 0x08
3179 #define RAM_SAVE_FLAG_EOS 0x10
3181 static int is_dup_page(uint8_t *page, uint8_t ch)
3183 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3184 uint32_t *array = (uint32_t *)page;
3185 int i;
3187 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3188 if (array[i] != val)
3189 return 0;
3192 return 1;
3195 static int ram_save_block(QEMUFile *f)
3197 static ram_addr_t current_addr = 0;
3198 ram_addr_t saved_addr = current_addr;
3199 ram_addr_t addr = 0;
3200 int found = 0;
3202 while (addr < phys_ram_size) {
3203 if (kvm_enabled() && current_addr == 0) {
3204 int r;
3205 r = kvm_update_dirty_pages_log();
3206 if (r) {
3207 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3208 qemu_file_set_error(f);
3209 return 0;
3212 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3213 uint8_t ch;
3215 cpu_physical_memory_reset_dirty(current_addr,
3216 current_addr + TARGET_PAGE_SIZE,
3217 MIGRATION_DIRTY_FLAG);
3219 ch = *(phys_ram_base + current_addr);
3221 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3222 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3223 qemu_put_byte(f, ch);
3224 } else {
3225 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3226 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3229 found = 1;
3230 break;
3232 addr += TARGET_PAGE_SIZE;
3233 current_addr = (saved_addr + addr) % phys_ram_size;
3236 return found;
3239 static ram_addr_t ram_save_threshold = 10;
3241 static ram_addr_t ram_save_remaining(void)
3243 ram_addr_t addr;
3244 ram_addr_t count = 0;
3246 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3247 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3248 count++;
3251 return count;
3254 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3256 ram_addr_t addr;
3258 if (stage == 1) {
3259 /* Make sure all dirty bits are set */
3260 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3261 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3262 cpu_physical_memory_set_dirty(addr);
3265 /* Enable dirty memory tracking */
3266 cpu_physical_memory_set_dirty_tracking(1);
3268 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3271 while (!qemu_file_rate_limit(f)) {
3272 int ret;
3274 ret = ram_save_block(f);
3275 if (ret == 0) /* no more blocks */
3276 break;
3279 /* try transferring iterative blocks of memory */
3281 if (stage == 3) {
3283 /* flush all remaining blocks regardless of rate limiting */
3284 while (ram_save_block(f) != 0);
3285 cpu_physical_memory_set_dirty_tracking(0);
3288 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3290 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3293 static int ram_load_dead(QEMUFile *f, void *opaque)
3295 RamDecompressState s1, *s = &s1;
3296 uint8_t buf[10];
3297 ram_addr_t i;
3299 if (ram_decompress_open(s, f) < 0)
3300 return -EINVAL;
3301 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3302 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3303 continue;
3304 if (ram_decompress_buf(s, buf, 1) < 0) {
3305 fprintf(stderr, "Error while reading ram block header\n");
3306 goto error;
3308 if (buf[0] == 0) {
3309 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3310 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3311 goto error;
3313 } else {
3314 error:
3315 printf("Error block header\n");
3316 return -EINVAL;
3319 ram_decompress_close(s);
3321 return 0;
3324 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3326 ram_addr_t addr;
3327 int flags;
3329 if (version_id == 1)
3330 return ram_load_v1(f, opaque);
3332 if (version_id == 2) {
3333 if (qemu_get_be32(f) != phys_ram_size)
3334 return -EINVAL;
3335 return ram_load_dead(f, opaque);
3338 if (version_id != 3)
3339 return -EINVAL;
3341 do {
3342 addr = qemu_get_be64(f);
3344 flags = addr & ~TARGET_PAGE_MASK;
3345 addr &= TARGET_PAGE_MASK;
3347 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3348 if (addr != phys_ram_size)
3349 return -EINVAL;
3352 if (flags & RAM_SAVE_FLAG_FULL) {
3353 if (ram_load_dead(f, opaque) < 0)
3354 return -EINVAL;
3357 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3358 uint8_t ch = qemu_get_byte(f);
3359 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3360 } else if (flags & RAM_SAVE_FLAG_PAGE)
3361 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3362 } while (!(flags & RAM_SAVE_FLAG_EOS));
3364 return 0;
3367 /***********************************************************/
3368 /* bottom halves (can be seen as timers which expire ASAP) */
3370 struct QEMUBH {
3371 QEMUBHFunc *cb;
3372 void *opaque;
3373 int scheduled;
3374 int idle;
3375 int deleted;
3376 QEMUBH *next;
3379 static QEMUBH *first_bh = NULL;
3381 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3383 QEMUBH *bh;
3384 bh = qemu_mallocz(sizeof(QEMUBH));
3385 bh->cb = cb;
3386 bh->opaque = opaque;
3387 bh->next = first_bh;
3388 first_bh = bh;
3389 return bh;
3392 int qemu_bh_poll(void)
3394 QEMUBH *bh, **bhp;
3395 int ret;
3397 ret = 0;
3398 for (bh = first_bh; bh; bh = bh->next) {
3399 if (!bh->deleted && bh->scheduled) {
3400 bh->scheduled = 0;
3401 if (!bh->idle)
3402 ret = 1;
3403 bh->idle = 0;
3404 bh->cb(bh->opaque);
3408 /* remove deleted bhs */
3409 bhp = &first_bh;
3410 while (*bhp) {
3411 bh = *bhp;
3412 if (bh->deleted) {
3413 *bhp = bh->next;
3414 qemu_free(bh);
3415 } else
3416 bhp = &bh->next;
3419 return ret;
3422 void qemu_bh_schedule_idle(QEMUBH *bh)
3424 if (bh->scheduled)
3425 return;
3426 bh->scheduled = 1;
3427 bh->idle = 1;
3430 void qemu_bh_schedule(QEMUBH *bh)
3432 CPUState *env = cpu_single_env;
3433 if (bh->scheduled)
3434 return;
3435 bh->scheduled = 1;
3436 bh->idle = 0;
3437 /* stop the currently executing CPU to execute the BH ASAP */
3438 if (env) {
3439 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3441 main_loop_break();
3444 void qemu_bh_cancel(QEMUBH *bh)
3446 bh->scheduled = 0;
3449 void qemu_bh_delete(QEMUBH *bh)
3451 bh->scheduled = 0;
3452 bh->deleted = 1;
3455 static void qemu_bh_update_timeout(int *timeout)
3457 QEMUBH *bh;
3459 for (bh = first_bh; bh; bh = bh->next) {
3460 if (!bh->deleted && bh->scheduled) {
3461 if (bh->idle) {
3462 /* idle bottom halves will be polled at least
3463 * every 10ms */
3464 *timeout = MIN(10, *timeout);
3465 } else {
3466 /* non-idle bottom halves will be executed
3467 * immediately */
3468 *timeout = 0;
3469 break;
3475 /***********************************************************/
3476 /* machine registration */
3478 static QEMUMachine *first_machine = NULL;
3479 QEMUMachine *current_machine = NULL;
3481 int qemu_register_machine(QEMUMachine *m)
3483 QEMUMachine **pm;
3484 pm = &first_machine;
3485 while (*pm != NULL)
3486 pm = &(*pm)->next;
3487 m->next = NULL;
3488 *pm = m;
3489 return 0;
3492 static QEMUMachine *find_machine(const char *name)
3494 QEMUMachine *m;
3496 for(m = first_machine; m != NULL; m = m->next) {
3497 if (!strcmp(m->name, name))
3498 return m;
3500 return NULL;
3503 /***********************************************************/
3504 /* main execution loop */
3506 static void gui_update(void *opaque)
3508 uint64_t interval = GUI_REFRESH_INTERVAL;
3509 DisplayState *ds = opaque;
3510 DisplayChangeListener *dcl = ds->listeners;
3512 dpy_refresh(ds);
3514 while (dcl != NULL) {
3515 if (dcl->gui_timer_interval &&
3516 dcl->gui_timer_interval < interval)
3517 interval = dcl->gui_timer_interval;
3518 dcl = dcl->next;
3520 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3523 static void nographic_update(void *opaque)
3525 uint64_t interval = GUI_REFRESH_INTERVAL;
3527 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3530 struct vm_change_state_entry {
3531 VMChangeStateHandler *cb;
3532 void *opaque;
3533 LIST_ENTRY (vm_change_state_entry) entries;
3536 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3538 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3539 void *opaque)
3541 VMChangeStateEntry *e;
3543 e = qemu_mallocz(sizeof (*e));
3545 e->cb = cb;
3546 e->opaque = opaque;
3547 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3548 return e;
3551 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3553 LIST_REMOVE (e, entries);
3554 qemu_free (e);
3557 static void vm_state_notify(int running, int reason)
3559 VMChangeStateEntry *e;
3561 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3562 e->cb(e->opaque, running, reason);
3566 void vm_start(void)
3568 if (!vm_running) {
3569 cpu_enable_ticks();
3570 vm_running = 1;
3571 vm_state_notify(1, 0);
3572 qemu_rearm_alarm_timer(alarm_timer);
3576 void vm_stop(int reason)
3578 if (vm_running) {
3579 cpu_disable_ticks();
3580 vm_running = 0;
3581 vm_state_notify(0, reason);
3585 /* reset/shutdown handler */
3587 typedef struct QEMUResetEntry {
3588 QEMUResetHandler *func;
3589 void *opaque;
3590 struct QEMUResetEntry *next;
3591 } QEMUResetEntry;
3593 static QEMUResetEntry *first_reset_entry;
3594 static int reset_requested;
3595 static int shutdown_requested;
3596 static int powerdown_requested;
3598 int qemu_no_shutdown(void)
3600 int r = no_shutdown;
3601 no_shutdown = 0;
3602 return r;
3605 int qemu_shutdown_requested(void)
3607 int r = shutdown_requested;
3608 shutdown_requested = 0;
3609 return r;
3612 int qemu_reset_requested(void)
3614 int r = reset_requested;
3615 reset_requested = 0;
3616 return r;
3619 int qemu_powerdown_requested(void)
3621 int r = powerdown_requested;
3622 powerdown_requested = 0;
3623 return r;
3626 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3628 QEMUResetEntry **pre, *re;
3630 pre = &first_reset_entry;
3631 while (*pre != NULL)
3632 pre = &(*pre)->next;
3633 re = qemu_mallocz(sizeof(QEMUResetEntry));
3634 re->func = func;
3635 re->opaque = opaque;
3636 re->next = NULL;
3637 *pre = re;
3640 void qemu_system_reset(void)
3642 QEMUResetEntry *re;
3644 /* reset all devices */
3645 for(re = first_reset_entry; re != NULL; re = re->next) {
3646 re->func(re->opaque);
3650 void qemu_system_reset_request(void)
3652 if (no_reboot) {
3653 shutdown_requested = 1;
3654 } else {
3655 reset_requested = 1;
3658 if (cpu_single_env) {
3659 qemu_kvm_cpu_stop(cpu_single_env);
3660 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3662 main_loop_break();
3665 void qemu_system_shutdown_request(void)
3667 shutdown_requested = 1;
3668 if (cpu_single_env)
3669 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3672 void qemu_system_powerdown_request(void)
3674 powerdown_requested = 1;
3675 if (cpu_single_env)
3676 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3679 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3680 struct timeval *tv)
3682 int ret;
3684 /* KVM holds a mutex while QEMU code is running, we need hooks to
3685 release the mutex whenever QEMU code sleeps. */
3687 kvm_sleep_begin();
3689 ret = select(max_fd, rfds, wfds, xfds, tv);
3691 kvm_sleep_end();
3693 return ret;
3696 #ifdef _WIN32
3697 static void host_main_loop_wait(int *timeout)
3699 int ret, ret2, i;
3700 PollingEntry *pe;
3703 /* XXX: need to suppress polling by better using win32 events */
3704 ret = 0;
3705 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3706 ret |= pe->func(pe->opaque);
3708 if (ret == 0) {
3709 int err;
3710 WaitObjects *w = &wait_objects;
3712 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3713 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3714 if (w->func[ret - WAIT_OBJECT_0])
3715 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3717 /* Check for additional signaled events */
3718 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3720 /* Check if event is signaled */
3721 ret2 = WaitForSingleObject(w->events[i], 0);
3722 if(ret2 == WAIT_OBJECT_0) {
3723 if (w->func[i])
3724 w->func[i](w->opaque[i]);
3725 } else if (ret2 == WAIT_TIMEOUT) {
3726 } else {
3727 err = GetLastError();
3728 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3731 } else if (ret == WAIT_TIMEOUT) {
3732 } else {
3733 err = GetLastError();
3734 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3738 *timeout = 0;
3740 #else
3741 static void host_main_loop_wait(int *timeout)
3744 #endif
3746 void main_loop_wait(int timeout)
3748 IOHandlerRecord *ioh;
3749 fd_set rfds, wfds, xfds;
3750 int ret, nfds;
3751 struct timeval tv;
3753 qemu_bh_update_timeout(&timeout);
3755 host_main_loop_wait(&timeout);
3757 /* poll any events */
3758 /* XXX: separate device handlers from system ones */
3759 nfds = -1;
3760 FD_ZERO(&rfds);
3761 FD_ZERO(&wfds);
3762 FD_ZERO(&xfds);
3763 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3764 if (ioh->deleted)
3765 continue;
3766 if (ioh->fd_read &&
3767 (!ioh->fd_read_poll ||
3768 ioh->fd_read_poll(ioh->opaque) != 0)) {
3769 FD_SET(ioh->fd, &rfds);
3770 if (ioh->fd > nfds)
3771 nfds = ioh->fd;
3773 if (ioh->fd_write) {
3774 FD_SET(ioh->fd, &wfds);
3775 if (ioh->fd > nfds)
3776 nfds = ioh->fd;
3780 tv.tv_sec = timeout / 1000;
3781 tv.tv_usec = (timeout % 1000) * 1000;
3783 #if defined(CONFIG_SLIRP)
3784 if (slirp_is_inited()) {
3785 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3787 #endif
3788 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3789 if (ret > 0) {
3790 IOHandlerRecord **pioh;
3792 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3793 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3794 ioh->fd_read(ioh->opaque);
3795 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3796 FD_CLR(ioh->fd, &rfds);
3798 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3799 ioh->fd_write(ioh->opaque);
3803 /* remove deleted IO handlers */
3804 pioh = &first_io_handler;
3805 while (*pioh) {
3806 ioh = *pioh;
3807 if (ioh->deleted) {
3808 *pioh = ioh->next;
3809 qemu_free(ioh);
3810 } else
3811 pioh = &ioh->next;
3814 #if defined(CONFIG_SLIRP)
3815 if (slirp_is_inited()) {
3816 if (ret < 0) {
3817 FD_ZERO(&rfds);
3818 FD_ZERO(&wfds);
3819 FD_ZERO(&xfds);
3821 slirp_select_poll(&rfds, &wfds, &xfds);
3823 #endif
3825 /* vm time timers */
3826 if (vm_running && (!cur_cpu
3827 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3828 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3829 qemu_get_clock(vm_clock));
3831 /* real time timers */
3832 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3833 qemu_get_clock(rt_clock));
3835 /* Check bottom-halves last in case any of the earlier events triggered
3836 them. */
3837 qemu_bh_poll();
3841 static int main_loop(void)
3843 int ret, timeout;
3844 #ifdef CONFIG_PROFILER
3845 int64_t ti;
3846 #endif
3847 CPUState *env;
3850 if (kvm_enabled()) {
3851 kvm_main_loop();
3852 cpu_disable_ticks();
3853 return 0;
3856 cur_cpu = first_cpu;
3857 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3858 for(;;) {
3859 if (vm_running) {
3861 for(;;) {
3862 /* get next cpu */
3863 env = next_cpu;
3864 #ifdef CONFIG_PROFILER
3865 ti = profile_getclock();
3866 #endif
3867 if (use_icount) {
3868 int64_t count;
3869 int decr;
3870 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3871 env->icount_decr.u16.low = 0;
3872 env->icount_extra = 0;
3873 count = qemu_next_deadline();
3874 count = (count + (1 << icount_time_shift) - 1)
3875 >> icount_time_shift;
3876 qemu_icount += count;
3877 decr = (count > 0xffff) ? 0xffff : count;
3878 count -= decr;
3879 env->icount_decr.u16.low = decr;
3880 env->icount_extra = count;
3882 ret = cpu_exec(env);
3883 #ifdef CONFIG_PROFILER
3884 qemu_time += profile_getclock() - ti;
3885 #endif
3886 if (use_icount) {
3887 /* Fold pending instructions back into the
3888 instruction counter, and clear the interrupt flag. */
3889 qemu_icount -= (env->icount_decr.u16.low
3890 + env->icount_extra);
3891 env->icount_decr.u32 = 0;
3892 env->icount_extra = 0;
3894 next_cpu = env->next_cpu ?: first_cpu;
3895 if (event_pending && likely(ret != EXCP_DEBUG)) {
3896 ret = EXCP_INTERRUPT;
3897 event_pending = 0;
3898 break;
3900 if (ret == EXCP_HLT) {
3901 /* Give the next CPU a chance to run. */
3902 cur_cpu = env;
3903 continue;
3905 if (ret != EXCP_HALTED)
3906 break;
3907 /* all CPUs are halted ? */
3908 if (env == cur_cpu)
3909 break;
3911 cur_cpu = env;
3913 if (shutdown_requested) {
3914 ret = EXCP_INTERRUPT;
3915 if (no_shutdown) {
3916 vm_stop(0);
3917 no_shutdown = 0;
3919 else
3920 break;
3922 if (reset_requested) {
3923 reset_requested = 0;
3924 qemu_system_reset();
3925 if (kvm_enabled())
3926 kvm_load_registers(env);
3927 ret = EXCP_INTERRUPT;
3929 if (powerdown_requested) {
3930 powerdown_requested = 0;
3931 qemu_system_powerdown();
3932 ret = EXCP_INTERRUPT;
3934 #ifdef CONFIG_GDBSTUB
3935 if (unlikely(ret == EXCP_DEBUG)) {
3936 gdb_set_stop_cpu(cur_cpu);
3937 vm_stop(EXCP_DEBUG);
3939 #endif
3940 /* If all cpus are halted then wait until the next IRQ */
3941 /* XXX: use timeout computed from timers */
3942 if (ret == EXCP_HALTED) {
3943 if (use_icount) {
3944 int64_t add;
3945 int64_t delta;
3946 /* Advance virtual time to the next event. */
3947 if (use_icount == 1) {
3948 /* When not using an adaptive execution frequency
3949 we tend to get badly out of sync with real time,
3950 so just delay for a reasonable amount of time. */
3951 delta = 0;
3952 } else {
3953 delta = cpu_get_icount() - cpu_get_clock();
3955 if (delta > 0) {
3956 /* If virtual time is ahead of real time then just
3957 wait for IO. */
3958 timeout = (delta / 1000000) + 1;
3959 } else {
3960 /* Wait for either IO to occur or the next
3961 timer event. */
3962 add = qemu_next_deadline();
3963 /* We advance the timer before checking for IO.
3964 Limit the amount we advance so that early IO
3965 activity won't get the guest too far ahead. */
3966 if (add > 10000000)
3967 add = 10000000;
3968 delta += add;
3969 add = (add + (1 << icount_time_shift) - 1)
3970 >> icount_time_shift;
3971 qemu_icount += add;
3972 timeout = delta / 1000000;
3973 if (timeout < 0)
3974 timeout = 0;
3976 } else {
3977 timeout = 5000;
3979 } else {
3980 timeout = 0;
3982 } else {
3983 if (shutdown_requested) {
3984 ret = EXCP_INTERRUPT;
3985 break;
3987 timeout = 5000;
3989 #ifdef CONFIG_PROFILER
3990 ti = profile_getclock();
3991 #endif
3992 main_loop_wait(timeout);
3993 #ifdef CONFIG_PROFILER
3994 dev_time += profile_getclock() - ti;
3995 #endif
3997 cpu_disable_ticks();
3998 return ret;
4001 static void help(int exitcode)
4003 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
4004 and qemu-doc.texi */
4005 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
4006 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4007 "usage: %s [options] [disk_image]\n"
4008 "\n"
4009 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4010 "\n"
4011 "Standard options:\n"
4012 "-h or -help display this help and exit\n"
4013 "-M machine select emulated machine (-M ? for list)\n"
4014 "-cpu cpu select CPU (-cpu ? for list)\n"
4015 "-smp n set the number of CPUs to 'n' [default=1]\n"
4016 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4017 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4018 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4019 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4020 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
4021 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
4022 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
4023 " [,boot=on|off]\n"
4024 " use 'file' as a drive image\n"
4025 "-mtdblock file use 'file' as on-board Flash memory image\n"
4026 "-sd file use 'file' as SecureDigital card image\n"
4027 "-pflash file use 'file' as a parallel flash image\n"
4028 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4029 "-snapshot write to temporary files instead of disk image files\n"
4030 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4031 #ifndef _WIN32
4032 "-k language use keyboard layout (for example \"fr\" for French)\n"
4033 #endif
4034 #ifdef HAS_AUDIO
4035 "-audio-help print list of audio drivers and their options\n"
4036 "-soundhw c1,... enable audio support\n"
4037 " and only specified sound cards (comma separated list)\n"
4038 " use -soundhw ? to get the list of supported cards\n"
4039 " use -soundhw all to enable all of them\n"
4040 #endif
4041 "-usb enable the USB driver (will be the default soon)\n"
4042 "-usbdevice name add the host or guest USB device 'name'\n"
4043 "-name string set the name of the guest\n"
4044 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
4045 " specify machine UUID\n"
4046 "\n"
4047 "Display options:\n"
4048 "-nographic disable graphical output and redirect serial I/Os to console\n"
4049 #ifdef CONFIG_CURSES
4050 "-curses use a curses/ncurses interface instead of SDL\n"
4051 #endif
4052 #ifdef CONFIG_SDL
4053 "-no-frame open SDL window without a frame and window decorations\n"
4054 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4055 "-no-quit disable SDL window close capability\n"
4056 "-sdl enable SDL\n"
4057 #endif
4058 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4059 "-vga [std|cirrus|vmware|none]\n"
4060 " select video card type\n"
4061 "-full-screen start in full screen\n"
4062 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4063 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4064 #endif
4065 "-vnc display start a VNC server on display\n"
4066 #ifdef TARGET_IA64
4067 "-nvram file use 'file' to save or load nvram image\n"
4068 #endif
4069 "-name string set the name of the guest\n"
4070 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4071 "\n"
4072 "Network options:\n"
4073 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
4074 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4075 #ifdef CONFIG_SLIRP
4076 "-net user[,vlan=n][,name=str][,hostname=host]\n"
4077 " connect the user mode network stack to VLAN 'n' and send\n"
4078 " hostname 'host' to DHCP clients\n"
4079 #endif
4080 #ifdef _WIN32
4081 "-net tap[,vlan=n][,name=str],ifname=name\n"
4082 " connect the host TAP network interface to VLAN 'n'\n"
4083 #else
4084 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4085 " connect the host TAP network interface to VLAN 'n' and use the\n"
4086 " network scripts 'file' (default=%s)\n"
4087 " and 'dfile' (default=%s);\n"
4088 " use '[down]script=no' to disable script execution;\n"
4089 " use 'fd=h' to connect to an already opened TAP interface\n"
4090 #endif
4091 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4092 " connect the vlan 'n' to another VLAN using a socket connection\n"
4093 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4094 " connect the vlan 'n' to multicast maddr and port\n"
4095 #ifdef CONFIG_VDE
4096 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4097 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4098 " on host and listening for incoming connections on 'socketpath'.\n"
4099 " Use group 'groupname' and mode 'octalmode' to change default\n"
4100 " ownership and permissions for communication port.\n"
4101 #endif
4102 "-net none use it alone to have zero network devices; if no -net option\n"
4103 " is provided, the default is '-net nic -net user'\n"
4104 #ifdef CONFIG_SLIRP
4105 "-tftp dir allow tftp access to files in dir [-net user]\n"
4106 "-bootp file advertise file in BOOTP replies\n"
4107 #ifndef _WIN32
4108 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4109 #endif
4110 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4111 " redirect TCP or UDP connections from host to guest [-net user]\n"
4112 #endif
4113 "\n"
4114 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4115 "-bt hci,host[:id]\n"
4116 " use host's HCI with the given name\n"
4117 "-bt hci[,vlan=n]\n"
4118 " emulate a standard HCI in virtual scatternet 'n'\n"
4119 "-bt vhci[,vlan=n]\n"
4120 " add host computer to virtual scatternet 'n' using VHCI\n"
4121 "-bt device:dev[,vlan=n]\n"
4122 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4123 "\n"
4124 #ifdef TARGET_I386
4125 "\n"
4126 "i386 target only:\n"
4127 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4128 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4129 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4130 "-no-acpi disable ACPI\n"
4131 "-no-hpet disable HPET\n"
4132 "-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"
4133 " ACPI table description\n"
4134 #endif
4135 "Linux boot specific:\n"
4136 "-kernel bzImage use 'bzImage' as kernel image\n"
4137 "-append cmdline use 'cmdline' as kernel command line\n"
4138 "-initrd file use 'file' as initial ram disk\n"
4139 "\n"
4140 "Debug/Expert options:\n"
4141 "-serial dev redirect the serial port to char device 'dev'\n"
4142 "-parallel dev redirect the parallel port to char device 'dev'\n"
4143 "-monitor dev redirect the monitor to char device 'dev'\n"
4144 "-pidfile file write PID to 'file'\n"
4145 "-S freeze CPU at startup (use 'c' to start execution)\n"
4146 "-s wait gdb connection to port\n"
4147 "-p port set gdb connection port [default=%s]\n"
4148 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4149 "-hdachs c,h,s[,t]\n"
4150 " force hard disk 0 physical geometry and the optional BIOS\n"
4151 " translation (t=none or lba) (usually qemu can guess them)\n"
4152 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4153 "-bios file set the filename for the BIOS\n"
4154 #ifdef USE_KQEMU
4155 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4156 "-no-kqemu disable KQEMU kernel module usage\n"
4157 #endif
4158 #ifdef CONFIG_KVM
4159 "-enable-kvm enable KVM full virtualization support\n"
4160 #endif
4161 #ifdef USE_KVM
4162 #ifndef NO_CPU_EMULATION
4163 "-no-kvm disable KVM hardware virtualization\n"
4164 #endif
4165 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4166 "-no-kvm-pit disable KVM kernel mode PIT\n"
4167 "-no-kvm-pit-reinjection disable KVM kernel mode PIT interrupt reinjection\n"
4168 "-enable-nesting enable support for running a VM inside the VM (AMD only)\n"
4169 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4170 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4171 " expose a PCI device to the guest OS.\n"
4172 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4173 " 'string' is used in log output.\n"
4174 #endif
4175 #endif
4176 "-no-reboot exit instead of rebooting\n"
4177 "-no-shutdown stop before shutdown\n"
4178 "-loadvm [tag|id]\n"
4179 " start right away with a saved state (loadvm in monitor)\n"
4180 #ifndef _WIN32
4181 "-daemonize daemonize QEMU after initializing\n"
4182 #endif
4183 "-tdf inject timer interrupts that got lost\n"
4184 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4185 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also\n"
4186 " enables allocation of guest memory with huge pages\n"
4187 #ifdef MAP_POPULATE
4188 "-mem-prealloc toggles preallocation of -mem-path backed physical memory\n"
4189 " at startup. Default is enabled.\n"
4190 #endif
4191 "-option-rom rom load a file, rom, into the option ROM space\n"
4192 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4193 "-prom-env variable=value\n"
4194 " set OpenBIOS nvram variables\n"
4195 #endif
4196 "-clock force the use of the given methods for timer alarm.\n"
4197 " To see what timers are available use -clock ?\n"
4198 "-localtime set the real time clock to local time [default=utc]\n"
4199 "-startdate select initial date of the clock\n"
4200 "-icount [N|auto]\n"
4201 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4202 "-echr chr set terminal escape character instead of ctrl-a\n"
4203 "-virtioconsole c\n"
4204 " set virtio console\n"
4205 "-show-cursor show cursor\n"
4206 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4207 "-semihosting semihosting mode\n"
4208 #endif
4209 #if defined(TARGET_ARM)
4210 "-old-param old param mode\n"
4211 #endif
4212 "-tb-size n set TB size\n"
4213 "-incoming p prepare for incoming migration, listen on port p\n"
4214 #ifndef _WIN32
4215 "-chroot dir Chroot to dir just before starting the VM.\n"
4216 "-runas user Change to user id user just before starting the VM.\n"
4217 #endif
4218 "\n"
4219 "During emulation, the following keys are useful:\n"
4220 "ctrl-alt-f toggle full screen\n"
4221 "ctrl-alt-n switch to virtual console 'n'\n"
4222 "ctrl-alt toggle mouse and keyboard grab\n"
4223 "\n"
4224 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4226 "qemu",
4227 DEFAULT_RAM_SIZE,
4228 #ifndef _WIN32
4229 DEFAULT_NETWORK_SCRIPT,
4230 DEFAULT_NETWORK_DOWN_SCRIPT,
4231 #endif
4232 DEFAULT_GDBSTUB_PORT,
4233 "/tmp/qemu.log");
4234 exit(exitcode);
4237 #define HAS_ARG 0x0001
4239 enum {
4240 /* Please keep in synch with help, qemu_options[] and
4241 qemu-doc.texi */
4242 /* Standard options: */
4243 QEMU_OPTION_h,
4244 QEMU_OPTION_M,
4245 QEMU_OPTION_cpu,
4246 QEMU_OPTION_smp,
4247 QEMU_OPTION_fda,
4248 QEMU_OPTION_fdb,
4249 QEMU_OPTION_hda,
4250 QEMU_OPTION_hdb,
4251 QEMU_OPTION_hdc,
4252 QEMU_OPTION_hdd,
4253 QEMU_OPTION_cdrom,
4254 QEMU_OPTION_drive,
4255 QEMU_OPTION_mtdblock,
4256 QEMU_OPTION_sd,
4257 QEMU_OPTION_pflash,
4258 QEMU_OPTION_boot,
4259 QEMU_OPTION_snapshot,
4260 QEMU_OPTION_m,
4261 QEMU_OPTION_k,
4262 QEMU_OPTION_audio_help,
4263 QEMU_OPTION_soundhw,
4264 QEMU_OPTION_usb,
4265 QEMU_OPTION_usbdevice,
4266 QEMU_OPTION_name,
4267 QEMU_OPTION_uuid,
4269 /* Display options: */
4270 QEMU_OPTION_nographic,
4271 QEMU_OPTION_curses,
4272 QEMU_OPTION_no_frame,
4273 QEMU_OPTION_alt_grab,
4274 QEMU_OPTION_no_quit,
4275 QEMU_OPTION_sdl,
4276 QEMU_OPTION_portrait,
4277 QEMU_OPTION_vga,
4278 QEMU_OPTION_full_screen,
4279 QEMU_OPTION_g,
4280 QEMU_OPTION_vnc,
4282 /* Network options: */
4283 QEMU_OPTION_net,
4284 QEMU_OPTION_tftp,
4285 QEMU_OPTION_bootp,
4286 QEMU_OPTION_smb,
4287 QEMU_OPTION_redir,
4288 QEMU_OPTION_bt,
4290 /* i386 target only: */
4291 QEMU_OPTION_win2k_hack,
4292 QEMU_OPTION_rtc_td_hack,
4293 QEMU_OPTION_no_fd_bootchk,
4294 QEMU_OPTION_no_acpi,
4295 QEMU_OPTION_no_hpet,
4296 QEMU_OPTION_acpitable,
4298 /* Linux boot specific: */
4299 QEMU_OPTION_kernel,
4300 QEMU_OPTION_append,
4301 QEMU_OPTION_initrd,
4303 /* Debug/Expert options: */
4304 QEMU_OPTION_serial,
4305 QEMU_OPTION_parallel,
4306 QEMU_OPTION_monitor,
4307 QEMU_OPTION_pidfile,
4308 QEMU_OPTION_S,
4309 QEMU_OPTION_s,
4310 QEMU_OPTION_p,
4311 QEMU_OPTION_d,
4312 QEMU_OPTION_hdachs,
4313 QEMU_OPTION_L,
4314 QEMU_OPTION_bios,
4315 QEMU_OPTION_kernel_kqemu,
4316 QEMU_OPTION_no_kqemu,
4317 QEMU_OPTION_enable_kvm,
4318 QEMU_OPTION_enable_nesting,
4319 QEMU_OPTION_no_kvm,
4320 QEMU_OPTION_no_kvm_irqchip,
4321 QEMU_OPTION_no_kvm_pit,
4322 QEMU_OPTION_no_kvm_pit_reinjection,
4323 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4324 QEMU_OPTION_pcidevice,
4325 #endif
4326 QEMU_OPTION_no_reboot,
4327 QEMU_OPTION_no_shutdown,
4328 QEMU_OPTION_loadvm,
4329 QEMU_OPTION_daemonize,
4330 QEMU_OPTION_option_rom,
4331 QEMU_OPTION_cpu_vendor,
4332 QEMU_OPTION_nvram,
4333 QEMU_OPTION_prom_env,
4334 QEMU_OPTION_clock,
4335 QEMU_OPTION_localtime,
4336 QEMU_OPTION_startdate,
4337 QEMU_OPTION_icount,
4338 QEMU_OPTION_echr,
4339 QEMU_OPTION_virtiocon,
4340 QEMU_OPTION_show_cursor,
4341 QEMU_OPTION_semihosting,
4342 QEMU_OPTION_old_param,
4343 QEMU_OPTION_tb_size,
4344 QEMU_OPTION_incoming,
4345 QEMU_OPTION_chroot,
4346 QEMU_OPTION_runas,
4347 QEMU_OPTION_tdf,
4348 QEMU_OPTION_kvm_shadow_memory,
4349 QEMU_OPTION_mempath,
4350 #ifdef MAP_POPULATE
4351 QEMU_OPTION_mem_prealloc,
4352 #endif
4355 typedef struct QEMUOption {
4356 const char *name;
4357 int flags;
4358 int index;
4359 } QEMUOption;
4361 static const QEMUOption qemu_options[] = {
4362 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4363 qemu-doc.texi */
4364 /* Standard options: */
4365 { "h", 0, QEMU_OPTION_h },
4366 { "help", 0, QEMU_OPTION_h },
4367 { "M", HAS_ARG, QEMU_OPTION_M },
4368 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4369 { "smp", HAS_ARG, QEMU_OPTION_smp },
4370 { "fda", HAS_ARG, QEMU_OPTION_fda },
4371 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4372 { "hda", HAS_ARG, QEMU_OPTION_hda },
4373 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4374 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4375 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4376 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4377 { "drive", HAS_ARG, QEMU_OPTION_drive },
4378 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4379 { "sd", HAS_ARG, QEMU_OPTION_sd },
4380 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4381 { "boot", HAS_ARG, QEMU_OPTION_boot },
4382 { "snapshot", 0, QEMU_OPTION_snapshot },
4383 { "m", HAS_ARG, QEMU_OPTION_m },
4384 { "k", HAS_ARG, QEMU_OPTION_k },
4385 #ifdef HAS_AUDIO
4386 { "audio-help", 0, QEMU_OPTION_audio_help },
4387 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4388 #endif
4389 { "usb", 0, QEMU_OPTION_usb },
4390 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4391 { "name", HAS_ARG, QEMU_OPTION_name },
4392 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4394 /* Display options: */
4395 { "nographic", 0, QEMU_OPTION_nographic },
4396 #ifdef CONFIG_CURSES
4397 { "curses", 0, QEMU_OPTION_curses },
4398 #endif
4399 #ifdef CONFIG_SDL
4400 { "no-frame", 0, QEMU_OPTION_no_frame },
4401 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4402 { "no-quit", 0, QEMU_OPTION_no_quit },
4403 { "sdl", 0, QEMU_OPTION_sdl },
4404 #endif
4405 { "portrait", 0, QEMU_OPTION_portrait },
4406 { "vga", HAS_ARG, QEMU_OPTION_vga },
4407 { "full-screen", 0, QEMU_OPTION_full_screen },
4408 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4409 { "g", 1, QEMU_OPTION_g },
4410 #endif
4411 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4413 /* Network options: */
4414 { "net", HAS_ARG, QEMU_OPTION_net},
4415 #ifdef CONFIG_SLIRP
4416 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4417 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4418 #ifndef _WIN32
4419 { "smb", HAS_ARG, QEMU_OPTION_smb },
4420 #endif
4421 { "redir", HAS_ARG, QEMU_OPTION_redir },
4422 #endif
4423 { "bt", HAS_ARG, QEMU_OPTION_bt },
4424 #ifdef TARGET_I386
4425 /* i386 target only: */
4426 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4427 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4428 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4429 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4430 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4431 { "acpitable", HAS_ARG, QEMU_OPTION_acpitable },
4432 #endif
4434 /* Linux boot specific: */
4435 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4436 { "append", HAS_ARG, QEMU_OPTION_append },
4437 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4439 /* Debug/Expert options: */
4440 { "serial", HAS_ARG, QEMU_OPTION_serial },
4441 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4442 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4443 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4444 { "S", 0, QEMU_OPTION_S },
4445 { "s", 0, QEMU_OPTION_s },
4446 { "p", HAS_ARG, QEMU_OPTION_p },
4447 { "d", HAS_ARG, QEMU_OPTION_d },
4448 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4449 { "L", HAS_ARG, QEMU_OPTION_L },
4450 { "bios", HAS_ARG, QEMU_OPTION_bios },
4451 #ifdef USE_KQEMU
4452 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4453 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4454 #endif
4455 #ifdef CONFIG_KVM
4456 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4457 #endif
4458 #ifdef USE_KVM
4459 #ifndef NO_CPU_EMULATION
4460 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4461 #endif
4462 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4463 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4464 { "no-kvm-pit-reinjection", 0, QEMU_OPTION_no_kvm_pit_reinjection },
4465 { "enable-nesting", 0, QEMU_OPTION_enable_nesting },
4466 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4467 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4468 #endif
4469 #endif
4470 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4471 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4472 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4473 { "daemonize", 0, QEMU_OPTION_daemonize },
4474 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4475 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4476 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4477 #endif
4478 { "clock", HAS_ARG, QEMU_OPTION_clock },
4479 { "localtime", 0, QEMU_OPTION_localtime },
4480 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4481 { "icount", HAS_ARG, QEMU_OPTION_icount },
4482 { "echr", HAS_ARG, QEMU_OPTION_echr },
4483 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4484 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4485 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4486 { "semihosting", 0, QEMU_OPTION_semihosting },
4487 #endif
4488 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4489 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4490 { "nvram", HAS_ARG, QEMU_OPTION_nvram },
4491 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4492 #if defined(TARGET_ARM)
4493 { "old-param", 0, QEMU_OPTION_old_param },
4494 #endif
4495 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4496 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4497 { "chroot", HAS_ARG, QEMU_OPTION_chroot },
4498 { "runas", HAS_ARG, QEMU_OPTION_runas },
4499 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4500 #ifdef MAP_POPULATE
4501 { "mem-prealloc", 0, QEMU_OPTION_mem_prealloc },
4502 #endif
4503 { NULL },
4506 #ifdef HAS_AUDIO
4507 struct soundhw soundhw[] = {
4508 #ifdef HAS_AUDIO_CHOICE
4509 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4511 "pcspk",
4512 "PC speaker",
4515 { .init_isa = pcspk_audio_init }
4517 #endif
4519 #ifdef CONFIG_SB16
4521 "sb16",
4522 "Creative Sound Blaster 16",
4525 { .init_isa = SB16_init }
4527 #endif
4529 #ifdef CONFIG_CS4231A
4531 "cs4231a",
4532 "CS4231A",
4535 { .init_isa = cs4231a_init }
4537 #endif
4539 #ifdef CONFIG_ADLIB
4541 "adlib",
4542 #ifdef HAS_YMF262
4543 "Yamaha YMF262 (OPL3)",
4544 #else
4545 "Yamaha YM3812 (OPL2)",
4546 #endif
4549 { .init_isa = Adlib_init }
4551 #endif
4553 #ifdef CONFIG_GUS
4555 "gus",
4556 "Gravis Ultrasound GF1",
4559 { .init_isa = GUS_init }
4561 #endif
4563 #ifdef CONFIG_AC97
4565 "ac97",
4566 "Intel 82801AA AC97 Audio",
4569 { .init_pci = ac97_init }
4571 #endif
4573 #ifdef CONFIG_ES1370
4575 "es1370",
4576 "ENSONIQ AudioPCI ES1370",
4579 { .init_pci = es1370_init }
4581 #endif
4583 #endif /* HAS_AUDIO_CHOICE */
4585 { NULL, NULL, 0, 0, { NULL } }
4588 static void select_soundhw (const char *optarg)
4590 struct soundhw *c;
4592 if (*optarg == '?') {
4593 show_valid_cards:
4595 printf ("Valid sound card names (comma separated):\n");
4596 for (c = soundhw; c->name; ++c) {
4597 printf ("%-11s %s\n", c->name, c->descr);
4599 printf ("\n-soundhw all will enable all of the above\n");
4600 exit (*optarg != '?');
4602 else {
4603 size_t l;
4604 const char *p;
4605 char *e;
4606 int bad_card = 0;
4608 if (!strcmp (optarg, "all")) {
4609 for (c = soundhw; c->name; ++c) {
4610 c->enabled = 1;
4612 return;
4615 p = optarg;
4616 while (*p) {
4617 e = strchr (p, ',');
4618 l = !e ? strlen (p) : (size_t) (e - p);
4620 for (c = soundhw; c->name; ++c) {
4621 if (!strncmp (c->name, p, l)) {
4622 c->enabled = 1;
4623 break;
4627 if (!c->name) {
4628 if (l > 80) {
4629 fprintf (stderr,
4630 "Unknown sound card name (too big to show)\n");
4632 else {
4633 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4634 (int) l, p);
4636 bad_card = 1;
4638 p += l + (e != NULL);
4641 if (bad_card)
4642 goto show_valid_cards;
4645 #endif
4647 static void select_vgahw (const char *p)
4649 const char *opts;
4651 if (strstart(p, "std", &opts)) {
4652 std_vga_enabled = 1;
4653 cirrus_vga_enabled = 0;
4654 vmsvga_enabled = 0;
4655 } else if (strstart(p, "cirrus", &opts)) {
4656 cirrus_vga_enabled = 1;
4657 std_vga_enabled = 0;
4658 vmsvga_enabled = 0;
4659 } else if (strstart(p, "vmware", &opts)) {
4660 cirrus_vga_enabled = 0;
4661 std_vga_enabled = 0;
4662 vmsvga_enabled = 1;
4663 } else if (strstart(p, "none", &opts)) {
4664 cirrus_vga_enabled = 0;
4665 std_vga_enabled = 0;
4666 vmsvga_enabled = 0;
4667 } else {
4668 invalid_vga:
4669 fprintf(stderr, "Unknown vga type: %s\n", p);
4670 exit(1);
4672 while (*opts) {
4673 const char *nextopt;
4675 if (strstart(opts, ",retrace=", &nextopt)) {
4676 opts = nextopt;
4677 if (strstart(opts, "dumb", &nextopt))
4678 vga_retrace_method = VGA_RETRACE_DUMB;
4679 else if (strstart(opts, "precise", &nextopt))
4680 vga_retrace_method = VGA_RETRACE_PRECISE;
4681 else goto invalid_vga;
4682 } else goto invalid_vga;
4683 opts = nextopt;
4687 #ifdef _WIN32
4688 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4690 exit(STATUS_CONTROL_C_EXIT);
4691 return TRUE;
4693 #endif
4695 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4697 int ret;
4699 if(strlen(str) != 36)
4700 return -1;
4702 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4703 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4704 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4706 if(ret != 16)
4707 return -1;
4709 return 0;
4712 #define MAX_NET_CLIENTS 32
4714 static int saved_argc;
4715 static char **saved_argv;
4717 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4719 *argc = saved_argc;
4720 *argv = saved_argv;
4721 *opt_daemonize = daemonize;
4722 *opt_incoming = incoming;
4725 #ifdef USE_KVM
4727 #define HUGETLBFS_MAGIC 0x958458f6
4729 static long gethugepagesize(const char *path)
4731 struct statfs fs;
4732 int ret;
4734 do {
4735 ret = statfs(path, &fs);
4736 } while (ret != 0 && errno == EINTR);
4738 if (ret != 0) {
4739 perror("statfs");
4740 return 0;
4743 if (fs.f_type != HUGETLBFS_MAGIC)
4744 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4746 return fs.f_bsize;
4749 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4751 char *filename;
4752 void *area;
4753 int fd;
4754 #ifdef MAP_POPULATE
4755 int flags;
4756 #endif
4758 if (!kvm_has_sync_mmu()) {
4759 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4760 return NULL;
4763 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4764 return NULL;
4766 hpagesize = gethugepagesize(path);
4767 if (!hpagesize)
4768 return NULL;
4770 fd = mkstemp(filename);
4771 if (fd < 0) {
4772 perror("mkstemp");
4773 free(filename);
4774 return NULL;
4776 unlink(filename);
4777 free(filename);
4779 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4782 * ftruncate is not supported by hugetlbfs in older
4783 * hosts, so don't bother checking for errors.
4784 * If anything goes wrong with it under other filesystems,
4785 * mmap will fail.
4787 ftruncate(fd, memory);
4789 #ifdef MAP_POPULATE
4790 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4791 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4792 * to sidestep this quirk.
4794 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4795 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4796 #else
4797 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4798 #endif
4799 if (area == MAP_FAILED) {
4800 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4801 close(fd);
4802 return (NULL);
4804 *len = memory;
4805 return area;
4807 #endif
4809 static void *qemu_alloc_physram(unsigned long memory)
4811 void *area = NULL;
4812 #ifdef USE_KVM
4813 unsigned long map_len = memory;
4815 if (mem_path)
4816 area = alloc_mem_area(memory, &map_len, mem_path);
4817 #endif
4818 if (!area)
4819 area = qemu_vmalloc(memory);
4820 #ifdef USE_KVM
4821 if (kvm_setup_guest_memory(area, map_len))
4822 area = NULL;
4823 #endif
4824 return area;
4827 #ifndef _WIN32
4829 static void termsig_handler(int signal)
4831 qemu_system_shutdown_request();
4834 static void termsig_setup(void)
4836 struct sigaction act;
4838 memset(&act, 0, sizeof(act));
4839 act.sa_handler = termsig_handler;
4840 sigaction(SIGINT, &act, NULL);
4841 sigaction(SIGHUP, &act, NULL);
4842 sigaction(SIGTERM, &act, NULL);
4845 #endif
4847 int main(int argc, char **argv, char **envp)
4849 #ifdef CONFIG_GDBSTUB
4850 int use_gdbstub;
4851 const char *gdbstub_port;
4852 #endif
4853 uint32_t boot_devices_bitmap = 0;
4854 int i;
4855 int snapshot, linux_boot, net_boot;
4856 const char *initrd_filename;
4857 const char *kernel_filename, *kernel_cmdline;
4858 const char *boot_devices = "";
4859 DisplayState *ds;
4860 DisplayChangeListener *dcl;
4861 int cyls, heads, secs, translation;
4862 const char *net_clients[MAX_NET_CLIENTS];
4863 int nb_net_clients;
4864 const char *bt_opts[MAX_BT_CMDLINE];
4865 int nb_bt_opts;
4866 int hda_index;
4867 int optind;
4868 const char *r, *optarg;
4869 CharDriverState *monitor_hd = NULL;
4870 const char *monitor_device;
4871 const char *serial_devices[MAX_SERIAL_PORTS];
4872 int serial_device_index;
4873 const char *parallel_devices[MAX_PARALLEL_PORTS];
4874 int parallel_device_index;
4875 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4876 int virtio_console_index;
4877 const char *loadvm = NULL;
4878 QEMUMachine *machine;
4879 const char *cpu_model;
4880 const char *usb_devices[MAX_USB_CMDLINE];
4881 int usb_devices_index;
4882 int fds[2];
4883 int tb_size;
4884 const char *pid_file = NULL;
4885 const char *incoming = NULL;
4886 int fd = 0;
4887 struct passwd *pwd = NULL;
4888 const char *chroot_dir = NULL;
4889 const char *run_as = NULL;
4891 qemu_cache_utils_init(envp);
4893 LIST_INIT (&vm_change_state_head);
4894 #ifndef _WIN32
4896 struct sigaction act;
4897 sigfillset(&act.sa_mask);
4898 act.sa_flags = 0;
4899 act.sa_handler = SIG_IGN;
4900 sigaction(SIGPIPE, &act, NULL);
4902 #else
4903 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4904 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4905 QEMU to run on a single CPU */
4907 HANDLE h;
4908 DWORD mask, smask;
4909 int i;
4910 h = GetCurrentProcess();
4911 if (GetProcessAffinityMask(h, &mask, &smask)) {
4912 for(i = 0; i < 32; i++) {
4913 if (mask & (1 << i))
4914 break;
4916 if (i != 32) {
4917 mask = 1 << i;
4918 SetProcessAffinityMask(h, mask);
4922 #endif
4924 register_machines();
4925 machine = first_machine;
4926 cpu_model = NULL;
4927 initrd_filename = NULL;
4928 ram_size = 0;
4929 vga_ram_size = VGA_RAM_SIZE;
4930 #ifdef CONFIG_GDBSTUB
4931 use_gdbstub = 0;
4932 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4933 #endif
4934 snapshot = 0;
4935 nographic = 0;
4936 curses = 0;
4937 kernel_filename = NULL;
4938 kernel_cmdline = "";
4939 cyls = heads = secs = 0;
4940 translation = BIOS_ATA_TRANSLATION_AUTO;
4941 monitor_device = "vc:80Cx24C";
4943 serial_devices[0] = "vc:80Cx24C";
4944 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4945 serial_devices[i] = NULL;
4946 serial_device_index = 0;
4948 parallel_devices[0] = "vc:80Cx24C";
4949 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4950 parallel_devices[i] = NULL;
4951 parallel_device_index = 0;
4953 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4954 virtio_consoles[i] = NULL;
4955 virtio_console_index = 0;
4957 usb_devices_index = 0;
4958 assigned_devices_index = 0;
4960 nb_net_clients = 0;
4961 nb_bt_opts = 0;
4962 nb_drives = 0;
4963 nb_drives_opt = 0;
4964 hda_index = -1;
4966 nb_nics = 0;
4968 tb_size = 0;
4969 autostart= 1;
4971 optind = 1;
4972 for(;;) {
4973 if (optind >= argc)
4974 break;
4975 r = argv[optind];
4976 if (r[0] != '-') {
4977 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4978 } else {
4979 const QEMUOption *popt;
4981 optind++;
4982 /* Treat --foo the same as -foo. */
4983 if (r[1] == '-')
4984 r++;
4985 popt = qemu_options;
4986 for(;;) {
4987 if (!popt->name) {
4988 fprintf(stderr, "%s: invalid option -- '%s'\n",
4989 argv[0], r);
4990 exit(1);
4992 if (!strcmp(popt->name, r + 1))
4993 break;
4994 popt++;
4996 if (popt->flags & HAS_ARG) {
4997 if (optind >= argc) {
4998 fprintf(stderr, "%s: option '%s' requires an argument\n",
4999 argv[0], r);
5000 exit(1);
5002 optarg = argv[optind++];
5003 } else {
5004 optarg = NULL;
5007 switch(popt->index) {
5008 case QEMU_OPTION_M:
5009 machine = find_machine(optarg);
5010 if (!machine) {
5011 QEMUMachine *m;
5012 printf("Supported machines are:\n");
5013 for(m = first_machine; m != NULL; m = m->next) {
5014 printf("%-10s %s%s\n",
5015 m->name, m->desc,
5016 m == first_machine ? " (default)" : "");
5018 exit(*optarg != '?');
5020 break;
5021 case QEMU_OPTION_cpu:
5022 /* hw initialization will check this */
5023 if (*optarg == '?') {
5024 /* XXX: implement xxx_cpu_list for targets that still miss it */
5025 #if defined(cpu_list)
5026 cpu_list(stdout, &fprintf);
5027 #endif
5028 exit(0);
5029 } else {
5030 cpu_model = optarg;
5032 break;
5033 case QEMU_OPTION_initrd:
5034 initrd_filename = optarg;
5035 break;
5036 case QEMU_OPTION_hda:
5037 if (cyls == 0)
5038 hda_index = drive_add(optarg, HD_ALIAS, 0);
5039 else
5040 hda_index = drive_add(optarg, HD_ALIAS
5041 ",cyls=%d,heads=%d,secs=%d%s",
5042 0, cyls, heads, secs,
5043 translation == BIOS_ATA_TRANSLATION_LBA ?
5044 ",trans=lba" :
5045 translation == BIOS_ATA_TRANSLATION_NONE ?
5046 ",trans=none" : "");
5047 break;
5048 case QEMU_OPTION_hdb:
5049 case QEMU_OPTION_hdc:
5050 case QEMU_OPTION_hdd:
5051 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5052 break;
5053 case QEMU_OPTION_drive:
5054 drive_add(NULL, "%s", optarg);
5055 break;
5056 case QEMU_OPTION_mtdblock:
5057 drive_add(optarg, MTD_ALIAS);
5058 break;
5059 case QEMU_OPTION_sd:
5060 drive_add(optarg, SD_ALIAS);
5061 break;
5062 case QEMU_OPTION_pflash:
5063 drive_add(optarg, PFLASH_ALIAS);
5064 break;
5065 case QEMU_OPTION_snapshot:
5066 snapshot = 1;
5067 break;
5068 case QEMU_OPTION_hdachs:
5070 const char *p;
5071 p = optarg;
5072 cyls = strtol(p, (char **)&p, 0);
5073 if (cyls < 1 || cyls > 16383)
5074 goto chs_fail;
5075 if (*p != ',')
5076 goto chs_fail;
5077 p++;
5078 heads = strtol(p, (char **)&p, 0);
5079 if (heads < 1 || heads > 16)
5080 goto chs_fail;
5081 if (*p != ',')
5082 goto chs_fail;
5083 p++;
5084 secs = strtol(p, (char **)&p, 0);
5085 if (secs < 1 || secs > 63)
5086 goto chs_fail;
5087 if (*p == ',') {
5088 p++;
5089 if (!strcmp(p, "none"))
5090 translation = BIOS_ATA_TRANSLATION_NONE;
5091 else if (!strcmp(p, "lba"))
5092 translation = BIOS_ATA_TRANSLATION_LBA;
5093 else if (!strcmp(p, "auto"))
5094 translation = BIOS_ATA_TRANSLATION_AUTO;
5095 else
5096 goto chs_fail;
5097 } else if (*p != '\0') {
5098 chs_fail:
5099 fprintf(stderr, "qemu: invalid physical CHS format\n");
5100 exit(1);
5102 if (hda_index != -1)
5103 snprintf(drives_opt[hda_index].opt,
5104 sizeof(drives_opt[hda_index].opt),
5105 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5106 0, cyls, heads, secs,
5107 translation == BIOS_ATA_TRANSLATION_LBA ?
5108 ",trans=lba" :
5109 translation == BIOS_ATA_TRANSLATION_NONE ?
5110 ",trans=none" : "");
5112 break;
5113 case QEMU_OPTION_nographic:
5114 nographic = 1;
5115 break;
5116 #ifdef CONFIG_CURSES
5117 case QEMU_OPTION_curses:
5118 curses = 1;
5119 break;
5120 #endif
5121 case QEMU_OPTION_portrait:
5122 graphic_rotate = 1;
5123 break;
5124 case QEMU_OPTION_kernel:
5125 kernel_filename = optarg;
5126 break;
5127 case QEMU_OPTION_append:
5128 kernel_cmdline = optarg;
5129 break;
5130 case QEMU_OPTION_cdrom:
5131 drive_add(optarg, CDROM_ALIAS);
5132 break;
5133 case QEMU_OPTION_boot:
5134 boot_devices = optarg;
5135 /* We just do some generic consistency checks */
5137 /* Could easily be extended to 64 devices if needed */
5138 const char *p;
5140 boot_devices_bitmap = 0;
5141 for (p = boot_devices; *p != '\0'; p++) {
5142 /* Allowed boot devices are:
5143 * a b : floppy disk drives
5144 * c ... f : IDE disk drives
5145 * g ... m : machine implementation dependant drives
5146 * n ... p : network devices
5147 * It's up to each machine implementation to check
5148 * if the given boot devices match the actual hardware
5149 * implementation and firmware features.
5151 if (*p < 'a' || *p > 'q') {
5152 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5153 exit(1);
5155 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5156 fprintf(stderr,
5157 "Boot device '%c' was given twice\n",*p);
5158 exit(1);
5160 boot_devices_bitmap |= 1 << (*p - 'a');
5163 break;
5164 case QEMU_OPTION_fda:
5165 case QEMU_OPTION_fdb:
5166 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5167 break;
5168 #ifdef TARGET_I386
5169 case QEMU_OPTION_no_fd_bootchk:
5170 fd_bootchk = 0;
5171 break;
5172 #endif
5173 case QEMU_OPTION_net:
5174 if (nb_net_clients >= MAX_NET_CLIENTS) {
5175 fprintf(stderr, "qemu: too many network clients\n");
5176 exit(1);
5178 net_clients[nb_net_clients] = optarg;
5179 nb_net_clients++;
5180 break;
5181 #ifdef CONFIG_SLIRP
5182 case QEMU_OPTION_tftp:
5183 tftp_prefix = optarg;
5184 break;
5185 case QEMU_OPTION_bootp:
5186 bootp_filename = optarg;
5187 break;
5188 #ifndef _WIN32
5189 case QEMU_OPTION_smb:
5190 net_slirp_smb(optarg);
5191 break;
5192 #endif
5193 case QEMU_OPTION_redir:
5194 net_slirp_redir(optarg);
5195 break;
5196 #endif
5197 case QEMU_OPTION_bt:
5198 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5199 fprintf(stderr, "qemu: too many bluetooth options\n");
5200 exit(1);
5202 bt_opts[nb_bt_opts++] = optarg;
5203 break;
5204 #ifdef HAS_AUDIO
5205 case QEMU_OPTION_audio_help:
5206 AUD_help ();
5207 exit (0);
5208 break;
5209 case QEMU_OPTION_soundhw:
5210 select_soundhw (optarg);
5211 break;
5212 #endif
5213 case QEMU_OPTION_h:
5214 help(0);
5215 break;
5216 case QEMU_OPTION_m: {
5217 uint64_t value;
5218 char *ptr;
5220 value = strtoul(optarg, &ptr, 10);
5221 switch (*ptr) {
5222 case 0: case 'M': case 'm':
5223 value <<= 20;
5224 break;
5225 case 'G': case 'g':
5226 value <<= 30;
5227 break;
5228 default:
5229 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5230 exit(1);
5233 /* On 32-bit hosts, QEMU is limited by virtual address space */
5234 if (value > (2047 << 20)
5235 #ifndef USE_KQEMU
5236 && HOST_LONG_BITS == 32
5237 #endif
5239 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5240 exit(1);
5242 if (value != (uint64_t)(ram_addr_t)value) {
5243 fprintf(stderr, "qemu: ram size too large\n");
5244 exit(1);
5246 ram_size = value;
5247 break;
5249 case QEMU_OPTION_d:
5251 int mask;
5252 const CPULogItem *item;
5254 mask = cpu_str_to_log_mask(optarg);
5255 if (!mask) {
5256 printf("Log items (comma separated):\n");
5257 for(item = cpu_log_items; item->mask != 0; item++) {
5258 printf("%-10s %s\n", item->name, item->help);
5260 exit(1);
5262 cpu_set_log(mask);
5264 break;
5265 #ifdef CONFIG_GDBSTUB
5266 case QEMU_OPTION_s:
5267 use_gdbstub = 1;
5268 break;
5269 case QEMU_OPTION_p:
5270 gdbstub_port = optarg;
5271 break;
5272 #endif
5273 case QEMU_OPTION_L:
5274 bios_dir = optarg;
5275 break;
5276 case QEMU_OPTION_bios:
5277 bios_name = optarg;
5278 break;
5279 case QEMU_OPTION_S:
5280 autostart = 0;
5281 break;
5282 case QEMU_OPTION_k:
5283 keyboard_layout = optarg;
5284 break;
5285 case QEMU_OPTION_localtime:
5286 rtc_utc = 0;
5287 break;
5288 case QEMU_OPTION_vga:
5289 select_vgahw (optarg);
5290 break;
5291 case QEMU_OPTION_g:
5293 const char *p;
5294 int w, h, depth;
5295 p = optarg;
5296 w = strtol(p, (char **)&p, 10);
5297 if (w <= 0) {
5298 graphic_error:
5299 fprintf(stderr, "qemu: invalid resolution or depth\n");
5300 exit(1);
5302 if (*p != 'x')
5303 goto graphic_error;
5304 p++;
5305 h = strtol(p, (char **)&p, 10);
5306 if (h <= 0)
5307 goto graphic_error;
5308 if (*p == 'x') {
5309 p++;
5310 depth = strtol(p, (char **)&p, 10);
5311 if (depth != 8 && depth != 15 && depth != 16 &&
5312 depth != 24 && depth != 32)
5313 goto graphic_error;
5314 } else if (*p == '\0') {
5315 depth = graphic_depth;
5316 } else {
5317 goto graphic_error;
5320 graphic_width = w;
5321 graphic_height = h;
5322 graphic_depth = depth;
5324 break;
5325 case QEMU_OPTION_echr:
5327 char *r;
5328 term_escape_char = strtol(optarg, &r, 0);
5329 if (r == optarg)
5330 printf("Bad argument to echr\n");
5331 break;
5333 case QEMU_OPTION_monitor:
5334 monitor_device = optarg;
5335 break;
5336 case QEMU_OPTION_serial:
5337 if (serial_device_index >= MAX_SERIAL_PORTS) {
5338 fprintf(stderr, "qemu: too many serial ports\n");
5339 exit(1);
5341 serial_devices[serial_device_index] = optarg;
5342 serial_device_index++;
5343 break;
5344 case QEMU_OPTION_virtiocon:
5345 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5346 fprintf(stderr, "qemu: too many virtio consoles\n");
5347 exit(1);
5349 virtio_consoles[virtio_console_index] = optarg;
5350 virtio_console_index++;
5351 break;
5352 case QEMU_OPTION_parallel:
5353 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5354 fprintf(stderr, "qemu: too many parallel ports\n");
5355 exit(1);
5357 parallel_devices[parallel_device_index] = optarg;
5358 parallel_device_index++;
5359 break;
5360 case QEMU_OPTION_loadvm:
5361 loadvm = optarg;
5362 break;
5363 case QEMU_OPTION_full_screen:
5364 full_screen = 1;
5365 break;
5366 #ifdef CONFIG_SDL
5367 case QEMU_OPTION_no_frame:
5368 no_frame = 1;
5369 break;
5370 case QEMU_OPTION_alt_grab:
5371 alt_grab = 1;
5372 break;
5373 case QEMU_OPTION_no_quit:
5374 no_quit = 1;
5375 break;
5376 case QEMU_OPTION_sdl:
5377 sdl = 1;
5378 break;
5379 #endif
5380 case QEMU_OPTION_pidfile:
5381 pid_file = optarg;
5382 break;
5383 #ifdef TARGET_I386
5384 case QEMU_OPTION_win2k_hack:
5385 win2k_install_hack = 1;
5386 break;
5387 case QEMU_OPTION_rtc_td_hack:
5388 rtc_td_hack = 1;
5389 break;
5390 case QEMU_OPTION_acpitable:
5391 if(acpi_table_add(optarg) < 0) {
5392 fprintf(stderr, "Wrong acpi table provided\n");
5393 exit(1);
5395 break;
5396 #endif
5397 #ifdef USE_KQEMU
5398 case QEMU_OPTION_no_kqemu:
5399 kqemu_allowed = 0;
5400 break;
5401 case QEMU_OPTION_kernel_kqemu:
5402 kqemu_allowed = 2;
5403 break;
5404 #endif
5405 #ifdef CONFIG_KVM
5406 case QEMU_OPTION_enable_kvm:
5407 kvm_allowed = 1;
5408 #ifdef USE_KQEMU
5409 kqemu_allowed = 0;
5410 #endif
5411 break;
5412 #endif
5413 #ifdef USE_KVM
5414 case QEMU_OPTION_no_kvm:
5415 kvm_allowed = 0;
5416 break;
5417 case QEMU_OPTION_no_kvm_irqchip: {
5418 kvm_irqchip = 0;
5419 kvm_pit = 0;
5420 break;
5422 case QEMU_OPTION_no_kvm_pit: {
5423 kvm_pit = 0;
5424 break;
5426 case QEMU_OPTION_no_kvm_pit_reinjection: {
5427 kvm_pit_reinject = 0;
5428 break;
5430 case QEMU_OPTION_enable_nesting: {
5431 kvm_nested = 1;
5432 break;
5434 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5435 case QEMU_OPTION_pcidevice:
5436 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5437 fprintf(stderr, "Too many assigned devices\n");
5438 exit(1);
5440 assigned_devices[assigned_devices_index] = optarg;
5441 assigned_devices_index++;
5442 break;
5443 #endif
5444 #endif
5445 case QEMU_OPTION_usb:
5446 usb_enabled = 1;
5447 break;
5448 case QEMU_OPTION_usbdevice:
5449 usb_enabled = 1;
5450 if (usb_devices_index >= MAX_USB_CMDLINE) {
5451 fprintf(stderr, "Too many USB devices\n");
5452 exit(1);
5454 usb_devices[usb_devices_index] = optarg;
5455 usb_devices_index++;
5456 break;
5457 case QEMU_OPTION_smp:
5458 smp_cpus = atoi(optarg);
5459 if (smp_cpus < 1) {
5460 fprintf(stderr, "Invalid number of CPUs\n");
5461 exit(1);
5463 break;
5464 case QEMU_OPTION_vnc:
5465 vnc_display = optarg;
5466 break;
5467 case QEMU_OPTION_no_acpi:
5468 acpi_enabled = 0;
5469 break;
5470 case QEMU_OPTION_no_hpet:
5471 no_hpet = 1;
5472 break;
5473 case QEMU_OPTION_no_reboot:
5474 no_reboot = 1;
5475 break;
5476 case QEMU_OPTION_no_shutdown:
5477 no_shutdown = 1;
5478 break;
5479 case QEMU_OPTION_show_cursor:
5480 cursor_hide = 0;
5481 break;
5482 case QEMU_OPTION_uuid:
5483 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5484 fprintf(stderr, "Fail to parse UUID string."
5485 " Wrong format.\n");
5486 exit(1);
5488 break;
5489 case QEMU_OPTION_daemonize:
5490 daemonize = 1;
5491 break;
5492 case QEMU_OPTION_option_rom:
5493 if (nb_option_roms >= MAX_OPTION_ROMS) {
5494 fprintf(stderr, "Too many option ROMs\n");
5495 exit(1);
5497 option_rom[nb_option_roms] = optarg;
5498 nb_option_roms++;
5499 break;
5500 case QEMU_OPTION_semihosting:
5501 semihosting_enabled = 1;
5502 break;
5503 case QEMU_OPTION_tdf:
5504 time_drift_fix = 1;
5505 break;
5506 case QEMU_OPTION_kvm_shadow_memory:
5507 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5508 break;
5509 case QEMU_OPTION_mempath:
5510 mem_path = optarg;
5511 break;
5512 #ifdef MAP_POPULATE
5513 case QEMU_OPTION_mem_prealloc:
5514 mem_prealloc = !mem_prealloc;
5515 break;
5516 #endif
5517 case QEMU_OPTION_name:
5518 qemu_name = optarg;
5519 break;
5520 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5521 case QEMU_OPTION_prom_env:
5522 if (nb_prom_envs >= MAX_PROM_ENVS) {
5523 fprintf(stderr, "Too many prom variables\n");
5524 exit(1);
5526 prom_envs[nb_prom_envs] = optarg;
5527 nb_prom_envs++;
5528 break;
5529 #endif
5530 case QEMU_OPTION_cpu_vendor:
5531 cpu_vendor_string = optarg;
5532 break;
5533 #ifdef TARGET_ARM
5534 case QEMU_OPTION_old_param:
5535 old_param = 1;
5536 break;
5537 #endif
5538 case QEMU_OPTION_clock:
5539 configure_alarms(optarg);
5540 break;
5541 case QEMU_OPTION_startdate:
5543 struct tm tm;
5544 time_t rtc_start_date;
5545 if (!strcmp(optarg, "now")) {
5546 rtc_date_offset = -1;
5547 } else {
5548 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5549 &tm.tm_year,
5550 &tm.tm_mon,
5551 &tm.tm_mday,
5552 &tm.tm_hour,
5553 &tm.tm_min,
5554 &tm.tm_sec) == 6) {
5555 /* OK */
5556 } else if (sscanf(optarg, "%d-%d-%d",
5557 &tm.tm_year,
5558 &tm.tm_mon,
5559 &tm.tm_mday) == 3) {
5560 tm.tm_hour = 0;
5561 tm.tm_min = 0;
5562 tm.tm_sec = 0;
5563 } else {
5564 goto date_fail;
5566 tm.tm_year -= 1900;
5567 tm.tm_mon--;
5568 rtc_start_date = mktimegm(&tm);
5569 if (rtc_start_date == -1) {
5570 date_fail:
5571 fprintf(stderr, "Invalid date format. Valid format are:\n"
5572 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5573 exit(1);
5575 rtc_date_offset = time(NULL) - rtc_start_date;
5578 break;
5579 case QEMU_OPTION_tb_size:
5580 tb_size = strtol(optarg, NULL, 0);
5581 if (tb_size < 0)
5582 tb_size = 0;
5583 break;
5584 case QEMU_OPTION_icount:
5585 use_icount = 1;
5586 if (strcmp(optarg, "auto") == 0) {
5587 icount_time_shift = -1;
5588 } else {
5589 icount_time_shift = strtol(optarg, NULL, 0);
5591 break;
5592 case QEMU_OPTION_incoming:
5593 incoming = optarg;
5594 break;
5595 case QEMU_OPTION_chroot:
5596 chroot_dir = optarg;
5597 break;
5598 case QEMU_OPTION_runas:
5599 run_as = optarg;
5600 case QEMU_OPTION_nvram:
5601 nvram = optarg;
5602 break;
5607 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5608 if (kvm_allowed && kqemu_allowed) {
5609 fprintf(stderr,
5610 "You can not enable both KVM and kqemu at the same time\n");
5611 exit(1);
5613 #endif
5615 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5616 if (smp_cpus > machine->max_cpus) {
5617 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5618 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5619 machine->max_cpus);
5620 exit(1);
5623 if (nographic) {
5624 if (serial_device_index == 0)
5625 serial_devices[0] = "stdio";
5626 if (parallel_device_index == 0)
5627 parallel_devices[0] = "null";
5628 if (strncmp(monitor_device, "vc", 2) == 0)
5629 monitor_device = "stdio";
5632 #ifndef _WIN32
5633 if (daemonize) {
5634 pid_t pid;
5636 if (pipe(fds) == -1)
5637 exit(1);
5639 pid = fork();
5640 if (pid > 0) {
5641 uint8_t status;
5642 ssize_t len;
5644 close(fds[1]);
5646 again:
5647 len = read(fds[0], &status, 1);
5648 if (len == -1 && (errno == EINTR))
5649 goto again;
5651 if (len != 1)
5652 exit(1);
5653 else if (status == 1) {
5654 fprintf(stderr, "Could not acquire pidfile\n");
5655 exit(1);
5656 } else
5657 exit(0);
5658 } else if (pid < 0)
5659 exit(1);
5661 setsid();
5663 pid = fork();
5664 if (pid > 0)
5665 exit(0);
5666 else if (pid < 0)
5667 exit(1);
5669 umask(027);
5671 signal(SIGTSTP, SIG_IGN);
5672 signal(SIGTTOU, SIG_IGN);
5673 signal(SIGTTIN, SIG_IGN);
5675 #endif
5677 #ifdef USE_KVM
5678 if (kvm_enabled()) {
5679 if (kvm_qemu_init() < 0) {
5680 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5681 #ifdef NO_CPU_EMULATION
5682 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5683 exit(1);
5684 #endif
5685 kvm_allowed = 0;
5688 #endif
5690 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5691 if (daemonize) {
5692 uint8_t status = 1;
5693 write(fds[1], &status, 1);
5694 } else
5695 fprintf(stderr, "Could not acquire pid file\n");
5696 exit(1);
5699 #ifdef USE_KQEMU
5700 if (smp_cpus > 1)
5701 kqemu_allowed = 0;
5702 #endif
5703 linux_boot = (kernel_filename != NULL);
5704 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5706 if (!linux_boot && net_boot == 0 &&
5707 !machine->nodisk_ok && nb_drives_opt == 0)
5708 help(1);
5710 if (!linux_boot && *kernel_cmdline != '\0') {
5711 fprintf(stderr, "-append only allowed with -kernel option\n");
5712 exit(1);
5715 if (!linux_boot && initrd_filename != NULL) {
5716 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5717 exit(1);
5720 /* boot to floppy or the default cd if no hard disk defined yet */
5721 if (!boot_devices[0]) {
5722 boot_devices = "cad";
5724 setvbuf(stdout, NULL, _IOLBF, 0);
5726 init_timers();
5727 if (init_timer_alarm() < 0) {
5728 fprintf(stderr, "could not initialize alarm timer\n");
5729 exit(1);
5731 if (use_icount && icount_time_shift < 0) {
5732 use_icount = 2;
5733 /* 125MIPS seems a reasonable initial guess at the guest speed.
5734 It will be corrected fairly quickly anyway. */
5735 icount_time_shift = 3;
5736 init_icount_adjust();
5739 #ifdef _WIN32
5740 socket_init();
5741 #endif
5743 /* init network clients */
5744 if (nb_net_clients == 0) {
5745 /* if no clients, we use a default config */
5746 net_clients[nb_net_clients++] = "nic";
5747 #ifdef CONFIG_SLIRP
5748 net_clients[nb_net_clients++] = "user";
5749 #endif
5752 for(i = 0;i < nb_net_clients; i++) {
5753 if (net_client_parse(net_clients[i]) < 0)
5754 exit(1);
5756 net_client_check();
5758 #ifdef TARGET_I386
5759 /* XXX: this should be moved in the PC machine instantiation code */
5760 if (net_boot != 0) {
5761 int netroms = 0;
5762 for (i = 0; i < nb_nics && i < 4; i++) {
5763 const char *model = nd_table[i].model;
5764 char buf[1024];
5765 if (net_boot & (1 << i)) {
5766 if (model == NULL)
5767 model = "rtl8139";
5768 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5769 if (get_image_size(buf) > 0) {
5770 if (nb_option_roms >= MAX_OPTION_ROMS) {
5771 fprintf(stderr, "Too many option ROMs\n");
5772 exit(1);
5774 option_rom[nb_option_roms] = strdup(buf);
5775 nb_option_roms++;
5776 netroms++;
5780 if (netroms == 0) {
5781 fprintf(stderr, "No valid PXE rom found for network device\n");
5782 exit(1);
5785 #endif
5787 /* init the bluetooth world */
5788 for (i = 0; i < nb_bt_opts; i++)
5789 if (bt_parse(bt_opts[i]))
5790 exit(1);
5792 /* init the memory */
5793 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5795 if (machine->ram_require & RAMSIZE_FIXED) {
5796 if (ram_size > 0) {
5797 if (ram_size < phys_ram_size) {
5798 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5799 machine->name, (unsigned long long) phys_ram_size);
5800 exit(-1);
5803 phys_ram_size = ram_size;
5804 } else
5805 ram_size = phys_ram_size;
5806 } else {
5807 if (ram_size == 0)
5808 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5810 phys_ram_size += ram_size;
5813 /* Initialize kvm */
5814 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5815 #define KVM_EXTRA_PAGES 3
5816 #else
5817 #define KVM_EXTRA_PAGES 0
5818 #endif
5819 if (kvm_enabled()) {
5820 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5821 if (kvm_qemu_create_context() < 0) {
5822 fprintf(stderr, "Could not create KVM context\n");
5823 exit(1);
5827 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5828 if (!phys_ram_base) {
5829 fprintf(stderr, "Could not allocate physical memory\n");
5830 exit(1);
5833 /* init the dynamic translator */
5834 cpu_exec_init_all(tb_size * 1024 * 1024);
5836 bdrv_init();
5837 dma_helper_init();
5839 /* we always create the cdrom drive, even if no disk is there */
5841 if (nb_drives_opt < MAX_DRIVES)
5842 drive_add(NULL, CDROM_ALIAS);
5844 /* we always create at least one floppy */
5846 if (nb_drives_opt < MAX_DRIVES)
5847 drive_add(NULL, FD_ALIAS, 0);
5849 /* we always create one sd slot, even if no card is in it */
5851 if (nb_drives_opt < MAX_DRIVES)
5852 drive_add(NULL, SD_ALIAS);
5854 /* open the virtual block devices
5855 * note that migration with device
5856 * hot add/remove is broken.
5858 for(i = 0; i < nb_drives_opt; i++)
5859 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5860 exit(1);
5862 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5863 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5865 #ifndef _WIN32
5866 /* must be after terminal init, SDL library changes signal handlers */
5867 termsig_setup();
5868 #endif
5870 /* Maintain compatibility with multiple stdio monitors */
5871 if (!strcmp(monitor_device,"stdio")) {
5872 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5873 const char *devname = serial_devices[i];
5874 if (devname && !strcmp(devname,"mon:stdio")) {
5875 monitor_device = NULL;
5876 break;
5877 } else if (devname && !strcmp(devname,"stdio")) {
5878 monitor_device = NULL;
5879 serial_devices[i] = "mon:stdio";
5880 break;
5885 #ifdef KVM_UPSTREAM
5886 if (kvm_enabled()) {
5887 int ret;
5889 ret = kvm_init(smp_cpus);
5890 if (ret < 0) {
5891 fprintf(stderr, "failed to initialize KVM\n");
5892 exit(1);
5895 #endif
5897 if (monitor_device) {
5898 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5899 if (!monitor_hd) {
5900 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5901 exit(1);
5905 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5906 const char *devname = serial_devices[i];
5907 if (devname && strcmp(devname, "none")) {
5908 char label[32];
5909 snprintf(label, sizeof(label), "serial%d", i);
5910 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5911 if (!serial_hds[i]) {
5912 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5913 devname);
5914 exit(1);
5919 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5920 const char *devname = parallel_devices[i];
5921 if (devname && strcmp(devname, "none")) {
5922 char label[32];
5923 snprintf(label, sizeof(label), "parallel%d", i);
5924 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5925 if (!parallel_hds[i]) {
5926 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5927 devname);
5928 exit(1);
5933 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5934 const char *devname = virtio_consoles[i];
5935 if (devname && strcmp(devname, "none")) {
5936 char label[32];
5937 snprintf(label, sizeof(label), "virtcon%d", i);
5938 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5939 if (!virtcon_hds[i]) {
5940 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5941 devname);
5942 exit(1);
5947 if (kvm_enabled())
5948 kvm_init_ap();
5950 machine->init(ram_size, vga_ram_size, boot_devices,
5951 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5953 current_machine = machine;
5955 /* Set KVM's vcpu state to qemu's initial CPUState. */
5956 if (kvm_enabled()) {
5957 int ret;
5959 ret = kvm_sync_vcpus();
5960 if (ret < 0) {
5961 fprintf(stderr, "failed to initialize vcpus\n");
5962 exit(1);
5966 /* init USB devices */
5967 if (usb_enabled) {
5968 for(i = 0; i < usb_devices_index; i++) {
5969 if (usb_device_add(usb_devices[i], 0) < 0) {
5970 fprintf(stderr, "Warning: could not add USB device %s\n",
5971 usb_devices[i]);
5976 if (!display_state)
5977 dumb_display_init();
5978 /* just use the first displaystate for the moment */
5979 ds = display_state;
5980 /* terminal init */
5981 if (nographic) {
5982 if (curses) {
5983 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5984 exit(1);
5986 } else {
5987 #if defined(CONFIG_CURSES)
5988 if (curses) {
5989 /* At the moment curses cannot be used with other displays */
5990 curses_display_init(ds, full_screen);
5991 } else
5992 #endif
5994 if (vnc_display != NULL) {
5995 vnc_display_init(ds);
5996 if (vnc_display_open(ds, vnc_display) < 0)
5997 exit(1);
5999 #if defined(CONFIG_SDL)
6000 if (sdl || !vnc_display)
6001 sdl_display_init(ds, full_screen, no_frame);
6002 #elif defined(CONFIG_COCOA)
6003 if (sdl || !vnc_display)
6004 cocoa_display_init(ds, full_screen);
6005 #endif
6008 dpy_resize(ds);
6010 dcl = ds->listeners;
6011 while (dcl != NULL) {
6012 if (dcl->dpy_refresh != NULL) {
6013 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6014 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6016 dcl = dcl->next;
6019 if (nographic || (vnc_display && !sdl)) {
6020 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6021 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6024 text_consoles_set_display(display_state);
6025 qemu_chr_initial_reset();
6027 if (monitor_device && monitor_hd)
6028 monitor_init(monitor_hd, !nographic);
6030 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6031 const char *devname = serial_devices[i];
6032 if (devname && strcmp(devname, "none")) {
6033 char label[32];
6034 snprintf(label, sizeof(label), "serial%d", i);
6035 if (strstart(devname, "vc", 0))
6036 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6040 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6041 const char *devname = parallel_devices[i];
6042 if (devname && strcmp(devname, "none")) {
6043 char label[32];
6044 snprintf(label, sizeof(label), "parallel%d", i);
6045 if (strstart(devname, "vc", 0))
6046 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6050 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6051 const char *devname = virtio_consoles[i];
6052 if (virtcon_hds[i] && devname) {
6053 char label[32];
6054 snprintf(label, sizeof(label), "virtcon%d", i);
6055 if (strstart(devname, "vc", 0))
6056 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6060 #ifdef CONFIG_GDBSTUB
6061 if (use_gdbstub) {
6062 /* XXX: use standard host:port notation and modify options
6063 accordingly. */
6064 if (gdbserver_start(gdbstub_port) < 0) {
6065 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6066 gdbstub_port);
6067 exit(1);
6070 #endif
6072 if (loadvm)
6073 do_loadvm(loadvm);
6075 if (incoming)
6076 qemu_start_incoming_migration(incoming);
6078 if (autostart)
6079 vm_start();
6081 if (daemonize) {
6082 uint8_t status = 0;
6083 ssize_t len;
6085 again1:
6086 len = write(fds[1], &status, 1);
6087 if (len == -1 && (errno == EINTR))
6088 goto again1;
6090 if (len != 1)
6091 exit(1);
6093 chdir("/");
6094 TFR(fd = open("/dev/null", O_RDWR));
6095 if (fd == -1)
6096 exit(1);
6099 #ifndef _WIN32
6100 if (run_as) {
6101 pwd = getpwnam(run_as);
6102 if (!pwd) {
6103 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6104 exit(1);
6108 if (chroot_dir) {
6109 if (chroot(chroot_dir) < 0) {
6110 fprintf(stderr, "chroot failed\n");
6111 exit(1);
6113 chdir("/");
6116 if (run_as) {
6117 if (setgid(pwd->pw_gid) < 0) {
6118 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6119 exit(1);
6121 if (setuid(pwd->pw_uid) < 0) {
6122 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6123 exit(1);
6125 if (setuid(0) != -1) {
6126 fprintf(stderr, "Dropping privileges failed\n");
6127 exit(1);
6130 #endif
6132 if (daemonize) {
6133 dup2(fd, 0);
6134 dup2(fd, 1);
6135 dup2(fd, 2);
6137 close(fd);
6140 main_loop();
6141 quit_timers();
6142 net_cleanup();
6144 return 0;