Sync idcache after emualted DMA operations for ia64
[qemu-kvm/fedora.git] / vl.c
blob8aa9ebc123d1422009c086d6f79b0ba440d32d8e
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.
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <time.h>
29 #include <errno.h>
30 #include <sys/time.h>
31 #include <zlib.h>
33 /* Needed early for HOST_BSD etc. */
34 #include "config-host.h"
36 #ifndef _WIN32
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <sys/vfs.h>
46 #include <netinet/in.h>
47 #include <net/if.h>
48 #if defined(__NetBSD__)
49 #include <net/if_tap.h>
50 #endif
51 #ifdef __linux__
52 #include <linux/if_tun.h>
53 #endif
54 #include <arpa/inet.h>
55 #include <dirent.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef HOST_BSD
59 #include <sys/stat.h>
60 #if defined(__FreeBSD__) || defined(__DragonFly__)
61 #include <libutil.h>
62 #else
63 #include <util.h>
64 #endif
65 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
66 #include <freebsd/stdlib.h>
67 #else
68 #ifdef __linux__
69 #include <pty.h>
70 #include <malloc.h>
71 #include <linux/rtc.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
76 #include "hpet.h"
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
80 #endif
81 #ifdef __sun__
82 #include <sys/stat.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
92 #include <net/if.h>
93 #include <syslog.h>
94 #include <stropts.h>
95 #endif
96 #endif
97 #endif
99 #if defined(__OpenBSD__)
100 #include <util.h>
101 #endif
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
105 #endif
107 #ifdef _WIN32
108 #include <windows.h>
109 #include <malloc.h>
110 #include <sys/timeb.h>
111 #include <mmsystem.h>
112 #define getopt_long_only getopt_long
113 #define memalign(align, size) malloc(size)
114 #endif
116 #ifdef CONFIG_SDL
117 #ifdef __APPLE__
118 #include <SDL/SDL.h>
119 int qemu_main(int argc, char **argv, char **envp);
120 int main(int argc, char **argv)
122 qemu_main(argc, argv, NULL);
124 #undef main
125 #define main qemu_main
126 #endif
127 #endif /* CONFIG_SDL */
129 #ifdef CONFIG_COCOA
130 #undef main
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
134 #include "hw/hw.h"
135 #include "hw/boards.h"
136 #include "hw/usb.h"
137 #include "hw/pcmcia.h"
138 #include "hw/pc.h"
139 #include "hw/audiodev.h"
140 #include "hw/isa.h"
141 #include "hw/baum.h"
142 #include "hw/bt.h"
143 #include "bt-host.h"
144 #include "net.h"
145 #include "monitor.h"
146 #include "console.h"
147 #include "sysemu.h"
148 #include "gdbstub.h"
149 #include "qemu-timer.h"
150 #include "qemu-char.h"
151 #include "cache-utils.h"
152 #include "block.h"
153 #include "dma.h"
154 #include "audio/audio.h"
155 #include "migration.h"
156 #include "kvm.h"
157 #include "balloon.h"
158 #include "qemu-kvm.h"
159 #include "hw/device-assignment.h"
161 #include "disas.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #if defined(CONFIG_SLIRP)
168 #include "libslirp.h"
169 #endif
171 //#define DEBUG_UNUSED_IOPORT
172 //#define DEBUG_IOPORT
173 //#define DEBUG_NET
174 //#define DEBUG_SLIRP
177 #ifdef DEBUG_IOPORT
178 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
179 #else
180 # define LOG_IOPORT(...) do { } while (0)
181 #endif
183 #define DEFAULT_RAM_SIZE 128
185 /* Max number of USB devices that can be specified on the commandline. */
186 #define MAX_USB_CMDLINE 8
188 /* Max number of bluetooth switches on the commandline. */
189 #define MAX_BT_CMDLINE 10
191 /* XXX: use a two level table to limit memory usage */
192 #define MAX_IOPORTS 65536
194 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
195 const char *bios_name = NULL;
196 static void *ioport_opaque[MAX_IOPORTS];
197 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
198 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
199 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
200 to store the VM snapshots */
201 DriveInfo drives_table[MAX_DRIVES+1];
202 int nb_drives;
203 int extboot_drive = -1;
204 static int vga_ram_size;
205 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
206 static DisplayState *display_state;
207 int nographic;
208 static int curses;
209 static int sdl;
210 const char* keyboard_layout = NULL;
211 int64_t ticks_per_sec;
212 ram_addr_t ram_size;
213 int nb_nics;
214 NICInfo nd_table[MAX_NICS];
215 int vm_running;
216 static int autostart;
217 static int rtc_utc = 1;
218 static int rtc_date_offset = -1; /* -1 means no change */
219 int cirrus_vga_enabled = 1;
220 int std_vga_enabled = 0;
221 int vmsvga_enabled = 0;
222 #ifdef TARGET_SPARC
223 int graphic_width = 1024;
224 int graphic_height = 768;
225 int graphic_depth = 8;
226 #else
227 int graphic_width = 800;
228 int graphic_height = 600;
229 int graphic_depth = 15;
230 #endif
231 static int full_screen = 0;
232 #ifdef CONFIG_SDL
233 static int no_frame = 0;
234 #endif
235 int no_quit = 0;
236 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
237 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
238 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
239 #ifdef TARGET_I386
240 int win2k_install_hack = 0;
241 int rtc_td_hack = 0;
242 #endif
243 int usb_enabled = 0;
244 int singlestep = 0;
245 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
246 int assigned_devices_index;
247 int smp_cpus = 1;
248 const char *vnc_display;
249 int acpi_enabled = 1;
250 int no_hpet = 0;
251 int fd_bootchk = 1;
252 int no_reboot = 0;
253 int no_shutdown = 0;
254 int cursor_hide = 1;
255 int graphic_rotate = 0;
256 #ifndef _WIN32
257 int daemonize = 0;
258 #endif
259 const char *option_rom[MAX_OPTION_ROMS];
260 int nb_option_roms;
261 int semihosting_enabled = 0;
262 int time_drift_fix = 0;
263 unsigned int kvm_shadow_memory = 0;
264 const char *mem_path = NULL;
265 #ifdef MAP_POPULATE
266 int mem_prealloc = 1; /* force preallocation of physical target memory */
267 #endif
268 long hpagesize = 0;
269 const char *cpu_vendor_string;
270 #ifdef TARGET_ARM
271 int old_param = 0;
272 #endif
273 const char *qemu_name;
274 int alt_grab = 0;
275 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
276 unsigned int nb_prom_envs = 0;
277 const char *prom_envs[MAX_PROM_ENVS];
278 #endif
279 int nb_drives_opt;
280 const char *nvram = NULL;
281 struct drive_opt drives_opt[MAX_DRIVES];
283 static CPUState *cur_cpu;
284 static CPUState *next_cpu;
285 static int event_pending = 1;
286 /* Conversion factor from emulated instructions to virtual clock ticks. */
287 static int icount_time_shift;
288 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
289 #define MAX_ICOUNT_SHIFT 10
290 /* Compensate for varying guest execution speed. */
291 static int64_t qemu_icount_bias;
292 static QEMUTimer *icount_rt_timer;
293 static QEMUTimer *icount_vm_timer;
294 static QEMUTimer *nographic_timer;
296 uint8_t qemu_uuid[16];
298 /* KVM runs the main loop in a separate thread. If we update one of the lists
299 * that are polled before or after select(), we need to make sure to break out
300 * of the select() to ensure the new item is serviced.
302 static void main_loop_break(void)
304 if (kvm_enabled())
305 qemu_kvm_notify_work();
308 /***********************************************************/
309 /* x86 ISA bus support */
311 target_phys_addr_t isa_mem_base = 0;
312 PicState2 *isa_pic;
314 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
315 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
317 static uint32_t ioport_read(int index, uint32_t address)
319 static IOPortReadFunc *default_func[3] = {
320 default_ioport_readb,
321 default_ioport_readw,
322 default_ioport_readl
324 IOPortReadFunc *func = ioport_read_table[index][address];
325 if (!func)
326 func = default_func[index];
327 return func(ioport_opaque[address], address);
330 static void ioport_write(int index, uint32_t address, uint32_t data)
332 static IOPortWriteFunc *default_func[3] = {
333 default_ioport_writeb,
334 default_ioport_writew,
335 default_ioport_writel
337 IOPortWriteFunc *func = ioport_write_table[index][address];
338 if (!func)
339 func = default_func[index];
340 func(ioport_opaque[address], address, data);
343 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
345 #ifdef DEBUG_UNUSED_IOPORT
346 fprintf(stderr, "unused inb: port=0x%04x\n", address);
347 #endif
348 return 0xff;
351 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
353 #ifdef DEBUG_UNUSED_IOPORT
354 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
355 #endif
358 /* default is to make two byte accesses */
359 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
361 uint32_t data;
362 data = ioport_read(0, address);
363 address = (address + 1) & (MAX_IOPORTS - 1);
364 data |= ioport_read(0, address) << 8;
365 return data;
368 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
370 ioport_write(0, address, data & 0xff);
371 address = (address + 1) & (MAX_IOPORTS - 1);
372 ioport_write(0, address, (data >> 8) & 0xff);
375 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
377 #ifdef DEBUG_UNUSED_IOPORT
378 fprintf(stderr, "unused inl: port=0x%04x\n", address);
379 #endif
380 return 0xffffffff;
383 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
385 #ifdef DEBUG_UNUSED_IOPORT
386 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
387 #endif
390 /* size is the word size in byte */
391 int register_ioport_read(int start, int length, int size,
392 IOPortReadFunc *func, void *opaque)
394 int i, bsize;
396 if (size == 1) {
397 bsize = 0;
398 } else if (size == 2) {
399 bsize = 1;
400 } else if (size == 4) {
401 bsize = 2;
402 } else {
403 hw_error("register_ioport_read: invalid size");
404 return -1;
406 for(i = start; i < start + length; i += size) {
407 ioport_read_table[bsize][i] = func;
408 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
409 hw_error("register_ioport_read: invalid opaque");
410 ioport_opaque[i] = opaque;
412 return 0;
415 /* size is the word size in byte */
416 int register_ioport_write(int start, int length, int size,
417 IOPortWriteFunc *func, void *opaque)
419 int i, bsize;
421 if (size == 1) {
422 bsize = 0;
423 } else if (size == 2) {
424 bsize = 1;
425 } else if (size == 4) {
426 bsize = 2;
427 } else {
428 hw_error("register_ioport_write: invalid size");
429 return -1;
431 for(i = start; i < start + length; i += size) {
432 ioport_write_table[bsize][i] = func;
433 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
434 hw_error("register_ioport_write: invalid opaque");
435 ioport_opaque[i] = opaque;
437 return 0;
440 void isa_unassign_ioport(int start, int length)
442 int i;
444 for(i = start; i < start + length; i++) {
445 ioport_read_table[0][i] = default_ioport_readb;
446 ioport_read_table[1][i] = default_ioport_readw;
447 ioport_read_table[2][i] = default_ioport_readl;
449 ioport_write_table[0][i] = default_ioport_writeb;
450 ioport_write_table[1][i] = default_ioport_writew;
451 ioport_write_table[2][i] = default_ioport_writel;
453 ioport_opaque[i] = NULL;
457 /***********************************************************/
459 void cpu_outb(CPUState *env, int addr, int val)
461 LOG_IOPORT("outb: %04x %02x\n", addr, val);
462 ioport_write(0, addr, val);
463 #ifdef USE_KQEMU
464 if (env)
465 env->last_io_time = cpu_get_time_fast();
466 #endif
469 void cpu_outw(CPUState *env, int addr, int val)
471 LOG_IOPORT("outw: %04x %04x\n", addr, val);
472 ioport_write(1, addr, val);
473 #ifdef USE_KQEMU
474 if (env)
475 env->last_io_time = cpu_get_time_fast();
476 #endif
479 void cpu_outl(CPUState *env, int addr, int val)
481 LOG_IOPORT("outl: %04x %08x\n", addr, val);
482 ioport_write(2, addr, val);
483 #ifdef USE_KQEMU
484 if (env)
485 env->last_io_time = cpu_get_time_fast();
486 #endif
489 int cpu_inb(CPUState *env, int addr)
491 int val;
492 val = ioport_read(0, addr);
493 LOG_IOPORT("inb : %04x %02x\n", addr, val);
494 #ifdef USE_KQEMU
495 if (env)
496 env->last_io_time = cpu_get_time_fast();
497 #endif
498 return val;
501 int cpu_inw(CPUState *env, int addr)
503 int val;
504 val = ioport_read(1, addr);
505 LOG_IOPORT("inw : %04x %04x\n", addr, val);
506 #ifdef USE_KQEMU
507 if (env)
508 env->last_io_time = cpu_get_time_fast();
509 #endif
510 return val;
513 int cpu_inl(CPUState *env, int addr)
515 int val;
516 val = ioport_read(2, addr);
517 LOG_IOPORT("inl : %04x %08x\n", addr, val);
518 #ifdef USE_KQEMU
519 if (env)
520 env->last_io_time = cpu_get_time_fast();
521 #endif
522 return val;
525 /***********************************************************/
526 void hw_error(const char *fmt, ...)
528 va_list ap;
529 CPUState *env;
531 va_start(ap, fmt);
532 fprintf(stderr, "qemu: hardware error: ");
533 vfprintf(stderr, fmt, ap);
534 fprintf(stderr, "\n");
535 for(env = first_cpu; env != NULL; env = env->next_cpu) {
536 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
537 #ifdef TARGET_I386
538 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
539 #else
540 cpu_dump_state(env, stderr, fprintf, 0);
541 #endif
543 va_end(ap);
544 abort();
547 /***************/
548 /* ballooning */
550 static QEMUBalloonEvent *qemu_balloon_event;
551 void *qemu_balloon_event_opaque;
553 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
555 qemu_balloon_event = func;
556 qemu_balloon_event_opaque = opaque;
559 void qemu_balloon(ram_addr_t target)
561 if (qemu_balloon_event)
562 qemu_balloon_event(qemu_balloon_event_opaque, target);
565 ram_addr_t qemu_balloon_status(void)
567 if (qemu_balloon_event)
568 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
569 return 0;
572 /***********************************************************/
573 /* keyboard/mouse */
575 static QEMUPutKBDEvent *qemu_put_kbd_event;
576 static void *qemu_put_kbd_event_opaque;
577 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
578 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
580 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
582 qemu_put_kbd_event_opaque = opaque;
583 qemu_put_kbd_event = func;
586 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
587 void *opaque, int absolute,
588 const char *name)
590 QEMUPutMouseEntry *s, *cursor;
592 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
594 s->qemu_put_mouse_event = func;
595 s->qemu_put_mouse_event_opaque = opaque;
596 s->qemu_put_mouse_event_absolute = absolute;
597 s->qemu_put_mouse_event_name = qemu_strdup(name);
598 s->next = NULL;
600 if (!qemu_put_mouse_event_head) {
601 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
602 return s;
605 cursor = qemu_put_mouse_event_head;
606 while (cursor->next != NULL)
607 cursor = cursor->next;
609 cursor->next = s;
610 qemu_put_mouse_event_current = s;
612 return s;
615 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
617 QEMUPutMouseEntry *prev = NULL, *cursor;
619 if (!qemu_put_mouse_event_head || entry == NULL)
620 return;
622 cursor = qemu_put_mouse_event_head;
623 while (cursor != NULL && cursor != entry) {
624 prev = cursor;
625 cursor = cursor->next;
628 if (cursor == NULL) // does not exist or list empty
629 return;
630 else if (prev == NULL) { // entry is head
631 qemu_put_mouse_event_head = cursor->next;
632 if (qemu_put_mouse_event_current == entry)
633 qemu_put_mouse_event_current = cursor->next;
634 qemu_free(entry->qemu_put_mouse_event_name);
635 qemu_free(entry);
636 return;
639 prev->next = entry->next;
641 if (qemu_put_mouse_event_current == entry)
642 qemu_put_mouse_event_current = prev;
644 qemu_free(entry->qemu_put_mouse_event_name);
645 qemu_free(entry);
648 void kbd_put_keycode(int keycode)
650 if (qemu_put_kbd_event) {
651 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
655 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
657 QEMUPutMouseEvent *mouse_event;
658 void *mouse_event_opaque;
659 int width;
661 if (!qemu_put_mouse_event_current) {
662 return;
665 mouse_event =
666 qemu_put_mouse_event_current->qemu_put_mouse_event;
667 mouse_event_opaque =
668 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
670 if (mouse_event) {
671 if (graphic_rotate) {
672 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
673 width = 0x7fff;
674 else
675 width = graphic_width - 1;
676 mouse_event(mouse_event_opaque,
677 width - dy, dx, dz, buttons_state);
678 } else
679 mouse_event(mouse_event_opaque,
680 dx, dy, dz, buttons_state);
684 int kbd_mouse_is_absolute(void)
686 if (!qemu_put_mouse_event_current)
687 return 0;
689 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
692 void do_info_mice(Monitor *mon)
694 QEMUPutMouseEntry *cursor;
695 int index = 0;
697 if (!qemu_put_mouse_event_head) {
698 monitor_printf(mon, "No mouse devices connected\n");
699 return;
702 monitor_printf(mon, "Mouse devices available:\n");
703 cursor = qemu_put_mouse_event_head;
704 while (cursor != NULL) {
705 monitor_printf(mon, "%c Mouse #%d: %s\n",
706 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
707 index, cursor->qemu_put_mouse_event_name);
708 index++;
709 cursor = cursor->next;
713 void do_mouse_set(Monitor *mon, int index)
715 QEMUPutMouseEntry *cursor;
716 int i = 0;
718 if (!qemu_put_mouse_event_head) {
719 monitor_printf(mon, "No mouse devices connected\n");
720 return;
723 cursor = qemu_put_mouse_event_head;
724 while (cursor != NULL && index != i) {
725 i++;
726 cursor = cursor->next;
729 if (cursor != NULL)
730 qemu_put_mouse_event_current = cursor;
731 else
732 monitor_printf(mon, "Mouse at given index not found\n");
735 /* compute with 96 bit intermediate result: (a*b)/c */
736 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
738 union {
739 uint64_t ll;
740 struct {
741 #ifdef WORDS_BIGENDIAN
742 uint32_t high, low;
743 #else
744 uint32_t low, high;
745 #endif
746 } l;
747 } u, res;
748 uint64_t rl, rh;
750 u.ll = a;
751 rl = (uint64_t)u.l.low * (uint64_t)b;
752 rh = (uint64_t)u.l.high * (uint64_t)b;
753 rh += (rl >> 32);
754 res.l.high = rh / c;
755 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
756 return res.ll;
759 /***********************************************************/
760 /* real time host monotonic timer */
762 #define QEMU_TIMER_BASE 1000000000LL
764 #ifdef WIN32
766 static int64_t clock_freq;
768 static void init_get_clock(void)
770 LARGE_INTEGER freq;
771 int ret;
772 ret = QueryPerformanceFrequency(&freq);
773 if (ret == 0) {
774 fprintf(stderr, "Could not calibrate ticks\n");
775 exit(1);
777 clock_freq = freq.QuadPart;
780 static int64_t get_clock(void)
782 LARGE_INTEGER ti;
783 QueryPerformanceCounter(&ti);
784 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
787 #else
789 static int use_rt_clock;
791 static void init_get_clock(void)
793 use_rt_clock = 0;
794 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
795 || defined(__DragonFly__)
797 struct timespec ts;
798 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
799 use_rt_clock = 1;
802 #endif
805 static int64_t get_clock(void)
807 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
808 || defined(__DragonFly__)
809 if (use_rt_clock) {
810 struct timespec ts;
811 clock_gettime(CLOCK_MONOTONIC, &ts);
812 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
813 } else
814 #endif
816 /* XXX: using gettimeofday leads to problems if the date
817 changes, so it should be avoided. */
818 struct timeval tv;
819 gettimeofday(&tv, NULL);
820 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
823 #endif
825 /* Return the virtual CPU time, based on the instruction counter. */
826 static int64_t cpu_get_icount(void)
828 int64_t icount;
829 CPUState *env = cpu_single_env;;
830 icount = qemu_icount;
831 if (env) {
832 if (!can_do_io(env))
833 fprintf(stderr, "Bad clock read\n");
834 icount -= (env->icount_decr.u16.low + env->icount_extra);
836 return qemu_icount_bias + (icount << icount_time_shift);
839 /***********************************************************/
840 /* guest cycle counter */
842 static int64_t cpu_ticks_prev;
843 static int64_t cpu_ticks_offset;
844 static int64_t cpu_clock_offset;
845 static int cpu_ticks_enabled;
847 /* return the host CPU cycle counter and handle stop/restart */
848 int64_t cpu_get_ticks(void)
850 if (use_icount) {
851 return cpu_get_icount();
853 if (!cpu_ticks_enabled) {
854 return cpu_ticks_offset;
855 } else {
856 int64_t ticks;
857 ticks = cpu_get_real_ticks();
858 if (cpu_ticks_prev > ticks) {
859 /* Note: non increasing ticks may happen if the host uses
860 software suspend */
861 cpu_ticks_offset += cpu_ticks_prev - ticks;
863 cpu_ticks_prev = ticks;
864 return ticks + cpu_ticks_offset;
868 /* return the host CPU monotonic timer and handle stop/restart */
869 static int64_t cpu_get_clock(void)
871 int64_t ti;
872 if (!cpu_ticks_enabled) {
873 return cpu_clock_offset;
874 } else {
875 ti = get_clock();
876 return ti + cpu_clock_offset;
880 /* enable cpu_get_ticks() */
881 void cpu_enable_ticks(void)
883 if (!cpu_ticks_enabled) {
884 cpu_ticks_offset -= cpu_get_real_ticks();
885 cpu_clock_offset -= get_clock();
886 cpu_ticks_enabled = 1;
890 /* disable cpu_get_ticks() : the clock is stopped. You must not call
891 cpu_get_ticks() after that. */
892 void cpu_disable_ticks(void)
894 if (cpu_ticks_enabled) {
895 cpu_ticks_offset = cpu_get_ticks();
896 cpu_clock_offset = cpu_get_clock();
897 cpu_ticks_enabled = 0;
901 /***********************************************************/
902 /* timers */
904 #define QEMU_TIMER_REALTIME 0
905 #define QEMU_TIMER_VIRTUAL 1
907 struct QEMUClock {
908 int type;
909 /* XXX: add frequency */
912 struct QEMUTimer {
913 QEMUClock *clock;
914 int64_t expire_time;
915 QEMUTimerCB *cb;
916 void *opaque;
917 struct QEMUTimer *next;
920 struct qemu_alarm_timer {
921 char const *name;
922 unsigned int flags;
924 int (*start)(struct qemu_alarm_timer *t);
925 void (*stop)(struct qemu_alarm_timer *t);
926 void (*rearm)(struct qemu_alarm_timer *t);
927 void *priv;
930 #define ALARM_FLAG_DYNTICKS 0x1
931 #define ALARM_FLAG_EXPIRED 0x2
933 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
935 return t->flags & ALARM_FLAG_DYNTICKS;
938 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
940 if (!alarm_has_dynticks(t))
941 return;
943 t->rearm(t);
946 /* TODO: MIN_TIMER_REARM_US should be optimized */
947 #define MIN_TIMER_REARM_US 250
949 static struct qemu_alarm_timer *alarm_timer;
950 #ifndef _WIN32
951 static int alarm_timer_rfd, alarm_timer_wfd;
952 #endif
954 #ifdef _WIN32
956 struct qemu_alarm_win32 {
957 MMRESULT timerId;
958 HANDLE host_alarm;
959 unsigned int period;
960 } alarm_win32_data = {0, NULL, -1};
962 static int win32_start_timer(struct qemu_alarm_timer *t);
963 static void win32_stop_timer(struct qemu_alarm_timer *t);
964 static void win32_rearm_timer(struct qemu_alarm_timer *t);
966 #else
968 static int unix_start_timer(struct qemu_alarm_timer *t);
969 static void unix_stop_timer(struct qemu_alarm_timer *t);
971 #ifdef __linux__
973 static int dynticks_start_timer(struct qemu_alarm_timer *t);
974 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
975 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
977 static int hpet_start_timer(struct qemu_alarm_timer *t);
978 static void hpet_stop_timer(struct qemu_alarm_timer *t);
980 static int rtc_start_timer(struct qemu_alarm_timer *t);
981 static void rtc_stop_timer(struct qemu_alarm_timer *t);
983 #endif /* __linux__ */
985 #endif /* _WIN32 */
987 /* Correlation between real and virtual time is always going to be
988 fairly approximate, so ignore small variation.
989 When the guest is idle real and virtual time will be aligned in
990 the IO wait loop. */
991 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
993 static void icount_adjust(void)
995 int64_t cur_time;
996 int64_t cur_icount;
997 int64_t delta;
998 static int64_t last_delta;
999 /* If the VM is not running, then do nothing. */
1000 if (!vm_running)
1001 return;
1003 cur_time = cpu_get_clock();
1004 cur_icount = qemu_get_clock(vm_clock);
1005 delta = cur_icount - cur_time;
1006 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1007 if (delta > 0
1008 && last_delta + ICOUNT_WOBBLE < delta * 2
1009 && icount_time_shift > 0) {
1010 /* The guest is getting too far ahead. Slow time down. */
1011 icount_time_shift--;
1013 if (delta < 0
1014 && last_delta - ICOUNT_WOBBLE > delta * 2
1015 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1016 /* The guest is getting too far behind. Speed time up. */
1017 icount_time_shift++;
1019 last_delta = delta;
1020 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1023 static void icount_adjust_rt(void * opaque)
1025 qemu_mod_timer(icount_rt_timer,
1026 qemu_get_clock(rt_clock) + 1000);
1027 icount_adjust();
1030 static void icount_adjust_vm(void * opaque)
1032 qemu_mod_timer(icount_vm_timer,
1033 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1034 icount_adjust();
1037 static void init_icount_adjust(void)
1039 /* Have both realtime and virtual time triggers for speed adjustment.
1040 The realtime trigger catches emulated time passing too slowly,
1041 the virtual time trigger catches emulated time passing too fast.
1042 Realtime triggers occur even when idle, so use them less frequently
1043 than VM triggers. */
1044 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1045 qemu_mod_timer(icount_rt_timer,
1046 qemu_get_clock(rt_clock) + 1000);
1047 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1048 qemu_mod_timer(icount_vm_timer,
1049 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1052 static struct qemu_alarm_timer alarm_timers[] = {
1053 #ifndef _WIN32
1054 #ifdef __linux__
1055 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1056 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1057 /* HPET - if available - is preferred */
1058 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1059 /* ...otherwise try RTC */
1060 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1061 #endif
1062 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1063 #else
1064 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1065 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1066 {"win32", 0, win32_start_timer,
1067 win32_stop_timer, NULL, &alarm_win32_data},
1068 #endif
1069 {NULL, }
1072 static void show_available_alarms(void)
1074 int i;
1076 printf("Available alarm timers, in order of precedence:\n");
1077 for (i = 0; alarm_timers[i].name; i++)
1078 printf("%s\n", alarm_timers[i].name);
1081 static void configure_alarms(char const *opt)
1083 int i;
1084 int cur = 0;
1085 int count = ARRAY_SIZE(alarm_timers) - 1;
1086 char *arg;
1087 char *name;
1088 struct qemu_alarm_timer tmp;
1090 if (!strcmp(opt, "?")) {
1091 show_available_alarms();
1092 exit(0);
1095 arg = strdup(opt);
1097 /* Reorder the array */
1098 name = strtok(arg, ",");
1099 while (name) {
1100 for (i = 0; i < count && alarm_timers[i].name; i++) {
1101 if (!strcmp(alarm_timers[i].name, name))
1102 break;
1105 if (i == count) {
1106 fprintf(stderr, "Unknown clock %s\n", name);
1107 goto next;
1110 if (i < cur)
1111 /* Ignore */
1112 goto next;
1114 /* Swap */
1115 tmp = alarm_timers[i];
1116 alarm_timers[i] = alarm_timers[cur];
1117 alarm_timers[cur] = tmp;
1119 cur++;
1120 next:
1121 name = strtok(NULL, ",");
1124 free(arg);
1126 if (cur) {
1127 /* Disable remaining timers */
1128 for (i = cur; i < count; i++)
1129 alarm_timers[i].name = NULL;
1130 } else {
1131 show_available_alarms();
1132 exit(1);
1136 QEMUClock *rt_clock;
1137 QEMUClock *vm_clock;
1139 static QEMUTimer *active_timers[2];
1141 static QEMUClock *qemu_new_clock(int type)
1143 QEMUClock *clock;
1144 clock = qemu_mallocz(sizeof(QEMUClock));
1145 clock->type = type;
1146 return clock;
1149 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1151 QEMUTimer *ts;
1153 ts = qemu_mallocz(sizeof(QEMUTimer));
1154 ts->clock = clock;
1155 ts->cb = cb;
1156 ts->opaque = opaque;
1157 return ts;
1160 void qemu_free_timer(QEMUTimer *ts)
1162 qemu_free(ts);
1165 /* stop a timer, but do not dealloc it */
1166 void qemu_del_timer(QEMUTimer *ts)
1168 QEMUTimer **pt, *t;
1170 /* NOTE: this code must be signal safe because
1171 qemu_timer_expired() can be called from a signal. */
1172 pt = &active_timers[ts->clock->type];
1173 for(;;) {
1174 t = *pt;
1175 if (!t)
1176 break;
1177 if (t == ts) {
1178 *pt = t->next;
1179 break;
1181 pt = &t->next;
1185 /* modify the current timer so that it will be fired when current_time
1186 >= expire_time. The corresponding callback will be called. */
1187 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1189 QEMUTimer **pt, *t;
1191 qemu_del_timer(ts);
1193 /* add the timer in the sorted list */
1194 /* NOTE: this code must be signal safe because
1195 qemu_timer_expired() can be called from a signal. */
1196 pt = &active_timers[ts->clock->type];
1197 for(;;) {
1198 t = *pt;
1199 if (!t)
1200 break;
1201 if (t->expire_time > expire_time)
1202 break;
1203 pt = &t->next;
1205 ts->expire_time = expire_time;
1206 ts->next = *pt;
1207 *pt = ts;
1209 /* Rearm if necessary */
1210 if (pt == &active_timers[ts->clock->type]) {
1211 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1212 qemu_rearm_alarm_timer(alarm_timer);
1214 /* Interrupt execution to force deadline recalculation. */
1215 if (use_icount && cpu_single_env) {
1216 cpu_exit(cpu_single_env);
1221 int qemu_timer_pending(QEMUTimer *ts)
1223 QEMUTimer *t;
1224 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1225 if (t == ts)
1226 return 1;
1228 return 0;
1231 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1233 if (!timer_head)
1234 return 0;
1235 return (timer_head->expire_time <= current_time);
1238 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1240 QEMUTimer *ts;
1242 for(;;) {
1243 ts = *ptimer_head;
1244 if (!ts || ts->expire_time > current_time)
1245 break;
1246 /* remove timer from the list before calling the callback */
1247 *ptimer_head = ts->next;
1248 ts->next = NULL;
1250 /* run the callback (the timer list can be modified) */
1251 ts->cb(ts->opaque);
1255 int64_t qemu_get_clock(QEMUClock *clock)
1257 switch(clock->type) {
1258 case QEMU_TIMER_REALTIME:
1259 return get_clock() / 1000000;
1260 default:
1261 case QEMU_TIMER_VIRTUAL:
1262 if (use_icount) {
1263 return cpu_get_icount();
1264 } else {
1265 return cpu_get_clock();
1270 static void init_timers(void)
1272 init_get_clock();
1273 ticks_per_sec = QEMU_TIMER_BASE;
1274 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1275 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1278 /* save a timer */
1279 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1281 uint64_t expire_time;
1283 if (qemu_timer_pending(ts)) {
1284 expire_time = ts->expire_time;
1285 } else {
1286 expire_time = -1;
1288 qemu_put_be64(f, expire_time);
1291 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1293 uint64_t expire_time;
1295 expire_time = qemu_get_be64(f);
1296 if (expire_time != -1) {
1297 qemu_mod_timer(ts, expire_time);
1298 } else {
1299 qemu_del_timer(ts);
1303 static void timer_save(QEMUFile *f, void *opaque)
1305 if (cpu_ticks_enabled) {
1306 hw_error("cannot save state if virtual timers are running");
1308 qemu_put_be64(f, cpu_ticks_offset);
1309 qemu_put_be64(f, ticks_per_sec);
1310 qemu_put_be64(f, cpu_clock_offset);
1313 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1315 if (version_id != 1 && version_id != 2)
1316 return -EINVAL;
1317 if (cpu_ticks_enabled) {
1318 return -EINVAL;
1320 cpu_ticks_offset=qemu_get_be64(f);
1321 ticks_per_sec=qemu_get_be64(f);
1322 if (version_id == 2) {
1323 cpu_clock_offset=qemu_get_be64(f);
1325 return 0;
1328 #ifdef _WIN32
1329 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1330 DWORD_PTR dwUser, DWORD_PTR dw1,
1331 DWORD_PTR dw2)
1332 #else
1333 static void host_alarm_handler(int host_signum)
1334 #endif
1336 #if 0
1337 #define DISP_FREQ 1000
1339 static int64_t delta_min = INT64_MAX;
1340 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1341 static int count;
1342 ti = qemu_get_clock(vm_clock);
1343 if (last_clock != 0) {
1344 delta = ti - last_clock;
1345 if (delta < delta_min)
1346 delta_min = delta;
1347 if (delta > delta_max)
1348 delta_max = delta;
1349 delta_cum += delta;
1350 if (++count == DISP_FREQ) {
1351 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1352 muldiv64(delta_min, 1000000, ticks_per_sec),
1353 muldiv64(delta_max, 1000000, ticks_per_sec),
1354 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1355 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1356 count = 0;
1357 delta_min = INT64_MAX;
1358 delta_max = 0;
1359 delta_cum = 0;
1362 last_clock = ti;
1364 #endif
1365 if (1 ||
1366 alarm_has_dynticks(alarm_timer) ||
1367 (!use_icount &&
1368 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1369 qemu_get_clock(vm_clock))) ||
1370 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1371 qemu_get_clock(rt_clock))) {
1372 CPUState *env = next_cpu;
1374 #ifdef _WIN32
1375 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1376 SetEvent(data->host_alarm);
1377 #else
1378 static const char byte = 0;
1379 write(alarm_timer_wfd, &byte, sizeof(byte));
1380 #endif
1381 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1383 if (env) {
1384 /* stop the currently executing cpu because a timer occured */
1385 cpu_exit(env);
1386 #ifdef USE_KQEMU
1387 if (env->kqemu_enabled) {
1388 kqemu_cpu_interrupt(env);
1390 #endif
1392 event_pending = 1;
1396 static int64_t qemu_next_deadline(void)
1398 int64_t delta;
1400 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1401 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1402 qemu_get_clock(vm_clock);
1403 } else {
1404 /* To avoid problems with overflow limit this to 2^32. */
1405 delta = INT32_MAX;
1408 if (delta < 0)
1409 delta = 0;
1411 return delta;
1414 #if defined(__linux__) || defined(_WIN32)
1415 static uint64_t qemu_next_deadline_dyntick(void)
1417 int64_t delta;
1418 int64_t rtdelta;
1420 if (use_icount)
1421 delta = INT32_MAX;
1422 else
1423 delta = (qemu_next_deadline() + 999) / 1000;
1425 if (active_timers[QEMU_TIMER_REALTIME]) {
1426 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1427 qemu_get_clock(rt_clock))*1000;
1428 if (rtdelta < delta)
1429 delta = rtdelta;
1432 if (delta < MIN_TIMER_REARM_US)
1433 delta = MIN_TIMER_REARM_US;
1435 return delta;
1437 #endif
1439 #ifndef _WIN32
1441 /* Sets a specific flag */
1442 static int fcntl_setfl(int fd, int flag)
1444 int flags;
1446 flags = fcntl(fd, F_GETFL);
1447 if (flags == -1)
1448 return -errno;
1450 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1451 return -errno;
1453 return 0;
1456 #if defined(__linux__)
1458 #define RTC_FREQ 1024
1460 static void enable_sigio_timer(int fd)
1462 struct sigaction act;
1464 /* timer signal */
1465 sigfillset(&act.sa_mask);
1466 act.sa_flags = 0;
1467 act.sa_handler = host_alarm_handler;
1469 sigaction(SIGIO, &act, NULL);
1470 fcntl_setfl(fd, O_ASYNC);
1471 fcntl(fd, F_SETOWN, getpid());
1474 static int hpet_start_timer(struct qemu_alarm_timer *t)
1476 struct hpet_info info;
1477 int r, fd;
1479 fd = open("/dev/hpet", O_RDONLY);
1480 if (fd < 0)
1481 return -1;
1483 /* Set frequency */
1484 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1485 if (r < 0) {
1486 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1487 "error, but for better emulation accuracy type:\n"
1488 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1489 goto fail;
1492 /* Check capabilities */
1493 r = ioctl(fd, HPET_INFO, &info);
1494 if (r < 0)
1495 goto fail;
1497 /* Enable periodic mode */
1498 r = ioctl(fd, HPET_EPI, 0);
1499 if (info.hi_flags && (r < 0))
1500 goto fail;
1502 /* Enable interrupt */
1503 r = ioctl(fd, HPET_IE_ON, 0);
1504 if (r < 0)
1505 goto fail;
1507 enable_sigio_timer(fd);
1508 t->priv = (void *)(long)fd;
1510 return 0;
1511 fail:
1512 close(fd);
1513 return -1;
1516 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1518 int fd = (long)t->priv;
1520 close(fd);
1523 static int rtc_start_timer(struct qemu_alarm_timer *t)
1525 int rtc_fd;
1526 unsigned long current_rtc_freq = 0;
1528 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1529 if (rtc_fd < 0)
1530 return -1;
1531 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1532 if (current_rtc_freq != RTC_FREQ &&
1533 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1534 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1535 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1536 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1537 goto fail;
1539 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1540 fail:
1541 close(rtc_fd);
1542 return -1;
1545 enable_sigio_timer(rtc_fd);
1547 t->priv = (void *)(long)rtc_fd;
1549 return 0;
1552 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1554 int rtc_fd = (long)t->priv;
1556 close(rtc_fd);
1559 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1561 struct sigevent ev;
1562 timer_t host_timer;
1563 struct sigaction act;
1565 sigfillset(&act.sa_mask);
1566 act.sa_flags = 0;
1567 act.sa_handler = host_alarm_handler;
1569 sigaction(SIGALRM, &act, NULL);
1571 ev.sigev_value.sival_int = 0;
1572 ev.sigev_notify = SIGEV_SIGNAL;
1573 ev.sigev_signo = SIGALRM;
1575 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1576 perror("timer_create");
1578 /* disable dynticks */
1579 fprintf(stderr, "Dynamic Ticks disabled\n");
1581 return -1;
1584 t->priv = (void *)(long)host_timer;
1586 return 0;
1589 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1591 timer_t host_timer = (timer_t)(long)t->priv;
1593 timer_delete(host_timer);
1596 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1598 timer_t host_timer = (timer_t)(long)t->priv;
1599 struct itimerspec timeout;
1600 int64_t nearest_delta_us = INT64_MAX;
1601 int64_t current_us;
1603 if (!active_timers[QEMU_TIMER_REALTIME] &&
1604 !active_timers[QEMU_TIMER_VIRTUAL])
1605 return;
1607 nearest_delta_us = qemu_next_deadline_dyntick();
1609 /* check whether a timer is already running */
1610 if (timer_gettime(host_timer, &timeout)) {
1611 perror("gettime");
1612 fprintf(stderr, "Internal timer error: aborting\n");
1613 exit(1);
1615 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1616 if (current_us && current_us <= nearest_delta_us)
1617 return;
1619 timeout.it_interval.tv_sec = 0;
1620 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1621 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1622 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1623 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1624 perror("settime");
1625 fprintf(stderr, "Internal timer error: aborting\n");
1626 exit(1);
1630 #endif /* defined(__linux__) */
1632 static int unix_start_timer(struct qemu_alarm_timer *t)
1634 struct sigaction act;
1635 struct itimerval itv;
1636 int err;
1638 /* timer signal */
1639 sigfillset(&act.sa_mask);
1640 act.sa_flags = 0;
1641 act.sa_handler = host_alarm_handler;
1643 sigaction(SIGALRM, &act, NULL);
1645 itv.it_interval.tv_sec = 0;
1646 /* for i386 kernel 2.6 to get 1 ms */
1647 itv.it_interval.tv_usec = 999;
1648 itv.it_value.tv_sec = 0;
1649 itv.it_value.tv_usec = 10 * 1000;
1651 err = setitimer(ITIMER_REAL, &itv, NULL);
1652 if (err)
1653 return -1;
1655 return 0;
1658 static void unix_stop_timer(struct qemu_alarm_timer *t)
1660 struct itimerval itv;
1662 memset(&itv, 0, sizeof(itv));
1663 setitimer(ITIMER_REAL, &itv, NULL);
1666 #endif /* !defined(_WIN32) */
1668 static void try_to_rearm_timer(void *opaque)
1670 struct qemu_alarm_timer *t = opaque;
1671 #ifndef _WIN32
1672 ssize_t len;
1674 /* Drain the notify pipe */
1675 do {
1676 char buffer[512];
1677 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1678 } while ((len == -1 && errno == EINTR) || len > 0);
1679 #endif
1681 if (t->flags & ALARM_FLAG_EXPIRED) {
1682 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1683 qemu_rearm_alarm_timer(alarm_timer);
1687 #ifdef _WIN32
1689 static int win32_start_timer(struct qemu_alarm_timer *t)
1691 TIMECAPS tc;
1692 struct qemu_alarm_win32 *data = t->priv;
1693 UINT flags;
1695 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1696 if (!data->host_alarm) {
1697 perror("Failed CreateEvent");
1698 return -1;
1701 memset(&tc, 0, sizeof(tc));
1702 timeGetDevCaps(&tc, sizeof(tc));
1704 if (data->period < tc.wPeriodMin)
1705 data->period = tc.wPeriodMin;
1707 timeBeginPeriod(data->period);
1709 flags = TIME_CALLBACK_FUNCTION;
1710 if (alarm_has_dynticks(t))
1711 flags |= TIME_ONESHOT;
1712 else
1713 flags |= TIME_PERIODIC;
1715 data->timerId = timeSetEvent(1, // interval (ms)
1716 data->period, // resolution
1717 host_alarm_handler, // function
1718 (DWORD)t, // parameter
1719 flags);
1721 if (!data->timerId) {
1722 perror("Failed to initialize win32 alarm timer");
1724 timeEndPeriod(data->period);
1725 CloseHandle(data->host_alarm);
1726 return -1;
1729 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1731 return 0;
1734 static void win32_stop_timer(struct qemu_alarm_timer *t)
1736 struct qemu_alarm_win32 *data = t->priv;
1738 timeKillEvent(data->timerId);
1739 timeEndPeriod(data->period);
1741 CloseHandle(data->host_alarm);
1744 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1746 struct qemu_alarm_win32 *data = t->priv;
1747 uint64_t nearest_delta_us;
1749 if (!active_timers[QEMU_TIMER_REALTIME] &&
1750 !active_timers[QEMU_TIMER_VIRTUAL])
1751 return;
1753 nearest_delta_us = qemu_next_deadline_dyntick();
1754 nearest_delta_us /= 1000;
1756 timeKillEvent(data->timerId);
1758 data->timerId = timeSetEvent(1,
1759 data->period,
1760 host_alarm_handler,
1761 (DWORD)t,
1762 TIME_ONESHOT | TIME_PERIODIC);
1764 if (!data->timerId) {
1765 perror("Failed to re-arm win32 alarm timer");
1767 timeEndPeriod(data->period);
1768 CloseHandle(data->host_alarm);
1769 exit(1);
1773 #endif /* _WIN32 */
1775 static int init_timer_alarm(void)
1777 struct qemu_alarm_timer *t = NULL;
1778 int i, err = -1;
1780 #ifndef _WIN32
1781 int fds[2];
1783 err = pipe(fds);
1784 if (err == -1)
1785 return -errno;
1787 err = fcntl_setfl(fds[0], O_NONBLOCK);
1788 if (err < 0)
1789 goto fail;
1791 err = fcntl_setfl(fds[1], O_NONBLOCK);
1792 if (err < 0)
1793 goto fail;
1795 alarm_timer_rfd = fds[0];
1796 alarm_timer_wfd = fds[1];
1797 #endif
1799 for (i = 0; alarm_timers[i].name; i++) {
1800 t = &alarm_timers[i];
1802 err = t->start(t);
1803 if (!err)
1804 break;
1807 if (err) {
1808 err = -ENOENT;
1809 goto fail;
1812 #ifndef _WIN32
1813 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1814 try_to_rearm_timer, NULL, t);
1815 #endif
1817 alarm_timer = t;
1819 return 0;
1821 fail:
1822 #ifndef _WIN32
1823 close(fds[0]);
1824 close(fds[1]);
1825 #endif
1826 return err;
1829 static void quit_timers(void)
1831 alarm_timer->stop(alarm_timer);
1832 alarm_timer = NULL;
1835 /***********************************************************/
1836 /* host time/date access */
1837 void qemu_get_timedate(struct tm *tm, int offset)
1839 time_t ti;
1840 struct tm *ret;
1842 time(&ti);
1843 ti += offset;
1844 if (rtc_date_offset == -1) {
1845 if (rtc_utc)
1846 ret = gmtime(&ti);
1847 else
1848 ret = localtime(&ti);
1849 } else {
1850 ti -= rtc_date_offset;
1851 ret = gmtime(&ti);
1854 memcpy(tm, ret, sizeof(struct tm));
1857 int qemu_timedate_diff(struct tm *tm)
1859 time_t seconds;
1861 if (rtc_date_offset == -1)
1862 if (rtc_utc)
1863 seconds = mktimegm(tm);
1864 else
1865 seconds = mktime(tm);
1866 else
1867 seconds = mktimegm(tm) + rtc_date_offset;
1869 return seconds - time(NULL);
1872 #ifdef _WIN32
1873 static void socket_cleanup(void)
1875 WSACleanup();
1878 static int socket_init(void)
1880 WSADATA Data;
1881 int ret, err;
1883 ret = WSAStartup(MAKEWORD(2,2), &Data);
1884 if (ret != 0) {
1885 err = WSAGetLastError();
1886 fprintf(stderr, "WSAStartup: %d\n", err);
1887 return -1;
1889 atexit(socket_cleanup);
1890 return 0;
1892 #endif
1894 const char *get_opt_name(char *buf, int buf_size, const char *p)
1896 char *q;
1898 q = buf;
1899 while (*p != '\0' && *p != '=') {
1900 if (q && (q - buf) < buf_size - 1)
1901 *q++ = *p;
1902 p++;
1904 if (q)
1905 *q = '\0';
1907 return p;
1910 const char *get_opt_value(char *buf, int buf_size, const char *p)
1912 char *q;
1914 q = buf;
1915 while (*p != '\0') {
1916 if (*p == ',') {
1917 if (*(p + 1) != ',')
1918 break;
1919 p++;
1921 if (q && (q - buf) < buf_size - 1)
1922 *q++ = *p;
1923 p++;
1925 if (q)
1926 *q = '\0';
1928 return p;
1931 int get_param_value(char *buf, int buf_size,
1932 const char *tag, const char *str)
1934 const char *p;
1935 char option[128];
1937 p = str;
1938 for(;;) {
1939 p = get_opt_name(option, sizeof(option), p);
1940 if (*p != '=')
1941 break;
1942 p++;
1943 if (!strcmp(tag, option)) {
1944 (void)get_opt_value(buf, buf_size, p);
1945 return strlen(buf);
1946 } else {
1947 p = get_opt_value(NULL, 0, p);
1949 if (*p != ',')
1950 break;
1951 p++;
1953 return 0;
1956 int check_params(char *buf, int buf_size,
1957 const char * const *params, const char *str)
1959 const char *p;
1960 int i;
1962 p = str;
1963 for(;;) {
1964 p = get_opt_name(buf, buf_size, p);
1965 if (*p != '=')
1966 return -1;
1967 p++;
1968 for(i = 0; params[i] != NULL; i++)
1969 if (!strcmp(params[i], buf))
1970 break;
1971 if (params[i] == NULL)
1972 return -1;
1973 p = get_opt_value(NULL, 0, p);
1974 if (*p != ',')
1975 break;
1976 p++;
1978 return 0;
1981 /***********************************************************/
1982 /* Bluetooth support */
1983 static int nb_hcis;
1984 static int cur_hci;
1985 static struct HCIInfo *hci_table[MAX_NICS];
1987 static struct bt_vlan_s {
1988 struct bt_scatternet_s net;
1989 int id;
1990 struct bt_vlan_s *next;
1991 } *first_bt_vlan;
1993 /* find or alloc a new bluetooth "VLAN" */
1994 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1996 struct bt_vlan_s **pvlan, *vlan;
1997 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1998 if (vlan->id == id)
1999 return &vlan->net;
2001 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
2002 vlan->id = id;
2003 pvlan = &first_bt_vlan;
2004 while (*pvlan != NULL)
2005 pvlan = &(*pvlan)->next;
2006 *pvlan = vlan;
2007 return &vlan->net;
2010 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2014 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2016 return -ENOTSUP;
2019 static struct HCIInfo null_hci = {
2020 .cmd_send = null_hci_send,
2021 .sco_send = null_hci_send,
2022 .acl_send = null_hci_send,
2023 .bdaddr_set = null_hci_addr_set,
2026 struct HCIInfo *qemu_next_hci(void)
2028 if (cur_hci == nb_hcis)
2029 return &null_hci;
2031 return hci_table[cur_hci++];
2034 static struct HCIInfo *hci_init(const char *str)
2036 char *endp;
2037 struct bt_scatternet_s *vlan = 0;
2039 if (!strcmp(str, "null"))
2040 /* null */
2041 return &null_hci;
2042 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2043 /* host[:hciN] */
2044 return bt_host_hci(str[4] ? str + 5 : "hci0");
2045 else if (!strncmp(str, "hci", 3)) {
2046 /* hci[,vlan=n] */
2047 if (str[3]) {
2048 if (!strncmp(str + 3, ",vlan=", 6)) {
2049 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2050 if (*endp)
2051 vlan = 0;
2053 } else
2054 vlan = qemu_find_bt_vlan(0);
2055 if (vlan)
2056 return bt_new_hci(vlan);
2059 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2061 return 0;
2064 static int bt_hci_parse(const char *str)
2066 struct HCIInfo *hci;
2067 bdaddr_t bdaddr;
2069 if (nb_hcis >= MAX_NICS) {
2070 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2071 return -1;
2074 hci = hci_init(str);
2075 if (!hci)
2076 return -1;
2078 bdaddr.b[0] = 0x52;
2079 bdaddr.b[1] = 0x54;
2080 bdaddr.b[2] = 0x00;
2081 bdaddr.b[3] = 0x12;
2082 bdaddr.b[4] = 0x34;
2083 bdaddr.b[5] = 0x56 + nb_hcis;
2084 hci->bdaddr_set(hci, bdaddr.b);
2086 hci_table[nb_hcis++] = hci;
2088 return 0;
2091 static void bt_vhci_add(int vlan_id)
2093 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2095 if (!vlan->slave)
2096 fprintf(stderr, "qemu: warning: adding a VHCI to "
2097 "an empty scatternet %i\n", vlan_id);
2099 bt_vhci_init(bt_new_hci(vlan));
2102 static struct bt_device_s *bt_device_add(const char *opt)
2104 struct bt_scatternet_s *vlan;
2105 int vlan_id = 0;
2106 char *endp = strstr(opt, ",vlan=");
2107 int len = (endp ? endp - opt : strlen(opt)) + 1;
2108 char devname[10];
2110 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2112 if (endp) {
2113 vlan_id = strtol(endp + 6, &endp, 0);
2114 if (*endp) {
2115 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2116 return 0;
2120 vlan = qemu_find_bt_vlan(vlan_id);
2122 if (!vlan->slave)
2123 fprintf(stderr, "qemu: warning: adding a slave device to "
2124 "an empty scatternet %i\n", vlan_id);
2126 if (!strcmp(devname, "keyboard"))
2127 return bt_keyboard_init(vlan);
2129 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2130 return 0;
2133 static int bt_parse(const char *opt)
2135 const char *endp, *p;
2136 int vlan;
2138 if (strstart(opt, "hci", &endp)) {
2139 if (!*endp || *endp == ',') {
2140 if (*endp)
2141 if (!strstart(endp, ",vlan=", 0))
2142 opt = endp + 1;
2144 return bt_hci_parse(opt);
2146 } else if (strstart(opt, "vhci", &endp)) {
2147 if (!*endp || *endp == ',') {
2148 if (*endp) {
2149 if (strstart(endp, ",vlan=", &p)) {
2150 vlan = strtol(p, (char **) &endp, 0);
2151 if (*endp) {
2152 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2153 return 1;
2155 } else {
2156 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2157 return 1;
2159 } else
2160 vlan = 0;
2162 bt_vhci_add(vlan);
2163 return 0;
2165 } else if (strstart(opt, "device:", &endp))
2166 return !bt_device_add(endp);
2168 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2169 return 1;
2172 /***********************************************************/
2173 /* QEMU Block devices */
2175 #define HD_ALIAS "index=%d,media=disk"
2176 #define CDROM_ALIAS "index=2,media=cdrom"
2177 #define FD_ALIAS "index=%d,if=floppy"
2178 #define PFLASH_ALIAS "if=pflash"
2179 #define MTD_ALIAS "if=mtd"
2180 #define SD_ALIAS "index=0,if=sd"
2182 static int drive_opt_get_free_idx(void)
2184 int index;
2186 for (index = 0; index < MAX_DRIVES; index++)
2187 if (!drives_opt[index].used) {
2188 drives_opt[index].used = 1;
2189 return index;
2192 return -1;
2195 static int drive_get_free_idx(void)
2197 int index;
2199 for (index = 0; index < MAX_DRIVES; index++)
2200 if (!drives_table[index].used) {
2201 drives_table[index].used = 1;
2202 return index;
2205 return -1;
2208 int drive_add(const char *file, const char *fmt, ...)
2210 va_list ap;
2211 int index = drive_opt_get_free_idx();
2213 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2214 fprintf(stderr, "qemu: too many drives\n");
2215 return -1;
2218 drives_opt[index].file = file;
2219 va_start(ap, fmt);
2220 vsnprintf(drives_opt[index].opt,
2221 sizeof(drives_opt[0].opt), fmt, ap);
2222 va_end(ap);
2224 nb_drives_opt++;
2225 return index;
2228 void drive_remove(int index)
2230 drives_opt[index].used = 0;
2231 nb_drives_opt--;
2234 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2236 int index;
2238 /* seek interface, bus and unit */
2240 for (index = 0; index < MAX_DRIVES; index++)
2241 if (drives_table[index].type == type &&
2242 drives_table[index].bus == bus &&
2243 drives_table[index].unit == unit &&
2244 drives_table[index].used)
2245 return index;
2247 return -1;
2250 int drive_get_max_bus(BlockInterfaceType type)
2252 int max_bus;
2253 int index;
2255 max_bus = -1;
2256 for (index = 0; index < nb_drives; index++) {
2257 if(drives_table[index].type == type &&
2258 drives_table[index].bus > max_bus)
2259 max_bus = drives_table[index].bus;
2261 return max_bus;
2264 const char *drive_get_serial(BlockDriverState *bdrv)
2266 int index;
2268 for (index = 0; index < nb_drives; index++)
2269 if (drives_table[index].bdrv == bdrv)
2270 return drives_table[index].serial;
2272 return "\0";
2275 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2277 int index;
2279 for (index = 0; index < nb_drives; index++)
2280 if (drives_table[index].bdrv == bdrv)
2281 return drives_table[index].onerror;
2283 return BLOCK_ERR_STOP_ENOSPC;
2286 static void bdrv_format_print(void *opaque, const char *name)
2288 fprintf(stderr, " %s", name);
2291 void drive_uninit(BlockDriverState *bdrv)
2293 int i;
2295 for (i = 0; i < MAX_DRIVES; i++)
2296 if (drives_table[i].bdrv == bdrv) {
2297 drives_table[i].bdrv = NULL;
2298 drives_table[i].used = 0;
2299 drive_remove(drives_table[i].drive_opt_idx);
2300 nb_drives--;
2301 break;
2305 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2307 char buf[128];
2308 char file[1024];
2309 char devname[128];
2310 char serial[21];
2311 const char *mediastr = "";
2312 BlockInterfaceType type;
2313 enum { MEDIA_DISK, MEDIA_CDROM } media;
2314 int bus_id, unit_id;
2315 int cyls, heads, secs, translation;
2316 BlockDriverState *bdrv;
2317 BlockDriver *drv = NULL;
2318 QEMUMachine *machine = opaque;
2319 int max_devs;
2320 int index;
2321 int cache;
2322 int bdrv_flags, onerror;
2323 int drives_table_idx;
2324 char *str = arg->opt;
2325 static const char * const params[] = { "bus", "unit", "if", "index",
2326 "cyls", "heads", "secs", "trans",
2327 "media", "snapshot", "file",
2328 "cache", "format", "serial", "werror",
2329 "boot", NULL };
2331 if (check_params(buf, sizeof(buf), params, str) < 0) {
2332 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2333 buf, str);
2334 return -1;
2337 file[0] = 0;
2338 cyls = heads = secs = 0;
2339 bus_id = 0;
2340 unit_id = -1;
2341 translation = BIOS_ATA_TRANSLATION_AUTO;
2342 index = -1;
2343 cache = 3;
2345 if (machine->use_scsi) {
2346 type = IF_SCSI;
2347 max_devs = MAX_SCSI_DEVS;
2348 pstrcpy(devname, sizeof(devname), "scsi");
2349 } else {
2350 type = IF_IDE;
2351 max_devs = MAX_IDE_DEVS;
2352 pstrcpy(devname, sizeof(devname), "ide");
2354 media = MEDIA_DISK;
2356 /* extract parameters */
2358 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2359 bus_id = strtol(buf, NULL, 0);
2360 if (bus_id < 0) {
2361 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2362 return -1;
2366 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2367 unit_id = strtol(buf, NULL, 0);
2368 if (unit_id < 0) {
2369 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2370 return -1;
2374 if (get_param_value(buf, sizeof(buf), "if", str)) {
2375 pstrcpy(devname, sizeof(devname), buf);
2376 if (!strcmp(buf, "ide")) {
2377 type = IF_IDE;
2378 max_devs = MAX_IDE_DEVS;
2379 } else if (!strcmp(buf, "scsi")) {
2380 type = IF_SCSI;
2381 max_devs = MAX_SCSI_DEVS;
2382 } else if (!strcmp(buf, "floppy")) {
2383 type = IF_FLOPPY;
2384 max_devs = 0;
2385 } else if (!strcmp(buf, "pflash")) {
2386 type = IF_PFLASH;
2387 max_devs = 0;
2388 } else if (!strcmp(buf, "mtd")) {
2389 type = IF_MTD;
2390 max_devs = 0;
2391 } else if (!strcmp(buf, "sd")) {
2392 type = IF_SD;
2393 max_devs = 0;
2394 } else if (!strcmp(buf, "virtio")) {
2395 type = IF_VIRTIO;
2396 max_devs = 0;
2397 } else {
2398 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2399 return -1;
2403 if (get_param_value(buf, sizeof(buf), "index", str)) {
2404 index = strtol(buf, NULL, 0);
2405 if (index < 0) {
2406 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2407 return -1;
2411 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2412 cyls = strtol(buf, NULL, 0);
2415 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2416 heads = strtol(buf, NULL, 0);
2419 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2420 secs = strtol(buf, NULL, 0);
2423 if (cyls || heads || secs) {
2424 if (cyls < 1 || cyls > 16383) {
2425 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2426 return -1;
2428 if (heads < 1 || heads > 16) {
2429 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2430 return -1;
2432 if (secs < 1 || secs > 63) {
2433 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2434 return -1;
2438 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2439 if (!cyls) {
2440 fprintf(stderr,
2441 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2442 str);
2443 return -1;
2445 if (!strcmp(buf, "none"))
2446 translation = BIOS_ATA_TRANSLATION_NONE;
2447 else if (!strcmp(buf, "lba"))
2448 translation = BIOS_ATA_TRANSLATION_LBA;
2449 else if (!strcmp(buf, "auto"))
2450 translation = BIOS_ATA_TRANSLATION_AUTO;
2451 else {
2452 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2453 return -1;
2457 if (get_param_value(buf, sizeof(buf), "media", str)) {
2458 if (!strcmp(buf, "disk")) {
2459 media = MEDIA_DISK;
2460 } else if (!strcmp(buf, "cdrom")) {
2461 if (cyls || secs || heads) {
2462 fprintf(stderr,
2463 "qemu: '%s' invalid physical CHS format\n", str);
2464 return -1;
2466 media = MEDIA_CDROM;
2467 } else {
2468 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2469 return -1;
2473 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2474 if (!strcmp(buf, "on"))
2475 snapshot = 1;
2476 else if (!strcmp(buf, "off"))
2477 snapshot = 0;
2478 else {
2479 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2480 return -1;
2484 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2485 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2486 cache = 0;
2487 else if (!strcmp(buf, "writethrough"))
2488 cache = 1;
2489 else if (!strcmp(buf, "writeback"))
2490 cache = 2;
2491 else {
2492 fprintf(stderr, "qemu: invalid cache option\n");
2493 return -1;
2497 if (get_param_value(buf, sizeof(buf), "format", str)) {
2498 if (strcmp(buf, "?") == 0) {
2499 fprintf(stderr, "qemu: Supported formats:");
2500 bdrv_iterate_format(bdrv_format_print, NULL);
2501 fprintf(stderr, "\n");
2502 return -1;
2504 drv = bdrv_find_format(buf);
2505 if (!drv) {
2506 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2507 return -1;
2511 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2512 if (!strcmp(buf, "on")) {
2513 if (extboot_drive != -1) {
2514 fprintf(stderr, "qemu: two bootable drives specified\n");
2515 return -1;
2517 extboot_drive = nb_drives;
2518 } else if (strcmp(buf, "off")) {
2519 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2520 return -1;
2524 if (arg->file == NULL)
2525 get_param_value(file, sizeof(file), "file", str);
2526 else
2527 pstrcpy(file, sizeof(file), arg->file);
2529 if (!get_param_value(serial, sizeof(serial), "serial", str))
2530 memset(serial, 0, sizeof(serial));
2532 onerror = BLOCK_ERR_STOP_ENOSPC;
2533 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2534 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2535 fprintf(stderr, "werror is no supported by this format\n");
2536 return -1;
2538 if (!strcmp(buf, "ignore"))
2539 onerror = BLOCK_ERR_IGNORE;
2540 else if (!strcmp(buf, "enospc"))
2541 onerror = BLOCK_ERR_STOP_ENOSPC;
2542 else if (!strcmp(buf, "stop"))
2543 onerror = BLOCK_ERR_STOP_ANY;
2544 else if (!strcmp(buf, "report"))
2545 onerror = BLOCK_ERR_REPORT;
2546 else {
2547 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2548 return -1;
2552 /* compute bus and unit according index */
2554 if (index != -1) {
2555 if (bus_id != 0 || unit_id != -1) {
2556 fprintf(stderr,
2557 "qemu: '%s' index cannot be used with bus and unit\n", str);
2558 return -1;
2560 if (max_devs == 0)
2562 unit_id = index;
2563 bus_id = 0;
2564 } else {
2565 unit_id = index % max_devs;
2566 bus_id = index / max_devs;
2570 /* if user doesn't specify a unit_id,
2571 * try to find the first free
2574 if (unit_id == -1) {
2575 unit_id = 0;
2576 while (drive_get_index(type, bus_id, unit_id) != -1) {
2577 unit_id++;
2578 if (max_devs && unit_id >= max_devs) {
2579 unit_id -= max_devs;
2580 bus_id++;
2585 /* check unit id */
2587 if (max_devs && unit_id >= max_devs) {
2588 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2589 str, unit_id, max_devs - 1);
2590 return -1;
2594 * ignore multiple definitions
2597 if (drive_get_index(type, bus_id, unit_id) != -1)
2598 return -2;
2600 /* init */
2602 if (type == IF_IDE || type == IF_SCSI)
2603 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2604 if (max_devs)
2605 snprintf(buf, sizeof(buf), "%s%i%s%i",
2606 devname, bus_id, mediastr, unit_id);
2607 else
2608 snprintf(buf, sizeof(buf), "%s%s%i",
2609 devname, mediastr, unit_id);
2610 bdrv = bdrv_new(buf);
2611 drives_table_idx = drive_get_free_idx();
2612 drives_table[drives_table_idx].bdrv = bdrv;
2613 drives_table[drives_table_idx].type = type;
2614 drives_table[drives_table_idx].bus = bus_id;
2615 drives_table[drives_table_idx].unit = unit_id;
2616 drives_table[drives_table_idx].onerror = onerror;
2617 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2618 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2619 nb_drives++;
2621 switch(type) {
2622 case IF_IDE:
2623 case IF_SCSI:
2624 switch(media) {
2625 case MEDIA_DISK:
2626 if (cyls != 0) {
2627 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2628 bdrv_set_translation_hint(bdrv, translation);
2630 break;
2631 case MEDIA_CDROM:
2632 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2633 break;
2635 break;
2636 case IF_SD:
2637 /* FIXME: This isn't really a floppy, but it's a reasonable
2638 approximation. */
2639 case IF_FLOPPY:
2640 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2641 break;
2642 case IF_PFLASH:
2643 case IF_MTD:
2644 case IF_VIRTIO:
2645 break;
2647 if (!file[0])
2648 return -2;
2649 bdrv_flags = 0;
2650 if (snapshot) {
2651 bdrv_flags |= BDRV_O_SNAPSHOT;
2652 cache = 2; /* always use write-back with snapshot */
2654 if (cache == 0) /* no caching */
2655 bdrv_flags |= BDRV_O_NOCACHE;
2656 else if (cache == 2) /* write-back */
2657 bdrv_flags |= BDRV_O_CACHE_WB;
2658 else if (cache == 3) /* not specified */
2659 bdrv_flags |= BDRV_O_CACHE_DEF;
2660 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2661 fprintf(stderr, "qemu: could not open disk image %s\n",
2662 file);
2663 return -1;
2665 if (bdrv_key_required(bdrv))
2666 autostart = 0;
2667 return drives_table_idx;
2670 /***********************************************************/
2671 /* USB devices */
2673 static USBPort *used_usb_ports;
2674 static USBPort *free_usb_ports;
2676 /* ??? Maybe change this to register a hub to keep track of the topology. */
2677 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2678 usb_attachfn attach)
2680 port->opaque = opaque;
2681 port->index = index;
2682 port->attach = attach;
2683 port->next = free_usb_ports;
2684 free_usb_ports = port;
2687 int usb_device_add_dev(USBDevice *dev)
2689 USBPort *port;
2691 /* Find a USB port to add the device to. */
2692 port = free_usb_ports;
2693 if (!port->next) {
2694 USBDevice *hub;
2696 /* Create a new hub and chain it on. */
2697 free_usb_ports = NULL;
2698 port->next = used_usb_ports;
2699 used_usb_ports = port;
2701 hub = usb_hub_init(VM_USB_HUB_SIZE);
2702 usb_attach(port, hub);
2703 port = free_usb_ports;
2706 free_usb_ports = port->next;
2707 port->next = used_usb_ports;
2708 used_usb_ports = port;
2709 usb_attach(port, dev);
2710 return 0;
2713 static void usb_msd_password_cb(void *opaque, int err)
2715 USBDevice *dev = opaque;
2717 if (!err)
2718 usb_device_add_dev(dev);
2719 else
2720 dev->handle_destroy(dev);
2723 static int usb_device_add(const char *devname, int is_hotplug)
2725 const char *p;
2726 USBDevice *dev;
2728 if (!free_usb_ports)
2729 return -1;
2731 if (strstart(devname, "host:", &p)) {
2732 dev = usb_host_device_open(p);
2733 } else if (!strcmp(devname, "mouse")) {
2734 dev = usb_mouse_init();
2735 } else if (!strcmp(devname, "tablet")) {
2736 dev = usb_tablet_init();
2737 } else if (!strcmp(devname, "keyboard")) {
2738 dev = usb_keyboard_init();
2739 } else if (strstart(devname, "disk:", &p)) {
2740 BlockDriverState *bs;
2742 dev = usb_msd_init(p);
2743 if (!dev)
2744 return -1;
2745 bs = usb_msd_get_bdrv(dev);
2746 if (bdrv_key_required(bs)) {
2747 autostart = 0;
2748 if (is_hotplug) {
2749 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2750 dev);
2751 return 0;
2754 } else if (!strcmp(devname, "wacom-tablet")) {
2755 dev = usb_wacom_init();
2756 } else if (strstart(devname, "serial:", &p)) {
2757 dev = usb_serial_init(p);
2758 #ifdef CONFIG_BRLAPI
2759 } else if (!strcmp(devname, "braille")) {
2760 dev = usb_baum_init();
2761 #endif
2762 } else if (strstart(devname, "net:", &p)) {
2763 int nic = nb_nics;
2765 if (net_client_init("nic", p) < 0)
2766 return -1;
2767 nd_table[nic].model = "usb";
2768 dev = usb_net_init(&nd_table[nic]);
2769 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2770 dev = usb_bt_init(devname[2] ? hci_init(p) :
2771 bt_new_hci(qemu_find_bt_vlan(0)));
2772 } else {
2773 return -1;
2775 if (!dev)
2776 return -1;
2778 return usb_device_add_dev(dev);
2781 int usb_device_del_addr(int bus_num, int addr)
2783 USBPort *port;
2784 USBPort **lastp;
2785 USBDevice *dev;
2787 if (!used_usb_ports)
2788 return -1;
2790 if (bus_num != 0)
2791 return -1;
2793 lastp = &used_usb_ports;
2794 port = used_usb_ports;
2795 while (port && port->dev->addr != addr) {
2796 lastp = &port->next;
2797 port = port->next;
2800 if (!port)
2801 return -1;
2803 dev = port->dev;
2804 *lastp = port->next;
2805 usb_attach(port, NULL);
2806 dev->handle_destroy(dev);
2807 port->next = free_usb_ports;
2808 free_usb_ports = port;
2809 return 0;
2812 static int usb_device_del(const char *devname)
2814 int bus_num, addr;
2815 const char *p;
2817 if (strstart(devname, "host:", &p))
2818 return usb_host_device_close(p);
2820 if (!used_usb_ports)
2821 return -1;
2823 p = strchr(devname, '.');
2824 if (!p)
2825 return -1;
2826 bus_num = strtoul(devname, NULL, 0);
2827 addr = strtoul(p + 1, NULL, 0);
2829 return usb_device_del_addr(bus_num, addr);
2832 void do_usb_add(Monitor *mon, const char *devname)
2834 usb_device_add(devname, 1);
2837 void do_usb_del(Monitor *mon, const char *devname)
2839 usb_device_del(devname);
2842 void usb_info(Monitor *mon)
2844 USBDevice *dev;
2845 USBPort *port;
2846 const char *speed_str;
2848 if (!usb_enabled) {
2849 monitor_printf(mon, "USB support not enabled\n");
2850 return;
2853 for (port = used_usb_ports; port; port = port->next) {
2854 dev = port->dev;
2855 if (!dev)
2856 continue;
2857 switch(dev->speed) {
2858 case USB_SPEED_LOW:
2859 speed_str = "1.5";
2860 break;
2861 case USB_SPEED_FULL:
2862 speed_str = "12";
2863 break;
2864 case USB_SPEED_HIGH:
2865 speed_str = "480";
2866 break;
2867 default:
2868 speed_str = "?";
2869 break;
2871 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2872 0, dev->addr, speed_str, dev->devname);
2876 /***********************************************************/
2877 /* PCMCIA/Cardbus */
2879 static struct pcmcia_socket_entry_s {
2880 struct pcmcia_socket_s *socket;
2881 struct pcmcia_socket_entry_s *next;
2882 } *pcmcia_sockets = 0;
2884 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2886 struct pcmcia_socket_entry_s *entry;
2888 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2889 entry->socket = socket;
2890 entry->next = pcmcia_sockets;
2891 pcmcia_sockets = entry;
2894 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2896 struct pcmcia_socket_entry_s *entry, **ptr;
2898 ptr = &pcmcia_sockets;
2899 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2900 if (entry->socket == socket) {
2901 *ptr = entry->next;
2902 qemu_free(entry);
2906 void pcmcia_info(Monitor *mon)
2908 struct pcmcia_socket_entry_s *iter;
2910 if (!pcmcia_sockets)
2911 monitor_printf(mon, "No PCMCIA sockets\n");
2913 for (iter = pcmcia_sockets; iter; iter = iter->next)
2914 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2915 iter->socket->attached ? iter->socket->card_string :
2916 "Empty");
2919 /***********************************************************/
2920 /* register display */
2922 struct DisplayAllocator default_allocator = {
2923 defaultallocator_create_displaysurface,
2924 defaultallocator_resize_displaysurface,
2925 defaultallocator_free_displaysurface
2928 void register_displaystate(DisplayState *ds)
2930 DisplayState **s;
2931 s = &display_state;
2932 while (*s != NULL)
2933 s = &(*s)->next;
2934 ds->next = NULL;
2935 *s = ds;
2938 DisplayState *get_displaystate(void)
2940 return display_state;
2943 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2945 if(ds->allocator == &default_allocator) ds->allocator = da;
2946 return ds->allocator;
2949 /* dumb display */
2951 static void dumb_display_init(void)
2953 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2954 ds->allocator = &default_allocator;
2955 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2956 register_displaystate(ds);
2959 /***********************************************************/
2960 /* I/O handling */
2962 typedef struct IOHandlerRecord {
2963 int fd;
2964 IOCanRWHandler *fd_read_poll;
2965 IOHandler *fd_read;
2966 IOHandler *fd_write;
2967 int deleted;
2968 void *opaque;
2969 /* temporary data */
2970 struct pollfd *ufd;
2971 struct IOHandlerRecord *next;
2972 } IOHandlerRecord;
2974 static IOHandlerRecord *first_io_handler;
2976 /* XXX: fd_read_poll should be suppressed, but an API change is
2977 necessary in the character devices to suppress fd_can_read(). */
2978 int qemu_set_fd_handler2(int fd,
2979 IOCanRWHandler *fd_read_poll,
2980 IOHandler *fd_read,
2981 IOHandler *fd_write,
2982 void *opaque)
2984 IOHandlerRecord **pioh, *ioh;
2986 if (!fd_read && !fd_write) {
2987 pioh = &first_io_handler;
2988 for(;;) {
2989 ioh = *pioh;
2990 if (ioh == NULL)
2991 break;
2992 if (ioh->fd == fd) {
2993 ioh->deleted = 1;
2994 break;
2996 pioh = &ioh->next;
2998 } else {
2999 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3000 if (ioh->fd == fd)
3001 goto found;
3003 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3004 ioh->next = first_io_handler;
3005 first_io_handler = ioh;
3006 found:
3007 ioh->fd = fd;
3008 ioh->fd_read_poll = fd_read_poll;
3009 ioh->fd_read = fd_read;
3010 ioh->fd_write = fd_write;
3011 ioh->opaque = opaque;
3012 ioh->deleted = 0;
3014 main_loop_break();
3015 return 0;
3018 int qemu_set_fd_handler(int fd,
3019 IOHandler *fd_read,
3020 IOHandler *fd_write,
3021 void *opaque)
3023 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3026 #ifdef _WIN32
3027 /***********************************************************/
3028 /* Polling handling */
3030 typedef struct PollingEntry {
3031 PollingFunc *func;
3032 void *opaque;
3033 struct PollingEntry *next;
3034 } PollingEntry;
3036 static PollingEntry *first_polling_entry;
3038 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3040 PollingEntry **ppe, *pe;
3041 pe = qemu_mallocz(sizeof(PollingEntry));
3042 pe->func = func;
3043 pe->opaque = opaque;
3044 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3045 *ppe = pe;
3046 return 0;
3049 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3051 PollingEntry **ppe, *pe;
3052 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3053 pe = *ppe;
3054 if (pe->func == func && pe->opaque == opaque) {
3055 *ppe = pe->next;
3056 qemu_free(pe);
3057 break;
3062 /***********************************************************/
3063 /* Wait objects support */
3064 typedef struct WaitObjects {
3065 int num;
3066 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3067 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3068 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3069 } WaitObjects;
3071 static WaitObjects wait_objects = {0};
3073 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3075 WaitObjects *w = &wait_objects;
3077 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3078 return -1;
3079 w->events[w->num] = handle;
3080 w->func[w->num] = func;
3081 w->opaque[w->num] = opaque;
3082 w->num++;
3083 return 0;
3086 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3088 int i, found;
3089 WaitObjects *w = &wait_objects;
3091 found = 0;
3092 for (i = 0; i < w->num; i++) {
3093 if (w->events[i] == handle)
3094 found = 1;
3095 if (found) {
3096 w->events[i] = w->events[i + 1];
3097 w->func[i] = w->func[i + 1];
3098 w->opaque[i] = w->opaque[i + 1];
3101 if (found)
3102 w->num--;
3104 #endif
3106 /***********************************************************/
3107 /* ram save/restore */
3109 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3111 int v;
3113 v = qemu_get_byte(f);
3114 switch(v) {
3115 case 0:
3116 if (qemu_get_buffer(f, buf, len) != len)
3117 return -EIO;
3118 break;
3119 case 1:
3120 v = qemu_get_byte(f);
3121 memset(buf, v, len);
3122 break;
3123 default:
3124 return -EINVAL;
3127 if (qemu_file_has_error(f))
3128 return -EIO;
3130 return 0;
3133 static int ram_load_v1(QEMUFile *f, void *opaque)
3135 int ret;
3136 ram_addr_t i;
3138 if (qemu_get_be32(f) != phys_ram_size)
3139 return -EINVAL;
3140 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3141 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3142 continue;
3143 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3144 if (ret)
3145 return ret;
3147 return 0;
3150 #define BDRV_HASH_BLOCK_SIZE 1024
3151 #define IOBUF_SIZE 4096
3152 #define RAM_CBLOCK_MAGIC 0xfabe
3154 typedef struct RamDecompressState {
3155 z_stream zstream;
3156 QEMUFile *f;
3157 uint8_t buf[IOBUF_SIZE];
3158 } RamDecompressState;
3160 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3162 int ret;
3163 memset(s, 0, sizeof(*s));
3164 s->f = f;
3165 ret = inflateInit(&s->zstream);
3166 if (ret != Z_OK)
3167 return -1;
3168 return 0;
3171 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3173 int ret, clen;
3175 s->zstream.avail_out = len;
3176 s->zstream.next_out = buf;
3177 while (s->zstream.avail_out > 0) {
3178 if (s->zstream.avail_in == 0) {
3179 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3180 return -1;
3181 clen = qemu_get_be16(s->f);
3182 if (clen > IOBUF_SIZE)
3183 return -1;
3184 qemu_get_buffer(s->f, s->buf, clen);
3185 s->zstream.avail_in = clen;
3186 s->zstream.next_in = s->buf;
3188 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3189 if (ret != Z_OK && ret != Z_STREAM_END) {
3190 return -1;
3193 return 0;
3196 static void ram_decompress_close(RamDecompressState *s)
3198 inflateEnd(&s->zstream);
3201 #define RAM_SAVE_FLAG_FULL 0x01
3202 #define RAM_SAVE_FLAG_COMPRESS 0x02
3203 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3204 #define RAM_SAVE_FLAG_PAGE 0x08
3205 #define RAM_SAVE_FLAG_EOS 0x10
3207 static int is_dup_page(uint8_t *page, uint8_t ch)
3209 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3210 uint32_t *array = (uint32_t *)page;
3211 int i;
3213 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3214 if (array[i] != val)
3215 return 0;
3218 return 1;
3221 static int ram_save_block(QEMUFile *f)
3223 static ram_addr_t current_addr = 0;
3224 ram_addr_t saved_addr = current_addr;
3225 ram_addr_t addr = 0;
3226 int found = 0;
3228 while (addr < phys_ram_size) {
3229 if (kvm_enabled() && current_addr == 0)
3230 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3231 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3232 uint8_t ch;
3234 cpu_physical_memory_reset_dirty(current_addr,
3235 current_addr + TARGET_PAGE_SIZE,
3236 MIGRATION_DIRTY_FLAG);
3238 ch = *(phys_ram_base + current_addr);
3240 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3241 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3242 qemu_put_byte(f, ch);
3243 } else {
3244 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3245 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3248 found = 1;
3249 break;
3251 addr += TARGET_PAGE_SIZE;
3252 current_addr = (saved_addr + addr) % phys_ram_size;
3255 return found;
3258 static ram_addr_t ram_save_threshold = 10;
3260 static ram_addr_t ram_save_remaining(void)
3262 ram_addr_t addr;
3263 ram_addr_t count = 0;
3265 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3266 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3267 count++;
3270 return count;
3273 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3275 ram_addr_t addr;
3277 if (stage == 1) {
3278 /* Make sure all dirty bits are set */
3279 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3280 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3281 cpu_physical_memory_set_dirty(addr);
3284 /* Enable dirty memory tracking */
3285 cpu_physical_memory_set_dirty_tracking(1);
3287 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3290 while (!qemu_file_rate_limit(f)) {
3291 int ret;
3293 ret = ram_save_block(f);
3294 if (ret == 0) /* no more blocks */
3295 break;
3298 /* try transferring iterative blocks of memory */
3300 if (stage == 3) {
3302 /* flush all remaining blocks regardless of rate limiting */
3303 while (ram_save_block(f) != 0);
3304 cpu_physical_memory_set_dirty_tracking(0);
3307 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3309 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3312 static int ram_load_dead(QEMUFile *f, void *opaque)
3314 RamDecompressState s1, *s = &s1;
3315 uint8_t buf[10];
3316 ram_addr_t i;
3318 if (ram_decompress_open(s, f) < 0)
3319 return -EINVAL;
3320 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3321 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3322 continue;
3323 if (ram_decompress_buf(s, buf, 1) < 0) {
3324 fprintf(stderr, "Error while reading ram block header\n");
3325 goto error;
3327 if (buf[0] == 0) {
3328 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3329 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3330 goto error;
3332 } else {
3333 error:
3334 printf("Error block header\n");
3335 return -EINVAL;
3338 ram_decompress_close(s);
3340 return 0;
3343 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3345 ram_addr_t addr;
3346 int flags;
3348 if (version_id == 1)
3349 return ram_load_v1(f, opaque);
3351 if (version_id == 2) {
3352 if (qemu_get_be32(f) != phys_ram_size)
3353 return -EINVAL;
3354 return ram_load_dead(f, opaque);
3357 if (version_id != 3)
3358 return -EINVAL;
3360 do {
3361 addr = qemu_get_be64(f);
3363 flags = addr & ~TARGET_PAGE_MASK;
3364 addr &= TARGET_PAGE_MASK;
3366 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3367 if (addr != phys_ram_size)
3368 return -EINVAL;
3371 if (flags & RAM_SAVE_FLAG_FULL) {
3372 if (ram_load_dead(f, opaque) < 0)
3373 return -EINVAL;
3376 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3377 uint8_t ch = qemu_get_byte(f);
3378 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3379 } else if (flags & RAM_SAVE_FLAG_PAGE)
3380 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3381 } while (!(flags & RAM_SAVE_FLAG_EOS));
3383 return 0;
3386 void qemu_service_io(void)
3388 CPUState *env = cpu_single_env;
3389 if (env) {
3390 cpu_exit(env);
3391 #ifdef USE_KQEMU
3392 if (env->kqemu_enabled) {
3393 kqemu_cpu_interrupt(env);
3395 #endif
3399 /***********************************************************/
3400 /* bottom halves (can be seen as timers which expire ASAP) */
3402 struct QEMUBH {
3403 QEMUBHFunc *cb;
3404 void *opaque;
3405 int scheduled;
3406 int idle;
3407 int deleted;
3408 QEMUBH *next;
3411 static QEMUBH *first_bh = NULL;
3413 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3415 QEMUBH *bh;
3416 bh = qemu_mallocz(sizeof(QEMUBH));
3417 bh->cb = cb;
3418 bh->opaque = opaque;
3419 bh->next = first_bh;
3420 first_bh = bh;
3421 return bh;
3424 int qemu_bh_poll(void)
3426 QEMUBH *bh, **bhp;
3427 int ret;
3429 ret = 0;
3430 for (bh = first_bh; bh; bh = bh->next) {
3431 if (!bh->deleted && bh->scheduled) {
3432 bh->scheduled = 0;
3433 if (!bh->idle)
3434 ret = 1;
3435 bh->idle = 0;
3436 bh->cb(bh->opaque);
3440 /* remove deleted bhs */
3441 bhp = &first_bh;
3442 while (*bhp) {
3443 bh = *bhp;
3444 if (bh->deleted) {
3445 *bhp = bh->next;
3446 qemu_free(bh);
3447 } else
3448 bhp = &bh->next;
3451 return ret;
3454 void qemu_bh_schedule_idle(QEMUBH *bh)
3456 if (bh->scheduled)
3457 return;
3458 bh->scheduled = 1;
3459 bh->idle = 1;
3462 void qemu_bh_schedule(QEMUBH *bh)
3464 CPUState *env = cpu_single_env;
3465 if (bh->scheduled)
3466 return;
3467 bh->scheduled = 1;
3468 bh->idle = 0;
3469 /* stop the currently executing CPU to execute the BH ASAP */
3470 if (env) {
3471 cpu_exit(env);
3473 main_loop_break();
3476 void qemu_bh_cancel(QEMUBH *bh)
3478 bh->scheduled = 0;
3481 void qemu_bh_delete(QEMUBH *bh)
3483 bh->scheduled = 0;
3484 bh->deleted = 1;
3487 static void qemu_bh_update_timeout(int *timeout)
3489 QEMUBH *bh;
3491 for (bh = first_bh; bh; bh = bh->next) {
3492 if (!bh->deleted && bh->scheduled) {
3493 if (bh->idle) {
3494 /* idle bottom halves will be polled at least
3495 * every 10ms */
3496 *timeout = MIN(10, *timeout);
3497 } else {
3498 /* non-idle bottom halves will be executed
3499 * immediately */
3500 *timeout = 0;
3501 break;
3507 /***********************************************************/
3508 /* machine registration */
3510 static QEMUMachine *first_machine = NULL;
3511 QEMUMachine *current_machine = NULL;
3513 int qemu_register_machine(QEMUMachine *m)
3515 QEMUMachine **pm;
3516 pm = &first_machine;
3517 while (*pm != NULL)
3518 pm = &(*pm)->next;
3519 m->next = NULL;
3520 *pm = m;
3521 return 0;
3524 static QEMUMachine *find_machine(const char *name)
3526 QEMUMachine *m;
3528 for(m = first_machine; m != NULL; m = m->next) {
3529 if (!strcmp(m->name, name))
3530 return m;
3532 return NULL;
3535 /***********************************************************/
3536 /* main execution loop */
3538 static void gui_update(void *opaque)
3540 uint64_t interval = GUI_REFRESH_INTERVAL;
3541 DisplayState *ds = opaque;
3542 DisplayChangeListener *dcl = ds->listeners;
3544 dpy_refresh(ds);
3546 while (dcl != NULL) {
3547 if (dcl->gui_timer_interval &&
3548 dcl->gui_timer_interval < interval)
3549 interval = dcl->gui_timer_interval;
3550 dcl = dcl->next;
3552 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3555 static void nographic_update(void *opaque)
3557 uint64_t interval = GUI_REFRESH_INTERVAL;
3559 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3562 struct vm_change_state_entry {
3563 VMChangeStateHandler *cb;
3564 void *opaque;
3565 LIST_ENTRY (vm_change_state_entry) entries;
3568 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3570 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3571 void *opaque)
3573 VMChangeStateEntry *e;
3575 e = qemu_mallocz(sizeof (*e));
3577 e->cb = cb;
3578 e->opaque = opaque;
3579 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3580 return e;
3583 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3585 LIST_REMOVE (e, entries);
3586 qemu_free (e);
3589 static void vm_state_notify(int running, int reason)
3591 VMChangeStateEntry *e;
3593 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3594 e->cb(e->opaque, running, reason);
3598 void vm_start(void)
3600 if (!vm_running) {
3601 cpu_enable_ticks();
3602 vm_running = 1;
3603 vm_state_notify(1, 0);
3604 if (kvm_enabled())
3605 qemu_kvm_resume_all_threads();
3606 qemu_rearm_alarm_timer(alarm_timer);
3610 void vm_stop(int reason)
3612 if (vm_running) {
3613 cpu_disable_ticks();
3614 vm_running = 0;
3615 if (kvm_enabled())
3616 qemu_kvm_pause_all_threads();
3617 vm_state_notify(0, reason);
3621 /* reset/shutdown handler */
3623 typedef struct QEMUResetEntry {
3624 QEMUResetHandler *func;
3625 void *opaque;
3626 struct QEMUResetEntry *next;
3627 } QEMUResetEntry;
3629 static QEMUResetEntry *first_reset_entry;
3630 static int reset_requested;
3631 static int shutdown_requested;
3632 static int powerdown_requested;
3634 int qemu_shutdown_requested(void)
3636 int r = shutdown_requested;
3637 shutdown_requested = 0;
3638 return r;
3641 int qemu_reset_requested(void)
3643 int r = reset_requested;
3644 reset_requested = 0;
3645 return r;
3648 int qemu_powerdown_requested(void)
3650 int r = powerdown_requested;
3651 powerdown_requested = 0;
3652 return r;
3655 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3657 QEMUResetEntry **pre, *re;
3659 pre = &first_reset_entry;
3660 while (*pre != NULL)
3661 pre = &(*pre)->next;
3662 re = qemu_mallocz(sizeof(QEMUResetEntry));
3663 re->func = func;
3664 re->opaque = opaque;
3665 re->next = NULL;
3666 *pre = re;
3669 void qemu_system_reset(void)
3671 QEMUResetEntry *re;
3673 /* reset all devices */
3674 for(re = first_reset_entry; re != NULL; re = re->next) {
3675 re->func(re->opaque);
3679 void qemu_system_reset_request(void)
3681 if (no_reboot) {
3682 shutdown_requested = 1;
3683 } else {
3684 reset_requested = 1;
3686 if (cpu_single_env) {
3687 qemu_kvm_cpu_stop(cpu_single_env);
3688 cpu_exit(cpu_single_env);
3692 void qemu_system_shutdown_request(void)
3694 shutdown_requested = 1;
3695 if (cpu_single_env)
3696 cpu_exit(cpu_single_env);
3699 void qemu_system_powerdown_request(void)
3701 powerdown_requested = 1;
3702 if (cpu_single_env)
3703 cpu_exit(cpu_single_env);
3706 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3707 struct timeval *tv)
3709 int ret;
3711 /* KVM holds a mutex while QEMU code is running, we need hooks to
3712 release the mutex whenever QEMU code sleeps. */
3714 kvm_sleep_begin();
3716 ret = select(max_fd, rfds, wfds, xfds, tv);
3718 kvm_sleep_end();
3720 return ret;
3723 #ifdef _WIN32
3724 static void host_main_loop_wait(int *timeout)
3726 int ret, ret2, i;
3727 PollingEntry *pe;
3730 /* XXX: need to suppress polling by better using win32 events */
3731 ret = 0;
3732 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3733 ret |= pe->func(pe->opaque);
3735 if (ret == 0) {
3736 int err;
3737 WaitObjects *w = &wait_objects;
3739 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3740 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3741 if (w->func[ret - WAIT_OBJECT_0])
3742 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3744 /* Check for additional signaled events */
3745 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3747 /* Check if event is signaled */
3748 ret2 = WaitForSingleObject(w->events[i], 0);
3749 if(ret2 == WAIT_OBJECT_0) {
3750 if (w->func[i])
3751 w->func[i](w->opaque[i]);
3752 } else if (ret2 == WAIT_TIMEOUT) {
3753 } else {
3754 err = GetLastError();
3755 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3758 } else if (ret == WAIT_TIMEOUT) {
3759 } else {
3760 err = GetLastError();
3761 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3765 *timeout = 0;
3767 #else
3768 static void host_main_loop_wait(int *timeout)
3771 #endif
3773 void main_loop_wait(int timeout)
3775 IOHandlerRecord *ioh;
3776 fd_set rfds, wfds, xfds;
3777 int ret, nfds;
3778 struct timeval tv;
3780 qemu_bh_update_timeout(&timeout);
3782 host_main_loop_wait(&timeout);
3784 /* poll any events */
3785 /* XXX: separate device handlers from system ones */
3786 nfds = -1;
3787 FD_ZERO(&rfds);
3788 FD_ZERO(&wfds);
3789 FD_ZERO(&xfds);
3790 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3791 if (ioh->deleted)
3792 continue;
3793 if (ioh->fd_read &&
3794 (!ioh->fd_read_poll ||
3795 ioh->fd_read_poll(ioh->opaque) != 0)) {
3796 FD_SET(ioh->fd, &rfds);
3797 if (ioh->fd > nfds)
3798 nfds = ioh->fd;
3800 if (ioh->fd_write) {
3801 FD_SET(ioh->fd, &wfds);
3802 if (ioh->fd > nfds)
3803 nfds = ioh->fd;
3807 tv.tv_sec = timeout / 1000;
3808 tv.tv_usec = (timeout % 1000) * 1000;
3810 #if defined(CONFIG_SLIRP)
3811 if (slirp_is_inited()) {
3812 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3814 #endif
3815 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3816 if (ret > 0) {
3817 IOHandlerRecord **pioh;
3819 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3820 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3821 ioh->fd_read(ioh->opaque);
3822 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3823 FD_CLR(ioh->fd, &rfds);
3825 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3826 ioh->fd_write(ioh->opaque);
3830 /* remove deleted IO handlers */
3831 pioh = &first_io_handler;
3832 while (*pioh) {
3833 ioh = *pioh;
3834 if (ioh->deleted) {
3835 *pioh = ioh->next;
3836 qemu_free(ioh);
3837 } else
3838 pioh = &ioh->next;
3841 #if defined(CONFIG_SLIRP)
3842 if (slirp_is_inited()) {
3843 if (ret < 0) {
3844 FD_ZERO(&rfds);
3845 FD_ZERO(&wfds);
3846 FD_ZERO(&xfds);
3848 slirp_select_poll(&rfds, &wfds, &xfds);
3850 #endif
3852 /* vm time timers */
3853 if (vm_running && (!cur_cpu
3854 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3855 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3856 qemu_get_clock(vm_clock));
3858 /* real time timers */
3859 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3860 qemu_get_clock(rt_clock));
3862 /* Check bottom-halves last in case any of the earlier events triggered
3863 them. */
3864 qemu_bh_poll();
3868 static int main_loop(void)
3870 int ret, timeout;
3871 #ifdef CONFIG_PROFILER
3872 int64_t ti;
3873 #endif
3874 CPUState *env;
3877 if (kvm_enabled()) {
3878 kvm_main_loop();
3879 cpu_disable_ticks();
3880 return 0;
3883 cur_cpu = first_cpu;
3884 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3885 for(;;) {
3886 if (vm_running) {
3888 for(;;) {
3889 /* get next cpu */
3890 env = next_cpu;
3891 #ifdef CONFIG_PROFILER
3892 ti = profile_getclock();
3893 #endif
3894 if (use_icount) {
3895 int64_t count;
3896 int decr;
3897 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3898 env->icount_decr.u16.low = 0;
3899 env->icount_extra = 0;
3900 count = qemu_next_deadline();
3901 count = (count + (1 << icount_time_shift) - 1)
3902 >> icount_time_shift;
3903 qemu_icount += count;
3904 decr = (count > 0xffff) ? 0xffff : count;
3905 count -= decr;
3906 env->icount_decr.u16.low = decr;
3907 env->icount_extra = count;
3909 ret = cpu_exec(env);
3910 #ifdef CONFIG_PROFILER
3911 qemu_time += profile_getclock() - ti;
3912 #endif
3913 if (use_icount) {
3914 /* Fold pending instructions back into the
3915 instruction counter, and clear the interrupt flag. */
3916 qemu_icount -= (env->icount_decr.u16.low
3917 + env->icount_extra);
3918 env->icount_decr.u32 = 0;
3919 env->icount_extra = 0;
3921 next_cpu = env->next_cpu ?: first_cpu;
3922 if (event_pending && likely(ret != EXCP_DEBUG)) {
3923 ret = EXCP_INTERRUPT;
3924 event_pending = 0;
3925 break;
3927 if (ret == EXCP_HLT) {
3928 /* Give the next CPU a chance to run. */
3929 cur_cpu = env;
3930 continue;
3932 if (ret != EXCP_HALTED)
3933 break;
3934 /* all CPUs are halted ? */
3935 if (env == cur_cpu)
3936 break;
3938 cur_cpu = env;
3940 if (shutdown_requested) {
3941 ret = EXCP_INTERRUPT;
3942 if (no_shutdown) {
3943 vm_stop(0);
3944 no_shutdown = 0;
3946 else
3947 break;
3949 if (reset_requested) {
3950 reset_requested = 0;
3951 qemu_system_reset();
3952 if (kvm_enabled())
3953 kvm_load_registers(env);
3954 ret = EXCP_INTERRUPT;
3956 if (powerdown_requested) {
3957 powerdown_requested = 0;
3958 qemu_system_powerdown();
3959 ret = EXCP_INTERRUPT;
3961 #ifdef CONFIG_GDBSTUB
3962 if (unlikely(ret == EXCP_DEBUG)) {
3963 gdb_set_stop_cpu(cur_cpu);
3964 vm_stop(EXCP_DEBUG);
3966 #endif
3967 /* If all cpus are halted then wait until the next IRQ */
3968 /* XXX: use timeout computed from timers */
3969 if (ret == EXCP_HALTED) {
3970 if (use_icount) {
3971 int64_t add;
3972 int64_t delta;
3973 /* Advance virtual time to the next event. */
3974 if (use_icount == 1) {
3975 /* When not using an adaptive execution frequency
3976 we tend to get badly out of sync with real time,
3977 so just delay for a reasonable amount of time. */
3978 delta = 0;
3979 } else {
3980 delta = cpu_get_icount() - cpu_get_clock();
3982 if (delta > 0) {
3983 /* If virtual time is ahead of real time then just
3984 wait for IO. */
3985 timeout = (delta / 1000000) + 1;
3986 } else {
3987 /* Wait for either IO to occur or the next
3988 timer event. */
3989 add = qemu_next_deadline();
3990 /* We advance the timer before checking for IO.
3991 Limit the amount we advance so that early IO
3992 activity won't get the guest too far ahead. */
3993 if (add > 10000000)
3994 add = 10000000;
3995 delta += add;
3996 add = (add + (1 << icount_time_shift) - 1)
3997 >> icount_time_shift;
3998 qemu_icount += add;
3999 timeout = delta / 1000000;
4000 if (timeout < 0)
4001 timeout = 0;
4003 } else {
4004 timeout = 5000;
4006 } else {
4007 timeout = 0;
4009 } else {
4010 if (shutdown_requested) {
4011 ret = EXCP_INTERRUPT;
4012 break;
4014 timeout = 5000;
4016 #ifdef CONFIG_PROFILER
4017 ti = profile_getclock();
4018 #endif
4019 main_loop_wait(timeout);
4020 #ifdef CONFIG_PROFILER
4021 dev_time += profile_getclock() - ti;
4022 #endif
4024 cpu_disable_ticks();
4025 return ret;
4028 static void help(int exitcode)
4030 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
4031 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4032 "usage: %s [options] [disk_image]\n"
4033 "\n"
4034 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4035 "\n"
4036 #define DEF(option, opt_arg, opt_enum, opt_help) \
4037 opt_help
4038 #define DEFHEADING(text) stringify(text) "\n"
4039 #include "qemu-options.h"
4040 #undef DEF
4041 #undef DEFHEADING
4042 #undef GEN_DOCS
4043 "\n"
4044 "During emulation, the following keys are useful:\n"
4045 "ctrl-alt-f toggle full screen\n"
4046 "ctrl-alt-n switch to virtual console 'n'\n"
4047 "ctrl-alt toggle mouse and keyboard grab\n"
4048 "\n"
4049 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4051 "qemu",
4052 DEFAULT_RAM_SIZE,
4053 #ifndef _WIN32
4054 DEFAULT_NETWORK_SCRIPT,
4055 DEFAULT_NETWORK_DOWN_SCRIPT,
4056 #endif
4057 DEFAULT_GDBSTUB_PORT,
4058 "/tmp/qemu.log");
4059 exit(exitcode);
4062 #define HAS_ARG 0x0001
4064 enum {
4065 #define DEF(option, opt_arg, opt_enum, opt_help) \
4066 opt_enum,
4067 #define DEFHEADING(text)
4068 #include "qemu-options.h"
4069 #undef DEF
4070 #undef DEFHEADING
4071 #undef GEN_DOCS
4074 typedef struct QEMUOption {
4075 const char *name;
4076 int flags;
4077 int index;
4078 } QEMUOption;
4080 static const QEMUOption qemu_options[] = {
4081 { "h", 0, QEMU_OPTION_h },
4082 #define DEF(option, opt_arg, opt_enum, opt_help) \
4083 { option, opt_arg, opt_enum },
4084 #define DEFHEADING(text)
4085 #include "qemu-options.h"
4086 #undef DEF
4087 #undef DEFHEADING
4088 #undef GEN_DOCS
4089 { NULL },
4092 #ifdef HAS_AUDIO
4093 struct soundhw soundhw[] = {
4094 #ifdef HAS_AUDIO_CHOICE
4095 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4097 "pcspk",
4098 "PC speaker",
4101 { .init_isa = pcspk_audio_init }
4103 #endif
4105 #ifdef CONFIG_SB16
4107 "sb16",
4108 "Creative Sound Blaster 16",
4111 { .init_isa = SB16_init }
4113 #endif
4115 #ifdef CONFIG_CS4231A
4117 "cs4231a",
4118 "CS4231A",
4121 { .init_isa = cs4231a_init }
4123 #endif
4125 #ifdef CONFIG_ADLIB
4127 "adlib",
4128 #ifdef HAS_YMF262
4129 "Yamaha YMF262 (OPL3)",
4130 #else
4131 "Yamaha YM3812 (OPL2)",
4132 #endif
4135 { .init_isa = Adlib_init }
4137 #endif
4139 #ifdef CONFIG_GUS
4141 "gus",
4142 "Gravis Ultrasound GF1",
4145 { .init_isa = GUS_init }
4147 #endif
4149 #ifdef CONFIG_AC97
4151 "ac97",
4152 "Intel 82801AA AC97 Audio",
4155 { .init_pci = ac97_init }
4157 #endif
4159 #ifdef CONFIG_ES1370
4161 "es1370",
4162 "ENSONIQ AudioPCI ES1370",
4165 { .init_pci = es1370_init }
4167 #endif
4169 #endif /* HAS_AUDIO_CHOICE */
4171 { NULL, NULL, 0, 0, { NULL } }
4174 static void select_soundhw (const char *optarg)
4176 struct soundhw *c;
4178 if (*optarg == '?') {
4179 show_valid_cards:
4181 printf ("Valid sound card names (comma separated):\n");
4182 for (c = soundhw; c->name; ++c) {
4183 printf ("%-11s %s\n", c->name, c->descr);
4185 printf ("\n-soundhw all will enable all of the above\n");
4186 exit (*optarg != '?');
4188 else {
4189 size_t l;
4190 const char *p;
4191 char *e;
4192 int bad_card = 0;
4194 if (!strcmp (optarg, "all")) {
4195 for (c = soundhw; c->name; ++c) {
4196 c->enabled = 1;
4198 return;
4201 p = optarg;
4202 while (*p) {
4203 e = strchr (p, ',');
4204 l = !e ? strlen (p) : (size_t) (e - p);
4206 for (c = soundhw; c->name; ++c) {
4207 if (!strncmp (c->name, p, l)) {
4208 c->enabled = 1;
4209 break;
4213 if (!c->name) {
4214 if (l > 80) {
4215 fprintf (stderr,
4216 "Unknown sound card name (too big to show)\n");
4218 else {
4219 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4220 (int) l, p);
4222 bad_card = 1;
4224 p += l + (e != NULL);
4227 if (bad_card)
4228 goto show_valid_cards;
4231 #endif
4233 static void select_vgahw (const char *p)
4235 const char *opts;
4237 if (strstart(p, "std", &opts)) {
4238 std_vga_enabled = 1;
4239 cirrus_vga_enabled = 0;
4240 vmsvga_enabled = 0;
4241 } else if (strstart(p, "cirrus", &opts)) {
4242 cirrus_vga_enabled = 1;
4243 std_vga_enabled = 0;
4244 vmsvga_enabled = 0;
4245 } else if (strstart(p, "vmware", &opts)) {
4246 cirrus_vga_enabled = 0;
4247 std_vga_enabled = 0;
4248 vmsvga_enabled = 1;
4249 } else if (strstart(p, "none", &opts)) {
4250 cirrus_vga_enabled = 0;
4251 std_vga_enabled = 0;
4252 vmsvga_enabled = 0;
4253 } else {
4254 invalid_vga:
4255 fprintf(stderr, "Unknown vga type: %s\n", p);
4256 exit(1);
4258 while (*opts) {
4259 const char *nextopt;
4261 if (strstart(opts, ",retrace=", &nextopt)) {
4262 opts = nextopt;
4263 if (strstart(opts, "dumb", &nextopt))
4264 vga_retrace_method = VGA_RETRACE_DUMB;
4265 else if (strstart(opts, "precise", &nextopt))
4266 vga_retrace_method = VGA_RETRACE_PRECISE;
4267 else goto invalid_vga;
4268 } else goto invalid_vga;
4269 opts = nextopt;
4273 #ifdef _WIN32
4274 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4276 exit(STATUS_CONTROL_C_EXIT);
4277 return TRUE;
4279 #endif
4281 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4283 int ret;
4285 if(strlen(str) != 36)
4286 return -1;
4288 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4289 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4290 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4292 if(ret != 16)
4293 return -1;
4295 return 0;
4298 #define MAX_NET_CLIENTS 32
4300 static int saved_argc;
4301 static char **saved_argv;
4302 static const char *saved_incoming;
4304 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4306 *argc = saved_argc;
4307 *argv = saved_argv;
4308 *opt_daemonize = daemonize;
4309 *opt_incoming = saved_incoming;
4312 #ifdef USE_KVM
4314 #define HUGETLBFS_MAGIC 0x958458f6
4316 static long gethugepagesize(const char *path)
4318 struct statfs fs;
4319 int ret;
4321 do {
4322 ret = statfs(path, &fs);
4323 } while (ret != 0 && errno == EINTR);
4325 if (ret != 0) {
4326 perror("statfs");
4327 return 0;
4330 if (fs.f_type != HUGETLBFS_MAGIC)
4331 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4333 return fs.f_bsize;
4336 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4338 char *filename;
4339 void *area;
4340 int fd;
4341 #ifdef MAP_POPULATE
4342 int flags;
4343 #endif
4345 if (!kvm_has_sync_mmu()) {
4346 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4347 return NULL;
4350 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4351 return NULL;
4353 hpagesize = gethugepagesize(path);
4354 if (!hpagesize)
4355 return NULL;
4357 fd = mkstemp(filename);
4358 if (fd < 0) {
4359 perror("mkstemp");
4360 free(filename);
4361 return NULL;
4363 unlink(filename);
4364 free(filename);
4366 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4369 * ftruncate is not supported by hugetlbfs in older
4370 * hosts, so don't bother checking for errors.
4371 * If anything goes wrong with it under other filesystems,
4372 * mmap will fail.
4374 ftruncate(fd, memory);
4376 #ifdef MAP_POPULATE
4377 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4378 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4379 * to sidestep this quirk.
4381 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4382 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4383 #else
4384 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4385 #endif
4386 if (area == MAP_FAILED) {
4387 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4388 close(fd);
4389 return (NULL);
4391 *len = memory;
4392 return area;
4394 #endif
4396 static void *qemu_alloc_physram(unsigned long memory)
4398 void *area = NULL;
4399 #ifdef USE_KVM
4400 unsigned long map_len = memory;
4402 if (mem_path)
4403 area = alloc_mem_area(memory, &map_len, mem_path);
4404 #endif
4405 if (!area)
4406 area = qemu_vmalloc(memory);
4407 #ifdef USE_KVM
4408 if (kvm_setup_guest_memory(area, map_len))
4409 area = NULL;
4410 #endif
4411 return area;
4414 #ifndef _WIN32
4416 static void termsig_handler(int signal)
4418 qemu_system_shutdown_request();
4421 static void termsig_setup(void)
4423 struct sigaction act;
4425 memset(&act, 0, sizeof(act));
4426 act.sa_handler = termsig_handler;
4427 sigaction(SIGINT, &act, NULL);
4428 sigaction(SIGHUP, &act, NULL);
4429 sigaction(SIGTERM, &act, NULL);
4432 #endif
4434 int main(int argc, char **argv, char **envp)
4436 #ifdef CONFIG_GDBSTUB
4437 const char *gdbstub_dev = NULL;
4438 #endif
4439 uint32_t boot_devices_bitmap = 0;
4440 int i;
4441 int snapshot, linux_boot, net_boot;
4442 const char *initrd_filename;
4443 const char *kernel_filename, *kernel_cmdline;
4444 const char *boot_devices = "";
4445 DisplayState *ds;
4446 DisplayChangeListener *dcl;
4447 int cyls, heads, secs, translation;
4448 const char *net_clients[MAX_NET_CLIENTS];
4449 int nb_net_clients;
4450 const char *bt_opts[MAX_BT_CMDLINE];
4451 int nb_bt_opts;
4452 int hda_index;
4453 int optind;
4454 const char *r, *optarg;
4455 CharDriverState *monitor_hd = NULL;
4456 const char *monitor_device;
4457 const char *serial_devices[MAX_SERIAL_PORTS];
4458 int serial_device_index;
4459 const char *parallel_devices[MAX_PARALLEL_PORTS];
4460 int parallel_device_index;
4461 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4462 int virtio_console_index;
4463 const char *loadvm = NULL;
4464 QEMUMachine *machine;
4465 const char *cpu_model;
4466 const char *usb_devices[MAX_USB_CMDLINE];
4467 int usb_devices_index;
4468 #ifndef _WIN32
4469 int fds[2];
4470 #endif
4471 int tb_size;
4472 const char *pid_file = NULL;
4473 const char *incoming = NULL;
4474 #ifndef _WIN32
4475 int fd = 0;
4476 struct passwd *pwd = NULL;
4477 const char *chroot_dir = NULL;
4478 const char *run_as = NULL;
4479 #endif
4481 qemu_cache_utils_init(envp);
4483 LIST_INIT (&vm_change_state_head);
4484 #ifndef _WIN32
4486 struct sigaction act;
4487 sigfillset(&act.sa_mask);
4488 act.sa_flags = 0;
4489 act.sa_handler = SIG_IGN;
4490 sigaction(SIGPIPE, &act, NULL);
4492 #else
4493 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4494 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4495 QEMU to run on a single CPU */
4497 HANDLE h;
4498 DWORD mask, smask;
4499 int i;
4500 h = GetCurrentProcess();
4501 if (GetProcessAffinityMask(h, &mask, &smask)) {
4502 for(i = 0; i < 32; i++) {
4503 if (mask & (1 << i))
4504 break;
4506 if (i != 32) {
4507 mask = 1 << i;
4508 SetProcessAffinityMask(h, mask);
4512 #endif
4514 register_machines();
4515 machine = first_machine;
4516 cpu_model = NULL;
4517 initrd_filename = NULL;
4518 ram_size = 0;
4519 vga_ram_size = VGA_RAM_SIZE;
4520 snapshot = 0;
4521 nographic = 0;
4522 curses = 0;
4523 kernel_filename = NULL;
4524 kernel_cmdline = "";
4525 cyls = heads = secs = 0;
4526 translation = BIOS_ATA_TRANSLATION_AUTO;
4527 monitor_device = "vc:80Cx24C";
4529 serial_devices[0] = "vc:80Cx24C";
4530 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4531 serial_devices[i] = NULL;
4532 serial_device_index = 0;
4534 parallel_devices[0] = "vc:80Cx24C";
4535 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4536 parallel_devices[i] = NULL;
4537 parallel_device_index = 0;
4539 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4540 virtio_consoles[i] = NULL;
4541 virtio_console_index = 0;
4543 usb_devices_index = 0;
4544 assigned_devices_index = 0;
4546 nb_net_clients = 0;
4547 nb_bt_opts = 0;
4548 nb_drives = 0;
4549 nb_drives_opt = 0;
4550 hda_index = -1;
4552 nb_nics = 0;
4554 tb_size = 0;
4555 autostart= 1;
4557 optind = 1;
4558 for(;;) {
4559 if (optind >= argc)
4560 break;
4561 r = argv[optind];
4562 if (r[0] != '-') {
4563 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4564 } else {
4565 const QEMUOption *popt;
4567 optind++;
4568 /* Treat --foo the same as -foo. */
4569 if (r[1] == '-')
4570 r++;
4571 popt = qemu_options;
4572 for(;;) {
4573 if (!popt->name) {
4574 fprintf(stderr, "%s: invalid option -- '%s'\n",
4575 argv[0], r);
4576 exit(1);
4578 if (!strcmp(popt->name, r + 1))
4579 break;
4580 popt++;
4582 if (popt->flags & HAS_ARG) {
4583 if (optind >= argc) {
4584 fprintf(stderr, "%s: option '%s' requires an argument\n",
4585 argv[0], r);
4586 exit(1);
4588 optarg = argv[optind++];
4589 } else {
4590 optarg = NULL;
4593 switch(popt->index) {
4594 case QEMU_OPTION_M:
4595 machine = find_machine(optarg);
4596 if (!machine) {
4597 QEMUMachine *m;
4598 printf("Supported machines are:\n");
4599 for(m = first_machine; m != NULL; m = m->next) {
4600 printf("%-10s %s%s\n",
4601 m->name, m->desc,
4602 m == first_machine ? " (default)" : "");
4604 exit(*optarg != '?');
4606 break;
4607 case QEMU_OPTION_cpu:
4608 /* hw initialization will check this */
4609 if (*optarg == '?') {
4610 /* XXX: implement xxx_cpu_list for targets that still miss it */
4611 #if defined(cpu_list)
4612 cpu_list(stdout, &fprintf);
4613 #endif
4614 exit(0);
4615 } else {
4616 cpu_model = optarg;
4618 break;
4619 case QEMU_OPTION_initrd:
4620 initrd_filename = optarg;
4621 break;
4622 case QEMU_OPTION_hda:
4623 if (cyls == 0)
4624 hda_index = drive_add(optarg, HD_ALIAS, 0);
4625 else
4626 hda_index = drive_add(optarg, HD_ALIAS
4627 ",cyls=%d,heads=%d,secs=%d%s",
4628 0, cyls, heads, secs,
4629 translation == BIOS_ATA_TRANSLATION_LBA ?
4630 ",trans=lba" :
4631 translation == BIOS_ATA_TRANSLATION_NONE ?
4632 ",trans=none" : "");
4633 break;
4634 case QEMU_OPTION_hdb:
4635 case QEMU_OPTION_hdc:
4636 case QEMU_OPTION_hdd:
4637 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4638 break;
4639 case QEMU_OPTION_drive:
4640 drive_add(NULL, "%s", optarg);
4641 break;
4642 case QEMU_OPTION_mtdblock:
4643 drive_add(optarg, MTD_ALIAS);
4644 break;
4645 case QEMU_OPTION_sd:
4646 drive_add(optarg, SD_ALIAS);
4647 break;
4648 case QEMU_OPTION_pflash:
4649 drive_add(optarg, PFLASH_ALIAS);
4650 break;
4651 case QEMU_OPTION_snapshot:
4652 snapshot = 1;
4653 break;
4654 case QEMU_OPTION_hdachs:
4656 const char *p;
4657 p = optarg;
4658 cyls = strtol(p, (char **)&p, 0);
4659 if (cyls < 1 || cyls > 16383)
4660 goto chs_fail;
4661 if (*p != ',')
4662 goto chs_fail;
4663 p++;
4664 heads = strtol(p, (char **)&p, 0);
4665 if (heads < 1 || heads > 16)
4666 goto chs_fail;
4667 if (*p != ',')
4668 goto chs_fail;
4669 p++;
4670 secs = strtol(p, (char **)&p, 0);
4671 if (secs < 1 || secs > 63)
4672 goto chs_fail;
4673 if (*p == ',') {
4674 p++;
4675 if (!strcmp(p, "none"))
4676 translation = BIOS_ATA_TRANSLATION_NONE;
4677 else if (!strcmp(p, "lba"))
4678 translation = BIOS_ATA_TRANSLATION_LBA;
4679 else if (!strcmp(p, "auto"))
4680 translation = BIOS_ATA_TRANSLATION_AUTO;
4681 else
4682 goto chs_fail;
4683 } else if (*p != '\0') {
4684 chs_fail:
4685 fprintf(stderr, "qemu: invalid physical CHS format\n");
4686 exit(1);
4688 if (hda_index != -1)
4689 snprintf(drives_opt[hda_index].opt,
4690 sizeof(drives_opt[hda_index].opt),
4691 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4692 0, cyls, heads, secs,
4693 translation == BIOS_ATA_TRANSLATION_LBA ?
4694 ",trans=lba" :
4695 translation == BIOS_ATA_TRANSLATION_NONE ?
4696 ",trans=none" : "");
4698 break;
4699 case QEMU_OPTION_nographic:
4700 nographic = 1;
4701 break;
4702 #ifdef CONFIG_CURSES
4703 case QEMU_OPTION_curses:
4704 curses = 1;
4705 break;
4706 #endif
4707 case QEMU_OPTION_portrait:
4708 graphic_rotate = 1;
4709 break;
4710 case QEMU_OPTION_kernel:
4711 kernel_filename = optarg;
4712 break;
4713 case QEMU_OPTION_append:
4714 kernel_cmdline = optarg;
4715 break;
4716 case QEMU_OPTION_cdrom:
4717 drive_add(optarg, CDROM_ALIAS);
4718 break;
4719 case QEMU_OPTION_boot:
4720 boot_devices = optarg;
4721 /* We just do some generic consistency checks */
4723 /* Could easily be extended to 64 devices if needed */
4724 const char *p;
4726 boot_devices_bitmap = 0;
4727 for (p = boot_devices; *p != '\0'; p++) {
4728 /* Allowed boot devices are:
4729 * a b : floppy disk drives
4730 * c ... f : IDE disk drives
4731 * g ... m : machine implementation dependant drives
4732 * n ... p : network devices
4733 * It's up to each machine implementation to check
4734 * if the given boot devices match the actual hardware
4735 * implementation and firmware features.
4737 if (*p < 'a' || *p > 'q') {
4738 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4739 exit(1);
4741 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4742 fprintf(stderr,
4743 "Boot device '%c' was given twice\n",*p);
4744 exit(1);
4746 boot_devices_bitmap |= 1 << (*p - 'a');
4749 break;
4750 case QEMU_OPTION_fda:
4751 case QEMU_OPTION_fdb:
4752 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4753 break;
4754 #ifdef TARGET_I386
4755 case QEMU_OPTION_no_fd_bootchk:
4756 fd_bootchk = 0;
4757 break;
4758 #endif
4759 case QEMU_OPTION_net:
4760 if (nb_net_clients >= MAX_NET_CLIENTS) {
4761 fprintf(stderr, "qemu: too many network clients\n");
4762 exit(1);
4764 net_clients[nb_net_clients] = optarg;
4765 nb_net_clients++;
4766 break;
4767 #ifdef CONFIG_SLIRP
4768 case QEMU_OPTION_tftp:
4769 tftp_prefix = optarg;
4770 break;
4771 case QEMU_OPTION_bootp:
4772 bootp_filename = optarg;
4773 break;
4774 #ifndef _WIN32
4775 case QEMU_OPTION_smb:
4776 net_slirp_smb(optarg);
4777 break;
4778 #endif
4779 case QEMU_OPTION_redir:
4780 net_slirp_redir(optarg);
4781 break;
4782 #endif
4783 case QEMU_OPTION_bt:
4784 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4785 fprintf(stderr, "qemu: too many bluetooth options\n");
4786 exit(1);
4788 bt_opts[nb_bt_opts++] = optarg;
4789 break;
4790 #ifdef HAS_AUDIO
4791 case QEMU_OPTION_audio_help:
4792 AUD_help ();
4793 exit (0);
4794 break;
4795 case QEMU_OPTION_soundhw:
4796 select_soundhw (optarg);
4797 break;
4798 #endif
4799 case QEMU_OPTION_h:
4800 help(0);
4801 break;
4802 case QEMU_OPTION_m: {
4803 uint64_t value;
4804 char *ptr;
4806 value = strtoul(optarg, &ptr, 10);
4807 switch (*ptr) {
4808 case 0: case 'M': case 'm':
4809 value <<= 20;
4810 break;
4811 case 'G': case 'g':
4812 value <<= 30;
4813 break;
4814 default:
4815 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4816 exit(1);
4819 /* On 32-bit hosts, QEMU is limited by virtual address space */
4820 if (value > (2047 << 20)
4821 #ifndef USE_KQEMU
4822 && HOST_LONG_BITS == 32
4823 #endif
4825 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4826 exit(1);
4828 if (value != (uint64_t)(ram_addr_t)value) {
4829 fprintf(stderr, "qemu: ram size too large\n");
4830 exit(1);
4832 ram_size = value;
4833 break;
4835 case QEMU_OPTION_d:
4837 int mask;
4838 const CPULogItem *item;
4840 mask = cpu_str_to_log_mask(optarg);
4841 if (!mask) {
4842 printf("Log items (comma separated):\n");
4843 for(item = cpu_log_items; item->mask != 0; item++) {
4844 printf("%-10s %s\n", item->name, item->help);
4846 exit(1);
4848 cpu_set_log(mask);
4850 break;
4851 #ifdef CONFIG_GDBSTUB
4852 case QEMU_OPTION_s:
4853 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4854 break;
4855 case QEMU_OPTION_gdb:
4856 gdbstub_dev = optarg;
4857 break;
4858 #endif
4859 case QEMU_OPTION_L:
4860 bios_dir = optarg;
4861 break;
4862 case QEMU_OPTION_bios:
4863 bios_name = optarg;
4864 break;
4865 case QEMU_OPTION_singlestep:
4866 singlestep = 1;
4867 break;
4868 case QEMU_OPTION_S:
4869 autostart = 0;
4870 break;
4871 #ifndef _WIN32
4872 case QEMU_OPTION_k:
4873 keyboard_layout = optarg;
4874 break;
4875 #endif
4876 case QEMU_OPTION_localtime:
4877 rtc_utc = 0;
4878 break;
4879 case QEMU_OPTION_vga:
4880 select_vgahw (optarg);
4881 break;
4882 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4883 case QEMU_OPTION_g:
4885 const char *p;
4886 int w, h, depth;
4887 p = optarg;
4888 w = strtol(p, (char **)&p, 10);
4889 if (w <= 0) {
4890 graphic_error:
4891 fprintf(stderr, "qemu: invalid resolution or depth\n");
4892 exit(1);
4894 if (*p != 'x')
4895 goto graphic_error;
4896 p++;
4897 h = strtol(p, (char **)&p, 10);
4898 if (h <= 0)
4899 goto graphic_error;
4900 if (*p == 'x') {
4901 p++;
4902 depth = strtol(p, (char **)&p, 10);
4903 if (depth != 8 && depth != 15 && depth != 16 &&
4904 depth != 24 && depth != 32)
4905 goto graphic_error;
4906 } else if (*p == '\0') {
4907 depth = graphic_depth;
4908 } else {
4909 goto graphic_error;
4912 graphic_width = w;
4913 graphic_height = h;
4914 graphic_depth = depth;
4916 break;
4917 #endif
4918 case QEMU_OPTION_echr:
4920 char *r;
4921 term_escape_char = strtol(optarg, &r, 0);
4922 if (r == optarg)
4923 printf("Bad argument to echr\n");
4924 break;
4926 case QEMU_OPTION_monitor:
4927 monitor_device = optarg;
4928 break;
4929 case QEMU_OPTION_serial:
4930 if (serial_device_index >= MAX_SERIAL_PORTS) {
4931 fprintf(stderr, "qemu: too many serial ports\n");
4932 exit(1);
4934 serial_devices[serial_device_index] = optarg;
4935 serial_device_index++;
4936 break;
4937 case QEMU_OPTION_virtiocon:
4938 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4939 fprintf(stderr, "qemu: too many virtio consoles\n");
4940 exit(1);
4942 virtio_consoles[virtio_console_index] = optarg;
4943 virtio_console_index++;
4944 break;
4945 case QEMU_OPTION_parallel:
4946 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4947 fprintf(stderr, "qemu: too many parallel ports\n");
4948 exit(1);
4950 parallel_devices[parallel_device_index] = optarg;
4951 parallel_device_index++;
4952 break;
4953 case QEMU_OPTION_loadvm:
4954 loadvm = optarg;
4955 break;
4956 case QEMU_OPTION_full_screen:
4957 full_screen = 1;
4958 break;
4959 #ifdef CONFIG_SDL
4960 case QEMU_OPTION_no_frame:
4961 no_frame = 1;
4962 break;
4963 case QEMU_OPTION_alt_grab:
4964 alt_grab = 1;
4965 break;
4966 case QEMU_OPTION_no_quit:
4967 no_quit = 1;
4968 break;
4969 case QEMU_OPTION_sdl:
4970 sdl = 1;
4971 break;
4972 #endif
4973 case QEMU_OPTION_pidfile:
4974 pid_file = optarg;
4975 break;
4976 #ifdef TARGET_I386
4977 case QEMU_OPTION_win2k_hack:
4978 win2k_install_hack = 1;
4979 break;
4980 case QEMU_OPTION_rtc_td_hack:
4981 rtc_td_hack = 1;
4982 break;
4983 case QEMU_OPTION_acpitable:
4984 if(acpi_table_add(optarg) < 0) {
4985 fprintf(stderr, "Wrong acpi table provided\n");
4986 exit(1);
4988 break;
4989 #endif
4990 #ifdef USE_KQEMU
4991 case QEMU_OPTION_no_kqemu:
4992 kqemu_allowed = 0;
4993 break;
4994 case QEMU_OPTION_kernel_kqemu:
4995 kqemu_allowed = 2;
4996 break;
4997 #endif
4998 #ifdef CONFIG_KVM
4999 case QEMU_OPTION_enable_kvm:
5000 kvm_allowed = 1;
5001 #ifdef USE_KQEMU
5002 kqemu_allowed = 0;
5003 #endif
5004 break;
5005 #endif
5006 #ifdef USE_KVM
5007 case QEMU_OPTION_no_kvm:
5008 kvm_allowed = 0;
5009 break;
5010 case QEMU_OPTION_no_kvm_irqchip: {
5011 kvm_irqchip = 0;
5012 kvm_pit = 0;
5013 break;
5015 case QEMU_OPTION_no_kvm_pit: {
5016 kvm_pit = 0;
5017 break;
5019 case QEMU_OPTION_no_kvm_pit_reinjection: {
5020 kvm_pit_reinject = 0;
5021 break;
5023 case QEMU_OPTION_enable_nesting: {
5024 kvm_nested = 1;
5025 break;
5027 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5028 case QEMU_OPTION_pcidevice:
5029 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5030 fprintf(stderr, "Too many assigned devices\n");
5031 exit(1);
5033 assigned_devices[assigned_devices_index] = optarg;
5034 assigned_devices_index++;
5035 break;
5036 #endif
5037 #endif
5038 case QEMU_OPTION_usb:
5039 usb_enabled = 1;
5040 break;
5041 case QEMU_OPTION_usbdevice:
5042 usb_enabled = 1;
5043 if (usb_devices_index >= MAX_USB_CMDLINE) {
5044 fprintf(stderr, "Too many USB devices\n");
5045 exit(1);
5047 usb_devices[usb_devices_index] = optarg;
5048 usb_devices_index++;
5049 break;
5050 case QEMU_OPTION_smp:
5051 smp_cpus = atoi(optarg);
5052 if (smp_cpus < 1) {
5053 fprintf(stderr, "Invalid number of CPUs\n");
5054 exit(1);
5056 break;
5057 case QEMU_OPTION_vnc:
5058 vnc_display = optarg;
5059 break;
5060 #ifdef TARGET_I386
5061 case QEMU_OPTION_no_acpi:
5062 acpi_enabled = 0;
5063 break;
5064 case QEMU_OPTION_no_hpet:
5065 no_hpet = 1;
5066 break;
5067 #endif
5068 case QEMU_OPTION_no_reboot:
5069 no_reboot = 1;
5070 break;
5071 case QEMU_OPTION_no_shutdown:
5072 no_shutdown = 1;
5073 break;
5074 case QEMU_OPTION_show_cursor:
5075 cursor_hide = 0;
5076 break;
5077 case QEMU_OPTION_uuid:
5078 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5079 fprintf(stderr, "Fail to parse UUID string."
5080 " Wrong format.\n");
5081 exit(1);
5083 break;
5084 #ifndef _WIN32
5085 case QEMU_OPTION_daemonize:
5086 daemonize = 1;
5087 break;
5088 #endif
5089 case QEMU_OPTION_option_rom:
5090 if (nb_option_roms >= MAX_OPTION_ROMS) {
5091 fprintf(stderr, "Too many option ROMs\n");
5092 exit(1);
5094 option_rom[nb_option_roms] = optarg;
5095 nb_option_roms++;
5096 break;
5097 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5098 case QEMU_OPTION_semihosting:
5099 semihosting_enabled = 1;
5100 break;
5101 #endif
5102 case QEMU_OPTION_tdf:
5103 time_drift_fix = 1;
5104 break;
5105 case QEMU_OPTION_kvm_shadow_memory:
5106 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5107 break;
5108 case QEMU_OPTION_mempath:
5109 mem_path = optarg;
5110 break;
5111 #ifdef MAP_POPULATE
5112 case QEMU_OPTION_mem_prealloc:
5113 mem_prealloc = !mem_prealloc;
5114 break;
5115 #endif
5116 case QEMU_OPTION_name:
5117 qemu_name = optarg;
5118 break;
5119 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5120 case QEMU_OPTION_prom_env:
5121 if (nb_prom_envs >= MAX_PROM_ENVS) {
5122 fprintf(stderr, "Too many prom variables\n");
5123 exit(1);
5125 prom_envs[nb_prom_envs] = optarg;
5126 nb_prom_envs++;
5127 break;
5128 #endif
5129 case QEMU_OPTION_cpu_vendor:
5130 cpu_vendor_string = optarg;
5131 break;
5132 #ifdef TARGET_ARM
5133 case QEMU_OPTION_old_param:
5134 old_param = 1;
5135 break;
5136 #endif
5137 case QEMU_OPTION_clock:
5138 configure_alarms(optarg);
5139 break;
5140 case QEMU_OPTION_startdate:
5142 struct tm tm;
5143 time_t rtc_start_date;
5144 if (!strcmp(optarg, "now")) {
5145 rtc_date_offset = -1;
5146 } else {
5147 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5148 &tm.tm_year,
5149 &tm.tm_mon,
5150 &tm.tm_mday,
5151 &tm.tm_hour,
5152 &tm.tm_min,
5153 &tm.tm_sec) == 6) {
5154 /* OK */
5155 } else if (sscanf(optarg, "%d-%d-%d",
5156 &tm.tm_year,
5157 &tm.tm_mon,
5158 &tm.tm_mday) == 3) {
5159 tm.tm_hour = 0;
5160 tm.tm_min = 0;
5161 tm.tm_sec = 0;
5162 } else {
5163 goto date_fail;
5165 tm.tm_year -= 1900;
5166 tm.tm_mon--;
5167 rtc_start_date = mktimegm(&tm);
5168 if (rtc_start_date == -1) {
5169 date_fail:
5170 fprintf(stderr, "Invalid date format. Valid format are:\n"
5171 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5172 exit(1);
5174 rtc_date_offset = time(NULL) - rtc_start_date;
5177 break;
5178 case QEMU_OPTION_tb_size:
5179 tb_size = strtol(optarg, NULL, 0);
5180 if (tb_size < 0)
5181 tb_size = 0;
5182 break;
5183 case QEMU_OPTION_icount:
5184 use_icount = 1;
5185 if (strcmp(optarg, "auto") == 0) {
5186 icount_time_shift = -1;
5187 } else {
5188 icount_time_shift = strtol(optarg, NULL, 0);
5190 break;
5191 case QEMU_OPTION_incoming:
5192 incoming = optarg;
5193 saved_incoming = incoming;
5194 break;
5195 #ifndef _WIN32
5196 case QEMU_OPTION_chroot:
5197 chroot_dir = optarg;
5198 break;
5199 case QEMU_OPTION_runas:
5200 run_as = optarg;
5201 break;
5202 case QEMU_OPTION_nvram:
5203 nvram = optarg;
5204 break;
5205 #endif
5210 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5211 if (kvm_allowed && kqemu_allowed) {
5212 fprintf(stderr,
5213 "You can not enable both KVM and kqemu at the same time\n");
5214 exit(1);
5216 #endif
5218 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5219 if (smp_cpus > machine->max_cpus) {
5220 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5221 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5222 machine->max_cpus);
5223 exit(1);
5226 if (nographic) {
5227 if (serial_device_index == 0)
5228 serial_devices[0] = "stdio";
5229 if (parallel_device_index == 0)
5230 parallel_devices[0] = "null";
5231 if (strncmp(monitor_device, "vc", 2) == 0)
5232 monitor_device = "stdio";
5235 #ifndef _WIN32
5236 if (daemonize) {
5237 pid_t pid;
5239 if (pipe(fds) == -1)
5240 exit(1);
5242 pid = fork();
5243 if (pid > 0) {
5244 uint8_t status;
5245 ssize_t len;
5247 close(fds[1]);
5249 again:
5250 len = read(fds[0], &status, 1);
5251 if (len == -1 && (errno == EINTR))
5252 goto again;
5254 if (len != 1)
5255 exit(1);
5256 else if (status == 1) {
5257 fprintf(stderr, "Could not acquire pidfile\n");
5258 exit(1);
5259 } else
5260 exit(0);
5261 } else if (pid < 0)
5262 exit(1);
5264 setsid();
5266 pid = fork();
5267 if (pid > 0)
5268 exit(0);
5269 else if (pid < 0)
5270 exit(1);
5272 umask(027);
5274 signal(SIGTSTP, SIG_IGN);
5275 signal(SIGTTOU, SIG_IGN);
5276 signal(SIGTTIN, SIG_IGN);
5279 #ifdef USE_KVM
5280 if (kvm_enabled()) {
5281 if (kvm_qemu_init() < 0) {
5282 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5283 #ifdef NO_CPU_EMULATION
5284 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5285 exit(1);
5286 #endif
5287 kvm_allowed = 0;
5290 #endif
5292 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5293 if (daemonize) {
5294 uint8_t status = 1;
5295 write(fds[1], &status, 1);
5296 } else
5297 fprintf(stderr, "Could not acquire pid file\n");
5298 exit(1);
5300 #endif
5302 #ifdef USE_KQEMU
5303 if (smp_cpus > 1)
5304 kqemu_allowed = 0;
5305 #endif
5306 linux_boot = (kernel_filename != NULL);
5307 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5309 if (!linux_boot && *kernel_cmdline != '\0') {
5310 fprintf(stderr, "-append only allowed with -kernel option\n");
5311 exit(1);
5314 if (!linux_boot && initrd_filename != NULL) {
5315 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5316 exit(1);
5319 /* boot to floppy or the default cd if no hard disk defined yet */
5320 if (!boot_devices[0]) {
5321 boot_devices = "cad";
5323 setvbuf(stdout, NULL, _IOLBF, 0);
5325 init_timers();
5326 if (init_timer_alarm() < 0) {
5327 fprintf(stderr, "could not initialize alarm timer\n");
5328 exit(1);
5330 if (use_icount && icount_time_shift < 0) {
5331 use_icount = 2;
5332 /* 125MIPS seems a reasonable initial guess at the guest speed.
5333 It will be corrected fairly quickly anyway. */
5334 icount_time_shift = 3;
5335 init_icount_adjust();
5338 #ifdef _WIN32
5339 socket_init();
5340 #endif
5342 /* init network clients */
5343 if (nb_net_clients == 0) {
5344 /* if no clients, we use a default config */
5345 net_clients[nb_net_clients++] = "nic";
5346 #ifdef CONFIG_SLIRP
5347 net_clients[nb_net_clients++] = "user";
5348 #endif
5351 for(i = 0;i < nb_net_clients; i++) {
5352 if (net_client_parse(net_clients[i]) < 0)
5353 exit(1);
5355 net_client_check();
5357 #ifdef TARGET_I386
5358 /* XXX: this should be moved in the PC machine instantiation code */
5359 if (net_boot != 0) {
5360 int netroms = 0;
5361 for (i = 0; i < nb_nics && i < 4; i++) {
5362 const char *model = nd_table[i].model;
5363 char buf[1024];
5364 if (net_boot & (1 << i)) {
5365 if (model == NULL)
5366 model = "rtl8139";
5367 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5368 if (get_image_size(buf) > 0) {
5369 if (nb_option_roms >= MAX_OPTION_ROMS) {
5370 fprintf(stderr, "Too many option ROMs\n");
5371 exit(1);
5373 option_rom[nb_option_roms] = strdup(buf);
5374 nb_option_roms++;
5375 netroms++;
5379 if (netroms == 0) {
5380 fprintf(stderr, "No valid PXE rom found for network device\n");
5381 exit(1);
5384 #endif
5386 /* init the bluetooth world */
5387 for (i = 0; i < nb_bt_opts; i++)
5388 if (bt_parse(bt_opts[i]))
5389 exit(1);
5391 /* init the memory */
5392 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5394 if (machine->ram_require & RAMSIZE_FIXED) {
5395 if (ram_size > 0) {
5396 if (ram_size < phys_ram_size) {
5397 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5398 machine->name, (unsigned long long) phys_ram_size);
5399 exit(-1);
5402 phys_ram_size = ram_size;
5403 } else
5404 ram_size = phys_ram_size;
5405 } else {
5406 if (ram_size == 0)
5407 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5409 phys_ram_size += ram_size;
5412 /* Initialize kvm */
5413 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5414 #define KVM_EXTRA_PAGES 3
5415 #else
5416 #define KVM_EXTRA_PAGES 0
5417 #endif
5418 if (kvm_enabled()) {
5419 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5420 if (kvm_qemu_create_context() < 0) {
5421 fprintf(stderr, "Could not create KVM context\n");
5422 exit(1);
5426 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5427 if (!phys_ram_base) {
5428 fprintf(stderr, "Could not allocate physical memory\n");
5429 exit(1);
5432 /* init the dynamic translator */
5433 cpu_exec_init_all(tb_size * 1024 * 1024);
5435 bdrv_init();
5436 dma_helper_init();
5438 /* we always create the cdrom drive, even if no disk is there */
5440 if (nb_drives_opt < MAX_DRIVES)
5441 drive_add(NULL, CDROM_ALIAS);
5443 /* we always create at least one floppy */
5445 if (nb_drives_opt < MAX_DRIVES)
5446 drive_add(NULL, FD_ALIAS, 0);
5448 /* we always create one sd slot, even if no card is in it */
5450 if (nb_drives_opt < MAX_DRIVES)
5451 drive_add(NULL, SD_ALIAS);
5453 /* open the virtual block devices
5454 * note that migration with device
5455 * hot add/remove is broken.
5457 for(i = 0; i < nb_drives_opt; i++)
5458 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5459 exit(1);
5461 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5462 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5464 #ifndef _WIN32
5465 /* must be after terminal init, SDL library changes signal handlers */
5466 termsig_setup();
5467 #endif
5469 /* Maintain compatibility with multiple stdio monitors */
5470 if (!strcmp(monitor_device,"stdio")) {
5471 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5472 const char *devname = serial_devices[i];
5473 if (devname && !strcmp(devname,"mon:stdio")) {
5474 monitor_device = NULL;
5475 break;
5476 } else if (devname && !strcmp(devname,"stdio")) {
5477 monitor_device = NULL;
5478 serial_devices[i] = "mon:stdio";
5479 break;
5484 #ifdef KVM_UPSTREAM
5485 if (kvm_enabled()) {
5486 int ret;
5488 ret = kvm_init(smp_cpus);
5489 if (ret < 0) {
5490 fprintf(stderr, "failed to initialize KVM\n");
5491 exit(1);
5494 #endif
5496 if (monitor_device) {
5497 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5498 if (!monitor_hd) {
5499 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5500 exit(1);
5504 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5505 const char *devname = serial_devices[i];
5506 if (devname && strcmp(devname, "none")) {
5507 char label[32];
5508 snprintf(label, sizeof(label), "serial%d", i);
5509 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5510 if (!serial_hds[i]) {
5511 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5512 devname);
5513 exit(1);
5518 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5519 const char *devname = parallel_devices[i];
5520 if (devname && strcmp(devname, "none")) {
5521 char label[32];
5522 snprintf(label, sizeof(label), "parallel%d", i);
5523 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5524 if (!parallel_hds[i]) {
5525 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5526 devname);
5527 exit(1);
5532 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5533 const char *devname = virtio_consoles[i];
5534 if (devname && strcmp(devname, "none")) {
5535 char label[32];
5536 snprintf(label, sizeof(label), "virtcon%d", i);
5537 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5538 if (!virtcon_hds[i]) {
5539 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5540 devname);
5541 exit(1);
5546 if (kvm_enabled())
5547 kvm_init_ap();
5549 machine->init(ram_size, vga_ram_size, boot_devices,
5550 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5552 current_machine = machine;
5554 /* Set KVM's vcpu state to qemu's initial CPUState. */
5555 if (kvm_enabled()) {
5556 int ret;
5558 ret = kvm_sync_vcpus();
5559 if (ret < 0) {
5560 fprintf(stderr, "failed to initialize vcpus\n");
5561 exit(1);
5565 /* init USB devices */
5566 if (usb_enabled) {
5567 for(i = 0; i < usb_devices_index; i++) {
5568 if (usb_device_add(usb_devices[i], 0) < 0) {
5569 fprintf(stderr, "Warning: could not add USB device %s\n",
5570 usb_devices[i]);
5575 if (!display_state)
5576 dumb_display_init();
5577 /* just use the first displaystate for the moment */
5578 ds = display_state;
5579 /* terminal init */
5580 if (nographic) {
5581 if (curses) {
5582 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5583 exit(1);
5585 } else {
5586 #if defined(CONFIG_CURSES)
5587 if (curses) {
5588 /* At the moment curses cannot be used with other displays */
5589 curses_display_init(ds, full_screen);
5590 } else
5591 #endif
5593 if (vnc_display != NULL) {
5594 vnc_display_init(ds);
5595 if (vnc_display_open(ds, vnc_display) < 0)
5596 exit(1);
5598 #if defined(CONFIG_SDL)
5599 if (sdl || !vnc_display)
5600 sdl_display_init(ds, full_screen, no_frame);
5601 #elif defined(CONFIG_COCOA)
5602 if (sdl || !vnc_display)
5603 cocoa_display_init(ds, full_screen);
5604 #endif
5607 dpy_resize(ds);
5609 dcl = ds->listeners;
5610 while (dcl != NULL) {
5611 if (dcl->dpy_refresh != NULL) {
5612 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5613 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5615 dcl = dcl->next;
5618 if (nographic || (vnc_display && !sdl)) {
5619 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5620 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5623 text_consoles_set_display(display_state);
5624 qemu_chr_initial_reset();
5626 if (monitor_device && monitor_hd)
5627 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5629 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5630 const char *devname = serial_devices[i];
5631 if (devname && strcmp(devname, "none")) {
5632 char label[32];
5633 snprintf(label, sizeof(label), "serial%d", i);
5634 if (strstart(devname, "vc", 0))
5635 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5639 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5640 const char *devname = parallel_devices[i];
5641 if (devname && strcmp(devname, "none")) {
5642 char label[32];
5643 snprintf(label, sizeof(label), "parallel%d", i);
5644 if (strstart(devname, "vc", 0))
5645 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5649 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5650 const char *devname = virtio_consoles[i];
5651 if (virtcon_hds[i] && devname) {
5652 char label[32];
5653 snprintf(label, sizeof(label), "virtcon%d", i);
5654 if (strstart(devname, "vc", 0))
5655 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5659 #ifdef CONFIG_GDBSTUB
5660 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5661 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5662 gdbstub_dev);
5663 exit(1);
5665 #endif
5667 if (loadvm)
5668 do_loadvm(cur_mon, loadvm);
5670 if (incoming) {
5671 autostart = 0; /* fixme how to deal with -daemonize */
5672 qemu_start_incoming_migration(incoming);
5675 if (autostart)
5676 vm_start();
5678 #ifndef _WIN32
5679 if (daemonize) {
5680 uint8_t status = 0;
5681 ssize_t len;
5683 again1:
5684 len = write(fds[1], &status, 1);
5685 if (len == -1 && (errno == EINTR))
5686 goto again1;
5688 if (len != 1)
5689 exit(1);
5691 chdir("/");
5692 TFR(fd = open("/dev/null", O_RDWR));
5693 if (fd == -1)
5694 exit(1);
5697 if (run_as) {
5698 pwd = getpwnam(run_as);
5699 if (!pwd) {
5700 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5701 exit(1);
5705 if (chroot_dir) {
5706 if (chroot(chroot_dir) < 0) {
5707 fprintf(stderr, "chroot failed\n");
5708 exit(1);
5710 chdir("/");
5713 if (run_as) {
5714 if (setgid(pwd->pw_gid) < 0) {
5715 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5716 exit(1);
5718 if (setuid(pwd->pw_uid) < 0) {
5719 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5720 exit(1);
5722 if (setuid(0) != -1) {
5723 fprintf(stderr, "Dropping privileges failed\n");
5724 exit(1);
5728 if (daemonize) {
5729 dup2(fd, 0);
5730 dup2(fd, 1);
5731 dup2(fd, 2);
5733 close(fd);
5735 #endif
5737 main_loop();
5738 quit_timers();
5739 net_cleanup();
5741 return 0;