Pull qemu headers into libkvm
[qemu-kvm/fedora.git] / vl.c
blob2fda17b71e109bb2a4368cc13e581c79c17aaf8f
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 <netinet/in.h>
45 #include <net/if.h>
46 #if defined(__NetBSD__)
47 #include <net/if_tap.h>
48 #endif
49 #ifdef __linux__
50 #include <linux/if_tun.h>
51 #endif
52 #include <arpa/inet.h>
53 #include <dirent.h>
54 #include <netdb.h>
55 #include <sys/select.h>
56 #ifdef HOST_BSD
57 #include <sys/stat.h>
58 #if defined(__FreeBSD__) || defined(__DragonFly__)
59 #include <libutil.h>
60 #else
61 #include <util.h>
62 #endif
63 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
64 #include <freebsd/stdlib.h>
65 #else
66 #ifdef __linux__
67 #include <pty.h>
68 #include <malloc.h>
69 #include <linux/rtc.h>
71 /* For the benefit of older linux systems which don't supply it,
72 we use a local copy of hpet.h. */
73 /* #include <linux/hpet.h> */
74 #include "hpet.h"
76 #include <linux/ppdev.h>
77 #include <linux/parport.h>
78 #endif
79 #ifdef __sun__
80 #include <sys/stat.h>
81 #include <sys/ethernet.h>
82 #include <sys/sockio.h>
83 #include <netinet/arp.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #include <netinet/ip_icmp.h> // must come after ip.h
88 #include <netinet/udp.h>
89 #include <netinet/tcp.h>
90 #include <net/if.h>
91 #include <syslog.h>
92 #include <stropts.h>
93 #endif
94 #endif
95 #endif
97 #if defined(__OpenBSD__)
98 #include <util.h>
99 #endif
101 #if defined(CONFIG_VDE)
102 #include <libvdeplug.h>
103 #endif
105 #ifdef _WIN32
106 #include <windows.h>
107 #include <malloc.h>
108 #include <sys/timeb.h>
109 #include <mmsystem.h>
110 #define getopt_long_only getopt_long
111 #define memalign(align, size) malloc(size)
112 #endif
114 #ifdef CONFIG_SDL
115 #ifdef __APPLE__
116 #include <SDL/SDL.h>
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 qemu_main(argc, argv, NULL);
122 #undef main
123 #define main qemu_main
124 #endif
125 #endif /* CONFIG_SDL */
127 #ifdef CONFIG_COCOA
128 #undef main
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
132 #include "hw/hw.h"
133 #include "hw/boards.h"
134 #include "hw/usb.h"
135 #include "hw/pcmcia.h"
136 #include "hw/pc.h"
137 #include "hw/audiodev.h"
138 #include "hw/isa.h"
139 #include "hw/baum.h"
140 #include "hw/bt.h"
141 #include "hw/watchdog.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-option.h"
160 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
163 #include "disas.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #if defined(CONFIG_SLIRP)
170 #include "libslirp.h"
171 #endif
173 //#define DEBUG_UNUSED_IOPORT
174 //#define DEBUG_IOPORT
175 //#define DEBUG_NET
176 //#define DEBUG_SLIRP
179 #ifdef DEBUG_IOPORT
180 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
181 #else
182 # define LOG_IOPORT(...) do { } while (0)
183 #endif
185 #define DEFAULT_RAM_SIZE 128
187 /* Max number of USB devices that can be specified on the commandline. */
188 #define MAX_USB_CMDLINE 8
190 /* Max number of bluetooth switches on the commandline. */
191 #define MAX_BT_CMDLINE 10
193 /* XXX: use a two level table to limit memory usage */
194 #define MAX_IOPORTS 65536
196 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
197 const char *bios_name = NULL;
198 static void *ioport_opaque[MAX_IOPORTS];
199 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
200 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
201 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
202 to store the VM snapshots */
203 DriveInfo drives_table[MAX_DRIVES+1];
204 int nb_drives;
205 int extboot_drive = -1;
206 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
207 static DisplayState *display_state;
208 DisplayType display_type = DT_DEFAULT;
209 const char* keyboard_layout = NULL;
210 int64_t ticks_per_sec;
211 ram_addr_t ram_size;
212 int nb_nics;
213 NICInfo nd_table[MAX_NICS];
214 int vm_running;
215 static int autostart;
216 static int rtc_utc = 1;
217 static int rtc_date_offset = -1; /* -1 means no change */
218 int cirrus_vga_enabled = 1;
219 int std_vga_enabled = 0;
220 int vmsvga_enabled = 0;
221 int xenfb_enabled = 0;
222 #ifdef TARGET_SPARC
223 int graphic_width = 1024;
224 int graphic_height = 768;
225 int graphic_depth = 8;
226 #else
227 int graphic_width = 800;
228 int graphic_height = 600;
229 int graphic_depth = 15;
230 #endif
231 static int full_screen = 0;
232 #ifdef CONFIG_SDL
233 static int no_frame = 0;
234 #endif
235 int no_quit = 0;
236 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
237 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
238 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
239 #ifdef TARGET_I386
240 int win2k_install_hack = 0;
241 int rtc_td_hack = 0;
242 #endif
243 int usb_enabled = 0;
244 int singlestep = 0;
245 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
246 int assigned_devices_index;
247 int smp_cpus = 1;
248 const char *vnc_display;
249 int acpi_enabled = 1;
250 int no_hpet = 0;
251 int fd_bootchk = 1;
252 int no_reboot = 0;
253 int no_shutdown = 0;
254 int cursor_hide = 1;
255 int graphic_rotate = 0;
256 #ifndef _WIN32
257 int daemonize = 0;
258 #endif
259 WatchdogTimerModel *watchdog = NULL;
260 int watchdog_action = WDT_RESET;
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 #ifdef TARGET_ARM
271 int old_param = 0;
272 #endif
273 const char *qemu_name;
274 int alt_grab = 0;
275 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
276 unsigned int nb_prom_envs = 0;
277 const char *prom_envs[MAX_PROM_ENVS];
278 #endif
279 int nb_drives_opt;
280 const char *nvram = NULL;
281 struct drive_opt drives_opt[MAX_DRIVES];
283 int nb_numa_nodes;
284 uint64_t node_mem[MAX_NODES];
285 uint64_t node_cpumask[MAX_NODES];
287 static CPUState *cur_cpu;
288 static CPUState *next_cpu;
289 static int timer_alarm_pending = 1;
290 /* Conversion factor from emulated instructions to virtual clock ticks. */
291 static int icount_time_shift;
292 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
293 #define MAX_ICOUNT_SHIFT 10
294 /* Compensate for varying guest execution speed. */
295 static int64_t qemu_icount_bias;
296 static QEMUTimer *icount_rt_timer;
297 static QEMUTimer *icount_vm_timer;
298 static QEMUTimer *nographic_timer;
300 uint8_t qemu_uuid[16];
302 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
303 struct timeval *tv)
305 int ret;
307 /* KVM holds a mutex while QEMU code is running, we need hooks to
308 release the mutex whenever QEMU code sleeps. */
310 kvm_sleep_begin();
312 ret = select(max_fd, rfds, wfds, xfds, tv);
314 kvm_sleep_end();
316 return ret;
320 /***********************************************************/
321 /* x86 ISA bus support */
323 target_phys_addr_t isa_mem_base = 0;
324 PicState2 *isa_pic;
326 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
327 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
329 static uint32_t ioport_read(int index, uint32_t address)
331 static IOPortReadFunc *default_func[3] = {
332 default_ioport_readb,
333 default_ioport_readw,
334 default_ioport_readl
336 IOPortReadFunc *func = ioport_read_table[index][address];
337 if (!func)
338 func = default_func[index];
339 return func(ioport_opaque[address], address);
342 static void ioport_write(int index, uint32_t address, uint32_t data)
344 static IOPortWriteFunc *default_func[3] = {
345 default_ioport_writeb,
346 default_ioport_writew,
347 default_ioport_writel
349 IOPortWriteFunc *func = ioport_write_table[index][address];
350 if (!func)
351 func = default_func[index];
352 func(ioport_opaque[address], address, data);
355 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
357 #ifdef DEBUG_UNUSED_IOPORT
358 fprintf(stderr, "unused inb: port=0x%04x\n", address);
359 #endif
360 return 0xff;
363 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
365 #ifdef DEBUG_UNUSED_IOPORT
366 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
367 #endif
370 /* default is to make two byte accesses */
371 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
373 uint32_t data;
374 data = ioport_read(0, address);
375 address = (address + 1) & (MAX_IOPORTS - 1);
376 data |= ioport_read(0, address) << 8;
377 return data;
380 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
382 ioport_write(0, address, data & 0xff);
383 address = (address + 1) & (MAX_IOPORTS - 1);
384 ioport_write(0, address, (data >> 8) & 0xff);
387 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
389 #ifdef DEBUG_UNUSED_IOPORT
390 fprintf(stderr, "unused inl: port=0x%04x\n", address);
391 #endif
392 return 0xffffffff;
395 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
397 #ifdef DEBUG_UNUSED_IOPORT
398 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
399 #endif
402 /* size is the word size in byte */
403 int register_ioport_read(int start, int length, int size,
404 IOPortReadFunc *func, void *opaque)
406 int i, bsize;
408 if (size == 1) {
409 bsize = 0;
410 } else if (size == 2) {
411 bsize = 1;
412 } else if (size == 4) {
413 bsize = 2;
414 } else {
415 hw_error("register_ioport_read: invalid size");
416 return -1;
418 for(i = start; i < start + length; i += size) {
419 ioport_read_table[bsize][i] = func;
420 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
421 hw_error("register_ioport_read: invalid opaque");
422 ioport_opaque[i] = opaque;
424 return 0;
427 /* size is the word size in byte */
428 int register_ioport_write(int start, int length, int size,
429 IOPortWriteFunc *func, void *opaque)
431 int i, bsize;
433 if (size == 1) {
434 bsize = 0;
435 } else if (size == 2) {
436 bsize = 1;
437 } else if (size == 4) {
438 bsize = 2;
439 } else {
440 hw_error("register_ioport_write: invalid size");
441 return -1;
443 for(i = start; i < start + length; i += size) {
444 ioport_write_table[bsize][i] = func;
445 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
446 hw_error("register_ioport_write: invalid opaque");
447 ioport_opaque[i] = opaque;
449 return 0;
452 void isa_unassign_ioport(int start, int length)
454 int i;
456 for(i = start; i < start + length; i++) {
457 ioport_read_table[0][i] = default_ioport_readb;
458 ioport_read_table[1][i] = default_ioport_readw;
459 ioport_read_table[2][i] = default_ioport_readl;
461 ioport_write_table[0][i] = default_ioport_writeb;
462 ioport_write_table[1][i] = default_ioport_writew;
463 ioport_write_table[2][i] = default_ioport_writel;
465 ioport_opaque[i] = NULL;
469 /***********************************************************/
471 void cpu_outb(CPUState *env, int addr, int val)
473 LOG_IOPORT("outb: %04x %02x\n", addr, val);
474 ioport_write(0, addr, val);
475 #ifdef CONFIG_KQEMU
476 if (env)
477 env->last_io_time = cpu_get_time_fast();
478 #endif
481 void cpu_outw(CPUState *env, int addr, int val)
483 LOG_IOPORT("outw: %04x %04x\n", addr, val);
484 ioport_write(1, addr, val);
485 #ifdef CONFIG_KQEMU
486 if (env)
487 env->last_io_time = cpu_get_time_fast();
488 #endif
491 void cpu_outl(CPUState *env, int addr, int val)
493 LOG_IOPORT("outl: %04x %08x\n", addr, val);
494 ioport_write(2, addr, val);
495 #ifdef CONFIG_KQEMU
496 if (env)
497 env->last_io_time = cpu_get_time_fast();
498 #endif
501 int cpu_inb(CPUState *env, int addr)
503 int val;
504 val = ioport_read(0, addr);
505 LOG_IOPORT("inb : %04x %02x\n", addr, val);
506 #ifdef CONFIG_KQEMU
507 if (env)
508 env->last_io_time = cpu_get_time_fast();
509 #endif
510 return val;
513 int cpu_inw(CPUState *env, int addr)
515 int val;
516 val = ioport_read(1, addr);
517 LOG_IOPORT("inw : %04x %04x\n", addr, val);
518 #ifdef CONFIG_KQEMU
519 if (env)
520 env->last_io_time = cpu_get_time_fast();
521 #endif
522 return val;
525 int cpu_inl(CPUState *env, int addr)
527 int val;
528 val = ioport_read(2, addr);
529 LOG_IOPORT("inl : %04x %08x\n", addr, val);
530 #ifdef CONFIG_KQEMU
531 if (env)
532 env->last_io_time = cpu_get_time_fast();
533 #endif
534 return val;
537 /***********************************************************/
538 void hw_error(const char *fmt, ...)
540 va_list ap;
541 CPUState *env;
543 va_start(ap, fmt);
544 fprintf(stderr, "qemu: hardware error: ");
545 vfprintf(stderr, fmt, ap);
546 fprintf(stderr, "\n");
547 for(env = first_cpu; env != NULL; env = env->next_cpu) {
548 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
549 #ifdef TARGET_I386
550 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
551 #else
552 cpu_dump_state(env, stderr, fprintf, 0);
553 #endif
555 va_end(ap);
556 abort();
559 /***************/
560 /* ballooning */
562 static QEMUBalloonEvent *qemu_balloon_event;
563 void *qemu_balloon_event_opaque;
565 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
567 qemu_balloon_event = func;
568 qemu_balloon_event_opaque = opaque;
571 void qemu_balloon(ram_addr_t target)
573 if (qemu_balloon_event)
574 qemu_balloon_event(qemu_balloon_event_opaque, target);
577 ram_addr_t qemu_balloon_status(void)
579 if (qemu_balloon_event)
580 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
581 return 0;
584 /***********************************************************/
585 /* keyboard/mouse */
587 static QEMUPutKBDEvent *qemu_put_kbd_event;
588 static void *qemu_put_kbd_event_opaque;
589 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
590 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
592 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
594 qemu_put_kbd_event_opaque = opaque;
595 qemu_put_kbd_event = func;
598 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
599 void *opaque, int absolute,
600 const char *name)
602 QEMUPutMouseEntry *s, *cursor;
604 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
606 s->qemu_put_mouse_event = func;
607 s->qemu_put_mouse_event_opaque = opaque;
608 s->qemu_put_mouse_event_absolute = absolute;
609 s->qemu_put_mouse_event_name = qemu_strdup(name);
610 s->next = NULL;
612 if (!qemu_put_mouse_event_head) {
613 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
614 return s;
617 cursor = qemu_put_mouse_event_head;
618 while (cursor->next != NULL)
619 cursor = cursor->next;
621 cursor->next = s;
622 qemu_put_mouse_event_current = s;
624 return s;
627 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
629 QEMUPutMouseEntry *prev = NULL, *cursor;
631 if (!qemu_put_mouse_event_head || entry == NULL)
632 return;
634 cursor = qemu_put_mouse_event_head;
635 while (cursor != NULL && cursor != entry) {
636 prev = cursor;
637 cursor = cursor->next;
640 if (cursor == NULL) // does not exist or list empty
641 return;
642 else if (prev == NULL) { // entry is head
643 qemu_put_mouse_event_head = cursor->next;
644 if (qemu_put_mouse_event_current == entry)
645 qemu_put_mouse_event_current = cursor->next;
646 qemu_free(entry->qemu_put_mouse_event_name);
647 qemu_free(entry);
648 return;
651 prev->next = entry->next;
653 if (qemu_put_mouse_event_current == entry)
654 qemu_put_mouse_event_current = prev;
656 qemu_free(entry->qemu_put_mouse_event_name);
657 qemu_free(entry);
660 void kbd_put_keycode(int keycode)
662 if (qemu_put_kbd_event) {
663 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
667 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
669 QEMUPutMouseEvent *mouse_event;
670 void *mouse_event_opaque;
671 int width;
673 if (!qemu_put_mouse_event_current) {
674 return;
677 mouse_event =
678 qemu_put_mouse_event_current->qemu_put_mouse_event;
679 mouse_event_opaque =
680 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
682 if (mouse_event) {
683 if (graphic_rotate) {
684 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
685 width = 0x7fff;
686 else
687 width = graphic_width - 1;
688 mouse_event(mouse_event_opaque,
689 width - dy, dx, dz, buttons_state);
690 } else
691 mouse_event(mouse_event_opaque,
692 dx, dy, dz, buttons_state);
696 int kbd_mouse_is_absolute(void)
698 if (!qemu_put_mouse_event_current)
699 return 0;
701 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
704 void do_info_mice(Monitor *mon)
706 QEMUPutMouseEntry *cursor;
707 int index = 0;
709 if (!qemu_put_mouse_event_head) {
710 monitor_printf(mon, "No mouse devices connected\n");
711 return;
714 monitor_printf(mon, "Mouse devices available:\n");
715 cursor = qemu_put_mouse_event_head;
716 while (cursor != NULL) {
717 monitor_printf(mon, "%c Mouse #%d: %s\n",
718 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
719 index, cursor->qemu_put_mouse_event_name);
720 index++;
721 cursor = cursor->next;
725 void do_mouse_set(Monitor *mon, int index)
727 QEMUPutMouseEntry *cursor;
728 int i = 0;
730 if (!qemu_put_mouse_event_head) {
731 monitor_printf(mon, "No mouse devices connected\n");
732 return;
735 cursor = qemu_put_mouse_event_head;
736 while (cursor != NULL && index != i) {
737 i++;
738 cursor = cursor->next;
741 if (cursor != NULL)
742 qemu_put_mouse_event_current = cursor;
743 else
744 monitor_printf(mon, "Mouse at given index not found\n");
747 /* compute with 96 bit intermediate result: (a*b)/c */
748 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
750 union {
751 uint64_t ll;
752 struct {
753 #ifdef WORDS_BIGENDIAN
754 uint32_t high, low;
755 #else
756 uint32_t low, high;
757 #endif
758 } l;
759 } u, res;
760 uint64_t rl, rh;
762 u.ll = a;
763 rl = (uint64_t)u.l.low * (uint64_t)b;
764 rh = (uint64_t)u.l.high * (uint64_t)b;
765 rh += (rl >> 32);
766 res.l.high = rh / c;
767 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
768 return res.ll;
771 /***********************************************************/
772 /* real time host monotonic timer */
774 #define QEMU_TIMER_BASE 1000000000LL
776 #ifdef WIN32
778 static int64_t clock_freq;
780 static void init_get_clock(void)
782 LARGE_INTEGER freq;
783 int ret;
784 ret = QueryPerformanceFrequency(&freq);
785 if (ret == 0) {
786 fprintf(stderr, "Could not calibrate ticks\n");
787 exit(1);
789 clock_freq = freq.QuadPart;
792 static int64_t get_clock(void)
794 LARGE_INTEGER ti;
795 QueryPerformanceCounter(&ti);
796 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
799 #else
801 static int use_rt_clock;
803 static void init_get_clock(void)
805 use_rt_clock = 0;
806 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
807 || defined(__DragonFly__)
809 struct timespec ts;
810 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
811 use_rt_clock = 1;
814 #endif
817 static int64_t get_clock(void)
819 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
820 || defined(__DragonFly__)
821 if (use_rt_clock) {
822 struct timespec ts;
823 clock_gettime(CLOCK_MONOTONIC, &ts);
824 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
825 } else
826 #endif
828 /* XXX: using gettimeofday leads to problems if the date
829 changes, so it should be avoided. */
830 struct timeval tv;
831 gettimeofday(&tv, NULL);
832 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
835 #endif
837 /* Return the virtual CPU time, based on the instruction counter. */
838 static int64_t cpu_get_icount(void)
840 int64_t icount;
841 CPUState *env = cpu_single_env;;
842 icount = qemu_icount;
843 if (env) {
844 if (!can_do_io(env))
845 fprintf(stderr, "Bad clock read\n");
846 icount -= (env->icount_decr.u16.low + env->icount_extra);
848 return qemu_icount_bias + (icount << icount_time_shift);
851 /***********************************************************/
852 /* guest cycle counter */
854 static int64_t cpu_ticks_prev;
855 static int64_t cpu_ticks_offset;
856 static int64_t cpu_clock_offset;
857 static int cpu_ticks_enabled;
859 /* return the host CPU cycle counter and handle stop/restart */
860 int64_t cpu_get_ticks(void)
862 if (use_icount) {
863 return cpu_get_icount();
865 if (!cpu_ticks_enabled) {
866 return cpu_ticks_offset;
867 } else {
868 int64_t ticks;
869 ticks = cpu_get_real_ticks();
870 if (cpu_ticks_prev > ticks) {
871 /* Note: non increasing ticks may happen if the host uses
872 software suspend */
873 cpu_ticks_offset += cpu_ticks_prev - ticks;
875 cpu_ticks_prev = ticks;
876 return ticks + cpu_ticks_offset;
880 /* return the host CPU monotonic timer and handle stop/restart */
881 static int64_t cpu_get_clock(void)
883 int64_t ti;
884 if (!cpu_ticks_enabled) {
885 return cpu_clock_offset;
886 } else {
887 ti = get_clock();
888 return ti + cpu_clock_offset;
892 /* enable cpu_get_ticks() */
893 void cpu_enable_ticks(void)
895 if (!cpu_ticks_enabled) {
896 cpu_ticks_offset -= cpu_get_real_ticks();
897 cpu_clock_offset -= get_clock();
898 cpu_ticks_enabled = 1;
902 /* disable cpu_get_ticks() : the clock is stopped. You must not call
903 cpu_get_ticks() after that. */
904 void cpu_disable_ticks(void)
906 if (cpu_ticks_enabled) {
907 cpu_ticks_offset = cpu_get_ticks();
908 cpu_clock_offset = cpu_get_clock();
909 cpu_ticks_enabled = 0;
913 /***********************************************************/
914 /* timers */
916 #define QEMU_TIMER_REALTIME 0
917 #define QEMU_TIMER_VIRTUAL 1
919 struct QEMUClock {
920 int type;
921 /* XXX: add frequency */
924 struct QEMUTimer {
925 QEMUClock *clock;
926 int64_t expire_time;
927 QEMUTimerCB *cb;
928 void *opaque;
929 struct QEMUTimer *next;
932 struct qemu_alarm_timer {
933 char const *name;
934 unsigned int flags;
936 int (*start)(struct qemu_alarm_timer *t);
937 void (*stop)(struct qemu_alarm_timer *t);
938 void (*rearm)(struct qemu_alarm_timer *t);
939 void *priv;
942 #define ALARM_FLAG_DYNTICKS 0x1
943 #define ALARM_FLAG_EXPIRED 0x2
945 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
947 return t && (t->flags & ALARM_FLAG_DYNTICKS);
950 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
952 if (!alarm_has_dynticks(t))
953 return;
955 t->rearm(t);
958 /* TODO: MIN_TIMER_REARM_US should be optimized */
959 #define MIN_TIMER_REARM_US 250
961 static struct qemu_alarm_timer *alarm_timer;
963 #ifdef _WIN32
965 struct qemu_alarm_win32 {
966 MMRESULT timerId;
967 unsigned int period;
968 } alarm_win32_data = {0, -1};
970 static int win32_start_timer(struct qemu_alarm_timer *t);
971 static void win32_stop_timer(struct qemu_alarm_timer *t);
972 static void win32_rearm_timer(struct qemu_alarm_timer *t);
974 #else
976 static int unix_start_timer(struct qemu_alarm_timer *t);
977 static void unix_stop_timer(struct qemu_alarm_timer *t);
979 #ifdef __linux__
981 static int dynticks_start_timer(struct qemu_alarm_timer *t);
982 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
983 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
985 static int hpet_start_timer(struct qemu_alarm_timer *t);
986 static void hpet_stop_timer(struct qemu_alarm_timer *t);
988 static int rtc_start_timer(struct qemu_alarm_timer *t);
989 static void rtc_stop_timer(struct qemu_alarm_timer *t);
991 #endif /* __linux__ */
993 #endif /* _WIN32 */
995 /* Correlation between real and virtual time is always going to be
996 fairly approximate, so ignore small variation.
997 When the guest is idle real and virtual time will be aligned in
998 the IO wait loop. */
999 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1001 static void icount_adjust(void)
1003 int64_t cur_time;
1004 int64_t cur_icount;
1005 int64_t delta;
1006 static int64_t last_delta;
1007 /* If the VM is not running, then do nothing. */
1008 if (!vm_running)
1009 return;
1011 cur_time = cpu_get_clock();
1012 cur_icount = qemu_get_clock(vm_clock);
1013 delta = cur_icount - cur_time;
1014 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1015 if (delta > 0
1016 && last_delta + ICOUNT_WOBBLE < delta * 2
1017 && icount_time_shift > 0) {
1018 /* The guest is getting too far ahead. Slow time down. */
1019 icount_time_shift--;
1021 if (delta < 0
1022 && last_delta - ICOUNT_WOBBLE > delta * 2
1023 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1024 /* The guest is getting too far behind. Speed time up. */
1025 icount_time_shift++;
1027 last_delta = delta;
1028 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1031 static void icount_adjust_rt(void * opaque)
1033 qemu_mod_timer(icount_rt_timer,
1034 qemu_get_clock(rt_clock) + 1000);
1035 icount_adjust();
1038 static void icount_adjust_vm(void * opaque)
1040 qemu_mod_timer(icount_vm_timer,
1041 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1042 icount_adjust();
1045 static void init_icount_adjust(void)
1047 /* Have both realtime and virtual time triggers for speed adjustment.
1048 The realtime trigger catches emulated time passing too slowly,
1049 the virtual time trigger catches emulated time passing too fast.
1050 Realtime triggers occur even when idle, so use them less frequently
1051 than VM triggers. */
1052 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1053 qemu_mod_timer(icount_rt_timer,
1054 qemu_get_clock(rt_clock) + 1000);
1055 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1056 qemu_mod_timer(icount_vm_timer,
1057 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1060 static struct qemu_alarm_timer alarm_timers[] = {
1061 #ifndef _WIN32
1062 #ifdef __linux__
1063 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1064 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1065 /* HPET - if available - is preferred */
1066 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1067 /* ...otherwise try RTC */
1068 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1069 #endif
1070 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1071 #else
1072 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1073 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1074 {"win32", 0, win32_start_timer,
1075 win32_stop_timer, NULL, &alarm_win32_data},
1076 #endif
1077 {NULL, }
1080 static void show_available_alarms(void)
1082 int i;
1084 printf("Available alarm timers, in order of precedence:\n");
1085 for (i = 0; alarm_timers[i].name; i++)
1086 printf("%s\n", alarm_timers[i].name);
1089 static void configure_alarms(char const *opt)
1091 int i;
1092 int cur = 0;
1093 int count = ARRAY_SIZE(alarm_timers) - 1;
1094 char *arg;
1095 char *name;
1096 struct qemu_alarm_timer tmp;
1098 if (!strcmp(opt, "?")) {
1099 show_available_alarms();
1100 exit(0);
1103 arg = strdup(opt);
1105 /* Reorder the array */
1106 name = strtok(arg, ",");
1107 while (name) {
1108 for (i = 0; i < count && alarm_timers[i].name; i++) {
1109 if (!strcmp(alarm_timers[i].name, name))
1110 break;
1113 if (i == count) {
1114 fprintf(stderr, "Unknown clock %s\n", name);
1115 goto next;
1118 if (i < cur)
1119 /* Ignore */
1120 goto next;
1122 /* Swap */
1123 tmp = alarm_timers[i];
1124 alarm_timers[i] = alarm_timers[cur];
1125 alarm_timers[cur] = tmp;
1127 cur++;
1128 next:
1129 name = strtok(NULL, ",");
1132 free(arg);
1134 if (cur) {
1135 /* Disable remaining timers */
1136 for (i = cur; i < count; i++)
1137 alarm_timers[i].name = NULL;
1138 } else {
1139 show_available_alarms();
1140 exit(1);
1144 QEMUClock *rt_clock;
1145 QEMUClock *vm_clock;
1147 static QEMUTimer *active_timers[2];
1149 static QEMUClock *qemu_new_clock(int type)
1151 QEMUClock *clock;
1152 clock = qemu_mallocz(sizeof(QEMUClock));
1153 clock->type = type;
1154 return clock;
1157 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1159 QEMUTimer *ts;
1161 ts = qemu_mallocz(sizeof(QEMUTimer));
1162 ts->clock = clock;
1163 ts->cb = cb;
1164 ts->opaque = opaque;
1165 return ts;
1168 void qemu_free_timer(QEMUTimer *ts)
1170 qemu_free(ts);
1173 /* stop a timer, but do not dealloc it */
1174 void qemu_del_timer(QEMUTimer *ts)
1176 QEMUTimer **pt, *t;
1178 /* NOTE: this code must be signal safe because
1179 qemu_timer_expired() can be called from a signal. */
1180 pt = &active_timers[ts->clock->type];
1181 for(;;) {
1182 t = *pt;
1183 if (!t)
1184 break;
1185 if (t == ts) {
1186 *pt = t->next;
1187 break;
1189 pt = &t->next;
1193 /* modify the current timer so that it will be fired when current_time
1194 >= expire_time. The corresponding callback will be called. */
1195 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1197 QEMUTimer **pt, *t;
1199 qemu_del_timer(ts);
1201 /* add the timer in the sorted list */
1202 /* NOTE: this code must be signal safe because
1203 qemu_timer_expired() can be called from a signal. */
1204 pt = &active_timers[ts->clock->type];
1205 for(;;) {
1206 t = *pt;
1207 if (!t)
1208 break;
1209 if (t->expire_time > expire_time)
1210 break;
1211 pt = &t->next;
1213 ts->expire_time = expire_time;
1214 ts->next = *pt;
1215 *pt = ts;
1217 /* Rearm if necessary */
1218 if (pt == &active_timers[ts->clock->type]) {
1219 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1220 qemu_rearm_alarm_timer(alarm_timer);
1222 /* Interrupt execution to force deadline recalculation. */
1223 if (use_icount)
1224 qemu_notify_event();
1228 int qemu_timer_pending(QEMUTimer *ts)
1230 QEMUTimer *t;
1231 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1232 if (t == ts)
1233 return 1;
1235 return 0;
1238 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1240 if (!timer_head)
1241 return 0;
1242 return (timer_head->expire_time <= current_time);
1245 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1247 QEMUTimer *ts;
1249 for(;;) {
1250 ts = *ptimer_head;
1251 if (!ts || ts->expire_time > current_time)
1252 break;
1253 /* remove timer from the list before calling the callback */
1254 *ptimer_head = ts->next;
1255 ts->next = NULL;
1257 /* run the callback (the timer list can be modified) */
1258 ts->cb(ts->opaque);
1262 int64_t qemu_get_clock(QEMUClock *clock)
1264 switch(clock->type) {
1265 case QEMU_TIMER_REALTIME:
1266 return get_clock() / 1000000;
1267 default:
1268 case QEMU_TIMER_VIRTUAL:
1269 if (use_icount) {
1270 return cpu_get_icount();
1271 } else {
1272 return cpu_get_clock();
1277 static void init_timers(void)
1279 init_get_clock();
1280 ticks_per_sec = QEMU_TIMER_BASE;
1281 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1282 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1285 /* save a timer */
1286 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1288 uint64_t expire_time;
1290 if (qemu_timer_pending(ts)) {
1291 expire_time = ts->expire_time;
1292 } else {
1293 expire_time = -1;
1295 qemu_put_be64(f, expire_time);
1298 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1300 uint64_t expire_time;
1302 expire_time = qemu_get_be64(f);
1303 if (expire_time != -1) {
1304 qemu_mod_timer(ts, expire_time);
1305 } else {
1306 qemu_del_timer(ts);
1310 static void timer_save(QEMUFile *f, void *opaque)
1312 if (cpu_ticks_enabled) {
1313 hw_error("cannot save state if virtual timers are running");
1315 qemu_put_be64(f, cpu_ticks_offset);
1316 qemu_put_be64(f, ticks_per_sec);
1317 qemu_put_be64(f, cpu_clock_offset);
1320 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1322 if (version_id != 1 && version_id != 2)
1323 return -EINVAL;
1324 if (cpu_ticks_enabled) {
1325 return -EINVAL;
1327 cpu_ticks_offset=qemu_get_be64(f);
1328 ticks_per_sec=qemu_get_be64(f);
1329 if (version_id == 2) {
1330 cpu_clock_offset=qemu_get_be64(f);
1332 return 0;
1335 static void qemu_event_increment(void);
1337 #ifdef _WIN32
1338 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1339 DWORD_PTR dwUser, DWORD_PTR dw1,
1340 DWORD_PTR dw2)
1341 #else
1342 static void host_alarm_handler(int host_signum)
1343 #endif
1345 #if 0
1346 #define DISP_FREQ 1000
1348 static int64_t delta_min = INT64_MAX;
1349 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1350 static int count;
1351 ti = qemu_get_clock(vm_clock);
1352 if (last_clock != 0) {
1353 delta = ti - last_clock;
1354 if (delta < delta_min)
1355 delta_min = delta;
1356 if (delta > delta_max)
1357 delta_max = delta;
1358 delta_cum += delta;
1359 if (++count == DISP_FREQ) {
1360 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1361 muldiv64(delta_min, 1000000, ticks_per_sec),
1362 muldiv64(delta_max, 1000000, ticks_per_sec),
1363 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1364 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1365 count = 0;
1366 delta_min = INT64_MAX;
1367 delta_max = 0;
1368 delta_cum = 0;
1371 last_clock = ti;
1373 #endif
1374 if (alarm_has_dynticks(alarm_timer) ||
1375 (!use_icount &&
1376 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1377 qemu_get_clock(vm_clock))) ||
1378 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1379 qemu_get_clock(rt_clock))) {
1380 qemu_event_increment();
1381 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1383 #ifndef CONFIG_IOTHREAD
1384 if (next_cpu) {
1385 /* stop the currently executing cpu because a timer occured */
1386 cpu_exit(next_cpu);
1387 #ifdef CONFIG_KQEMU
1388 if (next_cpu->kqemu_enabled) {
1389 kqemu_cpu_interrupt(next_cpu);
1391 #endif
1393 #endif
1394 timer_alarm_pending = 1;
1395 qemu_notify_event();
1399 static int64_t qemu_next_deadline(void)
1401 int64_t delta;
1403 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1404 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1405 qemu_get_clock(vm_clock);
1406 } else {
1407 /* To avoid problems with overflow limit this to 2^32. */
1408 delta = INT32_MAX;
1411 if (delta < 0)
1412 delta = 0;
1414 return delta;
1417 #if defined(__linux__) || defined(_WIN32)
1418 static uint64_t qemu_next_deadline_dyntick(void)
1420 int64_t delta;
1421 int64_t rtdelta;
1423 if (use_icount)
1424 delta = INT32_MAX;
1425 else
1426 delta = (qemu_next_deadline() + 999) / 1000;
1428 if (active_timers[QEMU_TIMER_REALTIME]) {
1429 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1430 qemu_get_clock(rt_clock))*1000;
1431 if (rtdelta < delta)
1432 delta = rtdelta;
1435 if (delta < MIN_TIMER_REARM_US)
1436 delta = MIN_TIMER_REARM_US;
1438 return delta;
1440 #endif
1442 #ifndef _WIN32
1444 /* Sets a specific flag */
1445 static int fcntl_setfl(int fd, int flag)
1447 int flags;
1449 flags = fcntl(fd, F_GETFL);
1450 if (flags == -1)
1451 return -errno;
1453 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1454 return -errno;
1456 return 0;
1459 #if defined(__linux__)
1461 #define RTC_FREQ 1024
1463 static void enable_sigio_timer(int fd)
1465 struct sigaction act;
1467 /* timer signal */
1468 sigfillset(&act.sa_mask);
1469 act.sa_flags = 0;
1470 act.sa_handler = host_alarm_handler;
1472 sigaction(SIGIO, &act, NULL);
1473 fcntl_setfl(fd, O_ASYNC);
1474 fcntl(fd, F_SETOWN, getpid());
1477 static int hpet_start_timer(struct qemu_alarm_timer *t)
1479 struct hpet_info info;
1480 int r, fd;
1482 fd = open("/dev/hpet", O_RDONLY);
1483 if (fd < 0)
1484 return -1;
1486 /* Set frequency */
1487 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1488 if (r < 0) {
1489 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1490 "error, but for better emulation accuracy type:\n"
1491 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1492 goto fail;
1495 /* Check capabilities */
1496 r = ioctl(fd, HPET_INFO, &info);
1497 if (r < 0)
1498 goto fail;
1500 /* Enable periodic mode */
1501 r = ioctl(fd, HPET_EPI, 0);
1502 if (info.hi_flags && (r < 0))
1503 goto fail;
1505 /* Enable interrupt */
1506 r = ioctl(fd, HPET_IE_ON, 0);
1507 if (r < 0)
1508 goto fail;
1510 enable_sigio_timer(fd);
1511 t->priv = (void *)(long)fd;
1513 return 0;
1514 fail:
1515 close(fd);
1516 return -1;
1519 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1521 int fd = (long)t->priv;
1523 close(fd);
1526 static int rtc_start_timer(struct qemu_alarm_timer *t)
1528 int rtc_fd;
1529 unsigned long current_rtc_freq = 0;
1531 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1532 if (rtc_fd < 0)
1533 return -1;
1534 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1535 if (current_rtc_freq != RTC_FREQ &&
1536 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1537 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1538 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1539 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1540 goto fail;
1542 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1543 fail:
1544 close(rtc_fd);
1545 return -1;
1548 enable_sigio_timer(rtc_fd);
1550 t->priv = (void *)(long)rtc_fd;
1552 return 0;
1555 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1557 int rtc_fd = (long)t->priv;
1559 close(rtc_fd);
1562 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1564 struct sigevent ev;
1565 timer_t host_timer;
1566 struct sigaction act;
1568 sigfillset(&act.sa_mask);
1569 act.sa_flags = 0;
1570 act.sa_handler = host_alarm_handler;
1572 sigaction(SIGALRM, &act, NULL);
1575 * Initialize ev struct to 0 to avoid valgrind complaining
1576 * about uninitialized data in timer_create call
1578 memset(&ev, 0, sizeof(ev));
1579 ev.sigev_value.sival_int = 0;
1580 ev.sigev_notify = SIGEV_SIGNAL;
1581 ev.sigev_signo = SIGALRM;
1583 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1584 perror("timer_create");
1586 /* disable dynticks */
1587 fprintf(stderr, "Dynamic Ticks disabled\n");
1589 return -1;
1592 t->priv = (void *)(long)host_timer;
1594 return 0;
1597 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1599 timer_t host_timer = (timer_t)(long)t->priv;
1601 timer_delete(host_timer);
1604 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1606 timer_t host_timer = (timer_t)(long)t->priv;
1607 struct itimerspec timeout;
1608 int64_t nearest_delta_us = INT64_MAX;
1609 int64_t current_us;
1611 if (!active_timers[QEMU_TIMER_REALTIME] &&
1612 !active_timers[QEMU_TIMER_VIRTUAL])
1613 return;
1615 nearest_delta_us = qemu_next_deadline_dyntick();
1617 /* check whether a timer is already running */
1618 if (timer_gettime(host_timer, &timeout)) {
1619 perror("gettime");
1620 fprintf(stderr, "Internal timer error: aborting\n");
1621 exit(1);
1623 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1624 if (current_us && current_us <= nearest_delta_us)
1625 return;
1627 timeout.it_interval.tv_sec = 0;
1628 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1629 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1630 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1631 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1632 perror("settime");
1633 fprintf(stderr, "Internal timer error: aborting\n");
1634 exit(1);
1638 #endif /* defined(__linux__) */
1640 static int unix_start_timer(struct qemu_alarm_timer *t)
1642 struct sigaction act;
1643 struct itimerval itv;
1644 int err;
1646 /* timer signal */
1647 sigfillset(&act.sa_mask);
1648 act.sa_flags = 0;
1649 act.sa_handler = host_alarm_handler;
1651 sigaction(SIGALRM, &act, NULL);
1653 itv.it_interval.tv_sec = 0;
1654 /* for i386 kernel 2.6 to get 1 ms */
1655 itv.it_interval.tv_usec = 999;
1656 itv.it_value.tv_sec = 0;
1657 itv.it_value.tv_usec = 10 * 1000;
1659 err = setitimer(ITIMER_REAL, &itv, NULL);
1660 if (err)
1661 return -1;
1663 return 0;
1666 static void unix_stop_timer(struct qemu_alarm_timer *t)
1668 struct itimerval itv;
1670 memset(&itv, 0, sizeof(itv));
1671 setitimer(ITIMER_REAL, &itv, NULL);
1674 #endif /* !defined(_WIN32) */
1677 #ifdef _WIN32
1679 static int win32_start_timer(struct qemu_alarm_timer *t)
1681 TIMECAPS tc;
1682 struct qemu_alarm_win32 *data = t->priv;
1683 UINT flags;
1685 memset(&tc, 0, sizeof(tc));
1686 timeGetDevCaps(&tc, sizeof(tc));
1688 if (data->period < tc.wPeriodMin)
1689 data->period = tc.wPeriodMin;
1691 timeBeginPeriod(data->period);
1693 flags = TIME_CALLBACK_FUNCTION;
1694 if (alarm_has_dynticks(t))
1695 flags |= TIME_ONESHOT;
1696 else
1697 flags |= TIME_PERIODIC;
1699 data->timerId = timeSetEvent(1, // interval (ms)
1700 data->period, // resolution
1701 host_alarm_handler, // function
1702 (DWORD)t, // parameter
1703 flags);
1705 if (!data->timerId) {
1706 perror("Failed to initialize win32 alarm timer");
1707 timeEndPeriod(data->period);
1708 return -1;
1711 return 0;
1714 static void win32_stop_timer(struct qemu_alarm_timer *t)
1716 struct qemu_alarm_win32 *data = t->priv;
1718 timeKillEvent(data->timerId);
1719 timeEndPeriod(data->period);
1722 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1724 struct qemu_alarm_win32 *data = t->priv;
1725 uint64_t nearest_delta_us;
1727 if (!active_timers[QEMU_TIMER_REALTIME] &&
1728 !active_timers[QEMU_TIMER_VIRTUAL])
1729 return;
1731 nearest_delta_us = qemu_next_deadline_dyntick();
1732 nearest_delta_us /= 1000;
1734 timeKillEvent(data->timerId);
1736 data->timerId = timeSetEvent(1,
1737 data->period,
1738 host_alarm_handler,
1739 (DWORD)t,
1740 TIME_ONESHOT | TIME_PERIODIC);
1742 if (!data->timerId) {
1743 perror("Failed to re-arm win32 alarm timer");
1745 timeEndPeriod(data->period);
1746 exit(1);
1750 #endif /* _WIN32 */
1752 static int init_timer_alarm(void)
1754 struct qemu_alarm_timer *t = NULL;
1755 int i, err = -1;
1757 for (i = 0; alarm_timers[i].name; i++) {
1758 t = &alarm_timers[i];
1760 err = t->start(t);
1761 if (!err)
1762 break;
1765 if (err) {
1766 err = -ENOENT;
1767 goto fail;
1770 alarm_timer = t;
1772 return 0;
1774 fail:
1775 return err;
1778 static void quit_timers(void)
1780 alarm_timer->stop(alarm_timer);
1781 alarm_timer = NULL;
1784 /***********************************************************/
1785 /* host time/date access */
1786 void qemu_get_timedate(struct tm *tm, int offset)
1788 time_t ti;
1789 struct tm *ret;
1791 time(&ti);
1792 ti += offset;
1793 if (rtc_date_offset == -1) {
1794 if (rtc_utc)
1795 ret = gmtime(&ti);
1796 else
1797 ret = localtime(&ti);
1798 } else {
1799 ti -= rtc_date_offset;
1800 ret = gmtime(&ti);
1803 memcpy(tm, ret, sizeof(struct tm));
1806 int qemu_timedate_diff(struct tm *tm)
1808 time_t seconds;
1810 if (rtc_date_offset == -1)
1811 if (rtc_utc)
1812 seconds = mktimegm(tm);
1813 else
1814 seconds = mktime(tm);
1815 else
1816 seconds = mktimegm(tm) + rtc_date_offset;
1818 return seconds - time(NULL);
1821 #ifdef _WIN32
1822 static void socket_cleanup(void)
1824 WSACleanup();
1827 static int socket_init(void)
1829 WSADATA Data;
1830 int ret, err;
1832 ret = WSAStartup(MAKEWORD(2,2), &Data);
1833 if (ret != 0) {
1834 err = WSAGetLastError();
1835 fprintf(stderr, "WSAStartup: %d\n", err);
1836 return -1;
1838 atexit(socket_cleanup);
1839 return 0;
1841 #endif
1843 int get_param_value(char *buf, int buf_size,
1844 const char *tag, const char *str)
1846 const char *p;
1847 char option[128];
1849 p = str;
1850 for(;;) {
1851 p = get_opt_name(option, sizeof(option), p, '=');
1852 if (*p != '=')
1853 break;
1854 p++;
1855 if (!strcmp(tag, option)) {
1856 (void)get_opt_value(buf, buf_size, p);
1857 return strlen(buf);
1858 } else {
1859 p = get_opt_value(NULL, 0, p);
1861 if (*p != ',')
1862 break;
1863 p++;
1865 return 0;
1868 int check_params(const char * const *params, const char *str)
1870 int name_buf_size = 1;
1871 const char *p;
1872 char *name_buf;
1873 int i, len;
1874 int ret = 0;
1876 for (i = 0; params[i] != NULL; i++) {
1877 len = strlen(params[i]) + 1;
1878 if (len > name_buf_size) {
1879 name_buf_size = len;
1882 name_buf = qemu_malloc(name_buf_size);
1884 p = str;
1885 while (*p != '\0') {
1886 p = get_opt_name(name_buf, name_buf_size, p, '=');
1887 if (*p != '=') {
1888 ret = -1;
1889 break;
1891 p++;
1892 for(i = 0; params[i] != NULL; i++)
1893 if (!strcmp(params[i], name_buf))
1894 break;
1895 if (params[i] == NULL) {
1896 ret = -1;
1897 break;
1899 p = get_opt_value(NULL, 0, p);
1900 if (*p != ',')
1901 break;
1902 p++;
1905 qemu_free(name_buf);
1906 return ret;
1909 /***********************************************************/
1910 /* Bluetooth support */
1911 static int nb_hcis;
1912 static int cur_hci;
1913 static struct HCIInfo *hci_table[MAX_NICS];
1915 static struct bt_vlan_s {
1916 struct bt_scatternet_s net;
1917 int id;
1918 struct bt_vlan_s *next;
1919 } *first_bt_vlan;
1921 /* find or alloc a new bluetooth "VLAN" */
1922 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1924 struct bt_vlan_s **pvlan, *vlan;
1925 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1926 if (vlan->id == id)
1927 return &vlan->net;
1929 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1930 vlan->id = id;
1931 pvlan = &first_bt_vlan;
1932 while (*pvlan != NULL)
1933 pvlan = &(*pvlan)->next;
1934 *pvlan = vlan;
1935 return &vlan->net;
1938 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1942 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1944 return -ENOTSUP;
1947 static struct HCIInfo null_hci = {
1948 .cmd_send = null_hci_send,
1949 .sco_send = null_hci_send,
1950 .acl_send = null_hci_send,
1951 .bdaddr_set = null_hci_addr_set,
1954 struct HCIInfo *qemu_next_hci(void)
1956 if (cur_hci == nb_hcis)
1957 return &null_hci;
1959 return hci_table[cur_hci++];
1962 static struct HCIInfo *hci_init(const char *str)
1964 char *endp;
1965 struct bt_scatternet_s *vlan = 0;
1967 if (!strcmp(str, "null"))
1968 /* null */
1969 return &null_hci;
1970 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1971 /* host[:hciN] */
1972 return bt_host_hci(str[4] ? str + 5 : "hci0");
1973 else if (!strncmp(str, "hci", 3)) {
1974 /* hci[,vlan=n] */
1975 if (str[3]) {
1976 if (!strncmp(str + 3, ",vlan=", 6)) {
1977 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1978 if (*endp)
1979 vlan = 0;
1981 } else
1982 vlan = qemu_find_bt_vlan(0);
1983 if (vlan)
1984 return bt_new_hci(vlan);
1987 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1989 return 0;
1992 static int bt_hci_parse(const char *str)
1994 struct HCIInfo *hci;
1995 bdaddr_t bdaddr;
1997 if (nb_hcis >= MAX_NICS) {
1998 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1999 return -1;
2002 hci = hci_init(str);
2003 if (!hci)
2004 return -1;
2006 bdaddr.b[0] = 0x52;
2007 bdaddr.b[1] = 0x54;
2008 bdaddr.b[2] = 0x00;
2009 bdaddr.b[3] = 0x12;
2010 bdaddr.b[4] = 0x34;
2011 bdaddr.b[5] = 0x56 + nb_hcis;
2012 hci->bdaddr_set(hci, bdaddr.b);
2014 hci_table[nb_hcis++] = hci;
2016 return 0;
2019 static void bt_vhci_add(int vlan_id)
2021 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2023 if (!vlan->slave)
2024 fprintf(stderr, "qemu: warning: adding a VHCI to "
2025 "an empty scatternet %i\n", vlan_id);
2027 bt_vhci_init(bt_new_hci(vlan));
2030 static struct bt_device_s *bt_device_add(const char *opt)
2032 struct bt_scatternet_s *vlan;
2033 int vlan_id = 0;
2034 char *endp = strstr(opt, ",vlan=");
2035 int len = (endp ? endp - opt : strlen(opt)) + 1;
2036 char devname[10];
2038 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2040 if (endp) {
2041 vlan_id = strtol(endp + 6, &endp, 0);
2042 if (*endp) {
2043 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2044 return 0;
2048 vlan = qemu_find_bt_vlan(vlan_id);
2050 if (!vlan->slave)
2051 fprintf(stderr, "qemu: warning: adding a slave device to "
2052 "an empty scatternet %i\n", vlan_id);
2054 if (!strcmp(devname, "keyboard"))
2055 return bt_keyboard_init(vlan);
2057 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2058 return 0;
2061 static int bt_parse(const char *opt)
2063 const char *endp, *p;
2064 int vlan;
2066 if (strstart(opt, "hci", &endp)) {
2067 if (!*endp || *endp == ',') {
2068 if (*endp)
2069 if (!strstart(endp, ",vlan=", 0))
2070 opt = endp + 1;
2072 return bt_hci_parse(opt);
2074 } else if (strstart(opt, "vhci", &endp)) {
2075 if (!*endp || *endp == ',') {
2076 if (*endp) {
2077 if (strstart(endp, ",vlan=", &p)) {
2078 vlan = strtol(p, (char **) &endp, 0);
2079 if (*endp) {
2080 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2081 return 1;
2083 } else {
2084 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2085 return 1;
2087 } else
2088 vlan = 0;
2090 bt_vhci_add(vlan);
2091 return 0;
2093 } else if (strstart(opt, "device:", &endp))
2094 return !bt_device_add(endp);
2096 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2097 return 1;
2100 /***********************************************************/
2101 /* QEMU Block devices */
2103 #define HD_ALIAS "index=%d,media=disk"
2104 #define CDROM_ALIAS "index=2,media=cdrom"
2105 #define FD_ALIAS "index=%d,if=floppy"
2106 #define PFLASH_ALIAS "if=pflash"
2107 #define MTD_ALIAS "if=mtd"
2108 #define SD_ALIAS "index=0,if=sd"
2110 static int drive_opt_get_free_idx(void)
2112 int index;
2114 for (index = 0; index < MAX_DRIVES; index++)
2115 if (!drives_opt[index].used) {
2116 drives_opt[index].used = 1;
2117 return index;
2120 return -1;
2123 static int drive_get_free_idx(void)
2125 int index;
2127 for (index = 0; index < MAX_DRIVES; index++)
2128 if (!drives_table[index].used) {
2129 drives_table[index].used = 1;
2130 return index;
2133 return -1;
2136 int drive_add(const char *file, const char *fmt, ...)
2138 va_list ap;
2139 int index = drive_opt_get_free_idx();
2141 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2142 fprintf(stderr, "qemu: too many drives\n");
2143 return -1;
2146 drives_opt[index].file = file;
2147 va_start(ap, fmt);
2148 vsnprintf(drives_opt[index].opt,
2149 sizeof(drives_opt[0].opt), fmt, ap);
2150 va_end(ap);
2152 nb_drives_opt++;
2153 return index;
2156 void drive_remove(int index)
2158 drives_opt[index].used = 0;
2159 nb_drives_opt--;
2162 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2164 int index;
2166 /* seek interface, bus and unit */
2168 for (index = 0; index < MAX_DRIVES; index++)
2169 if (drives_table[index].type == type &&
2170 drives_table[index].bus == bus &&
2171 drives_table[index].unit == unit &&
2172 drives_table[index].used)
2173 return index;
2175 return -1;
2178 int drive_get_max_bus(BlockInterfaceType type)
2180 int max_bus;
2181 int index;
2183 max_bus = -1;
2184 for (index = 0; index < nb_drives; index++) {
2185 if(drives_table[index].type == type &&
2186 drives_table[index].bus > max_bus)
2187 max_bus = drives_table[index].bus;
2189 return max_bus;
2192 const char *drive_get_serial(BlockDriverState *bdrv)
2194 int index;
2196 for (index = 0; index < nb_drives; index++)
2197 if (drives_table[index].bdrv == bdrv)
2198 return drives_table[index].serial;
2200 return "\0";
2203 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2205 int index;
2207 for (index = 0; index < nb_drives; index++)
2208 if (drives_table[index].bdrv == bdrv)
2209 return drives_table[index].onerror;
2211 return BLOCK_ERR_STOP_ENOSPC;
2214 static void bdrv_format_print(void *opaque, const char *name)
2216 fprintf(stderr, " %s", name);
2219 void drive_uninit(BlockDriverState *bdrv)
2221 int i;
2223 for (i = 0; i < MAX_DRIVES; i++)
2224 if (drives_table[i].bdrv == bdrv) {
2225 drives_table[i].bdrv = NULL;
2226 drives_table[i].used = 0;
2227 drive_remove(drives_table[i].drive_opt_idx);
2228 nb_drives--;
2229 break;
2233 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2235 char buf[128];
2236 char file[1024];
2237 char devname[128];
2238 char serial[21];
2239 const char *mediastr = "";
2240 BlockInterfaceType type;
2241 enum { MEDIA_DISK, MEDIA_CDROM } media;
2242 int bus_id, unit_id;
2243 int cyls, heads, secs, translation;
2244 BlockDriverState *bdrv;
2245 BlockDriver *drv = NULL;
2246 QEMUMachine *machine = opaque;
2247 int max_devs;
2248 int index;
2249 int cache;
2250 int bdrv_flags, onerror;
2251 int drives_table_idx;
2252 char *str = arg->opt;
2253 static const char * const params[] = { "bus", "unit", "if", "index",
2254 "cyls", "heads", "secs", "trans",
2255 "media", "snapshot", "file",
2256 "cache", "format", "serial", "werror",
2257 "boot", NULL };
2259 if (check_params(params, str) < 0) {
2260 fprintf(stderr, "qemu: unknown parameter in '%s'\n", str);
2261 return -1;
2264 file[0] = 0;
2265 cyls = heads = secs = 0;
2266 bus_id = 0;
2267 unit_id = -1;
2268 translation = BIOS_ATA_TRANSLATION_AUTO;
2269 index = -1;
2270 cache = 3;
2272 if (machine->use_scsi) {
2273 type = IF_SCSI;
2274 max_devs = MAX_SCSI_DEVS;
2275 pstrcpy(devname, sizeof(devname), "scsi");
2276 } else {
2277 type = IF_IDE;
2278 max_devs = MAX_IDE_DEVS;
2279 pstrcpy(devname, sizeof(devname), "ide");
2281 media = MEDIA_DISK;
2283 /* extract parameters */
2285 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2286 bus_id = strtol(buf, NULL, 0);
2287 if (bus_id < 0) {
2288 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2289 return -1;
2293 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2294 unit_id = strtol(buf, NULL, 0);
2295 if (unit_id < 0) {
2296 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2297 return -1;
2301 if (get_param_value(buf, sizeof(buf), "if", str)) {
2302 pstrcpy(devname, sizeof(devname), buf);
2303 if (!strcmp(buf, "ide")) {
2304 type = IF_IDE;
2305 max_devs = MAX_IDE_DEVS;
2306 } else if (!strcmp(buf, "scsi")) {
2307 type = IF_SCSI;
2308 max_devs = MAX_SCSI_DEVS;
2309 } else if (!strcmp(buf, "floppy")) {
2310 type = IF_FLOPPY;
2311 max_devs = 0;
2312 } else if (!strcmp(buf, "pflash")) {
2313 type = IF_PFLASH;
2314 max_devs = 0;
2315 } else if (!strcmp(buf, "mtd")) {
2316 type = IF_MTD;
2317 max_devs = 0;
2318 } else if (!strcmp(buf, "sd")) {
2319 type = IF_SD;
2320 max_devs = 0;
2321 } else if (!strcmp(buf, "virtio")) {
2322 type = IF_VIRTIO;
2323 max_devs = 0;
2324 } else if (!strcmp(buf, "xen")) {
2325 type = IF_XEN;
2326 max_devs = 0;
2327 } else {
2328 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2329 return -1;
2333 if (get_param_value(buf, sizeof(buf), "index", str)) {
2334 index = strtol(buf, NULL, 0);
2335 if (index < 0) {
2336 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2337 return -1;
2341 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2342 cyls = strtol(buf, NULL, 0);
2345 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2346 heads = strtol(buf, NULL, 0);
2349 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2350 secs = strtol(buf, NULL, 0);
2353 if (cyls || heads || secs) {
2354 if (cyls < 1 || cyls > 16383) {
2355 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2356 return -1;
2358 if (heads < 1 || heads > 16) {
2359 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2360 return -1;
2362 if (secs < 1 || secs > 63) {
2363 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2364 return -1;
2368 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2369 if (!cyls) {
2370 fprintf(stderr,
2371 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2372 str);
2373 return -1;
2375 if (!strcmp(buf, "none"))
2376 translation = BIOS_ATA_TRANSLATION_NONE;
2377 else if (!strcmp(buf, "lba"))
2378 translation = BIOS_ATA_TRANSLATION_LBA;
2379 else if (!strcmp(buf, "auto"))
2380 translation = BIOS_ATA_TRANSLATION_AUTO;
2381 else {
2382 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2383 return -1;
2387 if (get_param_value(buf, sizeof(buf), "media", str)) {
2388 if (!strcmp(buf, "disk")) {
2389 media = MEDIA_DISK;
2390 } else if (!strcmp(buf, "cdrom")) {
2391 if (cyls || secs || heads) {
2392 fprintf(stderr,
2393 "qemu: '%s' invalid physical CHS format\n", str);
2394 return -1;
2396 media = MEDIA_CDROM;
2397 } else {
2398 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2399 return -1;
2403 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2404 if (!strcmp(buf, "on"))
2405 snapshot = 1;
2406 else if (!strcmp(buf, "off"))
2407 snapshot = 0;
2408 else {
2409 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2410 return -1;
2414 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2415 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2416 cache = 0;
2417 else if (!strcmp(buf, "writethrough"))
2418 cache = 1;
2419 else if (!strcmp(buf, "writeback"))
2420 cache = 2;
2421 else {
2422 fprintf(stderr, "qemu: invalid cache option\n");
2423 return -1;
2427 if (get_param_value(buf, sizeof(buf), "format", str)) {
2428 if (strcmp(buf, "?") == 0) {
2429 fprintf(stderr, "qemu: Supported formats:");
2430 bdrv_iterate_format(bdrv_format_print, NULL);
2431 fprintf(stderr, "\n");
2432 return -1;
2434 drv = bdrv_find_format(buf);
2435 if (!drv) {
2436 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2437 return -1;
2441 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2442 if (!strcmp(buf, "on")) {
2443 if (extboot_drive != -1) {
2444 fprintf(stderr, "qemu: two bootable drives specified\n");
2445 return -1;
2447 extboot_drive = nb_drives;
2448 } else if (strcmp(buf, "off")) {
2449 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2450 return -1;
2454 if (arg->file == NULL)
2455 get_param_value(file, sizeof(file), "file", str);
2456 else
2457 pstrcpy(file, sizeof(file), arg->file);
2459 if (!get_param_value(serial, sizeof(serial), "serial", str))
2460 memset(serial, 0, sizeof(serial));
2462 onerror = BLOCK_ERR_STOP_ENOSPC;
2463 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2464 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2465 fprintf(stderr, "werror is no supported by this format\n");
2466 return -1;
2468 if (!strcmp(buf, "ignore"))
2469 onerror = BLOCK_ERR_IGNORE;
2470 else if (!strcmp(buf, "enospc"))
2471 onerror = BLOCK_ERR_STOP_ENOSPC;
2472 else if (!strcmp(buf, "stop"))
2473 onerror = BLOCK_ERR_STOP_ANY;
2474 else if (!strcmp(buf, "report"))
2475 onerror = BLOCK_ERR_REPORT;
2476 else {
2477 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2478 return -1;
2482 /* compute bus and unit according index */
2484 if (index != -1) {
2485 if (bus_id != 0 || unit_id != -1) {
2486 fprintf(stderr,
2487 "qemu: '%s' index cannot be used with bus and unit\n", str);
2488 return -1;
2490 if (max_devs == 0)
2492 unit_id = index;
2493 bus_id = 0;
2494 } else {
2495 unit_id = index % max_devs;
2496 bus_id = index / max_devs;
2500 /* if user doesn't specify a unit_id,
2501 * try to find the first free
2504 if (unit_id == -1) {
2505 unit_id = 0;
2506 while (drive_get_index(type, bus_id, unit_id) != -1) {
2507 unit_id++;
2508 if (max_devs && unit_id >= max_devs) {
2509 unit_id -= max_devs;
2510 bus_id++;
2515 /* check unit id */
2517 if (max_devs && unit_id >= max_devs) {
2518 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2519 str, unit_id, max_devs - 1);
2520 return -1;
2524 * ignore multiple definitions
2527 if (drive_get_index(type, bus_id, unit_id) != -1)
2528 return -2;
2530 /* init */
2532 if (type == IF_IDE || type == IF_SCSI)
2533 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2534 if (max_devs)
2535 snprintf(buf, sizeof(buf), "%s%i%s%i",
2536 devname, bus_id, mediastr, unit_id);
2537 else
2538 snprintf(buf, sizeof(buf), "%s%s%i",
2539 devname, mediastr, unit_id);
2540 bdrv = bdrv_new(buf);
2541 drives_table_idx = drive_get_free_idx();
2542 drives_table[drives_table_idx].bdrv = bdrv;
2543 drives_table[drives_table_idx].type = type;
2544 drives_table[drives_table_idx].bus = bus_id;
2545 drives_table[drives_table_idx].unit = unit_id;
2546 drives_table[drives_table_idx].onerror = onerror;
2547 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2548 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2549 nb_drives++;
2551 switch(type) {
2552 case IF_IDE:
2553 case IF_SCSI:
2554 case IF_XEN:
2555 switch(media) {
2556 case MEDIA_DISK:
2557 if (cyls != 0) {
2558 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2559 bdrv_set_translation_hint(bdrv, translation);
2561 break;
2562 case MEDIA_CDROM:
2563 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2564 break;
2566 break;
2567 case IF_SD:
2568 /* FIXME: This isn't really a floppy, but it's a reasonable
2569 approximation. */
2570 case IF_FLOPPY:
2571 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2572 break;
2573 case IF_PFLASH:
2574 case IF_MTD:
2575 case IF_VIRTIO:
2576 break;
2577 case IF_COUNT:
2578 abort();
2580 if (!file[0])
2581 return -2;
2582 bdrv_flags = 0;
2583 if (snapshot) {
2584 bdrv_flags |= BDRV_O_SNAPSHOT;
2585 cache = 2; /* always use write-back with snapshot */
2587 if (cache == 0) /* no caching */
2588 bdrv_flags |= BDRV_O_NOCACHE;
2589 else if (cache == 2) /* write-back */
2590 bdrv_flags |= BDRV_O_CACHE_WB;
2591 else if (cache == 3) /* not specified */
2592 bdrv_flags |= BDRV_O_CACHE_DEF;
2593 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2594 fprintf(stderr, "qemu: could not open disk image %s\n",
2595 file);
2596 return -1;
2598 if (bdrv_key_required(bdrv))
2599 autostart = 0;
2600 return drives_table_idx;
2603 static void numa_add(const char *optarg)
2605 char option[128];
2606 char *endptr;
2607 unsigned long long value, endvalue;
2608 int nodenr;
2610 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2611 if (!strcmp(option, "node")) {
2612 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2613 nodenr = nb_numa_nodes;
2614 } else {
2615 nodenr = strtoull(option, NULL, 10);
2618 if (get_param_value(option, 128, "mem", optarg) == 0) {
2619 node_mem[nodenr] = 0;
2620 } else {
2621 value = strtoull(option, &endptr, 0);
2622 switch (*endptr) {
2623 case 0: case 'M': case 'm':
2624 value <<= 20;
2625 break;
2626 case 'G': case 'g':
2627 value <<= 30;
2628 break;
2630 node_mem[nodenr] = value;
2632 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2633 node_cpumask[nodenr] = 0;
2634 } else {
2635 value = strtoull(option, &endptr, 10);
2636 if (value >= 64) {
2637 value = 63;
2638 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2639 } else {
2640 if (*endptr == '-') {
2641 endvalue = strtoull(endptr+1, &endptr, 10);
2642 if (endvalue >= 63) {
2643 endvalue = 62;
2644 fprintf(stderr,
2645 "only 63 CPUs in NUMA mode supported.\n");
2647 value = (1 << (endvalue + 1)) - (1 << value);
2648 } else {
2649 value = 1 << value;
2652 node_cpumask[nodenr] = value;
2654 nb_numa_nodes++;
2656 return;
2659 /***********************************************************/
2660 /* USB devices */
2662 static USBPort *used_usb_ports;
2663 static USBPort *free_usb_ports;
2665 /* ??? Maybe change this to register a hub to keep track of the topology. */
2666 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2667 usb_attachfn attach)
2669 port->opaque = opaque;
2670 port->index = index;
2671 port->attach = attach;
2672 port->next = free_usb_ports;
2673 free_usb_ports = port;
2676 int usb_device_add_dev(USBDevice *dev)
2678 USBPort *port;
2680 /* Find a USB port to add the device to. */
2681 port = free_usb_ports;
2682 if (!port->next) {
2683 USBDevice *hub;
2685 /* Create a new hub and chain it on. */
2686 free_usb_ports = NULL;
2687 port->next = used_usb_ports;
2688 used_usb_ports = port;
2690 hub = usb_hub_init(VM_USB_HUB_SIZE);
2691 usb_attach(port, hub);
2692 port = free_usb_ports;
2695 free_usb_ports = port->next;
2696 port->next = used_usb_ports;
2697 used_usb_ports = port;
2698 usb_attach(port, dev);
2699 return 0;
2702 static void usb_msd_password_cb(void *opaque, int err)
2704 USBDevice *dev = opaque;
2706 if (!err)
2707 usb_device_add_dev(dev);
2708 else
2709 dev->handle_destroy(dev);
2712 static int usb_device_add(const char *devname, int is_hotplug)
2714 const char *p;
2715 USBDevice *dev;
2717 if (!free_usb_ports)
2718 return -1;
2720 if (strstart(devname, "host:", &p)) {
2721 dev = usb_host_device_open(p);
2722 } else if (!strcmp(devname, "mouse")) {
2723 dev = usb_mouse_init();
2724 } else if (!strcmp(devname, "tablet")) {
2725 dev = usb_tablet_init();
2726 } else if (!strcmp(devname, "keyboard")) {
2727 dev = usb_keyboard_init();
2728 } else if (strstart(devname, "disk:", &p)) {
2729 BlockDriverState *bs;
2731 dev = usb_msd_init(p);
2732 if (!dev)
2733 return -1;
2734 bs = usb_msd_get_bdrv(dev);
2735 if (bdrv_key_required(bs)) {
2736 autostart = 0;
2737 if (is_hotplug) {
2738 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2739 dev);
2740 return 0;
2743 } else if (!strcmp(devname, "wacom-tablet")) {
2744 dev = usb_wacom_init();
2745 } else if (strstart(devname, "serial:", &p)) {
2746 dev = usb_serial_init(p);
2747 #ifdef CONFIG_BRLAPI
2748 } else if (!strcmp(devname, "braille")) {
2749 dev = usb_baum_init();
2750 #endif
2751 } else if (strstart(devname, "net:", &p)) {
2752 int nic = nb_nics;
2754 if (net_client_init("nic", p) < 0)
2755 return -1;
2756 nd_table[nic].model = "usb";
2757 dev = usb_net_init(&nd_table[nic]);
2758 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2759 dev = usb_bt_init(devname[2] ? hci_init(p) :
2760 bt_new_hci(qemu_find_bt_vlan(0)));
2761 } else {
2762 return -1;
2764 if (!dev)
2765 return -1;
2767 return usb_device_add_dev(dev);
2770 int usb_device_del_addr(int bus_num, int addr)
2772 USBPort *port;
2773 USBPort **lastp;
2774 USBDevice *dev;
2776 if (!used_usb_ports)
2777 return -1;
2779 if (bus_num != 0)
2780 return -1;
2782 lastp = &used_usb_ports;
2783 port = used_usb_ports;
2784 while (port && port->dev->addr != addr) {
2785 lastp = &port->next;
2786 port = port->next;
2789 if (!port)
2790 return -1;
2792 dev = port->dev;
2793 *lastp = port->next;
2794 usb_attach(port, NULL);
2795 dev->handle_destroy(dev);
2796 port->next = free_usb_ports;
2797 free_usb_ports = port;
2798 return 0;
2801 static int usb_device_del(const char *devname)
2803 int bus_num, addr;
2804 const char *p;
2806 if (strstart(devname, "host:", &p))
2807 return usb_host_device_close(p);
2809 if (!used_usb_ports)
2810 return -1;
2812 p = strchr(devname, '.');
2813 if (!p)
2814 return -1;
2815 bus_num = strtoul(devname, NULL, 0);
2816 addr = strtoul(p + 1, NULL, 0);
2818 return usb_device_del_addr(bus_num, addr);
2821 void do_usb_add(Monitor *mon, const char *devname)
2823 usb_device_add(devname, 1);
2826 void do_usb_del(Monitor *mon, const char *devname)
2828 usb_device_del(devname);
2831 void usb_info(Monitor *mon)
2833 USBDevice *dev;
2834 USBPort *port;
2835 const char *speed_str;
2837 if (!usb_enabled) {
2838 monitor_printf(mon, "USB support not enabled\n");
2839 return;
2842 for (port = used_usb_ports; port; port = port->next) {
2843 dev = port->dev;
2844 if (!dev)
2845 continue;
2846 switch(dev->speed) {
2847 case USB_SPEED_LOW:
2848 speed_str = "1.5";
2849 break;
2850 case USB_SPEED_FULL:
2851 speed_str = "12";
2852 break;
2853 case USB_SPEED_HIGH:
2854 speed_str = "480";
2855 break;
2856 default:
2857 speed_str = "?";
2858 break;
2860 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2861 0, dev->addr, speed_str, dev->devname);
2865 /***********************************************************/
2866 /* PCMCIA/Cardbus */
2868 static struct pcmcia_socket_entry_s {
2869 PCMCIASocket *socket;
2870 struct pcmcia_socket_entry_s *next;
2871 } *pcmcia_sockets = 0;
2873 void pcmcia_socket_register(PCMCIASocket *socket)
2875 struct pcmcia_socket_entry_s *entry;
2877 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2878 entry->socket = socket;
2879 entry->next = pcmcia_sockets;
2880 pcmcia_sockets = entry;
2883 void pcmcia_socket_unregister(PCMCIASocket *socket)
2885 struct pcmcia_socket_entry_s *entry, **ptr;
2887 ptr = &pcmcia_sockets;
2888 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2889 if (entry->socket == socket) {
2890 *ptr = entry->next;
2891 qemu_free(entry);
2895 void pcmcia_info(Monitor *mon)
2897 struct pcmcia_socket_entry_s *iter;
2899 if (!pcmcia_sockets)
2900 monitor_printf(mon, "No PCMCIA sockets\n");
2902 for (iter = pcmcia_sockets; iter; iter = iter->next)
2903 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2904 iter->socket->attached ? iter->socket->card_string :
2905 "Empty");
2908 /***********************************************************/
2909 /* register display */
2911 struct DisplayAllocator default_allocator = {
2912 defaultallocator_create_displaysurface,
2913 defaultallocator_resize_displaysurface,
2914 defaultallocator_free_displaysurface
2917 void register_displaystate(DisplayState *ds)
2919 DisplayState **s;
2920 s = &display_state;
2921 while (*s != NULL)
2922 s = &(*s)->next;
2923 ds->next = NULL;
2924 *s = ds;
2927 DisplayState *get_displaystate(void)
2929 return display_state;
2932 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2934 if(ds->allocator == &default_allocator) ds->allocator = da;
2935 return ds->allocator;
2938 /* dumb display */
2940 static void dumb_display_init(void)
2942 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2943 ds->allocator = &default_allocator;
2944 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2945 register_displaystate(ds);
2948 /***********************************************************/
2949 /* I/O handling */
2951 typedef struct IOHandlerRecord {
2952 int fd;
2953 IOCanRWHandler *fd_read_poll;
2954 IOHandler *fd_read;
2955 IOHandler *fd_write;
2956 int deleted;
2957 void *opaque;
2958 /* temporary data */
2959 struct pollfd *ufd;
2960 struct IOHandlerRecord *next;
2961 } IOHandlerRecord;
2963 static IOHandlerRecord *first_io_handler;
2965 /* XXX: fd_read_poll should be suppressed, but an API change is
2966 necessary in the character devices to suppress fd_can_read(). */
2967 int qemu_set_fd_handler2(int fd,
2968 IOCanRWHandler *fd_read_poll,
2969 IOHandler *fd_read,
2970 IOHandler *fd_write,
2971 void *opaque)
2973 IOHandlerRecord **pioh, *ioh;
2975 if (!fd_read && !fd_write) {
2976 pioh = &first_io_handler;
2977 for(;;) {
2978 ioh = *pioh;
2979 if (ioh == NULL)
2980 break;
2981 if (ioh->fd == fd) {
2982 ioh->deleted = 1;
2983 break;
2985 pioh = &ioh->next;
2987 } else {
2988 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2989 if (ioh->fd == fd)
2990 goto found;
2992 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2993 ioh->next = first_io_handler;
2994 first_io_handler = ioh;
2995 found:
2996 ioh->fd = fd;
2997 ioh->fd_read_poll = fd_read_poll;
2998 ioh->fd_read = fd_read;
2999 ioh->fd_write = fd_write;
3000 ioh->opaque = opaque;
3001 ioh->deleted = 0;
3003 qemu_notify_event();
3004 return 0;
3007 int qemu_set_fd_handler(int fd,
3008 IOHandler *fd_read,
3009 IOHandler *fd_write,
3010 void *opaque)
3012 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3015 #ifdef _WIN32
3016 /***********************************************************/
3017 /* Polling handling */
3019 typedef struct PollingEntry {
3020 PollingFunc *func;
3021 void *opaque;
3022 struct PollingEntry *next;
3023 } PollingEntry;
3025 static PollingEntry *first_polling_entry;
3027 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3029 PollingEntry **ppe, *pe;
3030 pe = qemu_mallocz(sizeof(PollingEntry));
3031 pe->func = func;
3032 pe->opaque = opaque;
3033 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3034 *ppe = pe;
3035 return 0;
3038 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3040 PollingEntry **ppe, *pe;
3041 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3042 pe = *ppe;
3043 if (pe->func == func && pe->opaque == opaque) {
3044 *ppe = pe->next;
3045 qemu_free(pe);
3046 break;
3051 /***********************************************************/
3052 /* Wait objects support */
3053 typedef struct WaitObjects {
3054 int num;
3055 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3056 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3057 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3058 } WaitObjects;
3060 static WaitObjects wait_objects = {0};
3062 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3064 WaitObjects *w = &wait_objects;
3066 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3067 return -1;
3068 w->events[w->num] = handle;
3069 w->func[w->num] = func;
3070 w->opaque[w->num] = opaque;
3071 w->num++;
3072 return 0;
3075 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3077 int i, found;
3078 WaitObjects *w = &wait_objects;
3080 found = 0;
3081 for (i = 0; i < w->num; i++) {
3082 if (w->events[i] == handle)
3083 found = 1;
3084 if (found) {
3085 w->events[i] = w->events[i + 1];
3086 w->func[i] = w->func[i + 1];
3087 w->opaque[i] = w->opaque[i + 1];
3090 if (found)
3091 w->num--;
3093 #endif
3095 /***********************************************************/
3096 /* ram save/restore */
3098 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3100 int v;
3102 v = qemu_get_byte(f);
3103 switch(v) {
3104 case 0:
3105 if (qemu_get_buffer(f, buf, len) != len)
3106 return -EIO;
3107 break;
3108 case 1:
3109 v = qemu_get_byte(f);
3110 memset(buf, v, len);
3111 break;
3112 default:
3113 return -EINVAL;
3116 if (qemu_file_has_error(f))
3117 return -EIO;
3119 return 0;
3122 static int ram_load_v1(QEMUFile *f, void *opaque)
3124 int ret;
3125 ram_addr_t i;
3127 if (qemu_get_be32(f) != last_ram_offset)
3128 return -EINVAL;
3129 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3130 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3131 continue;
3132 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3133 if (ret)
3134 return ret;
3136 return 0;
3139 #define BDRV_HASH_BLOCK_SIZE 1024
3140 #define IOBUF_SIZE 4096
3141 #define RAM_CBLOCK_MAGIC 0xfabe
3143 typedef struct RamDecompressState {
3144 z_stream zstream;
3145 QEMUFile *f;
3146 uint8_t buf[IOBUF_SIZE];
3147 } RamDecompressState;
3149 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3151 int ret;
3152 memset(s, 0, sizeof(*s));
3153 s->f = f;
3154 ret = inflateInit(&s->zstream);
3155 if (ret != Z_OK)
3156 return -1;
3157 return 0;
3160 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3162 int ret, clen;
3164 s->zstream.avail_out = len;
3165 s->zstream.next_out = buf;
3166 while (s->zstream.avail_out > 0) {
3167 if (s->zstream.avail_in == 0) {
3168 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3169 return -1;
3170 clen = qemu_get_be16(s->f);
3171 if (clen > IOBUF_SIZE)
3172 return -1;
3173 qemu_get_buffer(s->f, s->buf, clen);
3174 s->zstream.avail_in = clen;
3175 s->zstream.next_in = s->buf;
3177 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3178 if (ret != Z_OK && ret != Z_STREAM_END) {
3179 return -1;
3182 return 0;
3185 static void ram_decompress_close(RamDecompressState *s)
3187 inflateEnd(&s->zstream);
3190 #define RAM_SAVE_FLAG_FULL 0x01
3191 #define RAM_SAVE_FLAG_COMPRESS 0x02
3192 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3193 #define RAM_SAVE_FLAG_PAGE 0x08
3194 #define RAM_SAVE_FLAG_EOS 0x10
3196 static int is_dup_page(uint8_t *page, uint8_t ch)
3198 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3199 uint32_t *array = (uint32_t *)page;
3200 int i;
3202 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3203 if (array[i] != val)
3204 return 0;
3207 return 1;
3210 static int ram_save_block(QEMUFile *f)
3212 static ram_addr_t current_addr = 0;
3213 ram_addr_t saved_addr = current_addr;
3214 ram_addr_t addr = 0;
3215 int found = 0;
3217 while (addr < last_ram_offset) {
3218 if (kvm_enabled() && current_addr == 0) {
3219 int r;
3220 r = kvm_update_dirty_pages_log();
3221 if (r) {
3222 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3223 qemu_file_set_error(f);
3224 return 0;
3227 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3228 uint8_t *p;
3230 cpu_physical_memory_reset_dirty(current_addr,
3231 current_addr + TARGET_PAGE_SIZE,
3232 MIGRATION_DIRTY_FLAG);
3234 p = qemu_get_ram_ptr(current_addr);
3236 if (is_dup_page(p, *p)) {
3237 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3238 qemu_put_byte(f, *p);
3239 } else {
3240 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3241 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3244 found = 1;
3245 break;
3247 addr += TARGET_PAGE_SIZE;
3248 current_addr = (saved_addr + addr) % last_ram_offset;
3251 return found;
3254 static ram_addr_t ram_save_threshold = 10;
3255 static uint64_t bytes_transferred = 0;
3257 static ram_addr_t ram_save_remaining(void)
3259 ram_addr_t addr;
3260 ram_addr_t count = 0;
3262 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3263 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3264 count++;
3267 return count;
3270 uint64_t ram_bytes_remaining(void)
3272 return ram_save_remaining() * TARGET_PAGE_SIZE;
3275 uint64_t ram_bytes_transferred(void)
3277 return bytes_transferred;
3280 uint64_t ram_bytes_total(void)
3282 return last_ram_offset;
3285 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3287 ram_addr_t addr;
3289 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3290 qemu_file_set_error(f);
3291 return 0;
3294 if (stage == 1) {
3295 /* Make sure all dirty bits are set */
3296 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3297 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3298 cpu_physical_memory_set_dirty(addr);
3301 /* Enable dirty memory tracking */
3302 cpu_physical_memory_set_dirty_tracking(1);
3304 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3307 while (!qemu_file_rate_limit(f)) {
3308 int ret;
3310 ret = ram_save_block(f);
3311 bytes_transferred += ret * TARGET_PAGE_SIZE;
3312 if (ret == 0) /* no more blocks */
3313 break;
3316 /* try transferring iterative blocks of memory */
3318 if (stage == 3) {
3320 /* flush all remaining blocks regardless of rate limiting */
3321 while (ram_save_block(f) != 0) {
3322 bytes_transferred += TARGET_PAGE_SIZE;
3324 cpu_physical_memory_set_dirty_tracking(0);
3327 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3329 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3332 static int ram_load_dead(QEMUFile *f, void *opaque)
3334 RamDecompressState s1, *s = &s1;
3335 uint8_t buf[10];
3336 ram_addr_t i;
3338 if (ram_decompress_open(s, f) < 0)
3339 return -EINVAL;
3340 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3341 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3342 continue;
3343 if (ram_decompress_buf(s, buf, 1) < 0) {
3344 fprintf(stderr, "Error while reading ram block header\n");
3345 goto error;
3347 if (buf[0] == 0) {
3348 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3349 BDRV_HASH_BLOCK_SIZE) < 0) {
3350 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3351 goto error;
3353 } else {
3354 error:
3355 printf("Error block header\n");
3356 return -EINVAL;
3359 ram_decompress_close(s);
3361 return 0;
3364 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3366 ram_addr_t addr;
3367 int flags;
3369 if (version_id == 1)
3370 return ram_load_v1(f, opaque);
3372 if (version_id == 2) {
3373 if (qemu_get_be32(f) != last_ram_offset)
3374 return -EINVAL;
3375 return ram_load_dead(f, opaque);
3378 if (version_id != 3)
3379 return -EINVAL;
3381 do {
3382 addr = qemu_get_be64(f);
3384 flags = addr & ~TARGET_PAGE_MASK;
3385 addr &= TARGET_PAGE_MASK;
3387 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3388 if (addr != last_ram_offset)
3389 return -EINVAL;
3392 if (flags & RAM_SAVE_FLAG_FULL) {
3393 if (ram_load_dead(f, opaque) < 0)
3394 return -EINVAL;
3397 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3398 uint8_t ch = qemu_get_byte(f);
3399 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3400 } else if (flags & RAM_SAVE_FLAG_PAGE)
3401 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3402 } while (!(flags & RAM_SAVE_FLAG_EOS));
3404 return 0;
3407 void qemu_service_io(void)
3409 qemu_notify_event();
3412 /***********************************************************/
3413 /* bottom halves (can be seen as timers which expire ASAP) */
3415 struct QEMUBH {
3416 QEMUBHFunc *cb;
3417 void *opaque;
3418 int scheduled;
3419 int idle;
3420 int deleted;
3421 QEMUBH *next;
3424 static QEMUBH *first_bh = NULL;
3426 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3428 QEMUBH *bh;
3429 bh = qemu_mallocz(sizeof(QEMUBH));
3430 bh->cb = cb;
3431 bh->opaque = opaque;
3432 bh->next = first_bh;
3433 first_bh = bh;
3434 return bh;
3437 int qemu_bh_poll(void)
3439 QEMUBH *bh, **bhp;
3440 int ret;
3442 ret = 0;
3443 for (bh = first_bh; bh; bh = bh->next) {
3444 if (!bh->deleted && bh->scheduled) {
3445 bh->scheduled = 0;
3446 if (!bh->idle)
3447 ret = 1;
3448 bh->idle = 0;
3449 bh->cb(bh->opaque);
3453 /* remove deleted bhs */
3454 bhp = &first_bh;
3455 while (*bhp) {
3456 bh = *bhp;
3457 if (bh->deleted) {
3458 *bhp = bh->next;
3459 qemu_free(bh);
3460 } else
3461 bhp = &bh->next;
3464 return ret;
3467 void qemu_bh_schedule_idle(QEMUBH *bh)
3469 if (bh->scheduled)
3470 return;
3471 bh->scheduled = 1;
3472 bh->idle = 1;
3475 void qemu_bh_schedule(QEMUBH *bh)
3477 if (bh->scheduled)
3478 return;
3479 bh->scheduled = 1;
3480 bh->idle = 0;
3481 /* stop the currently executing CPU to execute the BH ASAP */
3482 qemu_notify_event();
3485 void qemu_bh_cancel(QEMUBH *bh)
3487 bh->scheduled = 0;
3490 void qemu_bh_delete(QEMUBH *bh)
3492 bh->scheduled = 0;
3493 bh->deleted = 1;
3496 static void qemu_bh_update_timeout(int *timeout)
3498 QEMUBH *bh;
3500 for (bh = first_bh; bh; bh = bh->next) {
3501 if (!bh->deleted && bh->scheduled) {
3502 if (bh->idle) {
3503 /* idle bottom halves will be polled at least
3504 * every 10ms */
3505 *timeout = MIN(10, *timeout);
3506 } else {
3507 /* non-idle bottom halves will be executed
3508 * immediately */
3509 *timeout = 0;
3510 break;
3516 /***********************************************************/
3517 /* machine registration */
3519 static QEMUMachine *first_machine = NULL;
3520 QEMUMachine *current_machine = NULL;
3522 int qemu_register_machine(QEMUMachine *m)
3524 QEMUMachine **pm;
3525 pm = &first_machine;
3526 while (*pm != NULL)
3527 pm = &(*pm)->next;
3528 m->next = NULL;
3529 *pm = m;
3530 return 0;
3533 static QEMUMachine *find_machine(const char *name)
3535 QEMUMachine *m;
3537 for(m = first_machine; m != NULL; m = m->next) {
3538 if (!strcmp(m->name, name))
3539 return m;
3541 return NULL;
3544 static QEMUMachine *find_default_machine(void)
3546 QEMUMachine *m;
3548 for(m = first_machine; m != NULL; m = m->next) {
3549 if (m->is_default) {
3550 return m;
3553 return NULL;
3556 /***********************************************************/
3557 /* main execution loop */
3559 static void gui_update(void *opaque)
3561 uint64_t interval = GUI_REFRESH_INTERVAL;
3562 DisplayState *ds = opaque;
3563 DisplayChangeListener *dcl = ds->listeners;
3565 dpy_refresh(ds);
3567 while (dcl != NULL) {
3568 if (dcl->gui_timer_interval &&
3569 dcl->gui_timer_interval < interval)
3570 interval = dcl->gui_timer_interval;
3571 dcl = dcl->next;
3573 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3576 static void nographic_update(void *opaque)
3578 uint64_t interval = GUI_REFRESH_INTERVAL;
3580 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3583 struct vm_change_state_entry {
3584 VMChangeStateHandler *cb;
3585 void *opaque;
3586 LIST_ENTRY (vm_change_state_entry) entries;
3589 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3591 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3592 void *opaque)
3594 VMChangeStateEntry *e;
3596 e = qemu_mallocz(sizeof (*e));
3598 e->cb = cb;
3599 e->opaque = opaque;
3600 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3601 return e;
3604 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3606 LIST_REMOVE (e, entries);
3607 qemu_free (e);
3610 static void vm_state_notify(int running, int reason)
3612 VMChangeStateEntry *e;
3614 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3615 e->cb(e->opaque, running, reason);
3619 static void resume_all_vcpus(void);
3620 static void pause_all_vcpus(void);
3622 void vm_start(void)
3624 if (!vm_running) {
3625 cpu_enable_ticks();
3626 vm_running = 1;
3627 vm_state_notify(1, 0);
3628 qemu_rearm_alarm_timer(alarm_timer);
3629 resume_all_vcpus();
3633 /* reset/shutdown handler */
3635 typedef struct QEMUResetEntry {
3636 QEMUResetHandler *func;
3637 void *opaque;
3638 int order;
3639 struct QEMUResetEntry *next;
3640 } QEMUResetEntry;
3642 static QEMUResetEntry *first_reset_entry;
3643 static int reset_requested;
3644 static int shutdown_requested;
3645 static int powerdown_requested;
3646 static int debug_requested;
3647 static int vmstop_requested;
3649 int qemu_no_shutdown(void)
3651 int r = no_shutdown;
3652 no_shutdown = 0;
3653 return r;
3656 int qemu_shutdown_requested(void)
3658 int r = shutdown_requested;
3659 shutdown_requested = 0;
3660 return r;
3663 int qemu_reset_requested(void)
3665 int r = reset_requested;
3666 reset_requested = 0;
3667 return r;
3670 int qemu_powerdown_requested(void)
3672 int r = powerdown_requested;
3673 powerdown_requested = 0;
3674 return r;
3677 static int qemu_debug_requested(void)
3679 int r = debug_requested;
3680 debug_requested = 0;
3681 return r;
3684 static int qemu_vmstop_requested(void)
3686 int r = vmstop_requested;
3687 vmstop_requested = 0;
3688 return r;
3691 static void do_vm_stop(int reason)
3693 if (vm_running) {
3694 cpu_disable_ticks();
3695 vm_running = 0;
3696 pause_all_vcpus();
3697 vm_state_notify(0, reason);
3701 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
3703 QEMUResetEntry **pre, *re;
3705 pre = &first_reset_entry;
3706 while (*pre != NULL && (*pre)->order >= order) {
3707 pre = &(*pre)->next;
3709 re = qemu_mallocz(sizeof(QEMUResetEntry));
3710 re->func = func;
3711 re->opaque = opaque;
3712 re->order = order;
3713 re->next = NULL;
3714 *pre = re;
3717 void qemu_system_reset(void)
3719 QEMUResetEntry *re;
3721 /* reset all devices */
3722 for(re = first_reset_entry; re != NULL; re = re->next) {
3723 re->func(re->opaque);
3727 void qemu_system_reset_request(void)
3729 if (no_reboot) {
3730 shutdown_requested = 1;
3731 } else {
3732 reset_requested = 1;
3734 if (cpu_single_env) {
3735 qemu_kvm_cpu_stop(cpu_single_env);
3736 cpu_exit(cpu_single_env);
3738 qemu_notify_event();
3741 void qemu_system_shutdown_request(void)
3743 shutdown_requested = 1;
3744 qemu_notify_event();
3747 void qemu_system_powerdown_request(void)
3749 powerdown_requested = 1;
3750 qemu_notify_event();
3753 #ifdef CONFIG_IOTHREAD
3754 static void qemu_system_vmstop_request(int reason)
3756 vmstop_requested = reason;
3757 qemu_notify_event();
3759 #endif
3761 #ifndef _WIN32
3762 static int io_thread_fd = -1;
3764 static void qemu_event_increment(void)
3766 static const char byte = 0;
3768 if (io_thread_fd == -1)
3769 return;
3771 write(io_thread_fd, &byte, sizeof(byte));
3774 static void qemu_event_read(void *opaque)
3776 int fd = (unsigned long)opaque;
3777 ssize_t len;
3779 /* Drain the notify pipe */
3780 do {
3781 char buffer[512];
3782 len = read(fd, buffer, sizeof(buffer));
3783 } while ((len == -1 && errno == EINTR) || len > 0);
3786 static int qemu_event_init(void)
3788 int err;
3789 int fds[2];
3791 err = pipe(fds);
3792 if (err == -1)
3793 return -errno;
3795 err = fcntl_setfl(fds[0], O_NONBLOCK);
3796 if (err < 0)
3797 goto fail;
3799 err = fcntl_setfl(fds[1], O_NONBLOCK);
3800 if (err < 0)
3801 goto fail;
3803 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3804 (void *)(unsigned long)fds[0]);
3806 io_thread_fd = fds[1];
3807 return 0;
3809 fail:
3810 close(fds[0]);
3811 close(fds[1]);
3812 return err;
3814 #else
3815 HANDLE qemu_event_handle;
3817 static void dummy_event_handler(void *opaque)
3821 static int qemu_event_init(void)
3823 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3824 if (!qemu_event_handle) {
3825 perror("Failed CreateEvent");
3826 return -1;
3828 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3829 return 0;
3832 static void qemu_event_increment(void)
3834 SetEvent(qemu_event_handle);
3836 #endif
3838 static int cpu_can_run(CPUState *env)
3840 if (env->stop)
3841 return 0;
3842 if (env->stopped)
3843 return 0;
3844 return 1;
3847 #ifndef CONFIG_IOTHREAD
3848 static int qemu_init_main_loop(void)
3850 return qemu_event_init();
3853 void qemu_init_vcpu(void *_env)
3855 CPUState *env = _env;
3857 if (kvm_enabled())
3858 kvm_init_vcpu(env);
3859 return;
3862 int qemu_cpu_self(void *env)
3864 return 1;
3867 static void resume_all_vcpus(void)
3871 static void pause_all_vcpus(void)
3875 void qemu_cpu_kick(void *env)
3877 return;
3880 void qemu_notify_event(void)
3882 CPUState *env = cpu_single_env;
3884 if (kvm_enabled()) {
3885 qemu_kvm_notify_work();
3886 return;
3888 if (env) {
3889 cpu_exit(env);
3890 #ifdef USE_KQEMU
3891 if (env->kqemu_enabled)
3892 kqemu_cpu_interrupt(env);
3893 #endif
3897 #define qemu_mutex_lock_iothread() do { } while (0)
3898 #define qemu_mutex_unlock_iothread() do { } while (0)
3900 void vm_stop(int reason)
3902 do_vm_stop(reason);
3905 #else /* CONFIG_IOTHREAD */
3907 #include "qemu-thread.h"
3909 QemuMutex qemu_global_mutex;
3910 static QemuMutex qemu_fair_mutex;
3912 static QemuThread io_thread;
3914 static QemuThread *tcg_cpu_thread;
3915 static QemuCond *tcg_halt_cond;
3917 static int qemu_system_ready;
3918 /* cpu creation */
3919 static QemuCond qemu_cpu_cond;
3920 /* system init */
3921 static QemuCond qemu_system_cond;
3922 static QemuCond qemu_pause_cond;
3924 static void block_io_signals(void);
3925 static void unblock_io_signals(void);
3926 static int tcg_has_work(void);
3928 static int qemu_init_main_loop(void)
3930 int ret;
3932 ret = qemu_event_init();
3933 if (ret)
3934 return ret;
3936 qemu_cond_init(&qemu_pause_cond);
3937 qemu_mutex_init(&qemu_fair_mutex);
3938 qemu_mutex_init(&qemu_global_mutex);
3939 qemu_mutex_lock(&qemu_global_mutex);
3941 unblock_io_signals();
3942 qemu_thread_self(&io_thread);
3944 return 0;
3947 static void qemu_wait_io_event(CPUState *env)
3949 while (!tcg_has_work())
3950 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3952 qemu_mutex_unlock(&qemu_global_mutex);
3955 * Users of qemu_global_mutex can be starved, having no chance
3956 * to acquire it since this path will get to it first.
3957 * So use another lock to provide fairness.
3959 qemu_mutex_lock(&qemu_fair_mutex);
3960 qemu_mutex_unlock(&qemu_fair_mutex);
3962 qemu_mutex_lock(&qemu_global_mutex);
3963 if (env->stop) {
3964 env->stop = 0;
3965 env->stopped = 1;
3966 qemu_cond_signal(&qemu_pause_cond);
3970 static int qemu_cpu_exec(CPUState *env);
3972 static void *kvm_cpu_thread_fn(void *arg)
3974 CPUState *env = arg;
3976 block_io_signals();
3977 qemu_thread_self(env->thread);
3979 /* signal CPU creation */
3980 qemu_mutex_lock(&qemu_global_mutex);
3981 env->created = 1;
3982 qemu_cond_signal(&qemu_cpu_cond);
3984 /* and wait for machine initialization */
3985 while (!qemu_system_ready)
3986 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3988 while (1) {
3989 if (cpu_can_run(env))
3990 qemu_cpu_exec(env);
3991 qemu_wait_io_event(env);
3994 return NULL;
3997 static void tcg_cpu_exec(void);
3999 static void *tcg_cpu_thread_fn(void *arg)
4001 CPUState *env = arg;
4003 block_io_signals();
4004 qemu_thread_self(env->thread);
4006 /* signal CPU creation */
4007 qemu_mutex_lock(&qemu_global_mutex);
4008 for (env = first_cpu; env != NULL; env = env->next_cpu)
4009 env->created = 1;
4010 qemu_cond_signal(&qemu_cpu_cond);
4012 /* and wait for machine initialization */
4013 while (!qemu_system_ready)
4014 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4016 while (1) {
4017 tcg_cpu_exec();
4018 qemu_wait_io_event(cur_cpu);
4021 return NULL;
4024 void qemu_cpu_kick(void *_env)
4026 CPUState *env = _env;
4027 qemu_cond_broadcast(env->halt_cond);
4028 if (kvm_enabled())
4029 qemu_thread_signal(env->thread, SIGUSR1);
4032 int qemu_cpu_self(void *env)
4034 return (cpu_single_env != NULL);
4037 static void cpu_signal(int sig)
4039 if (cpu_single_env)
4040 cpu_exit(cpu_single_env);
4043 static void block_io_signals(void)
4045 sigset_t set;
4046 struct sigaction sigact;
4048 sigemptyset(&set);
4049 sigaddset(&set, SIGUSR2);
4050 sigaddset(&set, SIGIO);
4051 sigaddset(&set, SIGALRM);
4052 pthread_sigmask(SIG_BLOCK, &set, NULL);
4054 sigemptyset(&set);
4055 sigaddset(&set, SIGUSR1);
4056 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4058 memset(&sigact, 0, sizeof(sigact));
4059 sigact.sa_handler = cpu_signal;
4060 sigaction(SIGUSR1, &sigact, NULL);
4063 static void unblock_io_signals(void)
4065 sigset_t set;
4067 sigemptyset(&set);
4068 sigaddset(&set, SIGUSR2);
4069 sigaddset(&set, SIGIO);
4070 sigaddset(&set, SIGALRM);
4071 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4073 sigemptyset(&set);
4074 sigaddset(&set, SIGUSR1);
4075 pthread_sigmask(SIG_BLOCK, &set, NULL);
4078 static void qemu_signal_lock(unsigned int msecs)
4080 qemu_mutex_lock(&qemu_fair_mutex);
4082 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4083 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4084 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4085 break;
4087 qemu_mutex_unlock(&qemu_fair_mutex);
4090 static void qemu_mutex_lock_iothread(void)
4092 if (kvm_enabled()) {
4093 qemu_mutex_lock(&qemu_fair_mutex);
4094 qemu_mutex_lock(&qemu_global_mutex);
4095 qemu_mutex_unlock(&qemu_fair_mutex);
4096 } else
4097 qemu_signal_lock(100);
4100 static void qemu_mutex_unlock_iothread(void)
4102 qemu_mutex_unlock(&qemu_global_mutex);
4105 static int all_vcpus_paused(void)
4107 CPUState *penv = first_cpu;
4109 while (penv) {
4110 if (!penv->stopped)
4111 return 0;
4112 penv = (CPUState *)penv->next_cpu;
4115 return 1;
4118 static void pause_all_vcpus(void)
4120 CPUState *penv = first_cpu;
4122 while (penv) {
4123 penv->stop = 1;
4124 qemu_thread_signal(penv->thread, SIGUSR1);
4125 qemu_cpu_kick(penv);
4126 penv = (CPUState *)penv->next_cpu;
4129 while (!all_vcpus_paused()) {
4130 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4131 penv = first_cpu;
4132 while (penv) {
4133 qemu_thread_signal(penv->thread, SIGUSR1);
4134 penv = (CPUState *)penv->next_cpu;
4139 static void resume_all_vcpus(void)
4141 CPUState *penv = first_cpu;
4143 while (penv) {
4144 penv->stop = 0;
4145 penv->stopped = 0;
4146 qemu_thread_signal(penv->thread, SIGUSR1);
4147 qemu_cpu_kick(penv);
4148 penv = (CPUState *)penv->next_cpu;
4152 static void tcg_init_vcpu(void *_env)
4154 CPUState *env = _env;
4155 /* share a single thread for all cpus with TCG */
4156 if (!tcg_cpu_thread) {
4157 env->thread = qemu_mallocz(sizeof(QemuThread));
4158 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4159 qemu_cond_init(env->halt_cond);
4160 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4161 while (env->created == 0)
4162 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4163 tcg_cpu_thread = env->thread;
4164 tcg_halt_cond = env->halt_cond;
4165 } else {
4166 env->thread = tcg_cpu_thread;
4167 env->halt_cond = tcg_halt_cond;
4171 static void kvm_start_vcpu(CPUState *env)
4173 kvm_init_vcpu(env);
4174 env->thread = qemu_mallocz(sizeof(QemuThread));
4175 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4176 qemu_cond_init(env->halt_cond);
4177 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4178 while (env->created == 0)
4179 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4182 void qemu_init_vcpu(void *_env)
4184 CPUState *env = _env;
4186 if (kvm_enabled())
4187 kvm_start_vcpu(env);
4188 else
4189 tcg_init_vcpu(env);
4192 void qemu_notify_event(void)
4194 qemu_event_increment();
4197 void vm_stop(int reason)
4199 QemuThread me;
4200 qemu_thread_self(&me);
4202 if (!qemu_thread_equal(&me, &io_thread)) {
4203 qemu_system_vmstop_request(reason);
4205 * FIXME: should not return to device code in case
4206 * vm_stop() has been requested.
4208 if (cpu_single_env) {
4209 cpu_exit(cpu_single_env);
4210 cpu_single_env->stop = 1;
4212 return;
4214 do_vm_stop(reason);
4217 #endif
4220 #ifdef _WIN32
4221 static void host_main_loop_wait(int *timeout)
4223 int ret, ret2, i;
4224 PollingEntry *pe;
4227 /* XXX: need to suppress polling by better using win32 events */
4228 ret = 0;
4229 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4230 ret |= pe->func(pe->opaque);
4232 if (ret == 0) {
4233 int err;
4234 WaitObjects *w = &wait_objects;
4236 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4237 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4238 if (w->func[ret - WAIT_OBJECT_0])
4239 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4241 /* Check for additional signaled events */
4242 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4244 /* Check if event is signaled */
4245 ret2 = WaitForSingleObject(w->events[i], 0);
4246 if(ret2 == WAIT_OBJECT_0) {
4247 if (w->func[i])
4248 w->func[i](w->opaque[i]);
4249 } else if (ret2 == WAIT_TIMEOUT) {
4250 } else {
4251 err = GetLastError();
4252 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4255 } else if (ret == WAIT_TIMEOUT) {
4256 } else {
4257 err = GetLastError();
4258 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4262 *timeout = 0;
4264 #else
4265 static void host_main_loop_wait(int *timeout)
4268 #endif
4270 void main_loop_wait(int timeout)
4272 IOHandlerRecord *ioh;
4273 fd_set rfds, wfds, xfds;
4274 int ret, nfds;
4275 struct timeval tv;
4277 qemu_bh_update_timeout(&timeout);
4279 host_main_loop_wait(&timeout);
4281 /* poll any events */
4282 /* XXX: separate device handlers from system ones */
4283 nfds = -1;
4284 FD_ZERO(&rfds);
4285 FD_ZERO(&wfds);
4286 FD_ZERO(&xfds);
4287 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4288 if (ioh->deleted)
4289 continue;
4290 if (ioh->fd_read &&
4291 (!ioh->fd_read_poll ||
4292 ioh->fd_read_poll(ioh->opaque) != 0)) {
4293 FD_SET(ioh->fd, &rfds);
4294 if (ioh->fd > nfds)
4295 nfds = ioh->fd;
4297 if (ioh->fd_write) {
4298 FD_SET(ioh->fd, &wfds);
4299 if (ioh->fd > nfds)
4300 nfds = ioh->fd;
4304 tv.tv_sec = timeout / 1000;
4305 tv.tv_usec = (timeout % 1000) * 1000;
4307 #if defined(CONFIG_SLIRP)
4308 if (slirp_is_inited()) {
4309 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4311 #endif
4312 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4313 if (ret > 0) {
4314 IOHandlerRecord **pioh;
4316 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4317 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4318 ioh->fd_read(ioh->opaque);
4319 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4320 FD_CLR(ioh->fd, &rfds);
4322 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4323 ioh->fd_write(ioh->opaque);
4327 /* remove deleted IO handlers */
4328 pioh = &first_io_handler;
4329 while (*pioh) {
4330 ioh = *pioh;
4331 if (ioh->deleted) {
4332 *pioh = ioh->next;
4333 qemu_free(ioh);
4334 } else
4335 pioh = &ioh->next;
4338 #if defined(CONFIG_SLIRP)
4339 if (slirp_is_inited()) {
4340 if (ret < 0) {
4341 FD_ZERO(&rfds);
4342 FD_ZERO(&wfds);
4343 FD_ZERO(&xfds);
4345 slirp_select_poll(&rfds, &wfds, &xfds);
4347 #endif
4349 /* rearm timer, if not periodic */
4350 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4351 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4352 qemu_rearm_alarm_timer(alarm_timer);
4355 /* vm time timers */
4356 if (vm_running) {
4357 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4358 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4359 qemu_get_clock(vm_clock));
4362 /* real time timers */
4363 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4364 qemu_get_clock(rt_clock));
4366 /* Check bottom-halves last in case any of the earlier events triggered
4367 them. */
4368 qemu_bh_poll();
4372 static int qemu_cpu_exec(CPUState *env)
4374 int ret;
4375 #ifdef CONFIG_PROFILER
4376 int64_t ti;
4377 #endif
4379 #ifdef CONFIG_PROFILER
4380 ti = profile_getclock();
4381 #endif
4382 if (use_icount) {
4383 int64_t count;
4384 int decr;
4385 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4386 env->icount_decr.u16.low = 0;
4387 env->icount_extra = 0;
4388 count = qemu_next_deadline();
4389 count = (count + (1 << icount_time_shift) - 1)
4390 >> icount_time_shift;
4391 qemu_icount += count;
4392 decr = (count > 0xffff) ? 0xffff : count;
4393 count -= decr;
4394 env->icount_decr.u16.low = decr;
4395 env->icount_extra = count;
4397 ret = cpu_exec(env);
4398 #ifdef CONFIG_PROFILER
4399 qemu_time += profile_getclock() - ti;
4400 #endif
4401 if (use_icount) {
4402 /* Fold pending instructions back into the
4403 instruction counter, and clear the interrupt flag. */
4404 qemu_icount -= (env->icount_decr.u16.low
4405 + env->icount_extra);
4406 env->icount_decr.u32 = 0;
4407 env->icount_extra = 0;
4409 return ret;
4412 static void tcg_cpu_exec(void)
4414 int ret = 0;
4416 if (next_cpu == NULL)
4417 next_cpu = first_cpu;
4418 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4419 CPUState *env = cur_cpu = next_cpu;
4421 if (!vm_running)
4422 break;
4423 if (timer_alarm_pending) {
4424 timer_alarm_pending = 0;
4425 break;
4427 if (cpu_can_run(env))
4428 ret = qemu_cpu_exec(env);
4429 if (ret == EXCP_DEBUG) {
4430 gdb_set_stop_cpu(env);
4431 debug_requested = 1;
4432 break;
4437 static int cpu_has_work(CPUState *env)
4439 if (env->stop)
4440 return 1;
4441 if (env->stopped)
4442 return 0;
4443 if (!env->halted)
4444 return 1;
4445 if (qemu_cpu_has_work(env))
4446 return 1;
4447 return 0;
4450 static int tcg_has_work(void)
4452 CPUState *env;
4454 for (env = first_cpu; env != NULL; env = env->next_cpu)
4455 if (cpu_has_work(env))
4456 return 1;
4457 return 0;
4460 static int qemu_calculate_timeout(void)
4462 int timeout;
4464 if (!vm_running)
4465 timeout = 5000;
4466 else if (tcg_has_work())
4467 timeout = 0;
4468 else if (!use_icount)
4469 timeout = 5000;
4470 else {
4471 /* XXX: use timeout computed from timers */
4472 int64_t add;
4473 int64_t delta;
4474 /* Advance virtual time to the next event. */
4475 if (use_icount == 1) {
4476 /* When not using an adaptive execution frequency
4477 we tend to get badly out of sync with real time,
4478 so just delay for a reasonable amount of time. */
4479 delta = 0;
4480 } else {
4481 delta = cpu_get_icount() - cpu_get_clock();
4483 if (delta > 0) {
4484 /* If virtual time is ahead of real time then just
4485 wait for IO. */
4486 timeout = (delta / 1000000) + 1;
4487 } else {
4488 /* Wait for either IO to occur or the next
4489 timer event. */
4490 add = qemu_next_deadline();
4491 /* We advance the timer before checking for IO.
4492 Limit the amount we advance so that early IO
4493 activity won't get the guest too far ahead. */
4494 if (add > 10000000)
4495 add = 10000000;
4496 delta += add;
4497 add = (add + (1 << icount_time_shift) - 1)
4498 >> icount_time_shift;
4499 qemu_icount += add;
4500 timeout = delta / 1000000;
4501 if (timeout < 0)
4502 timeout = 0;
4506 return timeout;
4509 static int vm_can_run(void)
4511 if (powerdown_requested)
4512 return 0;
4513 if (reset_requested)
4514 return 0;
4515 if (shutdown_requested)
4516 return 0;
4517 if (debug_requested)
4518 return 0;
4519 return 1;
4522 static void main_loop(void)
4524 int r;
4526 if (kvm_enabled()) {
4527 kvm_main_loop();
4528 cpu_disable_ticks();
4529 return;
4532 #ifdef CONFIG_IOTHREAD
4533 qemu_system_ready = 1;
4534 qemu_cond_broadcast(&qemu_system_cond);
4535 #endif
4537 for (;;) {
4538 do {
4539 #ifdef CONFIG_PROFILER
4540 int64_t ti;
4541 #endif
4542 #ifndef CONFIG_IOTHREAD
4543 tcg_cpu_exec();
4544 #endif
4545 #ifdef CONFIG_PROFILER
4546 ti = profile_getclock();
4547 #endif
4548 #ifdef CONFIG_IOTHREAD
4549 main_loop_wait(1000);
4550 #else
4551 main_loop_wait(qemu_calculate_timeout());
4552 #endif
4553 #ifdef CONFIG_PROFILER
4554 dev_time += profile_getclock() - ti;
4555 #endif
4556 } while (vm_can_run());
4558 if (qemu_debug_requested())
4559 vm_stop(EXCP_DEBUG);
4560 if (qemu_shutdown_requested()) {
4561 if (no_shutdown) {
4562 vm_stop(0);
4563 no_shutdown = 0;
4564 } else
4565 break;
4567 if (qemu_reset_requested()) {
4568 pause_all_vcpus();
4569 qemu_system_reset();
4570 resume_all_vcpus();
4572 if (qemu_powerdown_requested())
4573 qemu_system_powerdown();
4574 if ((r = qemu_vmstop_requested()))
4575 vm_stop(r);
4577 pause_all_vcpus();
4580 static void version(void)
4582 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4585 static void help(int exitcode)
4587 version();
4588 printf("usage: %s [options] [disk_image]\n"
4589 "\n"
4590 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4591 "\n"
4592 #define DEF(option, opt_arg, opt_enum, opt_help) \
4593 opt_help
4594 #define DEFHEADING(text) stringify(text) "\n"
4595 #include "qemu-options.h"
4596 #undef DEF
4597 #undef DEFHEADING
4598 #undef GEN_DOCS
4599 "\n"
4600 "During emulation, the following keys are useful:\n"
4601 "ctrl-alt-f toggle full screen\n"
4602 "ctrl-alt-n switch to virtual console 'n'\n"
4603 "ctrl-alt toggle mouse and keyboard grab\n"
4604 "\n"
4605 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4607 "qemu",
4608 DEFAULT_RAM_SIZE,
4609 #ifndef _WIN32
4610 DEFAULT_NETWORK_SCRIPT,
4611 DEFAULT_NETWORK_DOWN_SCRIPT,
4612 #endif
4613 DEFAULT_GDBSTUB_PORT,
4614 "/tmp/qemu.log");
4615 exit(exitcode);
4618 #define HAS_ARG 0x0001
4620 enum {
4621 #define DEF(option, opt_arg, opt_enum, opt_help) \
4622 opt_enum,
4623 #define DEFHEADING(text)
4624 #include "qemu-options.h"
4625 #undef DEF
4626 #undef DEFHEADING
4627 #undef GEN_DOCS
4630 typedef struct QEMUOption {
4631 const char *name;
4632 int flags;
4633 int index;
4634 } QEMUOption;
4636 static const QEMUOption qemu_options[] = {
4637 { "h", 0, QEMU_OPTION_h },
4638 #define DEF(option, opt_arg, opt_enum, opt_help) \
4639 { option, opt_arg, opt_enum },
4640 #define DEFHEADING(text)
4641 #include "qemu-options.h"
4642 #undef DEF
4643 #undef DEFHEADING
4644 #undef GEN_DOCS
4645 { NULL },
4648 #ifdef HAS_AUDIO
4649 struct soundhw soundhw[] = {
4650 #ifdef HAS_AUDIO_CHOICE
4651 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4653 "pcspk",
4654 "PC speaker",
4657 { .init_isa = pcspk_audio_init }
4659 #endif
4661 #ifdef CONFIG_SB16
4663 "sb16",
4664 "Creative Sound Blaster 16",
4667 { .init_isa = SB16_init }
4669 #endif
4671 #ifdef CONFIG_CS4231A
4673 "cs4231a",
4674 "CS4231A",
4677 { .init_isa = cs4231a_init }
4679 #endif
4681 #ifdef CONFIG_ADLIB
4683 "adlib",
4684 #ifdef HAS_YMF262
4685 "Yamaha YMF262 (OPL3)",
4686 #else
4687 "Yamaha YM3812 (OPL2)",
4688 #endif
4691 { .init_isa = Adlib_init }
4693 #endif
4695 #ifdef CONFIG_GUS
4697 "gus",
4698 "Gravis Ultrasound GF1",
4701 { .init_isa = GUS_init }
4703 #endif
4705 #ifdef CONFIG_AC97
4707 "ac97",
4708 "Intel 82801AA AC97 Audio",
4711 { .init_pci = ac97_init }
4713 #endif
4715 #ifdef CONFIG_ES1370
4717 "es1370",
4718 "ENSONIQ AudioPCI ES1370",
4721 { .init_pci = es1370_init }
4723 #endif
4725 #endif /* HAS_AUDIO_CHOICE */
4727 { NULL, NULL, 0, 0, { NULL } }
4730 static void select_soundhw (const char *optarg)
4732 struct soundhw *c;
4734 if (*optarg == '?') {
4735 show_valid_cards:
4737 printf ("Valid sound card names (comma separated):\n");
4738 for (c = soundhw; c->name; ++c) {
4739 printf ("%-11s %s\n", c->name, c->descr);
4741 printf ("\n-soundhw all will enable all of the above\n");
4742 exit (*optarg != '?');
4744 else {
4745 size_t l;
4746 const char *p;
4747 char *e;
4748 int bad_card = 0;
4750 if (!strcmp (optarg, "all")) {
4751 for (c = soundhw; c->name; ++c) {
4752 c->enabled = 1;
4754 return;
4757 p = optarg;
4758 while (*p) {
4759 e = strchr (p, ',');
4760 l = !e ? strlen (p) : (size_t) (e - p);
4762 for (c = soundhw; c->name; ++c) {
4763 if (!strncmp (c->name, p, l)) {
4764 c->enabled = 1;
4765 break;
4769 if (!c->name) {
4770 if (l > 80) {
4771 fprintf (stderr,
4772 "Unknown sound card name (too big to show)\n");
4774 else {
4775 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4776 (int) l, p);
4778 bad_card = 1;
4780 p += l + (e != NULL);
4783 if (bad_card)
4784 goto show_valid_cards;
4787 #endif
4789 static void select_vgahw (const char *p)
4791 const char *opts;
4793 cirrus_vga_enabled = 0;
4794 std_vga_enabled = 0;
4795 vmsvga_enabled = 0;
4796 xenfb_enabled = 0;
4797 if (strstart(p, "std", &opts)) {
4798 std_vga_enabled = 1;
4799 } else if (strstart(p, "cirrus", &opts)) {
4800 cirrus_vga_enabled = 1;
4801 } else if (strstart(p, "vmware", &opts)) {
4802 vmsvga_enabled = 1;
4803 } else if (strstart(p, "xenfb", &opts)) {
4804 xenfb_enabled = 1;
4805 } else if (!strstart(p, "none", &opts)) {
4806 invalid_vga:
4807 fprintf(stderr, "Unknown vga type: %s\n", p);
4808 exit(1);
4810 while (*opts) {
4811 const char *nextopt;
4813 if (strstart(opts, ",retrace=", &nextopt)) {
4814 opts = nextopt;
4815 if (strstart(opts, "dumb", &nextopt))
4816 vga_retrace_method = VGA_RETRACE_DUMB;
4817 else if (strstart(opts, "precise", &nextopt))
4818 vga_retrace_method = VGA_RETRACE_PRECISE;
4819 else goto invalid_vga;
4820 } else goto invalid_vga;
4821 opts = nextopt;
4825 #ifdef _WIN32
4826 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4828 exit(STATUS_CONTROL_C_EXIT);
4829 return TRUE;
4831 #endif
4833 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4835 int ret;
4837 if(strlen(str) != 36)
4838 return -1;
4840 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4841 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4842 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4844 if(ret != 16)
4845 return -1;
4847 #ifdef TARGET_I386
4848 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4849 #endif
4851 return 0;
4854 #define MAX_NET_CLIENTS 32
4856 #ifndef _WIN32
4858 static void termsig_handler(int signal)
4860 qemu_system_shutdown_request();
4863 static void termsig_setup(void)
4865 struct sigaction act;
4867 memset(&act, 0, sizeof(act));
4868 act.sa_handler = termsig_handler;
4869 sigaction(SIGINT, &act, NULL);
4870 sigaction(SIGHUP, &act, NULL);
4871 sigaction(SIGTERM, &act, NULL);
4874 #endif
4876 int main(int argc, char **argv, char **envp)
4878 const char *gdbstub_dev = NULL;
4879 uint32_t boot_devices_bitmap = 0;
4880 int i;
4881 int snapshot, linux_boot, net_boot;
4882 const char *initrd_filename;
4883 const char *kernel_filename, *kernel_cmdline;
4884 const char *boot_devices = "";
4885 DisplayState *ds;
4886 DisplayChangeListener *dcl;
4887 int cyls, heads, secs, translation;
4888 const char *net_clients[MAX_NET_CLIENTS];
4889 int nb_net_clients;
4890 const char *bt_opts[MAX_BT_CMDLINE];
4891 int nb_bt_opts;
4892 int hda_index;
4893 int optind;
4894 const char *r, *optarg;
4895 CharDriverState *monitor_hd = NULL;
4896 const char *monitor_device;
4897 const char *serial_devices[MAX_SERIAL_PORTS];
4898 int serial_device_index;
4899 const char *parallel_devices[MAX_PARALLEL_PORTS];
4900 int parallel_device_index;
4901 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4902 int virtio_console_index;
4903 const char *loadvm = NULL;
4904 QEMUMachine *machine;
4905 const char *cpu_model;
4906 const char *usb_devices[MAX_USB_CMDLINE];
4907 int usb_devices_index;
4908 #ifndef _WIN32
4909 int fds[2];
4910 #endif
4911 int tb_size;
4912 const char *pid_file = NULL;
4913 const char *incoming = NULL;
4914 #ifndef _WIN32
4915 int fd = 0;
4916 struct passwd *pwd = NULL;
4917 const char *chroot_dir = NULL;
4918 const char *run_as = NULL;
4919 #endif
4920 CPUState *env;
4921 int show_vnc_port = 0;
4923 qemu_cache_utils_init(envp);
4925 LIST_INIT (&vm_change_state_head);
4926 #ifndef _WIN32
4928 struct sigaction act;
4929 sigfillset(&act.sa_mask);
4930 act.sa_flags = 0;
4931 act.sa_handler = SIG_IGN;
4932 sigaction(SIGPIPE, &act, NULL);
4934 #else
4935 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4936 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4937 QEMU to run on a single CPU */
4939 HANDLE h;
4940 DWORD mask, smask;
4941 int i;
4942 h = GetCurrentProcess();
4943 if (GetProcessAffinityMask(h, &mask, &smask)) {
4944 for(i = 0; i < 32; i++) {
4945 if (mask & (1 << i))
4946 break;
4948 if (i != 32) {
4949 mask = 1 << i;
4950 SetProcessAffinityMask(h, mask);
4954 #endif
4956 module_call_init(MODULE_INIT_MACHINE);
4957 machine = find_default_machine();
4958 cpu_model = NULL;
4959 initrd_filename = NULL;
4960 ram_size = 0;
4961 snapshot = 0;
4962 kernel_filename = NULL;
4963 kernel_cmdline = "";
4964 cyls = heads = secs = 0;
4965 translation = BIOS_ATA_TRANSLATION_AUTO;
4966 monitor_device = "vc:80Cx24C";
4968 serial_devices[0] = "vc:80Cx24C";
4969 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4970 serial_devices[i] = NULL;
4971 serial_device_index = 0;
4973 parallel_devices[0] = "vc:80Cx24C";
4974 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4975 parallel_devices[i] = NULL;
4976 parallel_device_index = 0;
4978 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4979 virtio_consoles[i] = NULL;
4980 virtio_console_index = 0;
4982 for (i = 0; i < MAX_NODES; i++) {
4983 node_mem[i] = 0;
4984 node_cpumask[i] = 0;
4987 usb_devices_index = 0;
4988 assigned_devices_index = 0;
4990 nb_net_clients = 0;
4991 nb_bt_opts = 0;
4992 nb_drives = 0;
4993 nb_drives_opt = 0;
4994 nb_numa_nodes = 0;
4995 hda_index = -1;
4997 nb_nics = 0;
4999 tb_size = 0;
5000 autostart= 1;
5002 register_watchdogs();
5004 optind = 1;
5005 for(;;) {
5006 if (optind >= argc)
5007 break;
5008 r = argv[optind];
5009 if (r[0] != '-') {
5010 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5011 } else {
5012 const QEMUOption *popt;
5014 optind++;
5015 /* Treat --foo the same as -foo. */
5016 if (r[1] == '-')
5017 r++;
5018 popt = qemu_options;
5019 for(;;) {
5020 if (!popt->name) {
5021 fprintf(stderr, "%s: invalid option -- '%s'\n",
5022 argv[0], r);
5023 exit(1);
5025 if (!strcmp(popt->name, r + 1))
5026 break;
5027 popt++;
5029 if (popt->flags & HAS_ARG) {
5030 if (optind >= argc) {
5031 fprintf(stderr, "%s: option '%s' requires an argument\n",
5032 argv[0], r);
5033 exit(1);
5035 optarg = argv[optind++];
5036 } else {
5037 optarg = NULL;
5040 switch(popt->index) {
5041 case QEMU_OPTION_M:
5042 machine = find_machine(optarg);
5043 if (!machine) {
5044 QEMUMachine *m;
5045 printf("Supported machines are:\n");
5046 for(m = first_machine; m != NULL; m = m->next) {
5047 printf("%-10s %s%s\n",
5048 m->name, m->desc,
5049 m->is_default ? " (default)" : "");
5051 exit(*optarg != '?');
5053 break;
5054 case QEMU_OPTION_cpu:
5055 /* hw initialization will check this */
5056 if (*optarg == '?') {
5057 /* XXX: implement xxx_cpu_list for targets that still miss it */
5058 #if defined(cpu_list)
5059 cpu_list(stdout, &fprintf);
5060 #endif
5061 exit(0);
5062 } else {
5063 cpu_model = optarg;
5065 break;
5066 case QEMU_OPTION_initrd:
5067 initrd_filename = optarg;
5068 break;
5069 case QEMU_OPTION_hda:
5070 if (cyls == 0)
5071 hda_index = drive_add(optarg, HD_ALIAS, 0);
5072 else
5073 hda_index = drive_add(optarg, HD_ALIAS
5074 ",cyls=%d,heads=%d,secs=%d%s",
5075 0, cyls, heads, secs,
5076 translation == BIOS_ATA_TRANSLATION_LBA ?
5077 ",trans=lba" :
5078 translation == BIOS_ATA_TRANSLATION_NONE ?
5079 ",trans=none" : "");
5080 break;
5081 case QEMU_OPTION_hdb:
5082 case QEMU_OPTION_hdc:
5083 case QEMU_OPTION_hdd:
5084 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5085 break;
5086 case QEMU_OPTION_drive:
5087 drive_add(NULL, "%s", optarg);
5088 break;
5089 case QEMU_OPTION_mtdblock:
5090 drive_add(optarg, MTD_ALIAS);
5091 break;
5092 case QEMU_OPTION_sd:
5093 drive_add(optarg, SD_ALIAS);
5094 break;
5095 case QEMU_OPTION_pflash:
5096 drive_add(optarg, PFLASH_ALIAS);
5097 break;
5098 case QEMU_OPTION_snapshot:
5099 snapshot = 1;
5100 break;
5101 case QEMU_OPTION_hdachs:
5103 const char *p;
5104 p = optarg;
5105 cyls = strtol(p, (char **)&p, 0);
5106 if (cyls < 1 || cyls > 16383)
5107 goto chs_fail;
5108 if (*p != ',')
5109 goto chs_fail;
5110 p++;
5111 heads = strtol(p, (char **)&p, 0);
5112 if (heads < 1 || heads > 16)
5113 goto chs_fail;
5114 if (*p != ',')
5115 goto chs_fail;
5116 p++;
5117 secs = strtol(p, (char **)&p, 0);
5118 if (secs < 1 || secs > 63)
5119 goto chs_fail;
5120 if (*p == ',') {
5121 p++;
5122 if (!strcmp(p, "none"))
5123 translation = BIOS_ATA_TRANSLATION_NONE;
5124 else if (!strcmp(p, "lba"))
5125 translation = BIOS_ATA_TRANSLATION_LBA;
5126 else if (!strcmp(p, "auto"))
5127 translation = BIOS_ATA_TRANSLATION_AUTO;
5128 else
5129 goto chs_fail;
5130 } else if (*p != '\0') {
5131 chs_fail:
5132 fprintf(stderr, "qemu: invalid physical CHS format\n");
5133 exit(1);
5135 if (hda_index != -1)
5136 snprintf(drives_opt[hda_index].opt,
5137 sizeof(drives_opt[hda_index].opt),
5138 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5139 0, cyls, heads, secs,
5140 translation == BIOS_ATA_TRANSLATION_LBA ?
5141 ",trans=lba" :
5142 translation == BIOS_ATA_TRANSLATION_NONE ?
5143 ",trans=none" : "");
5145 break;
5146 case QEMU_OPTION_numa:
5147 if (nb_numa_nodes >= MAX_NODES) {
5148 fprintf(stderr, "qemu: too many NUMA nodes\n");
5149 exit(1);
5151 numa_add(optarg);
5152 break;
5153 case QEMU_OPTION_nographic:
5154 display_type = DT_NOGRAPHIC;
5155 break;
5156 #ifdef CONFIG_CURSES
5157 case QEMU_OPTION_curses:
5158 display_type = DT_CURSES;
5159 break;
5160 #endif
5161 case QEMU_OPTION_portrait:
5162 graphic_rotate = 1;
5163 break;
5164 case QEMU_OPTION_kernel:
5165 kernel_filename = optarg;
5166 break;
5167 case QEMU_OPTION_append:
5168 kernel_cmdline = optarg;
5169 break;
5170 case QEMU_OPTION_cdrom:
5171 drive_add(optarg, CDROM_ALIAS);
5172 break;
5173 case QEMU_OPTION_boot:
5174 boot_devices = optarg;
5175 /* We just do some generic consistency checks */
5177 /* Could easily be extended to 64 devices if needed */
5178 const char *p;
5180 boot_devices_bitmap = 0;
5181 for (p = boot_devices; *p != '\0'; p++) {
5182 /* Allowed boot devices are:
5183 * a b : floppy disk drives
5184 * c ... f : IDE disk drives
5185 * g ... m : machine implementation dependant drives
5186 * n ... p : network devices
5187 * It's up to each machine implementation to check
5188 * if the given boot devices match the actual hardware
5189 * implementation and firmware features.
5191 if (*p < 'a' || *p > 'q') {
5192 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5193 exit(1);
5195 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5196 fprintf(stderr,
5197 "Boot device '%c' was given twice\n",*p);
5198 exit(1);
5200 boot_devices_bitmap |= 1 << (*p - 'a');
5203 break;
5204 case QEMU_OPTION_fda:
5205 case QEMU_OPTION_fdb:
5206 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5207 break;
5208 #ifdef TARGET_I386
5209 case QEMU_OPTION_no_fd_bootchk:
5210 fd_bootchk = 0;
5211 break;
5212 #endif
5213 case QEMU_OPTION_net:
5214 if (nb_net_clients >= MAX_NET_CLIENTS) {
5215 fprintf(stderr, "qemu: too many network clients\n");
5216 exit(1);
5218 net_clients[nb_net_clients] = optarg;
5219 nb_net_clients++;
5220 break;
5221 #ifdef CONFIG_SLIRP
5222 case QEMU_OPTION_tftp:
5223 tftp_prefix = optarg;
5224 break;
5225 case QEMU_OPTION_bootp:
5226 bootp_filename = optarg;
5227 break;
5228 #ifndef _WIN32
5229 case QEMU_OPTION_smb:
5230 net_slirp_smb(optarg);
5231 break;
5232 #endif
5233 case QEMU_OPTION_redir:
5234 net_slirp_redir(NULL, optarg, NULL);
5235 break;
5236 #endif
5237 case QEMU_OPTION_bt:
5238 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5239 fprintf(stderr, "qemu: too many bluetooth options\n");
5240 exit(1);
5242 bt_opts[nb_bt_opts++] = optarg;
5243 break;
5244 #ifdef HAS_AUDIO
5245 case QEMU_OPTION_audio_help:
5246 AUD_help ();
5247 exit (0);
5248 break;
5249 case QEMU_OPTION_soundhw:
5250 select_soundhw (optarg);
5251 break;
5252 #endif
5253 case QEMU_OPTION_h:
5254 help(0);
5255 break;
5256 case QEMU_OPTION_version:
5257 version();
5258 exit(0);
5259 break;
5260 case QEMU_OPTION_m: {
5261 uint64_t value;
5262 char *ptr;
5264 value = strtoul(optarg, &ptr, 10);
5265 switch (*ptr) {
5266 case 0: case 'M': case 'm':
5267 value <<= 20;
5268 break;
5269 case 'G': case 'g':
5270 value <<= 30;
5271 break;
5272 default:
5273 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5274 exit(1);
5277 /* On 32-bit hosts, QEMU is limited by virtual address space */
5278 if (value > (2047 << 20)
5279 #ifndef CONFIG_KQEMU
5280 && HOST_LONG_BITS == 32
5281 #endif
5283 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5284 exit(1);
5286 if (value != (uint64_t)(ram_addr_t)value) {
5287 fprintf(stderr, "qemu: ram size too large\n");
5288 exit(1);
5290 ram_size = value;
5291 break;
5293 case QEMU_OPTION_d:
5295 int mask;
5296 const CPULogItem *item;
5298 mask = cpu_str_to_log_mask(optarg);
5299 if (!mask) {
5300 printf("Log items (comma separated):\n");
5301 for(item = cpu_log_items; item->mask != 0; item++) {
5302 printf("%-10s %s\n", item->name, item->help);
5304 exit(1);
5306 cpu_set_log(mask);
5308 break;
5309 case QEMU_OPTION_s:
5310 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5311 break;
5312 case QEMU_OPTION_gdb:
5313 gdbstub_dev = optarg;
5314 break;
5315 case QEMU_OPTION_L:
5316 bios_dir = optarg;
5317 break;
5318 case QEMU_OPTION_bios:
5319 bios_name = optarg;
5320 break;
5321 case QEMU_OPTION_singlestep:
5322 singlestep = 1;
5323 break;
5324 case QEMU_OPTION_S:
5325 autostart = 0;
5326 break;
5327 #ifndef _WIN32
5328 case QEMU_OPTION_k:
5329 keyboard_layout = optarg;
5330 break;
5331 #endif
5332 case QEMU_OPTION_localtime:
5333 rtc_utc = 0;
5334 break;
5335 case QEMU_OPTION_vga:
5336 select_vgahw (optarg);
5337 break;
5338 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5339 case QEMU_OPTION_g:
5341 const char *p;
5342 int w, h, depth;
5343 p = optarg;
5344 w = strtol(p, (char **)&p, 10);
5345 if (w <= 0) {
5346 graphic_error:
5347 fprintf(stderr, "qemu: invalid resolution or depth\n");
5348 exit(1);
5350 if (*p != 'x')
5351 goto graphic_error;
5352 p++;
5353 h = strtol(p, (char **)&p, 10);
5354 if (h <= 0)
5355 goto graphic_error;
5356 if (*p == 'x') {
5357 p++;
5358 depth = strtol(p, (char **)&p, 10);
5359 if (depth != 8 && depth != 15 && depth != 16 &&
5360 depth != 24 && depth != 32)
5361 goto graphic_error;
5362 } else if (*p == '\0') {
5363 depth = graphic_depth;
5364 } else {
5365 goto graphic_error;
5368 graphic_width = w;
5369 graphic_height = h;
5370 graphic_depth = depth;
5372 break;
5373 #endif
5374 case QEMU_OPTION_echr:
5376 char *r;
5377 term_escape_char = strtol(optarg, &r, 0);
5378 if (r == optarg)
5379 printf("Bad argument to echr\n");
5380 break;
5382 case QEMU_OPTION_monitor:
5383 monitor_device = optarg;
5384 break;
5385 case QEMU_OPTION_serial:
5386 if (serial_device_index >= MAX_SERIAL_PORTS) {
5387 fprintf(stderr, "qemu: too many serial ports\n");
5388 exit(1);
5390 serial_devices[serial_device_index] = optarg;
5391 serial_device_index++;
5392 break;
5393 case QEMU_OPTION_watchdog:
5394 i = select_watchdog(optarg);
5395 if (i > 0)
5396 exit (i == 1 ? 1 : 0);
5397 break;
5398 case QEMU_OPTION_watchdog_action:
5399 if (select_watchdog_action(optarg) == -1) {
5400 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5401 exit(1);
5403 break;
5404 case QEMU_OPTION_virtiocon:
5405 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5406 fprintf(stderr, "qemu: too many virtio consoles\n");
5407 exit(1);
5409 virtio_consoles[virtio_console_index] = optarg;
5410 virtio_console_index++;
5411 break;
5412 case QEMU_OPTION_parallel:
5413 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5414 fprintf(stderr, "qemu: too many parallel ports\n");
5415 exit(1);
5417 parallel_devices[parallel_device_index] = optarg;
5418 parallel_device_index++;
5419 break;
5420 case QEMU_OPTION_loadvm:
5421 loadvm = optarg;
5422 break;
5423 case QEMU_OPTION_full_screen:
5424 full_screen = 1;
5425 break;
5426 #ifdef CONFIG_SDL
5427 case QEMU_OPTION_no_frame:
5428 no_frame = 1;
5429 break;
5430 case QEMU_OPTION_alt_grab:
5431 alt_grab = 1;
5432 break;
5433 case QEMU_OPTION_no_quit:
5434 no_quit = 1;
5435 break;
5436 case QEMU_OPTION_sdl:
5437 display_type = DT_SDL;
5438 break;
5439 #endif
5440 case QEMU_OPTION_pidfile:
5441 pid_file = optarg;
5442 break;
5443 #ifdef TARGET_I386
5444 case QEMU_OPTION_win2k_hack:
5445 win2k_install_hack = 1;
5446 break;
5447 case QEMU_OPTION_rtc_td_hack:
5448 rtc_td_hack = 1;
5449 break;
5450 case QEMU_OPTION_acpitable:
5451 if(acpi_table_add(optarg) < 0) {
5452 fprintf(stderr, "Wrong acpi table provided\n");
5453 exit(1);
5455 break;
5456 case QEMU_OPTION_smbios:
5457 if(smbios_entry_add(optarg) < 0) {
5458 fprintf(stderr, "Wrong smbios provided\n");
5459 exit(1);
5461 break;
5462 #endif
5463 #ifdef CONFIG_KQEMU
5464 case QEMU_OPTION_no_kqemu:
5465 kqemu_allowed = 0;
5466 break;
5467 case QEMU_OPTION_kernel_kqemu:
5468 kqemu_allowed = 2;
5469 break;
5470 #endif
5471 #ifdef CONFIG_KVM
5472 case QEMU_OPTION_enable_kvm:
5473 kvm_allowed = 1;
5474 #ifdef CONFIG_KQEMU
5475 kqemu_allowed = 0;
5476 #endif
5477 break;
5478 #endif
5479 #ifdef USE_KVM
5480 case QEMU_OPTION_no_kvm:
5481 kvm_allowed = 0;
5482 break;
5483 case QEMU_OPTION_no_kvm_irqchip: {
5484 kvm_irqchip = 0;
5485 kvm_pit = 0;
5486 break;
5488 case QEMU_OPTION_no_kvm_pit: {
5489 kvm_pit = 0;
5490 break;
5492 case QEMU_OPTION_no_kvm_pit_reinjection: {
5493 kvm_pit_reinject = 0;
5494 break;
5496 case QEMU_OPTION_enable_nesting: {
5497 kvm_nested = 1;
5498 break;
5500 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5501 case QEMU_OPTION_pcidevice:
5502 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5503 fprintf(stderr, "Too many assigned devices\n");
5504 exit(1);
5506 assigned_devices[assigned_devices_index] = optarg;
5507 assigned_devices_index++;
5508 break;
5509 #endif
5510 #endif
5511 case QEMU_OPTION_usb:
5512 usb_enabled = 1;
5513 break;
5514 case QEMU_OPTION_usbdevice:
5515 usb_enabled = 1;
5516 if (usb_devices_index >= MAX_USB_CMDLINE) {
5517 fprintf(stderr, "Too many USB devices\n");
5518 exit(1);
5520 usb_devices[usb_devices_index] = optarg;
5521 usb_devices_index++;
5522 break;
5523 case QEMU_OPTION_smp:
5524 smp_cpus = atoi(optarg);
5525 if (smp_cpus < 1) {
5526 fprintf(stderr, "Invalid number of CPUs\n");
5527 exit(1);
5529 break;
5530 case QEMU_OPTION_vnc:
5531 display_type = DT_VNC;
5532 vnc_display = optarg;
5533 break;
5534 #ifdef TARGET_I386
5535 case QEMU_OPTION_no_acpi:
5536 acpi_enabled = 0;
5537 break;
5538 case QEMU_OPTION_no_hpet:
5539 no_hpet = 1;
5540 break;
5541 #endif
5542 case QEMU_OPTION_no_reboot:
5543 no_reboot = 1;
5544 break;
5545 case QEMU_OPTION_no_shutdown:
5546 no_shutdown = 1;
5547 break;
5548 case QEMU_OPTION_show_cursor:
5549 cursor_hide = 0;
5550 break;
5551 case QEMU_OPTION_uuid:
5552 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5553 fprintf(stderr, "Fail to parse UUID string."
5554 " Wrong format.\n");
5555 exit(1);
5557 break;
5558 #ifndef _WIN32
5559 case QEMU_OPTION_daemonize:
5560 daemonize = 1;
5561 break;
5562 #endif
5563 case QEMU_OPTION_option_rom:
5564 if (nb_option_roms >= MAX_OPTION_ROMS) {
5565 fprintf(stderr, "Too many option ROMs\n");
5566 exit(1);
5568 option_rom[nb_option_roms] = optarg;
5569 nb_option_roms++;
5570 break;
5571 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5572 case QEMU_OPTION_semihosting:
5573 semihosting_enabled = 1;
5574 break;
5575 #endif
5576 case QEMU_OPTION_tdf:
5577 time_drift_fix = 1;
5578 break;
5579 case QEMU_OPTION_kvm_shadow_memory:
5580 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5581 break;
5582 case QEMU_OPTION_mempath:
5583 mem_path = optarg;
5584 break;
5585 #ifdef MAP_POPULATE
5586 case QEMU_OPTION_mem_prealloc:
5587 mem_prealloc = !mem_prealloc;
5588 break;
5589 #endif
5590 case QEMU_OPTION_name:
5591 qemu_name = optarg;
5592 break;
5593 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5594 case QEMU_OPTION_prom_env:
5595 if (nb_prom_envs >= MAX_PROM_ENVS) {
5596 fprintf(stderr, "Too many prom variables\n");
5597 exit(1);
5599 prom_envs[nb_prom_envs] = optarg;
5600 nb_prom_envs++;
5601 break;
5602 #endif
5603 #ifdef TARGET_ARM
5604 case QEMU_OPTION_old_param:
5605 old_param = 1;
5606 break;
5607 #endif
5608 case QEMU_OPTION_clock:
5609 configure_alarms(optarg);
5610 break;
5611 case QEMU_OPTION_startdate:
5613 struct tm tm;
5614 time_t rtc_start_date;
5615 if (!strcmp(optarg, "now")) {
5616 rtc_date_offset = -1;
5617 } else {
5618 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5619 &tm.tm_year,
5620 &tm.tm_mon,
5621 &tm.tm_mday,
5622 &tm.tm_hour,
5623 &tm.tm_min,
5624 &tm.tm_sec) == 6) {
5625 /* OK */
5626 } else if (sscanf(optarg, "%d-%d-%d",
5627 &tm.tm_year,
5628 &tm.tm_mon,
5629 &tm.tm_mday) == 3) {
5630 tm.tm_hour = 0;
5631 tm.tm_min = 0;
5632 tm.tm_sec = 0;
5633 } else {
5634 goto date_fail;
5636 tm.tm_year -= 1900;
5637 tm.tm_mon--;
5638 rtc_start_date = mktimegm(&tm);
5639 if (rtc_start_date == -1) {
5640 date_fail:
5641 fprintf(stderr, "Invalid date format. Valid format are:\n"
5642 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5643 exit(1);
5645 rtc_date_offset = time(NULL) - rtc_start_date;
5648 break;
5649 case QEMU_OPTION_tb_size:
5650 tb_size = strtol(optarg, NULL, 0);
5651 if (tb_size < 0)
5652 tb_size = 0;
5653 break;
5654 case QEMU_OPTION_icount:
5655 use_icount = 1;
5656 if (strcmp(optarg, "auto") == 0) {
5657 icount_time_shift = -1;
5658 } else {
5659 icount_time_shift = strtol(optarg, NULL, 0);
5661 break;
5662 case QEMU_OPTION_incoming:
5663 incoming = optarg;
5664 break;
5665 #ifndef _WIN32
5666 case QEMU_OPTION_chroot:
5667 chroot_dir = optarg;
5668 break;
5669 case QEMU_OPTION_runas:
5670 run_as = optarg;
5671 break;
5672 case QEMU_OPTION_nvram:
5673 nvram = optarg;
5674 break;
5675 #endif
5676 #ifdef CONFIG_XEN
5677 case QEMU_OPTION_xen_domid:
5678 xen_domid = atoi(optarg);
5679 break;
5680 case QEMU_OPTION_xen_create:
5681 xen_mode = XEN_CREATE;
5682 break;
5683 case QEMU_OPTION_xen_attach:
5684 xen_mode = XEN_ATTACH;
5685 break;
5686 #endif
5691 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5692 if (kvm_allowed && kqemu_allowed) {
5693 fprintf(stderr,
5694 "You can not enable both KVM and kqemu at the same time\n");
5695 exit(1);
5697 #endif
5699 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5700 if (smp_cpus > machine->max_cpus) {
5701 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5702 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5703 machine->max_cpus);
5704 exit(1);
5707 if (display_type == DT_NOGRAPHIC) {
5708 if (serial_device_index == 0)
5709 serial_devices[0] = "stdio";
5710 if (parallel_device_index == 0)
5711 parallel_devices[0] = "null";
5712 if (strncmp(monitor_device, "vc", 2) == 0)
5713 monitor_device = "stdio";
5716 #ifndef _WIN32
5717 if (daemonize) {
5718 pid_t pid;
5720 if (pipe(fds) == -1)
5721 exit(1);
5723 pid = fork();
5724 if (pid > 0) {
5725 uint8_t status;
5726 ssize_t len;
5728 close(fds[1]);
5730 again:
5731 len = read(fds[0], &status, 1);
5732 if (len == -1 && (errno == EINTR))
5733 goto again;
5735 if (len != 1)
5736 exit(1);
5737 else if (status == 1) {
5738 fprintf(stderr, "Could not acquire pidfile\n");
5739 exit(1);
5740 } else
5741 exit(0);
5742 } else if (pid < 0)
5743 exit(1);
5745 setsid();
5747 pid = fork();
5748 if (pid > 0)
5749 exit(0);
5750 else if (pid < 0)
5751 exit(1);
5753 umask(027);
5755 signal(SIGTSTP, SIG_IGN);
5756 signal(SIGTTOU, SIG_IGN);
5757 signal(SIGTTIN, SIG_IGN);
5760 #ifdef USE_KVM
5761 if (kvm_enabled()) {
5762 if (kvm_qemu_init() < 0) {
5763 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5764 #ifdef NO_CPU_EMULATION
5765 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5766 exit(1);
5767 #endif
5768 kvm_allowed = 0;
5771 #endif
5773 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5774 if (daemonize) {
5775 uint8_t status = 1;
5776 write(fds[1], &status, 1);
5777 } else
5778 fprintf(stderr, "Could not acquire pid file\n");
5779 exit(1);
5781 #endif
5783 #ifdef CONFIG_KQEMU
5784 if (smp_cpus > 1)
5785 kqemu_allowed = 0;
5786 #endif
5787 if (qemu_init_main_loop()) {
5788 fprintf(stderr, "qemu_init_main_loop failed\n");
5789 exit(1);
5791 linux_boot = (kernel_filename != NULL);
5792 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5794 if (!linux_boot && *kernel_cmdline != '\0') {
5795 fprintf(stderr, "-append only allowed with -kernel option\n");
5796 exit(1);
5799 if (!linux_boot && initrd_filename != NULL) {
5800 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5801 exit(1);
5804 /* boot to floppy or the default cd if no hard disk defined yet */
5805 if (!boot_devices[0]) {
5806 boot_devices = "cad";
5808 setvbuf(stdout, NULL, _IOLBF, 0);
5810 init_timers();
5811 if (init_timer_alarm() < 0) {
5812 fprintf(stderr, "could not initialize alarm timer\n");
5813 exit(1);
5815 if (use_icount && icount_time_shift < 0) {
5816 use_icount = 2;
5817 /* 125MIPS seems a reasonable initial guess at the guest speed.
5818 It will be corrected fairly quickly anyway. */
5819 icount_time_shift = 3;
5820 init_icount_adjust();
5823 #ifdef _WIN32
5824 socket_init();
5825 #endif
5827 /* init network clients */
5828 if (nb_net_clients == 0) {
5829 /* if no clients, we use a default config */
5830 net_clients[nb_net_clients++] = "nic";
5831 #ifdef CONFIG_SLIRP
5832 net_clients[nb_net_clients++] = "user";
5833 #endif
5836 for(i = 0;i < nb_net_clients; i++) {
5837 if (net_client_parse(net_clients[i]) < 0)
5838 exit(1);
5840 net_client_check();
5842 #ifdef TARGET_I386
5843 /* XXX: this should be moved in the PC machine instantiation code */
5844 if (net_boot != 0) {
5845 int netroms = 0;
5846 for (i = 0; i < nb_nics && i < 4; i++) {
5847 const char *model = nd_table[i].model;
5848 char buf[1024];
5849 if (net_boot & (1 << i)) {
5850 if (model == NULL)
5851 model = "rtl8139";
5852 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5853 if (get_image_size(buf) > 0) {
5854 if (nb_option_roms >= MAX_OPTION_ROMS) {
5855 fprintf(stderr, "Too many option ROMs\n");
5856 exit(1);
5858 option_rom[nb_option_roms] = strdup(buf);
5859 nb_option_roms++;
5860 netroms++;
5864 if (netroms == 0) {
5865 fprintf(stderr, "No valid PXE rom found for network device\n");
5866 exit(1);
5869 #endif
5871 /* init the bluetooth world */
5872 for (i = 0; i < nb_bt_opts; i++)
5873 if (bt_parse(bt_opts[i]))
5874 exit(1);
5876 /* init the memory */
5877 if (ram_size == 0)
5878 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5880 if (kvm_enabled()) {
5881 if (kvm_qemu_create_context() < 0) {
5882 fprintf(stderr, "Could not create KVM context\n");
5883 exit(1);
5887 #ifdef CONFIG_KQEMU
5888 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5889 guest ram allocation. It needs to go away. */
5890 if (kqemu_allowed) {
5891 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5892 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5893 if (!kqemu_phys_ram_base) {
5894 fprintf(stderr, "Could not allocate physical memory\n");
5895 exit(1);
5898 #endif
5900 /* init the dynamic translator */
5901 cpu_exec_init_all(tb_size * 1024 * 1024);
5903 bdrv_init();
5905 /* we always create the cdrom drive, even if no disk is there */
5907 if (nb_drives_opt < MAX_DRIVES)
5908 drive_add(NULL, CDROM_ALIAS);
5910 /* we always create at least one floppy */
5912 if (nb_drives_opt < MAX_DRIVES)
5913 drive_add(NULL, FD_ALIAS, 0);
5915 /* we always create one sd slot, even if no card is in it */
5917 if (nb_drives_opt < MAX_DRIVES)
5918 drive_add(NULL, SD_ALIAS);
5920 /* open the virtual block devices
5921 * note that migration with device
5922 * hot add/remove is broken.
5924 for(i = 0; i < nb_drives_opt; i++)
5925 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5926 exit(1);
5928 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5929 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5931 #ifndef _WIN32
5932 /* must be after terminal init, SDL library changes signal handlers */
5933 termsig_setup();
5934 #endif
5936 /* Maintain compatibility with multiple stdio monitors */
5937 if (!strcmp(monitor_device,"stdio")) {
5938 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5939 const char *devname = serial_devices[i];
5940 if (devname && !strcmp(devname,"mon:stdio")) {
5941 monitor_device = NULL;
5942 break;
5943 } else if (devname && !strcmp(devname,"stdio")) {
5944 monitor_device = NULL;
5945 serial_devices[i] = "mon:stdio";
5946 break;
5951 if (nb_numa_nodes > 0) {
5952 int i;
5954 if (nb_numa_nodes > smp_cpus) {
5955 nb_numa_nodes = smp_cpus;
5958 /* If no memory size if given for any node, assume the default case
5959 * and distribute the available memory equally across all nodes
5961 for (i = 0; i < nb_numa_nodes; i++) {
5962 if (node_mem[i] != 0)
5963 break;
5965 if (i == nb_numa_nodes) {
5966 uint64_t usedmem = 0;
5968 /* On Linux, the each node's border has to be 8MB aligned,
5969 * the final node gets the rest.
5971 for (i = 0; i < nb_numa_nodes - 1; i++) {
5972 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5973 usedmem += node_mem[i];
5975 node_mem[i] = ram_size - usedmem;
5978 for (i = 0; i < nb_numa_nodes; i++) {
5979 if (node_cpumask[i] != 0)
5980 break;
5982 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5983 * must cope with this anyway, because there are BIOSes out there in
5984 * real machines which also use this scheme.
5986 if (i == nb_numa_nodes) {
5987 for (i = 0; i < smp_cpus; i++) {
5988 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5993 #ifdef KVM_UPSTREAM
5994 if (kvm_enabled()) {
5995 int ret;
5997 ret = kvm_init(smp_cpus);
5998 if (ret < 0) {
5999 fprintf(stderr, "failed to initialize KVM\n");
6000 exit(1);
6003 #endif
6005 if (monitor_device) {
6006 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6007 if (!monitor_hd) {
6008 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6009 exit(1);
6013 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6014 const char *devname = serial_devices[i];
6015 if (devname && strcmp(devname, "none")) {
6016 char label[32];
6017 snprintf(label, sizeof(label), "serial%d", i);
6018 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6019 if (!serial_hds[i]) {
6020 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6021 devname);
6022 exit(1);
6027 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6028 const char *devname = parallel_devices[i];
6029 if (devname && strcmp(devname, "none")) {
6030 char label[32];
6031 snprintf(label, sizeof(label), "parallel%d", i);
6032 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6033 if (!parallel_hds[i]) {
6034 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6035 devname);
6036 exit(1);
6041 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6042 const char *devname = virtio_consoles[i];
6043 if (devname && strcmp(devname, "none")) {
6044 char label[32];
6045 snprintf(label, sizeof(label), "virtcon%d", i);
6046 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6047 if (!virtcon_hds[i]) {
6048 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6049 devname);
6050 exit(1);
6055 module_call_init(MODULE_INIT_DEVICE);
6057 if (kvm_enabled())
6058 kvm_init_ap();
6060 machine->init(ram_size, boot_devices,
6061 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6064 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6065 for (i = 0; i < nb_numa_nodes; i++) {
6066 if (node_cpumask[i] & (1 << env->cpu_index)) {
6067 env->numa_node = i;
6072 current_machine = machine;
6074 /* Set KVM's vcpu state to qemu's initial CPUState. */
6075 if (kvm_enabled()) {
6076 int ret;
6078 ret = kvm_sync_vcpus();
6079 if (ret < 0) {
6080 fprintf(stderr, "failed to initialize vcpus\n");
6081 exit(1);
6085 /* init USB devices */
6086 if (usb_enabled) {
6087 for(i = 0; i < usb_devices_index; i++) {
6088 if (usb_device_add(usb_devices[i], 0) < 0) {
6089 fprintf(stderr, "Warning: could not add USB device %s\n",
6090 usb_devices[i]);
6095 if (!display_state)
6096 dumb_display_init();
6097 /* just use the first displaystate for the moment */
6098 ds = display_state;
6100 if (display_type == DT_DEFAULT) {
6101 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6102 display_type = DT_SDL;
6103 #else
6104 display_type = DT_VNC;
6105 vnc_display = "localhost:0,to=99";
6106 show_vnc_port = 1;
6107 #endif
6111 switch (display_type) {
6112 case DT_NOGRAPHIC:
6113 break;
6114 #if defined(CONFIG_CURSES)
6115 case DT_CURSES:
6116 curses_display_init(ds, full_screen);
6117 break;
6118 #endif
6119 #if defined(CONFIG_SDL)
6120 case DT_SDL:
6121 sdl_display_init(ds, full_screen, no_frame);
6122 break;
6123 #elif defined(CONFIG_COCOA)
6124 case DT_SDL:
6125 cocoa_display_init(ds, full_screen);
6126 break;
6127 #endif
6128 case DT_VNC:
6129 vnc_display_init(ds);
6130 if (vnc_display_open(ds, vnc_display) < 0)
6131 exit(1);
6133 if (show_vnc_port) {
6134 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6136 break;
6137 default:
6138 break;
6140 dpy_resize(ds);
6142 dcl = ds->listeners;
6143 while (dcl != NULL) {
6144 if (dcl->dpy_refresh != NULL) {
6145 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6146 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6148 dcl = dcl->next;
6151 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6152 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6153 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6156 text_consoles_set_display(display_state);
6157 qemu_chr_initial_reset();
6159 if (monitor_device && monitor_hd)
6160 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6162 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6163 const char *devname = serial_devices[i];
6164 if (devname && strcmp(devname, "none")) {
6165 char label[32];
6166 snprintf(label, sizeof(label), "serial%d", i);
6167 if (strstart(devname, "vc", 0))
6168 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6172 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6173 const char *devname = parallel_devices[i];
6174 if (devname && strcmp(devname, "none")) {
6175 char label[32];
6176 snprintf(label, sizeof(label), "parallel%d", i);
6177 if (strstart(devname, "vc", 0))
6178 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6182 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6183 const char *devname = virtio_consoles[i];
6184 if (virtcon_hds[i] && devname) {
6185 char label[32];
6186 snprintf(label, sizeof(label), "virtcon%d", i);
6187 if (strstart(devname, "vc", 0))
6188 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6192 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6193 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6194 gdbstub_dev);
6195 exit(1);
6198 if (loadvm)
6199 do_loadvm(cur_mon, loadvm);
6201 if (incoming) {
6202 autostart = 0; /* fixme how to deal with -daemonize */
6203 qemu_start_incoming_migration(incoming);
6206 if (autostart)
6207 vm_start();
6209 #ifndef _WIN32
6210 if (daemonize) {
6211 uint8_t status = 0;
6212 ssize_t len;
6214 again1:
6215 len = write(fds[1], &status, 1);
6216 if (len == -1 && (errno == EINTR))
6217 goto again1;
6219 if (len != 1)
6220 exit(1);
6222 chdir("/");
6223 TFR(fd = open("/dev/null", O_RDWR));
6224 if (fd == -1)
6225 exit(1);
6228 if (run_as) {
6229 pwd = getpwnam(run_as);
6230 if (!pwd) {
6231 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6232 exit(1);
6236 if (chroot_dir) {
6237 if (chroot(chroot_dir) < 0) {
6238 fprintf(stderr, "chroot failed\n");
6239 exit(1);
6241 chdir("/");
6244 if (run_as) {
6245 if (setgid(pwd->pw_gid) < 0) {
6246 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6247 exit(1);
6249 if (setuid(pwd->pw_uid) < 0) {
6250 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6251 exit(1);
6253 if (setuid(0) != -1) {
6254 fprintf(stderr, "Dropping privileges failed\n");
6255 exit(1);
6259 if (daemonize) {
6260 dup2(fd, 0);
6261 dup2(fd, 1);
6262 dup2(fd, 2);
6264 close(fd);
6266 #endif
6268 main_loop();
6269 quit_timers();
6270 net_cleanup();
6272 return 0;