Make binary stripping conditional (Riku Voipio)
[qemu-kvm/fedora.git] / vl.c
blob1774d1c8bc80ab46259578615a179259cd3e1597
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "hw/bt.h"
33 #include "net.h"
34 #include "console.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
39 #include "cache-utils.h"
40 #include "block.h"
41 #include "audio/audio.h"
42 #include "hw/device-assignment.h"
43 #include "migration.h"
44 #include "kvm.h"
45 #include "balloon.h"
46 #include "qemu-kvm.h"
48 #include <unistd.h>
49 #include <fcntl.h>
50 #include <signal.h>
51 #include <time.h>
52 #include <errno.h>
53 #include <sys/time.h>
54 #include <zlib.h>
56 #ifndef _WIN32
57 #include <pwd.h>
58 #include <sys/times.h>
59 #include <sys/wait.h>
60 #include <termios.h>
61 #include <sys/mman.h>
62 #include <sys/ioctl.h>
63 #include <sys/resource.h>
64 #include <sys/socket.h>
65 #include <netinet/in.h>
66 #include <net/if.h>
67 #if defined(__NetBSD__)
68 #include <net/if_tap.h>
69 #endif
70 #ifdef __linux__
71 #include <linux/if_tun.h>
72 #endif
73 #include <arpa/inet.h>
74 #include <dirent.h>
75 #include <netdb.h>
76 #include <sys/select.h>
77 #ifdef _BSD
78 #include <sys/stat.h>
79 #ifdef __FreeBSD__
80 #include <libutil.h>
81 #else
82 #include <util.h>
83 #endif
84 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
85 #include <freebsd/stdlib.h>
86 #else
87 #ifdef __linux__
88 #include <pty.h>
89 #include <malloc.h>
90 #include <linux/rtc.h>
92 /* For the benefit of older linux systems which don't supply it,
93 we use a local copy of hpet.h. */
94 /* #include <linux/hpet.h> */
95 #include "hpet.h"
97 #include <linux/ppdev.h>
98 #include <linux/parport.h>
99 #endif
100 #ifdef __sun__
101 #include <sys/stat.h>
102 #include <sys/ethernet.h>
103 #include <sys/sockio.h>
104 #include <netinet/arp.h>
105 #include <netinet/in.h>
106 #include <netinet/in_systm.h>
107 #include <netinet/ip.h>
108 #include <netinet/ip_icmp.h> // must come after ip.h
109 #include <netinet/udp.h>
110 #include <netinet/tcp.h>
111 #include <net/if.h>
112 #include <syslog.h>
113 #include <stropts.h>
114 #endif
115 #endif
116 #endif
118 #include "qemu_socket.h"
120 #if defined(CONFIG_SLIRP)
121 #include "libslirp.h"
122 #endif
124 #if defined(__OpenBSD__)
125 #include <util.h>
126 #endif
128 #if defined(CONFIG_VDE)
129 #include <libvdeplug.h>
130 #endif
132 #ifdef _WIN32
133 #include <malloc.h>
134 #include <sys/timeb.h>
135 #include <mmsystem.h>
136 #define getopt_long_only getopt_long
137 #define memalign(align, size) malloc(size)
138 #endif
140 #ifdef CONFIG_SDL
141 #ifdef __APPLE__
142 #include <SDL/SDL.h>
143 int qemu_main(int argc, char **argv, char **envp);
144 int main(int argc, char **argv)
146 qemu_main(argc, argv, NULL);
148 #undef main
149 #define main qemu_main
150 #endif
151 #endif /* CONFIG_SDL */
153 #ifdef CONFIG_COCOA
154 #undef main
155 #define main qemu_main
156 #endif /* CONFIG_COCOA */
158 #include "disas.h"
160 #include "exec-all.h"
162 #include "qemu-kvm.h"
164 //#define DEBUG_UNUSED_IOPORT
165 //#define DEBUG_IOPORT
166 //#define DEBUG_NET
167 //#define DEBUG_SLIRP
170 #ifdef DEBUG_IOPORT
171 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
172 #else
173 # define LOG_IOPORT(...) do { } while (0)
174 #endif
176 #define DEFAULT_RAM_SIZE 128
178 /* Max number of USB devices that can be specified on the commandline. */
179 #define MAX_USB_CMDLINE 8
181 /* Max number of bluetooth switches on the commandline. */
182 #define MAX_BT_CMDLINE 10
184 /* XXX: use a two level table to limit memory usage */
185 #define MAX_IOPORTS 65536
187 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
188 const char *bios_name = NULL;
189 static void *ioport_opaque[MAX_IOPORTS];
190 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
191 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
192 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
193 to store the VM snapshots */
194 DriveInfo drives_table[MAX_DRIVES+1];
195 int nb_drives;
196 int extboot_drive = -1;
197 static int vga_ram_size;
198 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
199 static DisplayState *display_state;
200 int nographic;
201 static int curses;
202 static int sdl;
203 const char* keyboard_layout = NULL;
204 int64_t ticks_per_sec;
205 ram_addr_t ram_size;
206 int nb_nics;
207 NICInfo nd_table[MAX_NICS];
208 int vm_running;
209 static int autostart;
210 static int rtc_utc = 1;
211 static int rtc_date_offset = -1; /* -1 means no change */
212 int cirrus_vga_enabled = 1;
213 int std_vga_enabled = 0;
214 int vmsvga_enabled = 0;
215 #ifdef TARGET_SPARC
216 int graphic_width = 1024;
217 int graphic_height = 768;
218 int graphic_depth = 8;
219 #else
220 int graphic_width = 800;
221 int graphic_height = 600;
222 int graphic_depth = 15;
223 #endif
224 static int full_screen = 0;
225 #ifdef CONFIG_SDL
226 static int no_frame = 0;
227 #endif
228 int no_quit = 0;
229 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
230 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
231 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
232 #ifdef TARGET_I386
233 int win2k_install_hack = 0;
234 int rtc_td_hack = 0;
235 #endif
236 int usb_enabled = 0;
237 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
238 int assigned_devices_index;
239 int smp_cpus = 1;
240 const char *vnc_display;
241 int acpi_enabled = 1;
242 int no_hpet = 0;
243 int fd_bootchk = 1;
244 int no_reboot = 0;
245 int no_shutdown = 0;
246 int cursor_hide = 1;
247 int graphic_rotate = 0;
248 int daemonize = 0;
249 const char *incoming;
250 const char *option_rom[MAX_OPTION_ROMS];
251 int nb_option_roms;
252 int semihosting_enabled = 0;
253 int time_drift_fix = 0;
254 unsigned int kvm_shadow_memory = 0;
255 const char *mem_path = NULL;
256 #ifdef MAP_POPULATE
257 int mem_prealloc = 1; /* force preallocation of physical target memory */
258 #endif
259 int hpagesize = 0;
260 const char *cpu_vendor_string;
261 #ifdef TARGET_ARM
262 int old_param = 0;
263 #endif
264 const char *qemu_name;
265 int alt_grab = 0;
266 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
267 unsigned int nb_prom_envs = 0;
268 const char *prom_envs[MAX_PROM_ENVS];
269 #endif
270 int nb_drives_opt;
271 const char *nvram = NULL;
272 struct drive_opt drives_opt[MAX_DRIVES];
274 static CPUState *cur_cpu;
275 static CPUState *next_cpu;
276 static int event_pending = 1;
277 /* Conversion factor from emulated instructions to virtual clock ticks. */
278 static int icount_time_shift;
279 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
280 #define MAX_ICOUNT_SHIFT 10
281 /* Compensate for varying guest execution speed. */
282 static int64_t qemu_icount_bias;
283 static QEMUTimer *icount_rt_timer;
284 static QEMUTimer *icount_vm_timer;
285 static QEMUTimer *nographic_timer;
287 uint8_t qemu_uuid[16];
289 /* KVM runs the main loop in a separate thread. If we update one of the lists
290 * that are polled before or after select(), we need to make sure to break out
291 * of the select() to ensure the new item is serviced.
293 static void main_loop_break(void)
295 if (kvm_enabled())
296 qemu_kvm_notify_work();
299 /***********************************************************/
300 /* x86 ISA bus support */
302 target_phys_addr_t isa_mem_base = 0;
303 PicState2 *isa_pic;
305 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
306 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
308 static uint32_t ioport_read(int index, uint32_t address)
310 static IOPortReadFunc *default_func[3] = {
311 default_ioport_readb,
312 default_ioport_readw,
313 default_ioport_readl
315 IOPortReadFunc *func = ioport_read_table[index][address];
316 if (!func)
317 func = default_func[index];
318 return func(ioport_opaque[address], address);
321 static void ioport_write(int index, uint32_t address, uint32_t data)
323 static IOPortWriteFunc *default_func[3] = {
324 default_ioport_writeb,
325 default_ioport_writew,
326 default_ioport_writel
328 IOPortWriteFunc *func = ioport_write_table[index][address];
329 if (!func)
330 func = default_func[index];
331 func(ioport_opaque[address], address, data);
334 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
336 #ifdef DEBUG_UNUSED_IOPORT
337 fprintf(stderr, "unused inb: port=0x%04x\n", address);
338 #endif
339 return 0xff;
342 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
344 #ifdef DEBUG_UNUSED_IOPORT
345 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
346 #endif
349 /* default is to make two byte accesses */
350 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
352 uint32_t data;
353 data = ioport_read(0, address);
354 address = (address + 1) & (MAX_IOPORTS - 1);
355 data |= ioport_read(0, address) << 8;
356 return data;
359 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
361 ioport_write(0, address, data & 0xff);
362 address = (address + 1) & (MAX_IOPORTS - 1);
363 ioport_write(0, address, (data >> 8) & 0xff);
366 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
368 #ifdef DEBUG_UNUSED_IOPORT
369 fprintf(stderr, "unused inl: port=0x%04x\n", address);
370 #endif
371 return 0xffffffff;
374 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
376 #ifdef DEBUG_UNUSED_IOPORT
377 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
378 #endif
381 /* size is the word size in byte */
382 int register_ioport_read(int start, int length, int size,
383 IOPortReadFunc *func, void *opaque)
385 int i, bsize;
387 if (size == 1) {
388 bsize = 0;
389 } else if (size == 2) {
390 bsize = 1;
391 } else if (size == 4) {
392 bsize = 2;
393 } else {
394 hw_error("register_ioport_read: invalid size");
395 return -1;
397 for(i = start; i < start + length; i += size) {
398 ioport_read_table[bsize][i] = func;
399 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
400 hw_error("register_ioport_read: invalid opaque");
401 ioport_opaque[i] = opaque;
403 return 0;
406 /* size is the word size in byte */
407 int register_ioport_write(int start, int length, int size,
408 IOPortWriteFunc *func, void *opaque)
410 int i, bsize;
412 if (size == 1) {
413 bsize = 0;
414 } else if (size == 2) {
415 bsize = 1;
416 } else if (size == 4) {
417 bsize = 2;
418 } else {
419 hw_error("register_ioport_write: invalid size");
420 return -1;
422 for(i = start; i < start + length; i += size) {
423 ioport_write_table[bsize][i] = func;
424 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
425 hw_error("register_ioport_write: invalid opaque");
426 ioport_opaque[i] = opaque;
428 return 0;
431 void isa_unassign_ioport(int start, int length)
433 int i;
435 for(i = start; i < start + length; i++) {
436 ioport_read_table[0][i] = default_ioport_readb;
437 ioport_read_table[1][i] = default_ioport_readw;
438 ioport_read_table[2][i] = default_ioport_readl;
440 ioport_write_table[0][i] = default_ioport_writeb;
441 ioport_write_table[1][i] = default_ioport_writew;
442 ioport_write_table[2][i] = default_ioport_writel;
444 ioport_opaque[i] = NULL;
448 /***********************************************************/
450 void cpu_outb(CPUState *env, int addr, int val)
452 LOG_IOPORT("outb: %04x %02x\n", addr, val);
453 ioport_write(0, addr, val);
454 #ifdef USE_KQEMU
455 if (env)
456 env->last_io_time = cpu_get_time_fast();
457 #endif
460 void cpu_outw(CPUState *env, int addr, int val)
462 LOG_IOPORT("outw: %04x %04x\n", addr, val);
463 ioport_write(1, addr, val);
464 #ifdef USE_KQEMU
465 if (env)
466 env->last_io_time = cpu_get_time_fast();
467 #endif
470 void cpu_outl(CPUState *env, int addr, int val)
472 LOG_IOPORT("outl: %04x %08x\n", addr, val);
473 ioport_write(2, addr, val);
474 #ifdef USE_KQEMU
475 if (env)
476 env->last_io_time = cpu_get_time_fast();
477 #endif
480 int cpu_inb(CPUState *env, int addr)
482 int val;
483 val = ioport_read(0, addr);
484 LOG_IOPORT("inb : %04x %02x\n", addr, val);
485 #ifdef USE_KQEMU
486 if (env)
487 env->last_io_time = cpu_get_time_fast();
488 #endif
489 return val;
492 int cpu_inw(CPUState *env, int addr)
494 int val;
495 val = ioport_read(1, addr);
496 LOG_IOPORT("inw : %04x %04x\n", addr, val);
497 #ifdef USE_KQEMU
498 if (env)
499 env->last_io_time = cpu_get_time_fast();
500 #endif
501 return val;
504 int cpu_inl(CPUState *env, int addr)
506 int val;
507 val = ioport_read(2, addr);
508 LOG_IOPORT("inl : %04x %08x\n", addr, val);
509 #ifdef USE_KQEMU
510 if (env)
511 env->last_io_time = cpu_get_time_fast();
512 #endif
513 return val;
516 /***********************************************************/
517 void hw_error(const char *fmt, ...)
519 va_list ap;
520 CPUState *env;
522 va_start(ap, fmt);
523 fprintf(stderr, "qemu: hardware error: ");
524 vfprintf(stderr, fmt, ap);
525 fprintf(stderr, "\n");
526 for(env = first_cpu; env != NULL; env = env->next_cpu) {
527 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
528 #ifdef TARGET_I386
529 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
530 #else
531 cpu_dump_state(env, stderr, fprintf, 0);
532 #endif
534 va_end(ap);
535 abort();
538 /***************/
539 /* ballooning */
541 static QEMUBalloonEvent *qemu_balloon_event;
542 void *qemu_balloon_event_opaque;
544 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
546 qemu_balloon_event = func;
547 qemu_balloon_event_opaque = opaque;
550 void qemu_balloon(ram_addr_t target)
552 if (qemu_balloon_event)
553 qemu_balloon_event(qemu_balloon_event_opaque, target);
556 ram_addr_t qemu_balloon_status(void)
558 if (qemu_balloon_event)
559 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
560 return 0;
563 /***********************************************************/
564 /* keyboard/mouse */
566 static QEMUPutKBDEvent *qemu_put_kbd_event;
567 static void *qemu_put_kbd_event_opaque;
568 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
569 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
571 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
573 qemu_put_kbd_event_opaque = opaque;
574 qemu_put_kbd_event = func;
577 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
578 void *opaque, int absolute,
579 const char *name)
581 QEMUPutMouseEntry *s, *cursor;
583 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
585 s->qemu_put_mouse_event = func;
586 s->qemu_put_mouse_event_opaque = opaque;
587 s->qemu_put_mouse_event_absolute = absolute;
588 s->qemu_put_mouse_event_name = qemu_strdup(name);
589 s->next = NULL;
591 if (!qemu_put_mouse_event_head) {
592 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
593 return s;
596 cursor = qemu_put_mouse_event_head;
597 while (cursor->next != NULL)
598 cursor = cursor->next;
600 cursor->next = s;
601 qemu_put_mouse_event_current = s;
603 return s;
606 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
608 QEMUPutMouseEntry *prev = NULL, *cursor;
610 if (!qemu_put_mouse_event_head || entry == NULL)
611 return;
613 cursor = qemu_put_mouse_event_head;
614 while (cursor != NULL && cursor != entry) {
615 prev = cursor;
616 cursor = cursor->next;
619 if (cursor == NULL) // does not exist or list empty
620 return;
621 else if (prev == NULL) { // entry is head
622 qemu_put_mouse_event_head = cursor->next;
623 if (qemu_put_mouse_event_current == entry)
624 qemu_put_mouse_event_current = cursor->next;
625 qemu_free(entry->qemu_put_mouse_event_name);
626 qemu_free(entry);
627 return;
630 prev->next = entry->next;
632 if (qemu_put_mouse_event_current == entry)
633 qemu_put_mouse_event_current = prev;
635 qemu_free(entry->qemu_put_mouse_event_name);
636 qemu_free(entry);
639 void kbd_put_keycode(int keycode)
641 if (qemu_put_kbd_event) {
642 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
646 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
648 QEMUPutMouseEvent *mouse_event;
649 void *mouse_event_opaque;
650 int width;
652 if (!qemu_put_mouse_event_current) {
653 return;
656 mouse_event =
657 qemu_put_mouse_event_current->qemu_put_mouse_event;
658 mouse_event_opaque =
659 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
661 if (mouse_event) {
662 if (graphic_rotate) {
663 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
664 width = 0x7fff;
665 else
666 width = graphic_width - 1;
667 mouse_event(mouse_event_opaque,
668 width - dy, dx, dz, buttons_state);
669 } else
670 mouse_event(mouse_event_opaque,
671 dx, dy, dz, buttons_state);
675 int kbd_mouse_is_absolute(void)
677 if (!qemu_put_mouse_event_current)
678 return 0;
680 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
683 void do_info_mice(void)
685 QEMUPutMouseEntry *cursor;
686 int index = 0;
688 if (!qemu_put_mouse_event_head) {
689 term_printf("No mouse devices connected\n");
690 return;
693 term_printf("Mouse devices available:\n");
694 cursor = qemu_put_mouse_event_head;
695 while (cursor != NULL) {
696 term_printf("%c Mouse #%d: %s\n",
697 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
698 index, cursor->qemu_put_mouse_event_name);
699 index++;
700 cursor = cursor->next;
704 void do_mouse_set(int index)
706 QEMUPutMouseEntry *cursor;
707 int i = 0;
709 if (!qemu_put_mouse_event_head) {
710 term_printf("No mouse devices connected\n");
711 return;
714 cursor = qemu_put_mouse_event_head;
715 while (cursor != NULL && index != i) {
716 i++;
717 cursor = cursor->next;
720 if (cursor != NULL)
721 qemu_put_mouse_event_current = cursor;
722 else
723 term_printf("Mouse at given index not found\n");
726 /* compute with 96 bit intermediate result: (a*b)/c */
727 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
729 union {
730 uint64_t ll;
731 struct {
732 #ifdef WORDS_BIGENDIAN
733 uint32_t high, low;
734 #else
735 uint32_t low, high;
736 #endif
737 } l;
738 } u, res;
739 uint64_t rl, rh;
741 u.ll = a;
742 rl = (uint64_t)u.l.low * (uint64_t)b;
743 rh = (uint64_t)u.l.high * (uint64_t)b;
744 rh += (rl >> 32);
745 res.l.high = rh / c;
746 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
747 return res.ll;
750 /***********************************************************/
751 /* real time host monotonic timer */
753 #define QEMU_TIMER_BASE 1000000000LL
755 #ifdef WIN32
757 static int64_t clock_freq;
759 static void init_get_clock(void)
761 LARGE_INTEGER freq;
762 int ret;
763 ret = QueryPerformanceFrequency(&freq);
764 if (ret == 0) {
765 fprintf(stderr, "Could not calibrate ticks\n");
766 exit(1);
768 clock_freq = freq.QuadPart;
771 static int64_t get_clock(void)
773 LARGE_INTEGER ti;
774 QueryPerformanceCounter(&ti);
775 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
778 #else
780 static int use_rt_clock;
782 static void init_get_clock(void)
784 use_rt_clock = 0;
785 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
787 struct timespec ts;
788 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
789 use_rt_clock = 1;
792 #endif
795 static int64_t get_clock(void)
797 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
798 if (use_rt_clock) {
799 struct timespec ts;
800 clock_gettime(CLOCK_MONOTONIC, &ts);
801 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
802 } else
803 #endif
805 /* XXX: using gettimeofday leads to problems if the date
806 changes, so it should be avoided. */
807 struct timeval tv;
808 gettimeofday(&tv, NULL);
809 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
812 #endif
814 /* Return the virtual CPU time, based on the instruction counter. */
815 static int64_t cpu_get_icount(void)
817 int64_t icount;
818 CPUState *env = cpu_single_env;;
819 icount = qemu_icount;
820 if (env) {
821 if (!can_do_io(env))
822 fprintf(stderr, "Bad clock read\n");
823 icount -= (env->icount_decr.u16.low + env->icount_extra);
825 return qemu_icount_bias + (icount << icount_time_shift);
828 /***********************************************************/
829 /* guest cycle counter */
831 static int64_t cpu_ticks_prev;
832 static int64_t cpu_ticks_offset;
833 static int64_t cpu_clock_offset;
834 static int cpu_ticks_enabled;
836 /* return the host CPU cycle counter and handle stop/restart */
837 int64_t cpu_get_ticks(void)
839 if (use_icount) {
840 return cpu_get_icount();
842 if (!cpu_ticks_enabled) {
843 return cpu_ticks_offset;
844 } else {
845 int64_t ticks;
846 ticks = cpu_get_real_ticks();
847 if (cpu_ticks_prev > ticks) {
848 /* Note: non increasing ticks may happen if the host uses
849 software suspend */
850 cpu_ticks_offset += cpu_ticks_prev - ticks;
852 cpu_ticks_prev = ticks;
853 return ticks + cpu_ticks_offset;
857 /* return the host CPU monotonic timer and handle stop/restart */
858 static int64_t cpu_get_clock(void)
860 int64_t ti;
861 if (!cpu_ticks_enabled) {
862 return cpu_clock_offset;
863 } else {
864 ti = get_clock();
865 return ti + cpu_clock_offset;
869 /* enable cpu_get_ticks() */
870 void cpu_enable_ticks(void)
872 if (!cpu_ticks_enabled) {
873 cpu_ticks_offset -= cpu_get_real_ticks();
874 cpu_clock_offset -= get_clock();
875 cpu_ticks_enabled = 1;
879 /* disable cpu_get_ticks() : the clock is stopped. You must not call
880 cpu_get_ticks() after that. */
881 void cpu_disable_ticks(void)
883 if (cpu_ticks_enabled) {
884 cpu_ticks_offset = cpu_get_ticks();
885 cpu_clock_offset = cpu_get_clock();
886 cpu_ticks_enabled = 0;
890 /***********************************************************/
891 /* timers */
893 #define QEMU_TIMER_REALTIME 0
894 #define QEMU_TIMER_VIRTUAL 1
896 struct QEMUClock {
897 int type;
898 /* XXX: add frequency */
901 struct QEMUTimer {
902 QEMUClock *clock;
903 int64_t expire_time;
904 QEMUTimerCB *cb;
905 void *opaque;
906 struct QEMUTimer *next;
909 struct qemu_alarm_timer {
910 char const *name;
911 unsigned int flags;
913 int (*start)(struct qemu_alarm_timer *t);
914 void (*stop)(struct qemu_alarm_timer *t);
915 void (*rearm)(struct qemu_alarm_timer *t);
916 void *priv;
919 #define ALARM_FLAG_DYNTICKS 0x1
920 #define ALARM_FLAG_EXPIRED 0x2
922 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
924 return t && (t->flags & ALARM_FLAG_DYNTICKS);
927 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
929 if (!alarm_has_dynticks(t))
930 return;
932 t->rearm(t);
935 /* TODO: MIN_TIMER_REARM_US should be optimized */
936 #define MIN_TIMER_REARM_US 250
938 static struct qemu_alarm_timer *alarm_timer;
939 #ifndef _WIN32
940 static int alarm_timer_rfd, alarm_timer_wfd;
941 #endif
943 #ifdef _WIN32
945 struct qemu_alarm_win32 {
946 MMRESULT timerId;
947 HANDLE host_alarm;
948 unsigned int period;
949 } alarm_win32_data = {0, NULL, -1};
951 static int win32_start_timer(struct qemu_alarm_timer *t);
952 static void win32_stop_timer(struct qemu_alarm_timer *t);
953 static void win32_rearm_timer(struct qemu_alarm_timer *t);
955 #else
957 static int unix_start_timer(struct qemu_alarm_timer *t);
958 static void unix_stop_timer(struct qemu_alarm_timer *t);
960 #ifdef __linux__
962 static int dynticks_start_timer(struct qemu_alarm_timer *t);
963 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
964 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
966 static int hpet_start_timer(struct qemu_alarm_timer *t);
967 static void hpet_stop_timer(struct qemu_alarm_timer *t);
969 static int rtc_start_timer(struct qemu_alarm_timer *t);
970 static void rtc_stop_timer(struct qemu_alarm_timer *t);
972 #endif /* __linux__ */
974 #endif /* _WIN32 */
976 /* Correlation between real and virtual time is always going to be
977 fairly approximate, so ignore small variation.
978 When the guest is idle real and virtual time will be aligned in
979 the IO wait loop. */
980 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
982 static void icount_adjust(void)
984 int64_t cur_time;
985 int64_t cur_icount;
986 int64_t delta;
987 static int64_t last_delta;
988 /* If the VM is not running, then do nothing. */
989 if (!vm_running)
990 return;
992 cur_time = cpu_get_clock();
993 cur_icount = qemu_get_clock(vm_clock);
994 delta = cur_icount - cur_time;
995 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
996 if (delta > 0
997 && last_delta + ICOUNT_WOBBLE < delta * 2
998 && icount_time_shift > 0) {
999 /* The guest is getting too far ahead. Slow time down. */
1000 icount_time_shift--;
1002 if (delta < 0
1003 && last_delta - ICOUNT_WOBBLE > delta * 2
1004 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1005 /* The guest is getting too far behind. Speed time up. */
1006 icount_time_shift++;
1008 last_delta = delta;
1009 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1012 static void icount_adjust_rt(void * opaque)
1014 qemu_mod_timer(icount_rt_timer,
1015 qemu_get_clock(rt_clock) + 1000);
1016 icount_adjust();
1019 static void icount_adjust_vm(void * opaque)
1021 qemu_mod_timer(icount_vm_timer,
1022 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1023 icount_adjust();
1026 static void init_icount_adjust(void)
1028 /* Have both realtime and virtual time triggers for speed adjustment.
1029 The realtime trigger catches emulated time passing too slowly,
1030 the virtual time trigger catches emulated time passing too fast.
1031 Realtime triggers occur even when idle, so use them less frequently
1032 than VM triggers. */
1033 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1034 qemu_mod_timer(icount_rt_timer,
1035 qemu_get_clock(rt_clock) + 1000);
1036 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1037 qemu_mod_timer(icount_vm_timer,
1038 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1041 static struct qemu_alarm_timer alarm_timers[] = {
1042 #ifndef _WIN32
1043 #ifdef __linux__
1044 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1045 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1046 /* HPET - if available - is preferred */
1047 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1048 /* ...otherwise try RTC */
1049 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1050 #endif
1051 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1052 #else
1053 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1054 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1055 {"win32", 0, win32_start_timer,
1056 win32_stop_timer, NULL, &alarm_win32_data},
1057 #endif
1058 {NULL, }
1061 static void show_available_alarms(void)
1063 int i;
1065 printf("Available alarm timers, in order of precedence:\n");
1066 for (i = 0; alarm_timers[i].name; i++)
1067 printf("%s\n", alarm_timers[i].name);
1070 static void configure_alarms(char const *opt)
1072 int i;
1073 int cur = 0;
1074 int count = ARRAY_SIZE(alarm_timers) - 1;
1075 char *arg;
1076 char *name;
1077 struct qemu_alarm_timer tmp;
1079 if (!strcmp(opt, "?")) {
1080 show_available_alarms();
1081 exit(0);
1084 arg = strdup(opt);
1086 /* Reorder the array */
1087 name = strtok(arg, ",");
1088 while (name) {
1089 for (i = 0; i < count && alarm_timers[i].name; i++) {
1090 if (!strcmp(alarm_timers[i].name, name))
1091 break;
1094 if (i == count) {
1095 fprintf(stderr, "Unknown clock %s\n", name);
1096 goto next;
1099 if (i < cur)
1100 /* Ignore */
1101 goto next;
1103 /* Swap */
1104 tmp = alarm_timers[i];
1105 alarm_timers[i] = alarm_timers[cur];
1106 alarm_timers[cur] = tmp;
1108 cur++;
1109 next:
1110 name = strtok(NULL, ",");
1113 free(arg);
1115 if (cur) {
1116 /* Disable remaining timers */
1117 for (i = cur; i < count; i++)
1118 alarm_timers[i].name = NULL;
1119 } else {
1120 show_available_alarms();
1121 exit(1);
1125 QEMUClock *rt_clock;
1126 QEMUClock *vm_clock;
1128 static QEMUTimer *active_timers[2];
1130 static QEMUClock *qemu_new_clock(int type)
1132 QEMUClock *clock;
1133 clock = qemu_mallocz(sizeof(QEMUClock));
1134 clock->type = type;
1135 return clock;
1138 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1140 QEMUTimer *ts;
1142 ts = qemu_mallocz(sizeof(QEMUTimer));
1143 ts->clock = clock;
1144 ts->cb = cb;
1145 ts->opaque = opaque;
1146 return ts;
1149 void qemu_free_timer(QEMUTimer *ts)
1151 qemu_free(ts);
1154 /* stop a timer, but do not dealloc it */
1155 void qemu_del_timer(QEMUTimer *ts)
1157 QEMUTimer **pt, *t;
1159 /* NOTE: this code must be signal safe because
1160 qemu_timer_expired() can be called from a signal. */
1161 pt = &active_timers[ts->clock->type];
1162 for(;;) {
1163 t = *pt;
1164 if (!t)
1165 break;
1166 if (t == ts) {
1167 *pt = t->next;
1168 break;
1170 pt = &t->next;
1174 /* modify the current timer so that it will be fired when current_time
1175 >= expire_time. The corresponding callback will be called. */
1176 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1178 QEMUTimer **pt, *t;
1180 qemu_del_timer(ts);
1182 /* add the timer in the sorted list */
1183 /* NOTE: this code must be signal safe because
1184 qemu_timer_expired() can be called from a signal. */
1185 pt = &active_timers[ts->clock->type];
1186 for(;;) {
1187 t = *pt;
1188 if (!t)
1189 break;
1190 if (t->expire_time > expire_time)
1191 break;
1192 pt = &t->next;
1194 ts->expire_time = expire_time;
1195 ts->next = *pt;
1196 *pt = ts;
1198 /* Rearm if necessary */
1199 if (pt == &active_timers[ts->clock->type]) {
1200 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1201 qemu_rearm_alarm_timer(alarm_timer);
1203 /* Interrupt execution to force deadline recalculation. */
1204 if (use_icount && cpu_single_env) {
1205 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1210 int qemu_timer_pending(QEMUTimer *ts)
1212 QEMUTimer *t;
1213 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1214 if (t == ts)
1215 return 1;
1217 return 0;
1220 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1222 if (!timer_head)
1223 return 0;
1224 return (timer_head->expire_time <= current_time);
1227 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1229 QEMUTimer *ts;
1231 for(;;) {
1232 ts = *ptimer_head;
1233 if (!ts || ts->expire_time > current_time)
1234 break;
1235 /* remove timer from the list before calling the callback */
1236 *ptimer_head = ts->next;
1237 ts->next = NULL;
1239 /* run the callback (the timer list can be modified) */
1240 ts->cb(ts->opaque);
1244 int64_t qemu_get_clock(QEMUClock *clock)
1246 switch(clock->type) {
1247 case QEMU_TIMER_REALTIME:
1248 return get_clock() / 1000000;
1249 default:
1250 case QEMU_TIMER_VIRTUAL:
1251 if (use_icount) {
1252 return cpu_get_icount();
1253 } else {
1254 return cpu_get_clock();
1259 static void init_timers(void)
1261 init_get_clock();
1262 ticks_per_sec = QEMU_TIMER_BASE;
1263 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1264 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1267 /* save a timer */
1268 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1270 uint64_t expire_time;
1272 if (qemu_timer_pending(ts)) {
1273 expire_time = ts->expire_time;
1274 } else {
1275 expire_time = -1;
1277 qemu_put_be64(f, expire_time);
1280 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1282 uint64_t expire_time;
1284 expire_time = qemu_get_be64(f);
1285 if (expire_time != -1) {
1286 qemu_mod_timer(ts, expire_time);
1287 } else {
1288 qemu_del_timer(ts);
1292 static void timer_save(QEMUFile *f, void *opaque)
1294 if (cpu_ticks_enabled) {
1295 hw_error("cannot save state if virtual timers are running");
1297 qemu_put_be64(f, cpu_ticks_offset);
1298 qemu_put_be64(f, ticks_per_sec);
1299 qemu_put_be64(f, cpu_clock_offset);
1302 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1304 if (version_id != 1 && version_id != 2)
1305 return -EINVAL;
1306 if (cpu_ticks_enabled) {
1307 return -EINVAL;
1309 cpu_ticks_offset=qemu_get_be64(f);
1310 ticks_per_sec=qemu_get_be64(f);
1311 if (version_id == 2) {
1312 cpu_clock_offset=qemu_get_be64(f);
1314 return 0;
1317 #ifdef _WIN32
1318 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1319 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1320 #else
1321 static void host_alarm_handler(int host_signum)
1322 #endif
1324 #if 0
1325 #define DISP_FREQ 1000
1327 static int64_t delta_min = INT64_MAX;
1328 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1329 static int count;
1330 ti = qemu_get_clock(vm_clock);
1331 if (last_clock != 0) {
1332 delta = ti - last_clock;
1333 if (delta < delta_min)
1334 delta_min = delta;
1335 if (delta > delta_max)
1336 delta_max = delta;
1337 delta_cum += delta;
1338 if (++count == DISP_FREQ) {
1339 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1340 muldiv64(delta_min, 1000000, ticks_per_sec),
1341 muldiv64(delta_max, 1000000, ticks_per_sec),
1342 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1343 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1344 count = 0;
1345 delta_min = INT64_MAX;
1346 delta_max = 0;
1347 delta_cum = 0;
1350 last_clock = ti;
1352 #endif
1353 if (1 ||
1354 alarm_has_dynticks(alarm_timer) ||
1355 (!use_icount &&
1356 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1357 qemu_get_clock(vm_clock))) ||
1358 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1359 qemu_get_clock(rt_clock))) {
1360 CPUState *env = next_cpu;
1362 #ifdef _WIN32
1363 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1364 SetEvent(data->host_alarm);
1365 #else
1366 static const char byte = 0;
1367 write(alarm_timer_wfd, &byte, sizeof(byte));
1368 #endif
1369 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1371 if (env) {
1372 /* stop the currently executing cpu because a timer occured */
1373 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1374 #ifdef USE_KQEMU
1375 if (env->kqemu_enabled) {
1376 kqemu_cpu_interrupt(env);
1378 #endif
1380 event_pending = 1;
1384 static int64_t qemu_next_deadline(void)
1386 int64_t delta;
1388 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1389 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1390 qemu_get_clock(vm_clock);
1391 } else {
1392 /* To avoid problems with overflow limit this to 2^32. */
1393 delta = INT32_MAX;
1396 if (delta < 0)
1397 delta = 0;
1399 return delta;
1402 #if defined(__linux__) || defined(_WIN32)
1403 static uint64_t qemu_next_deadline_dyntick(void)
1405 int64_t delta;
1406 int64_t rtdelta;
1408 if (use_icount)
1409 delta = INT32_MAX;
1410 else
1411 delta = (qemu_next_deadline() + 999) / 1000;
1413 if (active_timers[QEMU_TIMER_REALTIME]) {
1414 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1415 qemu_get_clock(rt_clock))*1000;
1416 if (rtdelta < delta)
1417 delta = rtdelta;
1420 if (delta < MIN_TIMER_REARM_US)
1421 delta = MIN_TIMER_REARM_US;
1423 return delta;
1425 #endif
1427 #ifndef _WIN32
1429 /* Sets a specific flag */
1430 static int fcntl_setfl(int fd, int flag)
1432 int flags;
1434 flags = fcntl(fd, F_GETFL);
1435 if (flags == -1)
1436 return -errno;
1438 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1439 return -errno;
1441 return 0;
1444 #if defined(__linux__)
1446 #define RTC_FREQ 1024
1448 static void enable_sigio_timer(int fd)
1450 struct sigaction act;
1452 /* timer signal */
1453 sigfillset(&act.sa_mask);
1454 act.sa_flags = 0;
1455 act.sa_handler = host_alarm_handler;
1457 sigaction(SIGIO, &act, NULL);
1458 fcntl_setfl(fd, O_ASYNC);
1459 fcntl(fd, F_SETOWN, getpid());
1462 static int hpet_start_timer(struct qemu_alarm_timer *t)
1464 struct hpet_info info;
1465 int r, fd;
1467 fd = open("/dev/hpet", O_RDONLY);
1468 if (fd < 0)
1469 return -1;
1471 /* Set frequency */
1472 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1473 if (r < 0) {
1474 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1475 "error, but for better emulation accuracy type:\n"
1476 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1477 goto fail;
1480 /* Check capabilities */
1481 r = ioctl(fd, HPET_INFO, &info);
1482 if (r < 0)
1483 goto fail;
1485 /* Enable periodic mode */
1486 r = ioctl(fd, HPET_EPI, 0);
1487 if (info.hi_flags && (r < 0))
1488 goto fail;
1490 /* Enable interrupt */
1491 r = ioctl(fd, HPET_IE_ON, 0);
1492 if (r < 0)
1493 goto fail;
1495 enable_sigio_timer(fd);
1496 t->priv = (void *)(long)fd;
1498 return 0;
1499 fail:
1500 close(fd);
1501 return -1;
1504 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1506 int fd = (long)t->priv;
1508 close(fd);
1511 static int rtc_start_timer(struct qemu_alarm_timer *t)
1513 int rtc_fd;
1514 unsigned long current_rtc_freq = 0;
1516 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1517 if (rtc_fd < 0)
1518 return -1;
1519 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1520 if (current_rtc_freq != RTC_FREQ &&
1521 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1522 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1523 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1524 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1525 goto fail;
1527 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1528 fail:
1529 close(rtc_fd);
1530 return -1;
1533 enable_sigio_timer(rtc_fd);
1535 t->priv = (void *)(long)rtc_fd;
1537 return 0;
1540 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1542 int rtc_fd = (long)t->priv;
1544 close(rtc_fd);
1547 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1549 struct sigevent ev;
1550 timer_t host_timer;
1551 struct sigaction act;
1553 sigfillset(&act.sa_mask);
1554 act.sa_flags = 0;
1555 act.sa_handler = host_alarm_handler;
1557 sigaction(SIGALRM, &act, NULL);
1560 * Initialize ev struct to 0 to avoid valgrind complaining
1561 * about uninitialized data in timer_create call
1563 memset(&ev, 0, sizeof(ev));
1564 ev.sigev_value.sival_int = 0;
1565 ev.sigev_notify = SIGEV_SIGNAL;
1566 ev.sigev_signo = SIGALRM;
1568 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1569 perror("timer_create");
1571 /* disable dynticks */
1572 fprintf(stderr, "Dynamic Ticks disabled\n");
1574 return -1;
1577 t->priv = (void *)(long)host_timer;
1579 return 0;
1582 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1584 timer_t host_timer = (timer_t)(long)t->priv;
1586 timer_delete(host_timer);
1589 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1591 timer_t host_timer = (timer_t)(long)t->priv;
1592 struct itimerspec timeout;
1593 int64_t nearest_delta_us = INT64_MAX;
1594 int64_t current_us;
1596 if (!active_timers[QEMU_TIMER_REALTIME] &&
1597 !active_timers[QEMU_TIMER_VIRTUAL])
1598 return;
1600 nearest_delta_us = qemu_next_deadline_dyntick();
1602 /* check whether a timer is already running */
1603 if (timer_gettime(host_timer, &timeout)) {
1604 perror("gettime");
1605 fprintf(stderr, "Internal timer error: aborting\n");
1606 exit(1);
1608 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1609 if (current_us && current_us <= nearest_delta_us)
1610 return;
1612 timeout.it_interval.tv_sec = 0;
1613 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1614 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1615 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1616 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1617 perror("settime");
1618 fprintf(stderr, "Internal timer error: aborting\n");
1619 exit(1);
1623 #endif /* defined(__linux__) */
1625 static int unix_start_timer(struct qemu_alarm_timer *t)
1627 struct sigaction act;
1628 struct itimerval itv;
1629 int err;
1631 /* timer signal */
1632 sigfillset(&act.sa_mask);
1633 act.sa_flags = 0;
1634 act.sa_handler = host_alarm_handler;
1636 sigaction(SIGALRM, &act, NULL);
1638 itv.it_interval.tv_sec = 0;
1639 /* for i386 kernel 2.6 to get 1 ms */
1640 itv.it_interval.tv_usec = 999;
1641 itv.it_value.tv_sec = 0;
1642 itv.it_value.tv_usec = 10 * 1000;
1644 err = setitimer(ITIMER_REAL, &itv, NULL);
1645 if (err)
1646 return -1;
1648 return 0;
1651 static void unix_stop_timer(struct qemu_alarm_timer *t)
1653 struct itimerval itv;
1655 memset(&itv, 0, sizeof(itv));
1656 setitimer(ITIMER_REAL, &itv, NULL);
1659 #endif /* !defined(_WIN32) */
1661 static void try_to_rearm_timer(void *opaque)
1663 struct qemu_alarm_timer *t = opaque;
1664 #ifndef _WIN32
1665 ssize_t len;
1667 /* Drain the notify pipe */
1668 do {
1669 char buffer[512];
1670 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1671 } while ((len == -1 && errno == EINTR) || len > 0);
1672 #endif
1674 if (t->flags & ALARM_FLAG_EXPIRED) {
1675 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1676 qemu_rearm_alarm_timer(alarm_timer);
1680 #ifdef _WIN32
1682 static int win32_start_timer(struct qemu_alarm_timer *t)
1684 TIMECAPS tc;
1685 struct qemu_alarm_win32 *data = t->priv;
1686 UINT flags;
1688 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1689 if (!data->host_alarm) {
1690 perror("Failed CreateEvent");
1691 return -1;
1694 memset(&tc, 0, sizeof(tc));
1695 timeGetDevCaps(&tc, sizeof(tc));
1697 if (data->period < tc.wPeriodMin)
1698 data->period = tc.wPeriodMin;
1700 timeBeginPeriod(data->period);
1702 flags = TIME_CALLBACK_FUNCTION;
1703 if (alarm_has_dynticks(t))
1704 flags |= TIME_ONESHOT;
1705 else
1706 flags |= TIME_PERIODIC;
1708 data->timerId = timeSetEvent(1, // interval (ms)
1709 data->period, // resolution
1710 host_alarm_handler, // function
1711 (DWORD)t, // parameter
1712 flags);
1714 if (!data->timerId) {
1715 perror("Failed to initialize win32 alarm timer");
1717 timeEndPeriod(data->period);
1718 CloseHandle(data->host_alarm);
1719 return -1;
1722 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1724 return 0;
1727 static void win32_stop_timer(struct qemu_alarm_timer *t)
1729 struct qemu_alarm_win32 *data = t->priv;
1731 timeKillEvent(data->timerId);
1732 timeEndPeriod(data->period);
1734 CloseHandle(data->host_alarm);
1737 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1739 struct qemu_alarm_win32 *data = t->priv;
1740 uint64_t nearest_delta_us;
1742 if (!active_timers[QEMU_TIMER_REALTIME] &&
1743 !active_timers[QEMU_TIMER_VIRTUAL])
1744 return;
1746 nearest_delta_us = qemu_next_deadline_dyntick();
1747 nearest_delta_us /= 1000;
1749 timeKillEvent(data->timerId);
1751 data->timerId = timeSetEvent(1,
1752 data->period,
1753 host_alarm_handler,
1754 (DWORD)t,
1755 TIME_ONESHOT | TIME_PERIODIC);
1757 if (!data->timerId) {
1758 perror("Failed to re-arm win32 alarm timer");
1760 timeEndPeriod(data->period);
1761 CloseHandle(data->host_alarm);
1762 exit(1);
1766 #endif /* _WIN32 */
1768 static int init_timer_alarm(void)
1770 struct qemu_alarm_timer *t = NULL;
1771 int i, err = -1;
1773 #ifndef _WIN32
1774 int fds[2];
1776 err = pipe(fds);
1777 if (err == -1)
1778 return -errno;
1780 err = fcntl_setfl(fds[0], O_NONBLOCK);
1781 if (err < 0)
1782 goto fail;
1784 err = fcntl_setfl(fds[1], O_NONBLOCK);
1785 if (err < 0)
1786 goto fail;
1788 alarm_timer_rfd = fds[0];
1789 alarm_timer_wfd = fds[1];
1790 #endif
1792 for (i = 0; alarm_timers[i].name; i++) {
1793 t = &alarm_timers[i];
1795 err = t->start(t);
1796 if (!err)
1797 break;
1800 if (err) {
1801 err = -ENOENT;
1802 goto fail;
1805 #ifndef _WIN32
1806 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1807 try_to_rearm_timer, NULL, t);
1808 #endif
1810 alarm_timer = t;
1812 return 0;
1814 fail:
1815 #ifndef _WIN32
1816 close(fds[0]);
1817 close(fds[1]);
1818 #endif
1819 return err;
1822 static void quit_timers(void)
1824 alarm_timer->stop(alarm_timer);
1825 alarm_timer = NULL;
1828 /***********************************************************/
1829 /* host time/date access */
1830 void qemu_get_timedate(struct tm *tm, int offset)
1832 time_t ti;
1833 struct tm *ret;
1835 time(&ti);
1836 ti += offset;
1837 if (rtc_date_offset == -1) {
1838 if (rtc_utc)
1839 ret = gmtime(&ti);
1840 else
1841 ret = localtime(&ti);
1842 } else {
1843 ti -= rtc_date_offset;
1844 ret = gmtime(&ti);
1847 memcpy(tm, ret, sizeof(struct tm));
1850 int qemu_timedate_diff(struct tm *tm)
1852 time_t seconds;
1854 if (rtc_date_offset == -1)
1855 if (rtc_utc)
1856 seconds = mktimegm(tm);
1857 else
1858 seconds = mktime(tm);
1859 else
1860 seconds = mktimegm(tm) + rtc_date_offset;
1862 return seconds - time(NULL);
1865 #ifdef _WIN32
1866 static void socket_cleanup(void)
1868 WSACleanup();
1871 static int socket_init(void)
1873 WSADATA Data;
1874 int ret, err;
1876 ret = WSAStartup(MAKEWORD(2,2), &Data);
1877 if (ret != 0) {
1878 err = WSAGetLastError();
1879 fprintf(stderr, "WSAStartup: %d\n", err);
1880 return -1;
1882 atexit(socket_cleanup);
1883 return 0;
1885 #endif
1887 const char *get_opt_name(char *buf, int buf_size, const char *p)
1889 char *q;
1891 q = buf;
1892 while (*p != '\0' && *p != '=') {
1893 if (q && (q - buf) < buf_size - 1)
1894 *q++ = *p;
1895 p++;
1897 if (q)
1898 *q = '\0';
1900 return p;
1903 const char *get_opt_value(char *buf, int buf_size, const char *p)
1905 char *q;
1907 q = buf;
1908 while (*p != '\0') {
1909 if (*p == ',') {
1910 if (*(p + 1) != ',')
1911 break;
1912 p++;
1914 if (q && (q - buf) < buf_size - 1)
1915 *q++ = *p;
1916 p++;
1918 if (q)
1919 *q = '\0';
1921 return p;
1924 int get_param_value(char *buf, int buf_size,
1925 const char *tag, const char *str)
1927 const char *p;
1928 char option[128];
1930 p = str;
1931 for(;;) {
1932 p = get_opt_name(option, sizeof(option), p);
1933 if (*p != '=')
1934 break;
1935 p++;
1936 if (!strcmp(tag, option)) {
1937 (void)get_opt_value(buf, buf_size, p);
1938 return strlen(buf);
1939 } else {
1940 p = get_opt_value(NULL, 0, p);
1942 if (*p != ',')
1943 break;
1944 p++;
1946 return 0;
1949 int check_params(char *buf, int buf_size,
1950 const char * const *params, const char *str)
1952 const char *p;
1953 int i;
1955 p = str;
1956 for(;;) {
1957 p = get_opt_name(buf, buf_size, p);
1958 if (*p != '=')
1959 return -1;
1960 p++;
1961 for(i = 0; params[i] != NULL; i++)
1962 if (!strcmp(params[i], buf))
1963 break;
1964 if (params[i] == NULL)
1965 return -1;
1966 p = get_opt_value(NULL, 0, p);
1967 if (*p != ',')
1968 break;
1969 p++;
1971 return 0;
1974 /***********************************************************/
1975 /* Bluetooth support */
1976 static int nb_hcis;
1977 static int cur_hci;
1978 static struct HCIInfo *hci_table[MAX_NICS];
1980 static struct bt_vlan_s {
1981 struct bt_scatternet_s net;
1982 int id;
1983 struct bt_vlan_s *next;
1984 } *first_bt_vlan;
1986 /* find or alloc a new bluetooth "VLAN" */
1987 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1989 struct bt_vlan_s **pvlan, *vlan;
1990 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1991 if (vlan->id == id)
1992 return &vlan->net;
1994 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1995 vlan->id = id;
1996 pvlan = &first_bt_vlan;
1997 while (*pvlan != NULL)
1998 pvlan = &(*pvlan)->next;
1999 *pvlan = vlan;
2000 return &vlan->net;
2003 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2007 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2009 return -ENOTSUP;
2012 static struct HCIInfo null_hci = {
2013 .cmd_send = null_hci_send,
2014 .sco_send = null_hci_send,
2015 .acl_send = null_hci_send,
2016 .bdaddr_set = null_hci_addr_set,
2019 struct HCIInfo *qemu_next_hci(void)
2021 if (cur_hci == nb_hcis)
2022 return &null_hci;
2024 return hci_table[cur_hci++];
2027 static struct HCIInfo *hci_init(const char *str)
2029 char *endp;
2030 struct bt_scatternet_s *vlan = 0;
2032 if (!strcmp(str, "null"))
2033 /* null */
2034 return &null_hci;
2035 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2036 /* host[:hciN] */
2037 return bt_host_hci(str[4] ? str + 5 : "hci0");
2038 else if (!strncmp(str, "hci", 3)) {
2039 /* hci[,vlan=n] */
2040 if (str[3]) {
2041 if (!strncmp(str + 3, ",vlan=", 6)) {
2042 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2043 if (*endp)
2044 vlan = 0;
2046 } else
2047 vlan = qemu_find_bt_vlan(0);
2048 if (vlan)
2049 return bt_new_hci(vlan);
2052 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2054 return 0;
2057 static int bt_hci_parse(const char *str)
2059 struct HCIInfo *hci;
2060 bdaddr_t bdaddr;
2062 if (nb_hcis >= MAX_NICS) {
2063 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2064 return -1;
2067 hci = hci_init(str);
2068 if (!hci)
2069 return -1;
2071 bdaddr.b[0] = 0x52;
2072 bdaddr.b[1] = 0x54;
2073 bdaddr.b[2] = 0x00;
2074 bdaddr.b[3] = 0x12;
2075 bdaddr.b[4] = 0x34;
2076 bdaddr.b[5] = 0x56 + nb_hcis;
2077 hci->bdaddr_set(hci, bdaddr.b);
2079 hci_table[nb_hcis++] = hci;
2081 return 0;
2084 static void bt_vhci_add(int vlan_id)
2086 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2088 if (!vlan->slave)
2089 fprintf(stderr, "qemu: warning: adding a VHCI to "
2090 "an empty scatternet %i\n", vlan_id);
2092 bt_vhci_init(bt_new_hci(vlan));
2095 static struct bt_device_s *bt_device_add(const char *opt)
2097 struct bt_scatternet_s *vlan;
2098 int vlan_id = 0;
2099 char *endp = strstr(opt, ",vlan=");
2100 int len = (endp ? endp - opt : strlen(opt)) + 1;
2101 char devname[10];
2103 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2105 if (endp) {
2106 vlan_id = strtol(endp + 6, &endp, 0);
2107 if (*endp) {
2108 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2109 return 0;
2113 vlan = qemu_find_bt_vlan(vlan_id);
2115 if (!vlan->slave)
2116 fprintf(stderr, "qemu: warning: adding a slave device to "
2117 "an empty scatternet %i\n", vlan_id);
2119 if (!strcmp(devname, "keyboard"))
2120 return bt_keyboard_init(vlan);
2122 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2123 return 0;
2126 static int bt_parse(const char *opt)
2128 const char *endp, *p;
2129 int vlan;
2131 if (strstart(opt, "hci", &endp)) {
2132 if (!*endp || *endp == ',') {
2133 if (*endp)
2134 if (!strstart(endp, ",vlan=", 0))
2135 opt = endp + 1;
2137 return bt_hci_parse(opt);
2139 } else if (strstart(opt, "vhci", &endp)) {
2140 if (!*endp || *endp == ',') {
2141 if (*endp) {
2142 if (strstart(endp, ",vlan=", &p)) {
2143 vlan = strtol(p, (char **) &endp, 0);
2144 if (*endp) {
2145 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2146 return 1;
2148 } else {
2149 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2150 return 1;
2152 } else
2153 vlan = 0;
2155 bt_vhci_add(vlan);
2156 return 0;
2158 } else if (strstart(opt, "device:", &endp))
2159 return !bt_device_add(endp);
2161 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2162 return 1;
2165 /***********************************************************/
2166 /* QEMU Block devices */
2168 #define HD_ALIAS "index=%d,media=disk"
2169 #ifdef TARGET_PPC
2170 #define CDROM_ALIAS "index=1,media=cdrom"
2171 #else
2172 #define CDROM_ALIAS "index=2,media=cdrom"
2173 #endif
2174 #define FD_ALIAS "index=%d,if=floppy"
2175 #define PFLASH_ALIAS "if=pflash"
2176 #define MTD_ALIAS "if=mtd"
2177 #define SD_ALIAS "index=0,if=sd"
2179 static int drive_opt_get_free_idx(void)
2181 int index;
2183 for (index = 0; index < MAX_DRIVES; index++)
2184 if (!drives_opt[index].used) {
2185 drives_opt[index].used = 1;
2186 return index;
2189 return -1;
2192 static int drive_get_free_idx(void)
2194 int index;
2196 for (index = 0; index < MAX_DRIVES; index++)
2197 if (!drives_table[index].used) {
2198 drives_table[index].used = 1;
2199 return index;
2202 return -1;
2205 int drive_add(const char *file, const char *fmt, ...)
2207 va_list ap;
2208 int index = drive_opt_get_free_idx();
2210 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2211 fprintf(stderr, "qemu: too many drives\n");
2212 return -1;
2215 drives_opt[index].file = file;
2216 va_start(ap, fmt);
2217 vsnprintf(drives_opt[index].opt,
2218 sizeof(drives_opt[0].opt), fmt, ap);
2219 va_end(ap);
2221 nb_drives_opt++;
2222 return index;
2225 void drive_remove(int index)
2227 drives_opt[index].used = 0;
2228 nb_drives_opt--;
2231 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2233 int index;
2235 /* seek interface, bus and unit */
2237 for (index = 0; index < MAX_DRIVES; index++)
2238 if (drives_table[index].type == type &&
2239 drives_table[index].bus == bus &&
2240 drives_table[index].unit == unit &&
2241 drives_table[index].used)
2242 return index;
2244 return -1;
2247 int drive_get_max_bus(BlockInterfaceType type)
2249 int max_bus;
2250 int index;
2252 max_bus = -1;
2253 for (index = 0; index < nb_drives; index++) {
2254 if(drives_table[index].type == type &&
2255 drives_table[index].bus > max_bus)
2256 max_bus = drives_table[index].bus;
2258 return max_bus;
2261 const char *drive_get_serial(BlockDriverState *bdrv)
2263 int index;
2265 for (index = 0; index < nb_drives; index++)
2266 if (drives_table[index].bdrv == bdrv)
2267 return drives_table[index].serial;
2269 return "\0";
2272 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2274 int index;
2276 for (index = 0; index < nb_drives; index++)
2277 if (drives_table[index].bdrv == bdrv)
2278 return drives_table[index].onerror;
2280 return BLOCK_ERR_STOP_ENOSPC;
2283 static void bdrv_format_print(void *opaque, const char *name)
2285 fprintf(stderr, " %s", name);
2288 void drive_uninit(BlockDriverState *bdrv)
2290 int i;
2292 for (i = 0; i < MAX_DRIVES; i++)
2293 if (drives_table[i].bdrv == bdrv) {
2294 drives_table[i].bdrv = NULL;
2295 drives_table[i].used = 0;
2296 drive_remove(drives_table[i].drive_opt_idx);
2297 nb_drives--;
2298 break;
2302 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2304 char buf[128];
2305 char file[1024];
2306 char devname[128];
2307 char serial[21];
2308 const char *mediastr = "";
2309 BlockInterfaceType type;
2310 enum { MEDIA_DISK, MEDIA_CDROM } media;
2311 int bus_id, unit_id;
2312 int cyls, heads, secs, translation;
2313 BlockDriverState *bdrv;
2314 BlockDriver *drv = NULL;
2315 QEMUMachine *machine = opaque;
2316 int max_devs;
2317 int index;
2318 int cache;
2319 int bdrv_flags, onerror;
2320 int drives_table_idx;
2321 char *str = arg->opt;
2322 static const char * const params[] = { "bus", "unit", "if", "index",
2323 "cyls", "heads", "secs", "trans",
2324 "media", "snapshot", "file",
2325 "cache", "format", "serial", "werror",
2326 "boot", NULL };
2328 if (check_params(buf, sizeof(buf), params, str) < 0) {
2329 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2330 buf, str);
2331 return -1;
2334 file[0] = 0;
2335 cyls = heads = secs = 0;
2336 bus_id = 0;
2337 unit_id = -1;
2338 translation = BIOS_ATA_TRANSLATION_AUTO;
2339 index = -1;
2340 cache = 3;
2342 if (machine->use_scsi) {
2343 type = IF_SCSI;
2344 max_devs = MAX_SCSI_DEVS;
2345 pstrcpy(devname, sizeof(devname), "scsi");
2346 } else {
2347 type = IF_IDE;
2348 max_devs = MAX_IDE_DEVS;
2349 pstrcpy(devname, sizeof(devname), "ide");
2351 media = MEDIA_DISK;
2353 /* extract parameters */
2355 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2356 bus_id = strtol(buf, NULL, 0);
2357 if (bus_id < 0) {
2358 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2359 return -1;
2363 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2364 unit_id = strtol(buf, NULL, 0);
2365 if (unit_id < 0) {
2366 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2367 return -1;
2371 if (get_param_value(buf, sizeof(buf), "if", str)) {
2372 pstrcpy(devname, sizeof(devname), buf);
2373 if (!strcmp(buf, "ide")) {
2374 type = IF_IDE;
2375 max_devs = MAX_IDE_DEVS;
2376 } else if (!strcmp(buf, "scsi")) {
2377 type = IF_SCSI;
2378 max_devs = MAX_SCSI_DEVS;
2379 } else if (!strcmp(buf, "floppy")) {
2380 type = IF_FLOPPY;
2381 max_devs = 0;
2382 } else if (!strcmp(buf, "pflash")) {
2383 type = IF_PFLASH;
2384 max_devs = 0;
2385 } else if (!strcmp(buf, "mtd")) {
2386 type = IF_MTD;
2387 max_devs = 0;
2388 } else if (!strcmp(buf, "sd")) {
2389 type = IF_SD;
2390 max_devs = 0;
2391 } else if (!strcmp(buf, "virtio")) {
2392 type = IF_VIRTIO;
2393 max_devs = 0;
2394 } else {
2395 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2396 return -1;
2400 if (get_param_value(buf, sizeof(buf), "index", str)) {
2401 index = strtol(buf, NULL, 0);
2402 if (index < 0) {
2403 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2404 return -1;
2408 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2409 cyls = strtol(buf, NULL, 0);
2412 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2413 heads = strtol(buf, NULL, 0);
2416 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2417 secs = strtol(buf, NULL, 0);
2420 if (cyls || heads || secs) {
2421 if (cyls < 1 || cyls > 16383) {
2422 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2423 return -1;
2425 if (heads < 1 || heads > 16) {
2426 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2427 return -1;
2429 if (secs < 1 || secs > 63) {
2430 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2431 return -1;
2435 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2436 if (!cyls) {
2437 fprintf(stderr,
2438 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2439 str);
2440 return -1;
2442 if (!strcmp(buf, "none"))
2443 translation = BIOS_ATA_TRANSLATION_NONE;
2444 else if (!strcmp(buf, "lba"))
2445 translation = BIOS_ATA_TRANSLATION_LBA;
2446 else if (!strcmp(buf, "auto"))
2447 translation = BIOS_ATA_TRANSLATION_AUTO;
2448 else {
2449 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2450 return -1;
2454 if (get_param_value(buf, sizeof(buf), "media", str)) {
2455 if (!strcmp(buf, "disk")) {
2456 media = MEDIA_DISK;
2457 } else if (!strcmp(buf, "cdrom")) {
2458 if (cyls || secs || heads) {
2459 fprintf(stderr,
2460 "qemu: '%s' invalid physical CHS format\n", str);
2461 return -1;
2463 media = MEDIA_CDROM;
2464 } else {
2465 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2466 return -1;
2470 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2471 if (!strcmp(buf, "on"))
2472 snapshot = 1;
2473 else if (!strcmp(buf, "off"))
2474 snapshot = 0;
2475 else {
2476 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2477 return -1;
2481 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2482 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2483 cache = 0;
2484 else if (!strcmp(buf, "writethrough"))
2485 cache = 1;
2486 else if (!strcmp(buf, "writeback"))
2487 cache = 2;
2488 else {
2489 fprintf(stderr, "qemu: invalid cache option\n");
2490 return -1;
2494 if (get_param_value(buf, sizeof(buf), "format", str)) {
2495 if (strcmp(buf, "?") == 0) {
2496 fprintf(stderr, "qemu: Supported formats:");
2497 bdrv_iterate_format(bdrv_format_print, NULL);
2498 fprintf(stderr, "\n");
2499 return -1;
2501 drv = bdrv_find_format(buf);
2502 if (!drv) {
2503 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2504 return -1;
2508 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2509 if (!strcmp(buf, "on")) {
2510 if (extboot_drive != -1) {
2511 fprintf(stderr, "qemu: two bootable drives specified\n");
2512 return -1;
2514 extboot_drive = nb_drives;
2515 } else if (strcmp(buf, "off")) {
2516 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2517 return -1;
2521 if (arg->file == NULL)
2522 get_param_value(file, sizeof(file), "file", str);
2523 else
2524 pstrcpy(file, sizeof(file), arg->file);
2526 if (!get_param_value(serial, sizeof(serial), "serial", str))
2527 memset(serial, 0, sizeof(serial));
2529 onerror = BLOCK_ERR_STOP_ENOSPC;
2530 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2531 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2532 fprintf(stderr, "werror is no supported by this format\n");
2533 return -1;
2535 if (!strcmp(buf, "ignore"))
2536 onerror = BLOCK_ERR_IGNORE;
2537 else if (!strcmp(buf, "enospc"))
2538 onerror = BLOCK_ERR_STOP_ENOSPC;
2539 else if (!strcmp(buf, "stop"))
2540 onerror = BLOCK_ERR_STOP_ANY;
2541 else if (!strcmp(buf, "report"))
2542 onerror = BLOCK_ERR_REPORT;
2543 else {
2544 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2545 return -1;
2549 /* compute bus and unit according index */
2551 if (index != -1) {
2552 if (bus_id != 0 || unit_id != -1) {
2553 fprintf(stderr,
2554 "qemu: '%s' index cannot be used with bus and unit\n", str);
2555 return -1;
2557 if (max_devs == 0)
2559 unit_id = index;
2560 bus_id = 0;
2561 } else {
2562 unit_id = index % max_devs;
2563 bus_id = index / max_devs;
2567 /* if user doesn't specify a unit_id,
2568 * try to find the first free
2571 if (unit_id == -1) {
2572 unit_id = 0;
2573 while (drive_get_index(type, bus_id, unit_id) != -1) {
2574 unit_id++;
2575 if (max_devs && unit_id >= max_devs) {
2576 unit_id -= max_devs;
2577 bus_id++;
2582 /* check unit id */
2584 if (max_devs && unit_id >= max_devs) {
2585 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2586 str, unit_id, max_devs - 1);
2587 return -1;
2591 * ignore multiple definitions
2594 if (drive_get_index(type, bus_id, unit_id) != -1)
2595 return -2;
2597 /* init */
2599 if (type == IF_IDE || type == IF_SCSI)
2600 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2601 if (max_devs)
2602 snprintf(buf, sizeof(buf), "%s%i%s%i",
2603 devname, bus_id, mediastr, unit_id);
2604 else
2605 snprintf(buf, sizeof(buf), "%s%s%i",
2606 devname, mediastr, unit_id);
2607 bdrv = bdrv_new(buf);
2608 drives_table_idx = drive_get_free_idx();
2609 drives_table[drives_table_idx].bdrv = bdrv;
2610 drives_table[drives_table_idx].type = type;
2611 drives_table[drives_table_idx].bus = bus_id;
2612 drives_table[drives_table_idx].unit = unit_id;
2613 drives_table[drives_table_idx].onerror = onerror;
2614 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2615 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2616 nb_drives++;
2618 switch(type) {
2619 case IF_IDE:
2620 case IF_SCSI:
2621 switch(media) {
2622 case MEDIA_DISK:
2623 if (cyls != 0) {
2624 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2625 bdrv_set_translation_hint(bdrv, translation);
2627 break;
2628 case MEDIA_CDROM:
2629 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2630 break;
2632 break;
2633 case IF_SD:
2634 /* FIXME: This isn't really a floppy, but it's a reasonable
2635 approximation. */
2636 case IF_FLOPPY:
2637 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2638 break;
2639 case IF_PFLASH:
2640 case IF_MTD:
2641 case IF_VIRTIO:
2642 break;
2644 if (!file[0])
2645 return -2;
2646 bdrv_flags = 0;
2647 if (snapshot) {
2648 bdrv_flags |= BDRV_O_SNAPSHOT;
2649 cache = 2; /* always use write-back with snapshot */
2651 if (cache == 0) /* no caching */
2652 bdrv_flags |= BDRV_O_NOCACHE;
2653 else if (cache == 2) /* write-back */
2654 bdrv_flags |= BDRV_O_CACHE_WB;
2655 else if (cache == 3) /* not specified */
2656 bdrv_flags |= BDRV_O_CACHE_DEF;
2657 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2658 fprintf(stderr, "qemu: could not open disk image %s\n",
2659 file);
2660 return -1;
2662 if (bdrv_key_required(bdrv))
2663 autostart = 0;
2664 return drives_table_idx;
2667 /***********************************************************/
2668 /* USB devices */
2670 static USBPort *used_usb_ports;
2671 static USBPort *free_usb_ports;
2673 /* ??? Maybe change this to register a hub to keep track of the topology. */
2674 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2675 usb_attachfn attach)
2677 port->opaque = opaque;
2678 port->index = index;
2679 port->attach = attach;
2680 port->next = free_usb_ports;
2681 free_usb_ports = port;
2684 int usb_device_add_dev(USBDevice *dev)
2686 USBPort *port;
2688 /* Find a USB port to add the device to. */
2689 port = free_usb_ports;
2690 if (!port->next) {
2691 USBDevice *hub;
2693 /* Create a new hub and chain it on. */
2694 free_usb_ports = NULL;
2695 port->next = used_usb_ports;
2696 used_usb_ports = port;
2698 hub = usb_hub_init(VM_USB_HUB_SIZE);
2699 usb_attach(port, hub);
2700 port = free_usb_ports;
2703 free_usb_ports = port->next;
2704 port->next = used_usb_ports;
2705 used_usb_ports = port;
2706 usb_attach(port, dev);
2707 return 0;
2710 static int usb_device_add(const char *devname, int is_hotplug)
2712 const char *p;
2713 USBDevice *dev;
2715 if (!free_usb_ports)
2716 return -1;
2718 if (strstart(devname, "host:", &p)) {
2719 dev = usb_host_device_open(p);
2720 } else if (!strcmp(devname, "mouse")) {
2721 dev = usb_mouse_init();
2722 } else if (!strcmp(devname, "tablet")) {
2723 dev = usb_tablet_init();
2724 } else if (!strcmp(devname, "keyboard")) {
2725 dev = usb_keyboard_init();
2726 } else if (strstart(devname, "disk:", &p)) {
2727 BlockDriverState *bs;
2729 dev = usb_msd_init(p, &bs);
2730 if (!dev)
2731 return -1;
2732 if (bdrv_key_required(bs)) {
2733 autostart = 0;
2734 if (is_hotplug && monitor_read_bdrv_key(bs) < 0) {
2735 dev->handle_destroy(dev);
2736 return -1;
2739 } else if (!strcmp(devname, "wacom-tablet")) {
2740 dev = usb_wacom_init();
2741 } else if (strstart(devname, "serial:", &p)) {
2742 dev = usb_serial_init(p);
2743 #ifdef CONFIG_BRLAPI
2744 } else if (!strcmp(devname, "braille")) {
2745 dev = usb_baum_init();
2746 #endif
2747 } else if (strstart(devname, "net:", &p)) {
2748 int nic = nb_nics;
2750 if (net_client_init("nic", p) < 0)
2751 return -1;
2752 nd_table[nic].model = "usb";
2753 dev = usb_net_init(&nd_table[nic]);
2754 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2755 dev = usb_bt_init(devname[2] ? hci_init(p) :
2756 bt_new_hci(qemu_find_bt_vlan(0)));
2757 } else {
2758 return -1;
2760 if (!dev)
2761 return -1;
2763 return usb_device_add_dev(dev);
2766 int usb_device_del_addr(int bus_num, int addr)
2768 USBPort *port;
2769 USBPort **lastp;
2770 USBDevice *dev;
2772 if (!used_usb_ports)
2773 return -1;
2775 if (bus_num != 0)
2776 return -1;
2778 lastp = &used_usb_ports;
2779 port = used_usb_ports;
2780 while (port && port->dev->addr != addr) {
2781 lastp = &port->next;
2782 port = port->next;
2785 if (!port)
2786 return -1;
2788 dev = port->dev;
2789 *lastp = port->next;
2790 usb_attach(port, NULL);
2791 dev->handle_destroy(dev);
2792 port->next = free_usb_ports;
2793 free_usb_ports = port;
2794 return 0;
2797 static int usb_device_del(const char *devname)
2799 int bus_num, addr;
2800 const char *p;
2802 if (strstart(devname, "host:", &p))
2803 return usb_host_device_close(p);
2805 if (!used_usb_ports)
2806 return -1;
2808 p = strchr(devname, '.');
2809 if (!p)
2810 return -1;
2811 bus_num = strtoul(devname, NULL, 0);
2812 addr = strtoul(p + 1, NULL, 0);
2814 return usb_device_del_addr(bus_num, addr);
2817 void do_usb_add(const char *devname)
2819 usb_device_add(devname, 1);
2822 void do_usb_del(const char *devname)
2824 usb_device_del(devname);
2827 void usb_info(void)
2829 USBDevice *dev;
2830 USBPort *port;
2831 const char *speed_str;
2833 if (!usb_enabled) {
2834 term_printf("USB support not enabled\n");
2835 return;
2838 for (port = used_usb_ports; port; port = port->next) {
2839 dev = port->dev;
2840 if (!dev)
2841 continue;
2842 switch(dev->speed) {
2843 case USB_SPEED_LOW:
2844 speed_str = "1.5";
2845 break;
2846 case USB_SPEED_FULL:
2847 speed_str = "12";
2848 break;
2849 case USB_SPEED_HIGH:
2850 speed_str = "480";
2851 break;
2852 default:
2853 speed_str = "?";
2854 break;
2856 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
2857 0, dev->addr, speed_str, dev->devname);
2861 /***********************************************************/
2862 /* PCMCIA/Cardbus */
2864 static struct pcmcia_socket_entry_s {
2865 struct pcmcia_socket_s *socket;
2866 struct pcmcia_socket_entry_s *next;
2867 } *pcmcia_sockets = 0;
2869 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2871 struct pcmcia_socket_entry_s *entry;
2873 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2874 entry->socket = socket;
2875 entry->next = pcmcia_sockets;
2876 pcmcia_sockets = entry;
2879 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2881 struct pcmcia_socket_entry_s *entry, **ptr;
2883 ptr = &pcmcia_sockets;
2884 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2885 if (entry->socket == socket) {
2886 *ptr = entry->next;
2887 qemu_free(entry);
2891 void pcmcia_info(void)
2893 struct pcmcia_socket_entry_s *iter;
2894 if (!pcmcia_sockets)
2895 term_printf("No PCMCIA sockets\n");
2897 for (iter = pcmcia_sockets; iter; iter = iter->next)
2898 term_printf("%s: %s\n", iter->socket->slot_string,
2899 iter->socket->attached ? iter->socket->card_string :
2900 "Empty");
2903 /***********************************************************/
2904 /* register display */
2906 void register_displaystate(DisplayState *ds)
2908 DisplayState **s;
2909 s = &display_state;
2910 while (*s != NULL)
2911 s = &(*s)->next;
2912 ds->next = NULL;
2913 *s = ds;
2916 DisplayState *get_displaystate(void)
2918 return display_state;
2921 /* dumb display */
2923 static void dumb_display_init(void)
2925 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2926 ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
2927 register_displaystate(ds);
2930 /***********************************************************/
2931 /* I/O handling */
2933 #define MAX_IO_HANDLERS 64
2935 typedef struct IOHandlerRecord {
2936 int fd;
2937 IOCanRWHandler *fd_read_poll;
2938 IOHandler *fd_read;
2939 IOHandler *fd_write;
2940 int deleted;
2941 void *opaque;
2942 /* temporary data */
2943 struct pollfd *ufd;
2944 struct IOHandlerRecord *next;
2945 } IOHandlerRecord;
2947 static IOHandlerRecord *first_io_handler;
2949 /* XXX: fd_read_poll should be suppressed, but an API change is
2950 necessary in the character devices to suppress fd_can_read(). */
2951 int qemu_set_fd_handler2(int fd,
2952 IOCanRWHandler *fd_read_poll,
2953 IOHandler *fd_read,
2954 IOHandler *fd_write,
2955 void *opaque)
2957 IOHandlerRecord **pioh, *ioh;
2959 if (!fd_read && !fd_write) {
2960 pioh = &first_io_handler;
2961 for(;;) {
2962 ioh = *pioh;
2963 if (ioh == NULL)
2964 break;
2965 if (ioh->fd == fd) {
2966 ioh->deleted = 1;
2967 break;
2969 pioh = &ioh->next;
2971 } else {
2972 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2973 if (ioh->fd == fd)
2974 goto found;
2976 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2977 ioh->next = first_io_handler;
2978 first_io_handler = ioh;
2979 found:
2980 ioh->fd = fd;
2981 ioh->fd_read_poll = fd_read_poll;
2982 ioh->fd_read = fd_read;
2983 ioh->fd_write = fd_write;
2984 ioh->opaque = opaque;
2985 ioh->deleted = 0;
2987 main_loop_break();
2988 return 0;
2991 int qemu_set_fd_handler(int fd,
2992 IOHandler *fd_read,
2993 IOHandler *fd_write,
2994 void *opaque)
2996 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2999 #ifdef _WIN32
3000 /***********************************************************/
3001 /* Polling handling */
3003 typedef struct PollingEntry {
3004 PollingFunc *func;
3005 void *opaque;
3006 struct PollingEntry *next;
3007 } PollingEntry;
3009 static PollingEntry *first_polling_entry;
3011 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3013 PollingEntry **ppe, *pe;
3014 pe = qemu_mallocz(sizeof(PollingEntry));
3015 pe->func = func;
3016 pe->opaque = opaque;
3017 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3018 *ppe = pe;
3019 return 0;
3022 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3024 PollingEntry **ppe, *pe;
3025 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3026 pe = *ppe;
3027 if (pe->func == func && pe->opaque == opaque) {
3028 *ppe = pe->next;
3029 qemu_free(pe);
3030 break;
3035 /***********************************************************/
3036 /* Wait objects support */
3037 typedef struct WaitObjects {
3038 int num;
3039 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3040 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3041 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3042 } WaitObjects;
3044 static WaitObjects wait_objects = {0};
3046 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3048 WaitObjects *w = &wait_objects;
3050 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3051 return -1;
3052 w->events[w->num] = handle;
3053 w->func[w->num] = func;
3054 w->opaque[w->num] = opaque;
3055 w->num++;
3056 return 0;
3059 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3061 int i, found;
3062 WaitObjects *w = &wait_objects;
3064 found = 0;
3065 for (i = 0; i < w->num; i++) {
3066 if (w->events[i] == handle)
3067 found = 1;
3068 if (found) {
3069 w->events[i] = w->events[i + 1];
3070 w->func[i] = w->func[i + 1];
3071 w->opaque[i] = w->opaque[i + 1];
3074 if (found)
3075 w->num--;
3077 #endif
3079 /***********************************************************/
3080 /* ram save/restore */
3082 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3084 int v;
3086 v = qemu_get_byte(f);
3087 switch(v) {
3088 case 0:
3089 if (qemu_get_buffer(f, buf, len) != len)
3090 return -EIO;
3091 break;
3092 case 1:
3093 v = qemu_get_byte(f);
3094 memset(buf, v, len);
3095 break;
3096 default:
3097 return -EINVAL;
3100 if (qemu_file_has_error(f))
3101 return -EIO;
3103 return 0;
3106 static int ram_load_v1(QEMUFile *f, void *opaque)
3108 int ret;
3109 ram_addr_t i;
3111 if (qemu_get_be32(f) != phys_ram_size)
3112 return -EINVAL;
3113 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3114 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3115 continue;
3116 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3117 if (ret)
3118 return ret;
3120 return 0;
3123 #define BDRV_HASH_BLOCK_SIZE 1024
3124 #define IOBUF_SIZE 4096
3125 #define RAM_CBLOCK_MAGIC 0xfabe
3127 typedef struct RamDecompressState {
3128 z_stream zstream;
3129 QEMUFile *f;
3130 uint8_t buf[IOBUF_SIZE];
3131 } RamDecompressState;
3133 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3135 int ret;
3136 memset(s, 0, sizeof(*s));
3137 s->f = f;
3138 ret = inflateInit(&s->zstream);
3139 if (ret != Z_OK)
3140 return -1;
3141 return 0;
3144 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3146 int ret, clen;
3148 s->zstream.avail_out = len;
3149 s->zstream.next_out = buf;
3150 while (s->zstream.avail_out > 0) {
3151 if (s->zstream.avail_in == 0) {
3152 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3153 return -1;
3154 clen = qemu_get_be16(s->f);
3155 if (clen > IOBUF_SIZE)
3156 return -1;
3157 qemu_get_buffer(s->f, s->buf, clen);
3158 s->zstream.avail_in = clen;
3159 s->zstream.next_in = s->buf;
3161 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3162 if (ret != Z_OK && ret != Z_STREAM_END) {
3163 return -1;
3166 return 0;
3169 static void ram_decompress_close(RamDecompressState *s)
3171 inflateEnd(&s->zstream);
3174 #define RAM_SAVE_FLAG_FULL 0x01
3175 #define RAM_SAVE_FLAG_COMPRESS 0x02
3176 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3177 #define RAM_SAVE_FLAG_PAGE 0x08
3178 #define RAM_SAVE_FLAG_EOS 0x10
3180 static int is_dup_page(uint8_t *page, uint8_t ch)
3182 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3183 uint32_t *array = (uint32_t *)page;
3184 int i;
3186 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3187 if (array[i] != val)
3188 return 0;
3191 return 1;
3194 static int ram_save_block(QEMUFile *f)
3196 static ram_addr_t current_addr = 0;
3197 ram_addr_t saved_addr = current_addr;
3198 ram_addr_t addr = 0;
3199 int found = 0;
3201 while (addr < phys_ram_size) {
3202 if (kvm_enabled() && current_addr == 0) {
3203 int r;
3204 r = kvm_update_dirty_pages_log();
3205 if (r) {
3206 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3207 qemu_file_set_error(f);
3208 return 0;
3211 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3212 uint8_t ch;
3214 cpu_physical_memory_reset_dirty(current_addr,
3215 current_addr + TARGET_PAGE_SIZE,
3216 MIGRATION_DIRTY_FLAG);
3218 ch = *(phys_ram_base + current_addr);
3220 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3221 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3222 qemu_put_byte(f, ch);
3223 } else {
3224 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3225 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3228 found = 1;
3229 break;
3231 addr += TARGET_PAGE_SIZE;
3232 current_addr = (saved_addr + addr) % phys_ram_size;
3235 return found;
3238 static ram_addr_t ram_save_threshold = 10;
3240 static ram_addr_t ram_save_remaining(void)
3242 ram_addr_t addr;
3243 ram_addr_t count = 0;
3245 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3246 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3247 count++;
3250 return count;
3253 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3255 ram_addr_t addr;
3257 if (stage == 1) {
3258 /* Make sure all dirty bits are set */
3259 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3260 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3261 cpu_physical_memory_set_dirty(addr);
3264 /* Enable dirty memory tracking */
3265 cpu_physical_memory_set_dirty_tracking(1);
3267 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3270 while (!qemu_file_rate_limit(f)) {
3271 int ret;
3273 ret = ram_save_block(f);
3274 if (ret == 0) /* no more blocks */
3275 break;
3278 /* try transferring iterative blocks of memory */
3280 if (stage == 3) {
3282 /* flush all remaining blocks regardless of rate limiting */
3283 while (ram_save_block(f) != 0);
3284 cpu_physical_memory_set_dirty_tracking(0);
3287 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3289 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3292 static int ram_load_dead(QEMUFile *f, void *opaque)
3294 RamDecompressState s1, *s = &s1;
3295 uint8_t buf[10];
3296 ram_addr_t i;
3298 if (ram_decompress_open(s, f) < 0)
3299 return -EINVAL;
3300 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3301 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3302 continue;
3303 if (ram_decompress_buf(s, buf, 1) < 0) {
3304 fprintf(stderr, "Error while reading ram block header\n");
3305 goto error;
3307 if (buf[0] == 0) {
3308 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3309 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3310 goto error;
3312 } else {
3313 error:
3314 printf("Error block header\n");
3315 return -EINVAL;
3318 ram_decompress_close(s);
3320 return 0;
3323 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3325 ram_addr_t addr;
3326 int flags;
3328 if (version_id == 1)
3329 return ram_load_v1(f, opaque);
3331 if (version_id == 2) {
3332 if (qemu_get_be32(f) != phys_ram_size)
3333 return -EINVAL;
3334 return ram_load_dead(f, opaque);
3337 if (version_id != 3)
3338 return -EINVAL;
3340 do {
3341 addr = qemu_get_be64(f);
3343 flags = addr & ~TARGET_PAGE_MASK;
3344 addr &= TARGET_PAGE_MASK;
3346 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3347 if (addr != phys_ram_size)
3348 return -EINVAL;
3351 if (flags & RAM_SAVE_FLAG_FULL) {
3352 if (ram_load_dead(f, opaque) < 0)
3353 return -EINVAL;
3356 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3357 uint8_t ch = qemu_get_byte(f);
3358 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3359 } else if (flags & RAM_SAVE_FLAG_PAGE)
3360 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3361 } while (!(flags & RAM_SAVE_FLAG_EOS));
3363 return 0;
3366 /***********************************************************/
3367 /* bottom halves (can be seen as timers which expire ASAP) */
3369 struct QEMUBH {
3370 QEMUBHFunc *cb;
3371 void *opaque;
3372 int scheduled;
3373 int idle;
3374 int deleted;
3375 QEMUBH *next;
3378 static QEMUBH *first_bh = NULL;
3380 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3382 QEMUBH *bh;
3383 bh = qemu_mallocz(sizeof(QEMUBH));
3384 bh->cb = cb;
3385 bh->opaque = opaque;
3386 bh->next = first_bh;
3387 first_bh = bh;
3388 return bh;
3391 int qemu_bh_poll(void)
3393 QEMUBH *bh, **bhp;
3394 int ret;
3396 ret = 0;
3397 for (bh = first_bh; bh; bh = bh->next) {
3398 if (!bh->deleted && bh->scheduled) {
3399 bh->scheduled = 0;
3400 if (!bh->idle)
3401 ret = 1;
3402 bh->idle = 0;
3403 bh->cb(bh->opaque);
3407 /* remove deleted bhs */
3408 bhp = &first_bh;
3409 while (*bhp) {
3410 bh = *bhp;
3411 if (bh->deleted) {
3412 *bhp = bh->next;
3413 qemu_free(bh);
3414 } else
3415 bhp = &bh->next;
3418 return ret;
3421 void qemu_bh_schedule_idle(QEMUBH *bh)
3423 if (bh->scheduled)
3424 return;
3425 bh->scheduled = 1;
3426 bh->idle = 1;
3429 void qemu_bh_schedule(QEMUBH *bh)
3431 CPUState *env = cpu_single_env;
3432 if (bh->scheduled)
3433 return;
3434 bh->scheduled = 1;
3435 bh->idle = 0;
3436 /* stop the currently executing CPU to execute the BH ASAP */
3437 if (env) {
3438 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3440 main_loop_break();
3443 void qemu_bh_cancel(QEMUBH *bh)
3445 bh->scheduled = 0;
3448 void qemu_bh_delete(QEMUBH *bh)
3450 bh->scheduled = 0;
3451 bh->deleted = 1;
3454 static void qemu_bh_update_timeout(int *timeout)
3456 QEMUBH *bh;
3458 for (bh = first_bh; bh; bh = bh->next) {
3459 if (!bh->deleted && bh->scheduled) {
3460 if (bh->idle) {
3461 /* idle bottom halves will be polled at least
3462 * every 10ms */
3463 *timeout = MIN(10, *timeout);
3464 } else {
3465 /* non-idle bottom halves will be executed
3466 * immediately */
3467 *timeout = 0;
3468 break;
3474 /***********************************************************/
3475 /* machine registration */
3477 static QEMUMachine *first_machine = NULL;
3478 QEMUMachine *current_machine = NULL;
3480 int qemu_register_machine(QEMUMachine *m)
3482 QEMUMachine **pm;
3483 pm = &first_machine;
3484 while (*pm != NULL)
3485 pm = &(*pm)->next;
3486 m->next = NULL;
3487 *pm = m;
3488 return 0;
3491 static QEMUMachine *find_machine(const char *name)
3493 QEMUMachine *m;
3495 for(m = first_machine; m != NULL; m = m->next) {
3496 if (!strcmp(m->name, name))
3497 return m;
3499 return NULL;
3502 /***********************************************************/
3503 /* main execution loop */
3505 static void gui_update(void *opaque)
3507 uint64_t interval = GUI_REFRESH_INTERVAL;
3508 DisplayState *ds = opaque;
3509 DisplayChangeListener *dcl = ds->listeners;
3511 dpy_refresh(ds);
3513 while (dcl != NULL) {
3514 if (dcl->gui_timer_interval &&
3515 dcl->gui_timer_interval < interval)
3516 interval = dcl->gui_timer_interval;
3517 dcl = dcl->next;
3519 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3522 static void nographic_update(void *opaque)
3524 uint64_t interval = GUI_REFRESH_INTERVAL;
3526 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3529 struct vm_change_state_entry {
3530 VMChangeStateHandler *cb;
3531 void *opaque;
3532 LIST_ENTRY (vm_change_state_entry) entries;
3535 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3537 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3538 void *opaque)
3540 VMChangeStateEntry *e;
3542 e = qemu_mallocz(sizeof (*e));
3544 e->cb = cb;
3545 e->opaque = opaque;
3546 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3547 return e;
3550 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3552 LIST_REMOVE (e, entries);
3553 qemu_free (e);
3556 static void vm_state_notify(int running, int reason)
3558 VMChangeStateEntry *e;
3560 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3561 e->cb(e->opaque, running, reason);
3565 void vm_start(void)
3567 if (!vm_running) {
3568 cpu_enable_ticks();
3569 vm_running = 1;
3570 vm_state_notify(1, 0);
3571 qemu_rearm_alarm_timer(alarm_timer);
3575 void vm_stop(int reason)
3577 if (vm_running) {
3578 cpu_disable_ticks();
3579 vm_running = 0;
3580 vm_state_notify(0, reason);
3584 /* reset/shutdown handler */
3586 typedef struct QEMUResetEntry {
3587 QEMUResetHandler *func;
3588 void *opaque;
3589 struct QEMUResetEntry *next;
3590 } QEMUResetEntry;
3592 static QEMUResetEntry *first_reset_entry;
3593 static int reset_requested;
3594 static int shutdown_requested;
3595 static int powerdown_requested;
3597 int qemu_no_shutdown(void)
3599 int r = no_shutdown;
3600 no_shutdown = 0;
3601 return r;
3604 int qemu_shutdown_requested(void)
3606 int r = shutdown_requested;
3607 shutdown_requested = 0;
3608 return r;
3611 int qemu_reset_requested(void)
3613 int r = reset_requested;
3614 reset_requested = 0;
3615 return r;
3618 int qemu_powerdown_requested(void)
3620 int r = powerdown_requested;
3621 powerdown_requested = 0;
3622 return r;
3625 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3627 QEMUResetEntry **pre, *re;
3629 pre = &first_reset_entry;
3630 while (*pre != NULL)
3631 pre = &(*pre)->next;
3632 re = qemu_mallocz(sizeof(QEMUResetEntry));
3633 re->func = func;
3634 re->opaque = opaque;
3635 re->next = NULL;
3636 *pre = re;
3639 void qemu_system_reset(void)
3641 QEMUResetEntry *re;
3643 /* reset all devices */
3644 for(re = first_reset_entry; re != NULL; re = re->next) {
3645 re->func(re->opaque);
3649 void qemu_system_reset_request(void)
3651 if (no_reboot) {
3652 shutdown_requested = 1;
3653 } else {
3654 reset_requested = 1;
3657 if (cpu_single_env) {
3658 qemu_kvm_cpu_stop(cpu_single_env);
3659 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3661 main_loop_break();
3664 void qemu_system_shutdown_request(void)
3666 shutdown_requested = 1;
3667 if (cpu_single_env)
3668 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3671 void qemu_system_powerdown_request(void)
3673 powerdown_requested = 1;
3674 if (cpu_single_env)
3675 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3678 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3679 struct timeval *tv)
3681 int ret;
3683 /* KVM holds a mutex while QEMU code is running, we need hooks to
3684 release the mutex whenever QEMU code sleeps. */
3686 kvm_sleep_begin();
3688 ret = select(max_fd, rfds, wfds, xfds, tv);
3690 kvm_sleep_end();
3692 return ret;
3695 #ifdef _WIN32
3696 static void host_main_loop_wait(int *timeout)
3698 int ret, ret2, i;
3699 PollingEntry *pe;
3702 /* XXX: need to suppress polling by better using win32 events */
3703 ret = 0;
3704 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3705 ret |= pe->func(pe->opaque);
3707 if (ret == 0) {
3708 int err;
3709 WaitObjects *w = &wait_objects;
3711 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3712 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3713 if (w->func[ret - WAIT_OBJECT_0])
3714 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3716 /* Check for additional signaled events */
3717 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3719 /* Check if event is signaled */
3720 ret2 = WaitForSingleObject(w->events[i], 0);
3721 if(ret2 == WAIT_OBJECT_0) {
3722 if (w->func[i])
3723 w->func[i](w->opaque[i]);
3724 } else if (ret2 == WAIT_TIMEOUT) {
3725 } else {
3726 err = GetLastError();
3727 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3730 } else if (ret == WAIT_TIMEOUT) {
3731 } else {
3732 err = GetLastError();
3733 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3737 *timeout = 0;
3739 #else
3740 static void host_main_loop_wait(int *timeout)
3743 #endif
3745 void main_loop_wait(int timeout)
3747 IOHandlerRecord *ioh;
3748 fd_set rfds, wfds, xfds;
3749 int ret, nfds;
3750 struct timeval tv;
3752 qemu_bh_update_timeout(&timeout);
3754 host_main_loop_wait(&timeout);
3756 /* poll any events */
3757 /* XXX: separate device handlers from system ones */
3758 nfds = -1;
3759 FD_ZERO(&rfds);
3760 FD_ZERO(&wfds);
3761 FD_ZERO(&xfds);
3762 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3763 if (ioh->deleted)
3764 continue;
3765 if (ioh->fd_read &&
3766 (!ioh->fd_read_poll ||
3767 ioh->fd_read_poll(ioh->opaque) != 0)) {
3768 FD_SET(ioh->fd, &rfds);
3769 if (ioh->fd > nfds)
3770 nfds = ioh->fd;
3772 if (ioh->fd_write) {
3773 FD_SET(ioh->fd, &wfds);
3774 if (ioh->fd > nfds)
3775 nfds = ioh->fd;
3779 tv.tv_sec = timeout / 1000;
3780 tv.tv_usec = (timeout % 1000) * 1000;
3782 #if defined(CONFIG_SLIRP)
3783 if (slirp_is_inited()) {
3784 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3786 #endif
3787 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3788 if (ret > 0) {
3789 IOHandlerRecord **pioh;
3791 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3792 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3793 ioh->fd_read(ioh->opaque);
3794 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3795 FD_CLR(ioh->fd, &rfds);
3797 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3798 ioh->fd_write(ioh->opaque);
3802 /* remove deleted IO handlers */
3803 pioh = &first_io_handler;
3804 while (*pioh) {
3805 ioh = *pioh;
3806 if (ioh->deleted) {
3807 *pioh = ioh->next;
3808 qemu_free(ioh);
3809 } else
3810 pioh = &ioh->next;
3813 #if defined(CONFIG_SLIRP)
3814 if (slirp_is_inited()) {
3815 if (ret < 0) {
3816 FD_ZERO(&rfds);
3817 FD_ZERO(&wfds);
3818 FD_ZERO(&xfds);
3820 slirp_select_poll(&rfds, &wfds, &xfds);
3822 #endif
3824 /* vm time timers */
3825 if (vm_running && (!cur_cpu
3826 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3827 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3828 qemu_get_clock(vm_clock));
3830 /* real time timers */
3831 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3832 qemu_get_clock(rt_clock));
3834 /* Check bottom-halves last in case any of the earlier events triggered
3835 them. */
3836 qemu_bh_poll();
3840 static int main_loop(void)
3842 int ret, timeout;
3843 #ifdef CONFIG_PROFILER
3844 int64_t ti;
3845 #endif
3846 CPUState *env;
3849 if (kvm_enabled()) {
3850 kvm_main_loop();
3851 cpu_disable_ticks();
3852 return 0;
3855 cur_cpu = first_cpu;
3856 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3857 for(;;) {
3858 if (vm_running) {
3860 for(;;) {
3861 /* get next cpu */
3862 env = next_cpu;
3863 #ifdef CONFIG_PROFILER
3864 ti = profile_getclock();
3865 #endif
3866 if (use_icount) {
3867 int64_t count;
3868 int decr;
3869 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3870 env->icount_decr.u16.low = 0;
3871 env->icount_extra = 0;
3872 count = qemu_next_deadline();
3873 count = (count + (1 << icount_time_shift) - 1)
3874 >> icount_time_shift;
3875 qemu_icount += count;
3876 decr = (count > 0xffff) ? 0xffff : count;
3877 count -= decr;
3878 env->icount_decr.u16.low = decr;
3879 env->icount_extra = count;
3881 ret = cpu_exec(env);
3882 #ifdef CONFIG_PROFILER
3883 qemu_time += profile_getclock() - ti;
3884 #endif
3885 if (use_icount) {
3886 /* Fold pending instructions back into the
3887 instruction counter, and clear the interrupt flag. */
3888 qemu_icount -= (env->icount_decr.u16.low
3889 + env->icount_extra);
3890 env->icount_decr.u32 = 0;
3891 env->icount_extra = 0;
3893 next_cpu = env->next_cpu ?: first_cpu;
3894 if (event_pending && likely(ret != EXCP_DEBUG)) {
3895 ret = EXCP_INTERRUPT;
3896 event_pending = 0;
3897 break;
3899 if (ret == EXCP_HLT) {
3900 /* Give the next CPU a chance to run. */
3901 cur_cpu = env;
3902 continue;
3904 if (ret != EXCP_HALTED)
3905 break;
3906 /* all CPUs are halted ? */
3907 if (env == cur_cpu)
3908 break;
3910 cur_cpu = env;
3912 if (shutdown_requested) {
3913 ret = EXCP_INTERRUPT;
3914 if (no_shutdown) {
3915 vm_stop(0);
3916 no_shutdown = 0;
3918 else
3919 break;
3921 if (reset_requested) {
3922 reset_requested = 0;
3923 qemu_system_reset();
3924 if (kvm_enabled())
3925 kvm_load_registers(env);
3926 ret = EXCP_INTERRUPT;
3928 if (powerdown_requested) {
3929 powerdown_requested = 0;
3930 qemu_system_powerdown();
3931 ret = EXCP_INTERRUPT;
3933 #ifdef CONFIG_GDBSTUB
3934 if (unlikely(ret == EXCP_DEBUG)) {
3935 gdb_set_stop_cpu(cur_cpu);
3936 vm_stop(EXCP_DEBUG);
3938 #endif
3939 /* If all cpus are halted then wait until the next IRQ */
3940 /* XXX: use timeout computed from timers */
3941 if (ret == EXCP_HALTED) {
3942 if (use_icount) {
3943 int64_t add;
3944 int64_t delta;
3945 /* Advance virtual time to the next event. */
3946 if (use_icount == 1) {
3947 /* When not using an adaptive execution frequency
3948 we tend to get badly out of sync with real time,
3949 so just delay for a reasonable amount of time. */
3950 delta = 0;
3951 } else {
3952 delta = cpu_get_icount() - cpu_get_clock();
3954 if (delta > 0) {
3955 /* If virtual time is ahead of real time then just
3956 wait for IO. */
3957 timeout = (delta / 1000000) + 1;
3958 } else {
3959 /* Wait for either IO to occur or the next
3960 timer event. */
3961 add = qemu_next_deadline();
3962 /* We advance the timer before checking for IO.
3963 Limit the amount we advance so that early IO
3964 activity won't get the guest too far ahead. */
3965 if (add > 10000000)
3966 add = 10000000;
3967 delta += add;
3968 add = (add + (1 << icount_time_shift) - 1)
3969 >> icount_time_shift;
3970 qemu_icount += add;
3971 timeout = delta / 1000000;
3972 if (timeout < 0)
3973 timeout = 0;
3975 } else {
3976 timeout = 5000;
3978 } else {
3979 timeout = 0;
3981 } else {
3982 if (shutdown_requested) {
3983 ret = EXCP_INTERRUPT;
3984 break;
3986 timeout = 5000;
3988 #ifdef CONFIG_PROFILER
3989 ti = profile_getclock();
3990 #endif
3991 main_loop_wait(timeout);
3992 #ifdef CONFIG_PROFILER
3993 dev_time += profile_getclock() - ti;
3994 #endif
3996 cpu_disable_ticks();
3997 return ret;
4000 static void help(int exitcode)
4002 /* Please keep in synch with QEMU_OPTION_ enums, qemu_options[]
4003 and qemu-doc.texi */
4004 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
4005 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4006 "usage: %s [options] [disk_image]\n"
4007 "\n"
4008 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4009 "\n"
4010 "Standard options:\n"
4011 "-h or -help display this help and exit\n"
4012 "-M machine select emulated machine (-M ? for list)\n"
4013 "-cpu cpu select CPU (-cpu ? for list)\n"
4014 "-smp n set the number of CPUs to 'n' [default=1]\n"
4015 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4016 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4017 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4018 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4019 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
4020 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
4021 " [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
4022 " [,boot=on|off]\n"
4023 " use 'file' as a drive image\n"
4024 "-mtdblock file use 'file' as on-board Flash memory image\n"
4025 "-sd file use 'file' as SecureDigital card image\n"
4026 "-pflash file use 'file' as a parallel flash image\n"
4027 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4028 "-snapshot write to temporary files instead of disk image files\n"
4029 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4030 #ifndef _WIN32
4031 "-k language use keyboard layout (for example \"fr\" for French)\n"
4032 #endif
4033 #ifdef HAS_AUDIO
4034 "-audio-help print list of audio drivers and their options\n"
4035 "-soundhw c1,... enable audio support\n"
4036 " and only specified sound cards (comma separated list)\n"
4037 " use -soundhw ? to get the list of supported cards\n"
4038 " use -soundhw all to enable all of them\n"
4039 #endif
4040 "-usb enable the USB driver (will be the default soon)\n"
4041 "-usbdevice name add the host or guest USB device 'name'\n"
4042 "-name string set the name of the guest\n"
4043 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x\n"
4044 " specify machine UUID\n"
4045 "\n"
4046 "Display options:\n"
4047 "-nographic disable graphical output and redirect serial I/Os to console\n"
4048 #ifdef CONFIG_CURSES
4049 "-curses use a curses/ncurses interface instead of SDL\n"
4050 #endif
4051 #ifdef CONFIG_SDL
4052 "-no-frame open SDL window without a frame and window decorations\n"
4053 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4054 "-no-quit disable SDL window close capability\n"
4055 "-sdl enable SDL\n"
4056 #endif
4057 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4058 "-vga [std|cirrus|vmware|none]\n"
4059 " select video card type\n"
4060 "-full-screen start in full screen\n"
4061 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4062 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4063 #endif
4064 "-vnc display start a VNC server on display\n"
4065 #ifdef TARGET_IA64
4066 "-nvram file use 'file' to save or load nvram image\n"
4067 #endif
4068 "-name string set the name of the guest\n"
4069 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4070 "\n"
4071 "Network options:\n"
4072 "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
4073 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4074 #ifdef CONFIG_SLIRP
4075 "-net user[,vlan=n][,name=str][,hostname=host]\n"
4076 " connect the user mode network stack to VLAN 'n' and send\n"
4077 " hostname 'host' to DHCP clients\n"
4078 #endif
4079 #ifdef _WIN32
4080 "-net tap[,vlan=n][,name=str],ifname=name\n"
4081 " connect the host TAP network interface to VLAN 'n'\n"
4082 #else
4083 "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4084 " connect the host TAP network interface to VLAN 'n' and use the\n"
4085 " network scripts 'file' (default=%s)\n"
4086 " and 'dfile' (default=%s);\n"
4087 " use '[down]script=no' to disable script execution;\n"
4088 " use 'fd=h' to connect to an already opened TAP interface\n"
4089 #endif
4090 "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4091 " connect the vlan 'n' to another VLAN using a socket connection\n"
4092 "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
4093 " connect the vlan 'n' to multicast maddr and port\n"
4094 #ifdef CONFIG_VDE
4095 "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4096 " connect the vlan 'n' to port 'n' of a vde switch running\n"
4097 " on host and listening for incoming connections on 'socketpath'.\n"
4098 " Use group 'groupname' and mode 'octalmode' to change default\n"
4099 " ownership and permissions for communication port.\n"
4100 #endif
4101 "-net none use it alone to have zero network devices; if no -net option\n"
4102 " is provided, the default is '-net nic -net user'\n"
4103 #ifdef CONFIG_SLIRP
4104 "-tftp dir allow tftp access to files in dir [-net user]\n"
4105 "-bootp file advertise file in BOOTP replies\n"
4106 #ifndef _WIN32
4107 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4108 #endif
4109 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4110 " redirect TCP or UDP connections from host to guest [-net user]\n"
4111 #endif
4112 "\n"
4113 "-bt hci,null dumb bluetooth HCI - doesn't respond to commands\n"
4114 "-bt hci,host[:id]\n"
4115 " use host's HCI with the given name\n"
4116 "-bt hci[,vlan=n]\n"
4117 " emulate a standard HCI in virtual scatternet 'n'\n"
4118 "-bt vhci[,vlan=n]\n"
4119 " add host computer to virtual scatternet 'n' using VHCI\n"
4120 "-bt device:dev[,vlan=n]\n"
4121 " emulate a bluetooth device 'dev' in scatternet 'n'\n"
4122 "\n"
4123 #ifdef TARGET_I386
4124 "\n"
4125 "i386 target only:\n"
4126 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4127 "-rtc-td-hack use it to fix time drift in Windows ACPI HAL\n"
4128 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
4129 "-no-acpi disable ACPI\n"
4130 "-no-hpet disable HPET\n"
4131 "-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"
4132 " ACPI table description\n"
4133 #endif
4134 "Linux boot specific:\n"
4135 "-kernel bzImage use 'bzImage' as kernel image\n"
4136 "-append cmdline use 'cmdline' as kernel command line\n"
4137 "-initrd file use 'file' as initial ram disk\n"
4138 "\n"
4139 "Debug/Expert options:\n"
4140 "-serial dev redirect the serial port to char device 'dev'\n"
4141 "-parallel dev redirect the parallel port to char device 'dev'\n"
4142 "-monitor dev redirect the monitor to char device 'dev'\n"
4143 "-pidfile file write PID to 'file'\n"
4144 "-S freeze CPU at startup (use 'c' to start execution)\n"
4145 "-s wait gdb connection to port\n"
4146 "-p port set gdb connection port [default=%s]\n"
4147 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4148 "-hdachs c,h,s[,t]\n"
4149 " force hard disk 0 physical geometry and the optional BIOS\n"
4150 " translation (t=none or lba) (usually qemu can guess them)\n"
4151 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
4152 "-bios file set the filename for the BIOS\n"
4153 #ifdef USE_KQEMU
4154 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
4155 "-no-kqemu disable KQEMU kernel module usage\n"
4156 #endif
4157 #ifdef CONFIG_KVM
4158 "-enable-kvm enable KVM full virtualization support\n"
4159 #endif
4160 #ifdef USE_KVM
4161 #ifndef NO_CPU_EMULATION
4162 "-no-kvm disable KVM hardware virtualization\n"
4163 #endif
4164 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
4165 "-no-kvm-pit disable KVM kernel mode PIT\n"
4166 "-no-kvm-pit-reinjection disable KVM kernel mode PIT interrupt reinjection\n"
4167 "-enable-nesting enable support for running a VM inside the VM (AMD only)\n"
4168 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4169 "-pcidevice host=bus:dev.func[,dma=none][,name=string]\n"
4170 " expose a PCI device to the guest OS.\n"
4171 " dma=none: don't perform any dma translations (default is to use an iommu)\n"
4172 " 'string' is used in log output.\n"
4173 #endif
4174 #endif
4175 "-no-reboot exit instead of rebooting\n"
4176 "-no-shutdown stop before shutdown\n"
4177 "-loadvm [tag|id]\n"
4178 " start right away with a saved state (loadvm in monitor)\n"
4179 #ifndef _WIN32
4180 "-daemonize daemonize QEMU after initializing\n"
4181 #endif
4182 "-tdf inject timer interrupts that got lost\n"
4183 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
4184 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also\n"
4185 " enables allocation of guest memory with huge pages\n"
4186 #ifdef MAP_POPULATE
4187 "-mem-prealloc toggles preallocation of -mem-path backed physical memory\n"
4188 " at startup. Default is enabled.\n"
4189 #endif
4190 "-option-rom rom load a file, rom, into the option ROM space\n"
4191 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4192 "-prom-env variable=value\n"
4193 " set OpenBIOS nvram variables\n"
4194 #endif
4195 "-clock force the use of the given methods for timer alarm.\n"
4196 " To see what timers are available use -clock ?\n"
4197 "-localtime set the real time clock to local time [default=utc]\n"
4198 "-startdate select initial date of the clock\n"
4199 "-icount [N|auto]\n"
4200 " enable virtual instruction counter with 2^N clock ticks per instruction\n"
4201 "-echr chr set terminal escape character instead of ctrl-a\n"
4202 "-virtioconsole c\n"
4203 " set virtio console\n"
4204 "-show-cursor show cursor\n"
4205 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4206 "-semihosting semihosting mode\n"
4207 #endif
4208 #if defined(TARGET_ARM)
4209 "-old-param old param mode\n"
4210 #endif
4211 "-tb-size n set TB size\n"
4212 "-incoming p prepare for incoming migration, listen on port p\n"
4213 #ifndef _WIN32
4214 "-chroot dir Chroot to dir just before starting the VM.\n"
4215 "-runas user Change to user id user just before starting the VM.\n"
4216 #endif
4217 "\n"
4218 "During emulation, the following keys are useful:\n"
4219 "ctrl-alt-f toggle full screen\n"
4220 "ctrl-alt-n switch to virtual console 'n'\n"
4221 "ctrl-alt toggle mouse and keyboard grab\n"
4222 "\n"
4223 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4225 "qemu",
4226 DEFAULT_RAM_SIZE,
4227 #ifndef _WIN32
4228 DEFAULT_NETWORK_SCRIPT,
4229 DEFAULT_NETWORK_DOWN_SCRIPT,
4230 #endif
4231 DEFAULT_GDBSTUB_PORT,
4232 "/tmp/qemu.log");
4233 exit(exitcode);
4236 #define HAS_ARG 0x0001
4238 enum {
4239 /* Please keep in synch with help, qemu_options[] and
4240 qemu-doc.texi */
4241 /* Standard options: */
4242 QEMU_OPTION_h,
4243 QEMU_OPTION_M,
4244 QEMU_OPTION_cpu,
4245 QEMU_OPTION_smp,
4246 QEMU_OPTION_fda,
4247 QEMU_OPTION_fdb,
4248 QEMU_OPTION_hda,
4249 QEMU_OPTION_hdb,
4250 QEMU_OPTION_hdc,
4251 QEMU_OPTION_hdd,
4252 QEMU_OPTION_cdrom,
4253 QEMU_OPTION_drive,
4254 QEMU_OPTION_mtdblock,
4255 QEMU_OPTION_sd,
4256 QEMU_OPTION_pflash,
4257 QEMU_OPTION_boot,
4258 QEMU_OPTION_snapshot,
4259 QEMU_OPTION_m,
4260 QEMU_OPTION_k,
4261 QEMU_OPTION_audio_help,
4262 QEMU_OPTION_soundhw,
4263 QEMU_OPTION_usb,
4264 QEMU_OPTION_usbdevice,
4265 QEMU_OPTION_name,
4266 QEMU_OPTION_uuid,
4268 /* Display options: */
4269 QEMU_OPTION_nographic,
4270 QEMU_OPTION_curses,
4271 QEMU_OPTION_no_frame,
4272 QEMU_OPTION_alt_grab,
4273 QEMU_OPTION_no_quit,
4274 QEMU_OPTION_sdl,
4275 QEMU_OPTION_portrait,
4276 QEMU_OPTION_vga,
4277 QEMU_OPTION_full_screen,
4278 QEMU_OPTION_g,
4279 QEMU_OPTION_vnc,
4281 /* Network options: */
4282 QEMU_OPTION_net,
4283 QEMU_OPTION_tftp,
4284 QEMU_OPTION_bootp,
4285 QEMU_OPTION_smb,
4286 QEMU_OPTION_redir,
4287 QEMU_OPTION_bt,
4289 /* i386 target only: */
4290 QEMU_OPTION_win2k_hack,
4291 QEMU_OPTION_rtc_td_hack,
4292 QEMU_OPTION_no_fd_bootchk,
4293 QEMU_OPTION_no_acpi,
4294 QEMU_OPTION_no_hpet,
4295 QEMU_OPTION_acpitable,
4297 /* Linux boot specific: */
4298 QEMU_OPTION_kernel,
4299 QEMU_OPTION_append,
4300 QEMU_OPTION_initrd,
4302 /* Debug/Expert options: */
4303 QEMU_OPTION_serial,
4304 QEMU_OPTION_parallel,
4305 QEMU_OPTION_monitor,
4306 QEMU_OPTION_pidfile,
4307 QEMU_OPTION_S,
4308 QEMU_OPTION_s,
4309 QEMU_OPTION_p,
4310 QEMU_OPTION_d,
4311 QEMU_OPTION_hdachs,
4312 QEMU_OPTION_L,
4313 QEMU_OPTION_bios,
4314 QEMU_OPTION_kernel_kqemu,
4315 QEMU_OPTION_no_kqemu,
4316 QEMU_OPTION_enable_kvm,
4317 QEMU_OPTION_enable_nesting,
4318 QEMU_OPTION_no_kvm,
4319 QEMU_OPTION_no_kvm_irqchip,
4320 QEMU_OPTION_no_kvm_pit,
4321 QEMU_OPTION_no_kvm_pit_reinjection,
4322 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4323 QEMU_OPTION_pcidevice,
4324 #endif
4325 QEMU_OPTION_no_reboot,
4326 QEMU_OPTION_no_shutdown,
4327 QEMU_OPTION_loadvm,
4328 QEMU_OPTION_daemonize,
4329 QEMU_OPTION_option_rom,
4330 QEMU_OPTION_cpu_vendor,
4331 QEMU_OPTION_nvram,
4332 QEMU_OPTION_prom_env,
4333 QEMU_OPTION_clock,
4334 QEMU_OPTION_localtime,
4335 QEMU_OPTION_startdate,
4336 QEMU_OPTION_icount,
4337 QEMU_OPTION_echr,
4338 QEMU_OPTION_virtiocon,
4339 QEMU_OPTION_show_cursor,
4340 QEMU_OPTION_semihosting,
4341 QEMU_OPTION_old_param,
4342 QEMU_OPTION_tb_size,
4343 QEMU_OPTION_incoming,
4344 QEMU_OPTION_chroot,
4345 QEMU_OPTION_runas,
4346 QEMU_OPTION_tdf,
4347 QEMU_OPTION_kvm_shadow_memory,
4348 QEMU_OPTION_mempath,
4349 #ifdef MAP_POPULATE
4350 QEMU_OPTION_mem_prealloc,
4351 #endif
4354 typedef struct QEMUOption {
4355 const char *name;
4356 int flags;
4357 int index;
4358 } QEMUOption;
4360 static const QEMUOption qemu_options[] = {
4361 /* Please keep in synch with help, QEMU_OPTION_ enums, and
4362 qemu-doc.texi */
4363 /* Standard options: */
4364 { "h", 0, QEMU_OPTION_h },
4365 { "help", 0, QEMU_OPTION_h },
4366 { "M", HAS_ARG, QEMU_OPTION_M },
4367 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4368 { "smp", HAS_ARG, QEMU_OPTION_smp },
4369 { "fda", HAS_ARG, QEMU_OPTION_fda },
4370 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4371 { "hda", HAS_ARG, QEMU_OPTION_hda },
4372 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4373 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4374 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4375 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4376 { "drive", HAS_ARG, QEMU_OPTION_drive },
4377 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4378 { "sd", HAS_ARG, QEMU_OPTION_sd },
4379 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4380 { "boot", HAS_ARG, QEMU_OPTION_boot },
4381 { "snapshot", 0, QEMU_OPTION_snapshot },
4382 { "m", HAS_ARG, QEMU_OPTION_m },
4383 { "k", HAS_ARG, QEMU_OPTION_k },
4384 #ifdef HAS_AUDIO
4385 { "audio-help", 0, QEMU_OPTION_audio_help },
4386 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4387 #endif
4388 { "usb", 0, QEMU_OPTION_usb },
4389 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4390 { "name", HAS_ARG, QEMU_OPTION_name },
4391 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4393 /* Display options: */
4394 { "nographic", 0, QEMU_OPTION_nographic },
4395 #ifdef CONFIG_CURSES
4396 { "curses", 0, QEMU_OPTION_curses },
4397 #endif
4398 #ifdef CONFIG_SDL
4399 { "no-frame", 0, QEMU_OPTION_no_frame },
4400 { "alt-grab", 0, QEMU_OPTION_alt_grab },
4401 { "no-quit", 0, QEMU_OPTION_no_quit },
4402 { "sdl", 0, QEMU_OPTION_sdl },
4403 #endif
4404 { "portrait", 0, QEMU_OPTION_portrait },
4405 { "vga", HAS_ARG, QEMU_OPTION_vga },
4406 { "full-screen", 0, QEMU_OPTION_full_screen },
4407 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4408 { "g", 1, QEMU_OPTION_g },
4409 #endif
4410 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4412 /* Network options: */
4413 { "net", HAS_ARG, QEMU_OPTION_net},
4414 #ifdef CONFIG_SLIRP
4415 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4416 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4417 #ifndef _WIN32
4418 { "smb", HAS_ARG, QEMU_OPTION_smb },
4419 #endif
4420 { "redir", HAS_ARG, QEMU_OPTION_redir },
4421 #endif
4422 { "bt", HAS_ARG, QEMU_OPTION_bt },
4423 #ifdef TARGET_I386
4424 /* i386 target only: */
4425 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4426 { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4427 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4428 { "no-acpi", 0, QEMU_OPTION_no_acpi },
4429 { "no-hpet", 0, QEMU_OPTION_no_hpet },
4430 { "acpitable", HAS_ARG, QEMU_OPTION_acpitable },
4431 #endif
4433 /* Linux boot specific: */
4434 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4435 { "append", HAS_ARG, QEMU_OPTION_append },
4436 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4438 /* Debug/Expert options: */
4439 { "serial", HAS_ARG, QEMU_OPTION_serial },
4440 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4441 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4442 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4443 { "S", 0, QEMU_OPTION_S },
4444 { "s", 0, QEMU_OPTION_s },
4445 { "p", HAS_ARG, QEMU_OPTION_p },
4446 { "d", HAS_ARG, QEMU_OPTION_d },
4447 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4448 { "L", HAS_ARG, QEMU_OPTION_L },
4449 { "bios", HAS_ARG, QEMU_OPTION_bios },
4450 #ifdef USE_KQEMU
4451 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4452 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4453 #endif
4454 #ifdef CONFIG_KVM
4455 { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4456 #endif
4457 #ifdef USE_KVM
4458 #ifndef NO_CPU_EMULATION
4459 { "no-kvm", 0, QEMU_OPTION_no_kvm },
4460 #endif
4461 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip },
4462 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit },
4463 { "no-kvm-pit-reinjection", 0, QEMU_OPTION_no_kvm_pit_reinjection },
4464 { "enable-nesting", 0, QEMU_OPTION_enable_nesting },
4465 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
4466 { "pcidevice", HAS_ARG, QEMU_OPTION_pcidevice },
4467 #endif
4468 #endif
4469 { "no-reboot", 0, QEMU_OPTION_no_reboot },
4470 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4471 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4472 { "daemonize", 0, QEMU_OPTION_daemonize },
4473 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4474 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4475 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4476 #endif
4477 { "clock", HAS_ARG, QEMU_OPTION_clock },
4478 { "localtime", 0, QEMU_OPTION_localtime },
4479 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4480 { "icount", HAS_ARG, QEMU_OPTION_icount },
4481 { "echr", HAS_ARG, QEMU_OPTION_echr },
4482 { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4483 { "show-cursor", 0, QEMU_OPTION_show_cursor },
4484 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4485 { "semihosting", 0, QEMU_OPTION_semihosting },
4486 #endif
4487 { "tdf", 0, QEMU_OPTION_tdf }, /* enable time drift fix */
4488 { "kvm-shadow-memory", HAS_ARG, QEMU_OPTION_kvm_shadow_memory },
4489 { "nvram", HAS_ARG, QEMU_OPTION_nvram },
4490 { "cpu-vendor", HAS_ARG, QEMU_OPTION_cpu_vendor },
4491 #if defined(TARGET_ARM)
4492 { "old-param", 0, QEMU_OPTION_old_param },
4493 #endif
4494 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4495 { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4496 { "chroot", HAS_ARG, QEMU_OPTION_chroot },
4497 { "runas", HAS_ARG, QEMU_OPTION_runas },
4498 { "mem-path", HAS_ARG, QEMU_OPTION_mempath },
4499 #ifdef MAP_POPULATE
4500 { "mem-prealloc", 0, QEMU_OPTION_mem_prealloc },
4501 #endif
4502 { NULL },
4505 #ifdef HAS_AUDIO
4506 struct soundhw soundhw[] = {
4507 #ifdef HAS_AUDIO_CHOICE
4508 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4510 "pcspk",
4511 "PC speaker",
4514 { .init_isa = pcspk_audio_init }
4516 #endif
4518 #ifdef CONFIG_SB16
4520 "sb16",
4521 "Creative Sound Blaster 16",
4524 { .init_isa = SB16_init }
4526 #endif
4528 #ifdef CONFIG_CS4231A
4530 "cs4231a",
4531 "CS4231A",
4534 { .init_isa = cs4231a_init }
4536 #endif
4538 #ifdef CONFIG_ADLIB
4540 "adlib",
4541 #ifdef HAS_YMF262
4542 "Yamaha YMF262 (OPL3)",
4543 #else
4544 "Yamaha YM3812 (OPL2)",
4545 #endif
4548 { .init_isa = Adlib_init }
4550 #endif
4552 #ifdef CONFIG_GUS
4554 "gus",
4555 "Gravis Ultrasound GF1",
4558 { .init_isa = GUS_init }
4560 #endif
4562 #ifdef CONFIG_AC97
4564 "ac97",
4565 "Intel 82801AA AC97 Audio",
4568 { .init_pci = ac97_init }
4570 #endif
4572 #ifdef CONFIG_ES1370
4574 "es1370",
4575 "ENSONIQ AudioPCI ES1370",
4578 { .init_pci = es1370_init }
4580 #endif
4582 #endif /* HAS_AUDIO_CHOICE */
4584 { NULL, NULL, 0, 0, { NULL } }
4587 static void select_soundhw (const char *optarg)
4589 struct soundhw *c;
4591 if (*optarg == '?') {
4592 show_valid_cards:
4594 printf ("Valid sound card names (comma separated):\n");
4595 for (c = soundhw; c->name; ++c) {
4596 printf ("%-11s %s\n", c->name, c->descr);
4598 printf ("\n-soundhw all will enable all of the above\n");
4599 exit (*optarg != '?');
4601 else {
4602 size_t l;
4603 const char *p;
4604 char *e;
4605 int bad_card = 0;
4607 if (!strcmp (optarg, "all")) {
4608 for (c = soundhw; c->name; ++c) {
4609 c->enabled = 1;
4611 return;
4614 p = optarg;
4615 while (*p) {
4616 e = strchr (p, ',');
4617 l = !e ? strlen (p) : (size_t) (e - p);
4619 for (c = soundhw; c->name; ++c) {
4620 if (!strncmp (c->name, p, l)) {
4621 c->enabled = 1;
4622 break;
4626 if (!c->name) {
4627 if (l > 80) {
4628 fprintf (stderr,
4629 "Unknown sound card name (too big to show)\n");
4631 else {
4632 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4633 (int) l, p);
4635 bad_card = 1;
4637 p += l + (e != NULL);
4640 if (bad_card)
4641 goto show_valid_cards;
4644 #endif
4646 static void select_vgahw (const char *p)
4648 const char *opts;
4650 if (strstart(p, "std", &opts)) {
4651 std_vga_enabled = 1;
4652 cirrus_vga_enabled = 0;
4653 vmsvga_enabled = 0;
4654 } else if (strstart(p, "cirrus", &opts)) {
4655 cirrus_vga_enabled = 1;
4656 std_vga_enabled = 0;
4657 vmsvga_enabled = 0;
4658 } else if (strstart(p, "vmware", &opts)) {
4659 cirrus_vga_enabled = 0;
4660 std_vga_enabled = 0;
4661 vmsvga_enabled = 1;
4662 } else if (strstart(p, "none", &opts)) {
4663 cirrus_vga_enabled = 0;
4664 std_vga_enabled = 0;
4665 vmsvga_enabled = 0;
4666 } else {
4667 invalid_vga:
4668 fprintf(stderr, "Unknown vga type: %s\n", p);
4669 exit(1);
4671 while (*opts) {
4672 const char *nextopt;
4674 if (strstart(opts, ",retrace=", &nextopt)) {
4675 opts = nextopt;
4676 if (strstart(opts, "dumb", &nextopt))
4677 vga_retrace_method = VGA_RETRACE_DUMB;
4678 else if (strstart(opts, "precise", &nextopt))
4679 vga_retrace_method = VGA_RETRACE_PRECISE;
4680 else goto invalid_vga;
4681 } else goto invalid_vga;
4682 opts = nextopt;
4686 #ifdef _WIN32
4687 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4689 exit(STATUS_CONTROL_C_EXIT);
4690 return TRUE;
4692 #endif
4694 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4696 int ret;
4698 if(strlen(str) != 36)
4699 return -1;
4701 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4702 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4703 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4705 if(ret != 16)
4706 return -1;
4708 return 0;
4711 #define MAX_NET_CLIENTS 32
4713 static int saved_argc;
4714 static char **saved_argv;
4716 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4718 *argc = saved_argc;
4719 *argv = saved_argv;
4720 *opt_daemonize = daemonize;
4721 *opt_incoming = incoming;
4724 #ifdef USE_KVM
4725 static int gethugepagesize(void)
4727 int ret, fd;
4728 char buf[4096];
4729 const char *needle = "Hugepagesize:";
4730 char *size;
4731 unsigned long hugepagesize;
4733 fd = open("/proc/meminfo", O_RDONLY);
4734 if (fd < 0) {
4735 perror("open");
4736 exit(0);
4739 ret = read(fd, buf, sizeof(buf));
4740 if (ret < 0) {
4741 perror("read");
4742 exit(0);
4745 size = strstr(buf, needle);
4746 if (!size)
4747 return 0;
4748 size += strlen(needle);
4749 hugepagesize = strtol(size, NULL, 0);
4750 return hugepagesize;
4753 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4755 char *filename;
4756 void *area;
4757 int fd;
4758 #ifdef MAP_POPULATE
4759 int flags;
4760 #endif
4762 if (!kvm_has_sync_mmu()) {
4763 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4764 return NULL;
4767 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4768 return NULL;
4770 hpagesize = gethugepagesize() * 1024;
4771 if (!hpagesize)
4772 return NULL;
4774 fd = mkstemp(filename);
4775 if (fd < 0) {
4776 perror("mkstemp");
4777 free(filename);
4778 return NULL;
4780 unlink(filename);
4781 free(filename);
4783 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4786 * ftruncate is not supported by hugetlbfs in older
4787 * hosts, so don't bother checking for errors.
4788 * If anything goes wrong with it under other filesystems,
4789 * mmap will fail.
4791 ftruncate(fd, memory);
4793 #ifdef MAP_POPULATE
4794 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4795 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4796 * to sidestep this quirk.
4798 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4799 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4800 #else
4801 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4802 #endif
4803 if (area == MAP_FAILED) {
4804 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4805 close(fd);
4806 return (NULL);
4808 *len = memory;
4809 return area;
4811 #endif
4813 static void *qemu_alloc_physram(unsigned long memory)
4815 void *area = NULL;
4816 #ifdef USE_KVM
4817 unsigned long map_len = memory;
4819 if (mem_path)
4820 area = alloc_mem_area(memory, &map_len, mem_path);
4821 #endif
4822 if (!area)
4823 area = qemu_vmalloc(memory);
4824 #ifdef USE_KVM
4825 if (kvm_setup_guest_memory(area, map_len))
4826 area = NULL;
4827 #endif
4828 return area;
4831 #ifndef _WIN32
4833 static void termsig_handler(int signal)
4835 qemu_system_shutdown_request();
4838 static void termsig_setup(void)
4840 struct sigaction act;
4842 memset(&act, 0, sizeof(act));
4843 act.sa_handler = termsig_handler;
4844 sigaction(SIGINT, &act, NULL);
4845 sigaction(SIGHUP, &act, NULL);
4846 sigaction(SIGTERM, &act, NULL);
4849 #endif
4851 int main(int argc, char **argv, char **envp)
4853 #ifdef CONFIG_GDBSTUB
4854 int use_gdbstub;
4855 const char *gdbstub_port;
4856 #endif
4857 uint32_t boot_devices_bitmap = 0;
4858 int i;
4859 int snapshot, linux_boot, net_boot;
4860 const char *initrd_filename;
4861 const char *kernel_filename, *kernel_cmdline;
4862 const char *boot_devices = "";
4863 DisplayState *ds;
4864 DisplayChangeListener *dcl;
4865 int cyls, heads, secs, translation;
4866 const char *net_clients[MAX_NET_CLIENTS];
4867 int nb_net_clients;
4868 const char *bt_opts[MAX_BT_CMDLINE];
4869 int nb_bt_opts;
4870 int hda_index;
4871 int optind;
4872 const char *r, *optarg;
4873 CharDriverState *monitor_hd = NULL;
4874 const char *monitor_device;
4875 const char *serial_devices[MAX_SERIAL_PORTS];
4876 int serial_device_index;
4877 const char *parallel_devices[MAX_PARALLEL_PORTS];
4878 int parallel_device_index;
4879 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4880 int virtio_console_index;
4881 const char *loadvm = NULL;
4882 QEMUMachine *machine;
4883 const char *cpu_model;
4884 const char *usb_devices[MAX_USB_CMDLINE];
4885 int usb_devices_index;
4886 int fds[2];
4887 int tb_size;
4888 const char *pid_file = NULL;
4889 const char *incoming = NULL;
4890 int fd = 0;
4891 struct passwd *pwd = NULL;
4892 const char *chroot_dir = NULL;
4893 const char *run_as = NULL;
4895 qemu_cache_utils_init(envp);
4897 LIST_INIT (&vm_change_state_head);
4898 #ifndef _WIN32
4900 struct sigaction act;
4901 sigfillset(&act.sa_mask);
4902 act.sa_flags = 0;
4903 act.sa_handler = SIG_IGN;
4904 sigaction(SIGPIPE, &act, NULL);
4906 #else
4907 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4908 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4909 QEMU to run on a single CPU */
4911 HANDLE h;
4912 DWORD mask, smask;
4913 int i;
4914 h = GetCurrentProcess();
4915 if (GetProcessAffinityMask(h, &mask, &smask)) {
4916 for(i = 0; i < 32; i++) {
4917 if (mask & (1 << i))
4918 break;
4920 if (i != 32) {
4921 mask = 1 << i;
4922 SetProcessAffinityMask(h, mask);
4926 #endif
4928 register_machines();
4929 machine = first_machine;
4930 cpu_model = NULL;
4931 initrd_filename = NULL;
4932 ram_size = 0;
4933 vga_ram_size = VGA_RAM_SIZE;
4934 #ifdef CONFIG_GDBSTUB
4935 use_gdbstub = 0;
4936 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4937 #endif
4938 snapshot = 0;
4939 nographic = 0;
4940 curses = 0;
4941 kernel_filename = NULL;
4942 kernel_cmdline = "";
4943 cyls = heads = secs = 0;
4944 translation = BIOS_ATA_TRANSLATION_AUTO;
4945 monitor_device = "vc:80Cx24C";
4947 serial_devices[0] = "vc:80Cx24C";
4948 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4949 serial_devices[i] = NULL;
4950 serial_device_index = 0;
4952 parallel_devices[0] = "vc:80Cx24C";
4953 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4954 parallel_devices[i] = NULL;
4955 parallel_device_index = 0;
4957 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4958 virtio_consoles[i] = NULL;
4959 virtio_console_index = 0;
4961 usb_devices_index = 0;
4962 assigned_devices_index = 0;
4964 nb_net_clients = 0;
4965 nb_bt_opts = 0;
4966 nb_drives = 0;
4967 nb_drives_opt = 0;
4968 hda_index = -1;
4970 nb_nics = 0;
4972 tb_size = 0;
4973 autostart= 1;
4975 optind = 1;
4976 for(;;) {
4977 if (optind >= argc)
4978 break;
4979 r = argv[optind];
4980 if (r[0] != '-') {
4981 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4982 } else {
4983 const QEMUOption *popt;
4985 optind++;
4986 /* Treat --foo the same as -foo. */
4987 if (r[1] == '-')
4988 r++;
4989 popt = qemu_options;
4990 for(;;) {
4991 if (!popt->name) {
4992 fprintf(stderr, "%s: invalid option -- '%s'\n",
4993 argv[0], r);
4994 exit(1);
4996 if (!strcmp(popt->name, r + 1))
4997 break;
4998 popt++;
5000 if (popt->flags & HAS_ARG) {
5001 if (optind >= argc) {
5002 fprintf(stderr, "%s: option '%s' requires an argument\n",
5003 argv[0], r);
5004 exit(1);
5006 optarg = argv[optind++];
5007 } else {
5008 optarg = NULL;
5011 switch(popt->index) {
5012 case QEMU_OPTION_M:
5013 machine = find_machine(optarg);
5014 if (!machine) {
5015 QEMUMachine *m;
5016 printf("Supported machines are:\n");
5017 for(m = first_machine; m != NULL; m = m->next) {
5018 printf("%-10s %s%s\n",
5019 m->name, m->desc,
5020 m == first_machine ? " (default)" : "");
5022 exit(*optarg != '?');
5024 break;
5025 case QEMU_OPTION_cpu:
5026 /* hw initialization will check this */
5027 if (*optarg == '?') {
5028 /* XXX: implement xxx_cpu_list for targets that still miss it */
5029 #if defined(cpu_list)
5030 cpu_list(stdout, &fprintf);
5031 #endif
5032 exit(0);
5033 } else {
5034 cpu_model = optarg;
5036 break;
5037 case QEMU_OPTION_initrd:
5038 initrd_filename = optarg;
5039 break;
5040 case QEMU_OPTION_hda:
5041 if (cyls == 0)
5042 hda_index = drive_add(optarg, HD_ALIAS, 0);
5043 else
5044 hda_index = drive_add(optarg, HD_ALIAS
5045 ",cyls=%d,heads=%d,secs=%d%s",
5046 0, cyls, heads, secs,
5047 translation == BIOS_ATA_TRANSLATION_LBA ?
5048 ",trans=lba" :
5049 translation == BIOS_ATA_TRANSLATION_NONE ?
5050 ",trans=none" : "");
5051 break;
5052 case QEMU_OPTION_hdb:
5053 case QEMU_OPTION_hdc:
5054 case QEMU_OPTION_hdd:
5055 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5056 break;
5057 case QEMU_OPTION_drive:
5058 drive_add(NULL, "%s", optarg);
5059 break;
5060 case QEMU_OPTION_mtdblock:
5061 drive_add(optarg, MTD_ALIAS);
5062 break;
5063 case QEMU_OPTION_sd:
5064 drive_add(optarg, SD_ALIAS);
5065 break;
5066 case QEMU_OPTION_pflash:
5067 drive_add(optarg, PFLASH_ALIAS);
5068 break;
5069 case QEMU_OPTION_snapshot:
5070 snapshot = 1;
5071 break;
5072 case QEMU_OPTION_hdachs:
5074 const char *p;
5075 p = optarg;
5076 cyls = strtol(p, (char **)&p, 0);
5077 if (cyls < 1 || cyls > 16383)
5078 goto chs_fail;
5079 if (*p != ',')
5080 goto chs_fail;
5081 p++;
5082 heads = strtol(p, (char **)&p, 0);
5083 if (heads < 1 || heads > 16)
5084 goto chs_fail;
5085 if (*p != ',')
5086 goto chs_fail;
5087 p++;
5088 secs = strtol(p, (char **)&p, 0);
5089 if (secs < 1 || secs > 63)
5090 goto chs_fail;
5091 if (*p == ',') {
5092 p++;
5093 if (!strcmp(p, "none"))
5094 translation = BIOS_ATA_TRANSLATION_NONE;
5095 else if (!strcmp(p, "lba"))
5096 translation = BIOS_ATA_TRANSLATION_LBA;
5097 else if (!strcmp(p, "auto"))
5098 translation = BIOS_ATA_TRANSLATION_AUTO;
5099 else
5100 goto chs_fail;
5101 } else if (*p != '\0') {
5102 chs_fail:
5103 fprintf(stderr, "qemu: invalid physical CHS format\n");
5104 exit(1);
5106 if (hda_index != -1)
5107 snprintf(drives_opt[hda_index].opt,
5108 sizeof(drives_opt[hda_index].opt),
5109 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5110 0, cyls, heads, secs,
5111 translation == BIOS_ATA_TRANSLATION_LBA ?
5112 ",trans=lba" :
5113 translation == BIOS_ATA_TRANSLATION_NONE ?
5114 ",trans=none" : "");
5116 break;
5117 case QEMU_OPTION_nographic:
5118 nographic = 1;
5119 break;
5120 #ifdef CONFIG_CURSES
5121 case QEMU_OPTION_curses:
5122 curses = 1;
5123 break;
5124 #endif
5125 case QEMU_OPTION_portrait:
5126 graphic_rotate = 1;
5127 break;
5128 case QEMU_OPTION_kernel:
5129 kernel_filename = optarg;
5130 break;
5131 case QEMU_OPTION_append:
5132 kernel_cmdline = optarg;
5133 break;
5134 case QEMU_OPTION_cdrom:
5135 drive_add(optarg, CDROM_ALIAS);
5136 break;
5137 case QEMU_OPTION_boot:
5138 boot_devices = optarg;
5139 /* We just do some generic consistency checks */
5141 /* Could easily be extended to 64 devices if needed */
5142 const char *p;
5144 boot_devices_bitmap = 0;
5145 for (p = boot_devices; *p != '\0'; p++) {
5146 /* Allowed boot devices are:
5147 * a b : floppy disk drives
5148 * c ... f : IDE disk drives
5149 * g ... m : machine implementation dependant drives
5150 * n ... p : network devices
5151 * It's up to each machine implementation to check
5152 * if the given boot devices match the actual hardware
5153 * implementation and firmware features.
5155 if (*p < 'a' || *p > 'q') {
5156 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5157 exit(1);
5159 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5160 fprintf(stderr,
5161 "Boot device '%c' was given twice\n",*p);
5162 exit(1);
5164 boot_devices_bitmap |= 1 << (*p - 'a');
5167 break;
5168 case QEMU_OPTION_fda:
5169 case QEMU_OPTION_fdb:
5170 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5171 break;
5172 #ifdef TARGET_I386
5173 case QEMU_OPTION_no_fd_bootchk:
5174 fd_bootchk = 0;
5175 break;
5176 #endif
5177 case QEMU_OPTION_net:
5178 if (nb_net_clients >= MAX_NET_CLIENTS) {
5179 fprintf(stderr, "qemu: too many network clients\n");
5180 exit(1);
5182 net_clients[nb_net_clients] = optarg;
5183 nb_net_clients++;
5184 break;
5185 #ifdef CONFIG_SLIRP
5186 case QEMU_OPTION_tftp:
5187 tftp_prefix = optarg;
5188 break;
5189 case QEMU_OPTION_bootp:
5190 bootp_filename = optarg;
5191 break;
5192 #ifndef _WIN32
5193 case QEMU_OPTION_smb:
5194 net_slirp_smb(optarg);
5195 break;
5196 #endif
5197 case QEMU_OPTION_redir:
5198 net_slirp_redir(optarg);
5199 break;
5200 #endif
5201 case QEMU_OPTION_bt:
5202 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5203 fprintf(stderr, "qemu: too many bluetooth options\n");
5204 exit(1);
5206 bt_opts[nb_bt_opts++] = optarg;
5207 break;
5208 #ifdef HAS_AUDIO
5209 case QEMU_OPTION_audio_help:
5210 AUD_help ();
5211 exit (0);
5212 break;
5213 case QEMU_OPTION_soundhw:
5214 select_soundhw (optarg);
5215 break;
5216 #endif
5217 case QEMU_OPTION_h:
5218 help(0);
5219 break;
5220 case QEMU_OPTION_m: {
5221 uint64_t value;
5222 char *ptr;
5224 value = strtoul(optarg, &ptr, 10);
5225 switch (*ptr) {
5226 case 0: case 'M': case 'm':
5227 value <<= 20;
5228 break;
5229 case 'G': case 'g':
5230 value <<= 30;
5231 break;
5232 default:
5233 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5234 exit(1);
5237 /* On 32-bit hosts, QEMU is limited by virtual address space */
5238 if (value > (2047 << 20)
5239 #ifndef USE_KQEMU
5240 && HOST_LONG_BITS == 32
5241 #endif
5243 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5244 exit(1);
5246 if (value != (uint64_t)(ram_addr_t)value) {
5247 fprintf(stderr, "qemu: ram size too large\n");
5248 exit(1);
5250 ram_size = value;
5251 break;
5253 case QEMU_OPTION_d:
5255 int mask;
5256 const CPULogItem *item;
5258 mask = cpu_str_to_log_mask(optarg);
5259 if (!mask) {
5260 printf("Log items (comma separated):\n");
5261 for(item = cpu_log_items; item->mask != 0; item++) {
5262 printf("%-10s %s\n", item->name, item->help);
5264 exit(1);
5266 cpu_set_log(mask);
5268 break;
5269 #ifdef CONFIG_GDBSTUB
5270 case QEMU_OPTION_s:
5271 use_gdbstub = 1;
5272 break;
5273 case QEMU_OPTION_p:
5274 gdbstub_port = optarg;
5275 break;
5276 #endif
5277 case QEMU_OPTION_L:
5278 bios_dir = optarg;
5279 break;
5280 case QEMU_OPTION_bios:
5281 bios_name = optarg;
5282 break;
5283 case QEMU_OPTION_S:
5284 autostart = 0;
5285 break;
5286 case QEMU_OPTION_k:
5287 keyboard_layout = optarg;
5288 break;
5289 case QEMU_OPTION_localtime:
5290 rtc_utc = 0;
5291 break;
5292 case QEMU_OPTION_vga:
5293 select_vgahw (optarg);
5294 break;
5295 case QEMU_OPTION_g:
5297 const char *p;
5298 int w, h, depth;
5299 p = optarg;
5300 w = strtol(p, (char **)&p, 10);
5301 if (w <= 0) {
5302 graphic_error:
5303 fprintf(stderr, "qemu: invalid resolution or depth\n");
5304 exit(1);
5306 if (*p != 'x')
5307 goto graphic_error;
5308 p++;
5309 h = strtol(p, (char **)&p, 10);
5310 if (h <= 0)
5311 goto graphic_error;
5312 if (*p == 'x') {
5313 p++;
5314 depth = strtol(p, (char **)&p, 10);
5315 if (depth != 8 && depth != 15 && depth != 16 &&
5316 depth != 24 && depth != 32)
5317 goto graphic_error;
5318 } else if (*p == '\0') {
5319 depth = graphic_depth;
5320 } else {
5321 goto graphic_error;
5324 graphic_width = w;
5325 graphic_height = h;
5326 graphic_depth = depth;
5328 break;
5329 case QEMU_OPTION_echr:
5331 char *r;
5332 term_escape_char = strtol(optarg, &r, 0);
5333 if (r == optarg)
5334 printf("Bad argument to echr\n");
5335 break;
5337 case QEMU_OPTION_monitor:
5338 monitor_device = optarg;
5339 break;
5340 case QEMU_OPTION_serial:
5341 if (serial_device_index >= MAX_SERIAL_PORTS) {
5342 fprintf(stderr, "qemu: too many serial ports\n");
5343 exit(1);
5345 serial_devices[serial_device_index] = optarg;
5346 serial_device_index++;
5347 break;
5348 case QEMU_OPTION_virtiocon:
5349 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5350 fprintf(stderr, "qemu: too many virtio consoles\n");
5351 exit(1);
5353 virtio_consoles[virtio_console_index] = optarg;
5354 virtio_console_index++;
5355 break;
5356 case QEMU_OPTION_parallel:
5357 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5358 fprintf(stderr, "qemu: too many parallel ports\n");
5359 exit(1);
5361 parallel_devices[parallel_device_index] = optarg;
5362 parallel_device_index++;
5363 break;
5364 case QEMU_OPTION_loadvm:
5365 loadvm = optarg;
5366 break;
5367 case QEMU_OPTION_full_screen:
5368 full_screen = 1;
5369 break;
5370 #ifdef CONFIG_SDL
5371 case QEMU_OPTION_no_frame:
5372 no_frame = 1;
5373 break;
5374 case QEMU_OPTION_alt_grab:
5375 alt_grab = 1;
5376 break;
5377 case QEMU_OPTION_no_quit:
5378 no_quit = 1;
5379 break;
5380 case QEMU_OPTION_sdl:
5381 sdl = 1;
5382 break;
5383 #endif
5384 case QEMU_OPTION_pidfile:
5385 pid_file = optarg;
5386 break;
5387 #ifdef TARGET_I386
5388 case QEMU_OPTION_win2k_hack:
5389 win2k_install_hack = 1;
5390 break;
5391 case QEMU_OPTION_rtc_td_hack:
5392 rtc_td_hack = 1;
5393 break;
5394 case QEMU_OPTION_acpitable:
5395 if(acpi_table_add(optarg) < 0) {
5396 fprintf(stderr, "Wrong acpi table provided\n");
5397 exit(1);
5399 break;
5400 #endif
5401 #ifdef USE_KQEMU
5402 case QEMU_OPTION_no_kqemu:
5403 kqemu_allowed = 0;
5404 break;
5405 case QEMU_OPTION_kernel_kqemu:
5406 kqemu_allowed = 2;
5407 break;
5408 #endif
5409 #ifdef CONFIG_KVM
5410 case QEMU_OPTION_enable_kvm:
5411 kvm_allowed = 1;
5412 #ifdef USE_KQEMU
5413 kqemu_allowed = 0;
5414 #endif
5415 break;
5416 #endif
5417 #ifdef USE_KVM
5418 case QEMU_OPTION_no_kvm:
5419 kvm_allowed = 0;
5420 break;
5421 case QEMU_OPTION_no_kvm_irqchip: {
5422 kvm_irqchip = 0;
5423 kvm_pit = 0;
5424 break;
5426 case QEMU_OPTION_no_kvm_pit: {
5427 kvm_pit = 0;
5428 break;
5430 case QEMU_OPTION_no_kvm_pit_reinjection: {
5431 kvm_pit_reinject = 0;
5432 break;
5434 case QEMU_OPTION_enable_nesting: {
5435 kvm_nested = 1;
5436 break;
5438 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5439 case QEMU_OPTION_pcidevice:
5440 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5441 fprintf(stderr, "Too many assigned devices\n");
5442 exit(1);
5444 assigned_devices[assigned_devices_index] = optarg;
5445 assigned_devices_index++;
5446 break;
5447 #endif
5448 #endif
5449 case QEMU_OPTION_usb:
5450 usb_enabled = 1;
5451 break;
5452 case QEMU_OPTION_usbdevice:
5453 usb_enabled = 1;
5454 if (usb_devices_index >= MAX_USB_CMDLINE) {
5455 fprintf(stderr, "Too many USB devices\n");
5456 exit(1);
5458 usb_devices[usb_devices_index] = optarg;
5459 usb_devices_index++;
5460 break;
5461 case QEMU_OPTION_smp:
5462 smp_cpus = atoi(optarg);
5463 if (smp_cpus < 1) {
5464 fprintf(stderr, "Invalid number of CPUs\n");
5465 exit(1);
5467 break;
5468 case QEMU_OPTION_vnc:
5469 vnc_display = optarg;
5470 break;
5471 case QEMU_OPTION_no_acpi:
5472 acpi_enabled = 0;
5473 break;
5474 case QEMU_OPTION_no_hpet:
5475 no_hpet = 1;
5476 break;
5477 case QEMU_OPTION_no_reboot:
5478 no_reboot = 1;
5479 break;
5480 case QEMU_OPTION_no_shutdown:
5481 no_shutdown = 1;
5482 break;
5483 case QEMU_OPTION_show_cursor:
5484 cursor_hide = 0;
5485 break;
5486 case QEMU_OPTION_uuid:
5487 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5488 fprintf(stderr, "Fail to parse UUID string."
5489 " Wrong format.\n");
5490 exit(1);
5492 break;
5493 case QEMU_OPTION_daemonize:
5494 daemonize = 1;
5495 break;
5496 case QEMU_OPTION_option_rom:
5497 if (nb_option_roms >= MAX_OPTION_ROMS) {
5498 fprintf(stderr, "Too many option ROMs\n");
5499 exit(1);
5501 option_rom[nb_option_roms] = optarg;
5502 nb_option_roms++;
5503 break;
5504 case QEMU_OPTION_semihosting:
5505 semihosting_enabled = 1;
5506 break;
5507 case QEMU_OPTION_tdf:
5508 time_drift_fix = 1;
5509 break;
5510 case QEMU_OPTION_kvm_shadow_memory:
5511 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5512 break;
5513 case QEMU_OPTION_mempath:
5514 mem_path = optarg;
5515 break;
5516 #ifdef MAP_POPULATE
5517 case QEMU_OPTION_mem_prealloc:
5518 mem_prealloc = !mem_prealloc;
5519 break;
5520 #endif
5521 case QEMU_OPTION_name:
5522 qemu_name = optarg;
5523 break;
5524 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5525 case QEMU_OPTION_prom_env:
5526 if (nb_prom_envs >= MAX_PROM_ENVS) {
5527 fprintf(stderr, "Too many prom variables\n");
5528 exit(1);
5530 prom_envs[nb_prom_envs] = optarg;
5531 nb_prom_envs++;
5532 break;
5533 #endif
5534 case QEMU_OPTION_cpu_vendor:
5535 cpu_vendor_string = optarg;
5536 break;
5537 #ifdef TARGET_ARM
5538 case QEMU_OPTION_old_param:
5539 old_param = 1;
5540 break;
5541 #endif
5542 case QEMU_OPTION_clock:
5543 configure_alarms(optarg);
5544 break;
5545 case QEMU_OPTION_startdate:
5547 struct tm tm;
5548 time_t rtc_start_date;
5549 if (!strcmp(optarg, "now")) {
5550 rtc_date_offset = -1;
5551 } else {
5552 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5553 &tm.tm_year,
5554 &tm.tm_mon,
5555 &tm.tm_mday,
5556 &tm.tm_hour,
5557 &tm.tm_min,
5558 &tm.tm_sec) == 6) {
5559 /* OK */
5560 } else if (sscanf(optarg, "%d-%d-%d",
5561 &tm.tm_year,
5562 &tm.tm_mon,
5563 &tm.tm_mday) == 3) {
5564 tm.tm_hour = 0;
5565 tm.tm_min = 0;
5566 tm.tm_sec = 0;
5567 } else {
5568 goto date_fail;
5570 tm.tm_year -= 1900;
5571 tm.tm_mon--;
5572 rtc_start_date = mktimegm(&tm);
5573 if (rtc_start_date == -1) {
5574 date_fail:
5575 fprintf(stderr, "Invalid date format. Valid format are:\n"
5576 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5577 exit(1);
5579 rtc_date_offset = time(NULL) - rtc_start_date;
5582 break;
5583 case QEMU_OPTION_tb_size:
5584 tb_size = strtol(optarg, NULL, 0);
5585 if (tb_size < 0)
5586 tb_size = 0;
5587 break;
5588 case QEMU_OPTION_icount:
5589 use_icount = 1;
5590 if (strcmp(optarg, "auto") == 0) {
5591 icount_time_shift = -1;
5592 } else {
5593 icount_time_shift = strtol(optarg, NULL, 0);
5595 break;
5596 case QEMU_OPTION_incoming:
5597 incoming = optarg;
5598 break;
5599 case QEMU_OPTION_chroot:
5600 chroot_dir = optarg;
5601 break;
5602 case QEMU_OPTION_runas:
5603 run_as = optarg;
5604 case QEMU_OPTION_nvram:
5605 nvram = optarg;
5606 break;
5611 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5612 if (kvm_allowed && kqemu_allowed) {
5613 fprintf(stderr,
5614 "You can not enable both KVM and kqemu at the same time\n");
5615 exit(1);
5617 #endif
5619 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5620 if (smp_cpus > machine->max_cpus) {
5621 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5622 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5623 machine->max_cpus);
5624 exit(1);
5627 if (nographic) {
5628 if (serial_device_index == 0)
5629 serial_devices[0] = "stdio";
5630 if (parallel_device_index == 0)
5631 parallel_devices[0] = "null";
5632 if (strncmp(monitor_device, "vc", 2) == 0)
5633 monitor_device = "stdio";
5636 #ifndef _WIN32
5637 if (daemonize) {
5638 pid_t pid;
5640 if (pipe(fds) == -1)
5641 exit(1);
5643 pid = fork();
5644 if (pid > 0) {
5645 uint8_t status;
5646 ssize_t len;
5648 close(fds[1]);
5650 again:
5651 len = read(fds[0], &status, 1);
5652 if (len == -1 && (errno == EINTR))
5653 goto again;
5655 if (len != 1)
5656 exit(1);
5657 else if (status == 1) {
5658 fprintf(stderr, "Could not acquire pidfile\n");
5659 exit(1);
5660 } else
5661 exit(0);
5662 } else if (pid < 0)
5663 exit(1);
5665 setsid();
5667 pid = fork();
5668 if (pid > 0)
5669 exit(0);
5670 else if (pid < 0)
5671 exit(1);
5673 umask(027);
5675 signal(SIGTSTP, SIG_IGN);
5676 signal(SIGTTOU, SIG_IGN);
5677 signal(SIGTTIN, SIG_IGN);
5679 #endif
5681 #ifdef USE_KVM
5682 if (kvm_enabled()) {
5683 if (kvm_qemu_init() < 0) {
5684 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5685 #ifdef NO_CPU_EMULATION
5686 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5687 exit(1);
5688 #endif
5689 kvm_allowed = 0;
5692 #endif
5694 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5695 if (daemonize) {
5696 uint8_t status = 1;
5697 write(fds[1], &status, 1);
5698 } else
5699 fprintf(stderr, "Could not acquire pid file\n");
5700 exit(1);
5703 #ifdef USE_KQEMU
5704 if (smp_cpus > 1)
5705 kqemu_allowed = 0;
5706 #endif
5707 linux_boot = (kernel_filename != NULL);
5708 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5710 if (!linux_boot && net_boot == 0 &&
5711 !machine->nodisk_ok && nb_drives_opt == 0)
5712 help(1);
5714 if (!linux_boot && *kernel_cmdline != '\0') {
5715 fprintf(stderr, "-append only allowed with -kernel option\n");
5716 exit(1);
5719 if (!linux_boot && initrd_filename != NULL) {
5720 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5721 exit(1);
5724 /* boot to floppy or the default cd if no hard disk defined yet */
5725 if (!boot_devices[0]) {
5726 boot_devices = "cad";
5728 setvbuf(stdout, NULL, _IOLBF, 0);
5730 init_timers();
5731 if (init_timer_alarm() < 0) {
5732 fprintf(stderr, "could not initialize alarm timer\n");
5733 exit(1);
5735 if (use_icount && icount_time_shift < 0) {
5736 use_icount = 2;
5737 /* 125MIPS seems a reasonable initial guess at the guest speed.
5738 It will be corrected fairly quickly anyway. */
5739 icount_time_shift = 3;
5740 init_icount_adjust();
5743 #ifdef _WIN32
5744 socket_init();
5745 #endif
5747 /* init network clients */
5748 if (nb_net_clients == 0) {
5749 /* if no clients, we use a default config */
5750 net_clients[nb_net_clients++] = "nic";
5751 #ifdef CONFIG_SLIRP
5752 net_clients[nb_net_clients++] = "user";
5753 #endif
5756 for(i = 0;i < nb_net_clients; i++) {
5757 if (net_client_parse(net_clients[i]) < 0)
5758 exit(1);
5760 net_client_check();
5762 #ifdef TARGET_I386
5763 /* XXX: this should be moved in the PC machine instantiation code */
5764 if (net_boot != 0) {
5765 int netroms = 0;
5766 for (i = 0; i < nb_nics && i < 4; i++) {
5767 const char *model = nd_table[i].model;
5768 char buf[1024];
5769 if (net_boot & (1 << i)) {
5770 if (model == NULL)
5771 model = "rtl8139";
5772 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5773 if (get_image_size(buf) > 0) {
5774 if (nb_option_roms >= MAX_OPTION_ROMS) {
5775 fprintf(stderr, "Too many option ROMs\n");
5776 exit(1);
5778 option_rom[nb_option_roms] = strdup(buf);
5779 nb_option_roms++;
5780 netroms++;
5784 if (netroms == 0) {
5785 fprintf(stderr, "No valid PXE rom found for network device\n");
5786 exit(1);
5789 #endif
5791 /* init the bluetooth world */
5792 for (i = 0; i < nb_bt_opts; i++)
5793 if (bt_parse(bt_opts[i]))
5794 exit(1);
5796 /* init the memory */
5797 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5799 if (machine->ram_require & RAMSIZE_FIXED) {
5800 if (ram_size > 0) {
5801 if (ram_size < phys_ram_size) {
5802 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5803 machine->name, (unsigned long long) phys_ram_size);
5804 exit(-1);
5807 phys_ram_size = ram_size;
5808 } else
5809 ram_size = phys_ram_size;
5810 } else {
5811 if (ram_size == 0)
5812 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5814 phys_ram_size += ram_size;
5817 /* Initialize kvm */
5818 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5819 #define KVM_EXTRA_PAGES 3
5820 #else
5821 #define KVM_EXTRA_PAGES 0
5822 #endif
5823 if (kvm_enabled()) {
5824 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5825 if (kvm_qemu_create_context() < 0) {
5826 fprintf(stderr, "Could not create KVM context\n");
5827 exit(1);
5831 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5832 if (!phys_ram_base) {
5833 fprintf(stderr, "Could not allocate physical memory\n");
5834 exit(1);
5837 /* init the dynamic translator */
5838 cpu_exec_init_all(tb_size * 1024 * 1024);
5840 bdrv_init();
5841 dma_helper_init();
5843 /* we always create the cdrom drive, even if no disk is there */
5845 if (nb_drives_opt < MAX_DRIVES)
5846 drive_add(NULL, CDROM_ALIAS);
5848 /* we always create at least one floppy */
5850 if (nb_drives_opt < MAX_DRIVES)
5851 drive_add(NULL, FD_ALIAS, 0);
5853 /* we always create one sd slot, even if no card is in it */
5855 if (nb_drives_opt < MAX_DRIVES)
5856 drive_add(NULL, SD_ALIAS);
5858 /* open the virtual block devices
5859 * note that migration with device
5860 * hot add/remove is broken.
5862 for(i = 0; i < nb_drives_opt; i++)
5863 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5864 exit(1);
5866 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5867 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5869 #ifndef _WIN32
5870 /* must be after terminal init, SDL library changes signal handlers */
5871 termsig_setup();
5872 #endif
5874 /* Maintain compatibility with multiple stdio monitors */
5875 if (!strcmp(monitor_device,"stdio")) {
5876 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5877 const char *devname = serial_devices[i];
5878 if (devname && !strcmp(devname,"mon:stdio")) {
5879 monitor_device = NULL;
5880 break;
5881 } else if (devname && !strcmp(devname,"stdio")) {
5882 monitor_device = NULL;
5883 serial_devices[i] = "mon:stdio";
5884 break;
5889 #ifdef KVM_UPSTREAM
5890 if (kvm_enabled()) {
5891 int ret;
5893 ret = kvm_init(smp_cpus);
5894 if (ret < 0) {
5895 fprintf(stderr, "failed to initialize KVM\n");
5896 exit(1);
5899 #endif
5901 if (monitor_device) {
5902 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5903 if (!monitor_hd) {
5904 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5905 exit(1);
5909 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5910 const char *devname = serial_devices[i];
5911 if (devname && strcmp(devname, "none")) {
5912 char label[32];
5913 snprintf(label, sizeof(label), "serial%d", i);
5914 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5915 if (!serial_hds[i]) {
5916 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5917 devname);
5918 exit(1);
5923 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5924 const char *devname = parallel_devices[i];
5925 if (devname && strcmp(devname, "none")) {
5926 char label[32];
5927 snprintf(label, sizeof(label), "parallel%d", i);
5928 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5929 if (!parallel_hds[i]) {
5930 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5931 devname);
5932 exit(1);
5937 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5938 const char *devname = virtio_consoles[i];
5939 if (devname && strcmp(devname, "none")) {
5940 char label[32];
5941 snprintf(label, sizeof(label), "virtcon%d", i);
5942 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5943 if (!virtcon_hds[i]) {
5944 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5945 devname);
5946 exit(1);
5951 if (kvm_enabled())
5952 kvm_init_ap();
5954 machine->init(ram_size, vga_ram_size, boot_devices,
5955 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5957 current_machine = machine;
5959 /* Set KVM's vcpu state to qemu's initial CPUState. */
5960 if (kvm_enabled()) {
5961 int ret;
5963 ret = kvm_sync_vcpus();
5964 if (ret < 0) {
5965 fprintf(stderr, "failed to initialize vcpus\n");
5966 exit(1);
5970 /* init USB devices */
5971 if (usb_enabled) {
5972 for(i = 0; i < usb_devices_index; i++) {
5973 if (usb_device_add(usb_devices[i], 0) < 0) {
5974 fprintf(stderr, "Warning: could not add USB device %s\n",
5975 usb_devices[i]);
5980 if (!display_state)
5981 dumb_display_init();
5982 /* just use the first displaystate for the moment */
5983 ds = display_state;
5984 /* terminal init */
5985 if (nographic) {
5986 if (curses) {
5987 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5988 exit(1);
5990 } else {
5991 #if defined(CONFIG_CURSES)
5992 if (curses) {
5993 /* At the moment curses cannot be used with other displays */
5994 curses_display_init(ds, full_screen);
5995 } else
5996 #endif
5998 if (vnc_display != NULL) {
5999 vnc_display_init(ds);
6000 if (vnc_display_open(ds, vnc_display) < 0)
6001 exit(1);
6003 #if defined(CONFIG_SDL)
6004 if (sdl || !vnc_display)
6005 sdl_display_init(ds, full_screen, no_frame);
6006 #elif defined(CONFIG_COCOA)
6007 if (sdl || !vnc_display)
6008 cocoa_display_init(ds, full_screen);
6009 #endif
6012 dpy_resize(ds);
6014 dcl = ds->listeners;
6015 while (dcl != NULL) {
6016 if (dcl->dpy_refresh != NULL) {
6017 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6018 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6020 dcl = dcl->next;
6023 if (nographic || (vnc_display && !sdl)) {
6024 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6025 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6028 text_consoles_set_display(display_state);
6029 qemu_chr_initial_reset();
6031 if (monitor_device && monitor_hd)
6032 monitor_init(monitor_hd, !nographic);
6034 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6035 const char *devname = serial_devices[i];
6036 if (devname && strcmp(devname, "none")) {
6037 char label[32];
6038 snprintf(label, sizeof(label), "serial%d", i);
6039 if (strstart(devname, "vc", 0))
6040 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6044 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6045 const char *devname = parallel_devices[i];
6046 if (devname && strcmp(devname, "none")) {
6047 char label[32];
6048 snprintf(label, sizeof(label), "parallel%d", i);
6049 if (strstart(devname, "vc", 0))
6050 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6054 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6055 const char *devname = virtio_consoles[i];
6056 if (virtcon_hds[i] && devname) {
6057 char label[32];
6058 snprintf(label, sizeof(label), "virtcon%d", i);
6059 if (strstart(devname, "vc", 0))
6060 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6064 #ifdef CONFIG_GDBSTUB
6065 if (use_gdbstub) {
6066 /* XXX: use standard host:port notation and modify options
6067 accordingly. */
6068 if (gdbserver_start(gdbstub_port) < 0) {
6069 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6070 gdbstub_port);
6071 exit(1);
6074 #endif
6076 if (loadvm)
6077 do_loadvm(loadvm);
6079 if (incoming)
6080 qemu_start_incoming_migration(incoming);
6082 if (autostart)
6083 vm_start();
6085 if (daemonize) {
6086 uint8_t status = 0;
6087 ssize_t len;
6089 again1:
6090 len = write(fds[1], &status, 1);
6091 if (len == -1 && (errno == EINTR))
6092 goto again1;
6094 if (len != 1)
6095 exit(1);
6097 chdir("/");
6098 TFR(fd = open("/dev/null", O_RDWR));
6099 if (fd == -1)
6100 exit(1);
6103 #ifndef _WIN32
6104 if (run_as) {
6105 pwd = getpwnam(run_as);
6106 if (!pwd) {
6107 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6108 exit(1);
6112 if (chroot_dir) {
6113 if (chroot(chroot_dir) < 0) {
6114 fprintf(stderr, "chroot failed\n");
6115 exit(1);
6117 chdir("/");
6120 if (run_as) {
6121 if (setgid(pwd->pw_gid) < 0) {
6122 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6123 exit(1);
6125 if (setuid(pwd->pw_uid) < 0) {
6126 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6127 exit(1);
6129 if (setuid(0) != -1) {
6130 fprintf(stderr, "Dropping privileges failed\n");
6131 exit(1);
6134 #endif
6136 if (daemonize) {
6137 dup2(fd, 0);
6138 dup2(fd, 1);
6139 dup2(fd, 2);
6141 close(fd);
6144 main_loop();
6145 quit_timers();
6146 net_cleanup();
6148 return 0;