slirp: tftp: Refactor tftp_handle_rrq
[qemu/ar7.git] / vl.c
blob23add311bc30a394661ceb2b9c4144e26b690750
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 #if defined(__APPLE__) || defined(main)
117 #include <SDL.h>
118 int qemu_main(int argc, char **argv, char **envp);
119 int main(int argc, char **argv)
121 return 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"
162 #include "disas.h"
164 #include "exec-all.h"
166 #include "qemu_socket.h"
168 #if defined(CONFIG_SLIRP)
169 #include "libslirp.h"
170 #endif
172 //#define DEBUG_UNUSED_IOPORT
173 //#define DEBUG_IOPORT
174 //#define DEBUG_NET
175 //#define DEBUG_SLIRP
178 #ifdef DEBUG_IOPORT
179 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
180 #else
181 # define LOG_IOPORT(...) do { } while (0)
182 #endif
184 #define DEFAULT_RAM_SIZE 128
186 /* Max number of USB devices that can be specified on the commandline. */
187 #define MAX_USB_CMDLINE 8
189 /* Max number of bluetooth switches on the commandline. */
190 #define MAX_BT_CMDLINE 10
192 /* XXX: use a two level table to limit memory usage */
193 #define MAX_IOPORTS 65536
195 static const char *data_dir;
196 const char *bios_name = NULL;
197 static void *ioport_opaque[MAX_IOPORTS];
198 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
199 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
200 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
201 to store the VM snapshots */
202 DriveInfo drives_table[MAX_DRIVES+1];
203 int nb_drives;
204 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
205 static DisplayState *display_state;
206 DisplayType display_type = DT_DEFAULT;
207 const char* keyboard_layout = NULL;
208 int64_t ticks_per_sec;
209 ram_addr_t ram_size;
210 int nb_nics;
211 NICInfo nd_table[MAX_NICS];
212 int vm_running;
213 static int autostart;
214 static int rtc_utc = 1;
215 static int rtc_date_offset = -1; /* -1 means no change */
216 int cirrus_vga_enabled = 1;
217 int std_vga_enabled = 0;
218 int vmsvga_enabled = 0;
219 int xenfb_enabled = 0;
220 #ifdef TARGET_SPARC
221 int graphic_width = 1024;
222 int graphic_height = 768;
223 int graphic_depth = 8;
224 #else
225 int graphic_width = 800;
226 int graphic_height = 600;
227 int graphic_depth = 15;
228 #endif
229 static int full_screen = 0;
230 #ifdef CONFIG_SDL
231 static int no_frame = 0;
232 #endif
233 int no_quit = 0;
234 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
235 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
236 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
237 #ifdef TARGET_I386
238 int win2k_install_hack = 0;
239 int rtc_td_hack = 0;
240 #endif
241 int usb_enabled = 0;
242 int singlestep = 0;
243 int smp_cpus = 1;
244 const char *vnc_display;
245 int acpi_enabled = 1;
246 int no_hpet = 0;
247 int no_virtio_balloon = 0;
248 int fd_bootchk = 1;
249 int no_reboot = 0;
250 int no_shutdown = 0;
251 int cursor_hide = 1;
252 int graphic_rotate = 0;
253 #ifndef _WIN32
254 int daemonize = 0;
255 #endif
256 WatchdogTimerModel *watchdog = NULL;
257 int watchdog_action = WDT_RESET;
258 const char *option_rom[MAX_OPTION_ROMS];
259 int nb_option_roms;
260 int semihosting_enabled = 0;
261 #ifdef TARGET_ARM
262 int old_param = 0;
263 #endif
264 const char *qemu_name;
265 int alt_grab = 0;
266 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
267 unsigned int nb_prom_envs = 0;
268 const char *prom_envs[MAX_PROM_ENVS];
269 #endif
270 int nb_drives_opt;
271 struct drive_opt drives_opt[MAX_DRIVES];
273 int nb_numa_nodes;
274 uint64_t node_mem[MAX_NODES];
275 uint64_t node_cpumask[MAX_NODES];
277 static CPUState *cur_cpu;
278 static CPUState *next_cpu;
279 static int timer_alarm_pending = 1;
280 /* Conversion factor from emulated instructions to virtual clock ticks. */
281 static int icount_time_shift;
282 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
283 #define MAX_ICOUNT_SHIFT 10
284 /* Compensate for varying guest execution speed. */
285 static int64_t qemu_icount_bias;
286 static QEMUTimer *icount_rt_timer;
287 static QEMUTimer *icount_vm_timer;
288 static QEMUTimer *nographic_timer;
290 uint8_t qemu_uuid[16];
292 /***********************************************************/
293 /* x86 ISA bus support */
295 target_phys_addr_t isa_mem_base = 0;
296 PicState2 *isa_pic;
298 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
299 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
301 static uint32_t ioport_read(int index, uint32_t address)
303 static IOPortReadFunc *default_func[3] = {
304 default_ioport_readb,
305 default_ioport_readw,
306 default_ioport_readl
308 IOPortReadFunc *func = ioport_read_table[index][address];
309 if (!func)
310 func = default_func[index];
311 return func(ioport_opaque[address], address);
314 static void ioport_write(int index, uint32_t address, uint32_t data)
316 static IOPortWriteFunc *default_func[3] = {
317 default_ioport_writeb,
318 default_ioport_writew,
319 default_ioport_writel
321 IOPortWriteFunc *func = ioport_write_table[index][address];
322 if (!func)
323 func = default_func[index];
324 func(ioport_opaque[address], address, data);
327 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
329 #ifdef DEBUG_UNUSED_IOPORT
330 fprintf(stderr, "unused inb: port=0x%04x\n", address);
331 #endif
332 return 0xff;
335 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
337 #ifdef DEBUG_UNUSED_IOPORT
338 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
339 #endif
342 /* default is to make two byte accesses */
343 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
345 uint32_t data;
346 data = ioport_read(0, address);
347 address = (address + 1) & (MAX_IOPORTS - 1);
348 data |= ioport_read(0, address) << 8;
349 return data;
352 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
354 ioport_write(0, address, data & 0xff);
355 address = (address + 1) & (MAX_IOPORTS - 1);
356 ioport_write(0, address, (data >> 8) & 0xff);
359 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
361 #ifdef DEBUG_UNUSED_IOPORT
362 fprintf(stderr, "unused inl: port=0x%04x\n", address);
363 #endif
364 return 0xffffffff;
367 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
369 #ifdef DEBUG_UNUSED_IOPORT
370 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
371 #endif
374 /* size is the word size in byte */
375 int register_ioport_read(int start, int length, int size,
376 IOPortReadFunc *func, void *opaque)
378 int i, bsize;
380 if (size == 1) {
381 bsize = 0;
382 } else if (size == 2) {
383 bsize = 1;
384 } else if (size == 4) {
385 bsize = 2;
386 } else {
387 hw_error("register_ioport_read: invalid size");
388 return -1;
390 for(i = start; i < start + length; i += size) {
391 ioport_read_table[bsize][i] = func;
392 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
393 hw_error("register_ioport_read: invalid opaque");
394 ioport_opaque[i] = opaque;
396 return 0;
399 /* size is the word size in byte */
400 int register_ioport_write(int start, int length, int size,
401 IOPortWriteFunc *func, void *opaque)
403 int i, bsize;
405 if (size == 1) {
406 bsize = 0;
407 } else if (size == 2) {
408 bsize = 1;
409 } else if (size == 4) {
410 bsize = 2;
411 } else {
412 hw_error("register_ioport_write: invalid size");
413 return -1;
415 for(i = start; i < start + length; i += size) {
416 ioport_write_table[bsize][i] = func;
417 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
418 hw_error("register_ioport_write: invalid opaque");
419 ioport_opaque[i] = opaque;
421 return 0;
424 void isa_unassign_ioport(int start, int length)
426 int i;
428 for(i = start; i < start + length; i++) {
429 ioport_read_table[0][i] = default_ioport_readb;
430 ioport_read_table[1][i] = default_ioport_readw;
431 ioport_read_table[2][i] = default_ioport_readl;
433 ioport_write_table[0][i] = default_ioport_writeb;
434 ioport_write_table[1][i] = default_ioport_writew;
435 ioport_write_table[2][i] = default_ioport_writel;
437 ioport_opaque[i] = NULL;
441 /***********************************************************/
443 void cpu_outb(CPUState *env, int addr, int val)
445 LOG_IOPORT("outb: %04x %02x\n", addr, val);
446 ioport_write(0, addr, val);
447 #ifdef CONFIG_KQEMU
448 if (env)
449 env->last_io_time = cpu_get_time_fast();
450 #endif
453 void cpu_outw(CPUState *env, int addr, int val)
455 LOG_IOPORT("outw: %04x %04x\n", addr, val);
456 ioport_write(1, addr, val);
457 #ifdef CONFIG_KQEMU
458 if (env)
459 env->last_io_time = cpu_get_time_fast();
460 #endif
463 void cpu_outl(CPUState *env, int addr, int val)
465 LOG_IOPORT("outl: %04x %08x\n", addr, val);
466 ioport_write(2, addr, val);
467 #ifdef CONFIG_KQEMU
468 if (env)
469 env->last_io_time = cpu_get_time_fast();
470 #endif
473 int cpu_inb(CPUState *env, int addr)
475 int val;
476 val = ioport_read(0, addr);
477 LOG_IOPORT("inb : %04x %02x\n", addr, val);
478 #ifdef CONFIG_KQEMU
479 if (env)
480 env->last_io_time = cpu_get_time_fast();
481 #endif
482 return val;
485 int cpu_inw(CPUState *env, int addr)
487 int val;
488 val = ioport_read(1, addr);
489 LOG_IOPORT("inw : %04x %04x\n", addr, val);
490 #ifdef CONFIG_KQEMU
491 if (env)
492 env->last_io_time = cpu_get_time_fast();
493 #endif
494 return val;
497 int cpu_inl(CPUState *env, int addr)
499 int val;
500 val = ioport_read(2, addr);
501 LOG_IOPORT("inl : %04x %08x\n", addr, val);
502 #ifdef CONFIG_KQEMU
503 if (env)
504 env->last_io_time = cpu_get_time_fast();
505 #endif
506 return val;
509 /***********************************************************/
510 void hw_error(const char *fmt, ...)
512 va_list ap;
513 CPUState *env;
515 va_start(ap, fmt);
516 fprintf(stderr, "qemu: hardware error: ");
517 vfprintf(stderr, fmt, ap);
518 fprintf(stderr, "\n");
519 for(env = first_cpu; env != NULL; env = env->next_cpu) {
520 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
521 #ifdef TARGET_I386
522 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
523 #else
524 cpu_dump_state(env, stderr, fprintf, 0);
525 #endif
527 va_end(ap);
528 abort();
531 /***************/
532 /* ballooning */
534 static QEMUBalloonEvent *qemu_balloon_event;
535 void *qemu_balloon_event_opaque;
537 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
539 qemu_balloon_event = func;
540 qemu_balloon_event_opaque = opaque;
543 void qemu_balloon(ram_addr_t target)
545 if (qemu_balloon_event)
546 qemu_balloon_event(qemu_balloon_event_opaque, target);
549 ram_addr_t qemu_balloon_status(void)
551 if (qemu_balloon_event)
552 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
553 return 0;
556 /***********************************************************/
557 /* keyboard/mouse */
559 static QEMUPutKBDEvent *qemu_put_kbd_event;
560 static void *qemu_put_kbd_event_opaque;
561 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
562 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
564 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
566 qemu_put_kbd_event_opaque = opaque;
567 qemu_put_kbd_event = func;
570 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
571 void *opaque, int absolute,
572 const char *name)
574 QEMUPutMouseEntry *s, *cursor;
576 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
578 s->qemu_put_mouse_event = func;
579 s->qemu_put_mouse_event_opaque = opaque;
580 s->qemu_put_mouse_event_absolute = absolute;
581 s->qemu_put_mouse_event_name = qemu_strdup(name);
582 s->next = NULL;
584 if (!qemu_put_mouse_event_head) {
585 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
586 return s;
589 cursor = qemu_put_mouse_event_head;
590 while (cursor->next != NULL)
591 cursor = cursor->next;
593 cursor->next = s;
594 qemu_put_mouse_event_current = s;
596 return s;
599 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
601 QEMUPutMouseEntry *prev = NULL, *cursor;
603 if (!qemu_put_mouse_event_head || entry == NULL)
604 return;
606 cursor = qemu_put_mouse_event_head;
607 while (cursor != NULL && cursor != entry) {
608 prev = cursor;
609 cursor = cursor->next;
612 if (cursor == NULL) // does not exist or list empty
613 return;
614 else if (prev == NULL) { // entry is head
615 qemu_put_mouse_event_head = cursor->next;
616 if (qemu_put_mouse_event_current == entry)
617 qemu_put_mouse_event_current = cursor->next;
618 qemu_free(entry->qemu_put_mouse_event_name);
619 qemu_free(entry);
620 return;
623 prev->next = entry->next;
625 if (qemu_put_mouse_event_current == entry)
626 qemu_put_mouse_event_current = prev;
628 qemu_free(entry->qemu_put_mouse_event_name);
629 qemu_free(entry);
632 void kbd_put_keycode(int keycode)
634 if (qemu_put_kbd_event) {
635 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
639 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
641 QEMUPutMouseEvent *mouse_event;
642 void *mouse_event_opaque;
643 int width;
645 if (!qemu_put_mouse_event_current) {
646 return;
649 mouse_event =
650 qemu_put_mouse_event_current->qemu_put_mouse_event;
651 mouse_event_opaque =
652 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
654 if (mouse_event) {
655 if (graphic_rotate) {
656 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
657 width = 0x7fff;
658 else
659 width = graphic_width - 1;
660 mouse_event(mouse_event_opaque,
661 width - dy, dx, dz, buttons_state);
662 } else
663 mouse_event(mouse_event_opaque,
664 dx, dy, dz, buttons_state);
668 int kbd_mouse_is_absolute(void)
670 if (!qemu_put_mouse_event_current)
671 return 0;
673 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
676 void do_info_mice(Monitor *mon)
678 QEMUPutMouseEntry *cursor;
679 int index = 0;
681 if (!qemu_put_mouse_event_head) {
682 monitor_printf(mon, "No mouse devices connected\n");
683 return;
686 monitor_printf(mon, "Mouse devices available:\n");
687 cursor = qemu_put_mouse_event_head;
688 while (cursor != NULL) {
689 monitor_printf(mon, "%c Mouse #%d: %s\n",
690 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
691 index, cursor->qemu_put_mouse_event_name);
692 index++;
693 cursor = cursor->next;
697 void do_mouse_set(Monitor *mon, int index)
699 QEMUPutMouseEntry *cursor;
700 int i = 0;
702 if (!qemu_put_mouse_event_head) {
703 monitor_printf(mon, "No mouse devices connected\n");
704 return;
707 cursor = qemu_put_mouse_event_head;
708 while (cursor != NULL && index != i) {
709 i++;
710 cursor = cursor->next;
713 if (cursor != NULL)
714 qemu_put_mouse_event_current = cursor;
715 else
716 monitor_printf(mon, "Mouse at given index not found\n");
719 /* compute with 96 bit intermediate result: (a*b)/c */
720 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
722 union {
723 uint64_t ll;
724 struct {
725 #ifdef WORDS_BIGENDIAN
726 uint32_t high, low;
727 #else
728 uint32_t low, high;
729 #endif
730 } l;
731 } u, res;
732 uint64_t rl, rh;
734 u.ll = a;
735 rl = (uint64_t)u.l.low * (uint64_t)b;
736 rh = (uint64_t)u.l.high * (uint64_t)b;
737 rh += (rl >> 32);
738 res.l.high = rh / c;
739 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
740 return res.ll;
743 /***********************************************************/
744 /* real time host monotonic timer */
746 #define QEMU_TIMER_BASE 1000000000LL
748 #ifdef WIN32
750 static int64_t clock_freq;
752 static void init_get_clock(void)
754 LARGE_INTEGER freq;
755 int ret;
756 ret = QueryPerformanceFrequency(&freq);
757 if (ret == 0) {
758 fprintf(stderr, "Could not calibrate ticks\n");
759 exit(1);
761 clock_freq = freq.QuadPart;
764 static int64_t get_clock(void)
766 LARGE_INTEGER ti;
767 QueryPerformanceCounter(&ti);
768 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
771 #else
773 static int use_rt_clock;
775 static void init_get_clock(void)
777 use_rt_clock = 0;
778 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
779 || defined(__DragonFly__)
781 struct timespec ts;
782 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
783 use_rt_clock = 1;
786 #endif
789 static int64_t get_clock(void)
791 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
792 || defined(__DragonFly__)
793 if (use_rt_clock) {
794 struct timespec ts;
795 clock_gettime(CLOCK_MONOTONIC, &ts);
796 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
797 } else
798 #endif
800 /* XXX: using gettimeofday leads to problems if the date
801 changes, so it should be avoided. */
802 struct timeval tv;
803 gettimeofday(&tv, NULL);
804 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
807 #endif
809 /* Return the virtual CPU time, based on the instruction counter. */
810 static int64_t cpu_get_icount(void)
812 int64_t icount;
813 CPUState *env = cpu_single_env;;
814 icount = qemu_icount;
815 if (env) {
816 if (!can_do_io(env))
817 fprintf(stderr, "Bad clock read\n");
818 icount -= (env->icount_decr.u16.low + env->icount_extra);
820 return qemu_icount_bias + (icount << icount_time_shift);
823 /***********************************************************/
824 /* guest cycle counter */
826 static int64_t cpu_ticks_prev;
827 static int64_t cpu_ticks_offset;
828 static int64_t cpu_clock_offset;
829 static int cpu_ticks_enabled;
831 /* return the host CPU cycle counter and handle stop/restart */
832 int64_t cpu_get_ticks(void)
834 if (use_icount) {
835 return cpu_get_icount();
837 if (!cpu_ticks_enabled) {
838 return cpu_ticks_offset;
839 } else {
840 int64_t ticks;
841 ticks = cpu_get_real_ticks();
842 if (cpu_ticks_prev > ticks) {
843 /* Note: non increasing ticks may happen if the host uses
844 software suspend */
845 cpu_ticks_offset += cpu_ticks_prev - ticks;
847 cpu_ticks_prev = ticks;
848 return ticks + cpu_ticks_offset;
852 /* return the host CPU monotonic timer and handle stop/restart */
853 static int64_t cpu_get_clock(void)
855 int64_t ti;
856 if (!cpu_ticks_enabled) {
857 return cpu_clock_offset;
858 } else {
859 ti = get_clock();
860 return ti + cpu_clock_offset;
864 /* enable cpu_get_ticks() */
865 void cpu_enable_ticks(void)
867 if (!cpu_ticks_enabled) {
868 cpu_ticks_offset -= cpu_get_real_ticks();
869 cpu_clock_offset -= get_clock();
870 cpu_ticks_enabled = 1;
874 /* disable cpu_get_ticks() : the clock is stopped. You must not call
875 cpu_get_ticks() after that. */
876 void cpu_disable_ticks(void)
878 if (cpu_ticks_enabled) {
879 cpu_ticks_offset = cpu_get_ticks();
880 cpu_clock_offset = cpu_get_clock();
881 cpu_ticks_enabled = 0;
885 /***********************************************************/
886 /* timers */
888 #define QEMU_TIMER_REALTIME 0
889 #define QEMU_TIMER_VIRTUAL 1
891 struct QEMUClock {
892 int type;
893 /* XXX: add frequency */
896 struct QEMUTimer {
897 QEMUClock *clock;
898 int64_t expire_time;
899 QEMUTimerCB *cb;
900 void *opaque;
901 struct QEMUTimer *next;
904 struct qemu_alarm_timer {
905 char const *name;
906 unsigned int flags;
908 int (*start)(struct qemu_alarm_timer *t);
909 void (*stop)(struct qemu_alarm_timer *t);
910 void (*rearm)(struct qemu_alarm_timer *t);
911 void *priv;
914 #define ALARM_FLAG_DYNTICKS 0x1
915 #define ALARM_FLAG_EXPIRED 0x2
917 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
919 return t && (t->flags & ALARM_FLAG_DYNTICKS);
922 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
924 if (!alarm_has_dynticks(t))
925 return;
927 t->rearm(t);
930 /* TODO: MIN_TIMER_REARM_US should be optimized */
931 #define MIN_TIMER_REARM_US 250
933 static struct qemu_alarm_timer *alarm_timer;
935 #ifdef _WIN32
937 struct qemu_alarm_win32 {
938 MMRESULT timerId;
939 unsigned int period;
940 } alarm_win32_data = {0, -1};
942 static int win32_start_timer(struct qemu_alarm_timer *t);
943 static void win32_stop_timer(struct qemu_alarm_timer *t);
944 static void win32_rearm_timer(struct qemu_alarm_timer *t);
946 #else
948 static int unix_start_timer(struct qemu_alarm_timer *t);
949 static void unix_stop_timer(struct qemu_alarm_timer *t);
951 #ifdef __linux__
953 static int dynticks_start_timer(struct qemu_alarm_timer *t);
954 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
955 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
957 static int hpet_start_timer(struct qemu_alarm_timer *t);
958 static void hpet_stop_timer(struct qemu_alarm_timer *t);
960 static int rtc_start_timer(struct qemu_alarm_timer *t);
961 static void rtc_stop_timer(struct qemu_alarm_timer *t);
963 #endif /* __linux__ */
965 #endif /* _WIN32 */
967 /* Correlation between real and virtual time is always going to be
968 fairly approximate, so ignore small variation.
969 When the guest is idle real and virtual time will be aligned in
970 the IO wait loop. */
971 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
973 static void icount_adjust(void)
975 int64_t cur_time;
976 int64_t cur_icount;
977 int64_t delta;
978 static int64_t last_delta;
979 /* If the VM is not running, then do nothing. */
980 if (!vm_running)
981 return;
983 cur_time = cpu_get_clock();
984 cur_icount = qemu_get_clock(vm_clock);
985 delta = cur_icount - cur_time;
986 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
987 if (delta > 0
988 && last_delta + ICOUNT_WOBBLE < delta * 2
989 && icount_time_shift > 0) {
990 /* The guest is getting too far ahead. Slow time down. */
991 icount_time_shift--;
993 if (delta < 0
994 && last_delta - ICOUNT_WOBBLE > delta * 2
995 && icount_time_shift < MAX_ICOUNT_SHIFT) {
996 /* The guest is getting too far behind. Speed time up. */
997 icount_time_shift++;
999 last_delta = delta;
1000 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1003 static void icount_adjust_rt(void * opaque)
1005 qemu_mod_timer(icount_rt_timer,
1006 qemu_get_clock(rt_clock) + 1000);
1007 icount_adjust();
1010 static void icount_adjust_vm(void * opaque)
1012 qemu_mod_timer(icount_vm_timer,
1013 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1014 icount_adjust();
1017 static void init_icount_adjust(void)
1019 /* Have both realtime and virtual time triggers for speed adjustment.
1020 The realtime trigger catches emulated time passing too slowly,
1021 the virtual time trigger catches emulated time passing too fast.
1022 Realtime triggers occur even when idle, so use them less frequently
1023 than VM triggers. */
1024 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1025 qemu_mod_timer(icount_rt_timer,
1026 qemu_get_clock(rt_clock) + 1000);
1027 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1028 qemu_mod_timer(icount_vm_timer,
1029 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1032 static struct qemu_alarm_timer alarm_timers[] = {
1033 #ifndef _WIN32
1034 #ifdef __linux__
1035 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1036 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1037 /* HPET - if available - is preferred */
1038 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1039 /* ...otherwise try RTC */
1040 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1041 #endif
1042 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1043 #else
1044 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1045 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1046 {"win32", 0, win32_start_timer,
1047 win32_stop_timer, NULL, &alarm_win32_data},
1048 #endif
1049 {NULL, }
1052 static void show_available_alarms(void)
1054 int i;
1056 printf("Available alarm timers, in order of precedence:\n");
1057 for (i = 0; alarm_timers[i].name; i++)
1058 printf("%s\n", alarm_timers[i].name);
1061 static void configure_alarms(char const *opt)
1063 int i;
1064 int cur = 0;
1065 int count = ARRAY_SIZE(alarm_timers) - 1;
1066 char *arg;
1067 char *name;
1068 struct qemu_alarm_timer tmp;
1070 if (!strcmp(opt, "?")) {
1071 show_available_alarms();
1072 exit(0);
1075 arg = strdup(opt);
1077 /* Reorder the array */
1078 name = strtok(arg, ",");
1079 while (name) {
1080 for (i = 0; i < count && alarm_timers[i].name; i++) {
1081 if (!strcmp(alarm_timers[i].name, name))
1082 break;
1085 if (i == count) {
1086 fprintf(stderr, "Unknown clock %s\n", name);
1087 goto next;
1090 if (i < cur)
1091 /* Ignore */
1092 goto next;
1094 /* Swap */
1095 tmp = alarm_timers[i];
1096 alarm_timers[i] = alarm_timers[cur];
1097 alarm_timers[cur] = tmp;
1099 cur++;
1100 next:
1101 name = strtok(NULL, ",");
1104 free(arg);
1106 if (cur) {
1107 /* Disable remaining timers */
1108 for (i = cur; i < count; i++)
1109 alarm_timers[i].name = NULL;
1110 } else {
1111 show_available_alarms();
1112 exit(1);
1116 QEMUClock *rt_clock;
1117 QEMUClock *vm_clock;
1119 static QEMUTimer *active_timers[2];
1121 static QEMUClock *qemu_new_clock(int type)
1123 QEMUClock *clock;
1124 clock = qemu_mallocz(sizeof(QEMUClock));
1125 clock->type = type;
1126 return clock;
1129 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1131 QEMUTimer *ts;
1133 ts = qemu_mallocz(sizeof(QEMUTimer));
1134 ts->clock = clock;
1135 ts->cb = cb;
1136 ts->opaque = opaque;
1137 return ts;
1140 void qemu_free_timer(QEMUTimer *ts)
1142 qemu_free(ts);
1145 /* stop a timer, but do not dealloc it */
1146 void qemu_del_timer(QEMUTimer *ts)
1148 QEMUTimer **pt, *t;
1150 /* NOTE: this code must be signal safe because
1151 qemu_timer_expired() can be called from a signal. */
1152 pt = &active_timers[ts->clock->type];
1153 for(;;) {
1154 t = *pt;
1155 if (!t)
1156 break;
1157 if (t == ts) {
1158 *pt = t->next;
1159 break;
1161 pt = &t->next;
1165 /* modify the current timer so that it will be fired when current_time
1166 >= expire_time. The corresponding callback will be called. */
1167 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1169 QEMUTimer **pt, *t;
1171 qemu_del_timer(ts);
1173 /* add the timer in the sorted list */
1174 /* NOTE: this code must be signal safe because
1175 qemu_timer_expired() can be called from a signal. */
1176 pt = &active_timers[ts->clock->type];
1177 for(;;) {
1178 t = *pt;
1179 if (!t)
1180 break;
1181 if (t->expire_time > expire_time)
1182 break;
1183 pt = &t->next;
1185 ts->expire_time = expire_time;
1186 ts->next = *pt;
1187 *pt = ts;
1189 /* Rearm if necessary */
1190 if (pt == &active_timers[ts->clock->type]) {
1191 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1192 qemu_rearm_alarm_timer(alarm_timer);
1194 /* Interrupt execution to force deadline recalculation. */
1195 if (use_icount)
1196 qemu_notify_event();
1200 int qemu_timer_pending(QEMUTimer *ts)
1202 QEMUTimer *t;
1203 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1204 if (t == ts)
1205 return 1;
1207 return 0;
1210 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1212 if (!timer_head)
1213 return 0;
1214 return (timer_head->expire_time <= current_time);
1217 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1219 QEMUTimer *ts;
1221 for(;;) {
1222 ts = *ptimer_head;
1223 if (!ts || ts->expire_time > current_time)
1224 break;
1225 /* remove timer from the list before calling the callback */
1226 *ptimer_head = ts->next;
1227 ts->next = NULL;
1229 /* run the callback (the timer list can be modified) */
1230 ts->cb(ts->opaque);
1234 int64_t qemu_get_clock(QEMUClock *clock)
1236 switch(clock->type) {
1237 case QEMU_TIMER_REALTIME:
1238 return get_clock() / 1000000;
1239 default:
1240 case QEMU_TIMER_VIRTUAL:
1241 if (use_icount) {
1242 return cpu_get_icount();
1243 } else {
1244 return cpu_get_clock();
1249 static void init_timers(void)
1251 init_get_clock();
1252 ticks_per_sec = QEMU_TIMER_BASE;
1253 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1254 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1257 /* save a timer */
1258 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1260 uint64_t expire_time;
1262 if (qemu_timer_pending(ts)) {
1263 expire_time = ts->expire_time;
1264 } else {
1265 expire_time = -1;
1267 qemu_put_be64(f, expire_time);
1270 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1272 uint64_t expire_time;
1274 expire_time = qemu_get_be64(f);
1275 if (expire_time != -1) {
1276 qemu_mod_timer(ts, expire_time);
1277 } else {
1278 qemu_del_timer(ts);
1282 static void timer_save(QEMUFile *f, void *opaque)
1284 if (cpu_ticks_enabled) {
1285 hw_error("cannot save state if virtual timers are running");
1287 qemu_put_be64(f, cpu_ticks_offset);
1288 qemu_put_be64(f, ticks_per_sec);
1289 qemu_put_be64(f, cpu_clock_offset);
1292 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1294 if (version_id != 1 && version_id != 2)
1295 return -EINVAL;
1296 if (cpu_ticks_enabled) {
1297 return -EINVAL;
1299 cpu_ticks_offset=qemu_get_be64(f);
1300 ticks_per_sec=qemu_get_be64(f);
1301 if (version_id == 2) {
1302 cpu_clock_offset=qemu_get_be64(f);
1304 return 0;
1307 static void qemu_event_increment(void);
1309 #ifdef _WIN32
1310 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1311 DWORD_PTR dwUser, DWORD_PTR dw1,
1312 DWORD_PTR dw2)
1313 #else
1314 static void host_alarm_handler(int host_signum)
1315 #endif
1317 #if 0
1318 #define DISP_FREQ 1000
1320 static int64_t delta_min = INT64_MAX;
1321 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1322 static int count;
1323 ti = qemu_get_clock(vm_clock);
1324 if (last_clock != 0) {
1325 delta = ti - last_clock;
1326 if (delta < delta_min)
1327 delta_min = delta;
1328 if (delta > delta_max)
1329 delta_max = delta;
1330 delta_cum += delta;
1331 if (++count == DISP_FREQ) {
1332 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1333 muldiv64(delta_min, 1000000, ticks_per_sec),
1334 muldiv64(delta_max, 1000000, ticks_per_sec),
1335 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1336 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1337 count = 0;
1338 delta_min = INT64_MAX;
1339 delta_max = 0;
1340 delta_cum = 0;
1343 last_clock = ti;
1345 #endif
1346 if (alarm_has_dynticks(alarm_timer) ||
1347 (!use_icount &&
1348 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1349 qemu_get_clock(vm_clock))) ||
1350 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1351 qemu_get_clock(rt_clock))) {
1352 qemu_event_increment();
1353 if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1355 #ifndef CONFIG_IOTHREAD
1356 if (next_cpu) {
1357 /* stop the currently executing cpu because a timer occured */
1358 cpu_exit(next_cpu);
1359 #ifdef CONFIG_KQEMU
1360 if (next_cpu->kqemu_enabled) {
1361 kqemu_cpu_interrupt(next_cpu);
1363 #endif
1365 #endif
1366 timer_alarm_pending = 1;
1367 qemu_notify_event();
1371 static int64_t qemu_next_deadline(void)
1373 int64_t delta;
1375 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1376 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1377 qemu_get_clock(vm_clock);
1378 } else {
1379 /* To avoid problems with overflow limit this to 2^32. */
1380 delta = INT32_MAX;
1383 if (delta < 0)
1384 delta = 0;
1386 return delta;
1389 #if defined(__linux__) || defined(_WIN32)
1390 static uint64_t qemu_next_deadline_dyntick(void)
1392 int64_t delta;
1393 int64_t rtdelta;
1395 if (use_icount)
1396 delta = INT32_MAX;
1397 else
1398 delta = (qemu_next_deadline() + 999) / 1000;
1400 if (active_timers[QEMU_TIMER_REALTIME]) {
1401 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1402 qemu_get_clock(rt_clock))*1000;
1403 if (rtdelta < delta)
1404 delta = rtdelta;
1407 if (delta < MIN_TIMER_REARM_US)
1408 delta = MIN_TIMER_REARM_US;
1410 return delta;
1412 #endif
1414 #ifndef _WIN32
1416 /* Sets a specific flag */
1417 static int fcntl_setfl(int fd, int flag)
1419 int flags;
1421 flags = fcntl(fd, F_GETFL);
1422 if (flags == -1)
1423 return -errno;
1425 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1426 return -errno;
1428 return 0;
1431 #if defined(__linux__)
1433 #define RTC_FREQ 1024
1435 static void enable_sigio_timer(int fd)
1437 struct sigaction act;
1439 /* timer signal */
1440 sigfillset(&act.sa_mask);
1441 act.sa_flags = 0;
1442 act.sa_handler = host_alarm_handler;
1444 sigaction(SIGIO, &act, NULL);
1445 fcntl_setfl(fd, O_ASYNC);
1446 fcntl(fd, F_SETOWN, getpid());
1449 static int hpet_start_timer(struct qemu_alarm_timer *t)
1451 struct hpet_info info;
1452 int r, fd;
1454 fd = open("/dev/hpet", O_RDONLY);
1455 if (fd < 0)
1456 return -1;
1458 /* Set frequency */
1459 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1460 if (r < 0) {
1461 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1462 "error, but for better emulation accuracy type:\n"
1463 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1464 goto fail;
1467 /* Check capabilities */
1468 r = ioctl(fd, HPET_INFO, &info);
1469 if (r < 0)
1470 goto fail;
1472 /* Enable periodic mode */
1473 r = ioctl(fd, HPET_EPI, 0);
1474 if (info.hi_flags && (r < 0))
1475 goto fail;
1477 /* Enable interrupt */
1478 r = ioctl(fd, HPET_IE_ON, 0);
1479 if (r < 0)
1480 goto fail;
1482 enable_sigio_timer(fd);
1483 t->priv = (void *)(long)fd;
1485 return 0;
1486 fail:
1487 close(fd);
1488 return -1;
1491 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1493 int fd = (long)t->priv;
1495 close(fd);
1498 static int rtc_start_timer(struct qemu_alarm_timer *t)
1500 int rtc_fd;
1501 unsigned long current_rtc_freq = 0;
1503 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1504 if (rtc_fd < 0)
1505 return -1;
1506 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1507 if (current_rtc_freq != RTC_FREQ &&
1508 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1509 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1510 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1511 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1512 goto fail;
1514 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1515 fail:
1516 close(rtc_fd);
1517 return -1;
1520 enable_sigio_timer(rtc_fd);
1522 t->priv = (void *)(long)rtc_fd;
1524 return 0;
1527 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1529 int rtc_fd = (long)t->priv;
1531 close(rtc_fd);
1534 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1536 struct sigevent ev;
1537 timer_t host_timer;
1538 struct sigaction act;
1540 sigfillset(&act.sa_mask);
1541 act.sa_flags = 0;
1542 act.sa_handler = host_alarm_handler;
1544 sigaction(SIGALRM, &act, NULL);
1547 * Initialize ev struct to 0 to avoid valgrind complaining
1548 * about uninitialized data in timer_create call
1550 memset(&ev, 0, sizeof(ev));
1551 ev.sigev_value.sival_int = 0;
1552 ev.sigev_notify = SIGEV_SIGNAL;
1553 ev.sigev_signo = SIGALRM;
1555 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1556 perror("timer_create");
1558 /* disable dynticks */
1559 fprintf(stderr, "Dynamic Ticks disabled\n");
1561 return -1;
1564 t->priv = (void *)(long)host_timer;
1566 return 0;
1569 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1571 timer_t host_timer = (timer_t)(long)t->priv;
1573 timer_delete(host_timer);
1576 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1578 timer_t host_timer = (timer_t)(long)t->priv;
1579 struct itimerspec timeout;
1580 int64_t nearest_delta_us = INT64_MAX;
1581 int64_t current_us;
1583 if (!active_timers[QEMU_TIMER_REALTIME] &&
1584 !active_timers[QEMU_TIMER_VIRTUAL])
1585 return;
1587 nearest_delta_us = qemu_next_deadline_dyntick();
1589 /* check whether a timer is already running */
1590 if (timer_gettime(host_timer, &timeout)) {
1591 perror("gettime");
1592 fprintf(stderr, "Internal timer error: aborting\n");
1593 exit(1);
1595 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1596 if (current_us && current_us <= nearest_delta_us)
1597 return;
1599 timeout.it_interval.tv_sec = 0;
1600 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1601 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1602 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1603 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1604 perror("settime");
1605 fprintf(stderr, "Internal timer error: aborting\n");
1606 exit(1);
1610 #endif /* defined(__linux__) */
1612 static int unix_start_timer(struct qemu_alarm_timer *t)
1614 struct sigaction act;
1615 struct itimerval itv;
1616 int err;
1618 /* timer signal */
1619 sigfillset(&act.sa_mask);
1620 act.sa_flags = 0;
1621 act.sa_handler = host_alarm_handler;
1623 sigaction(SIGALRM, &act, NULL);
1625 itv.it_interval.tv_sec = 0;
1626 /* for i386 kernel 2.6 to get 1 ms */
1627 itv.it_interval.tv_usec = 999;
1628 itv.it_value.tv_sec = 0;
1629 itv.it_value.tv_usec = 10 * 1000;
1631 err = setitimer(ITIMER_REAL, &itv, NULL);
1632 if (err)
1633 return -1;
1635 return 0;
1638 static void unix_stop_timer(struct qemu_alarm_timer *t)
1640 struct itimerval itv;
1642 memset(&itv, 0, sizeof(itv));
1643 setitimer(ITIMER_REAL, &itv, NULL);
1646 #endif /* !defined(_WIN32) */
1649 #ifdef _WIN32
1651 static int win32_start_timer(struct qemu_alarm_timer *t)
1653 TIMECAPS tc;
1654 struct qemu_alarm_win32 *data = t->priv;
1655 UINT flags;
1657 memset(&tc, 0, sizeof(tc));
1658 timeGetDevCaps(&tc, sizeof(tc));
1660 if (data->period < tc.wPeriodMin)
1661 data->period = tc.wPeriodMin;
1663 timeBeginPeriod(data->period);
1665 flags = TIME_CALLBACK_FUNCTION;
1666 if (alarm_has_dynticks(t))
1667 flags |= TIME_ONESHOT;
1668 else
1669 flags |= TIME_PERIODIC;
1671 data->timerId = timeSetEvent(1, // interval (ms)
1672 data->period, // resolution
1673 host_alarm_handler, // function
1674 (DWORD)t, // parameter
1675 flags);
1677 if (!data->timerId) {
1678 perror("Failed to initialize win32 alarm timer");
1679 timeEndPeriod(data->period);
1680 return -1;
1683 return 0;
1686 static void win32_stop_timer(struct qemu_alarm_timer *t)
1688 struct qemu_alarm_win32 *data = t->priv;
1690 timeKillEvent(data->timerId);
1691 timeEndPeriod(data->period);
1694 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1696 struct qemu_alarm_win32 *data = t->priv;
1697 uint64_t nearest_delta_us;
1699 if (!active_timers[QEMU_TIMER_REALTIME] &&
1700 !active_timers[QEMU_TIMER_VIRTUAL])
1701 return;
1703 nearest_delta_us = qemu_next_deadline_dyntick();
1704 nearest_delta_us /= 1000;
1706 timeKillEvent(data->timerId);
1708 data->timerId = timeSetEvent(1,
1709 data->period,
1710 host_alarm_handler,
1711 (DWORD)t,
1712 TIME_ONESHOT | TIME_PERIODIC);
1714 if (!data->timerId) {
1715 perror("Failed to re-arm win32 alarm timer");
1717 timeEndPeriod(data->period);
1718 exit(1);
1722 #endif /* _WIN32 */
1724 static int init_timer_alarm(void)
1726 struct qemu_alarm_timer *t = NULL;
1727 int i, err = -1;
1729 for (i = 0; alarm_timers[i].name; i++) {
1730 t = &alarm_timers[i];
1732 err = t->start(t);
1733 if (!err)
1734 break;
1737 if (err) {
1738 err = -ENOENT;
1739 goto fail;
1742 alarm_timer = t;
1744 return 0;
1746 fail:
1747 return err;
1750 static void quit_timers(void)
1752 alarm_timer->stop(alarm_timer);
1753 alarm_timer = NULL;
1756 /***********************************************************/
1757 /* host time/date access */
1758 void qemu_get_timedate(struct tm *tm, int offset)
1760 time_t ti;
1761 struct tm *ret;
1763 time(&ti);
1764 ti += offset;
1765 if (rtc_date_offset == -1) {
1766 if (rtc_utc)
1767 ret = gmtime(&ti);
1768 else
1769 ret = localtime(&ti);
1770 } else {
1771 ti -= rtc_date_offset;
1772 ret = gmtime(&ti);
1775 memcpy(tm, ret, sizeof(struct tm));
1778 int qemu_timedate_diff(struct tm *tm)
1780 time_t seconds;
1782 if (rtc_date_offset == -1)
1783 if (rtc_utc)
1784 seconds = mktimegm(tm);
1785 else
1786 seconds = mktime(tm);
1787 else
1788 seconds = mktimegm(tm) + rtc_date_offset;
1790 return seconds - time(NULL);
1793 #ifdef _WIN32
1794 static void socket_cleanup(void)
1796 WSACleanup();
1799 static int socket_init(void)
1801 WSADATA Data;
1802 int ret, err;
1804 ret = WSAStartup(MAKEWORD(2,2), &Data);
1805 if (ret != 0) {
1806 err = WSAGetLastError();
1807 fprintf(stderr, "WSAStartup: %d\n", err);
1808 return -1;
1810 atexit(socket_cleanup);
1811 return 0;
1813 #endif
1815 int get_next_param_value(char *buf, int buf_size,
1816 const char *tag, const char **pstr)
1818 const char *p;
1819 char option[128];
1821 p = *pstr;
1822 for(;;) {
1823 p = get_opt_name(option, sizeof(option), p, '=');
1824 if (*p != '=')
1825 break;
1826 p++;
1827 if (!strcmp(tag, option)) {
1828 *pstr = get_opt_value(buf, buf_size, p);
1829 if (**pstr == ',') {
1830 (*pstr)++;
1832 return strlen(buf);
1833 } else {
1834 p = get_opt_value(NULL, 0, p);
1836 if (*p != ',')
1837 break;
1838 p++;
1840 return 0;
1843 int get_param_value(char *buf, int buf_size,
1844 const char *tag, const char *str)
1846 return get_next_param_value(buf, buf_size, tag, &str);
1849 int check_params(char *buf, int buf_size,
1850 const char * const *params, const char *str)
1852 const char *p;
1853 int i;
1855 p = str;
1856 while (*p != '\0') {
1857 p = get_opt_name(buf, buf_size, p, '=');
1858 if (*p != '=') {
1859 return -1;
1861 p++;
1862 for (i = 0; params[i] != NULL; i++) {
1863 if (!strcmp(params[i], buf)) {
1864 break;
1867 if (params[i] == NULL) {
1868 return -1;
1870 p = get_opt_value(NULL, 0, p);
1871 if (*p != ',') {
1872 break;
1874 p++;
1876 return 0;
1879 /***********************************************************/
1880 /* Bluetooth support */
1881 static int nb_hcis;
1882 static int cur_hci;
1883 static struct HCIInfo *hci_table[MAX_NICS];
1885 static struct bt_vlan_s {
1886 struct bt_scatternet_s net;
1887 int id;
1888 struct bt_vlan_s *next;
1889 } *first_bt_vlan;
1891 /* find or alloc a new bluetooth "VLAN" */
1892 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1894 struct bt_vlan_s **pvlan, *vlan;
1895 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1896 if (vlan->id == id)
1897 return &vlan->net;
1899 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1900 vlan->id = id;
1901 pvlan = &first_bt_vlan;
1902 while (*pvlan != NULL)
1903 pvlan = &(*pvlan)->next;
1904 *pvlan = vlan;
1905 return &vlan->net;
1908 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1912 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1914 return -ENOTSUP;
1917 static struct HCIInfo null_hci = {
1918 .cmd_send = null_hci_send,
1919 .sco_send = null_hci_send,
1920 .acl_send = null_hci_send,
1921 .bdaddr_set = null_hci_addr_set,
1924 struct HCIInfo *qemu_next_hci(void)
1926 if (cur_hci == nb_hcis)
1927 return &null_hci;
1929 return hci_table[cur_hci++];
1932 static struct HCIInfo *hci_init(const char *str)
1934 char *endp;
1935 struct bt_scatternet_s *vlan = 0;
1937 if (!strcmp(str, "null"))
1938 /* null */
1939 return &null_hci;
1940 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1941 /* host[:hciN] */
1942 return bt_host_hci(str[4] ? str + 5 : "hci0");
1943 else if (!strncmp(str, "hci", 3)) {
1944 /* hci[,vlan=n] */
1945 if (str[3]) {
1946 if (!strncmp(str + 3, ",vlan=", 6)) {
1947 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1948 if (*endp)
1949 vlan = 0;
1951 } else
1952 vlan = qemu_find_bt_vlan(0);
1953 if (vlan)
1954 return bt_new_hci(vlan);
1957 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1959 return 0;
1962 static int bt_hci_parse(const char *str)
1964 struct HCIInfo *hci;
1965 bdaddr_t bdaddr;
1967 if (nb_hcis >= MAX_NICS) {
1968 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1969 return -1;
1972 hci = hci_init(str);
1973 if (!hci)
1974 return -1;
1976 bdaddr.b[0] = 0x52;
1977 bdaddr.b[1] = 0x54;
1978 bdaddr.b[2] = 0x00;
1979 bdaddr.b[3] = 0x12;
1980 bdaddr.b[4] = 0x34;
1981 bdaddr.b[5] = 0x56 + nb_hcis;
1982 hci->bdaddr_set(hci, bdaddr.b);
1984 hci_table[nb_hcis++] = hci;
1986 return 0;
1989 static void bt_vhci_add(int vlan_id)
1991 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1993 if (!vlan->slave)
1994 fprintf(stderr, "qemu: warning: adding a VHCI to "
1995 "an empty scatternet %i\n", vlan_id);
1997 bt_vhci_init(bt_new_hci(vlan));
2000 static struct bt_device_s *bt_device_add(const char *opt)
2002 struct bt_scatternet_s *vlan;
2003 int vlan_id = 0;
2004 char *endp = strstr(opt, ",vlan=");
2005 int len = (endp ? endp - opt : strlen(opt)) + 1;
2006 char devname[10];
2008 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2010 if (endp) {
2011 vlan_id = strtol(endp + 6, &endp, 0);
2012 if (*endp) {
2013 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2014 return 0;
2018 vlan = qemu_find_bt_vlan(vlan_id);
2020 if (!vlan->slave)
2021 fprintf(stderr, "qemu: warning: adding a slave device to "
2022 "an empty scatternet %i\n", vlan_id);
2024 if (!strcmp(devname, "keyboard"))
2025 return bt_keyboard_init(vlan);
2027 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2028 return 0;
2031 static int bt_parse(const char *opt)
2033 const char *endp, *p;
2034 int vlan;
2036 if (strstart(opt, "hci", &endp)) {
2037 if (!*endp || *endp == ',') {
2038 if (*endp)
2039 if (!strstart(endp, ",vlan=", 0))
2040 opt = endp + 1;
2042 return bt_hci_parse(opt);
2044 } else if (strstart(opt, "vhci", &endp)) {
2045 if (!*endp || *endp == ',') {
2046 if (*endp) {
2047 if (strstart(endp, ",vlan=", &p)) {
2048 vlan = strtol(p, (char **) &endp, 0);
2049 if (*endp) {
2050 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2051 return 1;
2053 } else {
2054 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2055 return 1;
2057 } else
2058 vlan = 0;
2060 bt_vhci_add(vlan);
2061 return 0;
2063 } else if (strstart(opt, "device:", &endp))
2064 return !bt_device_add(endp);
2066 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2067 return 1;
2070 /***********************************************************/
2071 /* QEMU Block devices */
2073 #define HD_ALIAS "index=%d,media=disk"
2074 #define CDROM_ALIAS "index=2,media=cdrom"
2075 #define FD_ALIAS "index=%d,if=floppy"
2076 #define PFLASH_ALIAS "if=pflash"
2077 #define MTD_ALIAS "if=mtd"
2078 #define SD_ALIAS "index=0,if=sd"
2080 static int drive_opt_get_free_idx(void)
2082 int index;
2084 for (index = 0; index < MAX_DRIVES; index++)
2085 if (!drives_opt[index].used) {
2086 drives_opt[index].used = 1;
2087 return index;
2090 return -1;
2093 static int drive_get_free_idx(void)
2095 int index;
2097 for (index = 0; index < MAX_DRIVES; index++)
2098 if (!drives_table[index].used) {
2099 drives_table[index].used = 1;
2100 return index;
2103 return -1;
2106 int drive_add(const char *file, const char *fmt, ...)
2108 va_list ap;
2109 int index = drive_opt_get_free_idx();
2111 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2112 fprintf(stderr, "qemu: too many drives\n");
2113 return -1;
2116 drives_opt[index].file = file;
2117 va_start(ap, fmt);
2118 vsnprintf(drives_opt[index].opt,
2119 sizeof(drives_opt[0].opt), fmt, ap);
2120 va_end(ap);
2122 nb_drives_opt++;
2123 return index;
2126 void drive_remove(int index)
2128 drives_opt[index].used = 0;
2129 nb_drives_opt--;
2132 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2134 int index;
2136 /* seek interface, bus and unit */
2138 for (index = 0; index < MAX_DRIVES; index++)
2139 if (drives_table[index].type == type &&
2140 drives_table[index].bus == bus &&
2141 drives_table[index].unit == unit &&
2142 drives_table[index].used)
2143 return index;
2145 return -1;
2148 int drive_get_max_bus(BlockInterfaceType type)
2150 int max_bus;
2151 int index;
2153 max_bus = -1;
2154 for (index = 0; index < nb_drives; index++) {
2155 if(drives_table[index].type == type &&
2156 drives_table[index].bus > max_bus)
2157 max_bus = drives_table[index].bus;
2159 return max_bus;
2162 const char *drive_get_serial(BlockDriverState *bdrv)
2164 int index;
2166 for (index = 0; index < nb_drives; index++)
2167 if (drives_table[index].bdrv == bdrv)
2168 return drives_table[index].serial;
2170 return "\0";
2173 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2175 int index;
2177 for (index = 0; index < nb_drives; index++)
2178 if (drives_table[index].bdrv == bdrv)
2179 return drives_table[index].onerror;
2181 return BLOCK_ERR_STOP_ENOSPC;
2184 static void bdrv_format_print(void *opaque, const char *name)
2186 fprintf(stderr, " %s", name);
2189 void drive_uninit(BlockDriverState *bdrv)
2191 int i;
2193 for (i = 0; i < MAX_DRIVES; i++)
2194 if (drives_table[i].bdrv == bdrv) {
2195 drives_table[i].bdrv = NULL;
2196 drives_table[i].used = 0;
2197 drive_remove(drives_table[i].drive_opt_idx);
2198 nb_drives--;
2199 break;
2203 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2205 char buf[128];
2206 char file[1024];
2207 char devname[128];
2208 char serial[21];
2209 const char *mediastr = "";
2210 BlockInterfaceType type;
2211 enum { MEDIA_DISK, MEDIA_CDROM } media;
2212 int bus_id, unit_id;
2213 int cyls, heads, secs, translation;
2214 BlockDriverState *bdrv;
2215 BlockDriver *drv = NULL;
2216 QEMUMachine *machine = opaque;
2217 int max_devs;
2218 int index;
2219 int cache;
2220 int bdrv_flags, onerror;
2221 const char *devaddr;
2222 int drives_table_idx;
2223 char *str = arg->opt;
2224 static const char * const params[] = { "bus", "unit", "if", "index",
2225 "cyls", "heads", "secs", "trans",
2226 "media", "snapshot", "file",
2227 "cache", "format", "serial",
2228 "werror", "addr",
2229 NULL };
2231 if (check_params(buf, sizeof(buf), params, str) < 0) {
2232 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2233 buf, str);
2234 return -1;
2237 file[0] = 0;
2238 cyls = heads = secs = 0;
2239 bus_id = 0;
2240 unit_id = -1;
2241 translation = BIOS_ATA_TRANSLATION_AUTO;
2242 index = -1;
2243 cache = 3;
2245 if (machine->use_scsi) {
2246 type = IF_SCSI;
2247 max_devs = MAX_SCSI_DEVS;
2248 pstrcpy(devname, sizeof(devname), "scsi");
2249 } else {
2250 type = IF_IDE;
2251 max_devs = MAX_IDE_DEVS;
2252 pstrcpy(devname, sizeof(devname), "ide");
2254 media = MEDIA_DISK;
2256 /* extract parameters */
2258 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2259 bus_id = strtol(buf, NULL, 0);
2260 if (bus_id < 0) {
2261 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2262 return -1;
2266 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2267 unit_id = strtol(buf, NULL, 0);
2268 if (unit_id < 0) {
2269 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2270 return -1;
2274 if (get_param_value(buf, sizeof(buf), "if", str)) {
2275 pstrcpy(devname, sizeof(devname), buf);
2276 if (!strcmp(buf, "ide")) {
2277 type = IF_IDE;
2278 max_devs = MAX_IDE_DEVS;
2279 } else if (!strcmp(buf, "scsi")) {
2280 type = IF_SCSI;
2281 max_devs = MAX_SCSI_DEVS;
2282 } else if (!strcmp(buf, "floppy")) {
2283 type = IF_FLOPPY;
2284 max_devs = 0;
2285 } else if (!strcmp(buf, "pflash")) {
2286 type = IF_PFLASH;
2287 max_devs = 0;
2288 } else if (!strcmp(buf, "mtd")) {
2289 type = IF_MTD;
2290 max_devs = 0;
2291 } else if (!strcmp(buf, "sd")) {
2292 type = IF_SD;
2293 max_devs = 0;
2294 } else if (!strcmp(buf, "virtio")) {
2295 type = IF_VIRTIO;
2296 max_devs = 0;
2297 } else if (!strcmp(buf, "xen")) {
2298 type = IF_XEN;
2299 max_devs = 0;
2300 } else {
2301 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2302 return -1;
2306 if (get_param_value(buf, sizeof(buf), "index", str)) {
2307 index = strtol(buf, NULL, 0);
2308 if (index < 0) {
2309 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2310 return -1;
2314 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2315 cyls = strtol(buf, NULL, 0);
2318 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2319 heads = strtol(buf, NULL, 0);
2322 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2323 secs = strtol(buf, NULL, 0);
2326 if (cyls || heads || secs) {
2327 if (cyls < 1 || cyls > 16383) {
2328 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2329 return -1;
2331 if (heads < 1 || heads > 16) {
2332 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2333 return -1;
2335 if (secs < 1 || secs > 63) {
2336 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2337 return -1;
2341 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2342 if (!cyls) {
2343 fprintf(stderr,
2344 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2345 str);
2346 return -1;
2348 if (!strcmp(buf, "none"))
2349 translation = BIOS_ATA_TRANSLATION_NONE;
2350 else if (!strcmp(buf, "lba"))
2351 translation = BIOS_ATA_TRANSLATION_LBA;
2352 else if (!strcmp(buf, "auto"))
2353 translation = BIOS_ATA_TRANSLATION_AUTO;
2354 else {
2355 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2356 return -1;
2360 if (get_param_value(buf, sizeof(buf), "media", str)) {
2361 if (!strcmp(buf, "disk")) {
2362 media = MEDIA_DISK;
2363 } else if (!strcmp(buf, "cdrom")) {
2364 if (cyls || secs || heads) {
2365 fprintf(stderr,
2366 "qemu: '%s' invalid physical CHS format\n", str);
2367 return -1;
2369 media = MEDIA_CDROM;
2370 } else {
2371 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2372 return -1;
2376 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2377 if (!strcmp(buf, "on"))
2378 snapshot = 1;
2379 else if (!strcmp(buf, "off"))
2380 snapshot = 0;
2381 else {
2382 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2383 return -1;
2387 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2388 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2389 cache = 0;
2390 else if (!strcmp(buf, "writethrough"))
2391 cache = 1;
2392 else if (!strcmp(buf, "writeback"))
2393 cache = 2;
2394 else {
2395 fprintf(stderr, "qemu: invalid cache option\n");
2396 return -1;
2400 if (get_param_value(buf, sizeof(buf), "format", str)) {
2401 if (strcmp(buf, "?") == 0) {
2402 fprintf(stderr, "qemu: Supported formats:");
2403 bdrv_iterate_format(bdrv_format_print, NULL);
2404 fprintf(stderr, "\n");
2405 return -1;
2407 drv = bdrv_find_format(buf);
2408 if (!drv) {
2409 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2410 return -1;
2414 if (arg->file == NULL)
2415 get_param_value(file, sizeof(file), "file", str);
2416 else
2417 pstrcpy(file, sizeof(file), arg->file);
2419 if (!get_param_value(serial, sizeof(serial), "serial", str))
2420 memset(serial, 0, sizeof(serial));
2422 onerror = BLOCK_ERR_STOP_ENOSPC;
2423 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2424 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2425 fprintf(stderr, "werror is no supported by this format\n");
2426 return -1;
2428 if (!strcmp(buf, "ignore"))
2429 onerror = BLOCK_ERR_IGNORE;
2430 else if (!strcmp(buf, "enospc"))
2431 onerror = BLOCK_ERR_STOP_ENOSPC;
2432 else if (!strcmp(buf, "stop"))
2433 onerror = BLOCK_ERR_STOP_ANY;
2434 else if (!strcmp(buf, "report"))
2435 onerror = BLOCK_ERR_REPORT;
2436 else {
2437 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2438 return -1;
2442 devaddr = NULL;
2443 if (get_param_value(buf, sizeof(buf), "addr", str)) {
2444 if (type != IF_VIRTIO) {
2445 fprintf(stderr, "addr is not supported by in '%s'\n", str);
2446 return -1;
2448 devaddr = strdup(buf);
2451 /* compute bus and unit according index */
2453 if (index != -1) {
2454 if (bus_id != 0 || unit_id != -1) {
2455 fprintf(stderr,
2456 "qemu: '%s' index cannot be used with bus and unit\n", str);
2457 return -1;
2459 if (max_devs == 0)
2461 unit_id = index;
2462 bus_id = 0;
2463 } else {
2464 unit_id = index % max_devs;
2465 bus_id = index / max_devs;
2469 /* if user doesn't specify a unit_id,
2470 * try to find the first free
2473 if (unit_id == -1) {
2474 unit_id = 0;
2475 while (drive_get_index(type, bus_id, unit_id) != -1) {
2476 unit_id++;
2477 if (max_devs && unit_id >= max_devs) {
2478 unit_id -= max_devs;
2479 bus_id++;
2484 /* check unit id */
2486 if (max_devs && unit_id >= max_devs) {
2487 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2488 str, unit_id, max_devs - 1);
2489 return -1;
2493 * ignore multiple definitions
2496 if (drive_get_index(type, bus_id, unit_id) != -1)
2497 return -2;
2499 /* init */
2501 if (type == IF_IDE || type == IF_SCSI)
2502 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2503 if (max_devs)
2504 snprintf(buf, sizeof(buf), "%s%i%s%i",
2505 devname, bus_id, mediastr, unit_id);
2506 else
2507 snprintf(buf, sizeof(buf), "%s%s%i",
2508 devname, mediastr, unit_id);
2509 bdrv = bdrv_new(buf);
2510 drives_table_idx = drive_get_free_idx();
2511 drives_table[drives_table_idx].bdrv = bdrv;
2512 drives_table[drives_table_idx].devaddr = devaddr;
2513 drives_table[drives_table_idx].type = type;
2514 drives_table[drives_table_idx].bus = bus_id;
2515 drives_table[drives_table_idx].unit = unit_id;
2516 drives_table[drives_table_idx].onerror = onerror;
2517 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2518 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2519 nb_drives++;
2521 switch(type) {
2522 case IF_IDE:
2523 case IF_SCSI:
2524 case IF_XEN:
2525 switch(media) {
2526 case MEDIA_DISK:
2527 if (cyls != 0) {
2528 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2529 bdrv_set_translation_hint(bdrv, translation);
2531 break;
2532 case MEDIA_CDROM:
2533 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2534 break;
2536 break;
2537 case IF_SD:
2538 /* FIXME: This isn't really a floppy, but it's a reasonable
2539 approximation. */
2540 case IF_FLOPPY:
2541 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2542 break;
2543 case IF_PFLASH:
2544 case IF_MTD:
2545 case IF_VIRTIO:
2546 break;
2547 case IF_COUNT:
2548 abort();
2550 if (!file[0])
2551 return -2;
2552 bdrv_flags = 0;
2553 if (snapshot) {
2554 bdrv_flags |= BDRV_O_SNAPSHOT;
2555 cache = 2; /* always use write-back with snapshot */
2557 if (cache == 0) /* no caching */
2558 bdrv_flags |= BDRV_O_NOCACHE;
2559 else if (cache == 2) /* write-back */
2560 bdrv_flags |= BDRV_O_CACHE_WB;
2561 else if (cache == 3) /* not specified */
2562 bdrv_flags |= BDRV_O_CACHE_DEF;
2563 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2564 fprintf(stderr, "qemu: could not open disk image %s\n",
2565 file);
2566 return -1;
2568 if (bdrv_key_required(bdrv))
2569 autostart = 0;
2570 return drives_table_idx;
2573 static void numa_add(const char *optarg)
2575 char option[128];
2576 char *endptr;
2577 unsigned long long value, endvalue;
2578 int nodenr;
2580 optarg = get_opt_name(option, 128, optarg, ',') + 1;
2581 if (!strcmp(option, "node")) {
2582 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2583 nodenr = nb_numa_nodes;
2584 } else {
2585 nodenr = strtoull(option, NULL, 10);
2588 if (get_param_value(option, 128, "mem", optarg) == 0) {
2589 node_mem[nodenr] = 0;
2590 } else {
2591 value = strtoull(option, &endptr, 0);
2592 switch (*endptr) {
2593 case 0: case 'M': case 'm':
2594 value <<= 20;
2595 break;
2596 case 'G': case 'g':
2597 value <<= 30;
2598 break;
2600 node_mem[nodenr] = value;
2602 if (get_param_value(option, 128, "cpus", optarg) == 0) {
2603 node_cpumask[nodenr] = 0;
2604 } else {
2605 value = strtoull(option, &endptr, 10);
2606 if (value >= 64) {
2607 value = 63;
2608 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2609 } else {
2610 if (*endptr == '-') {
2611 endvalue = strtoull(endptr+1, &endptr, 10);
2612 if (endvalue >= 63) {
2613 endvalue = 62;
2614 fprintf(stderr,
2615 "only 63 CPUs in NUMA mode supported.\n");
2617 value = (1 << (endvalue + 1)) - (1 << value);
2618 } else {
2619 value = 1 << value;
2622 node_cpumask[nodenr] = value;
2624 nb_numa_nodes++;
2626 return;
2629 /***********************************************************/
2630 /* USB devices */
2632 static USBPort *used_usb_ports;
2633 static USBPort *free_usb_ports;
2635 /* ??? Maybe change this to register a hub to keep track of the topology. */
2636 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2637 usb_attachfn attach)
2639 port->opaque = opaque;
2640 port->index = index;
2641 port->attach = attach;
2642 port->next = free_usb_ports;
2643 free_usb_ports = port;
2646 int usb_device_add_dev(USBDevice *dev)
2648 USBPort *port;
2650 /* Find a USB port to add the device to. */
2651 port = free_usb_ports;
2652 if (!port->next) {
2653 USBDevice *hub;
2655 /* Create a new hub and chain it on. */
2656 free_usb_ports = NULL;
2657 port->next = used_usb_ports;
2658 used_usb_ports = port;
2660 hub = usb_hub_init(VM_USB_HUB_SIZE);
2661 usb_attach(port, hub);
2662 port = free_usb_ports;
2665 free_usb_ports = port->next;
2666 port->next = used_usb_ports;
2667 used_usb_ports = port;
2668 usb_attach(port, dev);
2669 return 0;
2672 static void usb_msd_password_cb(void *opaque, int err)
2674 USBDevice *dev = opaque;
2676 if (!err)
2677 usb_device_add_dev(dev);
2678 else
2679 dev->handle_destroy(dev);
2682 static int usb_device_add(const char *devname, int is_hotplug)
2684 const char *p;
2685 USBDevice *dev;
2687 if (!free_usb_ports)
2688 return -1;
2690 if (strstart(devname, "host:", &p)) {
2691 dev = usb_host_device_open(p);
2692 } else if (!strcmp(devname, "mouse")) {
2693 dev = usb_mouse_init();
2694 } else if (!strcmp(devname, "tablet")) {
2695 dev = usb_tablet_init();
2696 } else if (!strcmp(devname, "keyboard")) {
2697 dev = usb_keyboard_init();
2698 } else if (strstart(devname, "disk:", &p)) {
2699 BlockDriverState *bs;
2701 dev = usb_msd_init(p);
2702 if (!dev)
2703 return -1;
2704 bs = usb_msd_get_bdrv(dev);
2705 if (bdrv_key_required(bs)) {
2706 autostart = 0;
2707 if (is_hotplug) {
2708 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2709 dev);
2710 return 0;
2713 } else if (!strcmp(devname, "wacom-tablet")) {
2714 dev = usb_wacom_init();
2715 } else if (strstart(devname, "serial:", &p)) {
2716 dev = usb_serial_init(p);
2717 #ifdef CONFIG_BRLAPI
2718 } else if (!strcmp(devname, "braille")) {
2719 dev = usb_baum_init();
2720 #endif
2721 } else if (strstart(devname, "net:", &p)) {
2722 int nic = nb_nics;
2724 if (net_client_init(NULL, "nic", p) < 0)
2725 return -1;
2726 nd_table[nic].model = "usb";
2727 dev = usb_net_init(&nd_table[nic]);
2728 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2729 dev = usb_bt_init(devname[2] ? hci_init(p) :
2730 bt_new_hci(qemu_find_bt_vlan(0)));
2731 } else {
2732 return -1;
2734 if (!dev)
2735 return -1;
2737 return usb_device_add_dev(dev);
2740 int usb_device_del_addr(int bus_num, int addr)
2742 USBPort *port;
2743 USBPort **lastp;
2744 USBDevice *dev;
2746 if (!used_usb_ports)
2747 return -1;
2749 if (bus_num != 0)
2750 return -1;
2752 lastp = &used_usb_ports;
2753 port = used_usb_ports;
2754 while (port && port->dev->addr != addr) {
2755 lastp = &port->next;
2756 port = port->next;
2759 if (!port)
2760 return -1;
2762 dev = port->dev;
2763 *lastp = port->next;
2764 usb_attach(port, NULL);
2765 dev->handle_destroy(dev);
2766 port->next = free_usb_ports;
2767 free_usb_ports = port;
2768 return 0;
2771 static int usb_device_del(const char *devname)
2773 int bus_num, addr;
2774 const char *p;
2776 if (strstart(devname, "host:", &p))
2777 return usb_host_device_close(p);
2779 if (!used_usb_ports)
2780 return -1;
2782 p = strchr(devname, '.');
2783 if (!p)
2784 return -1;
2785 bus_num = strtoul(devname, NULL, 0);
2786 addr = strtoul(p + 1, NULL, 0);
2788 return usb_device_del_addr(bus_num, addr);
2791 void do_usb_add(Monitor *mon, const char *devname)
2793 usb_device_add(devname, 1);
2796 void do_usb_del(Monitor *mon, const char *devname)
2798 usb_device_del(devname);
2801 void usb_info(Monitor *mon)
2803 USBDevice *dev;
2804 USBPort *port;
2805 const char *speed_str;
2807 if (!usb_enabled) {
2808 monitor_printf(mon, "USB support not enabled\n");
2809 return;
2812 for (port = used_usb_ports; port; port = port->next) {
2813 dev = port->dev;
2814 if (!dev)
2815 continue;
2816 switch(dev->speed) {
2817 case USB_SPEED_LOW:
2818 speed_str = "1.5";
2819 break;
2820 case USB_SPEED_FULL:
2821 speed_str = "12";
2822 break;
2823 case USB_SPEED_HIGH:
2824 speed_str = "480";
2825 break;
2826 default:
2827 speed_str = "?";
2828 break;
2830 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2831 0, dev->addr, speed_str, dev->devname);
2835 /***********************************************************/
2836 /* PCMCIA/Cardbus */
2838 static struct pcmcia_socket_entry_s {
2839 PCMCIASocket *socket;
2840 struct pcmcia_socket_entry_s *next;
2841 } *pcmcia_sockets = 0;
2843 void pcmcia_socket_register(PCMCIASocket *socket)
2845 struct pcmcia_socket_entry_s *entry;
2847 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2848 entry->socket = socket;
2849 entry->next = pcmcia_sockets;
2850 pcmcia_sockets = entry;
2853 void pcmcia_socket_unregister(PCMCIASocket *socket)
2855 struct pcmcia_socket_entry_s *entry, **ptr;
2857 ptr = &pcmcia_sockets;
2858 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2859 if (entry->socket == socket) {
2860 *ptr = entry->next;
2861 qemu_free(entry);
2865 void pcmcia_info(Monitor *mon)
2867 struct pcmcia_socket_entry_s *iter;
2869 if (!pcmcia_sockets)
2870 monitor_printf(mon, "No PCMCIA sockets\n");
2872 for (iter = pcmcia_sockets; iter; iter = iter->next)
2873 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2874 iter->socket->attached ? iter->socket->card_string :
2875 "Empty");
2878 /***********************************************************/
2879 /* register display */
2881 struct DisplayAllocator default_allocator = {
2882 defaultallocator_create_displaysurface,
2883 defaultallocator_resize_displaysurface,
2884 defaultallocator_free_displaysurface
2887 void register_displaystate(DisplayState *ds)
2889 DisplayState **s;
2890 s = &display_state;
2891 while (*s != NULL)
2892 s = &(*s)->next;
2893 ds->next = NULL;
2894 *s = ds;
2897 DisplayState *get_displaystate(void)
2899 return display_state;
2902 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2904 if(ds->allocator == &default_allocator) ds->allocator = da;
2905 return ds->allocator;
2908 /* dumb display */
2910 static void dumb_display_init(void)
2912 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2913 ds->allocator = &default_allocator;
2914 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2915 register_displaystate(ds);
2918 /***********************************************************/
2919 /* I/O handling */
2921 typedef struct IOHandlerRecord {
2922 int fd;
2923 IOCanRWHandler *fd_read_poll;
2924 IOHandler *fd_read;
2925 IOHandler *fd_write;
2926 int deleted;
2927 void *opaque;
2928 /* temporary data */
2929 struct pollfd *ufd;
2930 struct IOHandlerRecord *next;
2931 } IOHandlerRecord;
2933 static IOHandlerRecord *first_io_handler;
2935 /* XXX: fd_read_poll should be suppressed, but an API change is
2936 necessary in the character devices to suppress fd_can_read(). */
2937 int qemu_set_fd_handler2(int fd,
2938 IOCanRWHandler *fd_read_poll,
2939 IOHandler *fd_read,
2940 IOHandler *fd_write,
2941 void *opaque)
2943 IOHandlerRecord **pioh, *ioh;
2945 if (!fd_read && !fd_write) {
2946 pioh = &first_io_handler;
2947 for(;;) {
2948 ioh = *pioh;
2949 if (ioh == NULL)
2950 break;
2951 if (ioh->fd == fd) {
2952 ioh->deleted = 1;
2953 break;
2955 pioh = &ioh->next;
2957 } else {
2958 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2959 if (ioh->fd == fd)
2960 goto found;
2962 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2963 ioh->next = first_io_handler;
2964 first_io_handler = ioh;
2965 found:
2966 ioh->fd = fd;
2967 ioh->fd_read_poll = fd_read_poll;
2968 ioh->fd_read = fd_read;
2969 ioh->fd_write = fd_write;
2970 ioh->opaque = opaque;
2971 ioh->deleted = 0;
2973 return 0;
2976 int qemu_set_fd_handler(int fd,
2977 IOHandler *fd_read,
2978 IOHandler *fd_write,
2979 void *opaque)
2981 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2984 #ifdef _WIN32
2985 /***********************************************************/
2986 /* Polling handling */
2988 typedef struct PollingEntry {
2989 PollingFunc *func;
2990 void *opaque;
2991 struct PollingEntry *next;
2992 } PollingEntry;
2994 static PollingEntry *first_polling_entry;
2996 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2998 PollingEntry **ppe, *pe;
2999 pe = qemu_mallocz(sizeof(PollingEntry));
3000 pe->func = func;
3001 pe->opaque = opaque;
3002 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3003 *ppe = pe;
3004 return 0;
3007 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3009 PollingEntry **ppe, *pe;
3010 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3011 pe = *ppe;
3012 if (pe->func == func && pe->opaque == opaque) {
3013 *ppe = pe->next;
3014 qemu_free(pe);
3015 break;
3020 /***********************************************************/
3021 /* Wait objects support */
3022 typedef struct WaitObjects {
3023 int num;
3024 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3025 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3026 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3027 } WaitObjects;
3029 static WaitObjects wait_objects = {0};
3031 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3033 WaitObjects *w = &wait_objects;
3035 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3036 return -1;
3037 w->events[w->num] = handle;
3038 w->func[w->num] = func;
3039 w->opaque[w->num] = opaque;
3040 w->num++;
3041 return 0;
3044 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3046 int i, found;
3047 WaitObjects *w = &wait_objects;
3049 found = 0;
3050 for (i = 0; i < w->num; i++) {
3051 if (w->events[i] == handle)
3052 found = 1;
3053 if (found) {
3054 w->events[i] = w->events[i + 1];
3055 w->func[i] = w->func[i + 1];
3056 w->opaque[i] = w->opaque[i + 1];
3059 if (found)
3060 w->num--;
3062 #endif
3064 /***********************************************************/
3065 /* ram save/restore */
3067 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3069 int v;
3071 v = qemu_get_byte(f);
3072 switch(v) {
3073 case 0:
3074 if (qemu_get_buffer(f, buf, len) != len)
3075 return -EIO;
3076 break;
3077 case 1:
3078 v = qemu_get_byte(f);
3079 memset(buf, v, len);
3080 break;
3081 default:
3082 return -EINVAL;
3085 if (qemu_file_has_error(f))
3086 return -EIO;
3088 return 0;
3091 static int ram_load_v1(QEMUFile *f, void *opaque)
3093 int ret;
3094 ram_addr_t i;
3096 if (qemu_get_be32(f) != last_ram_offset)
3097 return -EINVAL;
3098 for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3099 ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3100 if (ret)
3101 return ret;
3103 return 0;
3106 #define BDRV_HASH_BLOCK_SIZE 1024
3107 #define IOBUF_SIZE 4096
3108 #define RAM_CBLOCK_MAGIC 0xfabe
3110 typedef struct RamDecompressState {
3111 z_stream zstream;
3112 QEMUFile *f;
3113 uint8_t buf[IOBUF_SIZE];
3114 } RamDecompressState;
3116 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3118 int ret;
3119 memset(s, 0, sizeof(*s));
3120 s->f = f;
3121 ret = inflateInit(&s->zstream);
3122 if (ret != Z_OK)
3123 return -1;
3124 return 0;
3127 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3129 int ret, clen;
3131 s->zstream.avail_out = len;
3132 s->zstream.next_out = buf;
3133 while (s->zstream.avail_out > 0) {
3134 if (s->zstream.avail_in == 0) {
3135 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3136 return -1;
3137 clen = qemu_get_be16(s->f);
3138 if (clen > IOBUF_SIZE)
3139 return -1;
3140 qemu_get_buffer(s->f, s->buf, clen);
3141 s->zstream.avail_in = clen;
3142 s->zstream.next_in = s->buf;
3144 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3145 if (ret != Z_OK && ret != Z_STREAM_END) {
3146 return -1;
3149 return 0;
3152 static void ram_decompress_close(RamDecompressState *s)
3154 inflateEnd(&s->zstream);
3157 #define RAM_SAVE_FLAG_FULL 0x01
3158 #define RAM_SAVE_FLAG_COMPRESS 0x02
3159 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3160 #define RAM_SAVE_FLAG_PAGE 0x08
3161 #define RAM_SAVE_FLAG_EOS 0x10
3163 static int is_dup_page(uint8_t *page, uint8_t ch)
3165 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3166 uint32_t *array = (uint32_t *)page;
3167 int i;
3169 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3170 if (array[i] != val)
3171 return 0;
3174 return 1;
3177 static int ram_save_block(QEMUFile *f)
3179 static ram_addr_t current_addr = 0;
3180 ram_addr_t saved_addr = current_addr;
3181 ram_addr_t addr = 0;
3182 int found = 0;
3184 while (addr < last_ram_offset) {
3185 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3186 uint8_t *p;
3188 cpu_physical_memory_reset_dirty(current_addr,
3189 current_addr + TARGET_PAGE_SIZE,
3190 MIGRATION_DIRTY_FLAG);
3192 p = qemu_get_ram_ptr(current_addr);
3194 if (is_dup_page(p, *p)) {
3195 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3196 qemu_put_byte(f, *p);
3197 } else {
3198 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3199 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3202 found = 1;
3203 break;
3205 addr += TARGET_PAGE_SIZE;
3206 current_addr = (saved_addr + addr) % last_ram_offset;
3209 return found;
3212 static uint64_t bytes_transferred = 0;
3214 static ram_addr_t ram_save_remaining(void)
3216 ram_addr_t addr;
3217 ram_addr_t count = 0;
3219 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3220 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3221 count++;
3224 return count;
3227 uint64_t ram_bytes_remaining(void)
3229 return ram_save_remaining() * TARGET_PAGE_SIZE;
3232 uint64_t ram_bytes_transferred(void)
3234 return bytes_transferred;
3237 uint64_t ram_bytes_total(void)
3239 return last_ram_offset;
3242 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3244 ram_addr_t addr;
3245 uint64_t bytes_transferred_last;
3246 double bwidth = 0;
3247 uint64_t expected_time = 0;
3249 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3250 qemu_file_set_error(f);
3251 return 0;
3254 if (stage == 1) {
3255 /* Make sure all dirty bits are set */
3256 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3257 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3258 cpu_physical_memory_set_dirty(addr);
3261 /* Enable dirty memory tracking */
3262 cpu_physical_memory_set_dirty_tracking(1);
3264 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3267 bytes_transferred_last = bytes_transferred;
3268 bwidth = get_clock();
3270 while (!qemu_file_rate_limit(f)) {
3271 int ret;
3273 ret = ram_save_block(f);
3274 bytes_transferred += ret * TARGET_PAGE_SIZE;
3275 if (ret == 0) /* no more blocks */
3276 break;
3279 bwidth = get_clock() - bwidth;
3280 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3282 /* if we haven't transferred anything this round, force expected_time to a
3283 * a very high value, but without crashing */
3284 if (bwidth == 0)
3285 bwidth = 0.000001;
3287 /* try transferring iterative blocks of memory */
3289 if (stage == 3) {
3291 /* flush all remaining blocks regardless of rate limiting */
3292 while (ram_save_block(f) != 0) {
3293 bytes_transferred += TARGET_PAGE_SIZE;
3295 cpu_physical_memory_set_dirty_tracking(0);
3298 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3300 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3302 return (stage == 2) && (expected_time <= migrate_max_downtime());
3305 static int ram_load_dead(QEMUFile *f, void *opaque)
3307 RamDecompressState s1, *s = &s1;
3308 uint8_t buf[10];
3309 ram_addr_t i;
3311 if (ram_decompress_open(s, f) < 0)
3312 return -EINVAL;
3313 for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3314 if (ram_decompress_buf(s, buf, 1) < 0) {
3315 fprintf(stderr, "Error while reading ram block header\n");
3316 goto error;
3318 if (buf[0] == 0) {
3319 if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3320 BDRV_HASH_BLOCK_SIZE) < 0) {
3321 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3322 goto error;
3324 } else {
3325 error:
3326 printf("Error block header\n");
3327 return -EINVAL;
3330 ram_decompress_close(s);
3332 return 0;
3335 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3337 ram_addr_t addr;
3338 int flags;
3340 if (version_id == 1)
3341 return ram_load_v1(f, opaque);
3343 if (version_id == 2) {
3344 if (qemu_get_be32(f) != last_ram_offset)
3345 return -EINVAL;
3346 return ram_load_dead(f, opaque);
3349 if (version_id != 3)
3350 return -EINVAL;
3352 do {
3353 addr = qemu_get_be64(f);
3355 flags = addr & ~TARGET_PAGE_MASK;
3356 addr &= TARGET_PAGE_MASK;
3358 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3359 if (addr != last_ram_offset)
3360 return -EINVAL;
3363 if (flags & RAM_SAVE_FLAG_FULL) {
3364 if (ram_load_dead(f, opaque) < 0)
3365 return -EINVAL;
3368 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3369 uint8_t ch = qemu_get_byte(f);
3370 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3371 #ifndef _WIN32
3372 if (ch == 0 &&
3373 (!kvm_enabled() || kvm_has_sync_mmu())) {
3374 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3376 #endif
3377 } else if (flags & RAM_SAVE_FLAG_PAGE)
3378 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3379 } while (!(flags & RAM_SAVE_FLAG_EOS));
3381 return 0;
3384 void qemu_service_io(void)
3386 qemu_notify_event();
3389 /***********************************************************/
3390 /* bottom halves (can be seen as timers which expire ASAP) */
3392 struct QEMUBH {
3393 QEMUBHFunc *cb;
3394 void *opaque;
3395 int scheduled;
3396 int idle;
3397 int deleted;
3398 QEMUBH *next;
3401 static QEMUBH *first_bh = NULL;
3403 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3405 QEMUBH *bh;
3406 bh = qemu_mallocz(sizeof(QEMUBH));
3407 bh->cb = cb;
3408 bh->opaque = opaque;
3409 bh->next = first_bh;
3410 first_bh = bh;
3411 return bh;
3414 int qemu_bh_poll(void)
3416 QEMUBH *bh, **bhp;
3417 int ret;
3419 ret = 0;
3420 for (bh = first_bh; bh; bh = bh->next) {
3421 if (!bh->deleted && bh->scheduled) {
3422 bh->scheduled = 0;
3423 if (!bh->idle)
3424 ret = 1;
3425 bh->idle = 0;
3426 bh->cb(bh->opaque);
3430 /* remove deleted bhs */
3431 bhp = &first_bh;
3432 while (*bhp) {
3433 bh = *bhp;
3434 if (bh->deleted) {
3435 *bhp = bh->next;
3436 qemu_free(bh);
3437 } else
3438 bhp = &bh->next;
3441 return ret;
3444 void qemu_bh_schedule_idle(QEMUBH *bh)
3446 if (bh->scheduled)
3447 return;
3448 bh->scheduled = 1;
3449 bh->idle = 1;
3452 void qemu_bh_schedule(QEMUBH *bh)
3454 if (bh->scheduled)
3455 return;
3456 bh->scheduled = 1;
3457 bh->idle = 0;
3458 /* stop the currently executing CPU to execute the BH ASAP */
3459 qemu_notify_event();
3462 void qemu_bh_cancel(QEMUBH *bh)
3464 bh->scheduled = 0;
3467 void qemu_bh_delete(QEMUBH *bh)
3469 bh->scheduled = 0;
3470 bh->deleted = 1;
3473 static void qemu_bh_update_timeout(int *timeout)
3475 QEMUBH *bh;
3477 for (bh = first_bh; bh; bh = bh->next) {
3478 if (!bh->deleted && bh->scheduled) {
3479 if (bh->idle) {
3480 /* idle bottom halves will be polled at least
3481 * every 10ms */
3482 *timeout = MIN(10, *timeout);
3483 } else {
3484 /* non-idle bottom halves will be executed
3485 * immediately */
3486 *timeout = 0;
3487 break;
3493 /***********************************************************/
3494 /* machine registration */
3496 static QEMUMachine *first_machine = NULL;
3497 QEMUMachine *current_machine = NULL;
3499 int qemu_register_machine(QEMUMachine *m)
3501 QEMUMachine **pm;
3502 pm = &first_machine;
3503 while (*pm != NULL)
3504 pm = &(*pm)->next;
3505 m->next = NULL;
3506 *pm = m;
3507 return 0;
3510 static QEMUMachine *find_machine(const char *name)
3512 QEMUMachine *m;
3514 for(m = first_machine; m != NULL; m = m->next) {
3515 if (!strcmp(m->name, name))
3516 return m;
3518 return NULL;
3521 static QEMUMachine *find_default_machine(void)
3523 QEMUMachine *m;
3525 for(m = first_machine; m != NULL; m = m->next) {
3526 if (m->is_default) {
3527 return m;
3530 return NULL;
3533 /***********************************************************/
3534 /* main execution loop */
3536 static void gui_update(void *opaque)
3538 uint64_t interval = GUI_REFRESH_INTERVAL;
3539 DisplayState *ds = opaque;
3540 DisplayChangeListener *dcl = ds->listeners;
3542 dpy_refresh(ds);
3544 while (dcl != NULL) {
3545 if (dcl->gui_timer_interval &&
3546 dcl->gui_timer_interval < interval)
3547 interval = dcl->gui_timer_interval;
3548 dcl = dcl->next;
3550 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3553 static void nographic_update(void *opaque)
3555 uint64_t interval = GUI_REFRESH_INTERVAL;
3557 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3560 struct vm_change_state_entry {
3561 VMChangeStateHandler *cb;
3562 void *opaque;
3563 LIST_ENTRY (vm_change_state_entry) entries;
3566 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3568 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3569 void *opaque)
3571 VMChangeStateEntry *e;
3573 e = qemu_mallocz(sizeof (*e));
3575 e->cb = cb;
3576 e->opaque = opaque;
3577 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3578 return e;
3581 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3583 LIST_REMOVE (e, entries);
3584 qemu_free (e);
3587 static void vm_state_notify(int running, int reason)
3589 VMChangeStateEntry *e;
3591 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3592 e->cb(e->opaque, running, reason);
3596 static void resume_all_vcpus(void);
3597 static void pause_all_vcpus(void);
3599 void vm_start(void)
3601 if (!vm_running) {
3602 cpu_enable_ticks();
3603 vm_running = 1;
3604 vm_state_notify(1, 0);
3605 qemu_rearm_alarm_timer(alarm_timer);
3606 resume_all_vcpus();
3610 /* reset/shutdown handler */
3612 typedef struct QEMUResetEntry {
3613 QEMUResetHandler *func;
3614 void *opaque;
3615 int order;
3616 struct QEMUResetEntry *next;
3617 } QEMUResetEntry;
3619 static QEMUResetEntry *first_reset_entry;
3620 static int reset_requested;
3621 static int shutdown_requested;
3622 static int powerdown_requested;
3623 static int debug_requested;
3624 static int vmstop_requested;
3626 int qemu_shutdown_requested(void)
3628 int r = shutdown_requested;
3629 shutdown_requested = 0;
3630 return r;
3633 int qemu_reset_requested(void)
3635 int r = reset_requested;
3636 reset_requested = 0;
3637 return r;
3640 int qemu_powerdown_requested(void)
3642 int r = powerdown_requested;
3643 powerdown_requested = 0;
3644 return r;
3647 static int qemu_debug_requested(void)
3649 int r = debug_requested;
3650 debug_requested = 0;
3651 return r;
3654 static int qemu_vmstop_requested(void)
3656 int r = vmstop_requested;
3657 vmstop_requested = 0;
3658 return r;
3661 static void do_vm_stop(int reason)
3663 if (vm_running) {
3664 cpu_disable_ticks();
3665 vm_running = 0;
3666 pause_all_vcpus();
3667 vm_state_notify(0, reason);
3671 void qemu_register_reset(QEMUResetHandler *func, int order, void *opaque)
3673 QEMUResetEntry **pre, *re;
3675 pre = &first_reset_entry;
3676 while (*pre != NULL && (*pre)->order >= order) {
3677 pre = &(*pre)->next;
3679 re = qemu_mallocz(sizeof(QEMUResetEntry));
3680 re->func = func;
3681 re->opaque = opaque;
3682 re->order = order;
3683 re->next = NULL;
3684 *pre = re;
3687 void qemu_system_reset(void)
3689 QEMUResetEntry *re;
3691 /* reset all devices */
3692 for(re = first_reset_entry; re != NULL; re = re->next) {
3693 re->func(re->opaque);
3697 void qemu_system_reset_request(void)
3699 if (no_reboot) {
3700 shutdown_requested = 1;
3701 } else {
3702 reset_requested = 1;
3704 qemu_notify_event();
3707 void qemu_system_shutdown_request(void)
3709 shutdown_requested = 1;
3710 qemu_notify_event();
3713 void qemu_system_powerdown_request(void)
3715 powerdown_requested = 1;
3716 qemu_notify_event();
3719 #ifdef CONFIG_IOTHREAD
3720 static void qemu_system_vmstop_request(int reason)
3722 vmstop_requested = reason;
3723 qemu_notify_event();
3725 #endif
3727 #ifndef _WIN32
3728 static int io_thread_fd = -1;
3730 static void qemu_event_increment(void)
3732 static const char byte = 0;
3734 if (io_thread_fd == -1)
3735 return;
3737 write(io_thread_fd, &byte, sizeof(byte));
3740 static void qemu_event_read(void *opaque)
3742 int fd = (unsigned long)opaque;
3743 ssize_t len;
3745 /* Drain the notify pipe */
3746 do {
3747 char buffer[512];
3748 len = read(fd, buffer, sizeof(buffer));
3749 } while ((len == -1 && errno == EINTR) || len > 0);
3752 static int qemu_event_init(void)
3754 int err;
3755 int fds[2];
3757 err = pipe(fds);
3758 if (err == -1)
3759 return -errno;
3761 err = fcntl_setfl(fds[0], O_NONBLOCK);
3762 if (err < 0)
3763 goto fail;
3765 err = fcntl_setfl(fds[1], O_NONBLOCK);
3766 if (err < 0)
3767 goto fail;
3769 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3770 (void *)(unsigned long)fds[0]);
3772 io_thread_fd = fds[1];
3773 return 0;
3775 fail:
3776 close(fds[0]);
3777 close(fds[1]);
3778 return err;
3780 #else
3781 HANDLE qemu_event_handle;
3783 static void dummy_event_handler(void *opaque)
3787 static int qemu_event_init(void)
3789 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3790 if (!qemu_event_handle) {
3791 perror("Failed CreateEvent");
3792 return -1;
3794 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3795 return 0;
3798 static void qemu_event_increment(void)
3800 SetEvent(qemu_event_handle);
3802 #endif
3804 static int cpu_can_run(CPUState *env)
3806 if (env->stop)
3807 return 0;
3808 if (env->stopped)
3809 return 0;
3810 return 1;
3813 #ifndef CONFIG_IOTHREAD
3814 static int qemu_init_main_loop(void)
3816 return qemu_event_init();
3819 void qemu_init_vcpu(void *_env)
3821 CPUState *env = _env;
3823 if (kvm_enabled())
3824 kvm_init_vcpu(env);
3825 return;
3828 int qemu_cpu_self(void *env)
3830 return 1;
3833 static void resume_all_vcpus(void)
3837 static void pause_all_vcpus(void)
3841 void qemu_cpu_kick(void *env)
3843 return;
3846 void qemu_notify_event(void)
3848 CPUState *env = cpu_single_env;
3850 if (env) {
3851 cpu_exit(env);
3852 #ifdef USE_KQEMU
3853 if (env->kqemu_enabled)
3854 kqemu_cpu_interrupt(env);
3855 #endif
3859 #define qemu_mutex_lock_iothread() do { } while (0)
3860 #define qemu_mutex_unlock_iothread() do { } while (0)
3862 void vm_stop(int reason)
3864 do_vm_stop(reason);
3867 #else /* CONFIG_IOTHREAD */
3869 #include "qemu-thread.h"
3871 QemuMutex qemu_global_mutex;
3872 static QemuMutex qemu_fair_mutex;
3874 static QemuThread io_thread;
3876 static QemuThread *tcg_cpu_thread;
3877 static QemuCond *tcg_halt_cond;
3879 static int qemu_system_ready;
3880 /* cpu creation */
3881 static QemuCond qemu_cpu_cond;
3882 /* system init */
3883 static QemuCond qemu_system_cond;
3884 static QemuCond qemu_pause_cond;
3886 static void block_io_signals(void);
3887 static void unblock_io_signals(void);
3888 static int tcg_has_work(void);
3890 static int qemu_init_main_loop(void)
3892 int ret;
3894 ret = qemu_event_init();
3895 if (ret)
3896 return ret;
3898 qemu_cond_init(&qemu_pause_cond);
3899 qemu_mutex_init(&qemu_fair_mutex);
3900 qemu_mutex_init(&qemu_global_mutex);
3901 qemu_mutex_lock(&qemu_global_mutex);
3903 unblock_io_signals();
3904 qemu_thread_self(&io_thread);
3906 return 0;
3909 static void qemu_wait_io_event(CPUState *env)
3911 while (!tcg_has_work())
3912 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3914 qemu_mutex_unlock(&qemu_global_mutex);
3917 * Users of qemu_global_mutex can be starved, having no chance
3918 * to acquire it since this path will get to it first.
3919 * So use another lock to provide fairness.
3921 qemu_mutex_lock(&qemu_fair_mutex);
3922 qemu_mutex_unlock(&qemu_fair_mutex);
3924 qemu_mutex_lock(&qemu_global_mutex);
3925 if (env->stop) {
3926 env->stop = 0;
3927 env->stopped = 1;
3928 qemu_cond_signal(&qemu_pause_cond);
3932 static int qemu_cpu_exec(CPUState *env);
3934 static void *kvm_cpu_thread_fn(void *arg)
3936 CPUState *env = arg;
3938 block_io_signals();
3939 qemu_thread_self(env->thread);
3941 /* signal CPU creation */
3942 qemu_mutex_lock(&qemu_global_mutex);
3943 env->created = 1;
3944 qemu_cond_signal(&qemu_cpu_cond);
3946 /* and wait for machine initialization */
3947 while (!qemu_system_ready)
3948 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3950 while (1) {
3951 if (cpu_can_run(env))
3952 qemu_cpu_exec(env);
3953 qemu_wait_io_event(env);
3956 return NULL;
3959 static void tcg_cpu_exec(void);
3961 static void *tcg_cpu_thread_fn(void *arg)
3963 CPUState *env = arg;
3965 block_io_signals();
3966 qemu_thread_self(env->thread);
3968 /* signal CPU creation */
3969 qemu_mutex_lock(&qemu_global_mutex);
3970 for (env = first_cpu; env != NULL; env = env->next_cpu)
3971 env->created = 1;
3972 qemu_cond_signal(&qemu_cpu_cond);
3974 /* and wait for machine initialization */
3975 while (!qemu_system_ready)
3976 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3978 while (1) {
3979 tcg_cpu_exec();
3980 qemu_wait_io_event(cur_cpu);
3983 return NULL;
3986 void qemu_cpu_kick(void *_env)
3988 CPUState *env = _env;
3989 qemu_cond_broadcast(env->halt_cond);
3990 if (kvm_enabled())
3991 qemu_thread_signal(env->thread, SIGUSR1);
3994 int qemu_cpu_self(void *env)
3996 return (cpu_single_env != NULL);
3999 static void cpu_signal(int sig)
4001 if (cpu_single_env)
4002 cpu_exit(cpu_single_env);
4005 static void block_io_signals(void)
4007 sigset_t set;
4008 struct sigaction sigact;
4010 sigemptyset(&set);
4011 sigaddset(&set, SIGUSR2);
4012 sigaddset(&set, SIGIO);
4013 sigaddset(&set, SIGALRM);
4014 pthread_sigmask(SIG_BLOCK, &set, NULL);
4016 sigemptyset(&set);
4017 sigaddset(&set, SIGUSR1);
4018 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4020 memset(&sigact, 0, sizeof(sigact));
4021 sigact.sa_handler = cpu_signal;
4022 sigaction(SIGUSR1, &sigact, NULL);
4025 static void unblock_io_signals(void)
4027 sigset_t set;
4029 sigemptyset(&set);
4030 sigaddset(&set, SIGUSR2);
4031 sigaddset(&set, SIGIO);
4032 sigaddset(&set, SIGALRM);
4033 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
4035 sigemptyset(&set);
4036 sigaddset(&set, SIGUSR1);
4037 pthread_sigmask(SIG_BLOCK, &set, NULL);
4040 static void qemu_signal_lock(unsigned int msecs)
4042 qemu_mutex_lock(&qemu_fair_mutex);
4044 while (qemu_mutex_trylock(&qemu_global_mutex)) {
4045 qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
4046 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
4047 break;
4049 qemu_mutex_unlock(&qemu_fair_mutex);
4052 static void qemu_mutex_lock_iothread(void)
4054 if (kvm_enabled()) {
4055 qemu_mutex_lock(&qemu_fair_mutex);
4056 qemu_mutex_lock(&qemu_global_mutex);
4057 qemu_mutex_unlock(&qemu_fair_mutex);
4058 } else
4059 qemu_signal_lock(100);
4062 static void qemu_mutex_unlock_iothread(void)
4064 qemu_mutex_unlock(&qemu_global_mutex);
4067 static int all_vcpus_paused(void)
4069 CPUState *penv = first_cpu;
4071 while (penv) {
4072 if (!penv->stopped)
4073 return 0;
4074 penv = (CPUState *)penv->next_cpu;
4077 return 1;
4080 static void pause_all_vcpus(void)
4082 CPUState *penv = first_cpu;
4084 while (penv) {
4085 penv->stop = 1;
4086 qemu_thread_signal(penv->thread, SIGUSR1);
4087 qemu_cpu_kick(penv);
4088 penv = (CPUState *)penv->next_cpu;
4091 while (!all_vcpus_paused()) {
4092 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
4093 penv = first_cpu;
4094 while (penv) {
4095 qemu_thread_signal(penv->thread, SIGUSR1);
4096 penv = (CPUState *)penv->next_cpu;
4101 static void resume_all_vcpus(void)
4103 CPUState *penv = first_cpu;
4105 while (penv) {
4106 penv->stop = 0;
4107 penv->stopped = 0;
4108 qemu_thread_signal(penv->thread, SIGUSR1);
4109 qemu_cpu_kick(penv);
4110 penv = (CPUState *)penv->next_cpu;
4114 static void tcg_init_vcpu(void *_env)
4116 CPUState *env = _env;
4117 /* share a single thread for all cpus with TCG */
4118 if (!tcg_cpu_thread) {
4119 env->thread = qemu_mallocz(sizeof(QemuThread));
4120 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4121 qemu_cond_init(env->halt_cond);
4122 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
4123 while (env->created == 0)
4124 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4125 tcg_cpu_thread = env->thread;
4126 tcg_halt_cond = env->halt_cond;
4127 } else {
4128 env->thread = tcg_cpu_thread;
4129 env->halt_cond = tcg_halt_cond;
4133 static void kvm_start_vcpu(CPUState *env)
4135 kvm_init_vcpu(env);
4136 env->thread = qemu_mallocz(sizeof(QemuThread));
4137 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
4138 qemu_cond_init(env->halt_cond);
4139 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
4140 while (env->created == 0)
4141 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
4144 void qemu_init_vcpu(void *_env)
4146 CPUState *env = _env;
4148 if (kvm_enabled())
4149 kvm_start_vcpu(env);
4150 else
4151 tcg_init_vcpu(env);
4154 void qemu_notify_event(void)
4156 qemu_event_increment();
4159 void vm_stop(int reason)
4161 QemuThread me;
4162 qemu_thread_self(&me);
4164 if (!qemu_thread_equal(&me, &io_thread)) {
4165 qemu_system_vmstop_request(reason);
4167 * FIXME: should not return to device code in case
4168 * vm_stop() has been requested.
4170 if (cpu_single_env) {
4171 cpu_exit(cpu_single_env);
4172 cpu_single_env->stop = 1;
4174 return;
4176 do_vm_stop(reason);
4179 #endif
4182 #ifdef _WIN32
4183 static void host_main_loop_wait(int *timeout)
4185 int ret, ret2, i;
4186 PollingEntry *pe;
4189 /* XXX: need to suppress polling by better using win32 events */
4190 ret = 0;
4191 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4192 ret |= pe->func(pe->opaque);
4194 if (ret == 0) {
4195 int err;
4196 WaitObjects *w = &wait_objects;
4198 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4199 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4200 if (w->func[ret - WAIT_OBJECT_0])
4201 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4203 /* Check for additional signaled events */
4204 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4206 /* Check if event is signaled */
4207 ret2 = WaitForSingleObject(w->events[i], 0);
4208 if(ret2 == WAIT_OBJECT_0) {
4209 if (w->func[i])
4210 w->func[i](w->opaque[i]);
4211 } else if (ret2 == WAIT_TIMEOUT) {
4212 } else {
4213 err = GetLastError();
4214 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4217 } else if (ret == WAIT_TIMEOUT) {
4218 } else {
4219 err = GetLastError();
4220 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4224 *timeout = 0;
4226 #else
4227 static void host_main_loop_wait(int *timeout)
4230 #endif
4232 void main_loop_wait(int timeout)
4234 IOHandlerRecord *ioh;
4235 fd_set rfds, wfds, xfds;
4236 int ret, nfds;
4237 struct timeval tv;
4239 qemu_bh_update_timeout(&timeout);
4241 host_main_loop_wait(&timeout);
4243 /* poll any events */
4244 /* XXX: separate device handlers from system ones */
4245 nfds = -1;
4246 FD_ZERO(&rfds);
4247 FD_ZERO(&wfds);
4248 FD_ZERO(&xfds);
4249 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4250 if (ioh->deleted)
4251 continue;
4252 if (ioh->fd_read &&
4253 (!ioh->fd_read_poll ||
4254 ioh->fd_read_poll(ioh->opaque) != 0)) {
4255 FD_SET(ioh->fd, &rfds);
4256 if (ioh->fd > nfds)
4257 nfds = ioh->fd;
4259 if (ioh->fd_write) {
4260 FD_SET(ioh->fd, &wfds);
4261 if (ioh->fd > nfds)
4262 nfds = ioh->fd;
4266 tv.tv_sec = timeout / 1000;
4267 tv.tv_usec = (timeout % 1000) * 1000;
4269 #if defined(CONFIG_SLIRP)
4270 if (slirp_is_inited()) {
4271 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4273 #endif
4274 qemu_mutex_unlock_iothread();
4275 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4276 qemu_mutex_lock_iothread();
4277 if (ret > 0) {
4278 IOHandlerRecord **pioh;
4280 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4281 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4282 ioh->fd_read(ioh->opaque);
4284 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4285 ioh->fd_write(ioh->opaque);
4289 /* remove deleted IO handlers */
4290 pioh = &first_io_handler;
4291 while (*pioh) {
4292 ioh = *pioh;
4293 if (ioh->deleted) {
4294 *pioh = ioh->next;
4295 qemu_free(ioh);
4296 } else
4297 pioh = &ioh->next;
4300 #if defined(CONFIG_SLIRP)
4301 if (slirp_is_inited()) {
4302 if (ret < 0) {
4303 FD_ZERO(&rfds);
4304 FD_ZERO(&wfds);
4305 FD_ZERO(&xfds);
4307 slirp_select_poll(&rfds, &wfds, &xfds);
4309 #endif
4311 /* rearm timer, if not periodic */
4312 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4313 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4314 qemu_rearm_alarm_timer(alarm_timer);
4317 /* vm time timers */
4318 if (vm_running) {
4319 if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4320 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4321 qemu_get_clock(vm_clock));
4324 /* real time timers */
4325 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4326 qemu_get_clock(rt_clock));
4328 /* Check bottom-halves last in case any of the earlier events triggered
4329 them. */
4330 qemu_bh_poll();
4334 static int qemu_cpu_exec(CPUState *env)
4336 int ret;
4337 #ifdef CONFIG_PROFILER
4338 int64_t ti;
4339 #endif
4341 #ifdef CONFIG_PROFILER
4342 ti = profile_getclock();
4343 #endif
4344 if (use_icount) {
4345 int64_t count;
4346 int decr;
4347 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4348 env->icount_decr.u16.low = 0;
4349 env->icount_extra = 0;
4350 count = qemu_next_deadline();
4351 count = (count + (1 << icount_time_shift) - 1)
4352 >> icount_time_shift;
4353 qemu_icount += count;
4354 decr = (count > 0xffff) ? 0xffff : count;
4355 count -= decr;
4356 env->icount_decr.u16.low = decr;
4357 env->icount_extra = count;
4359 ret = cpu_exec(env);
4360 #ifdef CONFIG_PROFILER
4361 qemu_time += profile_getclock() - ti;
4362 #endif
4363 if (use_icount) {
4364 /* Fold pending instructions back into the
4365 instruction counter, and clear the interrupt flag. */
4366 qemu_icount -= (env->icount_decr.u16.low
4367 + env->icount_extra);
4368 env->icount_decr.u32 = 0;
4369 env->icount_extra = 0;
4371 return ret;
4374 static void tcg_cpu_exec(void)
4376 int ret = 0;
4378 if (next_cpu == NULL)
4379 next_cpu = first_cpu;
4380 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4381 CPUState *env = cur_cpu = next_cpu;
4383 if (!vm_running)
4384 break;
4385 if (timer_alarm_pending) {
4386 timer_alarm_pending = 0;
4387 break;
4389 if (cpu_can_run(env))
4390 ret = qemu_cpu_exec(env);
4391 if (ret == EXCP_DEBUG) {
4392 gdb_set_stop_cpu(env);
4393 debug_requested = 1;
4394 break;
4399 static int cpu_has_work(CPUState *env)
4401 if (env->stop)
4402 return 1;
4403 if (env->stopped)
4404 return 0;
4405 if (!env->halted)
4406 return 1;
4407 if (qemu_cpu_has_work(env))
4408 return 1;
4409 return 0;
4412 static int tcg_has_work(void)
4414 CPUState *env;
4416 for (env = first_cpu; env != NULL; env = env->next_cpu)
4417 if (cpu_has_work(env))
4418 return 1;
4419 return 0;
4422 static int qemu_calculate_timeout(void)
4424 #ifndef CONFIG_IOTHREAD
4425 int timeout;
4427 if (!vm_running)
4428 timeout = 5000;
4429 else if (tcg_has_work())
4430 timeout = 0;
4431 else if (!use_icount)
4432 timeout = 5000;
4433 else {
4434 /* XXX: use timeout computed from timers */
4435 int64_t add;
4436 int64_t delta;
4437 /* Advance virtual time to the next event. */
4438 if (use_icount == 1) {
4439 /* When not using an adaptive execution frequency
4440 we tend to get badly out of sync with real time,
4441 so just delay for a reasonable amount of time. */
4442 delta = 0;
4443 } else {
4444 delta = cpu_get_icount() - cpu_get_clock();
4446 if (delta > 0) {
4447 /* If virtual time is ahead of real time then just
4448 wait for IO. */
4449 timeout = (delta / 1000000) + 1;
4450 } else {
4451 /* Wait for either IO to occur or the next
4452 timer event. */
4453 add = qemu_next_deadline();
4454 /* We advance the timer before checking for IO.
4455 Limit the amount we advance so that early IO
4456 activity won't get the guest too far ahead. */
4457 if (add > 10000000)
4458 add = 10000000;
4459 delta += add;
4460 add = (add + (1 << icount_time_shift) - 1)
4461 >> icount_time_shift;
4462 qemu_icount += add;
4463 timeout = delta / 1000000;
4464 if (timeout < 0)
4465 timeout = 0;
4469 return timeout;
4470 #else /* CONFIG_IOTHREAD */
4471 return 1000;
4472 #endif
4475 static int vm_can_run(void)
4477 if (powerdown_requested)
4478 return 0;
4479 if (reset_requested)
4480 return 0;
4481 if (shutdown_requested)
4482 return 0;
4483 if (debug_requested)
4484 return 0;
4485 return 1;
4488 static void main_loop(void)
4490 int r;
4492 #ifdef CONFIG_IOTHREAD
4493 qemu_system_ready = 1;
4494 qemu_cond_broadcast(&qemu_system_cond);
4495 #endif
4497 for (;;) {
4498 do {
4499 #ifdef CONFIG_PROFILER
4500 int64_t ti;
4501 #endif
4502 #ifndef CONFIG_IOTHREAD
4503 tcg_cpu_exec();
4504 #endif
4505 #ifdef CONFIG_PROFILER
4506 ti = profile_getclock();
4507 #endif
4508 main_loop_wait(qemu_calculate_timeout());
4509 #ifdef CONFIG_PROFILER
4510 dev_time += profile_getclock() - ti;
4511 #endif
4512 } while (vm_can_run());
4514 if (qemu_debug_requested())
4515 vm_stop(EXCP_DEBUG);
4516 if (qemu_shutdown_requested()) {
4517 if (no_shutdown) {
4518 vm_stop(0);
4519 no_shutdown = 0;
4520 } else
4521 break;
4523 if (qemu_reset_requested()) {
4524 pause_all_vcpus();
4525 qemu_system_reset();
4526 resume_all_vcpus();
4528 if (qemu_powerdown_requested())
4529 qemu_system_powerdown();
4530 if ((r = qemu_vmstop_requested()))
4531 vm_stop(r);
4533 pause_all_vcpus();
4536 static void version(void)
4538 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4541 static void help(int exitcode)
4543 version();
4544 printf("usage: %s [options] [disk_image]\n"
4545 "\n"
4546 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4547 "\n"
4548 #define DEF(option, opt_arg, opt_enum, opt_help) \
4549 opt_help
4550 #define DEFHEADING(text) stringify(text) "\n"
4551 #include "qemu-options.h"
4552 #undef DEF
4553 #undef DEFHEADING
4554 #undef GEN_DOCS
4555 "\n"
4556 "During emulation, the following keys are useful:\n"
4557 "ctrl-alt-f toggle full screen\n"
4558 "ctrl-alt-n switch to virtual console 'n'\n"
4559 "ctrl-alt toggle mouse and keyboard grab\n"
4560 "\n"
4561 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4563 "qemu",
4564 DEFAULT_RAM_SIZE,
4565 #ifndef _WIN32
4566 DEFAULT_NETWORK_SCRIPT,
4567 DEFAULT_NETWORK_DOWN_SCRIPT,
4568 #endif
4569 DEFAULT_GDBSTUB_PORT,
4570 "/tmp/qemu.log");
4571 exit(exitcode);
4574 #define HAS_ARG 0x0001
4576 enum {
4577 #define DEF(option, opt_arg, opt_enum, opt_help) \
4578 opt_enum,
4579 #define DEFHEADING(text)
4580 #include "qemu-options.h"
4581 #undef DEF
4582 #undef DEFHEADING
4583 #undef GEN_DOCS
4586 typedef struct QEMUOption {
4587 const char *name;
4588 int flags;
4589 int index;
4590 } QEMUOption;
4592 static const QEMUOption qemu_options[] = {
4593 { "h", 0, QEMU_OPTION_h },
4594 #define DEF(option, opt_arg, opt_enum, opt_help) \
4595 { option, opt_arg, opt_enum },
4596 #define DEFHEADING(text)
4597 #include "qemu-options.h"
4598 #undef DEF
4599 #undef DEFHEADING
4600 #undef GEN_DOCS
4601 { NULL },
4604 #ifdef HAS_AUDIO
4605 struct soundhw soundhw[] = {
4606 #ifdef HAS_AUDIO_CHOICE
4607 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4609 "pcspk",
4610 "PC speaker",
4613 { .init_isa = pcspk_audio_init }
4615 #endif
4617 #ifdef CONFIG_SB16
4619 "sb16",
4620 "Creative Sound Blaster 16",
4623 { .init_isa = SB16_init }
4625 #endif
4627 #ifdef CONFIG_CS4231A
4629 "cs4231a",
4630 "CS4231A",
4633 { .init_isa = cs4231a_init }
4635 #endif
4637 #ifdef CONFIG_ADLIB
4639 "adlib",
4640 #ifdef HAS_YMF262
4641 "Yamaha YMF262 (OPL3)",
4642 #else
4643 "Yamaha YM3812 (OPL2)",
4644 #endif
4647 { .init_isa = Adlib_init }
4649 #endif
4651 #ifdef CONFIG_GUS
4653 "gus",
4654 "Gravis Ultrasound GF1",
4657 { .init_isa = GUS_init }
4659 #endif
4661 #ifdef CONFIG_AC97
4663 "ac97",
4664 "Intel 82801AA AC97 Audio",
4667 { .init_pci = ac97_init }
4669 #endif
4671 #ifdef CONFIG_ES1370
4673 "es1370",
4674 "ENSONIQ AudioPCI ES1370",
4677 { .init_pci = es1370_init }
4679 #endif
4681 #endif /* HAS_AUDIO_CHOICE */
4683 { NULL, NULL, 0, 0, { NULL } }
4686 static void select_soundhw (const char *optarg)
4688 struct soundhw *c;
4690 if (*optarg == '?') {
4691 show_valid_cards:
4693 printf ("Valid sound card names (comma separated):\n");
4694 for (c = soundhw; c->name; ++c) {
4695 printf ("%-11s %s\n", c->name, c->descr);
4697 printf ("\n-soundhw all will enable all of the above\n");
4698 exit (*optarg != '?');
4700 else {
4701 size_t l;
4702 const char *p;
4703 char *e;
4704 int bad_card = 0;
4706 if (!strcmp (optarg, "all")) {
4707 for (c = soundhw; c->name; ++c) {
4708 c->enabled = 1;
4710 return;
4713 p = optarg;
4714 while (*p) {
4715 e = strchr (p, ',');
4716 l = !e ? strlen (p) : (size_t) (e - p);
4718 for (c = soundhw; c->name; ++c) {
4719 if (!strncmp (c->name, p, l)) {
4720 c->enabled = 1;
4721 break;
4725 if (!c->name) {
4726 if (l > 80) {
4727 fprintf (stderr,
4728 "Unknown sound card name (too big to show)\n");
4730 else {
4731 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4732 (int) l, p);
4734 bad_card = 1;
4736 p += l + (e != NULL);
4739 if (bad_card)
4740 goto show_valid_cards;
4743 #endif
4745 static void select_vgahw (const char *p)
4747 const char *opts;
4749 cirrus_vga_enabled = 0;
4750 std_vga_enabled = 0;
4751 vmsvga_enabled = 0;
4752 xenfb_enabled = 0;
4753 if (strstart(p, "std", &opts)) {
4754 std_vga_enabled = 1;
4755 } else if (strstart(p, "cirrus", &opts)) {
4756 cirrus_vga_enabled = 1;
4757 } else if (strstart(p, "vmware", &opts)) {
4758 vmsvga_enabled = 1;
4759 } else if (strstart(p, "xenfb", &opts)) {
4760 xenfb_enabled = 1;
4761 } else if (!strstart(p, "none", &opts)) {
4762 invalid_vga:
4763 fprintf(stderr, "Unknown vga type: %s\n", p);
4764 exit(1);
4766 while (*opts) {
4767 const char *nextopt;
4769 if (strstart(opts, ",retrace=", &nextopt)) {
4770 opts = nextopt;
4771 if (strstart(opts, "dumb", &nextopt))
4772 vga_retrace_method = VGA_RETRACE_DUMB;
4773 else if (strstart(opts, "precise", &nextopt))
4774 vga_retrace_method = VGA_RETRACE_PRECISE;
4775 else goto invalid_vga;
4776 } else goto invalid_vga;
4777 opts = nextopt;
4781 #ifdef _WIN32
4782 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4784 exit(STATUS_CONTROL_C_EXIT);
4785 return TRUE;
4787 #endif
4789 int qemu_uuid_parse(const char *str, uint8_t *uuid)
4791 int ret;
4793 if(strlen(str) != 36)
4794 return -1;
4796 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4797 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4798 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4800 if(ret != 16)
4801 return -1;
4803 #ifdef TARGET_I386
4804 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4805 #endif
4807 return 0;
4810 #define MAX_NET_CLIENTS 32
4812 #ifndef _WIN32
4814 static void termsig_handler(int signal)
4816 qemu_system_shutdown_request();
4819 static void sigchld_handler(int signal)
4821 waitpid(-1, NULL, WNOHANG);
4824 static void sighandler_setup(void)
4826 struct sigaction act;
4828 memset(&act, 0, sizeof(act));
4829 act.sa_handler = termsig_handler;
4830 sigaction(SIGINT, &act, NULL);
4831 sigaction(SIGHUP, &act, NULL);
4832 sigaction(SIGTERM, &act, NULL);
4834 act.sa_handler = sigchld_handler;
4835 act.sa_flags = SA_NOCLDSTOP;
4836 sigaction(SIGCHLD, &act, NULL);
4839 #endif
4841 #ifdef _WIN32
4842 /* Look for support files in the same directory as the executable. */
4843 static char *find_datadir(const char *argv0)
4845 char *p;
4846 char buf[MAX_PATH];
4847 DWORD len;
4849 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4850 if (len == 0) {
4851 return NULL;
4854 buf[len] = 0;
4855 p = buf + len - 1;
4856 while (p != buf && *p != '\\')
4857 p--;
4858 *p = 0;
4859 if (access(buf, R_OK) == 0) {
4860 return qemu_strdup(buf);
4862 return NULL;
4864 #else /* !_WIN32 */
4866 /* Find a likely location for support files using the location of the binary.
4867 For installed binaries this will be "$bindir/../share/qemu". When
4868 running from the build tree this will be "$bindir/../pc-bios". */
4869 #define SHARE_SUFFIX "/share/qemu"
4870 #define BUILD_SUFFIX "/pc-bios"
4871 static char *find_datadir(const char *argv0)
4873 char *dir;
4874 char *p = NULL;
4875 char *res;
4876 #ifdef PATH_MAX
4877 char buf[PATH_MAX];
4878 #endif
4879 size_t max_len;
4881 #if defined(__linux__)
4883 int len;
4884 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4885 if (len > 0) {
4886 buf[len] = 0;
4887 p = buf;
4890 #elif defined(__FreeBSD__)
4892 int len;
4893 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4894 if (len > 0) {
4895 buf[len] = 0;
4896 p = buf;
4899 #endif
4900 /* If we don't have any way of figuring out the actual executable
4901 location then try argv[0]. */
4902 if (!p) {
4903 #ifdef PATH_MAX
4904 p = buf;
4905 #endif
4906 p = realpath(argv0, p);
4907 if (!p) {
4908 return NULL;
4911 dir = dirname(p);
4912 dir = dirname(dir);
4914 max_len = strlen(dir) +
4915 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4916 res = qemu_mallocz(max_len);
4917 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4918 if (access(res, R_OK)) {
4919 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4920 if (access(res, R_OK)) {
4921 qemu_free(res);
4922 res = NULL;
4925 #ifndef PATH_MAX
4926 free(p);
4927 #endif
4928 return res;
4930 #undef SHARE_SUFFIX
4931 #undef BUILD_SUFFIX
4932 #endif
4934 char *qemu_find_file(int type, const char *name)
4936 int len;
4937 const char *subdir;
4938 char *buf;
4940 /* If name contains path separators then try it as a straight path. */
4941 if ((strchr(name, '/') || strchr(name, '\\'))
4942 && access(name, R_OK) == 0) {
4943 return strdup(name);
4945 switch (type) {
4946 case QEMU_FILE_TYPE_BIOS:
4947 subdir = "";
4948 break;
4949 case QEMU_FILE_TYPE_KEYMAP:
4950 subdir = "keymaps/";
4951 break;
4952 default:
4953 abort();
4955 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4956 buf = qemu_mallocz(len);
4957 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4958 if (access(buf, R_OK)) {
4959 qemu_free(buf);
4960 return NULL;
4962 return buf;
4965 int main(int argc, char **argv, char **envp)
4967 const char *gdbstub_dev = NULL;
4968 uint32_t boot_devices_bitmap = 0;
4969 int i;
4970 int snapshot, linux_boot, net_boot;
4971 const char *initrd_filename;
4972 const char *kernel_filename, *kernel_cmdline;
4973 const char *boot_devices = "";
4974 DisplayState *ds;
4975 DisplayChangeListener *dcl;
4976 int cyls, heads, secs, translation;
4977 const char *net_clients[MAX_NET_CLIENTS];
4978 int nb_net_clients;
4979 const char *bt_opts[MAX_BT_CMDLINE];
4980 int nb_bt_opts;
4981 int hda_index;
4982 int optind;
4983 const char *r, *optarg;
4984 CharDriverState *monitor_hd = NULL;
4985 const char *monitor_device;
4986 const char *serial_devices[MAX_SERIAL_PORTS];
4987 int serial_device_index;
4988 const char *parallel_devices[MAX_PARALLEL_PORTS];
4989 int parallel_device_index;
4990 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4991 int virtio_console_index;
4992 const char *loadvm = NULL;
4993 QEMUMachine *machine;
4994 const char *cpu_model;
4995 const char *usb_devices[MAX_USB_CMDLINE];
4996 int usb_devices_index;
4997 #ifndef _WIN32
4998 int fds[2];
4999 #endif
5000 int tb_size;
5001 const char *pid_file = NULL;
5002 const char *incoming = NULL;
5003 #ifndef _WIN32
5004 int fd = 0;
5005 struct passwd *pwd = NULL;
5006 const char *chroot_dir = NULL;
5007 const char *run_as = NULL;
5008 #endif
5009 CPUState *env;
5010 int show_vnc_port = 0;
5012 qemu_cache_utils_init(envp);
5014 LIST_INIT (&vm_change_state_head);
5015 #ifndef _WIN32
5017 struct sigaction act;
5018 sigfillset(&act.sa_mask);
5019 act.sa_flags = 0;
5020 act.sa_handler = SIG_IGN;
5021 sigaction(SIGPIPE, &act, NULL);
5023 #else
5024 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5025 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5026 QEMU to run on a single CPU */
5028 HANDLE h;
5029 DWORD mask, smask;
5030 int i;
5031 h = GetCurrentProcess();
5032 if (GetProcessAffinityMask(h, &mask, &smask)) {
5033 for(i = 0; i < 32; i++) {
5034 if (mask & (1 << i))
5035 break;
5037 if (i != 32) {
5038 mask = 1 << i;
5039 SetProcessAffinityMask(h, mask);
5043 #endif
5045 module_call_init(MODULE_INIT_MACHINE);
5046 machine = find_default_machine();
5047 cpu_model = NULL;
5048 initrd_filename = NULL;
5049 ram_size = 0;
5050 snapshot = 0;
5051 kernel_filename = NULL;
5052 kernel_cmdline = "";
5053 cyls = heads = secs = 0;
5054 translation = BIOS_ATA_TRANSLATION_AUTO;
5055 monitor_device = "vc:80Cx24C";
5057 serial_devices[0] = "vc:80Cx24C";
5058 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5059 serial_devices[i] = NULL;
5060 serial_device_index = 0;
5062 parallel_devices[0] = "vc:80Cx24C";
5063 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5064 parallel_devices[i] = NULL;
5065 parallel_device_index = 0;
5067 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
5068 virtio_consoles[i] = NULL;
5069 virtio_console_index = 0;
5071 for (i = 0; i < MAX_NODES; i++) {
5072 node_mem[i] = 0;
5073 node_cpumask[i] = 0;
5076 usb_devices_index = 0;
5078 nb_net_clients = 0;
5079 nb_bt_opts = 0;
5080 nb_drives = 0;
5081 nb_drives_opt = 0;
5082 nb_numa_nodes = 0;
5083 hda_index = -1;
5085 nb_nics = 0;
5087 tb_size = 0;
5088 autostart= 1;
5090 register_watchdogs();
5092 optind = 1;
5093 for(;;) {
5094 if (optind >= argc)
5095 break;
5096 r = argv[optind];
5097 if (r[0] != '-') {
5098 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5099 } else {
5100 const QEMUOption *popt;
5102 optind++;
5103 /* Treat --foo the same as -foo. */
5104 if (r[1] == '-')
5105 r++;
5106 popt = qemu_options;
5107 for(;;) {
5108 if (!popt->name) {
5109 fprintf(stderr, "%s: invalid option -- '%s'\n",
5110 argv[0], r);
5111 exit(1);
5113 if (!strcmp(popt->name, r + 1))
5114 break;
5115 popt++;
5117 if (popt->flags & HAS_ARG) {
5118 if (optind >= argc) {
5119 fprintf(stderr, "%s: option '%s' requires an argument\n",
5120 argv[0], r);
5121 exit(1);
5123 optarg = argv[optind++];
5124 } else {
5125 optarg = NULL;
5128 switch(popt->index) {
5129 case QEMU_OPTION_M:
5130 machine = find_machine(optarg);
5131 if (!machine) {
5132 QEMUMachine *m;
5133 printf("Supported machines are:\n");
5134 for(m = first_machine; m != NULL; m = m->next) {
5135 printf("%-10s %s%s\n",
5136 m->name, m->desc,
5137 m->is_default ? " (default)" : "");
5139 exit(*optarg != '?');
5141 break;
5142 case QEMU_OPTION_cpu:
5143 /* hw initialization will check this */
5144 if (*optarg == '?') {
5145 /* XXX: implement xxx_cpu_list for targets that still miss it */
5146 #if defined(cpu_list)
5147 cpu_list(stdout, &fprintf);
5148 #endif
5149 exit(0);
5150 } else {
5151 cpu_model = optarg;
5153 break;
5154 case QEMU_OPTION_initrd:
5155 initrd_filename = optarg;
5156 break;
5157 case QEMU_OPTION_hda:
5158 if (cyls == 0)
5159 hda_index = drive_add(optarg, HD_ALIAS, 0);
5160 else
5161 hda_index = drive_add(optarg, HD_ALIAS
5162 ",cyls=%d,heads=%d,secs=%d%s",
5163 0, cyls, heads, secs,
5164 translation == BIOS_ATA_TRANSLATION_LBA ?
5165 ",trans=lba" :
5166 translation == BIOS_ATA_TRANSLATION_NONE ?
5167 ",trans=none" : "");
5168 break;
5169 case QEMU_OPTION_hdb:
5170 case QEMU_OPTION_hdc:
5171 case QEMU_OPTION_hdd:
5172 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5173 break;
5174 case QEMU_OPTION_drive:
5175 drive_add(NULL, "%s", optarg);
5176 break;
5177 case QEMU_OPTION_mtdblock:
5178 drive_add(optarg, MTD_ALIAS);
5179 break;
5180 case QEMU_OPTION_sd:
5181 drive_add(optarg, SD_ALIAS);
5182 break;
5183 case QEMU_OPTION_pflash:
5184 drive_add(optarg, PFLASH_ALIAS);
5185 break;
5186 case QEMU_OPTION_snapshot:
5187 snapshot = 1;
5188 break;
5189 case QEMU_OPTION_hdachs:
5191 const char *p;
5192 p = optarg;
5193 cyls = strtol(p, (char **)&p, 0);
5194 if (cyls < 1 || cyls > 16383)
5195 goto chs_fail;
5196 if (*p != ',')
5197 goto chs_fail;
5198 p++;
5199 heads = strtol(p, (char **)&p, 0);
5200 if (heads < 1 || heads > 16)
5201 goto chs_fail;
5202 if (*p != ',')
5203 goto chs_fail;
5204 p++;
5205 secs = strtol(p, (char **)&p, 0);
5206 if (secs < 1 || secs > 63)
5207 goto chs_fail;
5208 if (*p == ',') {
5209 p++;
5210 if (!strcmp(p, "none"))
5211 translation = BIOS_ATA_TRANSLATION_NONE;
5212 else if (!strcmp(p, "lba"))
5213 translation = BIOS_ATA_TRANSLATION_LBA;
5214 else if (!strcmp(p, "auto"))
5215 translation = BIOS_ATA_TRANSLATION_AUTO;
5216 else
5217 goto chs_fail;
5218 } else if (*p != '\0') {
5219 chs_fail:
5220 fprintf(stderr, "qemu: invalid physical CHS format\n");
5221 exit(1);
5223 if (hda_index != -1)
5224 snprintf(drives_opt[hda_index].opt,
5225 sizeof(drives_opt[hda_index].opt),
5226 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5227 0, cyls, heads, secs,
5228 translation == BIOS_ATA_TRANSLATION_LBA ?
5229 ",trans=lba" :
5230 translation == BIOS_ATA_TRANSLATION_NONE ?
5231 ",trans=none" : "");
5233 break;
5234 case QEMU_OPTION_numa:
5235 if (nb_numa_nodes >= MAX_NODES) {
5236 fprintf(stderr, "qemu: too many NUMA nodes\n");
5237 exit(1);
5239 numa_add(optarg);
5240 break;
5241 case QEMU_OPTION_nographic:
5242 display_type = DT_NOGRAPHIC;
5243 break;
5244 #ifdef CONFIG_CURSES
5245 case QEMU_OPTION_curses:
5246 display_type = DT_CURSES;
5247 break;
5248 #endif
5249 case QEMU_OPTION_portrait:
5250 graphic_rotate = 1;
5251 break;
5252 case QEMU_OPTION_kernel:
5253 kernel_filename = optarg;
5254 break;
5255 case QEMU_OPTION_append:
5256 kernel_cmdline = optarg;
5257 break;
5258 case QEMU_OPTION_cdrom:
5259 drive_add(optarg, CDROM_ALIAS);
5260 break;
5261 case QEMU_OPTION_boot:
5262 boot_devices = optarg;
5263 /* We just do some generic consistency checks */
5265 /* Could easily be extended to 64 devices if needed */
5266 const char *p;
5268 boot_devices_bitmap = 0;
5269 for (p = boot_devices; *p != '\0'; p++) {
5270 /* Allowed boot devices are:
5271 * a b : floppy disk drives
5272 * c ... f : IDE disk drives
5273 * g ... m : machine implementation dependant drives
5274 * n ... p : network devices
5275 * It's up to each machine implementation to check
5276 * if the given boot devices match the actual hardware
5277 * implementation and firmware features.
5279 if (*p < 'a' || *p > 'q') {
5280 fprintf(stderr, "Invalid boot device '%c'\n", *p);
5281 exit(1);
5283 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5284 fprintf(stderr,
5285 "Boot device '%c' was given twice\n",*p);
5286 exit(1);
5288 boot_devices_bitmap |= 1 << (*p - 'a');
5291 break;
5292 case QEMU_OPTION_fda:
5293 case QEMU_OPTION_fdb:
5294 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5295 break;
5296 #ifdef TARGET_I386
5297 case QEMU_OPTION_no_fd_bootchk:
5298 fd_bootchk = 0;
5299 break;
5300 #endif
5301 case QEMU_OPTION_net:
5302 if (nb_net_clients >= MAX_NET_CLIENTS) {
5303 fprintf(stderr, "qemu: too many network clients\n");
5304 exit(1);
5306 net_clients[nb_net_clients] = optarg;
5307 nb_net_clients++;
5308 break;
5309 #ifdef CONFIG_SLIRP
5310 case QEMU_OPTION_tftp:
5311 legacy_tftp_prefix = optarg;
5312 break;
5313 case QEMU_OPTION_bootp:
5314 legacy_bootp_filename = optarg;
5315 break;
5316 #ifndef _WIN32
5317 case QEMU_OPTION_smb:
5318 net_slirp_smb(optarg);
5319 break;
5320 #endif
5321 case QEMU_OPTION_redir:
5322 net_slirp_redir(optarg);
5323 break;
5324 #endif
5325 case QEMU_OPTION_bt:
5326 if (nb_bt_opts >= MAX_BT_CMDLINE) {
5327 fprintf(stderr, "qemu: too many bluetooth options\n");
5328 exit(1);
5330 bt_opts[nb_bt_opts++] = optarg;
5331 break;
5332 #ifdef HAS_AUDIO
5333 case QEMU_OPTION_audio_help:
5334 AUD_help ();
5335 exit (0);
5336 break;
5337 case QEMU_OPTION_soundhw:
5338 select_soundhw (optarg);
5339 break;
5340 #endif
5341 case QEMU_OPTION_h:
5342 help(0);
5343 break;
5344 case QEMU_OPTION_version:
5345 version();
5346 exit(0);
5347 break;
5348 case QEMU_OPTION_m: {
5349 uint64_t value;
5350 char *ptr;
5352 value = strtoul(optarg, &ptr, 10);
5353 switch (*ptr) {
5354 case 0: case 'M': case 'm':
5355 value <<= 20;
5356 break;
5357 case 'G': case 'g':
5358 value <<= 30;
5359 break;
5360 default:
5361 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5362 exit(1);
5365 /* On 32-bit hosts, QEMU is limited by virtual address space */
5366 if (value > (2047 << 20)
5367 #ifndef CONFIG_KQEMU
5368 && HOST_LONG_BITS == 32
5369 #endif
5371 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5372 exit(1);
5374 if (value != (uint64_t)(ram_addr_t)value) {
5375 fprintf(stderr, "qemu: ram size too large\n");
5376 exit(1);
5378 ram_size = value;
5379 break;
5381 case QEMU_OPTION_d:
5383 int mask;
5384 const CPULogItem *item;
5386 mask = cpu_str_to_log_mask(optarg);
5387 if (!mask) {
5388 printf("Log items (comma separated):\n");
5389 for(item = cpu_log_items; item->mask != 0; item++) {
5390 printf("%-10s %s\n", item->name, item->help);
5392 exit(1);
5394 cpu_set_log(mask);
5396 break;
5397 case QEMU_OPTION_s:
5398 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5399 break;
5400 case QEMU_OPTION_gdb:
5401 gdbstub_dev = optarg;
5402 break;
5403 case QEMU_OPTION_L:
5404 data_dir = optarg;
5405 break;
5406 case QEMU_OPTION_bios:
5407 bios_name = optarg;
5408 break;
5409 case QEMU_OPTION_singlestep:
5410 singlestep = 1;
5411 break;
5412 case QEMU_OPTION_S:
5413 autostart = 0;
5414 break;
5415 #ifndef _WIN32
5416 case QEMU_OPTION_k:
5417 keyboard_layout = optarg;
5418 break;
5419 #endif
5420 case QEMU_OPTION_localtime:
5421 rtc_utc = 0;
5422 break;
5423 case QEMU_OPTION_vga:
5424 select_vgahw (optarg);
5425 break;
5426 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5427 case QEMU_OPTION_g:
5429 const char *p;
5430 int w, h, depth;
5431 p = optarg;
5432 w = strtol(p, (char **)&p, 10);
5433 if (w <= 0) {
5434 graphic_error:
5435 fprintf(stderr, "qemu: invalid resolution or depth\n");
5436 exit(1);
5438 if (*p != 'x')
5439 goto graphic_error;
5440 p++;
5441 h = strtol(p, (char **)&p, 10);
5442 if (h <= 0)
5443 goto graphic_error;
5444 if (*p == 'x') {
5445 p++;
5446 depth = strtol(p, (char **)&p, 10);
5447 if (depth != 8 && depth != 15 && depth != 16 &&
5448 depth != 24 && depth != 32)
5449 goto graphic_error;
5450 } else if (*p == '\0') {
5451 depth = graphic_depth;
5452 } else {
5453 goto graphic_error;
5456 graphic_width = w;
5457 graphic_height = h;
5458 graphic_depth = depth;
5460 break;
5461 #endif
5462 case QEMU_OPTION_echr:
5464 char *r;
5465 term_escape_char = strtol(optarg, &r, 0);
5466 if (r == optarg)
5467 printf("Bad argument to echr\n");
5468 break;
5470 case QEMU_OPTION_monitor:
5471 monitor_device = optarg;
5472 break;
5473 case QEMU_OPTION_serial:
5474 if (serial_device_index >= MAX_SERIAL_PORTS) {
5475 fprintf(stderr, "qemu: too many serial ports\n");
5476 exit(1);
5478 serial_devices[serial_device_index] = optarg;
5479 serial_device_index++;
5480 break;
5481 case QEMU_OPTION_watchdog:
5482 i = select_watchdog(optarg);
5483 if (i > 0)
5484 exit (i == 1 ? 1 : 0);
5485 break;
5486 case QEMU_OPTION_watchdog_action:
5487 if (select_watchdog_action(optarg) == -1) {
5488 fprintf(stderr, "Unknown -watchdog-action parameter\n");
5489 exit(1);
5491 break;
5492 case QEMU_OPTION_virtiocon:
5493 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5494 fprintf(stderr, "qemu: too many virtio consoles\n");
5495 exit(1);
5497 virtio_consoles[virtio_console_index] = optarg;
5498 virtio_console_index++;
5499 break;
5500 case QEMU_OPTION_parallel:
5501 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5502 fprintf(stderr, "qemu: too many parallel ports\n");
5503 exit(1);
5505 parallel_devices[parallel_device_index] = optarg;
5506 parallel_device_index++;
5507 break;
5508 case QEMU_OPTION_loadvm:
5509 loadvm = optarg;
5510 break;
5511 case QEMU_OPTION_full_screen:
5512 full_screen = 1;
5513 break;
5514 #ifdef CONFIG_SDL
5515 case QEMU_OPTION_no_frame:
5516 no_frame = 1;
5517 break;
5518 case QEMU_OPTION_alt_grab:
5519 alt_grab = 1;
5520 break;
5521 case QEMU_OPTION_no_quit:
5522 no_quit = 1;
5523 break;
5524 case QEMU_OPTION_sdl:
5525 display_type = DT_SDL;
5526 break;
5527 #endif
5528 case QEMU_OPTION_pidfile:
5529 pid_file = optarg;
5530 break;
5531 #ifdef TARGET_I386
5532 case QEMU_OPTION_win2k_hack:
5533 win2k_install_hack = 1;
5534 break;
5535 case QEMU_OPTION_rtc_td_hack:
5536 rtc_td_hack = 1;
5537 break;
5538 case QEMU_OPTION_acpitable:
5539 if(acpi_table_add(optarg) < 0) {
5540 fprintf(stderr, "Wrong acpi table provided\n");
5541 exit(1);
5543 break;
5544 case QEMU_OPTION_smbios:
5545 if(smbios_entry_add(optarg) < 0) {
5546 fprintf(stderr, "Wrong smbios provided\n");
5547 exit(1);
5549 break;
5550 #endif
5551 #ifdef CONFIG_KQEMU
5552 case QEMU_OPTION_no_kqemu:
5553 kqemu_allowed = 0;
5554 break;
5555 case QEMU_OPTION_kernel_kqemu:
5556 kqemu_allowed = 2;
5557 break;
5558 #endif
5559 #ifdef CONFIG_KVM
5560 case QEMU_OPTION_enable_kvm:
5561 kvm_allowed = 1;
5562 #ifdef CONFIG_KQEMU
5563 kqemu_allowed = 0;
5564 #endif
5565 break;
5566 #endif
5567 case QEMU_OPTION_usb:
5568 usb_enabled = 1;
5569 break;
5570 case QEMU_OPTION_usbdevice:
5571 usb_enabled = 1;
5572 if (usb_devices_index >= MAX_USB_CMDLINE) {
5573 fprintf(stderr, "Too many USB devices\n");
5574 exit(1);
5576 usb_devices[usb_devices_index] = optarg;
5577 usb_devices_index++;
5578 break;
5579 case QEMU_OPTION_smp:
5580 smp_cpus = atoi(optarg);
5581 if (smp_cpus < 1) {
5582 fprintf(stderr, "Invalid number of CPUs\n");
5583 exit(1);
5585 break;
5586 case QEMU_OPTION_vnc:
5587 display_type = DT_VNC;
5588 vnc_display = optarg;
5589 break;
5590 #ifdef TARGET_I386
5591 case QEMU_OPTION_no_acpi:
5592 acpi_enabled = 0;
5593 break;
5594 case QEMU_OPTION_no_hpet:
5595 no_hpet = 1;
5596 break;
5597 case QEMU_OPTION_no_virtio_balloon:
5598 no_virtio_balloon = 1;
5599 break;
5600 #endif
5601 case QEMU_OPTION_no_reboot:
5602 no_reboot = 1;
5603 break;
5604 case QEMU_OPTION_no_shutdown:
5605 no_shutdown = 1;
5606 break;
5607 case QEMU_OPTION_show_cursor:
5608 cursor_hide = 0;
5609 break;
5610 case QEMU_OPTION_uuid:
5611 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5612 fprintf(stderr, "Fail to parse UUID string."
5613 " Wrong format.\n");
5614 exit(1);
5616 break;
5617 #ifndef _WIN32
5618 case QEMU_OPTION_daemonize:
5619 daemonize = 1;
5620 break;
5621 #endif
5622 case QEMU_OPTION_option_rom:
5623 if (nb_option_roms >= MAX_OPTION_ROMS) {
5624 fprintf(stderr, "Too many option ROMs\n");
5625 exit(1);
5627 option_rom[nb_option_roms] = optarg;
5628 nb_option_roms++;
5629 break;
5630 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5631 case QEMU_OPTION_semihosting:
5632 semihosting_enabled = 1;
5633 break;
5634 #endif
5635 case QEMU_OPTION_name:
5636 qemu_name = optarg;
5637 break;
5638 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5639 case QEMU_OPTION_prom_env:
5640 if (nb_prom_envs >= MAX_PROM_ENVS) {
5641 fprintf(stderr, "Too many prom variables\n");
5642 exit(1);
5644 prom_envs[nb_prom_envs] = optarg;
5645 nb_prom_envs++;
5646 break;
5647 #endif
5648 #ifdef TARGET_ARM
5649 case QEMU_OPTION_old_param:
5650 old_param = 1;
5651 break;
5652 #endif
5653 case QEMU_OPTION_clock:
5654 configure_alarms(optarg);
5655 break;
5656 case QEMU_OPTION_startdate:
5658 struct tm tm;
5659 time_t rtc_start_date;
5660 if (!strcmp(optarg, "now")) {
5661 rtc_date_offset = -1;
5662 } else {
5663 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5664 &tm.tm_year,
5665 &tm.tm_mon,
5666 &tm.tm_mday,
5667 &tm.tm_hour,
5668 &tm.tm_min,
5669 &tm.tm_sec) == 6) {
5670 /* OK */
5671 } else if (sscanf(optarg, "%d-%d-%d",
5672 &tm.tm_year,
5673 &tm.tm_mon,
5674 &tm.tm_mday) == 3) {
5675 tm.tm_hour = 0;
5676 tm.tm_min = 0;
5677 tm.tm_sec = 0;
5678 } else {
5679 goto date_fail;
5681 tm.tm_year -= 1900;
5682 tm.tm_mon--;
5683 rtc_start_date = mktimegm(&tm);
5684 if (rtc_start_date == -1) {
5685 date_fail:
5686 fprintf(stderr, "Invalid date format. Valid format are:\n"
5687 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5688 exit(1);
5690 rtc_date_offset = time(NULL) - rtc_start_date;
5693 break;
5694 case QEMU_OPTION_tb_size:
5695 tb_size = strtol(optarg, NULL, 0);
5696 if (tb_size < 0)
5697 tb_size = 0;
5698 break;
5699 case QEMU_OPTION_icount:
5700 use_icount = 1;
5701 if (strcmp(optarg, "auto") == 0) {
5702 icount_time_shift = -1;
5703 } else {
5704 icount_time_shift = strtol(optarg, NULL, 0);
5706 break;
5707 case QEMU_OPTION_incoming:
5708 incoming = optarg;
5709 break;
5710 #ifndef _WIN32
5711 case QEMU_OPTION_chroot:
5712 chroot_dir = optarg;
5713 break;
5714 case QEMU_OPTION_runas:
5715 run_as = optarg;
5716 break;
5717 #endif
5718 #ifdef CONFIG_XEN
5719 case QEMU_OPTION_xen_domid:
5720 xen_domid = atoi(optarg);
5721 break;
5722 case QEMU_OPTION_xen_create:
5723 xen_mode = XEN_CREATE;
5724 break;
5725 case QEMU_OPTION_xen_attach:
5726 xen_mode = XEN_ATTACH;
5727 break;
5728 #endif
5733 /* If no data_dir is specified then try to find it relative to the
5734 executable path. */
5735 if (!data_dir) {
5736 data_dir = find_datadir(argv[0]);
5738 /* If all else fails use the install patch specified when building. */
5739 if (!data_dir) {
5740 data_dir = CONFIG_QEMU_SHAREDIR;
5743 #if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5744 if (kvm_allowed && kqemu_allowed) {
5745 fprintf(stderr,
5746 "You can not enable both KVM and kqemu at the same time\n");
5747 exit(1);
5749 #endif
5751 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5752 if (smp_cpus > machine->max_cpus) {
5753 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5754 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5755 machine->max_cpus);
5756 exit(1);
5759 if (display_type == DT_NOGRAPHIC) {
5760 if (serial_device_index == 0)
5761 serial_devices[0] = "stdio";
5762 if (parallel_device_index == 0)
5763 parallel_devices[0] = "null";
5764 if (strncmp(monitor_device, "vc", 2) == 0)
5765 monitor_device = "stdio";
5768 #ifndef _WIN32
5769 if (daemonize) {
5770 pid_t pid;
5772 if (pipe(fds) == -1)
5773 exit(1);
5775 pid = fork();
5776 if (pid > 0) {
5777 uint8_t status;
5778 ssize_t len;
5780 close(fds[1]);
5782 again:
5783 len = read(fds[0], &status, 1);
5784 if (len == -1 && (errno == EINTR))
5785 goto again;
5787 if (len != 1)
5788 exit(1);
5789 else if (status == 1) {
5790 fprintf(stderr, "Could not acquire pidfile\n");
5791 exit(1);
5792 } else
5793 exit(0);
5794 } else if (pid < 0)
5795 exit(1);
5797 setsid();
5799 pid = fork();
5800 if (pid > 0)
5801 exit(0);
5802 else if (pid < 0)
5803 exit(1);
5805 umask(027);
5807 signal(SIGTSTP, SIG_IGN);
5808 signal(SIGTTOU, SIG_IGN);
5809 signal(SIGTTIN, SIG_IGN);
5812 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5813 if (daemonize) {
5814 uint8_t status = 1;
5815 write(fds[1], &status, 1);
5816 } else
5817 fprintf(stderr, "Could not acquire pid file\n");
5818 exit(1);
5820 #endif
5822 #ifdef CONFIG_KQEMU
5823 if (smp_cpus > 1)
5824 kqemu_allowed = 0;
5825 #endif
5826 if (qemu_init_main_loop()) {
5827 fprintf(stderr, "qemu_init_main_loop failed\n");
5828 exit(1);
5830 linux_boot = (kernel_filename != NULL);
5832 if (!linux_boot && *kernel_cmdline != '\0') {
5833 fprintf(stderr, "-append only allowed with -kernel option\n");
5834 exit(1);
5837 if (!linux_boot && initrd_filename != NULL) {
5838 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5839 exit(1);
5842 /* boot to floppy or the default cd if no hard disk defined yet */
5843 if (!boot_devices[0]) {
5844 boot_devices = "cad";
5846 setvbuf(stdout, NULL, _IOLBF, 0);
5848 init_timers();
5849 if (init_timer_alarm() < 0) {
5850 fprintf(stderr, "could not initialize alarm timer\n");
5851 exit(1);
5853 if (use_icount && icount_time_shift < 0) {
5854 use_icount = 2;
5855 /* 125MIPS seems a reasonable initial guess at the guest speed.
5856 It will be corrected fairly quickly anyway. */
5857 icount_time_shift = 3;
5858 init_icount_adjust();
5861 #ifdef _WIN32
5862 socket_init();
5863 #endif
5865 /* init network clients */
5866 if (nb_net_clients == 0) {
5867 /* if no clients, we use a default config */
5868 net_clients[nb_net_clients++] = "nic";
5869 #ifdef CONFIG_SLIRP
5870 net_clients[nb_net_clients++] = "user";
5871 #endif
5874 for(i = 0;i < nb_net_clients; i++) {
5875 if (net_client_parse(net_clients[i]) < 0)
5876 exit(1);
5879 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5880 net_set_boot_mask(net_boot);
5882 net_client_check();
5884 /* init the bluetooth world */
5885 for (i = 0; i < nb_bt_opts; i++)
5886 if (bt_parse(bt_opts[i]))
5887 exit(1);
5889 /* init the memory */
5890 if (ram_size == 0)
5891 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5893 #ifdef CONFIG_KQEMU
5894 /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5895 guest ram allocation. It needs to go away. */
5896 if (kqemu_allowed) {
5897 kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5898 kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5899 if (!kqemu_phys_ram_base) {
5900 fprintf(stderr, "Could not allocate physical memory\n");
5901 exit(1);
5904 #endif
5906 /* init the dynamic translator */
5907 cpu_exec_init_all(tb_size * 1024 * 1024);
5909 bdrv_init();
5911 /* we always create the cdrom drive, even if no disk is there */
5913 if (nb_drives_opt < MAX_DRIVES)
5914 drive_add(NULL, CDROM_ALIAS);
5916 /* we always create at least one floppy */
5918 if (nb_drives_opt < MAX_DRIVES)
5919 drive_add(NULL, FD_ALIAS, 0);
5921 /* we always create one sd slot, even if no card is in it */
5923 if (nb_drives_opt < MAX_DRIVES)
5924 drive_add(NULL, SD_ALIAS);
5926 /* open the virtual block devices */
5928 for(i = 0; i < nb_drives_opt; i++)
5929 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5930 exit(1);
5932 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5933 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5935 #ifndef _WIN32
5936 /* must be after terminal init, SDL library changes signal handlers */
5937 sighandler_setup();
5938 #endif
5940 /* Maintain compatibility with multiple stdio monitors */
5941 if (!strcmp(monitor_device,"stdio")) {
5942 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5943 const char *devname = serial_devices[i];
5944 if (devname && !strcmp(devname,"mon:stdio")) {
5945 monitor_device = NULL;
5946 break;
5947 } else if (devname && !strcmp(devname,"stdio")) {
5948 monitor_device = NULL;
5949 serial_devices[i] = "mon:stdio";
5950 break;
5955 if (nb_numa_nodes > 0) {
5956 int i;
5958 if (nb_numa_nodes > smp_cpus) {
5959 nb_numa_nodes = smp_cpus;
5962 /* If no memory size if given for any node, assume the default case
5963 * and distribute the available memory equally across all nodes
5965 for (i = 0; i < nb_numa_nodes; i++) {
5966 if (node_mem[i] != 0)
5967 break;
5969 if (i == nb_numa_nodes) {
5970 uint64_t usedmem = 0;
5972 /* On Linux, the each node's border has to be 8MB aligned,
5973 * the final node gets the rest.
5975 for (i = 0; i < nb_numa_nodes - 1; i++) {
5976 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5977 usedmem += node_mem[i];
5979 node_mem[i] = ram_size - usedmem;
5982 for (i = 0; i < nb_numa_nodes; i++) {
5983 if (node_cpumask[i] != 0)
5984 break;
5986 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5987 * must cope with this anyway, because there are BIOSes out there in
5988 * real machines which also use this scheme.
5990 if (i == nb_numa_nodes) {
5991 for (i = 0; i < smp_cpus; i++) {
5992 node_cpumask[i % nb_numa_nodes] |= 1 << i;
5997 if (kvm_enabled()) {
5998 int ret;
6000 ret = kvm_init(smp_cpus);
6001 if (ret < 0) {
6002 fprintf(stderr, "failed to initialize KVM\n");
6003 exit(1);
6007 if (monitor_device) {
6008 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
6009 if (!monitor_hd) {
6010 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6011 exit(1);
6015 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6016 const char *devname = serial_devices[i];
6017 if (devname && strcmp(devname, "none")) {
6018 char label[32];
6019 snprintf(label, sizeof(label), "serial%d", i);
6020 serial_hds[i] = qemu_chr_open(label, devname, NULL);
6021 if (!serial_hds[i]) {
6022 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6023 devname);
6024 exit(1);
6029 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6030 const char *devname = parallel_devices[i];
6031 if (devname && strcmp(devname, "none")) {
6032 char label[32];
6033 snprintf(label, sizeof(label), "parallel%d", i);
6034 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
6035 if (!parallel_hds[i]) {
6036 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6037 devname);
6038 exit(1);
6043 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6044 const char *devname = virtio_consoles[i];
6045 if (devname && strcmp(devname, "none")) {
6046 char label[32];
6047 snprintf(label, sizeof(label), "virtcon%d", i);
6048 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
6049 if (!virtcon_hds[i]) {
6050 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
6051 devname);
6052 exit(1);
6057 module_call_init(MODULE_INIT_DEVICE);
6059 machine->init(ram_size, boot_devices,
6060 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6063 for (env = first_cpu; env != NULL; env = env->next_cpu) {
6064 for (i = 0; i < nb_numa_nodes; i++) {
6065 if (node_cpumask[i] & (1 << env->cpu_index)) {
6066 env->numa_node = i;
6071 current_machine = machine;
6073 /* Set KVM's vcpu state to qemu's initial CPUState. */
6074 if (kvm_enabled()) {
6075 int ret;
6077 ret = kvm_sync_vcpus();
6078 if (ret < 0) {
6079 fprintf(stderr, "failed to initialize vcpus\n");
6080 exit(1);
6084 /* init USB devices */
6085 if (usb_enabled) {
6086 for(i = 0; i < usb_devices_index; i++) {
6087 if (usb_device_add(usb_devices[i], 0) < 0) {
6088 fprintf(stderr, "Warning: could not add USB device %s\n",
6089 usb_devices[i]);
6094 if (!display_state)
6095 dumb_display_init();
6096 /* just use the first displaystate for the moment */
6097 ds = display_state;
6099 if (display_type == DT_DEFAULT) {
6100 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6101 display_type = DT_SDL;
6102 #else
6103 display_type = DT_VNC;
6104 vnc_display = "localhost:0,to=99";
6105 show_vnc_port = 1;
6106 #endif
6110 switch (display_type) {
6111 case DT_NOGRAPHIC:
6112 break;
6113 #if defined(CONFIG_CURSES)
6114 case DT_CURSES:
6115 curses_display_init(ds, full_screen);
6116 break;
6117 #endif
6118 #if defined(CONFIG_SDL)
6119 case DT_SDL:
6120 sdl_display_init(ds, full_screen, no_frame);
6121 break;
6122 #elif defined(CONFIG_COCOA)
6123 case DT_SDL:
6124 cocoa_display_init(ds, full_screen);
6125 break;
6126 #endif
6127 case DT_VNC:
6128 vnc_display_init(ds);
6129 if (vnc_display_open(ds, vnc_display) < 0)
6130 exit(1);
6132 if (show_vnc_port) {
6133 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6135 break;
6136 default:
6137 break;
6139 dpy_resize(ds);
6141 dcl = ds->listeners;
6142 while (dcl != NULL) {
6143 if (dcl->dpy_refresh != NULL) {
6144 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6145 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6147 dcl = dcl->next;
6150 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6151 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6152 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6155 text_consoles_set_display(display_state);
6156 qemu_chr_initial_reset();
6158 if (monitor_device && monitor_hd)
6159 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6161 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6162 const char *devname = serial_devices[i];
6163 if (devname && strcmp(devname, "none")) {
6164 if (strstart(devname, "vc", 0))
6165 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6169 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6170 const char *devname = parallel_devices[i];
6171 if (devname && strcmp(devname, "none")) {
6172 if (strstart(devname, "vc", 0))
6173 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6177 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6178 const char *devname = virtio_consoles[i];
6179 if (virtcon_hds[i] && devname) {
6180 if (strstart(devname, "vc", 0))
6181 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6185 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6186 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6187 gdbstub_dev);
6188 exit(1);
6191 if (loadvm)
6192 do_loadvm(cur_mon, loadvm);
6194 if (incoming) {
6195 autostart = 0; /* fixme how to deal with -daemonize */
6196 qemu_start_incoming_migration(incoming);
6199 if (autostart)
6200 vm_start();
6202 #ifndef _WIN32
6203 if (daemonize) {
6204 uint8_t status = 0;
6205 ssize_t len;
6207 again1:
6208 len = write(fds[1], &status, 1);
6209 if (len == -1 && (errno == EINTR))
6210 goto again1;
6212 if (len != 1)
6213 exit(1);
6215 chdir("/");
6216 TFR(fd = open("/dev/null", O_RDWR));
6217 if (fd == -1)
6218 exit(1);
6221 if (run_as) {
6222 pwd = getpwnam(run_as);
6223 if (!pwd) {
6224 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6225 exit(1);
6229 if (chroot_dir) {
6230 if (chroot(chroot_dir) < 0) {
6231 fprintf(stderr, "chroot failed\n");
6232 exit(1);
6234 chdir("/");
6237 if (run_as) {
6238 if (setgid(pwd->pw_gid) < 0) {
6239 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6240 exit(1);
6242 if (setuid(pwd->pw_uid) < 0) {
6243 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6244 exit(1);
6246 if (setuid(0) != -1) {
6247 fprintf(stderr, "Dropping privileges failed\n");
6248 exit(1);
6252 if (daemonize) {
6253 dup2(fd, 0);
6254 dup2(fd, 1);
6255 dup2(fd, 2);
6257 close(fd);
6259 #endif
6261 main_loop();
6262 quit_timers();
6263 net_cleanup();
6265 return 0;