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"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
40 #include "audio/audio.h"
51 #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>
90 #include <sys/ethernet.h>
91 #include <sys/sockio.h>
92 #include <netinet/arp.h>
93 #include <netinet/in.h>
94 #include <netinet/in_systm.h>
95 #include <netinet/ip.h>
96 #include <netinet/ip_icmp.h> // must come after ip.h
97 #include <netinet/udp.h>
98 #include <netinet/tcp.h>
106 #include "qemu_socket.h"
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)
132 #endif /* CONFIG_SDL */
136 #define main qemu_main
137 #endif /* CONFIG_COCOA */
141 #include "exec-all.h"
143 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
144 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
146 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
148 #define SMBD_COMMAND "/usr/sbin/smbd"
151 //#define DEBUG_UNUSED_IOPORT
152 //#define DEBUG_IOPORT
154 //#define DEBUG_SLIRP
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 static void *ioport_opaque[MAX_IOPORTS];
171 static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
172 static 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 static BlockDriverState *bs_snapshots;
179 static int vga_ram_size;
180 enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
181 static DisplayState display_state;
184 const char* keyboard_layout = NULL;
185 int64_t ticks_per_sec;
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;
203 static int full_screen = 0;
204 static int no_frame = 0;
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 int acpi_enabled = 1;
220 int graphic_rotate = 0;
222 const char *option_rom[MAX_OPTION_ROMS];
224 int semihosting_enabled = 0;
228 const char *qemu_name;
231 unsigned int nb_prom_envs = 0;
232 const char *prom_envs[MAX_PROM_ENVS];
234 static int nb_drives_opt;
235 static struct drive_opt {
238 } drives_opt[MAX_DRIVES];
240 static CPUState *cur_cpu;
241 static CPUState *next_cpu;
242 static int event_pending = 1;
243 /* Conversion factor from emulated instructions to virtual clock ticks. */
244 static int icount_time_shift;
245 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
246 #define MAX_ICOUNT_SHIFT 10
247 /* Compensate for varying guest execution speed. */
248 static int64_t qemu_icount_bias;
249 static QEMUTimer *icount_rt_timer;
250 static QEMUTimer *icount_vm_timer;
252 uint8_t qemu_uuid[16];
254 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
256 /***********************************************************/
257 /* x86 ISA bus support */
259 target_phys_addr_t isa_mem_base = 0;
262 static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
263 static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
265 static uint32_t ioport_read(int index, uint32_t address)
267 static IOPortReadFunc *default_func[3] = {
268 default_ioport_readb,
269 default_ioport_readw,
272 IOPortReadFunc *func = ioport_read_table[index][address];
274 func = default_func[index];
275 return func(ioport_opaque[address], address);
278 static void ioport_write(int index, uint32_t address, uint32_t data)
280 static IOPortWriteFunc *default_func[3] = {
281 default_ioport_writeb,
282 default_ioport_writew,
283 default_ioport_writel
285 IOPortWriteFunc *func = ioport_write_table[index][address];
287 func = default_func[index];
288 func(ioport_opaque[address], address, data);
291 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
293 #ifdef DEBUG_UNUSED_IOPORT
294 fprintf(stderr, "unused inb: port=0x%04x\n", address);
299 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
301 #ifdef DEBUG_UNUSED_IOPORT
302 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
306 /* default is to make two byte accesses */
307 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
310 data = ioport_read(0, address);
311 address = (address + 1) & (MAX_IOPORTS - 1);
312 data |= ioport_read(0, address) << 8;
316 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
318 ioport_write(0, address, data & 0xff);
319 address = (address + 1) & (MAX_IOPORTS - 1);
320 ioport_write(0, address, (data >> 8) & 0xff);
323 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
325 #ifdef DEBUG_UNUSED_IOPORT
326 fprintf(stderr, "unused inl: port=0x%04x\n", address);
331 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
333 #ifdef DEBUG_UNUSED_IOPORT
334 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
338 /* size is the word size in byte */
339 int register_ioport_read(int start, int length, int size,
340 IOPortReadFunc *func, void *opaque)
346 } else if (size == 2) {
348 } else if (size == 4) {
351 hw_error("register_ioport_read: invalid size");
354 for(i = start; i < start + length; i += size) {
355 ioport_read_table[bsize][i] = func;
356 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
357 hw_error("register_ioport_read: invalid opaque");
358 ioport_opaque[i] = opaque;
363 /* size is the word size in byte */
364 int register_ioport_write(int start, int length, int size,
365 IOPortWriteFunc *func, void *opaque)
371 } else if (size == 2) {
373 } else if (size == 4) {
376 hw_error("register_ioport_write: invalid size");
379 for(i = start; i < start + length; i += size) {
380 ioport_write_table[bsize][i] = func;
381 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
382 hw_error("register_ioport_write: invalid opaque");
383 ioport_opaque[i] = opaque;
388 void isa_unassign_ioport(int start, int length)
392 for(i = start; i < start + length; i++) {
393 ioport_read_table[0][i] = default_ioport_readb;
394 ioport_read_table[1][i] = default_ioport_readw;
395 ioport_read_table[2][i] = default_ioport_readl;
397 ioport_write_table[0][i] = default_ioport_writeb;
398 ioport_write_table[1][i] = default_ioport_writew;
399 ioport_write_table[2][i] = default_ioport_writel;
403 /***********************************************************/
405 void cpu_outb(CPUState *env, int addr, int val)
408 if (loglevel & CPU_LOG_IOPORT)
409 fprintf(logfile, "outb: %04x %02x\n", addr, val);
411 ioport_write(0, addr, val);
414 env->last_io_time = cpu_get_time_fast();
418 void cpu_outw(CPUState *env, int addr, int val)
421 if (loglevel & CPU_LOG_IOPORT)
422 fprintf(logfile, "outw: %04x %04x\n", addr, val);
424 ioport_write(1, addr, val);
427 env->last_io_time = cpu_get_time_fast();
431 void cpu_outl(CPUState *env, int addr, int val)
434 if (loglevel & CPU_LOG_IOPORT)
435 fprintf(logfile, "outl: %04x %08x\n", addr, val);
437 ioport_write(2, addr, val);
440 env->last_io_time = cpu_get_time_fast();
444 int cpu_inb(CPUState *env, int addr)
447 val = ioport_read(0, addr);
449 if (loglevel & CPU_LOG_IOPORT)
450 fprintf(logfile, "inb : %04x %02x\n", addr, val);
454 env->last_io_time = cpu_get_time_fast();
459 int cpu_inw(CPUState *env, int addr)
462 val = ioport_read(1, addr);
464 if (loglevel & CPU_LOG_IOPORT)
465 fprintf(logfile, "inw : %04x %04x\n", addr, val);
469 env->last_io_time = cpu_get_time_fast();
474 int cpu_inl(CPUState *env, int addr)
477 val = ioport_read(2, addr);
479 if (loglevel & CPU_LOG_IOPORT)
480 fprintf(logfile, "inl : %04x %08x\n", addr, val);
484 env->last_io_time = cpu_get_time_fast();
489 /***********************************************************/
490 void hw_error(const char *fmt, ...)
496 fprintf(stderr, "qemu: hardware error: ");
497 vfprintf(stderr, fmt, ap);
498 fprintf(stderr, "\n");
499 for(env = first_cpu; env != NULL; env = env->next_cpu) {
500 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
502 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
504 cpu_dump_state(env, stderr, fprintf, 0);
511 /***********************************************************/
514 static QEMUPutKBDEvent *qemu_put_kbd_event;
515 static void *qemu_put_kbd_event_opaque;
516 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
517 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
519 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
521 qemu_put_kbd_event_opaque = opaque;
522 qemu_put_kbd_event = func;
525 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
526 void *opaque, int absolute,
529 QEMUPutMouseEntry *s, *cursor;
531 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
535 s->qemu_put_mouse_event = func;
536 s->qemu_put_mouse_event_opaque = opaque;
537 s->qemu_put_mouse_event_absolute = absolute;
538 s->qemu_put_mouse_event_name = qemu_strdup(name);
541 if (!qemu_put_mouse_event_head) {
542 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
546 cursor = qemu_put_mouse_event_head;
547 while (cursor->next != NULL)
548 cursor = cursor->next;
551 qemu_put_mouse_event_current = s;
556 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
558 QEMUPutMouseEntry *prev = NULL, *cursor;
560 if (!qemu_put_mouse_event_head || entry == NULL)
563 cursor = qemu_put_mouse_event_head;
564 while (cursor != NULL && cursor != entry) {
566 cursor = cursor->next;
569 if (cursor == NULL) // does not exist or list empty
571 else if (prev == NULL) { // entry is head
572 qemu_put_mouse_event_head = cursor->next;
573 if (qemu_put_mouse_event_current == entry)
574 qemu_put_mouse_event_current = cursor->next;
575 qemu_free(entry->qemu_put_mouse_event_name);
580 prev->next = entry->next;
582 if (qemu_put_mouse_event_current == entry)
583 qemu_put_mouse_event_current = prev;
585 qemu_free(entry->qemu_put_mouse_event_name);
589 void kbd_put_keycode(int keycode)
591 if (qemu_put_kbd_event) {
592 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
596 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
598 QEMUPutMouseEvent *mouse_event;
599 void *mouse_event_opaque;
602 if (!qemu_put_mouse_event_current) {
607 qemu_put_mouse_event_current->qemu_put_mouse_event;
609 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
612 if (graphic_rotate) {
613 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
616 width = graphic_width - 1;
617 mouse_event(mouse_event_opaque,
618 width - dy, dx, dz, buttons_state);
620 mouse_event(mouse_event_opaque,
621 dx, dy, dz, buttons_state);
625 int kbd_mouse_is_absolute(void)
627 if (!qemu_put_mouse_event_current)
630 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
633 void do_info_mice(void)
635 QEMUPutMouseEntry *cursor;
638 if (!qemu_put_mouse_event_head) {
639 term_printf("No mouse devices connected\n");
643 term_printf("Mouse devices available:\n");
644 cursor = qemu_put_mouse_event_head;
645 while (cursor != NULL) {
646 term_printf("%c Mouse #%d: %s\n",
647 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
648 index, cursor->qemu_put_mouse_event_name);
650 cursor = cursor->next;
654 void do_mouse_set(int index)
656 QEMUPutMouseEntry *cursor;
659 if (!qemu_put_mouse_event_head) {
660 term_printf("No mouse devices connected\n");
664 cursor = qemu_put_mouse_event_head;
665 while (cursor != NULL && index != i) {
667 cursor = cursor->next;
671 qemu_put_mouse_event_current = cursor;
673 term_printf("Mouse at given index not found\n");
676 /* compute with 96 bit intermediate result: (a*b)/c */
677 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
682 #ifdef WORDS_BIGENDIAN
692 rl = (uint64_t)u.l.low * (uint64_t)b;
693 rh = (uint64_t)u.l.high * (uint64_t)b;
696 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
700 /***********************************************************/
701 /* real time host monotonic timer */
703 #define QEMU_TIMER_BASE 1000000000LL
707 static int64_t clock_freq;
709 static void init_get_clock(void)
713 ret = QueryPerformanceFrequency(&freq);
715 fprintf(stderr, "Could not calibrate ticks\n");
718 clock_freq = freq.QuadPart;
721 static int64_t get_clock(void)
724 QueryPerformanceCounter(&ti);
725 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
730 static int use_rt_clock;
732 static void init_get_clock(void)
735 #if defined(__linux__)
738 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
745 static int64_t get_clock(void)
747 #if defined(__linux__)
750 clock_gettime(CLOCK_MONOTONIC, &ts);
751 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
755 /* XXX: using gettimeofday leads to problems if the date
756 changes, so it should be avoided. */
758 gettimeofday(&tv, NULL);
759 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
764 /* Return the virtual CPU time, based on the instruction counter. */
765 static int64_t cpu_get_icount(void)
768 CPUState *env = cpu_single_env;;
769 icount = qemu_icount;
772 fprintf(stderr, "Bad clock read\n");
773 icount -= (env->icount_decr.u16.low + env->icount_extra);
775 return qemu_icount_bias + (icount << icount_time_shift);
778 /***********************************************************/
779 /* guest cycle counter */
781 static int64_t cpu_ticks_prev;
782 static int64_t cpu_ticks_offset;
783 static int64_t cpu_clock_offset;
784 static int cpu_ticks_enabled;
786 /* return the host CPU cycle counter and handle stop/restart */
787 int64_t cpu_get_ticks(void)
790 return cpu_get_icount();
792 if (!cpu_ticks_enabled) {
793 return cpu_ticks_offset;
796 ticks = cpu_get_real_ticks();
797 if (cpu_ticks_prev > ticks) {
798 /* Note: non increasing ticks may happen if the host uses
800 cpu_ticks_offset += cpu_ticks_prev - ticks;
802 cpu_ticks_prev = ticks;
803 return ticks + cpu_ticks_offset;
807 /* return the host CPU monotonic timer and handle stop/restart */
808 static int64_t cpu_get_clock(void)
811 if (!cpu_ticks_enabled) {
812 return cpu_clock_offset;
815 return ti + cpu_clock_offset;
819 /* enable cpu_get_ticks() */
820 void cpu_enable_ticks(void)
822 if (!cpu_ticks_enabled) {
823 cpu_ticks_offset -= cpu_get_real_ticks();
824 cpu_clock_offset -= get_clock();
825 cpu_ticks_enabled = 1;
829 /* disable cpu_get_ticks() : the clock is stopped. You must not call
830 cpu_get_ticks() after that. */
831 void cpu_disable_ticks(void)
833 if (cpu_ticks_enabled) {
834 cpu_ticks_offset = cpu_get_ticks();
835 cpu_clock_offset = cpu_get_clock();
836 cpu_ticks_enabled = 0;
840 /***********************************************************/
843 #define QEMU_TIMER_REALTIME 0
844 #define QEMU_TIMER_VIRTUAL 1
848 /* XXX: add frequency */
856 struct QEMUTimer *next;
859 struct qemu_alarm_timer {
863 int (*start)(struct qemu_alarm_timer *t);
864 void (*stop)(struct qemu_alarm_timer *t);
865 void (*rearm)(struct qemu_alarm_timer *t);
869 #define ALARM_FLAG_DYNTICKS 0x1
870 #define ALARM_FLAG_EXPIRED 0x2
872 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
874 return t->flags & ALARM_FLAG_DYNTICKS;
877 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
879 if (!alarm_has_dynticks(t))
885 /* TODO: MIN_TIMER_REARM_US should be optimized */
886 #define MIN_TIMER_REARM_US 250
888 static struct qemu_alarm_timer *alarm_timer;
892 struct qemu_alarm_win32 {
896 } alarm_win32_data = {0, NULL, -1};
898 static int win32_start_timer(struct qemu_alarm_timer *t);
899 static void win32_stop_timer(struct qemu_alarm_timer *t);
900 static void win32_rearm_timer(struct qemu_alarm_timer *t);
904 static int unix_start_timer(struct qemu_alarm_timer *t);
905 static void unix_stop_timer(struct qemu_alarm_timer *t);
909 static int dynticks_start_timer(struct qemu_alarm_timer *t);
910 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
911 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
913 static int hpet_start_timer(struct qemu_alarm_timer *t);
914 static void hpet_stop_timer(struct qemu_alarm_timer *t);
916 static int rtc_start_timer(struct qemu_alarm_timer *t);
917 static void rtc_stop_timer(struct qemu_alarm_timer *t);
919 #endif /* __linux__ */
923 /* Correlation between real and virtual time is always going to be
924 fairly approximate, so ignore small variation.
925 When the guest is idle real and virtual time will be aligned in
927 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
929 static void icount_adjust(void)
934 static int64_t last_delta;
935 /* If the VM is not running, then do nothing. */
939 cur_time = cpu_get_clock();
940 cur_icount = qemu_get_clock(vm_clock);
941 delta = cur_icount - cur_time;
942 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
944 && last_delta + ICOUNT_WOBBLE < delta * 2
945 && icount_time_shift > 0) {
946 /* The guest is getting too far ahead. Slow time down. */
950 && last_delta - ICOUNT_WOBBLE > delta * 2
951 && icount_time_shift < MAX_ICOUNT_SHIFT) {
952 /* The guest is getting too far behind. Speed time up. */
956 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
959 static void icount_adjust_rt(void * opaque)
961 qemu_mod_timer(icount_rt_timer,
962 qemu_get_clock(rt_clock) + 1000);
966 static void icount_adjust_vm(void * opaque)
968 qemu_mod_timer(icount_vm_timer,
969 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
973 static void init_icount_adjust(void)
975 /* Have both realtime and virtual time triggers for speed adjustment.
976 The realtime trigger catches emulated time passing too slowly,
977 the virtual time trigger catches emulated time passing too fast.
978 Realtime triggers occur even when idle, so use them less frequently
980 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
981 qemu_mod_timer(icount_rt_timer,
982 qemu_get_clock(rt_clock) + 1000);
983 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
984 qemu_mod_timer(icount_vm_timer,
985 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
988 static struct qemu_alarm_timer alarm_timers[] = {
991 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
992 dynticks_stop_timer, dynticks_rearm_timer, NULL},
993 /* HPET - if available - is preferred */
994 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
995 /* ...otherwise try RTC */
996 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
998 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1000 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1001 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1002 {"win32", 0, win32_start_timer,
1003 win32_stop_timer, NULL, &alarm_win32_data},
1008 static void show_available_alarms(void)
1012 printf("Available alarm timers, in order of precedence:\n");
1013 for (i = 0; alarm_timers[i].name; i++)
1014 printf("%s\n", alarm_timers[i].name);
1017 static void configure_alarms(char const *opt)
1021 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1024 struct qemu_alarm_timer tmp;
1026 if (!strcmp(opt, "?")) {
1027 show_available_alarms();
1033 /* Reorder the array */
1034 name = strtok(arg, ",");
1036 for (i = 0; i < count && alarm_timers[i].name; i++) {
1037 if (!strcmp(alarm_timers[i].name, name))
1042 fprintf(stderr, "Unknown clock %s\n", name);
1051 tmp = alarm_timers[i];
1052 alarm_timers[i] = alarm_timers[cur];
1053 alarm_timers[cur] = tmp;
1057 name = strtok(NULL, ",");
1063 /* Disable remaining timers */
1064 for (i = cur; i < count; i++)
1065 alarm_timers[i].name = NULL;
1067 show_available_alarms();
1072 QEMUClock *rt_clock;
1073 QEMUClock *vm_clock;
1075 static QEMUTimer *active_timers[2];
1077 static QEMUClock *qemu_new_clock(int type)
1080 clock = qemu_mallocz(sizeof(QEMUClock));
1087 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1091 ts = qemu_mallocz(sizeof(QEMUTimer));
1094 ts->opaque = opaque;
1098 void qemu_free_timer(QEMUTimer *ts)
1103 /* stop a timer, but do not dealloc it */
1104 void qemu_del_timer(QEMUTimer *ts)
1108 /* NOTE: this code must be signal safe because
1109 qemu_timer_expired() can be called from a signal. */
1110 pt = &active_timers[ts->clock->type];
1123 /* modify the current timer so that it will be fired when current_time
1124 >= expire_time. The corresponding callback will be called. */
1125 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1131 /* add the timer in the sorted list */
1132 /* NOTE: this code must be signal safe because
1133 qemu_timer_expired() can be called from a signal. */
1134 pt = &active_timers[ts->clock->type];
1139 if (t->expire_time > expire_time)
1143 ts->expire_time = expire_time;
1147 /* Rearm if necessary */
1148 if (pt == &active_timers[ts->clock->type]) {
1149 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1150 qemu_rearm_alarm_timer(alarm_timer);
1152 /* Interrupt execution to force deadline recalculation. */
1153 if (use_icount && cpu_single_env) {
1154 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1159 int qemu_timer_pending(QEMUTimer *ts)
1162 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1169 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1173 return (timer_head->expire_time <= current_time);
1176 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1182 if (!ts || ts->expire_time > current_time)
1184 /* remove timer from the list before calling the callback */
1185 *ptimer_head = ts->next;
1188 /* run the callback (the timer list can be modified) */
1193 int64_t qemu_get_clock(QEMUClock *clock)
1195 switch(clock->type) {
1196 case QEMU_TIMER_REALTIME:
1197 return get_clock() / 1000000;
1199 case QEMU_TIMER_VIRTUAL:
1201 return cpu_get_icount();
1203 return cpu_get_clock();
1208 static void init_timers(void)
1211 ticks_per_sec = QEMU_TIMER_BASE;
1212 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1213 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1217 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1219 uint64_t expire_time;
1221 if (qemu_timer_pending(ts)) {
1222 expire_time = ts->expire_time;
1226 qemu_put_be64(f, expire_time);
1229 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1231 uint64_t expire_time;
1233 expire_time = qemu_get_be64(f);
1234 if (expire_time != -1) {
1235 qemu_mod_timer(ts, expire_time);
1241 static void timer_save(QEMUFile *f, void *opaque)
1243 if (cpu_ticks_enabled) {
1244 hw_error("cannot save state if virtual timers are running");
1246 qemu_put_be64(f, cpu_ticks_offset);
1247 qemu_put_be64(f, ticks_per_sec);
1248 qemu_put_be64(f, cpu_clock_offset);
1251 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1253 if (version_id != 1 && version_id != 2)
1255 if (cpu_ticks_enabled) {
1258 cpu_ticks_offset=qemu_get_be64(f);
1259 ticks_per_sec=qemu_get_be64(f);
1260 if (version_id == 2) {
1261 cpu_clock_offset=qemu_get_be64(f);
1267 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1268 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1270 static void host_alarm_handler(int host_signum)
1274 #define DISP_FREQ 1000
1276 static int64_t delta_min = INT64_MAX;
1277 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1279 ti = qemu_get_clock(vm_clock);
1280 if (last_clock != 0) {
1281 delta = ti - last_clock;
1282 if (delta < delta_min)
1284 if (delta > delta_max)
1287 if (++count == DISP_FREQ) {
1288 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1289 muldiv64(delta_min, 1000000, ticks_per_sec),
1290 muldiv64(delta_max, 1000000, ticks_per_sec),
1291 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1292 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1294 delta_min = INT64_MAX;
1302 if (alarm_has_dynticks(alarm_timer) ||
1304 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1305 qemu_get_clock(vm_clock))) ||
1306 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1307 qemu_get_clock(rt_clock))) {
1309 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1310 SetEvent(data->host_alarm);
1312 CPUState *env = next_cpu;
1314 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1317 /* stop the currently executing cpu because a timer occured */
1318 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1320 if (env->kqemu_enabled) {
1321 kqemu_cpu_interrupt(env);
1329 static int64_t qemu_next_deadline(void)
1333 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1334 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1335 qemu_get_clock(vm_clock);
1337 /* To avoid problems with overflow limit this to 2^32. */
1347 #if defined(__linux__) || defined(_WIN32)
1348 static uint64_t qemu_next_deadline_dyntick(void)
1356 delta = (qemu_next_deadline() + 999) / 1000;
1358 if (active_timers[QEMU_TIMER_REALTIME]) {
1359 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1360 qemu_get_clock(rt_clock))*1000;
1361 if (rtdelta < delta)
1365 if (delta < MIN_TIMER_REARM_US)
1366 delta = MIN_TIMER_REARM_US;
1374 #if defined(__linux__)
1376 #define RTC_FREQ 1024
1378 static void enable_sigio_timer(int fd)
1380 struct sigaction act;
1383 sigfillset(&act.sa_mask);
1385 act.sa_handler = host_alarm_handler;
1387 sigaction(SIGIO, &act, NULL);
1388 fcntl(fd, F_SETFL, O_ASYNC);
1389 fcntl(fd, F_SETOWN, getpid());
1392 static int hpet_start_timer(struct qemu_alarm_timer *t)
1394 struct hpet_info info;
1397 fd = open("/dev/hpet", O_RDONLY);
1402 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1404 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1405 "error, but for better emulation accuracy type:\n"
1406 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1410 /* Check capabilities */
1411 r = ioctl(fd, HPET_INFO, &info);
1415 /* Enable periodic mode */
1416 r = ioctl(fd, HPET_EPI, 0);
1417 if (info.hi_flags && (r < 0))
1420 /* Enable interrupt */
1421 r = ioctl(fd, HPET_IE_ON, 0);
1425 enable_sigio_timer(fd);
1426 t->priv = (void *)(long)fd;
1434 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1436 int fd = (long)t->priv;
1441 static int rtc_start_timer(struct qemu_alarm_timer *t)
1444 unsigned long current_rtc_freq = 0;
1446 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1449 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1450 if (current_rtc_freq != RTC_FREQ &&
1451 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1452 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1453 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1454 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1457 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1463 enable_sigio_timer(rtc_fd);
1465 t->priv = (void *)(long)rtc_fd;
1470 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1472 int rtc_fd = (long)t->priv;
1477 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1481 struct sigaction act;
1483 sigfillset(&act.sa_mask);
1485 act.sa_handler = host_alarm_handler;
1487 sigaction(SIGALRM, &act, NULL);
1489 ev.sigev_value.sival_int = 0;
1490 ev.sigev_notify = SIGEV_SIGNAL;
1491 ev.sigev_signo = SIGALRM;
1493 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1494 perror("timer_create");
1496 /* disable dynticks */
1497 fprintf(stderr, "Dynamic Ticks disabled\n");
1502 t->priv = (void *)host_timer;
1507 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1509 timer_t host_timer = (timer_t)t->priv;
1511 timer_delete(host_timer);
1514 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1516 timer_t host_timer = (timer_t)t->priv;
1517 struct itimerspec timeout;
1518 int64_t nearest_delta_us = INT64_MAX;
1521 if (!active_timers[QEMU_TIMER_REALTIME] &&
1522 !active_timers[QEMU_TIMER_VIRTUAL])
1525 nearest_delta_us = qemu_next_deadline_dyntick();
1527 /* check whether a timer is already running */
1528 if (timer_gettime(host_timer, &timeout)) {
1530 fprintf(stderr, "Internal timer error: aborting\n");
1533 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1534 if (current_us && current_us <= nearest_delta_us)
1537 timeout.it_interval.tv_sec = 0;
1538 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1539 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1540 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1541 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1543 fprintf(stderr, "Internal timer error: aborting\n");
1548 #endif /* defined(__linux__) */
1550 static int unix_start_timer(struct qemu_alarm_timer *t)
1552 struct sigaction act;
1553 struct itimerval itv;
1557 sigfillset(&act.sa_mask);
1559 act.sa_handler = host_alarm_handler;
1561 sigaction(SIGALRM, &act, NULL);
1563 itv.it_interval.tv_sec = 0;
1564 /* for i386 kernel 2.6 to get 1 ms */
1565 itv.it_interval.tv_usec = 999;
1566 itv.it_value.tv_sec = 0;
1567 itv.it_value.tv_usec = 10 * 1000;
1569 err = setitimer(ITIMER_REAL, &itv, NULL);
1576 static void unix_stop_timer(struct qemu_alarm_timer *t)
1578 struct itimerval itv;
1580 memset(&itv, 0, sizeof(itv));
1581 setitimer(ITIMER_REAL, &itv, NULL);
1584 #endif /* !defined(_WIN32) */
1588 static int win32_start_timer(struct qemu_alarm_timer *t)
1591 struct qemu_alarm_win32 *data = t->priv;
1594 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1595 if (!data->host_alarm) {
1596 perror("Failed CreateEvent");
1600 memset(&tc, 0, sizeof(tc));
1601 timeGetDevCaps(&tc, sizeof(tc));
1603 if (data->period < tc.wPeriodMin)
1604 data->period = tc.wPeriodMin;
1606 timeBeginPeriod(data->period);
1608 flags = TIME_CALLBACK_FUNCTION;
1609 if (alarm_has_dynticks(t))
1610 flags |= TIME_ONESHOT;
1612 flags |= TIME_PERIODIC;
1614 data->timerId = timeSetEvent(1, // interval (ms)
1615 data->period, // resolution
1616 host_alarm_handler, // function
1617 (DWORD)t, // parameter
1620 if (!data->timerId) {
1621 perror("Failed to initialize win32 alarm timer");
1623 timeEndPeriod(data->period);
1624 CloseHandle(data->host_alarm);
1628 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1633 static void win32_stop_timer(struct qemu_alarm_timer *t)
1635 struct qemu_alarm_win32 *data = t->priv;
1637 timeKillEvent(data->timerId);
1638 timeEndPeriod(data->period);
1640 CloseHandle(data->host_alarm);
1643 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1645 struct qemu_alarm_win32 *data = t->priv;
1646 uint64_t nearest_delta_us;
1648 if (!active_timers[QEMU_TIMER_REALTIME] &&
1649 !active_timers[QEMU_TIMER_VIRTUAL])
1652 nearest_delta_us = qemu_next_deadline_dyntick();
1653 nearest_delta_us /= 1000;
1655 timeKillEvent(data->timerId);
1657 data->timerId = timeSetEvent(1,
1661 TIME_ONESHOT | TIME_PERIODIC);
1663 if (!data->timerId) {
1664 perror("Failed to re-arm win32 alarm timer");
1666 timeEndPeriod(data->period);
1667 CloseHandle(data->host_alarm);
1674 static void init_timer_alarm(void)
1676 struct qemu_alarm_timer *t = NULL;
1679 for (i = 0; alarm_timers[i].name; i++) {
1680 t = &alarm_timers[i];
1688 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1689 fprintf(stderr, "Terminating\n");
1696 static void quit_timers(void)
1698 alarm_timer->stop(alarm_timer);
1702 /***********************************************************/
1703 /* host time/date access */
1704 void qemu_get_timedate(struct tm *tm, int offset)
1711 if (rtc_date_offset == -1) {
1715 ret = localtime(&ti);
1717 ti -= rtc_date_offset;
1721 memcpy(tm, ret, sizeof(struct tm));
1724 int qemu_timedate_diff(struct tm *tm)
1728 if (rtc_date_offset == -1)
1730 seconds = mktimegm(tm);
1732 seconds = mktime(tm);
1734 seconds = mktimegm(tm) + rtc_date_offset;
1736 return seconds - time(NULL);
1739 /***********************************************************/
1740 /* character device */
1742 static void qemu_chr_event(CharDriverState *s, int event)
1746 s->chr_event(s->handler_opaque, event);
1749 static void qemu_chr_reset_bh(void *opaque)
1751 CharDriverState *s = opaque;
1752 qemu_chr_event(s, CHR_EVENT_RESET);
1753 qemu_bh_delete(s->bh);
1757 void qemu_chr_reset(CharDriverState *s)
1759 if (s->bh == NULL) {
1760 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1761 qemu_bh_schedule(s->bh);
1765 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1767 return s->chr_write(s, buf, len);
1770 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1774 return s->chr_ioctl(s, cmd, arg);
1777 int qemu_chr_can_read(CharDriverState *s)
1779 if (!s->chr_can_read)
1781 return s->chr_can_read(s->handler_opaque);
1784 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1786 s->chr_read(s->handler_opaque, buf, len);
1789 void qemu_chr_accept_input(CharDriverState *s)
1791 if (s->chr_accept_input)
1792 s->chr_accept_input(s);
1795 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1800 vsnprintf(buf, sizeof(buf), fmt, ap);
1801 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1805 void qemu_chr_send_event(CharDriverState *s, int event)
1807 if (s->chr_send_event)
1808 s->chr_send_event(s, event);
1811 void qemu_chr_add_handlers(CharDriverState *s,
1812 IOCanRWHandler *fd_can_read,
1813 IOReadHandler *fd_read,
1814 IOEventHandler *fd_event,
1817 s->chr_can_read = fd_can_read;
1818 s->chr_read = fd_read;
1819 s->chr_event = fd_event;
1820 s->handler_opaque = opaque;
1821 if (s->chr_update_read_handler)
1822 s->chr_update_read_handler(s);
1825 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1830 static CharDriverState *qemu_chr_open_null(void)
1832 CharDriverState *chr;
1834 chr = qemu_mallocz(sizeof(CharDriverState));
1837 chr->chr_write = null_chr_write;
1841 /* MUX driver for serial I/O splitting */
1842 static int term_timestamps;
1843 static int64_t term_timestamps_start;
1845 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1846 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1848 IOCanRWHandler *chr_can_read[MAX_MUX];
1849 IOReadHandler *chr_read[MAX_MUX];
1850 IOEventHandler *chr_event[MAX_MUX];
1851 void *ext_opaque[MAX_MUX];
1852 CharDriverState *drv;
1853 unsigned char buffer[MUX_BUFFER_SIZE];
1857 int term_got_escape;
1862 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1864 MuxDriver *d = chr->opaque;
1866 if (!term_timestamps) {
1867 ret = d->drv->chr_write(d->drv, buf, len);
1872 for(i = 0; i < len; i++) {
1873 ret += d->drv->chr_write(d->drv, buf+i, 1);
1874 if (buf[i] == '\n') {
1880 if (term_timestamps_start == -1)
1881 term_timestamps_start = ti;
1882 ti -= term_timestamps_start;
1883 secs = ti / 1000000000;
1884 snprintf(buf1, sizeof(buf1),
1885 "[%02d:%02d:%02d.%03d] ",
1889 (int)((ti / 1000000) % 1000));
1890 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1897 static const char * const mux_help[] = {
1898 "% h print this help\n\r",
1899 "% x exit emulator\n\r",
1900 "% s save disk data back to file (if -snapshot)\n\r",
1901 "% t toggle console timestamps\n\r"
1902 "% b send break (magic sysrq)\n\r",
1903 "% c switch between console and monitor\n\r",
1908 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1909 static void mux_print_help(CharDriverState *chr)
1912 char ebuf[15] = "Escape-Char";
1913 char cbuf[50] = "\n\r";
1915 if (term_escape_char > 0 && term_escape_char < 26) {
1916 snprintf(cbuf, sizeof(cbuf), "\n\r");
1917 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
1919 snprintf(cbuf, sizeof(cbuf),
1920 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1923 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1924 for (i = 0; mux_help[i] != NULL; i++) {
1925 for (j=0; mux_help[i][j] != '\0'; j++) {
1926 if (mux_help[i][j] == '%')
1927 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1929 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1934 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1936 if (d->term_got_escape) {
1937 d->term_got_escape = 0;
1938 if (ch == term_escape_char)
1943 mux_print_help(chr);
1947 const char *term = "QEMU: Terminated\n\r";
1948 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1955 for (i = 0; i < nb_drives; i++) {
1956 bdrv_commit(drives_table[i].bdrv);
1961 qemu_chr_event(chr, CHR_EVENT_BREAK);
1964 /* Switch to the next registered device */
1966 if (chr->focus >= d->mux_cnt)
1970 term_timestamps = !term_timestamps;
1971 term_timestamps_start = -1;
1974 } else if (ch == term_escape_char) {
1975 d->term_got_escape = 1;
1983 static void mux_chr_accept_input(CharDriverState *chr)
1986 MuxDriver *d = chr->opaque;
1988 while (d->prod != d->cons &&
1989 d->chr_can_read[m] &&
1990 d->chr_can_read[m](d->ext_opaque[m])) {
1991 d->chr_read[m](d->ext_opaque[m],
1992 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1996 static int mux_chr_can_read(void *opaque)
1998 CharDriverState *chr = opaque;
1999 MuxDriver *d = chr->opaque;
2001 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2003 if (d->chr_can_read[chr->focus])
2004 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2008 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2010 CharDriverState *chr = opaque;
2011 MuxDriver *d = chr->opaque;
2015 mux_chr_accept_input (opaque);
2017 for(i = 0; i < size; i++)
2018 if (mux_proc_byte(chr, d, buf[i])) {
2019 if (d->prod == d->cons &&
2020 d->chr_can_read[m] &&
2021 d->chr_can_read[m](d->ext_opaque[m]))
2022 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2024 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2028 static void mux_chr_event(void *opaque, int event)
2030 CharDriverState *chr = opaque;
2031 MuxDriver *d = chr->opaque;
2034 /* Send the event to all registered listeners */
2035 for (i = 0; i < d->mux_cnt; i++)
2036 if (d->chr_event[i])
2037 d->chr_event[i](d->ext_opaque[i], event);
2040 static void mux_chr_update_read_handler(CharDriverState *chr)
2042 MuxDriver *d = chr->opaque;
2044 if (d->mux_cnt >= MAX_MUX) {
2045 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2048 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2049 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2050 d->chr_read[d->mux_cnt] = chr->chr_read;
2051 d->chr_event[d->mux_cnt] = chr->chr_event;
2052 /* Fix up the real driver with mux routines */
2053 if (d->mux_cnt == 0) {
2054 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2055 mux_chr_event, chr);
2057 chr->focus = d->mux_cnt;
2061 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2063 CharDriverState *chr;
2066 chr = qemu_mallocz(sizeof(CharDriverState));
2069 d = qemu_mallocz(sizeof(MuxDriver));
2078 chr->chr_write = mux_chr_write;
2079 chr->chr_update_read_handler = mux_chr_update_read_handler;
2080 chr->chr_accept_input = mux_chr_accept_input;
2087 static void socket_cleanup(void)
2092 static int socket_init(void)
2097 ret = WSAStartup(MAKEWORD(2,2), &Data);
2099 err = WSAGetLastError();
2100 fprintf(stderr, "WSAStartup: %d\n", err);
2103 atexit(socket_cleanup);
2107 static int send_all(int fd, const uint8_t *buf, int len1)
2113 ret = send(fd, buf, len, 0);
2116 errno = WSAGetLastError();
2117 if (errno != WSAEWOULDBLOCK) {
2120 } else if (ret == 0) {
2132 static int unix_write(int fd, const uint8_t *buf, int len1)
2138 ret = write(fd, buf, len);
2140 if (errno != EINTR && errno != EAGAIN)
2142 } else if (ret == 0) {
2152 static inline int send_all(int fd, const uint8_t *buf, int len1)
2154 return unix_write(fd, buf, len1);
2156 #endif /* !_WIN32 */
2165 #define STDIO_MAX_CLIENTS 1
2166 static int stdio_nb_clients = 0;
2168 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2170 FDCharDriver *s = chr->opaque;
2171 return unix_write(s->fd_out, buf, len);
2174 static int fd_chr_read_poll(void *opaque)
2176 CharDriverState *chr = opaque;
2177 FDCharDriver *s = chr->opaque;
2179 s->max_size = qemu_chr_can_read(chr);
2183 static void fd_chr_read(void *opaque)
2185 CharDriverState *chr = opaque;
2186 FDCharDriver *s = chr->opaque;
2191 if (len > s->max_size)
2195 size = read(s->fd_in, buf, len);
2197 /* FD has been closed. Remove it from the active list. */
2198 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2202 qemu_chr_read(chr, buf, size);
2206 static void fd_chr_update_read_handler(CharDriverState *chr)
2208 FDCharDriver *s = chr->opaque;
2210 if (s->fd_in >= 0) {
2211 if (nographic && s->fd_in == 0) {
2213 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2214 fd_chr_read, NULL, chr);
2219 static void fd_chr_close(struct CharDriverState *chr)
2221 FDCharDriver *s = chr->opaque;
2223 if (s->fd_in >= 0) {
2224 if (nographic && s->fd_in == 0) {
2226 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2233 /* open a character device to a unix fd */
2234 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2236 CharDriverState *chr;
2239 chr = qemu_mallocz(sizeof(CharDriverState));
2242 s = qemu_mallocz(sizeof(FDCharDriver));
2250 chr->chr_write = fd_chr_write;
2251 chr->chr_update_read_handler = fd_chr_update_read_handler;
2252 chr->chr_close = fd_chr_close;
2254 qemu_chr_reset(chr);
2259 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2263 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2266 return qemu_chr_open_fd(-1, fd_out);
2269 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2272 char filename_in[256], filename_out[256];
2274 snprintf(filename_in, 256, "%s.in", filename);
2275 snprintf(filename_out, 256, "%s.out", filename);
2276 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2277 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2278 if (fd_in < 0 || fd_out < 0) {
2283 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2287 return qemu_chr_open_fd(fd_in, fd_out);
2291 /* for STDIO, we handle the case where several clients use it
2294 #define TERM_FIFO_MAX_SIZE 1
2296 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2297 static int term_fifo_size;
2299 static int stdio_read_poll(void *opaque)
2301 CharDriverState *chr = opaque;
2303 /* try to flush the queue if needed */
2304 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2305 qemu_chr_read(chr, term_fifo, 1);
2308 /* see if we can absorb more chars */
2309 if (term_fifo_size == 0)
2315 static void stdio_read(void *opaque)
2319 CharDriverState *chr = opaque;
2321 size = read(0, buf, 1);
2323 /* stdin has been closed. Remove it from the active list. */
2324 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2328 if (qemu_chr_can_read(chr) > 0) {
2329 qemu_chr_read(chr, buf, 1);
2330 } else if (term_fifo_size == 0) {
2331 term_fifo[term_fifo_size++] = buf[0];
2336 /* init terminal so that we can grab keys */
2337 static struct termios oldtty;
2338 static int old_fd0_flags;
2339 static int term_atexit_done;
2341 static void term_exit(void)
2343 tcsetattr (0, TCSANOW, &oldtty);
2344 fcntl(0, F_SETFL, old_fd0_flags);
2347 static void term_init(void)
2351 tcgetattr (0, &tty);
2353 old_fd0_flags = fcntl(0, F_GETFL);
2355 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2356 |INLCR|IGNCR|ICRNL|IXON);
2357 tty.c_oflag |= OPOST;
2358 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2359 /* if graphical mode, we allow Ctrl-C handling */
2361 tty.c_lflag &= ~ISIG;
2362 tty.c_cflag &= ~(CSIZE|PARENB);
2365 tty.c_cc[VTIME] = 0;
2367 tcsetattr (0, TCSANOW, &tty);
2369 if (!term_atexit_done++)
2372 fcntl(0, F_SETFL, O_NONBLOCK);
2375 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2379 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2383 static CharDriverState *qemu_chr_open_stdio(void)
2385 CharDriverState *chr;
2387 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2389 chr = qemu_chr_open_fd(0, 1);
2390 chr->chr_close = qemu_chr_close_stdio;
2391 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2399 /* Once Solaris has openpty(), this is going to be removed. */
2400 int openpty(int *amaster, int *aslave, char *name,
2401 struct termios *termp, struct winsize *winp)
2404 int mfd = -1, sfd = -1;
2406 *amaster = *aslave = -1;
2408 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2412 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2415 if ((slave = ptsname(mfd)) == NULL)
2418 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2421 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2422 (termp != NULL && tcgetattr(sfd, termp) < 0))
2430 ioctl(sfd, TIOCSWINSZ, winp);
2441 void cfmakeraw (struct termios *termios_p)
2443 termios_p->c_iflag &=
2444 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2445 termios_p->c_oflag &= ~OPOST;
2446 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2447 termios_p->c_cflag &= ~(CSIZE|PARENB);
2448 termios_p->c_cflag |= CS8;
2450 termios_p->c_cc[VMIN] = 0;
2451 termios_p->c_cc[VTIME] = 0;
2455 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2456 || defined(__NetBSD__) || defined(__OpenBSD__)
2466 static void pty_chr_update_read_handler(CharDriverState *chr);
2467 static void pty_chr_state(CharDriverState *chr, int connected);
2469 static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2471 PtyCharDriver *s = chr->opaque;
2473 if (!s->connected) {
2474 /* guest sends data, check for (re-)connect */
2475 pty_chr_update_read_handler(chr);
2478 return unix_write(s->fd, buf, len);
2481 static int pty_chr_read_poll(void *opaque)
2483 CharDriverState *chr = opaque;
2484 PtyCharDriver *s = chr->opaque;
2486 s->read_bytes = qemu_chr_can_read(chr);
2487 return s->read_bytes;
2490 static void pty_chr_read(void *opaque)
2492 CharDriverState *chr = opaque;
2493 PtyCharDriver *s = chr->opaque;
2498 if (len > s->read_bytes)
2499 len = s->read_bytes;
2502 size = read(s->fd, buf, len);
2503 if ((size == -1 && errno == EIO) ||
2505 pty_chr_state(chr, 0);
2509 pty_chr_state(chr, 1);
2510 qemu_chr_read(chr, buf, size);
2514 static void pty_chr_update_read_handler(CharDriverState *chr)
2516 PtyCharDriver *s = chr->opaque;
2518 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2519 pty_chr_read, NULL, chr);
2522 * Short timeout here: just need wait long enougth that qemu makes
2523 * it through the poll loop once. When reconnected we want a
2524 * short timeout so we notice it almost instantly. Otherwise
2525 * read() gives us -EIO instantly, making pty_chr_state() reset the
2526 * timeout to the normal (much longer) poll interval before the
2529 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2532 static void pty_chr_state(CharDriverState *chr, int connected)
2534 PtyCharDriver *s = chr->opaque;
2537 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2540 /* (re-)connect poll interval for idle guests: once per second.
2541 * We check more frequently in case the guests sends data to
2542 * the virtual device linked to our pty. */
2543 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2546 qemu_chr_reset(chr);
2551 static void pty_chr_timer(void *opaque)
2553 struct CharDriverState *chr = opaque;
2554 PtyCharDriver *s = chr->opaque;
2559 /* If we arrive here without polling being cleared due
2560 * read returning -EIO, then we are (re-)connected */
2561 pty_chr_state(chr, 1);
2566 pty_chr_update_read_handler(chr);
2569 static void pty_chr_close(struct CharDriverState *chr)
2571 PtyCharDriver *s = chr->opaque;
2573 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2578 static CharDriverState *qemu_chr_open_pty(void)
2580 CharDriverState *chr;
2584 #if defined(__OpenBSD__)
2585 char pty_name[PATH_MAX];
2586 #define q_ptsname(x) pty_name
2588 char *pty_name = NULL;
2589 #define q_ptsname(x) ptsname(x)
2592 chr = qemu_mallocz(sizeof(CharDriverState));
2595 s = qemu_mallocz(sizeof(PtyCharDriver));
2601 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
2605 /* Set raw attributes on the pty. */
2607 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2610 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
2613 chr->chr_write = pty_chr_write;
2614 chr->chr_update_read_handler = pty_chr_update_read_handler;
2615 chr->chr_close = pty_chr_close;
2617 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2622 static void tty_serial_init(int fd, int speed,
2623 int parity, int data_bits, int stop_bits)
2629 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2630 speed, parity, data_bits, stop_bits);
2632 tcgetattr (fd, &tty);
2635 if (speed <= 50 * MARGIN)
2637 else if (speed <= 75 * MARGIN)
2639 else if (speed <= 300 * MARGIN)
2641 else if (speed <= 600 * MARGIN)
2643 else if (speed <= 1200 * MARGIN)
2645 else if (speed <= 2400 * MARGIN)
2647 else if (speed <= 4800 * MARGIN)
2649 else if (speed <= 9600 * MARGIN)
2651 else if (speed <= 19200 * MARGIN)
2653 else if (speed <= 38400 * MARGIN)
2655 else if (speed <= 57600 * MARGIN)
2657 else if (speed <= 115200 * MARGIN)
2662 cfsetispeed(&tty, spd);
2663 cfsetospeed(&tty, spd);
2665 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2666 |INLCR|IGNCR|ICRNL|IXON);
2667 tty.c_oflag |= OPOST;
2668 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2669 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2690 tty.c_cflag |= PARENB;
2693 tty.c_cflag |= PARENB | PARODD;
2697 tty.c_cflag |= CSTOPB;
2699 tcsetattr (fd, TCSANOW, &tty);
2702 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2704 FDCharDriver *s = chr->opaque;
2707 case CHR_IOCTL_SERIAL_SET_PARAMS:
2709 QEMUSerialSetParams *ssp = arg;
2710 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2711 ssp->data_bits, ssp->stop_bits);
2714 case CHR_IOCTL_SERIAL_SET_BREAK:
2716 int enable = *(int *)arg;
2718 tcsendbreak(s->fd_in, 1);
2721 case CHR_IOCTL_SERIAL_GET_TIOCM:
2724 int *targ = (int *)arg;
2725 ioctl(s->fd_in, TIOCMGET, &sarg);
2727 if (sarg | TIOCM_CTS)
2728 *targ |= CHR_TIOCM_CTS;
2729 if (sarg | TIOCM_CAR)
2730 *targ |= CHR_TIOCM_CAR;
2731 if (sarg | TIOCM_DSR)
2732 *targ |= CHR_TIOCM_DSR;
2733 if (sarg | TIOCM_RI)
2734 *targ |= CHR_TIOCM_RI;
2735 if (sarg | TIOCM_DTR)
2736 *targ |= CHR_TIOCM_DTR;
2737 if (sarg | TIOCM_RTS)
2738 *targ |= CHR_TIOCM_RTS;
2741 case CHR_IOCTL_SERIAL_SET_TIOCM:
2743 int sarg = *(int *)arg;
2745 if (sarg | CHR_TIOCM_DTR)
2747 if (sarg | CHR_TIOCM_RTS)
2749 ioctl(s->fd_in, TIOCMSET, &targ);
2758 static CharDriverState *qemu_chr_open_tty(const char *filename)
2760 CharDriverState *chr;
2763 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2764 tty_serial_init(fd, 115200, 'N', 8, 1);
2765 chr = qemu_chr_open_fd(fd, fd);
2770 chr->chr_ioctl = tty_serial_ioctl;
2771 qemu_chr_reset(chr);
2774 #else /* ! __linux__ && ! __sun__ */
2775 static CharDriverState *qemu_chr_open_pty(void)
2779 #endif /* __linux__ || __sun__ */
2781 #if defined(__linux__)
2785 } ParallelCharDriver;
2787 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2789 if (s->mode != mode) {
2791 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2798 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2800 ParallelCharDriver *drv = chr->opaque;
2805 case CHR_IOCTL_PP_READ_DATA:
2806 if (ioctl(fd, PPRDATA, &b) < 0)
2808 *(uint8_t *)arg = b;
2810 case CHR_IOCTL_PP_WRITE_DATA:
2811 b = *(uint8_t *)arg;
2812 if (ioctl(fd, PPWDATA, &b) < 0)
2815 case CHR_IOCTL_PP_READ_CONTROL:
2816 if (ioctl(fd, PPRCONTROL, &b) < 0)
2818 /* Linux gives only the lowest bits, and no way to know data
2819 direction! For better compatibility set the fixed upper
2821 *(uint8_t *)arg = b | 0xc0;
2823 case CHR_IOCTL_PP_WRITE_CONTROL:
2824 b = *(uint8_t *)arg;
2825 if (ioctl(fd, PPWCONTROL, &b) < 0)
2828 case CHR_IOCTL_PP_READ_STATUS:
2829 if (ioctl(fd, PPRSTATUS, &b) < 0)
2831 *(uint8_t *)arg = b;
2833 case CHR_IOCTL_PP_DATA_DIR:
2834 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2837 case CHR_IOCTL_PP_EPP_READ_ADDR:
2838 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2839 struct ParallelIOArg *parg = arg;
2840 int n = read(fd, parg->buffer, parg->count);
2841 if (n != parg->count) {
2846 case CHR_IOCTL_PP_EPP_READ:
2847 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2848 struct ParallelIOArg *parg = arg;
2849 int n = read(fd, parg->buffer, parg->count);
2850 if (n != parg->count) {
2855 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2856 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2857 struct ParallelIOArg *parg = arg;
2858 int n = write(fd, parg->buffer, parg->count);
2859 if (n != parg->count) {
2864 case CHR_IOCTL_PP_EPP_WRITE:
2865 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2866 struct ParallelIOArg *parg = arg;
2867 int n = write(fd, parg->buffer, parg->count);
2868 if (n != parg->count) {
2879 static void pp_close(CharDriverState *chr)
2881 ParallelCharDriver *drv = chr->opaque;
2884 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2885 ioctl(fd, PPRELEASE);
2890 static CharDriverState *qemu_chr_open_pp(const char *filename)
2892 CharDriverState *chr;
2893 ParallelCharDriver *drv;
2896 TFR(fd = open(filename, O_RDWR));
2900 if (ioctl(fd, PPCLAIM) < 0) {
2905 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2911 drv->mode = IEEE1284_MODE_COMPAT;
2913 chr = qemu_mallocz(sizeof(CharDriverState));
2919 chr->chr_write = null_chr_write;
2920 chr->chr_ioctl = pp_ioctl;
2921 chr->chr_close = pp_close;
2924 qemu_chr_reset(chr);
2928 #endif /* __linux__ */
2934 HANDLE hcom, hrecv, hsend;
2935 OVERLAPPED orecv, osend;
2940 #define NSENDBUF 2048
2941 #define NRECVBUF 2048
2942 #define MAXCONNECT 1
2943 #define NTIMEOUT 5000
2945 static int win_chr_poll(void *opaque);
2946 static int win_chr_pipe_poll(void *opaque);
2948 static void win_chr_close(CharDriverState *chr)
2950 WinCharState *s = chr->opaque;
2953 CloseHandle(s->hsend);
2957 CloseHandle(s->hrecv);
2961 CloseHandle(s->hcom);
2965 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2967 qemu_del_polling_cb(win_chr_poll, chr);
2970 static int win_chr_init(CharDriverState *chr, const char *filename)
2972 WinCharState *s = chr->opaque;
2974 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2979 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2981 fprintf(stderr, "Failed CreateEvent\n");
2984 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2986 fprintf(stderr, "Failed CreateEvent\n");
2990 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2991 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2992 if (s->hcom == INVALID_HANDLE_VALUE) {
2993 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2998 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2999 fprintf(stderr, "Failed SetupComm\n");
3003 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3004 size = sizeof(COMMCONFIG);
3005 GetDefaultCommConfig(filename, &comcfg, &size);
3006 comcfg.dcb.DCBlength = sizeof(DCB);
3007 CommConfigDialog(filename, NULL, &comcfg);
3009 if (!SetCommState(s->hcom, &comcfg.dcb)) {
3010 fprintf(stderr, "Failed SetCommState\n");
3014 if (!SetCommMask(s->hcom, EV_ERR)) {
3015 fprintf(stderr, "Failed SetCommMask\n");
3019 cto.ReadIntervalTimeout = MAXDWORD;
3020 if (!SetCommTimeouts(s->hcom, &cto)) {
3021 fprintf(stderr, "Failed SetCommTimeouts\n");
3025 if (!ClearCommError(s->hcom, &err, &comstat)) {
3026 fprintf(stderr, "Failed ClearCommError\n");
3029 qemu_add_polling_cb(win_chr_poll, chr);
3037 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3039 WinCharState *s = chr->opaque;
3040 DWORD len, ret, size, err;
3043 ZeroMemory(&s->osend, sizeof(s->osend));
3044 s->osend.hEvent = s->hsend;
3047 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3049 ret = WriteFile(s->hcom, buf, len, &size, NULL);
3051 err = GetLastError();
3052 if (err == ERROR_IO_PENDING) {
3053 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3071 static int win_chr_read_poll(CharDriverState *chr)
3073 WinCharState *s = chr->opaque;
3075 s->max_size = qemu_chr_can_read(chr);
3079 static void win_chr_readfile(CharDriverState *chr)
3081 WinCharState *s = chr->opaque;
3086 ZeroMemory(&s->orecv, sizeof(s->orecv));
3087 s->orecv.hEvent = s->hrecv;
3088 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3090 err = GetLastError();
3091 if (err == ERROR_IO_PENDING) {
3092 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3097 qemu_chr_read(chr, buf, size);
3101 static void win_chr_read(CharDriverState *chr)
3103 WinCharState *s = chr->opaque;
3105 if (s->len > s->max_size)
3106 s->len = s->max_size;
3110 win_chr_readfile(chr);
3113 static int win_chr_poll(void *opaque)
3115 CharDriverState *chr = opaque;
3116 WinCharState *s = chr->opaque;
3120 ClearCommError(s->hcom, &comerr, &status);
3121 if (status.cbInQue > 0) {
3122 s->len = status.cbInQue;
3123 win_chr_read_poll(chr);
3130 static CharDriverState *qemu_chr_open_win(const char *filename)
3132 CharDriverState *chr;
3135 chr = qemu_mallocz(sizeof(CharDriverState));
3138 s = qemu_mallocz(sizeof(WinCharState));
3144 chr->chr_write = win_chr_write;
3145 chr->chr_close = win_chr_close;
3147 if (win_chr_init(chr, filename) < 0) {
3152 qemu_chr_reset(chr);
3156 static int win_chr_pipe_poll(void *opaque)
3158 CharDriverState *chr = opaque;
3159 WinCharState *s = chr->opaque;
3162 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3165 win_chr_read_poll(chr);
3172 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3174 WinCharState *s = chr->opaque;
3182 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3184 fprintf(stderr, "Failed CreateEvent\n");
3187 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3189 fprintf(stderr, "Failed CreateEvent\n");
3193 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3194 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3195 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3197 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3198 if (s->hcom == INVALID_HANDLE_VALUE) {
3199 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3204 ZeroMemory(&ov, sizeof(ov));
3205 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3206 ret = ConnectNamedPipe(s->hcom, &ov);
3208 fprintf(stderr, "Failed ConnectNamedPipe\n");
3212 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3214 fprintf(stderr, "Failed GetOverlappedResult\n");
3216 CloseHandle(ov.hEvent);
3223 CloseHandle(ov.hEvent);
3226 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3235 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3237 CharDriverState *chr;
3240 chr = qemu_mallocz(sizeof(CharDriverState));
3243 s = qemu_mallocz(sizeof(WinCharState));
3249 chr->chr_write = win_chr_write;
3250 chr->chr_close = win_chr_close;
3252 if (win_chr_pipe_init(chr, filename) < 0) {
3257 qemu_chr_reset(chr);
3261 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3263 CharDriverState *chr;
3266 chr = qemu_mallocz(sizeof(CharDriverState));
3269 s = qemu_mallocz(sizeof(WinCharState));
3276 chr->chr_write = win_chr_write;
3277 qemu_chr_reset(chr);
3281 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3283 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3286 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3290 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3291 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3292 if (fd_out == INVALID_HANDLE_VALUE)
3295 return qemu_chr_open_win_file(fd_out);
3297 #endif /* !_WIN32 */
3299 /***********************************************************/
3300 /* UDP Net console */
3304 struct sockaddr_in daddr;
3311 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3313 NetCharDriver *s = chr->opaque;
3315 return sendto(s->fd, buf, len, 0,
3316 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3319 static int udp_chr_read_poll(void *opaque)
3321 CharDriverState *chr = opaque;
3322 NetCharDriver *s = chr->opaque;
3324 s->max_size = qemu_chr_can_read(chr);
3326 /* If there were any stray characters in the queue process them
3329 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3330 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3332 s->max_size = qemu_chr_can_read(chr);
3337 static void udp_chr_read(void *opaque)
3339 CharDriverState *chr = opaque;
3340 NetCharDriver *s = chr->opaque;
3342 if (s->max_size == 0)
3344 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3345 s->bufptr = s->bufcnt;
3350 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3351 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3353 s->max_size = qemu_chr_can_read(chr);
3357 static void udp_chr_update_read_handler(CharDriverState *chr)
3359 NetCharDriver *s = chr->opaque;
3362 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3363 udp_chr_read, NULL, chr);
3367 int parse_host_port(struct sockaddr_in *saddr, const char *str);
3369 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3371 int parse_host_src_port(struct sockaddr_in *haddr,
3372 struct sockaddr_in *saddr,
3375 static CharDriverState *qemu_chr_open_udp(const char *def)
3377 CharDriverState *chr = NULL;
3378 NetCharDriver *s = NULL;
3380 struct sockaddr_in saddr;
3382 chr = qemu_mallocz(sizeof(CharDriverState));
3385 s = qemu_mallocz(sizeof(NetCharDriver));
3389 fd = socket(PF_INET, SOCK_DGRAM, 0);
3391 perror("socket(PF_INET, SOCK_DGRAM)");
3395 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3396 printf("Could not parse: %s\n", def);
3400 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3410 chr->chr_write = udp_chr_write;
3411 chr->chr_update_read_handler = udp_chr_update_read_handler;
3424 /***********************************************************/
3425 /* TCP Net console */
3436 static void tcp_chr_accept(void *opaque);
3438 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3440 TCPCharDriver *s = chr->opaque;
3442 return send_all(s->fd, buf, len);
3444 /* XXX: indicate an error ? */
3449 static int tcp_chr_read_poll(void *opaque)
3451 CharDriverState *chr = opaque;
3452 TCPCharDriver *s = chr->opaque;
3455 s->max_size = qemu_chr_can_read(chr);
3460 #define IAC_BREAK 243
3461 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3463 uint8_t *buf, int *size)
3465 /* Handle any telnet client's basic IAC options to satisfy char by
3466 * char mode with no echo. All IAC options will be removed from
3467 * the buf and the do_telnetopt variable will be used to track the
3468 * state of the width of the IAC information.
3470 * IAC commands come in sets of 3 bytes with the exception of the
3471 * "IAC BREAK" command and the double IAC.
3477 for (i = 0; i < *size; i++) {
3478 if (s->do_telnetopt > 1) {
3479 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3480 /* Double IAC means send an IAC */
3484 s->do_telnetopt = 1;
3486 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3487 /* Handle IAC break commands by sending a serial break */
3488 qemu_chr_event(chr, CHR_EVENT_BREAK);
3493 if (s->do_telnetopt >= 4) {
3494 s->do_telnetopt = 1;
3497 if ((unsigned char)buf[i] == IAC) {
3498 s->do_telnetopt = 2;
3509 static void tcp_chr_read(void *opaque)
3511 CharDriverState *chr = opaque;
3512 TCPCharDriver *s = chr->opaque;
3516 if (!s->connected || s->max_size <= 0)
3519 if (len > s->max_size)
3521 size = recv(s->fd, buf, len, 0);
3523 /* connection closed */
3525 if (s->listen_fd >= 0) {
3526 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3528 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3531 } else if (size > 0) {
3532 if (s->do_telnetopt)
3533 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3535 qemu_chr_read(chr, buf, size);
3539 static void tcp_chr_connect(void *opaque)
3541 CharDriverState *chr = opaque;
3542 TCPCharDriver *s = chr->opaque;
3545 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3546 tcp_chr_read, NULL, chr);
3547 qemu_chr_reset(chr);
3550 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3551 static void tcp_chr_telnet_init(int fd)
3554 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3555 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3556 send(fd, (char *)buf, 3, 0);
3557 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3558 send(fd, (char *)buf, 3, 0);
3559 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3560 send(fd, (char *)buf, 3, 0);
3561 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3562 send(fd, (char *)buf, 3, 0);
3565 static void socket_set_nodelay(int fd)
3568 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3571 static void tcp_chr_accept(void *opaque)
3573 CharDriverState *chr = opaque;
3574 TCPCharDriver *s = chr->opaque;
3575 struct sockaddr_in saddr;
3577 struct sockaddr_un uaddr;
3579 struct sockaddr *addr;
3586 len = sizeof(uaddr);
3587 addr = (struct sockaddr *)&uaddr;
3591 len = sizeof(saddr);
3592 addr = (struct sockaddr *)&saddr;
3594 fd = accept(s->listen_fd, addr, &len);
3595 if (fd < 0 && errno != EINTR) {
3597 } else if (fd >= 0) {
3598 if (s->do_telnetopt)
3599 tcp_chr_telnet_init(fd);
3603 socket_set_nonblock(fd);
3605 socket_set_nodelay(fd);
3607 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3608 tcp_chr_connect(chr);
3611 static void tcp_chr_close(CharDriverState *chr)
3613 TCPCharDriver *s = chr->opaque;
3616 if (s->listen_fd >= 0)
3617 closesocket(s->listen_fd);
3621 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3625 CharDriverState *chr = NULL;
3626 TCPCharDriver *s = NULL;
3627 int fd = -1, ret, err, val;
3629 int is_waitconnect = 1;
3632 struct sockaddr_in saddr;
3634 struct sockaddr_un uaddr;
3636 struct sockaddr *addr;
3641 addr = (struct sockaddr *)&uaddr;
3642 addrlen = sizeof(uaddr);
3643 if (parse_unix_path(&uaddr, host_str) < 0)
3648 addr = (struct sockaddr *)&saddr;
3649 addrlen = sizeof(saddr);
3650 if (parse_host_port(&saddr, host_str) < 0)
3655 while((ptr = strchr(ptr,','))) {
3657 if (!strncmp(ptr,"server",6)) {
3659 } else if (!strncmp(ptr,"nowait",6)) {
3661 } else if (!strncmp(ptr,"nodelay",6)) {
3664 printf("Unknown option: %s\n", ptr);
3671 chr = qemu_mallocz(sizeof(CharDriverState));
3674 s = qemu_mallocz(sizeof(TCPCharDriver));
3680 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3683 fd = socket(PF_INET, SOCK_STREAM, 0);
3688 if (!is_waitconnect)
3689 socket_set_nonblock(fd);
3694 s->is_unix = is_unix;
3695 s->do_nodelay = do_nodelay && !is_unix;
3698 chr->chr_write = tcp_chr_write;
3699 chr->chr_close = tcp_chr_close;
3702 /* allow fast reuse */
3706 pstrcpy(path, sizeof(path), uaddr.sun_path);
3712 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3715 ret = bind(fd, addr, addrlen);
3719 ret = listen(fd, 0);
3724 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3726 s->do_telnetopt = 1;
3729 ret = connect(fd, addr, addrlen);
3731 err = socket_error();
3732 if (err == EINTR || err == EWOULDBLOCK) {
3733 } else if (err == EINPROGRESS) {
3736 } else if (err == WSAEALREADY) {
3748 socket_set_nodelay(fd);
3750 tcp_chr_connect(chr);
3752 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3755 if (is_listen && is_waitconnect) {
3756 printf("QEMU waiting for connection on: %s\n", host_str);
3757 tcp_chr_accept(chr);
3758 socket_set_nonblock(s->listen_fd);
3770 CharDriverState *qemu_chr_open(const char *filename)
3774 if (!strcmp(filename, "vc")) {
3775 return text_console_init(&display_state, 0);
3776 } else if (strstart(filename, "vc:", &p)) {
3777 return text_console_init(&display_state, p);
3778 } else if (!strcmp(filename, "null")) {
3779 return qemu_chr_open_null();
3781 if (strstart(filename, "tcp:", &p)) {
3782 return qemu_chr_open_tcp(p, 0, 0);
3784 if (strstart(filename, "telnet:", &p)) {
3785 return qemu_chr_open_tcp(p, 1, 0);
3787 if (strstart(filename, "udp:", &p)) {
3788 return qemu_chr_open_udp(p);
3790 if (strstart(filename, "mon:", &p)) {
3791 CharDriverState *drv = qemu_chr_open(p);
3793 drv = qemu_chr_open_mux(drv);
3794 monitor_init(drv, !nographic);
3797 printf("Unable to open driver: %s\n", p);
3801 if (strstart(filename, "unix:", &p)) {
3802 return qemu_chr_open_tcp(p, 0, 1);
3803 } else if (strstart(filename, "file:", &p)) {
3804 return qemu_chr_open_file_out(p);
3805 } else if (strstart(filename, "pipe:", &p)) {
3806 return qemu_chr_open_pipe(p);
3807 } else if (!strcmp(filename, "pty")) {
3808 return qemu_chr_open_pty();
3809 } else if (!strcmp(filename, "stdio")) {
3810 return qemu_chr_open_stdio();
3812 #if defined(__linux__)
3813 if (strstart(filename, "/dev/parport", NULL)) {
3814 return qemu_chr_open_pp(filename);
3817 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3818 || defined(__NetBSD__) || defined(__OpenBSD__)
3819 if (strstart(filename, "/dev/", NULL)) {
3820 return qemu_chr_open_tty(filename);
3824 if (strstart(filename, "COM", NULL)) {
3825 return qemu_chr_open_win(filename);
3827 if (strstart(filename, "pipe:", &p)) {
3828 return qemu_chr_open_win_pipe(p);
3830 if (strstart(filename, "con:", NULL)) {
3831 return qemu_chr_open_win_con(filename);
3833 if (strstart(filename, "file:", &p)) {
3834 return qemu_chr_open_win_file_out(p);
3837 #ifdef CONFIG_BRLAPI
3838 if (!strcmp(filename, "braille")) {
3839 return chr_baum_init();
3847 void qemu_chr_close(CharDriverState *chr)
3850 chr->chr_close(chr);
3854 /***********************************************************/
3855 /* network device redirectors */
3857 #if defined(DEBUG_NET) || defined(DEBUG_SLIRP)
3858 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3862 for(i=0;i<size;i+=16) {
3866 fprintf(f, "%08x ", i);
3869 fprintf(f, " %02x", buf[i+j]);
3874 for(j=0;j<len;j++) {
3876 if (c < ' ' || c > '~')
3878 fprintf(f, "%c", c);
3885 static int parse_macaddr(uint8_t *macaddr, const char *p)
3892 offset = strtol(p, &last_char, 0);
3893 if (0 == errno && '\0' == *last_char &&
3894 offset >= 0 && offset <= 0xFFFFFF) {
3895 macaddr[3] = (offset & 0xFF0000) >> 16;
3896 macaddr[4] = (offset & 0xFF00) >> 8;
3897 macaddr[5] = offset & 0xFF;
3900 for(i = 0; i < 6; i++) {
3901 macaddr[i] = strtol(p, (char **)&p, 16);
3906 if (*p != ':' && *p != '-')
3917 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3922 p1 = strchr(p, sep);
3928 if (len > buf_size - 1)
3930 memcpy(buf, p, len);
3937 int parse_host_src_port(struct sockaddr_in *haddr,
3938 struct sockaddr_in *saddr,
3939 const char *input_str)
3941 char *str = strdup(input_str);
3942 char *host_str = str;
3944 const char *src_str2;
3948 * Chop off any extra arguments at the end of the string which
3949 * would start with a comma, then fill in the src port information
3950 * if it was provided else use the "any address" and "any port".
3952 if ((ptr = strchr(str,',')))
3955 if ((src_str = strchr(input_str,'@'))) {
3960 if (parse_host_port(haddr, host_str) < 0)
3964 if (!src_str || *src_str == '\0')
3967 if (parse_host_port(saddr, src_str2) < 0)
3978 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3986 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3988 saddr->sin_family = AF_INET;
3989 if (buf[0] == '\0') {
3990 saddr->sin_addr.s_addr = 0;
3992 if (isdigit(buf[0])) {
3993 if (!inet_aton(buf, &saddr->sin_addr))
3996 if ((he = gethostbyname(buf)) == NULL)
3998 saddr->sin_addr = *(struct in_addr *)he->h_addr;
4001 port = strtol(p, (char **)&r, 0);
4004 saddr->sin_port = htons(port);
4009 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4014 len = MIN(108, strlen(str));
4015 p = strchr(str, ',');
4017 len = MIN(len, p - str);
4019 memset(uaddr, 0, sizeof(*uaddr));
4021 uaddr->sun_family = AF_UNIX;
4022 memcpy(uaddr->sun_path, str, len);
4028 /* find or alloc a new VLAN */
4029 VLANState *qemu_find_vlan(int id)
4031 VLANState **pvlan, *vlan;
4032 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4036 vlan = qemu_mallocz(sizeof(VLANState));
4041 pvlan = &first_vlan;
4042 while (*pvlan != NULL)
4043 pvlan = &(*pvlan)->next;
4048 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4049 IOReadHandler *fd_read,
4050 IOCanRWHandler *fd_can_read,
4053 VLANClientState *vc, **pvc;
4054 vc = qemu_mallocz(sizeof(VLANClientState));
4057 vc->fd_read = fd_read;
4058 vc->fd_can_read = fd_can_read;
4059 vc->opaque = opaque;
4063 pvc = &vlan->first_client;
4064 while (*pvc != NULL)
4065 pvc = &(*pvc)->next;
4070 void qemu_del_vlan_client(VLANClientState *vc)
4072 VLANClientState **pvc = &vc->vlan->first_client;
4074 while (*pvc != NULL)
4080 pvc = &(*pvc)->next;
4083 int qemu_can_send_packet(VLANClientState *vc1)
4085 VLANState *vlan = vc1->vlan;
4086 VLANClientState *vc;
4088 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4090 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4097 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4099 VLANState *vlan = vc1->vlan;
4100 VLANClientState *vc;
4103 printf("vlan %d send:\n", vlan->id);
4104 hex_dump(stdout, buf, size);
4106 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4108 vc->fd_read(vc->opaque, buf, size);
4113 #if defined(CONFIG_SLIRP)
4115 /* slirp network adapter */
4117 static int slirp_inited;
4118 static VLANClientState *slirp_vc;
4120 int slirp_can_output(void)
4122 return !slirp_vc || qemu_can_send_packet(slirp_vc);
4125 void slirp_output(const uint8_t *pkt, int pkt_len)
4128 printf("slirp output:\n");
4129 hex_dump(stdout, pkt, pkt_len);
4133 qemu_send_packet(slirp_vc, pkt, pkt_len);
4136 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4139 printf("slirp input:\n");
4140 hex_dump(stdout, buf, size);
4142 slirp_input(buf, size);
4145 static int net_slirp_init(VLANState *vlan)
4147 if (!slirp_inited) {
4151 slirp_vc = qemu_new_vlan_client(vlan,
4152 slirp_receive, NULL, NULL);
4153 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4157 static void net_slirp_redir(const char *redir_str)
4162 struct in_addr guest_addr;
4163 int host_port, guest_port;
4165 if (!slirp_inited) {
4171 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4173 if (!strcmp(buf, "tcp")) {
4175 } else if (!strcmp(buf, "udp")) {
4181 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4183 host_port = strtol(buf, &r, 0);
4187 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4189 if (buf[0] == '\0') {
4190 pstrcpy(buf, sizeof(buf), "10.0.2.15");
4192 if (!inet_aton(buf, &guest_addr))
4195 guest_port = strtol(p, &r, 0);
4199 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4200 fprintf(stderr, "qemu: could not set up redirection\n");
4205 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4211 static char smb_dir[1024];
4213 static void erase_dir(char *dir_name)
4217 char filename[1024];
4219 /* erase all the files in the directory */
4220 if ((d = opendir(dir_name)) != 0) {
4225 if (strcmp(de->d_name, ".") != 0 &&
4226 strcmp(de->d_name, "..") != 0) {
4227 snprintf(filename, sizeof(filename), "%s/%s",
4228 smb_dir, de->d_name);
4229 if (unlink(filename) != 0) /* is it a directory? */
4230 erase_dir(filename);
4238 /* automatic user mode samba server configuration */
4239 static void smb_exit(void)
4244 /* automatic user mode samba server configuration */
4245 static void net_slirp_smb(const char *exported_dir)
4247 char smb_conf[1024];
4248 char smb_cmdline[1024];
4251 if (!slirp_inited) {
4256 /* XXX: better tmp dir construction */
4257 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4258 if (mkdir(smb_dir, 0700) < 0) {
4259 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4262 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4264 f = fopen(smb_conf, "w");
4266 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4273 "socket address=127.0.0.1\n"
4274 "pid directory=%s\n"
4275 "lock directory=%s\n"
4276 "log file=%s/log.smbd\n"
4277 "smb passwd file=%s/smbpasswd\n"
4278 "security = share\n"
4293 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4294 SMBD_COMMAND, smb_conf);
4296 slirp_add_exec(0, smb_cmdline, 4, 139);
4299 #endif /* !defined(_WIN32) */
4300 void do_info_slirp(void)
4305 #endif /* CONFIG_SLIRP */
4307 #if !defined(_WIN32)
4309 typedef struct TAPState {
4310 VLANClientState *vc;
4312 char down_script[1024];
4315 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4317 TAPState *s = opaque;
4320 ret = write(s->fd, buf, size);
4321 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4328 static void tap_send(void *opaque)
4330 TAPState *s = opaque;
4337 sbuf.maxlen = sizeof(buf);
4339 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4341 size = read(s->fd, buf, sizeof(buf));
4344 qemu_send_packet(s->vc, buf, size);
4350 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4354 s = qemu_mallocz(sizeof(TAPState));
4358 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4359 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4360 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4364 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4365 static int tap_open(char *ifname, int ifname_size)
4371 TFR(fd = open("/dev/tap", O_RDWR));
4373 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4378 dev = devname(s.st_rdev, S_IFCHR);
4379 pstrcpy(ifname, ifname_size, dev);
4381 fcntl(fd, F_SETFL, O_NONBLOCK);
4384 #elif defined(__sun__)
4385 #define TUNNEWPPA (('T'<<16) | 0x0001)
4387 * Allocate TAP device, returns opened fd.
4388 * Stores dev name in the first arg(must be large enough).
4390 int tap_alloc(char *dev, size_t dev_size)
4392 int tap_fd, if_fd, ppa = -1;
4393 static int ip_fd = 0;
4396 static int arp_fd = 0;
4397 int ip_muxid, arp_muxid;
4398 struct strioctl strioc_if, strioc_ppa;
4399 int link_type = I_PLINK;;
4401 char actual_name[32] = "";
4403 memset(&ifr, 0x0, sizeof(ifr));
4407 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4411 /* Check if IP device was opened */
4415 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4417 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4421 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4423 syslog(LOG_ERR, "Can't open /dev/tap");
4427 /* Assign a new PPA and get its unit number. */
4428 strioc_ppa.ic_cmd = TUNNEWPPA;
4429 strioc_ppa.ic_timout = 0;
4430 strioc_ppa.ic_len = sizeof(ppa);
4431 strioc_ppa.ic_dp = (char *)&ppa;
4432 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4433 syslog (LOG_ERR, "Can't assign new interface");
4435 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4437 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4440 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4441 syslog(LOG_ERR, "Can't push IP module");
4445 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4446 syslog(LOG_ERR, "Can't get flags\n");
4448 snprintf (actual_name, 32, "tap%d", ppa);
4449 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4452 /* Assign ppa according to the unit number returned by tun device */
4454 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4455 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4456 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4457 syslog (LOG_ERR, "Can't get flags\n");
4458 /* Push arp module to if_fd */
4459 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4460 syslog (LOG_ERR, "Can't push ARP module (2)");
4462 /* Push arp module to ip_fd */
4463 if (ioctl (ip_fd, I_POP, NULL) < 0)
4464 syslog (LOG_ERR, "I_POP failed\n");
4465 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4466 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4468 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4470 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4472 /* Set ifname to arp */
4473 strioc_if.ic_cmd = SIOCSLIFNAME;
4474 strioc_if.ic_timout = 0;
4475 strioc_if.ic_len = sizeof(ifr);
4476 strioc_if.ic_dp = (char *)𝔦
4477 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4478 syslog (LOG_ERR, "Can't set ifname to arp\n");
4481 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4482 syslog(LOG_ERR, "Can't link TAP device to IP");
4486 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4487 syslog (LOG_ERR, "Can't link TAP device to ARP");
4491 memset(&ifr, 0x0, sizeof(ifr));
4492 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4493 ifr.lifr_ip_muxid = ip_muxid;
4494 ifr.lifr_arp_muxid = arp_muxid;
4496 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4498 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4499 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4500 syslog (LOG_ERR, "Can't set multiplexor id");
4503 snprintf(dev, dev_size, "tap%d", ppa);
4507 static int tap_open(char *ifname, int ifname_size)
4511 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
4512 fprintf(stderr, "Cannot allocate TAP device\n");
4515 pstrcpy(ifname, ifname_size, dev);
4516 fcntl(fd, F_SETFL, O_NONBLOCK);
4520 static int tap_open(char *ifname, int ifname_size)
4525 TFR(fd = open("/dev/net/tun", O_RDWR));
4527 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4530 memset(&ifr, 0, sizeof(ifr));
4531 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4532 if (ifname[0] != '\0')
4533 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4535 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4536 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4538 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4542 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4543 fcntl(fd, F_SETFL, O_NONBLOCK);
4548 static int launch_script(const char *setup_script, const char *ifname, int fd)
4554 /* try to launch network script */
4558 int open_max = sysconf (_SC_OPEN_MAX), i;
4559 for (i = 0; i < open_max; i++)
4560 if (i != STDIN_FILENO &&
4561 i != STDOUT_FILENO &&
4562 i != STDERR_FILENO &&
4567 *parg++ = (char *)setup_script;
4568 *parg++ = (char *)ifname;
4570 execv(setup_script, args);
4573 while (waitpid(pid, &status, 0) != pid);
4574 if (!WIFEXITED(status) ||
4575 WEXITSTATUS(status) != 0) {
4576 fprintf(stderr, "%s: could not launch network script\n",
4584 static int net_tap_init(VLANState *vlan, const char *ifname1,
4585 const char *setup_script, const char *down_script)
4591 if (ifname1 != NULL)
4592 pstrcpy(ifname, sizeof(ifname), ifname1);
4595 TFR(fd = tap_open(ifname, sizeof(ifname)));
4599 if (!setup_script || !strcmp(setup_script, "no"))
4601 if (setup_script[0] != '\0') {
4602 if (launch_script(setup_script, ifname, fd))
4605 s = net_tap_fd_init(vlan, fd);
4608 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4609 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4610 if (down_script && strcmp(down_script, "no"))
4611 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4615 #endif /* !_WIN32 */
4617 #if defined(CONFIG_VDE)
4618 typedef struct VDEState {
4619 VLANClientState *vc;
4623 static void vde_to_qemu(void *opaque)
4625 VDEState *s = opaque;
4629 size = vde_recv(s->vde, buf, sizeof(buf), 0);
4631 qemu_send_packet(s->vc, buf, size);
4635 static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4637 VDEState *s = opaque;
4640 ret = vde_send(s->vde, buf, size, 0);
4641 if (ret < 0 && errno == EINTR) {
4648 static int net_vde_init(VLANState *vlan, const char *sock, int port,
4649 const char *group, int mode)
4652 char *init_group = strlen(group) ? (char *)group : NULL;
4653 char *init_sock = strlen(sock) ? (char *)sock : NULL;
4655 struct vde_open_args args = {
4657 .group = init_group,
4661 s = qemu_mallocz(sizeof(VDEState));
4664 s->vde = vde_open(init_sock, "QEMU", &args);
4669 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4670 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4671 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4672 sock, vde_datafd(s->vde));
4677 /* network connection */
4678 typedef struct NetSocketState {
4679 VLANClientState *vc;
4681 int state; /* 0 = getting length, 1 = getting data */
4685 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4688 typedef struct NetSocketListenState {
4691 } NetSocketListenState;
4693 /* XXX: we consider we can send the whole packet without blocking */
4694 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4696 NetSocketState *s = opaque;
4700 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4701 send_all(s->fd, buf, size);
4704 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4706 NetSocketState *s = opaque;
4707 sendto(s->fd, buf, size, 0,
4708 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4711 static void net_socket_send(void *opaque)
4713 NetSocketState *s = opaque;
4718 size = recv(s->fd, buf1, sizeof(buf1), 0);
4720 err = socket_error();
4721 if (err != EWOULDBLOCK)
4723 } else if (size == 0) {
4724 /* end of connection */
4726 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4732 /* reassemble a packet from the network */
4738 memcpy(s->buf + s->index, buf, l);
4742 if (s->index == 4) {
4744 s->packet_len = ntohl(*(uint32_t *)s->buf);
4750 l = s->packet_len - s->index;
4753 memcpy(s->buf + s->index, buf, l);
4757 if (s->index >= s->packet_len) {
4758 qemu_send_packet(s->vc, s->buf, s->packet_len);
4767 static void net_socket_send_dgram(void *opaque)
4769 NetSocketState *s = opaque;
4772 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4776 /* end of connection */
4777 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4780 qemu_send_packet(s->vc, s->buf, size);
4783 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4788 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4789 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4790 inet_ntoa(mcastaddr->sin_addr),
4791 (int)ntohl(mcastaddr->sin_addr.s_addr));
4795 fd = socket(PF_INET, SOCK_DGRAM, 0);
4797 perror("socket(PF_INET, SOCK_DGRAM)");
4802 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4803 (const char *)&val, sizeof(val));
4805 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4809 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4815 /* Add host to multicast group */
4816 imr.imr_multiaddr = mcastaddr->sin_addr;
4817 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4819 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4820 (const char *)&imr, sizeof(struct ip_mreq));
4822 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4826 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4828 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4829 (const char *)&val, sizeof(val));
4831 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4835 socket_set_nonblock(fd);
4843 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4846 struct sockaddr_in saddr;
4848 socklen_t saddr_len;
4851 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4852 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4853 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4857 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4859 if (saddr.sin_addr.s_addr==0) {
4860 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4864 /* clone dgram socket */
4865 newfd = net_socket_mcast_create(&saddr);
4867 /* error already reported by net_socket_mcast_create() */
4871 /* clone newfd to fd, close newfd */
4876 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4877 fd, strerror(errno));
4882 s = qemu_mallocz(sizeof(NetSocketState));
4887 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4888 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4890 /* mcast: save bound address as dst */
4891 if (is_connected) s->dgram_dst=saddr;
4893 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4894 "socket: fd=%d (%s mcast=%s:%d)",
4895 fd, is_connected? "cloned" : "",
4896 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4900 static void net_socket_connect(void *opaque)
4902 NetSocketState *s = opaque;
4903 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4906 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4910 s = qemu_mallocz(sizeof(NetSocketState));
4914 s->vc = qemu_new_vlan_client(vlan,
4915 net_socket_receive, NULL, s);
4916 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4917 "socket: fd=%d", fd);
4919 net_socket_connect(s);
4921 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4926 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4929 int so_type=-1, optlen=sizeof(so_type);
4931 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4932 (socklen_t *)&optlen)< 0) {
4933 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4938 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4940 return net_socket_fd_init_stream(vlan, fd, is_connected);
4942 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4943 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4944 return net_socket_fd_init_stream(vlan, fd, is_connected);
4949 static void net_socket_accept(void *opaque)
4951 NetSocketListenState *s = opaque;
4953 struct sockaddr_in saddr;
4958 len = sizeof(saddr);
4959 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4960 if (fd < 0 && errno != EINTR) {
4962 } else if (fd >= 0) {
4966 s1 = net_socket_fd_init(s->vlan, fd, 1);
4970 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4971 "socket: connection from %s:%d",
4972 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4976 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4978 NetSocketListenState *s;
4980 struct sockaddr_in saddr;
4982 if (parse_host_port(&saddr, host_str) < 0)
4985 s = qemu_mallocz(sizeof(NetSocketListenState));
4989 fd = socket(PF_INET, SOCK_STREAM, 0);
4994 socket_set_nonblock(fd);
4996 /* allow fast reuse */
4998 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5000 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5005 ret = listen(fd, 0);
5012 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5016 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5019 int fd, connected, ret, err;
5020 struct sockaddr_in saddr;
5022 if (parse_host_port(&saddr, host_str) < 0)
5025 fd = socket(PF_INET, SOCK_STREAM, 0);
5030 socket_set_nonblock(fd);
5034 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5036 err = socket_error();
5037 if (err == EINTR || err == EWOULDBLOCK) {
5038 } else if (err == EINPROGRESS) {
5041 } else if (err == WSAEALREADY) {
5054 s = net_socket_fd_init(vlan, fd, connected);
5057 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5058 "socket: connect to %s:%d",
5059 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5063 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5067 struct sockaddr_in saddr;
5069 if (parse_host_port(&saddr, host_str) < 0)
5073 fd = net_socket_mcast_create(&saddr);
5077 s = net_socket_fd_init(vlan, fd, 0);
5081 s->dgram_dst = saddr;
5083 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5084 "socket: mcast=%s:%d",
5085 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5090 static const char *get_opt_name(char *buf, int buf_size, const char *p)
5095 while (*p != '\0' && *p != '=') {
5096 if (q && (q - buf) < buf_size - 1)
5106 static const char *get_opt_value(char *buf, int buf_size, const char *p)
5111 while (*p != '\0') {
5113 if (*(p + 1) != ',')
5117 if (q && (q - buf) < buf_size - 1)
5127 static int get_param_value(char *buf, int buf_size,
5128 const char *tag, const char *str)
5135 p = get_opt_name(option, sizeof(option), p);
5139 if (!strcmp(tag, option)) {
5140 (void)get_opt_value(buf, buf_size, p);
5143 p = get_opt_value(NULL, 0, p);
5152 static int check_params(char *buf, int buf_size,
5153 const char * const *params, const char *str)
5160 p = get_opt_name(buf, buf_size, p);
5164 for(i = 0; params[i] != NULL; i++)
5165 if (!strcmp(params[i], buf))
5167 if (params[i] == NULL)
5169 p = get_opt_value(NULL, 0, p);
5177 static int net_client_init(const char *device, const char *p)
5184 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5185 vlan_id = strtol(buf, NULL, 0);
5187 vlan = qemu_find_vlan(vlan_id);
5189 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5192 if (!strcmp(device, "nic")) {
5196 if (nb_nics >= MAX_NICS) {
5197 fprintf(stderr, "Too Many NICs\n");
5200 nd = &nd_table[nb_nics];
5201 macaddr = nd->macaddr;
5207 macaddr[5] = 0x56 + nb_nics;
5209 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5210 if (parse_macaddr(macaddr, buf) < 0) {
5211 fprintf(stderr, "invalid syntax for ethernet address\n");
5215 if (get_param_value(buf, sizeof(buf), "model", p)) {
5216 nd->model = strdup(buf);
5220 vlan->nb_guest_devs++;
5223 if (!strcmp(device, "none")) {
5224 /* does nothing. It is needed to signal that no network cards
5229 if (!strcmp(device, "user")) {
5230 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5231 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5233 vlan->nb_host_devs++;
5234 ret = net_slirp_init(vlan);
5238 if (!strcmp(device, "tap")) {
5240 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5241 fprintf(stderr, "tap: no interface name\n");
5244 vlan->nb_host_devs++;
5245 ret = tap_win32_init(vlan, ifname);
5248 if (!strcmp(device, "tap")) {
5250 char setup_script[1024], down_script[1024];
5252 vlan->nb_host_devs++;
5253 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5254 fd = strtol(buf, NULL, 0);
5255 fcntl(fd, F_SETFL, O_NONBLOCK);
5257 if (net_tap_fd_init(vlan, fd))
5260 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5263 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5264 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5266 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5267 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5269 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5273 if (!strcmp(device, "socket")) {
5274 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5276 fd = strtol(buf, NULL, 0);
5278 if (net_socket_fd_init(vlan, fd, 1))
5280 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5281 ret = net_socket_listen_init(vlan, buf);
5282 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5283 ret = net_socket_connect_init(vlan, buf);
5284 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5285 ret = net_socket_mcast_init(vlan, buf);
5287 fprintf(stderr, "Unknown socket options: %s\n", p);
5290 vlan->nb_host_devs++;
5293 if (!strcmp(device, "vde")) {
5294 char vde_sock[1024], vde_group[512];
5295 int vde_port, vde_mode;
5296 vlan->nb_host_devs++;
5297 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5300 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5301 vde_port = strtol(buf, NULL, 10);
5305 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5306 vde_group[0] = '\0';
5308 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5309 vde_mode = strtol(buf, NULL, 8);
5313 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5317 fprintf(stderr, "Unknown network device: %s\n", device);
5321 fprintf(stderr, "Could not initialize device '%s'\n", device);
5327 static int net_client_parse(const char *str)
5335 while (*p != '\0' && *p != ',') {
5336 if ((q - device) < sizeof(device) - 1)
5344 return net_client_init(device, p);
5347 void do_info_network(void)
5350 VLANClientState *vc;
5352 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5353 term_printf("VLAN %d devices:\n", vlan->id);
5354 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5355 term_printf(" %s\n", vc->info_str);
5359 /***********************************************************/
5360 /* Bluetooth support */
5363 static struct HCIInfo *hci_table[MAX_NICS];
5364 static struct bt_vlan_s {
5365 struct bt_scatternet_s net;
5367 struct bt_vlan_s *next;
5370 /* find or alloc a new bluetooth "VLAN" */
5371 static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
5373 struct bt_vlan_s **pvlan, *vlan;
5374 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
5378 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
5380 pvlan = &first_bt_vlan;
5381 while (*pvlan != NULL)
5382 pvlan = &(*pvlan)->next;
5387 static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
5391 static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
5396 static struct HCIInfo null_hci = {
5397 .cmd_send = null_hci_send,
5398 .sco_send = null_hci_send,
5399 .acl_send = null_hci_send,
5400 .bdaddr_set = null_hci_addr_set,
5403 struct HCIInfo *qemu_next_hci(void)
5405 if (cur_hci == nb_hcis)
5408 return hci_table[cur_hci++];
5411 /***********************************************************/
5412 /* QEMU Block devices */
5414 #define HD_ALIAS "index=%d,media=disk"
5416 #define CDROM_ALIAS "index=1,media=cdrom"
5418 #define CDROM_ALIAS "index=2,media=cdrom"
5420 #define FD_ALIAS "index=%d,if=floppy"
5421 #define PFLASH_ALIAS "if=pflash"
5422 #define MTD_ALIAS "if=mtd"
5423 #define SD_ALIAS "index=0,if=sd"
5425 static int drive_add(const char *file, const char *fmt, ...)
5429 if (nb_drives_opt >= MAX_DRIVES) {
5430 fprintf(stderr, "qemu: too many drives\n");
5434 drives_opt[nb_drives_opt].file = file;
5436 vsnprintf(drives_opt[nb_drives_opt].opt,
5437 sizeof(drives_opt[0].opt), fmt, ap);
5440 return nb_drives_opt++;
5443 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5447 /* seek interface, bus and unit */
5449 for (index = 0; index < nb_drives; index++)
5450 if (drives_table[index].type == type &&
5451 drives_table[index].bus == bus &&
5452 drives_table[index].unit == unit)
5458 int drive_get_max_bus(BlockInterfaceType type)
5464 for (index = 0; index < nb_drives; index++) {
5465 if(drives_table[index].type == type &&
5466 drives_table[index].bus > max_bus)
5467 max_bus = drives_table[index].bus;
5472 static void bdrv_format_print(void *opaque, const char *name)
5474 fprintf(stderr, " %s", name);
5477 static int drive_init(struct drive_opt *arg, int snapshot,
5478 QEMUMachine *machine)
5483 const char *mediastr = "";
5484 BlockInterfaceType type;
5485 enum { MEDIA_DISK, MEDIA_CDROM } media;
5486 int bus_id, unit_id;
5487 int cyls, heads, secs, translation;
5488 BlockDriverState *bdrv;
5489 BlockDriver *drv = NULL;
5494 char *str = arg->opt;
5495 static const char * const params[] = { "bus", "unit", "if", "index",
5496 "cyls", "heads", "secs", "trans",
5497 "media", "snapshot", "file",
5498 "cache", "format", NULL };
5500 if (check_params(buf, sizeof(buf), params, str) < 0) {
5501 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5507 cyls = heads = secs = 0;
5510 translation = BIOS_ATA_TRANSLATION_AUTO;
5514 if (machine->use_scsi) {
5516 max_devs = MAX_SCSI_DEVS;
5517 pstrcpy(devname, sizeof(devname), "scsi");
5520 max_devs = MAX_IDE_DEVS;
5521 pstrcpy(devname, sizeof(devname), "ide");
5525 /* extract parameters */
5527 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5528 bus_id = strtol(buf, NULL, 0);
5530 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5535 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5536 unit_id = strtol(buf, NULL, 0);
5538 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5543 if (get_param_value(buf, sizeof(buf), "if", str)) {
5544 pstrcpy(devname, sizeof(devname), buf);
5545 if (!strcmp(buf, "ide")) {
5547 max_devs = MAX_IDE_DEVS;
5548 } else if (!strcmp(buf, "scsi")) {
5550 max_devs = MAX_SCSI_DEVS;
5551 } else if (!strcmp(buf, "floppy")) {
5554 } else if (!strcmp(buf, "pflash")) {
5557 } else if (!strcmp(buf, "mtd")) {
5560 } else if (!strcmp(buf, "sd")) {
5564 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5569 if (get_param_value(buf, sizeof(buf), "index", str)) {
5570 index = strtol(buf, NULL, 0);
5572 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5577 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5578 cyls = strtol(buf, NULL, 0);
5581 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5582 heads = strtol(buf, NULL, 0);
5585 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5586 secs = strtol(buf, NULL, 0);
5589 if (cyls || heads || secs) {
5590 if (cyls < 1 || cyls > 16383) {
5591 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5594 if (heads < 1 || heads > 16) {
5595 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5598 if (secs < 1 || secs > 63) {
5599 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5604 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5607 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5611 if (!strcmp(buf, "none"))
5612 translation = BIOS_ATA_TRANSLATION_NONE;
5613 else if (!strcmp(buf, "lba"))
5614 translation = BIOS_ATA_TRANSLATION_LBA;
5615 else if (!strcmp(buf, "auto"))
5616 translation = BIOS_ATA_TRANSLATION_AUTO;
5618 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5623 if (get_param_value(buf, sizeof(buf), "media", str)) {
5624 if (!strcmp(buf, "disk")) {
5626 } else if (!strcmp(buf, "cdrom")) {
5627 if (cyls || secs || heads) {
5629 "qemu: '%s' invalid physical CHS format\n", str);
5632 media = MEDIA_CDROM;
5634 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5639 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5640 if (!strcmp(buf, "on"))
5642 else if (!strcmp(buf, "off"))
5645 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5650 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5651 if (!strcmp(buf, "off"))
5653 else if (!strcmp(buf, "on"))
5656 fprintf(stderr, "qemu: invalid cache option\n");
5661 if (get_param_value(buf, sizeof(buf), "format", str)) {
5662 if (strcmp(buf, "?") == 0) {
5663 fprintf(stderr, "qemu: Supported formats:");
5664 bdrv_iterate_format(bdrv_format_print, NULL);
5665 fprintf(stderr, "\n");
5668 drv = bdrv_find_format(buf);
5670 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5675 if (arg->file == NULL)
5676 get_param_value(file, sizeof(file), "file", str);
5678 pstrcpy(file, sizeof(file), arg->file);
5680 /* compute bus and unit according index */
5683 if (bus_id != 0 || unit_id != -1) {
5685 "qemu: '%s' index cannot be used with bus and unit\n", str);
5693 unit_id = index % max_devs;
5694 bus_id = index / max_devs;
5698 /* if user doesn't specify a unit_id,
5699 * try to find the first free
5702 if (unit_id == -1) {
5704 while (drive_get_index(type, bus_id, unit_id) != -1) {
5706 if (max_devs && unit_id >= max_devs) {
5707 unit_id -= max_devs;
5715 if (max_devs && unit_id >= max_devs) {
5716 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5717 str, unit_id, max_devs - 1);
5722 * ignore multiple definitions
5725 if (drive_get_index(type, bus_id, unit_id) != -1)
5730 if (type == IF_IDE || type == IF_SCSI)
5731 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5733 snprintf(buf, sizeof(buf), "%s%i%s%i",
5734 devname, bus_id, mediastr, unit_id);
5736 snprintf(buf, sizeof(buf), "%s%s%i",
5737 devname, mediastr, unit_id);
5738 bdrv = bdrv_new(buf);
5739 drives_table[nb_drives].bdrv = bdrv;
5740 drives_table[nb_drives].type = type;
5741 drives_table[nb_drives].bus = bus_id;
5742 drives_table[nb_drives].unit = unit_id;
5751 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5752 bdrv_set_translation_hint(bdrv, translation);
5756 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5761 /* FIXME: This isn't really a floppy, but it's a reasonable
5764 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5774 bdrv_flags |= BDRV_O_SNAPSHOT;
5776 bdrv_flags |= BDRV_O_DIRECT;
5777 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5778 fprintf(stderr, "qemu: could not open disk image %s\n",
5785 /***********************************************************/
5788 static USBPort *used_usb_ports;
5789 static USBPort *free_usb_ports;
5791 /* ??? Maybe change this to register a hub to keep track of the topology. */
5792 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5793 usb_attachfn attach)
5795 port->opaque = opaque;
5796 port->index = index;
5797 port->attach = attach;
5798 port->next = free_usb_ports;
5799 free_usb_ports = port;
5802 int usb_device_add_dev(USBDevice *dev)
5806 /* Find a USB port to add the device to. */
5807 port = free_usb_ports;
5811 /* Create a new hub and chain it on. */
5812 free_usb_ports = NULL;
5813 port->next = used_usb_ports;
5814 used_usb_ports = port;
5816 hub = usb_hub_init(VM_USB_HUB_SIZE);
5817 usb_attach(port, hub);
5818 port = free_usb_ports;
5821 free_usb_ports = port->next;
5822 port->next = used_usb_ports;
5823 used_usb_ports = port;
5824 usb_attach(port, dev);
5828 static int usb_device_add(const char *devname)
5833 if (!free_usb_ports)
5836 if (strstart(devname, "host:", &p)) {
5837 dev = usb_host_device_open(p);
5838 } else if (!strcmp(devname, "mouse")) {
5839 dev = usb_mouse_init();
5840 } else if (!strcmp(devname, "tablet")) {
5841 dev = usb_tablet_init();
5842 } else if (!strcmp(devname, "keyboard")) {
5843 dev = usb_keyboard_init();
5844 } else if (strstart(devname, "disk:", &p)) {
5845 dev = usb_msd_init(p);
5846 } else if (!strcmp(devname, "wacom-tablet")) {
5847 dev = usb_wacom_init();
5848 } else if (strstart(devname, "serial:", &p)) {
5849 dev = usb_serial_init(p);
5850 #ifdef CONFIG_BRLAPI
5851 } else if (!strcmp(devname, "braille")) {
5852 dev = usb_baum_init();
5854 } else if (strstart(devname, "net:", &p)) {
5857 if (net_client_init("nic", p) < 0)
5859 nd_table[nic].model = "usb";
5860 dev = usb_net_init(&nd_table[nic]);
5867 return usb_device_add_dev(dev);
5870 int usb_device_del_addr(int bus_num, int addr)
5876 if (!used_usb_ports)
5882 lastp = &used_usb_ports;
5883 port = used_usb_ports;
5884 while (port && port->dev->addr != addr) {
5885 lastp = &port->next;
5893 *lastp = port->next;
5894 usb_attach(port, NULL);
5895 dev->handle_destroy(dev);
5896 port->next = free_usb_ports;
5897 free_usb_ports = port;
5901 static int usb_device_del(const char *devname)
5906 if (strstart(devname, "host:", &p))
5907 return usb_host_device_close(p);
5909 if (!used_usb_ports)
5912 p = strchr(devname, '.');
5915 bus_num = strtoul(devname, NULL, 0);
5916 addr = strtoul(p + 1, NULL, 0);
5918 return usb_device_del_addr(bus_num, addr);
5921 void do_usb_add(const char *devname)
5923 usb_device_add(devname);
5926 void do_usb_del(const char *devname)
5928 usb_device_del(devname);
5935 const char *speed_str;
5938 term_printf("USB support not enabled\n");
5942 for (port = used_usb_ports; port; port = port->next) {
5946 switch(dev->speed) {
5950 case USB_SPEED_FULL:
5953 case USB_SPEED_HIGH:
5960 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5961 0, dev->addr, speed_str, dev->devname);
5965 /***********************************************************/
5966 /* PCMCIA/Cardbus */
5968 static struct pcmcia_socket_entry_s {
5969 struct pcmcia_socket_s *socket;
5970 struct pcmcia_socket_entry_s *next;
5971 } *pcmcia_sockets = 0;
5973 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5975 struct pcmcia_socket_entry_s *entry;
5977 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5978 entry->socket = socket;
5979 entry->next = pcmcia_sockets;
5980 pcmcia_sockets = entry;
5983 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5985 struct pcmcia_socket_entry_s *entry, **ptr;
5987 ptr = &pcmcia_sockets;
5988 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5989 if (entry->socket == socket) {
5995 void pcmcia_info(void)
5997 struct pcmcia_socket_entry_s *iter;
5998 if (!pcmcia_sockets)
5999 term_printf("No PCMCIA sockets\n");
6001 for (iter = pcmcia_sockets; iter; iter = iter->next)
6002 term_printf("%s: %s\n", iter->socket->slot_string,
6003 iter->socket->attached ? iter->socket->card_string :
6007 /***********************************************************/
6010 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
6014 static void dumb_resize(DisplayState *ds, int w, int h)
6018 static void dumb_refresh(DisplayState *ds)
6020 #if defined(CONFIG_SDL)
6025 static void dumb_display_init(DisplayState *ds)
6030 ds->dpy_update = dumb_update;
6031 ds->dpy_resize = dumb_resize;
6032 ds->dpy_refresh = dumb_refresh;
6033 ds->gui_timer_interval = 500;
6037 /***********************************************************/
6040 #define MAX_IO_HANDLERS 64
6042 typedef struct IOHandlerRecord {
6044 IOCanRWHandler *fd_read_poll;
6046 IOHandler *fd_write;
6049 /* temporary data */
6051 struct IOHandlerRecord *next;
6054 static IOHandlerRecord *first_io_handler;
6056 /* XXX: fd_read_poll should be suppressed, but an API change is
6057 necessary in the character devices to suppress fd_can_read(). */
6058 int qemu_set_fd_handler2(int fd,
6059 IOCanRWHandler *fd_read_poll,
6061 IOHandler *fd_write,
6064 IOHandlerRecord **pioh, *ioh;
6066 if (!fd_read && !fd_write) {
6067 pioh = &first_io_handler;
6072 if (ioh->fd == fd) {
6079 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6083 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6086 ioh->next = first_io_handler;
6087 first_io_handler = ioh;
6090 ioh->fd_read_poll = fd_read_poll;
6091 ioh->fd_read = fd_read;
6092 ioh->fd_write = fd_write;
6093 ioh->opaque = opaque;
6099 int qemu_set_fd_handler(int fd,
6101 IOHandler *fd_write,
6104 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6107 /***********************************************************/
6108 /* Polling handling */
6110 typedef struct PollingEntry {
6113 struct PollingEntry *next;
6116 static PollingEntry *first_polling_entry;
6118 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6120 PollingEntry **ppe, *pe;
6121 pe = qemu_mallocz(sizeof(PollingEntry));
6125 pe->opaque = opaque;
6126 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6131 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6133 PollingEntry **ppe, *pe;
6134 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6136 if (pe->func == func && pe->opaque == opaque) {
6145 /***********************************************************/
6146 /* Wait objects support */
6147 typedef struct WaitObjects {
6149 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6150 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6151 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6154 static WaitObjects wait_objects = {0};
6156 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6158 WaitObjects *w = &wait_objects;
6160 if (w->num >= MAXIMUM_WAIT_OBJECTS)
6162 w->events[w->num] = handle;
6163 w->func[w->num] = func;
6164 w->opaque[w->num] = opaque;
6169 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6172 WaitObjects *w = &wait_objects;
6175 for (i = 0; i < w->num; i++) {
6176 if (w->events[i] == handle)
6179 w->events[i] = w->events[i + 1];
6180 w->func[i] = w->func[i + 1];
6181 w->opaque[i] = w->opaque[i + 1];
6189 /***********************************************************/
6190 /* savevm/loadvm support */
6192 #define IO_BUF_SIZE 32768
6195 QEMUFilePutBufferFunc *put_buffer;
6196 QEMUFileGetBufferFunc *get_buffer;
6197 QEMUFileCloseFunc *close;
6198 QEMUFileRateLimit *rate_limit;
6202 int64_t buf_offset; /* start of buffer when writing, end of buffer
6205 int buf_size; /* 0 when writing */
6206 uint8_t buf[IO_BUF_SIZE];
6211 typedef struct QEMUFileFD
6217 static int fd_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6219 QEMUFileFD *s = opaque;
6223 len = read(s->fd, buf, size);
6224 } while (len == -1 && errno == EINTR);
6232 static int fd_close(void *opaque)
6234 QEMUFileFD *s = opaque;
6239 QEMUFile *qemu_fopen_fd(int fd)
6241 QEMUFileFD *s = qemu_mallocz(sizeof(QEMUFileFD));
6247 s->file = qemu_fopen_ops(s, NULL, fd_get_buffer, fd_close, NULL);
6251 typedef struct QEMUFileStdio
6256 static int file_put_buffer(void *opaque, const uint8_t *buf,
6257 int64_t pos, int size)
6259 QEMUFileStdio *s = opaque;
6260 fseek(s->outfile, pos, SEEK_SET);
6261 fwrite(buf, 1, size, s->outfile);
6265 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6267 QEMUFileStdio *s = opaque;
6268 fseek(s->outfile, pos, SEEK_SET);
6269 return fread(buf, 1, size, s->outfile);
6272 static int file_close(void *opaque)
6274 QEMUFileStdio *s = opaque;
6280 QEMUFile *qemu_fopen(const char *filename, const char *mode)
6284 s = qemu_mallocz(sizeof(QEMUFileStdio));
6288 s->outfile = fopen(filename, mode);
6292 if (!strcmp(mode, "wb"))
6293 return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
6294 else if (!strcmp(mode, "rb"))
6295 return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
6304 typedef struct QEMUFileBdrv
6306 BlockDriverState *bs;
6307 int64_t base_offset;
6310 static int bdrv_put_buffer(void *opaque, const uint8_t *buf,
6311 int64_t pos, int size)
6313 QEMUFileBdrv *s = opaque;
6314 bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
6318 static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
6320 QEMUFileBdrv *s = opaque;
6321 return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
6324 static int bdrv_fclose(void *opaque)
6326 QEMUFileBdrv *s = opaque;
6331 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6335 s = qemu_mallocz(sizeof(QEMUFileBdrv));
6340 s->base_offset = offset;
6343 return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
6345 return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
6348 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
6349 QEMUFileGetBufferFunc *get_buffer,
6350 QEMUFileCloseFunc *close,
6351 QEMUFileRateLimit *rate_limit)
6355 f = qemu_mallocz(sizeof(QEMUFile));
6360 f->put_buffer = put_buffer;
6361 f->get_buffer = get_buffer;
6363 f->rate_limit = rate_limit;
6369 int qemu_file_has_error(QEMUFile *f)
6371 return f->has_error;
6374 void qemu_fflush(QEMUFile *f)
6379 if (f->is_write && f->buf_index > 0) {
6382 len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
6384 f->buf_offset += f->buf_index;
6391 static void qemu_fill_buffer(QEMUFile *f)
6401 len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
6405 f->buf_offset += len;
6406 } else if (len != -EAGAIN)
6410 int qemu_fclose(QEMUFile *f)
6415 ret = f->close(f->opaque);
6420 void qemu_file_put_notify(QEMUFile *f)
6422 f->put_buffer(f->opaque, NULL, 0, 0);
6425 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6429 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
6431 "Attempted to write to buffer while read buffer is not empty\n");
6435 while (!f->has_error && size > 0) {
6436 l = IO_BUF_SIZE - f->buf_index;
6439 memcpy(f->buf + f->buf_index, buf, l);
6444 if (f->buf_index >= IO_BUF_SIZE)
6449 void qemu_put_byte(QEMUFile *f, int v)
6451 if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
6453 "Attempted to write to buffer while read buffer is not empty\n");
6457 f->buf[f->buf_index++] = v;
6459 if (f->buf_index >= IO_BUF_SIZE)
6463 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6472 l = f->buf_size - f->buf_index;
6474 qemu_fill_buffer(f);
6475 l = f->buf_size - f->buf_index;
6481 memcpy(buf, f->buf + f->buf_index, l);
6486 return size1 - size;
6489 int qemu_get_byte(QEMUFile *f)
6494 if (f->buf_index >= f->buf_size) {
6495 qemu_fill_buffer(f);
6496 if (f->buf_index >= f->buf_size)
6499 return f->buf[f->buf_index++];
6502 int64_t qemu_ftell(QEMUFile *f)
6504 return f->buf_offset - f->buf_size + f->buf_index;
6507 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6509 if (whence == SEEK_SET) {
6511 } else if (whence == SEEK_CUR) {
6512 pos += qemu_ftell(f);
6514 /* SEEK_END not supported */
6517 if (f->put_buffer) {
6519 f->buf_offset = pos;
6521 f->buf_offset = pos;
6528 int qemu_file_rate_limit(QEMUFile *f)
6531 return f->rate_limit(f->opaque);
6536 void qemu_put_be16(QEMUFile *f, unsigned int v)
6538 qemu_put_byte(f, v >> 8);
6539 qemu_put_byte(f, v);
6542 void qemu_put_be32(QEMUFile *f, unsigned int v)
6544 qemu_put_byte(f, v >> 24);
6545 qemu_put_byte(f, v >> 16);
6546 qemu_put_byte(f, v >> 8);
6547 qemu_put_byte(f, v);
6550 void qemu_put_be64(QEMUFile *f, uint64_t v)
6552 qemu_put_be32(f, v >> 32);
6553 qemu_put_be32(f, v);
6556 unsigned int qemu_get_be16(QEMUFile *f)
6559 v = qemu_get_byte(f) << 8;
6560 v |= qemu_get_byte(f);
6564 unsigned int qemu_get_be32(QEMUFile *f)
6567 v = qemu_get_byte(f) << 24;
6568 v |= qemu_get_byte(f) << 16;
6569 v |= qemu_get_byte(f) << 8;
6570 v |= qemu_get_byte(f);
6574 uint64_t qemu_get_be64(QEMUFile *f)
6577 v = (uint64_t)qemu_get_be32(f) << 32;
6578 v |= qemu_get_be32(f);
6582 typedef struct SaveStateEntry {
6587 SaveLiveStateHandler *save_live_state;
6588 SaveStateHandler *save_state;
6589 LoadStateHandler *load_state;
6591 struct SaveStateEntry *next;
6594 static SaveStateEntry *first_se;
6596 /* TODO: Individual devices generally have very little idea about the rest
6597 of the system, so instance_id should be removed/replaced.
6598 Meanwhile pass -1 as instance_id if you do not already have a clearly
6599 distinguishing id for all instances of your device class. */
6600 int register_savevm_live(const char *idstr,
6603 SaveLiveStateHandler *save_live_state,
6604 SaveStateHandler *save_state,
6605 LoadStateHandler *load_state,
6608 SaveStateEntry *se, **pse;
6609 static int global_section_id;
6611 se = qemu_malloc(sizeof(SaveStateEntry));
6614 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6615 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6616 se->version_id = version_id;
6617 se->section_id = global_section_id++;
6618 se->save_live_state = save_live_state;
6619 se->save_state = save_state;
6620 se->load_state = load_state;
6621 se->opaque = opaque;
6624 /* add at the end of list */
6626 while (*pse != NULL) {
6627 if (instance_id == -1
6628 && strcmp(se->idstr, (*pse)->idstr) == 0
6629 && se->instance_id <= (*pse)->instance_id)
6630 se->instance_id = (*pse)->instance_id + 1;
6631 pse = &(*pse)->next;
6637 int register_savevm(const char *idstr,
6640 SaveStateHandler *save_state,
6641 LoadStateHandler *load_state,
6644 return register_savevm_live(idstr, instance_id, version_id,
6645 NULL, save_state, load_state, opaque);
6648 #define QEMU_VM_FILE_MAGIC 0x5145564d
6649 #define QEMU_VM_FILE_VERSION_COMPAT 0x00000002
6650 #define QEMU_VM_FILE_VERSION 0x00000003
6652 #define QEMU_VM_EOF 0x00
6653 #define QEMU_VM_SECTION_START 0x01
6654 #define QEMU_VM_SECTION_PART 0x02
6655 #define QEMU_VM_SECTION_END 0x03
6656 #define QEMU_VM_SECTION_FULL 0x04
6658 int qemu_savevm_state_begin(QEMUFile *f)
6662 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6663 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6665 for (se = first_se; se != NULL; se = se->next) {
6668 if (se->save_live_state == NULL)
6672 qemu_put_byte(f, QEMU_VM_SECTION_START);
6673 qemu_put_be32(f, se->section_id);
6676 len = strlen(se->idstr);
6677 qemu_put_byte(f, len);
6678 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6680 qemu_put_be32(f, se->instance_id);
6681 qemu_put_be32(f, se->version_id);
6683 se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
6686 if (qemu_file_has_error(f))
6692 int qemu_savevm_state_iterate(QEMUFile *f)
6697 for (se = first_se; se != NULL; se = se->next) {
6698 if (se->save_live_state == NULL)
6702 qemu_put_byte(f, QEMU_VM_SECTION_PART);
6703 qemu_put_be32(f, se->section_id);
6705 ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
6711 if (qemu_file_has_error(f))
6717 int qemu_savevm_state_complete(QEMUFile *f)
6721 for (se = first_se; se != NULL; se = se->next) {
6722 if (se->save_live_state == NULL)
6726 qemu_put_byte(f, QEMU_VM_SECTION_END);
6727 qemu_put_be32(f, se->section_id);
6729 se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
6732 for(se = first_se; se != NULL; se = se->next) {
6735 if (se->save_state == NULL)
6739 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
6740 qemu_put_be32(f, se->section_id);
6743 len = strlen(se->idstr);
6744 qemu_put_byte(f, len);
6745 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6747 qemu_put_be32(f, se->instance_id);
6748 qemu_put_be32(f, se->version_id);
6750 se->save_state(f, se->opaque);
6753 qemu_put_byte(f, QEMU_VM_EOF);
6755 if (qemu_file_has_error(f))
6761 int qemu_savevm_state(QEMUFile *f)
6763 int saved_vm_running;
6766 saved_vm_running = vm_running;
6769 ret = qemu_savevm_state_begin(f);
6774 ret = qemu_savevm_state_iterate(f);
6779 ret = qemu_savevm_state_complete(f);
6782 if (qemu_file_has_error(f))
6785 if (!ret && saved_vm_running)
6791 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6795 for(se = first_se; se != NULL; se = se->next) {
6796 if (!strcmp(se->idstr, idstr) &&
6797 instance_id == se->instance_id)
6803 typedef struct LoadStateEntry {
6807 struct LoadStateEntry *next;
6810 static int qemu_loadvm_state_v2(QEMUFile *f)
6813 int len, ret, instance_id, record_len, version_id;
6814 int64_t total_len, end_pos, cur_pos;
6817 total_len = qemu_get_be64(f);
6818 end_pos = total_len + qemu_ftell(f);
6820 if (qemu_ftell(f) >= end_pos)
6822 len = qemu_get_byte(f);
6823 qemu_get_buffer(f, (uint8_t *)idstr, len);
6825 instance_id = qemu_get_be32(f);
6826 version_id = qemu_get_be32(f);
6827 record_len = qemu_get_be32(f);
6828 cur_pos = qemu_ftell(f);
6829 se = find_se(idstr, instance_id);
6831 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6832 instance_id, idstr);
6834 ret = se->load_state(f, se->opaque, version_id);
6836 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6837 instance_id, idstr);
6840 /* always seek to exact end of record */
6841 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6844 if (qemu_file_has_error(f))
6850 int qemu_loadvm_state(QEMUFile *f)
6852 LoadStateEntry *first_le = NULL;
6853 uint8_t section_type;
6857 v = qemu_get_be32(f);
6858 if (v != QEMU_VM_FILE_MAGIC)
6861 v = qemu_get_be32(f);
6862 if (v == QEMU_VM_FILE_VERSION_COMPAT)
6863 return qemu_loadvm_state_v2(f);
6864 if (v != QEMU_VM_FILE_VERSION)
6867 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
6868 uint32_t instance_id, version_id, section_id;
6874 switch (section_type) {
6875 case QEMU_VM_SECTION_START:
6876 case QEMU_VM_SECTION_FULL:
6877 /* Read section start */
6878 section_id = qemu_get_be32(f);
6879 len = qemu_get_byte(f);
6880 qemu_get_buffer(f, (uint8_t *)idstr, len);
6882 instance_id = qemu_get_be32(f);
6883 version_id = qemu_get_be32(f);
6885 /* Find savevm section */
6886 se = find_se(idstr, instance_id);
6888 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
6893 /* Validate version */
6894 if (version_id > se->version_id) {
6895 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
6896 version_id, idstr, se->version_id);
6902 le = qemu_mallocz(sizeof(*le));
6909 le->section_id = section_id;
6910 le->version_id = version_id;
6911 le->next = first_le;
6914 le->se->load_state(f, le->se->opaque, le->version_id);
6916 case QEMU_VM_SECTION_PART:
6917 case QEMU_VM_SECTION_END:
6918 section_id = qemu_get_be32(f);
6920 for (le = first_le; le && le->section_id != section_id; le = le->next);
6922 fprintf(stderr, "Unknown savevm section %d\n", section_id);
6927 le->se->load_state(f, le->se->opaque, le->version_id);
6930 fprintf(stderr, "Unknown savevm section type %d\n", section_type);
6940 LoadStateEntry *le = first_le;
6941 first_le = first_le->next;
6945 if (qemu_file_has_error(f))
6951 /* device can contain snapshots */
6952 static int bdrv_can_snapshot(BlockDriverState *bs)
6955 !bdrv_is_removable(bs) &&
6956 !bdrv_is_read_only(bs));
6959 /* device must be snapshots in order to have a reliable snapshot */
6960 static int bdrv_has_snapshot(BlockDriverState *bs)
6963 !bdrv_is_removable(bs) &&
6964 !bdrv_is_read_only(bs));
6967 static BlockDriverState *get_bs_snapshots(void)
6969 BlockDriverState *bs;
6973 return bs_snapshots;
6974 for(i = 0; i <= nb_drives; i++) {
6975 bs = drives_table[i].bdrv;
6976 if (bdrv_can_snapshot(bs))
6985 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6988 QEMUSnapshotInfo *sn_tab, *sn;
6992 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6995 for(i = 0; i < nb_sns; i++) {
6997 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
7007 void do_savevm(const char *name)
7009 BlockDriverState *bs, *bs1;
7010 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
7011 int must_delete, ret, i;
7012 BlockDriverInfo bdi1, *bdi = &bdi1;
7014 int saved_vm_running;
7021 bs = get_bs_snapshots();
7023 term_printf("No block device can accept snapshots\n");
7027 /* ??? Should this occur after vm_stop? */
7030 saved_vm_running = vm_running;
7035 ret = bdrv_snapshot_find(bs, old_sn, name);
7040 memset(sn, 0, sizeof(*sn));
7042 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
7043 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
7046 pstrcpy(sn->name, sizeof(sn->name), name);
7049 /* fill auxiliary fields */
7052 sn->date_sec = tb.time;
7053 sn->date_nsec = tb.millitm * 1000000;
7055 gettimeofday(&tv, NULL);
7056 sn->date_sec = tv.tv_sec;
7057 sn->date_nsec = tv.tv_usec * 1000;
7059 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
7061 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7062 term_printf("Device %s does not support VM state snapshots\n",
7063 bdrv_get_device_name(bs));
7067 /* save the VM state */
7068 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
7070 term_printf("Could not open VM state file\n");
7073 ret = qemu_savevm_state(f);
7074 sn->vm_state_size = qemu_ftell(f);
7077 term_printf("Error %d while writing VM\n", ret);
7081 /* create the snapshots */
7083 for(i = 0; i < nb_drives; i++) {
7084 bs1 = drives_table[i].bdrv;
7085 if (bdrv_has_snapshot(bs1)) {
7087 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
7089 term_printf("Error while deleting snapshot on '%s'\n",
7090 bdrv_get_device_name(bs1));
7093 ret = bdrv_snapshot_create(bs1, sn);
7095 term_printf("Error while creating snapshot on '%s'\n",
7096 bdrv_get_device_name(bs1));
7102 if (saved_vm_running)
7106 void do_loadvm(const char *name)
7108 BlockDriverState *bs, *bs1;
7109 BlockDriverInfo bdi1, *bdi = &bdi1;
7112 int saved_vm_running;
7114 bs = get_bs_snapshots();
7116 term_printf("No block device supports snapshots\n");
7120 /* Flush all IO requests so they don't interfere with the new state. */
7123 saved_vm_running = vm_running;
7126 for(i = 0; i <= nb_drives; i++) {
7127 bs1 = drives_table[i].bdrv;
7128 if (bdrv_has_snapshot(bs1)) {
7129 ret = bdrv_snapshot_goto(bs1, name);
7132 term_printf("Warning: ");
7135 term_printf("Snapshots not supported on device '%s'\n",
7136 bdrv_get_device_name(bs1));
7139 term_printf("Could not find snapshot '%s' on device '%s'\n",
7140 name, bdrv_get_device_name(bs1));
7143 term_printf("Error %d while activating snapshot on '%s'\n",
7144 ret, bdrv_get_device_name(bs1));
7147 /* fatal on snapshot block device */
7154 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7155 term_printf("Device %s does not support VM state snapshots\n",
7156 bdrv_get_device_name(bs));
7160 /* restore the VM state */
7161 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
7163 term_printf("Could not open VM state file\n");
7166 ret = qemu_loadvm_state(f);
7169 term_printf("Error %d while loading VM state\n", ret);
7172 if (saved_vm_running)
7176 void do_delvm(const char *name)
7178 BlockDriverState *bs, *bs1;
7181 bs = get_bs_snapshots();
7183 term_printf("No block device supports snapshots\n");
7187 for(i = 0; i <= nb_drives; i++) {
7188 bs1 = drives_table[i].bdrv;
7189 if (bdrv_has_snapshot(bs1)) {
7190 ret = bdrv_snapshot_delete(bs1, name);
7192 if (ret == -ENOTSUP)
7193 term_printf("Snapshots not supported on device '%s'\n",
7194 bdrv_get_device_name(bs1));
7196 term_printf("Error %d while deleting snapshot on '%s'\n",
7197 ret, bdrv_get_device_name(bs1));
7203 void do_info_snapshots(void)
7205 BlockDriverState *bs, *bs1;
7206 QEMUSnapshotInfo *sn_tab, *sn;
7210 bs = get_bs_snapshots();
7212 term_printf("No available block device supports snapshots\n");
7215 term_printf("Snapshot devices:");
7216 for(i = 0; i <= nb_drives; i++) {
7217 bs1 = drives_table[i].bdrv;
7218 if (bdrv_has_snapshot(bs1)) {
7220 term_printf(" %s", bdrv_get_device_name(bs1));
7225 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7227 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
7230 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
7231 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
7232 for(i = 0; i < nb_sns; i++) {
7234 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
7239 /***********************************************************/
7240 /* ram save/restore */
7242 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7246 v = qemu_get_byte(f);
7249 if (qemu_get_buffer(f, buf, len) != len)
7253 v = qemu_get_byte(f);
7254 memset(buf, v, len);
7260 if (qemu_file_has_error(f))
7266 static int ram_load_v1(QEMUFile *f, void *opaque)
7271 if (qemu_get_be32(f) != phys_ram_size)
7273 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7274 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7281 #define BDRV_HASH_BLOCK_SIZE 1024
7282 #define IOBUF_SIZE 4096
7283 #define RAM_CBLOCK_MAGIC 0xfabe
7285 typedef struct RamDecompressState {
7288 uint8_t buf[IOBUF_SIZE];
7289 } RamDecompressState;
7291 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7294 memset(s, 0, sizeof(*s));
7296 ret = inflateInit(&s->zstream);
7302 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7306 s->zstream.avail_out = len;
7307 s->zstream.next_out = buf;
7308 while (s->zstream.avail_out > 0) {
7309 if (s->zstream.avail_in == 0) {
7310 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7312 clen = qemu_get_be16(s->f);
7313 if (clen > IOBUF_SIZE)
7315 qemu_get_buffer(s->f, s->buf, clen);
7316 s->zstream.avail_in = clen;
7317 s->zstream.next_in = s->buf;
7319 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7320 if (ret != Z_OK && ret != Z_STREAM_END) {
7327 static void ram_decompress_close(RamDecompressState *s)
7329 inflateEnd(&s->zstream);
7332 #define RAM_SAVE_FLAG_FULL 0x01
7333 #define RAM_SAVE_FLAG_COMPRESS 0x02
7334 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
7335 #define RAM_SAVE_FLAG_PAGE 0x08
7336 #define RAM_SAVE_FLAG_EOS 0x10
7338 static int is_dup_page(uint8_t *page, uint8_t ch)
7340 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
7341 uint32_t *array = (uint32_t *)page;
7344 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
7345 if (array[i] != val)
7352 static int ram_save_block(QEMUFile *f)
7354 static ram_addr_t current_addr = 0;
7355 ram_addr_t saved_addr = current_addr;
7356 ram_addr_t addr = 0;
7359 while (addr < phys_ram_size) {
7360 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
7363 cpu_physical_memory_reset_dirty(current_addr,
7364 current_addr + TARGET_PAGE_SIZE,
7365 MIGRATION_DIRTY_FLAG);
7367 ch = *(phys_ram_base + current_addr);
7369 if (is_dup_page(phys_ram_base + current_addr, ch)) {
7370 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
7371 qemu_put_byte(f, ch);
7373 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
7374 qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
7380 addr += TARGET_PAGE_SIZE;
7381 current_addr = (saved_addr + addr) % phys_ram_size;
7387 static ram_addr_t ram_save_threshold = 10;
7389 static ram_addr_t ram_save_remaining(void)
7392 ram_addr_t count = 0;
7394 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7395 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
7402 static int ram_save_live(QEMUFile *f, int stage, void *opaque)
7407 /* Make sure all dirty bits are set */
7408 for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
7409 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
7410 cpu_physical_memory_set_dirty(addr);
7413 /* Enable dirty memory tracking */
7414 cpu_physical_memory_set_dirty_tracking(1);
7416 qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
7419 while (!qemu_file_rate_limit(f)) {
7422 ret = ram_save_block(f);
7423 if (ret == 0) /* no more blocks */
7427 /* try transferring iterative blocks of memory */
7430 cpu_physical_memory_set_dirty_tracking(0);
7432 /* flush all remaining blocks regardless of rate limiting */
7433 while (ram_save_block(f) != 0);
7436 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
7438 return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
7441 static int ram_load_dead(QEMUFile *f, void *opaque)
7443 RamDecompressState s1, *s = &s1;
7447 if (ram_decompress_open(s, f) < 0)
7449 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7450 if (ram_decompress_buf(s, buf, 1) < 0) {
7451 fprintf(stderr, "Error while reading ram block header\n");
7455 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7456 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7461 printf("Error block header\n");
7465 ram_decompress_close(s);
7470 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7475 if (version_id == 1)
7476 return ram_load_v1(f, opaque);
7478 if (version_id == 2) {
7479 if (qemu_get_be32(f) != phys_ram_size)
7481 return ram_load_dead(f, opaque);
7484 if (version_id != 3)
7488 addr = qemu_get_be64(f);
7490 flags = addr & ~TARGET_PAGE_MASK;
7491 addr &= TARGET_PAGE_MASK;
7493 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
7494 if (addr != phys_ram_size)
7498 if (flags & RAM_SAVE_FLAG_FULL) {
7499 if (ram_load_dead(f, opaque) < 0)
7503 if (flags & RAM_SAVE_FLAG_COMPRESS) {
7504 uint8_t ch = qemu_get_byte(f);
7505 memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
7506 } else if (flags & RAM_SAVE_FLAG_PAGE)
7507 qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
7508 } while (!(flags & RAM_SAVE_FLAG_EOS));
7513 void qemu_service_io(void)
7515 CPUState *env = cpu_single_env;
7517 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7519 if (env->kqemu_enabled) {
7520 kqemu_cpu_interrupt(env);
7526 /***********************************************************/
7527 /* bottom halves (can be seen as timers which expire ASAP) */
7536 static QEMUBH *first_bh = NULL;
7538 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7541 bh = qemu_mallocz(sizeof(QEMUBH));
7545 bh->opaque = opaque;
7549 int qemu_bh_poll(void)
7568 void qemu_bh_schedule(QEMUBH *bh)
7570 CPUState *env = cpu_single_env;
7574 bh->next = first_bh;
7577 /* stop the currently executing CPU to execute the BH ASAP */
7579 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7583 void qemu_bh_cancel(QEMUBH *bh)
7586 if (bh->scheduled) {
7589 pbh = &(*pbh)->next;
7595 void qemu_bh_delete(QEMUBH *bh)
7601 /***********************************************************/
7602 /* machine registration */
7604 static QEMUMachine *first_machine = NULL;
7606 int qemu_register_machine(QEMUMachine *m)
7609 pm = &first_machine;
7617 static QEMUMachine *find_machine(const char *name)
7621 for(m = first_machine; m != NULL; m = m->next) {
7622 if (!strcmp(m->name, name))
7628 /***********************************************************/
7629 /* main execution loop */
7631 static void gui_update(void *opaque)
7633 DisplayState *ds = opaque;
7634 ds->dpy_refresh(ds);
7635 qemu_mod_timer(ds->gui_timer,
7636 (ds->gui_timer_interval ?
7637 ds->gui_timer_interval :
7638 GUI_REFRESH_INTERVAL)
7639 + qemu_get_clock(rt_clock));
7642 struct vm_change_state_entry {
7643 VMChangeStateHandler *cb;
7645 LIST_ENTRY (vm_change_state_entry) entries;
7648 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7650 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7653 VMChangeStateEntry *e;
7655 e = qemu_mallocz(sizeof (*e));
7661 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7665 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7667 LIST_REMOVE (e, entries);
7671 static void vm_state_notify(int running)
7673 VMChangeStateEntry *e;
7675 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7676 e->cb(e->opaque, running);
7680 /* XXX: support several handlers */
7681 static VMStopHandler *vm_stop_cb;
7682 static void *vm_stop_opaque;
7684 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7687 vm_stop_opaque = opaque;
7691 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7702 qemu_rearm_alarm_timer(alarm_timer);
7706 void vm_stop(int reason)
7709 cpu_disable_ticks();
7713 vm_stop_cb(vm_stop_opaque, reason);
7720 /* reset/shutdown handler */
7722 typedef struct QEMUResetEntry {
7723 QEMUResetHandler *func;
7725 struct QEMUResetEntry *next;
7728 static QEMUResetEntry *first_reset_entry;
7729 static int reset_requested;
7730 static int shutdown_requested;
7731 static int powerdown_requested;
7733 int qemu_shutdown_requested(void)
7735 int r = shutdown_requested;
7736 shutdown_requested = 0;
7740 int qemu_reset_requested(void)
7742 int r = reset_requested;
7743 reset_requested = 0;
7747 int qemu_powerdown_requested(void)
7749 int r = powerdown_requested;
7750 powerdown_requested = 0;
7754 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7756 QEMUResetEntry **pre, *re;
7758 pre = &first_reset_entry;
7759 while (*pre != NULL)
7760 pre = &(*pre)->next;
7761 re = qemu_mallocz(sizeof(QEMUResetEntry));
7763 re->opaque = opaque;
7768 void qemu_system_reset(void)
7772 /* reset all devices */
7773 for(re = first_reset_entry; re != NULL; re = re->next) {
7774 re->func(re->opaque);
7778 void qemu_system_reset_request(void)
7781 shutdown_requested = 1;
7783 reset_requested = 1;
7786 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7789 void qemu_system_shutdown_request(void)
7791 shutdown_requested = 1;
7793 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7796 void qemu_system_powerdown_request(void)
7798 powerdown_requested = 1;
7800 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7803 void main_loop_wait(int timeout)
7805 IOHandlerRecord *ioh;
7806 fd_set rfds, wfds, xfds;
7815 /* XXX: need to suppress polling by better using win32 events */
7817 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7818 ret |= pe->func(pe->opaque);
7823 WaitObjects *w = &wait_objects;
7825 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7826 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7827 if (w->func[ret - WAIT_OBJECT_0])
7828 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7830 /* Check for additional signaled events */
7831 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7833 /* Check if event is signaled */
7834 ret2 = WaitForSingleObject(w->events[i], 0);
7835 if(ret2 == WAIT_OBJECT_0) {
7837 w->func[i](w->opaque[i]);
7838 } else if (ret2 == WAIT_TIMEOUT) {
7840 err = GetLastError();
7841 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7844 } else if (ret == WAIT_TIMEOUT) {
7846 err = GetLastError();
7847 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7851 /* poll any events */
7852 /* XXX: separate device handlers from system ones */
7857 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7861 (!ioh->fd_read_poll ||
7862 ioh->fd_read_poll(ioh->opaque) != 0)) {
7863 FD_SET(ioh->fd, &rfds);
7867 if (ioh->fd_write) {
7868 FD_SET(ioh->fd, &wfds);
7878 tv.tv_usec = timeout * 1000;
7880 #if defined(CONFIG_SLIRP)
7882 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7885 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7887 IOHandlerRecord **pioh;
7889 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7890 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7891 ioh->fd_read(ioh->opaque);
7893 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7894 ioh->fd_write(ioh->opaque);
7898 /* remove deleted IO handlers */
7899 pioh = &first_io_handler;
7909 #if defined(CONFIG_SLIRP)
7916 slirp_select_poll(&rfds, &wfds, &xfds);
7921 if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7922 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7923 qemu_get_clock(vm_clock));
7924 /* run dma transfers, if any */
7928 /* real time timers */
7929 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7930 qemu_get_clock(rt_clock));
7932 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7933 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7934 qemu_rearm_alarm_timer(alarm_timer);
7937 /* Check bottom-halves last in case any of the earlier events triggered
7943 static int main_loop(void)
7946 #ifdef CONFIG_PROFILER
7951 cur_cpu = first_cpu;
7952 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7959 #ifdef CONFIG_PROFILER
7960 ti = profile_getclock();
7965 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7966 env->icount_decr.u16.low = 0;
7967 env->icount_extra = 0;
7968 count = qemu_next_deadline();
7969 count = (count + (1 << icount_time_shift) - 1)
7970 >> icount_time_shift;
7971 qemu_icount += count;
7972 decr = (count > 0xffff) ? 0xffff : count;
7974 env->icount_decr.u16.low = decr;
7975 env->icount_extra = count;
7977 ret = cpu_exec(env);
7978 #ifdef CONFIG_PROFILER
7979 qemu_time += profile_getclock() - ti;
7982 /* Fold pending instructions back into the
7983 instruction counter, and clear the interrupt flag. */
7984 qemu_icount -= (env->icount_decr.u16.low
7985 + env->icount_extra);
7986 env->icount_decr.u32 = 0;
7987 env->icount_extra = 0;
7989 next_cpu = env->next_cpu ?: first_cpu;
7990 if (event_pending && likely(ret != EXCP_DEBUG)) {
7991 ret = EXCP_INTERRUPT;
7995 if (ret == EXCP_HLT) {
7996 /* Give the next CPU a chance to run. */
8000 if (ret != EXCP_HALTED)
8002 /* all CPUs are halted ? */
8008 if (shutdown_requested) {
8009 ret = EXCP_INTERRUPT;
8017 if (reset_requested) {
8018 reset_requested = 0;
8019 qemu_system_reset();
8020 ret = EXCP_INTERRUPT;
8022 if (powerdown_requested) {
8023 powerdown_requested = 0;
8024 qemu_system_powerdown();
8025 ret = EXCP_INTERRUPT;
8027 if (unlikely(ret == EXCP_DEBUG)) {
8028 vm_stop(EXCP_DEBUG);
8030 /* If all cpus are halted then wait until the next IRQ */
8031 /* XXX: use timeout computed from timers */
8032 if (ret == EXCP_HALTED) {
8036 /* Advance virtual time to the next event. */
8037 if (use_icount == 1) {
8038 /* When not using an adaptive execution frequency
8039 we tend to get badly out of sync with real time,
8040 so just delay for a reasonable amount of time. */
8043 delta = cpu_get_icount() - cpu_get_clock();
8046 /* If virtual time is ahead of real time then just
8048 timeout = (delta / 1000000) + 1;
8050 /* Wait for either IO to occur or the next
8052 add = qemu_next_deadline();
8053 /* We advance the timer before checking for IO.
8054 Limit the amount we advance so that early IO
8055 activity won't get the guest too far ahead. */
8059 add = (add + (1 << icount_time_shift) - 1)
8060 >> icount_time_shift;
8062 timeout = delta / 1000000;
8073 if (shutdown_requested) {
8074 ret = EXCP_INTERRUPT;
8079 #ifdef CONFIG_PROFILER
8080 ti = profile_getclock();
8082 main_loop_wait(timeout);
8083 #ifdef CONFIG_PROFILER
8084 dev_time += profile_getclock() - ti;
8087 cpu_disable_ticks();
8091 static void help(int exitcode)
8093 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8094 "usage: %s [options] [disk_image]\n"
8096 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8098 "Standard options:\n"
8099 "-M machine select emulated machine (-M ? for list)\n"
8100 "-cpu cpu select CPU (-cpu ? for list)\n"
8101 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8102 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8103 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8104 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8105 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8106 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8107 " [,cache=on|off][,format=f]\n"
8108 " use 'file' as a drive image\n"
8109 "-mtdblock file use 'file' as on-board Flash memory image\n"
8110 "-sd file use 'file' as SecureDigital card image\n"
8111 "-pflash file use 'file' as a parallel flash image\n"
8112 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8113 "-snapshot write to temporary files instead of disk image files\n"
8115 "-no-frame open SDL window without a frame and window decorations\n"
8116 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8117 "-no-quit disable SDL window close capability\n"
8120 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8122 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8123 "-smp n set the number of CPUs to 'n' [default=1]\n"
8124 "-nographic disable graphical output and redirect serial I/Os to console\n"
8125 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8127 "-k language use keyboard layout (for example \"fr\" for French)\n"
8130 "-audio-help print list of audio drivers and their options\n"
8131 "-soundhw c1,... enable audio support\n"
8132 " and only specified sound cards (comma separated list)\n"
8133 " use -soundhw ? to get the list of supported cards\n"
8134 " use -soundhw all to enable all of them\n"
8136 "-vga [std|cirrus|vmware]\n"
8137 " select video card type\n"
8138 "-localtime set the real time clock to local time [default=utc]\n"
8139 "-full-screen start in full screen\n"
8141 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8143 "-usb enable the USB driver (will be the default soon)\n"
8144 "-usbdevice name add the host or guest USB device 'name'\n"
8145 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8146 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8148 "-name string set the name of the guest\n"
8149 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
8151 "Network options:\n"
8152 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8153 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8155 "-net user[,vlan=n][,hostname=host]\n"
8156 " connect the user mode network stack to VLAN 'n' and send\n"
8157 " hostname 'host' to DHCP clients\n"
8160 "-net tap[,vlan=n],ifname=name\n"
8161 " connect the host TAP network interface to VLAN 'n'\n"
8163 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8164 " connect the host TAP network interface to VLAN 'n' and use the\n"
8165 " network scripts 'file' (default=%s)\n"
8166 " and 'dfile' (default=%s);\n"
8167 " use '[down]script=no' to disable script execution;\n"
8168 " use 'fd=h' to connect to an already opened TAP interface\n"
8170 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8171 " connect the vlan 'n' to another VLAN using a socket connection\n"
8172 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8173 " connect the vlan 'n' to multicast maddr and port\n"
8175 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8176 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8177 " on host and listening for incoming connections on 'socketpath'.\n"
8178 " Use group 'groupname' and mode 'octalmode' to change default\n"
8179 " ownership and permissions for communication port.\n"
8181 "-net none use it alone to have zero network devices; if no -net option\n"
8182 " is provided, the default is '-net nic -net user'\n"
8185 "-tftp dir allow tftp access to files in dir [-net user]\n"
8186 "-bootp file advertise file in BOOTP replies\n"
8188 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8190 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8191 " redirect TCP or UDP connections from host to guest [-net user]\n"
8194 "Linux boot specific:\n"
8195 "-kernel bzImage use 'bzImage' as kernel image\n"
8196 "-append cmdline use 'cmdline' as kernel command line\n"
8197 "-initrd file use 'file' as initial ram disk\n"
8199 "Debug/Expert options:\n"
8200 "-monitor dev redirect the monitor to char device 'dev'\n"
8201 "-serial dev redirect the serial port to char device 'dev'\n"
8202 "-parallel dev redirect the parallel port to char device 'dev'\n"
8203 "-pidfile file Write PID to 'file'\n"
8204 "-S freeze CPU at startup (use 'c' to start execution)\n"
8205 "-s wait gdb connection to port\n"
8206 "-p port set gdb connection port [default=%s]\n"
8207 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8208 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8209 " translation (t=none or lba) (usually qemu can guess them)\n"
8210 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8212 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8213 "-no-kqemu disable KQEMU kernel module usage\n"
8216 "-no-acpi disable ACPI\n"
8218 #ifdef CONFIG_CURSES
8219 "-curses use a curses/ncurses interface instead of SDL\n"
8221 "-no-reboot exit instead of rebooting\n"
8222 "-no-shutdown stop before shutdown\n"
8223 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8224 "-vnc display start a VNC server on display\n"
8226 "-daemonize daemonize QEMU after initializing\n"
8228 "-option-rom rom load a file, rom, into the option ROM space\n"
8230 "-prom-env variable=value set OpenBIOS nvram variables\n"
8232 "-clock force the use of the given methods for timer alarm.\n"
8233 " To see what timers are available use -clock ?\n"
8234 "-startdate select initial date of the clock\n"
8235 "-icount [N|auto]\n"
8236 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8238 "During emulation, the following keys are useful:\n"
8239 "ctrl-alt-f toggle full screen\n"
8240 "ctrl-alt-n switch to virtual console 'n'\n"
8241 "ctrl-alt toggle mouse and keyboard grab\n"
8243 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8248 DEFAULT_NETWORK_SCRIPT,
8249 DEFAULT_NETWORK_DOWN_SCRIPT,
8251 DEFAULT_GDBSTUB_PORT,
8256 #define HAS_ARG 0x0001
8271 QEMU_OPTION_mtdblock,
8275 QEMU_OPTION_snapshot,
8277 QEMU_OPTION_no_fd_bootchk,
8280 QEMU_OPTION_nographic,
8281 QEMU_OPTION_portrait,
8283 QEMU_OPTION_audio_help,
8284 QEMU_OPTION_soundhw,
8305 QEMU_OPTION_localtime,
8309 QEMU_OPTION_monitor,
8311 QEMU_OPTION_parallel,
8313 QEMU_OPTION_full_screen,
8314 QEMU_OPTION_no_frame,
8315 QEMU_OPTION_alt_grab,
8316 QEMU_OPTION_no_quit,
8317 QEMU_OPTION_pidfile,
8318 QEMU_OPTION_no_kqemu,
8319 QEMU_OPTION_kernel_kqemu,
8320 QEMU_OPTION_win2k_hack,
8322 QEMU_OPTION_usbdevice,
8325 QEMU_OPTION_no_acpi,
8327 QEMU_OPTION_no_reboot,
8328 QEMU_OPTION_no_shutdown,
8329 QEMU_OPTION_show_cursor,
8330 QEMU_OPTION_daemonize,
8331 QEMU_OPTION_option_rom,
8332 QEMU_OPTION_semihosting,
8334 QEMU_OPTION_prom_env,
8335 QEMU_OPTION_old_param,
8337 QEMU_OPTION_startdate,
8338 QEMU_OPTION_tb_size,
8343 typedef struct QEMUOption {
8349 static const QEMUOption qemu_options[] = {
8350 { "h", 0, QEMU_OPTION_h },
8351 { "help", 0, QEMU_OPTION_h },
8353 { "M", HAS_ARG, QEMU_OPTION_M },
8354 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8355 { "fda", HAS_ARG, QEMU_OPTION_fda },
8356 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8357 { "hda", HAS_ARG, QEMU_OPTION_hda },
8358 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8359 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8360 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8361 { "drive", HAS_ARG, QEMU_OPTION_drive },
8362 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8363 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8364 { "sd", HAS_ARG, QEMU_OPTION_sd },
8365 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8366 { "boot", HAS_ARG, QEMU_OPTION_boot },
8367 { "snapshot", 0, QEMU_OPTION_snapshot },
8369 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8371 { "m", HAS_ARG, QEMU_OPTION_m },
8372 { "nographic", 0, QEMU_OPTION_nographic },
8373 { "portrait", 0, QEMU_OPTION_portrait },
8374 { "k", HAS_ARG, QEMU_OPTION_k },
8376 { "audio-help", 0, QEMU_OPTION_audio_help },
8377 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8380 { "net", HAS_ARG, QEMU_OPTION_net},
8382 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8383 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8385 { "smb", HAS_ARG, QEMU_OPTION_smb },
8387 { "redir", HAS_ARG, QEMU_OPTION_redir },
8390 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8391 { "append", HAS_ARG, QEMU_OPTION_append },
8392 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8394 { "S", 0, QEMU_OPTION_S },
8395 { "s", 0, QEMU_OPTION_s },
8396 { "p", HAS_ARG, QEMU_OPTION_p },
8397 { "d", HAS_ARG, QEMU_OPTION_d },
8398 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8399 { "L", HAS_ARG, QEMU_OPTION_L },
8400 { "bios", HAS_ARG, QEMU_OPTION_bios },
8402 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8403 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8405 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8406 { "g", 1, QEMU_OPTION_g },
8408 { "localtime", 0, QEMU_OPTION_localtime },
8409 { "vga", HAS_ARG, QEMU_OPTION_vga },
8410 { "echr", HAS_ARG, QEMU_OPTION_echr },
8411 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8412 { "serial", HAS_ARG, QEMU_OPTION_serial },
8413 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8414 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8415 { "full-screen", 0, QEMU_OPTION_full_screen },
8417 { "no-frame", 0, QEMU_OPTION_no_frame },
8418 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8419 { "no-quit", 0, QEMU_OPTION_no_quit },
8421 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8422 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8423 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8424 { "smp", HAS_ARG, QEMU_OPTION_smp },
8425 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8426 #ifdef CONFIG_CURSES
8427 { "curses", 0, QEMU_OPTION_curses },
8429 { "uuid", HAS_ARG, QEMU_OPTION_uuid },
8431 /* temporary options */
8432 { "usb", 0, QEMU_OPTION_usb },
8433 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8434 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8435 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8436 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8437 { "daemonize", 0, QEMU_OPTION_daemonize },
8438 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8439 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8440 { "semihosting", 0, QEMU_OPTION_semihosting },
8442 { "name", HAS_ARG, QEMU_OPTION_name },
8443 #if defined(TARGET_SPARC)
8444 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8446 #if defined(TARGET_ARM)
8447 { "old-param", 0, QEMU_OPTION_old_param },
8449 { "clock", HAS_ARG, QEMU_OPTION_clock },
8450 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8451 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8452 { "icount", HAS_ARG, QEMU_OPTION_icount },
8456 /* password input */
8458 int qemu_key_check(BlockDriverState *bs, const char *name)
8463 if (!bdrv_is_encrypted(bs))
8466 term_printf("%s is encrypted.\n", name);
8467 for(i = 0; i < 3; i++) {
8468 monitor_readline("Password: ", 1, password, sizeof(password));
8469 if (bdrv_set_key(bs, password) == 0)
8471 term_printf("invalid password\n");
8476 static BlockDriverState *get_bdrv(int index)
8478 if (index > nb_drives)
8480 return drives_table[index].bdrv;
8483 static void read_passwords(void)
8485 BlockDriverState *bs;
8488 for(i = 0; i < 6; i++) {
8491 qemu_key_check(bs, bdrv_get_device_name(bs));
8496 struct soundhw soundhw[] = {
8497 #ifdef HAS_AUDIO_CHOICE
8498 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8504 { .init_isa = pcspk_audio_init }
8509 "Creative Sound Blaster 16",
8512 { .init_isa = SB16_init }
8515 #ifdef CONFIG_CS4231A
8521 { .init_isa = cs4231a_init }
8529 "Yamaha YMF262 (OPL3)",
8531 "Yamaha YM3812 (OPL2)",
8535 { .init_isa = Adlib_init }
8542 "Gravis Ultrasound GF1",
8545 { .init_isa = GUS_init }
8552 "Intel 82801AA AC97 Audio",
8555 { .init_pci = ac97_init }
8561 "ENSONIQ AudioPCI ES1370",
8564 { .init_pci = es1370_init }
8568 { NULL, NULL, 0, 0, { NULL } }
8571 static void select_soundhw (const char *optarg)
8575 if (*optarg == '?') {
8578 printf ("Valid sound card names (comma separated):\n");
8579 for (c = soundhw; c->name; ++c) {
8580 printf ("%-11s %s\n", c->name, c->descr);
8582 printf ("\n-soundhw all will enable all of the above\n");
8583 exit (*optarg != '?');
8591 if (!strcmp (optarg, "all")) {
8592 for (c = soundhw; c->name; ++c) {
8600 e = strchr (p, ',');
8601 l = !e ? strlen (p) : (size_t) (e - p);
8603 for (c = soundhw; c->name; ++c) {
8604 if (!strncmp (c->name, p, l)) {
8613 "Unknown sound card name (too big to show)\n");
8616 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8621 p += l + (e != NULL);
8625 goto show_valid_cards;
8630 static void select_vgahw (const char *p)
8634 if (strstart(p, "std", &opts)) {
8635 cirrus_vga_enabled = 0;
8637 } else if (strstart(p, "cirrus", &opts)) {
8638 cirrus_vga_enabled = 1;
8640 } else if (strstart(p, "vmware", &opts)) {
8641 cirrus_vga_enabled = 0;
8645 fprintf(stderr, "Unknown vga type: %s\n", p);
8649 const char *nextopt;
8651 if (strstart(opts, ",retrace=", &nextopt)) {
8653 if (strstart(opts, "dumb", &nextopt))
8654 vga_retrace_method = VGA_RETRACE_DUMB;
8655 else if (strstart(opts, "precise", &nextopt))
8656 vga_retrace_method = VGA_RETRACE_PRECISE;
8657 else goto invalid_vga;
8658 } else goto invalid_vga;
8664 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8666 exit(STATUS_CONTROL_C_EXIT);
8671 static int qemu_uuid_parse(const char *str, uint8_t *uuid)
8675 if(strlen(str) != 36)
8678 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
8679 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
8680 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
8688 #define MAX_NET_CLIENTS 32
8692 static void termsig_handler(int signal)
8694 qemu_system_shutdown_request();
8697 static void termsig_setup(void)
8699 struct sigaction act;
8701 memset(&act, 0, sizeof(act));
8702 act.sa_handler = termsig_handler;
8703 sigaction(SIGINT, &act, NULL);
8704 sigaction(SIGHUP, &act, NULL);
8705 sigaction(SIGTERM, &act, NULL);
8710 int main(int argc, char **argv)
8712 #ifdef CONFIG_GDBSTUB
8714 const char *gdbstub_port;
8716 uint32_t boot_devices_bitmap = 0;
8718 int snapshot, linux_boot, net_boot;
8719 const char *initrd_filename;
8720 const char *kernel_filename, *kernel_cmdline;
8721 const char *boot_devices = "";
8722 DisplayState *ds = &display_state;
8723 int cyls, heads, secs, translation;
8724 const char *net_clients[MAX_NET_CLIENTS];
8728 const char *r, *optarg;
8729 CharDriverState *monitor_hd;
8730 const char *monitor_device;
8731 const char *serial_devices[MAX_SERIAL_PORTS];
8732 int serial_device_index;
8733 const char *parallel_devices[MAX_PARALLEL_PORTS];
8734 int parallel_device_index;
8735 const char *loadvm = NULL;
8736 QEMUMachine *machine;
8737 const char *cpu_model;
8738 const char *usb_devices[MAX_USB_CMDLINE];
8739 int usb_devices_index;
8742 const char *pid_file = NULL;
8746 LIST_INIT (&vm_change_state_head);
8749 struct sigaction act;
8750 sigfillset(&act.sa_mask);
8752 act.sa_handler = SIG_IGN;
8753 sigaction(SIGPIPE, &act, NULL);
8756 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8757 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8758 QEMU to run on a single CPU */
8763 h = GetCurrentProcess();
8764 if (GetProcessAffinityMask(h, &mask, &smask)) {
8765 for(i = 0; i < 32; i++) {
8766 if (mask & (1 << i))
8771 SetProcessAffinityMask(h, mask);
8777 register_machines();
8778 machine = first_machine;
8780 initrd_filename = NULL;
8782 vga_ram_size = VGA_RAM_SIZE;
8783 #ifdef CONFIG_GDBSTUB
8785 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8790 kernel_filename = NULL;
8791 kernel_cmdline = "";
8792 cyls = heads = secs = 0;
8793 translation = BIOS_ATA_TRANSLATION_AUTO;
8794 monitor_device = "vc";
8796 serial_devices[0] = "vc:80Cx24C";
8797 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8798 serial_devices[i] = NULL;
8799 serial_device_index = 0;
8801 parallel_devices[0] = "vc:640x480";
8802 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8803 parallel_devices[i] = NULL;
8804 parallel_device_index = 0;
8806 usb_devices_index = 0;
8824 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8826 const QEMUOption *popt;
8829 /* Treat --foo the same as -foo. */
8832 popt = qemu_options;
8835 fprintf(stderr, "%s: invalid option -- '%s'\n",
8839 if (!strcmp(popt->name, r + 1))
8843 if (popt->flags & HAS_ARG) {
8844 if (optind >= argc) {
8845 fprintf(stderr, "%s: option '%s' requires an argument\n",
8849 optarg = argv[optind++];
8854 switch(popt->index) {
8856 machine = find_machine(optarg);
8859 printf("Supported machines are:\n");
8860 for(m = first_machine; m != NULL; m = m->next) {
8861 printf("%-10s %s%s\n",
8863 m == first_machine ? " (default)" : "");
8865 exit(*optarg != '?');
8868 case QEMU_OPTION_cpu:
8869 /* hw initialization will check this */
8870 if (*optarg == '?') {
8871 /* XXX: implement xxx_cpu_list for targets that still miss it */
8872 #if defined(cpu_list)
8873 cpu_list(stdout, &fprintf);
8880 case QEMU_OPTION_initrd:
8881 initrd_filename = optarg;
8883 case QEMU_OPTION_hda:
8885 hda_index = drive_add(optarg, HD_ALIAS, 0);
8887 hda_index = drive_add(optarg, HD_ALIAS
8888 ",cyls=%d,heads=%d,secs=%d%s",
8889 0, cyls, heads, secs,
8890 translation == BIOS_ATA_TRANSLATION_LBA ?
8892 translation == BIOS_ATA_TRANSLATION_NONE ?
8893 ",trans=none" : "");
8895 case QEMU_OPTION_hdb:
8896 case QEMU_OPTION_hdc:
8897 case QEMU_OPTION_hdd:
8898 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8900 case QEMU_OPTION_drive:
8901 drive_add(NULL, "%s", optarg);
8903 case QEMU_OPTION_mtdblock:
8904 drive_add(optarg, MTD_ALIAS);
8906 case QEMU_OPTION_sd:
8907 drive_add(optarg, SD_ALIAS);
8909 case QEMU_OPTION_pflash:
8910 drive_add(optarg, PFLASH_ALIAS);
8912 case QEMU_OPTION_snapshot:
8915 case QEMU_OPTION_hdachs:
8919 cyls = strtol(p, (char **)&p, 0);
8920 if (cyls < 1 || cyls > 16383)
8925 heads = strtol(p, (char **)&p, 0);
8926 if (heads < 1 || heads > 16)
8931 secs = strtol(p, (char **)&p, 0);
8932 if (secs < 1 || secs > 63)
8936 if (!strcmp(p, "none"))
8937 translation = BIOS_ATA_TRANSLATION_NONE;
8938 else if (!strcmp(p, "lba"))
8939 translation = BIOS_ATA_TRANSLATION_LBA;
8940 else if (!strcmp(p, "auto"))
8941 translation = BIOS_ATA_TRANSLATION_AUTO;
8944 } else if (*p != '\0') {
8946 fprintf(stderr, "qemu: invalid physical CHS format\n");
8949 if (hda_index != -1)
8950 snprintf(drives_opt[hda_index].opt,
8951 sizeof(drives_opt[hda_index].opt),
8952 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8953 0, cyls, heads, secs,
8954 translation == BIOS_ATA_TRANSLATION_LBA ?
8956 translation == BIOS_ATA_TRANSLATION_NONE ?
8957 ",trans=none" : "");
8960 case QEMU_OPTION_nographic:
8963 #ifdef CONFIG_CURSES
8964 case QEMU_OPTION_curses:
8968 case QEMU_OPTION_portrait:
8971 case QEMU_OPTION_kernel:
8972 kernel_filename = optarg;
8974 case QEMU_OPTION_append:
8975 kernel_cmdline = optarg;
8977 case QEMU_OPTION_cdrom:
8978 drive_add(optarg, CDROM_ALIAS);
8980 case QEMU_OPTION_boot:
8981 boot_devices = optarg;
8982 /* We just do some generic consistency checks */
8984 /* Could easily be extended to 64 devices if needed */
8987 boot_devices_bitmap = 0;
8988 for (p = boot_devices; *p != '\0'; p++) {
8989 /* Allowed boot devices are:
8990 * a b : floppy disk drives
8991 * c ... f : IDE disk drives
8992 * g ... m : machine implementation dependant drives
8993 * n ... p : network devices
8994 * It's up to each machine implementation to check
8995 * if the given boot devices match the actual hardware
8996 * implementation and firmware features.
8998 if (*p < 'a' || *p > 'q') {
8999 fprintf(stderr, "Invalid boot device '%c'\n", *p);
9002 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
9004 "Boot device '%c' was given twice\n",*p);
9007 boot_devices_bitmap |= 1 << (*p - 'a');
9011 case QEMU_OPTION_fda:
9012 case QEMU_OPTION_fdb:
9013 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9016 case QEMU_OPTION_no_fd_bootchk:
9020 case QEMU_OPTION_net:
9021 if (nb_net_clients >= MAX_NET_CLIENTS) {
9022 fprintf(stderr, "qemu: too many network clients\n");
9025 net_clients[nb_net_clients] = optarg;
9029 case QEMU_OPTION_tftp:
9030 tftp_prefix = optarg;
9032 case QEMU_OPTION_bootp:
9033 bootp_filename = optarg;
9036 case QEMU_OPTION_smb:
9037 net_slirp_smb(optarg);
9040 case QEMU_OPTION_redir:
9041 net_slirp_redir(optarg);
9045 case QEMU_OPTION_audio_help:
9049 case QEMU_OPTION_soundhw:
9050 select_soundhw (optarg);
9056 case QEMU_OPTION_m: {
9060 value = strtoul(optarg, &ptr, 10);
9062 case 0: case 'M': case 'm':
9069 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
9073 /* On 32-bit hosts, QEMU is limited by virtual address space */
9074 if (value > (2047 << 20)
9076 && HOST_LONG_BITS == 32
9079 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
9082 if (value != (uint64_t)(ram_addr_t)value) {
9083 fprintf(stderr, "qemu: ram size too large\n");
9092 const CPULogItem *item;
9094 mask = cpu_str_to_log_mask(optarg);
9096 printf("Log items (comma separated):\n");
9097 for(item = cpu_log_items; item->mask != 0; item++) {
9098 printf("%-10s %s\n", item->name, item->help);
9105 #ifdef CONFIG_GDBSTUB
9110 gdbstub_port = optarg;
9116 case QEMU_OPTION_bios:
9123 keyboard_layout = optarg;
9125 case QEMU_OPTION_localtime:
9128 case QEMU_OPTION_vga:
9129 select_vgahw (optarg);
9136 w = strtol(p, (char **)&p, 10);
9139 fprintf(stderr, "qemu: invalid resolution or depth\n");
9145 h = strtol(p, (char **)&p, 10);
9150 depth = strtol(p, (char **)&p, 10);
9151 if (depth != 8 && depth != 15 && depth != 16 &&
9152 depth != 24 && depth != 32)
9154 } else if (*p == '\0') {
9155 depth = graphic_depth;
9162 graphic_depth = depth;
9165 case QEMU_OPTION_echr:
9168 term_escape_char = strtol(optarg, &r, 0);
9170 printf("Bad argument to echr\n");
9173 case QEMU_OPTION_monitor:
9174 monitor_device = optarg;
9176 case QEMU_OPTION_serial:
9177 if (serial_device_index >= MAX_SERIAL_PORTS) {
9178 fprintf(stderr, "qemu: too many serial ports\n");
9181 serial_devices[serial_device_index] = optarg;
9182 serial_device_index++;
9184 case QEMU_OPTION_parallel:
9185 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9186 fprintf(stderr, "qemu: too many parallel ports\n");
9189 parallel_devices[parallel_device_index] = optarg;
9190 parallel_device_index++;
9192 case QEMU_OPTION_loadvm:
9195 case QEMU_OPTION_full_screen:
9199 case QEMU_OPTION_no_frame:
9202 case QEMU_OPTION_alt_grab:
9205 case QEMU_OPTION_no_quit:
9209 case QEMU_OPTION_pidfile:
9213 case QEMU_OPTION_win2k_hack:
9214 win2k_install_hack = 1;
9218 case QEMU_OPTION_no_kqemu:
9221 case QEMU_OPTION_kernel_kqemu:
9225 case QEMU_OPTION_usb:
9228 case QEMU_OPTION_usbdevice:
9230 if (usb_devices_index >= MAX_USB_CMDLINE) {
9231 fprintf(stderr, "Too many USB devices\n");
9234 usb_devices[usb_devices_index] = optarg;
9235 usb_devices_index++;
9237 case QEMU_OPTION_smp:
9238 smp_cpus = atoi(optarg);
9240 fprintf(stderr, "Invalid number of CPUs\n");
9244 case QEMU_OPTION_vnc:
9245 vnc_display = optarg;
9247 case QEMU_OPTION_no_acpi:
9250 case QEMU_OPTION_no_reboot:
9253 case QEMU_OPTION_no_shutdown:
9256 case QEMU_OPTION_show_cursor:
9259 case QEMU_OPTION_uuid:
9260 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
9261 fprintf(stderr, "Fail to parse UUID string."
9262 " Wrong format.\n");
9266 case QEMU_OPTION_daemonize:
9269 case QEMU_OPTION_option_rom:
9270 if (nb_option_roms >= MAX_OPTION_ROMS) {
9271 fprintf(stderr, "Too many option ROMs\n");
9274 option_rom[nb_option_roms] = optarg;
9277 case QEMU_OPTION_semihosting:
9278 semihosting_enabled = 1;
9280 case QEMU_OPTION_name:
9284 case QEMU_OPTION_prom_env:
9285 if (nb_prom_envs >= MAX_PROM_ENVS) {
9286 fprintf(stderr, "Too many prom variables\n");
9289 prom_envs[nb_prom_envs] = optarg;
9294 case QEMU_OPTION_old_param:
9298 case QEMU_OPTION_clock:
9299 configure_alarms(optarg);
9301 case QEMU_OPTION_startdate:
9304 time_t rtc_start_date;
9305 if (!strcmp(optarg, "now")) {
9306 rtc_date_offset = -1;
9308 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9316 } else if (sscanf(optarg, "%d-%d-%d",
9319 &tm.tm_mday) == 3) {
9328 rtc_start_date = mktimegm(&tm);
9329 if (rtc_start_date == -1) {
9331 fprintf(stderr, "Invalid date format. Valid format are:\n"
9332 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9335 rtc_date_offset = time(NULL) - rtc_start_date;
9339 case QEMU_OPTION_tb_size:
9340 tb_size = strtol(optarg, NULL, 0);
9344 case QEMU_OPTION_icount:
9346 if (strcmp(optarg, "auto") == 0) {
9347 icount_time_shift = -1;
9349 icount_time_shift = strtol(optarg, NULL, 0);
9356 if (smp_cpus > machine->max_cpus) {
9357 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
9358 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
9364 if (serial_device_index == 0)
9365 serial_devices[0] = "stdio";
9366 if (parallel_device_index == 0)
9367 parallel_devices[0] = "null";
9368 if (strncmp(monitor_device, "vc", 2) == 0)
9369 monitor_device = "stdio";
9376 if (pipe(fds) == -1)
9387 len = read(fds[0], &status, 1);
9388 if (len == -1 && (errno == EINTR))
9393 else if (status == 1) {
9394 fprintf(stderr, "Could not acquire pidfile\n");
9411 signal(SIGTSTP, SIG_IGN);
9412 signal(SIGTTOU, SIG_IGN);
9413 signal(SIGTTIN, SIG_IGN);
9417 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9420 write(fds[1], &status, 1);
9422 fprintf(stderr, "Could not acquire pid file\n");
9430 linux_boot = (kernel_filename != NULL);
9431 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9433 if (!linux_boot && net_boot == 0 &&
9434 !machine->nodisk_ok && nb_drives_opt == 0)
9437 if (!linux_boot && *kernel_cmdline != '\0') {
9438 fprintf(stderr, "-append only allowed with -kernel option\n");
9442 if (!linux_boot && initrd_filename != NULL) {
9443 fprintf(stderr, "-initrd only allowed with -kernel option\n");
9447 /* boot to floppy or the default cd if no hard disk defined yet */
9448 if (!boot_devices[0]) {
9449 boot_devices = "cad";
9451 setvbuf(stdout, NULL, _IOLBF, 0);
9455 if (use_icount && icount_time_shift < 0) {
9457 /* 125MIPS seems a reasonable initial guess at the guest speed.
9458 It will be corrected fairly quickly anyway. */
9459 icount_time_shift = 3;
9460 init_icount_adjust();
9467 /* init network clients */
9468 if (nb_net_clients == 0) {
9469 /* if no clients, we use a default config */
9470 net_clients[nb_net_clients++] = "nic";
9472 net_clients[nb_net_clients++] = "user";
9476 for(i = 0;i < nb_net_clients; i++) {
9477 if (net_client_parse(net_clients[i]) < 0)
9480 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9481 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9483 if (vlan->nb_guest_devs == 0)
9484 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
9485 if (vlan->nb_host_devs == 0)
9487 "Warning: vlan %d is not connected to host network\n",
9492 /* XXX: this should be moved in the PC machine instantiation code */
9493 if (net_boot != 0) {
9495 for (i = 0; i < nb_nics && i < 4; i++) {
9496 const char *model = nd_table[i].model;
9498 if (net_boot & (1 << i)) {
9501 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9502 if (get_image_size(buf) > 0) {
9503 if (nb_option_roms >= MAX_OPTION_ROMS) {
9504 fprintf(stderr, "Too many option ROMs\n");
9507 option_rom[nb_option_roms] = strdup(buf);
9514 fprintf(stderr, "No valid PXE rom found for network device\n");
9520 /* init the memory */
9521 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9523 if (machine->ram_require & RAMSIZE_FIXED) {
9525 if (ram_size < phys_ram_size) {
9526 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9527 machine->name, (unsigned long long) phys_ram_size);
9531 phys_ram_size = ram_size;
9533 ram_size = phys_ram_size;
9536 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9538 phys_ram_size += ram_size;
9541 phys_ram_base = qemu_vmalloc(phys_ram_size);
9542 if (!phys_ram_base) {
9543 fprintf(stderr, "Could not allocate physical memory\n");
9547 /* init the dynamic translator */
9548 cpu_exec_init_all(tb_size * 1024 * 1024);
9552 /* we always create the cdrom drive, even if no disk is there */
9554 if (nb_drives_opt < MAX_DRIVES)
9555 drive_add(NULL, CDROM_ALIAS);
9557 /* we always create at least one floppy */
9559 if (nb_drives_opt < MAX_DRIVES)
9560 drive_add(NULL, FD_ALIAS, 0);
9562 /* we always create one sd slot, even if no card is in it */
9564 if (nb_drives_opt < MAX_DRIVES)
9565 drive_add(NULL, SD_ALIAS);
9567 /* open the virtual block devices */
9569 for(i = 0; i < nb_drives_opt; i++)
9570 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9573 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9574 register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
9577 memset(&display_state, 0, sizeof(display_state));
9580 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9583 /* nearly nothing to do */
9584 dumb_display_init(ds);
9585 } else if (vnc_display != NULL) {
9586 vnc_display_init(ds);
9587 if (vnc_display_open(ds, vnc_display) < 0)
9590 #if defined(CONFIG_CURSES)
9592 curses_display_init(ds, full_screen);
9596 #if defined(CONFIG_SDL)
9597 sdl_display_init(ds, full_screen, no_frame);
9598 #elif defined(CONFIG_COCOA)
9599 cocoa_display_init(ds, full_screen);
9601 dumb_display_init(ds);
9606 /* must be after terminal init, SDL library changes signal handlers */
9610 /* Maintain compatibility with multiple stdio monitors */
9611 if (!strcmp(monitor_device,"stdio")) {
9612 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9613 const char *devname = serial_devices[i];
9614 if (devname && !strcmp(devname,"mon:stdio")) {
9615 monitor_device = NULL;
9617 } else if (devname && !strcmp(devname,"stdio")) {
9618 monitor_device = NULL;
9619 serial_devices[i] = "mon:stdio";
9624 if (monitor_device) {
9625 monitor_hd = qemu_chr_open(monitor_device);
9627 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9630 monitor_init(monitor_hd, !nographic);
9633 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9634 const char *devname = serial_devices[i];
9635 if (devname && strcmp(devname, "none")) {
9636 serial_hds[i] = qemu_chr_open(devname);
9637 if (!serial_hds[i]) {
9638 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9642 if (strstart(devname, "vc", 0))
9643 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9647 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9648 const char *devname = parallel_devices[i];
9649 if (devname && strcmp(devname, "none")) {
9650 parallel_hds[i] = qemu_chr_open(devname);
9651 if (!parallel_hds[i]) {
9652 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9656 if (strstart(devname, "vc", 0))
9657 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9661 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9662 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9664 /* init USB devices */
9666 for(i = 0; i < usb_devices_index; i++) {
9667 if (usb_device_add(usb_devices[i]) < 0) {
9668 fprintf(stderr, "Warning: could not add USB device %s\n",
9674 if (display_state.dpy_refresh) {
9675 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9676 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9679 #ifdef CONFIG_GDBSTUB
9681 /* XXX: use standard host:port notation and modify options
9683 if (gdbserver_start(gdbstub_port) < 0) {
9684 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9695 /* XXX: simplify init */
9708 len = write(fds[1], &status, 1);
9709 if (len == -1 && (errno == EINTR))
9716 TFR(fd = open("/dev/null", O_RDWR));
9730 #if !defined(_WIN32)
9731 /* close network clients */
9732 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9733 VLANClientState *vc;
9735 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9736 if (vc->fd_read == tap_receive) {
9738 TAPState *s = vc->opaque;
9740 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9742 launch_script(s->down_script, ifname, s->fd);
9744 #if defined(CONFIG_VDE)
9745 if (vc->fd_read == vde_from_qemu) {
9746 VDEState *s = vc->opaque;