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
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
37 #include <sys/times.h>
41 #include <sys/ioctl.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
46 #if defined(__NetBSD__)
47 #include <net/if_tap.h>
50 #include <linux/if_tun.h>
52 #include <arpa/inet.h>
55 #include <sys/select.h>
58 #if defined(__FreeBSD__) || defined(__DragonFly__)
63 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
64 #include <freebsd/stdlib.h>
69 #include <linux/rtc.h>
71 /* For the benefit of older linux systems which don't supply it,
72 we use a local copy of hpet.h. */
73 /* #include <linux/hpet.h> */
76 #include <linux/ppdev.h>
77 #include <linux/parport.h>
81 #include <sys/ethernet.h>
82 #include <sys/sockio.h>
83 #include <netinet/arp.h>
84 #include <netinet/in.h>
85 #include <netinet/in_systm.h>
86 #include <netinet/ip.h>
87 #include <netinet/ip_icmp.h> // must come after ip.h
88 #include <netinet/udp.h>
89 #include <netinet/tcp.h>
97 #if defined(__OpenBSD__)
101 #if defined(CONFIG_VDE)
102 #include <libvdeplug.h>
108 #include <sys/timeb.h>
109 #include <mmsystem.h>
110 #define getopt_long_only getopt_long
111 #define memalign(align, size) malloc(size)
117 int qemu_main(int argc, char **argv, char **envp);
118 int main(int argc, char **argv)
120 qemu_main(argc, argv, NULL);
123 #define main qemu_main
125 #endif /* CONFIG_SDL */
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
133 #include "hw/boards.h"
135 #include "hw/pcmcia.h"
137 #include "hw/audiodev.h"
147 #include "qemu-timer.h"
148 #include "qemu-char.h"
149 #include "cache-utils.h"
152 #include "audio/audio.h"
153 #include "migration.h"
159 #include "exec-all.h"
161 #include "qemu_socket.h"
163 #if defined(CONFIG_SLIRP)
164 #include "libslirp.h"
167 //#define DEBUG_UNUSED_IOPORT
168 //#define DEBUG_IOPORT
170 //#define DEBUG_SLIRP
174 # define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
176 # define LOG_IOPORT(...) do { } while (0)
179 #define DEFAULT_RAM_SIZE 128
181 /* Max number of USB devices that can be specified on the commandline. */
182 #define MAX_USB_CMDLINE 8
184 /* Max number of bluetooth switches on the commandline. */
185 #define MAX_BT_CMDLINE 10
187 /* XXX: use a two level table to limit memory usage */
188 #define MAX_IOPORTS 65536
190 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
191 const char *bios_name = NULL;
192 static void *ioport_opaque[MAX_IOPORTS];
193 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
194 static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
195 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
196 to store the VM snapshots */
197 DriveInfo drives_table[MAX_DRIVES+1];
199 static int vga_ram_size;
200 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
201 static DisplayState *display_state;
205 const char* keyboard_layout = NULL;
206 int64_t ticks_per_sec;
209 NICInfo nd_table[MAX_NICS];
211 static int autostart;
212 static int rtc_utc = 1;
213 static int rtc_date_offset = -1; /* -1 means no change */
214 int cirrus_vga_enabled = 1;
215 int std_vga_enabled = 0;
216 int vmsvga_enabled = 0;
218 int graphic_width = 1024;
219 int graphic_height = 768;
220 int graphic_depth = 8;
222 int graphic_width = 800;
223 int graphic_height = 600;
224 int graphic_depth = 15;
226 static int full_screen = 0;
228 static int no_frame = 0;
231 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
232 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
233 CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
235 int win2k_install_hack = 0;
240 const char *vnc_display;
241 int acpi_enabled = 1;
247 int graphic_rotate = 0;
251 const char *option_rom[MAX_OPTION_ROMS];
253 int semihosting_enabled = 0;
257 const char *qemu_name;
259 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
260 unsigned int nb_prom_envs = 0;
261 const char *prom_envs[MAX_PROM_ENVS];
264 struct drive_opt drives_opt[MAX_DRIVES];
266 static CPUState *cur_cpu;
267 static CPUState *next_cpu;
268 static int event_pending = 1;
269 /* Conversion factor from emulated instructions to virtual clock ticks. */
270 static int icount_time_shift;
271 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
272 #define MAX_ICOUNT_SHIFT 10
273 /* Compensate for varying guest execution speed. */
274 static int64_t qemu_icount_bias;
275 static QEMUTimer *icount_rt_timer;
276 static QEMUTimer *icount_vm_timer;
277 static QEMUTimer *nographic_timer;
279 uint8_t qemu_uuid[16];
281 /***********************************************************/
282 /* x86 ISA bus support */
284 target_phys_addr_t isa_mem_base = 0;
287 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
288 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
290 static uint32_t ioport_read(int index, uint32_t address)
292 static IOPortReadFunc *default_func[3] = {
293 default_ioport_readb,
294 default_ioport_readw,
297 IOPortReadFunc *func = ioport_read_table[index][address];
299 func = default_func[index];
300 return func(ioport_opaque[address], address);
303 static void ioport_write(int index, uint32_t address, uint32_t data)
305 static IOPortWriteFunc *default_func[3] = {
306 default_ioport_writeb,
307 default_ioport_writew,
308 default_ioport_writel
310 IOPortWriteFunc *func = ioport_write_table[index][address];
312 func = default_func[index];
313 func(ioport_opaque[address], address, data);
316 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
318 #ifdef DEBUG_UNUSED_IOPORT
319 fprintf(stderr, "unused inb: port=0x%04x\n", address);
324 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
326 #ifdef DEBUG_UNUSED_IOPORT
327 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
331 /* default is to make two byte accesses */
332 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
335 data = ioport_read(0, address);
336 address = (address + 1) & (MAX_IOPORTS - 1);
337 data |= ioport_read(0, address) << 8;
341 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
343 ioport_write(0, address, data & 0xff);
344 address = (address + 1) & (MAX_IOPORTS - 1);
345 ioport_write(0, address, (data >> 8) & 0xff);
348 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
350 #ifdef DEBUG_UNUSED_IOPORT
351 fprintf(stderr, "unused inl: port=0x%04x\n", address);
356 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
358 #ifdef DEBUG_UNUSED_IOPORT
359 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
363 /* size is the word size in byte */
364 int register_ioport_read(int start, int length, int size,
365 IOPortReadFunc *func, void *opaque)
371 } else if (size == 2) {
373 } else if (size == 4) {
376 hw_error("register_ioport_read: invalid size");
379 for(i = start; i < start + length; i += size) {
380 ioport_read_table[bsize][i] = func;
381 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
382 hw_error("register_ioport_read: invalid opaque");
383 ioport_opaque[i] = opaque;
388 /* size is the word size in byte */
389 int register_ioport_write(int start, int length, int size,
390 IOPortWriteFunc *func, void *opaque)
396 } else if (size == 2) {
398 } else if (size == 4) {
401 hw_error("register_ioport_write: invalid size");
404 for(i = start; i < start + length; i += size) {
405 ioport_write_table[bsize][i] = func;
406 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
407 hw_error("register_ioport_write: invalid opaque");
408 ioport_opaque[i] = opaque;
413 void isa_unassign_ioport(int start, int length)
417 for(i = start; i < start + length; i++) {
418 ioport_read_table[0][i] = default_ioport_readb;
419 ioport_read_table[1][i] = default_ioport_readw;
420 ioport_read_table[2][i] = default_ioport_readl;
422 ioport_write_table[0][i] = default_ioport_writeb;
423 ioport_write_table[1][i] = default_ioport_writew;
424 ioport_write_table[2][i] = default_ioport_writel;
426 ioport_opaque[i] = NULL;
430 /***********************************************************/
432 void cpu_outb(CPUState *env, int addr, int val)
434 LOG_IOPORT("outb: %04x %02x\n", addr, val);
435 ioport_write(0, addr, val);
438 env->last_io_time = cpu_get_time_fast();
442 void cpu_outw(CPUState *env, int addr, int val)
444 LOG_IOPORT("outw: %04x %04x\n", addr, val);
445 ioport_write(1, addr, val);
448 env->last_io_time = cpu_get_time_fast();
452 void cpu_outl(CPUState *env, int addr, int val)
454 LOG_IOPORT("outl: %04x %08x\n", addr, val);
455 ioport_write(2, addr, val);
458 env->last_io_time = cpu_get_time_fast();
462 int cpu_inb(CPUState *env, int addr)
465 val = ioport_read(0, addr);
466 LOG_IOPORT("inb : %04x %02x\n", addr, val);
469 env->last_io_time = cpu_get_time_fast();
474 int cpu_inw(CPUState *env, int addr)
477 val = ioport_read(1, addr);
478 LOG_IOPORT("inw : %04x %04x\n", addr, val);
481 env->last_io_time = cpu_get_time_fast();
486 int cpu_inl(CPUState *env, int addr)
489 val = ioport_read(2, addr);
490 LOG_IOPORT("inl : %04x %08x\n", addr, val);
493 env->last_io_time = cpu_get_time_fast();
498 /***********************************************************/
499 void hw_error(const char *fmt, ...)
505 fprintf(stderr, "qemu: hardware error: ");
506 vfprintf(stderr, fmt, ap);
507 fprintf(stderr, "\n");
508 for(env = first_cpu; env != NULL; env = env->next_cpu) {
509 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
511 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
513 cpu_dump_state(env, stderr, fprintf, 0);
523 static QEMUBalloonEvent *qemu_balloon_event;
524 void *qemu_balloon_event_opaque;
526 void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
528 qemu_balloon_event = func;
529 qemu_balloon_event_opaque = opaque;
532 void qemu_balloon(ram_addr_t target)
534 if (qemu_balloon_event)
535 qemu_balloon_event(qemu_balloon_event_opaque, target);
538 ram_addr_t qemu_balloon_status(void)
540 if (qemu_balloon_event)
541 return qemu_balloon_event(qemu_balloon_event_opaque, 0);
545 /***********************************************************/
548 static QEMUPutKBDEvent *qemu_put_kbd_event;
549 static void *qemu_put_kbd_event_opaque;
550 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
551 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
553 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
555 qemu_put_kbd_event_opaque = opaque;
556 qemu_put_kbd_event = func;
559 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
560 void *opaque, int absolute,
563 QEMUPutMouseEntry *s, *cursor;
565 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
567 s->qemu_put_mouse_event = func;
568 s->qemu_put_mouse_event_opaque = opaque;
569 s->qemu_put_mouse_event_absolute = absolute;
570 s->qemu_put_mouse_event_name = qemu_strdup(name);
573 if (!qemu_put_mouse_event_head) {
574 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
578 cursor = qemu_put_mouse_event_head;
579 while (cursor->next != NULL)
580 cursor = cursor->next;
583 qemu_put_mouse_event_current = s;
588 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
590 QEMUPutMouseEntry *prev = NULL, *cursor;
592 if (!qemu_put_mouse_event_head || entry == NULL)
595 cursor = qemu_put_mouse_event_head;
596 while (cursor != NULL && cursor != entry) {
598 cursor = cursor->next;
601 if (cursor == NULL) // does not exist or list empty
603 else if (prev == NULL) { // entry is head
604 qemu_put_mouse_event_head = cursor->next;
605 if (qemu_put_mouse_event_current == entry)
606 qemu_put_mouse_event_current = cursor->next;
607 qemu_free(entry->qemu_put_mouse_event_name);
612 prev->next = entry->next;
614 if (qemu_put_mouse_event_current == entry)
615 qemu_put_mouse_event_current = prev;
617 qemu_free(entry->qemu_put_mouse_event_name);
621 void kbd_put_keycode(int keycode)
623 if (qemu_put_kbd_event) {
624 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
628 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
630 QEMUPutMouseEvent *mouse_event;
631 void *mouse_event_opaque;
634 if (!qemu_put_mouse_event_current) {
639 qemu_put_mouse_event_current->qemu_put_mouse_event;
641 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
644 if (graphic_rotate) {
645 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
648 width = graphic_width - 1;
649 mouse_event(mouse_event_opaque,
650 width - dy, dx, dz, buttons_state);
652 mouse_event(mouse_event_opaque,
653 dx, dy, dz, buttons_state);
657 int kbd_mouse_is_absolute(void)
659 if (!qemu_put_mouse_event_current)
662 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
665 void do_info_mice(Monitor *mon)
667 QEMUPutMouseEntry *cursor;
670 if (!qemu_put_mouse_event_head) {
671 monitor_printf(mon, "No mouse devices connected\n");
675 monitor_printf(mon, "Mouse devices available:\n");
676 cursor = qemu_put_mouse_event_head;
677 while (cursor != NULL) {
678 monitor_printf(mon, "%c Mouse #%d: %s\n",
679 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
680 index, cursor->qemu_put_mouse_event_name);
682 cursor = cursor->next;
686 void do_mouse_set(Monitor *mon, int index)
688 QEMUPutMouseEntry *cursor;
691 if (!qemu_put_mouse_event_head) {
692 monitor_printf(mon, "No mouse devices connected\n");
696 cursor = qemu_put_mouse_event_head;
697 while (cursor != NULL && index != i) {
699 cursor = cursor->next;
703 qemu_put_mouse_event_current = cursor;
705 monitor_printf(mon, "Mouse at given index not found\n");
708 /* compute with 96 bit intermediate result: (a*b)/c */
709 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
714 #ifdef WORDS_BIGENDIAN
724 rl = (uint64_t)u.l.low * (uint64_t)b;
725 rh = (uint64_t)u.l.high * (uint64_t)b;
728 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
732 /***********************************************************/
733 /* real time host monotonic timer */
735 #define QEMU_TIMER_BASE 1000000000LL
739 static int64_t clock_freq;
741 static void init_get_clock(void)
745 ret = QueryPerformanceFrequency(&freq);
747 fprintf(stderr, "Could not calibrate ticks\n");
750 clock_freq = freq.QuadPart;
753 static int64_t get_clock(void)
756 QueryPerformanceCounter(&ti);
757 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
762 static int use_rt_clock;
764 static void init_get_clock(void)
767 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
768 || defined(__DragonFly__)
771 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
778 static int64_t get_clock(void)
780 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
781 || defined(__DragonFly__)
784 clock_gettime(CLOCK_MONOTONIC, &ts);
785 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
789 /* XXX: using gettimeofday leads to problems if the date
790 changes, so it should be avoided. */
792 gettimeofday(&tv, NULL);
793 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
798 /* Return the virtual CPU time, based on the instruction counter. */
799 static int64_t cpu_get_icount(void)
802 CPUState *env = cpu_single_env;;
803 icount = qemu_icount;
806 fprintf(stderr, "Bad clock read\n");
807 icount -= (env->icount_decr.u16.low + env->icount_extra);
809 return qemu_icount_bias + (icount << icount_time_shift);
812 /***********************************************************/
813 /* guest cycle counter */
815 static int64_t cpu_ticks_prev;
816 static int64_t cpu_ticks_offset;
817 static int64_t cpu_clock_offset;
818 static int cpu_ticks_enabled;
820 /* return the host CPU cycle counter and handle stop/restart */
821 int64_t cpu_get_ticks(void)
824 return cpu_get_icount();
826 if (!cpu_ticks_enabled) {
827 return cpu_ticks_offset;
830 ticks = cpu_get_real_ticks();
831 if (cpu_ticks_prev > ticks) {
832 /* Note: non increasing ticks may happen if the host uses
834 cpu_ticks_offset += cpu_ticks_prev - ticks;
836 cpu_ticks_prev = ticks;
837 return ticks + cpu_ticks_offset;
841 /* return the host CPU monotonic timer and handle stop/restart */
842 static int64_t cpu_get_clock(void)
845 if (!cpu_ticks_enabled) {
846 return cpu_clock_offset;
849 return ti + cpu_clock_offset;
853 /* enable cpu_get_ticks() */
854 void cpu_enable_ticks(void)
856 if (!cpu_ticks_enabled) {
857 cpu_ticks_offset -= cpu_get_real_ticks();
858 cpu_clock_offset -= get_clock();
859 cpu_ticks_enabled = 1;
863 /* disable cpu_get_ticks() : the clock is stopped. You must not call
864 cpu_get_ticks() after that. */
865 void cpu_disable_ticks(void)
867 if (cpu_ticks_enabled) {
868 cpu_ticks_offset = cpu_get_ticks();
869 cpu_clock_offset = cpu_get_clock();
870 cpu_ticks_enabled = 0;
874 /***********************************************************/
877 #define QEMU_TIMER_REALTIME 0
878 #define QEMU_TIMER_VIRTUAL 1
882 /* XXX: add frequency */
890 struct QEMUTimer *next;
893 struct qemu_alarm_timer {
897 int (*start)(struct qemu_alarm_timer *t);
898 void (*stop)(struct qemu_alarm_timer *t);
899 void (*rearm)(struct qemu_alarm_timer *t);
903 #define ALARM_FLAG_DYNTICKS 0x1
904 #define ALARM_FLAG_EXPIRED 0x2
906 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
908 return t->flags & ALARM_FLAG_DYNTICKS;
911 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
913 if (!alarm_has_dynticks(t))
919 /* TODO: MIN_TIMER_REARM_US should be optimized */
920 #define MIN_TIMER_REARM_US 250
922 static struct qemu_alarm_timer *alarm_timer;
924 static int alarm_timer_rfd, alarm_timer_wfd;
929 struct qemu_alarm_win32 {
933 } alarm_win32_data = {0, NULL, -1};
935 static int win32_start_timer(struct qemu_alarm_timer *t);
936 static void win32_stop_timer(struct qemu_alarm_timer *t);
937 static void win32_rearm_timer(struct qemu_alarm_timer *t);
941 static int unix_start_timer(struct qemu_alarm_timer *t);
942 static void unix_stop_timer(struct qemu_alarm_timer *t);
946 static int dynticks_start_timer(struct qemu_alarm_timer *t);
947 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
948 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
950 static int hpet_start_timer(struct qemu_alarm_timer *t);
951 static void hpet_stop_timer(struct qemu_alarm_timer *t);
953 static int rtc_start_timer(struct qemu_alarm_timer *t);
954 static void rtc_stop_timer(struct qemu_alarm_timer *t);
956 #endif /* __linux__ */
960 /* Correlation between real and virtual time is always going to be
961 fairly approximate, so ignore small variation.
962 When the guest is idle real and virtual time will be aligned in
964 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
966 static void icount_adjust(void)
971 static int64_t last_delta;
972 /* If the VM is not running, then do nothing. */
976 cur_time = cpu_get_clock();
977 cur_icount = qemu_get_clock(vm_clock);
978 delta = cur_icount - cur_time;
979 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
981 && last_delta + ICOUNT_WOBBLE < delta * 2
982 && icount_time_shift > 0) {
983 /* The guest is getting too far ahead. Slow time down. */
987 && last_delta - ICOUNT_WOBBLE > delta * 2
988 && icount_time_shift < MAX_ICOUNT_SHIFT) {
989 /* The guest is getting too far behind. Speed time up. */
993 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
996 static void icount_adjust_rt(void * opaque)
998 qemu_mod_timer(icount_rt_timer,
999 qemu_get_clock(rt_clock) + 1000);
1003 static void icount_adjust_vm(void * opaque)
1005 qemu_mod_timer(icount_vm_timer,
1006 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1010 static void init_icount_adjust(void)
1012 /* Have both realtime and virtual time triggers for speed adjustment.
1013 The realtime trigger catches emulated time passing too slowly,
1014 the virtual time trigger catches emulated time passing too fast.
1015 Realtime triggers occur even when idle, so use them less frequently
1016 than VM triggers. */
1017 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1018 qemu_mod_timer(icount_rt_timer,
1019 qemu_get_clock(rt_clock) + 1000);
1020 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1021 qemu_mod_timer(icount_vm_timer,
1022 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1025 static struct qemu_alarm_timer alarm_timers[] = {
1028 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1029 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1030 /* HPET - if available - is preferred */
1031 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1032 /* ...otherwise try RTC */
1033 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1035 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1037 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1038 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1039 {"win32", 0, win32_start_timer,
1040 win32_stop_timer, NULL, &alarm_win32_data},
1045 static void show_available_alarms(void)
1049 printf("Available alarm timers, in order of precedence:\n");
1050 for (i = 0; alarm_timers[i].name; i++)
1051 printf("%s\n", alarm_timers[i].name);
1054 static void configure_alarms(char const *opt)
1058 int count = ARRAY_SIZE(alarm_timers) - 1;
1061 struct qemu_alarm_timer tmp;
1063 if (!strcmp(opt, "?")) {
1064 show_available_alarms();
1070 /* Reorder the array */
1071 name = strtok(arg, ",");
1073 for (i = 0; i < count && alarm_timers[i].name; i++) {
1074 if (!strcmp(alarm_timers[i].name, name))
1079 fprintf(stderr, "Unknown clock %s\n", name);
1088 tmp = alarm_timers[i];
1089 alarm_timers[i] = alarm_timers[cur];
1090 alarm_timers[cur] = tmp;
1094 name = strtok(NULL, ",");
1100 /* Disable remaining timers */
1101 for (i = cur; i < count; i++)
1102 alarm_timers[i].name = NULL;
1104 show_available_alarms();
1109 QEMUClock *rt_clock;
1110 QEMUClock *vm_clock;
1112 static QEMUTimer *active_timers[2];
1114 static QEMUClock *qemu_new_clock(int type)
1117 clock = qemu_mallocz(sizeof(QEMUClock));
1122 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1126 ts = qemu_mallocz(sizeof(QEMUTimer));
1129 ts->opaque = opaque;
1133 void qemu_free_timer(QEMUTimer *ts)
1138 /* stop a timer, but do not dealloc it */
1139 void qemu_del_timer(QEMUTimer *ts)
1143 /* NOTE: this code must be signal safe because
1144 qemu_timer_expired() can be called from a signal. */
1145 pt = &active_timers[ts->clock->type];
1158 /* modify the current timer so that it will be fired when current_time
1159 >= expire_time. The corresponding callback will be called. */
1160 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1166 /* add the timer in the sorted list */
1167 /* NOTE: this code must be signal safe because
1168 qemu_timer_expired() can be called from a signal. */
1169 pt = &active_timers[ts->clock->type];
1174 if (t->expire_time > expire_time)
1178 ts->expire_time = expire_time;
1182 /* Rearm if necessary */
1183 if (pt == &active_timers[ts->clock->type]) {
1184 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1185 qemu_rearm_alarm_timer(alarm_timer);
1187 /* Interrupt execution to force deadline recalculation. */
1188 if (use_icount && cpu_single_env) {
1189 cpu_exit(cpu_single_env);
1194 int qemu_timer_pending(QEMUTimer *ts)
1197 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1204 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1208 return (timer_head->expire_time <= current_time);
1211 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1217 if (!ts || ts->expire_time > current_time)
1219 /* remove timer from the list before calling the callback */
1220 *ptimer_head = ts->next;
1223 /* run the callback (the timer list can be modified) */
1228 int64_t qemu_get_clock(QEMUClock *clock)
1230 switch(clock->type) {
1231 case QEMU_TIMER_REALTIME:
1232 return get_clock() / 1000000;
1234 case QEMU_TIMER_VIRTUAL:
1236 return cpu_get_icount();
1238 return cpu_get_clock();
1243 static void init_timers(void)
1246 ticks_per_sec = QEMU_TIMER_BASE;
1247 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1248 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1252 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1254 uint64_t expire_time;
1256 if (qemu_timer_pending(ts)) {
1257 expire_time = ts->expire_time;
1261 qemu_put_be64(f, expire_time);
1264 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1266 uint64_t expire_time;
1268 expire_time = qemu_get_be64(f);
1269 if (expire_time != -1) {
1270 qemu_mod_timer(ts, expire_time);
1276 static void timer_save(QEMUFile *f, void *opaque)
1278 if (cpu_ticks_enabled) {
1279 hw_error("cannot save state if virtual timers are running");
1281 qemu_put_be64(f, cpu_ticks_offset);
1282 qemu_put_be64(f, ticks_per_sec);
1283 qemu_put_be64(f, cpu_clock_offset);
1286 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1288 if (version_id != 1 && version_id != 2)
1290 if (cpu_ticks_enabled) {
1293 cpu_ticks_offset=qemu_get_be64(f);
1294 ticks_per_sec=qemu_get_be64(f);
1295 if (version_id == 2) {
1296 cpu_clock_offset=qemu_get_be64(f);
1302 static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1303 DWORD_PTR dwUser, DWORD_PTR dw1,
1306 static void host_alarm_handler(int host_signum)
1310 #define DISP_FREQ 1000
1312 static int64_t delta_min = INT64_MAX;
1313 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1315 ti = qemu_get_clock(vm_clock);
1316 if (last_clock != 0) {
1317 delta = ti - last_clock;
1318 if (delta < delta_min)
1320 if (delta > delta_max)
1323 if (++count == DISP_FREQ) {
1324 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1325 muldiv64(delta_min, 1000000, ticks_per_sec),
1326 muldiv64(delta_max, 1000000, ticks_per_sec),
1327 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1328 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1330 delta_min = INT64_MAX;
1338 if (alarm_has_dynticks(alarm_timer) ||
1340 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1341 qemu_get_clock(vm_clock))) ||
1342 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1343 qemu_get_clock(rt_clock))) {
1344 CPUState *env = next_cpu;
1347 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1348 SetEvent(data->host_alarm);
1350 static const char byte = 0;
1351 write(alarm_timer_wfd, &byte, sizeof(byte));
1353 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1356 /* stop the currently executing cpu because a timer occured */
1359 if (env->kqemu_enabled) {
1360 kqemu_cpu_interrupt(env);
1368 static int64_t qemu_next_deadline(void)
1372 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1373 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1374 qemu_get_clock(vm_clock);
1376 /* To avoid problems with overflow limit this to 2^32. */
1386 #if defined(__linux__) || defined(_WIN32)
1387 static uint64_t qemu_next_deadline_dyntick(void)
1395 delta = (qemu_next_deadline() + 999) / 1000;
1397 if (active_timers[QEMU_TIMER_REALTIME]) {
1398 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1399 qemu_get_clock(rt_clock))*1000;
1400 if (rtdelta < delta)
1404 if (delta < MIN_TIMER_REARM_US)
1405 delta = MIN_TIMER_REARM_US;
1413 /* Sets a specific flag */
1414 static int fcntl_setfl(int fd, int flag)
1418 flags = fcntl(fd, F_GETFL);
1422 if (fcntl(fd, F_SETFL, flags | flag) == -1)
1428 #if defined(__linux__)
1430 #define RTC_FREQ 1024
1432 static void enable_sigio_timer(int fd)
1434 struct sigaction act;
1437 sigfillset(&act.sa_mask);
1439 act.sa_handler = host_alarm_handler;
1441 sigaction(SIGIO, &act, NULL);
1442 fcntl_setfl(fd, O_ASYNC);
1443 fcntl(fd, F_SETOWN, getpid());
1446 static int hpet_start_timer(struct qemu_alarm_timer *t)
1448 struct hpet_info info;
1451 fd = open("/dev/hpet", O_RDONLY);
1456 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1458 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1459 "error, but for better emulation accuracy type:\n"
1460 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1464 /* Check capabilities */
1465 r = ioctl(fd, HPET_INFO, &info);
1469 /* Enable periodic mode */
1470 r = ioctl(fd, HPET_EPI, 0);
1471 if (info.hi_flags && (r < 0))
1474 /* Enable interrupt */
1475 r = ioctl(fd, HPET_IE_ON, 0);
1479 enable_sigio_timer(fd);
1480 t->priv = (void *)(long)fd;
1488 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1490 int fd = (long)t->priv;
1495 static int rtc_start_timer(struct qemu_alarm_timer *t)
1498 unsigned long current_rtc_freq = 0;
1500 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1503 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1504 if (current_rtc_freq != RTC_FREQ &&
1505 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1506 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1507 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1508 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1511 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1517 enable_sigio_timer(rtc_fd);
1519 t->priv = (void *)(long)rtc_fd;
1524 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1526 int rtc_fd = (long)t->priv;
1531 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1535 struct sigaction act;
1537 sigfillset(&act.sa_mask);
1539 act.sa_handler = host_alarm_handler;
1541 sigaction(SIGALRM, &act, NULL);
1543 ev.sigev_value.sival_int = 0;
1544 ev.sigev_notify = SIGEV_SIGNAL;
1545 ev.sigev_signo = SIGALRM;
1547 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1548 perror("timer_create");
1550 /* disable dynticks */
1551 fprintf(stderr, "Dynamic Ticks disabled\n");
1556 t->priv = (void *)(long)host_timer;
1561 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1563 timer_t host_timer = (timer_t)(long)t->priv;
1565 timer_delete(host_timer);
1568 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1570 timer_t host_timer = (timer_t)(long)t->priv;
1571 struct itimerspec timeout;
1572 int64_t nearest_delta_us = INT64_MAX;
1575 if (!active_timers[QEMU_TIMER_REALTIME] &&
1576 !active_timers[QEMU_TIMER_VIRTUAL])
1579 nearest_delta_us = qemu_next_deadline_dyntick();
1581 /* check whether a timer is already running */
1582 if (timer_gettime(host_timer, &timeout)) {
1584 fprintf(stderr, "Internal timer error: aborting\n");
1587 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1588 if (current_us && current_us <= nearest_delta_us)
1591 timeout.it_interval.tv_sec = 0;
1592 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1593 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1594 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1595 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1597 fprintf(stderr, "Internal timer error: aborting\n");
1602 #endif /* defined(__linux__) */
1604 static int unix_start_timer(struct qemu_alarm_timer *t)
1606 struct sigaction act;
1607 struct itimerval itv;
1611 sigfillset(&act.sa_mask);
1613 act.sa_handler = host_alarm_handler;
1615 sigaction(SIGALRM, &act, NULL);
1617 itv.it_interval.tv_sec = 0;
1618 /* for i386 kernel 2.6 to get 1 ms */
1619 itv.it_interval.tv_usec = 999;
1620 itv.it_value.tv_sec = 0;
1621 itv.it_value.tv_usec = 10 * 1000;
1623 err = setitimer(ITIMER_REAL, &itv, NULL);
1630 static void unix_stop_timer(struct qemu_alarm_timer *t)
1632 struct itimerval itv;
1634 memset(&itv, 0, sizeof(itv));
1635 setitimer(ITIMER_REAL, &itv, NULL);
1638 #endif /* !defined(_WIN32) */
1640 static void try_to_rearm_timer(void *opaque)
1642 struct qemu_alarm_timer *t = opaque;
1646 /* Drain the notify pipe */
1649 len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1650 } while ((len == -1 && errno == EINTR) || len > 0);
1653 if (t->flags & ALARM_FLAG_EXPIRED) {
1654 alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1655 qemu_rearm_alarm_timer(alarm_timer);
1661 static int win32_start_timer(struct qemu_alarm_timer *t)
1664 struct qemu_alarm_win32 *data = t->priv;
1667 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1668 if (!data->host_alarm) {
1669 perror("Failed CreateEvent");
1673 memset(&tc, 0, sizeof(tc));
1674 timeGetDevCaps(&tc, sizeof(tc));
1676 if (data->period < tc.wPeriodMin)
1677 data->period = tc.wPeriodMin;
1679 timeBeginPeriod(data->period);
1681 flags = TIME_CALLBACK_FUNCTION;
1682 if (alarm_has_dynticks(t))
1683 flags |= TIME_ONESHOT;
1685 flags |= TIME_PERIODIC;
1687 data->timerId = timeSetEvent(1, // interval (ms)
1688 data->period, // resolution
1689 host_alarm_handler, // function
1690 (DWORD)t, // parameter
1693 if (!data->timerId) {
1694 perror("Failed to initialize win32 alarm timer");
1696 timeEndPeriod(data->period);
1697 CloseHandle(data->host_alarm);
1701 qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1706 static void win32_stop_timer(struct qemu_alarm_timer *t)
1708 struct qemu_alarm_win32 *data = t->priv;
1710 timeKillEvent(data->timerId);
1711 timeEndPeriod(data->period);
1713 CloseHandle(data->host_alarm);
1716 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1718 struct qemu_alarm_win32 *data = t->priv;
1719 uint64_t nearest_delta_us;
1721 if (!active_timers[QEMU_TIMER_REALTIME] &&
1722 !active_timers[QEMU_TIMER_VIRTUAL])
1725 nearest_delta_us = qemu_next_deadline_dyntick();
1726 nearest_delta_us /= 1000;
1728 timeKillEvent(data->timerId);
1730 data->timerId = timeSetEvent(1,
1734 TIME_ONESHOT | TIME_PERIODIC);
1736 if (!data->timerId) {
1737 perror("Failed to re-arm win32 alarm timer");
1739 timeEndPeriod(data->period);
1740 CloseHandle(data->host_alarm);
1747 static int init_timer_alarm(void)
1749 struct qemu_alarm_timer *t = NULL;
1759 err = fcntl_setfl(fds[0], O_NONBLOCK);
1763 err = fcntl_setfl(fds[1], O_NONBLOCK);
1767 alarm_timer_rfd = fds[0];
1768 alarm_timer_wfd = fds[1];
1771 for (i = 0; alarm_timers[i].name; i++) {
1772 t = &alarm_timers[i];
1785 qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1786 try_to_rearm_timer, NULL, t);
1801 static void quit_timers(void)
1803 alarm_timer->stop(alarm_timer);
1807 /***********************************************************/
1808 /* host time/date access */
1809 void qemu_get_timedate(struct tm *tm, int offset)
1816 if (rtc_date_offset == -1) {
1820 ret = localtime(&ti);
1822 ti -= rtc_date_offset;
1826 memcpy(tm, ret, sizeof(struct tm));
1829 int qemu_timedate_diff(struct tm *tm)
1833 if (rtc_date_offset == -1)
1835 seconds = mktimegm(tm);
1837 seconds = mktime(tm);
1839 seconds = mktimegm(tm) + rtc_date_offset;
1841 return seconds - time(NULL);
1845 static void socket_cleanup(void)
1850 static int socket_init(void)
1855 ret = WSAStartup(MAKEWORD(2,2), &Data);
1857 err = WSAGetLastError();
1858 fprintf(stderr, "WSAStartup: %d\n", err);
1861 atexit(socket_cleanup);
1866 const char *get_opt_name(char *buf, int buf_size, const char *p)
1871 while (*p != '\0' && *p != '=') {
1872 if (q && (q - buf) < buf_size - 1)
1882 const char *get_opt_value(char *buf, int buf_size, const char *p)
1887 while (*p != '\0') {
1889 if (*(p + 1) != ',')
1893 if (q && (q - buf) < buf_size - 1)
1903 int get_param_value(char *buf, int buf_size,
1904 const char *tag, const char *str)
1911 p = get_opt_name(option, sizeof(option), p);
1915 if (!strcmp(tag, option)) {
1916 (void)get_opt_value(buf, buf_size, p);
1919 p = get_opt_value(NULL, 0, p);
1928 int check_params(char *buf, int buf_size,
1929 const char * const *params, const char *str)
1936 p = get_opt_name(buf, buf_size, p);
1940 for(i = 0; params[i] != NULL; i++)
1941 if (!strcmp(params[i], buf))
1943 if (params[i] == NULL)
1945 p = get_opt_value(NULL, 0, p);
1953 /***********************************************************/
1954 /* Bluetooth support */
1957 static struct HCIInfo *hci_table[MAX_NICS];
1959 static struct bt_vlan_s {
1960 struct bt_scatternet_s net;
1962 struct bt_vlan_s *next;
1965 /* find or alloc a new bluetooth "VLAN" */
1966 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1968 struct bt_vlan_s **pvlan, *vlan;
1969 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1973 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1975 pvlan = &first_bt_vlan;
1976 while (*pvlan != NULL)
1977 pvlan = &(*pvlan)->next;
1982 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1986 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1991 static struct HCIInfo null_hci = {
1992 .cmd_send = null_hci_send,
1993 .sco_send = null_hci_send,
1994 .acl_send = null_hci_send,
1995 .bdaddr_set = null_hci_addr_set,
1998 struct HCIInfo *qemu_next_hci(void)
2000 if (cur_hci == nb_hcis)
2003 return hci_table[cur_hci++];
2006 static struct HCIInfo *hci_init(const char *str)
2009 struct bt_scatternet_s *vlan = 0;
2011 if (!strcmp(str, "null"))
2014 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2016 return bt_host_hci(str[4] ? str + 5 : "hci0");
2017 else if (!strncmp(str, "hci", 3)) {
2020 if (!strncmp(str + 3, ",vlan=", 6)) {
2021 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2026 vlan = qemu_find_bt_vlan(0);
2028 return bt_new_hci(vlan);
2031 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2036 static int bt_hci_parse(const char *str)
2038 struct HCIInfo *hci;
2041 if (nb_hcis >= MAX_NICS) {
2042 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2046 hci = hci_init(str);
2055 bdaddr.b[5] = 0x56 + nb_hcis;
2056 hci->bdaddr_set(hci, bdaddr.b);
2058 hci_table[nb_hcis++] = hci;
2063 static void bt_vhci_add(int vlan_id)
2065 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2068 fprintf(stderr, "qemu: warning: adding a VHCI to "
2069 "an empty scatternet %i\n", vlan_id);
2071 bt_vhci_init(bt_new_hci(vlan));
2074 static struct bt_device_s *bt_device_add(const char *opt)
2076 struct bt_scatternet_s *vlan;
2078 char *endp = strstr(opt, ",vlan=");
2079 int len = (endp ? endp - opt : strlen(opt)) + 1;
2082 pstrcpy(devname, MIN(sizeof(devname), len), opt);
2085 vlan_id = strtol(endp + 6, &endp, 0);
2087 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2092 vlan = qemu_find_bt_vlan(vlan_id);
2095 fprintf(stderr, "qemu: warning: adding a slave device to "
2096 "an empty scatternet %i\n", vlan_id);
2098 if (!strcmp(devname, "keyboard"))
2099 return bt_keyboard_init(vlan);
2101 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2105 static int bt_parse(const char *opt)
2107 const char *endp, *p;
2110 if (strstart(opt, "hci", &endp)) {
2111 if (!*endp || *endp == ',') {
2113 if (!strstart(endp, ",vlan=", 0))
2116 return bt_hci_parse(opt);
2118 } else if (strstart(opt, "vhci", &endp)) {
2119 if (!*endp || *endp == ',') {
2121 if (strstart(endp, ",vlan=", &p)) {
2122 vlan = strtol(p, (char **) &endp, 0);
2124 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2128 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2137 } else if (strstart(opt, "device:", &endp))
2138 return !bt_device_add(endp);
2140 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2144 /***********************************************************/
2145 /* QEMU Block devices */
2147 #define HD_ALIAS "index=%d,media=disk"
2148 #define CDROM_ALIAS "index=2,media=cdrom"
2149 #define FD_ALIAS "index=%d,if=floppy"
2150 #define PFLASH_ALIAS "if=pflash"
2151 #define MTD_ALIAS "if=mtd"
2152 #define SD_ALIAS "index=0,if=sd"
2154 static int drive_opt_get_free_idx(void)
2158 for (index = 0; index < MAX_DRIVES; index++)
2159 if (!drives_opt[index].used) {
2160 drives_opt[index].used = 1;
2167 static int drive_get_free_idx(void)
2171 for (index = 0; index < MAX_DRIVES; index++)
2172 if (!drives_table[index].used) {
2173 drives_table[index].used = 1;
2180 int drive_add(const char *file, const char *fmt, ...)
2183 int index = drive_opt_get_free_idx();
2185 if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2186 fprintf(stderr, "qemu: too many drives\n");
2190 drives_opt[index].file = file;
2192 vsnprintf(drives_opt[index].opt,
2193 sizeof(drives_opt[0].opt), fmt, ap);
2200 void drive_remove(int index)
2202 drives_opt[index].used = 0;
2206 int drive_get_index(BlockInterfaceType type, int bus, int unit)
2210 /* seek interface, bus and unit */
2212 for (index = 0; index < MAX_DRIVES; index++)
2213 if (drives_table[index].type == type &&
2214 drives_table[index].bus == bus &&
2215 drives_table[index].unit == unit &&
2216 drives_table[index].used)
2222 int drive_get_max_bus(BlockInterfaceType type)
2228 for (index = 0; index < nb_drives; index++) {
2229 if(drives_table[index].type == type &&
2230 drives_table[index].bus > max_bus)
2231 max_bus = drives_table[index].bus;
2236 const char *drive_get_serial(BlockDriverState *bdrv)
2240 for (index = 0; index < nb_drives; index++)
2241 if (drives_table[index].bdrv == bdrv)
2242 return drives_table[index].serial;
2247 BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2251 for (index = 0; index < nb_drives; index++)
2252 if (drives_table[index].bdrv == bdrv)
2253 return drives_table[index].onerror;
2255 return BLOCK_ERR_STOP_ENOSPC;
2258 static void bdrv_format_print(void *opaque, const char *name)
2260 fprintf(stderr, " %s", name);
2263 void drive_uninit(BlockDriverState *bdrv)
2267 for (i = 0; i < MAX_DRIVES; i++)
2268 if (drives_table[i].bdrv == bdrv) {
2269 drives_table[i].bdrv = NULL;
2270 drives_table[i].used = 0;
2271 drive_remove(drives_table[i].drive_opt_idx);
2277 int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2283 const char *mediastr = "";
2284 BlockInterfaceType type;
2285 enum { MEDIA_DISK, MEDIA_CDROM } media;
2286 int bus_id, unit_id;
2287 int cyls, heads, secs, translation;
2288 BlockDriverState *bdrv;
2289 BlockDriver *drv = NULL;
2290 QEMUMachine *machine = opaque;
2294 int bdrv_flags, onerror;
2295 int drives_table_idx;
2296 char *str = arg->opt;
2297 static const char * const params[] = { "bus", "unit", "if", "index",
2298 "cyls", "heads", "secs", "trans",
2299 "media", "snapshot", "file",
2300 "cache", "format", "serial", "werror",
2303 if (check_params(buf, sizeof(buf), params, str) < 0) {
2304 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2310 cyls = heads = secs = 0;
2313 translation = BIOS_ATA_TRANSLATION_AUTO;
2317 if (machine->use_scsi) {
2319 max_devs = MAX_SCSI_DEVS;
2320 pstrcpy(devname, sizeof(devname), "scsi");
2323 max_devs = MAX_IDE_DEVS;
2324 pstrcpy(devname, sizeof(devname), "ide");
2328 /* extract parameters */
2330 if (get_param_value(buf, sizeof(buf), "bus", str)) {
2331 bus_id = strtol(buf, NULL, 0);
2333 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2338 if (get_param_value(buf, sizeof(buf), "unit", str)) {
2339 unit_id = strtol(buf, NULL, 0);
2341 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2346 if (get_param_value(buf, sizeof(buf), "if", str)) {
2347 pstrcpy(devname, sizeof(devname), buf);
2348 if (!strcmp(buf, "ide")) {
2350 max_devs = MAX_IDE_DEVS;
2351 } else if (!strcmp(buf, "scsi")) {
2353 max_devs = MAX_SCSI_DEVS;
2354 } else if (!strcmp(buf, "floppy")) {
2357 } else if (!strcmp(buf, "pflash")) {
2360 } else if (!strcmp(buf, "mtd")) {
2363 } else if (!strcmp(buf, "sd")) {
2366 } else if (!strcmp(buf, "virtio")) {
2370 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2375 if (get_param_value(buf, sizeof(buf), "index", str)) {
2376 index = strtol(buf, NULL, 0);
2378 fprintf(stderr, "qemu: '%s' invalid index\n", str);
2383 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2384 cyls = strtol(buf, NULL, 0);
2387 if (get_param_value(buf, sizeof(buf), "heads", str)) {
2388 heads = strtol(buf, NULL, 0);
2391 if (get_param_value(buf, sizeof(buf), "secs", str)) {
2392 secs = strtol(buf, NULL, 0);
2395 if (cyls || heads || secs) {
2396 if (cyls < 1 || cyls > 16383) {
2397 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2400 if (heads < 1 || heads > 16) {
2401 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2404 if (secs < 1 || secs > 63) {
2405 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2410 if (get_param_value(buf, sizeof(buf), "trans", str)) {
2413 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2417 if (!strcmp(buf, "none"))
2418 translation = BIOS_ATA_TRANSLATION_NONE;
2419 else if (!strcmp(buf, "lba"))
2420 translation = BIOS_ATA_TRANSLATION_LBA;
2421 else if (!strcmp(buf, "auto"))
2422 translation = BIOS_ATA_TRANSLATION_AUTO;
2424 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2429 if (get_param_value(buf, sizeof(buf), "media", str)) {
2430 if (!strcmp(buf, "disk")) {
2432 } else if (!strcmp(buf, "cdrom")) {
2433 if (cyls || secs || heads) {
2435 "qemu: '%s' invalid physical CHS format\n", str);
2438 media = MEDIA_CDROM;
2440 fprintf(stderr, "qemu: '%s' invalid media\n", str);
2445 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2446 if (!strcmp(buf, "on"))
2448 else if (!strcmp(buf, "off"))
2451 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2456 if (get_param_value(buf, sizeof(buf), "cache", str)) {
2457 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2459 else if (!strcmp(buf, "writethrough"))
2461 else if (!strcmp(buf, "writeback"))
2464 fprintf(stderr, "qemu: invalid cache option\n");
2469 if (get_param_value(buf, sizeof(buf), "format", str)) {
2470 if (strcmp(buf, "?") == 0) {
2471 fprintf(stderr, "qemu: Supported formats:");
2472 bdrv_iterate_format(bdrv_format_print, NULL);
2473 fprintf(stderr, "\n");
2476 drv = bdrv_find_format(buf);
2478 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2483 if (arg->file == NULL)
2484 get_param_value(file, sizeof(file), "file", str);
2486 pstrcpy(file, sizeof(file), arg->file);
2488 if (!get_param_value(serial, sizeof(serial), "serial", str))
2489 memset(serial, 0, sizeof(serial));
2491 onerror = BLOCK_ERR_STOP_ENOSPC;
2492 if (get_param_value(buf, sizeof(serial), "werror", str)) {
2493 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2494 fprintf(stderr, "werror is no supported by this format\n");
2497 if (!strcmp(buf, "ignore"))
2498 onerror = BLOCK_ERR_IGNORE;
2499 else if (!strcmp(buf, "enospc"))
2500 onerror = BLOCK_ERR_STOP_ENOSPC;
2501 else if (!strcmp(buf, "stop"))
2502 onerror = BLOCK_ERR_STOP_ANY;
2503 else if (!strcmp(buf, "report"))
2504 onerror = BLOCK_ERR_REPORT;
2506 fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2511 /* compute bus and unit according index */
2514 if (bus_id != 0 || unit_id != -1) {
2516 "qemu: '%s' index cannot be used with bus and unit\n", str);
2524 unit_id = index % max_devs;
2525 bus_id = index / max_devs;
2529 /* if user doesn't specify a unit_id,
2530 * try to find the first free
2533 if (unit_id == -1) {
2535 while (drive_get_index(type, bus_id, unit_id) != -1) {
2537 if (max_devs && unit_id >= max_devs) {
2538 unit_id -= max_devs;
2546 if (max_devs && unit_id >= max_devs) {
2547 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2548 str, unit_id, max_devs - 1);
2553 * ignore multiple definitions
2556 if (drive_get_index(type, bus_id, unit_id) != -1)
2561 if (type == IF_IDE || type == IF_SCSI)
2562 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2564 snprintf(buf, sizeof(buf), "%s%i%s%i",
2565 devname, bus_id, mediastr, unit_id);
2567 snprintf(buf, sizeof(buf), "%s%s%i",
2568 devname, mediastr, unit_id);
2569 bdrv = bdrv_new(buf);
2570 drives_table_idx = drive_get_free_idx();
2571 drives_table[drives_table_idx].bdrv = bdrv;
2572 drives_table[drives_table_idx].type = type;
2573 drives_table[drives_table_idx].bus = bus_id;
2574 drives_table[drives_table_idx].unit = unit_id;
2575 drives_table[drives_table_idx].onerror = onerror;
2576 drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2577 strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2586 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2587 bdrv_set_translation_hint(bdrv, translation);
2591 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2596 /* FIXME: This isn't really a floppy, but it's a reasonable
2599 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2610 bdrv_flags |= BDRV_O_SNAPSHOT;
2611 cache = 2; /* always use write-back with snapshot */
2613 if (cache == 0) /* no caching */
2614 bdrv_flags |= BDRV_O_NOCACHE;
2615 else if (cache == 2) /* write-back */
2616 bdrv_flags |= BDRV_O_CACHE_WB;
2617 else if (cache == 3) /* not specified */
2618 bdrv_flags |= BDRV_O_CACHE_DEF;
2619 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2620 fprintf(stderr, "qemu: could not open disk image %s\n",
2624 if (bdrv_key_required(bdrv))
2626 return drives_table_idx;
2629 /***********************************************************/
2632 static USBPort *used_usb_ports;
2633 static USBPort *free_usb_ports;
2635 /* ??? Maybe change this to register a hub to keep track of the topology. */
2636 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2637 usb_attachfn attach)
2639 port->opaque = opaque;
2640 port->index = index;
2641 port->attach = attach;
2642 port->next = free_usb_ports;
2643 free_usb_ports = port;
2646 int usb_device_add_dev(USBDevice *dev)
2650 /* Find a USB port to add the device to. */
2651 port = free_usb_ports;
2655 /* Create a new hub and chain it on. */
2656 free_usb_ports = NULL;
2657 port->next = used_usb_ports;
2658 used_usb_ports = port;
2660 hub = usb_hub_init(VM_USB_HUB_SIZE);
2661 usb_attach(port, hub);
2662 port = free_usb_ports;
2665 free_usb_ports = port->next;
2666 port->next = used_usb_ports;
2667 used_usb_ports = port;
2668 usb_attach(port, dev);
2672 static void usb_msd_password_cb(void *opaque, int err)
2674 USBDevice *dev = opaque;
2677 usb_device_add_dev(dev);
2679 dev->handle_destroy(dev);
2682 static int usb_device_add(const char *devname, int is_hotplug)
2687 if (!free_usb_ports)
2690 if (strstart(devname, "host:", &p)) {
2691 dev = usb_host_device_open(p);
2692 } else if (!strcmp(devname, "mouse")) {
2693 dev = usb_mouse_init();
2694 } else if (!strcmp(devname, "tablet")) {
2695 dev = usb_tablet_init();
2696 } else if (!strcmp(devname, "keyboard")) {
2697 dev = usb_keyboard_init();
2698 } else if (strstart(devname, "disk:", &p)) {
2699 BlockDriverState *bs;
2701 dev = usb_msd_init(p);
2704 bs = usb_msd_get_bdrv(dev);
2705 if (bdrv_key_required(bs)) {
2708 monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2713 } else if (!strcmp(devname, "wacom-tablet")) {
2714 dev = usb_wacom_init();
2715 } else if (strstart(devname, "serial:", &p)) {
2716 dev = usb_serial_init(p);
2717 #ifdef CONFIG_BRLAPI
2718 } else if (!strcmp(devname, "braille")) {
2719 dev = usb_baum_init();
2721 } else if (strstart(devname, "net:", &p)) {
2724 if (net_client_init("nic", p) < 0)
2726 nd_table[nic].model = "usb";
2727 dev = usb_net_init(&nd_table[nic]);
2728 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2729 dev = usb_bt_init(devname[2] ? hci_init(p) :
2730 bt_new_hci(qemu_find_bt_vlan(0)));
2737 return usb_device_add_dev(dev);
2740 int usb_device_del_addr(int bus_num, int addr)
2746 if (!used_usb_ports)
2752 lastp = &used_usb_ports;
2753 port = used_usb_ports;
2754 while (port && port->dev->addr != addr) {
2755 lastp = &port->next;
2763 *lastp = port->next;
2764 usb_attach(port, NULL);
2765 dev->handle_destroy(dev);
2766 port->next = free_usb_ports;
2767 free_usb_ports = port;
2771 static int usb_device_del(const char *devname)
2776 if (strstart(devname, "host:", &p))
2777 return usb_host_device_close(p);
2779 if (!used_usb_ports)
2782 p = strchr(devname, '.');
2785 bus_num = strtoul(devname, NULL, 0);
2786 addr = strtoul(p + 1, NULL, 0);
2788 return usb_device_del_addr(bus_num, addr);
2791 void do_usb_add(Monitor *mon, const char *devname)
2793 usb_device_add(devname, 1);
2796 void do_usb_del(Monitor *mon, const char *devname)
2798 usb_device_del(devname);
2801 void usb_info(Monitor *mon)
2805 const char *speed_str;
2808 monitor_printf(mon, "USB support not enabled\n");
2812 for (port = used_usb_ports; port; port = port->next) {
2816 switch(dev->speed) {
2820 case USB_SPEED_FULL:
2823 case USB_SPEED_HIGH:
2830 monitor_printf(mon, " Device %d.%d, Speed %s Mb/s, Product %s\n",
2831 0, dev->addr, speed_str, dev->devname);
2835 /***********************************************************/
2836 /* PCMCIA/Cardbus */
2838 static struct pcmcia_socket_entry_s {
2839 struct pcmcia_socket_s *socket;
2840 struct pcmcia_socket_entry_s *next;
2841 } *pcmcia_sockets = 0;
2843 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2845 struct pcmcia_socket_entry_s *entry;
2847 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2848 entry->socket = socket;
2849 entry->next = pcmcia_sockets;
2850 pcmcia_sockets = entry;
2853 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2855 struct pcmcia_socket_entry_s *entry, **ptr;
2857 ptr = &pcmcia_sockets;
2858 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2859 if (entry->socket == socket) {
2865 void pcmcia_info(Monitor *mon)
2867 struct pcmcia_socket_entry_s *iter;
2869 if (!pcmcia_sockets)
2870 monitor_printf(mon, "No PCMCIA sockets\n");
2872 for (iter = pcmcia_sockets; iter; iter = iter->next)
2873 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2874 iter->socket->attached ? iter->socket->card_string :
2878 /***********************************************************/
2879 /* register display */
2881 struct DisplayAllocator default_allocator = {
2882 defaultallocator_create_displaysurface,
2883 defaultallocator_resize_displaysurface,
2884 defaultallocator_free_displaysurface
2887 void register_displaystate(DisplayState *ds)
2897 DisplayState *get_displaystate(void)
2899 return display_state;
2902 DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2904 if(ds->allocator == &default_allocator) ds->allocator = da;
2905 return ds->allocator;
2910 static void dumb_display_init(void)
2912 DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2913 ds->allocator = &default_allocator;
2914 ds->surface = qemu_create_displaysurface(ds, 640, 480);
2915 register_displaystate(ds);
2918 /***********************************************************/
2921 typedef struct IOHandlerRecord {
2923 IOCanRWHandler *fd_read_poll;
2925 IOHandler *fd_write;
2928 /* temporary data */
2930 struct IOHandlerRecord *next;
2933 static IOHandlerRecord *first_io_handler;
2935 /* XXX: fd_read_poll should be suppressed, but an API change is
2936 necessary in the character devices to suppress fd_can_read(). */
2937 int qemu_set_fd_handler2(int fd,
2938 IOCanRWHandler *fd_read_poll,
2940 IOHandler *fd_write,
2943 IOHandlerRecord **pioh, *ioh;
2945 if (!fd_read && !fd_write) {
2946 pioh = &first_io_handler;
2951 if (ioh->fd == fd) {
2958 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2962 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2963 ioh->next = first_io_handler;
2964 first_io_handler = ioh;
2967 ioh->fd_read_poll = fd_read_poll;
2968 ioh->fd_read = fd_read;
2969 ioh->fd_write = fd_write;
2970 ioh->opaque = opaque;
2976 int qemu_set_fd_handler(int fd,
2978 IOHandler *fd_write,
2981 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2985 /***********************************************************/
2986 /* Polling handling */
2988 typedef struct PollingEntry {
2991 struct PollingEntry *next;
2994 static PollingEntry *first_polling_entry;
2996 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2998 PollingEntry **ppe, *pe;
2999 pe = qemu_mallocz(sizeof(PollingEntry));
3001 pe->opaque = opaque;
3002 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3007 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3009 PollingEntry **ppe, *pe;
3010 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3012 if (pe->func == func && pe->opaque == opaque) {
3020 /***********************************************************/
3021 /* Wait objects support */
3022 typedef struct WaitObjects {
3024 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3025 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3026 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3029 static WaitObjects wait_objects = {0};
3031 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3033 WaitObjects *w = &wait_objects;
3035 if (w->num >= MAXIMUM_WAIT_OBJECTS)
3037 w->events[w->num] = handle;
3038 w->func[w->num] = func;
3039 w->opaque[w->num] = opaque;
3044 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3047 WaitObjects *w = &wait_objects;
3050 for (i = 0; i < w->num; i++) {
3051 if (w->events[i] == handle)
3054 w->events[i] = w->events[i + 1];
3055 w->func[i] = w->func[i + 1];
3056 w->opaque[i] = w->opaque[i + 1];
3064 /***********************************************************/
3065 /* ram save/restore */
3067 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3071 v = qemu_get_byte(f);
3074 if (qemu_get_buffer(f, buf, len) != len)
3078 v = qemu_get_byte(f);
3079 memset(buf, v, len);
3085 if (qemu_file_has_error(f))
3091 static int ram_load_v1(QEMUFile *f, void *opaque)
3096 if (qemu_get_be32(f) != phys_ram_size)
3098 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3099 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3106 #define BDRV_HASH_BLOCK_SIZE 1024
3107 #define IOBUF_SIZE 4096
3108 #define RAM_CBLOCK_MAGIC 0xfabe
3110 typedef struct RamDecompressState {
3113 uint8_t buf[IOBUF_SIZE];
3114 } RamDecompressState;
3116 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3119 memset(s, 0, sizeof(*s));
3121 ret = inflateInit(&s->zstream);
3127 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3131 s->zstream.avail_out = len;
3132 s->zstream.next_out = buf;
3133 while (s->zstream.avail_out > 0) {
3134 if (s->zstream.avail_in == 0) {
3135 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3137 clen = qemu_get_be16(s->f);
3138 if (clen > IOBUF_SIZE)
3140 qemu_get_buffer(s->f, s->buf, clen);
3141 s->zstream.avail_in = clen;
3142 s->zstream.next_in = s->buf;
3144 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3145 if (ret != Z_OK && ret != Z_STREAM_END) {
3152 static void ram_decompress_close(RamDecompressState *s)
3154 inflateEnd(&s->zstream);
3157 #define RAM_SAVE_FLAG_FULL 0x01
3158 #define RAM_SAVE_FLAG_COMPRESS 0x02
3159 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
3160 #define RAM_SAVE_FLAG_PAGE 0x08
3161 #define RAM_SAVE_FLAG_EOS 0x10
3163 static int is_dup_page(uint8_t *page, uint8_t ch)
3165 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3166 uint32_t *array = (uint32_t *)page;
3169 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3170 if (array[i] != val)
3177 static int ram_save_block(QEMUFile *f)
3179 static ram_addr_t current_addr = 0;
3180 ram_addr_t saved_addr = current_addr;
3181 ram_addr_t addr = 0;
3184 while (addr < phys_ram_size) {
3185 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3188 cpu_physical_memory_reset_dirty(current_addr,
3189 current_addr + TARGET_PAGE_SIZE,
3190 MIGRATION_DIRTY_FLAG);
3192 ch = *(phys_ram_base + current_addr);
3194 if (is_dup_page(phys_ram_base + current_addr, ch)) {
3195 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3196 qemu_put_byte(f, ch);
3198 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3199 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3205 addr += TARGET_PAGE_SIZE;
3206 current_addr = (saved_addr + addr) % phys_ram_size;
3212 static ram_addr_t ram_save_threshold = 10;
3214 static ram_addr_t ram_save_remaining(void)
3217 ram_addr_t count = 0;
3219 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3220 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3227 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3232 /* Make sure all dirty bits are set */
3233 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3234 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3235 cpu_physical_memory_set_dirty(addr);
3238 /* Enable dirty memory tracking */
3239 cpu_physical_memory_set_dirty_tracking(1);
3241 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3244 while (!qemu_file_rate_limit(f)) {
3247 ret = ram_save_block(f);
3248 if (ret == 0) /* no more blocks */
3252 /* try transferring iterative blocks of memory */
3256 /* flush all remaining blocks regardless of rate limiting */
3257 while (ram_save_block(f) != 0);
3258 cpu_physical_memory_set_dirty_tracking(0);
3261 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3263 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3266 static int ram_load_dead(QEMUFile *f, void *opaque)
3268 RamDecompressState s1, *s = &s1;
3272 if (ram_decompress_open(s, f) < 0)
3274 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3275 if (ram_decompress_buf(s, buf, 1) < 0) {
3276 fprintf(stderr, "Error while reading ram block header\n");
3280 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3281 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3286 printf("Error block header\n");
3290 ram_decompress_close(s);
3295 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3300 if (version_id == 1)
3301 return ram_load_v1(f, opaque);
3303 if (version_id == 2) {
3304 if (qemu_get_be32(f) != phys_ram_size)
3306 return ram_load_dead(f, opaque);
3309 if (version_id != 3)
3313 addr = qemu_get_be64(f);
3315 flags = addr & ~TARGET_PAGE_MASK;
3316 addr &= TARGET_PAGE_MASK;
3318 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3319 if (addr != phys_ram_size)
3323 if (flags & RAM_SAVE_FLAG_FULL) {
3324 if (ram_load_dead(f, opaque) < 0)
3328 if (flags & RAM_SAVE_FLAG_COMPRESS) {
3329 uint8_t ch = qemu_get_byte(f);
3330 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3331 } else if (flags & RAM_SAVE_FLAG_PAGE)
3332 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3333 } while (!(flags & RAM_SAVE_FLAG_EOS));
3338 void qemu_service_io(void)
3340 CPUState *env = cpu_single_env;
3344 if (env->kqemu_enabled) {
3345 kqemu_cpu_interrupt(env);
3351 /***********************************************************/
3352 /* bottom halves (can be seen as timers which expire ASAP) */
3363 static QEMUBH *first_bh = NULL;
3365 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3368 bh = qemu_mallocz(sizeof(QEMUBH));
3370 bh->opaque = opaque;
3371 bh->next = first_bh;
3376 int qemu_bh_poll(void)
3382 for (bh = first_bh; bh; bh = bh->next) {
3383 if (!bh->deleted && bh->scheduled) {
3392 /* remove deleted bhs */
3406 void qemu_bh_schedule_idle(QEMUBH *bh)
3414 void qemu_bh_schedule(QEMUBH *bh)
3416 CPUState *env = cpu_single_env;
3421 /* stop the currently executing CPU to execute the BH ASAP */
3427 void qemu_bh_cancel(QEMUBH *bh)
3432 void qemu_bh_delete(QEMUBH *bh)
3438 static void qemu_bh_update_timeout(int *timeout)
3442 for (bh = first_bh; bh; bh = bh->next) {
3443 if (!bh->deleted && bh->scheduled) {
3445 /* idle bottom halves will be polled at least
3447 *timeout = MIN(10, *timeout);
3449 /* non-idle bottom halves will be executed
3458 /***********************************************************/
3459 /* machine registration */
3461 static QEMUMachine *first_machine = NULL;
3462 QEMUMachine *current_machine = NULL;
3464 int qemu_register_machine(QEMUMachine *m)
3467 pm = &first_machine;
3475 static QEMUMachine *find_machine(const char *name)
3479 for(m = first_machine; m != NULL; m = m->next) {
3480 if (!strcmp(m->name, name))
3486 /***********************************************************/
3487 /* main execution loop */
3489 static void gui_update(void *opaque)
3491 uint64_t interval = GUI_REFRESH_INTERVAL;
3492 DisplayState *ds = opaque;
3493 DisplayChangeListener *dcl = ds->listeners;
3497 while (dcl != NULL) {
3498 if (dcl->gui_timer_interval &&
3499 dcl->gui_timer_interval < interval)
3500 interval = dcl->gui_timer_interval;
3503 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3506 static void nographic_update(void *opaque)
3508 uint64_t interval = GUI_REFRESH_INTERVAL;
3510 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3513 struct vm_change_state_entry {
3514 VMChangeStateHandler *cb;
3516 LIST_ENTRY (vm_change_state_entry) entries;
3519 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3521 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3524 VMChangeStateEntry *e;
3526 e = qemu_mallocz(sizeof (*e));
3530 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3534 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3536 LIST_REMOVE (e, entries);
3540 static void vm_state_notify(int running, int reason)
3542 VMChangeStateEntry *e;
3544 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3545 e->cb(e->opaque, running, reason);
3554 vm_state_notify(1, 0);
3555 qemu_rearm_alarm_timer(alarm_timer);
3559 void vm_stop(int reason)
3562 cpu_disable_ticks();
3564 vm_state_notify(0, reason);
3568 /* reset/shutdown handler */
3570 typedef struct QEMUResetEntry {
3571 QEMUResetHandler *func;
3573 struct QEMUResetEntry *next;
3576 static QEMUResetEntry *first_reset_entry;
3577 static int reset_requested;
3578 static int shutdown_requested;
3579 static int powerdown_requested;
3581 int qemu_shutdown_requested(void)
3583 int r = shutdown_requested;
3584 shutdown_requested = 0;
3588 int qemu_reset_requested(void)
3590 int r = reset_requested;
3591 reset_requested = 0;
3595 int qemu_powerdown_requested(void)
3597 int r = powerdown_requested;
3598 powerdown_requested = 0;
3602 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3604 QEMUResetEntry **pre, *re;
3606 pre = &first_reset_entry;
3607 while (*pre != NULL)
3608 pre = &(*pre)->next;
3609 re = qemu_mallocz(sizeof(QEMUResetEntry));
3611 re->opaque = opaque;
3616 void qemu_system_reset(void)
3620 /* reset all devices */
3621 for(re = first_reset_entry; re != NULL; re = re->next) {
3622 re->func(re->opaque);
3626 void qemu_system_reset_request(void)
3629 shutdown_requested = 1;
3631 reset_requested = 1;
3634 cpu_exit(cpu_single_env);
3637 void qemu_system_shutdown_request(void)
3639 shutdown_requested = 1;
3641 cpu_exit(cpu_single_env);
3644 void qemu_system_powerdown_request(void)
3646 powerdown_requested = 1;
3648 cpu_exit(cpu_single_env);
3652 static void host_main_loop_wait(int *timeout)
3658 /* XXX: need to suppress polling by better using win32 events */
3660 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3661 ret |= pe->func(pe->opaque);
3665 WaitObjects *w = &wait_objects;
3667 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3668 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3669 if (w->func[ret - WAIT_OBJECT_0])
3670 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3672 /* Check for additional signaled events */
3673 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3675 /* Check if event is signaled */
3676 ret2 = WaitForSingleObject(w->events[i], 0);
3677 if(ret2 == WAIT_OBJECT_0) {
3679 w->func[i](w->opaque[i]);
3680 } else if (ret2 == WAIT_TIMEOUT) {
3682 err = GetLastError();
3683 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3686 } else if (ret == WAIT_TIMEOUT) {
3688 err = GetLastError();
3689 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3696 static void host_main_loop_wait(int *timeout)
3701 void main_loop_wait(int timeout)
3703 IOHandlerRecord *ioh;
3704 fd_set rfds, wfds, xfds;
3708 qemu_bh_update_timeout(&timeout);
3710 host_main_loop_wait(&timeout);
3712 /* poll any events */
3713 /* XXX: separate device handlers from system ones */
3718 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3722 (!ioh->fd_read_poll ||
3723 ioh->fd_read_poll(ioh->opaque) != 0)) {
3724 FD_SET(ioh->fd, &rfds);
3728 if (ioh->fd_write) {
3729 FD_SET(ioh->fd, &wfds);
3735 tv.tv_sec = timeout / 1000;
3736 tv.tv_usec = (timeout % 1000) * 1000;
3738 #if defined(CONFIG_SLIRP)
3739 if (slirp_is_inited()) {
3740 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3743 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3745 IOHandlerRecord **pioh;
3747 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3748 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3749 ioh->fd_read(ioh->opaque);
3751 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3752 ioh->fd_write(ioh->opaque);
3756 /* remove deleted IO handlers */
3757 pioh = &first_io_handler;
3767 #if defined(CONFIG_SLIRP)
3768 if (slirp_is_inited()) {
3774 slirp_select_poll(&rfds, &wfds, &xfds);
3778 /* vm time timers */
3779 if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3780 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3781 qemu_get_clock(vm_clock));
3783 /* real time timers */
3784 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3785 qemu_get_clock(rt_clock));
3787 /* Check bottom-halves last in case any of the earlier events triggered
3793 static int main_loop(void)
3796 #ifdef CONFIG_PROFILER
3801 cur_cpu = first_cpu;
3802 next_cpu = cur_cpu->next_cpu ?: first_cpu;
3809 #ifdef CONFIG_PROFILER
3810 ti = profile_getclock();
3815 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3816 env->icount_decr.u16.low = 0;
3817 env->icount_extra = 0;
3818 count = qemu_next_deadline();
3819 count = (count + (1 << icount_time_shift) - 1)
3820 >> icount_time_shift;
3821 qemu_icount += count;
3822 decr = (count > 0xffff) ? 0xffff : count;
3824 env->icount_decr.u16.low = decr;
3825 env->icount_extra = count;
3827 ret = cpu_exec(env);
3828 #ifdef CONFIG_PROFILER
3829 qemu_time += profile_getclock() - ti;
3832 /* Fold pending instructions back into the
3833 instruction counter, and clear the interrupt flag. */
3834 qemu_icount -= (env->icount_decr.u16.low
3835 + env->icount_extra);
3836 env->icount_decr.u32 = 0;
3837 env->icount_extra = 0;
3839 next_cpu = env->next_cpu ?: first_cpu;
3840 if (event_pending && likely(ret != EXCP_DEBUG)) {
3841 ret = EXCP_INTERRUPT;
3845 if (ret == EXCP_HLT) {
3846 /* Give the next CPU a chance to run. */
3850 if (ret != EXCP_HALTED)
3852 /* all CPUs are halted ? */
3858 if (shutdown_requested) {
3859 ret = EXCP_INTERRUPT;
3867 if (reset_requested) {
3868 reset_requested = 0;
3869 qemu_system_reset();
3870 ret = EXCP_INTERRUPT;
3872 if (powerdown_requested) {
3873 powerdown_requested = 0;
3874 qemu_system_powerdown();
3875 ret = EXCP_INTERRUPT;
3877 if (unlikely(ret == EXCP_DEBUG)) {
3878 gdb_set_stop_cpu(cur_cpu);
3879 vm_stop(EXCP_DEBUG);
3881 /* If all cpus are halted then wait until the next IRQ */
3882 /* XXX: use timeout computed from timers */
3883 if (ret == EXCP_HALTED) {
3887 /* Advance virtual time to the next event. */
3888 if (use_icount == 1) {
3889 /* When not using an adaptive execution frequency
3890 we tend to get badly out of sync with real time,
3891 so just delay for a reasonable amount of time. */
3894 delta = cpu_get_icount() - cpu_get_clock();
3897 /* If virtual time is ahead of real time then just
3899 timeout = (delta / 1000000) + 1;
3901 /* Wait for either IO to occur or the next
3903 add = qemu_next_deadline();
3904 /* We advance the timer before checking for IO.
3905 Limit the amount we advance so that early IO
3906 activity won't get the guest too far ahead. */
3910 add = (add + (1 << icount_time_shift) - 1)
3911 >> icount_time_shift;
3913 timeout = delta / 1000000;
3924 if (shutdown_requested) {
3925 ret = EXCP_INTERRUPT;
3930 #ifdef CONFIG_PROFILER
3931 ti = profile_getclock();
3933 main_loop_wait(timeout);
3934 #ifdef CONFIG_PROFILER
3935 dev_time += profile_getclock() - ti;
3938 cpu_disable_ticks();
3942 static void help(int exitcode)
3944 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3945 "usage: %s [options] [disk_image]\n"
3947 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3949 #define DEF(option, opt_arg, opt_enum, opt_help) \
3951 #define DEFHEADING(text) stringify(text) "\n"
3952 #include "qemu-options.h"
3957 "During emulation, the following keys are useful:\n"
3958 "ctrl-alt-f toggle full screen\n"
3959 "ctrl-alt-n switch to virtual console 'n'\n"
3960 "ctrl-alt toggle mouse and keyboard grab\n"
3962 "When using -nographic, press 'ctrl-a h' to get some help.\n"
3967 DEFAULT_NETWORK_SCRIPT,
3968 DEFAULT_NETWORK_DOWN_SCRIPT,
3970 DEFAULT_GDBSTUB_PORT,
3975 #define HAS_ARG 0x0001
3978 #define DEF(option, opt_arg, opt_enum, opt_help) \
3980 #define DEFHEADING(text)
3981 #include "qemu-options.h"
3987 typedef struct QEMUOption {
3993 static const QEMUOption qemu_options[] = {
3994 { "h", 0, QEMU_OPTION_h },
3995 #define DEF(option, opt_arg, opt_enum, opt_help) \
3996 { option, opt_arg, opt_enum },
3997 #define DEFHEADING(text)
3998 #include "qemu-options.h"
4006 struct soundhw soundhw[] = {
4007 #ifdef HAS_AUDIO_CHOICE
4008 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4014 { .init_isa = pcspk_audio_init }
4021 "Creative Sound Blaster 16",
4024 { .init_isa = SB16_init }
4028 #ifdef CONFIG_CS4231A
4034 { .init_isa = cs4231a_init }
4042 "Yamaha YMF262 (OPL3)",
4044 "Yamaha YM3812 (OPL2)",
4048 { .init_isa = Adlib_init }
4055 "Gravis Ultrasound GF1",
4058 { .init_isa = GUS_init }
4065 "Intel 82801AA AC97 Audio",
4068 { .init_pci = ac97_init }
4072 #ifdef CONFIG_ES1370
4075 "ENSONIQ AudioPCI ES1370",
4078 { .init_pci = es1370_init }
4082 #endif /* HAS_AUDIO_CHOICE */
4084 { NULL, NULL, 0, 0, { NULL } }
4087 static void select_soundhw (const char *optarg)
4091 if (*optarg == '?') {
4094 printf ("Valid sound card names (comma separated):\n");
4095 for (c = soundhw; c->name; ++c) {
4096 printf ("%-11s %s\n", c->name, c->descr);
4098 printf ("\n-soundhw all will enable all of the above\n");
4099 exit (*optarg != '?');
4107 if (!strcmp (optarg, "all")) {
4108 for (c = soundhw; c->name; ++c) {
4116 e = strchr (p, ',');
4117 l = !e ? strlen (p) : (size_t) (e - p);
4119 for (c = soundhw; c->name; ++c) {
4120 if (!strncmp (c->name, p, l)) {
4129 "Unknown sound card name (too big to show)\n");
4132 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4137 p += l + (e != NULL);
4141 goto show_valid_cards;
4146 static void select_vgahw (const char *p)
4150 if (strstart(p, "std", &opts)) {
4151 std_vga_enabled = 1;
4152 cirrus_vga_enabled = 0;
4154 } else if (strstart(p, "cirrus", &opts)) {
4155 cirrus_vga_enabled = 1;
4156 std_vga_enabled = 0;
4158 } else if (strstart(p, "vmware", &opts)) {
4159 cirrus_vga_enabled = 0;
4160 std_vga_enabled = 0;
4162 } else if (strstart(p, "none", &opts)) {
4163 cirrus_vga_enabled = 0;
4164 std_vga_enabled = 0;
4168 fprintf(stderr, "Unknown vga type: %s\n", p);
4172 const char *nextopt;
4174 if (strstart(opts, ",retrace=", &nextopt)) {
4176 if (strstart(opts, "dumb", &nextopt))
4177 vga_retrace_method = VGA_RETRACE_DUMB;
4178 else if (strstart(opts, "precise", &nextopt))
4179 vga_retrace_method = VGA_RETRACE_PRECISE;
4180 else goto invalid_vga;
4181 } else goto invalid_vga;
4187 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4189 exit(STATUS_CONTROL_C_EXIT);
4194 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4198 if(strlen(str) != 36)
4201 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4202 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4203 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4211 #define MAX_NET_CLIENTS 32
4215 static void termsig_handler(int signal)
4217 qemu_system_shutdown_request();
4220 static void termsig_setup(void)
4222 struct sigaction act;
4224 memset(&act, 0, sizeof(act));
4225 act.sa_handler = termsig_handler;
4226 sigaction(SIGINT, &act, NULL);
4227 sigaction(SIGHUP, &act, NULL);
4228 sigaction(SIGTERM, &act, NULL);
4233 int main(int argc, char **argv, char **envp)
4235 #ifdef CONFIG_GDBSTUB
4236 const char *gdbstub_dev = NULL;
4238 uint32_t boot_devices_bitmap = 0;
4240 int snapshot, linux_boot, net_boot;
4241 const char *initrd_filename;
4242 const char *kernel_filename, *kernel_cmdline;
4243 const char *boot_devices = "";
4245 DisplayChangeListener *dcl;
4246 int cyls, heads, secs, translation;
4247 const char *net_clients[MAX_NET_CLIENTS];
4249 const char *bt_opts[MAX_BT_CMDLINE];
4253 const char *r, *optarg;
4254 CharDriverState *monitor_hd = NULL;
4255 const char *monitor_device;
4256 const char *serial_devices[MAX_SERIAL_PORTS];
4257 int serial_device_index;
4258 const char *parallel_devices[MAX_PARALLEL_PORTS];
4259 int parallel_device_index;
4260 const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4261 int virtio_console_index;
4262 const char *loadvm = NULL;
4263 QEMUMachine *machine;
4264 const char *cpu_model;
4265 const char *usb_devices[MAX_USB_CMDLINE];
4266 int usb_devices_index;
4271 const char *pid_file = NULL;
4272 const char *incoming = NULL;
4275 struct passwd *pwd = NULL;
4276 const char *chroot_dir = NULL;
4277 const char *run_as = NULL;
4280 qemu_cache_utils_init(envp);
4282 LIST_INIT (&vm_change_state_head);
4285 struct sigaction act;
4286 sigfillset(&act.sa_mask);
4288 act.sa_handler = SIG_IGN;
4289 sigaction(SIGPIPE, &act, NULL);
4292 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4293 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4294 QEMU to run on a single CPU */
4299 h = GetCurrentProcess();
4300 if (GetProcessAffinityMask(h, &mask, &smask)) {
4301 for(i = 0; i < 32; i++) {
4302 if (mask & (1 << i))
4307 SetProcessAffinityMask(h, mask);
4313 register_machines();
4314 machine = first_machine;
4316 initrd_filename = NULL;
4318 vga_ram_size = VGA_RAM_SIZE;
4322 kernel_filename = NULL;
4323 kernel_cmdline = "";
4324 cyls = heads = secs = 0;
4325 translation = BIOS_ATA_TRANSLATION_AUTO;
4326 monitor_device = "vc:80Cx24C";
4328 serial_devices[0] = "vc:80Cx24C";
4329 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4330 serial_devices[i] = NULL;
4331 serial_device_index = 0;
4333 parallel_devices[0] = "vc:80Cx24C";
4334 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4335 parallel_devices[i] = NULL;
4336 parallel_device_index = 0;
4338 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4339 virtio_consoles[i] = NULL;
4340 virtio_console_index = 0;
4342 usb_devices_index = 0;
4361 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4363 const QEMUOption *popt;
4366 /* Treat --foo the same as -foo. */
4369 popt = qemu_options;
4372 fprintf(stderr, "%s: invalid option -- '%s'\n",
4376 if (!strcmp(popt->name, r + 1))
4380 if (popt->flags & HAS_ARG) {
4381 if (optind >= argc) {
4382 fprintf(stderr, "%s: option '%s' requires an argument\n",
4386 optarg = argv[optind++];
4391 switch(popt->index) {
4393 machine = find_machine(optarg);
4396 printf("Supported machines are:\n");
4397 for(m = first_machine; m != NULL; m = m->next) {
4398 printf("%-10s %s%s\n",
4400 m == first_machine ? " (default)" : "");
4402 exit(*optarg != '?');
4405 case QEMU_OPTION_cpu:
4406 /* hw initialization will check this */
4407 if (*optarg == '?') {
4408 /* XXX: implement xxx_cpu_list for targets that still miss it */
4409 #if defined(cpu_list)
4410 cpu_list(stdout, &fprintf);
4417 case QEMU_OPTION_initrd:
4418 initrd_filename = optarg;
4420 case QEMU_OPTION_hda:
4422 hda_index = drive_add(optarg, HD_ALIAS, 0);
4424 hda_index = drive_add(optarg, HD_ALIAS
4425 ",cyls=%d,heads=%d,secs=%d%s",
4426 0, cyls, heads, secs,
4427 translation == BIOS_ATA_TRANSLATION_LBA ?
4429 translation == BIOS_ATA_TRANSLATION_NONE ?
4430 ",trans=none" : "");
4432 case QEMU_OPTION_hdb:
4433 case QEMU_OPTION_hdc:
4434 case QEMU_OPTION_hdd:
4435 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4437 case QEMU_OPTION_drive:
4438 drive_add(NULL, "%s", optarg);
4440 case QEMU_OPTION_mtdblock:
4441 drive_add(optarg, MTD_ALIAS);
4443 case QEMU_OPTION_sd:
4444 drive_add(optarg, SD_ALIAS);
4446 case QEMU_OPTION_pflash:
4447 drive_add(optarg, PFLASH_ALIAS);
4449 case QEMU_OPTION_snapshot:
4452 case QEMU_OPTION_hdachs:
4456 cyls = strtol(p, (char **)&p, 0);
4457 if (cyls < 1 || cyls > 16383)
4462 heads = strtol(p, (char **)&p, 0);
4463 if (heads < 1 || heads > 16)
4468 secs = strtol(p, (char **)&p, 0);
4469 if (secs < 1 || secs > 63)
4473 if (!strcmp(p, "none"))
4474 translation = BIOS_ATA_TRANSLATION_NONE;
4475 else if (!strcmp(p, "lba"))
4476 translation = BIOS_ATA_TRANSLATION_LBA;
4477 else if (!strcmp(p, "auto"))
4478 translation = BIOS_ATA_TRANSLATION_AUTO;
4481 } else if (*p != '\0') {
4483 fprintf(stderr, "qemu: invalid physical CHS format\n");
4486 if (hda_index != -1)
4487 snprintf(drives_opt[hda_index].opt,
4488 sizeof(drives_opt[hda_index].opt),
4489 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4490 0, cyls, heads, secs,
4491 translation == BIOS_ATA_TRANSLATION_LBA ?
4493 translation == BIOS_ATA_TRANSLATION_NONE ?
4494 ",trans=none" : "");
4497 case QEMU_OPTION_nographic:
4500 #ifdef CONFIG_CURSES
4501 case QEMU_OPTION_curses:
4505 case QEMU_OPTION_portrait:
4508 case QEMU_OPTION_kernel:
4509 kernel_filename = optarg;
4511 case QEMU_OPTION_append:
4512 kernel_cmdline = optarg;
4514 case QEMU_OPTION_cdrom:
4515 drive_add(optarg, CDROM_ALIAS);
4517 case QEMU_OPTION_boot:
4518 boot_devices = optarg;
4519 /* We just do some generic consistency checks */
4521 /* Could easily be extended to 64 devices if needed */
4524 boot_devices_bitmap = 0;
4525 for (p = boot_devices; *p != '\0'; p++) {
4526 /* Allowed boot devices are:
4527 * a b : floppy disk drives
4528 * c ... f : IDE disk drives
4529 * g ... m : machine implementation dependant drives
4530 * n ... p : network devices
4531 * It's up to each machine implementation to check
4532 * if the given boot devices match the actual hardware
4533 * implementation and firmware features.
4535 if (*p < 'a' || *p > 'q') {
4536 fprintf(stderr, "Invalid boot device '%c'\n", *p);
4539 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4541 "Boot device '%c' was given twice\n",*p);
4544 boot_devices_bitmap |= 1 << (*p - 'a');
4548 case QEMU_OPTION_fda:
4549 case QEMU_OPTION_fdb:
4550 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4553 case QEMU_OPTION_no_fd_bootchk:
4557 case QEMU_OPTION_net:
4558 if (nb_net_clients >= MAX_NET_CLIENTS) {
4559 fprintf(stderr, "qemu: too many network clients\n");
4562 net_clients[nb_net_clients] = optarg;
4566 case QEMU_OPTION_tftp:
4567 tftp_prefix = optarg;
4569 case QEMU_OPTION_bootp:
4570 bootp_filename = optarg;
4573 case QEMU_OPTION_smb:
4574 net_slirp_smb(optarg);
4577 case QEMU_OPTION_redir:
4578 net_slirp_redir(optarg);
4581 case QEMU_OPTION_bt:
4582 if (nb_bt_opts >= MAX_BT_CMDLINE) {
4583 fprintf(stderr, "qemu: too many bluetooth options\n");
4586 bt_opts[nb_bt_opts++] = optarg;
4589 case QEMU_OPTION_audio_help:
4593 case QEMU_OPTION_soundhw:
4594 select_soundhw (optarg);
4600 case QEMU_OPTION_m: {
4604 value = strtoul(optarg, &ptr, 10);
4606 case 0: case 'M': case 'm':
4613 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4617 /* On 32-bit hosts, QEMU is limited by virtual address space */
4618 if (value > (2047 << 20)
4620 && HOST_LONG_BITS == 32
4623 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4626 if (value != (uint64_t)(ram_addr_t)value) {
4627 fprintf(stderr, "qemu: ram size too large\n");
4636 const CPULogItem *item;
4638 mask = cpu_str_to_log_mask(optarg);
4640 printf("Log items (comma separated):\n");
4641 for(item = cpu_log_items; item->mask != 0; item++) {
4642 printf("%-10s %s\n", item->name, item->help);
4649 #ifdef CONFIG_GDBSTUB
4651 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4653 case QEMU_OPTION_gdb:
4654 gdbstub_dev = optarg;
4660 case QEMU_OPTION_bios:
4668 keyboard_layout = optarg;
4671 case QEMU_OPTION_localtime:
4674 case QEMU_OPTION_vga:
4675 select_vgahw (optarg);
4677 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4683 w = strtol(p, (char **)&p, 10);
4686 fprintf(stderr, "qemu: invalid resolution or depth\n");
4692 h = strtol(p, (char **)&p, 10);
4697 depth = strtol(p, (char **)&p, 10);
4698 if (depth != 8 && depth != 15 && depth != 16 &&
4699 depth != 24 && depth != 32)
4701 } else if (*p == '\0') {
4702 depth = graphic_depth;
4709 graphic_depth = depth;
4713 case QEMU_OPTION_echr:
4716 term_escape_char = strtol(optarg, &r, 0);
4718 printf("Bad argument to echr\n");
4721 case QEMU_OPTION_monitor:
4722 monitor_device = optarg;
4724 case QEMU_OPTION_serial:
4725 if (serial_device_index >= MAX_SERIAL_PORTS) {
4726 fprintf(stderr, "qemu: too many serial ports\n");
4729 serial_devices[serial_device_index] = optarg;
4730 serial_device_index++;
4732 case QEMU_OPTION_virtiocon:
4733 if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4734 fprintf(stderr, "qemu: too many virtio consoles\n");
4737 virtio_consoles[virtio_console_index] = optarg;
4738 virtio_console_index++;
4740 case QEMU_OPTION_parallel:
4741 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4742 fprintf(stderr, "qemu: too many parallel ports\n");
4745 parallel_devices[parallel_device_index] = optarg;
4746 parallel_device_index++;
4748 case QEMU_OPTION_loadvm:
4751 case QEMU_OPTION_full_screen:
4755 case QEMU_OPTION_no_frame:
4758 case QEMU_OPTION_alt_grab:
4761 case QEMU_OPTION_no_quit:
4764 case QEMU_OPTION_sdl:
4768 case QEMU_OPTION_pidfile:
4772 case QEMU_OPTION_win2k_hack:
4773 win2k_install_hack = 1;
4775 case QEMU_OPTION_rtc_td_hack:
4778 case QEMU_OPTION_acpitable:
4779 if(acpi_table_add(optarg) < 0) {
4780 fprintf(stderr, "Wrong acpi table provided\n");
4786 case QEMU_OPTION_no_kqemu:
4789 case QEMU_OPTION_kernel_kqemu:
4794 case QEMU_OPTION_enable_kvm:
4801 case QEMU_OPTION_usb:
4804 case QEMU_OPTION_usbdevice:
4806 if (usb_devices_index >= MAX_USB_CMDLINE) {
4807 fprintf(stderr, "Too many USB devices\n");
4810 usb_devices[usb_devices_index] = optarg;
4811 usb_devices_index++;
4813 case QEMU_OPTION_smp:
4814 smp_cpus = atoi(optarg);
4816 fprintf(stderr, "Invalid number of CPUs\n");
4820 case QEMU_OPTION_vnc:
4821 vnc_display = optarg;
4824 case QEMU_OPTION_no_acpi:
4827 case QEMU_OPTION_no_hpet:
4831 case QEMU_OPTION_no_reboot:
4834 case QEMU_OPTION_no_shutdown:
4837 case QEMU_OPTION_show_cursor:
4840 case QEMU_OPTION_uuid:
4841 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4842 fprintf(stderr, "Fail to parse UUID string."
4843 " Wrong format.\n");
4848 case QEMU_OPTION_daemonize:
4852 case QEMU_OPTION_option_rom:
4853 if (nb_option_roms >= MAX_OPTION_ROMS) {
4854 fprintf(stderr, "Too many option ROMs\n");
4857 option_rom[nb_option_roms] = optarg;
4860 #if defined(TARGET_ARM) || defined(TARGET_M68K)
4861 case QEMU_OPTION_semihosting:
4862 semihosting_enabled = 1;
4865 case QEMU_OPTION_name:
4868 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
4869 case QEMU_OPTION_prom_env:
4870 if (nb_prom_envs >= MAX_PROM_ENVS) {
4871 fprintf(stderr, "Too many prom variables\n");
4874 prom_envs[nb_prom_envs] = optarg;
4879 case QEMU_OPTION_old_param:
4883 case QEMU_OPTION_clock:
4884 configure_alarms(optarg);
4886 case QEMU_OPTION_startdate:
4889 time_t rtc_start_date;
4890 if (!strcmp(optarg, "now")) {
4891 rtc_date_offset = -1;
4893 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
4901 } else if (sscanf(optarg, "%d-%d-%d",
4904 &tm.tm_mday) == 3) {
4913 rtc_start_date = mktimegm(&tm);
4914 if (rtc_start_date == -1) {
4916 fprintf(stderr, "Invalid date format. Valid format are:\n"
4917 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
4920 rtc_date_offset = time(NULL) - rtc_start_date;
4924 case QEMU_OPTION_tb_size:
4925 tb_size = strtol(optarg, NULL, 0);
4929 case QEMU_OPTION_icount:
4931 if (strcmp(optarg, "auto") == 0) {
4932 icount_time_shift = -1;
4934 icount_time_shift = strtol(optarg, NULL, 0);
4937 case QEMU_OPTION_incoming:
4941 case QEMU_OPTION_chroot:
4942 chroot_dir = optarg;
4944 case QEMU_OPTION_runas:
4952 #if defined(CONFIG_KVM) && defined(USE_KQEMU)
4953 if (kvm_allowed && kqemu_allowed) {
4955 "You can not enable both KVM and kqemu at the same time\n");
4960 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4961 if (smp_cpus > machine->max_cpus) {
4962 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4963 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
4969 if (serial_device_index == 0)
4970 serial_devices[0] = "stdio";
4971 if (parallel_device_index == 0)
4972 parallel_devices[0] = "null";
4973 if (strncmp(monitor_device, "vc", 2) == 0)
4974 monitor_device = "stdio";
4981 if (pipe(fds) == -1)
4992 len = read(fds[0], &status, 1);
4993 if (len == -1 && (errno == EINTR))
4998 else if (status == 1) {
4999 fprintf(stderr, "Could not acquire pidfile\n");
5016 signal(SIGTSTP, SIG_IGN);
5017 signal(SIGTTOU, SIG_IGN);
5018 signal(SIGTTIN, SIG_IGN);
5021 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5024 write(fds[1], &status, 1);
5026 fprintf(stderr, "Could not acquire pid file\n");
5035 linux_boot = (kernel_filename != NULL);
5036 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5038 if (!linux_boot && *kernel_cmdline != '\0') {
5039 fprintf(stderr, "-append only allowed with -kernel option\n");
5043 if (!linux_boot && initrd_filename != NULL) {
5044 fprintf(stderr, "-initrd only allowed with -kernel option\n");
5048 /* boot to floppy or the default cd if no hard disk defined yet */
5049 if (!boot_devices[0]) {
5050 boot_devices = "cad";
5052 setvbuf(stdout, NULL, _IOLBF, 0);
5055 if (init_timer_alarm() < 0) {
5056 fprintf(stderr, "could not initialize alarm timer\n");
5059 if (use_icount && icount_time_shift < 0) {
5061 /* 125MIPS seems a reasonable initial guess at the guest speed.
5062 It will be corrected fairly quickly anyway. */
5063 icount_time_shift = 3;
5064 init_icount_adjust();
5071 /* init network clients */
5072 if (nb_net_clients == 0) {
5073 /* if no clients, we use a default config */
5074 net_clients[nb_net_clients++] = "nic";
5076 net_clients[nb_net_clients++] = "user";
5080 for(i = 0;i < nb_net_clients; i++) {
5081 if (net_client_parse(net_clients[i]) < 0)
5087 /* XXX: this should be moved in the PC machine instantiation code */
5088 if (net_boot != 0) {
5090 for (i = 0; i < nb_nics && i < 4; i++) {
5091 const char *model = nd_table[i].model;
5093 if (net_boot & (1 << i)) {
5096 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5097 if (get_image_size(buf) > 0) {
5098 if (nb_option_roms >= MAX_OPTION_ROMS) {
5099 fprintf(stderr, "Too many option ROMs\n");
5102 option_rom[nb_option_roms] = strdup(buf);
5109 fprintf(stderr, "No valid PXE rom found for network device\n");
5115 /* init the bluetooth world */
5116 for (i = 0; i < nb_bt_opts; i++)
5117 if (bt_parse(bt_opts[i]))
5120 /* init the memory */
5121 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5123 if (machine->ram_require & RAMSIZE_FIXED) {
5125 if (ram_size < phys_ram_size) {
5126 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5127 machine->name, (unsigned long long) phys_ram_size);
5131 phys_ram_size = ram_size;
5133 ram_size = phys_ram_size;
5136 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5138 phys_ram_size += ram_size;
5141 phys_ram_base = qemu_vmalloc(phys_ram_size);
5142 if (!phys_ram_base) {
5143 fprintf(stderr, "Could not allocate physical memory\n");
5147 /* init the dynamic translator */
5148 cpu_exec_init_all(tb_size * 1024 * 1024);
5153 /* we always create the cdrom drive, even if no disk is there */
5155 if (nb_drives_opt < MAX_DRIVES)
5156 drive_add(NULL, CDROM_ALIAS);
5158 /* we always create at least one floppy */
5160 if (nb_drives_opt < MAX_DRIVES)
5161 drive_add(NULL, FD_ALIAS, 0);
5163 /* we always create one sd slot, even if no card is in it */
5165 if (nb_drives_opt < MAX_DRIVES)
5166 drive_add(NULL, SD_ALIAS);
5168 /* open the virtual block devices */
5170 for(i = 0; i < nb_drives_opt; i++)
5171 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5174 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5175 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5178 /* must be after terminal init, SDL library changes signal handlers */
5182 /* Maintain compatibility with multiple stdio monitors */
5183 if (!strcmp(monitor_device,"stdio")) {
5184 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5185 const char *devname = serial_devices[i];
5186 if (devname && !strcmp(devname,"mon:stdio")) {
5187 monitor_device = NULL;
5189 } else if (devname && !strcmp(devname,"stdio")) {
5190 monitor_device = NULL;
5191 serial_devices[i] = "mon:stdio";
5197 if (kvm_enabled()) {
5200 ret = kvm_init(smp_cpus);
5202 fprintf(stderr, "failed to initialize KVM\n");
5207 if (monitor_device) {
5208 monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5210 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5215 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5216 const char *devname = serial_devices[i];
5217 if (devname && strcmp(devname, "none")) {
5219 snprintf(label, sizeof(label), "serial%d", i);
5220 serial_hds[i] = qemu_chr_open(label, devname, NULL);
5221 if (!serial_hds[i]) {
5222 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5229 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5230 const char *devname = parallel_devices[i];
5231 if (devname && strcmp(devname, "none")) {
5233 snprintf(label, sizeof(label), "parallel%d", i);
5234 parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5235 if (!parallel_hds[i]) {
5236 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5243 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5244 const char *devname = virtio_consoles[i];
5245 if (devname && strcmp(devname, "none")) {
5247 snprintf(label, sizeof(label), "virtcon%d", i);
5248 virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5249 if (!virtcon_hds[i]) {
5250 fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5257 machine->init(ram_size, vga_ram_size, boot_devices,
5258 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5260 current_machine = machine;
5262 /* Set KVM's vcpu state to qemu's initial CPUState. */
5263 if (kvm_enabled()) {
5266 ret = kvm_sync_vcpus();
5268 fprintf(stderr, "failed to initialize vcpus\n");
5273 /* init USB devices */
5275 for(i = 0; i < usb_devices_index; i++) {
5276 if (usb_device_add(usb_devices[i], 0) < 0) {
5277 fprintf(stderr, "Warning: could not add USB device %s\n",
5284 dumb_display_init();
5285 /* just use the first displaystate for the moment */
5290 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5294 #if defined(CONFIG_CURSES)
5296 /* At the moment curses cannot be used with other displays */
5297 curses_display_init(ds, full_screen);
5301 if (vnc_display != NULL) {
5302 vnc_display_init(ds);
5303 if (vnc_display_open(ds, vnc_display) < 0)
5306 #if defined(CONFIG_SDL)
5307 if (sdl || !vnc_display)
5308 sdl_display_init(ds, full_screen, no_frame);
5309 #elif defined(CONFIG_COCOA)
5310 if (sdl || !vnc_display)
5311 cocoa_display_init(ds, full_screen);
5317 dcl = ds->listeners;
5318 while (dcl != NULL) {
5319 if (dcl->dpy_refresh != NULL) {
5320 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5321 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5326 if (nographic || (vnc_display && !sdl)) {
5327 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5328 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5331 text_consoles_set_display(display_state);
5332 qemu_chr_initial_reset();
5334 if (monitor_device && monitor_hd)
5335 monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5337 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5338 const char *devname = serial_devices[i];
5339 if (devname && strcmp(devname, "none")) {
5341 snprintf(label, sizeof(label), "serial%d", i);
5342 if (strstart(devname, "vc", 0))
5343 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5347 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5348 const char *devname = parallel_devices[i];
5349 if (devname && strcmp(devname, "none")) {
5351 snprintf(label, sizeof(label), "parallel%d", i);
5352 if (strstart(devname, "vc", 0))
5353 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5357 for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5358 const char *devname = virtio_consoles[i];
5359 if (virtcon_hds[i] && devname) {
5361 snprintf(label, sizeof(label), "virtcon%d", i);
5362 if (strstart(devname, "vc", 0))
5363 qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5367 #ifdef CONFIG_GDBSTUB
5368 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5369 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5376 do_loadvm(cur_mon, loadvm);
5379 autostart = 0; /* fixme how to deal with -daemonize */
5380 qemu_start_incoming_migration(incoming);
5392 len = write(fds[1], &status, 1);
5393 if (len == -1 && (errno == EINTR))
5400 TFR(fd = open("/dev/null", O_RDWR));
5406 pwd = getpwnam(run_as);
5408 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5414 if (chroot(chroot_dir) < 0) {
5415 fprintf(stderr, "chroot failed\n");
5422 if (setgid(pwd->pw_gid) < 0) {
5423 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5426 if (setuid(pwd->pw_uid) < 0) {
5427 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5430 if (setuid(0) != -1) {
5431 fprintf(stderr, "Dropping privileges failed\n");