Remove host_alarm_timer hacks
[qemu-kvm/fedora.git] / vl.c
blob3d6ebd9a55d8582c665eba449e1364d5ade26396
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
35 #ifndef _WIN32
36 #include <pwd.h>
37 #include <sys/times.h>
38 #include <sys/wait.h>
39 #include <termios.h>
40 #include <sys/mman.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <sys/vfs.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef HOST_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
75 #include "hpet.h"
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
98 #if defined(__OpenBSD__)
99 #include <util.h>
100 #endif
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
104 #endif
106 #ifdef _WIN32
107 #include <windows.h>
108 #include <malloc.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
113 #endif
115 #ifdef CONFIG_SDL
116 #ifdef __APPLE__
117 #include <SDL/SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/smbios.h"
143 #include "hw/xen.h"
144 #include "bt-host.h"
145 #include "net.h"
146 #include "monitor.h"
147 #include "console.h"
148 #include "sysemu.h"
149 #include "gdbstub.h"
150 #include "qemu-timer.h"
151 #include "qemu-char.h"
152 #include "cache-utils.h"
153 #include "block.h"
154 #include "dma.h"
155 #include "audio/audio.h"
156 #include "migration.h"
157 #include "kvm.h"
158 #include "balloon.h"
159 #include "qemu-kvm.h"
160 #include "hw/device-assignment.h"
162 #include "disas.h"
164 #include "exec-all.h"
166 #include "qemu_socket.h"
168 #if defined(CONFIG_SLIRP)
169 #include "libslirp.h"
170 #endif
172 //#define DEBUG_UNUSED_IOPORT
173 //#define DEBUG_IOPORT
174 //#define DEBUG_NET
175 //#define DEBUG_SLIRP
178 #ifdef DEBUG_IOPORT
179 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
180 #else
181 # define LOG_IOPORT(...) do { } while (0)
182 #endif
184 #define DEFAULT_RAM_SIZE 128
186 /* Max number of USB devices that can be specified on the commandline. */
187 #define MAX_USB_CMDLINE 8
189 /* Max number of bluetooth switches on the commandline. */
190 #define MAX_BT_CMDLINE 10
192 /* XXX: use a two level table to limit memory usage */
193 #define MAX_IOPORTS 65536
195 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
196 const char *bios_name = NULL;
197 static void *ioport_opaque[MAX_IOPORTS];
198 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
199 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
200 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
201 to store the VM snapshots */
202 DriveInfo drives_table[MAX_DRIVES+1];
203 int nb_drives;
204 int extboot_drive = -1;
205 static int vga_ram_size;
206 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
207 static DisplayState *display_state;
208 int nographic;
209 static int curses;
210 static int sdl;
211 const char* keyboard_layout = NULL;
212 int64_t ticks_per_sec;
213 ram_addr_t ram_size;
214 int nb_nics;
215 NICInfo nd_table[MAX_NICS];
216 int vm_running;
217 static int autostart;
218 static int rtc_utc = 1;
219 static int rtc_date_offset = -1; /* -1 means no change */
220 int cirrus_vga_enabled = 1;
221 int std_vga_enabled = 0;
222 int vmsvga_enabled = 0;
223 int xenfb_enabled = 0;
224 #ifdef TARGET_SPARC
225 int graphic_width = 1024;
226 int graphic_height = 768;
227 int graphic_depth = 8;
228 #else
229 int graphic_width = 800;
230 int graphic_height = 600;
231 int graphic_depth = 15;
232 #endif
233 static int full_screen = 0;
234 #ifdef CONFIG_SDL
235 static int no_frame = 0;
236 #endif
237 int no_quit = 0;
238 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
239 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
240 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
241 #ifdef TARGET_I386
242 int win2k_install_hack = 0;
243 int rtc_td_hack = 0;
244 #endif
245 int usb_enabled = 0;
246 int singlestep = 0;
247 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
248 int assigned_devices_index;
249 int smp_cpus = 1;
250 const char *vnc_display;
251 int acpi_enabled = 1;
252 int no_hpet = 0;
253 int fd_bootchk = 1;
254 int no_reboot = 0;
255 int no_shutdown = 0;
256 int cursor_hide = 1;
257 int graphic_rotate = 0;
258 #ifndef _WIN32
259 int daemonize = 0;
260 #endif
261 const char *option_rom[MAX_OPTION_ROMS];
262 int nb_option_roms;
263 int semihosting_enabled = 0;
264 int time_drift_fix = 0;
265 unsigned int kvm_shadow_memory = 0;
266 const char *mem_path = NULL;
267 #ifdef MAP_POPULATE
268 int mem_prealloc = 1; /* force preallocation of physical target memory */
269 #endif
270 long hpagesize = 0;
271 #ifdef TARGET_ARM
272 int old_param = 0;
273 #endif
274 const char *qemu_name;
275 int alt_grab = 0;
276 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
277 unsigned int nb_prom_envs = 0;
278 const char *prom_envs[MAX_PROM_ENVS];
279 #endif
280 int nb_drives_opt;
281 const char *nvram = NULL;
282 struct drive_opt drives_opt[MAX_DRIVES];
284 int nb_numa_nodes;
285 uint64_t node_mem[MAX_NODES];
286 uint64_t node_cpumask[MAX_NODES];
288 static CPUState *cur_cpu;
289 static CPUState *next_cpu;
290 static int event_pending = 1;
291 /* Conversion factor from emulated instructions to virtual clock ticks. */
292 static int icount_time_shift;
293 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
294 #define MAX_ICOUNT_SHIFT 10
295 /* Compensate for varying guest execution speed. */
296 static int64_t qemu_icount_bias;
297 static QEMUTimer *icount_rt_timer;
298 static QEMUTimer *icount_vm_timer;
299 static QEMUTimer *nographic_timer;
301 uint8_t qemu_uuid[16];
303 /* KVM runs the main loop in a separate thread. If we update one of the lists
304 * that are polled before or after select(), we need to make sure to break out
305 * of the select() to ensure the new item is serviced.
307 static void main_loop_break(void)
309 if (kvm_enabled())
310 qemu_kvm_notify_work();
313 /***********************************************************/
314 /* x86 ISA bus support */
316 target_phys_addr_t isa_mem_base = 0;
317 PicState2 *isa_pic;
319 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
320 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
322 static uint32_t ioport_read(int index, uint32_t address)
324 static IOPortReadFunc *default_func[3] = {
325 default_ioport_readb,
326 default_ioport_readw,
327 default_ioport_readl
329 IOPortReadFunc *func = ioport_read_table[index][address];
330 if (!func)
331 func = default_func[index];
332 return func(ioport_opaque[address], address);
335 static void ioport_write(int index, uint32_t address, uint32_t data)
337 static IOPortWriteFunc *default_func[3] = {
338 default_ioport_writeb,
339 default_ioport_writew,
340 default_ioport_writel
342 IOPortWriteFunc *func = ioport_write_table[index][address];
343 if (!func)
344 func = default_func[index];
345 func(ioport_opaque[address], address, data);
348 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
350 #ifdef DEBUG_UNUSED_IOPORT
351 fprintf(stderr, "unused inb: port=0x%04x\n", address);
352 #endif
353 return 0xff;
356 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
358 #ifdef DEBUG_UNUSED_IOPORT
359 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
360 #endif
363 /* default is to make two byte accesses */
364 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
366 uint32_t data;
367 data = ioport_read(0, address);
368 address = (address + 1) & (MAX_IOPORTS - 1);
369 data |= ioport_read(0, address) << 8;
370 return data;
373 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
375 ioport_write(0, address, data & 0xff);
376 address = (address + 1) & (MAX_IOPORTS - 1);
377 ioport_write(0, address, (data >> 8) & 0xff);
380 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
382 #ifdef DEBUG_UNUSED_IOPORT
383 fprintf(stderr, "unused inl: port=0x%04x\n", address);
384 #endif
385 return 0xffffffff;
388 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
390 #ifdef DEBUG_UNUSED_IOPORT
391 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
392 #endif
395 /* size is the word size in byte */
396 int register_ioport_read(int start, int length, int size,
397 IOPortReadFunc *func, void *opaque)
399 int i, bsize;
401 if (size == 1) {
402 bsize = 0;
403 } else if (size == 2) {
404 bsize = 1;
405 } else if (size == 4) {
406 bsize = 2;
407 } else {
408 hw_error("register_ioport_read: invalid size");
409 return -1;
411 for(i = start; i < start + length; i += size) {
412 ioport_read_table[bsize][i] = func;
413 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
414 hw_error("register_ioport_read: invalid opaque");
415 ioport_opaque[i] = opaque;
417 return 0;
420 /* size is the word size in byte */
421 int register_ioport_write(int start, int length, int size,
422 IOPortWriteFunc *func, void *opaque)
424 int i, bsize;
426 if (size == 1) {
427 bsize = 0;
428 } else if (size == 2) {
429 bsize = 1;
430 } else if (size == 4) {
431 bsize = 2;
432 } else {
433 hw_error("register_ioport_write: invalid size");
434 return -1;
436 for(i = start; i < start + length; i += size) {
437 ioport_write_table[bsize][i] = func;
438 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
439 hw_error("register_ioport_write: invalid opaque");
440 ioport_opaque[i] = opaque;
442 return 0;
445 void isa_unassign_ioport(int start, int length)
447 int i;
449 for(i = start; i < start + length; i++) {
450 ioport_read_table[0][i] = default_ioport_readb;
451 ioport_read_table[1][i] = default_ioport_readw;
452 ioport_read_table[2][i] = default_ioport_readl;
454 ioport_write_table[0][i] = default_ioport_writeb;
455 ioport_write_table[1][i] = default_ioport_writew;
456 ioport_write_table[2][i] = default_ioport_writel;
458 ioport_opaque[i] = NULL;
462 /***********************************************************/
464 void cpu_outb(CPUState *env, int addr, int val)
466 LOG_IOPORT("outb: %04x %02x\n", addr, val);
467 ioport_write(0, addr, val);
468 #ifdef CONFIG_KQEMU
469 if (env)
470 env->last_io_time = cpu_get_time_fast();
471 #endif
474 void cpu_outw(CPUState *env, int addr, int val)
476 LOG_IOPORT("outw: %04x %04x\n", addr, val);
477 ioport_write(1, addr, val);
478 #ifdef CONFIG_KQEMU
479 if (env)
480 env->last_io_time = cpu_get_time_fast();
481 #endif
484 void cpu_outl(CPUState *env, int addr, int val)
486 LOG_IOPORT("outl: %04x %08x\n", addr, val);
487 ioport_write(2, addr, val);
488 #ifdef CONFIG_KQEMU
489 if (env)
490 env->last_io_time = cpu_get_time_fast();
491 #endif
494 int cpu_inb(CPUState *env, int addr)
496 int val;
497 val = ioport_read(0, addr);
498 LOG_IOPORT("inb : %04x %02x\n", addr, val);
499 #ifdef CONFIG_KQEMU
500 if (env)
501 env->last_io_time = cpu_get_time_fast();
502 #endif
503 return val;
506 int cpu_inw(CPUState *env, int addr)
508 int val;
509 val = ioport_read(1, addr);
510 LOG_IOPORT("inw : %04x %04x\n", addr, val);
511 #ifdef CONFIG_KQEMU
512 if (env)
513 env->last_io_time = cpu_get_time_fast();
514 #endif
515 return val;
518 int cpu_inl(CPUState *env, int addr)
520 int val;
521 val = ioport_read(2, addr);
522 LOG_IOPORT("inl : %04x %08x\n", addr, val);
523 #ifdef CONFIG_KQEMU
524 if (env)
525 env->last_io_time = cpu_get_time_fast();
526 #endif
527 return val;
530 /***********************************************************/
531 void hw_error(const char *fmt, ...)
533 va_list ap;
534 CPUState *env;
536 va_start(ap, fmt);
537 fprintf(stderr, "qemu: hardware error: ");
538 vfprintf(stderr, fmt, ap);
539 fprintf(stderr, "\n");
540 for(env = first_cpu; env != NULL; env = env->next_cpu) {
541 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
542 #ifdef TARGET_I386
543 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
544 #else
545 cpu_dump_state(env, stderr, fprintf, 0);
546 #endif
548 va_end(ap);
549 abort();
552 /***************/
553 /* ballooning */
555 static QEMUBalloonEvent *qemu_balloon_event;
556 void *qemu_balloon_event_opaque;
558 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
560 qemu_balloon_event = func;
561 qemu_balloon_event_opaque = opaque;
564 void qemu_balloon(ram_addr_t target)
566 if (qemu_balloon_event)
567 qemu_balloon_event(qemu_balloon_event_opaque, target);
570 ram_addr_t qemu_balloon_status(void)
572 if (qemu_balloon_event)
573 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
574 return 0;
577 /***********************************************************/
578 /* keyboard/mouse */
580 static QEMUPutKBDEvent *qemu_put_kbd_event;
581 static void *qemu_put_kbd_event_opaque;
582 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
583 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
585 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
587 qemu_put_kbd_event_opaque = opaque;
588 qemu_put_kbd_event = func;
591 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
592 void *opaque, int absolute,
593 const char *name)
595 QEMUPutMouseEntry *s, *cursor;
597 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
599 s->qemu_put_mouse_event = func;
600 s->qemu_put_mouse_event_opaque = opaque;
601 s->qemu_put_mouse_event_absolute = absolute;
602 s->qemu_put_mouse_event_name = qemu_strdup(name);
603 s->next = NULL;
605 if (!qemu_put_mouse_event_head) {
606 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
607 return s;
610 cursor = qemu_put_mouse_event_head;
611 while (cursor->next != NULL)
612 cursor = cursor->next;
614 cursor->next = s;
615 qemu_put_mouse_event_current = s;
617 return s;
620 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
622 QEMUPutMouseEntry *prev = NULL, *cursor;
624 if (!qemu_put_mouse_event_head || entry == NULL)
625 return;
627 cursor = qemu_put_mouse_event_head;
628 while (cursor != NULL && cursor != entry) {
629 prev = cursor;
630 cursor = cursor->next;
633 if (cursor == NULL) // does not exist or list empty
634 return;
635 else if (prev == NULL) { // entry is head
636 qemu_put_mouse_event_head = cursor->next;
637 if (qemu_put_mouse_event_current == entry)
638 qemu_put_mouse_event_current = cursor->next;
639 qemu_free(entry->qemu_put_mouse_event_name);
640 qemu_free(entry);
641 return;
644 prev->next = entry->next;
646 if (qemu_put_mouse_event_current == entry)
647 qemu_put_mouse_event_current = prev;
649 qemu_free(entry->qemu_put_mouse_event_name);
650 qemu_free(entry);
653 void kbd_put_keycode(int keycode)
655 if (qemu_put_kbd_event) {
656 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
660 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
662 QEMUPutMouseEvent *mouse_event;
663 void *mouse_event_opaque;
664 int width;
666 if (!qemu_put_mouse_event_current) {
667 return;
670 mouse_event =
671 qemu_put_mouse_event_current->qemu_put_mouse_event;
672 mouse_event_opaque =
673 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
675 if (mouse_event) {
676 if (graphic_rotate) {
677 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
678 width = 0x7fff;
679 else
680 width = graphic_width - 1;
681 mouse_event(mouse_event_opaque,
682 width - dy, dx, dz, buttons_state);
683 } else
684 mouse_event(mouse_event_opaque,
685 dx, dy, dz, buttons_state);
689 int kbd_mouse_is_absolute(void)
691 if (!qemu_put_mouse_event_current)
692 return 0;
694 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
697 void do_info_mice(Monitor *mon)
699 QEMUPutMouseEntry *cursor;
700 int index = 0;
702 if (!qemu_put_mouse_event_head) {
703 monitor_printf(mon, "No mouse devices connected\n");
704 return;
707 monitor_printf(mon, "Mouse devices available:\n");
708 cursor = qemu_put_mouse_event_head;
709 while (cursor != NULL) {
710 monitor_printf(mon, "%c Mouse #%d: %s\n",
711 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
712 index, cursor->qemu_put_mouse_event_name);
713 index++;
714 cursor = cursor->next;
718 void do_mouse_set(Monitor *mon, int index)
720 QEMUPutMouseEntry *cursor;
721 int i = 0;
723 if (!qemu_put_mouse_event_head) {
724 monitor_printf(mon, "No mouse devices connected\n");
725 return;
728 cursor = qemu_put_mouse_event_head;
729 while (cursor != NULL && index != i) {
730 i++;
731 cursor = cursor->next;
734 if (cursor != NULL)
735 qemu_put_mouse_event_current = cursor;
736 else
737 monitor_printf(mon, "Mouse at given index not found\n");
740 /* compute with 96 bit intermediate result: (a*b)/c */
741 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
743 union {
744 uint64_t ll;
745 struct {
746 #ifdef WORDS_BIGENDIAN
747 uint32_t high, low;
748 #else
749 uint32_t low, high;
750 #endif
751 } l;
752 } u, res;
753 uint64_t rl, rh;
755 u.ll = a;
756 rl = (uint64_t)u.l.low * (uint64_t)b;
757 rh = (uint64_t)u.l.high * (uint64_t)b;
758 rh += (rl >> 32);
759 res.l.high = rh / c;
760 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
761 return res.ll;
764 /***********************************************************/
765 /* real time host monotonic timer */
767 #define QEMU_TIMER_BASE 1000000000LL
769 #ifdef WIN32
771 static int64_t clock_freq;
773 static void init_get_clock(void)
775 LARGE_INTEGER freq;
776 int ret;
777 ret = QueryPerformanceFrequency(&freq);
778 if (ret == 0) {
779 fprintf(stderr, "Could not calibrate ticks\n");
780 exit(1);
782 clock_freq = freq.QuadPart;
785 static int64_t get_clock(void)
787 LARGE_INTEGER ti;
788 QueryPerformanceCounter(&ti);
789 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
792 #else
794 static int use_rt_clock;
796 static void init_get_clock(void)
798 use_rt_clock = 0;
799 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
800 || defined(__DragonFly__)
802 struct timespec ts;
803 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
804 use_rt_clock = 1;
807 #endif
810 static int64_t get_clock(void)
812 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
813 || defined(__DragonFly__)
814 if (use_rt_clock) {
815 struct timespec ts;
816 clock_gettime(CLOCK_MONOTONIC, &ts);
817 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
818 } else
819 #endif
821 /* XXX: using gettimeofday leads to problems if the date
822 changes, so it should be avoided. */
823 struct timeval tv;
824 gettimeofday(&tv, NULL);
825 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
828 #endif
830 /* Return the virtual CPU time, based on the instruction counter. */
831 static int64_t cpu_get_icount(void)
833 int64_t icount;
834 CPUState *env = cpu_single_env;;
835 icount = qemu_icount;
836 if (env) {
837 if (!can_do_io(env))
838 fprintf(stderr, "Bad clock read\n");
839 icount -= (env->icount_decr.u16.low + env->icount_extra);
841 return qemu_icount_bias + (icount << icount_time_shift);
844 /***********************************************************/
845 /* guest cycle counter */
847 static int64_t cpu_ticks_prev;
848 static int64_t cpu_ticks_offset;
849 static int64_t cpu_clock_offset;
850 static int cpu_ticks_enabled;
852 /* return the host CPU cycle counter and handle stop/restart */
853 int64_t cpu_get_ticks(void)
855 if (use_icount) {
856 return cpu_get_icount();
858 if (!cpu_ticks_enabled) {
859 return cpu_ticks_offset;
860 } else {
861 int64_t ticks;
862 ticks = cpu_get_real_ticks();
863 if (cpu_ticks_prev > ticks) {
864 /* Note: non increasing ticks may happen if the host uses
865 software suspend */
866 cpu_ticks_offset += cpu_ticks_prev - ticks;
868 cpu_ticks_prev = ticks;
869 return ticks + cpu_ticks_offset;
873 /* return the host CPU monotonic timer and handle stop/restart */
874 static int64_t cpu_get_clock(void)
876 int64_t ti;
877 if (!cpu_ticks_enabled) {
878 return cpu_clock_offset;
879 } else {
880 ti = get_clock();
881 return ti + cpu_clock_offset;
885 /* enable cpu_get_ticks() */
886 void cpu_enable_ticks(void)
888 if (!cpu_ticks_enabled) {
889 cpu_ticks_offset -= cpu_get_real_ticks();
890 cpu_clock_offset -= get_clock();
891 cpu_ticks_enabled = 1;
895 /* disable cpu_get_ticks() : the clock is stopped. You must not call
896 cpu_get_ticks() after that. */
897 void cpu_disable_ticks(void)
899 if (cpu_ticks_enabled) {
900 cpu_ticks_offset = cpu_get_ticks();
901 cpu_clock_offset = cpu_get_clock();
902 cpu_ticks_enabled = 0;
906 /***********************************************************/
907 /* timers */
909 #define QEMU_TIMER_REALTIME 0
910 #define QEMU_TIMER_VIRTUAL 1
912 struct QEMUClock {
913 int type;
914 /* XXX: add frequency */
917 struct QEMUTimer {
918 QEMUClock *clock;
919 int64_t expire_time;
920 QEMUTimerCB *cb;
921 void *opaque;
922 struct QEMUTimer *next;
925 struct qemu_alarm_timer {
926 char const *name;
927 unsigned int flags;
929 int (*start)(struct qemu_alarm_timer *t);
930 void (*stop)(struct qemu_alarm_timer *t);
931 void (*rearm)(struct qemu_alarm_timer *t);
932 void *priv;
935 #define ALARM_FLAG_DYNTICKS 0x1
936 #define ALARM_FLAG_EXPIRED 0x2
938 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
940 return t->flags & ALARM_FLAG_DYNTICKS;
943 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
945 if (!alarm_has_dynticks(t))
946 return;
948 t->rearm(t);
951 /* TODO: MIN_TIMER_REARM_US should be optimized */
952 #define MIN_TIMER_REARM_US 250
954 static struct qemu_alarm_timer *alarm_timer;
955 #ifndef _WIN32
956 static int alarm_timer_rfd, alarm_timer_wfd;
957 #endif
959 #ifdef _WIN32
961 struct qemu_alarm_win32 {
962 MMRESULT timerId;
963 HANDLE host_alarm;
964 unsigned int period;
965 } alarm_win32_data = {0, NULL, -1};
967 static int win32_start_timer(struct qemu_alarm_timer *t);
968 static void win32_stop_timer(struct qemu_alarm_timer *t);
969 static void win32_rearm_timer(struct qemu_alarm_timer *t);
971 #else
973 static int unix_start_timer(struct qemu_alarm_timer *t);
974 static void unix_stop_timer(struct qemu_alarm_timer *t);
976 #ifdef __linux__
978 static int dynticks_start_timer(struct qemu_alarm_timer *t);
979 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
980 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
982 static int hpet_start_timer(struct qemu_alarm_timer *t);
983 static void hpet_stop_timer(struct qemu_alarm_timer *t);
985 static int rtc_start_timer(struct qemu_alarm_timer *t);
986 static void rtc_stop_timer(struct qemu_alarm_timer *t);
988 #endif /* __linux__ */
990 #endif /* _WIN32 */
992 /* Correlation between real and virtual time is always going to be
993 fairly approximate, so ignore small variation.
994 When the guest is idle real and virtual time will be aligned in
995 the IO wait loop. */
996 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
998 static void icount_adjust(void)
1000 int64_t cur_time;
1001 int64_t cur_icount;
1002 int64_t delta;
1003 static int64_t last_delta;
1004 /* If the VM is not running, then do nothing. */
1005 if (!vm_running)
1006 return;
1008 cur_time = cpu_get_clock();
1009 cur_icount = qemu_get_clock(vm_clock);
1010 delta = cur_icount - cur_time;
1011 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1012 if (delta > 0
1013 && last_delta + ICOUNT_WOBBLE < delta * 2
1014 && icount_time_shift > 0) {
1015 /* The guest is getting too far ahead. Slow time down. */
1016 icount_time_shift--;
1018 if (delta < 0
1019 && last_delta - ICOUNT_WOBBLE > delta * 2
1020 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1021 /* The guest is getting too far behind. Speed time up. */
1022 icount_time_shift++;
1024 last_delta = delta;
1025 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1028 static void icount_adjust_rt(void * opaque)
1030 qemu_mod_timer(icount_rt_timer,
1031 qemu_get_clock(rt_clock) + 1000);
1032 icount_adjust();
1035 static void icount_adjust_vm(void * opaque)
1037 qemu_mod_timer(icount_vm_timer,
1038 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1039 icount_adjust();
1042 static void init_icount_adjust(void)
1044 /* Have both realtime and virtual time triggers for speed adjustment.
1045 The realtime trigger catches emulated time passing too slowly,
1046 the virtual time trigger catches emulated time passing too fast.
1047 Realtime triggers occur even when idle, so use them less frequently
1048 than VM triggers. */
1049 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1050 qemu_mod_timer(icount_rt_timer,
1051 qemu_get_clock(rt_clock) + 1000);
1052 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1053 qemu_mod_timer(icount_vm_timer,
1054 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1057 static struct qemu_alarm_timer alarm_timers[] = {
1058 #ifndef _WIN32
1059 #ifdef __linux__
1060 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1061 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1062 /* HPET - if available - is preferred */
1063 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1064 /* ...otherwise try RTC */
1065 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1066 #endif
1067 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1068 #else
1069 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1070 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1071 {"win32", 0, win32_start_timer,
1072 win32_stop_timer, NULL, &alarm_win32_data},
1073 #endif
1074 {NULL, }
1077 static void show_available_alarms(void)
1079 int i;
1081 printf("Available alarm timers, in order of precedence:\n");
1082 for (i = 0; alarm_timers[i].name; i++)
1083 printf("%s\n", alarm_timers[i].name);
1086 static void configure_alarms(char const *opt)
1088 int i;
1089 int cur = 0;
1090 int count = ARRAY_SIZE(alarm_timers) - 1;
1091 char *arg;
1092 char *name;
1093 struct qemu_alarm_timer tmp;
1095 if (!strcmp(opt, "?")) {
1096 show_available_alarms();
1097 exit(0);
1100 arg = strdup(opt);
1102 /* Reorder the array */
1103 name = strtok(arg, ",");
1104 while (name) {
1105 for (i = 0; i < count && alarm_timers[i].name; i++) {
1106 if (!strcmp(alarm_timers[i].name, name))
1107 break;
1110 if (i == count) {
1111 fprintf(stderr, "Unknown clock %s\n", name);
1112 goto next;
1115 if (i < cur)
1116 /* Ignore */
1117 goto next;
1119 /* Swap */
1120 tmp = alarm_timers[i];
1121 alarm_timers[i] = alarm_timers[cur];
1122 alarm_timers[cur] = tmp;
1124 cur++;
1125 next:
1126 name = strtok(NULL, ",");
1129 free(arg);
1131 if (cur) {
1132 /* Disable remaining timers */
1133 for (i = cur; i < count; i++)
1134 alarm_timers[i].name = NULL;
1135 } else {
1136 show_available_alarms();
1137 exit(1);
1141 QEMUClock *rt_clock;
1142 QEMUClock *vm_clock;
1144 static QEMUTimer *active_timers[2];
1146 static QEMUClock *qemu_new_clock(int type)
1148 QEMUClock *clock;
1149 clock = qemu_mallocz(sizeof(QEMUClock));
1150 clock->type = type;
1151 return clock;
1154 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1156 QEMUTimer *ts;
1158 ts = qemu_mallocz(sizeof(QEMUTimer));
1159 ts->clock = clock;
1160 ts->cb = cb;
1161 ts->opaque = opaque;
1162 return ts;
1165 void qemu_free_timer(QEMUTimer *ts)
1167 qemu_free(ts);
1170 /* stop a timer, but do not dealloc it */
1171 void qemu_del_timer(QEMUTimer *ts)
1173 QEMUTimer **pt, *t;
1175 /* NOTE: this code must be signal safe because
1176 qemu_timer_expired() can be called from a signal. */
1177 pt = &active_timers[ts->clock->type];
1178 for(;;) {
1179 t = *pt;
1180 if (!t)
1181 break;
1182 if (t == ts) {
1183 *pt = t->next;
1184 break;
1186 pt = &t->next;
1190 /* modify the current timer so that it will be fired when current_time
1191 >= expire_time. The corresponding callback will be called. */
1192 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1194 QEMUTimer **pt, *t;
1196 qemu_del_timer(ts);
1198 /* add the timer in the sorted list */
1199 /* NOTE: this code must be signal safe because
1200 qemu_timer_expired() can be called from a signal. */
1201 pt = &active_timers[ts->clock->type];
1202 for(;;) {
1203 t = *pt;
1204 if (!t)
1205 break;
1206 if (t->expire_time > expire_time)
1207 break;
1208 pt = &t->next;
1210 ts->expire_time = expire_time;
1211 ts->next = *pt;
1212 *pt = ts;
1214 /* Rearm if necessary */
1215 if (pt == &active_timers[ts->clock->type]) {
1216 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1217 qemu_rearm_alarm_timer(alarm_timer);
1219 /* Interrupt execution to force deadline recalculation. */
1220 if (use_icount && cpu_single_env) {
1221 cpu_exit(cpu_single_env);
1226 int qemu_timer_pending(QEMUTimer *ts)
1228 QEMUTimer *t;
1229 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1230 if (t == ts)
1231 return 1;
1233 return 0;
1236 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1238 if (!timer_head)
1239 return 0;
1240 return (timer_head->expire_time <= current_time);
1243 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1245 QEMUTimer *ts;
1247 for(;;) {
1248 ts = *ptimer_head;
1249 if (!ts || ts->expire_time > current_time)
1250 break;
1251 /* remove timer from the list before calling the callback */
1252 *ptimer_head = ts->next;
1253 ts->next = NULL;
1255 /* run the callback (the timer list can be modified) */
1256 ts->cb(ts->opaque);
1260 int64_t qemu_get_clock(QEMUClock *clock)
1262 switch(clock->type) {
1263 case QEMU_TIMER_REALTIME:
1264 return get_clock() / 1000000;
1265 default:
1266 case QEMU_TIMER_VIRTUAL:
1267 if (use_icount) {
1268 return cpu_get_icount();
1269 } else {
1270 return cpu_get_clock();
1275 static void init_timers(void)
1277 init_get_clock();
1278 ticks_per_sec = QEMU_TIMER_BASE;
1279 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1280 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1283 /* save a timer */
1284 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1286 uint64_t expire_time;
1288 if (qemu_timer_pending(ts)) {
1289 expire_time = ts->expire_time;
1290 } else {
1291 expire_time = -1;
1293 qemu_put_be64(f, expire_time);
1296 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1298 uint64_t expire_time;
1300 expire_time = qemu_get_be64(f);
1301 if (expire_time != -1) {
1302 qemu_mod_timer(ts, expire_time);
1303 } else {
1304 qemu_del_timer(ts);
1308 static void timer_save(QEMUFile *f, void *opaque)
1310 if (cpu_ticks_enabled) {
1311 hw_error("cannot save state if virtual timers are running");
1313 qemu_put_be64(f, cpu_ticks_offset);
1314 qemu_put_be64(f, ticks_per_sec);
1315 qemu_put_be64(f, cpu_clock_offset);
1318 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1320 if (version_id != 1 && version_id != 2)
1321 return -EINVAL;
1322 if (cpu_ticks_enabled) {
1323 return -EINVAL;
1325 cpu_ticks_offset=qemu_get_be64(f);
1326 ticks_per_sec=qemu_get_be64(f);
1327 if (version_id == 2) {
1328 cpu_clock_offset=qemu_get_be64(f);
1330 return 0;
1333 #ifdef _WIN32
1334 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1335 DWORD_PTR dwUser, DWORD_PTR dw1,
1336 DWORD_PTR dw2)
1337 #else
1338 static void host_alarm_handler(int host_signum)
1339 #endif
1341 #if 0
1342 #define DISP_FREQ 1000
1344 static int64_t delta_min = INT64_MAX;
1345 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1346 static int count;
1347 ti = qemu_get_clock(vm_clock);
1348 if (last_clock != 0) {
1349 delta = ti - last_clock;
1350 if (delta < delta_min)
1351 delta_min = delta;
1352 if (delta > delta_max)
1353 delta_max = delta;
1354 delta_cum += delta;
1355 if (++count == DISP_FREQ) {
1356 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1357 muldiv64(delta_min, 1000000, ticks_per_sec),
1358 muldiv64(delta_max, 1000000, ticks_per_sec),
1359 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1360 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1361 count = 0;
1362 delta_min = INT64_MAX;
1363 delta_max = 0;
1364 delta_cum = 0;
1367 last_clock = ti;
1369 #endif
1370 if (alarm_has_dynticks(alarm_timer) ||
1371 (!use_icount &&
1372 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1373 qemu_get_clock(vm_clock))) ||
1374 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1375 qemu_get_clock(rt_clock))) {
1376 CPUState *env = next_cpu;
1378 #ifdef _WIN32
1379 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1380 SetEvent(data->host_alarm);
1381 #else
1382 static const char byte = 0;
1383 write(alarm_timer_wfd, &byte, sizeof(byte));
1384 #endif
1385 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1387 if (env) {
1388 /* stop the currently executing cpu because a timer occured */
1389 cpu_exit(env);
1390 #ifdef CONFIG_KQEMU
1391 if (env->kqemu_enabled) {
1392 kqemu_cpu_interrupt(env);
1394 #endif
1396 event_pending = 1;
1400 static int64_t qemu_next_deadline(void)
1402 int64_t delta;
1404 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1405 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1406 qemu_get_clock(vm_clock);
1407 } else {
1408 /* To avoid problems with overflow limit this to 2^32. */
1409 delta = INT32_MAX;
1412 if (delta < 0)
1413 delta = 0;
1415 return delta;
1418 #if defined(__linux__) || defined(_WIN32)
1419 static uint64_t qemu_next_deadline_dyntick(void)
1421 int64_t delta;
1422 int64_t rtdelta;
1424 if (use_icount)
1425 delta = INT32_MAX;
1426 else
1427 delta = (qemu_next_deadline() + 999) / 1000;
1429 if (active_timers[QEMU_TIMER_REALTIME]) {
1430 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1431 qemu_get_clock(rt_clock))*1000;
1432 if (rtdelta < delta)
1433 delta = rtdelta;
1436 if (delta < MIN_TIMER_REARM_US)
1437 delta = MIN_TIMER_REARM_US;
1439 return delta;
1441 #endif
1443 #ifndef _WIN32
1445 /* Sets a specific flag */
1446 static int fcntl_setfl(int fd, int flag)
1448 int flags;
1450 flags = fcntl(fd, F_GETFL);
1451 if (flags == -1)
1452 return -errno;
1454 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1455 return -errno;
1457 return 0;
1460 #if defined(__linux__)
1462 #define RTC_FREQ 1024
1464 static void enable_sigio_timer(int fd)
1466 struct sigaction act;
1468 /* timer signal */
1469 sigfillset(&act.sa_mask);
1470 act.sa_flags = 0;
1471 act.sa_handler = host_alarm_handler;
1473 sigaction(SIGIO, &act, NULL);
1474 fcntl_setfl(fd, O_ASYNC);
1475 fcntl(fd, F_SETOWN, getpid());
1478 static int hpet_start_timer(struct qemu_alarm_timer *t)
1480 struct hpet_info info;
1481 int r, fd;
1483 fd = open("/dev/hpet", O_RDONLY);
1484 if (fd < 0)
1485 return -1;
1487 /* Set frequency */
1488 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1489 if (r < 0) {
1490 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1491 "error, but for better emulation accuracy type:\n"
1492 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1493 goto fail;
1496 /* Check capabilities */
1497 r = ioctl(fd, HPET_INFO, &info);
1498 if (r < 0)
1499 goto fail;
1501 /* Enable periodic mode */
1502 r = ioctl(fd, HPET_EPI, 0);
1503 if (info.hi_flags && (r < 0))
1504 goto fail;
1506 /* Enable interrupt */
1507 r = ioctl(fd, HPET_IE_ON, 0);
1508 if (r < 0)
1509 goto fail;
1511 enable_sigio_timer(fd);
1512 t->priv = (void *)(long)fd;
1514 return 0;
1515 fail:
1516 close(fd);
1517 return -1;
1520 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1522 int fd = (long)t->priv;
1524 close(fd);
1527 static int rtc_start_timer(struct qemu_alarm_timer *t)
1529 int rtc_fd;
1530 unsigned long current_rtc_freq = 0;
1532 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1533 if (rtc_fd < 0)
1534 return -1;
1535 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1536 if (current_rtc_freq != RTC_FREQ &&
1537 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1538 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1539 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1540 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1541 goto fail;
1543 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1544 fail:
1545 close(rtc_fd);
1546 return -1;
1549 enable_sigio_timer(rtc_fd);
1551 t->priv = (void *)(long)rtc_fd;
1553 return 0;
1556 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1558 int rtc_fd = (long)t->priv;
1560 close(rtc_fd);
1563 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1565 struct sigevent ev;
1566 timer_t host_timer;
1567 struct sigaction act;
1569 sigfillset(&act.sa_mask);
1570 act.sa_flags = 0;
1571 act.sa_handler = host_alarm_handler;
1573 sigaction(SIGALRM, &act, NULL);
1575 ev.sigev_value.sival_int = 0;
1576 ev.sigev_notify = SIGEV_SIGNAL;
1577 ev.sigev_signo = SIGALRM;
1579 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1580 perror("timer_create");
1582 /* disable dynticks */
1583 fprintf(stderr, "Dynamic Ticks disabled\n");
1585 return -1;
1588 t->priv = (void *)(long)host_timer;
1590 return 0;
1593 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1595 timer_t host_timer = (timer_t)(long)t->priv;
1597 timer_delete(host_timer);
1600 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1602 timer_t host_timer = (timer_t)(long)t->priv;
1603 struct itimerspec timeout;
1604 int64_t nearest_delta_us = INT64_MAX;
1605 int64_t current_us;
1607 if (!active_timers[QEMU_TIMER_REALTIME] &&
1608 !active_timers[QEMU_TIMER_VIRTUAL])
1609 return;
1611 nearest_delta_us = qemu_next_deadline_dyntick();
1613 /* check whether a timer is already running */
1614 if (timer_gettime(host_timer, &timeout)) {
1615 perror("gettime");
1616 fprintf(stderr, "Internal timer error: aborting\n");
1617 exit(1);
1619 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1620 if (current_us && current_us <= nearest_delta_us)
1621 return;
1623 timeout.it_interval.tv_sec = 0;
1624 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1625 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1626 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1627 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1628 perror("settime");
1629 fprintf(stderr, "Internal timer error: aborting\n");
1630 exit(1);
1634 #endif /* defined(__linux__) */
1636 static int unix_start_timer(struct qemu_alarm_timer *t)
1638 struct sigaction act;
1639 struct itimerval itv;
1640 int err;
1642 /* timer signal */
1643 sigfillset(&act.sa_mask);
1644 act.sa_flags = 0;
1645 act.sa_handler = host_alarm_handler;
1647 sigaction(SIGALRM, &act, NULL);
1649 itv.it_interval.tv_sec = 0;
1650 /* for i386 kernel 2.6 to get 1 ms */
1651 itv.it_interval.tv_usec = 999;
1652 itv.it_value.tv_sec = 0;
1653 itv.it_value.tv_usec = 10 * 1000;
1655 err = setitimer(ITIMER_REAL, &itv, NULL);
1656 if (err)
1657 return -1;
1659 return 0;
1662 static void unix_stop_timer(struct qemu_alarm_timer *t)
1664 struct itimerval itv;
1666 memset(&itv, 0, sizeof(itv));
1667 setitimer(ITIMER_REAL, &itv, NULL);
1670 #endif /* !defined(_WIN32) */
1672 static void try_to_rearm_timer(void *opaque)
1674 struct qemu_alarm_timer *t = opaque;
1675 #ifndef _WIN32
1676 ssize_t len;
1678 /* Drain the notify pipe */
1679 do {
1680 char buffer[512];
1681 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1682 } while ((len == -1 && errno == EINTR) || len > 0);
1683 #endif
1685 if (t->flags & ALARM_FLAG_EXPIRED) {
1686 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1687 qemu_rearm_alarm_timer(alarm_timer);
1691 #ifdef _WIN32
1693 static int win32_start_timer(struct qemu_alarm_timer *t)
1695 TIMECAPS tc;
1696 struct qemu_alarm_win32 *data = t->priv;
1697 UINT flags;
1699 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1700 if (!data->host_alarm) {
1701 perror("Failed CreateEvent");
1702 return -1;
1705 memset(&tc, 0, sizeof(tc));
1706 timeGetDevCaps(&tc, sizeof(tc));
1708 if (data->period < tc.wPeriodMin)
1709 data->period = tc.wPeriodMin;
1711 timeBeginPeriod(data->period);
1713 flags = TIME_CALLBACK_FUNCTION;
1714 if (alarm_has_dynticks(t))
1715 flags |= TIME_ONESHOT;
1716 else
1717 flags |= TIME_PERIODIC;
1719 data->timerId = timeSetEvent(1, // interval (ms)
1720 data->period, // resolution
1721 host_alarm_handler, // function
1722 (DWORD)t, // parameter
1723 flags);
1725 if (!data->timerId) {
1726 perror("Failed to initialize win32 alarm timer");
1728 timeEndPeriod(data->period);
1729 CloseHandle(data->host_alarm);
1730 return -1;
1733 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1735 return 0;
1738 static void win32_stop_timer(struct qemu_alarm_timer *t)
1740 struct qemu_alarm_win32 *data = t->priv;
1742 timeKillEvent(data->timerId);
1743 timeEndPeriod(data->period);
1745 CloseHandle(data->host_alarm);
1748 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1750 struct qemu_alarm_win32 *data = t->priv;
1751 uint64_t nearest_delta_us;
1753 if (!active_timers[QEMU_TIMER_REALTIME] &&
1754 !active_timers[QEMU_TIMER_VIRTUAL])
1755 return;
1757 nearest_delta_us = qemu_next_deadline_dyntick();
1758 nearest_delta_us /= 1000;
1760 timeKillEvent(data->timerId);
1762 data->timerId = timeSetEvent(1,
1763 data->period,
1764 host_alarm_handler,
1765 (DWORD)t,
1766 TIME_ONESHOT | TIME_PERIODIC);
1768 if (!data->timerId) {
1769 perror("Failed to re-arm win32 alarm timer");
1771 timeEndPeriod(data->period);
1772 CloseHandle(data->host_alarm);
1773 exit(1);
1777 #endif /* _WIN32 */
1779 static int init_timer_alarm(void)
1781 struct qemu_alarm_timer *t = NULL;
1782 int i, err = -1;
1784 #ifndef _WIN32
1785 int fds[2];
1787 err = pipe(fds);
1788 if (err == -1)
1789 return -errno;
1791 err = fcntl_setfl(fds[0], O_NONBLOCK);
1792 if (err < 0)
1793 goto fail;
1795 err = fcntl_setfl(fds[1], O_NONBLOCK);
1796 if (err < 0)
1797 goto fail;
1799 alarm_timer_rfd = fds[0];
1800 alarm_timer_wfd = fds[1];
1801 #endif
1803 for (i = 0; alarm_timers[i].name; i++) {
1804 t = &alarm_timers[i];
1806 err = t->start(t);
1807 if (!err)
1808 break;
1811 if (err) {
1812 err = -ENOENT;
1813 goto fail;
1816 #ifndef _WIN32
1817 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1818 try_to_rearm_timer, NULL, t);
1819 #endif
1821 alarm_timer = t;
1823 return 0;
1825 fail:
1826 #ifndef _WIN32
1827 close(fds[0]);
1828 close(fds[1]);
1829 #endif
1830 return err;
1833 static void quit_timers(void)
1835 alarm_timer->stop(alarm_timer);
1836 alarm_timer = NULL;
1839 /***********************************************************/
1840 /* host time/date access */
1841 void qemu_get_timedate(struct tm *tm, int offset)
1843 time_t ti;
1844 struct tm *ret;
1846 time(&ti);
1847 ti += offset;
1848 if (rtc_date_offset == -1) {
1849 if (rtc_utc)
1850 ret = gmtime(&ti);
1851 else
1852 ret = localtime(&ti);
1853 } else {
1854 ti -= rtc_date_offset;
1855 ret = gmtime(&ti);
1858 memcpy(tm, ret, sizeof(struct tm));
1861 int qemu_timedate_diff(struct tm *tm)
1863 time_t seconds;
1865 if (rtc_date_offset == -1)
1866 if (rtc_utc)
1867 seconds = mktimegm(tm);
1868 else
1869 seconds = mktime(tm);
1870 else
1871 seconds = mktimegm(tm) + rtc_date_offset;
1873 return seconds - time(NULL);
1876 #ifdef _WIN32
1877 static void socket_cleanup(void)
1879 WSACleanup();
1882 static int socket_init(void)
1884 WSADATA Data;
1885 int ret, err;
1887 ret = WSAStartup(MAKEWORD(2,2), &Data);
1888 if (ret != 0) {
1889 err = WSAGetLastError();
1890 fprintf(stderr, "WSAStartup: %d\n", err);
1891 return -1;
1893 atexit(socket_cleanup);
1894 return 0;
1896 #endif
1898 const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
1900 char *q;
1902 q = buf;
1903 while (*p != '\0' && *p != delim) {
1904 if (q && (q - buf) < buf_size - 1)
1905 *q++ = *p;
1906 p++;
1908 if (q)
1909 *q = '\0';
1911 return p;
1914 const char *get_opt_value(char *buf, int buf_size, const char *p)
1916 char *q;
1918 q = buf;
1919 while (*p != '\0') {
1920 if (*p == ',') {
1921 if (*(p + 1) != ',')
1922 break;
1923 p++;
1925 if (q && (q - buf) < buf_size - 1)
1926 *q++ = *p;
1927 p++;
1929 if (q)
1930 *q = '\0';
1932 return p;
1935 int get_param_value(char *buf, int buf_size,
1936 const char *tag, const char *str)
1938 const char *p;
1939 char option[128];
1941 p = str;
1942 for(;;) {
1943 p = get_opt_name(option, sizeof(option), p, '=');
1944 if (*p != '=')
1945 break;
1946 p++;
1947 if (!strcmp(tag, option)) {
1948 (void)get_opt_value(buf, buf_size, p);
1949 return strlen(buf);
1950 } else {
1951 p = get_opt_value(NULL, 0, p);
1953 if (*p != ',')
1954 break;
1955 p++;
1957 return 0;
1960 int check_params(char *buf, int buf_size,
1961 const char * const *params, const char *str)
1963 const char *p;
1964 int i;
1966 p = str;
1967 while (*p != '\0') {
1968 p = get_opt_name(buf, buf_size, p, '=');
1969 if (*p != '=')
1970 return -1;
1971 p++;
1972 for(i = 0; params[i] != NULL; i++)
1973 if (!strcmp(params[i], buf))
1974 break;
1975 if (params[i] == NULL)
1976 return -1;
1977 p = get_opt_value(NULL, 0, p);
1978 if (*p != ',')
1979 break;
1980 p++;
1982 return 0;
1985 /***********************************************************/
1986 /* Bluetooth support */
1987 static int nb_hcis;
1988 static int cur_hci;
1989 static struct HCIInfo *hci_table[MAX_NICS];
1991 static struct bt_vlan_s {
1992 struct bt_scatternet_s net;
1993 int id;
1994 struct bt_vlan_s *next;
1995 } *first_bt_vlan;
1997 /* find or alloc a new bluetooth "VLAN" */
1998 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
2000 struct bt_vlan_s **pvlan, *vlan;
2001 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
2002 if (vlan->id == id)
2003 return &vlan->net;
2005 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
2006 vlan->id = id;
2007 pvlan = &first_bt_vlan;
2008 while (*pvlan != NULL)
2009 pvlan = &(*pvlan)->next;
2010 *pvlan = vlan;
2011 return &vlan->net;
2014 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2018 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2020 return -ENOTSUP;
2023 static struct HCIInfo null_hci = {
2024 .cmd_send = null_hci_send,
2025 .sco_send = null_hci_send,
2026 .acl_send = null_hci_send,
2027 .bdaddr_set = null_hci_addr_set,
2030 struct HCIInfo *qemu_next_hci(void)
2032 if (cur_hci == nb_hcis)
2033 return &null_hci;
2035 return hci_table[cur_hci++];
2038 static struct HCIInfo *hci_init(const char *str)
2040 char *endp;
2041 struct bt_scatternet_s *vlan = 0;
2043 if (!strcmp(str, "null"))
2044 /* null */
2045 return &null_hci;
2046 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2047 /* host[:hciN] */
2048 return bt_host_hci(str[4] ? str + 5 : "hci0");
2049 else if (!strncmp(str, "hci", 3)) {
2050 /* hci[,vlan=n] */
2051 if (str[3]) {
2052 if (!strncmp(str + 3, ",vlan=", 6)) {
2053 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2054 if (*endp)
2055 vlan = 0;
2057 } else
2058 vlan = qemu_find_bt_vlan(0);
2059 if (vlan)
2060 return bt_new_hci(vlan);
2063 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2065 return 0;
2068 static int bt_hci_parse(const char *str)
2070 struct HCIInfo *hci;
2071 bdaddr_t bdaddr;
2073 if (nb_hcis >= MAX_NICS) {
2074 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2075 return -1;
2078 hci = hci_init(str);
2079 if (!hci)
2080 return -1;
2082 bdaddr.b[0] = 0x52;
2083 bdaddr.b[1] = 0x54;
2084 bdaddr.b[2] = 0x00;
2085 bdaddr.b[3] = 0x12;
2086 bdaddr.b[4] = 0x34;
2087 bdaddr.b[5] = 0x56 + nb_hcis;
2088 hci->bdaddr_set(hci, bdaddr.b);
2090 hci_table[nb_hcis++] = hci;
2092 return 0;
2095 static void bt_vhci_add(int vlan_id)
2097 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2099 if (!vlan->slave)
2100 fprintf(stderr, "qemu: warning: adding a VHCI to "
2101 "an empty scatternet %i\n", vlan_id);
2103 bt_vhci_init(bt_new_hci(vlan));
2106 static struct bt_device_s *bt_device_add(const char *opt)
2108 struct bt_scatternet_s *vlan;
2109 int vlan_id = 0;
2110 char *endp = strstr(opt, ",vlan=");
2111 int len = (endp ? endp - opt : strlen(opt)) + 1;
2112 char devname[10];
2114 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2116 if (endp) {
2117 vlan_id = strtol(endp + 6, &endp, 0);
2118 if (*endp) {
2119 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2120 return 0;
2124 vlan = qemu_find_bt_vlan(vlan_id);
2126 if (!vlan->slave)
2127 fprintf(stderr, "qemu: warning: adding a slave device to "
2128 "an empty scatternet %i\n", vlan_id);
2130 if (!strcmp(devname, "keyboard"))
2131 return bt_keyboard_init(vlan);
2133 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2134 return 0;
2137 static int bt_parse(const char *opt)
2139 const char *endp, *p;
2140 int vlan;
2142 if (strstart(opt, "hci", &endp)) {
2143 if (!*endp || *endp == ',') {
2144 if (*endp)
2145 if (!strstart(endp, ",vlan=", 0))
2146 opt = endp + 1;
2148 return bt_hci_parse(opt);
2150 } else if (strstart(opt, "vhci", &endp)) {
2151 if (!*endp || *endp == ',') {
2152 if (*endp) {
2153 if (strstart(endp, ",vlan=", &p)) {
2154 vlan = strtol(p, (char **) &endp, 0);
2155 if (*endp) {
2156 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2157 return 1;
2159 } else {
2160 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2161 return 1;
2163 } else
2164 vlan = 0;
2166 bt_vhci_add(vlan);
2167 return 0;
2169 } else if (strstart(opt, "device:", &endp))
2170 return !bt_device_add(endp);
2172 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2173 return 1;
2176 /***********************************************************/
2177 /* QEMU Block devices */
2179 #define HD_ALIAS "index=%d,media=disk"
2180 #define CDROM_ALIAS "index=2,media=cdrom"
2181 #define FD_ALIAS "index=%d,if=floppy"
2182 #define PFLASH_ALIAS "if=pflash"
2183 #define MTD_ALIAS "if=mtd"
2184 #define SD_ALIAS "index=0,if=sd"
2186 static int drive_opt_get_free_idx(void)
2188 int index;
2190 for (index = 0; index < MAX_DRIVES; index++)
2191 if (!drives_opt[index].used) {
2192 drives_opt[index].used = 1;
2193 return index;
2196 return -1;
2199 static int drive_get_free_idx(void)
2201 int index;
2203 for (index = 0; index < MAX_DRIVES; index++)
2204 if (!drives_table[index].used) {
2205 drives_table[index].used = 1;
2206 return index;
2209 return -1;
2212 int drive_add(const char *file, const char *fmt, ...)
2214 va_list ap;
2215 int index = drive_opt_get_free_idx();
2217 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2218 fprintf(stderr, "qemu: too many drives\n");
2219 return -1;
2222 drives_opt[index].file = file;
2223 va_start(ap, fmt);
2224 vsnprintf(drives_opt[index].opt,
2225 sizeof(drives_opt[0].opt), fmt, ap);
2226 va_end(ap);
2228 nb_drives_opt++;
2229 return index;
2232 void drive_remove(int index)
2234 drives_opt[index].used = 0;
2235 nb_drives_opt--;
2238 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2240 int index;
2242 /* seek interface, bus and unit */
2244 for (index = 0; index < MAX_DRIVES; index++)
2245 if (drives_table[index].type == type &&
2246 drives_table[index].bus == bus &&
2247 drives_table[index].unit == unit &&
2248 drives_table[index].used)
2249 return index;
2251 return -1;
2254 int drive_get_max_bus(BlockInterfaceType type)
2256 int max_bus;
2257 int index;
2259 max_bus = -1;
2260 for (index = 0; index < nb_drives; index++) {
2261 if(drives_table[index].type == type &&
2262 drives_table[index].bus > max_bus)
2263 max_bus = drives_table[index].bus;
2265 return max_bus;
2268 const char *drive_get_serial(BlockDriverState *bdrv)
2270 int index;
2272 for (index = 0; index < nb_drives; index++)
2273 if (drives_table[index].bdrv == bdrv)
2274 return drives_table[index].serial;
2276 return "\0";
2279 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2281 int index;
2283 for (index = 0; index < nb_drives; index++)
2284 if (drives_table[index].bdrv == bdrv)
2285 return drives_table[index].onerror;
2287 return BLOCK_ERR_STOP_ENOSPC;
2290 static void bdrv_format_print(void *opaque, const char *name)
2292 fprintf(stderr, " %s", name);
2295 void drive_uninit(BlockDriverState *bdrv)
2297 int i;
2299 for (i = 0; i < MAX_DRIVES; i++)
2300 if (drives_table[i].bdrv == bdrv) {
2301 drives_table[i].bdrv = NULL;
2302 drives_table[i].used = 0;
2303 drive_remove(drives_table[i].drive_opt_idx);
2304 nb_drives--;
2305 break;
2309 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2311 char buf[128];
2312 char file[1024];
2313 char devname[128];
2314 char serial[21];
2315 const char *mediastr = "";
2316 BlockInterfaceType type;
2317 enum { MEDIA_DISK, MEDIA_CDROM } media;
2318 int bus_id, unit_id;
2319 int cyls, heads, secs, translation;
2320 BlockDriverState *bdrv;
2321 BlockDriver *drv = NULL;
2322 QEMUMachine *machine = opaque;
2323 int max_devs;
2324 int index;
2325 int cache;
2326 int bdrv_flags, onerror;
2327 int drives_table_idx;
2328 char *str = arg->opt;
2329 static const char * const params[] = { "bus", "unit", "if", "index",
2330 "cyls", "heads", "secs", "trans",
2331 "media", "snapshot", "file",
2332 "cache", "format", "serial", "werror",
2333 "boot", NULL };
2335 if (check_params(buf, sizeof(buf), params, str) < 0) {
2336 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2337 buf, str);
2338 return -1;
2341 file[0] = 0;
2342 cyls = heads = secs = 0;
2343 bus_id = 0;
2344 unit_id = -1;
2345 translation = BIOS_ATA_TRANSLATION_AUTO;
2346 index = -1;
2347 cache = 3;
2349 if (machine->use_scsi) {
2350 type = IF_SCSI;
2351 max_devs = MAX_SCSI_DEVS;
2352 pstrcpy(devname, sizeof(devname), "scsi");
2353 } else {
2354 type = IF_IDE;
2355 max_devs = MAX_IDE_DEVS;
2356 pstrcpy(devname, sizeof(devname), "ide");
2358 media = MEDIA_DISK;
2360 /* extract parameters */
2362 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2363 bus_id = strtol(buf, NULL, 0);
2364 if (bus_id < 0) {
2365 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2366 return -1;
2370 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2371 unit_id = strtol(buf, NULL, 0);
2372 if (unit_id < 0) {
2373 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2374 return -1;
2378 if (get_param_value(buf, sizeof(buf), "if", str)) {
2379 pstrcpy(devname, sizeof(devname), buf);
2380 if (!strcmp(buf, "ide")) {
2381 type = IF_IDE;
2382 max_devs = MAX_IDE_DEVS;
2383 } else if (!strcmp(buf, "scsi")) {
2384 type = IF_SCSI;
2385 max_devs = MAX_SCSI_DEVS;
2386 } else if (!strcmp(buf, "floppy")) {
2387 type = IF_FLOPPY;
2388 max_devs = 0;
2389 } else if (!strcmp(buf, "pflash")) {
2390 type = IF_PFLASH;
2391 max_devs = 0;
2392 } else if (!strcmp(buf, "mtd")) {
2393 type = IF_MTD;
2394 max_devs = 0;
2395 } else if (!strcmp(buf, "sd")) {
2396 type = IF_SD;
2397 max_devs = 0;
2398 } else if (!strcmp(buf, "virtio")) {
2399 type = IF_VIRTIO;
2400 max_devs = 0;
2401 } else if (!strcmp(buf, "xen")) {
2402 type = IF_XEN;
2403 max_devs = 0;
2404 } else {
2405 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2406 return -1;
2410 if (get_param_value(buf, sizeof(buf), "index", str)) {
2411 index = strtol(buf, NULL, 0);
2412 if (index < 0) {
2413 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2414 return -1;
2418 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2419 cyls = strtol(buf, NULL, 0);
2422 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2423 heads = strtol(buf, NULL, 0);
2426 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2427 secs = strtol(buf, NULL, 0);
2430 if (cyls || heads || secs) {
2431 if (cyls < 1 || cyls > 16383) {
2432 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2433 return -1;
2435 if (heads < 1 || heads > 16) {
2436 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2437 return -1;
2439 if (secs < 1 || secs > 63) {
2440 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2441 return -1;
2445 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2446 if (!cyls) {
2447 fprintf(stderr,
2448 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2449 str);
2450 return -1;
2452 if (!strcmp(buf, "none"))
2453 translation = BIOS_ATA_TRANSLATION_NONE;
2454 else if (!strcmp(buf, "lba"))
2455 translation = BIOS_ATA_TRANSLATION_LBA;
2456 else if (!strcmp(buf, "auto"))
2457 translation = BIOS_ATA_TRANSLATION_AUTO;
2458 else {
2459 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2460 return -1;
2464 if (get_param_value(buf, sizeof(buf), "media", str)) {
2465 if (!strcmp(buf, "disk")) {
2466 media = MEDIA_DISK;
2467 } else if (!strcmp(buf, "cdrom")) {
2468 if (cyls || secs || heads) {
2469 fprintf(stderr,
2470 "qemu: '%s' invalid physical CHS format\n", str);
2471 return -1;
2473 media = MEDIA_CDROM;
2474 } else {
2475 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2476 return -1;
2480 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2481 if (!strcmp(buf, "on"))
2482 snapshot = 1;
2483 else if (!strcmp(buf, "off"))
2484 snapshot = 0;
2485 else {
2486 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2487 return -1;
2491 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2492 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2493 cache = 0;
2494 else if (!strcmp(buf, "writethrough"))
2495 cache = 1;
2496 else if (!strcmp(buf, "writeback"))
2497 cache = 2;
2498 else {
2499 fprintf(stderr, "qemu: invalid cache option\n");
2500 return -1;
2504 if (get_param_value(buf, sizeof(buf), "format", str)) {
2505 if (strcmp(buf, "?") == 0) {
2506 fprintf(stderr, "qemu: Supported formats:");
2507 bdrv_iterate_format(bdrv_format_print, NULL);
2508 fprintf(stderr, "\n");
2509 return -1;
2511 drv = bdrv_find_format(buf);
2512 if (!drv) {
2513 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2514 return -1;
2518 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2519 if (!strcmp(buf, "on")) {
2520 if (extboot_drive != -1) {
2521 fprintf(stderr, "qemu: two bootable drives specified\n");
2522 return -1;
2524 extboot_drive = nb_drives;
2525 } else if (strcmp(buf, "off")) {
2526 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2527 return -1;
2531 if (arg->file == NULL)
2532 get_param_value(file, sizeof(file), "file", str);
2533 else
2534 pstrcpy(file, sizeof(file), arg->file);
2536 if (!get_param_value(serial, sizeof(serial), "serial", str))
2537 memset(serial, 0, sizeof(serial));
2539 onerror = BLOCK_ERR_STOP_ENOSPC;
2540 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2541 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2542 fprintf(stderr, "werror is no supported by this format\n");
2543 return -1;
2545 if (!strcmp(buf, "ignore"))
2546 onerror = BLOCK_ERR_IGNORE;
2547 else if (!strcmp(buf, "enospc"))
2548 onerror = BLOCK_ERR_STOP_ENOSPC;
2549 else if (!strcmp(buf, "stop"))
2550 onerror = BLOCK_ERR_STOP_ANY;
2551 else if (!strcmp(buf, "report"))
2552 onerror = BLOCK_ERR_REPORT;
2553 else {
2554 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2555 return -1;
2559 /* compute bus and unit according index */
2561 if (index != -1) {
2562 if (bus_id != 0 || unit_id != -1) {
2563 fprintf(stderr,
2564 "qemu: '%s' index cannot be used with bus and unit\n", str);
2565 return -1;
2567 if (max_devs == 0)
2569 unit_id = index;
2570 bus_id = 0;
2571 } else {
2572 unit_id = index % max_devs;
2573 bus_id = index / max_devs;
2577 /* if user doesn't specify a unit_id,
2578 * try to find the first free
2581 if (unit_id == -1) {
2582 unit_id = 0;
2583 while (drive_get_index(type, bus_id, unit_id) != -1) {
2584 unit_id++;
2585 if (max_devs && unit_id >= max_devs) {
2586 unit_id -= max_devs;
2587 bus_id++;
2592 /* check unit id */
2594 if (max_devs && unit_id >= max_devs) {
2595 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2596 str, unit_id, max_devs - 1);
2597 return -1;
2601 * ignore multiple definitions
2604 if (drive_get_index(type, bus_id, unit_id) != -1)
2605 return -2;
2607 /* init */
2609 if (type == IF_IDE || type == IF_SCSI)
2610 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2611 if (max_devs)
2612 snprintf(buf, sizeof(buf), "%s%i%s%i",
2613 devname, bus_id, mediastr, unit_id);
2614 else
2615 snprintf(buf, sizeof(buf), "%s%s%i",
2616 devname, mediastr, unit_id);
2617 bdrv = bdrv_new(buf);
2618 drives_table_idx = drive_get_free_idx();
2619 drives_table[drives_table_idx].bdrv = bdrv;
2620 drives_table[drives_table_idx].type = type;
2621 drives_table[drives_table_idx].bus = bus_id;
2622 drives_table[drives_table_idx].unit = unit_id;
2623 drives_table[drives_table_idx].onerror = onerror;
2624 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2625 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2626 nb_drives++;
2628 switch(type) {
2629 case IF_IDE:
2630 case IF_SCSI:
2631 case IF_XEN:
2632 switch(media) {
2633 case MEDIA_DISK:
2634 if (cyls != 0) {
2635 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2636 bdrv_set_translation_hint(bdrv, translation);
2638 break;
2639 case MEDIA_CDROM:
2640 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2641 break;
2643 break;
2644 case IF_SD:
2645 /* FIXME: This isn't really a floppy, but it's a reasonable
2646 approximation. */
2647 case IF_FLOPPY:
2648 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2649 break;
2650 case IF_PFLASH:
2651 case IF_MTD:
2652 case IF_VIRTIO:
2653 break;
2655 if (!file[0])
2656 return -2;
2657 bdrv_flags = 0;
2658 if (snapshot) {
2659 bdrv_flags |= BDRV_O_SNAPSHOT;
2660 cache = 2; /* always use write-back with snapshot */
2662 if (cache == 0) /* no caching */
2663 bdrv_flags |= BDRV_O_NOCACHE;
2664 else if (cache == 2) /* write-back */
2665 bdrv_flags |= BDRV_O_CACHE_WB;
2666 else if (cache == 3) /* not specified */
2667 bdrv_flags |= BDRV_O_CACHE_DEF;
2668 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2669 fprintf(stderr, "qemu: could not open disk image %s\n",
2670 file);
2671 return -1;
2673 if (bdrv_key_required(bdrv))
2674 autostart = 0;
2675 return drives_table_idx;
2678 static void numa_add(const char *optarg)
2680 char option[128];
2681 char *endptr;
2682 unsigned long long value, endvalue;
2683 int nodenr;
2685 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2686 if (!strcmp(option, "node")) {
2687 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2688 nodenr = nb_numa_nodes;
2689 } else {
2690 nodenr = strtoull(option, NULL, 10);
2693 if (get_param_value(option, 128, "mem", optarg) == 0) {
2694 node_mem[nodenr] = 0;
2695 } else {
2696 value = strtoull(option, &endptr, 0);
2697 switch (*endptr) {
2698 case 0: case 'M': case 'm':
2699 value <<= 20;
2700 break;
2701 case 'G': case 'g':
2702 value <<= 30;
2703 break;
2705 node_mem[nodenr] = value;
2707 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2708 node_cpumask[nodenr] = 0;
2709 } else {
2710 value = strtoull(option, &endptr, 10);
2711 if (value >= 64) {
2712 value = 63;
2713 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2714 } else {
2715 if (*endptr == '-') {
2716 endvalue = strtoull(endptr+1, &endptr, 10);
2717 if (endvalue >= 63) {
2718 endvalue = 62;
2719 fprintf(stderr,
2720 "only 63 CPUs in NUMA mode supported.\n");
2722 value = (1 << (endvalue + 1)) - (1 << value);
2723 } else {
2724 value = 1 << value;
2727 node_cpumask[nodenr] = value;
2729 nb_numa_nodes++;
2731 return;
2734 /***********************************************************/
2735 /* USB devices */
2737 static USBPort *used_usb_ports;
2738 static USBPort *free_usb_ports;
2740 /* ??? Maybe change this to register a hub to keep track of the topology. */
2741 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2742 usb_attachfn attach)
2744 port->opaque = opaque;
2745 port->index = index;
2746 port->attach = attach;
2747 port->next = free_usb_ports;
2748 free_usb_ports = port;
2751 int usb_device_add_dev(USBDevice *dev)
2753 USBPort *port;
2755 /* Find a USB port to add the device to. */
2756 port = free_usb_ports;
2757 if (!port->next) {
2758 USBDevice *hub;
2760 /* Create a new hub and chain it on. */
2761 free_usb_ports = NULL;
2762 port->next = used_usb_ports;
2763 used_usb_ports = port;
2765 hub = usb_hub_init(VM_USB_HUB_SIZE);
2766 usb_attach(port, hub);
2767 port = free_usb_ports;
2770 free_usb_ports = port->next;
2771 port->next = used_usb_ports;
2772 used_usb_ports = port;
2773 usb_attach(port, dev);
2774 return 0;
2777 static void usb_msd_password_cb(void *opaque, int err)
2779 USBDevice *dev = opaque;
2781 if (!err)
2782 usb_device_add_dev(dev);
2783 else
2784 dev->handle_destroy(dev);
2787 static int usb_device_add(const char *devname, int is_hotplug)
2789 const char *p;
2790 USBDevice *dev;
2792 if (!free_usb_ports)
2793 return -1;
2795 if (strstart(devname, "host:", &p)) {
2796 dev = usb_host_device_open(p);
2797 } else if (!strcmp(devname, "mouse")) {
2798 dev = usb_mouse_init();
2799 } else if (!strcmp(devname, "tablet")) {
2800 dev = usb_tablet_init();
2801 } else if (!strcmp(devname, "keyboard")) {
2802 dev = usb_keyboard_init();
2803 } else if (strstart(devname, "disk:", &p)) {
2804 BlockDriverState *bs;
2806 dev = usb_msd_init(p);
2807 if (!dev)
2808 return -1;
2809 bs = usb_msd_get_bdrv(dev);
2810 if (bdrv_key_required(bs)) {
2811 autostart = 0;
2812 if (is_hotplug) {
2813 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2814 dev);
2815 return 0;
2818 } else if (!strcmp(devname, "wacom-tablet")) {
2819 dev = usb_wacom_init();
2820 } else if (strstart(devname, "serial:", &p)) {
2821 dev = usb_serial_init(p);
2822 #ifdef CONFIG_BRLAPI
2823 } else if (!strcmp(devname, "braille")) {
2824 dev = usb_baum_init();
2825 #endif
2826 } else if (strstart(devname, "net:", &p)) {
2827 int nic = nb_nics;
2829 if (net_client_init("nic", p) < 0)
2830 return -1;
2831 nd_table[nic].model = "usb";
2832 dev = usb_net_init(&nd_table[nic]);
2833 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2834 dev = usb_bt_init(devname[2] ? hci_init(p) :
2835 bt_new_hci(qemu_find_bt_vlan(0)));
2836 } else {
2837 return -1;
2839 if (!dev)
2840 return -1;
2842 return usb_device_add_dev(dev);
2845 int usb_device_del_addr(int bus_num, int addr)
2847 USBPort *port;
2848 USBPort **lastp;
2849 USBDevice *dev;
2851 if (!used_usb_ports)
2852 return -1;
2854 if (bus_num != 0)
2855 return -1;
2857 lastp = &used_usb_ports;
2858 port = used_usb_ports;
2859 while (port && port->dev->addr != addr) {
2860 lastp = &port->next;
2861 port = port->next;
2864 if (!port)
2865 return -1;
2867 dev = port->dev;
2868 *lastp = port->next;
2869 usb_attach(port, NULL);
2870 dev->handle_destroy(dev);
2871 port->next = free_usb_ports;
2872 free_usb_ports = port;
2873 return 0;
2876 static int usb_device_del(const char *devname)
2878 int bus_num, addr;
2879 const char *p;
2881 if (strstart(devname, "host:", &p))
2882 return usb_host_device_close(p);
2884 if (!used_usb_ports)
2885 return -1;
2887 p = strchr(devname, '.');
2888 if (!p)
2889 return -1;
2890 bus_num = strtoul(devname, NULL, 0);
2891 addr = strtoul(p + 1, NULL, 0);
2893 return usb_device_del_addr(bus_num, addr);
2896 void do_usb_add(Monitor *mon, const char *devname)
2898 usb_device_add(devname, 1);
2901 void do_usb_del(Monitor *mon, const char *devname)
2903 usb_device_del(devname);
2906 void usb_info(Monitor *mon)
2908 USBDevice *dev;
2909 USBPort *port;
2910 const char *speed_str;
2912 if (!usb_enabled) {
2913 monitor_printf(mon, "USB support not enabled\n");
2914 return;
2917 for (port = used_usb_ports; port; port = port->next) {
2918 dev = port->dev;
2919 if (!dev)
2920 continue;
2921 switch(dev->speed) {
2922 case USB_SPEED_LOW:
2923 speed_str = "1.5";
2924 break;
2925 case USB_SPEED_FULL:
2926 speed_str = "12";
2927 break;
2928 case USB_SPEED_HIGH:
2929 speed_str = "480";
2930 break;
2931 default:
2932 speed_str = "?";
2933 break;
2935 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2936 0, dev->addr, speed_str, dev->devname);
2940 /***********************************************************/
2941 /* PCMCIA/Cardbus */
2943 static struct pcmcia_socket_entry_s {
2944 struct pcmcia_socket_s *socket;
2945 struct pcmcia_socket_entry_s *next;
2946 } *pcmcia_sockets = 0;
2948 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2950 struct pcmcia_socket_entry_s *entry;
2952 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2953 entry->socket = socket;
2954 entry->next = pcmcia_sockets;
2955 pcmcia_sockets = entry;
2958 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2960 struct pcmcia_socket_entry_s *entry, **ptr;
2962 ptr = &pcmcia_sockets;
2963 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2964 if (entry->socket == socket) {
2965 *ptr = entry->next;
2966 qemu_free(entry);
2970 void pcmcia_info(Monitor *mon)
2972 struct pcmcia_socket_entry_s *iter;
2974 if (!pcmcia_sockets)
2975 monitor_printf(mon, "No PCMCIA sockets\n");
2977 for (iter = pcmcia_sockets; iter; iter = iter->next)
2978 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2979 iter->socket->attached ? iter->socket->card_string :
2980 "Empty");
2983 /***********************************************************/
2984 /* register display */
2986 struct DisplayAllocator default_allocator = {
2987 defaultallocator_create_displaysurface,
2988 defaultallocator_resize_displaysurface,
2989 defaultallocator_free_displaysurface
2992 void register_displaystate(DisplayState *ds)
2994 DisplayState **s;
2995 s = &display_state;
2996 while (*s != NULL)
2997 s = &(*s)->next;
2998 ds->next = NULL;
2999 *s = ds;
3002 DisplayState *get_displaystate(void)
3004 return display_state;
3007 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
3009 if(ds->allocator == &default_allocator) ds->allocator = da;
3010 return ds->allocator;
3013 /* dumb display */
3015 static void dumb_display_init(void)
3017 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
3018 ds->allocator = &default_allocator;
3019 ds->surface = qemu_create_displaysurface(ds, 640, 480);
3020 register_displaystate(ds);
3023 /***********************************************************/
3024 /* I/O handling */
3026 typedef struct IOHandlerRecord {
3027 int fd;
3028 IOCanRWHandler *fd_read_poll;
3029 IOHandler *fd_read;
3030 IOHandler *fd_write;
3031 int deleted;
3032 void *opaque;
3033 /* temporary data */
3034 struct pollfd *ufd;
3035 struct IOHandlerRecord *next;
3036 } IOHandlerRecord;
3038 static IOHandlerRecord *first_io_handler;
3040 /* XXX: fd_read_poll should be suppressed, but an API change is
3041 necessary in the character devices to suppress fd_can_read(). */
3042 int qemu_set_fd_handler2(int fd,
3043 IOCanRWHandler *fd_read_poll,
3044 IOHandler *fd_read,
3045 IOHandler *fd_write,
3046 void *opaque)
3048 IOHandlerRecord **pioh, *ioh;
3050 if (!fd_read && !fd_write) {
3051 pioh = &first_io_handler;
3052 for(;;) {
3053 ioh = *pioh;
3054 if (ioh == NULL)
3055 break;
3056 if (ioh->fd == fd) {
3057 ioh->deleted = 1;
3058 break;
3060 pioh = &ioh->next;
3062 } else {
3063 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3064 if (ioh->fd == fd)
3065 goto found;
3067 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3068 ioh->next = first_io_handler;
3069 first_io_handler = ioh;
3070 found:
3071 ioh->fd = fd;
3072 ioh->fd_read_poll = fd_read_poll;
3073 ioh->fd_read = fd_read;
3074 ioh->fd_write = fd_write;
3075 ioh->opaque = opaque;
3076 ioh->deleted = 0;
3078 main_loop_break();
3079 return 0;
3082 int qemu_set_fd_handler(int fd,
3083 IOHandler *fd_read,
3084 IOHandler *fd_write,
3085 void *opaque)
3087 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3090 #ifdef _WIN32
3091 /***********************************************************/
3092 /* Polling handling */
3094 typedef struct PollingEntry {
3095 PollingFunc *func;
3096 void *opaque;
3097 struct PollingEntry *next;
3098 } PollingEntry;
3100 static PollingEntry *first_polling_entry;
3102 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3104 PollingEntry **ppe, *pe;
3105 pe = qemu_mallocz(sizeof(PollingEntry));
3106 pe->func = func;
3107 pe->opaque = opaque;
3108 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3109 *ppe = pe;
3110 return 0;
3113 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3115 PollingEntry **ppe, *pe;
3116 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3117 pe = *ppe;
3118 if (pe->func == func && pe->opaque == opaque) {
3119 *ppe = pe->next;
3120 qemu_free(pe);
3121 break;
3126 /***********************************************************/
3127 /* Wait objects support */
3128 typedef struct WaitObjects {
3129 int num;
3130 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3131 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3132 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3133 } WaitObjects;
3135 static WaitObjects wait_objects = {0};
3137 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3139 WaitObjects *w = &wait_objects;
3141 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3142 return -1;
3143 w->events[w->num] = handle;
3144 w->func[w->num] = func;
3145 w->opaque[w->num] = opaque;
3146 w->num++;
3147 return 0;
3150 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3152 int i, found;
3153 WaitObjects *w = &wait_objects;
3155 found = 0;
3156 for (i = 0; i < w->num; i++) {
3157 if (w->events[i] == handle)
3158 found = 1;
3159 if (found) {
3160 w->events[i] = w->events[i + 1];
3161 w->func[i] = w->func[i + 1];
3162 w->opaque[i] = w->opaque[i + 1];
3165 if (found)
3166 w->num--;
3168 #endif
3170 /***********************************************************/
3171 /* ram save/restore */
3173 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3175 int v;
3177 v = qemu_get_byte(f);
3178 switch(v) {
3179 case 0:
3180 if (qemu_get_buffer(f, buf, len) != len)
3181 return -EIO;
3182 break;
3183 case 1:
3184 v = qemu_get_byte(f);
3185 memset(buf, v, len);
3186 break;
3187 default:
3188 return -EINVAL;
3191 if (qemu_file_has_error(f))
3192 return -EIO;
3194 return 0;
3197 static int ram_load_v1(QEMUFile *f, void *opaque)
3199 int ret;
3200 ram_addr_t i;
3202 if (qemu_get_be32(f) != last_ram_offset)
3203 return -EINVAL;
3204 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3205 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3206 continue;
3207 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3208 if (ret)
3209 return ret;
3211 return 0;
3214 #define BDRV_HASH_BLOCK_SIZE 1024
3215 #define IOBUF_SIZE 4096
3216 #define RAM_CBLOCK_MAGIC 0xfabe
3218 typedef struct RamDecompressState {
3219 z_stream zstream;
3220 QEMUFile *f;
3221 uint8_t buf[IOBUF_SIZE];
3222 } RamDecompressState;
3224 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3226 int ret;
3227 memset(s, 0, sizeof(*s));
3228 s->f = f;
3229 ret = inflateInit(&s->zstream);
3230 if (ret != Z_OK)
3231 return -1;
3232 return 0;
3235 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3237 int ret, clen;
3239 s->zstream.avail_out = len;
3240 s->zstream.next_out = buf;
3241 while (s->zstream.avail_out > 0) {
3242 if (s->zstream.avail_in == 0) {
3243 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3244 return -1;
3245 clen = qemu_get_be16(s->f);
3246 if (clen > IOBUF_SIZE)
3247 return -1;
3248 qemu_get_buffer(s->f, s->buf, clen);
3249 s->zstream.avail_in = clen;
3250 s->zstream.next_in = s->buf;
3252 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3253 if (ret != Z_OK && ret != Z_STREAM_END) {
3254 return -1;
3257 return 0;
3260 static void ram_decompress_close(RamDecompressState *s)
3262 inflateEnd(&s->zstream);
3265 #define RAM_SAVE_FLAG_FULL 0x01
3266 #define RAM_SAVE_FLAG_COMPRESS 0x02
3267 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3268 #define RAM_SAVE_FLAG_PAGE 0x08
3269 #define RAM_SAVE_FLAG_EOS 0x10
3271 static int is_dup_page(uint8_t *page, uint8_t ch)
3273 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3274 uint32_t *array = (uint32_t *)page;
3275 int i;
3277 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3278 if (array[i] != val)
3279 return 0;
3282 return 1;
3285 static int ram_save_block(QEMUFile *f)
3287 static ram_addr_t current_addr = 0;
3288 ram_addr_t saved_addr = current_addr;
3289 ram_addr_t addr = 0;
3290 int found = 0;
3292 while (addr < last_ram_offset) {
3293 if (kvm_enabled() && current_addr == 0) {
3294 int r;
3295 r = kvm_update_dirty_pages_log();
3296 if (r) {
3297 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3298 qemu_file_set_error(f);
3299 return 0;
3302 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3303 uint8_t *p;
3305 cpu_physical_memory_reset_dirty(current_addr,
3306 current_addr + TARGET_PAGE_SIZE,
3307 MIGRATION_DIRTY_FLAG);
3309 p = qemu_get_ram_ptr(current_addr);
3311 if (is_dup_page(p, *p)) {
3312 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3313 qemu_put_byte(f, *p);
3314 } else {
3315 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3316 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3319 found = 1;
3320 break;
3322 addr += TARGET_PAGE_SIZE;
3323 current_addr = (saved_addr + addr) % last_ram_offset;
3326 return found;
3329 static ram_addr_t ram_save_threshold = 10;
3331 static ram_addr_t ram_save_remaining(void)
3333 ram_addr_t addr;
3334 ram_addr_t count = 0;
3336 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3337 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3338 count++;
3341 return count;
3344 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3346 ram_addr_t addr;
3348 if (stage == 1) {
3349 /* Make sure all dirty bits are set */
3350 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3351 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3352 cpu_physical_memory_set_dirty(addr);
3355 /* Enable dirty memory tracking */
3356 cpu_physical_memory_set_dirty_tracking(1);
3358 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3361 while (!qemu_file_rate_limit(f)) {
3362 int ret;
3364 ret = ram_save_block(f);
3365 if (ret == 0) /* no more blocks */
3366 break;
3369 /* try transferring iterative blocks of memory */
3371 if (stage == 3) {
3373 /* flush all remaining blocks regardless of rate limiting */
3374 while (ram_save_block(f) != 0);
3375 cpu_physical_memory_set_dirty_tracking(0);
3378 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3380 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3383 static int ram_load_dead(QEMUFile *f, void *opaque)
3385 RamDecompressState s1, *s = &s1;
3386 uint8_t buf[10];
3387 ram_addr_t i;
3389 if (ram_decompress_open(s, f) < 0)
3390 return -EINVAL;
3391 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3392 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3393 continue;
3394 if (ram_decompress_buf(s, buf, 1) < 0) {
3395 fprintf(stderr, "Error while reading ram block header\n");
3396 goto error;
3398 if (buf[0] == 0) {
3399 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3400 BDRV_HASH_BLOCK_SIZE) < 0) {
3401 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3402 goto error;
3404 } else {
3405 error:
3406 printf("Error block header\n");
3407 return -EINVAL;
3410 ram_decompress_close(s);
3412 return 0;
3415 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3417 ram_addr_t addr;
3418 int flags;
3420 if (version_id == 1)
3421 return ram_load_v1(f, opaque);
3423 if (version_id == 2) {
3424 if (qemu_get_be32(f) != last_ram_offset)
3425 return -EINVAL;
3426 return ram_load_dead(f, opaque);
3429 if (version_id != 3)
3430 return -EINVAL;
3432 do {
3433 addr = qemu_get_be64(f);
3435 flags = addr & ~TARGET_PAGE_MASK;
3436 addr &= TARGET_PAGE_MASK;
3438 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3439 if (addr != last_ram_offset)
3440 return -EINVAL;
3443 if (flags & RAM_SAVE_FLAG_FULL) {
3444 if (ram_load_dead(f, opaque) < 0)
3445 return -EINVAL;
3448 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3449 uint8_t ch = qemu_get_byte(f);
3450 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3451 } else if (flags & RAM_SAVE_FLAG_PAGE)
3452 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3453 } while (!(flags & RAM_SAVE_FLAG_EOS));
3455 return 0;
3458 void qemu_service_io(void)
3460 CPUState *env = cpu_single_env;
3461 if (env) {
3462 cpu_exit(env);
3463 #ifdef CONFIG_KQEMU
3464 if (env->kqemu_enabled) {
3465 kqemu_cpu_interrupt(env);
3467 #endif
3471 /***********************************************************/
3472 /* bottom halves (can be seen as timers which expire ASAP) */
3474 struct QEMUBH {
3475 QEMUBHFunc *cb;
3476 void *opaque;
3477 int scheduled;
3478 int idle;
3479 int deleted;
3480 QEMUBH *next;
3483 static QEMUBH *first_bh = NULL;
3485 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3487 QEMUBH *bh;
3488 bh = qemu_mallocz(sizeof(QEMUBH));
3489 bh->cb = cb;
3490 bh->opaque = opaque;
3491 bh->next = first_bh;
3492 first_bh = bh;
3493 return bh;
3496 int qemu_bh_poll(void)
3498 QEMUBH *bh, **bhp;
3499 int ret;
3501 ret = 0;
3502 for (bh = first_bh; bh; bh = bh->next) {
3503 if (!bh->deleted && bh->scheduled) {
3504 bh->scheduled = 0;
3505 if (!bh->idle)
3506 ret = 1;
3507 bh->idle = 0;
3508 bh->cb(bh->opaque);
3512 /* remove deleted bhs */
3513 bhp = &first_bh;
3514 while (*bhp) {
3515 bh = *bhp;
3516 if (bh->deleted) {
3517 *bhp = bh->next;
3518 qemu_free(bh);
3519 } else
3520 bhp = &bh->next;
3523 return ret;
3526 void qemu_bh_schedule_idle(QEMUBH *bh)
3528 if (bh->scheduled)
3529 return;
3530 bh->scheduled = 1;
3531 bh->idle = 1;
3534 void qemu_bh_schedule(QEMUBH *bh)
3536 CPUState *env = cpu_single_env;
3537 if (bh->scheduled)
3538 return;
3539 bh->scheduled = 1;
3540 bh->idle = 0;
3541 /* stop the currently executing CPU to execute the BH ASAP */
3542 if (env) {
3543 cpu_exit(env);
3545 main_loop_break();
3548 void qemu_bh_cancel(QEMUBH *bh)
3550 bh->scheduled = 0;
3553 void qemu_bh_delete(QEMUBH *bh)
3555 bh->scheduled = 0;
3556 bh->deleted = 1;
3559 static void qemu_bh_update_timeout(int *timeout)
3561 QEMUBH *bh;
3563 for (bh = first_bh; bh; bh = bh->next) {
3564 if (!bh->deleted && bh->scheduled) {
3565 if (bh->idle) {
3566 /* idle bottom halves will be polled at least
3567 * every 10ms */
3568 *timeout = MIN(10, *timeout);
3569 } else {
3570 /* non-idle bottom halves will be executed
3571 * immediately */
3572 *timeout = 0;
3573 break;
3579 /***********************************************************/
3580 /* machine registration */
3582 static QEMUMachine *first_machine = NULL;
3583 QEMUMachine *current_machine = NULL;
3585 int qemu_register_machine(QEMUMachine *m)
3587 QEMUMachine **pm;
3588 pm = &first_machine;
3589 while (*pm != NULL)
3590 pm = &(*pm)->next;
3591 m->next = NULL;
3592 *pm = m;
3593 return 0;
3596 static QEMUMachine *find_machine(const char *name)
3598 QEMUMachine *m;
3600 for(m = first_machine; m != NULL; m = m->next) {
3601 if (!strcmp(m->name, name))
3602 return m;
3604 return NULL;
3607 /***********************************************************/
3608 /* main execution loop */
3610 static void gui_update(void *opaque)
3612 uint64_t interval = GUI_REFRESH_INTERVAL;
3613 DisplayState *ds = opaque;
3614 DisplayChangeListener *dcl = ds->listeners;
3616 dpy_refresh(ds);
3618 while (dcl != NULL) {
3619 if (dcl->gui_timer_interval &&
3620 dcl->gui_timer_interval < interval)
3621 interval = dcl->gui_timer_interval;
3622 dcl = dcl->next;
3624 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3627 static void nographic_update(void *opaque)
3629 uint64_t interval = GUI_REFRESH_INTERVAL;
3631 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3634 struct vm_change_state_entry {
3635 VMChangeStateHandler *cb;
3636 void *opaque;
3637 LIST_ENTRY (vm_change_state_entry) entries;
3640 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3642 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3643 void *opaque)
3645 VMChangeStateEntry *e;
3647 e = qemu_mallocz(sizeof (*e));
3649 e->cb = cb;
3650 e->opaque = opaque;
3651 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3652 return e;
3655 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3657 LIST_REMOVE (e, entries);
3658 qemu_free (e);
3661 static void vm_state_notify(int running, int reason)
3663 VMChangeStateEntry *e;
3665 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3666 e->cb(e->opaque, running, reason);
3670 void vm_start(void)
3672 if (!vm_running) {
3673 cpu_enable_ticks();
3674 vm_running = 1;
3675 vm_state_notify(1, 0);
3676 if (kvm_enabled())
3677 qemu_kvm_resume_all_threads();
3678 qemu_rearm_alarm_timer(alarm_timer);
3682 void vm_stop(int reason)
3684 if (vm_running) {
3685 cpu_disable_ticks();
3686 vm_running = 0;
3687 if (kvm_enabled())
3688 qemu_kvm_pause_all_threads();
3689 vm_state_notify(0, reason);
3693 /* reset/shutdown handler */
3695 typedef struct QEMUResetEntry {
3696 QEMUResetHandler *func;
3697 void *opaque;
3698 struct QEMUResetEntry *next;
3699 } QEMUResetEntry;
3701 static QEMUResetEntry *first_reset_entry;
3702 static int reset_requested;
3703 static int shutdown_requested;
3704 static int powerdown_requested;
3706 int qemu_shutdown_requested(void)
3708 int r = shutdown_requested;
3709 shutdown_requested = 0;
3710 return r;
3713 int qemu_reset_requested(void)
3715 int r = reset_requested;
3716 reset_requested = 0;
3717 return r;
3720 int qemu_powerdown_requested(void)
3722 int r = powerdown_requested;
3723 powerdown_requested = 0;
3724 return r;
3727 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3729 QEMUResetEntry **pre, *re;
3731 pre = &first_reset_entry;
3732 while (*pre != NULL)
3733 pre = &(*pre)->next;
3734 re = qemu_mallocz(sizeof(QEMUResetEntry));
3735 re->func = func;
3736 re->opaque = opaque;
3737 re->next = NULL;
3738 *pre = re;
3741 void qemu_system_reset(void)
3743 QEMUResetEntry *re;
3745 /* reset all devices */
3746 for(re = first_reset_entry; re != NULL; re = re->next) {
3747 re->func(re->opaque);
3749 if (kvm_enabled())
3750 kvm_sync_vcpus();
3753 void qemu_system_reset_request(void)
3755 if (no_reboot) {
3756 shutdown_requested = 1;
3757 } else {
3758 reset_requested = 1;
3760 if (cpu_single_env) {
3761 qemu_kvm_cpu_stop(cpu_single_env);
3762 cpu_exit(cpu_single_env);
3766 void qemu_system_shutdown_request(void)
3768 shutdown_requested = 1;
3769 if (cpu_single_env)
3770 cpu_exit(cpu_single_env);
3773 void qemu_system_powerdown_request(void)
3775 powerdown_requested = 1;
3776 if (cpu_single_env)
3777 cpu_exit(cpu_single_env);
3780 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3781 struct timeval *tv)
3783 int ret;
3785 /* KVM holds a mutex while QEMU code is running, we need hooks to
3786 release the mutex whenever QEMU code sleeps. */
3788 kvm_sleep_begin();
3790 ret = select(max_fd, rfds, wfds, xfds, tv);
3792 kvm_sleep_end();
3794 return ret;
3797 #ifdef _WIN32
3798 static void host_main_loop_wait(int *timeout)
3800 int ret, ret2, i;
3801 PollingEntry *pe;
3804 /* XXX: need to suppress polling by better using win32 events */
3805 ret = 0;
3806 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3807 ret |= pe->func(pe->opaque);
3809 if (ret == 0) {
3810 int err;
3811 WaitObjects *w = &wait_objects;
3813 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3814 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3815 if (w->func[ret - WAIT_OBJECT_0])
3816 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3818 /* Check for additional signaled events */
3819 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3821 /* Check if event is signaled */
3822 ret2 = WaitForSingleObject(w->events[i], 0);
3823 if(ret2 == WAIT_OBJECT_0) {
3824 if (w->func[i])
3825 w->func[i](w->opaque[i]);
3826 } else if (ret2 == WAIT_TIMEOUT) {
3827 } else {
3828 err = GetLastError();
3829 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3832 } else if (ret == WAIT_TIMEOUT) {
3833 } else {
3834 err = GetLastError();
3835 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3839 *timeout = 0;
3841 #else
3842 static void host_main_loop_wait(int *timeout)
3845 #endif
3847 void main_loop_wait(int timeout)
3849 IOHandlerRecord *ioh;
3850 fd_set rfds, wfds, xfds;
3851 int ret, nfds;
3852 struct timeval tv;
3854 qemu_bh_update_timeout(&timeout);
3856 host_main_loop_wait(&timeout);
3858 /* poll any events */
3859 /* XXX: separate device handlers from system ones */
3860 nfds = -1;
3861 FD_ZERO(&rfds);
3862 FD_ZERO(&wfds);
3863 FD_ZERO(&xfds);
3864 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3865 if (ioh->deleted)
3866 continue;
3867 if (ioh->fd_read &&
3868 (!ioh->fd_read_poll ||
3869 ioh->fd_read_poll(ioh->opaque) != 0)) {
3870 FD_SET(ioh->fd, &rfds);
3871 if (ioh->fd > nfds)
3872 nfds = ioh->fd;
3874 if (ioh->fd_write) {
3875 FD_SET(ioh->fd, &wfds);
3876 if (ioh->fd > nfds)
3877 nfds = ioh->fd;
3881 tv.tv_sec = timeout / 1000;
3882 tv.tv_usec = (timeout % 1000) * 1000;
3884 #if defined(CONFIG_SLIRP)
3885 if (slirp_is_inited()) {
3886 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3888 #endif
3889 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3890 if (ret > 0) {
3891 IOHandlerRecord **pioh;
3893 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3894 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3895 ioh->fd_read(ioh->opaque);
3896 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3897 FD_CLR(ioh->fd, &rfds);
3899 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3900 ioh->fd_write(ioh->opaque);
3904 /* remove deleted IO handlers */
3905 pioh = &first_io_handler;
3906 while (*pioh) {
3907 ioh = *pioh;
3908 if (ioh->deleted) {
3909 *pioh = ioh->next;
3910 qemu_free(ioh);
3911 } else
3912 pioh = &ioh->next;
3915 #if defined(CONFIG_SLIRP)
3916 if (slirp_is_inited()) {
3917 if (ret < 0) {
3918 FD_ZERO(&rfds);
3919 FD_ZERO(&wfds);
3920 FD_ZERO(&xfds);
3922 slirp_select_poll(&rfds, &wfds, &xfds);
3924 #endif
3926 /* vm time timers */
3927 if (vm_running && (!cur_cpu
3928 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3929 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3930 qemu_get_clock(vm_clock));
3932 /* real time timers */
3933 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3934 qemu_get_clock(rt_clock));
3936 /* Check bottom-halves last in case any of the earlier events triggered
3937 them. */
3938 qemu_bh_poll();
3942 static int main_loop(void)
3944 int ret, timeout;
3945 #ifdef CONFIG_PROFILER
3946 int64_t ti;
3947 #endif
3948 CPUState *env;
3951 if (kvm_enabled()) {
3952 kvm_main_loop();
3953 cpu_disable_ticks();
3954 return 0;
3957 cur_cpu = first_cpu;
3958 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3959 for(;;) {
3960 if (vm_running) {
3962 for(;;) {
3963 /* get next cpu */
3964 env = next_cpu;
3965 #ifdef CONFIG_PROFILER
3966 ti = profile_getclock();
3967 #endif
3968 if (use_icount) {
3969 int64_t count;
3970 int decr;
3971 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3972 env->icount_decr.u16.low = 0;
3973 env->icount_extra = 0;
3974 count = qemu_next_deadline();
3975 count = (count + (1 << icount_time_shift) - 1)
3976 >> icount_time_shift;
3977 qemu_icount += count;
3978 decr = (count > 0xffff) ? 0xffff : count;
3979 count -= decr;
3980 env->icount_decr.u16.low = decr;
3981 env->icount_extra = count;
3983 ret = cpu_exec(env);
3984 #ifdef CONFIG_PROFILER
3985 qemu_time += profile_getclock() - ti;
3986 #endif
3987 if (use_icount) {
3988 /* Fold pending instructions back into the
3989 instruction counter, and clear the interrupt flag. */
3990 qemu_icount -= (env->icount_decr.u16.low
3991 + env->icount_extra);
3992 env->icount_decr.u32 = 0;
3993 env->icount_extra = 0;
3995 next_cpu = env->next_cpu ?: first_cpu;
3996 if (event_pending && likely(ret != EXCP_DEBUG)) {
3997 ret = EXCP_INTERRUPT;
3998 event_pending = 0;
3999 break;
4001 if (ret == EXCP_HLT) {
4002 /* Give the next CPU a chance to run. */
4003 cur_cpu = env;
4004 continue;
4006 if (ret != EXCP_HALTED)
4007 break;
4008 /* all CPUs are halted ? */
4009 if (env == cur_cpu)
4010 break;
4012 cur_cpu = env;
4014 if (shutdown_requested) {
4015 ret = EXCP_INTERRUPT;
4016 if (no_shutdown) {
4017 vm_stop(0);
4018 no_shutdown = 0;
4020 else
4021 break;
4023 if (reset_requested) {
4024 reset_requested = 0;
4025 qemu_system_reset();
4026 ret = EXCP_INTERRUPT;
4028 if (powerdown_requested) {
4029 powerdown_requested = 0;
4030 qemu_system_powerdown();
4031 ret = EXCP_INTERRUPT;
4033 #ifdef CONFIG_GDBSTUB
4034 if (unlikely(ret == EXCP_DEBUG)) {
4035 gdb_set_stop_cpu(cur_cpu);
4036 vm_stop(EXCP_DEBUG);
4038 #endif
4039 /* If all cpus are halted then wait until the next IRQ */
4040 /* XXX: use timeout computed from timers */
4041 if (ret == EXCP_HALTED) {
4042 if (use_icount) {
4043 int64_t add;
4044 int64_t delta;
4045 /* Advance virtual time to the next event. */
4046 if (use_icount == 1) {
4047 /* When not using an adaptive execution frequency
4048 we tend to get badly out of sync with real time,
4049 so just delay for a reasonable amount of time. */
4050 delta = 0;
4051 } else {
4052 delta = cpu_get_icount() - cpu_get_clock();
4054 if (delta > 0) {
4055 /* If virtual time is ahead of real time then just
4056 wait for IO. */
4057 timeout = (delta / 1000000) + 1;
4058 } else {
4059 /* Wait for either IO to occur or the next
4060 timer event. */
4061 add = qemu_next_deadline();
4062 /* We advance the timer before checking for IO.
4063 Limit the amount we advance so that early IO
4064 activity won't get the guest too far ahead. */
4065 if (add > 10000000)
4066 add = 10000000;
4067 delta += add;
4068 add = (add + (1 << icount_time_shift) - 1)
4069 >> icount_time_shift;
4070 qemu_icount += add;
4071 timeout = delta / 1000000;
4072 if (timeout < 0)
4073 timeout = 0;
4075 } else {
4076 timeout = 5000;
4078 } else {
4079 timeout = 0;
4081 } else {
4082 if (shutdown_requested) {
4083 ret = EXCP_INTERRUPT;
4084 break;
4086 timeout = 5000;
4088 #ifdef CONFIG_PROFILER
4089 ti = profile_getclock();
4090 #endif
4091 main_loop_wait(timeout);
4092 #ifdef CONFIG_PROFILER
4093 dev_time += profile_getclock() - ti;
4094 #endif
4096 cpu_disable_ticks();
4097 return ret;
4100 static void version(void)
4102 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4105 static void help(int exitcode)
4107 version();
4108 printf("usage: %s [options] [disk_image]\n"
4109 "\n"
4110 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4111 "\n"
4112 #define DEF(option, opt_arg, opt_enum, opt_help) \
4113 opt_help
4114 #define DEFHEADING(text) stringify(text) "\n"
4115 #include "qemu-options.h"
4116 #undef DEF
4117 #undef DEFHEADING
4118 #undef GEN_DOCS
4119 "\n"
4120 "During emulation, the following keys are useful:\n"
4121 "ctrl-alt-f toggle full screen\n"
4122 "ctrl-alt-n switch to virtual console 'n'\n"
4123 "ctrl-alt toggle mouse and keyboard grab\n"
4124 "\n"
4125 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4127 "qemu",
4128 DEFAULT_RAM_SIZE,
4129 #ifndef _WIN32
4130 DEFAULT_NETWORK_SCRIPT,
4131 DEFAULT_NETWORK_DOWN_SCRIPT,
4132 #endif
4133 DEFAULT_GDBSTUB_PORT,
4134 "/tmp/qemu.log");
4135 exit(exitcode);
4138 #define HAS_ARG 0x0001
4140 enum {
4141 #define DEF(option, opt_arg, opt_enum, opt_help) \
4142 opt_enum,
4143 #define DEFHEADING(text)
4144 #include "qemu-options.h"
4145 #undef DEF
4146 #undef DEFHEADING
4147 #undef GEN_DOCS
4150 typedef struct QEMUOption {
4151 const char *name;
4152 int flags;
4153 int index;
4154 } QEMUOption;
4156 static const QEMUOption qemu_options[] = {
4157 { "h", 0, QEMU_OPTION_h },
4158 #define DEF(option, opt_arg, opt_enum, opt_help) \
4159 { option, opt_arg, opt_enum },
4160 #define DEFHEADING(text)
4161 #include "qemu-options.h"
4162 #undef DEF
4163 #undef DEFHEADING
4164 #undef GEN_DOCS
4165 { NULL },
4168 #ifdef HAS_AUDIO
4169 struct soundhw soundhw[] = {
4170 #ifdef HAS_AUDIO_CHOICE
4171 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4173 "pcspk",
4174 "PC speaker",
4177 { .init_isa = pcspk_audio_init }
4179 #endif
4181 #ifdef CONFIG_SB16
4183 "sb16",
4184 "Creative Sound Blaster 16",
4187 { .init_isa = SB16_init }
4189 #endif
4191 #ifdef CONFIG_CS4231A
4193 "cs4231a",
4194 "CS4231A",
4197 { .init_isa = cs4231a_init }
4199 #endif
4201 #ifdef CONFIG_ADLIB
4203 "adlib",
4204 #ifdef HAS_YMF262
4205 "Yamaha YMF262 (OPL3)",
4206 #else
4207 "Yamaha YM3812 (OPL2)",
4208 #endif
4211 { .init_isa = Adlib_init }
4213 #endif
4215 #ifdef CONFIG_GUS
4217 "gus",
4218 "Gravis Ultrasound GF1",
4221 { .init_isa = GUS_init }
4223 #endif
4225 #ifdef CONFIG_AC97
4227 "ac97",
4228 "Intel 82801AA AC97 Audio",
4231 { .init_pci = ac97_init }
4233 #endif
4235 #ifdef CONFIG_ES1370
4237 "es1370",
4238 "ENSONIQ AudioPCI ES1370",
4241 { .init_pci = es1370_init }
4243 #endif
4245 #endif /* HAS_AUDIO_CHOICE */
4247 { NULL, NULL, 0, 0, { NULL } }
4250 static void select_soundhw (const char *optarg)
4252 struct soundhw *c;
4254 if (*optarg == '?') {
4255 show_valid_cards:
4257 printf ("Valid sound card names (comma separated):\n");
4258 for (c = soundhw; c->name; ++c) {
4259 printf ("%-11s %s\n", c->name, c->descr);
4261 printf ("\n-soundhw all will enable all of the above\n");
4262 exit (*optarg != '?');
4264 else {
4265 size_t l;
4266 const char *p;
4267 char *e;
4268 int bad_card = 0;
4270 if (!strcmp (optarg, "all")) {
4271 for (c = soundhw; c->name; ++c) {
4272 c->enabled = 1;
4274 return;
4277 p = optarg;
4278 while (*p) {
4279 e = strchr (p, ',');
4280 l = !e ? strlen (p) : (size_t) (e - p);
4282 for (c = soundhw; c->name; ++c) {
4283 if (!strncmp (c->name, p, l)) {
4284 c->enabled = 1;
4285 break;
4289 if (!c->name) {
4290 if (l > 80) {
4291 fprintf (stderr,
4292 "Unknown sound card name (too big to show)\n");
4294 else {
4295 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4296 (int) l, p);
4298 bad_card = 1;
4300 p += l + (e != NULL);
4303 if (bad_card)
4304 goto show_valid_cards;
4307 #endif
4309 static void select_vgahw (const char *p)
4311 const char *opts;
4313 cirrus_vga_enabled = 0;
4314 std_vga_enabled = 0;
4315 vmsvga_enabled = 0;
4316 xenfb_enabled = 0;
4317 if (strstart(p, "std", &opts)) {
4318 std_vga_enabled = 1;
4319 } else if (strstart(p, "cirrus", &opts)) {
4320 cirrus_vga_enabled = 1;
4321 } else if (strstart(p, "vmware", &opts)) {
4322 vmsvga_enabled = 1;
4323 } else if (strstart(p, "xenfb", &opts)) {
4324 xenfb_enabled = 1;
4325 } else if (!strstart(p, "none", &opts)) {
4326 invalid_vga:
4327 fprintf(stderr, "Unknown vga type: %s\n", p);
4328 exit(1);
4330 while (*opts) {
4331 const char *nextopt;
4333 if (strstart(opts, ",retrace=", &nextopt)) {
4334 opts = nextopt;
4335 if (strstart(opts, "dumb", &nextopt))
4336 vga_retrace_method = VGA_RETRACE_DUMB;
4337 else if (strstart(opts, "precise", &nextopt))
4338 vga_retrace_method = VGA_RETRACE_PRECISE;
4339 else goto invalid_vga;
4340 } else goto invalid_vga;
4341 opts = nextopt;
4345 #ifdef _WIN32
4346 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4348 exit(STATUS_CONTROL_C_EXIT);
4349 return TRUE;
4351 #endif
4353 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4355 int ret;
4357 if(strlen(str) != 36)
4358 return -1;
4360 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4361 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4362 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4364 if(ret != 16)
4365 return -1;
4367 #ifdef TARGET_I386
4368 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4369 #endif
4371 return 0;
4374 #define MAX_NET_CLIENTS 32
4376 #ifdef USE_KVM
4378 #define HUGETLBFS_MAGIC 0x958458f6
4380 static long gethugepagesize(const char *path)
4382 struct statfs fs;
4383 int ret;
4385 do {
4386 ret = statfs(path, &fs);
4387 } while (ret != 0 && errno == EINTR);
4389 if (ret != 0) {
4390 perror("statfs");
4391 return 0;
4394 if (fs.f_type != HUGETLBFS_MAGIC)
4395 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4397 return fs.f_bsize;
4400 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4402 char *filename;
4403 void *area;
4404 int fd;
4405 #ifdef MAP_POPULATE
4406 int flags;
4407 #endif
4409 if (!kvm_has_sync_mmu()) {
4410 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4411 return NULL;
4414 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4415 return NULL;
4417 hpagesize = gethugepagesize(path);
4418 if (!hpagesize)
4419 return NULL;
4421 fd = mkstemp(filename);
4422 if (fd < 0) {
4423 perror("mkstemp");
4424 free(filename);
4425 return NULL;
4427 unlink(filename);
4428 free(filename);
4430 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4433 * ftruncate is not supported by hugetlbfs in older
4434 * hosts, so don't bother checking for errors.
4435 * If anything goes wrong with it under other filesystems,
4436 * mmap will fail.
4438 ftruncate(fd, memory);
4440 #ifdef MAP_POPULATE
4441 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4442 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4443 * to sidestep this quirk.
4445 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4446 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4447 #else
4448 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4449 #endif
4450 if (area == MAP_FAILED) {
4451 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4452 close(fd);
4453 return (NULL);
4455 *len = memory;
4456 return area;
4458 #endif
4460 static void *qemu_alloc_physram(unsigned long memory)
4462 void *area = NULL;
4463 #ifdef USE_KVM
4464 unsigned long map_len = memory;
4466 if (mem_path)
4467 area = alloc_mem_area(memory, &map_len, mem_path);
4468 #endif
4469 if (!area)
4470 area = qemu_vmalloc(memory);
4471 #ifdef USE_KVM
4472 if (kvm_setup_guest_memory(area, map_len))
4473 area = NULL;
4474 #endif
4475 return area;
4478 #ifndef _WIN32
4480 static void termsig_handler(int signal)
4482 qemu_system_shutdown_request();
4485 static void termsig_setup(void)
4487 struct sigaction act;
4489 memset(&act, 0, sizeof(act));
4490 act.sa_handler = termsig_handler;
4491 sigaction(SIGINT, &act, NULL);
4492 sigaction(SIGHUP, &act, NULL);
4493 sigaction(SIGTERM, &act, NULL);
4496 #endif
4498 int main(int argc, char **argv, char **envp)
4500 #ifdef CONFIG_GDBSTUB
4501 const char *gdbstub_dev = NULL;
4502 #endif
4503 uint32_t boot_devices_bitmap = 0;
4504 int i;
4505 int snapshot, linux_boot, net_boot;
4506 const char *initrd_filename;
4507 const char *kernel_filename, *kernel_cmdline;
4508 const char *boot_devices = "";
4509 DisplayState *ds;
4510 DisplayChangeListener *dcl;
4511 int cyls, heads, secs, translation;
4512 const char *net_clients[MAX_NET_CLIENTS];
4513 int nb_net_clients;
4514 const char *bt_opts[MAX_BT_CMDLINE];
4515 int nb_bt_opts;
4516 int hda_index;
4517 int optind;
4518 const char *r, *optarg;
4519 CharDriverState *monitor_hd = NULL;
4520 const char *monitor_device;
4521 const char *serial_devices[MAX_SERIAL_PORTS];
4522 int serial_device_index;
4523 const char *parallel_devices[MAX_PARALLEL_PORTS];
4524 int parallel_device_index;
4525 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4526 int virtio_console_index;
4527 const char *loadvm = NULL;
4528 QEMUMachine *machine;
4529 const char *cpu_model;
4530 const char *usb_devices[MAX_USB_CMDLINE];
4531 int usb_devices_index;
4532 #ifndef _WIN32
4533 int fds[2];
4534 #endif
4535 int tb_size;
4536 const char *pid_file = NULL;
4537 const char *incoming = NULL;
4538 #ifndef _WIN32
4539 int fd = 0;
4540 struct passwd *pwd = NULL;
4541 const char *chroot_dir = NULL;
4542 const char *run_as = NULL;
4543 #endif
4544 CPUState *env;
4546 qemu_cache_utils_init(envp);
4548 LIST_INIT (&vm_change_state_head);
4549 #ifndef _WIN32
4551 struct sigaction act;
4552 sigfillset(&act.sa_mask);
4553 act.sa_flags = 0;
4554 act.sa_handler = SIG_IGN;
4555 sigaction(SIGPIPE, &act, NULL);
4557 #else
4558 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4559 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4560 QEMU to run on a single CPU */
4562 HANDLE h;
4563 DWORD mask, smask;
4564 int i;
4565 h = GetCurrentProcess();
4566 if (GetProcessAffinityMask(h, &mask, &smask)) {
4567 for(i = 0; i < 32; i++) {
4568 if (mask & (1 << i))
4569 break;
4571 if (i != 32) {
4572 mask = 1 << i;
4573 SetProcessAffinityMask(h, mask);
4577 #endif
4579 register_machines();
4580 machine = first_machine;
4581 cpu_model = NULL;
4582 initrd_filename = NULL;
4583 ram_size = 0;
4584 vga_ram_size = VGA_RAM_SIZE;
4585 snapshot = 0;
4586 nographic = 0;
4587 curses = 0;
4588 kernel_filename = NULL;
4589 kernel_cmdline = "";
4590 cyls = heads = secs = 0;
4591 translation = BIOS_ATA_TRANSLATION_AUTO;
4592 monitor_device = "vc:80Cx24C";
4594 serial_devices[0] = "vc:80Cx24C";
4595 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4596 serial_devices[i] = NULL;
4597 serial_device_index = 0;
4599 parallel_devices[0] = "vc:80Cx24C";
4600 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4601 parallel_devices[i] = NULL;
4602 parallel_device_index = 0;
4604 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4605 virtio_consoles[i] = NULL;
4606 virtio_console_index = 0;
4608 for (i = 0; i < MAX_NODES; i++) {
4609 node_mem[i] = 0;
4610 node_cpumask[i] = 0;
4613 usb_devices_index = 0;
4614 assigned_devices_index = 0;
4616 nb_net_clients = 0;
4617 nb_bt_opts = 0;
4618 nb_drives = 0;
4619 nb_drives_opt = 0;
4620 nb_numa_nodes = 0;
4621 hda_index = -1;
4623 nb_nics = 0;
4625 tb_size = 0;
4626 autostart= 1;
4628 optind = 1;
4629 for(;;) {
4630 if (optind >= argc)
4631 break;
4632 r = argv[optind];
4633 if (r[0] != '-') {
4634 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4635 } else {
4636 const QEMUOption *popt;
4638 optind++;
4639 /* Treat --foo the same as -foo. */
4640 if (r[1] == '-')
4641 r++;
4642 popt = qemu_options;
4643 for(;;) {
4644 if (!popt->name) {
4645 fprintf(stderr, "%s: invalid option -- '%s'\n",
4646 argv[0], r);
4647 exit(1);
4649 if (!strcmp(popt->name, r + 1))
4650 break;
4651 popt++;
4653 if (popt->flags & HAS_ARG) {
4654 if (optind >= argc) {
4655 fprintf(stderr, "%s: option '%s' requires an argument\n",
4656 argv[0], r);
4657 exit(1);
4659 optarg = argv[optind++];
4660 } else {
4661 optarg = NULL;
4664 switch(popt->index) {
4665 case QEMU_OPTION_M:
4666 machine = find_machine(optarg);
4667 if (!machine) {
4668 QEMUMachine *m;
4669 printf("Supported machines are:\n");
4670 for(m = first_machine; m != NULL; m = m->next) {
4671 printf("%-10s %s%s\n",
4672 m->name, m->desc,
4673 m == first_machine ? " (default)" : "");
4675 exit(*optarg != '?');
4677 break;
4678 case QEMU_OPTION_cpu:
4679 /* hw initialization will check this */
4680 if (*optarg == '?') {
4681 /* XXX: implement xxx_cpu_list for targets that still miss it */
4682 #if defined(cpu_list)
4683 cpu_list(stdout, &fprintf);
4684 #endif
4685 exit(0);
4686 } else {
4687 cpu_model = optarg;
4689 break;
4690 case QEMU_OPTION_initrd:
4691 initrd_filename = optarg;
4692 break;
4693 case QEMU_OPTION_hda:
4694 if (cyls == 0)
4695 hda_index = drive_add(optarg, HD_ALIAS, 0);
4696 else
4697 hda_index = drive_add(optarg, HD_ALIAS
4698 ",cyls=%d,heads=%d,secs=%d%s",
4699 0, cyls, heads, secs,
4700 translation == BIOS_ATA_TRANSLATION_LBA ?
4701 ",trans=lba" :
4702 translation == BIOS_ATA_TRANSLATION_NONE ?
4703 ",trans=none" : "");
4704 break;
4705 case QEMU_OPTION_hdb:
4706 case QEMU_OPTION_hdc:
4707 case QEMU_OPTION_hdd:
4708 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4709 break;
4710 case QEMU_OPTION_drive:
4711 drive_add(NULL, "%s", optarg);
4712 break;
4713 case QEMU_OPTION_mtdblock:
4714 drive_add(optarg, MTD_ALIAS);
4715 break;
4716 case QEMU_OPTION_sd:
4717 drive_add(optarg, SD_ALIAS);
4718 break;
4719 case QEMU_OPTION_pflash:
4720 drive_add(optarg, PFLASH_ALIAS);
4721 break;
4722 case QEMU_OPTION_snapshot:
4723 snapshot = 1;
4724 break;
4725 case QEMU_OPTION_hdachs:
4727 const char *p;
4728 p = optarg;
4729 cyls = strtol(p, (char **)&p, 0);
4730 if (cyls < 1 || cyls > 16383)
4731 goto chs_fail;
4732 if (*p != ',')
4733 goto chs_fail;
4734 p++;
4735 heads = strtol(p, (char **)&p, 0);
4736 if (heads < 1 || heads > 16)
4737 goto chs_fail;
4738 if (*p != ',')
4739 goto chs_fail;
4740 p++;
4741 secs = strtol(p, (char **)&p, 0);
4742 if (secs < 1 || secs > 63)
4743 goto chs_fail;
4744 if (*p == ',') {
4745 p++;
4746 if (!strcmp(p, "none"))
4747 translation = BIOS_ATA_TRANSLATION_NONE;
4748 else if (!strcmp(p, "lba"))
4749 translation = BIOS_ATA_TRANSLATION_LBA;
4750 else if (!strcmp(p, "auto"))
4751 translation = BIOS_ATA_TRANSLATION_AUTO;
4752 else
4753 goto chs_fail;
4754 } else if (*p != '\0') {
4755 chs_fail:
4756 fprintf(stderr, "qemu: invalid physical CHS format\n");
4757 exit(1);
4759 if (hda_index != -1)
4760 snprintf(drives_opt[hda_index].opt,
4761 sizeof(drives_opt[hda_index].opt),
4762 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4763 0, cyls, heads, secs,
4764 translation == BIOS_ATA_TRANSLATION_LBA ?
4765 ",trans=lba" :
4766 translation == BIOS_ATA_TRANSLATION_NONE ?
4767 ",trans=none" : "");
4769 break;
4770 case QEMU_OPTION_numa:
4771 if (nb_numa_nodes >= MAX_NODES) {
4772 fprintf(stderr, "qemu: too many NUMA nodes\n");
4773 exit(1);
4775 numa_add(optarg);
4776 break;
4777 case QEMU_OPTION_nographic:
4778 nographic = 1;
4779 break;
4780 #ifdef CONFIG_CURSES
4781 case QEMU_OPTION_curses:
4782 curses = 1;
4783 break;
4784 #endif
4785 case QEMU_OPTION_portrait:
4786 graphic_rotate = 1;
4787 break;
4788 case QEMU_OPTION_kernel:
4789 kernel_filename = optarg;
4790 break;
4791 case QEMU_OPTION_append:
4792 kernel_cmdline = optarg;
4793 break;
4794 case QEMU_OPTION_cdrom:
4795 drive_add(optarg, CDROM_ALIAS);
4796 break;
4797 case QEMU_OPTION_boot:
4798 boot_devices = optarg;
4799 /* We just do some generic consistency checks */
4801 /* Could easily be extended to 64 devices if needed */
4802 const char *p;
4804 boot_devices_bitmap = 0;
4805 for (p = boot_devices; *p != '\0'; p++) {
4806 /* Allowed boot devices are:
4807 * a b : floppy disk drives
4808 * c ... f : IDE disk drives
4809 * g ... m : machine implementation dependant drives
4810 * n ... p : network devices
4811 * It's up to each machine implementation to check
4812 * if the given boot devices match the actual hardware
4813 * implementation and firmware features.
4815 if (*p < 'a' || *p > 'q') {
4816 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4817 exit(1);
4819 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4820 fprintf(stderr,
4821 "Boot device '%c' was given twice\n",*p);
4822 exit(1);
4824 boot_devices_bitmap |= 1 << (*p - 'a');
4827 break;
4828 case QEMU_OPTION_fda:
4829 case QEMU_OPTION_fdb:
4830 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4831 break;
4832 #ifdef TARGET_I386
4833 case QEMU_OPTION_no_fd_bootchk:
4834 fd_bootchk = 0;
4835 break;
4836 #endif
4837 case QEMU_OPTION_net:
4838 if (nb_net_clients >= MAX_NET_CLIENTS) {
4839 fprintf(stderr, "qemu: too many network clients\n");
4840 exit(1);
4842 net_clients[nb_net_clients] = optarg;
4843 nb_net_clients++;
4844 break;
4845 #ifdef CONFIG_SLIRP
4846 case QEMU_OPTION_tftp:
4847 tftp_prefix = optarg;
4848 break;
4849 case QEMU_OPTION_bootp:
4850 bootp_filename = optarg;
4851 break;
4852 #ifndef _WIN32
4853 case QEMU_OPTION_smb:
4854 net_slirp_smb(optarg);
4855 break;
4856 #endif
4857 case QEMU_OPTION_redir:
4858 net_slirp_redir(NULL, optarg);
4859 break;
4860 #endif
4861 case QEMU_OPTION_bt:
4862 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4863 fprintf(stderr, "qemu: too many bluetooth options\n");
4864 exit(1);
4866 bt_opts[nb_bt_opts++] = optarg;
4867 break;
4868 #ifdef HAS_AUDIO
4869 case QEMU_OPTION_audio_help:
4870 AUD_help ();
4871 exit (0);
4872 break;
4873 case QEMU_OPTION_soundhw:
4874 select_soundhw (optarg);
4875 break;
4876 #endif
4877 case QEMU_OPTION_h:
4878 help(0);
4879 break;
4880 case QEMU_OPTION_version:
4881 version();
4882 exit(0);
4883 break;
4884 case QEMU_OPTION_m: {
4885 uint64_t value;
4886 char *ptr;
4888 value = strtoul(optarg, &ptr, 10);
4889 switch (*ptr) {
4890 case 0: case 'M': case 'm':
4891 value <<= 20;
4892 break;
4893 case 'G': case 'g':
4894 value <<= 30;
4895 break;
4896 default:
4897 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4898 exit(1);
4901 /* On 32-bit hosts, QEMU is limited by virtual address space */
4902 if (value > (2047 << 20)
4903 #ifndef CONFIG_KQEMU
4904 && HOST_LONG_BITS == 32
4905 #endif
4907 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4908 exit(1);
4910 if (value != (uint64_t)(ram_addr_t)value) {
4911 fprintf(stderr, "qemu: ram size too large\n");
4912 exit(1);
4914 ram_size = value;
4915 break;
4917 case QEMU_OPTION_d:
4919 int mask;
4920 const CPULogItem *item;
4922 mask = cpu_str_to_log_mask(optarg);
4923 if (!mask) {
4924 printf("Log items (comma separated):\n");
4925 for(item = cpu_log_items; item->mask != 0; item++) {
4926 printf("%-10s %s\n", item->name, item->help);
4928 exit(1);
4930 cpu_set_log(mask);
4932 break;
4933 #ifdef CONFIG_GDBSTUB
4934 case QEMU_OPTION_s:
4935 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4936 break;
4937 case QEMU_OPTION_gdb:
4938 gdbstub_dev = optarg;
4939 break;
4940 #endif
4941 case QEMU_OPTION_L:
4942 bios_dir = optarg;
4943 break;
4944 case QEMU_OPTION_bios:
4945 bios_name = optarg;
4946 break;
4947 case QEMU_OPTION_singlestep:
4948 singlestep = 1;
4949 break;
4950 case QEMU_OPTION_S:
4951 autostart = 0;
4952 break;
4953 #ifndef _WIN32
4954 case QEMU_OPTION_k:
4955 keyboard_layout = optarg;
4956 break;
4957 #endif
4958 case QEMU_OPTION_localtime:
4959 rtc_utc = 0;
4960 break;
4961 case QEMU_OPTION_vga:
4962 select_vgahw (optarg);
4963 break;
4964 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4965 case QEMU_OPTION_g:
4967 const char *p;
4968 int w, h, depth;
4969 p = optarg;
4970 w = strtol(p, (char **)&p, 10);
4971 if (w <= 0) {
4972 graphic_error:
4973 fprintf(stderr, "qemu: invalid resolution or depth\n");
4974 exit(1);
4976 if (*p != 'x')
4977 goto graphic_error;
4978 p++;
4979 h = strtol(p, (char **)&p, 10);
4980 if (h <= 0)
4981 goto graphic_error;
4982 if (*p == 'x') {
4983 p++;
4984 depth = strtol(p, (char **)&p, 10);
4985 if (depth != 8 && depth != 15 && depth != 16 &&
4986 depth != 24 && depth != 32)
4987 goto graphic_error;
4988 } else if (*p == '\0') {
4989 depth = graphic_depth;
4990 } else {
4991 goto graphic_error;
4994 graphic_width = w;
4995 graphic_height = h;
4996 graphic_depth = depth;
4998 break;
4999 #endif
5000 case QEMU_OPTION_echr:
5002 char *r;
5003 term_escape_char = strtol(optarg, &r, 0);
5004 if (r == optarg)
5005 printf("Bad argument to echr\n");
5006 break;
5008 case QEMU_OPTION_monitor:
5009 monitor_device = optarg;
5010 break;
5011 case QEMU_OPTION_serial:
5012 if (serial_device_index >= MAX_SERIAL_PORTS) {
5013 fprintf(stderr, "qemu: too many serial ports\n");
5014 exit(1);
5016 serial_devices[serial_device_index] = optarg;
5017 serial_device_index++;
5018 break;
5019 case QEMU_OPTION_virtiocon:
5020 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5021 fprintf(stderr, "qemu: too many virtio consoles\n");
5022 exit(1);
5024 virtio_consoles[virtio_console_index] = optarg;
5025 virtio_console_index++;
5026 break;
5027 case QEMU_OPTION_parallel:
5028 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5029 fprintf(stderr, "qemu: too many parallel ports\n");
5030 exit(1);
5032 parallel_devices[parallel_device_index] = optarg;
5033 parallel_device_index++;
5034 break;
5035 case QEMU_OPTION_loadvm:
5036 loadvm = optarg;
5037 break;
5038 case QEMU_OPTION_full_screen:
5039 full_screen = 1;
5040 break;
5041 #ifdef CONFIG_SDL
5042 case QEMU_OPTION_no_frame:
5043 no_frame = 1;
5044 break;
5045 case QEMU_OPTION_alt_grab:
5046 alt_grab = 1;
5047 break;
5048 case QEMU_OPTION_no_quit:
5049 no_quit = 1;
5050 break;
5051 case QEMU_OPTION_sdl:
5052 sdl = 1;
5053 break;
5054 #endif
5055 case QEMU_OPTION_pidfile:
5056 pid_file = optarg;
5057 break;
5058 #ifdef TARGET_I386
5059 case QEMU_OPTION_win2k_hack:
5060 win2k_install_hack = 1;
5061 break;
5062 case QEMU_OPTION_rtc_td_hack:
5063 rtc_td_hack = 1;
5064 break;
5065 case QEMU_OPTION_acpitable:
5066 if(acpi_table_add(optarg) < 0) {
5067 fprintf(stderr, "Wrong acpi table provided\n");
5068 exit(1);
5070 break;
5071 case QEMU_OPTION_smbios:
5072 if(smbios_entry_add(optarg) < 0) {
5073 fprintf(stderr, "Wrong smbios provided\n");
5074 exit(1);
5076 break;
5077 #endif
5078 #ifdef CONFIG_KQEMU
5079 case QEMU_OPTION_no_kqemu:
5080 kqemu_allowed = 0;
5081 break;
5082 case QEMU_OPTION_kernel_kqemu:
5083 kqemu_allowed = 2;
5084 break;
5085 #endif
5086 #ifdef CONFIG_KVM
5087 case QEMU_OPTION_enable_kvm:
5088 kvm_allowed = 1;
5089 #ifdef CONFIG_KQEMU
5090 kqemu_allowed = 0;
5091 #endif
5092 break;
5093 #endif
5094 #ifdef USE_KVM
5095 case QEMU_OPTION_no_kvm:
5096 kvm_allowed = 0;
5097 break;
5098 case QEMU_OPTION_no_kvm_irqchip: {
5099 kvm_irqchip = 0;
5100 kvm_pit = 0;
5101 break;
5103 case QEMU_OPTION_no_kvm_pit: {
5104 kvm_pit = 0;
5105 break;
5107 case QEMU_OPTION_no_kvm_pit_reinjection: {
5108 kvm_pit_reinject = 0;
5109 break;
5111 case QEMU_OPTION_enable_nesting: {
5112 kvm_nested = 1;
5113 break;
5115 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5116 case QEMU_OPTION_pcidevice:
5117 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5118 fprintf(stderr, "Too many assigned devices\n");
5119 exit(1);
5121 assigned_devices[assigned_devices_index] = optarg;
5122 assigned_devices_index++;
5123 break;
5124 #endif
5125 #endif
5126 case QEMU_OPTION_usb:
5127 usb_enabled = 1;
5128 break;
5129 case QEMU_OPTION_usbdevice:
5130 usb_enabled = 1;
5131 if (usb_devices_index >= MAX_USB_CMDLINE) {
5132 fprintf(stderr, "Too many USB devices\n");
5133 exit(1);
5135 usb_devices[usb_devices_index] = optarg;
5136 usb_devices_index++;
5137 break;
5138 case QEMU_OPTION_smp:
5139 smp_cpus = atoi(optarg);
5140 if (smp_cpus < 1) {
5141 fprintf(stderr, "Invalid number of CPUs\n");
5142 exit(1);
5144 break;
5145 case QEMU_OPTION_vnc:
5146 vnc_display = optarg;
5147 break;
5148 #ifdef TARGET_I386
5149 case QEMU_OPTION_no_acpi:
5150 acpi_enabled = 0;
5151 break;
5152 case QEMU_OPTION_no_hpet:
5153 no_hpet = 1;
5154 break;
5155 #endif
5156 case QEMU_OPTION_no_reboot:
5157 no_reboot = 1;
5158 break;
5159 case QEMU_OPTION_no_shutdown:
5160 no_shutdown = 1;
5161 break;
5162 case QEMU_OPTION_show_cursor:
5163 cursor_hide = 0;
5164 break;
5165 case QEMU_OPTION_uuid:
5166 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5167 fprintf(stderr, "Fail to parse UUID string."
5168 " Wrong format.\n");
5169 exit(1);
5171 break;
5172 #ifndef _WIN32
5173 case QEMU_OPTION_daemonize:
5174 daemonize = 1;
5175 break;
5176 #endif
5177 case QEMU_OPTION_option_rom:
5178 if (nb_option_roms >= MAX_OPTION_ROMS) {
5179 fprintf(stderr, "Too many option ROMs\n");
5180 exit(1);
5182 option_rom[nb_option_roms] = optarg;
5183 nb_option_roms++;
5184 break;
5185 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5186 case QEMU_OPTION_semihosting:
5187 semihosting_enabled = 1;
5188 break;
5189 #endif
5190 case QEMU_OPTION_tdf:
5191 time_drift_fix = 1;
5192 break;
5193 case QEMU_OPTION_kvm_shadow_memory:
5194 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5195 break;
5196 case QEMU_OPTION_mempath:
5197 mem_path = optarg;
5198 break;
5199 #ifdef MAP_POPULATE
5200 case QEMU_OPTION_mem_prealloc:
5201 mem_prealloc = !mem_prealloc;
5202 break;
5203 #endif
5204 case QEMU_OPTION_name:
5205 qemu_name = optarg;
5206 break;
5207 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5208 case QEMU_OPTION_prom_env:
5209 if (nb_prom_envs >= MAX_PROM_ENVS) {
5210 fprintf(stderr, "Too many prom variables\n");
5211 exit(1);
5213 prom_envs[nb_prom_envs] = optarg;
5214 nb_prom_envs++;
5215 break;
5216 #endif
5217 #ifdef TARGET_ARM
5218 case QEMU_OPTION_old_param:
5219 old_param = 1;
5220 break;
5221 #endif
5222 case QEMU_OPTION_clock:
5223 configure_alarms(optarg);
5224 break;
5225 case QEMU_OPTION_startdate:
5227 struct tm tm;
5228 time_t rtc_start_date;
5229 if (!strcmp(optarg, "now")) {
5230 rtc_date_offset = -1;
5231 } else {
5232 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5233 &tm.tm_year,
5234 &tm.tm_mon,
5235 &tm.tm_mday,
5236 &tm.tm_hour,
5237 &tm.tm_min,
5238 &tm.tm_sec) == 6) {
5239 /* OK */
5240 } else if (sscanf(optarg, "%d-%d-%d",
5241 &tm.tm_year,
5242 &tm.tm_mon,
5243 &tm.tm_mday) == 3) {
5244 tm.tm_hour = 0;
5245 tm.tm_min = 0;
5246 tm.tm_sec = 0;
5247 } else {
5248 goto date_fail;
5250 tm.tm_year -= 1900;
5251 tm.tm_mon--;
5252 rtc_start_date = mktimegm(&tm);
5253 if (rtc_start_date == -1) {
5254 date_fail:
5255 fprintf(stderr, "Invalid date format. Valid format are:\n"
5256 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5257 exit(1);
5259 rtc_date_offset = time(NULL) - rtc_start_date;
5262 break;
5263 case QEMU_OPTION_tb_size:
5264 tb_size = strtol(optarg, NULL, 0);
5265 if (tb_size < 0)
5266 tb_size = 0;
5267 break;
5268 case QEMU_OPTION_icount:
5269 use_icount = 1;
5270 if (strcmp(optarg, "auto") == 0) {
5271 icount_time_shift = -1;
5272 } else {
5273 icount_time_shift = strtol(optarg, NULL, 0);
5275 break;
5276 case QEMU_OPTION_incoming:
5277 incoming = optarg;
5278 break;
5279 #ifndef _WIN32
5280 case QEMU_OPTION_chroot:
5281 chroot_dir = optarg;
5282 break;
5283 case QEMU_OPTION_runas:
5284 run_as = optarg;
5285 break;
5286 case QEMU_OPTION_nvram:
5287 nvram = optarg;
5288 break;
5289 #endif
5290 #ifdef CONFIG_XEN
5291 case QEMU_OPTION_xen_domid:
5292 xen_domid = atoi(optarg);
5293 break;
5294 case QEMU_OPTION_xen_create:
5295 xen_mode = XEN_CREATE;
5296 break;
5297 case QEMU_OPTION_xen_attach:
5298 xen_mode = XEN_ATTACH;
5299 break;
5300 #endif
5305 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5306 if (kvm_allowed && kqemu_allowed) {
5307 fprintf(stderr,
5308 "You can not enable both KVM and kqemu at the same time\n");
5309 exit(1);
5311 #endif
5313 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5314 if (smp_cpus > machine->max_cpus) {
5315 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5316 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5317 machine->max_cpus);
5318 exit(1);
5321 if (nographic) {
5322 if (serial_device_index == 0)
5323 serial_devices[0] = "stdio";
5324 if (parallel_device_index == 0)
5325 parallel_devices[0] = "null";
5326 if (strncmp(monitor_device, "vc", 2) == 0)
5327 monitor_device = "stdio";
5330 #ifndef _WIN32
5331 if (daemonize) {
5332 pid_t pid;
5334 if (pipe(fds) == -1)
5335 exit(1);
5337 pid = fork();
5338 if (pid > 0) {
5339 uint8_t status;
5340 ssize_t len;
5342 close(fds[1]);
5344 again:
5345 len = read(fds[0], &status, 1);
5346 if (len == -1 && (errno == EINTR))
5347 goto again;
5349 if (len != 1)
5350 exit(1);
5351 else if (status == 1) {
5352 fprintf(stderr, "Could not acquire pidfile\n");
5353 exit(1);
5354 } else
5355 exit(0);
5356 } else if (pid < 0)
5357 exit(1);
5359 setsid();
5361 pid = fork();
5362 if (pid > 0)
5363 exit(0);
5364 else if (pid < 0)
5365 exit(1);
5367 umask(027);
5369 signal(SIGTSTP, SIG_IGN);
5370 signal(SIGTTOU, SIG_IGN);
5371 signal(SIGTTIN, SIG_IGN);
5374 #ifdef USE_KVM
5375 if (kvm_enabled()) {
5376 if (kvm_qemu_init() < 0) {
5377 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5378 #ifdef NO_CPU_EMULATION
5379 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5380 exit(1);
5381 #endif
5382 kvm_allowed = 0;
5385 #endif
5387 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5388 if (daemonize) {
5389 uint8_t status = 1;
5390 write(fds[1], &status, 1);
5391 } else
5392 fprintf(stderr, "Could not acquire pid file\n");
5393 exit(1);
5395 #endif
5397 #ifdef CONFIG_KQEMU
5398 if (smp_cpus > 1)
5399 kqemu_allowed = 0;
5400 #endif
5401 linux_boot = (kernel_filename != NULL);
5402 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5404 if (!linux_boot && *kernel_cmdline != '\0') {
5405 fprintf(stderr, "-append only allowed with -kernel option\n");
5406 exit(1);
5409 if (!linux_boot && initrd_filename != NULL) {
5410 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5411 exit(1);
5414 /* boot to floppy or the default cd if no hard disk defined yet */
5415 if (!boot_devices[0]) {
5416 boot_devices = "cad";
5418 setvbuf(stdout, NULL, _IOLBF, 0);
5420 init_timers();
5421 if (init_timer_alarm() < 0) {
5422 fprintf(stderr, "could not initialize alarm timer\n");
5423 exit(1);
5425 if (use_icount && icount_time_shift < 0) {
5426 use_icount = 2;
5427 /* 125MIPS seems a reasonable initial guess at the guest speed.
5428 It will be corrected fairly quickly anyway. */
5429 icount_time_shift = 3;
5430 init_icount_adjust();
5433 #ifdef _WIN32
5434 socket_init();
5435 #endif
5437 /* init network clients */
5438 if (nb_net_clients == 0) {
5439 /* if no clients, we use a default config */
5440 net_clients[nb_net_clients++] = "nic";
5441 #ifdef CONFIG_SLIRP
5442 net_clients[nb_net_clients++] = "user";
5443 #endif
5446 for(i = 0;i < nb_net_clients; i++) {
5447 if (net_client_parse(net_clients[i]) < 0)
5448 exit(1);
5450 net_client_check();
5452 #ifdef TARGET_I386
5453 /* XXX: this should be moved in the PC machine instantiation code */
5454 if (net_boot != 0) {
5455 int netroms = 0;
5456 for (i = 0; i < nb_nics && i < 4; i++) {
5457 const char *model = nd_table[i].model;
5458 char buf[1024];
5459 if (net_boot & (1 << i)) {
5460 if (model == NULL)
5461 model = "rtl8139";
5462 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5463 if (get_image_size(buf) > 0) {
5464 if (nb_option_roms >= MAX_OPTION_ROMS) {
5465 fprintf(stderr, "Too many option ROMs\n");
5466 exit(1);
5468 option_rom[nb_option_roms] = strdup(buf);
5469 nb_option_roms++;
5470 netroms++;
5474 if (netroms == 0) {
5475 fprintf(stderr, "No valid PXE rom found for network device\n");
5476 exit(1);
5479 #endif
5481 /* init the bluetooth world */
5482 for (i = 0; i < nb_bt_opts; i++)
5483 if (bt_parse(bt_opts[i]))
5484 exit(1);
5486 /* init the memory */
5487 if (ram_size == 0)
5488 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5490 if (kvm_enabled()) {
5491 if (kvm_qemu_create_context() < 0) {
5492 fprintf(stderr, "Could not create KVM context\n");
5493 exit(1);
5497 #ifdef CONFIG_KQEMU
5498 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5499 guest ram allocation. It needs to go away. */
5500 if (kqemu_allowed) {
5501 kqemu_phys_ram_size = ram_size + VGA_RAM_SIZE + 4 * 1024 * 1024;
5502 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5503 if (!kqemu_phys_ram_base) {
5504 fprintf(stderr, "Could not allocate physical memory\n");
5505 exit(1);
5508 #endif
5510 /* init the dynamic translator */
5511 cpu_exec_init_all(tb_size * 1024 * 1024);
5513 bdrv_init();
5514 dma_helper_init();
5516 /* we always create the cdrom drive, even if no disk is there */
5518 if (nb_drives_opt < MAX_DRIVES)
5519 drive_add(NULL, CDROM_ALIAS);
5521 /* we always create at least one floppy */
5523 if (nb_drives_opt < MAX_DRIVES)
5524 drive_add(NULL, FD_ALIAS, 0);
5526 /* we always create one sd slot, even if no card is in it */
5528 if (nb_drives_opt < MAX_DRIVES)
5529 drive_add(NULL, SD_ALIAS);
5531 /* open the virtual block devices
5532 * note that migration with device
5533 * hot add/remove is broken.
5535 for(i = 0; i < nb_drives_opt; i++)
5536 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5537 exit(1);
5539 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5540 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5542 #ifndef _WIN32
5543 /* must be after terminal init, SDL library changes signal handlers */
5544 termsig_setup();
5545 #endif
5547 /* Maintain compatibility with multiple stdio monitors */
5548 if (!strcmp(monitor_device,"stdio")) {
5549 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5550 const char *devname = serial_devices[i];
5551 if (devname && !strcmp(devname,"mon:stdio")) {
5552 monitor_device = NULL;
5553 break;
5554 } else if (devname && !strcmp(devname,"stdio")) {
5555 monitor_device = NULL;
5556 serial_devices[i] = "mon:stdio";
5557 break;
5562 if (nb_numa_nodes > 0) {
5563 int i;
5565 if (nb_numa_nodes > smp_cpus) {
5566 nb_numa_nodes = smp_cpus;
5569 /* If no memory size if given for any node, assume the default case
5570 * and distribute the available memory equally across all nodes
5572 for (i = 0; i < nb_numa_nodes; i++) {
5573 if (node_mem[i] != 0)
5574 break;
5576 if (i == nb_numa_nodes) {
5577 uint64_t usedmem = 0;
5579 /* On Linux, the each node's border has to be 8MB aligned,
5580 * the final node gets the rest.
5582 for (i = 0; i < nb_numa_nodes - 1; i++) {
5583 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5584 usedmem += node_mem[i];
5586 node_mem[i] = ram_size - usedmem;
5589 for (i = 0; i < nb_numa_nodes; i++) {
5590 if (node_cpumask[i] != 0)
5591 break;
5593 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5594 * must cope with this anyway, because there are BIOSes out there in
5595 * real machines which also use this scheme.
5597 if (i == nb_numa_nodes) {
5598 for (i = 0; i < smp_cpus; i++) {
5599 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5604 #ifdef KVM_UPSTREAM
5605 if (kvm_enabled()) {
5606 int ret;
5608 ret = kvm_init(smp_cpus);
5609 if (ret < 0) {
5610 fprintf(stderr, "failed to initialize KVM\n");
5611 exit(1);
5614 #endif
5616 if (monitor_device) {
5617 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5618 if (!monitor_hd) {
5619 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5620 exit(1);
5624 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5625 const char *devname = serial_devices[i];
5626 if (devname && strcmp(devname, "none")) {
5627 char label[32];
5628 snprintf(label, sizeof(label), "serial%d", i);
5629 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5630 if (!serial_hds[i]) {
5631 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5632 devname);
5633 exit(1);
5638 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5639 const char *devname = parallel_devices[i];
5640 if (devname && strcmp(devname, "none")) {
5641 char label[32];
5642 snprintf(label, sizeof(label), "parallel%d", i);
5643 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5644 if (!parallel_hds[i]) {
5645 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5646 devname);
5647 exit(1);
5652 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5653 const char *devname = virtio_consoles[i];
5654 if (devname && strcmp(devname, "none")) {
5655 char label[32];
5656 snprintf(label, sizeof(label), "virtcon%d", i);
5657 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5658 if (!virtcon_hds[i]) {
5659 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5660 devname);
5661 exit(1);
5666 if (kvm_enabled())
5667 kvm_init_ap();
5669 machine->init(ram_size, vga_ram_size, boot_devices,
5670 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5673 for (env = first_cpu; env != NULL; env = env->next_cpu) {
5674 for (i = 0; i < nb_numa_nodes; i++) {
5675 if (node_cpumask[i] & (1 << env->cpu_index)) {
5676 env->numa_node = i;
5681 current_machine = machine;
5683 /* Set KVM's vcpu state to qemu's initial CPUState. */
5684 if (kvm_enabled()) {
5685 int ret;
5687 ret = kvm_sync_vcpus();
5688 if (ret < 0) {
5689 fprintf(stderr, "failed to initialize vcpus\n");
5690 exit(1);
5694 /* init USB devices */
5695 if (usb_enabled) {
5696 for(i = 0; i < usb_devices_index; i++) {
5697 if (usb_device_add(usb_devices[i], 0) < 0) {
5698 fprintf(stderr, "Warning: could not add USB device %s\n",
5699 usb_devices[i]);
5704 if (!display_state)
5705 dumb_display_init();
5706 /* just use the first displaystate for the moment */
5707 ds = display_state;
5708 /* terminal init */
5709 if (nographic) {
5710 if (curses) {
5711 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5712 exit(1);
5714 } else {
5715 #if defined(CONFIG_CURSES)
5716 if (curses) {
5717 /* At the moment curses cannot be used with other displays */
5718 curses_display_init(ds, full_screen);
5719 } else
5720 #endif
5722 if (vnc_display != NULL) {
5723 vnc_display_init(ds);
5724 if (vnc_display_open(ds, vnc_display) < 0)
5725 exit(1);
5727 #if defined(CONFIG_SDL)
5728 if (sdl || !vnc_display)
5729 sdl_display_init(ds, full_screen, no_frame);
5730 #elif defined(CONFIG_COCOA)
5731 if (sdl || !vnc_display)
5732 cocoa_display_init(ds, full_screen);
5733 #endif
5736 dpy_resize(ds);
5738 dcl = ds->listeners;
5739 while (dcl != NULL) {
5740 if (dcl->dpy_refresh != NULL) {
5741 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5742 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5744 dcl = dcl->next;
5747 if (nographic || (vnc_display && !sdl)) {
5748 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5749 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5752 text_consoles_set_display(display_state);
5753 qemu_chr_initial_reset();
5755 if (monitor_device && monitor_hd)
5756 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5758 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5759 const char *devname = serial_devices[i];
5760 if (devname && strcmp(devname, "none")) {
5761 char label[32];
5762 snprintf(label, sizeof(label), "serial%d", i);
5763 if (strstart(devname, "vc", 0))
5764 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5768 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5769 const char *devname = parallel_devices[i];
5770 if (devname && strcmp(devname, "none")) {
5771 char label[32];
5772 snprintf(label, sizeof(label), "parallel%d", i);
5773 if (strstart(devname, "vc", 0))
5774 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5778 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5779 const char *devname = virtio_consoles[i];
5780 if (virtcon_hds[i] && devname) {
5781 char label[32];
5782 snprintf(label, sizeof(label), "virtcon%d", i);
5783 if (strstart(devname, "vc", 0))
5784 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5788 #ifdef CONFIG_GDBSTUB
5789 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5790 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5791 gdbstub_dev);
5792 exit(1);
5794 #endif
5796 if (loadvm)
5797 do_loadvm(cur_mon, loadvm);
5799 if (incoming) {
5800 autostart = 0; /* fixme how to deal with -daemonize */
5801 qemu_start_incoming_migration(incoming);
5804 if (autostart)
5805 vm_start();
5807 #ifndef _WIN32
5808 if (daemonize) {
5809 uint8_t status = 0;
5810 ssize_t len;
5812 again1:
5813 len = write(fds[1], &status, 1);
5814 if (len == -1 && (errno == EINTR))
5815 goto again1;
5817 if (len != 1)
5818 exit(1);
5820 chdir("/");
5821 TFR(fd = open("/dev/null", O_RDWR));
5822 if (fd == -1)
5823 exit(1);
5826 if (run_as) {
5827 pwd = getpwnam(run_as);
5828 if (!pwd) {
5829 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5830 exit(1);
5834 if (chroot_dir) {
5835 if (chroot(chroot_dir) < 0) {
5836 fprintf(stderr, "chroot failed\n");
5837 exit(1);
5839 chdir("/");
5842 if (run_as) {
5843 if (setgid(pwd->pw_gid) < 0) {
5844 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5845 exit(1);
5847 if (setuid(pwd->pw_uid) < 0) {
5848 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5849 exit(1);
5851 if (setuid(0) != -1) {
5852 fprintf(stderr, "Dropping privileges failed\n");
5853 exit(1);
5857 if (daemonize) {
5858 dup2(fd, 0);
5859 dup2(fd, 1);
5860 dup2(fd, 2);
5862 close(fd);
5864 #endif
5866 main_loop();
5867 quit_timers();
5868 net_cleanup();
5870 return 0;