Merge branch 'master' of git://git.sv.gnu.org/qemu
[qemu-kvm/markmc.git] / vl.c
blobe522d293d9640b876e6114391457b3efeb57627a
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 <libgen.h>
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <net/if.h>
47 #if defined(__NetBSD__)
48 #include <net/if_tap.h>
49 #endif
50 #ifdef __linux__
51 #include <linux/if_tun.h>
52 #endif
53 #include <arpa/inet.h>
54 #include <dirent.h>
55 #include <netdb.h>
56 #include <sys/select.h>
57 #ifdef HOST_BSD
58 #include <sys/stat.h>
59 #if defined(__FreeBSD__) || defined(__DragonFly__)
60 #include <libutil.h>
61 #else
62 #include <util.h>
63 #endif
64 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65 #include <freebsd/stdlib.h>
66 #else
67 #ifdef __linux__
68 #include <pty.h>
69 #include <malloc.h>
70 #include <linux/rtc.h>
72 /* For the benefit of older linux systems which don't supply it,
73 we use a local copy of hpet.h. */
74 /* #include <linux/hpet.h> */
75 #include "hpet.h"
77 #include <linux/ppdev.h>
78 #include <linux/parport.h>
79 #endif
80 #ifdef __sun__
81 #include <sys/stat.h>
82 #include <sys/ethernet.h>
83 #include <sys/sockio.h>
84 #include <netinet/arp.h>
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/ip.h>
88 #include <netinet/ip_icmp.h> // must come after ip.h
89 #include <netinet/udp.h>
90 #include <netinet/tcp.h>
91 #include <net/if.h>
92 #include <syslog.h>
93 #include <stropts.h>
94 #endif
95 #endif
96 #endif
98 #if defined(__OpenBSD__)
99 #include <util.h>
100 #endif
102 #if defined(CONFIG_VDE)
103 #include <libvdeplug.h>
104 #endif
106 #ifdef _WIN32
107 #include <windows.h>
108 #include <malloc.h>
109 #include <sys/timeb.h>
110 #include <mmsystem.h>
111 #define getopt_long_only getopt_long
112 #define memalign(align, size) malloc(size)
113 #endif
115 #ifdef CONFIG_SDL
116 #ifdef __APPLE__
117 #include <SDL/SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 qemu_main(argc, argv, NULL);
123 #undef main
124 #define main qemu_main
125 #endif
126 #endif /* CONFIG_SDL */
128 #ifdef CONFIG_COCOA
129 #undef main
130 #define main qemu_main
131 #endif /* CONFIG_COCOA */
133 #include "hw/hw.h"
134 #include "hw/boards.h"
135 #include "hw/usb.h"
136 #include "hw/pcmcia.h"
137 #include "hw/pc.h"
138 #include "hw/audiodev.h"
139 #include "hw/isa.h"
140 #include "hw/baum.h"
141 #include "hw/bt.h"
142 #include "hw/watchdog.h"
143 #include "hw/smbios.h"
144 #include "hw/xen.h"
145 #include "bt-host.h"
146 #include "net.h"
147 #include "monitor.h"
148 #include "console.h"
149 #include "sysemu.h"
150 #include "gdbstub.h"
151 #include "qemu-timer.h"
152 #include "qemu-char.h"
153 #include "cache-utils.h"
154 #include "block.h"
155 #include "dma.h"
156 #include "audio/audio.h"
157 #include "migration.h"
158 #include "kvm.h"
159 #include "balloon.h"
160 #include "qemu-option.h"
161 #include "qemu-kvm.h"
162 #include "hw/device-assignment.h"
164 #include "disas.h"
166 #include "exec-all.h"
168 #include "qemu_socket.h"
170 #if defined(CONFIG_SLIRP)
171 #include "libslirp.h"
172 #endif
174 //#define DEBUG_UNUSED_IOPORT
175 //#define DEBUG_IOPORT
176 //#define DEBUG_NET
177 //#define DEBUG_SLIRP
180 #ifdef DEBUG_IOPORT
181 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
182 #else
183 # define LOG_IOPORT(...) do { } while (0)
184 #endif
186 #define DEFAULT_RAM_SIZE 128
188 /* Max number of USB devices that can be specified on the commandline. */
189 #define MAX_USB_CMDLINE 8
191 /* Max number of bluetooth switches on the commandline. */
192 #define MAX_BT_CMDLINE 10
194 /* XXX: use a two level table to limit memory usage */
195 #define MAX_IOPORTS 65536
197 static const char *data_dir;
198 const char *bios_name = NULL;
199 static void *ioport_opaque[MAX_IOPORTS];
200 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
201 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
202 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
203 to store the VM snapshots */
204 DriveInfo drives_table[MAX_DRIVES+1];
205 int nb_drives;
206 int extboot_drive = -1;
207 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
208 static DisplayState *display_state;
209 DisplayType display_type = DT_DEFAULT;
210 const char* keyboard_layout = NULL;
211 int64_t ticks_per_sec;
212 ram_addr_t ram_size;
213 int nb_nics;
214 NICInfo nd_table[MAX_NICS];
215 int vm_running;
216 static int autostart;
217 static int rtc_utc = 1;
218 static int rtc_date_offset = -1; /* -1 means no change */
219 int cirrus_vga_enabled = 1;
220 int std_vga_enabled = 0;
221 int vmsvga_enabled = 0;
222 int xenfb_enabled = 0;
223 #ifdef TARGET_SPARC
224 int graphic_width = 1024;
225 int graphic_height = 768;
226 int graphic_depth = 8;
227 #else
228 int graphic_width = 800;
229 int graphic_height = 600;
230 int graphic_depth = 15;
231 #endif
232 static int full_screen = 0;
233 #ifdef CONFIG_SDL
234 static int no_frame = 0;
235 #endif
236 int no_quit = 0;
237 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
238 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
239 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
240 #ifdef TARGET_I386
241 int win2k_install_hack = 0;
242 int rtc_td_hack = 0;
243 #endif
244 int usb_enabled = 0;
245 int singlestep = 0;
246 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
247 int assigned_devices_index;
248 int smp_cpus = 1;
249 const char *vnc_display;
250 int acpi_enabled = 1;
251 int no_hpet = 0;
252 int fd_bootchk = 1;
253 int no_reboot = 0;
254 int no_shutdown = 0;
255 int cursor_hide = 1;
256 int graphic_rotate = 0;
257 #ifndef _WIN32
258 int daemonize = 0;
259 #endif
260 WatchdogTimerModel *watchdog = NULL;
261 int watchdog_action = WDT_RESET;
262 const char *option_rom[MAX_OPTION_ROMS];
263 int nb_option_roms;
264 int semihosting_enabled = 0;
265 int time_drift_fix = 0;
266 unsigned int kvm_shadow_memory = 0;
267 const char *mem_path = NULL;
268 #ifdef MAP_POPULATE
269 int mem_prealloc = 1; /* force preallocation of physical target memory */
270 #endif
271 #ifdef TARGET_ARM
272 int old_param = 0;
273 #endif
274 const char *qemu_name;
275 int alt_grab = 0;
276 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
277 unsigned int nb_prom_envs = 0;
278 const char *prom_envs[MAX_PROM_ENVS];
279 #endif
280 int nb_drives_opt;
281 const char *nvram = NULL;
282 struct drive_opt drives_opt[MAX_DRIVES];
284 int nb_numa_nodes;
285 uint64_t node_mem[MAX_NODES];
286 uint64_t node_cpumask[MAX_NODES];
288 static CPUState *cur_cpu;
289 static CPUState *next_cpu;
290 static int timer_alarm_pending = 1;
291 /* Conversion factor from emulated instructions to virtual clock ticks. */
292 static int icount_time_shift;
293 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
294 #define MAX_ICOUNT_SHIFT 10
295 /* Compensate for varying guest execution speed. */
296 static int64_t qemu_icount_bias;
297 static QEMUTimer *icount_rt_timer;
298 static QEMUTimer *icount_vm_timer;
299 static QEMUTimer *nographic_timer;
301 uint8_t qemu_uuid[16];
303 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
304 struct timeval *tv)
306 int ret;
308 /* KVM holds a mutex while QEMU code is running, we need hooks to
309 release the mutex whenever QEMU code sleeps. */
311 kvm_sleep_begin();
313 ret = select(max_fd, rfds, wfds, xfds, tv);
315 kvm_sleep_end();
317 return ret;
321 /***********************************************************/
322 /* x86 ISA bus support */
324 target_phys_addr_t isa_mem_base = 0;
325 PicState2 *isa_pic;
327 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
328 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
330 static uint32_t ioport_read(int index, uint32_t address)
332 static IOPortReadFunc *default_func[3] = {
333 default_ioport_readb,
334 default_ioport_readw,
335 default_ioport_readl
337 IOPortReadFunc *func = ioport_read_table[index][address];
338 if (!func)
339 func = default_func[index];
340 return func(ioport_opaque[address], address);
343 static void ioport_write(int index, uint32_t address, uint32_t data)
345 static IOPortWriteFunc *default_func[3] = {
346 default_ioport_writeb,
347 default_ioport_writew,
348 default_ioport_writel
350 IOPortWriteFunc *func = ioport_write_table[index][address];
351 if (!func)
352 func = default_func[index];
353 func(ioport_opaque[address], address, data);
356 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
358 #ifdef DEBUG_UNUSED_IOPORT
359 fprintf(stderr, "unused inb: port=0x%04x\n", address);
360 #endif
361 return 0xff;
364 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
366 #ifdef DEBUG_UNUSED_IOPORT
367 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
368 #endif
371 /* default is to make two byte accesses */
372 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
374 uint32_t data;
375 data = ioport_read(0, address);
376 address = (address + 1) & (MAX_IOPORTS - 1);
377 data |= ioport_read(0, address) << 8;
378 return data;
381 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
383 ioport_write(0, address, data & 0xff);
384 address = (address + 1) & (MAX_IOPORTS - 1);
385 ioport_write(0, address, (data >> 8) & 0xff);
388 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
390 #ifdef DEBUG_UNUSED_IOPORT
391 fprintf(stderr, "unused inl: port=0x%04x\n", address);
392 #endif
393 return 0xffffffff;
396 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
398 #ifdef DEBUG_UNUSED_IOPORT
399 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
400 #endif
403 /* size is the word size in byte */
404 int register_ioport_read(int start, int length, int size,
405 IOPortReadFunc *func, void *opaque)
407 int i, bsize;
409 if (size == 1) {
410 bsize = 0;
411 } else if (size == 2) {
412 bsize = 1;
413 } else if (size == 4) {
414 bsize = 2;
415 } else {
416 hw_error("register_ioport_read: invalid size");
417 return -1;
419 for(i = start; i < start + length; i += size) {
420 ioport_read_table[bsize][i] = func;
421 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
422 hw_error("register_ioport_read: invalid opaque");
423 ioport_opaque[i] = opaque;
425 return 0;
428 /* size is the word size in byte */
429 int register_ioport_write(int start, int length, int size,
430 IOPortWriteFunc *func, void *opaque)
432 int i, bsize;
434 if (size == 1) {
435 bsize = 0;
436 } else if (size == 2) {
437 bsize = 1;
438 } else if (size == 4) {
439 bsize = 2;
440 } else {
441 hw_error("register_ioport_write: invalid size");
442 return -1;
444 for(i = start; i < start + length; i += size) {
445 ioport_write_table[bsize][i] = func;
446 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
447 hw_error("register_ioport_write: invalid opaque");
448 ioport_opaque[i] = opaque;
450 return 0;
453 void isa_unassign_ioport(int start, int length)
455 int i;
457 for(i = start; i < start + length; i++) {
458 ioport_read_table[0][i] = default_ioport_readb;
459 ioport_read_table[1][i] = default_ioport_readw;
460 ioport_read_table[2][i] = default_ioport_readl;
462 ioport_write_table[0][i] = default_ioport_writeb;
463 ioport_write_table[1][i] = default_ioport_writew;
464 ioport_write_table[2][i] = default_ioport_writel;
466 ioport_opaque[i] = NULL;
470 /***********************************************************/
472 void cpu_outb(CPUState *env, int addr, int val)
474 LOG_IOPORT("outb: %04x %02x\n", addr, val);
475 ioport_write(0, addr, val);
476 #ifdef CONFIG_KQEMU
477 if (env)
478 env->last_io_time = cpu_get_time_fast();
479 #endif
482 void cpu_outw(CPUState *env, int addr, int val)
484 LOG_IOPORT("outw: %04x %04x\n", addr, val);
485 ioport_write(1, addr, val);
486 #ifdef CONFIG_KQEMU
487 if (env)
488 env->last_io_time = cpu_get_time_fast();
489 #endif
492 void cpu_outl(CPUState *env, int addr, int val)
494 LOG_IOPORT("outl: %04x %08x\n", addr, val);
495 ioport_write(2, addr, val);
496 #ifdef CONFIG_KQEMU
497 if (env)
498 env->last_io_time = cpu_get_time_fast();
499 #endif
502 int cpu_inb(CPUState *env, int addr)
504 int val;
505 val = ioport_read(0, addr);
506 LOG_IOPORT("inb : %04x %02x\n", addr, val);
507 #ifdef CONFIG_KQEMU
508 if (env)
509 env->last_io_time = cpu_get_time_fast();
510 #endif
511 return val;
514 int cpu_inw(CPUState *env, int addr)
516 int val;
517 val = ioport_read(1, addr);
518 LOG_IOPORT("inw : %04x %04x\n", addr, val);
519 #ifdef CONFIG_KQEMU
520 if (env)
521 env->last_io_time = cpu_get_time_fast();
522 #endif
523 return val;
526 int cpu_inl(CPUState *env, int addr)
528 int val;
529 val = ioport_read(2, addr);
530 LOG_IOPORT("inl : %04x %08x\n", addr, val);
531 #ifdef CONFIG_KQEMU
532 if (env)
533 env->last_io_time = cpu_get_time_fast();
534 #endif
535 return val;
538 /***********************************************************/
539 void hw_error(const char *fmt, ...)
541 va_list ap;
542 CPUState *env;
544 va_start(ap, fmt);
545 fprintf(stderr, "qemu: hardware error: ");
546 vfprintf(stderr, fmt, ap);
547 fprintf(stderr, "\n");
548 for(env = first_cpu; env != NULL; env = env->next_cpu) {
549 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
550 #ifdef TARGET_I386
551 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
552 #else
553 cpu_dump_state(env, stderr, fprintf, 0);
554 #endif
556 va_end(ap);
557 abort();
560 /***************/
561 /* ballooning */
563 static QEMUBalloonEvent *qemu_balloon_event;
564 void *qemu_balloon_event_opaque;
566 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
568 qemu_balloon_event = func;
569 qemu_balloon_event_opaque = opaque;
572 void qemu_balloon(ram_addr_t target)
574 if (qemu_balloon_event)
575 qemu_balloon_event(qemu_balloon_event_opaque, target);
578 ram_addr_t qemu_balloon_status(void)
580 if (qemu_balloon_event)
581 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
582 return 0;
585 /***********************************************************/
586 /* keyboard/mouse */
588 static QEMUPutKBDEvent *qemu_put_kbd_event;
589 static void *qemu_put_kbd_event_opaque;
590 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
591 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
593 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
595 qemu_put_kbd_event_opaque = opaque;
596 qemu_put_kbd_event = func;
599 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
600 void *opaque, int absolute,
601 const char *name)
603 QEMUPutMouseEntry *s, *cursor;
605 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
607 s->qemu_put_mouse_event = func;
608 s->qemu_put_mouse_event_opaque = opaque;
609 s->qemu_put_mouse_event_absolute = absolute;
610 s->qemu_put_mouse_event_name = qemu_strdup(name);
611 s->next = NULL;
613 if (!qemu_put_mouse_event_head) {
614 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
615 return s;
618 cursor = qemu_put_mouse_event_head;
619 while (cursor->next != NULL)
620 cursor = cursor->next;
622 cursor->next = s;
623 qemu_put_mouse_event_current = s;
625 return s;
628 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
630 QEMUPutMouseEntry *prev = NULL, *cursor;
632 if (!qemu_put_mouse_event_head || entry == NULL)
633 return;
635 cursor = qemu_put_mouse_event_head;
636 while (cursor != NULL && cursor != entry) {
637 prev = cursor;
638 cursor = cursor->next;
641 if (cursor == NULL) // does not exist or list empty
642 return;
643 else if (prev == NULL) { // entry is head
644 qemu_put_mouse_event_head = cursor->next;
645 if (qemu_put_mouse_event_current == entry)
646 qemu_put_mouse_event_current = cursor->next;
647 qemu_free(entry->qemu_put_mouse_event_name);
648 qemu_free(entry);
649 return;
652 prev->next = entry->next;
654 if (qemu_put_mouse_event_current == entry)
655 qemu_put_mouse_event_current = prev;
657 qemu_free(entry->qemu_put_mouse_event_name);
658 qemu_free(entry);
661 void kbd_put_keycode(int keycode)
663 if (qemu_put_kbd_event) {
664 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
668 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
670 QEMUPutMouseEvent *mouse_event;
671 void *mouse_event_opaque;
672 int width;
674 if (!qemu_put_mouse_event_current) {
675 return;
678 mouse_event =
679 qemu_put_mouse_event_current->qemu_put_mouse_event;
680 mouse_event_opaque =
681 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
683 if (mouse_event) {
684 if (graphic_rotate) {
685 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
686 width = 0x7fff;
687 else
688 width = graphic_width - 1;
689 mouse_event(mouse_event_opaque,
690 width - dy, dx, dz, buttons_state);
691 } else
692 mouse_event(mouse_event_opaque,
693 dx, dy, dz, buttons_state);
697 int kbd_mouse_is_absolute(void)
699 if (!qemu_put_mouse_event_current)
700 return 0;
702 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
705 void do_info_mice(Monitor *mon)
707 QEMUPutMouseEntry *cursor;
708 int index = 0;
710 if (!qemu_put_mouse_event_head) {
711 monitor_printf(mon, "No mouse devices connected\n");
712 return;
715 monitor_printf(mon, "Mouse devices available:\n");
716 cursor = qemu_put_mouse_event_head;
717 while (cursor != NULL) {
718 monitor_printf(mon, "%c Mouse #%d: %s\n",
719 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
720 index, cursor->qemu_put_mouse_event_name);
721 index++;
722 cursor = cursor->next;
726 void do_mouse_set(Monitor *mon, int index)
728 QEMUPutMouseEntry *cursor;
729 int i = 0;
731 if (!qemu_put_mouse_event_head) {
732 monitor_printf(mon, "No mouse devices connected\n");
733 return;
736 cursor = qemu_put_mouse_event_head;
737 while (cursor != NULL && index != i) {
738 i++;
739 cursor = cursor->next;
742 if (cursor != NULL)
743 qemu_put_mouse_event_current = cursor;
744 else
745 monitor_printf(mon, "Mouse at given index not found\n");
748 /* compute with 96 bit intermediate result: (a*b)/c */
749 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
751 union {
752 uint64_t ll;
753 struct {
754 #ifdef WORDS_BIGENDIAN
755 uint32_t high, low;
756 #else
757 uint32_t low, high;
758 #endif
759 } l;
760 } u, res;
761 uint64_t rl, rh;
763 u.ll = a;
764 rl = (uint64_t)u.l.low * (uint64_t)b;
765 rh = (uint64_t)u.l.high * (uint64_t)b;
766 rh += (rl >> 32);
767 res.l.high = rh / c;
768 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
769 return res.ll;
772 /***********************************************************/
773 /* real time host monotonic timer */
775 #define QEMU_TIMER_BASE 1000000000LL
777 #ifdef WIN32
779 static int64_t clock_freq;
781 static void init_get_clock(void)
783 LARGE_INTEGER freq;
784 int ret;
785 ret = QueryPerformanceFrequency(&freq);
786 if (ret == 0) {
787 fprintf(stderr, "Could not calibrate ticks\n");
788 exit(1);
790 clock_freq = freq.QuadPart;
793 static int64_t get_clock(void)
795 LARGE_INTEGER ti;
796 QueryPerformanceCounter(&ti);
797 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
800 #else
802 static int use_rt_clock;
804 static void init_get_clock(void)
806 use_rt_clock = 0;
807 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
808 || defined(__DragonFly__)
810 struct timespec ts;
811 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
812 use_rt_clock = 1;
815 #endif
818 static int64_t get_clock(void)
820 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
821 || defined(__DragonFly__)
822 if (use_rt_clock) {
823 struct timespec ts;
824 clock_gettime(CLOCK_MONOTONIC, &ts);
825 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
826 } else
827 #endif
829 /* XXX: using gettimeofday leads to problems if the date
830 changes, so it should be avoided. */
831 struct timeval tv;
832 gettimeofday(&tv, NULL);
833 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
836 #endif
838 /* Return the virtual CPU time, based on the instruction counter. */
839 static int64_t cpu_get_icount(void)
841 int64_t icount;
842 CPUState *env = cpu_single_env;;
843 icount = qemu_icount;
844 if (env) {
845 if (!can_do_io(env))
846 fprintf(stderr, "Bad clock read\n");
847 icount -= (env->icount_decr.u16.low + env->icount_extra);
849 return qemu_icount_bias + (icount << icount_time_shift);
852 /***********************************************************/
853 /* guest cycle counter */
855 static int64_t cpu_ticks_prev;
856 static int64_t cpu_ticks_offset;
857 static int64_t cpu_clock_offset;
858 static int cpu_ticks_enabled;
860 /* return the host CPU cycle counter and handle stop/restart */
861 int64_t cpu_get_ticks(void)
863 if (use_icount) {
864 return cpu_get_icount();
866 if (!cpu_ticks_enabled) {
867 return cpu_ticks_offset;
868 } else {
869 int64_t ticks;
870 ticks = cpu_get_real_ticks();
871 if (cpu_ticks_prev > ticks) {
872 /* Note: non increasing ticks may happen if the host uses
873 software suspend */
874 cpu_ticks_offset += cpu_ticks_prev - ticks;
876 cpu_ticks_prev = ticks;
877 return ticks + cpu_ticks_offset;
881 /* return the host CPU monotonic timer and handle stop/restart */
882 static int64_t cpu_get_clock(void)
884 int64_t ti;
885 if (!cpu_ticks_enabled) {
886 return cpu_clock_offset;
887 } else {
888 ti = get_clock();
889 return ti + cpu_clock_offset;
893 /* enable cpu_get_ticks() */
894 void cpu_enable_ticks(void)
896 if (!cpu_ticks_enabled) {
897 cpu_ticks_offset -= cpu_get_real_ticks();
898 cpu_clock_offset -= get_clock();
899 cpu_ticks_enabled = 1;
903 /* disable cpu_get_ticks() : the clock is stopped. You must not call
904 cpu_get_ticks() after that. */
905 void cpu_disable_ticks(void)
907 if (cpu_ticks_enabled) {
908 cpu_ticks_offset = cpu_get_ticks();
909 cpu_clock_offset = cpu_get_clock();
910 cpu_ticks_enabled = 0;
914 /***********************************************************/
915 /* timers */
917 #define QEMU_TIMER_REALTIME 0
918 #define QEMU_TIMER_VIRTUAL 1
920 struct QEMUClock {
921 int type;
922 /* XXX: add frequency */
925 struct QEMUTimer {
926 QEMUClock *clock;
927 int64_t expire_time;
928 QEMUTimerCB *cb;
929 void *opaque;
930 struct QEMUTimer *next;
933 struct qemu_alarm_timer {
934 char const *name;
935 unsigned int flags;
937 int (*start)(struct qemu_alarm_timer *t);
938 void (*stop)(struct qemu_alarm_timer *t);
939 void (*rearm)(struct qemu_alarm_timer *t);
940 void *priv;
943 #define ALARM_FLAG_DYNTICKS 0x1
944 #define ALARM_FLAG_EXPIRED 0x2
946 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
948 return t && (t->flags & ALARM_FLAG_DYNTICKS);
951 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
953 if (!alarm_has_dynticks(t))
954 return;
956 t->rearm(t);
959 /* TODO: MIN_TIMER_REARM_US should be optimized */
960 #define MIN_TIMER_REARM_US 250
962 static struct qemu_alarm_timer *alarm_timer;
964 #ifdef _WIN32
966 struct qemu_alarm_win32 {
967 MMRESULT timerId;
968 unsigned int period;
969 } alarm_win32_data = {0, -1};
971 static int win32_start_timer(struct qemu_alarm_timer *t);
972 static void win32_stop_timer(struct qemu_alarm_timer *t);
973 static void win32_rearm_timer(struct qemu_alarm_timer *t);
975 #else
977 static int unix_start_timer(struct qemu_alarm_timer *t);
978 static void unix_stop_timer(struct qemu_alarm_timer *t);
980 #ifdef __linux__
982 static int dynticks_start_timer(struct qemu_alarm_timer *t);
983 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
984 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
986 static int hpet_start_timer(struct qemu_alarm_timer *t);
987 static void hpet_stop_timer(struct qemu_alarm_timer *t);
989 static int rtc_start_timer(struct qemu_alarm_timer *t);
990 static void rtc_stop_timer(struct qemu_alarm_timer *t);
992 #endif /* __linux__ */
994 #endif /* _WIN32 */
996 /* Correlation between real and virtual time is always going to be
997 fairly approximate, so ignore small variation.
998 When the guest is idle real and virtual time will be aligned in
999 the IO wait loop. */
1000 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1002 static void icount_adjust(void)
1004 int64_t cur_time;
1005 int64_t cur_icount;
1006 int64_t delta;
1007 static int64_t last_delta;
1008 /* If the VM is not running, then do nothing. */
1009 if (!vm_running)
1010 return;
1012 cur_time = cpu_get_clock();
1013 cur_icount = qemu_get_clock(vm_clock);
1014 delta = cur_icount - cur_time;
1015 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1016 if (delta > 0
1017 && last_delta + ICOUNT_WOBBLE < delta * 2
1018 && icount_time_shift > 0) {
1019 /* The guest is getting too far ahead. Slow time down. */
1020 icount_time_shift--;
1022 if (delta < 0
1023 && last_delta - ICOUNT_WOBBLE > delta * 2
1024 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1025 /* The guest is getting too far behind. Speed time up. */
1026 icount_time_shift++;
1028 last_delta = delta;
1029 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1032 static void icount_adjust_rt(void * opaque)
1034 qemu_mod_timer(icount_rt_timer,
1035 qemu_get_clock(rt_clock) + 1000);
1036 icount_adjust();
1039 static void icount_adjust_vm(void * opaque)
1041 qemu_mod_timer(icount_vm_timer,
1042 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1043 icount_adjust();
1046 static void init_icount_adjust(void)
1048 /* Have both realtime and virtual time triggers for speed adjustment.
1049 The realtime trigger catches emulated time passing too slowly,
1050 the virtual time trigger catches emulated time passing too fast.
1051 Realtime triggers occur even when idle, so use them less frequently
1052 than VM triggers. */
1053 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1054 qemu_mod_timer(icount_rt_timer,
1055 qemu_get_clock(rt_clock) + 1000);
1056 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1057 qemu_mod_timer(icount_vm_timer,
1058 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1061 static struct qemu_alarm_timer alarm_timers[] = {
1062 #ifndef _WIN32
1063 #ifdef __linux__
1064 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1065 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1066 /* HPET - if available - is preferred */
1067 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1068 /* ...otherwise try RTC */
1069 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1070 #endif
1071 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1072 #else
1073 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1074 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1075 {"win32", 0, win32_start_timer,
1076 win32_stop_timer, NULL, &alarm_win32_data},
1077 #endif
1078 {NULL, }
1081 static void show_available_alarms(void)
1083 int i;
1085 printf("Available alarm timers, in order of precedence:\n");
1086 for (i = 0; alarm_timers[i].name; i++)
1087 printf("%s\n", alarm_timers[i].name);
1090 static void configure_alarms(char const *opt)
1092 int i;
1093 int cur = 0;
1094 int count = ARRAY_SIZE(alarm_timers) - 1;
1095 char *arg;
1096 char *name;
1097 struct qemu_alarm_timer tmp;
1099 if (!strcmp(opt, "?")) {
1100 show_available_alarms();
1101 exit(0);
1104 arg = strdup(opt);
1106 /* Reorder the array */
1107 name = strtok(arg, ",");
1108 while (name) {
1109 for (i = 0; i < count && alarm_timers[i].name; i++) {
1110 if (!strcmp(alarm_timers[i].name, name))
1111 break;
1114 if (i == count) {
1115 fprintf(stderr, "Unknown clock %s\n", name);
1116 goto next;
1119 if (i < cur)
1120 /* Ignore */
1121 goto next;
1123 /* Swap */
1124 tmp = alarm_timers[i];
1125 alarm_timers[i] = alarm_timers[cur];
1126 alarm_timers[cur] = tmp;
1128 cur++;
1129 next:
1130 name = strtok(NULL, ",");
1133 free(arg);
1135 if (cur) {
1136 /* Disable remaining timers */
1137 for (i = cur; i < count; i++)
1138 alarm_timers[i].name = NULL;
1139 } else {
1140 show_available_alarms();
1141 exit(1);
1145 QEMUClock *rt_clock;
1146 QEMUClock *vm_clock;
1148 static QEMUTimer *active_timers[2];
1150 static QEMUClock *qemu_new_clock(int type)
1152 QEMUClock *clock;
1153 clock = qemu_mallocz(sizeof(QEMUClock));
1154 clock->type = type;
1155 return clock;
1158 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1160 QEMUTimer *ts;
1162 ts = qemu_mallocz(sizeof(QEMUTimer));
1163 ts->clock = clock;
1164 ts->cb = cb;
1165 ts->opaque = opaque;
1166 return ts;
1169 void qemu_free_timer(QEMUTimer *ts)
1171 qemu_free(ts);
1174 /* stop a timer, but do not dealloc it */
1175 void qemu_del_timer(QEMUTimer *ts)
1177 QEMUTimer **pt, *t;
1179 /* NOTE: this code must be signal safe because
1180 qemu_timer_expired() can be called from a signal. */
1181 pt = &active_timers[ts->clock->type];
1182 for(;;) {
1183 t = *pt;
1184 if (!t)
1185 break;
1186 if (t == ts) {
1187 *pt = t->next;
1188 break;
1190 pt = &t->next;
1194 /* modify the current timer so that it will be fired when current_time
1195 >= expire_time. The corresponding callback will be called. */
1196 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1198 QEMUTimer **pt, *t;
1200 qemu_del_timer(ts);
1202 /* add the timer in the sorted list */
1203 /* NOTE: this code must be signal safe because
1204 qemu_timer_expired() can be called from a signal. */
1205 pt = &active_timers[ts->clock->type];
1206 for(;;) {
1207 t = *pt;
1208 if (!t)
1209 break;
1210 if (t->expire_time > expire_time)
1211 break;
1212 pt = &t->next;
1214 ts->expire_time = expire_time;
1215 ts->next = *pt;
1216 *pt = ts;
1218 /* Rearm if necessary */
1219 if (pt == &active_timers[ts->clock->type]) {
1220 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1221 qemu_rearm_alarm_timer(alarm_timer);
1223 /* Interrupt execution to force deadline recalculation. */
1224 if (use_icount)
1225 qemu_notify_event();
1229 int qemu_timer_pending(QEMUTimer *ts)
1231 QEMUTimer *t;
1232 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1233 if (t == ts)
1234 return 1;
1236 return 0;
1239 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1241 if (!timer_head)
1242 return 0;
1243 return (timer_head->expire_time <= current_time);
1246 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1248 QEMUTimer *ts;
1250 for(;;) {
1251 ts = *ptimer_head;
1252 if (!ts || ts->expire_time > current_time)
1253 break;
1254 /* remove timer from the list before calling the callback */
1255 *ptimer_head = ts->next;
1256 ts->next = NULL;
1258 /* run the callback (the timer list can be modified) */
1259 ts->cb(ts->opaque);
1263 int64_t qemu_get_clock(QEMUClock *clock)
1265 switch(clock->type) {
1266 case QEMU_TIMER_REALTIME:
1267 return get_clock() / 1000000;
1268 default:
1269 case QEMU_TIMER_VIRTUAL:
1270 if (use_icount) {
1271 return cpu_get_icount();
1272 } else {
1273 return cpu_get_clock();
1278 static void init_timers(void)
1280 init_get_clock();
1281 ticks_per_sec = QEMU_TIMER_BASE;
1282 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1283 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1286 /* save a timer */
1287 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1289 uint64_t expire_time;
1291 if (qemu_timer_pending(ts)) {
1292 expire_time = ts->expire_time;
1293 } else {
1294 expire_time = -1;
1296 qemu_put_be64(f, expire_time);
1299 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1301 uint64_t expire_time;
1303 expire_time = qemu_get_be64(f);
1304 if (expire_time != -1) {
1305 qemu_mod_timer(ts, expire_time);
1306 } else {
1307 qemu_del_timer(ts);
1311 static void timer_save(QEMUFile *f, void *opaque)
1313 if (cpu_ticks_enabled) {
1314 hw_error("cannot save state if virtual timers are running");
1316 qemu_put_be64(f, cpu_ticks_offset);
1317 qemu_put_be64(f, ticks_per_sec);
1318 qemu_put_be64(f, cpu_clock_offset);
1321 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1323 if (version_id != 1 && version_id != 2)
1324 return -EINVAL;
1325 if (cpu_ticks_enabled) {
1326 return -EINVAL;
1328 cpu_ticks_offset=qemu_get_be64(f);
1329 ticks_per_sec=qemu_get_be64(f);
1330 if (version_id == 2) {
1331 cpu_clock_offset=qemu_get_be64(f);
1333 return 0;
1336 static void qemu_event_increment(void);
1338 #ifdef _WIN32
1339 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1340 DWORD_PTR dwUser, DWORD_PTR dw1,
1341 DWORD_PTR dw2)
1342 #else
1343 static void host_alarm_handler(int host_signum)
1344 #endif
1346 #if 0
1347 #define DISP_FREQ 1000
1349 static int64_t delta_min = INT64_MAX;
1350 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1351 static int count;
1352 ti = qemu_get_clock(vm_clock);
1353 if (last_clock != 0) {
1354 delta = ti - last_clock;
1355 if (delta < delta_min)
1356 delta_min = delta;
1357 if (delta > delta_max)
1358 delta_max = delta;
1359 delta_cum += delta;
1360 if (++count == DISP_FREQ) {
1361 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1362 muldiv64(delta_min, 1000000, ticks_per_sec),
1363 muldiv64(delta_max, 1000000, ticks_per_sec),
1364 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1365 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1366 count = 0;
1367 delta_min = INT64_MAX;
1368 delta_max = 0;
1369 delta_cum = 0;
1372 last_clock = ti;
1374 #endif
1375 if (alarm_has_dynticks(alarm_timer) ||
1376 (!use_icount &&
1377 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1378 qemu_get_clock(vm_clock))) ||
1379 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1380 qemu_get_clock(rt_clock))) {
1381 qemu_event_increment();
1382 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1384 #ifndef CONFIG_IOTHREAD
1385 if (next_cpu) {
1386 /* stop the currently executing cpu because a timer occured */
1387 cpu_exit(next_cpu);
1388 #ifdef CONFIG_KQEMU
1389 if (next_cpu->kqemu_enabled) {
1390 kqemu_cpu_interrupt(next_cpu);
1392 #endif
1394 #endif
1395 timer_alarm_pending = 1;
1396 qemu_notify_event();
1400 static int64_t qemu_next_deadline(void)
1402 int64_t delta;
1404 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1405 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1406 qemu_get_clock(vm_clock);
1407 } else {
1408 /* To avoid problems with overflow limit this to 2^32. */
1409 delta = INT32_MAX;
1412 if (delta < 0)
1413 delta = 0;
1415 return delta;
1418 #if defined(__linux__) || defined(_WIN32)
1419 static uint64_t qemu_next_deadline_dyntick(void)
1421 int64_t delta;
1422 int64_t rtdelta;
1424 if (use_icount)
1425 delta = INT32_MAX;
1426 else
1427 delta = (qemu_next_deadline() + 999) / 1000;
1429 if (active_timers[QEMU_TIMER_REALTIME]) {
1430 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1431 qemu_get_clock(rt_clock))*1000;
1432 if (rtdelta < delta)
1433 delta = rtdelta;
1436 if (delta < MIN_TIMER_REARM_US)
1437 delta = MIN_TIMER_REARM_US;
1439 return delta;
1441 #endif
1443 #ifndef _WIN32
1445 /* Sets a specific flag */
1446 static int fcntl_setfl(int fd, int flag)
1448 int flags;
1450 flags = fcntl(fd, F_GETFL);
1451 if (flags == -1)
1452 return -errno;
1454 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1455 return -errno;
1457 return 0;
1460 #if defined(__linux__)
1462 #define RTC_FREQ 1024
1464 static void enable_sigio_timer(int fd)
1466 struct sigaction act;
1468 /* timer signal */
1469 sigfillset(&act.sa_mask);
1470 act.sa_flags = 0;
1471 act.sa_handler = host_alarm_handler;
1473 sigaction(SIGIO, &act, NULL);
1474 fcntl_setfl(fd, O_ASYNC);
1475 fcntl(fd, F_SETOWN, getpid());
1478 static int hpet_start_timer(struct qemu_alarm_timer *t)
1480 struct hpet_info info;
1481 int r, fd;
1483 fd = open("/dev/hpet", O_RDONLY);
1484 if (fd < 0)
1485 return -1;
1487 /* Set frequency */
1488 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1489 if (r < 0) {
1490 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1491 "error, but for better emulation accuracy type:\n"
1492 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1493 goto fail;
1496 /* Check capabilities */
1497 r = ioctl(fd, HPET_INFO, &info);
1498 if (r < 0)
1499 goto fail;
1501 /* Enable periodic mode */
1502 r = ioctl(fd, HPET_EPI, 0);
1503 if (info.hi_flags && (r < 0))
1504 goto fail;
1506 /* Enable interrupt */
1507 r = ioctl(fd, HPET_IE_ON, 0);
1508 if (r < 0)
1509 goto fail;
1511 enable_sigio_timer(fd);
1512 t->priv = (void *)(long)fd;
1514 return 0;
1515 fail:
1516 close(fd);
1517 return -1;
1520 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1522 int fd = (long)t->priv;
1524 close(fd);
1527 static int rtc_start_timer(struct qemu_alarm_timer *t)
1529 int rtc_fd;
1530 unsigned long current_rtc_freq = 0;
1532 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1533 if (rtc_fd < 0)
1534 return -1;
1535 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1536 if (current_rtc_freq != RTC_FREQ &&
1537 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1538 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1539 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1540 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1541 goto fail;
1543 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1544 fail:
1545 close(rtc_fd);
1546 return -1;
1549 enable_sigio_timer(rtc_fd);
1551 t->priv = (void *)(long)rtc_fd;
1553 return 0;
1556 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1558 int rtc_fd = (long)t->priv;
1560 close(rtc_fd);
1563 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1565 struct sigevent ev;
1566 timer_t host_timer;
1567 struct sigaction act;
1569 sigfillset(&act.sa_mask);
1570 act.sa_flags = 0;
1571 act.sa_handler = host_alarm_handler;
1573 sigaction(SIGALRM, &act, NULL);
1576 * Initialize ev struct to 0 to avoid valgrind complaining
1577 * about uninitialized data in timer_create call
1579 memset(&ev, 0, sizeof(ev));
1580 ev.sigev_value.sival_int = 0;
1581 ev.sigev_notify = SIGEV_SIGNAL;
1582 ev.sigev_signo = SIGALRM;
1584 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1585 perror("timer_create");
1587 /* disable dynticks */
1588 fprintf(stderr, "Dynamic Ticks disabled\n");
1590 return -1;
1593 t->priv = (void *)(long)host_timer;
1595 return 0;
1598 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1600 timer_t host_timer = (timer_t)(long)t->priv;
1602 timer_delete(host_timer);
1605 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1607 timer_t host_timer = (timer_t)(long)t->priv;
1608 struct itimerspec timeout;
1609 int64_t nearest_delta_us = INT64_MAX;
1610 int64_t current_us;
1612 if (!active_timers[QEMU_TIMER_REALTIME] &&
1613 !active_timers[QEMU_TIMER_VIRTUAL])
1614 return;
1616 nearest_delta_us = qemu_next_deadline_dyntick();
1618 /* check whether a timer is already running */
1619 if (timer_gettime(host_timer, &timeout)) {
1620 perror("gettime");
1621 fprintf(stderr, "Internal timer error: aborting\n");
1622 exit(1);
1624 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1625 if (current_us && current_us <= nearest_delta_us)
1626 return;
1628 timeout.it_interval.tv_sec = 0;
1629 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1630 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1631 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1632 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1633 perror("settime");
1634 fprintf(stderr, "Internal timer error: aborting\n");
1635 exit(1);
1639 #endif /* defined(__linux__) */
1641 static int unix_start_timer(struct qemu_alarm_timer *t)
1643 struct sigaction act;
1644 struct itimerval itv;
1645 int err;
1647 /* timer signal */
1648 sigfillset(&act.sa_mask);
1649 act.sa_flags = 0;
1650 act.sa_handler = host_alarm_handler;
1652 sigaction(SIGALRM, &act, NULL);
1654 itv.it_interval.tv_sec = 0;
1655 /* for i386 kernel 2.6 to get 1 ms */
1656 itv.it_interval.tv_usec = 999;
1657 itv.it_value.tv_sec = 0;
1658 itv.it_value.tv_usec = 10 * 1000;
1660 err = setitimer(ITIMER_REAL, &itv, NULL);
1661 if (err)
1662 return -1;
1664 return 0;
1667 static void unix_stop_timer(struct qemu_alarm_timer *t)
1669 struct itimerval itv;
1671 memset(&itv, 0, sizeof(itv));
1672 setitimer(ITIMER_REAL, &itv, NULL);
1675 #endif /* !defined(_WIN32) */
1678 #ifdef _WIN32
1680 static int win32_start_timer(struct qemu_alarm_timer *t)
1682 TIMECAPS tc;
1683 struct qemu_alarm_win32 *data = t->priv;
1684 UINT flags;
1686 memset(&tc, 0, sizeof(tc));
1687 timeGetDevCaps(&tc, sizeof(tc));
1689 if (data->period < tc.wPeriodMin)
1690 data->period = tc.wPeriodMin;
1692 timeBeginPeriod(data->period);
1694 flags = TIME_CALLBACK_FUNCTION;
1695 if (alarm_has_dynticks(t))
1696 flags |= TIME_ONESHOT;
1697 else
1698 flags |= TIME_PERIODIC;
1700 data->timerId = timeSetEvent(1, // interval (ms)
1701 data->period, // resolution
1702 host_alarm_handler, // function
1703 (DWORD)t, // parameter
1704 flags);
1706 if (!data->timerId) {
1707 perror("Failed to initialize win32 alarm timer");
1708 timeEndPeriod(data->period);
1709 return -1;
1712 return 0;
1715 static void win32_stop_timer(struct qemu_alarm_timer *t)
1717 struct qemu_alarm_win32 *data = t->priv;
1719 timeKillEvent(data->timerId);
1720 timeEndPeriod(data->period);
1723 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1725 struct qemu_alarm_win32 *data = t->priv;
1726 uint64_t nearest_delta_us;
1728 if (!active_timers[QEMU_TIMER_REALTIME] &&
1729 !active_timers[QEMU_TIMER_VIRTUAL])
1730 return;
1732 nearest_delta_us = qemu_next_deadline_dyntick();
1733 nearest_delta_us /= 1000;
1735 timeKillEvent(data->timerId);
1737 data->timerId = timeSetEvent(1,
1738 data->period,
1739 host_alarm_handler,
1740 (DWORD)t,
1741 TIME_ONESHOT | TIME_PERIODIC);
1743 if (!data->timerId) {
1744 perror("Failed to re-arm win32 alarm timer");
1746 timeEndPeriod(data->period);
1747 exit(1);
1751 #endif /* _WIN32 */
1753 static int init_timer_alarm(void)
1755 struct qemu_alarm_timer *t = NULL;
1756 int i, err = -1;
1758 for (i = 0; alarm_timers[i].name; i++) {
1759 t = &alarm_timers[i];
1761 err = t->start(t);
1762 if (!err)
1763 break;
1766 if (err) {
1767 err = -ENOENT;
1768 goto fail;
1771 alarm_timer = t;
1773 return 0;
1775 fail:
1776 return err;
1779 static void quit_timers(void)
1781 alarm_timer->stop(alarm_timer);
1782 alarm_timer = NULL;
1785 /***********************************************************/
1786 /* host time/date access */
1787 void qemu_get_timedate(struct tm *tm, int offset)
1789 time_t ti;
1790 struct tm *ret;
1792 time(&ti);
1793 ti += offset;
1794 if (rtc_date_offset == -1) {
1795 if (rtc_utc)
1796 ret = gmtime(&ti);
1797 else
1798 ret = localtime(&ti);
1799 } else {
1800 ti -= rtc_date_offset;
1801 ret = gmtime(&ti);
1804 memcpy(tm, ret, sizeof(struct tm));
1807 int qemu_timedate_diff(struct tm *tm)
1809 time_t seconds;
1811 if (rtc_date_offset == -1)
1812 if (rtc_utc)
1813 seconds = mktimegm(tm);
1814 else
1815 seconds = mktime(tm);
1816 else
1817 seconds = mktimegm(tm) + rtc_date_offset;
1819 return seconds - time(NULL);
1822 #ifdef _WIN32
1823 static void socket_cleanup(void)
1825 WSACleanup();
1828 static int socket_init(void)
1830 WSADATA Data;
1831 int ret, err;
1833 ret = WSAStartup(MAKEWORD(2,2), &Data);
1834 if (ret != 0) {
1835 err = WSAGetLastError();
1836 fprintf(stderr, "WSAStartup: %d\n", err);
1837 return -1;
1839 atexit(socket_cleanup);
1840 return 0;
1842 #endif
1844 int get_param_value(char *buf, int buf_size,
1845 const char *tag, const char *str)
1847 const char *p;
1848 char option[128];
1850 p = str;
1851 for(;;) {
1852 p = get_opt_name(option, sizeof(option), p, '=');
1853 if (*p != '=')
1854 break;
1855 p++;
1856 if (!strcmp(tag, option)) {
1857 (void)get_opt_value(buf, buf_size, p);
1858 return strlen(buf);
1859 } else {
1860 p = get_opt_value(NULL, 0, p);
1862 if (*p != ',')
1863 break;
1864 p++;
1866 return 0;
1869 int check_params(const char * const *params, const char *str)
1871 int name_buf_size = 1;
1872 const char *p;
1873 char *name_buf;
1874 int i, len;
1875 int ret = 0;
1877 for (i = 0; params[i] != NULL; i++) {
1878 len = strlen(params[i]) + 1;
1879 if (len > name_buf_size) {
1880 name_buf_size = len;
1883 name_buf = qemu_malloc(name_buf_size);
1885 p = str;
1886 while (*p != '\0') {
1887 p = get_opt_name(name_buf, name_buf_size, p, '=');
1888 if (*p != '=') {
1889 ret = -1;
1890 break;
1892 p++;
1893 for(i = 0; params[i] != NULL; i++)
1894 if (!strcmp(params[i], name_buf))
1895 break;
1896 if (params[i] == NULL) {
1897 ret = -1;
1898 break;
1900 p = get_opt_value(NULL, 0, p);
1901 if (*p != ',')
1902 break;
1903 p++;
1906 qemu_free(name_buf);
1907 return ret;
1910 /***********************************************************/
1911 /* Bluetooth support */
1912 static int nb_hcis;
1913 static int cur_hci;
1914 static struct HCIInfo *hci_table[MAX_NICS];
1916 static struct bt_vlan_s {
1917 struct bt_scatternet_s net;
1918 int id;
1919 struct bt_vlan_s *next;
1920 } *first_bt_vlan;
1922 /* find or alloc a new bluetooth "VLAN" */
1923 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1925 struct bt_vlan_s **pvlan, *vlan;
1926 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1927 if (vlan->id == id)
1928 return &vlan->net;
1930 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1931 vlan->id = id;
1932 pvlan = &first_bt_vlan;
1933 while (*pvlan != NULL)
1934 pvlan = &(*pvlan)->next;
1935 *pvlan = vlan;
1936 return &vlan->net;
1939 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1943 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1945 return -ENOTSUP;
1948 static struct HCIInfo null_hci = {
1949 .cmd_send = null_hci_send,
1950 .sco_send = null_hci_send,
1951 .acl_send = null_hci_send,
1952 .bdaddr_set = null_hci_addr_set,
1955 struct HCIInfo *qemu_next_hci(void)
1957 if (cur_hci == nb_hcis)
1958 return &null_hci;
1960 return hci_table[cur_hci++];
1963 static struct HCIInfo *hci_init(const char *str)
1965 char *endp;
1966 struct bt_scatternet_s *vlan = 0;
1968 if (!strcmp(str, "null"))
1969 /* null */
1970 return &null_hci;
1971 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1972 /* host[:hciN] */
1973 return bt_host_hci(str[4] ? str + 5 : "hci0");
1974 else if (!strncmp(str, "hci", 3)) {
1975 /* hci[,vlan=n] */
1976 if (str[3]) {
1977 if (!strncmp(str + 3, ",vlan=", 6)) {
1978 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1979 if (*endp)
1980 vlan = 0;
1982 } else
1983 vlan = qemu_find_bt_vlan(0);
1984 if (vlan)
1985 return bt_new_hci(vlan);
1988 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1990 return 0;
1993 static int bt_hci_parse(const char *str)
1995 struct HCIInfo *hci;
1996 bdaddr_t bdaddr;
1998 if (nb_hcis >= MAX_NICS) {
1999 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2000 return -1;
2003 hci = hci_init(str);
2004 if (!hci)
2005 return -1;
2007 bdaddr.b[0] = 0x52;
2008 bdaddr.b[1] = 0x54;
2009 bdaddr.b[2] = 0x00;
2010 bdaddr.b[3] = 0x12;
2011 bdaddr.b[4] = 0x34;
2012 bdaddr.b[5] = 0x56 + nb_hcis;
2013 hci->bdaddr_set(hci, bdaddr.b);
2015 hci_table[nb_hcis++] = hci;
2017 return 0;
2020 static void bt_vhci_add(int vlan_id)
2022 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2024 if (!vlan->slave)
2025 fprintf(stderr, "qemu: warning: adding a VHCI to "
2026 "an empty scatternet %i\n", vlan_id);
2028 bt_vhci_init(bt_new_hci(vlan));
2031 static struct bt_device_s *bt_device_add(const char *opt)
2033 struct bt_scatternet_s *vlan;
2034 int vlan_id = 0;
2035 char *endp = strstr(opt, ",vlan=");
2036 int len = (endp ? endp - opt : strlen(opt)) + 1;
2037 char devname[10];
2039 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2041 if (endp) {
2042 vlan_id = strtol(endp + 6, &endp, 0);
2043 if (*endp) {
2044 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2045 return 0;
2049 vlan = qemu_find_bt_vlan(vlan_id);
2051 if (!vlan->slave)
2052 fprintf(stderr, "qemu: warning: adding a slave device to "
2053 "an empty scatternet %i\n", vlan_id);
2055 if (!strcmp(devname, "keyboard"))
2056 return bt_keyboard_init(vlan);
2058 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2059 return 0;
2062 static int bt_parse(const char *opt)
2064 const char *endp, *p;
2065 int vlan;
2067 if (strstart(opt, "hci", &endp)) {
2068 if (!*endp || *endp == ',') {
2069 if (*endp)
2070 if (!strstart(endp, ",vlan=", 0))
2071 opt = endp + 1;
2073 return bt_hci_parse(opt);
2075 } else if (strstart(opt, "vhci", &endp)) {
2076 if (!*endp || *endp == ',') {
2077 if (*endp) {
2078 if (strstart(endp, ",vlan=", &p)) {
2079 vlan = strtol(p, (char **) &endp, 0);
2080 if (*endp) {
2081 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2082 return 1;
2084 } else {
2085 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2086 return 1;
2088 } else
2089 vlan = 0;
2091 bt_vhci_add(vlan);
2092 return 0;
2094 } else if (strstart(opt, "device:", &endp))
2095 return !bt_device_add(endp);
2097 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2098 return 1;
2101 /***********************************************************/
2102 /* QEMU Block devices */
2104 #define HD_ALIAS "index=%d,media=disk"
2105 #define CDROM_ALIAS "index=2,media=cdrom"
2106 #define FD_ALIAS "index=%d,if=floppy"
2107 #define PFLASH_ALIAS "if=pflash"
2108 #define MTD_ALIAS "if=mtd"
2109 #define SD_ALIAS "index=0,if=sd"
2111 static int drive_opt_get_free_idx(void)
2113 int index;
2115 for (index = 0; index < MAX_DRIVES; index++)
2116 if (!drives_opt[index].used) {
2117 drives_opt[index].used = 1;
2118 return index;
2121 return -1;
2124 static int drive_get_free_idx(void)
2126 int index;
2128 for (index = 0; index < MAX_DRIVES; index++)
2129 if (!drives_table[index].used) {
2130 drives_table[index].used = 1;
2131 return index;
2134 return -1;
2137 int drive_add(const char *file, const char *fmt, ...)
2139 va_list ap;
2140 int index = drive_opt_get_free_idx();
2142 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2143 fprintf(stderr, "qemu: too many drives\n");
2144 return -1;
2147 drives_opt[index].file = file;
2148 va_start(ap, fmt);
2149 vsnprintf(drives_opt[index].opt,
2150 sizeof(drives_opt[0].opt), fmt, ap);
2151 va_end(ap);
2153 nb_drives_opt++;
2154 return index;
2157 void drive_remove(int index)
2159 drives_opt[index].used = 0;
2160 nb_drives_opt--;
2163 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2165 int index;
2167 /* seek interface, bus and unit */
2169 for (index = 0; index < MAX_DRIVES; index++)
2170 if (drives_table[index].type == type &&
2171 drives_table[index].bus == bus &&
2172 drives_table[index].unit == unit &&
2173 drives_table[index].used)
2174 return index;
2176 return -1;
2179 int drive_get_max_bus(BlockInterfaceType type)
2181 int max_bus;
2182 int index;
2184 max_bus = -1;
2185 for (index = 0; index < nb_drives; index++) {
2186 if(drives_table[index].type == type &&
2187 drives_table[index].bus > max_bus)
2188 max_bus = drives_table[index].bus;
2190 return max_bus;
2193 const char *drive_get_serial(BlockDriverState *bdrv)
2195 int index;
2197 for (index = 0; index < nb_drives; index++)
2198 if (drives_table[index].bdrv == bdrv)
2199 return drives_table[index].serial;
2201 return "\0";
2204 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2206 int index;
2208 for (index = 0; index < nb_drives; index++)
2209 if (drives_table[index].bdrv == bdrv)
2210 return drives_table[index].onerror;
2212 return BLOCK_ERR_STOP_ENOSPC;
2215 static void bdrv_format_print(void *opaque, const char *name)
2217 fprintf(stderr, " %s", name);
2220 void drive_uninit(BlockDriverState *bdrv)
2222 int i;
2224 for (i = 0; i < MAX_DRIVES; i++)
2225 if (drives_table[i].bdrv == bdrv) {
2226 drives_table[i].bdrv = NULL;
2227 drives_table[i].used = 0;
2228 drive_remove(drives_table[i].drive_opt_idx);
2229 nb_drives--;
2230 break;
2234 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2236 char buf[128];
2237 char file[1024];
2238 char devname[128];
2239 char serial[21];
2240 const char *mediastr = "";
2241 BlockInterfaceType type;
2242 enum { MEDIA_DISK, MEDIA_CDROM } media;
2243 int bus_id, unit_id;
2244 int cyls, heads, secs, translation;
2245 BlockDriverState *bdrv;
2246 BlockDriver *drv = NULL;
2247 QEMUMachine *machine = opaque;
2248 int max_devs;
2249 int index;
2250 int cache;
2251 int bdrv_flags, onerror;
2252 int drives_table_idx;
2253 char *str = arg->opt;
2254 static const char * const params[] = { "bus", "unit", "if", "index",
2255 "cyls", "heads", "secs", "trans",
2256 "media", "snapshot", "file",
2257 "cache", "format", "serial", "werror",
2258 "boot", NULL };
2260 if (check_params(params, str) < 0) {
2261 fprintf(stderr, "qemu: unknown parameter in '%s'\n", str);
2262 return -1;
2265 file[0] = 0;
2266 cyls = heads = secs = 0;
2267 bus_id = 0;
2268 unit_id = -1;
2269 translation = BIOS_ATA_TRANSLATION_AUTO;
2270 index = -1;
2271 cache = 3;
2273 if (machine->use_scsi) {
2274 type = IF_SCSI;
2275 max_devs = MAX_SCSI_DEVS;
2276 pstrcpy(devname, sizeof(devname), "scsi");
2277 } else {
2278 type = IF_IDE;
2279 max_devs = MAX_IDE_DEVS;
2280 pstrcpy(devname, sizeof(devname), "ide");
2282 media = MEDIA_DISK;
2284 /* extract parameters */
2286 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2287 bus_id = strtol(buf, NULL, 0);
2288 if (bus_id < 0) {
2289 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2290 return -1;
2294 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2295 unit_id = strtol(buf, NULL, 0);
2296 if (unit_id < 0) {
2297 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2298 return -1;
2302 if (get_param_value(buf, sizeof(buf), "if", str)) {
2303 pstrcpy(devname, sizeof(devname), buf);
2304 if (!strcmp(buf, "ide")) {
2305 type = IF_IDE;
2306 max_devs = MAX_IDE_DEVS;
2307 } else if (!strcmp(buf, "scsi")) {
2308 type = IF_SCSI;
2309 max_devs = MAX_SCSI_DEVS;
2310 } else if (!strcmp(buf, "floppy")) {
2311 type = IF_FLOPPY;
2312 max_devs = 0;
2313 } else if (!strcmp(buf, "pflash")) {
2314 type = IF_PFLASH;
2315 max_devs = 0;
2316 } else if (!strcmp(buf, "mtd")) {
2317 type = IF_MTD;
2318 max_devs = 0;
2319 } else if (!strcmp(buf, "sd")) {
2320 type = IF_SD;
2321 max_devs = 0;
2322 } else if (!strcmp(buf, "virtio")) {
2323 type = IF_VIRTIO;
2324 max_devs = 0;
2325 } else if (!strcmp(buf, "xen")) {
2326 type = IF_XEN;
2327 max_devs = 0;
2328 } else {
2329 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2330 return -1;
2334 if (get_param_value(buf, sizeof(buf), "index", str)) {
2335 index = strtol(buf, NULL, 0);
2336 if (index < 0) {
2337 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2338 return -1;
2342 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2343 cyls = strtol(buf, NULL, 0);
2346 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2347 heads = strtol(buf, NULL, 0);
2350 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2351 secs = strtol(buf, NULL, 0);
2354 if (cyls || heads || secs) {
2355 if (cyls < 1 || cyls > 16383) {
2356 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2357 return -1;
2359 if (heads < 1 || heads > 16) {
2360 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2361 return -1;
2363 if (secs < 1 || secs > 63) {
2364 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2365 return -1;
2369 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2370 if (!cyls) {
2371 fprintf(stderr,
2372 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2373 str);
2374 return -1;
2376 if (!strcmp(buf, "none"))
2377 translation = BIOS_ATA_TRANSLATION_NONE;
2378 else if (!strcmp(buf, "lba"))
2379 translation = BIOS_ATA_TRANSLATION_LBA;
2380 else if (!strcmp(buf, "auto"))
2381 translation = BIOS_ATA_TRANSLATION_AUTO;
2382 else {
2383 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2384 return -1;
2388 if (get_param_value(buf, sizeof(buf), "media", str)) {
2389 if (!strcmp(buf, "disk")) {
2390 media = MEDIA_DISK;
2391 } else if (!strcmp(buf, "cdrom")) {
2392 if (cyls || secs || heads) {
2393 fprintf(stderr,
2394 "qemu: '%s' invalid physical CHS format\n", str);
2395 return -1;
2397 media = MEDIA_CDROM;
2398 } else {
2399 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2400 return -1;
2404 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2405 if (!strcmp(buf, "on"))
2406 snapshot = 1;
2407 else if (!strcmp(buf, "off"))
2408 snapshot = 0;
2409 else {
2410 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2411 return -1;
2415 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2416 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2417 cache = 0;
2418 else if (!strcmp(buf, "writethrough"))
2419 cache = 1;
2420 else if (!strcmp(buf, "writeback"))
2421 cache = 2;
2422 else {
2423 fprintf(stderr, "qemu: invalid cache option\n");
2424 return -1;
2428 if (get_param_value(buf, sizeof(buf), "format", str)) {
2429 if (strcmp(buf, "?") == 0) {
2430 fprintf(stderr, "qemu: Supported formats:");
2431 bdrv_iterate_format(bdrv_format_print, NULL);
2432 fprintf(stderr, "\n");
2433 return -1;
2435 drv = bdrv_find_format(buf);
2436 if (!drv) {
2437 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2438 return -1;
2442 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2443 if (!strcmp(buf, "on")) {
2444 if (extboot_drive != -1) {
2445 fprintf(stderr, "qemu: two bootable drives specified\n");
2446 return -1;
2448 extboot_drive = nb_drives;
2449 } else if (strcmp(buf, "off")) {
2450 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2451 return -1;
2455 if (arg->file == NULL)
2456 get_param_value(file, sizeof(file), "file", str);
2457 else
2458 pstrcpy(file, sizeof(file), arg->file);
2460 if (!get_param_value(serial, sizeof(serial), "serial", str))
2461 memset(serial, 0, sizeof(serial));
2463 onerror = BLOCK_ERR_STOP_ENOSPC;
2464 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2465 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2466 fprintf(stderr, "werror is no supported by this format\n");
2467 return -1;
2469 if (!strcmp(buf, "ignore"))
2470 onerror = BLOCK_ERR_IGNORE;
2471 else if (!strcmp(buf, "enospc"))
2472 onerror = BLOCK_ERR_STOP_ENOSPC;
2473 else if (!strcmp(buf, "stop"))
2474 onerror = BLOCK_ERR_STOP_ANY;
2475 else if (!strcmp(buf, "report"))
2476 onerror = BLOCK_ERR_REPORT;
2477 else {
2478 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2479 return -1;
2483 /* compute bus and unit according index */
2485 if (index != -1) {
2486 if (bus_id != 0 || unit_id != -1) {
2487 fprintf(stderr,
2488 "qemu: '%s' index cannot be used with bus and unit\n", str);
2489 return -1;
2491 if (max_devs == 0)
2493 unit_id = index;
2494 bus_id = 0;
2495 } else {
2496 unit_id = index % max_devs;
2497 bus_id = index / max_devs;
2501 /* if user doesn't specify a unit_id,
2502 * try to find the first free
2505 if (unit_id == -1) {
2506 unit_id = 0;
2507 while (drive_get_index(type, bus_id, unit_id) != -1) {
2508 unit_id++;
2509 if (max_devs && unit_id >= max_devs) {
2510 unit_id -= max_devs;
2511 bus_id++;
2516 /* check unit id */
2518 if (max_devs && unit_id >= max_devs) {
2519 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2520 str, unit_id, max_devs - 1);
2521 return -1;
2525 * ignore multiple definitions
2528 if (drive_get_index(type, bus_id, unit_id) != -1)
2529 return -2;
2531 /* init */
2533 if (type == IF_IDE || type == IF_SCSI)
2534 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2535 if (max_devs)
2536 snprintf(buf, sizeof(buf), "%s%i%s%i",
2537 devname, bus_id, mediastr, unit_id);
2538 else
2539 snprintf(buf, sizeof(buf), "%s%s%i",
2540 devname, mediastr, unit_id);
2541 bdrv = bdrv_new(buf);
2542 drives_table_idx = drive_get_free_idx();
2543 drives_table[drives_table_idx].bdrv = bdrv;
2544 drives_table[drives_table_idx].type = type;
2545 drives_table[drives_table_idx].bus = bus_id;
2546 drives_table[drives_table_idx].unit = unit_id;
2547 drives_table[drives_table_idx].onerror = onerror;
2548 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2549 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2550 nb_drives++;
2552 switch(type) {
2553 case IF_IDE:
2554 case IF_SCSI:
2555 case IF_XEN:
2556 switch(media) {
2557 case MEDIA_DISK:
2558 if (cyls != 0) {
2559 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2560 bdrv_set_translation_hint(bdrv, translation);
2562 break;
2563 case MEDIA_CDROM:
2564 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2565 break;
2567 break;
2568 case IF_SD:
2569 /* FIXME: This isn't really a floppy, but it's a reasonable
2570 approximation. */
2571 case IF_FLOPPY:
2572 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2573 break;
2574 case IF_PFLASH:
2575 case IF_MTD:
2576 case IF_VIRTIO:
2577 break;
2578 case IF_COUNT:
2579 abort();
2581 if (!file[0])
2582 return -2;
2583 bdrv_flags = 0;
2584 if (snapshot) {
2585 bdrv_flags |= BDRV_O_SNAPSHOT;
2586 cache = 2; /* always use write-back with snapshot */
2588 if (cache == 0) /* no caching */
2589 bdrv_flags |= BDRV_O_NOCACHE;
2590 else if (cache == 2) /* write-back */
2591 bdrv_flags |= BDRV_O_CACHE_WB;
2592 else if (cache == 3) /* not specified */
2593 bdrv_flags |= BDRV_O_CACHE_DEF;
2594 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2595 fprintf(stderr, "qemu: could not open disk image %s\n",
2596 file);
2597 return -1;
2599 if (bdrv_key_required(bdrv))
2600 autostart = 0;
2601 return drives_table_idx;
2604 static void numa_add(const char *optarg)
2606 char option[128];
2607 char *endptr;
2608 unsigned long long value, endvalue;
2609 int nodenr;
2611 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2612 if (!strcmp(option, "node")) {
2613 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2614 nodenr = nb_numa_nodes;
2615 } else {
2616 nodenr = strtoull(option, NULL, 10);
2619 if (get_param_value(option, 128, "mem", optarg) == 0) {
2620 node_mem[nodenr] = 0;
2621 } else {
2622 value = strtoull(option, &endptr, 0);
2623 switch (*endptr) {
2624 case 0: case 'M': case 'm':
2625 value <<= 20;
2626 break;
2627 case 'G': case 'g':
2628 value <<= 30;
2629 break;
2631 node_mem[nodenr] = value;
2633 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2634 node_cpumask[nodenr] = 0;
2635 } else {
2636 value = strtoull(option, &endptr, 10);
2637 if (value >= 64) {
2638 value = 63;
2639 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2640 } else {
2641 if (*endptr == '-') {
2642 endvalue = strtoull(endptr+1, &endptr, 10);
2643 if (endvalue >= 63) {
2644 endvalue = 62;
2645 fprintf(stderr,
2646 "only 63 CPUs in NUMA mode supported.\n");
2648 value = (1 << (endvalue + 1)) - (1 << value);
2649 } else {
2650 value = 1 << value;
2653 node_cpumask[nodenr] = value;
2655 nb_numa_nodes++;
2657 return;
2660 /***********************************************************/
2661 /* USB devices */
2663 static USBPort *used_usb_ports;
2664 static USBPort *free_usb_ports;
2666 /* ??? Maybe change this to register a hub to keep track of the topology. */
2667 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2668 usb_attachfn attach)
2670 port->opaque = opaque;
2671 port->index = index;
2672 port->attach = attach;
2673 port->next = free_usb_ports;
2674 free_usb_ports = port;
2677 int usb_device_add_dev(USBDevice *dev)
2679 USBPort *port;
2681 /* Find a USB port to add the device to. */
2682 port = free_usb_ports;
2683 if (!port->next) {
2684 USBDevice *hub;
2686 /* Create a new hub and chain it on. */
2687 free_usb_ports = NULL;
2688 port->next = used_usb_ports;
2689 used_usb_ports = port;
2691 hub = usb_hub_init(VM_USB_HUB_SIZE);
2692 usb_attach(port, hub);
2693 port = free_usb_ports;
2696 free_usb_ports = port->next;
2697 port->next = used_usb_ports;
2698 used_usb_ports = port;
2699 usb_attach(port, dev);
2700 return 0;
2703 static void usb_msd_password_cb(void *opaque, int err)
2705 USBDevice *dev = opaque;
2707 if (!err)
2708 usb_device_add_dev(dev);
2709 else
2710 dev->handle_destroy(dev);
2713 static int usb_device_add(const char *devname, int is_hotplug)
2715 const char *p;
2716 USBDevice *dev;
2718 if (!free_usb_ports)
2719 return -1;
2721 if (strstart(devname, "host:", &p)) {
2722 dev = usb_host_device_open(p);
2723 } else if (!strcmp(devname, "mouse")) {
2724 dev = usb_mouse_init();
2725 } else if (!strcmp(devname, "tablet")) {
2726 dev = usb_tablet_init();
2727 } else if (!strcmp(devname, "keyboard")) {
2728 dev = usb_keyboard_init();
2729 } else if (strstart(devname, "disk:", &p)) {
2730 BlockDriverState *bs;
2732 dev = usb_msd_init(p);
2733 if (!dev)
2734 return -1;
2735 bs = usb_msd_get_bdrv(dev);
2736 if (bdrv_key_required(bs)) {
2737 autostart = 0;
2738 if (is_hotplug) {
2739 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2740 dev);
2741 return 0;
2744 } else if (!strcmp(devname, "wacom-tablet")) {
2745 dev = usb_wacom_init();
2746 } else if (strstart(devname, "serial:", &p)) {
2747 dev = usb_serial_init(p);
2748 #ifdef CONFIG_BRLAPI
2749 } else if (!strcmp(devname, "braille")) {
2750 dev = usb_baum_init();
2751 #endif
2752 } else if (strstart(devname, "net:", &p)) {
2753 int nic = nb_nics;
2755 if (net_client_init("nic", p) < 0)
2756 return -1;
2757 nd_table[nic].model = "usb";
2758 dev = usb_net_init(&nd_table[nic]);
2759 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2760 dev = usb_bt_init(devname[2] ? hci_init(p) :
2761 bt_new_hci(qemu_find_bt_vlan(0)));
2762 } else {
2763 return -1;
2765 if (!dev)
2766 return -1;
2768 return usb_device_add_dev(dev);
2771 int usb_device_del_addr(int bus_num, int addr)
2773 USBPort *port;
2774 USBPort **lastp;
2775 USBDevice *dev;
2777 if (!used_usb_ports)
2778 return -1;
2780 if (bus_num != 0)
2781 return -1;
2783 lastp = &used_usb_ports;
2784 port = used_usb_ports;
2785 while (port && port->dev->addr != addr) {
2786 lastp = &port->next;
2787 port = port->next;
2790 if (!port)
2791 return -1;
2793 dev = port->dev;
2794 *lastp = port->next;
2795 usb_attach(port, NULL);
2796 dev->handle_destroy(dev);
2797 port->next = free_usb_ports;
2798 free_usb_ports = port;
2799 return 0;
2802 static int usb_device_del(const char *devname)
2804 int bus_num, addr;
2805 const char *p;
2807 if (strstart(devname, "host:", &p))
2808 return usb_host_device_close(p);
2810 if (!used_usb_ports)
2811 return -1;
2813 p = strchr(devname, '.');
2814 if (!p)
2815 return -1;
2816 bus_num = strtoul(devname, NULL, 0);
2817 addr = strtoul(p + 1, NULL, 0);
2819 return usb_device_del_addr(bus_num, addr);
2822 void do_usb_add(Monitor *mon, const char *devname)
2824 usb_device_add(devname, 1);
2827 void do_usb_del(Monitor *mon, const char *devname)
2829 usb_device_del(devname);
2832 void usb_info(Monitor *mon)
2834 USBDevice *dev;
2835 USBPort *port;
2836 const char *speed_str;
2838 if (!usb_enabled) {
2839 monitor_printf(mon, "USB support not enabled\n");
2840 return;
2843 for (port = used_usb_ports; port; port = port->next) {
2844 dev = port->dev;
2845 if (!dev)
2846 continue;
2847 switch(dev->speed) {
2848 case USB_SPEED_LOW:
2849 speed_str = "1.5";
2850 break;
2851 case USB_SPEED_FULL:
2852 speed_str = "12";
2853 break;
2854 case USB_SPEED_HIGH:
2855 speed_str = "480";
2856 break;
2857 default:
2858 speed_str = "?";
2859 break;
2861 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2862 0, dev->addr, speed_str, dev->devname);
2866 /***********************************************************/
2867 /* PCMCIA/Cardbus */
2869 static struct pcmcia_socket_entry_s {
2870 PCMCIASocket *socket;
2871 struct pcmcia_socket_entry_s *next;
2872 } *pcmcia_sockets = 0;
2874 void pcmcia_socket_register(PCMCIASocket *socket)
2876 struct pcmcia_socket_entry_s *entry;
2878 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2879 entry->socket = socket;
2880 entry->next = pcmcia_sockets;
2881 pcmcia_sockets = entry;
2884 void pcmcia_socket_unregister(PCMCIASocket *socket)
2886 struct pcmcia_socket_entry_s *entry, **ptr;
2888 ptr = &pcmcia_sockets;
2889 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2890 if (entry->socket == socket) {
2891 *ptr = entry->next;
2892 qemu_free(entry);
2896 void pcmcia_info(Monitor *mon)
2898 struct pcmcia_socket_entry_s *iter;
2900 if (!pcmcia_sockets)
2901 monitor_printf(mon, "No PCMCIA sockets\n");
2903 for (iter = pcmcia_sockets; iter; iter = iter->next)
2904 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2905 iter->socket->attached ? iter->socket->card_string :
2906 "Empty");
2909 /***********************************************************/
2910 /* register display */
2912 struct DisplayAllocator default_allocator = {
2913 defaultallocator_create_displaysurface,
2914 defaultallocator_resize_displaysurface,
2915 defaultallocator_free_displaysurface
2918 void register_displaystate(DisplayState *ds)
2920 DisplayState **s;
2921 s = &display_state;
2922 while (*s != NULL)
2923 s = &(*s)->next;
2924 ds->next = NULL;
2925 *s = ds;
2928 DisplayState *get_displaystate(void)
2930 return display_state;
2933 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2935 if(ds->allocator == &default_allocator) ds->allocator = da;
2936 return ds->allocator;
2939 /* dumb display */
2941 static void dumb_display_init(void)
2943 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2944 ds->allocator = &default_allocator;
2945 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2946 register_displaystate(ds);
2949 /***********************************************************/
2950 /* I/O handling */
2952 typedef struct IOHandlerRecord {
2953 int fd;
2954 IOCanRWHandler *fd_read_poll;
2955 IOHandler *fd_read;
2956 IOHandler *fd_write;
2957 int deleted;
2958 void *opaque;
2959 /* temporary data */
2960 struct pollfd *ufd;
2961 struct IOHandlerRecord *next;
2962 } IOHandlerRecord;
2964 static IOHandlerRecord *first_io_handler;
2966 /* XXX: fd_read_poll should be suppressed, but an API change is
2967 necessary in the character devices to suppress fd_can_read(). */
2968 int qemu_set_fd_handler2(int fd,
2969 IOCanRWHandler *fd_read_poll,
2970 IOHandler *fd_read,
2971 IOHandler *fd_write,
2972 void *opaque)
2974 IOHandlerRecord **pioh, *ioh;
2976 if (!fd_read && !fd_write) {
2977 pioh = &first_io_handler;
2978 for(;;) {
2979 ioh = *pioh;
2980 if (ioh == NULL)
2981 break;
2982 if (ioh->fd == fd) {
2983 ioh->deleted = 1;
2984 break;
2986 pioh = &ioh->next;
2988 } else {
2989 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2990 if (ioh->fd == fd)
2991 goto found;
2993 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2994 ioh->next = first_io_handler;
2995 first_io_handler = ioh;
2996 found:
2997 ioh->fd = fd;
2998 ioh->fd_read_poll = fd_read_poll;
2999 ioh->fd_read = fd_read;
3000 ioh->fd_write = fd_write;
3001 ioh->opaque = opaque;
3002 ioh->deleted = 0;
3004 qemu_notify_event();
3005 return 0;
3008 int qemu_set_fd_handler(int fd,
3009 IOHandler *fd_read,
3010 IOHandler *fd_write,
3011 void *opaque)
3013 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3016 #ifdef _WIN32
3017 /***********************************************************/
3018 /* Polling handling */
3020 typedef struct PollingEntry {
3021 PollingFunc *func;
3022 void *opaque;
3023 struct PollingEntry *next;
3024 } PollingEntry;
3026 static PollingEntry *first_polling_entry;
3028 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3030 PollingEntry **ppe, *pe;
3031 pe = qemu_mallocz(sizeof(PollingEntry));
3032 pe->func = func;
3033 pe->opaque = opaque;
3034 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3035 *ppe = pe;
3036 return 0;
3039 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3041 PollingEntry **ppe, *pe;
3042 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3043 pe = *ppe;
3044 if (pe->func == func && pe->opaque == opaque) {
3045 *ppe = pe->next;
3046 qemu_free(pe);
3047 break;
3052 /***********************************************************/
3053 /* Wait objects support */
3054 typedef struct WaitObjects {
3055 int num;
3056 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3057 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3058 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3059 } WaitObjects;
3061 static WaitObjects wait_objects = {0};
3063 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3065 WaitObjects *w = &wait_objects;
3067 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3068 return -1;
3069 w->events[w->num] = handle;
3070 w->func[w->num] = func;
3071 w->opaque[w->num] = opaque;
3072 w->num++;
3073 return 0;
3076 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3078 int i, found;
3079 WaitObjects *w = &wait_objects;
3081 found = 0;
3082 for (i = 0; i < w->num; i++) {
3083 if (w->events[i] == handle)
3084 found = 1;
3085 if (found) {
3086 w->events[i] = w->events[i + 1];
3087 w->func[i] = w->func[i + 1];
3088 w->opaque[i] = w->opaque[i + 1];
3091 if (found)
3092 w->num--;
3094 #endif
3096 /***********************************************************/
3097 /* ram save/restore */
3099 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3101 int v;
3103 v = qemu_get_byte(f);
3104 switch(v) {
3105 case 0:
3106 if (qemu_get_buffer(f, buf, len) != len)
3107 return -EIO;
3108 break;
3109 case 1:
3110 v = qemu_get_byte(f);
3111 memset(buf, v, len);
3112 break;
3113 default:
3114 return -EINVAL;
3117 if (qemu_file_has_error(f))
3118 return -EIO;
3120 return 0;
3123 static int ram_load_v1(QEMUFile *f, void *opaque)
3125 int ret;
3126 ram_addr_t i;
3128 if (qemu_get_be32(f) != last_ram_offset)
3129 return -EINVAL;
3130 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3131 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3132 continue;
3133 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3134 if (ret)
3135 return ret;
3137 return 0;
3140 #define BDRV_HASH_BLOCK_SIZE 1024
3141 #define IOBUF_SIZE 4096
3142 #define RAM_CBLOCK_MAGIC 0xfabe
3144 typedef struct RamDecompressState {
3145 z_stream zstream;
3146 QEMUFile *f;
3147 uint8_t buf[IOBUF_SIZE];
3148 } RamDecompressState;
3150 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3152 int ret;
3153 memset(s, 0, sizeof(*s));
3154 s->f = f;
3155 ret = inflateInit(&s->zstream);
3156 if (ret != Z_OK)
3157 return -1;
3158 return 0;
3161 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3163 int ret, clen;
3165 s->zstream.avail_out = len;
3166 s->zstream.next_out = buf;
3167 while (s->zstream.avail_out > 0) {
3168 if (s->zstream.avail_in == 0) {
3169 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3170 return -1;
3171 clen = qemu_get_be16(s->f);
3172 if (clen > IOBUF_SIZE)
3173 return -1;
3174 qemu_get_buffer(s->f, s->buf, clen);
3175 s->zstream.avail_in = clen;
3176 s->zstream.next_in = s->buf;
3178 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3179 if (ret != Z_OK && ret != Z_STREAM_END) {
3180 return -1;
3183 return 0;
3186 static void ram_decompress_close(RamDecompressState *s)
3188 inflateEnd(&s->zstream);
3191 #define RAM_SAVE_FLAG_FULL 0x01
3192 #define RAM_SAVE_FLAG_COMPRESS 0x02
3193 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3194 #define RAM_SAVE_FLAG_PAGE 0x08
3195 #define RAM_SAVE_FLAG_EOS 0x10
3197 static int is_dup_page(uint8_t *page, uint8_t ch)
3199 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3200 uint32_t *array = (uint32_t *)page;
3201 int i;
3203 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3204 if (array[i] != val)
3205 return 0;
3208 return 1;
3211 static int ram_save_block(QEMUFile *f)
3213 static ram_addr_t current_addr = 0;
3214 ram_addr_t saved_addr = current_addr;
3215 ram_addr_t addr = 0;
3216 int found = 0;
3218 while (addr < last_ram_offset) {
3219 if (kvm_enabled() && current_addr == 0) {
3220 int r;
3221 r = kvm_update_dirty_pages_log();
3222 if (r) {
3223 fprintf(stderr, "%s: update dirty pages log failed %d\n", __FUNCTION__, r);
3224 qemu_file_set_error(f);
3225 return 0;
3228 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3229 uint8_t *p;
3231 cpu_physical_memory_reset_dirty(current_addr,
3232 current_addr + TARGET_PAGE_SIZE,
3233 MIGRATION_DIRTY_FLAG);
3235 p = qemu_get_ram_ptr(current_addr);
3237 if (is_dup_page(p, *p)) {
3238 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3239 qemu_put_byte(f, *p);
3240 } else {
3241 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3242 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3245 found = 1;
3246 break;
3248 addr += TARGET_PAGE_SIZE;
3249 current_addr = (saved_addr + addr) % last_ram_offset;
3252 return found;
3255 static ram_addr_t ram_save_threshold = 10;
3256 static uint64_t bytes_transferred = 0;
3258 static ram_addr_t ram_save_remaining(void)
3260 ram_addr_t addr;
3261 ram_addr_t count = 0;
3263 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3264 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3265 count++;
3268 return count;
3271 uint64_t ram_bytes_remaining(void)
3273 return ram_save_remaining() * TARGET_PAGE_SIZE;
3276 uint64_t ram_bytes_transferred(void)
3278 return bytes_transferred;
3281 uint64_t ram_bytes_total(void)
3283 return last_ram_offset;
3286 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3288 ram_addr_t addr;
3290 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3291 qemu_file_set_error(f);
3292 return 0;
3295 if (stage == 1) {
3296 /* Make sure all dirty bits are set */
3297 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3298 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3299 cpu_physical_memory_set_dirty(addr);
3302 /* Enable dirty memory tracking */
3303 cpu_physical_memory_set_dirty_tracking(1);
3305 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3308 while (!qemu_file_rate_limit(f)) {
3309 int ret;
3311 ret = ram_save_block(f);
3312 bytes_transferred += ret * TARGET_PAGE_SIZE;
3313 if (ret == 0) /* no more blocks */
3314 break;
3317 /* try transferring iterative blocks of memory */
3319 if (stage == 3) {
3321 /* flush all remaining blocks regardless of rate limiting */
3322 while (ram_save_block(f) != 0) {
3323 bytes_transferred += TARGET_PAGE_SIZE;
3325 cpu_physical_memory_set_dirty_tracking(0);
3328 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3330 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3333 static int ram_load_dead(QEMUFile *f, void *opaque)
3335 RamDecompressState s1, *s = &s1;
3336 uint8_t buf[10];
3337 ram_addr_t i;
3339 if (ram_decompress_open(s, f) < 0)
3340 return -EINVAL;
3341 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3342 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3343 continue;
3344 if (ram_decompress_buf(s, buf, 1) < 0) {
3345 fprintf(stderr, "Error while reading ram block header\n");
3346 goto error;
3348 if (buf[0] == 0) {
3349 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3350 BDRV_HASH_BLOCK_SIZE) < 0) {
3351 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3352 goto error;
3354 } else {
3355 error:
3356 printf("Error block header\n");
3357 return -EINVAL;
3360 ram_decompress_close(s);
3362 return 0;
3365 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3367 ram_addr_t addr;
3368 int flags;
3370 if (version_id == 1)
3371 return ram_load_v1(f, opaque);
3373 if (version_id == 2) {
3374 if (qemu_get_be32(f) != last_ram_offset)
3375 return -EINVAL;
3376 return ram_load_dead(f, opaque);
3379 if (version_id != 3)
3380 return -EINVAL;
3382 do {
3383 addr = qemu_get_be64(f);
3385 flags = addr & ~TARGET_PAGE_MASK;
3386 addr &= TARGET_PAGE_MASK;
3388 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3389 if (addr != last_ram_offset)
3390 return -EINVAL;
3393 if (flags & RAM_SAVE_FLAG_FULL) {
3394 if (ram_load_dead(f, opaque) < 0)
3395 return -EINVAL;
3398 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3399 uint8_t ch = qemu_get_byte(f);
3400 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3401 } else if (flags & RAM_SAVE_FLAG_PAGE)
3402 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3403 } while (!(flags & RAM_SAVE_FLAG_EOS));
3405 return 0;
3408 void qemu_service_io(void)
3410 qemu_notify_event();
3413 /***********************************************************/
3414 /* bottom halves (can be seen as timers which expire ASAP) */
3416 struct QEMUBH {
3417 QEMUBHFunc *cb;
3418 void *opaque;
3419 int scheduled;
3420 int idle;
3421 int deleted;
3422 QEMUBH *next;
3425 static QEMUBH *first_bh = NULL;
3427 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3429 QEMUBH *bh;
3430 bh = qemu_mallocz(sizeof(QEMUBH));
3431 bh->cb = cb;
3432 bh->opaque = opaque;
3433 bh->next = first_bh;
3434 first_bh = bh;
3435 return bh;
3438 int qemu_bh_poll(void)
3440 QEMUBH *bh, **bhp;
3441 int ret;
3443 ret = 0;
3444 for (bh = first_bh; bh; bh = bh->next) {
3445 if (!bh->deleted && bh->scheduled) {
3446 bh->scheduled = 0;
3447 if (!bh->idle)
3448 ret = 1;
3449 bh->idle = 0;
3450 bh->cb(bh->opaque);
3454 /* remove deleted bhs */
3455 bhp = &first_bh;
3456 while (*bhp) {
3457 bh = *bhp;
3458 if (bh->deleted) {
3459 *bhp = bh->next;
3460 qemu_free(bh);
3461 } else
3462 bhp = &bh->next;
3465 return ret;
3468 void qemu_bh_schedule_idle(QEMUBH *bh)
3470 if (bh->scheduled)
3471 return;
3472 bh->scheduled = 1;
3473 bh->idle = 1;
3476 void qemu_bh_schedule(QEMUBH *bh)
3478 if (bh->scheduled)
3479 return;
3480 bh->scheduled = 1;
3481 bh->idle = 0;
3482 /* stop the currently executing CPU to execute the BH ASAP */
3483 qemu_notify_event();
3486 void qemu_bh_cancel(QEMUBH *bh)
3488 bh->scheduled = 0;
3491 void qemu_bh_delete(QEMUBH *bh)
3493 bh->scheduled = 0;
3494 bh->deleted = 1;
3497 static void qemu_bh_update_timeout(int *timeout)
3499 QEMUBH *bh;
3501 for (bh = first_bh; bh; bh = bh->next) {
3502 if (!bh->deleted && bh->scheduled) {
3503 if (bh->idle) {
3504 /* idle bottom halves will be polled at least
3505 * every 10ms */
3506 *timeout = MIN(10, *timeout);
3507 } else {
3508 /* non-idle bottom halves will be executed
3509 * immediately */
3510 *timeout = 0;
3511 break;
3517 /***********************************************************/
3518 /* machine registration */
3520 static QEMUMachine *first_machine = NULL;
3521 QEMUMachine *current_machine = NULL;
3523 int qemu_register_machine(QEMUMachine *m)
3525 QEMUMachine **pm;
3526 pm = &first_machine;
3527 while (*pm != NULL)
3528 pm = &(*pm)->next;
3529 m->next = NULL;
3530 *pm = m;
3531 return 0;
3534 static QEMUMachine *find_machine(const char *name)
3536 QEMUMachine *m;
3538 for(m = first_machine; m != NULL; m = m->next) {
3539 if (!strcmp(m->name, name))
3540 return m;
3542 return NULL;
3545 static QEMUMachine *find_default_machine(void)
3547 QEMUMachine *m;
3549 for(m = first_machine; m != NULL; m = m->next) {
3550 if (m->is_default) {
3551 return m;
3554 return NULL;
3557 /***********************************************************/
3558 /* main execution loop */
3560 static void gui_update(void *opaque)
3562 uint64_t interval = GUI_REFRESH_INTERVAL;
3563 DisplayState *ds = opaque;
3564 DisplayChangeListener *dcl = ds->listeners;
3566 dpy_refresh(ds);
3568 while (dcl != NULL) {
3569 if (dcl->gui_timer_interval &&
3570 dcl->gui_timer_interval < interval)
3571 interval = dcl->gui_timer_interval;
3572 dcl = dcl->next;
3574 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3577 static void nographic_update(void *opaque)
3579 uint64_t interval = GUI_REFRESH_INTERVAL;
3581 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3584 struct vm_change_state_entry {
3585 VMChangeStateHandler *cb;
3586 void *opaque;
3587 LIST_ENTRY (vm_change_state_entry) entries;
3590 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3592 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3593 void *opaque)
3595 VMChangeStateEntry *e;
3597 e = qemu_mallocz(sizeof (*e));
3599 e->cb = cb;
3600 e->opaque = opaque;
3601 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3602 return e;
3605 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3607 LIST_REMOVE (e, entries);
3608 qemu_free (e);
3611 static void vm_state_notify(int running, int reason)
3613 VMChangeStateEntry *e;
3615 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3616 e->cb(e->opaque, running, reason);
3620 static void resume_all_vcpus(void);
3621 static void pause_all_vcpus(void);
3623 void vm_start(void)
3625 if (!vm_running) {
3626 cpu_enable_ticks();
3627 vm_running = 1;
3628 vm_state_notify(1, 0);
3629 qemu_rearm_alarm_timer(alarm_timer);
3630 resume_all_vcpus();
3634 /* reset/shutdown handler */
3636 typedef struct QEMUResetEntry {
3637 QEMUResetHandler *func;
3638 void *opaque;
3639 int order;
3640 struct QEMUResetEntry *next;
3641 } QEMUResetEntry;
3643 static QEMUResetEntry *first_reset_entry;
3644 static int reset_requested;
3645 static int shutdown_requested;
3646 static int powerdown_requested;
3647 static int debug_requested;
3648 static int vmstop_requested;
3650 int qemu_no_shutdown(void)
3652 int r = no_shutdown;
3653 no_shutdown = 0;
3654 return r;
3657 int qemu_shutdown_requested(void)
3659 int r = shutdown_requested;
3660 shutdown_requested = 0;
3661 return r;
3664 int qemu_reset_requested(void)
3666 int r = reset_requested;
3667 reset_requested = 0;
3668 return r;
3671 int qemu_powerdown_requested(void)
3673 int r = powerdown_requested;
3674 powerdown_requested = 0;
3675 return r;
3678 static int qemu_debug_requested(void)
3680 int r = debug_requested;
3681 debug_requested = 0;
3682 return r;
3685 static int qemu_vmstop_requested(void)
3687 int r = vmstop_requested;
3688 vmstop_requested = 0;
3689 return r;
3692 static void do_vm_stop(int reason)
3694 if (vm_running) {
3695 cpu_disable_ticks();
3696 vm_running = 0;
3697 pause_all_vcpus();
3698 vm_state_notify(0, reason);
3702 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
3704 QEMUResetEntry **pre, *re;
3706 pre = &first_reset_entry;
3707 while (*pre != NULL && (*pre)->order >= order) {
3708 pre = &(*pre)->next;
3710 re = qemu_mallocz(sizeof(QEMUResetEntry));
3711 re->func = func;
3712 re->opaque = opaque;
3713 re->order = order;
3714 re->next = NULL;
3715 *pre = re;
3718 void qemu_system_reset(void)
3720 QEMUResetEntry *re;
3722 /* reset all devices */
3723 for(re = first_reset_entry; re != NULL; re = re->next) {
3724 re->func(re->opaque);
3728 void qemu_system_reset_request(void)
3730 if (no_reboot) {
3731 shutdown_requested = 1;
3732 } else {
3733 reset_requested = 1;
3735 if (cpu_single_env) {
3736 qemu_kvm_cpu_stop(cpu_single_env);
3737 cpu_exit(cpu_single_env);
3739 qemu_notify_event();
3742 void qemu_system_shutdown_request(void)
3744 shutdown_requested = 1;
3745 qemu_notify_event();
3748 void qemu_system_powerdown_request(void)
3750 powerdown_requested = 1;
3751 qemu_notify_event();
3754 #ifdef CONFIG_IOTHREAD
3755 static void qemu_system_vmstop_request(int reason)
3757 vmstop_requested = reason;
3758 qemu_notify_event();
3760 #endif
3762 #ifndef _WIN32
3763 static int io_thread_fd = -1;
3765 static void qemu_event_increment(void)
3767 static const char byte = 0;
3769 if (io_thread_fd == -1)
3770 return;
3772 write(io_thread_fd, &byte, sizeof(byte));
3775 static void qemu_event_read(void *opaque)
3777 int fd = (unsigned long)opaque;
3778 ssize_t len;
3780 /* Drain the notify pipe */
3781 do {
3782 char buffer[512];
3783 len = read(fd, buffer, sizeof(buffer));
3784 } while ((len == -1 && errno == EINTR) || len > 0);
3787 static int qemu_event_init(void)
3789 int err;
3790 int fds[2];
3792 err = pipe(fds);
3793 if (err == -1)
3794 return -errno;
3796 err = fcntl_setfl(fds[0], O_NONBLOCK);
3797 if (err < 0)
3798 goto fail;
3800 err = fcntl_setfl(fds[1], O_NONBLOCK);
3801 if (err < 0)
3802 goto fail;
3804 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3805 (void *)(unsigned long)fds[0]);
3807 io_thread_fd = fds[1];
3808 return 0;
3810 fail:
3811 close(fds[0]);
3812 close(fds[1]);
3813 return err;
3815 #else
3816 HANDLE qemu_event_handle;
3818 static void dummy_event_handler(void *opaque)
3822 static int qemu_event_init(void)
3824 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3825 if (!qemu_event_handle) {
3826 perror("Failed CreateEvent");
3827 return -1;
3829 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3830 return 0;
3833 static void qemu_event_increment(void)
3835 SetEvent(qemu_event_handle);
3837 #endif
3839 static int cpu_can_run(CPUState *env)
3841 if (env->stop)
3842 return 0;
3843 if (env->stopped)
3844 return 0;
3845 return 1;
3848 #ifndef CONFIG_IOTHREAD
3849 static int qemu_init_main_loop(void)
3851 return qemu_event_init();
3854 void qemu_init_vcpu(void *_env)
3856 CPUState *env = _env;
3858 if (kvm_enabled())
3859 kvm_init_vcpu(env);
3860 return;
3863 int qemu_cpu_self(void *env)
3865 return 1;
3868 static void resume_all_vcpus(void)
3872 static void pause_all_vcpus(void)
3876 void qemu_cpu_kick(void *env)
3878 return;
3881 void qemu_notify_event(void)
3883 CPUState *env = cpu_single_env;
3885 if (kvm_enabled()) {
3886 qemu_kvm_notify_work();
3887 return;
3889 if (env) {
3890 cpu_exit(env);
3891 #ifdef USE_KQEMU
3892 if (env->kqemu_enabled)
3893 kqemu_cpu_interrupt(env);
3894 #endif
3898 #define qemu_mutex_lock_iothread() do { } while (0)
3899 #define qemu_mutex_unlock_iothread() do { } while (0)
3901 void vm_stop(int reason)
3903 do_vm_stop(reason);
3906 #else /* CONFIG_IOTHREAD */
3908 #include "qemu-thread.h"
3910 QemuMutex qemu_global_mutex;
3911 static QemuMutex qemu_fair_mutex;
3913 static QemuThread io_thread;
3915 static QemuThread *tcg_cpu_thread;
3916 static QemuCond *tcg_halt_cond;
3918 static int qemu_system_ready;
3919 /* cpu creation */
3920 static QemuCond qemu_cpu_cond;
3921 /* system init */
3922 static QemuCond qemu_system_cond;
3923 static QemuCond qemu_pause_cond;
3925 static void block_io_signals(void);
3926 static void unblock_io_signals(void);
3927 static int tcg_has_work(void);
3929 static int qemu_init_main_loop(void)
3931 int ret;
3933 ret = qemu_event_init();
3934 if (ret)
3935 return ret;
3937 qemu_cond_init(&qemu_pause_cond);
3938 qemu_mutex_init(&qemu_fair_mutex);
3939 qemu_mutex_init(&qemu_global_mutex);
3940 qemu_mutex_lock(&qemu_global_mutex);
3942 unblock_io_signals();
3943 qemu_thread_self(&io_thread);
3945 return 0;
3948 static void qemu_wait_io_event(CPUState *env)
3950 while (!tcg_has_work())
3951 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3953 qemu_mutex_unlock(&qemu_global_mutex);
3956 * Users of qemu_global_mutex can be starved, having no chance
3957 * to acquire it since this path will get to it first.
3958 * So use another lock to provide fairness.
3960 qemu_mutex_lock(&qemu_fair_mutex);
3961 qemu_mutex_unlock(&qemu_fair_mutex);
3963 qemu_mutex_lock(&qemu_global_mutex);
3964 if (env->stop) {
3965 env->stop = 0;
3966 env->stopped = 1;
3967 qemu_cond_signal(&qemu_pause_cond);
3971 static int qemu_cpu_exec(CPUState *env);
3973 static void *kvm_cpu_thread_fn(void *arg)
3975 CPUState *env = arg;
3977 block_io_signals();
3978 qemu_thread_self(env->thread);
3980 /* signal CPU creation */
3981 qemu_mutex_lock(&qemu_global_mutex);
3982 env->created = 1;
3983 qemu_cond_signal(&qemu_cpu_cond);
3985 /* and wait for machine initialization */
3986 while (!qemu_system_ready)
3987 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3989 while (1) {
3990 if (cpu_can_run(env))
3991 qemu_cpu_exec(env);
3992 qemu_wait_io_event(env);
3995 return NULL;
3998 static void tcg_cpu_exec(void);
4000 static void *tcg_cpu_thread_fn(void *arg)
4002 CPUState *env = arg;
4004 block_io_signals();
4005 qemu_thread_self(env->thread);
4007 /* signal CPU creation */
4008 qemu_mutex_lock(&qemu_global_mutex);
4009 for (env = first_cpu; env != NULL; env = env->next_cpu)
4010 env->created = 1;
4011 qemu_cond_signal(&qemu_cpu_cond);
4013 /* and wait for machine initialization */
4014 while (!qemu_system_ready)
4015 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
4017 while (1) {
4018 tcg_cpu_exec();
4019 qemu_wait_io_event(cur_cpu);
4022 return NULL;
4025 void qemu_cpu_kick(void *_env)
4027 CPUState *env = _env;
4028 qemu_cond_broadcast(env->halt_cond);
4029 if (kvm_enabled())
4030 qemu_thread_signal(env->thread, SIGUSR1);
4033 int qemu_cpu_self(void *env)
4035 return (cpu_single_env != NULL);
4038 static void cpu_signal(int sig)
4040 if (cpu_single_env)
4041 cpu_exit(cpu_single_env);
4044 static void block_io_signals(void)
4046 sigset_t set;
4047 struct sigaction sigact;
4049 sigemptyset(&set);
4050 sigaddset(&set, SIGUSR2);
4051 sigaddset(&set, SIGIO);
4052 sigaddset(&set, SIGALRM);
4053 pthread_sigmask(SIG_BLOCK, &set, NULL);
4055 sigemptyset(&set);
4056 sigaddset(&set, SIGUSR1);
4057 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4059 memset(&sigact, 0, sizeof(sigact));
4060 sigact.sa_handler = cpu_signal;
4061 sigaction(SIGUSR1, &sigact, NULL);
4064 static void unblock_io_signals(void)
4066 sigset_t set;
4068 sigemptyset(&set);
4069 sigaddset(&set, SIGUSR2);
4070 sigaddset(&set, SIGIO);
4071 sigaddset(&set, SIGALRM);
4072 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4074 sigemptyset(&set);
4075 sigaddset(&set, SIGUSR1);
4076 pthread_sigmask(SIG_BLOCK, &set, NULL);
4079 static void qemu_signal_lock(unsigned int msecs)
4081 qemu_mutex_lock(&qemu_fair_mutex);
4083 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4084 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4085 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4086 break;
4088 qemu_mutex_unlock(&qemu_fair_mutex);
4091 static void qemu_mutex_lock_iothread(void)
4093 if (kvm_enabled()) {
4094 qemu_mutex_lock(&qemu_fair_mutex);
4095 qemu_mutex_lock(&qemu_global_mutex);
4096 qemu_mutex_unlock(&qemu_fair_mutex);
4097 } else
4098 qemu_signal_lock(100);
4101 static void qemu_mutex_unlock_iothread(void)
4103 qemu_mutex_unlock(&qemu_global_mutex);
4106 static int all_vcpus_paused(void)
4108 CPUState *penv = first_cpu;
4110 while (penv) {
4111 if (!penv->stopped)
4112 return 0;
4113 penv = (CPUState *)penv->next_cpu;
4116 return 1;
4119 static void pause_all_vcpus(void)
4121 CPUState *penv = first_cpu;
4123 while (penv) {
4124 penv->stop = 1;
4125 qemu_thread_signal(penv->thread, SIGUSR1);
4126 qemu_cpu_kick(penv);
4127 penv = (CPUState *)penv->next_cpu;
4130 while (!all_vcpus_paused()) {
4131 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4132 penv = first_cpu;
4133 while (penv) {
4134 qemu_thread_signal(penv->thread, SIGUSR1);
4135 penv = (CPUState *)penv->next_cpu;
4140 static void resume_all_vcpus(void)
4142 CPUState *penv = first_cpu;
4144 while (penv) {
4145 penv->stop = 0;
4146 penv->stopped = 0;
4147 qemu_thread_signal(penv->thread, SIGUSR1);
4148 qemu_cpu_kick(penv);
4149 penv = (CPUState *)penv->next_cpu;
4153 static void tcg_init_vcpu(void *_env)
4155 CPUState *env = _env;
4156 /* share a single thread for all cpus with TCG */
4157 if (!tcg_cpu_thread) {
4158 env->thread = qemu_mallocz(sizeof(QemuThread));
4159 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4160 qemu_cond_init(env->halt_cond);
4161 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4162 while (env->created == 0)
4163 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4164 tcg_cpu_thread = env->thread;
4165 tcg_halt_cond = env->halt_cond;
4166 } else {
4167 env->thread = tcg_cpu_thread;
4168 env->halt_cond = tcg_halt_cond;
4172 static void kvm_start_vcpu(CPUState *env)
4174 kvm_init_vcpu(env);
4175 env->thread = qemu_mallocz(sizeof(QemuThread));
4176 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4177 qemu_cond_init(env->halt_cond);
4178 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4179 while (env->created == 0)
4180 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4183 void qemu_init_vcpu(void *_env)
4185 CPUState *env = _env;
4187 if (kvm_enabled())
4188 kvm_start_vcpu(env);
4189 else
4190 tcg_init_vcpu(env);
4193 void qemu_notify_event(void)
4195 qemu_event_increment();
4198 void vm_stop(int reason)
4200 QemuThread me;
4201 qemu_thread_self(&me);
4203 if (!qemu_thread_equal(&me, &io_thread)) {
4204 qemu_system_vmstop_request(reason);
4206 * FIXME: should not return to device code in case
4207 * vm_stop() has been requested.
4209 if (cpu_single_env) {
4210 cpu_exit(cpu_single_env);
4211 cpu_single_env->stop = 1;
4213 return;
4215 do_vm_stop(reason);
4218 #endif
4221 #ifdef _WIN32
4222 static void host_main_loop_wait(int *timeout)
4224 int ret, ret2, i;
4225 PollingEntry *pe;
4228 /* XXX: need to suppress polling by better using win32 events */
4229 ret = 0;
4230 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4231 ret |= pe->func(pe->opaque);
4233 if (ret == 0) {
4234 int err;
4235 WaitObjects *w = &wait_objects;
4237 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4238 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4239 if (w->func[ret - WAIT_OBJECT_0])
4240 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4242 /* Check for additional signaled events */
4243 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4245 /* Check if event is signaled */
4246 ret2 = WaitForSingleObject(w->events[i], 0);
4247 if(ret2 == WAIT_OBJECT_0) {
4248 if (w->func[i])
4249 w->func[i](w->opaque[i]);
4250 } else if (ret2 == WAIT_TIMEOUT) {
4251 } else {
4252 err = GetLastError();
4253 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4256 } else if (ret == WAIT_TIMEOUT) {
4257 } else {
4258 err = GetLastError();
4259 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4263 *timeout = 0;
4265 #else
4266 static void host_main_loop_wait(int *timeout)
4269 #endif
4271 void main_loop_wait(int timeout)
4273 IOHandlerRecord *ioh;
4274 fd_set rfds, wfds, xfds;
4275 int ret, nfds;
4276 struct timeval tv;
4278 qemu_bh_update_timeout(&timeout);
4280 host_main_loop_wait(&timeout);
4282 /* poll any events */
4283 /* XXX: separate device handlers from system ones */
4284 nfds = -1;
4285 FD_ZERO(&rfds);
4286 FD_ZERO(&wfds);
4287 FD_ZERO(&xfds);
4288 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4289 if (ioh->deleted)
4290 continue;
4291 if (ioh->fd_read &&
4292 (!ioh->fd_read_poll ||
4293 ioh->fd_read_poll(ioh->opaque) != 0)) {
4294 FD_SET(ioh->fd, &rfds);
4295 if (ioh->fd > nfds)
4296 nfds = ioh->fd;
4298 if (ioh->fd_write) {
4299 FD_SET(ioh->fd, &wfds);
4300 if (ioh->fd > nfds)
4301 nfds = ioh->fd;
4305 tv.tv_sec = timeout / 1000;
4306 tv.tv_usec = (timeout % 1000) * 1000;
4308 #if defined(CONFIG_SLIRP)
4309 if (slirp_is_inited()) {
4310 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4312 #endif
4313 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4314 if (ret > 0) {
4315 IOHandlerRecord **pioh;
4317 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4318 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4319 ioh->fd_read(ioh->opaque);
4320 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
4321 FD_CLR(ioh->fd, &rfds);
4323 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4324 ioh->fd_write(ioh->opaque);
4328 /* remove deleted IO handlers */
4329 pioh = &first_io_handler;
4330 while (*pioh) {
4331 ioh = *pioh;
4332 if (ioh->deleted) {
4333 *pioh = ioh->next;
4334 qemu_free(ioh);
4335 } else
4336 pioh = &ioh->next;
4339 #if defined(CONFIG_SLIRP)
4340 if (slirp_is_inited()) {
4341 if (ret < 0) {
4342 FD_ZERO(&rfds);
4343 FD_ZERO(&wfds);
4344 FD_ZERO(&xfds);
4346 slirp_select_poll(&rfds, &wfds, &xfds);
4348 #endif
4350 /* rearm timer, if not periodic */
4351 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4352 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4353 qemu_rearm_alarm_timer(alarm_timer);
4356 /* vm time timers */
4357 if (vm_running) {
4358 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4359 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4360 qemu_get_clock(vm_clock));
4363 /* real time timers */
4364 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4365 qemu_get_clock(rt_clock));
4367 /* Check bottom-halves last in case any of the earlier events triggered
4368 them. */
4369 qemu_bh_poll();
4373 static int qemu_cpu_exec(CPUState *env)
4375 int ret;
4376 #ifdef CONFIG_PROFILER
4377 int64_t ti;
4378 #endif
4380 #ifdef CONFIG_PROFILER
4381 ti = profile_getclock();
4382 #endif
4383 if (use_icount) {
4384 int64_t count;
4385 int decr;
4386 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4387 env->icount_decr.u16.low = 0;
4388 env->icount_extra = 0;
4389 count = qemu_next_deadline();
4390 count = (count + (1 << icount_time_shift) - 1)
4391 >> icount_time_shift;
4392 qemu_icount += count;
4393 decr = (count > 0xffff) ? 0xffff : count;
4394 count -= decr;
4395 env->icount_decr.u16.low = decr;
4396 env->icount_extra = count;
4398 ret = cpu_exec(env);
4399 #ifdef CONFIG_PROFILER
4400 qemu_time += profile_getclock() - ti;
4401 #endif
4402 if (use_icount) {
4403 /* Fold pending instructions back into the
4404 instruction counter, and clear the interrupt flag. */
4405 qemu_icount -= (env->icount_decr.u16.low
4406 + env->icount_extra);
4407 env->icount_decr.u32 = 0;
4408 env->icount_extra = 0;
4410 return ret;
4413 static void tcg_cpu_exec(void)
4415 int ret = 0;
4417 if (next_cpu == NULL)
4418 next_cpu = first_cpu;
4419 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4420 CPUState *env = cur_cpu = next_cpu;
4422 if (!vm_running)
4423 break;
4424 if (timer_alarm_pending) {
4425 timer_alarm_pending = 0;
4426 break;
4428 if (cpu_can_run(env))
4429 ret = qemu_cpu_exec(env);
4430 if (ret == EXCP_DEBUG) {
4431 gdb_set_stop_cpu(env);
4432 debug_requested = 1;
4433 break;
4438 static int cpu_has_work(CPUState *env)
4440 if (env->stop)
4441 return 1;
4442 if (env->stopped)
4443 return 0;
4444 if (!env->halted)
4445 return 1;
4446 if (qemu_cpu_has_work(env))
4447 return 1;
4448 return 0;
4451 static int tcg_has_work(void)
4453 CPUState *env;
4455 for (env = first_cpu; env != NULL; env = env->next_cpu)
4456 if (cpu_has_work(env))
4457 return 1;
4458 return 0;
4461 static int qemu_calculate_timeout(void)
4463 int timeout;
4465 if (!vm_running)
4466 timeout = 5000;
4467 else if (tcg_has_work())
4468 timeout = 0;
4469 else if (!use_icount)
4470 timeout = 5000;
4471 else {
4472 /* XXX: use timeout computed from timers */
4473 int64_t add;
4474 int64_t delta;
4475 /* Advance virtual time to the next event. */
4476 if (use_icount == 1) {
4477 /* When not using an adaptive execution frequency
4478 we tend to get badly out of sync with real time,
4479 so just delay for a reasonable amount of time. */
4480 delta = 0;
4481 } else {
4482 delta = cpu_get_icount() - cpu_get_clock();
4484 if (delta > 0) {
4485 /* If virtual time is ahead of real time then just
4486 wait for IO. */
4487 timeout = (delta / 1000000) + 1;
4488 } else {
4489 /* Wait for either IO to occur or the next
4490 timer event. */
4491 add = qemu_next_deadline();
4492 /* We advance the timer before checking for IO.
4493 Limit the amount we advance so that early IO
4494 activity won't get the guest too far ahead. */
4495 if (add > 10000000)
4496 add = 10000000;
4497 delta += add;
4498 add = (add + (1 << icount_time_shift) - 1)
4499 >> icount_time_shift;
4500 qemu_icount += add;
4501 timeout = delta / 1000000;
4502 if (timeout < 0)
4503 timeout = 0;
4507 return timeout;
4510 static int vm_can_run(void)
4512 if (powerdown_requested)
4513 return 0;
4514 if (reset_requested)
4515 return 0;
4516 if (shutdown_requested)
4517 return 0;
4518 if (debug_requested)
4519 return 0;
4520 return 1;
4523 static void main_loop(void)
4525 int r;
4527 if (kvm_enabled()) {
4528 kvm_main_loop();
4529 cpu_disable_ticks();
4530 return;
4533 #ifdef CONFIG_IOTHREAD
4534 qemu_system_ready = 1;
4535 qemu_cond_broadcast(&qemu_system_cond);
4536 #endif
4538 for (;;) {
4539 do {
4540 #ifdef CONFIG_PROFILER
4541 int64_t ti;
4542 #endif
4543 #ifndef CONFIG_IOTHREAD
4544 tcg_cpu_exec();
4545 #endif
4546 #ifdef CONFIG_PROFILER
4547 ti = profile_getclock();
4548 #endif
4549 #ifdef CONFIG_IOTHREAD
4550 main_loop_wait(1000);
4551 #else
4552 main_loop_wait(qemu_calculate_timeout());
4553 #endif
4554 #ifdef CONFIG_PROFILER
4555 dev_time += profile_getclock() - ti;
4556 #endif
4557 } while (vm_can_run());
4559 if (qemu_debug_requested())
4560 vm_stop(EXCP_DEBUG);
4561 if (qemu_shutdown_requested()) {
4562 if (no_shutdown) {
4563 vm_stop(0);
4564 no_shutdown = 0;
4565 } else
4566 break;
4568 if (qemu_reset_requested()) {
4569 pause_all_vcpus();
4570 qemu_system_reset();
4571 resume_all_vcpus();
4573 if (qemu_powerdown_requested())
4574 qemu_system_powerdown();
4575 if ((r = qemu_vmstop_requested()))
4576 vm_stop(r);
4578 pause_all_vcpus();
4581 static void version(void)
4583 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4586 static void help(int exitcode)
4588 version();
4589 printf("usage: %s [options] [disk_image]\n"
4590 "\n"
4591 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4592 "\n"
4593 #define DEF(option, opt_arg, opt_enum, opt_help) \
4594 opt_help
4595 #define DEFHEADING(text) stringify(text) "\n"
4596 #include "qemu-options.h"
4597 #undef DEF
4598 #undef DEFHEADING
4599 #undef GEN_DOCS
4600 "\n"
4601 "During emulation, the following keys are useful:\n"
4602 "ctrl-alt-f toggle full screen\n"
4603 "ctrl-alt-n switch to virtual console 'n'\n"
4604 "ctrl-alt toggle mouse and keyboard grab\n"
4605 "\n"
4606 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4608 "qemu",
4609 DEFAULT_RAM_SIZE,
4610 #ifndef _WIN32
4611 DEFAULT_NETWORK_SCRIPT,
4612 DEFAULT_NETWORK_DOWN_SCRIPT,
4613 #endif
4614 DEFAULT_GDBSTUB_PORT,
4615 "/tmp/qemu.log");
4616 exit(exitcode);
4619 #define HAS_ARG 0x0001
4621 enum {
4622 #define DEF(option, opt_arg, opt_enum, opt_help) \
4623 opt_enum,
4624 #define DEFHEADING(text)
4625 #include "qemu-options.h"
4626 #undef DEF
4627 #undef DEFHEADING
4628 #undef GEN_DOCS
4631 typedef struct QEMUOption {
4632 const char *name;
4633 int flags;
4634 int index;
4635 } QEMUOption;
4637 static const QEMUOption qemu_options[] = {
4638 { "h", 0, QEMU_OPTION_h },
4639 #define DEF(option, opt_arg, opt_enum, opt_help) \
4640 { option, opt_arg, opt_enum },
4641 #define DEFHEADING(text)
4642 #include "qemu-options.h"
4643 #undef DEF
4644 #undef DEFHEADING
4645 #undef GEN_DOCS
4646 { NULL },
4649 #ifdef HAS_AUDIO
4650 struct soundhw soundhw[] = {
4651 #ifdef HAS_AUDIO_CHOICE
4652 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4654 "pcspk",
4655 "PC speaker",
4658 { .init_isa = pcspk_audio_init }
4660 #endif
4662 #ifdef CONFIG_SB16
4664 "sb16",
4665 "Creative Sound Blaster 16",
4668 { .init_isa = SB16_init }
4670 #endif
4672 #ifdef CONFIG_CS4231A
4674 "cs4231a",
4675 "CS4231A",
4678 { .init_isa = cs4231a_init }
4680 #endif
4682 #ifdef CONFIG_ADLIB
4684 "adlib",
4685 #ifdef HAS_YMF262
4686 "Yamaha YMF262 (OPL3)",
4687 #else
4688 "Yamaha YM3812 (OPL2)",
4689 #endif
4692 { .init_isa = Adlib_init }
4694 #endif
4696 #ifdef CONFIG_GUS
4698 "gus",
4699 "Gravis Ultrasound GF1",
4702 { .init_isa = GUS_init }
4704 #endif
4706 #ifdef CONFIG_AC97
4708 "ac97",
4709 "Intel 82801AA AC97 Audio",
4712 { .init_pci = ac97_init }
4714 #endif
4716 #ifdef CONFIG_ES1370
4718 "es1370",
4719 "ENSONIQ AudioPCI ES1370",
4722 { .init_pci = es1370_init }
4724 #endif
4726 #endif /* HAS_AUDIO_CHOICE */
4728 { NULL, NULL, 0, 0, { NULL } }
4731 static void select_soundhw (const char *optarg)
4733 struct soundhw *c;
4735 if (*optarg == '?') {
4736 show_valid_cards:
4738 printf ("Valid sound card names (comma separated):\n");
4739 for (c = soundhw; c->name; ++c) {
4740 printf ("%-11s %s\n", c->name, c->descr);
4742 printf ("\n-soundhw all will enable all of the above\n");
4743 exit (*optarg != '?');
4745 else {
4746 size_t l;
4747 const char *p;
4748 char *e;
4749 int bad_card = 0;
4751 if (!strcmp (optarg, "all")) {
4752 for (c = soundhw; c->name; ++c) {
4753 c->enabled = 1;
4755 return;
4758 p = optarg;
4759 while (*p) {
4760 e = strchr (p, ',');
4761 l = !e ? strlen (p) : (size_t) (e - p);
4763 for (c = soundhw; c->name; ++c) {
4764 if (!strncmp (c->name, p, l)) {
4765 c->enabled = 1;
4766 break;
4770 if (!c->name) {
4771 if (l > 80) {
4772 fprintf (stderr,
4773 "Unknown sound card name (too big to show)\n");
4775 else {
4776 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4777 (int) l, p);
4779 bad_card = 1;
4781 p += l + (e != NULL);
4784 if (bad_card)
4785 goto show_valid_cards;
4788 #endif
4790 static void select_vgahw (const char *p)
4792 const char *opts;
4794 cirrus_vga_enabled = 0;
4795 std_vga_enabled = 0;
4796 vmsvga_enabled = 0;
4797 xenfb_enabled = 0;
4798 if (strstart(p, "std", &opts)) {
4799 std_vga_enabled = 1;
4800 } else if (strstart(p, "cirrus", &opts)) {
4801 cirrus_vga_enabled = 1;
4802 } else if (strstart(p, "vmware", &opts)) {
4803 vmsvga_enabled = 1;
4804 } else if (strstart(p, "xenfb", &opts)) {
4805 xenfb_enabled = 1;
4806 } else if (!strstart(p, "none", &opts)) {
4807 invalid_vga:
4808 fprintf(stderr, "Unknown vga type: %s\n", p);
4809 exit(1);
4811 while (*opts) {
4812 const char *nextopt;
4814 if (strstart(opts, ",retrace=", &nextopt)) {
4815 opts = nextopt;
4816 if (strstart(opts, "dumb", &nextopt))
4817 vga_retrace_method = VGA_RETRACE_DUMB;
4818 else if (strstart(opts, "precise", &nextopt))
4819 vga_retrace_method = VGA_RETRACE_PRECISE;
4820 else goto invalid_vga;
4821 } else goto invalid_vga;
4822 opts = nextopt;
4826 #ifdef _WIN32
4827 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4829 exit(STATUS_CONTROL_C_EXIT);
4830 return TRUE;
4832 #endif
4834 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4836 int ret;
4838 if(strlen(str) != 36)
4839 return -1;
4841 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4842 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4843 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4845 if(ret != 16)
4846 return -1;
4848 #ifdef TARGET_I386
4849 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4850 #endif
4852 return 0;
4855 #define MAX_NET_CLIENTS 32
4857 #ifndef _WIN32
4859 static void termsig_handler(int signal)
4861 qemu_system_shutdown_request();
4864 static void termsig_setup(void)
4866 struct sigaction act;
4868 memset(&act, 0, sizeof(act));
4869 act.sa_handler = termsig_handler;
4870 sigaction(SIGINT, &act, NULL);
4871 sigaction(SIGHUP, &act, NULL);
4872 sigaction(SIGTERM, &act, NULL);
4875 #endif
4877 #ifdef _WIN32
4878 /* Look for support files in the same directory as the executable. */
4879 static char *find_datadir(const char *argv0)
4881 char *p;
4882 char buf[MAX_PATH];
4883 DWORD len;
4885 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4886 if (len == 0) {
4887 return len;
4890 buf[len] = 0;
4891 p = buf + len - 1;
4892 while (p != buf && *p != '\\')
4893 p--;
4894 *p = 0;
4895 if (access(buf, R_OK) == 0) {
4896 return qemu_strdup(buf);
4898 return NULL;
4900 #else /* !_WIN32 */
4902 /* Find a likely location for support files using the location of the binary.
4903 For installed binaries this will be "$bindir/../share/qemu". When
4904 running from the build tree this will be "$bindir/../pc-bios". */
4905 #define SHARE_SUFFIX "/share/qemu"
4906 #define BUILD_SUFFIX "/pc-bios"
4907 static char *find_datadir(const char *argv0)
4909 char *dir;
4910 char *p = NULL;
4911 char *res;
4912 #ifdef PATH_MAX
4913 char buf[PATH_MAX];
4914 #endif
4916 #if defined(__linux__)
4918 int len;
4919 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4920 if (len > 0) {
4921 buf[len] = 0;
4922 p = buf;
4925 #elif defined(__FreeBSD__)
4927 int len;
4928 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4929 if (len > 0) {
4930 buf[len] = 0;
4931 p = buf;
4934 #endif
4935 /* If we don't have any way of figuring out the actual executable
4936 location then try argv[0]. */
4937 if (!p) {
4938 #ifdef PATH_MAX
4939 p = buf;
4940 #endif
4941 p = realpath(argv0, p);
4942 if (!p) {
4943 return NULL;
4946 dir = dirname(p);
4947 dir = dirname(dir);
4949 res = qemu_mallocz(strlen(dir) +
4950 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1);
4951 sprintf(res, "%s%s", dir, SHARE_SUFFIX);
4952 if (access(res, R_OK)) {
4953 sprintf(res, "%s%s", dir, BUILD_SUFFIX);
4954 if (access(res, R_OK)) {
4955 qemu_free(res);
4956 res = NULL;
4959 #ifndef PATH_MAX
4960 free(p);
4961 #endif
4962 return res;
4964 #undef SHARE_SUFFIX
4965 #undef BUILD_SUFFIX
4966 #endif
4968 char *qemu_find_file(int type, const char *name)
4970 int len;
4971 const char *subdir;
4972 char *buf;
4974 /* If name contains path separators then try it as a straight path. */
4975 if ((strchr(name, '/') || strchr(name, '\\'))
4976 && access(name, R_OK) == 0) {
4977 return strdup(name);
4979 switch (type) {
4980 case QEMU_FILE_TYPE_BIOS:
4981 subdir = "";
4982 break;
4983 case QEMU_FILE_TYPE_KEYMAP:
4984 subdir = "keymaps/";
4985 break;
4986 default:
4987 abort();
4989 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4990 buf = qemu_mallocz(len);
4991 sprintf(buf, "%s/%s%s", data_dir, subdir, name);
4992 if (access(buf, R_OK)) {
4993 qemu_free(buf);
4994 return NULL;
4996 return buf;
4999 int main(int argc, char **argv, char **envp)
5001 const char *gdbstub_dev = NULL;
5002 uint32_t boot_devices_bitmap = 0;
5003 int i;
5004 int snapshot, linux_boot, net_boot;
5005 const char *initrd_filename;
5006 const char *kernel_filename, *kernel_cmdline;
5007 const char *boot_devices = "";
5008 DisplayState *ds;
5009 DisplayChangeListener *dcl;
5010 int cyls, heads, secs, translation;
5011 const char *net_clients[MAX_NET_CLIENTS];
5012 int nb_net_clients;
5013 const char *bt_opts[MAX_BT_CMDLINE];
5014 int nb_bt_opts;
5015 int hda_index;
5016 int optind;
5017 const char *r, *optarg;
5018 CharDriverState *monitor_hd = NULL;
5019 const char *monitor_device;
5020 const char *serial_devices[MAX_SERIAL_PORTS];
5021 int serial_device_index;
5022 const char *parallel_devices[MAX_PARALLEL_PORTS];
5023 int parallel_device_index;
5024 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
5025 int virtio_console_index;
5026 const char *loadvm = NULL;
5027 QEMUMachine *machine;
5028 const char *cpu_model;
5029 const char *usb_devices[MAX_USB_CMDLINE];
5030 int usb_devices_index;
5031 #ifndef _WIN32
5032 int fds[2];
5033 #endif
5034 int tb_size;
5035 const char *pid_file = NULL;
5036 const char *incoming = NULL;
5037 #ifndef _WIN32
5038 int fd = 0;
5039 struct passwd *pwd = NULL;
5040 const char *chroot_dir = NULL;
5041 const char *run_as = NULL;
5042 #endif
5043 CPUState *env;
5044 int show_vnc_port = 0;
5046 qemu_cache_utils_init(envp);
5048 LIST_INIT (&vm_change_state_head);
5049 #ifndef _WIN32
5051 struct sigaction act;
5052 sigfillset(&act.sa_mask);
5053 act.sa_flags = 0;
5054 act.sa_handler = SIG_IGN;
5055 sigaction(SIGPIPE, &act, NULL);
5057 #else
5058 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5059 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5060 QEMU to run on a single CPU */
5062 HANDLE h;
5063 DWORD mask, smask;
5064 int i;
5065 h = GetCurrentProcess();
5066 if (GetProcessAffinityMask(h, &mask, &smask)) {
5067 for(i = 0; i < 32; i++) {
5068 if (mask & (1 << i))
5069 break;
5071 if (i != 32) {
5072 mask = 1 << i;
5073 SetProcessAffinityMask(h, mask);
5077 #endif
5079 module_call_init(MODULE_INIT_MACHINE);
5080 machine = find_default_machine();
5081 cpu_model = NULL;
5082 initrd_filename = NULL;
5083 ram_size = 0;
5084 snapshot = 0;
5085 kernel_filename = NULL;
5086 kernel_cmdline = "";
5087 cyls = heads = secs = 0;
5088 translation = BIOS_ATA_TRANSLATION_AUTO;
5089 monitor_device = "vc:80Cx24C";
5091 serial_devices[0] = "vc:80Cx24C";
5092 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5093 serial_devices[i] = NULL;
5094 serial_device_index = 0;
5096 parallel_devices[0] = "vc:80Cx24C";
5097 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5098 parallel_devices[i] = NULL;
5099 parallel_device_index = 0;
5101 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5102 virtio_consoles[i] = NULL;
5103 virtio_console_index = 0;
5105 for (i = 0; i < MAX_NODES; i++) {
5106 node_mem[i] = 0;
5107 node_cpumask[i] = 0;
5110 usb_devices_index = 0;
5111 assigned_devices_index = 0;
5113 nb_net_clients = 0;
5114 nb_bt_opts = 0;
5115 nb_drives = 0;
5116 nb_drives_opt = 0;
5117 nb_numa_nodes = 0;
5118 hda_index = -1;
5120 nb_nics = 0;
5122 tb_size = 0;
5123 autostart= 1;
5125 register_watchdogs();
5127 optind = 1;
5128 for(;;) {
5129 if (optind >= argc)
5130 break;
5131 r = argv[optind];
5132 if (r[0] != '-') {
5133 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5134 } else {
5135 const QEMUOption *popt;
5137 optind++;
5138 /* Treat --foo the same as -foo. */
5139 if (r[1] == '-')
5140 r++;
5141 popt = qemu_options;
5142 for(;;) {
5143 if (!popt->name) {
5144 fprintf(stderr, "%s: invalid option -- '%s'\n",
5145 argv[0], r);
5146 exit(1);
5148 if (!strcmp(popt->name, r + 1))
5149 break;
5150 popt++;
5152 if (popt->flags & HAS_ARG) {
5153 if (optind >= argc) {
5154 fprintf(stderr, "%s: option '%s' requires an argument\n",
5155 argv[0], r);
5156 exit(1);
5158 optarg = argv[optind++];
5159 } else {
5160 optarg = NULL;
5163 switch(popt->index) {
5164 case QEMU_OPTION_M:
5165 machine = find_machine(optarg);
5166 if (!machine) {
5167 QEMUMachine *m;
5168 printf("Supported machines are:\n");
5169 for(m = first_machine; m != NULL; m = m->next) {
5170 printf("%-10s %s%s\n",
5171 m->name, m->desc,
5172 m->is_default ? " (default)" : "");
5174 exit(*optarg != '?');
5176 break;
5177 case QEMU_OPTION_cpu:
5178 /* hw initialization will check this */
5179 if (*optarg == '?') {
5180 /* XXX: implement xxx_cpu_list for targets that still miss it */
5181 #if defined(cpu_list)
5182 cpu_list(stdout, &fprintf);
5183 #endif
5184 exit(0);
5185 } else {
5186 cpu_model = optarg;
5188 break;
5189 case QEMU_OPTION_initrd:
5190 initrd_filename = optarg;
5191 break;
5192 case QEMU_OPTION_hda:
5193 if (cyls == 0)
5194 hda_index = drive_add(optarg, HD_ALIAS, 0);
5195 else
5196 hda_index = drive_add(optarg, HD_ALIAS
5197 ",cyls=%d,heads=%d,secs=%d%s",
5198 0, cyls, heads, secs,
5199 translation == BIOS_ATA_TRANSLATION_LBA ?
5200 ",trans=lba" :
5201 translation == BIOS_ATA_TRANSLATION_NONE ?
5202 ",trans=none" : "");
5203 break;
5204 case QEMU_OPTION_hdb:
5205 case QEMU_OPTION_hdc:
5206 case QEMU_OPTION_hdd:
5207 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5208 break;
5209 case QEMU_OPTION_drive:
5210 drive_add(NULL, "%s", optarg);
5211 break;
5212 case QEMU_OPTION_mtdblock:
5213 drive_add(optarg, MTD_ALIAS);
5214 break;
5215 case QEMU_OPTION_sd:
5216 drive_add(optarg, SD_ALIAS);
5217 break;
5218 case QEMU_OPTION_pflash:
5219 drive_add(optarg, PFLASH_ALIAS);
5220 break;
5221 case QEMU_OPTION_snapshot:
5222 snapshot = 1;
5223 break;
5224 case QEMU_OPTION_hdachs:
5226 const char *p;
5227 p = optarg;
5228 cyls = strtol(p, (char **)&p, 0);
5229 if (cyls < 1 || cyls > 16383)
5230 goto chs_fail;
5231 if (*p != ',')
5232 goto chs_fail;
5233 p++;
5234 heads = strtol(p, (char **)&p, 0);
5235 if (heads < 1 || heads > 16)
5236 goto chs_fail;
5237 if (*p != ',')
5238 goto chs_fail;
5239 p++;
5240 secs = strtol(p, (char **)&p, 0);
5241 if (secs < 1 || secs > 63)
5242 goto chs_fail;
5243 if (*p == ',') {
5244 p++;
5245 if (!strcmp(p, "none"))
5246 translation = BIOS_ATA_TRANSLATION_NONE;
5247 else if (!strcmp(p, "lba"))
5248 translation = BIOS_ATA_TRANSLATION_LBA;
5249 else if (!strcmp(p, "auto"))
5250 translation = BIOS_ATA_TRANSLATION_AUTO;
5251 else
5252 goto chs_fail;
5253 } else if (*p != '\0') {
5254 chs_fail:
5255 fprintf(stderr, "qemu: invalid physical CHS format\n");
5256 exit(1);
5258 if (hda_index != -1)
5259 snprintf(drives_opt[hda_index].opt,
5260 sizeof(drives_opt[hda_index].opt),
5261 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5262 0, cyls, heads, secs,
5263 translation == BIOS_ATA_TRANSLATION_LBA ?
5264 ",trans=lba" :
5265 translation == BIOS_ATA_TRANSLATION_NONE ?
5266 ",trans=none" : "");
5268 break;
5269 case QEMU_OPTION_numa:
5270 if (nb_numa_nodes >= MAX_NODES) {
5271 fprintf(stderr, "qemu: too many NUMA nodes\n");
5272 exit(1);
5274 numa_add(optarg);
5275 break;
5276 case QEMU_OPTION_nographic:
5277 display_type = DT_NOGRAPHIC;
5278 break;
5279 #ifdef CONFIG_CURSES
5280 case QEMU_OPTION_curses:
5281 display_type = DT_CURSES;
5282 break;
5283 #endif
5284 case QEMU_OPTION_portrait:
5285 graphic_rotate = 1;
5286 break;
5287 case QEMU_OPTION_kernel:
5288 kernel_filename = optarg;
5289 break;
5290 case QEMU_OPTION_append:
5291 kernel_cmdline = optarg;
5292 break;
5293 case QEMU_OPTION_cdrom:
5294 drive_add(optarg, CDROM_ALIAS);
5295 break;
5296 case QEMU_OPTION_boot:
5297 boot_devices = optarg;
5298 /* We just do some generic consistency checks */
5300 /* Could easily be extended to 64 devices if needed */
5301 const char *p;
5303 boot_devices_bitmap = 0;
5304 for (p = boot_devices; *p != '\0'; p++) {
5305 /* Allowed boot devices are:
5306 * a b : floppy disk drives
5307 * c ... f : IDE disk drives
5308 * g ... m : machine implementation dependant drives
5309 * n ... p : network devices
5310 * It's up to each machine implementation to check
5311 * if the given boot devices match the actual hardware
5312 * implementation and firmware features.
5314 if (*p < 'a' || *p > 'q') {
5315 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5316 exit(1);
5318 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5319 fprintf(stderr,
5320 "Boot device '%c' was given twice\n",*p);
5321 exit(1);
5323 boot_devices_bitmap |= 1 << (*p - 'a');
5326 break;
5327 case QEMU_OPTION_fda:
5328 case QEMU_OPTION_fdb:
5329 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5330 break;
5331 #ifdef TARGET_I386
5332 case QEMU_OPTION_no_fd_bootchk:
5333 fd_bootchk = 0;
5334 break;
5335 #endif
5336 case QEMU_OPTION_net:
5337 if (nb_net_clients >= MAX_NET_CLIENTS) {
5338 fprintf(stderr, "qemu: too many network clients\n");
5339 exit(1);
5341 net_clients[nb_net_clients] = optarg;
5342 nb_net_clients++;
5343 break;
5344 #ifdef CONFIG_SLIRP
5345 case QEMU_OPTION_tftp:
5346 tftp_prefix = optarg;
5347 break;
5348 case QEMU_OPTION_bootp:
5349 bootp_filename = optarg;
5350 break;
5351 #ifndef _WIN32
5352 case QEMU_OPTION_smb:
5353 net_slirp_smb(optarg);
5354 break;
5355 #endif
5356 case QEMU_OPTION_redir:
5357 net_slirp_redir(NULL, optarg, NULL);
5358 break;
5359 #endif
5360 case QEMU_OPTION_bt:
5361 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5362 fprintf(stderr, "qemu: too many bluetooth options\n");
5363 exit(1);
5365 bt_opts[nb_bt_opts++] = optarg;
5366 break;
5367 #ifdef HAS_AUDIO
5368 case QEMU_OPTION_audio_help:
5369 AUD_help ();
5370 exit (0);
5371 break;
5372 case QEMU_OPTION_soundhw:
5373 select_soundhw (optarg);
5374 break;
5375 #endif
5376 case QEMU_OPTION_h:
5377 help(0);
5378 break;
5379 case QEMU_OPTION_version:
5380 version();
5381 exit(0);
5382 break;
5383 case QEMU_OPTION_m: {
5384 uint64_t value;
5385 char *ptr;
5387 value = strtoul(optarg, &ptr, 10);
5388 switch (*ptr) {
5389 case 0: case 'M': case 'm':
5390 value <<= 20;
5391 break;
5392 case 'G': case 'g':
5393 value <<= 30;
5394 break;
5395 default:
5396 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5397 exit(1);
5400 /* On 32-bit hosts, QEMU is limited by virtual address space */
5401 if (value > (2047 << 20)
5402 #ifndef CONFIG_KQEMU
5403 && HOST_LONG_BITS == 32
5404 #endif
5406 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5407 exit(1);
5409 if (value != (uint64_t)(ram_addr_t)value) {
5410 fprintf(stderr, "qemu: ram size too large\n");
5411 exit(1);
5413 ram_size = value;
5414 break;
5416 case QEMU_OPTION_d:
5418 int mask;
5419 const CPULogItem *item;
5421 mask = cpu_str_to_log_mask(optarg);
5422 if (!mask) {
5423 printf("Log items (comma separated):\n");
5424 for(item = cpu_log_items; item->mask != 0; item++) {
5425 printf("%-10s %s\n", item->name, item->help);
5427 exit(1);
5429 cpu_set_log(mask);
5431 break;
5432 case QEMU_OPTION_s:
5433 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5434 break;
5435 case QEMU_OPTION_gdb:
5436 gdbstub_dev = optarg;
5437 break;
5438 case QEMU_OPTION_L:
5439 data_dir = optarg;
5440 break;
5441 case QEMU_OPTION_bios:
5442 bios_name = optarg;
5443 break;
5444 case QEMU_OPTION_singlestep:
5445 singlestep = 1;
5446 break;
5447 case QEMU_OPTION_S:
5448 autostart = 0;
5449 break;
5450 #ifndef _WIN32
5451 case QEMU_OPTION_k:
5452 keyboard_layout = optarg;
5453 break;
5454 #endif
5455 case QEMU_OPTION_localtime:
5456 rtc_utc = 0;
5457 break;
5458 case QEMU_OPTION_vga:
5459 select_vgahw (optarg);
5460 break;
5461 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5462 case QEMU_OPTION_g:
5464 const char *p;
5465 int w, h, depth;
5466 p = optarg;
5467 w = strtol(p, (char **)&p, 10);
5468 if (w <= 0) {
5469 graphic_error:
5470 fprintf(stderr, "qemu: invalid resolution or depth\n");
5471 exit(1);
5473 if (*p != 'x')
5474 goto graphic_error;
5475 p++;
5476 h = strtol(p, (char **)&p, 10);
5477 if (h <= 0)
5478 goto graphic_error;
5479 if (*p == 'x') {
5480 p++;
5481 depth = strtol(p, (char **)&p, 10);
5482 if (depth != 8 && depth != 15 && depth != 16 &&
5483 depth != 24 && depth != 32)
5484 goto graphic_error;
5485 } else if (*p == '\0') {
5486 depth = graphic_depth;
5487 } else {
5488 goto graphic_error;
5491 graphic_width = w;
5492 graphic_height = h;
5493 graphic_depth = depth;
5495 break;
5496 #endif
5497 case QEMU_OPTION_echr:
5499 char *r;
5500 term_escape_char = strtol(optarg, &r, 0);
5501 if (r == optarg)
5502 printf("Bad argument to echr\n");
5503 break;
5505 case QEMU_OPTION_monitor:
5506 monitor_device = optarg;
5507 break;
5508 case QEMU_OPTION_serial:
5509 if (serial_device_index >= MAX_SERIAL_PORTS) {
5510 fprintf(stderr, "qemu: too many serial ports\n");
5511 exit(1);
5513 serial_devices[serial_device_index] = optarg;
5514 serial_device_index++;
5515 break;
5516 case QEMU_OPTION_watchdog:
5517 i = select_watchdog(optarg);
5518 if (i > 0)
5519 exit (i == 1 ? 1 : 0);
5520 break;
5521 case QEMU_OPTION_watchdog_action:
5522 if (select_watchdog_action(optarg) == -1) {
5523 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5524 exit(1);
5526 break;
5527 case QEMU_OPTION_virtiocon:
5528 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5529 fprintf(stderr, "qemu: too many virtio consoles\n");
5530 exit(1);
5532 virtio_consoles[virtio_console_index] = optarg;
5533 virtio_console_index++;
5534 break;
5535 case QEMU_OPTION_parallel:
5536 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5537 fprintf(stderr, "qemu: too many parallel ports\n");
5538 exit(1);
5540 parallel_devices[parallel_device_index] = optarg;
5541 parallel_device_index++;
5542 break;
5543 case QEMU_OPTION_loadvm:
5544 loadvm = optarg;
5545 break;
5546 case QEMU_OPTION_full_screen:
5547 full_screen = 1;
5548 break;
5549 #ifdef CONFIG_SDL
5550 case QEMU_OPTION_no_frame:
5551 no_frame = 1;
5552 break;
5553 case QEMU_OPTION_alt_grab:
5554 alt_grab = 1;
5555 break;
5556 case QEMU_OPTION_no_quit:
5557 no_quit = 1;
5558 break;
5559 case QEMU_OPTION_sdl:
5560 display_type = DT_SDL;
5561 break;
5562 #endif
5563 case QEMU_OPTION_pidfile:
5564 pid_file = optarg;
5565 break;
5566 #ifdef TARGET_I386
5567 case QEMU_OPTION_win2k_hack:
5568 win2k_install_hack = 1;
5569 break;
5570 case QEMU_OPTION_rtc_td_hack:
5571 rtc_td_hack = 1;
5572 break;
5573 case QEMU_OPTION_acpitable:
5574 if(acpi_table_add(optarg) < 0) {
5575 fprintf(stderr, "Wrong acpi table provided\n");
5576 exit(1);
5578 break;
5579 case QEMU_OPTION_smbios:
5580 if(smbios_entry_add(optarg) < 0) {
5581 fprintf(stderr, "Wrong smbios provided\n");
5582 exit(1);
5584 break;
5585 #endif
5586 #ifdef CONFIG_KQEMU
5587 case QEMU_OPTION_no_kqemu:
5588 kqemu_allowed = 0;
5589 break;
5590 case QEMU_OPTION_kernel_kqemu:
5591 kqemu_allowed = 2;
5592 break;
5593 #endif
5594 #ifdef CONFIG_KVM
5595 case QEMU_OPTION_enable_kvm:
5596 kvm_allowed = 1;
5597 #ifdef CONFIG_KQEMU
5598 kqemu_allowed = 0;
5599 #endif
5600 break;
5601 #endif
5602 #ifdef USE_KVM
5603 case QEMU_OPTION_no_kvm:
5604 kvm_allowed = 0;
5605 break;
5606 case QEMU_OPTION_no_kvm_irqchip: {
5607 kvm_irqchip = 0;
5608 kvm_pit = 0;
5609 break;
5611 case QEMU_OPTION_no_kvm_pit: {
5612 kvm_pit = 0;
5613 break;
5615 case QEMU_OPTION_no_kvm_pit_reinjection: {
5616 kvm_pit_reinject = 0;
5617 break;
5619 case QEMU_OPTION_enable_nesting: {
5620 kvm_nested = 1;
5621 break;
5623 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5624 case QEMU_OPTION_pcidevice:
5625 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5626 fprintf(stderr, "Too many assigned devices\n");
5627 exit(1);
5629 assigned_devices[assigned_devices_index] = optarg;
5630 assigned_devices_index++;
5631 break;
5632 #endif
5633 #endif
5634 case QEMU_OPTION_usb:
5635 usb_enabled = 1;
5636 break;
5637 case QEMU_OPTION_usbdevice:
5638 usb_enabled = 1;
5639 if (usb_devices_index >= MAX_USB_CMDLINE) {
5640 fprintf(stderr, "Too many USB devices\n");
5641 exit(1);
5643 usb_devices[usb_devices_index] = optarg;
5644 usb_devices_index++;
5645 break;
5646 case QEMU_OPTION_smp:
5647 smp_cpus = atoi(optarg);
5648 if (smp_cpus < 1) {
5649 fprintf(stderr, "Invalid number of CPUs\n");
5650 exit(1);
5652 break;
5653 case QEMU_OPTION_vnc:
5654 display_type = DT_VNC;
5655 vnc_display = optarg;
5656 break;
5657 #ifdef TARGET_I386
5658 case QEMU_OPTION_no_acpi:
5659 acpi_enabled = 0;
5660 break;
5661 case QEMU_OPTION_no_hpet:
5662 no_hpet = 1;
5663 break;
5664 #endif
5665 case QEMU_OPTION_no_reboot:
5666 no_reboot = 1;
5667 break;
5668 case QEMU_OPTION_no_shutdown:
5669 no_shutdown = 1;
5670 break;
5671 case QEMU_OPTION_show_cursor:
5672 cursor_hide = 0;
5673 break;
5674 case QEMU_OPTION_uuid:
5675 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5676 fprintf(stderr, "Fail to parse UUID string."
5677 " Wrong format.\n");
5678 exit(1);
5680 break;
5681 #ifndef _WIN32
5682 case QEMU_OPTION_daemonize:
5683 daemonize = 1;
5684 break;
5685 #endif
5686 case QEMU_OPTION_option_rom:
5687 if (nb_option_roms >= MAX_OPTION_ROMS) {
5688 fprintf(stderr, "Too many option ROMs\n");
5689 exit(1);
5691 option_rom[nb_option_roms] = optarg;
5692 nb_option_roms++;
5693 break;
5694 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5695 case QEMU_OPTION_semihosting:
5696 semihosting_enabled = 1;
5697 break;
5698 #endif
5699 case QEMU_OPTION_tdf:
5700 time_drift_fix = 1;
5701 break;
5702 case QEMU_OPTION_kvm_shadow_memory:
5703 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5704 break;
5705 case QEMU_OPTION_mempath:
5706 mem_path = optarg;
5707 break;
5708 #ifdef MAP_POPULATE
5709 case QEMU_OPTION_mem_prealloc:
5710 mem_prealloc = !mem_prealloc;
5711 break;
5712 #endif
5713 case QEMU_OPTION_name:
5714 qemu_name = optarg;
5715 break;
5716 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5717 case QEMU_OPTION_prom_env:
5718 if (nb_prom_envs >= MAX_PROM_ENVS) {
5719 fprintf(stderr, "Too many prom variables\n");
5720 exit(1);
5722 prom_envs[nb_prom_envs] = optarg;
5723 nb_prom_envs++;
5724 break;
5725 #endif
5726 #ifdef TARGET_ARM
5727 case QEMU_OPTION_old_param:
5728 old_param = 1;
5729 break;
5730 #endif
5731 case QEMU_OPTION_clock:
5732 configure_alarms(optarg);
5733 break;
5734 case QEMU_OPTION_startdate:
5736 struct tm tm;
5737 time_t rtc_start_date;
5738 if (!strcmp(optarg, "now")) {
5739 rtc_date_offset = -1;
5740 } else {
5741 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5742 &tm.tm_year,
5743 &tm.tm_mon,
5744 &tm.tm_mday,
5745 &tm.tm_hour,
5746 &tm.tm_min,
5747 &tm.tm_sec) == 6) {
5748 /* OK */
5749 } else if (sscanf(optarg, "%d-%d-%d",
5750 &tm.tm_year,
5751 &tm.tm_mon,
5752 &tm.tm_mday) == 3) {
5753 tm.tm_hour = 0;
5754 tm.tm_min = 0;
5755 tm.tm_sec = 0;
5756 } else {
5757 goto date_fail;
5759 tm.tm_year -= 1900;
5760 tm.tm_mon--;
5761 rtc_start_date = mktimegm(&tm);
5762 if (rtc_start_date == -1) {
5763 date_fail:
5764 fprintf(stderr, "Invalid date format. Valid format are:\n"
5765 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5766 exit(1);
5768 rtc_date_offset = time(NULL) - rtc_start_date;
5771 break;
5772 case QEMU_OPTION_tb_size:
5773 tb_size = strtol(optarg, NULL, 0);
5774 if (tb_size < 0)
5775 tb_size = 0;
5776 break;
5777 case QEMU_OPTION_icount:
5778 use_icount = 1;
5779 if (strcmp(optarg, "auto") == 0) {
5780 icount_time_shift = -1;
5781 } else {
5782 icount_time_shift = strtol(optarg, NULL, 0);
5784 break;
5785 case QEMU_OPTION_incoming:
5786 incoming = optarg;
5787 break;
5788 #ifndef _WIN32
5789 case QEMU_OPTION_chroot:
5790 chroot_dir = optarg;
5791 break;
5792 case QEMU_OPTION_runas:
5793 run_as = optarg;
5794 break;
5795 case QEMU_OPTION_nvram:
5796 nvram = optarg;
5797 break;
5798 #endif
5799 #ifdef CONFIG_XEN
5800 case QEMU_OPTION_xen_domid:
5801 xen_domid = atoi(optarg);
5802 break;
5803 case QEMU_OPTION_xen_create:
5804 xen_mode = XEN_CREATE;
5805 break;
5806 case QEMU_OPTION_xen_attach:
5807 xen_mode = XEN_ATTACH;
5808 break;
5809 #endif
5814 /* If no data_dir is specified then try to find it relative to the
5815 executable path. */
5816 if (!data_dir) {
5817 data_dir = find_datadir(argv[0]);
5819 /* If all else fails use the install patch specified when building. */
5820 if (!data_dir) {
5821 data_dir = CONFIG_QEMU_SHAREDIR;
5824 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5825 if (kvm_allowed && kqemu_allowed) {
5826 fprintf(stderr,
5827 "You can not enable both KVM and kqemu at the same time\n");
5828 exit(1);
5830 #endif
5832 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5833 if (smp_cpus > machine->max_cpus) {
5834 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5835 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5836 machine->max_cpus);
5837 exit(1);
5840 if (display_type == DT_NOGRAPHIC) {
5841 if (serial_device_index == 0)
5842 serial_devices[0] = "stdio";
5843 if (parallel_device_index == 0)
5844 parallel_devices[0] = "null";
5845 if (strncmp(monitor_device, "vc", 2) == 0)
5846 monitor_device = "stdio";
5849 #ifndef _WIN32
5850 if (daemonize) {
5851 pid_t pid;
5853 if (pipe(fds) == -1)
5854 exit(1);
5856 pid = fork();
5857 if (pid > 0) {
5858 uint8_t status;
5859 ssize_t len;
5861 close(fds[1]);
5863 again:
5864 len = read(fds[0], &status, 1);
5865 if (len == -1 && (errno == EINTR))
5866 goto again;
5868 if (len != 1)
5869 exit(1);
5870 else if (status == 1) {
5871 fprintf(stderr, "Could not acquire pidfile\n");
5872 exit(1);
5873 } else
5874 exit(0);
5875 } else if (pid < 0)
5876 exit(1);
5878 setsid();
5880 pid = fork();
5881 if (pid > 0)
5882 exit(0);
5883 else if (pid < 0)
5884 exit(1);
5886 umask(027);
5888 signal(SIGTSTP, SIG_IGN);
5889 signal(SIGTTOU, SIG_IGN);
5890 signal(SIGTTIN, SIG_IGN);
5893 #ifdef USE_KVM
5894 if (kvm_enabled()) {
5895 if (kvm_qemu_init() < 0) {
5896 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5897 #ifdef NO_CPU_EMULATION
5898 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5899 exit(1);
5900 #endif
5901 kvm_allowed = 0;
5904 #endif
5906 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5907 if (daemonize) {
5908 uint8_t status = 1;
5909 write(fds[1], &status, 1);
5910 } else
5911 fprintf(stderr, "Could not acquire pid file\n");
5912 exit(1);
5914 #endif
5916 #ifdef CONFIG_KQEMU
5917 if (smp_cpus > 1)
5918 kqemu_allowed = 0;
5919 #endif
5920 if (qemu_init_main_loop()) {
5921 fprintf(stderr, "qemu_init_main_loop failed\n");
5922 exit(1);
5924 linux_boot = (kernel_filename != NULL);
5925 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5927 if (!linux_boot && *kernel_cmdline != '\0') {
5928 fprintf(stderr, "-append only allowed with -kernel option\n");
5929 exit(1);
5932 if (!linux_boot && initrd_filename != NULL) {
5933 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5934 exit(1);
5937 /* boot to floppy or the default cd if no hard disk defined yet */
5938 if (!boot_devices[0]) {
5939 boot_devices = "cad";
5941 setvbuf(stdout, NULL, _IOLBF, 0);
5943 init_timers();
5944 if (init_timer_alarm() < 0) {
5945 fprintf(stderr, "could not initialize alarm timer\n");
5946 exit(1);
5948 if (use_icount && icount_time_shift < 0) {
5949 use_icount = 2;
5950 /* 125MIPS seems a reasonable initial guess at the guest speed.
5951 It will be corrected fairly quickly anyway. */
5952 icount_time_shift = 3;
5953 init_icount_adjust();
5956 #ifdef _WIN32
5957 socket_init();
5958 #endif
5960 /* init network clients */
5961 if (nb_net_clients == 0) {
5962 /* if no clients, we use a default config */
5963 net_clients[nb_net_clients++] = "nic";
5964 #ifdef CONFIG_SLIRP
5965 net_clients[nb_net_clients++] = "user";
5966 #endif
5969 for(i = 0;i < nb_net_clients; i++) {
5970 if (net_client_parse(net_clients[i]) < 0)
5971 exit(1);
5973 net_client_check();
5975 #ifdef TARGET_I386
5976 /* XXX: this should be moved in the PC machine instantiation code */
5977 if (net_boot != 0) {
5978 int netroms = 0;
5979 for (i = 0; i < nb_nics && i < 4; i++) {
5980 const char *model = nd_table[i].model;
5981 char buf[1024];
5982 char *filename;
5983 if (net_boot & (1 << i)) {
5984 if (model == NULL)
5985 model = "rtl8139";
5986 snprintf(buf, sizeof(buf), "pxe-%s.bin", model);
5987 filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, buf);
5988 if (filename && get_image_size(filename) > 0) {
5989 if (nb_option_roms >= MAX_OPTION_ROMS) {
5990 fprintf(stderr, "Too many option ROMs\n");
5991 exit(1);
5993 option_rom[nb_option_roms] = qemu_strdup(buf);
5994 nb_option_roms++;
5995 netroms++;
5997 if (filename) {
5998 qemu_free(filename);
6002 if (netroms == 0) {
6003 fprintf(stderr, "No valid PXE rom found for network device\n");
6004 exit(1);
6007 #endif
6009 /* init the bluetooth world */
6010 for (i = 0; i < nb_bt_opts; i++)
6011 if (bt_parse(bt_opts[i]))
6012 exit(1);
6014 /* init the memory */
6015 if (ram_size == 0)
6016 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6018 if (kvm_enabled()) {
6019 if (kvm_qemu_create_context() < 0) {
6020 fprintf(stderr, "Could not create KVM context\n");
6021 exit(1);
6025 #ifdef CONFIG_KQEMU
6026 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
6027 guest ram allocation. It needs to go away. */
6028 if (kqemu_allowed) {
6029 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
6030 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
6031 if (!kqemu_phys_ram_base) {
6032 fprintf(stderr, "Could not allocate physical memory\n");
6033 exit(1);
6036 #endif
6038 /* init the dynamic translator */
6039 cpu_exec_init_all(tb_size * 1024 * 1024);
6041 bdrv_init();
6043 /* we always create the cdrom drive, even if no disk is there */
6045 if (nb_drives_opt < MAX_DRIVES)
6046 drive_add(NULL, CDROM_ALIAS);
6048 /* we always create at least one floppy */
6050 if (nb_drives_opt < MAX_DRIVES)
6051 drive_add(NULL, FD_ALIAS, 0);
6053 /* we always create one sd slot, even if no card is in it */
6055 if (nb_drives_opt < MAX_DRIVES)
6056 drive_add(NULL, SD_ALIAS);
6058 /* open the virtual block devices
6059 * note that migration with device
6060 * hot add/remove is broken.
6062 for(i = 0; i < nb_drives_opt; i++)
6063 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6064 exit(1);
6066 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6067 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6069 #ifndef _WIN32
6070 /* must be after terminal init, SDL library changes signal handlers */
6071 termsig_setup();
6072 #endif
6074 /* Maintain compatibility with multiple stdio monitors */
6075 if (!strcmp(monitor_device,"stdio")) {
6076 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6077 const char *devname = serial_devices[i];
6078 if (devname && !strcmp(devname,"mon:stdio")) {
6079 monitor_device = NULL;
6080 break;
6081 } else if (devname && !strcmp(devname,"stdio")) {
6082 monitor_device = NULL;
6083 serial_devices[i] = "mon:stdio";
6084 break;
6089 if (nb_numa_nodes > 0) {
6090 int i;
6092 if (nb_numa_nodes > smp_cpus) {
6093 nb_numa_nodes = smp_cpus;
6096 /* If no memory size if given for any node, assume the default case
6097 * and distribute the available memory equally across all nodes
6099 for (i = 0; i < nb_numa_nodes; i++) {
6100 if (node_mem[i] != 0)
6101 break;
6103 if (i == nb_numa_nodes) {
6104 uint64_t usedmem = 0;
6106 /* On Linux, the each node's border has to be 8MB aligned,
6107 * the final node gets the rest.
6109 for (i = 0; i < nb_numa_nodes - 1; i++) {
6110 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
6111 usedmem += node_mem[i];
6113 node_mem[i] = ram_size - usedmem;
6116 for (i = 0; i < nb_numa_nodes; i++) {
6117 if (node_cpumask[i] != 0)
6118 break;
6120 /* assigning the VCPUs round-robin is easier to implement, guest OSes
6121 * must cope with this anyway, because there are BIOSes out there in
6122 * real machines which also use this scheme.
6124 if (i == nb_numa_nodes) {
6125 for (i = 0; i < smp_cpus; i++) {
6126 node_cpumask[i % nb_numa_nodes] |= 1 << i;
6131 #ifdef KVM_UPSTREAM
6132 if (kvm_enabled()) {
6133 int ret;
6135 ret = kvm_init(smp_cpus);
6136 if (ret < 0) {
6137 fprintf(stderr, "failed to initialize KVM\n");
6138 exit(1);
6141 #endif
6143 if (monitor_device) {
6144 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6145 if (!monitor_hd) {
6146 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6147 exit(1);
6151 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6152 const char *devname = serial_devices[i];
6153 if (devname && strcmp(devname, "none")) {
6154 char label[32];
6155 snprintf(label, sizeof(label), "serial%d", i);
6156 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6157 if (!serial_hds[i]) {
6158 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6159 devname);
6160 exit(1);
6165 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6166 const char *devname = parallel_devices[i];
6167 if (devname && strcmp(devname, "none")) {
6168 char label[32];
6169 snprintf(label, sizeof(label), "parallel%d", i);
6170 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6171 if (!parallel_hds[i]) {
6172 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6173 devname);
6174 exit(1);
6179 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6180 const char *devname = virtio_consoles[i];
6181 if (devname && strcmp(devname, "none")) {
6182 char label[32];
6183 snprintf(label, sizeof(label), "virtcon%d", i);
6184 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6185 if (!virtcon_hds[i]) {
6186 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6187 devname);
6188 exit(1);
6193 module_call_init(MODULE_INIT_DEVICE);
6195 if (kvm_enabled())
6196 kvm_init_ap();
6198 machine->init(ram_size, boot_devices,
6199 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6202 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6203 for (i = 0; i < nb_numa_nodes; i++) {
6204 if (node_cpumask[i] & (1 << env->cpu_index)) {
6205 env->numa_node = i;
6210 current_machine = machine;
6212 /* Set KVM's vcpu state to qemu's initial CPUState. */
6213 if (kvm_enabled()) {
6214 int ret;
6216 ret = kvm_sync_vcpus();
6217 if (ret < 0) {
6218 fprintf(stderr, "failed to initialize vcpus\n");
6219 exit(1);
6223 /* init USB devices */
6224 if (usb_enabled) {
6225 for(i = 0; i < usb_devices_index; i++) {
6226 if (usb_device_add(usb_devices[i], 0) < 0) {
6227 fprintf(stderr, "Warning: could not add USB device %s\n",
6228 usb_devices[i]);
6233 if (!display_state)
6234 dumb_display_init();
6235 /* just use the first displaystate for the moment */
6236 ds = display_state;
6238 if (display_type == DT_DEFAULT) {
6239 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6240 display_type = DT_SDL;
6241 #else
6242 display_type = DT_VNC;
6243 vnc_display = "localhost:0,to=99";
6244 show_vnc_port = 1;
6245 #endif
6249 switch (display_type) {
6250 case DT_NOGRAPHIC:
6251 break;
6252 #if defined(CONFIG_CURSES)
6253 case DT_CURSES:
6254 curses_display_init(ds, full_screen);
6255 break;
6256 #endif
6257 #if defined(CONFIG_SDL)
6258 case DT_SDL:
6259 sdl_display_init(ds, full_screen, no_frame);
6260 break;
6261 #elif defined(CONFIG_COCOA)
6262 case DT_SDL:
6263 cocoa_display_init(ds, full_screen);
6264 break;
6265 #endif
6266 case DT_VNC:
6267 vnc_display_init(ds);
6268 if (vnc_display_open(ds, vnc_display) < 0)
6269 exit(1);
6271 if (show_vnc_port) {
6272 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6274 break;
6275 default:
6276 break;
6278 dpy_resize(ds);
6280 dcl = ds->listeners;
6281 while (dcl != NULL) {
6282 if (dcl->dpy_refresh != NULL) {
6283 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6284 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6286 dcl = dcl->next;
6289 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6290 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6291 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6294 text_consoles_set_display(display_state);
6295 qemu_chr_initial_reset();
6297 if (monitor_device && monitor_hd)
6298 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6300 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6301 const char *devname = serial_devices[i];
6302 if (devname && strcmp(devname, "none")) {
6303 char label[32];
6304 snprintf(label, sizeof(label), "serial%d", i);
6305 if (strstart(devname, "vc", 0))
6306 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6310 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6311 const char *devname = parallel_devices[i];
6312 if (devname && strcmp(devname, "none")) {
6313 char label[32];
6314 snprintf(label, sizeof(label), "parallel%d", i);
6315 if (strstart(devname, "vc", 0))
6316 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6320 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6321 const char *devname = virtio_consoles[i];
6322 if (virtcon_hds[i] && devname) {
6323 char label[32];
6324 snprintf(label, sizeof(label), "virtcon%d", i);
6325 if (strstart(devname, "vc", 0))
6326 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6330 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6331 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6332 gdbstub_dev);
6333 exit(1);
6336 if (loadvm)
6337 do_loadvm(cur_mon, loadvm);
6339 if (incoming) {
6340 autostart = 0; /* fixme how to deal with -daemonize */
6341 qemu_start_incoming_migration(incoming);
6344 if (autostart)
6345 vm_start();
6347 #ifndef _WIN32
6348 if (daemonize) {
6349 uint8_t status = 0;
6350 ssize_t len;
6352 again1:
6353 len = write(fds[1], &status, 1);
6354 if (len == -1 && (errno == EINTR))
6355 goto again1;
6357 if (len != 1)
6358 exit(1);
6360 chdir("/");
6361 TFR(fd = open("/dev/null", O_RDWR));
6362 if (fd == -1)
6363 exit(1);
6366 if (run_as) {
6367 pwd = getpwnam(run_as);
6368 if (!pwd) {
6369 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6370 exit(1);
6374 if (chroot_dir) {
6375 if (chroot(chroot_dir) < 0) {
6376 fprintf(stderr, "chroot failed\n");
6377 exit(1);
6379 chdir("/");
6382 if (run_as) {
6383 if (setgid(pwd->pw_gid) < 0) {
6384 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6385 exit(1);
6387 if (setuid(pwd->pw_uid) < 0) {
6388 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6389 exit(1);
6391 if (setuid(0) != -1) {
6392 fprintf(stderr, "Dropping privileges failed\n");
6393 exit(1);
6397 if (daemonize) {
6398 dup2(fd, 0);
6399 dup2(fd, 1);
6400 dup2(fd, 2);
6402 close(fd);
6404 #endif
6406 main_loop();
6407 quit_timers();
6408 net_cleanup();
6410 return 0;