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
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
50 #include <sys/times.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
64 #if !defined(__APPLE__) && !defined(__OpenBSD__)
70 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
71 #include <freebsd/stdlib.h>
75 #include <linux/if_tun.h>
78 #include <linux/rtc.h>
80 /* For the benefit of older linux systems which don't supply it,
81 we use a local copy of hpet.h. */
82 /* #include <linux/hpet.h> */
85 #include <linux/ppdev.h>
86 #include <linux/parport.h>
89 #include <sys/ethernet.h>
90 #include <sys/sockio.h>
91 #include <netinet/arp.h>
92 #include <netinet/in.h>
93 #include <netinet/in_systm.h>
94 #include <netinet/ip.h>
95 #include <netinet/ip_icmp.h> // must come after ip.h
96 #include <netinet/udp.h>
97 #include <netinet/tcp.h>
104 #include <winsock2.h>
105 int inet_aton(const char *cp, struct in_addr *ia);
108 #if defined(CONFIG_SLIRP)
109 #include "libslirp.h"
112 #if defined(__OpenBSD__)
116 #if defined(CONFIG_VDE)
117 #include <libvdeplug.h>
122 #include <sys/timeb.h>
123 #include <mmsystem.h>
124 #define getopt_long_only getopt_long
125 #define memalign(align, size) malloc(size)
128 #include "qemu_socket.h"
134 #endif /* CONFIG_SDL */
138 #define main qemu_main
139 #endif /* CONFIG_COCOA */
143 #include "exec-all.h"
145 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
146 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
148 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
150 #define SMBD_COMMAND "/usr/sbin/smbd"
153 //#define DEBUG_UNUSED_IOPORT
154 //#define DEBUG_IOPORT
157 #define DEFAULT_RAM_SIZE 144
159 #define DEFAULT_RAM_SIZE 128
162 /* Max number of USB devices that can be specified on the commandline. */
163 #define MAX_USB_CMDLINE 8
165 /* XXX: use a two level table to limit memory usage */
166 #define MAX_IOPORTS 65536
168 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
169 const char *bios_name = NULL;
170 void *ioport_opaque[MAX_IOPORTS];
171 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
172 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
173 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
174 to store the VM snapshots */
175 DriveInfo drives_table[MAX_DRIVES+1];
177 /* point to the block driver where the snapshots are managed */
178 BlockDriverState *bs_snapshots;
180 static DisplayState display_state;
183 const char* keyboard_layout = NULL;
184 int64_t ticks_per_sec;
186 int pit_min_timer_count = 0;
188 NICInfo nd_table[MAX_NICS];
190 static int rtc_utc = 1;
191 static int rtc_date_offset = -1; /* -1 means no change */
192 int cirrus_vga_enabled = 1;
193 int vmsvga_enabled = 0;
195 int graphic_width = 1024;
196 int graphic_height = 768;
197 int graphic_depth = 8;
199 int graphic_width = 800;
200 int graphic_height = 600;
201 int graphic_depth = 15;
206 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
207 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
209 int win2k_install_hack = 0;
212 static VLANState *first_vlan;
214 const char *vnc_display;
215 #if defined(TARGET_SPARC)
217 #elif defined(TARGET_I386)
222 int acpi_enabled = 1;
227 int graphic_rotate = 0;
229 const char *option_rom[MAX_OPTION_ROMS];
231 int semihosting_enabled = 0;
236 const char *qemu_name;
239 unsigned int nb_prom_envs = 0;
240 const char *prom_envs[MAX_PROM_ENVS];
246 } drives_opt[MAX_DRIVES];
248 static CPUState *cur_cpu;
249 static CPUState *next_cpu;
250 static int event_pending = 1;
251 /* Conversion factor from emulated instructions to virtual clock ticks. */
252 static int icount_time_shift;
253 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
254 #define MAX_ICOUNT_SHIFT 10
255 /* Compensate for varying guest execution speed. */
256 static int64_t qemu_icount_bias;
257 QEMUTimer *icount_rt_timer;
258 QEMUTimer *icount_vm_timer;
260 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
262 /***********************************************************/
263 /* x86 ISA bus support */
265 target_phys_addr_t isa_mem_base = 0;
268 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
269 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
271 static uint32_t ioport_read(int index, uint32_t address)
273 static IOPortReadFunc *default_func[3] = {
274 default_ioport_readb,
275 default_ioport_readw,
278 IOPortReadFunc *func = ioport_read_table[index][address];
280 func = default_func[index];
281 return func(ioport_opaque[address], address);
284 static void ioport_write(int index, uint32_t address, uint32_t data)
286 static IOPortWriteFunc *default_func[3] = {
287 default_ioport_writeb,
288 default_ioport_writew,
289 default_ioport_writel
291 IOPortWriteFunc *func = ioport_write_table[index][address];
293 func = default_func[index];
294 func(ioport_opaque[address], address, data);
297 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
299 #ifdef DEBUG_UNUSED_IOPORT
300 fprintf(stderr, "unused inb: port=0x%04x\n", address);
305 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
307 #ifdef DEBUG_UNUSED_IOPORT
308 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
312 /* default is to make two byte accesses */
313 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
316 data = ioport_read(0, address);
317 address = (address + 1) & (MAX_IOPORTS - 1);
318 data |= ioport_read(0, address) << 8;
322 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
324 ioport_write(0, address, data & 0xff);
325 address = (address + 1) & (MAX_IOPORTS - 1);
326 ioport_write(0, address, (data >> 8) & 0xff);
329 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
331 #ifdef DEBUG_UNUSED_IOPORT
332 fprintf(stderr, "unused inl: port=0x%04x\n", address);
337 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
339 #ifdef DEBUG_UNUSED_IOPORT
340 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
344 /* size is the word size in byte */
345 int register_ioport_read(int start, int length, int size,
346 IOPortReadFunc *func, void *opaque)
352 } else if (size == 2) {
354 } else if (size == 4) {
357 hw_error("register_ioport_read: invalid size");
360 for(i = start; i < start + length; i += size) {
361 ioport_read_table[bsize][i] = func;
362 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
363 hw_error("register_ioport_read: invalid opaque");
364 ioport_opaque[i] = opaque;
369 /* size is the word size in byte */
370 int register_ioport_write(int start, int length, int size,
371 IOPortWriteFunc *func, void *opaque)
377 } else if (size == 2) {
379 } else if (size == 4) {
382 hw_error("register_ioport_write: invalid size");
385 for(i = start; i < start + length; i += size) {
386 ioport_write_table[bsize][i] = func;
387 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
388 hw_error("register_ioport_write: invalid opaque");
389 ioport_opaque[i] = opaque;
394 void isa_unassign_ioport(int start, int length)
398 for(i = start; i < start + length; i++) {
399 ioport_read_table[0][i] = default_ioport_readb;
400 ioport_read_table[1][i] = default_ioport_readw;
401 ioport_read_table[2][i] = default_ioport_readl;
403 ioport_write_table[0][i] = default_ioport_writeb;
404 ioport_write_table[1][i] = default_ioport_writew;
405 ioport_write_table[2][i] = default_ioport_writel;
409 /***********************************************************/
411 void cpu_outb(CPUState *env, int addr, int val)
414 if (loglevel & CPU_LOG_IOPORT)
415 fprintf(logfile, "outb: %04x %02x\n", addr, val);
417 ioport_write(0, addr, val);
420 env->last_io_time = cpu_get_time_fast();
424 void cpu_outw(CPUState *env, int addr, int val)
427 if (loglevel & CPU_LOG_IOPORT)
428 fprintf(logfile, "outw: %04x %04x\n", addr, val);
430 ioport_write(1, addr, val);
433 env->last_io_time = cpu_get_time_fast();
437 void cpu_outl(CPUState *env, int addr, int val)
440 if (loglevel & CPU_LOG_IOPORT)
441 fprintf(logfile, "outl: %04x %08x\n", addr, val);
443 ioport_write(2, addr, val);
446 env->last_io_time = cpu_get_time_fast();
450 int cpu_inb(CPUState *env, int addr)
453 val = ioport_read(0, addr);
455 if (loglevel & CPU_LOG_IOPORT)
456 fprintf(logfile, "inb : %04x %02x\n", addr, val);
460 env->last_io_time = cpu_get_time_fast();
465 int cpu_inw(CPUState *env, int addr)
468 val = ioport_read(1, addr);
470 if (loglevel & CPU_LOG_IOPORT)
471 fprintf(logfile, "inw : %04x %04x\n", addr, val);
475 env->last_io_time = cpu_get_time_fast();
480 int cpu_inl(CPUState *env, int addr)
483 val = ioport_read(2, addr);
485 if (loglevel & CPU_LOG_IOPORT)
486 fprintf(logfile, "inl : %04x %08x\n", addr, val);
490 env->last_io_time = cpu_get_time_fast();
495 /***********************************************************/
496 void hw_error(const char *fmt, ...)
502 fprintf(stderr, "qemu: hardware error: ");
503 vfprintf(stderr, fmt, ap);
504 fprintf(stderr, "\n");
505 for(env = first_cpu; env != NULL; env = env->next_cpu) {
506 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
508 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
510 cpu_dump_state(env, stderr, fprintf, 0);
517 /***********************************************************/
520 static QEMUPutKBDEvent *qemu_put_kbd_event;
521 static void *qemu_put_kbd_event_opaque;
522 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
523 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
525 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
527 qemu_put_kbd_event_opaque = opaque;
528 qemu_put_kbd_event = func;
531 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
532 void *opaque, int absolute,
535 QEMUPutMouseEntry *s, *cursor;
537 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
541 s->qemu_put_mouse_event = func;
542 s->qemu_put_mouse_event_opaque = opaque;
543 s->qemu_put_mouse_event_absolute = absolute;
544 s->qemu_put_mouse_event_name = qemu_strdup(name);
547 if (!qemu_put_mouse_event_head) {
548 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
552 cursor = qemu_put_mouse_event_head;
553 while (cursor->next != NULL)
554 cursor = cursor->next;
557 qemu_put_mouse_event_current = s;
562 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
564 QEMUPutMouseEntry *prev = NULL, *cursor;
566 if (!qemu_put_mouse_event_head || entry == NULL)
569 cursor = qemu_put_mouse_event_head;
570 while (cursor != NULL && cursor != entry) {
572 cursor = cursor->next;
575 if (cursor == NULL) // does not exist or list empty
577 else if (prev == NULL) { // entry is head
578 qemu_put_mouse_event_head = cursor->next;
579 if (qemu_put_mouse_event_current == entry)
580 qemu_put_mouse_event_current = cursor->next;
581 qemu_free(entry->qemu_put_mouse_event_name);
586 prev->next = entry->next;
588 if (qemu_put_mouse_event_current == entry)
589 qemu_put_mouse_event_current = prev;
591 qemu_free(entry->qemu_put_mouse_event_name);
595 void kbd_put_keycode(int keycode)
597 if (qemu_put_kbd_event) {
598 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
602 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
604 QEMUPutMouseEvent *mouse_event;
605 void *mouse_event_opaque;
608 if (!qemu_put_mouse_event_current) {
613 qemu_put_mouse_event_current->qemu_put_mouse_event;
615 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
618 if (graphic_rotate) {
619 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
622 width = graphic_width - 1;
623 mouse_event(mouse_event_opaque,
624 width - dy, dx, dz, buttons_state);
626 mouse_event(mouse_event_opaque,
627 dx, dy, dz, buttons_state);
631 int kbd_mouse_is_absolute(void)
633 if (!qemu_put_mouse_event_current)
636 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
639 void do_info_mice(void)
641 QEMUPutMouseEntry *cursor;
644 if (!qemu_put_mouse_event_head) {
645 term_printf("No mouse devices connected\n");
649 term_printf("Mouse devices available:\n");
650 cursor = qemu_put_mouse_event_head;
651 while (cursor != NULL) {
652 term_printf("%c Mouse #%d: %s\n",
653 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
654 index, cursor->qemu_put_mouse_event_name);
656 cursor = cursor->next;
660 void do_mouse_set(int index)
662 QEMUPutMouseEntry *cursor;
665 if (!qemu_put_mouse_event_head) {
666 term_printf("No mouse devices connected\n");
670 cursor = qemu_put_mouse_event_head;
671 while (cursor != NULL && index != i) {
673 cursor = cursor->next;
677 qemu_put_mouse_event_current = cursor;
679 term_printf("Mouse at given index not found\n");
682 /* compute with 96 bit intermediate result: (a*b)/c */
683 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
688 #ifdef WORDS_BIGENDIAN
698 rl = (uint64_t)u.l.low * (uint64_t)b;
699 rh = (uint64_t)u.l.high * (uint64_t)b;
702 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
706 /***********************************************************/
707 /* real time host monotonic timer */
709 #define QEMU_TIMER_BASE 1000000000LL
713 static int64_t clock_freq;
715 static void init_get_clock(void)
719 ret = QueryPerformanceFrequency(&freq);
721 fprintf(stderr, "Could not calibrate ticks\n");
724 clock_freq = freq.QuadPart;
727 static int64_t get_clock(void)
730 QueryPerformanceCounter(&ti);
731 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
736 static int use_rt_clock;
738 static void init_get_clock(void)
741 #if defined(__linux__)
744 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
751 static int64_t get_clock(void)
753 #if defined(__linux__)
756 clock_gettime(CLOCK_MONOTONIC, &ts);
757 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
761 /* XXX: using gettimeofday leads to problems if the date
762 changes, so it should be avoided. */
764 gettimeofday(&tv, NULL);
765 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
770 /* Return the virtual CPU time, based on the instruction counter. */
771 static int64_t cpu_get_icount(void)
774 CPUState *env = cpu_single_env;;
775 icount = qemu_icount;
778 fprintf(stderr, "Bad clock read\n");
779 icount -= (env->icount_decr.u16.low + env->icount_extra);
781 return qemu_icount_bias + (icount << icount_time_shift);
784 /***********************************************************/
785 /* guest cycle counter */
787 static int64_t cpu_ticks_prev;
788 static int64_t cpu_ticks_offset;
789 static int64_t cpu_clock_offset;
790 static int cpu_ticks_enabled;
792 /* return the host CPU cycle counter and handle stop/restart */
793 int64_t cpu_get_ticks(void)
796 return cpu_get_icount();
798 if (!cpu_ticks_enabled) {
799 return cpu_ticks_offset;
802 ticks = cpu_get_real_ticks();
803 if (cpu_ticks_prev > ticks) {
804 /* Note: non increasing ticks may happen if the host uses
806 cpu_ticks_offset += cpu_ticks_prev - ticks;
808 cpu_ticks_prev = ticks;
809 return ticks + cpu_ticks_offset;
813 /* return the host CPU monotonic timer and handle stop/restart */
814 static int64_t cpu_get_clock(void)
817 if (!cpu_ticks_enabled) {
818 return cpu_clock_offset;
821 return ti + cpu_clock_offset;
825 /* enable cpu_get_ticks() */
826 void cpu_enable_ticks(void)
828 if (!cpu_ticks_enabled) {
829 cpu_ticks_offset -= cpu_get_real_ticks();
830 cpu_clock_offset -= get_clock();
831 cpu_ticks_enabled = 1;
835 /* disable cpu_get_ticks() : the clock is stopped. You must not call
836 cpu_get_ticks() after that. */
837 void cpu_disable_ticks(void)
839 if (cpu_ticks_enabled) {
840 cpu_ticks_offset = cpu_get_ticks();
841 cpu_clock_offset = cpu_get_clock();
842 cpu_ticks_enabled = 0;
846 /***********************************************************/
849 #define QEMU_TIMER_REALTIME 0
850 #define QEMU_TIMER_VIRTUAL 1
854 /* XXX: add frequency */
862 struct QEMUTimer *next;
865 struct qemu_alarm_timer {
869 int (*start)(struct qemu_alarm_timer *t);
870 void (*stop)(struct qemu_alarm_timer *t);
871 void (*rearm)(struct qemu_alarm_timer *t);
875 #define ALARM_FLAG_DYNTICKS 0x1
876 #define ALARM_FLAG_EXPIRED 0x2
878 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
880 return t->flags & ALARM_FLAG_DYNTICKS;
883 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
885 if (!alarm_has_dynticks(t))
891 /* TODO: MIN_TIMER_REARM_US should be optimized */
892 #define MIN_TIMER_REARM_US 250
894 static struct qemu_alarm_timer *alarm_timer;
898 struct qemu_alarm_win32 {
902 } alarm_win32_data = {0, NULL, -1};
904 static int win32_start_timer(struct qemu_alarm_timer *t);
905 static void win32_stop_timer(struct qemu_alarm_timer *t);
906 static void win32_rearm_timer(struct qemu_alarm_timer *t);
910 static int unix_start_timer(struct qemu_alarm_timer *t);
911 static void unix_stop_timer(struct qemu_alarm_timer *t);
915 static int dynticks_start_timer(struct qemu_alarm_timer *t);
916 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
917 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
919 static int hpet_start_timer(struct qemu_alarm_timer *t);
920 static void hpet_stop_timer(struct qemu_alarm_timer *t);
922 static int rtc_start_timer(struct qemu_alarm_timer *t);
923 static void rtc_stop_timer(struct qemu_alarm_timer *t);
925 #endif /* __linux__ */
929 /* Correlation between real and virtual time is always going to be
930 fairly approximate, so ignore small variation.
931 When the guest is idle real and virtual time will be aligned in
933 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
935 static void icount_adjust(void)
940 static int64_t last_delta;
941 /* If the VM is not running, then do nothing. */
945 cur_time = cpu_get_clock();
946 cur_icount = qemu_get_clock(vm_clock);
947 delta = cur_icount - cur_time;
948 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
950 && last_delta + ICOUNT_WOBBLE < delta * 2
951 && icount_time_shift > 0) {
952 /* The guest is getting too far ahead. Slow time down. */
956 && last_delta - ICOUNT_WOBBLE > delta * 2
957 && icount_time_shift < MAX_ICOUNT_SHIFT) {
958 /* The guest is getting too far behind. Speed time up. */
962 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
965 static void icount_adjust_rt(void * opaque)
967 qemu_mod_timer(icount_rt_timer,
968 qemu_get_clock(rt_clock) + 1000);
972 static void icount_adjust_vm(void * opaque)
974 qemu_mod_timer(icount_vm_timer,
975 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
979 static void init_icount_adjust(void)
981 /* Have both realtime and virtual time triggers for speed adjustment.
982 The realtime trigger catches emulated time passing too slowly,
983 the virtual time trigger catches emulated time passing too fast.
984 Realtime triggers occur even when idle, so use them less frequently
986 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
987 qemu_mod_timer(icount_rt_timer,
988 qemu_get_clock(rt_clock) + 1000);
989 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
990 qemu_mod_timer(icount_vm_timer,
991 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
994 static struct qemu_alarm_timer alarm_timers[] = {
997 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
998 dynticks_stop_timer, dynticks_rearm_timer, NULL},
999 /* HPET - if available - is preferred */
1000 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1001 /* ...otherwise try RTC */
1002 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1004 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1006 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1007 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1008 {"win32", 0, win32_start_timer,
1009 win32_stop_timer, NULL, &alarm_win32_data},
1014 static void show_available_alarms(void)
1018 printf("Available alarm timers, in order of precedence:\n");
1019 for (i = 0; alarm_timers[i].name; i++)
1020 printf("%s\n", alarm_timers[i].name);
1023 static void configure_alarms(char const *opt)
1027 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1030 struct qemu_alarm_timer tmp;
1032 if (!strcmp(opt, "?")) {
1033 show_available_alarms();
1039 /* Reorder the array */
1040 name = strtok(arg, ",");
1042 for (i = 0; i < count && alarm_timers[i].name; i++) {
1043 if (!strcmp(alarm_timers[i].name, name))
1048 fprintf(stderr, "Unknown clock %s\n", name);
1057 tmp = alarm_timers[i];
1058 alarm_timers[i] = alarm_timers[cur];
1059 alarm_timers[cur] = tmp;
1063 name = strtok(NULL, ",");
1069 /* Disable remaining timers */
1070 for (i = cur; i < count; i++)
1071 alarm_timers[i].name = NULL;
1073 show_available_alarms();
1078 QEMUClock *rt_clock;
1079 QEMUClock *vm_clock;
1081 static QEMUTimer *active_timers[2];
1083 static QEMUClock *qemu_new_clock(int type)
1086 clock = qemu_mallocz(sizeof(QEMUClock));
1093 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1097 ts = qemu_mallocz(sizeof(QEMUTimer));
1100 ts->opaque = opaque;
1104 void qemu_free_timer(QEMUTimer *ts)
1109 /* stop a timer, but do not dealloc it */
1110 void qemu_del_timer(QEMUTimer *ts)
1114 /* NOTE: this code must be signal safe because
1115 qemu_timer_expired() can be called from a signal. */
1116 pt = &active_timers[ts->clock->type];
1129 /* modify the current timer so that it will be fired when current_time
1130 >= expire_time. The corresponding callback will be called. */
1131 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1137 /* add the timer in the sorted list */
1138 /* NOTE: this code must be signal safe because
1139 qemu_timer_expired() can be called from a signal. */
1140 pt = &active_timers[ts->clock->type];
1145 if (t->expire_time > expire_time)
1149 ts->expire_time = expire_time;
1153 /* Rearm if necessary */
1154 if (pt == &active_timers[ts->clock->type]) {
1155 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1156 qemu_rearm_alarm_timer(alarm_timer);
1158 /* Interrupt execution to force deadline recalculation. */
1159 if (use_icount && cpu_single_env) {
1160 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1165 int qemu_timer_pending(QEMUTimer *ts)
1168 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1175 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1179 return (timer_head->expire_time <= current_time);
1182 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1188 if (!ts || ts->expire_time > current_time)
1190 /* remove timer from the list before calling the callback */
1191 *ptimer_head = ts->next;
1194 /* run the callback (the timer list can be modified) */
1199 int64_t qemu_get_clock(QEMUClock *clock)
1201 switch(clock->type) {
1202 case QEMU_TIMER_REALTIME:
1203 return get_clock() / 1000000;
1205 case QEMU_TIMER_VIRTUAL:
1207 return cpu_get_icount();
1209 return cpu_get_clock();
1214 static void init_timers(void)
1217 ticks_per_sec = QEMU_TIMER_BASE;
1218 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1219 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1223 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1225 uint64_t expire_time;
1227 if (qemu_timer_pending(ts)) {
1228 expire_time = ts->expire_time;
1232 qemu_put_be64(f, expire_time);
1235 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1237 uint64_t expire_time;
1239 expire_time = qemu_get_be64(f);
1240 if (expire_time != -1) {
1241 qemu_mod_timer(ts, expire_time);
1247 static void timer_save(QEMUFile *f, void *opaque)
1249 if (cpu_ticks_enabled) {
1250 hw_error("cannot save state if virtual timers are running");
1252 qemu_put_be64(f, cpu_ticks_offset);
1253 qemu_put_be64(f, ticks_per_sec);
1254 qemu_put_be64(f, cpu_clock_offset);
1257 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1259 if (version_id != 1 && version_id != 2)
1261 if (cpu_ticks_enabled) {
1264 cpu_ticks_offset=qemu_get_be64(f);
1265 ticks_per_sec=qemu_get_be64(f);
1266 if (version_id == 2) {
1267 cpu_clock_offset=qemu_get_be64(f);
1273 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1274 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1276 static void host_alarm_handler(int host_signum)
1280 #define DISP_FREQ 1000
1282 static int64_t delta_min = INT64_MAX;
1283 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1285 ti = qemu_get_clock(vm_clock);
1286 if (last_clock != 0) {
1287 delta = ti - last_clock;
1288 if (delta < delta_min)
1290 if (delta > delta_max)
1293 if (++count == DISP_FREQ) {
1294 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1295 muldiv64(delta_min, 1000000, ticks_per_sec),
1296 muldiv64(delta_max, 1000000, ticks_per_sec),
1297 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1298 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1300 delta_min = INT64_MAX;
1308 if (alarm_has_dynticks(alarm_timer) ||
1310 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1311 qemu_get_clock(vm_clock))) ||
1312 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1313 qemu_get_clock(rt_clock))) {
1315 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1316 SetEvent(data->host_alarm);
1318 CPUState *env = next_cpu;
1320 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1323 /* stop the currently executing cpu because a timer occured */
1324 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1326 if (env->kqemu_enabled) {
1327 kqemu_cpu_interrupt(env);
1335 static int64_t qemu_next_deadline(void)
1339 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1340 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1341 qemu_get_clock(vm_clock);
1343 /* To avoid problems with overflow limit this to 2^32. */
1353 #if defined(__linux__) || defined(_WIN32)
1354 static uint64_t qemu_next_deadline_dyntick(void)
1362 delta = (qemu_next_deadline() + 999) / 1000;
1364 if (active_timers[QEMU_TIMER_REALTIME]) {
1365 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1366 qemu_get_clock(rt_clock))*1000;
1367 if (rtdelta < delta)
1371 if (delta < MIN_TIMER_REARM_US)
1372 delta = MIN_TIMER_REARM_US;
1380 #if defined(__linux__)
1382 #define RTC_FREQ 1024
1384 static void enable_sigio_timer(int fd)
1386 struct sigaction act;
1389 sigfillset(&act.sa_mask);
1391 act.sa_handler = host_alarm_handler;
1393 sigaction(SIGIO, &act, NULL);
1394 fcntl(fd, F_SETFL, O_ASYNC);
1395 fcntl(fd, F_SETOWN, getpid());
1398 static int hpet_start_timer(struct qemu_alarm_timer *t)
1400 struct hpet_info info;
1403 fd = open("/dev/hpet", O_RDONLY);
1408 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1410 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1411 "error, but for better emulation accuracy type:\n"
1412 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1416 /* Check capabilities */
1417 r = ioctl(fd, HPET_INFO, &info);
1421 /* Enable periodic mode */
1422 r = ioctl(fd, HPET_EPI, 0);
1423 if (info.hi_flags && (r < 0))
1426 /* Enable interrupt */
1427 r = ioctl(fd, HPET_IE_ON, 0);
1431 enable_sigio_timer(fd);
1432 t->priv = (void *)(long)fd;
1440 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1442 int fd = (long)t->priv;
1447 static int rtc_start_timer(struct qemu_alarm_timer *t)
1450 unsigned long current_rtc_freq = 0;
1452 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1455 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1456 if (current_rtc_freq != RTC_FREQ &&
1457 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1458 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1459 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1460 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1463 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1469 enable_sigio_timer(rtc_fd);
1471 t->priv = (void *)(long)rtc_fd;
1476 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1478 int rtc_fd = (long)t->priv;
1483 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1487 struct sigaction act;
1489 sigfillset(&act.sa_mask);
1491 act.sa_handler = host_alarm_handler;
1493 sigaction(SIGALRM, &act, NULL);
1495 ev.sigev_value.sival_int = 0;
1496 ev.sigev_notify = SIGEV_SIGNAL;
1497 ev.sigev_signo = SIGALRM;
1499 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1500 perror("timer_create");
1502 /* disable dynticks */
1503 fprintf(stderr, "Dynamic Ticks disabled\n");
1508 t->priv = (void *)host_timer;
1513 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1515 timer_t host_timer = (timer_t)t->priv;
1517 timer_delete(host_timer);
1520 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1522 timer_t host_timer = (timer_t)t->priv;
1523 struct itimerspec timeout;
1524 int64_t nearest_delta_us = INT64_MAX;
1527 if (!active_timers[QEMU_TIMER_REALTIME] &&
1528 !active_timers[QEMU_TIMER_VIRTUAL])
1531 nearest_delta_us = qemu_next_deadline_dyntick();
1533 /* check whether a timer is already running */
1534 if (timer_gettime(host_timer, &timeout)) {
1536 fprintf(stderr, "Internal timer error: aborting\n");
1539 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1540 if (current_us && current_us <= nearest_delta_us)
1543 timeout.it_interval.tv_sec = 0;
1544 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1545 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1546 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1547 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1549 fprintf(stderr, "Internal timer error: aborting\n");
1554 #endif /* defined(__linux__) */
1556 static int unix_start_timer(struct qemu_alarm_timer *t)
1558 struct sigaction act;
1559 struct itimerval itv;
1563 sigfillset(&act.sa_mask);
1565 act.sa_handler = host_alarm_handler;
1567 sigaction(SIGALRM, &act, NULL);
1569 itv.it_interval.tv_sec = 0;
1570 /* for i386 kernel 2.6 to get 1 ms */
1571 itv.it_interval.tv_usec = 999;
1572 itv.it_value.tv_sec = 0;
1573 itv.it_value.tv_usec = 10 * 1000;
1575 err = setitimer(ITIMER_REAL, &itv, NULL);
1582 static void unix_stop_timer(struct qemu_alarm_timer *t)
1584 struct itimerval itv;
1586 memset(&itv, 0, sizeof(itv));
1587 setitimer(ITIMER_REAL, &itv, NULL);
1590 #endif /* !defined(_WIN32) */
1594 static int win32_start_timer(struct qemu_alarm_timer *t)
1597 struct qemu_alarm_win32 *data = t->priv;
1600 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1601 if (!data->host_alarm) {
1602 perror("Failed CreateEvent");
1606 memset(&tc, 0, sizeof(tc));
1607 timeGetDevCaps(&tc, sizeof(tc));
1609 if (data->period < tc.wPeriodMin)
1610 data->period = tc.wPeriodMin;
1612 timeBeginPeriod(data->period);
1614 flags = TIME_CALLBACK_FUNCTION;
1615 if (alarm_has_dynticks(t))
1616 flags |= TIME_ONESHOT;
1618 flags |= TIME_PERIODIC;
1620 data->timerId = timeSetEvent(1, // interval (ms)
1621 data->period, // resolution
1622 host_alarm_handler, // function
1623 (DWORD)t, // parameter
1626 if (!data->timerId) {
1627 perror("Failed to initialize win32 alarm timer");
1629 timeEndPeriod(data->period);
1630 CloseHandle(data->host_alarm);
1634 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1639 static void win32_stop_timer(struct qemu_alarm_timer *t)
1641 struct qemu_alarm_win32 *data = t->priv;
1643 timeKillEvent(data->timerId);
1644 timeEndPeriod(data->period);
1646 CloseHandle(data->host_alarm);
1649 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1651 struct qemu_alarm_win32 *data = t->priv;
1652 uint64_t nearest_delta_us;
1654 if (!active_timers[QEMU_TIMER_REALTIME] &&
1655 !active_timers[QEMU_TIMER_VIRTUAL])
1658 nearest_delta_us = qemu_next_deadline_dyntick();
1659 nearest_delta_us /= 1000;
1661 timeKillEvent(data->timerId);
1663 data->timerId = timeSetEvent(1,
1667 TIME_ONESHOT | TIME_PERIODIC);
1669 if (!data->timerId) {
1670 perror("Failed to re-arm win32 alarm timer");
1672 timeEndPeriod(data->period);
1673 CloseHandle(data->host_alarm);
1680 static void init_timer_alarm(void)
1682 struct qemu_alarm_timer *t;
1685 for (i = 0; alarm_timers[i].name; i++) {
1686 t = &alarm_timers[i];
1694 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1695 fprintf(stderr, "Terminating\n");
1702 static void quit_timers(void)
1704 alarm_timer->stop(alarm_timer);
1708 /***********************************************************/
1709 /* host time/date access */
1710 void qemu_get_timedate(struct tm *tm, int offset)
1717 if (rtc_date_offset == -1) {
1721 ret = localtime(&ti);
1723 ti -= rtc_date_offset;
1727 memcpy(tm, ret, sizeof(struct tm));
1730 int qemu_timedate_diff(struct tm *tm)
1734 if (rtc_date_offset == -1)
1736 seconds = mktimegm(tm);
1738 seconds = mktime(tm);
1740 seconds = mktimegm(tm) + rtc_date_offset;
1742 return seconds - time(NULL);
1745 /***********************************************************/
1746 /* character device */
1748 static void qemu_chr_event(CharDriverState *s, int event)
1752 s->chr_event(s->handler_opaque, event);
1755 static void qemu_chr_reset_bh(void *opaque)
1757 CharDriverState *s = opaque;
1758 qemu_chr_event(s, CHR_EVENT_RESET);
1759 qemu_bh_delete(s->bh);
1763 void qemu_chr_reset(CharDriverState *s)
1765 if (s->bh == NULL) {
1766 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1767 qemu_bh_schedule(s->bh);
1771 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1773 return s->chr_write(s, buf, len);
1776 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1780 return s->chr_ioctl(s, cmd, arg);
1783 int qemu_chr_can_read(CharDriverState *s)
1785 if (!s->chr_can_read)
1787 return s->chr_can_read(s->handler_opaque);
1790 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1792 s->chr_read(s->handler_opaque, buf, len);
1795 void qemu_chr_accept_input(CharDriverState *s)
1797 if (s->chr_accept_input)
1798 s->chr_accept_input(s);
1801 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1806 vsnprintf(buf, sizeof(buf), fmt, ap);
1807 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1811 void qemu_chr_send_event(CharDriverState *s, int event)
1813 if (s->chr_send_event)
1814 s->chr_send_event(s, event);
1817 void qemu_chr_add_handlers(CharDriverState *s,
1818 IOCanRWHandler *fd_can_read,
1819 IOReadHandler *fd_read,
1820 IOEventHandler *fd_event,
1823 s->chr_can_read = fd_can_read;
1824 s->chr_read = fd_read;
1825 s->chr_event = fd_event;
1826 s->handler_opaque = opaque;
1827 if (s->chr_update_read_handler)
1828 s->chr_update_read_handler(s);
1831 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1836 static CharDriverState *qemu_chr_open_null(void)
1838 CharDriverState *chr;
1840 chr = qemu_mallocz(sizeof(CharDriverState));
1843 chr->chr_write = null_chr_write;
1847 /* MUX driver for serial I/O splitting */
1848 static int term_timestamps;
1849 static int64_t term_timestamps_start;
1851 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1852 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1854 IOCanRWHandler *chr_can_read[MAX_MUX];
1855 IOReadHandler *chr_read[MAX_MUX];
1856 IOEventHandler *chr_event[MAX_MUX];
1857 void *ext_opaque[MAX_MUX];
1858 CharDriverState *drv;
1859 unsigned char buffer[MUX_BUFFER_SIZE];
1863 int term_got_escape;
1868 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1870 MuxDriver *d = chr->opaque;
1872 if (!term_timestamps) {
1873 ret = d->drv->chr_write(d->drv, buf, len);
1878 for(i = 0; i < len; i++) {
1879 ret += d->drv->chr_write(d->drv, buf+i, 1);
1880 if (buf[i] == '\n') {
1886 if (term_timestamps_start == -1)
1887 term_timestamps_start = ti;
1888 ti -= term_timestamps_start;
1889 secs = ti / 1000000000;
1890 snprintf(buf1, sizeof(buf1),
1891 "[%02d:%02d:%02d.%03d] ",
1895 (int)((ti / 1000000) % 1000));
1896 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1903 static const char * const mux_help[] = {
1904 "% h print this help\n\r",
1905 "% x exit emulator\n\r",
1906 "% s save disk data back to file (if -snapshot)\n\r",
1907 "% t toggle console timestamps\n\r"
1908 "% b send break (magic sysrq)\n\r",
1909 "% c switch between console and monitor\n\r",
1914 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1915 static void mux_print_help(CharDriverState *chr)
1918 char ebuf[15] = "Escape-Char";
1919 char cbuf[50] = "\n\r";
1921 if (term_escape_char > 0 && term_escape_char < 26) {
1922 snprintf(cbuf, sizeof(cbuf), "\n\r");
1923 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
1925 snprintf(cbuf, sizeof(cbuf),
1926 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1929 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1930 for (i = 0; mux_help[i] != NULL; i++) {
1931 for (j=0; mux_help[i][j] != '\0'; j++) {
1932 if (mux_help[i][j] == '%')
1933 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1935 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1940 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1942 if (d->term_got_escape) {
1943 d->term_got_escape = 0;
1944 if (ch == term_escape_char)
1949 mux_print_help(chr);
1953 const char *term = "QEMU: Terminated\n\r";
1954 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1961 for (i = 0; i < nb_drives; i++) {
1962 bdrv_commit(drives_table[i].bdrv);
1967 qemu_chr_event(chr, CHR_EVENT_BREAK);
1970 /* Switch to the next registered device */
1972 if (chr->focus >= d->mux_cnt)
1976 term_timestamps = !term_timestamps;
1977 term_timestamps_start = -1;
1980 } else if (ch == term_escape_char) {
1981 d->term_got_escape = 1;
1989 static void mux_chr_accept_input(CharDriverState *chr)
1992 MuxDriver *d = chr->opaque;
1994 while (d->prod != d->cons &&
1995 d->chr_can_read[m] &&
1996 d->chr_can_read[m](d->ext_opaque[m])) {
1997 d->chr_read[m](d->ext_opaque[m],
1998 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
2002 static int mux_chr_can_read(void *opaque)
2004 CharDriverState *chr = opaque;
2005 MuxDriver *d = chr->opaque;
2007 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2009 if (d->chr_can_read[chr->focus])
2010 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2014 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2016 CharDriverState *chr = opaque;
2017 MuxDriver *d = chr->opaque;
2021 mux_chr_accept_input (opaque);
2023 for(i = 0; i < size; i++)
2024 if (mux_proc_byte(chr, d, buf[i])) {
2025 if (d->prod == d->cons &&
2026 d->chr_can_read[m] &&
2027 d->chr_can_read[m](d->ext_opaque[m]))
2028 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2030 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2034 static void mux_chr_event(void *opaque, int event)
2036 CharDriverState *chr = opaque;
2037 MuxDriver *d = chr->opaque;
2040 /* Send the event to all registered listeners */
2041 for (i = 0; i < d->mux_cnt; i++)
2042 if (d->chr_event[i])
2043 d->chr_event[i](d->ext_opaque[i], event);
2046 static void mux_chr_update_read_handler(CharDriverState *chr)
2048 MuxDriver *d = chr->opaque;
2050 if (d->mux_cnt >= MAX_MUX) {
2051 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2054 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2055 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2056 d->chr_read[d->mux_cnt] = chr->chr_read;
2057 d->chr_event[d->mux_cnt] = chr->chr_event;
2058 /* Fix up the real driver with mux routines */
2059 if (d->mux_cnt == 0) {
2060 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2061 mux_chr_event, chr);
2063 chr->focus = d->mux_cnt;
2067 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2069 CharDriverState *chr;
2072 chr = qemu_mallocz(sizeof(CharDriverState));
2075 d = qemu_mallocz(sizeof(MuxDriver));
2084 chr->chr_write = mux_chr_write;
2085 chr->chr_update_read_handler = mux_chr_update_read_handler;
2086 chr->chr_accept_input = mux_chr_accept_input;
2093 static void socket_cleanup(void)
2098 static int socket_init(void)
2103 ret = WSAStartup(MAKEWORD(2,2), &Data);
2105 err = WSAGetLastError();
2106 fprintf(stderr, "WSAStartup: %d\n", err);
2109 atexit(socket_cleanup);
2113 static int send_all(int fd, const uint8_t *buf, int len1)
2119 ret = send(fd, buf, len, 0);
2122 errno = WSAGetLastError();
2123 if (errno != WSAEWOULDBLOCK) {
2126 } else if (ret == 0) {
2136 void socket_set_nonblock(int fd)
2138 unsigned long opt = 1;
2139 ioctlsocket(fd, FIONBIO, &opt);
2144 static int unix_write(int fd, const uint8_t *buf, int len1)
2150 ret = write(fd, buf, len);
2152 if (errno != EINTR && errno != EAGAIN)
2154 } else if (ret == 0) {
2164 static inline int send_all(int fd, const uint8_t *buf, int len1)
2166 return unix_write(fd, buf, len1);
2169 void socket_set_nonblock(int fd)
2172 f = fcntl(fd, F_GETFL);
2173 fcntl(fd, F_SETFL, f | O_NONBLOCK);
2175 #endif /* !_WIN32 */
2184 #define STDIO_MAX_CLIENTS 1
2185 static int stdio_nb_clients = 0;
2187 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2189 FDCharDriver *s = chr->opaque;
2190 return unix_write(s->fd_out, buf, len);
2193 static int fd_chr_read_poll(void *opaque)
2195 CharDriverState *chr = opaque;
2196 FDCharDriver *s = chr->opaque;
2198 s->max_size = qemu_chr_can_read(chr);
2202 static void fd_chr_read(void *opaque)
2204 CharDriverState *chr = opaque;
2205 FDCharDriver *s = chr->opaque;
2210 if (len > s->max_size)
2214 size = read(s->fd_in, buf, len);
2216 /* FD has been closed. Remove it from the active list. */
2217 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2221 qemu_chr_read(chr, buf, size);
2225 static void fd_chr_update_read_handler(CharDriverState *chr)
2227 FDCharDriver *s = chr->opaque;
2229 if (s->fd_in >= 0) {
2230 if (nographic && s->fd_in == 0) {
2232 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2233 fd_chr_read, NULL, chr);
2238 static void fd_chr_close(struct CharDriverState *chr)
2240 FDCharDriver *s = chr->opaque;
2242 if (s->fd_in >= 0) {
2243 if (nographic && s->fd_in == 0) {
2245 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2252 /* open a character device to a unix fd */
2253 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2255 CharDriverState *chr;
2258 chr = qemu_mallocz(sizeof(CharDriverState));
2261 s = qemu_mallocz(sizeof(FDCharDriver));
2269 chr->chr_write = fd_chr_write;
2270 chr->chr_update_read_handler = fd_chr_update_read_handler;
2271 chr->chr_close = fd_chr_close;
2273 qemu_chr_reset(chr);
2278 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2282 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2285 return qemu_chr_open_fd(-1, fd_out);
2288 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2291 char filename_in[256], filename_out[256];
2293 snprintf(filename_in, 256, "%s.in", filename);
2294 snprintf(filename_out, 256, "%s.out", filename);
2295 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2296 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2297 if (fd_in < 0 || fd_out < 0) {
2302 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2306 return qemu_chr_open_fd(fd_in, fd_out);
2310 /* for STDIO, we handle the case where several clients use it
2313 #define TERM_FIFO_MAX_SIZE 1
2315 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2316 static int term_fifo_size;
2318 static int stdio_read_poll(void *opaque)
2320 CharDriverState *chr = opaque;
2322 /* try to flush the queue if needed */
2323 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2324 qemu_chr_read(chr, term_fifo, 1);
2327 /* see if we can absorb more chars */
2328 if (term_fifo_size == 0)
2334 static void stdio_read(void *opaque)
2338 CharDriverState *chr = opaque;
2340 size = read(0, buf, 1);
2342 /* stdin has been closed. Remove it from the active list. */
2343 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2347 if (qemu_chr_can_read(chr) > 0) {
2348 qemu_chr_read(chr, buf, 1);
2349 } else if (term_fifo_size == 0) {
2350 term_fifo[term_fifo_size++] = buf[0];
2355 /* init terminal so that we can grab keys */
2356 static struct termios oldtty;
2357 static int old_fd0_flags;
2358 static int term_atexit_done;
2360 static void term_exit(void)
2362 tcsetattr (0, TCSANOW, &oldtty);
2363 fcntl(0, F_SETFL, old_fd0_flags);
2366 static void term_init(void)
2370 tcgetattr (0, &tty);
2372 old_fd0_flags = fcntl(0, F_GETFL);
2374 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2375 |INLCR|IGNCR|ICRNL|IXON);
2376 tty.c_oflag |= OPOST;
2377 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2378 /* if graphical mode, we allow Ctrl-C handling */
2380 tty.c_lflag &= ~ISIG;
2381 tty.c_cflag &= ~(CSIZE|PARENB);
2384 tty.c_cc[VTIME] = 0;
2386 tcsetattr (0, TCSANOW, &tty);
2388 if (!term_atexit_done++)
2391 fcntl(0, F_SETFL, O_NONBLOCK);
2394 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2398 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2402 static CharDriverState *qemu_chr_open_stdio(void)
2404 CharDriverState *chr;
2406 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2408 chr = qemu_chr_open_fd(0, 1);
2409 chr->chr_close = qemu_chr_close_stdio;
2410 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2418 /* Once Solaris has openpty(), this is going to be removed. */
2419 int openpty(int *amaster, int *aslave, char *name,
2420 struct termios *termp, struct winsize *winp)
2423 int mfd = -1, sfd = -1;
2425 *amaster = *aslave = -1;
2427 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2431 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2434 if ((slave = ptsname(mfd)) == NULL)
2437 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2440 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2441 (termp != NULL && tcgetattr(sfd, termp) < 0))
2449 ioctl(sfd, TIOCSWINSZ, winp);
2460 void cfmakeraw (struct termios *termios_p)
2462 termios_p->c_iflag &=
2463 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2464 termios_p->c_oflag &= ~OPOST;
2465 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2466 termios_p->c_cflag &= ~(CSIZE|PARENB);
2467 termios_p->c_cflag |= CS8;
2469 termios_p->c_cc[VMIN] = 0;
2470 termios_p->c_cc[VTIME] = 0;
2474 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2475 || defined(__NetBSD__) || defined(__OpenBSD__)
2485 static void pty_chr_update_read_handler(CharDriverState *chr);
2486 static void pty_chr_state(CharDriverState *chr, int connected);
2488 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2490 PtyCharDriver *s = chr->opaque;
2492 if (!s->connected) {
2493 /* guest sends data, check for (re-)connect */
2494 pty_chr_update_read_handler(chr);
2497 return unix_write(s->fd, buf, len);
2500 static int pty_chr_read_poll(void *opaque)
2502 CharDriverState *chr = opaque;
2503 PtyCharDriver *s = chr->opaque;
2505 s->read_bytes = qemu_chr_can_read(chr);
2506 return s->read_bytes;
2509 static void pty_chr_read(void *opaque)
2511 CharDriverState *chr = opaque;
2512 PtyCharDriver *s = chr->opaque;
2517 if (len > s->read_bytes)
2518 len = s->read_bytes;
2521 size = read(s->fd, buf, len);
2522 if ((size == -1 && errno == EIO) ||
2524 pty_chr_state(chr, 0);
2528 pty_chr_state(chr, 1);
2529 qemu_chr_read(chr, buf, size);
2533 static void pty_chr_update_read_handler(CharDriverState *chr)
2535 PtyCharDriver *s = chr->opaque;
2537 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2538 pty_chr_read, NULL, chr);
2541 * Short timeout here: just need wait long enougth that qemu makes
2542 * it through the poll loop once. When reconnected we want a
2543 * short timeout so we notice it almost instantly. Otherwise
2544 * read() gives us -EIO instantly, making pty_chr_state() reset the
2545 * timeout to the normal (much longer) poll interval before the
2548 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2551 static void pty_chr_state(CharDriverState *chr, int connected)
2553 PtyCharDriver *s = chr->opaque;
2556 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2559 /* (re-)connect poll interval for idle guests: once per second.
2560 * We check more frequently in case the guests sends data to
2561 * the virtual device linked to our pty. */
2562 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2565 qemu_chr_reset(chr);
2570 static void pty_chr_timer(void *opaque)
2572 struct CharDriverState *chr = opaque;
2573 PtyCharDriver *s = chr->opaque;
2578 /* If we arrive here without polling being cleared due
2579 * read returning -EIO, then we are (re-)connected */
2580 pty_chr_state(chr, 1);
2585 pty_chr_update_read_handler(chr);
2588 static void pty_chr_close(struct CharDriverState *chr)
2590 PtyCharDriver *s = chr->opaque;
2592 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2597 static CharDriverState *qemu_chr_open_pty(void)
2599 CharDriverState *chr;
2603 #if defined(__OpenBSD__)
2604 char pty_name[PATH_MAX];
2605 #define q_ptsname(x) pty_name
2607 char *pty_name = NULL;
2608 #define q_ptsname(x) ptsname(x)
2611 chr = qemu_mallocz(sizeof(CharDriverState));
2614 s = qemu_mallocz(sizeof(PtyCharDriver));
2620 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
2624 /* Set raw attributes on the pty. */
2626 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2629 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
2632 chr->chr_write = pty_chr_write;
2633 chr->chr_update_read_handler = pty_chr_update_read_handler;
2634 chr->chr_close = pty_chr_close;
2636 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2641 static void tty_serial_init(int fd, int speed,
2642 int parity, int data_bits, int stop_bits)
2648 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2649 speed, parity, data_bits, stop_bits);
2651 tcgetattr (fd, &tty);
2654 if (speed <= 50 * MARGIN)
2656 else if (speed <= 75 * MARGIN)
2658 else if (speed <= 300 * MARGIN)
2660 else if (speed <= 600 * MARGIN)
2662 else if (speed <= 1200 * MARGIN)
2664 else if (speed <= 2400 * MARGIN)
2666 else if (speed <= 4800 * MARGIN)
2668 else if (speed <= 9600 * MARGIN)
2670 else if (speed <= 19200 * MARGIN)
2672 else if (speed <= 38400 * MARGIN)
2674 else if (speed <= 57600 * MARGIN)
2676 else if (speed <= 115200 * MARGIN)
2681 cfsetispeed(&tty, spd);
2682 cfsetospeed(&tty, spd);
2684 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2685 |INLCR|IGNCR|ICRNL|IXON);
2686 tty.c_oflag |= OPOST;
2687 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2688 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2709 tty.c_cflag |= PARENB;
2712 tty.c_cflag |= PARENB | PARODD;
2716 tty.c_cflag |= CSTOPB;
2718 tcsetattr (fd, TCSANOW, &tty);
2721 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2723 FDCharDriver *s = chr->opaque;
2726 case CHR_IOCTL_SERIAL_SET_PARAMS:
2728 QEMUSerialSetParams *ssp = arg;
2729 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2730 ssp->data_bits, ssp->stop_bits);
2733 case CHR_IOCTL_SERIAL_SET_BREAK:
2735 int enable = *(int *)arg;
2737 tcsendbreak(s->fd_in, 1);
2740 case CHR_IOCTL_SERIAL_GET_TIOCM:
2743 int *targ = (int *)arg;
2744 ioctl(s->fd_in, TIOCMGET, &sarg);
2746 if (sarg | TIOCM_CTS)
2747 *targ |= CHR_TIOCM_CTS;
2748 if (sarg | TIOCM_CAR)
2749 *targ |= CHR_TIOCM_CAR;
2750 if (sarg | TIOCM_DSR)
2751 *targ |= CHR_TIOCM_DSR;
2752 if (sarg | TIOCM_RI)
2753 *targ |= CHR_TIOCM_RI;
2754 if (sarg | TIOCM_DTR)
2755 *targ |= CHR_TIOCM_DTR;
2756 if (sarg | TIOCM_RTS)
2757 *targ |= CHR_TIOCM_RTS;
2760 case CHR_IOCTL_SERIAL_SET_TIOCM:
2762 int sarg = *(int *)arg;
2764 if (sarg | CHR_TIOCM_DTR)
2766 if (sarg | CHR_TIOCM_RTS)
2768 ioctl(s->fd_in, TIOCMSET, &targ);
2777 static CharDriverState *qemu_chr_open_tty(const char *filename)
2779 CharDriverState *chr;
2782 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2783 tty_serial_init(fd, 115200, 'N', 8, 1);
2784 chr = qemu_chr_open_fd(fd, fd);
2789 chr->chr_ioctl = tty_serial_ioctl;
2790 qemu_chr_reset(chr);
2793 #else /* ! __linux__ && ! __sun__ */
2794 static CharDriverState *qemu_chr_open_pty(void)
2798 #endif /* __linux__ || __sun__ */
2800 #if defined(__linux__)
2804 } ParallelCharDriver;
2806 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2808 if (s->mode != mode) {
2810 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2817 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2819 ParallelCharDriver *drv = chr->opaque;
2824 case CHR_IOCTL_PP_READ_DATA:
2825 if (ioctl(fd, PPRDATA, &b) < 0)
2827 *(uint8_t *)arg = b;
2829 case CHR_IOCTL_PP_WRITE_DATA:
2830 b = *(uint8_t *)arg;
2831 if (ioctl(fd, PPWDATA, &b) < 0)
2834 case CHR_IOCTL_PP_READ_CONTROL:
2835 if (ioctl(fd, PPRCONTROL, &b) < 0)
2837 /* Linux gives only the lowest bits, and no way to know data
2838 direction! For better compatibility set the fixed upper
2840 *(uint8_t *)arg = b | 0xc0;
2842 case CHR_IOCTL_PP_WRITE_CONTROL:
2843 b = *(uint8_t *)arg;
2844 if (ioctl(fd, PPWCONTROL, &b) < 0)
2847 case CHR_IOCTL_PP_READ_STATUS:
2848 if (ioctl(fd, PPRSTATUS, &b) < 0)
2850 *(uint8_t *)arg = b;
2852 case CHR_IOCTL_PP_DATA_DIR:
2853 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2856 case CHR_IOCTL_PP_EPP_READ_ADDR:
2857 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2858 struct ParallelIOArg *parg = arg;
2859 int n = read(fd, parg->buffer, parg->count);
2860 if (n != parg->count) {
2865 case CHR_IOCTL_PP_EPP_READ:
2866 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2867 struct ParallelIOArg *parg = arg;
2868 int n = read(fd, parg->buffer, parg->count);
2869 if (n != parg->count) {
2874 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2875 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2876 struct ParallelIOArg *parg = arg;
2877 int n = write(fd, parg->buffer, parg->count);
2878 if (n != parg->count) {
2883 case CHR_IOCTL_PP_EPP_WRITE:
2884 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2885 struct ParallelIOArg *parg = arg;
2886 int n = write(fd, parg->buffer, parg->count);
2887 if (n != parg->count) {
2898 static void pp_close(CharDriverState *chr)
2900 ParallelCharDriver *drv = chr->opaque;
2903 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2904 ioctl(fd, PPRELEASE);
2909 static CharDriverState *qemu_chr_open_pp(const char *filename)
2911 CharDriverState *chr;
2912 ParallelCharDriver *drv;
2915 TFR(fd = open(filename, O_RDWR));
2919 if (ioctl(fd, PPCLAIM) < 0) {
2924 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2930 drv->mode = IEEE1284_MODE_COMPAT;
2932 chr = qemu_mallocz(sizeof(CharDriverState));
2938 chr->chr_write = null_chr_write;
2939 chr->chr_ioctl = pp_ioctl;
2940 chr->chr_close = pp_close;
2943 qemu_chr_reset(chr);
2947 #endif /* __linux__ */
2953 HANDLE hcom, hrecv, hsend;
2954 OVERLAPPED orecv, osend;
2959 #define NSENDBUF 2048
2960 #define NRECVBUF 2048
2961 #define MAXCONNECT 1
2962 #define NTIMEOUT 5000
2964 static int win_chr_poll(void *opaque);
2965 static int win_chr_pipe_poll(void *opaque);
2967 static void win_chr_close(CharDriverState *chr)
2969 WinCharState *s = chr->opaque;
2972 CloseHandle(s->hsend);
2976 CloseHandle(s->hrecv);
2980 CloseHandle(s->hcom);
2984 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2986 qemu_del_polling_cb(win_chr_poll, chr);
2989 static int win_chr_init(CharDriverState *chr, const char *filename)
2991 WinCharState *s = chr->opaque;
2993 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2998 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3000 fprintf(stderr, "Failed CreateEvent\n");
3003 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3005 fprintf(stderr, "Failed CreateEvent\n");
3009 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
3010 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
3011 if (s->hcom == INVALID_HANDLE_VALUE) {
3012 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
3017 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
3018 fprintf(stderr, "Failed SetupComm\n");
3022 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3023 size = sizeof(COMMCONFIG);
3024 GetDefaultCommConfig(filename, &comcfg, &size);
3025 comcfg.dcb.DCBlength = sizeof(DCB);
3026 CommConfigDialog(filename, NULL, &comcfg);
3028 if (!SetCommState(s->hcom, &comcfg.dcb)) {
3029 fprintf(stderr, "Failed SetCommState\n");
3033 if (!SetCommMask(s->hcom, EV_ERR)) {
3034 fprintf(stderr, "Failed SetCommMask\n");
3038 cto.ReadIntervalTimeout = MAXDWORD;
3039 if (!SetCommTimeouts(s->hcom, &cto)) {
3040 fprintf(stderr, "Failed SetCommTimeouts\n");
3044 if (!ClearCommError(s->hcom, &err, &comstat)) {
3045 fprintf(stderr, "Failed ClearCommError\n");
3048 qemu_add_polling_cb(win_chr_poll, chr);
3056 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3058 WinCharState *s = chr->opaque;
3059 DWORD len, ret, size, err;
3062 ZeroMemory(&s->osend, sizeof(s->osend));
3063 s->osend.hEvent = s->hsend;
3066 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3068 ret = WriteFile(s->hcom, buf, len, &size, NULL);
3070 err = GetLastError();
3071 if (err == ERROR_IO_PENDING) {
3072 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3090 static int win_chr_read_poll(CharDriverState *chr)
3092 WinCharState *s = chr->opaque;
3094 s->max_size = qemu_chr_can_read(chr);
3098 static void win_chr_readfile(CharDriverState *chr)
3100 WinCharState *s = chr->opaque;
3105 ZeroMemory(&s->orecv, sizeof(s->orecv));
3106 s->orecv.hEvent = s->hrecv;
3107 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3109 err = GetLastError();
3110 if (err == ERROR_IO_PENDING) {
3111 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3116 qemu_chr_read(chr, buf, size);
3120 static void win_chr_read(CharDriverState *chr)
3122 WinCharState *s = chr->opaque;
3124 if (s->len > s->max_size)
3125 s->len = s->max_size;
3129 win_chr_readfile(chr);
3132 static int win_chr_poll(void *opaque)
3134 CharDriverState *chr = opaque;
3135 WinCharState *s = chr->opaque;
3139 ClearCommError(s->hcom, &comerr, &status);
3140 if (status.cbInQue > 0) {
3141 s->len = status.cbInQue;
3142 win_chr_read_poll(chr);
3149 static CharDriverState *qemu_chr_open_win(const char *filename)
3151 CharDriverState *chr;
3154 chr = qemu_mallocz(sizeof(CharDriverState));
3157 s = qemu_mallocz(sizeof(WinCharState));
3163 chr->chr_write = win_chr_write;
3164 chr->chr_close = win_chr_close;
3166 if (win_chr_init(chr, filename) < 0) {
3171 qemu_chr_reset(chr);
3175 static int win_chr_pipe_poll(void *opaque)
3177 CharDriverState *chr = opaque;
3178 WinCharState *s = chr->opaque;
3181 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3184 win_chr_read_poll(chr);
3191 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3193 WinCharState *s = chr->opaque;
3201 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3203 fprintf(stderr, "Failed CreateEvent\n");
3206 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3208 fprintf(stderr, "Failed CreateEvent\n");
3212 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3213 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3214 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3216 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3217 if (s->hcom == INVALID_HANDLE_VALUE) {
3218 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3223 ZeroMemory(&ov, sizeof(ov));
3224 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3225 ret = ConnectNamedPipe(s->hcom, &ov);
3227 fprintf(stderr, "Failed ConnectNamedPipe\n");
3231 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3233 fprintf(stderr, "Failed GetOverlappedResult\n");
3235 CloseHandle(ov.hEvent);
3242 CloseHandle(ov.hEvent);
3245 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3254 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3256 CharDriverState *chr;
3259 chr = qemu_mallocz(sizeof(CharDriverState));
3262 s = qemu_mallocz(sizeof(WinCharState));
3268 chr->chr_write = win_chr_write;
3269 chr->chr_close = win_chr_close;
3271 if (win_chr_pipe_init(chr, filename) < 0) {
3276 qemu_chr_reset(chr);
3280 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3282 CharDriverState *chr;
3285 chr = qemu_mallocz(sizeof(CharDriverState));
3288 s = qemu_mallocz(sizeof(WinCharState));
3295 chr->chr_write = win_chr_write;
3296 qemu_chr_reset(chr);
3300 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3302 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3305 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3309 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3310 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3311 if (fd_out == INVALID_HANDLE_VALUE)
3314 return qemu_chr_open_win_file(fd_out);
3316 #endif /* !_WIN32 */
3318 /***********************************************************/
3319 /* UDP Net console */
3323 struct sockaddr_in daddr;
3330 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3332 NetCharDriver *s = chr->opaque;
3334 return sendto(s->fd, buf, len, 0,
3335 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3338 static int udp_chr_read_poll(void *opaque)
3340 CharDriverState *chr = opaque;
3341 NetCharDriver *s = chr->opaque;
3343 s->max_size = qemu_chr_can_read(chr);
3345 /* If there were any stray characters in the queue process them
3348 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3349 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3351 s->max_size = qemu_chr_can_read(chr);
3356 static void udp_chr_read(void *opaque)
3358 CharDriverState *chr = opaque;
3359 NetCharDriver *s = chr->opaque;
3361 if (s->max_size == 0)
3363 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3364 s->bufptr = s->bufcnt;
3369 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3370 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3372 s->max_size = qemu_chr_can_read(chr);
3376 static void udp_chr_update_read_handler(CharDriverState *chr)
3378 NetCharDriver *s = chr->opaque;
3381 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3382 udp_chr_read, NULL, chr);
3386 int parse_host_port(struct sockaddr_in *saddr, const char *str);
3388 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3390 int parse_host_src_port(struct sockaddr_in *haddr,
3391 struct sockaddr_in *saddr,
3394 static CharDriverState *qemu_chr_open_udp(const char *def)
3396 CharDriverState *chr = NULL;
3397 NetCharDriver *s = NULL;
3399 struct sockaddr_in saddr;
3401 chr = qemu_mallocz(sizeof(CharDriverState));
3404 s = qemu_mallocz(sizeof(NetCharDriver));
3408 fd = socket(PF_INET, SOCK_DGRAM, 0);
3410 perror("socket(PF_INET, SOCK_DGRAM)");
3414 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3415 printf("Could not parse: %s\n", def);
3419 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3429 chr->chr_write = udp_chr_write;
3430 chr->chr_update_read_handler = udp_chr_update_read_handler;
3443 /***********************************************************/
3444 /* TCP Net console */
3455 static void tcp_chr_accept(void *opaque);
3457 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3459 TCPCharDriver *s = chr->opaque;
3461 return send_all(s->fd, buf, len);
3463 /* XXX: indicate an error ? */
3468 static int tcp_chr_read_poll(void *opaque)
3470 CharDriverState *chr = opaque;
3471 TCPCharDriver *s = chr->opaque;
3474 s->max_size = qemu_chr_can_read(chr);
3479 #define IAC_BREAK 243
3480 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3482 uint8_t *buf, int *size)
3484 /* Handle any telnet client's basic IAC options to satisfy char by
3485 * char mode with no echo. All IAC options will be removed from
3486 * the buf and the do_telnetopt variable will be used to track the
3487 * state of the width of the IAC information.
3489 * IAC commands come in sets of 3 bytes with the exception of the
3490 * "IAC BREAK" command and the double IAC.
3496 for (i = 0; i < *size; i++) {
3497 if (s->do_telnetopt > 1) {
3498 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3499 /* Double IAC means send an IAC */
3503 s->do_telnetopt = 1;
3505 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3506 /* Handle IAC break commands by sending a serial break */
3507 qemu_chr_event(chr, CHR_EVENT_BREAK);
3512 if (s->do_telnetopt >= 4) {
3513 s->do_telnetopt = 1;
3516 if ((unsigned char)buf[i] == IAC) {
3517 s->do_telnetopt = 2;
3528 static void tcp_chr_read(void *opaque)
3530 CharDriverState *chr = opaque;
3531 TCPCharDriver *s = chr->opaque;
3535 if (!s->connected || s->max_size <= 0)
3538 if (len > s->max_size)
3540 size = recv(s->fd, buf, len, 0);
3542 /* connection closed */
3544 if (s->listen_fd >= 0) {
3545 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3547 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3550 } else if (size > 0) {
3551 if (s->do_telnetopt)
3552 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3554 qemu_chr_read(chr, buf, size);
3558 static void tcp_chr_connect(void *opaque)
3560 CharDriverState *chr = opaque;
3561 TCPCharDriver *s = chr->opaque;
3564 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3565 tcp_chr_read, NULL, chr);
3566 qemu_chr_reset(chr);
3569 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3570 static void tcp_chr_telnet_init(int fd)
3573 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3574 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3575 send(fd, (char *)buf, 3, 0);
3576 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3577 send(fd, (char *)buf, 3, 0);
3578 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3579 send(fd, (char *)buf, 3, 0);
3580 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3581 send(fd, (char *)buf, 3, 0);
3584 static void socket_set_nodelay(int fd)
3587 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3590 static void tcp_chr_accept(void *opaque)
3592 CharDriverState *chr = opaque;
3593 TCPCharDriver *s = chr->opaque;
3594 struct sockaddr_in saddr;
3596 struct sockaddr_un uaddr;
3598 struct sockaddr *addr;
3605 len = sizeof(uaddr);
3606 addr = (struct sockaddr *)&uaddr;
3610 len = sizeof(saddr);
3611 addr = (struct sockaddr *)&saddr;
3613 fd = accept(s->listen_fd, addr, &len);
3614 if (fd < 0 && errno != EINTR) {
3616 } else if (fd >= 0) {
3617 if (s->do_telnetopt)
3618 tcp_chr_telnet_init(fd);
3622 socket_set_nonblock(fd);
3624 socket_set_nodelay(fd);
3626 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3627 tcp_chr_connect(chr);
3630 static void tcp_chr_close(CharDriverState *chr)
3632 TCPCharDriver *s = chr->opaque;
3635 if (s->listen_fd >= 0)
3636 closesocket(s->listen_fd);
3640 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3644 CharDriverState *chr = NULL;
3645 TCPCharDriver *s = NULL;
3646 int fd = -1, ret, err, val;
3648 int is_waitconnect = 1;
3651 struct sockaddr_in saddr;
3653 struct sockaddr_un uaddr;
3655 struct sockaddr *addr;
3660 addr = (struct sockaddr *)&uaddr;
3661 addrlen = sizeof(uaddr);
3662 if (parse_unix_path(&uaddr, host_str) < 0)
3667 addr = (struct sockaddr *)&saddr;
3668 addrlen = sizeof(saddr);
3669 if (parse_host_port(&saddr, host_str) < 0)
3674 while((ptr = strchr(ptr,','))) {
3676 if (!strncmp(ptr,"server",6)) {
3678 } else if (!strncmp(ptr,"nowait",6)) {
3680 } else if (!strncmp(ptr,"nodelay",6)) {
3683 printf("Unknown option: %s\n", ptr);
3690 chr = qemu_mallocz(sizeof(CharDriverState));
3693 s = qemu_mallocz(sizeof(TCPCharDriver));
3699 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3702 fd = socket(PF_INET, SOCK_STREAM, 0);
3707 if (!is_waitconnect)
3708 socket_set_nonblock(fd);
3713 s->is_unix = is_unix;
3714 s->do_nodelay = do_nodelay && !is_unix;
3717 chr->chr_write = tcp_chr_write;
3718 chr->chr_close = tcp_chr_close;
3721 /* allow fast reuse */
3725 pstrcpy(path, sizeof(path), uaddr.sun_path);
3731 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3734 ret = bind(fd, addr, addrlen);
3738 ret = listen(fd, 0);
3743 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3745 s->do_telnetopt = 1;
3748 ret = connect(fd, addr, addrlen);
3750 err = socket_error();
3751 if (err == EINTR || err == EWOULDBLOCK) {
3752 } else if (err == EINPROGRESS) {
3755 } else if (err == WSAEALREADY) {
3767 socket_set_nodelay(fd);
3769 tcp_chr_connect(chr);
3771 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3774 if (is_listen && is_waitconnect) {
3775 printf("QEMU waiting for connection on: %s\n", host_str);
3776 tcp_chr_accept(chr);
3777 socket_set_nonblock(s->listen_fd);
3789 CharDriverState *qemu_chr_open(const char *filename)
3793 if (!strcmp(filename, "vc")) {
3794 return text_console_init(&display_state, 0);
3795 } else if (strstart(filename, "vc:", &p)) {
3796 return text_console_init(&display_state, p);
3797 } else if (!strcmp(filename, "null")) {
3798 return qemu_chr_open_null();
3800 if (strstart(filename, "tcp:", &p)) {
3801 return qemu_chr_open_tcp(p, 0, 0);
3803 if (strstart(filename, "telnet:", &p)) {
3804 return qemu_chr_open_tcp(p, 1, 0);
3806 if (strstart(filename, "udp:", &p)) {
3807 return qemu_chr_open_udp(p);
3809 if (strstart(filename, "mon:", &p)) {
3810 CharDriverState *drv = qemu_chr_open(p);
3812 drv = qemu_chr_open_mux(drv);
3813 monitor_init(drv, !nographic);
3816 printf("Unable to open driver: %s\n", p);
3820 if (strstart(filename, "unix:", &p)) {
3821 return qemu_chr_open_tcp(p, 0, 1);
3822 } else if (strstart(filename, "file:", &p)) {
3823 return qemu_chr_open_file_out(p);
3824 } else if (strstart(filename, "pipe:", &p)) {
3825 return qemu_chr_open_pipe(p);
3826 } else if (!strcmp(filename, "pty")) {
3827 return qemu_chr_open_pty();
3828 } else if (!strcmp(filename, "stdio")) {
3829 return qemu_chr_open_stdio();
3831 #if defined(__linux__)
3832 if (strstart(filename, "/dev/parport", NULL)) {
3833 return qemu_chr_open_pp(filename);
3836 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3837 || defined(__NetBSD__) || defined(__OpenBSD__)
3838 if (strstart(filename, "/dev/", NULL)) {
3839 return qemu_chr_open_tty(filename);
3843 if (strstart(filename, "COM", NULL)) {
3844 return qemu_chr_open_win(filename);
3846 if (strstart(filename, "pipe:", &p)) {
3847 return qemu_chr_open_win_pipe(p);
3849 if (strstart(filename, "con:", NULL)) {
3850 return qemu_chr_open_win_con(filename);
3852 if (strstart(filename, "file:", &p)) {
3853 return qemu_chr_open_win_file_out(p);
3856 #ifdef CONFIG_BRLAPI
3857 if (!strcmp(filename, "braille")) {
3858 return chr_baum_init();
3866 void qemu_chr_close(CharDriverState *chr)
3869 chr->chr_close(chr);
3873 /***********************************************************/
3874 /* network device redirectors */
3876 __attribute__ (( unused ))
3877 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3881 for(i=0;i<size;i+=16) {
3885 fprintf(f, "%08x ", i);
3888 fprintf(f, " %02x", buf[i+j]);
3893 for(j=0;j<len;j++) {
3895 if (c < ' ' || c > '~')
3897 fprintf(f, "%c", c);
3903 static int parse_macaddr(uint8_t *macaddr, const char *p)
3910 offset = strtol(p, &last_char, 0);
3911 if (0 == errno && '\0' == *last_char &&
3912 offset >= 0 && offset <= 0xFFFFFF) {
3913 macaddr[3] = (offset & 0xFF0000) >> 16;
3914 macaddr[4] = (offset & 0xFF00) >> 8;
3915 macaddr[5] = offset & 0xFF;
3918 for(i = 0; i < 6; i++) {
3919 macaddr[i] = strtol(p, (char **)&p, 16);
3924 if (*p != ':' && *p != '-')
3935 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3940 p1 = strchr(p, sep);
3946 if (len > buf_size - 1)
3948 memcpy(buf, p, len);
3955 int parse_host_src_port(struct sockaddr_in *haddr,
3956 struct sockaddr_in *saddr,
3957 const char *input_str)
3959 char *str = strdup(input_str);
3960 char *host_str = str;
3962 const char *src_str2;
3966 * Chop off any extra arguments at the end of the string which
3967 * would start with a comma, then fill in the src port information
3968 * if it was provided else use the "any address" and "any port".
3970 if ((ptr = strchr(str,',')))
3973 if ((src_str = strchr(input_str,'@'))) {
3978 if (parse_host_port(haddr, host_str) < 0)
3982 if (!src_str || *src_str == '\0')
3985 if (parse_host_port(saddr, src_str2) < 0)
3996 int parse_host_port(struct sockaddr_in *saddr, const char *str)
4004 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4006 saddr->sin_family = AF_INET;
4007 if (buf[0] == '\0') {
4008 saddr->sin_addr.s_addr = 0;
4010 if (isdigit(buf[0])) {
4011 if (!inet_aton(buf, &saddr->sin_addr))
4014 if ((he = gethostbyname(buf)) == NULL)
4016 saddr->sin_addr = *(struct in_addr *)he->h_addr;
4019 port = strtol(p, (char **)&r, 0);
4022 saddr->sin_port = htons(port);
4027 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4032 len = MIN(108, strlen(str));
4033 p = strchr(str, ',');
4035 len = MIN(len, p - str);
4037 memset(uaddr, 0, sizeof(*uaddr));
4039 uaddr->sun_family = AF_UNIX;
4040 memcpy(uaddr->sun_path, str, len);
4046 /* find or alloc a new VLAN */
4047 VLANState *qemu_find_vlan(int id)
4049 VLANState **pvlan, *vlan;
4050 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4054 vlan = qemu_mallocz(sizeof(VLANState));
4059 pvlan = &first_vlan;
4060 while (*pvlan != NULL)
4061 pvlan = &(*pvlan)->next;
4066 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4067 IOReadHandler *fd_read,
4068 IOCanRWHandler *fd_can_read,
4071 VLANClientState *vc, **pvc;
4072 vc = qemu_mallocz(sizeof(VLANClientState));
4075 vc->fd_read = fd_read;
4076 vc->fd_can_read = fd_can_read;
4077 vc->opaque = opaque;
4081 pvc = &vlan->first_client;
4082 while (*pvc != NULL)
4083 pvc = &(*pvc)->next;
4088 void qemu_del_vlan_client(VLANClientState *vc)
4090 VLANClientState **pvc = &vc->vlan->first_client;
4092 while (*pvc != NULL)
4098 pvc = &(*pvc)->next;
4101 int qemu_can_send_packet(VLANClientState *vc1)
4103 VLANState *vlan = vc1->vlan;
4104 VLANClientState *vc;
4106 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4108 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4115 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4117 VLANState *vlan = vc1->vlan;
4118 VLANClientState *vc;
4121 printf("vlan %d send:\n", vlan->id);
4122 hex_dump(stdout, buf, size);
4124 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4126 vc->fd_read(vc->opaque, buf, size);
4131 #if defined(CONFIG_SLIRP)
4133 /* slirp network adapter */
4135 static int slirp_inited;
4136 static VLANClientState *slirp_vc;
4138 int slirp_can_output(void)
4140 return !slirp_vc || qemu_can_send_packet(slirp_vc);
4143 void slirp_output(const uint8_t *pkt, int pkt_len)
4146 printf("slirp output:\n");
4147 hex_dump(stdout, pkt, pkt_len);
4151 qemu_send_packet(slirp_vc, pkt, pkt_len);
4154 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4157 printf("slirp input:\n");
4158 hex_dump(stdout, buf, size);
4160 slirp_input(buf, size);
4163 static int net_slirp_init(VLANState *vlan)
4165 if (!slirp_inited) {
4169 slirp_vc = qemu_new_vlan_client(vlan,
4170 slirp_receive, NULL, NULL);
4171 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4175 static void net_slirp_redir(const char *redir_str)
4180 struct in_addr guest_addr;
4181 int host_port, guest_port;
4183 if (!slirp_inited) {
4189 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4191 if (!strcmp(buf, "tcp")) {
4193 } else if (!strcmp(buf, "udp")) {
4199 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4201 host_port = strtol(buf, &r, 0);
4205 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4207 if (buf[0] == '\0') {
4208 pstrcpy(buf, sizeof(buf), "10.0.2.15");
4210 if (!inet_aton(buf, &guest_addr))
4213 guest_port = strtol(p, &r, 0);
4217 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4218 fprintf(stderr, "qemu: could not set up redirection\n");
4223 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4231 static void erase_dir(char *dir_name)
4235 char filename[1024];
4237 /* erase all the files in the directory */
4238 if ((d = opendir(dir_name)) != 0) {
4243 if (strcmp(de->d_name, ".") != 0 &&
4244 strcmp(de->d_name, "..") != 0) {
4245 snprintf(filename, sizeof(filename), "%s/%s",
4246 smb_dir, de->d_name);
4247 if (unlink(filename) != 0) /* is it a directory? */
4248 erase_dir(filename);
4256 /* automatic user mode samba server configuration */
4257 static void smb_exit(void)
4262 /* automatic user mode samba server configuration */
4263 static void net_slirp_smb(const char *exported_dir)
4265 char smb_conf[1024];
4266 char smb_cmdline[1024];
4269 if (!slirp_inited) {
4274 /* XXX: better tmp dir construction */
4275 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4276 if (mkdir(smb_dir, 0700) < 0) {
4277 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4280 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4282 f = fopen(smb_conf, "w");
4284 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4291 "socket address=127.0.0.1\n"
4292 "pid directory=%s\n"
4293 "lock directory=%s\n"
4294 "log file=%s/log.smbd\n"
4295 "smb passwd file=%s/smbpasswd\n"
4296 "security = share\n"
4311 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4312 SMBD_COMMAND, smb_conf);
4314 slirp_add_exec(0, smb_cmdline, 4, 139);
4317 #endif /* !defined(_WIN32) */
4318 void do_info_slirp(void)
4323 #endif /* CONFIG_SLIRP */
4325 #if !defined(_WIN32)
4327 typedef struct TAPState {
4328 VLANClientState *vc;
4330 char down_script[1024];
4333 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4335 TAPState *s = opaque;
4338 ret = write(s->fd, buf, size);
4339 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4346 static void tap_send(void *opaque)
4348 TAPState *s = opaque;
4355 sbuf.maxlen = sizeof(buf);
4357 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4359 size = read(s->fd, buf, sizeof(buf));
4362 qemu_send_packet(s->vc, buf, size);
4368 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4372 s = qemu_mallocz(sizeof(TAPState));
4376 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4377 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4378 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4382 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4383 static int tap_open(char *ifname, int ifname_size)
4389 TFR(fd = open("/dev/tap", O_RDWR));
4391 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4396 dev = devname(s.st_rdev, S_IFCHR);
4397 pstrcpy(ifname, ifname_size, dev);
4399 fcntl(fd, F_SETFL, O_NONBLOCK);
4402 #elif defined(__sun__)
4403 #define TUNNEWPPA (('T'<<16) | 0x0001)
4405 * Allocate TAP device, returns opened fd.
4406 * Stores dev name in the first arg(must be large enough).
4408 int tap_alloc(char *dev, size_t dev_size)
4410 int tap_fd, if_fd, ppa = -1;
4411 static int ip_fd = 0;
4414 static int arp_fd = 0;
4415 int ip_muxid, arp_muxid;
4416 struct strioctl strioc_if, strioc_ppa;
4417 int link_type = I_PLINK;;
4419 char actual_name[32] = "";
4421 memset(&ifr, 0x0, sizeof(ifr));
4425 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4429 /* Check if IP device was opened */
4433 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4435 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4439 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4441 syslog(LOG_ERR, "Can't open /dev/tap");
4445 /* Assign a new PPA and get its unit number. */
4446 strioc_ppa.ic_cmd = TUNNEWPPA;
4447 strioc_ppa.ic_timout = 0;
4448 strioc_ppa.ic_len = sizeof(ppa);
4449 strioc_ppa.ic_dp = (char *)&ppa;
4450 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4451 syslog (LOG_ERR, "Can't assign new interface");
4453 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4455 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4458 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4459 syslog(LOG_ERR, "Can't push IP module");
4463 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4464 syslog(LOG_ERR, "Can't get flags\n");
4466 snprintf (actual_name, 32, "tap%d", ppa);
4467 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4470 /* Assign ppa according to the unit number returned by tun device */
4472 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4473 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4474 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4475 syslog (LOG_ERR, "Can't get flags\n");
4476 /* Push arp module to if_fd */
4477 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4478 syslog (LOG_ERR, "Can't push ARP module (2)");
4480 /* Push arp module to ip_fd */
4481 if (ioctl (ip_fd, I_POP, NULL) < 0)
4482 syslog (LOG_ERR, "I_POP failed\n");
4483 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4484 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4486 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4488 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4490 /* Set ifname to arp */
4491 strioc_if.ic_cmd = SIOCSLIFNAME;
4492 strioc_if.ic_timout = 0;
4493 strioc_if.ic_len = sizeof(ifr);
4494 strioc_if.ic_dp = (char *)𝔦
4495 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4496 syslog (LOG_ERR, "Can't set ifname to arp\n");
4499 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4500 syslog(LOG_ERR, "Can't link TAP device to IP");
4504 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4505 syslog (LOG_ERR, "Can't link TAP device to ARP");
4509 memset(&ifr, 0x0, sizeof(ifr));
4510 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4511 ifr.lifr_ip_muxid = ip_muxid;
4512 ifr.lifr_arp_muxid = arp_muxid;
4514 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4516 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4517 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4518 syslog (LOG_ERR, "Can't set multiplexor id");
4521 snprintf(dev, dev_size, "tap%d", ppa);
4525 static int tap_open(char *ifname, int ifname_size)
4529 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
4530 fprintf(stderr, "Cannot allocate TAP device\n");
4533 pstrcpy(ifname, ifname_size, dev);
4534 fcntl(fd, F_SETFL, O_NONBLOCK);
4538 static int tap_open(char *ifname, int ifname_size)
4543 TFR(fd = open("/dev/net/tun", O_RDWR));
4545 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4548 memset(&ifr, 0, sizeof(ifr));
4549 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4550 if (ifname[0] != '\0')
4551 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4553 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4554 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4556 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4560 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4561 fcntl(fd, F_SETFL, O_NONBLOCK);
4566 static int launch_script(const char *setup_script, const char *ifname, int fd)
4572 /* try to launch network script */
4576 int open_max = sysconf (_SC_OPEN_MAX), i;
4577 for (i = 0; i < open_max; i++)
4578 if (i != STDIN_FILENO &&
4579 i != STDOUT_FILENO &&
4580 i != STDERR_FILENO &&
4585 *parg++ = (char *)setup_script;
4586 *parg++ = (char *)ifname;
4588 execv(setup_script, args);
4591 while (waitpid(pid, &status, 0) != pid);
4592 if (!WIFEXITED(status) ||
4593 WEXITSTATUS(status) != 0) {
4594 fprintf(stderr, "%s: could not launch network script\n",
4602 static int net_tap_init(VLANState *vlan, const char *ifname1,
4603 const char *setup_script, const char *down_script)
4609 if (ifname1 != NULL)
4610 pstrcpy(ifname, sizeof(ifname), ifname1);
4613 TFR(fd = tap_open(ifname, sizeof(ifname)));
4617 if (!setup_script || !strcmp(setup_script, "no"))
4619 if (setup_script[0] != '\0') {
4620 if (launch_script(setup_script, ifname, fd))
4623 s = net_tap_fd_init(vlan, fd);
4626 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4627 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4628 if (down_script && strcmp(down_script, "no"))
4629 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4633 #endif /* !_WIN32 */
4635 #if defined(CONFIG_VDE)
4636 typedef struct VDEState {
4637 VLANClientState *vc;
4641 static void vde_to_qemu(void *opaque)
4643 VDEState *s = opaque;
4647 size = vde_recv(s->vde, buf, sizeof(buf), 0);
4649 qemu_send_packet(s->vc, buf, size);
4653 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4655 VDEState *s = opaque;
4658 ret = vde_send(s->vde, buf, size, 0);
4659 if (ret < 0 && errno == EINTR) {
4666 static int net_vde_init(VLANState *vlan, const char *sock, int port,
4667 const char *group, int mode)
4670 char *init_group = strlen(group) ? (char *)group : NULL;
4671 char *init_sock = strlen(sock) ? (char *)sock : NULL;
4673 struct vde_open_args args = {
4675 .group = init_group,
4679 s = qemu_mallocz(sizeof(VDEState));
4682 s->vde = vde_open(init_sock, "QEMU", &args);
4687 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4688 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4689 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4690 sock, vde_datafd(s->vde));
4695 /* network connection */
4696 typedef struct NetSocketState {
4697 VLANClientState *vc;
4699 int state; /* 0 = getting length, 1 = getting data */
4703 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4706 typedef struct NetSocketListenState {
4709 } NetSocketListenState;
4711 /* XXX: we consider we can send the whole packet without blocking */
4712 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4714 NetSocketState *s = opaque;
4718 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4719 send_all(s->fd, buf, size);
4722 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4724 NetSocketState *s = opaque;
4725 sendto(s->fd, buf, size, 0,
4726 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4729 static void net_socket_send(void *opaque)
4731 NetSocketState *s = opaque;
4736 size = recv(s->fd, buf1, sizeof(buf1), 0);
4738 err = socket_error();
4739 if (err != EWOULDBLOCK)
4741 } else if (size == 0) {
4742 /* end of connection */
4744 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4750 /* reassemble a packet from the network */
4756 memcpy(s->buf + s->index, buf, l);
4760 if (s->index == 4) {
4762 s->packet_len = ntohl(*(uint32_t *)s->buf);
4768 l = s->packet_len - s->index;
4771 memcpy(s->buf + s->index, buf, l);
4775 if (s->index >= s->packet_len) {
4776 qemu_send_packet(s->vc, s->buf, s->packet_len);
4785 static void net_socket_send_dgram(void *opaque)
4787 NetSocketState *s = opaque;
4790 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4794 /* end of connection */
4795 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4798 qemu_send_packet(s->vc, s->buf, size);
4801 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4806 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4807 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4808 inet_ntoa(mcastaddr->sin_addr),
4809 (int)ntohl(mcastaddr->sin_addr.s_addr));
4813 fd = socket(PF_INET, SOCK_DGRAM, 0);
4815 perror("socket(PF_INET, SOCK_DGRAM)");
4820 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4821 (const char *)&val, sizeof(val));
4823 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4827 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4833 /* Add host to multicast group */
4834 imr.imr_multiaddr = mcastaddr->sin_addr;
4835 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4837 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4838 (const char *)&imr, sizeof(struct ip_mreq));
4840 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4844 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4846 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4847 (const char *)&val, sizeof(val));
4849 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4853 socket_set_nonblock(fd);
4861 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4864 struct sockaddr_in saddr;
4866 socklen_t saddr_len;
4869 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4870 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4871 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4875 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4877 if (saddr.sin_addr.s_addr==0) {
4878 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4882 /* clone dgram socket */
4883 newfd = net_socket_mcast_create(&saddr);
4885 /* error already reported by net_socket_mcast_create() */
4889 /* clone newfd to fd, close newfd */
4894 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4895 fd, strerror(errno));
4900 s = qemu_mallocz(sizeof(NetSocketState));
4905 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4906 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4908 /* mcast: save bound address as dst */
4909 if (is_connected) s->dgram_dst=saddr;
4911 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4912 "socket: fd=%d (%s mcast=%s:%d)",
4913 fd, is_connected? "cloned" : "",
4914 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4918 static void net_socket_connect(void *opaque)
4920 NetSocketState *s = opaque;
4921 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4924 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4928 s = qemu_mallocz(sizeof(NetSocketState));
4932 s->vc = qemu_new_vlan_client(vlan,
4933 net_socket_receive, NULL, s);
4934 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4935 "socket: fd=%d", fd);
4937 net_socket_connect(s);
4939 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4944 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4947 int so_type=-1, optlen=sizeof(so_type);
4949 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4950 (socklen_t *)&optlen)< 0) {
4951 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4956 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4958 return net_socket_fd_init_stream(vlan, fd, is_connected);
4960 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4961 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4962 return net_socket_fd_init_stream(vlan, fd, is_connected);
4967 static void net_socket_accept(void *opaque)
4969 NetSocketListenState *s = opaque;
4971 struct sockaddr_in saddr;
4976 len = sizeof(saddr);
4977 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4978 if (fd < 0 && errno != EINTR) {
4980 } else if (fd >= 0) {
4984 s1 = net_socket_fd_init(s->vlan, fd, 1);
4988 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4989 "socket: connection from %s:%d",
4990 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4994 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4996 NetSocketListenState *s;
4998 struct sockaddr_in saddr;
5000 if (parse_host_port(&saddr, host_str) < 0)
5003 s = qemu_mallocz(sizeof(NetSocketListenState));
5007 fd = socket(PF_INET, SOCK_STREAM, 0);
5012 socket_set_nonblock(fd);
5014 /* allow fast reuse */
5016 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5018 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5023 ret = listen(fd, 0);
5030 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5034 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5037 int fd, connected, ret, err;
5038 struct sockaddr_in saddr;
5040 if (parse_host_port(&saddr, host_str) < 0)
5043 fd = socket(PF_INET, SOCK_STREAM, 0);
5048 socket_set_nonblock(fd);
5052 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5054 err = socket_error();
5055 if (err == EINTR || err == EWOULDBLOCK) {
5056 } else if (err == EINPROGRESS) {
5059 } else if (err == WSAEALREADY) {
5072 s = net_socket_fd_init(vlan, fd, connected);
5075 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5076 "socket: connect to %s:%d",
5077 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5081 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5085 struct sockaddr_in saddr;
5087 if (parse_host_port(&saddr, host_str) < 0)
5091 fd = net_socket_mcast_create(&saddr);
5095 s = net_socket_fd_init(vlan, fd, 0);
5099 s->dgram_dst = saddr;
5101 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5102 "socket: mcast=%s:%d",
5103 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5108 static const char *get_opt_name(char *buf, int buf_size, const char *p)
5113 while (*p != '\0' && *p != '=') {
5114 if (q && (q - buf) < buf_size - 1)
5124 static const char *get_opt_value(char *buf, int buf_size, const char *p)
5129 while (*p != '\0') {
5131 if (*(p + 1) != ',')
5135 if (q && (q - buf) < buf_size - 1)
5145 static int get_param_value(char *buf, int buf_size,
5146 const char *tag, const char *str)
5153 p = get_opt_name(option, sizeof(option), p);
5157 if (!strcmp(tag, option)) {
5158 (void)get_opt_value(buf, buf_size, p);
5161 p = get_opt_value(NULL, 0, p);
5170 static int check_params(char *buf, int buf_size,
5171 const char * const *params, const char *str)
5178 p = get_opt_name(buf, buf_size, p);
5182 for(i = 0; params[i] != NULL; i++)
5183 if (!strcmp(params[i], buf))
5185 if (params[i] == NULL)
5187 p = get_opt_value(NULL, 0, p);
5195 static int net_client_init(const char *device, const char *p)
5202 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5203 vlan_id = strtol(buf, NULL, 0);
5205 vlan = qemu_find_vlan(vlan_id);
5207 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5210 if (!strcmp(device, "nic")) {
5214 if (nb_nics >= MAX_NICS) {
5215 fprintf(stderr, "Too Many NICs\n");
5218 nd = &nd_table[nb_nics];
5219 macaddr = nd->macaddr;
5225 macaddr[5] = 0x56 + nb_nics;
5227 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5228 if (parse_macaddr(macaddr, buf) < 0) {
5229 fprintf(stderr, "invalid syntax for ethernet address\n");
5233 if (get_param_value(buf, sizeof(buf), "model", p)) {
5234 nd->model = strdup(buf);
5238 vlan->nb_guest_devs++;
5241 if (!strcmp(device, "none")) {
5242 /* does nothing. It is needed to signal that no network cards
5247 if (!strcmp(device, "user")) {
5248 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5249 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5251 vlan->nb_host_devs++;
5252 ret = net_slirp_init(vlan);
5256 if (!strcmp(device, "tap")) {
5258 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5259 fprintf(stderr, "tap: no interface name\n");
5262 vlan->nb_host_devs++;
5263 ret = tap_win32_init(vlan, ifname);
5266 if (!strcmp(device, "tap")) {
5268 char setup_script[1024], down_script[1024];
5270 vlan->nb_host_devs++;
5271 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5272 fd = strtol(buf, NULL, 0);
5273 fcntl(fd, F_SETFL, O_NONBLOCK);
5275 if (net_tap_fd_init(vlan, fd))
5278 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5281 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5282 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5284 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5285 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5287 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5291 if (!strcmp(device, "socket")) {
5292 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5294 fd = strtol(buf, NULL, 0);
5296 if (net_socket_fd_init(vlan, fd, 1))
5298 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5299 ret = net_socket_listen_init(vlan, buf);
5300 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5301 ret = net_socket_connect_init(vlan, buf);
5302 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5303 ret = net_socket_mcast_init(vlan, buf);
5305 fprintf(stderr, "Unknown socket options: %s\n", p);
5308 vlan->nb_host_devs++;
5311 if (!strcmp(device, "vde")) {
5312 char vde_sock[1024], vde_group[512];
5313 int vde_port, vde_mode;
5314 vlan->nb_host_devs++;
5315 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5318 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5319 vde_port = strtol(buf, NULL, 10);
5323 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5324 vde_group[0] = '\0';
5326 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5327 vde_mode = strtol(buf, NULL, 8);
5331 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5335 fprintf(stderr, "Unknown network device: %s\n", device);
5339 fprintf(stderr, "Could not initialize device '%s'\n", device);
5345 static int net_client_parse(const char *str)
5353 while (*p != '\0' && *p != ',') {
5354 if ((q - device) < sizeof(device) - 1)
5362 return net_client_init(device, p);
5365 void do_info_network(void)
5368 VLANClientState *vc;
5370 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5371 term_printf("VLAN %d devices:\n", vlan->id);
5372 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5373 term_printf(" %s\n", vc->info_str);
5377 #define HD_ALIAS "index=%d,media=disk"
5379 #define CDROM_ALIAS "index=1,media=cdrom"
5381 #define CDROM_ALIAS "index=2,media=cdrom"
5383 #define FD_ALIAS "index=%d,if=floppy"
5384 #define PFLASH_ALIAS "if=pflash"
5385 #define MTD_ALIAS "if=mtd"
5386 #define SD_ALIAS "index=0,if=sd"
5388 static int drive_add(const char *file, const char *fmt, ...)
5392 if (nb_drives_opt >= MAX_DRIVES) {
5393 fprintf(stderr, "qemu: too many drives\n");
5397 drives_opt[nb_drives_opt].file = file;
5399 vsnprintf(drives_opt[nb_drives_opt].opt,
5400 sizeof(drives_opt[0].opt), fmt, ap);
5403 return nb_drives_opt++;
5406 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5410 /* seek interface, bus and unit */
5412 for (index = 0; index < nb_drives; index++)
5413 if (drives_table[index].type == type &&
5414 drives_table[index].bus == bus &&
5415 drives_table[index].unit == unit)
5421 int drive_get_max_bus(BlockInterfaceType type)
5427 for (index = 0; index < nb_drives; index++) {
5428 if(drives_table[index].type == type &&
5429 drives_table[index].bus > max_bus)
5430 max_bus = drives_table[index].bus;
5435 static void bdrv_format_print(void *opaque, const char *name)
5437 fprintf(stderr, " %s", name);
5440 static int drive_init(struct drive_opt *arg, int snapshot,
5441 QEMUMachine *machine)
5446 const char *mediastr = "";
5447 BlockInterfaceType type;
5448 enum { MEDIA_DISK, MEDIA_CDROM } media;
5449 int bus_id, unit_id;
5450 int cyls, heads, secs, translation;
5451 BlockDriverState *bdrv;
5452 BlockDriver *drv = NULL;
5457 char *str = arg->opt;
5458 static const char * const params[] = { "bus", "unit", "if", "index",
5459 "cyls", "heads", "secs", "trans",
5460 "media", "snapshot", "file",
5461 "cache", "format", NULL };
5463 if (check_params(buf, sizeof(buf), params, str) < 0) {
5464 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5470 cyls = heads = secs = 0;
5473 translation = BIOS_ATA_TRANSLATION_AUTO;
5477 if (!strcmp(machine->name, "realview") ||
5478 !strcmp(machine->name, "SS-5") ||
5479 !strcmp(machine->name, "SS-10") ||
5480 !strcmp(machine->name, "SS-600MP") ||
5481 !strcmp(machine->name, "versatilepb") ||
5482 !strcmp(machine->name, "versatileab")) {
5484 max_devs = MAX_SCSI_DEVS;
5485 pstrcpy(devname, sizeof(devname), "scsi");
5488 max_devs = MAX_IDE_DEVS;
5489 pstrcpy(devname, sizeof(devname), "ide");
5493 /* extract parameters */
5495 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5496 bus_id = strtol(buf, NULL, 0);
5498 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5503 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5504 unit_id = strtol(buf, NULL, 0);
5506 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5511 if (get_param_value(buf, sizeof(buf), "if", str)) {
5512 pstrcpy(devname, sizeof(devname), buf);
5513 if (!strcmp(buf, "ide")) {
5515 max_devs = MAX_IDE_DEVS;
5516 } else if (!strcmp(buf, "scsi")) {
5518 max_devs = MAX_SCSI_DEVS;
5519 } else if (!strcmp(buf, "floppy")) {
5522 } else if (!strcmp(buf, "pflash")) {
5525 } else if (!strcmp(buf, "mtd")) {
5528 } else if (!strcmp(buf, "sd")) {
5532 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5537 if (get_param_value(buf, sizeof(buf), "index", str)) {
5538 index = strtol(buf, NULL, 0);
5540 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5545 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5546 cyls = strtol(buf, NULL, 0);
5549 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5550 heads = strtol(buf, NULL, 0);
5553 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5554 secs = strtol(buf, NULL, 0);
5557 if (cyls || heads || secs) {
5558 if (cyls < 1 || cyls > 16383) {
5559 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5562 if (heads < 1 || heads > 16) {
5563 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5566 if (secs < 1 || secs > 63) {
5567 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5572 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5575 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5579 if (!strcmp(buf, "none"))
5580 translation = BIOS_ATA_TRANSLATION_NONE;
5581 else if (!strcmp(buf, "lba"))
5582 translation = BIOS_ATA_TRANSLATION_LBA;
5583 else if (!strcmp(buf, "auto"))
5584 translation = BIOS_ATA_TRANSLATION_AUTO;
5586 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5591 if (get_param_value(buf, sizeof(buf), "media", str)) {
5592 if (!strcmp(buf, "disk")) {
5594 } else if (!strcmp(buf, "cdrom")) {
5595 if (cyls || secs || heads) {
5597 "qemu: '%s' invalid physical CHS format\n", str);
5600 media = MEDIA_CDROM;
5602 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5607 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5608 if (!strcmp(buf, "on"))
5610 else if (!strcmp(buf, "off"))
5613 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5618 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5619 if (!strcmp(buf, "off"))
5621 else if (!strcmp(buf, "on"))
5624 fprintf(stderr, "qemu: invalid cache option\n");
5629 if (get_param_value(buf, sizeof(buf), "format", str)) {
5630 if (strcmp(buf, "?") == 0) {
5631 fprintf(stderr, "qemu: Supported formats:");
5632 bdrv_iterate_format(bdrv_format_print, NULL);
5633 fprintf(stderr, "\n");
5636 drv = bdrv_find_format(buf);
5638 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5643 if (arg->file == NULL)
5644 get_param_value(file, sizeof(file), "file", str);
5646 pstrcpy(file, sizeof(file), arg->file);
5648 /* compute bus and unit according index */
5651 if (bus_id != 0 || unit_id != -1) {
5653 "qemu: '%s' index cannot be used with bus and unit\n", str);
5661 unit_id = index % max_devs;
5662 bus_id = index / max_devs;
5666 /* if user doesn't specify a unit_id,
5667 * try to find the first free
5670 if (unit_id == -1) {
5672 while (drive_get_index(type, bus_id, unit_id) != -1) {
5674 if (max_devs && unit_id >= max_devs) {
5675 unit_id -= max_devs;
5683 if (max_devs && unit_id >= max_devs) {
5684 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5685 str, unit_id, max_devs - 1);
5690 * ignore multiple definitions
5693 if (drive_get_index(type, bus_id, unit_id) != -1)
5698 if (type == IF_IDE || type == IF_SCSI)
5699 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5701 snprintf(buf, sizeof(buf), "%s%i%s%i",
5702 devname, bus_id, mediastr, unit_id);
5704 snprintf(buf, sizeof(buf), "%s%s%i",
5705 devname, mediastr, unit_id);
5706 bdrv = bdrv_new(buf);
5707 drives_table[nb_drives].bdrv = bdrv;
5708 drives_table[nb_drives].type = type;
5709 drives_table[nb_drives].bus = bus_id;
5710 drives_table[nb_drives].unit = unit_id;
5719 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5720 bdrv_set_translation_hint(bdrv, translation);
5724 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5729 /* FIXME: This isn't really a floppy, but it's a reasonable
5732 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5742 bdrv_flags |= BDRV_O_SNAPSHOT;
5744 bdrv_flags |= BDRV_O_DIRECT;
5745 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5746 fprintf(stderr, "qemu: could not open disk image %s\n",
5753 /***********************************************************/
5756 static USBPort *used_usb_ports;
5757 static USBPort *free_usb_ports;
5759 /* ??? Maybe change this to register a hub to keep track of the topology. */
5760 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5761 usb_attachfn attach)
5763 port->opaque = opaque;
5764 port->index = index;
5765 port->attach = attach;
5766 port->next = free_usb_ports;
5767 free_usb_ports = port;
5770 int usb_device_add_dev(USBDevice *dev)
5774 /* Find a USB port to add the device to. */
5775 port = free_usb_ports;
5779 /* Create a new hub and chain it on. */
5780 free_usb_ports = NULL;
5781 port->next = used_usb_ports;
5782 used_usb_ports = port;
5784 hub = usb_hub_init(VM_USB_HUB_SIZE);
5785 usb_attach(port, hub);
5786 port = free_usb_ports;
5789 free_usb_ports = port->next;
5790 port->next = used_usb_ports;
5791 used_usb_ports = port;
5792 usb_attach(port, dev);
5796 static int usb_device_add(const char *devname)
5801 if (!free_usb_ports)
5804 if (strstart(devname, "host:", &p)) {
5805 dev = usb_host_device_open(p);
5806 } else if (!strcmp(devname, "mouse")) {
5807 dev = usb_mouse_init();
5808 } else if (!strcmp(devname, "tablet")) {
5809 dev = usb_tablet_init();
5810 } else if (!strcmp(devname, "keyboard")) {
5811 dev = usb_keyboard_init();
5812 } else if (strstart(devname, "disk:", &p)) {
5813 dev = usb_msd_init(p);
5814 } else if (!strcmp(devname, "wacom-tablet")) {
5815 dev = usb_wacom_init();
5816 } else if (strstart(devname, "serial:", &p)) {
5817 dev = usb_serial_init(p);
5818 #ifdef CONFIG_BRLAPI
5819 } else if (!strcmp(devname, "braille")) {
5820 dev = usb_baum_init();
5822 } else if (strstart(devname, "net:", &p)) {
5825 if (net_client_init("nic", p) < 0)
5827 nd_table[nic].model = "usb";
5828 dev = usb_net_init(&nd_table[nic]);
5835 return usb_device_add_dev(dev);
5838 int usb_device_del_addr(int bus_num, int addr)
5844 if (!used_usb_ports)
5850 lastp = &used_usb_ports;
5851 port = used_usb_ports;
5852 while (port && port->dev->addr != addr) {
5853 lastp = &port->next;
5861 *lastp = port->next;
5862 usb_attach(port, NULL);
5863 dev->handle_destroy(dev);
5864 port->next = free_usb_ports;
5865 free_usb_ports = port;
5869 static int usb_device_del(const char *devname)
5874 if (strstart(devname, "host:", &p))
5875 return usb_host_device_close(p);
5877 if (!used_usb_ports)
5880 p = strchr(devname, '.');
5883 bus_num = strtoul(devname, NULL, 0);
5884 addr = strtoul(p + 1, NULL, 0);
5886 return usb_device_del_addr(bus_num, addr);
5889 void do_usb_add(const char *devname)
5891 usb_device_add(devname);
5894 void do_usb_del(const char *devname)
5896 usb_device_del(devname);
5903 const char *speed_str;
5906 term_printf("USB support not enabled\n");
5910 for (port = used_usb_ports; port; port = port->next) {
5914 switch(dev->speed) {
5918 case USB_SPEED_FULL:
5921 case USB_SPEED_HIGH:
5928 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5929 0, dev->addr, speed_str, dev->devname);
5933 /***********************************************************/
5934 /* PCMCIA/Cardbus */
5936 static struct pcmcia_socket_entry_s {
5937 struct pcmcia_socket_s *socket;
5938 struct pcmcia_socket_entry_s *next;
5939 } *pcmcia_sockets = 0;
5941 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5943 struct pcmcia_socket_entry_s *entry;
5945 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5946 entry->socket = socket;
5947 entry->next = pcmcia_sockets;
5948 pcmcia_sockets = entry;
5951 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5953 struct pcmcia_socket_entry_s *entry, **ptr;
5955 ptr = &pcmcia_sockets;
5956 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5957 if (entry->socket == socket) {
5963 void pcmcia_info(void)
5965 struct pcmcia_socket_entry_s *iter;
5966 if (!pcmcia_sockets)
5967 term_printf("No PCMCIA sockets\n");
5969 for (iter = pcmcia_sockets; iter; iter = iter->next)
5970 term_printf("%s: %s\n", iter->socket->slot_string,
5971 iter->socket->attached ? iter->socket->card_string :
5975 /***********************************************************/
5978 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5982 static void dumb_resize(DisplayState *ds, int w, int h)
5986 static void dumb_refresh(DisplayState *ds)
5988 #if defined(CONFIG_SDL)
5993 static void dumb_display_init(DisplayState *ds)
5998 ds->dpy_update = dumb_update;
5999 ds->dpy_resize = dumb_resize;
6000 ds->dpy_refresh = dumb_refresh;
6001 ds->gui_timer_interval = 500;
6005 /***********************************************************/
6008 #define MAX_IO_HANDLERS 64
6010 typedef struct IOHandlerRecord {
6012 IOCanRWHandler *fd_read_poll;
6014 IOHandler *fd_write;
6017 /* temporary data */
6019 struct IOHandlerRecord *next;
6022 static IOHandlerRecord *first_io_handler;
6024 /* XXX: fd_read_poll should be suppressed, but an API change is
6025 necessary in the character devices to suppress fd_can_read(). */
6026 int qemu_set_fd_handler2(int fd,
6027 IOCanRWHandler *fd_read_poll,
6029 IOHandler *fd_write,
6032 IOHandlerRecord **pioh, *ioh;
6034 if (!fd_read && !fd_write) {
6035 pioh = &first_io_handler;
6040 if (ioh->fd == fd) {
6047 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6051 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6054 ioh->next = first_io_handler;
6055 first_io_handler = ioh;
6058 ioh->fd_read_poll = fd_read_poll;
6059 ioh->fd_read = fd_read;
6060 ioh->fd_write = fd_write;
6061 ioh->opaque = opaque;
6067 int qemu_set_fd_handler(int fd,
6069 IOHandler *fd_write,
6072 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6075 /***********************************************************/
6076 /* Polling handling */
6078 typedef struct PollingEntry {
6081 struct PollingEntry *next;
6084 static PollingEntry *first_polling_entry;
6086 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6088 PollingEntry **ppe, *pe;
6089 pe = qemu_mallocz(sizeof(PollingEntry));
6093 pe->opaque = opaque;
6094 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6099 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6101 PollingEntry **ppe, *pe;
6102 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6104 if (pe->func == func && pe->opaque == opaque) {
6113 /***********************************************************/
6114 /* Wait objects support */
6115 typedef struct WaitObjects {
6117 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6118 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6119 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6122 static WaitObjects wait_objects = {0};
6124 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6126 WaitObjects *w = &wait_objects;
6128 if (w->num >= MAXIMUM_WAIT_OBJECTS)
6130 w->events[w->num] = handle;
6131 w->func[w->num] = func;
6132 w->opaque[w->num] = opaque;
6137 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6140 WaitObjects *w = &wait_objects;
6143 for (i = 0; i < w->num; i++) {
6144 if (w->events[i] == handle)
6147 w->events[i] = w->events[i + 1];
6148 w->func[i] = w->func[i + 1];
6149 w->opaque[i] = w->opaque[i + 1];
6157 /***********************************************************/
6158 /* savevm/loadvm support */
6160 #define IO_BUF_SIZE 32768
6164 BlockDriverState *bs;
6167 int64_t base_offset;
6168 int64_t buf_offset; /* start of buffer when writing, end of buffer
6171 int buf_size; /* 0 when writing */
6172 uint8_t buf[IO_BUF_SIZE];
6175 QEMUFile *qemu_fopen(const char *filename, const char *mode)
6179 f = qemu_mallocz(sizeof(QEMUFile));
6182 if (!strcmp(mode, "wb")) {
6184 } else if (!strcmp(mode, "rb")) {
6189 f->outfile = fopen(filename, mode);
6201 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6205 f = qemu_mallocz(sizeof(QEMUFile));
6210 f->is_writable = is_writable;
6211 f->base_offset = offset;
6215 void qemu_fflush(QEMUFile *f)
6217 if (!f->is_writable)
6219 if (f->buf_index > 0) {
6221 fseek(f->outfile, f->buf_offset, SEEK_SET);
6222 fwrite(f->buf, 1, f->buf_index, f->outfile);
6224 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
6225 f->buf, f->buf_index);
6227 f->buf_offset += f->buf_index;
6232 static void qemu_fill_buffer(QEMUFile *f)
6239 fseek(f->outfile, f->buf_offset, SEEK_SET);
6240 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
6244 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
6245 f->buf, IO_BUF_SIZE);
6251 f->buf_offset += len;
6254 void qemu_fclose(QEMUFile *f)
6264 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6268 l = IO_BUF_SIZE - f->buf_index;
6271 memcpy(f->buf + f->buf_index, buf, l);
6275 if (f->buf_index >= IO_BUF_SIZE)
6280 void qemu_put_byte(QEMUFile *f, int v)
6282 f->buf[f->buf_index++] = v;
6283 if (f->buf_index >= IO_BUF_SIZE)
6287 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6293 l = f->buf_size - f->buf_index;
6295 qemu_fill_buffer(f);
6296 l = f->buf_size - f->buf_index;
6302 memcpy(buf, f->buf + f->buf_index, l);
6307 return size1 - size;
6310 int qemu_get_byte(QEMUFile *f)
6312 if (f->buf_index >= f->buf_size) {
6313 qemu_fill_buffer(f);
6314 if (f->buf_index >= f->buf_size)
6317 return f->buf[f->buf_index++];
6320 int64_t qemu_ftell(QEMUFile *f)
6322 return f->buf_offset - f->buf_size + f->buf_index;
6325 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6327 if (whence == SEEK_SET) {
6329 } else if (whence == SEEK_CUR) {
6330 pos += qemu_ftell(f);
6332 /* SEEK_END not supported */
6335 if (f->is_writable) {
6337 f->buf_offset = pos;
6339 f->buf_offset = pos;
6346 void qemu_put_be16(QEMUFile *f, unsigned int v)
6348 qemu_put_byte(f, v >> 8);
6349 qemu_put_byte(f, v);
6352 void qemu_put_be32(QEMUFile *f, unsigned int v)
6354 qemu_put_byte(f, v >> 24);
6355 qemu_put_byte(f, v >> 16);
6356 qemu_put_byte(f, v >> 8);
6357 qemu_put_byte(f, v);
6360 void qemu_put_be64(QEMUFile *f, uint64_t v)
6362 qemu_put_be32(f, v >> 32);
6363 qemu_put_be32(f, v);
6366 unsigned int qemu_get_be16(QEMUFile *f)
6369 v = qemu_get_byte(f) << 8;
6370 v |= qemu_get_byte(f);
6374 unsigned int qemu_get_be32(QEMUFile *f)
6377 v = qemu_get_byte(f) << 24;
6378 v |= qemu_get_byte(f) << 16;
6379 v |= qemu_get_byte(f) << 8;
6380 v |= qemu_get_byte(f);
6384 uint64_t qemu_get_be64(QEMUFile *f)
6387 v = (uint64_t)qemu_get_be32(f) << 32;
6388 v |= qemu_get_be32(f);
6392 typedef struct SaveStateEntry {
6396 SaveStateHandler *save_state;
6397 LoadStateHandler *load_state;
6399 struct SaveStateEntry *next;
6402 static SaveStateEntry *first_se;
6404 /* TODO: Individual devices generally have very little idea about the rest
6405 of the system, so instance_id should be removed/replaced.
6406 Meanwhile pass -1 as instance_id if you do not already have a clearly
6407 distinguishing id for all instances of your device class. */
6408 int register_savevm(const char *idstr,
6411 SaveStateHandler *save_state,
6412 LoadStateHandler *load_state,
6415 SaveStateEntry *se, **pse;
6417 se = qemu_malloc(sizeof(SaveStateEntry));
6420 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6421 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6422 se->version_id = version_id;
6423 se->save_state = save_state;
6424 se->load_state = load_state;
6425 se->opaque = opaque;
6428 /* add at the end of list */
6430 while (*pse != NULL) {
6431 if (instance_id == -1
6432 && strcmp(se->idstr, (*pse)->idstr) == 0
6433 && se->instance_id <= (*pse)->instance_id)
6434 se->instance_id = (*pse)->instance_id + 1;
6435 pse = &(*pse)->next;
6441 #define QEMU_VM_FILE_MAGIC 0x5145564d
6442 #define QEMU_VM_FILE_VERSION 0x00000002
6444 static int qemu_savevm_state(QEMUFile *f)
6448 int64_t cur_pos, len_pos, total_len_pos;
6450 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6451 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6452 total_len_pos = qemu_ftell(f);
6453 qemu_put_be64(f, 0); /* total size */
6455 for(se = first_se; se != NULL; se = se->next) {
6456 if (se->save_state == NULL)
6457 /* this one has a loader only, for backwards compatibility */
6461 len = strlen(se->idstr);
6462 qemu_put_byte(f, len);
6463 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6465 qemu_put_be32(f, se->instance_id);
6466 qemu_put_be32(f, se->version_id);
6468 /* record size: filled later */
6469 len_pos = qemu_ftell(f);
6470 qemu_put_be32(f, 0);
6471 se->save_state(f, se->opaque);
6473 /* fill record size */
6474 cur_pos = qemu_ftell(f);
6475 len = cur_pos - len_pos - 4;
6476 qemu_fseek(f, len_pos, SEEK_SET);
6477 qemu_put_be32(f, len);
6478 qemu_fseek(f, cur_pos, SEEK_SET);
6480 cur_pos = qemu_ftell(f);
6481 qemu_fseek(f, total_len_pos, SEEK_SET);
6482 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6483 qemu_fseek(f, cur_pos, SEEK_SET);
6489 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6493 for(se = first_se; se != NULL; se = se->next) {
6494 if (!strcmp(se->idstr, idstr) &&
6495 instance_id == se->instance_id)
6501 static int qemu_loadvm_state(QEMUFile *f)
6504 int len, ret, instance_id, record_len, version_id;
6505 int64_t total_len, end_pos, cur_pos;
6509 v = qemu_get_be32(f);
6510 if (v != QEMU_VM_FILE_MAGIC)
6512 v = qemu_get_be32(f);
6513 if (v != QEMU_VM_FILE_VERSION) {
6518 total_len = qemu_get_be64(f);
6519 end_pos = total_len + qemu_ftell(f);
6521 if (qemu_ftell(f) >= end_pos)
6523 len = qemu_get_byte(f);
6524 qemu_get_buffer(f, (uint8_t *)idstr, len);
6526 instance_id = qemu_get_be32(f);
6527 version_id = qemu_get_be32(f);
6528 record_len = qemu_get_be32(f);
6530 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6531 idstr, instance_id, version_id, record_len);
6533 cur_pos = qemu_ftell(f);
6534 se = find_se(idstr, instance_id);
6536 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6537 instance_id, idstr);
6539 ret = se->load_state(f, se->opaque, version_id);
6541 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6542 instance_id, idstr);
6545 /* always seek to exact end of record */
6546 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6553 /* device can contain snapshots */
6554 static int bdrv_can_snapshot(BlockDriverState *bs)
6557 !bdrv_is_removable(bs) &&
6558 !bdrv_is_read_only(bs));
6561 /* device must be snapshots in order to have a reliable snapshot */
6562 static int bdrv_has_snapshot(BlockDriverState *bs)
6565 !bdrv_is_removable(bs) &&
6566 !bdrv_is_read_only(bs));
6569 static BlockDriverState *get_bs_snapshots(void)
6571 BlockDriverState *bs;
6575 return bs_snapshots;
6576 for(i = 0; i <= nb_drives; i++) {
6577 bs = drives_table[i].bdrv;
6578 if (bdrv_can_snapshot(bs))
6587 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6590 QEMUSnapshotInfo *sn_tab, *sn;
6594 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6597 for(i = 0; i < nb_sns; i++) {
6599 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6609 void do_savevm(const char *name)
6611 BlockDriverState *bs, *bs1;
6612 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6613 int must_delete, ret, i;
6614 BlockDriverInfo bdi1, *bdi = &bdi1;
6616 int saved_vm_running;
6623 bs = get_bs_snapshots();
6625 term_printf("No block device can accept snapshots\n");
6629 /* ??? Should this occur after vm_stop? */
6632 saved_vm_running = vm_running;
6637 ret = bdrv_snapshot_find(bs, old_sn, name);
6642 memset(sn, 0, sizeof(*sn));
6644 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6645 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6648 pstrcpy(sn->name, sizeof(sn->name), name);
6651 /* fill auxiliary fields */
6654 sn->date_sec = tb.time;
6655 sn->date_nsec = tb.millitm * 1000000;
6657 gettimeofday(&tv, NULL);
6658 sn->date_sec = tv.tv_sec;
6659 sn->date_nsec = tv.tv_usec * 1000;
6661 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6663 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6664 term_printf("Device %s does not support VM state snapshots\n",
6665 bdrv_get_device_name(bs));
6669 /* save the VM state */
6670 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6672 term_printf("Could not open VM state file\n");
6675 ret = qemu_savevm_state(f);
6676 sn->vm_state_size = qemu_ftell(f);
6679 term_printf("Error %d while writing VM\n", ret);
6683 /* create the snapshots */
6685 for(i = 0; i < nb_drives; i++) {
6686 bs1 = drives_table[i].bdrv;
6687 if (bdrv_has_snapshot(bs1)) {
6689 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6691 term_printf("Error while deleting snapshot on '%s'\n",
6692 bdrv_get_device_name(bs1));
6695 ret = bdrv_snapshot_create(bs1, sn);
6697 term_printf("Error while creating snapshot on '%s'\n",
6698 bdrv_get_device_name(bs1));
6704 if (saved_vm_running)
6708 void do_loadvm(const char *name)
6710 BlockDriverState *bs, *bs1;
6711 BlockDriverInfo bdi1, *bdi = &bdi1;
6714 int saved_vm_running;
6716 bs = get_bs_snapshots();
6718 term_printf("No block device supports snapshots\n");
6722 /* Flush all IO requests so they don't interfere with the new state. */
6725 saved_vm_running = vm_running;
6728 for(i = 0; i <= nb_drives; i++) {
6729 bs1 = drives_table[i].bdrv;
6730 if (bdrv_has_snapshot(bs1)) {
6731 ret = bdrv_snapshot_goto(bs1, name);
6734 term_printf("Warning: ");
6737 term_printf("Snapshots not supported on device '%s'\n",
6738 bdrv_get_device_name(bs1));
6741 term_printf("Could not find snapshot '%s' on device '%s'\n",
6742 name, bdrv_get_device_name(bs1));
6745 term_printf("Error %d while activating snapshot on '%s'\n",
6746 ret, bdrv_get_device_name(bs1));
6749 /* fatal on snapshot block device */
6756 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6757 term_printf("Device %s does not support VM state snapshots\n",
6758 bdrv_get_device_name(bs));
6762 /* restore the VM state */
6763 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6765 term_printf("Could not open VM state file\n");
6768 ret = qemu_loadvm_state(f);
6771 term_printf("Error %d while loading VM state\n", ret);
6774 if (saved_vm_running)
6778 void do_delvm(const char *name)
6780 BlockDriverState *bs, *bs1;
6783 bs = get_bs_snapshots();
6785 term_printf("No block device supports snapshots\n");
6789 for(i = 0; i <= nb_drives; i++) {
6790 bs1 = drives_table[i].bdrv;
6791 if (bdrv_has_snapshot(bs1)) {
6792 ret = bdrv_snapshot_delete(bs1, name);
6794 if (ret == -ENOTSUP)
6795 term_printf("Snapshots not supported on device '%s'\n",
6796 bdrv_get_device_name(bs1));
6798 term_printf("Error %d while deleting snapshot on '%s'\n",
6799 ret, bdrv_get_device_name(bs1));
6805 void do_info_snapshots(void)
6807 BlockDriverState *bs, *bs1;
6808 QEMUSnapshotInfo *sn_tab, *sn;
6812 bs = get_bs_snapshots();
6814 term_printf("No available block device supports snapshots\n");
6817 term_printf("Snapshot devices:");
6818 for(i = 0; i <= nb_drives; i++) {
6819 bs1 = drives_table[i].bdrv;
6820 if (bdrv_has_snapshot(bs1)) {
6822 term_printf(" %s", bdrv_get_device_name(bs1));
6827 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6829 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6832 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6833 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6834 for(i = 0; i < nb_sns; i++) {
6836 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6841 /***********************************************************/
6842 /* ram save/restore */
6844 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6848 v = qemu_get_byte(f);
6851 if (qemu_get_buffer(f, buf, len) != len)
6855 v = qemu_get_byte(f);
6856 memset(buf, v, len);
6864 static int ram_load_v1(QEMUFile *f, void *opaque)
6869 if (qemu_get_be32(f) != phys_ram_size)
6871 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6872 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6879 #define BDRV_HASH_BLOCK_SIZE 1024
6880 #define IOBUF_SIZE 4096
6881 #define RAM_CBLOCK_MAGIC 0xfabe
6883 typedef struct RamCompressState {
6886 uint8_t buf[IOBUF_SIZE];
6889 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6892 memset(s, 0, sizeof(*s));
6894 ret = deflateInit2(&s->zstream, 1,
6896 9, Z_DEFAULT_STRATEGY);
6899 s->zstream.avail_out = IOBUF_SIZE;
6900 s->zstream.next_out = s->buf;
6904 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6906 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6907 qemu_put_be16(s->f, len);
6908 qemu_put_buffer(s->f, buf, len);
6911 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6915 s->zstream.avail_in = len;
6916 s->zstream.next_in = (uint8_t *)buf;
6917 while (s->zstream.avail_in > 0) {
6918 ret = deflate(&s->zstream, Z_NO_FLUSH);
6921 if (s->zstream.avail_out == 0) {
6922 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6923 s->zstream.avail_out = IOBUF_SIZE;
6924 s->zstream.next_out = s->buf;
6930 static void ram_compress_close(RamCompressState *s)
6934 /* compress last bytes */
6936 ret = deflate(&s->zstream, Z_FINISH);
6937 if (ret == Z_OK || ret == Z_STREAM_END) {
6938 len = IOBUF_SIZE - s->zstream.avail_out;
6940 ram_put_cblock(s, s->buf, len);
6942 s->zstream.avail_out = IOBUF_SIZE;
6943 s->zstream.next_out = s->buf;
6944 if (ret == Z_STREAM_END)
6951 deflateEnd(&s->zstream);
6954 typedef struct RamDecompressState {
6957 uint8_t buf[IOBUF_SIZE];
6958 } RamDecompressState;
6960 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6963 memset(s, 0, sizeof(*s));
6965 ret = inflateInit(&s->zstream);
6971 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6975 s->zstream.avail_out = len;
6976 s->zstream.next_out = buf;
6977 while (s->zstream.avail_out > 0) {
6978 if (s->zstream.avail_in == 0) {
6979 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6981 clen = qemu_get_be16(s->f);
6982 if (clen > IOBUF_SIZE)
6984 qemu_get_buffer(s->f, s->buf, clen);
6985 s->zstream.avail_in = clen;
6986 s->zstream.next_in = s->buf;
6988 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6989 if (ret != Z_OK && ret != Z_STREAM_END) {
6996 static void ram_decompress_close(RamDecompressState *s)
6998 inflateEnd(&s->zstream);
7001 static void ram_save(QEMUFile *f, void *opaque)
7004 RamCompressState s1, *s = &s1;
7007 qemu_put_be32(f, phys_ram_size);
7008 if (ram_compress_open(s, f) < 0)
7010 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7012 if (tight_savevm_enabled) {
7016 /* find if the memory block is available on a virtual
7019 for(j = 0; j < nb_drives; j++) {
7020 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7022 BDRV_HASH_BLOCK_SIZE);
7023 if (sector_num >= 0)
7027 goto normal_compress;
7030 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7031 ram_compress_buf(s, buf, 10);
7037 ram_compress_buf(s, buf, 1);
7038 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7041 ram_compress_close(s);
7044 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7046 RamDecompressState s1, *s = &s1;
7050 if (version_id == 1)
7051 return ram_load_v1(f, opaque);
7052 if (version_id != 2)
7054 if (qemu_get_be32(f) != phys_ram_size)
7056 if (ram_decompress_open(s, f) < 0)
7058 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7059 if (ram_decompress_buf(s, buf, 1) < 0) {
7060 fprintf(stderr, "Error while reading ram block header\n");
7064 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7065 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7074 ram_decompress_buf(s, buf + 1, 9);
7076 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7077 if (bs_index >= nb_drives) {
7078 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7081 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7083 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7084 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7085 bs_index, sector_num);
7092 printf("Error block header\n");
7096 ram_decompress_close(s);
7100 /***********************************************************/
7101 /* bottom halves (can be seen as timers which expire ASAP) */
7110 static QEMUBH *first_bh = NULL;
7112 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7115 bh = qemu_mallocz(sizeof(QEMUBH));
7119 bh->opaque = opaque;
7123 int qemu_bh_poll(void)
7142 void qemu_bh_schedule(QEMUBH *bh)
7144 CPUState *env = cpu_single_env;
7148 bh->next = first_bh;
7151 /* stop the currently executing CPU to execute the BH ASAP */
7153 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7157 void qemu_bh_cancel(QEMUBH *bh)
7160 if (bh->scheduled) {
7163 pbh = &(*pbh)->next;
7169 void qemu_bh_delete(QEMUBH *bh)
7175 /***********************************************************/
7176 /* machine registration */
7178 QEMUMachine *first_machine = NULL;
7180 int qemu_register_machine(QEMUMachine *m)
7183 pm = &first_machine;
7191 static QEMUMachine *find_machine(const char *name)
7195 for(m = first_machine; m != NULL; m = m->next) {
7196 if (!strcmp(m->name, name))
7202 /***********************************************************/
7203 /* main execution loop */
7205 static void gui_update(void *opaque)
7207 DisplayState *ds = opaque;
7208 ds->dpy_refresh(ds);
7209 qemu_mod_timer(ds->gui_timer,
7210 (ds->gui_timer_interval ?
7211 ds->gui_timer_interval :
7212 GUI_REFRESH_INTERVAL)
7213 + qemu_get_clock(rt_clock));
7216 struct vm_change_state_entry {
7217 VMChangeStateHandler *cb;
7219 LIST_ENTRY (vm_change_state_entry) entries;
7222 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7224 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7227 VMChangeStateEntry *e;
7229 e = qemu_mallocz(sizeof (*e));
7235 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7239 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7241 LIST_REMOVE (e, entries);
7245 static void vm_state_notify(int running)
7247 VMChangeStateEntry *e;
7249 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7250 e->cb(e->opaque, running);
7254 /* XXX: support several handlers */
7255 static VMStopHandler *vm_stop_cb;
7256 static void *vm_stop_opaque;
7258 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7261 vm_stop_opaque = opaque;
7265 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7276 qemu_rearm_alarm_timer(alarm_timer);
7280 void vm_stop(int reason)
7283 cpu_disable_ticks();
7287 vm_stop_cb(vm_stop_opaque, reason);
7294 /* reset/shutdown handler */
7296 typedef struct QEMUResetEntry {
7297 QEMUResetHandler *func;
7299 struct QEMUResetEntry *next;
7302 static QEMUResetEntry *first_reset_entry;
7303 static int reset_requested;
7304 static int shutdown_requested;
7305 static int powerdown_requested;
7307 int qemu_shutdown_requested(void)
7309 int r = shutdown_requested;
7310 shutdown_requested = 0;
7314 int qemu_reset_requested(void)
7316 int r = reset_requested;
7317 reset_requested = 0;
7321 int qemu_powerdown_requested(void)
7323 int r = powerdown_requested;
7324 powerdown_requested = 0;
7328 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7330 QEMUResetEntry **pre, *re;
7332 pre = &first_reset_entry;
7333 while (*pre != NULL)
7334 pre = &(*pre)->next;
7335 re = qemu_mallocz(sizeof(QEMUResetEntry));
7337 re->opaque = opaque;
7342 void qemu_system_reset(void)
7346 /* reset all devices */
7347 for(re = first_reset_entry; re != NULL; re = re->next) {
7348 re->func(re->opaque);
7352 void qemu_system_reset_request(void)
7355 shutdown_requested = 1;
7357 reset_requested = 1;
7360 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7363 void qemu_system_shutdown_request(void)
7365 shutdown_requested = 1;
7367 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7370 void qemu_system_powerdown_request(void)
7372 powerdown_requested = 1;
7374 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7377 void main_loop_wait(int timeout)
7379 IOHandlerRecord *ioh;
7380 fd_set rfds, wfds, xfds;
7389 /* XXX: need to suppress polling by better using win32 events */
7391 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7392 ret |= pe->func(pe->opaque);
7397 WaitObjects *w = &wait_objects;
7399 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7400 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7401 if (w->func[ret - WAIT_OBJECT_0])
7402 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7404 /* Check for additional signaled events */
7405 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7407 /* Check if event is signaled */
7408 ret2 = WaitForSingleObject(w->events[i], 0);
7409 if(ret2 == WAIT_OBJECT_0) {
7411 w->func[i](w->opaque[i]);
7412 } else if (ret2 == WAIT_TIMEOUT) {
7414 err = GetLastError();
7415 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7418 } else if (ret == WAIT_TIMEOUT) {
7420 err = GetLastError();
7421 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7425 /* poll any events */
7426 /* XXX: separate device handlers from system ones */
7431 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7435 (!ioh->fd_read_poll ||
7436 ioh->fd_read_poll(ioh->opaque) != 0)) {
7437 FD_SET(ioh->fd, &rfds);
7441 if (ioh->fd_write) {
7442 FD_SET(ioh->fd, &wfds);
7452 tv.tv_usec = timeout * 1000;
7454 #if defined(CONFIG_SLIRP)
7456 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7459 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7461 IOHandlerRecord **pioh;
7463 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7464 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7465 ioh->fd_read(ioh->opaque);
7467 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7468 ioh->fd_write(ioh->opaque);
7472 /* remove deleted IO handlers */
7473 pioh = &first_io_handler;
7483 #if defined(CONFIG_SLIRP)
7490 slirp_select_poll(&rfds, &wfds, &xfds);
7495 if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7496 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7497 qemu_get_clock(vm_clock));
7498 /* run dma transfers, if any */
7502 /* real time timers */
7503 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7504 qemu_get_clock(rt_clock));
7506 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7507 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7508 qemu_rearm_alarm_timer(alarm_timer);
7511 /* Check bottom-halves last in case any of the earlier events triggered
7517 static int main_loop(void)
7520 #ifdef CONFIG_PROFILER
7525 cur_cpu = first_cpu;
7526 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7533 #ifdef CONFIG_PROFILER
7534 ti = profile_getclock();
7539 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7540 env->icount_decr.u16.low = 0;
7541 env->icount_extra = 0;
7542 count = qemu_next_deadline();
7543 count = (count + (1 << icount_time_shift) - 1)
7544 >> icount_time_shift;
7545 qemu_icount += count;
7546 decr = (count > 0xffff) ? 0xffff : count;
7548 env->icount_decr.u16.low = decr;
7549 env->icount_extra = count;
7551 ret = cpu_exec(env);
7552 #ifdef CONFIG_PROFILER
7553 qemu_time += profile_getclock() - ti;
7556 /* Fold pending instructions back into the
7557 instruction counter, and clear the interrupt flag. */
7558 qemu_icount -= (env->icount_decr.u16.low
7559 + env->icount_extra);
7560 env->icount_decr.u32 = 0;
7561 env->icount_extra = 0;
7563 next_cpu = env->next_cpu ?: first_cpu;
7564 if (event_pending && likely(ret != EXCP_DEBUG)) {
7565 ret = EXCP_INTERRUPT;
7569 if (ret == EXCP_HLT) {
7570 /* Give the next CPU a chance to run. */
7574 if (ret != EXCP_HALTED)
7576 /* all CPUs are halted ? */
7582 if (shutdown_requested) {
7583 ret = EXCP_INTERRUPT;
7591 if (reset_requested) {
7592 reset_requested = 0;
7593 qemu_system_reset();
7594 ret = EXCP_INTERRUPT;
7596 if (powerdown_requested) {
7597 powerdown_requested = 0;
7598 qemu_system_powerdown();
7599 ret = EXCP_INTERRUPT;
7601 if (unlikely(ret == EXCP_DEBUG)) {
7602 vm_stop(EXCP_DEBUG);
7604 /* If all cpus are halted then wait until the next IRQ */
7605 /* XXX: use timeout computed from timers */
7606 if (ret == EXCP_HALTED) {
7610 /* Advance virtual time to the next event. */
7611 if (use_icount == 1) {
7612 /* When not using an adaptive execution frequency
7613 we tend to get badly out of sync with real time,
7614 so just delay for a reasonable amount of time. */
7617 delta = cpu_get_icount() - cpu_get_clock();
7620 /* If virtual time is ahead of real time then just
7622 timeout = (delta / 1000000) + 1;
7624 /* Wait for either IO to occur or the next
7626 add = qemu_next_deadline();
7627 /* We advance the timer before checking for IO.
7628 Limit the amount we advance so that early IO
7629 activity won't get the guest too far ahead. */
7633 add = (add + (1 << icount_time_shift) - 1)
7634 >> icount_time_shift;
7636 timeout = delta / 1000000;
7647 if (shutdown_requested)
7651 #ifdef CONFIG_PROFILER
7652 ti = profile_getclock();
7654 main_loop_wait(timeout);
7655 #ifdef CONFIG_PROFILER
7656 dev_time += profile_getclock() - ti;
7659 cpu_disable_ticks();
7663 static void help(int exitcode)
7665 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7666 "usage: %s [options] [disk_image]\n"
7668 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7670 "Standard options:\n"
7671 "-M machine select emulated machine (-M ? for list)\n"
7672 "-cpu cpu select CPU (-cpu ? for list)\n"
7673 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7674 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7675 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7676 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7677 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7678 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7679 " [,cache=on|off][,format=f]\n"
7680 " use 'file' as a drive image\n"
7681 "-mtdblock file use 'file' as on-board Flash memory image\n"
7682 "-sd file use 'file' as SecureDigital card image\n"
7683 "-pflash file use 'file' as a parallel flash image\n"
7684 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7685 "-snapshot write to temporary files instead of disk image files\n"
7687 "-no-frame open SDL window without a frame and window decorations\n"
7688 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7689 "-no-quit disable SDL window close capability\n"
7692 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7694 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7695 "-smp n set the number of CPUs to 'n' [default=1]\n"
7696 "-nographic disable graphical output and redirect serial I/Os to console\n"
7697 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7699 "-k language use keyboard layout (for example \"fr\" for French)\n"
7702 "-audio-help print list of audio drivers and their options\n"
7703 "-soundhw c1,... enable audio support\n"
7704 " and only specified sound cards (comma separated list)\n"
7705 " use -soundhw ? to get the list of supported cards\n"
7706 " use -soundhw all to enable all of them\n"
7708 "-localtime set the real time clock to local time [default=utc]\n"
7709 "-full-screen start in full screen\n"
7711 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7713 "-usb enable the USB driver (will be the default soon)\n"
7714 "-usbdevice name add the host or guest USB device 'name'\n"
7715 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7716 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7718 "-name string set the name of the guest\n"
7720 "Network options:\n"
7721 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7722 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7724 "-net user[,vlan=n][,hostname=host]\n"
7725 " connect the user mode network stack to VLAN 'n' and send\n"
7726 " hostname 'host' to DHCP clients\n"
7729 "-net tap[,vlan=n],ifname=name\n"
7730 " connect the host TAP network interface to VLAN 'n'\n"
7732 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7733 " connect the host TAP network interface to VLAN 'n' and use the\n"
7734 " network scripts 'file' (default=%s)\n"
7735 " and 'dfile' (default=%s);\n"
7736 " use '[down]script=no' to disable script execution;\n"
7737 " use 'fd=h' to connect to an already opened TAP interface\n"
7739 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7740 " connect the vlan 'n' to another VLAN using a socket connection\n"
7741 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7742 " connect the vlan 'n' to multicast maddr and port\n"
7744 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7745 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7746 " on host and listening for incoming connections on 'socketpath'.\n"
7747 " Use group 'groupname' and mode 'octalmode' to change default\n"
7748 " ownership and permissions for communication port.\n"
7750 "-net none use it alone to have zero network devices; if no -net option\n"
7751 " is provided, the default is '-net nic -net user'\n"
7754 "-tftp dir allow tftp access to files in dir [-net user]\n"
7755 "-bootp file advertise file in BOOTP replies\n"
7757 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7759 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7760 " redirect TCP or UDP connections from host to guest [-net user]\n"
7763 "Linux boot specific:\n"
7764 "-kernel bzImage use 'bzImage' as kernel image\n"
7765 "-append cmdline use 'cmdline' as kernel command line\n"
7766 "-initrd file use 'file' as initial ram disk\n"
7768 "Debug/Expert options:\n"
7769 "-monitor dev redirect the monitor to char device 'dev'\n"
7770 "-serial dev redirect the serial port to char device 'dev'\n"
7771 "-parallel dev redirect the parallel port to char device 'dev'\n"
7772 "-pidfile file Write PID to 'file'\n"
7773 "-S freeze CPU at startup (use 'c' to start execution)\n"
7774 "-s wait gdb connection to port\n"
7775 "-p port set gdb connection port [default=%s]\n"
7776 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7777 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7778 " translation (t=none or lba) (usually qemu can guess them)\n"
7779 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7781 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7782 "-no-kqemu disable KQEMU kernel module usage\n"
7785 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7786 " (default is CL-GD5446 PCI VGA)\n"
7787 "-no-acpi disable ACPI\n"
7789 #ifdef CONFIG_CURSES
7790 "-curses use a curses/ncurses interface instead of SDL\n"
7792 "-no-reboot exit instead of rebooting\n"
7793 "-no-shutdown stop before shutdown\n"
7794 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7795 "-vnc display start a VNC server on display\n"
7797 "-daemonize daemonize QEMU after initializing\n"
7799 "-option-rom rom load a file, rom, into the option ROM space\n"
7801 "-prom-env variable=value set OpenBIOS nvram variables\n"
7803 "-clock force the use of the given methods for timer alarm.\n"
7804 " To see what timers are available use -clock ?\n"
7805 "-startdate select initial date of the clock\n"
7806 "-icount [N|auto]\n"
7807 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7809 "During emulation, the following keys are useful:\n"
7810 "ctrl-alt-f toggle full screen\n"
7811 "ctrl-alt-n switch to virtual console 'n'\n"
7812 "ctrl-alt toggle mouse and keyboard grab\n"
7814 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7819 DEFAULT_NETWORK_SCRIPT,
7820 DEFAULT_NETWORK_DOWN_SCRIPT,
7822 DEFAULT_GDBSTUB_PORT,
7827 #define HAS_ARG 0x0001
7842 QEMU_OPTION_mtdblock,
7846 QEMU_OPTION_snapshot,
7848 QEMU_OPTION_no_fd_bootchk,
7851 QEMU_OPTION_nographic,
7852 QEMU_OPTION_portrait,
7854 QEMU_OPTION_audio_help,
7855 QEMU_OPTION_soundhw,
7876 QEMU_OPTION_localtime,
7877 QEMU_OPTION_cirrusvga,
7880 QEMU_OPTION_std_vga,
7882 QEMU_OPTION_monitor,
7884 QEMU_OPTION_parallel,
7886 QEMU_OPTION_full_screen,
7887 QEMU_OPTION_no_frame,
7888 QEMU_OPTION_alt_grab,
7889 QEMU_OPTION_no_quit,
7890 QEMU_OPTION_pidfile,
7891 QEMU_OPTION_no_kqemu,
7892 QEMU_OPTION_kernel_kqemu,
7893 QEMU_OPTION_win2k_hack,
7895 QEMU_OPTION_usbdevice,
7898 QEMU_OPTION_no_acpi,
7900 QEMU_OPTION_no_reboot,
7901 QEMU_OPTION_no_shutdown,
7902 QEMU_OPTION_show_cursor,
7903 QEMU_OPTION_daemonize,
7904 QEMU_OPTION_option_rom,
7905 QEMU_OPTION_semihosting,
7907 QEMU_OPTION_prom_env,
7908 QEMU_OPTION_old_param,
7910 QEMU_OPTION_startdate,
7911 QEMU_OPTION_tb_size,
7915 typedef struct QEMUOption {
7921 const QEMUOption qemu_options[] = {
7922 { "h", 0, QEMU_OPTION_h },
7923 { "help", 0, QEMU_OPTION_h },
7925 { "M", HAS_ARG, QEMU_OPTION_M },
7926 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7927 { "fda", HAS_ARG, QEMU_OPTION_fda },
7928 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7929 { "hda", HAS_ARG, QEMU_OPTION_hda },
7930 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7931 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7932 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7933 { "drive", HAS_ARG, QEMU_OPTION_drive },
7934 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7935 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7936 { "sd", HAS_ARG, QEMU_OPTION_sd },
7937 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7938 { "boot", HAS_ARG, QEMU_OPTION_boot },
7939 { "snapshot", 0, QEMU_OPTION_snapshot },
7941 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7943 { "m", HAS_ARG, QEMU_OPTION_m },
7944 { "nographic", 0, QEMU_OPTION_nographic },
7945 { "portrait", 0, QEMU_OPTION_portrait },
7946 { "k", HAS_ARG, QEMU_OPTION_k },
7948 { "audio-help", 0, QEMU_OPTION_audio_help },
7949 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7952 { "net", HAS_ARG, QEMU_OPTION_net},
7954 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7955 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7957 { "smb", HAS_ARG, QEMU_OPTION_smb },
7959 { "redir", HAS_ARG, QEMU_OPTION_redir },
7962 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7963 { "append", HAS_ARG, QEMU_OPTION_append },
7964 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7966 { "S", 0, QEMU_OPTION_S },
7967 { "s", 0, QEMU_OPTION_s },
7968 { "p", HAS_ARG, QEMU_OPTION_p },
7969 { "d", HAS_ARG, QEMU_OPTION_d },
7970 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7971 { "L", HAS_ARG, QEMU_OPTION_L },
7972 { "bios", HAS_ARG, QEMU_OPTION_bios },
7974 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7975 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7977 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7978 { "g", 1, QEMU_OPTION_g },
7980 { "localtime", 0, QEMU_OPTION_localtime },
7981 { "std-vga", 0, QEMU_OPTION_std_vga },
7982 { "echr", HAS_ARG, QEMU_OPTION_echr },
7983 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7984 { "serial", HAS_ARG, QEMU_OPTION_serial },
7985 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7986 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7987 { "full-screen", 0, QEMU_OPTION_full_screen },
7989 { "no-frame", 0, QEMU_OPTION_no_frame },
7990 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7991 { "no-quit", 0, QEMU_OPTION_no_quit },
7993 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7994 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7995 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7996 { "smp", HAS_ARG, QEMU_OPTION_smp },
7997 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7998 #ifdef CONFIG_CURSES
7999 { "curses", 0, QEMU_OPTION_curses },
8002 /* temporary options */
8003 { "usb", 0, QEMU_OPTION_usb },
8004 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8005 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8006 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8007 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8008 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8009 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8010 { "daemonize", 0, QEMU_OPTION_daemonize },
8011 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8012 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8013 { "semihosting", 0, QEMU_OPTION_semihosting },
8015 { "name", HAS_ARG, QEMU_OPTION_name },
8016 #if defined(TARGET_SPARC)
8017 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8019 #if defined(TARGET_ARM)
8020 { "old-param", 0, QEMU_OPTION_old_param },
8022 { "clock", HAS_ARG, QEMU_OPTION_clock },
8023 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8024 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8025 { "icount", HAS_ARG, QEMU_OPTION_icount },
8029 /* password input */
8031 int qemu_key_check(BlockDriverState *bs, const char *name)
8036 if (!bdrv_is_encrypted(bs))
8039 term_printf("%s is encrypted.\n", name);
8040 for(i = 0; i < 3; i++) {
8041 monitor_readline("Password: ", 1, password, sizeof(password));
8042 if (bdrv_set_key(bs, password) == 0)
8044 term_printf("invalid password\n");
8049 static BlockDriverState *get_bdrv(int index)
8051 if (index > nb_drives)
8053 return drives_table[index].bdrv;
8056 static void read_passwords(void)
8058 BlockDriverState *bs;
8061 for(i = 0; i < 6; i++) {
8064 qemu_key_check(bs, bdrv_get_device_name(bs));
8069 struct soundhw soundhw[] = {
8070 #ifdef HAS_AUDIO_CHOICE
8071 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8077 { .init_isa = pcspk_audio_init }
8082 "Creative Sound Blaster 16",
8085 { .init_isa = SB16_init }
8088 #ifdef CONFIG_CS4231A
8094 { .init_isa = cs4231a_init }
8102 "Yamaha YMF262 (OPL3)",
8104 "Yamaha YM3812 (OPL2)",
8108 { .init_isa = Adlib_init }
8115 "Gravis Ultrasound GF1",
8118 { .init_isa = GUS_init }
8125 "Intel 82801AA AC97 Audio",
8128 { .init_pci = ac97_init }
8134 "ENSONIQ AudioPCI ES1370",
8137 { .init_pci = es1370_init }
8141 { NULL, NULL, 0, 0, { NULL } }
8144 static void select_soundhw (const char *optarg)
8148 if (*optarg == '?') {
8151 printf ("Valid sound card names (comma separated):\n");
8152 for (c = soundhw; c->name; ++c) {
8153 printf ("%-11s %s\n", c->name, c->descr);
8155 printf ("\n-soundhw all will enable all of the above\n");
8156 exit (*optarg != '?');
8164 if (!strcmp (optarg, "all")) {
8165 for (c = soundhw; c->name; ++c) {
8173 e = strchr (p, ',');
8174 l = !e ? strlen (p) : (size_t) (e - p);
8176 for (c = soundhw; c->name; ++c) {
8177 if (!strncmp (c->name, p, l)) {
8186 "Unknown sound card name (too big to show)\n");
8189 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8194 p += l + (e != NULL);
8198 goto show_valid_cards;
8204 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8206 exit(STATUS_CONTROL_C_EXIT);
8211 #define MAX_NET_CLIENTS 32
8215 static void termsig_handler(int signal)
8217 qemu_system_shutdown_request();
8220 static void termsig_setup(void)
8222 struct sigaction act;
8224 memset(&act, 0, sizeof(act));
8225 act.sa_handler = termsig_handler;
8226 sigaction(SIGINT, &act, NULL);
8227 sigaction(SIGHUP, &act, NULL);
8228 sigaction(SIGTERM, &act, NULL);
8233 int main(int argc, char **argv)
8235 #ifdef CONFIG_GDBSTUB
8237 const char *gdbstub_port;
8239 uint32_t boot_devices_bitmap = 0;
8241 int snapshot, linux_boot, net_boot;
8242 const char *initrd_filename;
8243 const char *kernel_filename, *kernel_cmdline;
8244 const char *boot_devices = "";
8245 DisplayState *ds = &display_state;
8246 int cyls, heads, secs, translation;
8247 const char *net_clients[MAX_NET_CLIENTS];
8251 const char *r, *optarg;
8252 CharDriverState *monitor_hd;
8253 const char *monitor_device;
8254 const char *serial_devices[MAX_SERIAL_PORTS];
8255 int serial_device_index;
8256 const char *parallel_devices[MAX_PARALLEL_PORTS];
8257 int parallel_device_index;
8258 const char *loadvm = NULL;
8259 QEMUMachine *machine;
8260 const char *cpu_model;
8261 const char *usb_devices[MAX_USB_CMDLINE];
8262 int usb_devices_index;
8265 const char *pid_file = NULL;
8268 LIST_INIT (&vm_change_state_head);
8271 struct sigaction act;
8272 sigfillset(&act.sa_mask);
8274 act.sa_handler = SIG_IGN;
8275 sigaction(SIGPIPE, &act, NULL);
8278 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8279 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8280 QEMU to run on a single CPU */
8285 h = GetCurrentProcess();
8286 if (GetProcessAffinityMask(h, &mask, &smask)) {
8287 for(i = 0; i < 32; i++) {
8288 if (mask & (1 << i))
8293 SetProcessAffinityMask(h, mask);
8299 register_machines();
8300 machine = first_machine;
8302 initrd_filename = NULL;
8304 vga_ram_size = VGA_RAM_SIZE;
8305 #ifdef CONFIG_GDBSTUB
8307 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8312 kernel_filename = NULL;
8313 kernel_cmdline = "";
8314 cyls = heads = secs = 0;
8315 translation = BIOS_ATA_TRANSLATION_AUTO;
8316 monitor_device = "vc";
8318 serial_devices[0] = "vc:80Cx24C";
8319 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8320 serial_devices[i] = NULL;
8321 serial_device_index = 0;
8323 parallel_devices[0] = "vc:640x480";
8324 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8325 parallel_devices[i] = NULL;
8326 parallel_device_index = 0;
8328 usb_devices_index = 0;
8345 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8347 const QEMUOption *popt;
8350 /* Treat --foo the same as -foo. */
8353 popt = qemu_options;
8356 fprintf(stderr, "%s: invalid option -- '%s'\n",
8360 if (!strcmp(popt->name, r + 1))
8364 if (popt->flags & HAS_ARG) {
8365 if (optind >= argc) {
8366 fprintf(stderr, "%s: option '%s' requires an argument\n",
8370 optarg = argv[optind++];
8375 switch(popt->index) {
8377 machine = find_machine(optarg);
8380 printf("Supported machines are:\n");
8381 for(m = first_machine; m != NULL; m = m->next) {
8382 printf("%-10s %s%s\n",
8384 m == first_machine ? " (default)" : "");
8386 exit(*optarg != '?');
8389 case QEMU_OPTION_cpu:
8390 /* hw initialization will check this */
8391 if (*optarg == '?') {
8392 /* XXX: implement xxx_cpu_list for targets that still miss it */
8393 #if defined(cpu_list)
8394 cpu_list(stdout, &fprintf);
8401 case QEMU_OPTION_initrd:
8402 initrd_filename = optarg;
8404 case QEMU_OPTION_hda:
8406 hda_index = drive_add(optarg, HD_ALIAS, 0);
8408 hda_index = drive_add(optarg, HD_ALIAS
8409 ",cyls=%d,heads=%d,secs=%d%s",
8410 0, cyls, heads, secs,
8411 translation == BIOS_ATA_TRANSLATION_LBA ?
8413 translation == BIOS_ATA_TRANSLATION_NONE ?
8414 ",trans=none" : "");
8416 case QEMU_OPTION_hdb:
8417 case QEMU_OPTION_hdc:
8418 case QEMU_OPTION_hdd:
8419 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8421 case QEMU_OPTION_drive:
8422 drive_add(NULL, "%s", optarg);
8424 case QEMU_OPTION_mtdblock:
8425 drive_add(optarg, MTD_ALIAS);
8427 case QEMU_OPTION_sd:
8428 drive_add(optarg, SD_ALIAS);
8430 case QEMU_OPTION_pflash:
8431 drive_add(optarg, PFLASH_ALIAS);
8433 case QEMU_OPTION_snapshot:
8436 case QEMU_OPTION_hdachs:
8440 cyls = strtol(p, (char **)&p, 0);
8441 if (cyls < 1 || cyls > 16383)
8446 heads = strtol(p, (char **)&p, 0);
8447 if (heads < 1 || heads > 16)
8452 secs = strtol(p, (char **)&p, 0);
8453 if (secs < 1 || secs > 63)
8457 if (!strcmp(p, "none"))
8458 translation = BIOS_ATA_TRANSLATION_NONE;
8459 else if (!strcmp(p, "lba"))
8460 translation = BIOS_ATA_TRANSLATION_LBA;
8461 else if (!strcmp(p, "auto"))
8462 translation = BIOS_ATA_TRANSLATION_AUTO;
8465 } else if (*p != '\0') {
8467 fprintf(stderr, "qemu: invalid physical CHS format\n");
8470 if (hda_index != -1)
8471 snprintf(drives_opt[hda_index].opt,
8472 sizeof(drives_opt[hda_index].opt),
8473 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8474 0, cyls, heads, secs,
8475 translation == BIOS_ATA_TRANSLATION_LBA ?
8477 translation == BIOS_ATA_TRANSLATION_NONE ?
8478 ",trans=none" : "");
8481 case QEMU_OPTION_nographic:
8484 #ifdef CONFIG_CURSES
8485 case QEMU_OPTION_curses:
8489 case QEMU_OPTION_portrait:
8492 case QEMU_OPTION_kernel:
8493 kernel_filename = optarg;
8495 case QEMU_OPTION_append:
8496 kernel_cmdline = optarg;
8498 case QEMU_OPTION_cdrom:
8499 drive_add(optarg, CDROM_ALIAS);
8501 case QEMU_OPTION_boot:
8502 boot_devices = optarg;
8503 /* We just do some generic consistency checks */
8505 /* Could easily be extended to 64 devices if needed */
8508 boot_devices_bitmap = 0;
8509 for (p = boot_devices; *p != '\0'; p++) {
8510 /* Allowed boot devices are:
8511 * a b : floppy disk drives
8512 * c ... f : IDE disk drives
8513 * g ... m : machine implementation dependant drives
8514 * n ... p : network devices
8515 * It's up to each machine implementation to check
8516 * if the given boot devices match the actual hardware
8517 * implementation and firmware features.
8519 if (*p < 'a' || *p > 'q') {
8520 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8523 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8525 "Boot device '%c' was given twice\n",*p);
8528 boot_devices_bitmap |= 1 << (*p - 'a');
8532 case QEMU_OPTION_fda:
8533 case QEMU_OPTION_fdb:
8534 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8537 case QEMU_OPTION_no_fd_bootchk:
8541 case QEMU_OPTION_net:
8542 if (nb_net_clients >= MAX_NET_CLIENTS) {
8543 fprintf(stderr, "qemu: too many network clients\n");
8546 net_clients[nb_net_clients] = optarg;
8550 case QEMU_OPTION_tftp:
8551 tftp_prefix = optarg;
8553 case QEMU_OPTION_bootp:
8554 bootp_filename = optarg;
8557 case QEMU_OPTION_smb:
8558 net_slirp_smb(optarg);
8561 case QEMU_OPTION_redir:
8562 net_slirp_redir(optarg);
8566 case QEMU_OPTION_audio_help:
8570 case QEMU_OPTION_soundhw:
8571 select_soundhw (optarg);
8577 case QEMU_OPTION_m: {
8581 value = strtoul(optarg, &ptr, 10);
8583 case 0: case 'M': case 'm':
8590 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8594 /* On 32-bit hosts, QEMU is limited by virtual address space */
8595 if (value > (2047 << 20)
8597 && HOST_LONG_BITS == 32
8600 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8603 if (value != (uint64_t)(ram_addr_t)value) {
8604 fprintf(stderr, "qemu: ram size too large\n");
8615 mask = cpu_str_to_log_mask(optarg);
8617 printf("Log items (comma separated):\n");
8618 for(item = cpu_log_items; item->mask != 0; item++) {
8619 printf("%-10s %s\n", item->name, item->help);
8626 #ifdef CONFIG_GDBSTUB
8631 gdbstub_port = optarg;
8637 case QEMU_OPTION_bios:
8644 keyboard_layout = optarg;
8646 case QEMU_OPTION_localtime:
8649 case QEMU_OPTION_cirrusvga:
8650 cirrus_vga_enabled = 1;
8653 case QEMU_OPTION_vmsvga:
8654 cirrus_vga_enabled = 0;
8657 case QEMU_OPTION_std_vga:
8658 cirrus_vga_enabled = 0;
8666 w = strtol(p, (char **)&p, 10);
8669 fprintf(stderr, "qemu: invalid resolution or depth\n");
8675 h = strtol(p, (char **)&p, 10);
8680 depth = strtol(p, (char **)&p, 10);
8681 if (depth != 8 && depth != 15 && depth != 16 &&
8682 depth != 24 && depth != 32)
8684 } else if (*p == '\0') {
8685 depth = graphic_depth;
8692 graphic_depth = depth;
8695 case QEMU_OPTION_echr:
8698 term_escape_char = strtol(optarg, &r, 0);
8700 printf("Bad argument to echr\n");
8703 case QEMU_OPTION_monitor:
8704 monitor_device = optarg;
8706 case QEMU_OPTION_serial:
8707 if (serial_device_index >= MAX_SERIAL_PORTS) {
8708 fprintf(stderr, "qemu: too many serial ports\n");
8711 serial_devices[serial_device_index] = optarg;
8712 serial_device_index++;
8714 case QEMU_OPTION_parallel:
8715 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8716 fprintf(stderr, "qemu: too many parallel ports\n");
8719 parallel_devices[parallel_device_index] = optarg;
8720 parallel_device_index++;
8722 case QEMU_OPTION_loadvm:
8725 case QEMU_OPTION_full_screen:
8729 case QEMU_OPTION_no_frame:
8732 case QEMU_OPTION_alt_grab:
8735 case QEMU_OPTION_no_quit:
8739 case QEMU_OPTION_pidfile:
8743 case QEMU_OPTION_win2k_hack:
8744 win2k_install_hack = 1;
8748 case QEMU_OPTION_no_kqemu:
8751 case QEMU_OPTION_kernel_kqemu:
8755 case QEMU_OPTION_usb:
8758 case QEMU_OPTION_usbdevice:
8760 if (usb_devices_index >= MAX_USB_CMDLINE) {
8761 fprintf(stderr, "Too many USB devices\n");
8764 usb_devices[usb_devices_index] = optarg;
8765 usb_devices_index++;
8767 case QEMU_OPTION_smp:
8768 smp_cpus = atoi(optarg);
8769 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8770 fprintf(stderr, "Invalid number of CPUs\n");
8774 case QEMU_OPTION_vnc:
8775 vnc_display = optarg;
8777 case QEMU_OPTION_no_acpi:
8780 case QEMU_OPTION_no_reboot:
8783 case QEMU_OPTION_no_shutdown:
8786 case QEMU_OPTION_show_cursor:
8789 case QEMU_OPTION_daemonize:
8792 case QEMU_OPTION_option_rom:
8793 if (nb_option_roms >= MAX_OPTION_ROMS) {
8794 fprintf(stderr, "Too many option ROMs\n");
8797 option_rom[nb_option_roms] = optarg;
8800 case QEMU_OPTION_semihosting:
8801 semihosting_enabled = 1;
8803 case QEMU_OPTION_name:
8807 case QEMU_OPTION_prom_env:
8808 if (nb_prom_envs >= MAX_PROM_ENVS) {
8809 fprintf(stderr, "Too many prom variables\n");
8812 prom_envs[nb_prom_envs] = optarg;
8817 case QEMU_OPTION_old_param:
8821 case QEMU_OPTION_clock:
8822 configure_alarms(optarg);
8824 case QEMU_OPTION_startdate:
8827 time_t rtc_start_date;
8828 if (!strcmp(optarg, "now")) {
8829 rtc_date_offset = -1;
8831 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8839 } else if (sscanf(optarg, "%d-%d-%d",
8842 &tm.tm_mday) == 3) {
8851 rtc_start_date = mktimegm(&tm);
8852 if (rtc_start_date == -1) {
8854 fprintf(stderr, "Invalid date format. Valid format are:\n"
8855 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8858 rtc_date_offset = time(NULL) - rtc_start_date;
8862 case QEMU_OPTION_tb_size:
8863 tb_size = strtol(optarg, NULL, 0);
8867 case QEMU_OPTION_icount:
8869 if (strcmp(optarg, "auto") == 0) {
8870 icount_time_shift = -1;
8872 icount_time_shift = strtol(optarg, NULL, 0);
8880 if (serial_device_index == 0)
8881 serial_devices[0] = "stdio";
8882 if (parallel_device_index == 0)
8883 parallel_devices[0] = "null";
8884 if (strncmp(monitor_device, "vc", 2) == 0)
8885 monitor_device = "stdio";
8892 if (pipe(fds) == -1)
8903 len = read(fds[0], &status, 1);
8904 if (len == -1 && (errno == EINTR))
8909 else if (status == 1) {
8910 fprintf(stderr, "Could not acquire pidfile\n");
8927 signal(SIGTSTP, SIG_IGN);
8928 signal(SIGTTOU, SIG_IGN);
8929 signal(SIGTTIN, SIG_IGN);
8933 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8936 write(fds[1], &status, 1);
8938 fprintf(stderr, "Could not acquire pid file\n");
8946 linux_boot = (kernel_filename != NULL);
8947 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8949 if (!linux_boot && net_boot == 0 &&
8950 !machine->nodisk_ok && nb_drives_opt == 0)
8953 if (!linux_boot && *kernel_cmdline != '\0') {
8954 fprintf(stderr, "-append only allowed with -kernel option\n");
8958 if (!linux_boot && initrd_filename != NULL) {
8959 fprintf(stderr, "-initrd only allowed with -kernel option\n");
8963 /* boot to floppy or the default cd if no hard disk defined yet */
8964 if (!boot_devices[0]) {
8965 boot_devices = "cad";
8967 setvbuf(stdout, NULL, _IOLBF, 0);
8972 if (use_icount && icount_time_shift < 0) {
8974 /* 125MIPS seems a reasonable initial guess at the guest speed.
8975 It will be corrected fairly quickly anyway. */
8976 icount_time_shift = 3;
8977 init_icount_adjust();
8984 /* init network clients */
8985 if (nb_net_clients == 0) {
8986 /* if no clients, we use a default config */
8987 net_clients[nb_net_clients++] = "nic";
8989 net_clients[nb_net_clients++] = "user";
8993 for(i = 0;i < nb_net_clients; i++) {
8994 if (net_client_parse(net_clients[i]) < 0)
8997 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8998 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9000 if (vlan->nb_guest_devs == 0)
9001 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
9002 if (vlan->nb_host_devs == 0)
9004 "Warning: vlan %d is not connected to host network\n",
9009 /* XXX: this should be moved in the PC machine instantiation code */
9010 if (net_boot != 0) {
9012 for (i = 0; i < nb_nics && i < 4; i++) {
9013 const char *model = nd_table[i].model;
9015 if (net_boot & (1 << i)) {
9018 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9019 if (get_image_size(buf) > 0) {
9020 if (nb_option_roms >= MAX_OPTION_ROMS) {
9021 fprintf(stderr, "Too many option ROMs\n");
9024 option_rom[nb_option_roms] = strdup(buf);
9031 fprintf(stderr, "No valid PXE rom found for network device\n");
9037 /* init the memory */
9038 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9040 if (machine->ram_require & RAMSIZE_FIXED) {
9042 if (ram_size < phys_ram_size) {
9043 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9044 machine->name, (unsigned long long) phys_ram_size);
9048 phys_ram_size = ram_size;
9050 ram_size = phys_ram_size;
9053 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9055 phys_ram_size += ram_size;
9058 phys_ram_base = qemu_vmalloc(phys_ram_size);
9059 if (!phys_ram_base) {
9060 fprintf(stderr, "Could not allocate physical memory\n");
9064 /* init the dynamic translator */
9065 cpu_exec_init_all(tb_size * 1024 * 1024);
9069 /* we always create the cdrom drive, even if no disk is there */
9071 if (nb_drives_opt < MAX_DRIVES)
9072 drive_add(NULL, CDROM_ALIAS);
9074 /* we always create at least one floppy */
9076 if (nb_drives_opt < MAX_DRIVES)
9077 drive_add(NULL, FD_ALIAS, 0);
9079 /* we always create one sd slot, even if no card is in it */
9081 if (nb_drives_opt < MAX_DRIVES)
9082 drive_add(NULL, SD_ALIAS);
9084 /* open the virtual block devices */
9086 for(i = 0; i < nb_drives_opt; i++)
9087 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9090 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9091 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
9094 memset(&display_state, 0, sizeof(display_state));
9097 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9100 /* nearly nothing to do */
9101 dumb_display_init(ds);
9102 } else if (vnc_display != NULL) {
9103 vnc_display_init(ds);
9104 if (vnc_display_open(ds, vnc_display) < 0)
9107 #if defined(CONFIG_CURSES)
9109 curses_display_init(ds, full_screen);
9113 #if defined(CONFIG_SDL)
9114 sdl_display_init(ds, full_screen, no_frame);
9115 #elif defined(CONFIG_COCOA)
9116 cocoa_display_init(ds, full_screen);
9118 dumb_display_init(ds);
9123 /* must be after terminal init, SDL library changes signal handlers */
9127 /* Maintain compatibility with multiple stdio monitors */
9128 if (!strcmp(monitor_device,"stdio")) {
9129 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9130 const char *devname = serial_devices[i];
9131 if (devname && !strcmp(devname,"mon:stdio")) {
9132 monitor_device = NULL;
9134 } else if (devname && !strcmp(devname,"stdio")) {
9135 monitor_device = NULL;
9136 serial_devices[i] = "mon:stdio";
9141 if (monitor_device) {
9142 monitor_hd = qemu_chr_open(monitor_device);
9144 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9147 monitor_init(monitor_hd, !nographic);
9150 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9151 const char *devname = serial_devices[i];
9152 if (devname && strcmp(devname, "none")) {
9153 serial_hds[i] = qemu_chr_open(devname);
9154 if (!serial_hds[i]) {
9155 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9159 if (strstart(devname, "vc", 0))
9160 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9164 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9165 const char *devname = parallel_devices[i];
9166 if (devname && strcmp(devname, "none")) {
9167 parallel_hds[i] = qemu_chr_open(devname);
9168 if (!parallel_hds[i]) {
9169 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9173 if (strstart(devname, "vc", 0))
9174 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9178 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9179 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9181 /* init USB devices */
9183 for(i = 0; i < usb_devices_index; i++) {
9184 if (usb_device_add(usb_devices[i]) < 0) {
9185 fprintf(stderr, "Warning: could not add USB device %s\n",
9191 if (display_state.dpy_refresh) {
9192 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9193 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9196 #ifdef CONFIG_GDBSTUB
9198 /* XXX: use standard host:port notation and modify options
9200 if (gdbserver_start(gdbstub_port) < 0) {
9201 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9212 /* XXX: simplify init */
9225 len = write(fds[1], &status, 1);
9226 if (len == -1 && (errno == EINTR))
9233 TFR(fd = open("/dev/null", O_RDWR));
9247 #if !defined(_WIN32)
9248 /* close network clients */
9249 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9250 VLANClientState *vc;
9252 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9253 if (vc->fd_read == tap_receive) {
9255 TAPState *s = vc->opaque;
9257 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9259 launch_script(s->down_script, ifname, s->fd);
9261 #if defined(CONFIG_VDE)
9262 if (vc->fd_read == vde_from_qemu) {
9263 VDEState *s = vc->opaque;