kvm: configure: --with-patched-kernel doesn't need kernelversion
[qemu-kvm/fedora.git] / vl.c
blobb3da7ad4277379dd1f7ee86facd696e940dd94bb
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <time.h>
29 #include <errno.h>
30 #include <sys/time.h>
31 #include <zlib.h>
33 /* Needed early for HOST_BSD etc. */
34 #include "config-host.h"
36 #ifndef _WIN32
37 #include <pwd.h>
38 #include <sys/times.h>
39 #include <sys/wait.h>
40 #include <termios.h>
41 #include <sys/mman.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <sys/vfs.h>
46 #include <netinet/in.h>
47 #include <net/if.h>
48 #if defined(__NetBSD__)
49 #include <net/if_tap.h>
50 #endif
51 #ifdef __linux__
52 #include <linux/if_tun.h>
53 #endif
54 #include <arpa/inet.h>
55 #include <dirent.h>
56 #include <netdb.h>
57 #include <sys/select.h>
58 #ifdef HOST_BSD
59 #include <sys/stat.h>
60 #if defined(__FreeBSD__) || defined(__DragonFly__)
61 #include <libutil.h>
62 #else
63 #include <util.h>
64 #endif
65 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
66 #include <freebsd/stdlib.h>
67 #else
68 #ifdef __linux__
69 #include <pty.h>
70 #include <malloc.h>
71 #include <linux/rtc.h>
73 /* For the benefit of older linux systems which don't supply it,
74 we use a local copy of hpet.h. */
75 /* #include <linux/hpet.h> */
76 #include "hpet.h"
78 #include <linux/ppdev.h>
79 #include <linux/parport.h>
80 #endif
81 #ifdef __sun__
82 #include <sys/stat.h>
83 #include <sys/ethernet.h>
84 #include <sys/sockio.h>
85 #include <netinet/arp.h>
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h> // must come after ip.h
90 #include <netinet/udp.h>
91 #include <netinet/tcp.h>
92 #include <net/if.h>
93 #include <syslog.h>
94 #include <stropts.h>
95 #endif
96 #endif
97 #endif
99 #if defined(__OpenBSD__)
100 #include <util.h>
101 #endif
103 #if defined(CONFIG_VDE)
104 #include <libvdeplug.h>
105 #endif
107 #ifdef _WIN32
108 #include <windows.h>
109 #include <malloc.h>
110 #include <sys/timeb.h>
111 #include <mmsystem.h>
112 #define getopt_long_only getopt_long
113 #define memalign(align, size) malloc(size)
114 #endif
116 #ifdef CONFIG_SDL
117 #ifdef __APPLE__
118 #include <SDL/SDL.h>
119 int qemu_main(int argc, char **argv, char **envp);
120 int main(int argc, char **argv)
122 qemu_main(argc, argv, NULL);
124 #undef main
125 #define main qemu_main
126 #endif
127 #endif /* CONFIG_SDL */
129 #ifdef CONFIG_COCOA
130 #undef main
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
134 #include "hw/hw.h"
135 #include "hw/boards.h"
136 #include "hw/usb.h"
137 #include "hw/pcmcia.h"
138 #include "hw/pc.h"
139 #include "hw/audiodev.h"
140 #include "hw/isa.h"
141 #include "hw/baum.h"
142 #include "hw/bt.h"
143 #include "bt-host.h"
144 #include "net.h"
145 #include "monitor.h"
146 #include "console.h"
147 #include "sysemu.h"
148 #include "gdbstub.h"
149 #include "qemu-timer.h"
150 #include "qemu-char.h"
151 #include "cache-utils.h"
152 #include "block.h"
153 #include "dma.h"
154 #include "audio/audio.h"
155 #include "migration.h"
156 #include "kvm.h"
157 #include "balloon.h"
158 #include "qemu-kvm.h"
159 #include "hw/device-assignment.h"
161 #include "disas.h"
163 #include "exec-all.h"
165 #include "qemu_socket.h"
167 #if defined(CONFIG_SLIRP)
168 #include "libslirp.h"
169 #endif
171 //#define DEBUG_UNUSED_IOPORT
172 //#define DEBUG_IOPORT
173 //#define DEBUG_NET
174 //#define DEBUG_SLIRP
177 #ifdef DEBUG_IOPORT
178 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
179 #else
180 # define LOG_IOPORT(...) do { } while (0)
181 #endif
183 #define DEFAULT_RAM_SIZE 128
185 /* Max number of USB devices that can be specified on the commandline. */
186 #define MAX_USB_CMDLINE 8
188 /* Max number of bluetooth switches on the commandline. */
189 #define MAX_BT_CMDLINE 10
191 /* XXX: use a two level table to limit memory usage */
192 #define MAX_IOPORTS 65536
194 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
195 const char *bios_name = NULL;
196 static void *ioport_opaque[MAX_IOPORTS];
197 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
198 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
199 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
200 to store the VM snapshots */
201 DriveInfo drives_table[MAX_DRIVES+1];
202 int nb_drives;
203 int extboot_drive = -1;
204 static int vga_ram_size;
205 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
206 static DisplayState *display_state;
207 int nographic;
208 static int curses;
209 static int sdl;
210 const char* keyboard_layout = NULL;
211 int64_t ticks_per_sec;
212 ram_addr_t ram_size;
213 int nb_nics;
214 NICInfo nd_table[MAX_NICS];
215 int vm_running;
216 static int autostart;
217 static int rtc_utc = 1;
218 static int rtc_date_offset = -1; /* -1 means no change */
219 int cirrus_vga_enabled = 1;
220 int std_vga_enabled = 0;
221 int vmsvga_enabled = 0;
222 #ifdef TARGET_SPARC
223 int graphic_width = 1024;
224 int graphic_height = 768;
225 int graphic_depth = 8;
226 #else
227 int graphic_width = 800;
228 int graphic_height = 600;
229 int graphic_depth = 15;
230 #endif
231 static int full_screen = 0;
232 #ifdef CONFIG_SDL
233 static int no_frame = 0;
234 #endif
235 int no_quit = 0;
236 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
237 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
238 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
239 #ifdef TARGET_I386
240 int win2k_install_hack = 0;
241 int rtc_td_hack = 0;
242 #endif
243 int usb_enabled = 0;
244 const char *assigned_devices[MAX_DEV_ASSIGN_CMDLINE];
245 int assigned_devices_index;
246 int smp_cpus = 1;
247 const char *vnc_display;
248 int acpi_enabled = 1;
249 int no_hpet = 0;
250 int fd_bootchk = 1;
251 int no_reboot = 0;
252 int no_shutdown = 0;
253 int cursor_hide = 1;
254 int graphic_rotate = 0;
255 int daemonize = 0;
256 const char *incoming;
257 const char *option_rom[MAX_OPTION_ROMS];
258 int nb_option_roms;
259 int semihosting_enabled = 0;
260 int time_drift_fix = 0;
261 unsigned int kvm_shadow_memory = 0;
262 const char *mem_path = NULL;
263 #ifdef MAP_POPULATE
264 int mem_prealloc = 1; /* force preallocation of physical target memory */
265 #endif
266 long hpagesize = 0;
267 const char *cpu_vendor_string;
268 #ifdef TARGET_ARM
269 int old_param = 0;
270 #endif
271 const char *qemu_name;
272 int alt_grab = 0;
273 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
274 unsigned int nb_prom_envs = 0;
275 const char *prom_envs[MAX_PROM_ENVS];
276 #endif
277 int nb_drives_opt;
278 const char *nvram = NULL;
279 struct drive_opt drives_opt[MAX_DRIVES];
281 static CPUState *cur_cpu;
282 static CPUState *next_cpu;
283 static int event_pending = 1;
284 /* Conversion factor from emulated instructions to virtual clock ticks. */
285 static int icount_time_shift;
286 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
287 #define MAX_ICOUNT_SHIFT 10
288 /* Compensate for varying guest execution speed. */
289 static int64_t qemu_icount_bias;
290 static QEMUTimer *icount_rt_timer;
291 static QEMUTimer *icount_vm_timer;
292 static QEMUTimer *nographic_timer;
294 uint8_t qemu_uuid[16];
296 /* KVM runs the main loop in a separate thread. If we update one of the lists
297 * that are polled before or after select(), we need to make sure to break out
298 * of the select() to ensure the new item is serviced.
300 static void main_loop_break(void)
302 if (kvm_enabled())
303 qemu_kvm_notify_work();
306 /***********************************************************/
307 /* x86 ISA bus support */
309 target_phys_addr_t isa_mem_base = 0;
310 PicState2 *isa_pic;
312 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
313 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
315 static uint32_t ioport_read(int index, uint32_t address)
317 static IOPortReadFunc *default_func[3] = {
318 default_ioport_readb,
319 default_ioport_readw,
320 default_ioport_readl
322 IOPortReadFunc *func = ioport_read_table[index][address];
323 if (!func)
324 func = default_func[index];
325 return func(ioport_opaque[address], address);
328 static void ioport_write(int index, uint32_t address, uint32_t data)
330 static IOPortWriteFunc *default_func[3] = {
331 default_ioport_writeb,
332 default_ioport_writew,
333 default_ioport_writel
335 IOPortWriteFunc *func = ioport_write_table[index][address];
336 if (!func)
337 func = default_func[index];
338 func(ioport_opaque[address], address, data);
341 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
343 #ifdef DEBUG_UNUSED_IOPORT
344 fprintf(stderr, "unused inb: port=0x%04x\n", address);
345 #endif
346 return 0xff;
349 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
351 #ifdef DEBUG_UNUSED_IOPORT
352 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
353 #endif
356 /* default is to make two byte accesses */
357 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
359 uint32_t data;
360 data = ioport_read(0, address);
361 address = (address + 1) & (MAX_IOPORTS - 1);
362 data |= ioport_read(0, address) << 8;
363 return data;
366 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
368 ioport_write(0, address, data & 0xff);
369 address = (address + 1) & (MAX_IOPORTS - 1);
370 ioport_write(0, address, (data >> 8) & 0xff);
373 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
375 #ifdef DEBUG_UNUSED_IOPORT
376 fprintf(stderr, "unused inl: port=0x%04x\n", address);
377 #endif
378 return 0xffffffff;
381 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
383 #ifdef DEBUG_UNUSED_IOPORT
384 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
385 #endif
388 /* size is the word size in byte */
389 int register_ioport_read(int start, int length, int size,
390 IOPortReadFunc *func, void *opaque)
392 int i, bsize;
394 if (size == 1) {
395 bsize = 0;
396 } else if (size == 2) {
397 bsize = 1;
398 } else if (size == 4) {
399 bsize = 2;
400 } else {
401 hw_error("register_ioport_read: invalid size");
402 return -1;
404 for(i = start; i < start + length; i += size) {
405 ioport_read_table[bsize][i] = func;
406 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
407 hw_error("register_ioport_read: invalid opaque");
408 ioport_opaque[i] = opaque;
410 return 0;
413 /* size is the word size in byte */
414 int register_ioport_write(int start, int length, int size,
415 IOPortWriteFunc *func, void *opaque)
417 int i, bsize;
419 if (size == 1) {
420 bsize = 0;
421 } else if (size == 2) {
422 bsize = 1;
423 } else if (size == 4) {
424 bsize = 2;
425 } else {
426 hw_error("register_ioport_write: invalid size");
427 return -1;
429 for(i = start; i < start + length; i += size) {
430 ioport_write_table[bsize][i] = func;
431 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
432 hw_error("register_ioport_write: invalid opaque");
433 ioport_opaque[i] = opaque;
435 return 0;
438 void isa_unassign_ioport(int start, int length)
440 int i;
442 for(i = start; i < start + length; i++) {
443 ioport_read_table[0][i] = default_ioport_readb;
444 ioport_read_table[1][i] = default_ioport_readw;
445 ioport_read_table[2][i] = default_ioport_readl;
447 ioport_write_table[0][i] = default_ioport_writeb;
448 ioport_write_table[1][i] = default_ioport_writew;
449 ioport_write_table[2][i] = default_ioport_writel;
451 ioport_opaque[i] = NULL;
455 /***********************************************************/
457 void cpu_outb(CPUState *env, int addr, int val)
459 LOG_IOPORT("outb: %04x %02x\n", addr, val);
460 ioport_write(0, addr, val);
461 #ifdef USE_KQEMU
462 if (env)
463 env->last_io_time = cpu_get_time_fast();
464 #endif
467 void cpu_outw(CPUState *env, int addr, int val)
469 LOG_IOPORT("outw: %04x %04x\n", addr, val);
470 ioport_write(1, addr, val);
471 #ifdef USE_KQEMU
472 if (env)
473 env->last_io_time = cpu_get_time_fast();
474 #endif
477 void cpu_outl(CPUState *env, int addr, int val)
479 LOG_IOPORT("outl: %04x %08x\n", addr, val);
480 ioport_write(2, addr, val);
481 #ifdef USE_KQEMU
482 if (env)
483 env->last_io_time = cpu_get_time_fast();
484 #endif
487 int cpu_inb(CPUState *env, int addr)
489 int val;
490 val = ioport_read(0, addr);
491 LOG_IOPORT("inb : %04x %02x\n", addr, val);
492 #ifdef USE_KQEMU
493 if (env)
494 env->last_io_time = cpu_get_time_fast();
495 #endif
496 return val;
499 int cpu_inw(CPUState *env, int addr)
501 int val;
502 val = ioport_read(1, addr);
503 LOG_IOPORT("inw : %04x %04x\n", addr, val);
504 #ifdef USE_KQEMU
505 if (env)
506 env->last_io_time = cpu_get_time_fast();
507 #endif
508 return val;
511 int cpu_inl(CPUState *env, int addr)
513 int val;
514 val = ioport_read(2, addr);
515 LOG_IOPORT("inl : %04x %08x\n", addr, val);
516 #ifdef USE_KQEMU
517 if (env)
518 env->last_io_time = cpu_get_time_fast();
519 #endif
520 return val;
523 /***********************************************************/
524 void hw_error(const char *fmt, ...)
526 va_list ap;
527 CPUState *env;
529 va_start(ap, fmt);
530 fprintf(stderr, "qemu: hardware error: ");
531 vfprintf(stderr, fmt, ap);
532 fprintf(stderr, "\n");
533 for(env = first_cpu; env != NULL; env = env->next_cpu) {
534 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
535 #ifdef TARGET_I386
536 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
537 #else
538 cpu_dump_state(env, stderr, fprintf, 0);
539 #endif
541 va_end(ap);
542 abort();
545 /***************/
546 /* ballooning */
548 static QEMUBalloonEvent *qemu_balloon_event;
549 void *qemu_balloon_event_opaque;
551 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
553 qemu_balloon_event = func;
554 qemu_balloon_event_opaque = opaque;
557 void qemu_balloon(ram_addr_t target)
559 if (qemu_balloon_event)
560 qemu_balloon_event(qemu_balloon_event_opaque, target);
563 ram_addr_t qemu_balloon_status(void)
565 if (qemu_balloon_event)
566 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
567 return 0;
570 /***********************************************************/
571 /* keyboard/mouse */
573 static QEMUPutKBDEvent *qemu_put_kbd_event;
574 static void *qemu_put_kbd_event_opaque;
575 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
576 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
578 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
580 qemu_put_kbd_event_opaque = opaque;
581 qemu_put_kbd_event = func;
584 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
585 void *opaque, int absolute,
586 const char *name)
588 QEMUPutMouseEntry *s, *cursor;
590 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
592 s->qemu_put_mouse_event = func;
593 s->qemu_put_mouse_event_opaque = opaque;
594 s->qemu_put_mouse_event_absolute = absolute;
595 s->qemu_put_mouse_event_name = qemu_strdup(name);
596 s->next = NULL;
598 if (!qemu_put_mouse_event_head) {
599 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
600 return s;
603 cursor = qemu_put_mouse_event_head;
604 while (cursor->next != NULL)
605 cursor = cursor->next;
607 cursor->next = s;
608 qemu_put_mouse_event_current = s;
610 return s;
613 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
615 QEMUPutMouseEntry *prev = NULL, *cursor;
617 if (!qemu_put_mouse_event_head || entry == NULL)
618 return;
620 cursor = qemu_put_mouse_event_head;
621 while (cursor != NULL && cursor != entry) {
622 prev = cursor;
623 cursor = cursor->next;
626 if (cursor == NULL) // does not exist or list empty
627 return;
628 else if (prev == NULL) { // entry is head
629 qemu_put_mouse_event_head = cursor->next;
630 if (qemu_put_mouse_event_current == entry)
631 qemu_put_mouse_event_current = cursor->next;
632 qemu_free(entry->qemu_put_mouse_event_name);
633 qemu_free(entry);
634 return;
637 prev->next = entry->next;
639 if (qemu_put_mouse_event_current == entry)
640 qemu_put_mouse_event_current = prev;
642 qemu_free(entry->qemu_put_mouse_event_name);
643 qemu_free(entry);
646 void kbd_put_keycode(int keycode)
648 if (qemu_put_kbd_event) {
649 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
653 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
655 QEMUPutMouseEvent *mouse_event;
656 void *mouse_event_opaque;
657 int width;
659 if (!qemu_put_mouse_event_current) {
660 return;
663 mouse_event =
664 qemu_put_mouse_event_current->qemu_put_mouse_event;
665 mouse_event_opaque =
666 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
668 if (mouse_event) {
669 if (graphic_rotate) {
670 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
671 width = 0x7fff;
672 else
673 width = graphic_width - 1;
674 mouse_event(mouse_event_opaque,
675 width - dy, dx, dz, buttons_state);
676 } else
677 mouse_event(mouse_event_opaque,
678 dx, dy, dz, buttons_state);
682 int kbd_mouse_is_absolute(void)
684 if (!qemu_put_mouse_event_current)
685 return 0;
687 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
690 void do_info_mice(Monitor *mon)
692 QEMUPutMouseEntry *cursor;
693 int index = 0;
695 if (!qemu_put_mouse_event_head) {
696 monitor_printf(mon, "No mouse devices connected\n");
697 return;
700 monitor_printf(mon, "Mouse devices available:\n");
701 cursor = qemu_put_mouse_event_head;
702 while (cursor != NULL) {
703 monitor_printf(mon, "%c Mouse #%d: %s\n",
704 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
705 index, cursor->qemu_put_mouse_event_name);
706 index++;
707 cursor = cursor->next;
711 void do_mouse_set(Monitor *mon, int index)
713 QEMUPutMouseEntry *cursor;
714 int i = 0;
716 if (!qemu_put_mouse_event_head) {
717 monitor_printf(mon, "No mouse devices connected\n");
718 return;
721 cursor = qemu_put_mouse_event_head;
722 while (cursor != NULL && index != i) {
723 i++;
724 cursor = cursor->next;
727 if (cursor != NULL)
728 qemu_put_mouse_event_current = cursor;
729 else
730 monitor_printf(mon, "Mouse at given index not found\n");
733 /* compute with 96 bit intermediate result: (a*b)/c */
734 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
736 union {
737 uint64_t ll;
738 struct {
739 #ifdef WORDS_BIGENDIAN
740 uint32_t high, low;
741 #else
742 uint32_t low, high;
743 #endif
744 } l;
745 } u, res;
746 uint64_t rl, rh;
748 u.ll = a;
749 rl = (uint64_t)u.l.low * (uint64_t)b;
750 rh = (uint64_t)u.l.high * (uint64_t)b;
751 rh += (rl >> 32);
752 res.l.high = rh / c;
753 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
754 return res.ll;
757 /***********************************************************/
758 /* real time host monotonic timer */
760 #define QEMU_TIMER_BASE 1000000000LL
762 #ifdef WIN32
764 static int64_t clock_freq;
766 static void init_get_clock(void)
768 LARGE_INTEGER freq;
769 int ret;
770 ret = QueryPerformanceFrequency(&freq);
771 if (ret == 0) {
772 fprintf(stderr, "Could not calibrate ticks\n");
773 exit(1);
775 clock_freq = freq.QuadPart;
778 static int64_t get_clock(void)
780 LARGE_INTEGER ti;
781 QueryPerformanceCounter(&ti);
782 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
785 #else
787 static int use_rt_clock;
789 static void init_get_clock(void)
791 use_rt_clock = 0;
792 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
793 || defined(__DragonFly__)
795 struct timespec ts;
796 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
797 use_rt_clock = 1;
800 #endif
803 static int64_t get_clock(void)
805 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
806 || defined(__DragonFly__)
807 if (use_rt_clock) {
808 struct timespec ts;
809 clock_gettime(CLOCK_MONOTONIC, &ts);
810 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
811 } else
812 #endif
814 /* XXX: using gettimeofday leads to problems if the date
815 changes, so it should be avoided. */
816 struct timeval tv;
817 gettimeofday(&tv, NULL);
818 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
821 #endif
823 /* Return the virtual CPU time, based on the instruction counter. */
824 static int64_t cpu_get_icount(void)
826 int64_t icount;
827 CPUState *env = cpu_single_env;;
828 icount = qemu_icount;
829 if (env) {
830 if (!can_do_io(env))
831 fprintf(stderr, "Bad clock read\n");
832 icount -= (env->icount_decr.u16.low + env->icount_extra);
834 return qemu_icount_bias + (icount << icount_time_shift);
837 /***********************************************************/
838 /* guest cycle counter */
840 static int64_t cpu_ticks_prev;
841 static int64_t cpu_ticks_offset;
842 static int64_t cpu_clock_offset;
843 static int cpu_ticks_enabled;
845 /* return the host CPU cycle counter and handle stop/restart */
846 int64_t cpu_get_ticks(void)
848 if (use_icount) {
849 return cpu_get_icount();
851 if (!cpu_ticks_enabled) {
852 return cpu_ticks_offset;
853 } else {
854 int64_t ticks;
855 ticks = cpu_get_real_ticks();
856 if (cpu_ticks_prev > ticks) {
857 /* Note: non increasing ticks may happen if the host uses
858 software suspend */
859 cpu_ticks_offset += cpu_ticks_prev - ticks;
861 cpu_ticks_prev = ticks;
862 return ticks + cpu_ticks_offset;
866 /* return the host CPU monotonic timer and handle stop/restart */
867 static int64_t cpu_get_clock(void)
869 int64_t ti;
870 if (!cpu_ticks_enabled) {
871 return cpu_clock_offset;
872 } else {
873 ti = get_clock();
874 return ti + cpu_clock_offset;
878 /* enable cpu_get_ticks() */
879 void cpu_enable_ticks(void)
881 if (!cpu_ticks_enabled) {
882 cpu_ticks_offset -= cpu_get_real_ticks();
883 cpu_clock_offset -= get_clock();
884 cpu_ticks_enabled = 1;
888 /* disable cpu_get_ticks() : the clock is stopped. You must not call
889 cpu_get_ticks() after that. */
890 void cpu_disable_ticks(void)
892 if (cpu_ticks_enabled) {
893 cpu_ticks_offset = cpu_get_ticks();
894 cpu_clock_offset = cpu_get_clock();
895 cpu_ticks_enabled = 0;
899 /***********************************************************/
900 /* timers */
902 #define QEMU_TIMER_REALTIME 0
903 #define QEMU_TIMER_VIRTUAL 1
905 struct QEMUClock {
906 int type;
907 /* XXX: add frequency */
910 struct QEMUTimer {
911 QEMUClock *clock;
912 int64_t expire_time;
913 QEMUTimerCB *cb;
914 void *opaque;
915 struct QEMUTimer *next;
918 struct qemu_alarm_timer {
919 char const *name;
920 unsigned int flags;
922 int (*start)(struct qemu_alarm_timer *t);
923 void (*stop)(struct qemu_alarm_timer *t);
924 void (*rearm)(struct qemu_alarm_timer *t);
925 void *priv;
928 #define ALARM_FLAG_DYNTICKS 0x1
929 #define ALARM_FLAG_EXPIRED 0x2
931 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
933 return t->flags & ALARM_FLAG_DYNTICKS;
936 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
938 if (!alarm_has_dynticks(t))
939 return;
941 t->rearm(t);
944 /* TODO: MIN_TIMER_REARM_US should be optimized */
945 #define MIN_TIMER_REARM_US 250
947 static struct qemu_alarm_timer *alarm_timer;
948 #ifndef _WIN32
949 static int alarm_timer_rfd, alarm_timer_wfd;
950 #endif
952 #ifdef _WIN32
954 struct qemu_alarm_win32 {
955 MMRESULT timerId;
956 HANDLE host_alarm;
957 unsigned int period;
958 } alarm_win32_data = {0, NULL, -1};
960 static int win32_start_timer(struct qemu_alarm_timer *t);
961 static void win32_stop_timer(struct qemu_alarm_timer *t);
962 static void win32_rearm_timer(struct qemu_alarm_timer *t);
964 #else
966 static int unix_start_timer(struct qemu_alarm_timer *t);
967 static void unix_stop_timer(struct qemu_alarm_timer *t);
969 #ifdef __linux__
971 static int dynticks_start_timer(struct qemu_alarm_timer *t);
972 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
973 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
975 static int hpet_start_timer(struct qemu_alarm_timer *t);
976 static void hpet_stop_timer(struct qemu_alarm_timer *t);
978 static int rtc_start_timer(struct qemu_alarm_timer *t);
979 static void rtc_stop_timer(struct qemu_alarm_timer *t);
981 #endif /* __linux__ */
983 #endif /* _WIN32 */
985 /* Correlation between real and virtual time is always going to be
986 fairly approximate, so ignore small variation.
987 When the guest is idle real and virtual time will be aligned in
988 the IO wait loop. */
989 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
991 static void icount_adjust(void)
993 int64_t cur_time;
994 int64_t cur_icount;
995 int64_t delta;
996 static int64_t last_delta;
997 /* If the VM is not running, then do nothing. */
998 if (!vm_running)
999 return;
1001 cur_time = cpu_get_clock();
1002 cur_icount = qemu_get_clock(vm_clock);
1003 delta = cur_icount - cur_time;
1004 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1005 if (delta > 0
1006 && last_delta + ICOUNT_WOBBLE < delta * 2
1007 && icount_time_shift > 0) {
1008 /* The guest is getting too far ahead. Slow time down. */
1009 icount_time_shift--;
1011 if (delta < 0
1012 && last_delta - ICOUNT_WOBBLE > delta * 2
1013 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1014 /* The guest is getting too far behind. Speed time up. */
1015 icount_time_shift++;
1017 last_delta = delta;
1018 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1021 static void icount_adjust_rt(void * opaque)
1023 qemu_mod_timer(icount_rt_timer,
1024 qemu_get_clock(rt_clock) + 1000);
1025 icount_adjust();
1028 static void icount_adjust_vm(void * opaque)
1030 qemu_mod_timer(icount_vm_timer,
1031 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1032 icount_adjust();
1035 static void init_icount_adjust(void)
1037 /* Have both realtime and virtual time triggers for speed adjustment.
1038 The realtime trigger catches emulated time passing too slowly,
1039 the virtual time trigger catches emulated time passing too fast.
1040 Realtime triggers occur even when idle, so use them less frequently
1041 than VM triggers. */
1042 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1043 qemu_mod_timer(icount_rt_timer,
1044 qemu_get_clock(rt_clock) + 1000);
1045 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1046 qemu_mod_timer(icount_vm_timer,
1047 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1050 static struct qemu_alarm_timer alarm_timers[] = {
1051 #ifndef _WIN32
1052 #ifdef __linux__
1053 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1054 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1055 /* HPET - if available - is preferred */
1056 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1057 /* ...otherwise try RTC */
1058 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1059 #endif
1060 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1061 #else
1062 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1063 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1064 {"win32", 0, win32_start_timer,
1065 win32_stop_timer, NULL, &alarm_win32_data},
1066 #endif
1067 {NULL, }
1070 static void show_available_alarms(void)
1072 int i;
1074 printf("Available alarm timers, in order of precedence:\n");
1075 for (i = 0; alarm_timers[i].name; i++)
1076 printf("%s\n", alarm_timers[i].name);
1079 static void configure_alarms(char const *opt)
1081 int i;
1082 int cur = 0;
1083 int count = ARRAY_SIZE(alarm_timers) - 1;
1084 char *arg;
1085 char *name;
1086 struct qemu_alarm_timer tmp;
1088 if (!strcmp(opt, "?")) {
1089 show_available_alarms();
1090 exit(0);
1093 arg = strdup(opt);
1095 /* Reorder the array */
1096 name = strtok(arg, ",");
1097 while (name) {
1098 for (i = 0; i < count && alarm_timers[i].name; i++) {
1099 if (!strcmp(alarm_timers[i].name, name))
1100 break;
1103 if (i == count) {
1104 fprintf(stderr, "Unknown clock %s\n", name);
1105 goto next;
1108 if (i < cur)
1109 /* Ignore */
1110 goto next;
1112 /* Swap */
1113 tmp = alarm_timers[i];
1114 alarm_timers[i] = alarm_timers[cur];
1115 alarm_timers[cur] = tmp;
1117 cur++;
1118 next:
1119 name = strtok(NULL, ",");
1122 free(arg);
1124 if (cur) {
1125 /* Disable remaining timers */
1126 for (i = cur; i < count; i++)
1127 alarm_timers[i].name = NULL;
1128 } else {
1129 show_available_alarms();
1130 exit(1);
1134 QEMUClock *rt_clock;
1135 QEMUClock *vm_clock;
1137 static QEMUTimer *active_timers[2];
1139 static QEMUClock *qemu_new_clock(int type)
1141 QEMUClock *clock;
1142 clock = qemu_mallocz(sizeof(QEMUClock));
1143 clock->type = type;
1144 return clock;
1147 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1149 QEMUTimer *ts;
1151 ts = qemu_mallocz(sizeof(QEMUTimer));
1152 ts->clock = clock;
1153 ts->cb = cb;
1154 ts->opaque = opaque;
1155 return ts;
1158 void qemu_free_timer(QEMUTimer *ts)
1160 qemu_free(ts);
1163 /* stop a timer, but do not dealloc it */
1164 void qemu_del_timer(QEMUTimer *ts)
1166 QEMUTimer **pt, *t;
1168 /* NOTE: this code must be signal safe because
1169 qemu_timer_expired() can be called from a signal. */
1170 pt = &active_timers[ts->clock->type];
1171 for(;;) {
1172 t = *pt;
1173 if (!t)
1174 break;
1175 if (t == ts) {
1176 *pt = t->next;
1177 break;
1179 pt = &t->next;
1183 /* modify the current timer so that it will be fired when current_time
1184 >= expire_time. The corresponding callback will be called. */
1185 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1187 QEMUTimer **pt, *t;
1189 qemu_del_timer(ts);
1191 /* add the timer in the sorted list */
1192 /* NOTE: this code must be signal safe because
1193 qemu_timer_expired() can be called from a signal. */
1194 pt = &active_timers[ts->clock->type];
1195 for(;;) {
1196 t = *pt;
1197 if (!t)
1198 break;
1199 if (t->expire_time > expire_time)
1200 break;
1201 pt = &t->next;
1203 ts->expire_time = expire_time;
1204 ts->next = *pt;
1205 *pt = ts;
1207 /* Rearm if necessary */
1208 if (pt == &active_timers[ts->clock->type]) {
1209 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1210 qemu_rearm_alarm_timer(alarm_timer);
1212 /* Interrupt execution to force deadline recalculation. */
1213 if (use_icount && cpu_single_env) {
1214 cpu_exit(cpu_single_env);
1219 int qemu_timer_pending(QEMUTimer *ts)
1221 QEMUTimer *t;
1222 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1223 if (t == ts)
1224 return 1;
1226 return 0;
1229 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1231 if (!timer_head)
1232 return 0;
1233 return (timer_head->expire_time <= current_time);
1236 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1238 QEMUTimer *ts;
1240 for(;;) {
1241 ts = *ptimer_head;
1242 if (!ts || ts->expire_time > current_time)
1243 break;
1244 /* remove timer from the list before calling the callback */
1245 *ptimer_head = ts->next;
1246 ts->next = NULL;
1248 /* run the callback (the timer list can be modified) */
1249 ts->cb(ts->opaque);
1253 int64_t qemu_get_clock(QEMUClock *clock)
1255 switch(clock->type) {
1256 case QEMU_TIMER_REALTIME:
1257 return get_clock() / 1000000;
1258 default:
1259 case QEMU_TIMER_VIRTUAL:
1260 if (use_icount) {
1261 return cpu_get_icount();
1262 } else {
1263 return cpu_get_clock();
1268 static void init_timers(void)
1270 init_get_clock();
1271 ticks_per_sec = QEMU_TIMER_BASE;
1272 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1273 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1276 /* save a timer */
1277 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1279 uint64_t expire_time;
1281 if (qemu_timer_pending(ts)) {
1282 expire_time = ts->expire_time;
1283 } else {
1284 expire_time = -1;
1286 qemu_put_be64(f, expire_time);
1289 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1291 uint64_t expire_time;
1293 expire_time = qemu_get_be64(f);
1294 if (expire_time != -1) {
1295 qemu_mod_timer(ts, expire_time);
1296 } else {
1297 qemu_del_timer(ts);
1301 static void timer_save(QEMUFile *f, void *opaque)
1303 if (cpu_ticks_enabled) {
1304 hw_error("cannot save state if virtual timers are running");
1306 qemu_put_be64(f, cpu_ticks_offset);
1307 qemu_put_be64(f, ticks_per_sec);
1308 qemu_put_be64(f, cpu_clock_offset);
1311 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1313 if (version_id != 1 && version_id != 2)
1314 return -EINVAL;
1315 if (cpu_ticks_enabled) {
1316 return -EINVAL;
1318 cpu_ticks_offset=qemu_get_be64(f);
1319 ticks_per_sec=qemu_get_be64(f);
1320 if (version_id == 2) {
1321 cpu_clock_offset=qemu_get_be64(f);
1323 return 0;
1326 #ifdef _WIN32
1327 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1328 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1329 #else
1330 static void host_alarm_handler(int host_signum)
1331 #endif
1333 #if 0
1334 #define DISP_FREQ 1000
1336 static int64_t delta_min = INT64_MAX;
1337 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1338 static int count;
1339 ti = qemu_get_clock(vm_clock);
1340 if (last_clock != 0) {
1341 delta = ti - last_clock;
1342 if (delta < delta_min)
1343 delta_min = delta;
1344 if (delta > delta_max)
1345 delta_max = delta;
1346 delta_cum += delta;
1347 if (++count == DISP_FREQ) {
1348 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1349 muldiv64(delta_min, 1000000, ticks_per_sec),
1350 muldiv64(delta_max, 1000000, ticks_per_sec),
1351 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1352 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1353 count = 0;
1354 delta_min = INT64_MAX;
1355 delta_max = 0;
1356 delta_cum = 0;
1359 last_clock = ti;
1361 #endif
1362 if (1 ||
1363 alarm_has_dynticks(alarm_timer) ||
1364 (!use_icount &&
1365 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1366 qemu_get_clock(vm_clock))) ||
1367 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1368 qemu_get_clock(rt_clock))) {
1369 CPUState *env = next_cpu;
1371 #ifdef _WIN32
1372 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1373 SetEvent(data->host_alarm);
1374 #else
1375 static const char byte = 0;
1376 write(alarm_timer_wfd, &byte, sizeof(byte));
1377 #endif
1378 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1380 if (env) {
1381 /* stop the currently executing cpu because a timer occured */
1382 cpu_exit(env);
1383 #ifdef USE_KQEMU
1384 if (env->kqemu_enabled) {
1385 kqemu_cpu_interrupt(env);
1387 #endif
1389 event_pending = 1;
1393 static int64_t qemu_next_deadline(void)
1395 int64_t delta;
1397 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1398 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1399 qemu_get_clock(vm_clock);
1400 } else {
1401 /* To avoid problems with overflow limit this to 2^32. */
1402 delta = INT32_MAX;
1405 if (delta < 0)
1406 delta = 0;
1408 return delta;
1411 #if defined(__linux__) || defined(_WIN32)
1412 static uint64_t qemu_next_deadline_dyntick(void)
1414 int64_t delta;
1415 int64_t rtdelta;
1417 if (use_icount)
1418 delta = INT32_MAX;
1419 else
1420 delta = (qemu_next_deadline() + 999) / 1000;
1422 if (active_timers[QEMU_TIMER_REALTIME]) {
1423 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1424 qemu_get_clock(rt_clock))*1000;
1425 if (rtdelta < delta)
1426 delta = rtdelta;
1429 if (delta < MIN_TIMER_REARM_US)
1430 delta = MIN_TIMER_REARM_US;
1432 return delta;
1434 #endif
1436 #ifndef _WIN32
1438 /* Sets a specific flag */
1439 static int fcntl_setfl(int fd, int flag)
1441 int flags;
1443 flags = fcntl(fd, F_GETFL);
1444 if (flags == -1)
1445 return -errno;
1447 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1448 return -errno;
1450 return 0;
1453 #if defined(__linux__)
1455 #define RTC_FREQ 1024
1457 static void enable_sigio_timer(int fd)
1459 struct sigaction act;
1461 /* timer signal */
1462 sigfillset(&act.sa_mask);
1463 act.sa_flags = 0;
1464 act.sa_handler = host_alarm_handler;
1466 sigaction(SIGIO, &act, NULL);
1467 fcntl_setfl(fd, O_ASYNC);
1468 fcntl(fd, F_SETOWN, getpid());
1471 static int hpet_start_timer(struct qemu_alarm_timer *t)
1473 struct hpet_info info;
1474 int r, fd;
1476 fd = open("/dev/hpet", O_RDONLY);
1477 if (fd < 0)
1478 return -1;
1480 /* Set frequency */
1481 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1482 if (r < 0) {
1483 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1484 "error, but for better emulation accuracy type:\n"
1485 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1486 goto fail;
1489 /* Check capabilities */
1490 r = ioctl(fd, HPET_INFO, &info);
1491 if (r < 0)
1492 goto fail;
1494 /* Enable periodic mode */
1495 r = ioctl(fd, HPET_EPI, 0);
1496 if (info.hi_flags && (r < 0))
1497 goto fail;
1499 /* Enable interrupt */
1500 r = ioctl(fd, HPET_IE_ON, 0);
1501 if (r < 0)
1502 goto fail;
1504 enable_sigio_timer(fd);
1505 t->priv = (void *)(long)fd;
1507 return 0;
1508 fail:
1509 close(fd);
1510 return -1;
1513 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1515 int fd = (long)t->priv;
1517 close(fd);
1520 static int rtc_start_timer(struct qemu_alarm_timer *t)
1522 int rtc_fd;
1523 unsigned long current_rtc_freq = 0;
1525 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1526 if (rtc_fd < 0)
1527 return -1;
1528 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1529 if (current_rtc_freq != RTC_FREQ &&
1530 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1531 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1532 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1533 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1534 goto fail;
1536 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1537 fail:
1538 close(rtc_fd);
1539 return -1;
1542 enable_sigio_timer(rtc_fd);
1544 t->priv = (void *)(long)rtc_fd;
1546 return 0;
1549 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1551 int rtc_fd = (long)t->priv;
1553 close(rtc_fd);
1556 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1558 struct sigevent ev;
1559 timer_t host_timer;
1560 struct sigaction act;
1562 sigfillset(&act.sa_mask);
1563 act.sa_flags = 0;
1564 act.sa_handler = host_alarm_handler;
1566 sigaction(SIGALRM, &act, NULL);
1568 ev.sigev_value.sival_int = 0;
1569 ev.sigev_notify = SIGEV_SIGNAL;
1570 ev.sigev_signo = SIGALRM;
1572 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1573 perror("timer_create");
1575 /* disable dynticks */
1576 fprintf(stderr, "Dynamic Ticks disabled\n");
1578 return -1;
1581 t->priv = (void *)(long)host_timer;
1583 return 0;
1586 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1588 timer_t host_timer = (timer_t)(long)t->priv;
1590 timer_delete(host_timer);
1593 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1595 timer_t host_timer = (timer_t)(long)t->priv;
1596 struct itimerspec timeout;
1597 int64_t nearest_delta_us = INT64_MAX;
1598 int64_t current_us;
1600 if (!active_timers[QEMU_TIMER_REALTIME] &&
1601 !active_timers[QEMU_TIMER_VIRTUAL])
1602 return;
1604 nearest_delta_us = qemu_next_deadline_dyntick();
1606 /* check whether a timer is already running */
1607 if (timer_gettime(host_timer, &timeout)) {
1608 perror("gettime");
1609 fprintf(stderr, "Internal timer error: aborting\n");
1610 exit(1);
1612 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1613 if (current_us && current_us <= nearest_delta_us)
1614 return;
1616 timeout.it_interval.tv_sec = 0;
1617 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1618 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1619 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1620 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1621 perror("settime");
1622 fprintf(stderr, "Internal timer error: aborting\n");
1623 exit(1);
1627 #endif /* defined(__linux__) */
1629 static int unix_start_timer(struct qemu_alarm_timer *t)
1631 struct sigaction act;
1632 struct itimerval itv;
1633 int err;
1635 /* timer signal */
1636 sigfillset(&act.sa_mask);
1637 act.sa_flags = 0;
1638 act.sa_handler = host_alarm_handler;
1640 sigaction(SIGALRM, &act, NULL);
1642 itv.it_interval.tv_sec = 0;
1643 /* for i386 kernel 2.6 to get 1 ms */
1644 itv.it_interval.tv_usec = 999;
1645 itv.it_value.tv_sec = 0;
1646 itv.it_value.tv_usec = 10 * 1000;
1648 err = setitimer(ITIMER_REAL, &itv, NULL);
1649 if (err)
1650 return -1;
1652 return 0;
1655 static void unix_stop_timer(struct qemu_alarm_timer *t)
1657 struct itimerval itv;
1659 memset(&itv, 0, sizeof(itv));
1660 setitimer(ITIMER_REAL, &itv, NULL);
1663 #endif /* !defined(_WIN32) */
1665 static void try_to_rearm_timer(void *opaque)
1667 struct qemu_alarm_timer *t = opaque;
1668 #ifndef _WIN32
1669 ssize_t len;
1671 /* Drain the notify pipe */
1672 do {
1673 char buffer[512];
1674 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1675 } while ((len == -1 && errno == EINTR) || len > 0);
1676 #endif
1678 if (t->flags & ALARM_FLAG_EXPIRED) {
1679 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1680 qemu_rearm_alarm_timer(alarm_timer);
1684 #ifdef _WIN32
1686 static int win32_start_timer(struct qemu_alarm_timer *t)
1688 TIMECAPS tc;
1689 struct qemu_alarm_win32 *data = t->priv;
1690 UINT flags;
1692 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1693 if (!data->host_alarm) {
1694 perror("Failed CreateEvent");
1695 return -1;
1698 memset(&tc, 0, sizeof(tc));
1699 timeGetDevCaps(&tc, sizeof(tc));
1701 if (data->period < tc.wPeriodMin)
1702 data->period = tc.wPeriodMin;
1704 timeBeginPeriod(data->period);
1706 flags = TIME_CALLBACK_FUNCTION;
1707 if (alarm_has_dynticks(t))
1708 flags |= TIME_ONESHOT;
1709 else
1710 flags |= TIME_PERIODIC;
1712 data->timerId = timeSetEvent(1, // interval (ms)
1713 data->period, // resolution
1714 host_alarm_handler, // function
1715 (DWORD)t, // parameter
1716 flags);
1718 if (!data->timerId) {
1719 perror("Failed to initialize win32 alarm timer");
1721 timeEndPeriod(data->period);
1722 CloseHandle(data->host_alarm);
1723 return -1;
1726 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1728 return 0;
1731 static void win32_stop_timer(struct qemu_alarm_timer *t)
1733 struct qemu_alarm_win32 *data = t->priv;
1735 timeKillEvent(data->timerId);
1736 timeEndPeriod(data->period);
1738 CloseHandle(data->host_alarm);
1741 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1743 struct qemu_alarm_win32 *data = t->priv;
1744 uint64_t nearest_delta_us;
1746 if (!active_timers[QEMU_TIMER_REALTIME] &&
1747 !active_timers[QEMU_TIMER_VIRTUAL])
1748 return;
1750 nearest_delta_us = qemu_next_deadline_dyntick();
1751 nearest_delta_us /= 1000;
1753 timeKillEvent(data->timerId);
1755 data->timerId = timeSetEvent(1,
1756 data->period,
1757 host_alarm_handler,
1758 (DWORD)t,
1759 TIME_ONESHOT | TIME_PERIODIC);
1761 if (!data->timerId) {
1762 perror("Failed to re-arm win32 alarm timer");
1764 timeEndPeriod(data->period);
1765 CloseHandle(data->host_alarm);
1766 exit(1);
1770 #endif /* _WIN32 */
1772 static int init_timer_alarm(void)
1774 struct qemu_alarm_timer *t = NULL;
1775 int i, err = -1;
1777 #ifndef _WIN32
1778 int fds[2];
1780 err = pipe(fds);
1781 if (err == -1)
1782 return -errno;
1784 err = fcntl_setfl(fds[0], O_NONBLOCK);
1785 if (err < 0)
1786 goto fail;
1788 err = fcntl_setfl(fds[1], O_NONBLOCK);
1789 if (err < 0)
1790 goto fail;
1792 alarm_timer_rfd = fds[0];
1793 alarm_timer_wfd = fds[1];
1794 #endif
1796 for (i = 0; alarm_timers[i].name; i++) {
1797 t = &alarm_timers[i];
1799 err = t->start(t);
1800 if (!err)
1801 break;
1804 if (err) {
1805 err = -ENOENT;
1806 goto fail;
1809 #ifndef _WIN32
1810 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1811 try_to_rearm_timer, NULL, t);
1812 #endif
1814 alarm_timer = t;
1816 return 0;
1818 fail:
1819 #ifndef _WIN32
1820 close(fds[0]);
1821 close(fds[1]);
1822 #endif
1823 return err;
1826 static void quit_timers(void)
1828 alarm_timer->stop(alarm_timer);
1829 alarm_timer = NULL;
1832 /***********************************************************/
1833 /* host time/date access */
1834 void qemu_get_timedate(struct tm *tm, int offset)
1836 time_t ti;
1837 struct tm *ret;
1839 time(&ti);
1840 ti += offset;
1841 if (rtc_date_offset == -1) {
1842 if (rtc_utc)
1843 ret = gmtime(&ti);
1844 else
1845 ret = localtime(&ti);
1846 } else {
1847 ti -= rtc_date_offset;
1848 ret = gmtime(&ti);
1851 memcpy(tm, ret, sizeof(struct tm));
1854 int qemu_timedate_diff(struct tm *tm)
1856 time_t seconds;
1858 if (rtc_date_offset == -1)
1859 if (rtc_utc)
1860 seconds = mktimegm(tm);
1861 else
1862 seconds = mktime(tm);
1863 else
1864 seconds = mktimegm(tm) + rtc_date_offset;
1866 return seconds - time(NULL);
1869 #ifdef _WIN32
1870 static void socket_cleanup(void)
1872 WSACleanup();
1875 static int socket_init(void)
1877 WSADATA Data;
1878 int ret, err;
1880 ret = WSAStartup(MAKEWORD(2,2), &Data);
1881 if (ret != 0) {
1882 err = WSAGetLastError();
1883 fprintf(stderr, "WSAStartup: %d\n", err);
1884 return -1;
1886 atexit(socket_cleanup);
1887 return 0;
1889 #endif
1891 const char *get_opt_name(char *buf, int buf_size, const char *p)
1893 char *q;
1895 q = buf;
1896 while (*p != '\0' && *p != '=') {
1897 if (q && (q - buf) < buf_size - 1)
1898 *q++ = *p;
1899 p++;
1901 if (q)
1902 *q = '\0';
1904 return p;
1907 const char *get_opt_value(char *buf, int buf_size, const char *p)
1909 char *q;
1911 q = buf;
1912 while (*p != '\0') {
1913 if (*p == ',') {
1914 if (*(p + 1) != ',')
1915 break;
1916 p++;
1918 if (q && (q - buf) < buf_size - 1)
1919 *q++ = *p;
1920 p++;
1922 if (q)
1923 *q = '\0';
1925 return p;
1928 int get_param_value(char *buf, int buf_size,
1929 const char *tag, const char *str)
1931 const char *p;
1932 char option[128];
1934 p = str;
1935 for(;;) {
1936 p = get_opt_name(option, sizeof(option), p);
1937 if (*p != '=')
1938 break;
1939 p++;
1940 if (!strcmp(tag, option)) {
1941 (void)get_opt_value(buf, buf_size, p);
1942 return strlen(buf);
1943 } else {
1944 p = get_opt_value(NULL, 0, p);
1946 if (*p != ',')
1947 break;
1948 p++;
1950 return 0;
1953 int check_params(char *buf, int buf_size,
1954 const char * const *params, const char *str)
1956 const char *p;
1957 int i;
1959 p = str;
1960 for(;;) {
1961 p = get_opt_name(buf, buf_size, p);
1962 if (*p != '=')
1963 return -1;
1964 p++;
1965 for(i = 0; params[i] != NULL; i++)
1966 if (!strcmp(params[i], buf))
1967 break;
1968 if (params[i] == NULL)
1969 return -1;
1970 p = get_opt_value(NULL, 0, p);
1971 if (*p != ',')
1972 break;
1973 p++;
1975 return 0;
1978 /***********************************************************/
1979 /* Bluetooth support */
1980 static int nb_hcis;
1981 static int cur_hci;
1982 static struct HCIInfo *hci_table[MAX_NICS];
1984 static struct bt_vlan_s {
1985 struct bt_scatternet_s net;
1986 int id;
1987 struct bt_vlan_s *next;
1988 } *first_bt_vlan;
1990 /* find or alloc a new bluetooth "VLAN" */
1991 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1993 struct bt_vlan_s **pvlan, *vlan;
1994 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1995 if (vlan->id == id)
1996 return &vlan->net;
1998 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1999 vlan->id = id;
2000 pvlan = &first_bt_vlan;
2001 while (*pvlan != NULL)
2002 pvlan = &(*pvlan)->next;
2003 *pvlan = vlan;
2004 return &vlan->net;
2007 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
2011 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
2013 return -ENOTSUP;
2016 static struct HCIInfo null_hci = {
2017 .cmd_send = null_hci_send,
2018 .sco_send = null_hci_send,
2019 .acl_send = null_hci_send,
2020 .bdaddr_set = null_hci_addr_set,
2023 struct HCIInfo *qemu_next_hci(void)
2025 if (cur_hci == nb_hcis)
2026 return &null_hci;
2028 return hci_table[cur_hci++];
2031 static struct HCIInfo *hci_init(const char *str)
2033 char *endp;
2034 struct bt_scatternet_s *vlan = 0;
2036 if (!strcmp(str, "null"))
2037 /* null */
2038 return &null_hci;
2039 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2040 /* host[:hciN] */
2041 return bt_host_hci(str[4] ? str + 5 : "hci0");
2042 else if (!strncmp(str, "hci", 3)) {
2043 /* hci[,vlan=n] */
2044 if (str[3]) {
2045 if (!strncmp(str + 3, ",vlan=", 6)) {
2046 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2047 if (*endp)
2048 vlan = 0;
2050 } else
2051 vlan = qemu_find_bt_vlan(0);
2052 if (vlan)
2053 return bt_new_hci(vlan);
2056 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2058 return 0;
2061 static int bt_hci_parse(const char *str)
2063 struct HCIInfo *hci;
2064 bdaddr_t bdaddr;
2066 if (nb_hcis >= MAX_NICS) {
2067 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2068 return -1;
2071 hci = hci_init(str);
2072 if (!hci)
2073 return -1;
2075 bdaddr.b[0] = 0x52;
2076 bdaddr.b[1] = 0x54;
2077 bdaddr.b[2] = 0x00;
2078 bdaddr.b[3] = 0x12;
2079 bdaddr.b[4] = 0x34;
2080 bdaddr.b[5] = 0x56 + nb_hcis;
2081 hci->bdaddr_set(hci, bdaddr.b);
2083 hci_table[nb_hcis++] = hci;
2085 return 0;
2088 static void bt_vhci_add(int vlan_id)
2090 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2092 if (!vlan->slave)
2093 fprintf(stderr, "qemu: warning: adding a VHCI to "
2094 "an empty scatternet %i\n", vlan_id);
2096 bt_vhci_init(bt_new_hci(vlan));
2099 static struct bt_device_s *bt_device_add(const char *opt)
2101 struct bt_scatternet_s *vlan;
2102 int vlan_id = 0;
2103 char *endp = strstr(opt, ",vlan=");
2104 int len = (endp ? endp - opt : strlen(opt)) + 1;
2105 char devname[10];
2107 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2109 if (endp) {
2110 vlan_id = strtol(endp + 6, &endp, 0);
2111 if (*endp) {
2112 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2113 return 0;
2117 vlan = qemu_find_bt_vlan(vlan_id);
2119 if (!vlan->slave)
2120 fprintf(stderr, "qemu: warning: adding a slave device to "
2121 "an empty scatternet %i\n", vlan_id);
2123 if (!strcmp(devname, "keyboard"))
2124 return bt_keyboard_init(vlan);
2126 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2127 return 0;
2130 static int bt_parse(const char *opt)
2132 const char *endp, *p;
2133 int vlan;
2135 if (strstart(opt, "hci", &endp)) {
2136 if (!*endp || *endp == ',') {
2137 if (*endp)
2138 if (!strstart(endp, ",vlan=", 0))
2139 opt = endp + 1;
2141 return bt_hci_parse(opt);
2143 } else if (strstart(opt, "vhci", &endp)) {
2144 if (!*endp || *endp == ',') {
2145 if (*endp) {
2146 if (strstart(endp, ",vlan=", &p)) {
2147 vlan = strtol(p, (char **) &endp, 0);
2148 if (*endp) {
2149 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2150 return 1;
2152 } else {
2153 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2154 return 1;
2156 } else
2157 vlan = 0;
2159 bt_vhci_add(vlan);
2160 return 0;
2162 } else if (strstart(opt, "device:", &endp))
2163 return !bt_device_add(endp);
2165 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2166 return 1;
2169 /***********************************************************/
2170 /* QEMU Block devices */
2172 #define HD_ALIAS "index=%d,media=disk"
2173 #define CDROM_ALIAS "index=2,media=cdrom"
2174 #define FD_ALIAS "index=%d,if=floppy"
2175 #define PFLASH_ALIAS "if=pflash"
2176 #define MTD_ALIAS "if=mtd"
2177 #define SD_ALIAS "index=0,if=sd"
2179 static int drive_opt_get_free_idx(void)
2181 int index;
2183 for (index = 0; index < MAX_DRIVES; index++)
2184 if (!drives_opt[index].used) {
2185 drives_opt[index].used = 1;
2186 return index;
2189 return -1;
2192 static int drive_get_free_idx(void)
2194 int index;
2196 for (index = 0; index < MAX_DRIVES; index++)
2197 if (!drives_table[index].used) {
2198 drives_table[index].used = 1;
2199 return index;
2202 return -1;
2205 int drive_add(const char *file, const char *fmt, ...)
2207 va_list ap;
2208 int index = drive_opt_get_free_idx();
2210 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2211 fprintf(stderr, "qemu: too many drives\n");
2212 return -1;
2215 drives_opt[index].file = file;
2216 va_start(ap, fmt);
2217 vsnprintf(drives_opt[index].opt,
2218 sizeof(drives_opt[0].opt), fmt, ap);
2219 va_end(ap);
2221 nb_drives_opt++;
2222 return index;
2225 void drive_remove(int index)
2227 drives_opt[index].used = 0;
2228 nb_drives_opt--;
2231 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2233 int index;
2235 /* seek interface, bus and unit */
2237 for (index = 0; index < MAX_DRIVES; index++)
2238 if (drives_table[index].type == type &&
2239 drives_table[index].bus == bus &&
2240 drives_table[index].unit == unit &&
2241 drives_table[index].used)
2242 return index;
2244 return -1;
2247 int drive_get_max_bus(BlockInterfaceType type)
2249 int max_bus;
2250 int index;
2252 max_bus = -1;
2253 for (index = 0; index < nb_drives; index++) {
2254 if(drives_table[index].type == type &&
2255 drives_table[index].bus > max_bus)
2256 max_bus = drives_table[index].bus;
2258 return max_bus;
2261 const char *drive_get_serial(BlockDriverState *bdrv)
2263 int index;
2265 for (index = 0; index < nb_drives; index++)
2266 if (drives_table[index].bdrv == bdrv)
2267 return drives_table[index].serial;
2269 return "\0";
2272 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2274 int index;
2276 for (index = 0; index < nb_drives; index++)
2277 if (drives_table[index].bdrv == bdrv)
2278 return drives_table[index].onerror;
2280 return BLOCK_ERR_STOP_ENOSPC;
2283 static void bdrv_format_print(void *opaque, const char *name)
2285 fprintf(stderr, " %s", name);
2288 void drive_uninit(BlockDriverState *bdrv)
2290 int i;
2292 for (i = 0; i < MAX_DRIVES; i++)
2293 if (drives_table[i].bdrv == bdrv) {
2294 drives_table[i].bdrv = NULL;
2295 drives_table[i].used = 0;
2296 drive_remove(drives_table[i].drive_opt_idx);
2297 nb_drives--;
2298 break;
2302 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2304 char buf[128];
2305 char file[1024];
2306 char devname[128];
2307 char serial[21];
2308 const char *mediastr = "";
2309 BlockInterfaceType type;
2310 enum { MEDIA_DISK, MEDIA_CDROM } media;
2311 int bus_id, unit_id;
2312 int cyls, heads, secs, translation;
2313 BlockDriverState *bdrv;
2314 BlockDriver *drv = NULL;
2315 QEMUMachine *machine = opaque;
2316 int max_devs;
2317 int index;
2318 int cache;
2319 int bdrv_flags, onerror;
2320 int drives_table_idx;
2321 char *str = arg->opt;
2322 static const char * const params[] = { "bus", "unit", "if", "index",
2323 "cyls", "heads", "secs", "trans",
2324 "media", "snapshot", "file",
2325 "cache", "format", "serial", "werror",
2326 "boot", NULL };
2328 if (check_params(buf, sizeof(buf), params, str) < 0) {
2329 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2330 buf, str);
2331 return -1;
2334 file[0] = 0;
2335 cyls = heads = secs = 0;
2336 bus_id = 0;
2337 unit_id = -1;
2338 translation = BIOS_ATA_TRANSLATION_AUTO;
2339 index = -1;
2340 cache = 3;
2342 if (machine->use_scsi) {
2343 type = IF_SCSI;
2344 max_devs = MAX_SCSI_DEVS;
2345 pstrcpy(devname, sizeof(devname), "scsi");
2346 } else {
2347 type = IF_IDE;
2348 max_devs = MAX_IDE_DEVS;
2349 pstrcpy(devname, sizeof(devname), "ide");
2351 media = MEDIA_DISK;
2353 /* extract parameters */
2355 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2356 bus_id = strtol(buf, NULL, 0);
2357 if (bus_id < 0) {
2358 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2359 return -1;
2363 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2364 unit_id = strtol(buf, NULL, 0);
2365 if (unit_id < 0) {
2366 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2367 return -1;
2371 if (get_param_value(buf, sizeof(buf), "if", str)) {
2372 pstrcpy(devname, sizeof(devname), buf);
2373 if (!strcmp(buf, "ide")) {
2374 type = IF_IDE;
2375 max_devs = MAX_IDE_DEVS;
2376 } else if (!strcmp(buf, "scsi")) {
2377 type = IF_SCSI;
2378 max_devs = MAX_SCSI_DEVS;
2379 } else if (!strcmp(buf, "floppy")) {
2380 type = IF_FLOPPY;
2381 max_devs = 0;
2382 } else if (!strcmp(buf, "pflash")) {
2383 type = IF_PFLASH;
2384 max_devs = 0;
2385 } else if (!strcmp(buf, "mtd")) {
2386 type = IF_MTD;
2387 max_devs = 0;
2388 } else if (!strcmp(buf, "sd")) {
2389 type = IF_SD;
2390 max_devs = 0;
2391 } else if (!strcmp(buf, "virtio")) {
2392 type = IF_VIRTIO;
2393 max_devs = 0;
2394 } else {
2395 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2396 return -1;
2400 if (get_param_value(buf, sizeof(buf), "index", str)) {
2401 index = strtol(buf, NULL, 0);
2402 if (index < 0) {
2403 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2404 return -1;
2408 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2409 cyls = strtol(buf, NULL, 0);
2412 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2413 heads = strtol(buf, NULL, 0);
2416 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2417 secs = strtol(buf, NULL, 0);
2420 if (cyls || heads || secs) {
2421 if (cyls < 1 || cyls > 16383) {
2422 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2423 return -1;
2425 if (heads < 1 || heads > 16) {
2426 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2427 return -1;
2429 if (secs < 1 || secs > 63) {
2430 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2431 return -1;
2435 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2436 if (!cyls) {
2437 fprintf(stderr,
2438 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2439 str);
2440 return -1;
2442 if (!strcmp(buf, "none"))
2443 translation = BIOS_ATA_TRANSLATION_NONE;
2444 else if (!strcmp(buf, "lba"))
2445 translation = BIOS_ATA_TRANSLATION_LBA;
2446 else if (!strcmp(buf, "auto"))
2447 translation = BIOS_ATA_TRANSLATION_AUTO;
2448 else {
2449 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2450 return -1;
2454 if (get_param_value(buf, sizeof(buf), "media", str)) {
2455 if (!strcmp(buf, "disk")) {
2456 media = MEDIA_DISK;
2457 } else if (!strcmp(buf, "cdrom")) {
2458 if (cyls || secs || heads) {
2459 fprintf(stderr,
2460 "qemu: '%s' invalid physical CHS format\n", str);
2461 return -1;
2463 media = MEDIA_CDROM;
2464 } else {
2465 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2466 return -1;
2470 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2471 if (!strcmp(buf, "on"))
2472 snapshot = 1;
2473 else if (!strcmp(buf, "off"))
2474 snapshot = 0;
2475 else {
2476 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2477 return -1;
2481 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2482 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2483 cache = 0;
2484 else if (!strcmp(buf, "writethrough"))
2485 cache = 1;
2486 else if (!strcmp(buf, "writeback"))
2487 cache = 2;
2488 else {
2489 fprintf(stderr, "qemu: invalid cache option\n");
2490 return -1;
2494 if (get_param_value(buf, sizeof(buf), "format", str)) {
2495 if (strcmp(buf, "?") == 0) {
2496 fprintf(stderr, "qemu: Supported formats:");
2497 bdrv_iterate_format(bdrv_format_print, NULL);
2498 fprintf(stderr, "\n");
2499 return -1;
2501 drv = bdrv_find_format(buf);
2502 if (!drv) {
2503 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2504 return -1;
2508 if (get_param_value(buf, sizeof(buf), "boot", str)) {
2509 if (!strcmp(buf, "on")) {
2510 if (extboot_drive != -1) {
2511 fprintf(stderr, "qemu: two bootable drives specified\n");
2512 return -1;
2514 extboot_drive = nb_drives;
2515 } else if (strcmp(buf, "off")) {
2516 fprintf(stderr, "qemu: '%s' invalid boot option\n", str);
2517 return -1;
2521 if (arg->file == NULL)
2522 get_param_value(file, sizeof(file), "file", str);
2523 else
2524 pstrcpy(file, sizeof(file), arg->file);
2526 if (!get_param_value(serial, sizeof(serial), "serial", str))
2527 memset(serial, 0, sizeof(serial));
2529 onerror = BLOCK_ERR_STOP_ENOSPC;
2530 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2531 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2532 fprintf(stderr, "werror is no supported by this format\n");
2533 return -1;
2535 if (!strcmp(buf, "ignore"))
2536 onerror = BLOCK_ERR_IGNORE;
2537 else if (!strcmp(buf, "enospc"))
2538 onerror = BLOCK_ERR_STOP_ENOSPC;
2539 else if (!strcmp(buf, "stop"))
2540 onerror = BLOCK_ERR_STOP_ANY;
2541 else if (!strcmp(buf, "report"))
2542 onerror = BLOCK_ERR_REPORT;
2543 else {
2544 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2545 return -1;
2549 /* compute bus and unit according index */
2551 if (index != -1) {
2552 if (bus_id != 0 || unit_id != -1) {
2553 fprintf(stderr,
2554 "qemu: '%s' index cannot be used with bus and unit\n", str);
2555 return -1;
2557 if (max_devs == 0)
2559 unit_id = index;
2560 bus_id = 0;
2561 } else {
2562 unit_id = index % max_devs;
2563 bus_id = index / max_devs;
2567 /* if user doesn't specify a unit_id,
2568 * try to find the first free
2571 if (unit_id == -1) {
2572 unit_id = 0;
2573 while (drive_get_index(type, bus_id, unit_id) != -1) {
2574 unit_id++;
2575 if (max_devs && unit_id >= max_devs) {
2576 unit_id -= max_devs;
2577 bus_id++;
2582 /* check unit id */
2584 if (max_devs && unit_id >= max_devs) {
2585 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2586 str, unit_id, max_devs - 1);
2587 return -1;
2591 * ignore multiple definitions
2594 if (drive_get_index(type, bus_id, unit_id) != -1)
2595 return -2;
2597 /* init */
2599 if (type == IF_IDE || type == IF_SCSI)
2600 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2601 if (max_devs)
2602 snprintf(buf, sizeof(buf), "%s%i%s%i",
2603 devname, bus_id, mediastr, unit_id);
2604 else
2605 snprintf(buf, sizeof(buf), "%s%s%i",
2606 devname, mediastr, unit_id);
2607 bdrv = bdrv_new(buf);
2608 drives_table_idx = drive_get_free_idx();
2609 drives_table[drives_table_idx].bdrv = bdrv;
2610 drives_table[drives_table_idx].type = type;
2611 drives_table[drives_table_idx].bus = bus_id;
2612 drives_table[drives_table_idx].unit = unit_id;
2613 drives_table[drives_table_idx].onerror = onerror;
2614 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2615 strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2616 nb_drives++;
2618 switch(type) {
2619 case IF_IDE:
2620 case IF_SCSI:
2621 switch(media) {
2622 case MEDIA_DISK:
2623 if (cyls != 0) {
2624 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2625 bdrv_set_translation_hint(bdrv, translation);
2627 break;
2628 case MEDIA_CDROM:
2629 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2630 break;
2632 break;
2633 case IF_SD:
2634 /* FIXME: This isn't really a floppy, but it's a reasonable
2635 approximation. */
2636 case IF_FLOPPY:
2637 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2638 break;
2639 case IF_PFLASH:
2640 case IF_MTD:
2641 case IF_VIRTIO:
2642 break;
2644 if (!file[0])
2645 return -2;
2646 bdrv_flags = 0;
2647 if (snapshot) {
2648 bdrv_flags |= BDRV_O_SNAPSHOT;
2649 cache = 2; /* always use write-back with snapshot */
2651 if (cache == 0) /* no caching */
2652 bdrv_flags |= BDRV_O_NOCACHE;
2653 else if (cache == 2) /* write-back */
2654 bdrv_flags |= BDRV_O_CACHE_WB;
2655 else if (cache == 3) /* not specified */
2656 bdrv_flags |= BDRV_O_CACHE_DEF;
2657 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2658 fprintf(stderr, "qemu: could not open disk image %s\n",
2659 file);
2660 return -1;
2662 if (bdrv_key_required(bdrv))
2663 autostart = 0;
2664 return drives_table_idx;
2667 /***********************************************************/
2668 /* USB devices */
2670 static USBPort *used_usb_ports;
2671 static USBPort *free_usb_ports;
2673 /* ??? Maybe change this to register a hub to keep track of the topology. */
2674 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2675 usb_attachfn attach)
2677 port->opaque = opaque;
2678 port->index = index;
2679 port->attach = attach;
2680 port->next = free_usb_ports;
2681 free_usb_ports = port;
2684 int usb_device_add_dev(USBDevice *dev)
2686 USBPort *port;
2688 /* Find a USB port to add the device to. */
2689 port = free_usb_ports;
2690 if (!port->next) {
2691 USBDevice *hub;
2693 /* Create a new hub and chain it on. */
2694 free_usb_ports = NULL;
2695 port->next = used_usb_ports;
2696 used_usb_ports = port;
2698 hub = usb_hub_init(VM_USB_HUB_SIZE);
2699 usb_attach(port, hub);
2700 port = free_usb_ports;
2703 free_usb_ports = port->next;
2704 port->next = used_usb_ports;
2705 used_usb_ports = port;
2706 usb_attach(port, dev);
2707 return 0;
2710 static void usb_msd_password_cb(void *opaque, int err)
2712 USBDevice *dev = opaque;
2714 if (!err)
2715 usb_device_add_dev(dev);
2716 else
2717 dev->handle_destroy(dev);
2720 static int usb_device_add(const char *devname, int is_hotplug)
2722 const char *p;
2723 USBDevice *dev;
2725 if (!free_usb_ports)
2726 return -1;
2728 if (strstart(devname, "host:", &p)) {
2729 dev = usb_host_device_open(p);
2730 } else if (!strcmp(devname, "mouse")) {
2731 dev = usb_mouse_init();
2732 } else if (!strcmp(devname, "tablet")) {
2733 dev = usb_tablet_init();
2734 } else if (!strcmp(devname, "keyboard")) {
2735 dev = usb_keyboard_init();
2736 } else if (strstart(devname, "disk:", &p)) {
2737 BlockDriverState *bs;
2739 dev = usb_msd_init(p);
2740 if (!dev)
2741 return -1;
2742 bs = usb_msd_get_bdrv(dev);
2743 if (bdrv_key_required(bs)) {
2744 autostart = 0;
2745 if (is_hotplug) {
2746 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2747 dev);
2748 return 0;
2751 } else if (!strcmp(devname, "wacom-tablet")) {
2752 dev = usb_wacom_init();
2753 } else if (strstart(devname, "serial:", &p)) {
2754 dev = usb_serial_init(p);
2755 #ifdef CONFIG_BRLAPI
2756 } else if (!strcmp(devname, "braille")) {
2757 dev = usb_baum_init();
2758 #endif
2759 } else if (strstart(devname, "net:", &p)) {
2760 int nic = nb_nics;
2762 if (net_client_init("nic", p) < 0)
2763 return -1;
2764 nd_table[nic].model = "usb";
2765 dev = usb_net_init(&nd_table[nic]);
2766 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2767 dev = usb_bt_init(devname[2] ? hci_init(p) :
2768 bt_new_hci(qemu_find_bt_vlan(0)));
2769 } else {
2770 return -1;
2772 if (!dev)
2773 return -1;
2775 return usb_device_add_dev(dev);
2778 int usb_device_del_addr(int bus_num, int addr)
2780 USBPort *port;
2781 USBPort **lastp;
2782 USBDevice *dev;
2784 if (!used_usb_ports)
2785 return -1;
2787 if (bus_num != 0)
2788 return -1;
2790 lastp = &used_usb_ports;
2791 port = used_usb_ports;
2792 while (port && port->dev->addr != addr) {
2793 lastp = &port->next;
2794 port = port->next;
2797 if (!port)
2798 return -1;
2800 dev = port->dev;
2801 *lastp = port->next;
2802 usb_attach(port, NULL);
2803 dev->handle_destroy(dev);
2804 port->next = free_usb_ports;
2805 free_usb_ports = port;
2806 return 0;
2809 static int usb_device_del(const char *devname)
2811 int bus_num, addr;
2812 const char *p;
2814 if (strstart(devname, "host:", &p))
2815 return usb_host_device_close(p);
2817 if (!used_usb_ports)
2818 return -1;
2820 p = strchr(devname, '.');
2821 if (!p)
2822 return -1;
2823 bus_num = strtoul(devname, NULL, 0);
2824 addr = strtoul(p + 1, NULL, 0);
2826 return usb_device_del_addr(bus_num, addr);
2829 void do_usb_add(Monitor *mon, const char *devname)
2831 usb_device_add(devname, 1);
2834 void do_usb_del(Monitor *mon, const char *devname)
2836 usb_device_del(devname);
2839 void usb_info(Monitor *mon)
2841 USBDevice *dev;
2842 USBPort *port;
2843 const char *speed_str;
2845 if (!usb_enabled) {
2846 monitor_printf(mon, "USB support not enabled\n");
2847 return;
2850 for (port = used_usb_ports; port; port = port->next) {
2851 dev = port->dev;
2852 if (!dev)
2853 continue;
2854 switch(dev->speed) {
2855 case USB_SPEED_LOW:
2856 speed_str = "1.5";
2857 break;
2858 case USB_SPEED_FULL:
2859 speed_str = "12";
2860 break;
2861 case USB_SPEED_HIGH:
2862 speed_str = "480";
2863 break;
2864 default:
2865 speed_str = "?";
2866 break;
2868 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2869 0, dev->addr, speed_str, dev->devname);
2873 /***********************************************************/
2874 /* PCMCIA/Cardbus */
2876 static struct pcmcia_socket_entry_s {
2877 struct pcmcia_socket_s *socket;
2878 struct pcmcia_socket_entry_s *next;
2879 } *pcmcia_sockets = 0;
2881 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2883 struct pcmcia_socket_entry_s *entry;
2885 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2886 entry->socket = socket;
2887 entry->next = pcmcia_sockets;
2888 pcmcia_sockets = entry;
2891 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2893 struct pcmcia_socket_entry_s *entry, **ptr;
2895 ptr = &pcmcia_sockets;
2896 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2897 if (entry->socket == socket) {
2898 *ptr = entry->next;
2899 qemu_free(entry);
2903 void pcmcia_info(Monitor *mon)
2905 struct pcmcia_socket_entry_s *iter;
2907 if (!pcmcia_sockets)
2908 monitor_printf(mon, "No PCMCIA sockets\n");
2910 for (iter = pcmcia_sockets; iter; iter = iter->next)
2911 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2912 iter->socket->attached ? iter->socket->card_string :
2913 "Empty");
2916 /***********************************************************/
2917 /* register display */
2919 struct DisplayAllocator default_allocator = {
2920 defaultallocator_create_displaysurface,
2921 defaultallocator_resize_displaysurface,
2922 defaultallocator_free_displaysurface
2925 void register_displaystate(DisplayState *ds)
2927 DisplayState **s;
2928 s = &display_state;
2929 while (*s != NULL)
2930 s = &(*s)->next;
2931 ds->next = NULL;
2932 *s = ds;
2935 DisplayState *get_displaystate(void)
2937 return display_state;
2940 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2942 if(ds->allocator == &default_allocator) ds->allocator = da;
2943 return ds->allocator;
2946 /* dumb display */
2948 static void dumb_display_init(void)
2950 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2951 ds->allocator = &default_allocator;
2952 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2953 register_displaystate(ds);
2956 /***********************************************************/
2957 /* I/O handling */
2959 typedef struct IOHandlerRecord {
2960 int fd;
2961 IOCanRWHandler *fd_read_poll;
2962 IOHandler *fd_read;
2963 IOHandler *fd_write;
2964 int deleted;
2965 void *opaque;
2966 /* temporary data */
2967 struct pollfd *ufd;
2968 struct IOHandlerRecord *next;
2969 } IOHandlerRecord;
2971 static IOHandlerRecord *first_io_handler;
2973 /* XXX: fd_read_poll should be suppressed, but an API change is
2974 necessary in the character devices to suppress fd_can_read(). */
2975 int qemu_set_fd_handler2(int fd,
2976 IOCanRWHandler *fd_read_poll,
2977 IOHandler *fd_read,
2978 IOHandler *fd_write,
2979 void *opaque)
2981 IOHandlerRecord **pioh, *ioh;
2983 if (!fd_read && !fd_write) {
2984 pioh = &first_io_handler;
2985 for(;;) {
2986 ioh = *pioh;
2987 if (ioh == NULL)
2988 break;
2989 if (ioh->fd == fd) {
2990 ioh->deleted = 1;
2991 break;
2993 pioh = &ioh->next;
2995 } else {
2996 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2997 if (ioh->fd == fd)
2998 goto found;
3000 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3001 ioh->next = first_io_handler;
3002 first_io_handler = ioh;
3003 found:
3004 ioh->fd = fd;
3005 ioh->fd_read_poll = fd_read_poll;
3006 ioh->fd_read = fd_read;
3007 ioh->fd_write = fd_write;
3008 ioh->opaque = opaque;
3009 ioh->deleted = 0;
3011 main_loop_break();
3012 return 0;
3015 int qemu_set_fd_handler(int fd,
3016 IOHandler *fd_read,
3017 IOHandler *fd_write,
3018 void *opaque)
3020 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3023 #ifdef _WIN32
3024 /***********************************************************/
3025 /* Polling handling */
3027 typedef struct PollingEntry {
3028 PollingFunc *func;
3029 void *opaque;
3030 struct PollingEntry *next;
3031 } PollingEntry;
3033 static PollingEntry *first_polling_entry;
3035 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3037 PollingEntry **ppe, *pe;
3038 pe = qemu_mallocz(sizeof(PollingEntry));
3039 pe->func = func;
3040 pe->opaque = opaque;
3041 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3042 *ppe = pe;
3043 return 0;
3046 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3048 PollingEntry **ppe, *pe;
3049 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3050 pe = *ppe;
3051 if (pe->func == func && pe->opaque == opaque) {
3052 *ppe = pe->next;
3053 qemu_free(pe);
3054 break;
3059 /***********************************************************/
3060 /* Wait objects support */
3061 typedef struct WaitObjects {
3062 int num;
3063 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3064 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3065 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3066 } WaitObjects;
3068 static WaitObjects wait_objects = {0};
3070 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3072 WaitObjects *w = &wait_objects;
3074 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3075 return -1;
3076 w->events[w->num] = handle;
3077 w->func[w->num] = func;
3078 w->opaque[w->num] = opaque;
3079 w->num++;
3080 return 0;
3083 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3085 int i, found;
3086 WaitObjects *w = &wait_objects;
3088 found = 0;
3089 for (i = 0; i < w->num; i++) {
3090 if (w->events[i] == handle)
3091 found = 1;
3092 if (found) {
3093 w->events[i] = w->events[i + 1];
3094 w->func[i] = w->func[i + 1];
3095 w->opaque[i] = w->opaque[i + 1];
3098 if (found)
3099 w->num--;
3101 #endif
3103 /***********************************************************/
3104 /* ram save/restore */
3106 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3108 int v;
3110 v = qemu_get_byte(f);
3111 switch(v) {
3112 case 0:
3113 if (qemu_get_buffer(f, buf, len) != len)
3114 return -EIO;
3115 break;
3116 case 1:
3117 v = qemu_get_byte(f);
3118 memset(buf, v, len);
3119 break;
3120 default:
3121 return -EINVAL;
3124 if (qemu_file_has_error(f))
3125 return -EIO;
3127 return 0;
3130 static int ram_load_v1(QEMUFile *f, void *opaque)
3132 int ret;
3133 ram_addr_t i;
3135 if (qemu_get_be32(f) != phys_ram_size)
3136 return -EINVAL;
3137 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3138 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3139 continue;
3140 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3141 if (ret)
3142 return ret;
3144 return 0;
3147 #define BDRV_HASH_BLOCK_SIZE 1024
3148 #define IOBUF_SIZE 4096
3149 #define RAM_CBLOCK_MAGIC 0xfabe
3151 typedef struct RamDecompressState {
3152 z_stream zstream;
3153 QEMUFile *f;
3154 uint8_t buf[IOBUF_SIZE];
3155 } RamDecompressState;
3157 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3159 int ret;
3160 memset(s, 0, sizeof(*s));
3161 s->f = f;
3162 ret = inflateInit(&s->zstream);
3163 if (ret != Z_OK)
3164 return -1;
3165 return 0;
3168 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3170 int ret, clen;
3172 s->zstream.avail_out = len;
3173 s->zstream.next_out = buf;
3174 while (s->zstream.avail_out > 0) {
3175 if (s->zstream.avail_in == 0) {
3176 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3177 return -1;
3178 clen = qemu_get_be16(s->f);
3179 if (clen > IOBUF_SIZE)
3180 return -1;
3181 qemu_get_buffer(s->f, s->buf, clen);
3182 s->zstream.avail_in = clen;
3183 s->zstream.next_in = s->buf;
3185 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3186 if (ret != Z_OK && ret != Z_STREAM_END) {
3187 return -1;
3190 return 0;
3193 static void ram_decompress_close(RamDecompressState *s)
3195 inflateEnd(&s->zstream);
3198 #define RAM_SAVE_FLAG_FULL 0x01
3199 #define RAM_SAVE_FLAG_COMPRESS 0x02
3200 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3201 #define RAM_SAVE_FLAG_PAGE 0x08
3202 #define RAM_SAVE_FLAG_EOS 0x10
3204 static int is_dup_page(uint8_t *page, uint8_t ch)
3206 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3207 uint32_t *array = (uint32_t *)page;
3208 int i;
3210 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3211 if (array[i] != val)
3212 return 0;
3215 return 1;
3218 static int ram_save_block(QEMUFile *f)
3220 static ram_addr_t current_addr = 0;
3221 ram_addr_t saved_addr = current_addr;
3222 ram_addr_t addr = 0;
3223 int found = 0;
3225 while (addr < phys_ram_size) {
3226 if (kvm_enabled() && current_addr == 0)
3227 kvm_update_dirty_pages_log(); /* FIXME: propagate errors */
3228 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3229 uint8_t ch;
3231 cpu_physical_memory_reset_dirty(current_addr,
3232 current_addr + TARGET_PAGE_SIZE,
3233 MIGRATION_DIRTY_FLAG);
3235 ch = *(phys_ram_base + current_addr);
3237 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3238 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3239 qemu_put_byte(f, ch);
3240 } else {
3241 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3242 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3245 found = 1;
3246 break;
3248 addr += TARGET_PAGE_SIZE;
3249 current_addr = (saved_addr + addr) % phys_ram_size;
3252 return found;
3255 static ram_addr_t ram_save_threshold = 10;
3257 static ram_addr_t ram_save_remaining(void)
3259 ram_addr_t addr;
3260 ram_addr_t count = 0;
3262 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3263 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3264 count++;
3267 return count;
3270 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3272 ram_addr_t addr;
3274 if (stage == 1) {
3275 /* Make sure all dirty bits are set */
3276 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3277 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3278 cpu_physical_memory_set_dirty(addr);
3281 /* Enable dirty memory tracking */
3282 cpu_physical_memory_set_dirty_tracking(1);
3284 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3287 while (!qemu_file_rate_limit(f)) {
3288 int ret;
3290 ret = ram_save_block(f);
3291 if (ret == 0) /* no more blocks */
3292 break;
3295 /* try transferring iterative blocks of memory */
3297 if (stage == 3) {
3298 cpu_physical_memory_set_dirty_tracking(0);
3300 /* flush all remaining blocks regardless of rate limiting */
3301 while (ram_save_block(f) != 0);
3304 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3306 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3309 static int ram_load_dead(QEMUFile *f, void *opaque)
3311 RamDecompressState s1, *s = &s1;
3312 uint8_t buf[10];
3313 ram_addr_t i;
3315 if (ram_decompress_open(s, f) < 0)
3316 return -EINVAL;
3317 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3318 if (kvm_enabled() && (i>=0xa0000) && (i<0xc0000)) /* do not access video-addresses */
3319 continue;
3320 if (ram_decompress_buf(s, buf, 1) < 0) {
3321 fprintf(stderr, "Error while reading ram block header\n");
3322 goto error;
3324 if (buf[0] == 0) {
3325 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3326 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3327 goto error;
3329 } else {
3330 error:
3331 printf("Error block header\n");
3332 return -EINVAL;
3335 ram_decompress_close(s);
3337 return 0;
3340 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3342 ram_addr_t addr;
3343 int flags;
3345 if (version_id == 1)
3346 return ram_load_v1(f, opaque);
3348 if (version_id == 2) {
3349 if (qemu_get_be32(f) != phys_ram_size)
3350 return -EINVAL;
3351 return ram_load_dead(f, opaque);
3354 if (version_id != 3)
3355 return -EINVAL;
3357 do {
3358 addr = qemu_get_be64(f);
3360 flags = addr & ~TARGET_PAGE_MASK;
3361 addr &= TARGET_PAGE_MASK;
3363 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3364 if (addr != phys_ram_size)
3365 return -EINVAL;
3368 if (flags & RAM_SAVE_FLAG_FULL) {
3369 if (ram_load_dead(f, opaque) < 0)
3370 return -EINVAL;
3373 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3374 uint8_t ch = qemu_get_byte(f);
3375 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3376 } else if (flags & RAM_SAVE_FLAG_PAGE)
3377 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3378 } while (!(flags & RAM_SAVE_FLAG_EOS));
3380 return 0;
3383 void qemu_service_io(void)
3385 CPUState *env = cpu_single_env;
3386 if (env) {
3387 cpu_exit(env);
3388 #ifdef USE_KQEMU
3389 if (env->kqemu_enabled) {
3390 kqemu_cpu_interrupt(env);
3392 #endif
3396 /***********************************************************/
3397 /* bottom halves (can be seen as timers which expire ASAP) */
3399 struct QEMUBH {
3400 QEMUBHFunc *cb;
3401 void *opaque;
3402 int scheduled;
3403 int idle;
3404 int deleted;
3405 QEMUBH *next;
3408 static QEMUBH *first_bh = NULL;
3410 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3412 QEMUBH *bh;
3413 bh = qemu_mallocz(sizeof(QEMUBH));
3414 bh->cb = cb;
3415 bh->opaque = opaque;
3416 bh->next = first_bh;
3417 first_bh = bh;
3418 return bh;
3421 int qemu_bh_poll(void)
3423 QEMUBH *bh, **bhp;
3424 int ret;
3426 ret = 0;
3427 for (bh = first_bh; bh; bh = bh->next) {
3428 if (!bh->deleted && bh->scheduled) {
3429 bh->scheduled = 0;
3430 if (!bh->idle)
3431 ret = 1;
3432 bh->idle = 0;
3433 bh->cb(bh->opaque);
3437 /* remove deleted bhs */
3438 bhp = &first_bh;
3439 while (*bhp) {
3440 bh = *bhp;
3441 if (bh->deleted) {
3442 *bhp = bh->next;
3443 qemu_free(bh);
3444 } else
3445 bhp = &bh->next;
3448 return ret;
3451 void qemu_bh_schedule_idle(QEMUBH *bh)
3453 if (bh->scheduled)
3454 return;
3455 bh->scheduled = 1;
3456 bh->idle = 1;
3459 void qemu_bh_schedule(QEMUBH *bh)
3461 CPUState *env = cpu_single_env;
3462 if (bh->scheduled)
3463 return;
3464 bh->scheduled = 1;
3465 bh->idle = 0;
3466 /* stop the currently executing CPU to execute the BH ASAP */
3467 if (env) {
3468 cpu_exit(env);
3470 main_loop_break();
3473 void qemu_bh_cancel(QEMUBH *bh)
3475 bh->scheduled = 0;
3478 void qemu_bh_delete(QEMUBH *bh)
3480 bh->scheduled = 0;
3481 bh->deleted = 1;
3484 static void qemu_bh_update_timeout(int *timeout)
3486 QEMUBH *bh;
3488 for (bh = first_bh; bh; bh = bh->next) {
3489 if (!bh->deleted && bh->scheduled) {
3490 if (bh->idle) {
3491 /* idle bottom halves will be polled at least
3492 * every 10ms */
3493 *timeout = MIN(10, *timeout);
3494 } else {
3495 /* non-idle bottom halves will be executed
3496 * immediately */
3497 *timeout = 0;
3498 break;
3504 /***********************************************************/
3505 /* machine registration */
3507 static QEMUMachine *first_machine = NULL;
3508 QEMUMachine *current_machine = NULL;
3510 int qemu_register_machine(QEMUMachine *m)
3512 QEMUMachine **pm;
3513 pm = &first_machine;
3514 while (*pm != NULL)
3515 pm = &(*pm)->next;
3516 m->next = NULL;
3517 *pm = m;
3518 return 0;
3521 static QEMUMachine *find_machine(const char *name)
3523 QEMUMachine *m;
3525 for(m = first_machine; m != NULL; m = m->next) {
3526 if (!strcmp(m->name, name))
3527 return m;
3529 return NULL;
3532 /***********************************************************/
3533 /* main execution loop */
3535 static void gui_update(void *opaque)
3537 uint64_t interval = GUI_REFRESH_INTERVAL;
3538 DisplayState *ds = opaque;
3539 DisplayChangeListener *dcl = ds->listeners;
3541 dpy_refresh(ds);
3543 while (dcl != NULL) {
3544 if (dcl->gui_timer_interval &&
3545 dcl->gui_timer_interval < interval)
3546 interval = dcl->gui_timer_interval;
3547 dcl = dcl->next;
3549 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3552 static void nographic_update(void *opaque)
3554 uint64_t interval = GUI_REFRESH_INTERVAL;
3556 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3559 struct vm_change_state_entry {
3560 VMChangeStateHandler *cb;
3561 void *opaque;
3562 LIST_ENTRY (vm_change_state_entry) entries;
3565 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3567 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3568 void *opaque)
3570 VMChangeStateEntry *e;
3572 e = qemu_mallocz(sizeof (*e));
3574 e->cb = cb;
3575 e->opaque = opaque;
3576 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3577 return e;
3580 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3582 LIST_REMOVE (e, entries);
3583 qemu_free (e);
3586 static void vm_state_notify(int running, int reason)
3588 VMChangeStateEntry *e;
3590 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3591 e->cb(e->opaque, running, reason);
3595 void vm_start(void)
3597 if (!vm_running) {
3598 cpu_enable_ticks();
3599 vm_running = 1;
3600 vm_state_notify(1, 0);
3601 if (kvm_enabled())
3602 qemu_kvm_resume_all_threads();
3603 qemu_rearm_alarm_timer(alarm_timer);
3607 void vm_stop(int reason)
3609 if (vm_running) {
3610 cpu_disable_ticks();
3611 vm_running = 0;
3612 if (kvm_enabled())
3613 qemu_kvm_pause_all_threads();
3614 vm_state_notify(0, reason);
3618 /* reset/shutdown handler */
3620 typedef struct QEMUResetEntry {
3621 QEMUResetHandler *func;
3622 void *opaque;
3623 struct QEMUResetEntry *next;
3624 } QEMUResetEntry;
3626 static QEMUResetEntry *first_reset_entry;
3627 static int reset_requested;
3628 static int shutdown_requested;
3629 static int powerdown_requested;
3631 int qemu_shutdown_requested(void)
3633 int r = shutdown_requested;
3634 shutdown_requested = 0;
3635 return r;
3638 int qemu_reset_requested(void)
3640 int r = reset_requested;
3641 reset_requested = 0;
3642 return r;
3645 int qemu_powerdown_requested(void)
3647 int r = powerdown_requested;
3648 powerdown_requested = 0;
3649 return r;
3652 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3654 QEMUResetEntry **pre, *re;
3656 pre = &first_reset_entry;
3657 while (*pre != NULL)
3658 pre = &(*pre)->next;
3659 re = qemu_mallocz(sizeof(QEMUResetEntry));
3660 re->func = func;
3661 re->opaque = opaque;
3662 re->next = NULL;
3663 *pre = re;
3666 void qemu_system_reset(void)
3668 QEMUResetEntry *re;
3670 /* reset all devices */
3671 for(re = first_reset_entry; re != NULL; re = re->next) {
3672 re->func(re->opaque);
3676 void qemu_system_reset_request(void)
3678 if (no_reboot) {
3679 shutdown_requested = 1;
3680 } else {
3681 reset_requested = 1;
3683 if (cpu_single_env) {
3684 qemu_kvm_cpu_stop(cpu_single_env);
3685 cpu_exit(cpu_single_env);
3689 void qemu_system_shutdown_request(void)
3691 shutdown_requested = 1;
3692 if (cpu_single_env)
3693 cpu_exit(cpu_single_env);
3696 void qemu_system_powerdown_request(void)
3698 powerdown_requested = 1;
3699 if (cpu_single_env)
3700 cpu_exit(cpu_single_env);
3703 static int qemu_select(int max_fd, fd_set *rfds, fd_set *wfds, fd_set *xfds,
3704 struct timeval *tv)
3706 int ret;
3708 /* KVM holds a mutex while QEMU code is running, we need hooks to
3709 release the mutex whenever QEMU code sleeps. */
3711 kvm_sleep_begin();
3713 ret = select(max_fd, rfds, wfds, xfds, tv);
3715 kvm_sleep_end();
3717 return ret;
3720 #ifdef _WIN32
3721 static void host_main_loop_wait(int *timeout)
3723 int ret, ret2, i;
3724 PollingEntry *pe;
3727 /* XXX: need to suppress polling by better using win32 events */
3728 ret = 0;
3729 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3730 ret |= pe->func(pe->opaque);
3732 if (ret == 0) {
3733 int err;
3734 WaitObjects *w = &wait_objects;
3736 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3737 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3738 if (w->func[ret - WAIT_OBJECT_0])
3739 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3741 /* Check for additional signaled events */
3742 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3744 /* Check if event is signaled */
3745 ret2 = WaitForSingleObject(w->events[i], 0);
3746 if(ret2 == WAIT_OBJECT_0) {
3747 if (w->func[i])
3748 w->func[i](w->opaque[i]);
3749 } else if (ret2 == WAIT_TIMEOUT) {
3750 } else {
3751 err = GetLastError();
3752 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3755 } else if (ret == WAIT_TIMEOUT) {
3756 } else {
3757 err = GetLastError();
3758 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3762 *timeout = 0;
3764 #else
3765 static void host_main_loop_wait(int *timeout)
3768 #endif
3770 void main_loop_wait(int timeout)
3772 IOHandlerRecord *ioh;
3773 fd_set rfds, wfds, xfds;
3774 int ret, nfds;
3775 struct timeval tv;
3777 qemu_bh_update_timeout(&timeout);
3779 host_main_loop_wait(&timeout);
3781 /* poll any events */
3782 /* XXX: separate device handlers from system ones */
3783 nfds = -1;
3784 FD_ZERO(&rfds);
3785 FD_ZERO(&wfds);
3786 FD_ZERO(&xfds);
3787 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3788 if (ioh->deleted)
3789 continue;
3790 if (ioh->fd_read &&
3791 (!ioh->fd_read_poll ||
3792 ioh->fd_read_poll(ioh->opaque) != 0)) {
3793 FD_SET(ioh->fd, &rfds);
3794 if (ioh->fd > nfds)
3795 nfds = ioh->fd;
3797 if (ioh->fd_write) {
3798 FD_SET(ioh->fd, &wfds);
3799 if (ioh->fd > nfds)
3800 nfds = ioh->fd;
3804 tv.tv_sec = timeout / 1000;
3805 tv.tv_usec = (timeout % 1000) * 1000;
3807 #if defined(CONFIG_SLIRP)
3808 if (slirp_is_inited()) {
3809 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3811 #endif
3812 ret = qemu_select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3813 if (ret > 0) {
3814 IOHandlerRecord **pioh;
3816 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3817 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3818 ioh->fd_read(ioh->opaque);
3819 if (!(ioh->fd_read_poll && ioh->fd_read_poll(ioh->opaque)))
3820 FD_CLR(ioh->fd, &rfds);
3822 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3823 ioh->fd_write(ioh->opaque);
3827 /* remove deleted IO handlers */
3828 pioh = &first_io_handler;
3829 while (*pioh) {
3830 ioh = *pioh;
3831 if (ioh->deleted) {
3832 *pioh = ioh->next;
3833 qemu_free(ioh);
3834 } else
3835 pioh = &ioh->next;
3838 #if defined(CONFIG_SLIRP)
3839 if (slirp_is_inited()) {
3840 if (ret < 0) {
3841 FD_ZERO(&rfds);
3842 FD_ZERO(&wfds);
3843 FD_ZERO(&xfds);
3845 slirp_select_poll(&rfds, &wfds, &xfds);
3847 #endif
3849 /* vm time timers */
3850 if (vm_running && (!cur_cpu
3851 || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER))))
3852 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3853 qemu_get_clock(vm_clock));
3855 /* real time timers */
3856 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3857 qemu_get_clock(rt_clock));
3859 /* Check bottom-halves last in case any of the earlier events triggered
3860 them. */
3861 qemu_bh_poll();
3865 static int main_loop(void)
3867 int ret, timeout;
3868 #ifdef CONFIG_PROFILER
3869 int64_t ti;
3870 #endif
3871 CPUState *env;
3874 if (kvm_enabled()) {
3875 kvm_main_loop();
3876 cpu_disable_ticks();
3877 return 0;
3880 cur_cpu = first_cpu;
3881 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3882 for(;;) {
3883 if (vm_running) {
3885 for(;;) {
3886 /* get next cpu */
3887 env = next_cpu;
3888 #ifdef CONFIG_PROFILER
3889 ti = profile_getclock();
3890 #endif
3891 if (use_icount) {
3892 int64_t count;
3893 int decr;
3894 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3895 env->icount_decr.u16.low = 0;
3896 env->icount_extra = 0;
3897 count = qemu_next_deadline();
3898 count = (count + (1 << icount_time_shift) - 1)
3899 >> icount_time_shift;
3900 qemu_icount += count;
3901 decr = (count > 0xffff) ? 0xffff : count;
3902 count -= decr;
3903 env->icount_decr.u16.low = decr;
3904 env->icount_extra = count;
3906 ret = cpu_exec(env);
3907 #ifdef CONFIG_PROFILER
3908 qemu_time += profile_getclock() - ti;
3909 #endif
3910 if (use_icount) {
3911 /* Fold pending instructions back into the
3912 instruction counter, and clear the interrupt flag. */
3913 qemu_icount -= (env->icount_decr.u16.low
3914 + env->icount_extra);
3915 env->icount_decr.u32 = 0;
3916 env->icount_extra = 0;
3918 next_cpu = env->next_cpu ?: first_cpu;
3919 if (event_pending && likely(ret != EXCP_DEBUG)) {
3920 ret = EXCP_INTERRUPT;
3921 event_pending = 0;
3922 break;
3924 if (ret == EXCP_HLT) {
3925 /* Give the next CPU a chance to run. */
3926 cur_cpu = env;
3927 continue;
3929 if (ret != EXCP_HALTED)
3930 break;
3931 /* all CPUs are halted ? */
3932 if (env == cur_cpu)
3933 break;
3935 cur_cpu = env;
3937 if (shutdown_requested) {
3938 ret = EXCP_INTERRUPT;
3939 if (no_shutdown) {
3940 vm_stop(0);
3941 no_shutdown = 0;
3943 else
3944 break;
3946 if (reset_requested) {
3947 reset_requested = 0;
3948 qemu_system_reset();
3949 if (kvm_enabled())
3950 kvm_load_registers(env);
3951 ret = EXCP_INTERRUPT;
3953 if (powerdown_requested) {
3954 powerdown_requested = 0;
3955 qemu_system_powerdown();
3956 ret = EXCP_INTERRUPT;
3958 #ifdef CONFIG_GDBSTUB
3959 if (unlikely(ret == EXCP_DEBUG)) {
3960 gdb_set_stop_cpu(cur_cpu);
3961 vm_stop(EXCP_DEBUG);
3963 #endif
3964 /* If all cpus are halted then wait until the next IRQ */
3965 /* XXX: use timeout computed from timers */
3966 if (ret == EXCP_HALTED) {
3967 if (use_icount) {
3968 int64_t add;
3969 int64_t delta;
3970 /* Advance virtual time to the next event. */
3971 if (use_icount == 1) {
3972 /* When not using an adaptive execution frequency
3973 we tend to get badly out of sync with real time,
3974 so just delay for a reasonable amount of time. */
3975 delta = 0;
3976 } else {
3977 delta = cpu_get_icount() - cpu_get_clock();
3979 if (delta > 0) {
3980 /* If virtual time is ahead of real time then just
3981 wait for IO. */
3982 timeout = (delta / 1000000) + 1;
3983 } else {
3984 /* Wait for either IO to occur or the next
3985 timer event. */
3986 add = qemu_next_deadline();
3987 /* We advance the timer before checking for IO.
3988 Limit the amount we advance so that early IO
3989 activity won't get the guest too far ahead. */
3990 if (add > 10000000)
3991 add = 10000000;
3992 delta += add;
3993 add = (add + (1 << icount_time_shift) - 1)
3994 >> icount_time_shift;
3995 qemu_icount += add;
3996 timeout = delta / 1000000;
3997 if (timeout < 0)
3998 timeout = 0;
4000 } else {
4001 timeout = 5000;
4003 } else {
4004 timeout = 0;
4006 } else {
4007 if (shutdown_requested) {
4008 ret = EXCP_INTERRUPT;
4009 break;
4011 timeout = 5000;
4013 #ifdef CONFIG_PROFILER
4014 ti = profile_getclock();
4015 #endif
4016 main_loop_wait(timeout);
4017 #ifdef CONFIG_PROFILER
4018 dev_time += profile_getclock() - ti;
4019 #endif
4021 cpu_disable_ticks();
4022 return ret;
4025 static void help(int exitcode)
4027 printf("QEMU PC emulator version " QEMU_VERSION " (" KVM_VERSION ")"
4028 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4029 "usage: %s [options] [disk_image]\n"
4030 "\n"
4031 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4032 "\n"
4033 #define DEF(option, opt_arg, opt_enum, opt_help) \
4034 opt_help
4035 #define DEFHEADING(text) stringify(text) "\n"
4036 #include "qemu-options.h"
4037 #undef DEF
4038 #undef DEFHEADING
4039 #undef GEN_DOCS
4040 "\n"
4041 "During emulation, the following keys are useful:\n"
4042 "ctrl-alt-f toggle full screen\n"
4043 "ctrl-alt-n switch to virtual console 'n'\n"
4044 "ctrl-alt toggle mouse and keyboard grab\n"
4045 "\n"
4046 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4048 "qemu",
4049 DEFAULT_RAM_SIZE,
4050 #ifndef _WIN32
4051 DEFAULT_NETWORK_SCRIPT,
4052 DEFAULT_NETWORK_DOWN_SCRIPT,
4053 #endif
4054 DEFAULT_GDBSTUB_PORT,
4055 "/tmp/qemu.log");
4056 exit(exitcode);
4059 #define HAS_ARG 0x0001
4061 enum {
4062 #define DEF(option, opt_arg, opt_enum, opt_help) \
4063 opt_enum,
4064 #define DEFHEADING(text)
4065 #include "qemu-options.h"
4066 #undef DEF
4067 #undef DEFHEADING
4068 #undef GEN_DOCS
4071 typedef struct QEMUOption {
4072 const char *name;
4073 int flags;
4074 int index;
4075 } QEMUOption;
4077 static const QEMUOption qemu_options[] = {
4078 { "h", 0, QEMU_OPTION_h },
4079 #define DEF(option, opt_arg, opt_enum, opt_help) \
4080 { option, opt_arg, opt_enum },
4081 #define DEFHEADING(text)
4082 #include "qemu-options.h"
4083 #undef DEF
4084 #undef DEFHEADING
4085 #undef GEN_DOCS
4086 { NULL },
4089 #ifdef HAS_AUDIO
4090 struct soundhw soundhw[] = {
4091 #ifdef HAS_AUDIO_CHOICE
4092 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4094 "pcspk",
4095 "PC speaker",
4098 { .init_isa = pcspk_audio_init }
4100 #endif
4102 #ifdef CONFIG_SB16
4104 "sb16",
4105 "Creative Sound Blaster 16",
4108 { .init_isa = SB16_init }
4110 #endif
4112 #ifdef CONFIG_CS4231A
4114 "cs4231a",
4115 "CS4231A",
4118 { .init_isa = cs4231a_init }
4120 #endif
4122 #ifdef CONFIG_ADLIB
4124 "adlib",
4125 #ifdef HAS_YMF262
4126 "Yamaha YMF262 (OPL3)",
4127 #else
4128 "Yamaha YM3812 (OPL2)",
4129 #endif
4132 { .init_isa = Adlib_init }
4134 #endif
4136 #ifdef CONFIG_GUS
4138 "gus",
4139 "Gravis Ultrasound GF1",
4142 { .init_isa = GUS_init }
4144 #endif
4146 #ifdef CONFIG_AC97
4148 "ac97",
4149 "Intel 82801AA AC97 Audio",
4152 { .init_pci = ac97_init }
4154 #endif
4156 #ifdef CONFIG_ES1370
4158 "es1370",
4159 "ENSONIQ AudioPCI ES1370",
4162 { .init_pci = es1370_init }
4164 #endif
4166 #endif /* HAS_AUDIO_CHOICE */
4168 { NULL, NULL, 0, 0, { NULL } }
4171 static void select_soundhw (const char *optarg)
4173 struct soundhw *c;
4175 if (*optarg == '?') {
4176 show_valid_cards:
4178 printf ("Valid sound card names (comma separated):\n");
4179 for (c = soundhw; c->name; ++c) {
4180 printf ("%-11s %s\n", c->name, c->descr);
4182 printf ("\n-soundhw all will enable all of the above\n");
4183 exit (*optarg != '?');
4185 else {
4186 size_t l;
4187 const char *p;
4188 char *e;
4189 int bad_card = 0;
4191 if (!strcmp (optarg, "all")) {
4192 for (c = soundhw; c->name; ++c) {
4193 c->enabled = 1;
4195 return;
4198 p = optarg;
4199 while (*p) {
4200 e = strchr (p, ',');
4201 l = !e ? strlen (p) : (size_t) (e - p);
4203 for (c = soundhw; c->name; ++c) {
4204 if (!strncmp (c->name, p, l)) {
4205 c->enabled = 1;
4206 break;
4210 if (!c->name) {
4211 if (l > 80) {
4212 fprintf (stderr,
4213 "Unknown sound card name (too big to show)\n");
4215 else {
4216 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4217 (int) l, p);
4219 bad_card = 1;
4221 p += l + (e != NULL);
4224 if (bad_card)
4225 goto show_valid_cards;
4228 #endif
4230 static void select_vgahw (const char *p)
4232 const char *opts;
4234 if (strstart(p, "std", &opts)) {
4235 std_vga_enabled = 1;
4236 cirrus_vga_enabled = 0;
4237 vmsvga_enabled = 0;
4238 } else if (strstart(p, "cirrus", &opts)) {
4239 cirrus_vga_enabled = 1;
4240 std_vga_enabled = 0;
4241 vmsvga_enabled = 0;
4242 } else if (strstart(p, "vmware", &opts)) {
4243 cirrus_vga_enabled = 0;
4244 std_vga_enabled = 0;
4245 vmsvga_enabled = 1;
4246 } else if (strstart(p, "none", &opts)) {
4247 cirrus_vga_enabled = 0;
4248 std_vga_enabled = 0;
4249 vmsvga_enabled = 0;
4250 } else {
4251 invalid_vga:
4252 fprintf(stderr, "Unknown vga type: %s\n", p);
4253 exit(1);
4255 while (*opts) {
4256 const char *nextopt;
4258 if (strstart(opts, ",retrace=", &nextopt)) {
4259 opts = nextopt;
4260 if (strstart(opts, "dumb", &nextopt))
4261 vga_retrace_method = VGA_RETRACE_DUMB;
4262 else if (strstart(opts, "precise", &nextopt))
4263 vga_retrace_method = VGA_RETRACE_PRECISE;
4264 else goto invalid_vga;
4265 } else goto invalid_vga;
4266 opts = nextopt;
4270 #ifdef _WIN32
4271 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4273 exit(STATUS_CONTROL_C_EXIT);
4274 return TRUE;
4276 #endif
4278 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4280 int ret;
4282 if(strlen(str) != 36)
4283 return -1;
4285 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4286 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4287 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4289 if(ret != 16)
4290 return -1;
4292 return 0;
4295 #define MAX_NET_CLIENTS 32
4297 static int saved_argc;
4298 static char **saved_argv;
4300 void qemu_get_launch_info(int *argc, char ***argv, int *opt_daemonize, const char **opt_incoming)
4302 *argc = saved_argc;
4303 *argv = saved_argv;
4304 *opt_daemonize = daemonize;
4305 *opt_incoming = incoming;
4308 #ifdef USE_KVM
4310 #define HUGETLBFS_MAGIC 0x958458f6
4312 static long gethugepagesize(const char *path)
4314 struct statfs fs;
4315 int ret;
4317 do {
4318 ret = statfs(path, &fs);
4319 } while (ret != 0 && errno == EINTR);
4321 if (ret != 0) {
4322 perror("statfs");
4323 return 0;
4326 if (fs.f_type != HUGETLBFS_MAGIC)
4327 fprintf(stderr, "Warning: path not on HugeTLBFS: %s\n", path);
4329 return fs.f_bsize;
4332 static void *alloc_mem_area(size_t memory, unsigned long *len, const char *path)
4334 char *filename;
4335 void *area;
4336 int fd;
4337 #ifdef MAP_POPULATE
4338 int flags;
4339 #endif
4341 if (!kvm_has_sync_mmu()) {
4342 fprintf(stderr, "host lacks mmu notifiers, disabling --mem-path\n");
4343 return NULL;
4346 if (asprintf(&filename, "%s/kvm.XXXXXX", path) == -1)
4347 return NULL;
4349 hpagesize = gethugepagesize(path);
4350 if (!hpagesize)
4351 return NULL;
4353 fd = mkstemp(filename);
4354 if (fd < 0) {
4355 perror("mkstemp");
4356 free(filename);
4357 return NULL;
4359 unlink(filename);
4360 free(filename);
4362 memory = (memory+hpagesize-1) & ~(hpagesize-1);
4365 * ftruncate is not supported by hugetlbfs in older
4366 * hosts, so don't bother checking for errors.
4367 * If anything goes wrong with it under other filesystems,
4368 * mmap will fail.
4370 ftruncate(fd, memory);
4372 #ifdef MAP_POPULATE
4373 /* NB: MAP_POPULATE won't exhaustively alloc all phys pages in the case
4374 * MAP_PRIVATE is requested. For mem_prealloc we mmap as MAP_SHARED
4375 * to sidestep this quirk.
4377 flags = mem_prealloc ? MAP_POPULATE|MAP_SHARED : MAP_PRIVATE;
4378 area = mmap(0, memory, PROT_READ|PROT_WRITE, flags, fd, 0);
4379 #else
4380 area = mmap(0, memory, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
4381 #endif
4382 if (area == MAP_FAILED) {
4383 perror("alloc_mem_area: can't mmap hugetlbfs pages");
4384 close(fd);
4385 return (NULL);
4387 *len = memory;
4388 return area;
4390 #endif
4392 static void *qemu_alloc_physram(unsigned long memory)
4394 void *area = NULL;
4395 #ifdef USE_KVM
4396 unsigned long map_len = memory;
4398 if (mem_path)
4399 area = alloc_mem_area(memory, &map_len, mem_path);
4400 #endif
4401 if (!area)
4402 area = qemu_vmalloc(memory);
4403 #ifdef USE_KVM
4404 if (kvm_setup_guest_memory(area, map_len))
4405 area = NULL;
4406 #endif
4407 return area;
4410 #ifndef _WIN32
4412 static void termsig_handler(int signal)
4414 qemu_system_shutdown_request();
4417 static void termsig_setup(void)
4419 struct sigaction act;
4421 memset(&act, 0, sizeof(act));
4422 act.sa_handler = termsig_handler;
4423 sigaction(SIGINT, &act, NULL);
4424 sigaction(SIGHUP, &act, NULL);
4425 sigaction(SIGTERM, &act, NULL);
4428 #endif
4430 int main(int argc, char **argv, char **envp)
4432 #ifdef CONFIG_GDBSTUB
4433 int use_gdbstub;
4434 const char *gdbstub_port;
4435 #endif
4436 uint32_t boot_devices_bitmap = 0;
4437 int i;
4438 int snapshot, linux_boot, net_boot;
4439 const char *initrd_filename;
4440 const char *kernel_filename, *kernel_cmdline;
4441 const char *boot_devices = "";
4442 DisplayState *ds;
4443 DisplayChangeListener *dcl;
4444 int cyls, heads, secs, translation;
4445 const char *net_clients[MAX_NET_CLIENTS];
4446 int nb_net_clients;
4447 const char *bt_opts[MAX_BT_CMDLINE];
4448 int nb_bt_opts;
4449 int hda_index;
4450 int optind;
4451 const char *r, *optarg;
4452 CharDriverState *monitor_hd = NULL;
4453 const char *monitor_device;
4454 const char *serial_devices[MAX_SERIAL_PORTS];
4455 int serial_device_index;
4456 const char *parallel_devices[MAX_PARALLEL_PORTS];
4457 int parallel_device_index;
4458 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4459 int virtio_console_index;
4460 const char *loadvm = NULL;
4461 QEMUMachine *machine;
4462 const char *cpu_model;
4463 const char *usb_devices[MAX_USB_CMDLINE];
4464 int usb_devices_index;
4465 int fds[2];
4466 int tb_size;
4467 const char *pid_file = NULL;
4468 const char *incoming = NULL;
4469 int fd = 0;
4470 struct passwd *pwd = NULL;
4471 const char *chroot_dir = NULL;
4472 const char *run_as = NULL;
4474 qemu_cache_utils_init(envp);
4476 LIST_INIT (&vm_change_state_head);
4477 #ifndef _WIN32
4479 struct sigaction act;
4480 sigfillset(&act.sa_mask);
4481 act.sa_flags = 0;
4482 act.sa_handler = SIG_IGN;
4483 sigaction(SIGPIPE, &act, NULL);
4485 #else
4486 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4487 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4488 QEMU to run on a single CPU */
4490 HANDLE h;
4491 DWORD mask, smask;
4492 int i;
4493 h = GetCurrentProcess();
4494 if (GetProcessAffinityMask(h, &mask, &smask)) {
4495 for(i = 0; i < 32; i++) {
4496 if (mask & (1 << i))
4497 break;
4499 if (i != 32) {
4500 mask = 1 << i;
4501 SetProcessAffinityMask(h, mask);
4505 #endif
4507 register_machines();
4508 machine = first_machine;
4509 cpu_model = NULL;
4510 initrd_filename = NULL;
4511 ram_size = 0;
4512 vga_ram_size = VGA_RAM_SIZE;
4513 #ifdef CONFIG_GDBSTUB
4514 use_gdbstub = 0;
4515 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4516 #endif
4517 snapshot = 0;
4518 nographic = 0;
4519 curses = 0;
4520 kernel_filename = NULL;
4521 kernel_cmdline = "";
4522 cyls = heads = secs = 0;
4523 translation = BIOS_ATA_TRANSLATION_AUTO;
4524 monitor_device = "vc:80Cx24C";
4526 serial_devices[0] = "vc:80Cx24C";
4527 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4528 serial_devices[i] = NULL;
4529 serial_device_index = 0;
4531 parallel_devices[0] = "vc:80Cx24C";
4532 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4533 parallel_devices[i] = NULL;
4534 parallel_device_index = 0;
4536 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4537 virtio_consoles[i] = NULL;
4538 virtio_console_index = 0;
4540 usb_devices_index = 0;
4541 assigned_devices_index = 0;
4543 nb_net_clients = 0;
4544 nb_bt_opts = 0;
4545 nb_drives = 0;
4546 nb_drives_opt = 0;
4547 hda_index = -1;
4549 nb_nics = 0;
4551 tb_size = 0;
4552 autostart= 1;
4554 optind = 1;
4555 for(;;) {
4556 if (optind >= argc)
4557 break;
4558 r = argv[optind];
4559 if (r[0] != '-') {
4560 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4561 } else {
4562 const QEMUOption *popt;
4564 optind++;
4565 /* Treat --foo the same as -foo. */
4566 if (r[1] == '-')
4567 r++;
4568 popt = qemu_options;
4569 for(;;) {
4570 if (!popt->name) {
4571 fprintf(stderr, "%s: invalid option -- '%s'\n",
4572 argv[0], r);
4573 exit(1);
4575 if (!strcmp(popt->name, r + 1))
4576 break;
4577 popt++;
4579 if (popt->flags & HAS_ARG) {
4580 if (optind >= argc) {
4581 fprintf(stderr, "%s: option '%s' requires an argument\n",
4582 argv[0], r);
4583 exit(1);
4585 optarg = argv[optind++];
4586 } else {
4587 optarg = NULL;
4590 switch(popt->index) {
4591 case QEMU_OPTION_M:
4592 machine = find_machine(optarg);
4593 if (!machine) {
4594 QEMUMachine *m;
4595 printf("Supported machines are:\n");
4596 for(m = first_machine; m != NULL; m = m->next) {
4597 printf("%-10s %s%s\n",
4598 m->name, m->desc,
4599 m == first_machine ? " (default)" : "");
4601 exit(*optarg != '?');
4603 break;
4604 case QEMU_OPTION_cpu:
4605 /* hw initialization will check this */
4606 if (*optarg == '?') {
4607 /* XXX: implement xxx_cpu_list for targets that still miss it */
4608 #if defined(cpu_list)
4609 cpu_list(stdout, &fprintf);
4610 #endif
4611 exit(0);
4612 } else {
4613 cpu_model = optarg;
4615 break;
4616 case QEMU_OPTION_initrd:
4617 initrd_filename = optarg;
4618 break;
4619 case QEMU_OPTION_hda:
4620 if (cyls == 0)
4621 hda_index = drive_add(optarg, HD_ALIAS, 0);
4622 else
4623 hda_index = drive_add(optarg, HD_ALIAS
4624 ",cyls=%d,heads=%d,secs=%d%s",
4625 0, cyls, heads, secs,
4626 translation == BIOS_ATA_TRANSLATION_LBA ?
4627 ",trans=lba" :
4628 translation == BIOS_ATA_TRANSLATION_NONE ?
4629 ",trans=none" : "");
4630 break;
4631 case QEMU_OPTION_hdb:
4632 case QEMU_OPTION_hdc:
4633 case QEMU_OPTION_hdd:
4634 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4635 break;
4636 case QEMU_OPTION_drive:
4637 drive_add(NULL, "%s", optarg);
4638 break;
4639 case QEMU_OPTION_mtdblock:
4640 drive_add(optarg, MTD_ALIAS);
4641 break;
4642 case QEMU_OPTION_sd:
4643 drive_add(optarg, SD_ALIAS);
4644 break;
4645 case QEMU_OPTION_pflash:
4646 drive_add(optarg, PFLASH_ALIAS);
4647 break;
4648 case QEMU_OPTION_snapshot:
4649 snapshot = 1;
4650 break;
4651 case QEMU_OPTION_hdachs:
4653 const char *p;
4654 p = optarg;
4655 cyls = strtol(p, (char **)&p, 0);
4656 if (cyls < 1 || cyls > 16383)
4657 goto chs_fail;
4658 if (*p != ',')
4659 goto chs_fail;
4660 p++;
4661 heads = strtol(p, (char **)&p, 0);
4662 if (heads < 1 || heads > 16)
4663 goto chs_fail;
4664 if (*p != ',')
4665 goto chs_fail;
4666 p++;
4667 secs = strtol(p, (char **)&p, 0);
4668 if (secs < 1 || secs > 63)
4669 goto chs_fail;
4670 if (*p == ',') {
4671 p++;
4672 if (!strcmp(p, "none"))
4673 translation = BIOS_ATA_TRANSLATION_NONE;
4674 else if (!strcmp(p, "lba"))
4675 translation = BIOS_ATA_TRANSLATION_LBA;
4676 else if (!strcmp(p, "auto"))
4677 translation = BIOS_ATA_TRANSLATION_AUTO;
4678 else
4679 goto chs_fail;
4680 } else if (*p != '\0') {
4681 chs_fail:
4682 fprintf(stderr, "qemu: invalid physical CHS format\n");
4683 exit(1);
4685 if (hda_index != -1)
4686 snprintf(drives_opt[hda_index].opt,
4687 sizeof(drives_opt[hda_index].opt),
4688 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4689 0, cyls, heads, secs,
4690 translation == BIOS_ATA_TRANSLATION_LBA ?
4691 ",trans=lba" :
4692 translation == BIOS_ATA_TRANSLATION_NONE ?
4693 ",trans=none" : "");
4695 break;
4696 case QEMU_OPTION_nographic:
4697 nographic = 1;
4698 break;
4699 #ifdef CONFIG_CURSES
4700 case QEMU_OPTION_curses:
4701 curses = 1;
4702 break;
4703 #endif
4704 case QEMU_OPTION_portrait:
4705 graphic_rotate = 1;
4706 break;
4707 case QEMU_OPTION_kernel:
4708 kernel_filename = optarg;
4709 break;
4710 case QEMU_OPTION_append:
4711 kernel_cmdline = optarg;
4712 break;
4713 case QEMU_OPTION_cdrom:
4714 drive_add(optarg, CDROM_ALIAS);
4715 break;
4716 case QEMU_OPTION_boot:
4717 boot_devices = optarg;
4718 /* We just do some generic consistency checks */
4720 /* Could easily be extended to 64 devices if needed */
4721 const char *p;
4723 boot_devices_bitmap = 0;
4724 for (p = boot_devices; *p != '\0'; p++) {
4725 /* Allowed boot devices are:
4726 * a b : floppy disk drives
4727 * c ... f : IDE disk drives
4728 * g ... m : machine implementation dependant drives
4729 * n ... p : network devices
4730 * It's up to each machine implementation to check
4731 * if the given boot devices match the actual hardware
4732 * implementation and firmware features.
4734 if (*p < 'a' || *p > 'q') {
4735 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4736 exit(1);
4738 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4739 fprintf(stderr,
4740 "Boot device '%c' was given twice\n",*p);
4741 exit(1);
4743 boot_devices_bitmap |= 1 << (*p - 'a');
4746 break;
4747 case QEMU_OPTION_fda:
4748 case QEMU_OPTION_fdb:
4749 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4750 break;
4751 #ifdef TARGET_I386
4752 case QEMU_OPTION_no_fd_bootchk:
4753 fd_bootchk = 0;
4754 break;
4755 #endif
4756 case QEMU_OPTION_net:
4757 if (nb_net_clients >= MAX_NET_CLIENTS) {
4758 fprintf(stderr, "qemu: too many network clients\n");
4759 exit(1);
4761 net_clients[nb_net_clients] = optarg;
4762 nb_net_clients++;
4763 break;
4764 #ifdef CONFIG_SLIRP
4765 case QEMU_OPTION_tftp:
4766 tftp_prefix = optarg;
4767 break;
4768 case QEMU_OPTION_bootp:
4769 bootp_filename = optarg;
4770 break;
4771 #ifndef _WIN32
4772 case QEMU_OPTION_smb:
4773 net_slirp_smb(optarg);
4774 break;
4775 #endif
4776 case QEMU_OPTION_redir:
4777 net_slirp_redir(optarg);
4778 break;
4779 #endif
4780 case QEMU_OPTION_bt:
4781 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4782 fprintf(stderr, "qemu: too many bluetooth options\n");
4783 exit(1);
4785 bt_opts[nb_bt_opts++] = optarg;
4786 break;
4787 #ifdef HAS_AUDIO
4788 case QEMU_OPTION_audio_help:
4789 AUD_help ();
4790 exit (0);
4791 break;
4792 case QEMU_OPTION_soundhw:
4793 select_soundhw (optarg);
4794 break;
4795 #endif
4796 case QEMU_OPTION_h:
4797 help(0);
4798 break;
4799 case QEMU_OPTION_m: {
4800 uint64_t value;
4801 char *ptr;
4803 value = strtoul(optarg, &ptr, 10);
4804 switch (*ptr) {
4805 case 0: case 'M': case 'm':
4806 value <<= 20;
4807 break;
4808 case 'G': case 'g':
4809 value <<= 30;
4810 break;
4811 default:
4812 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4813 exit(1);
4816 /* On 32-bit hosts, QEMU is limited by virtual address space */
4817 if (value > (2047 << 20)
4818 #ifndef USE_KQEMU
4819 && HOST_LONG_BITS == 32
4820 #endif
4822 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4823 exit(1);
4825 if (value != (uint64_t)(ram_addr_t)value) {
4826 fprintf(stderr, "qemu: ram size too large\n");
4827 exit(1);
4829 ram_size = value;
4830 break;
4832 case QEMU_OPTION_d:
4834 int mask;
4835 const CPULogItem *item;
4837 mask = cpu_str_to_log_mask(optarg);
4838 if (!mask) {
4839 printf("Log items (comma separated):\n");
4840 for(item = cpu_log_items; item->mask != 0; item++) {
4841 printf("%-10s %s\n", item->name, item->help);
4843 exit(1);
4845 cpu_set_log(mask);
4847 break;
4848 #ifdef CONFIG_GDBSTUB
4849 case QEMU_OPTION_s:
4850 use_gdbstub = 1;
4851 break;
4852 case QEMU_OPTION_p:
4853 gdbstub_port = optarg;
4854 break;
4855 #endif
4856 case QEMU_OPTION_L:
4857 bios_dir = optarg;
4858 break;
4859 case QEMU_OPTION_bios:
4860 bios_name = optarg;
4861 break;
4862 case QEMU_OPTION_S:
4863 autostart = 0;
4864 break;
4865 #ifndef _WIN32
4866 case QEMU_OPTION_k:
4867 keyboard_layout = optarg;
4868 break;
4869 #endif
4870 case QEMU_OPTION_localtime:
4871 rtc_utc = 0;
4872 break;
4873 case QEMU_OPTION_vga:
4874 select_vgahw (optarg);
4875 break;
4876 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4877 case QEMU_OPTION_g:
4879 const char *p;
4880 int w, h, depth;
4881 p = optarg;
4882 w = strtol(p, (char **)&p, 10);
4883 if (w <= 0) {
4884 graphic_error:
4885 fprintf(stderr, "qemu: invalid resolution or depth\n");
4886 exit(1);
4888 if (*p != 'x')
4889 goto graphic_error;
4890 p++;
4891 h = strtol(p, (char **)&p, 10);
4892 if (h <= 0)
4893 goto graphic_error;
4894 if (*p == 'x') {
4895 p++;
4896 depth = strtol(p, (char **)&p, 10);
4897 if (depth != 8 && depth != 15 && depth != 16 &&
4898 depth != 24 && depth != 32)
4899 goto graphic_error;
4900 } else if (*p == '\0') {
4901 depth = graphic_depth;
4902 } else {
4903 goto graphic_error;
4906 graphic_width = w;
4907 graphic_height = h;
4908 graphic_depth = depth;
4910 break;
4911 #endif
4912 case QEMU_OPTION_echr:
4914 char *r;
4915 term_escape_char = strtol(optarg, &r, 0);
4916 if (r == optarg)
4917 printf("Bad argument to echr\n");
4918 break;
4920 case QEMU_OPTION_monitor:
4921 monitor_device = optarg;
4922 break;
4923 case QEMU_OPTION_serial:
4924 if (serial_device_index >= MAX_SERIAL_PORTS) {
4925 fprintf(stderr, "qemu: too many serial ports\n");
4926 exit(1);
4928 serial_devices[serial_device_index] = optarg;
4929 serial_device_index++;
4930 break;
4931 case QEMU_OPTION_virtiocon:
4932 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4933 fprintf(stderr, "qemu: too many virtio consoles\n");
4934 exit(1);
4936 virtio_consoles[virtio_console_index] = optarg;
4937 virtio_console_index++;
4938 break;
4939 case QEMU_OPTION_parallel:
4940 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4941 fprintf(stderr, "qemu: too many parallel ports\n");
4942 exit(1);
4944 parallel_devices[parallel_device_index] = optarg;
4945 parallel_device_index++;
4946 break;
4947 case QEMU_OPTION_loadvm:
4948 loadvm = optarg;
4949 break;
4950 case QEMU_OPTION_full_screen:
4951 full_screen = 1;
4952 break;
4953 #ifdef CONFIG_SDL
4954 case QEMU_OPTION_no_frame:
4955 no_frame = 1;
4956 break;
4957 case QEMU_OPTION_alt_grab:
4958 alt_grab = 1;
4959 break;
4960 case QEMU_OPTION_no_quit:
4961 no_quit = 1;
4962 break;
4963 case QEMU_OPTION_sdl:
4964 sdl = 1;
4965 break;
4966 #endif
4967 case QEMU_OPTION_pidfile:
4968 pid_file = optarg;
4969 break;
4970 #ifdef TARGET_I386
4971 case QEMU_OPTION_win2k_hack:
4972 win2k_install_hack = 1;
4973 break;
4974 case QEMU_OPTION_rtc_td_hack:
4975 rtc_td_hack = 1;
4976 break;
4977 case QEMU_OPTION_acpitable:
4978 if(acpi_table_add(optarg) < 0) {
4979 fprintf(stderr, "Wrong acpi table provided\n");
4980 exit(1);
4982 break;
4983 #endif
4984 #ifdef USE_KQEMU
4985 case QEMU_OPTION_no_kqemu:
4986 kqemu_allowed = 0;
4987 break;
4988 case QEMU_OPTION_kernel_kqemu:
4989 kqemu_allowed = 2;
4990 break;
4991 #endif
4992 #ifdef CONFIG_KVM
4993 case QEMU_OPTION_enable_kvm:
4994 kvm_allowed = 1;
4995 #ifdef USE_KQEMU
4996 kqemu_allowed = 0;
4997 #endif
4998 break;
4999 #endif
5000 #ifdef USE_KVM
5001 case QEMU_OPTION_no_kvm:
5002 kvm_allowed = 0;
5003 break;
5004 case QEMU_OPTION_no_kvm_irqchip: {
5005 kvm_irqchip = 0;
5006 kvm_pit = 0;
5007 break;
5009 case QEMU_OPTION_no_kvm_pit: {
5010 kvm_pit = 0;
5011 break;
5013 case QEMU_OPTION_no_kvm_pit_reinjection: {
5014 kvm_pit_reinject = 0;
5015 break;
5017 case QEMU_OPTION_enable_nesting: {
5018 kvm_nested = 1;
5019 break;
5021 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5022 case QEMU_OPTION_pcidevice:
5023 if (assigned_devices_index >= MAX_DEV_ASSIGN_CMDLINE) {
5024 fprintf(stderr, "Too many assigned devices\n");
5025 exit(1);
5027 assigned_devices[assigned_devices_index] = optarg;
5028 assigned_devices_index++;
5029 break;
5030 #endif
5031 #endif
5032 case QEMU_OPTION_usb:
5033 usb_enabled = 1;
5034 break;
5035 case QEMU_OPTION_usbdevice:
5036 usb_enabled = 1;
5037 if (usb_devices_index >= MAX_USB_CMDLINE) {
5038 fprintf(stderr, "Too many USB devices\n");
5039 exit(1);
5041 usb_devices[usb_devices_index] = optarg;
5042 usb_devices_index++;
5043 break;
5044 case QEMU_OPTION_smp:
5045 smp_cpus = atoi(optarg);
5046 if (smp_cpus < 1) {
5047 fprintf(stderr, "Invalid number of CPUs\n");
5048 exit(1);
5050 break;
5051 case QEMU_OPTION_vnc:
5052 vnc_display = optarg;
5053 break;
5054 #ifdef TARGET_I386
5055 case QEMU_OPTION_no_acpi:
5056 acpi_enabled = 0;
5057 break;
5058 case QEMU_OPTION_no_hpet:
5059 no_hpet = 1;
5060 break;
5061 #endif
5062 case QEMU_OPTION_no_reboot:
5063 no_reboot = 1;
5064 break;
5065 case QEMU_OPTION_no_shutdown:
5066 no_shutdown = 1;
5067 break;
5068 case QEMU_OPTION_show_cursor:
5069 cursor_hide = 0;
5070 break;
5071 case QEMU_OPTION_uuid:
5072 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5073 fprintf(stderr, "Fail to parse UUID string."
5074 " Wrong format.\n");
5075 exit(1);
5077 break;
5078 #ifndef _WIN32
5079 case QEMU_OPTION_daemonize:
5080 daemonize = 1;
5081 break;
5082 #endif
5083 case QEMU_OPTION_option_rom:
5084 if (nb_option_roms >= MAX_OPTION_ROMS) {
5085 fprintf(stderr, "Too many option ROMs\n");
5086 exit(1);
5088 option_rom[nb_option_roms] = optarg;
5089 nb_option_roms++;
5090 break;
5091 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5092 case QEMU_OPTION_semihosting:
5093 semihosting_enabled = 1;
5094 break;
5095 #endif
5096 case QEMU_OPTION_tdf:
5097 time_drift_fix = 1;
5098 break;
5099 case QEMU_OPTION_kvm_shadow_memory:
5100 kvm_shadow_memory = (int64_t)atoi(optarg) * 1024 * 1024 / 4096;
5101 break;
5102 case QEMU_OPTION_mempath:
5103 mem_path = optarg;
5104 break;
5105 #ifdef MAP_POPULATE
5106 case QEMU_OPTION_mem_prealloc:
5107 mem_prealloc = !mem_prealloc;
5108 break;
5109 #endif
5110 case QEMU_OPTION_name:
5111 qemu_name = optarg;
5112 break;
5113 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5114 case QEMU_OPTION_prom_env:
5115 if (nb_prom_envs >= MAX_PROM_ENVS) {
5116 fprintf(stderr, "Too many prom variables\n");
5117 exit(1);
5119 prom_envs[nb_prom_envs] = optarg;
5120 nb_prom_envs++;
5121 break;
5122 #endif
5123 case QEMU_OPTION_cpu_vendor:
5124 cpu_vendor_string = optarg;
5125 break;
5126 #ifdef TARGET_ARM
5127 case QEMU_OPTION_old_param:
5128 old_param = 1;
5129 break;
5130 #endif
5131 case QEMU_OPTION_clock:
5132 configure_alarms(optarg);
5133 break;
5134 case QEMU_OPTION_startdate:
5136 struct tm tm;
5137 time_t rtc_start_date;
5138 if (!strcmp(optarg, "now")) {
5139 rtc_date_offset = -1;
5140 } else {
5141 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5142 &tm.tm_year,
5143 &tm.tm_mon,
5144 &tm.tm_mday,
5145 &tm.tm_hour,
5146 &tm.tm_min,
5147 &tm.tm_sec) == 6) {
5148 /* OK */
5149 } else if (sscanf(optarg, "%d-%d-%d",
5150 &tm.tm_year,
5151 &tm.tm_mon,
5152 &tm.tm_mday) == 3) {
5153 tm.tm_hour = 0;
5154 tm.tm_min = 0;
5155 tm.tm_sec = 0;
5156 } else {
5157 goto date_fail;
5159 tm.tm_year -= 1900;
5160 tm.tm_mon--;
5161 rtc_start_date = mktimegm(&tm);
5162 if (rtc_start_date == -1) {
5163 date_fail:
5164 fprintf(stderr, "Invalid date format. Valid format are:\n"
5165 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5166 exit(1);
5168 rtc_date_offset = time(NULL) - rtc_start_date;
5171 break;
5172 case QEMU_OPTION_tb_size:
5173 tb_size = strtol(optarg, NULL, 0);
5174 if (tb_size < 0)
5175 tb_size = 0;
5176 break;
5177 case QEMU_OPTION_icount:
5178 use_icount = 1;
5179 if (strcmp(optarg, "auto") == 0) {
5180 icount_time_shift = -1;
5181 } else {
5182 icount_time_shift = strtol(optarg, NULL, 0);
5184 break;
5185 case QEMU_OPTION_incoming:
5186 incoming = optarg;
5187 break;
5188 #ifndef _WIN32
5189 case QEMU_OPTION_chroot:
5190 chroot_dir = optarg;
5191 break;
5192 case QEMU_OPTION_runas:
5193 run_as = optarg;
5194 break;
5195 case QEMU_OPTION_nvram:
5196 nvram = optarg;
5197 break;
5198 #endif
5203 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
5204 if (kvm_allowed && kqemu_allowed) {
5205 fprintf(stderr,
5206 "You can not enable both KVM and kqemu at the same time\n");
5207 exit(1);
5209 #endif
5211 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5212 if (smp_cpus > machine->max_cpus) {
5213 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5214 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
5215 machine->max_cpus);
5216 exit(1);
5219 if (nographic) {
5220 if (serial_device_index == 0)
5221 serial_devices[0] = "stdio";
5222 if (parallel_device_index == 0)
5223 parallel_devices[0] = "null";
5224 if (strncmp(monitor_device, "vc", 2) == 0)
5225 monitor_device = "stdio";
5228 #ifndef _WIN32
5229 if (daemonize) {
5230 pid_t pid;
5232 if (pipe(fds) == -1)
5233 exit(1);
5235 pid = fork();
5236 if (pid > 0) {
5237 uint8_t status;
5238 ssize_t len;
5240 close(fds[1]);
5242 again:
5243 len = read(fds[0], &status, 1);
5244 if (len == -1 && (errno == EINTR))
5245 goto again;
5247 if (len != 1)
5248 exit(1);
5249 else if (status == 1) {
5250 fprintf(stderr, "Could not acquire pidfile\n");
5251 exit(1);
5252 } else
5253 exit(0);
5254 } else if (pid < 0)
5255 exit(1);
5257 setsid();
5259 pid = fork();
5260 if (pid > 0)
5261 exit(0);
5262 else if (pid < 0)
5263 exit(1);
5265 umask(027);
5267 signal(SIGTSTP, SIG_IGN);
5268 signal(SIGTTOU, SIG_IGN);
5269 signal(SIGTTIN, SIG_IGN);
5271 #endif
5273 #ifdef USE_KVM
5274 if (kvm_enabled()) {
5275 if (kvm_qemu_init() < 0) {
5276 fprintf(stderr, "Could not initialize KVM, will disable KVM support\n");
5277 #ifdef NO_CPU_EMULATION
5278 fprintf(stderr, "Compiled with --disable-cpu-emulation, exiting.\n");
5279 exit(1);
5280 #endif
5281 kvm_allowed = 0;
5284 #endif
5286 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5287 if (daemonize) {
5288 uint8_t status = 1;
5289 write(fds[1], &status, 1);
5290 } else
5291 fprintf(stderr, "Could not acquire pid file\n");
5292 exit(1);
5295 #ifdef USE_KQEMU
5296 if (smp_cpus > 1)
5297 kqemu_allowed = 0;
5298 #endif
5299 linux_boot = (kernel_filename != NULL);
5300 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5302 if (!linux_boot && *kernel_cmdline != '\0') {
5303 fprintf(stderr, "-append only allowed with -kernel option\n");
5304 exit(1);
5307 if (!linux_boot && initrd_filename != NULL) {
5308 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5309 exit(1);
5312 /* boot to floppy or the default cd if no hard disk defined yet */
5313 if (!boot_devices[0]) {
5314 boot_devices = "cad";
5316 setvbuf(stdout, NULL, _IOLBF, 0);
5318 init_timers();
5319 if (init_timer_alarm() < 0) {
5320 fprintf(stderr, "could not initialize alarm timer\n");
5321 exit(1);
5323 if (use_icount && icount_time_shift < 0) {
5324 use_icount = 2;
5325 /* 125MIPS seems a reasonable initial guess at the guest speed.
5326 It will be corrected fairly quickly anyway. */
5327 icount_time_shift = 3;
5328 init_icount_adjust();
5331 #ifdef _WIN32
5332 socket_init();
5333 #endif
5335 /* init network clients */
5336 if (nb_net_clients == 0) {
5337 /* if no clients, we use a default config */
5338 net_clients[nb_net_clients++] = "nic";
5339 #ifdef CONFIG_SLIRP
5340 net_clients[nb_net_clients++] = "user";
5341 #endif
5344 for(i = 0;i < nb_net_clients; i++) {
5345 if (net_client_parse(net_clients[i]) < 0)
5346 exit(1);
5348 net_client_check();
5350 #ifdef TARGET_I386
5351 /* XXX: this should be moved in the PC machine instantiation code */
5352 if (net_boot != 0) {
5353 int netroms = 0;
5354 for (i = 0; i < nb_nics && i < 4; i++) {
5355 const char *model = nd_table[i].model;
5356 char buf[1024];
5357 if (net_boot & (1 << i)) {
5358 if (model == NULL)
5359 model = "rtl8139";
5360 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5361 if (get_image_size(buf) > 0) {
5362 if (nb_option_roms >= MAX_OPTION_ROMS) {
5363 fprintf(stderr, "Too many option ROMs\n");
5364 exit(1);
5366 option_rom[nb_option_roms] = strdup(buf);
5367 nb_option_roms++;
5368 netroms++;
5372 if (netroms == 0) {
5373 fprintf(stderr, "No valid PXE rom found for network device\n");
5374 exit(1);
5377 #endif
5379 /* init the bluetooth world */
5380 for (i = 0; i < nb_bt_opts; i++)
5381 if (bt_parse(bt_opts[i]))
5382 exit(1);
5384 /* init the memory */
5385 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5387 if (machine->ram_require & RAMSIZE_FIXED) {
5388 if (ram_size > 0) {
5389 if (ram_size < phys_ram_size) {
5390 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5391 machine->name, (unsigned long long) phys_ram_size);
5392 exit(-1);
5395 phys_ram_size = ram_size;
5396 } else
5397 ram_size = phys_ram_size;
5398 } else {
5399 if (ram_size == 0)
5400 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5402 phys_ram_size += ram_size;
5405 /* Initialize kvm */
5406 #if defined(TARGET_I386) || defined(TARGET_X86_64)
5407 #define KVM_EXTRA_PAGES 3
5408 #else
5409 #define KVM_EXTRA_PAGES 0
5410 #endif
5411 if (kvm_enabled()) {
5412 phys_ram_size += KVM_EXTRA_PAGES * TARGET_PAGE_SIZE;
5413 if (kvm_qemu_create_context() < 0) {
5414 fprintf(stderr, "Could not create KVM context\n");
5415 exit(1);
5419 phys_ram_base = qemu_alloc_physram(phys_ram_size);
5420 if (!phys_ram_base) {
5421 fprintf(stderr, "Could not allocate physical memory\n");
5422 exit(1);
5425 /* init the dynamic translator */
5426 cpu_exec_init_all(tb_size * 1024 * 1024);
5428 bdrv_init();
5429 dma_helper_init();
5431 /* we always create the cdrom drive, even if no disk is there */
5433 if (nb_drives_opt < MAX_DRIVES)
5434 drive_add(NULL, CDROM_ALIAS);
5436 /* we always create at least one floppy */
5438 if (nb_drives_opt < MAX_DRIVES)
5439 drive_add(NULL, FD_ALIAS, 0);
5441 /* we always create one sd slot, even if no card is in it */
5443 if (nb_drives_opt < MAX_DRIVES)
5444 drive_add(NULL, SD_ALIAS);
5446 /* open the virtual block devices
5447 * note that migration with device
5448 * hot add/remove is broken.
5450 for(i = 0; i < nb_drives_opt; i++)
5451 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5452 exit(1);
5454 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5455 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5457 #ifndef _WIN32
5458 /* must be after terminal init, SDL library changes signal handlers */
5459 termsig_setup();
5460 #endif
5462 /* Maintain compatibility with multiple stdio monitors */
5463 if (!strcmp(monitor_device,"stdio")) {
5464 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5465 const char *devname = serial_devices[i];
5466 if (devname && !strcmp(devname,"mon:stdio")) {
5467 monitor_device = NULL;
5468 break;
5469 } else if (devname && !strcmp(devname,"stdio")) {
5470 monitor_device = NULL;
5471 serial_devices[i] = "mon:stdio";
5472 break;
5477 #ifdef KVM_UPSTREAM
5478 if (kvm_enabled()) {
5479 int ret;
5481 ret = kvm_init(smp_cpus);
5482 if (ret < 0) {
5483 fprintf(stderr, "failed to initialize KVM\n");
5484 exit(1);
5487 #endif
5489 if (monitor_device) {
5490 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5491 if (!monitor_hd) {
5492 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5493 exit(1);
5497 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5498 const char *devname = serial_devices[i];
5499 if (devname && strcmp(devname, "none")) {
5500 char label[32];
5501 snprintf(label, sizeof(label), "serial%d", i);
5502 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5503 if (!serial_hds[i]) {
5504 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5505 devname);
5506 exit(1);
5511 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5512 const char *devname = parallel_devices[i];
5513 if (devname && strcmp(devname, "none")) {
5514 char label[32];
5515 snprintf(label, sizeof(label), "parallel%d", i);
5516 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5517 if (!parallel_hds[i]) {
5518 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5519 devname);
5520 exit(1);
5525 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5526 const char *devname = virtio_consoles[i];
5527 if (devname && strcmp(devname, "none")) {
5528 char label[32];
5529 snprintf(label, sizeof(label), "virtcon%d", i);
5530 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5531 if (!virtcon_hds[i]) {
5532 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5533 devname);
5534 exit(1);
5539 if (kvm_enabled())
5540 kvm_init_ap();
5542 machine->init(ram_size, vga_ram_size, boot_devices,
5543 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5545 current_machine = machine;
5547 /* Set KVM's vcpu state to qemu's initial CPUState. */
5548 if (kvm_enabled()) {
5549 int ret;
5551 ret = kvm_sync_vcpus();
5552 if (ret < 0) {
5553 fprintf(stderr, "failed to initialize vcpus\n");
5554 exit(1);
5558 /* init USB devices */
5559 if (usb_enabled) {
5560 for(i = 0; i < usb_devices_index; i++) {
5561 if (usb_device_add(usb_devices[i], 0) < 0) {
5562 fprintf(stderr, "Warning: could not add USB device %s\n",
5563 usb_devices[i]);
5568 if (!display_state)
5569 dumb_display_init();
5570 /* just use the first displaystate for the moment */
5571 ds = display_state;
5572 /* terminal init */
5573 if (nographic) {
5574 if (curses) {
5575 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5576 exit(1);
5578 } else {
5579 #if defined(CONFIG_CURSES)
5580 if (curses) {
5581 /* At the moment curses cannot be used with other displays */
5582 curses_display_init(ds, full_screen);
5583 } else
5584 #endif
5586 if (vnc_display != NULL) {
5587 vnc_display_init(ds);
5588 if (vnc_display_open(ds, vnc_display) < 0)
5589 exit(1);
5591 #if defined(CONFIG_SDL)
5592 if (sdl || !vnc_display)
5593 sdl_display_init(ds, full_screen, no_frame);
5594 #elif defined(CONFIG_COCOA)
5595 if (sdl || !vnc_display)
5596 cocoa_display_init(ds, full_screen);
5597 #endif
5600 dpy_resize(ds);
5602 dcl = ds->listeners;
5603 while (dcl != NULL) {
5604 if (dcl->dpy_refresh != NULL) {
5605 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5606 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5608 dcl = dcl->next;
5611 if (nographic || (vnc_display && !sdl)) {
5612 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5613 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5616 text_consoles_set_display(display_state);
5617 qemu_chr_initial_reset();
5619 if (monitor_device && monitor_hd)
5620 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5622 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5623 const char *devname = serial_devices[i];
5624 if (devname && strcmp(devname, "none")) {
5625 char label[32];
5626 snprintf(label, sizeof(label), "serial%d", i);
5627 if (strstart(devname, "vc", 0))
5628 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5632 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5633 const char *devname = parallel_devices[i];
5634 if (devname && strcmp(devname, "none")) {
5635 char label[32];
5636 snprintf(label, sizeof(label), "parallel%d", i);
5637 if (strstart(devname, "vc", 0))
5638 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5642 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5643 const char *devname = virtio_consoles[i];
5644 if (virtcon_hds[i] && devname) {
5645 char label[32];
5646 snprintf(label, sizeof(label), "virtcon%d", i);
5647 if (strstart(devname, "vc", 0))
5648 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5652 #ifdef CONFIG_GDBSTUB
5653 if (use_gdbstub) {
5654 /* XXX: use standard host:port notation and modify options
5655 accordingly. */
5656 if (gdbserver_start(gdbstub_port) < 0) {
5657 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5658 gdbstub_port);
5659 exit(1);
5662 #endif
5664 if (loadvm)
5665 do_loadvm(cur_mon, loadvm);
5667 if (incoming) {
5668 autostart = 0; /* fixme how to deal with -daemonize */
5669 qemu_start_incoming_migration(incoming);
5672 if (autostart)
5673 vm_start();
5675 if (daemonize) {
5676 uint8_t status = 0;
5677 ssize_t len;
5679 again1:
5680 len = write(fds[1], &status, 1);
5681 if (len == -1 && (errno == EINTR))
5682 goto again1;
5684 if (len != 1)
5685 exit(1);
5687 chdir("/");
5688 TFR(fd = open("/dev/null", O_RDWR));
5689 if (fd == -1)
5690 exit(1);
5693 #ifndef _WIN32
5694 if (run_as) {
5695 pwd = getpwnam(run_as);
5696 if (!pwd) {
5697 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5698 exit(1);
5702 if (chroot_dir) {
5703 if (chroot(chroot_dir) < 0) {
5704 fprintf(stderr, "chroot failed\n");
5705 exit(1);
5707 chdir("/");
5710 if (run_as) {
5711 if (setgid(pwd->pw_gid) < 0) {
5712 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5713 exit(1);
5715 if (setuid(pwd->pw_uid) < 0) {
5716 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5717 exit(1);
5719 if (setuid(0) != -1) {
5720 fprintf(stderr, "Dropping privileges failed\n");
5721 exit(1);
5724 #endif
5726 if (daemonize) {
5727 dup2(fd, 0);
5728 dup2(fd, 1);
5729 dup2(fd, 2);
5731 close(fd);
5734 main_loop();
5735 quit_timers();
5736 net_cleanup();
5738 return 0;