4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
50 #include <sys/times.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.h>
72 #include <linux/if_tun.h>
75 #include <linux/rtc.h>
77 /* For the benefit of older linux systems which don't supply it,
78 we use a local copy of hpet.h. */
79 /* #include <linux/hpet.h> */
82 #include <linux/ppdev.h>
83 #include <linux/parport.h>
86 #include <sys/ethernet.h>
87 #include <sys/sockio.h>
88 #include <netinet/arp.h>
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h> // must come after ip.h
93 #include <netinet/udp.h>
94 #include <netinet/tcp.h>
101 #include <winsock2.h>
102 int inet_aton(const char *cp
, struct in_addr
*ia
);
105 #if defined(CONFIG_SLIRP)
106 #include "libslirp.h"
109 #if defined(CONFIG_VDE)
110 #include <libvdeplug.h>
115 #include <sys/timeb.h>
116 #include <mmsystem.h>
117 #define getopt_long_only getopt_long
118 #define memalign(align, size) malloc(size)
121 #include "qemu_socket.h"
127 #endif /* CONFIG_SDL */
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
136 #include "exec-all.h"
138 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
139 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
141 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
143 #define SMBD_COMMAND "/usr/sbin/smbd"
146 //#define DEBUG_UNUSED_IOPORT
147 //#define DEBUG_IOPORT
150 #define DEFAULT_RAM_SIZE 144
152 #define DEFAULT_RAM_SIZE 128
155 #define GUI_REFRESH_INTERVAL 30
157 /* Max number of USB devices that can be specified on the commandline. */
158 #define MAX_USB_CMDLINE 8
160 /* XXX: use a two level table to limit memory usage */
161 #define MAX_IOPORTS 65536
163 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
164 const char *bios_name
= NULL
;
165 void *ioport_opaque
[MAX_IOPORTS
];
166 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
167 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
168 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
169 to store the VM snapshots */
170 DriveInfo drives_table
[MAX_DRIVES
+1];
172 /* point to the block driver where the snapshots are managed */
173 BlockDriverState
*bs_snapshots
;
175 static DisplayState display_state
;
178 const char* keyboard_layout
= NULL
;
179 int64_t ticks_per_sec
;
181 int pit_min_timer_count
= 0;
183 NICInfo nd_table
[MAX_NICS
];
185 static int rtc_utc
= 1;
186 static int rtc_date_offset
= -1; /* -1 means no change */
187 int cirrus_vga_enabled
= 1;
188 int vmsvga_enabled
= 0;
190 int graphic_width
= 1024;
191 int graphic_height
= 768;
192 int graphic_depth
= 8;
194 int graphic_width
= 800;
195 int graphic_height
= 600;
196 int graphic_depth
= 15;
201 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
202 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
204 int win2k_install_hack
= 0;
207 static VLANState
*first_vlan
;
209 const char *vnc_display
;
210 #if defined(TARGET_SPARC)
212 #elif defined(TARGET_I386)
217 int acpi_enabled
= 1;
222 int graphic_rotate
= 0;
224 const char *option_rom
[MAX_OPTION_ROMS
];
226 int semihosting_enabled
= 0;
231 const char *qemu_name
;
234 unsigned int nb_prom_envs
= 0;
235 const char *prom_envs
[MAX_PROM_ENVS
];
241 } drives_opt
[MAX_DRIVES
];
243 static CPUState
*cur_cpu
;
244 static CPUState
*next_cpu
;
245 static int event_pending
= 1;
246 /* Conversion factor from emulated instructions to virtual clock ticks. */
247 static int icount_time_shift
;
248 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
249 #define MAX_ICOUNT_SHIFT 10
250 /* Compensate for varying guest execution speed. */
251 static int64_t qemu_icount_bias
;
252 QEMUTimer
*icount_rt_timer
;
253 QEMUTimer
*icount_vm_timer
;
255 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
257 /***********************************************************/
258 /* x86 ISA bus support */
260 target_phys_addr_t isa_mem_base
= 0;
263 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
264 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
266 static uint32_t ioport_read(int index
, uint32_t address
)
268 static IOPortReadFunc
*default_func
[3] = {
269 default_ioport_readb
,
270 default_ioport_readw
,
273 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
275 func
= default_func
[index
];
276 return func(ioport_opaque
[address
], address
);
279 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
281 static IOPortWriteFunc
*default_func
[3] = {
282 default_ioport_writeb
,
283 default_ioport_writew
,
284 default_ioport_writel
286 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
288 func
= default_func
[index
];
289 func(ioport_opaque
[address
], address
, data
);
292 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
294 #ifdef DEBUG_UNUSED_IOPORT
295 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
300 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
302 #ifdef DEBUG_UNUSED_IOPORT
303 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
307 /* default is to make two byte accesses */
308 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
311 data
= ioport_read(0, address
);
312 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
313 data
|= ioport_read(0, address
) << 8;
317 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
319 ioport_write(0, address
, data
& 0xff);
320 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
321 ioport_write(0, address
, (data
>> 8) & 0xff);
324 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
326 #ifdef DEBUG_UNUSED_IOPORT
327 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
332 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
334 #ifdef DEBUG_UNUSED_IOPORT
335 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
339 /* size is the word size in byte */
340 int register_ioport_read(int start
, int length
, int size
,
341 IOPortReadFunc
*func
, void *opaque
)
347 } else if (size
== 2) {
349 } else if (size
== 4) {
352 hw_error("register_ioport_read: invalid size");
355 for(i
= start
; i
< start
+ length
; i
+= size
) {
356 ioport_read_table
[bsize
][i
] = func
;
357 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
358 hw_error("register_ioport_read: invalid opaque");
359 ioport_opaque
[i
] = opaque
;
364 /* size is the word size in byte */
365 int register_ioport_write(int start
, int length
, int size
,
366 IOPortWriteFunc
*func
, void *opaque
)
372 } else if (size
== 2) {
374 } else if (size
== 4) {
377 hw_error("register_ioport_write: invalid size");
380 for(i
= start
; i
< start
+ length
; i
+= size
) {
381 ioport_write_table
[bsize
][i
] = func
;
382 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
383 hw_error("register_ioport_write: invalid opaque");
384 ioport_opaque
[i
] = opaque
;
389 void isa_unassign_ioport(int start
, int length
)
393 for(i
= start
; i
< start
+ length
; i
++) {
394 ioport_read_table
[0][i
] = default_ioport_readb
;
395 ioport_read_table
[1][i
] = default_ioport_readw
;
396 ioport_read_table
[2][i
] = default_ioport_readl
;
398 ioport_write_table
[0][i
] = default_ioport_writeb
;
399 ioport_write_table
[1][i
] = default_ioport_writew
;
400 ioport_write_table
[2][i
] = default_ioport_writel
;
404 /***********************************************************/
406 void cpu_outb(CPUState
*env
, int addr
, int val
)
409 if (loglevel
& CPU_LOG_IOPORT
)
410 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
412 ioport_write(0, addr
, val
);
415 env
->last_io_time
= cpu_get_time_fast();
419 void cpu_outw(CPUState
*env
, int addr
, int val
)
422 if (loglevel
& CPU_LOG_IOPORT
)
423 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
425 ioport_write(1, addr
, val
);
428 env
->last_io_time
= cpu_get_time_fast();
432 void cpu_outl(CPUState
*env
, int addr
, int val
)
435 if (loglevel
& CPU_LOG_IOPORT
)
436 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
438 ioport_write(2, addr
, val
);
441 env
->last_io_time
= cpu_get_time_fast();
445 int cpu_inb(CPUState
*env
, int addr
)
448 val
= ioport_read(0, addr
);
450 if (loglevel
& CPU_LOG_IOPORT
)
451 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
455 env
->last_io_time
= cpu_get_time_fast();
460 int cpu_inw(CPUState
*env
, int addr
)
463 val
= ioport_read(1, addr
);
465 if (loglevel
& CPU_LOG_IOPORT
)
466 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
470 env
->last_io_time
= cpu_get_time_fast();
475 int cpu_inl(CPUState
*env
, int addr
)
478 val
= ioport_read(2, addr
);
480 if (loglevel
& CPU_LOG_IOPORT
)
481 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
485 env
->last_io_time
= cpu_get_time_fast();
490 /***********************************************************/
491 void hw_error(const char *fmt
, ...)
497 fprintf(stderr
, "qemu: hardware error: ");
498 vfprintf(stderr
, fmt
, ap
);
499 fprintf(stderr
, "\n");
500 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
501 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
503 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
505 cpu_dump_state(env
, stderr
, fprintf
, 0);
512 /***********************************************************/
515 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
516 static void *qemu_put_kbd_event_opaque
;
517 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
518 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
520 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
522 qemu_put_kbd_event_opaque
= opaque
;
523 qemu_put_kbd_event
= func
;
526 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
527 void *opaque
, int absolute
,
530 QEMUPutMouseEntry
*s
, *cursor
;
532 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
536 s
->qemu_put_mouse_event
= func
;
537 s
->qemu_put_mouse_event_opaque
= opaque
;
538 s
->qemu_put_mouse_event_absolute
= absolute
;
539 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
542 if (!qemu_put_mouse_event_head
) {
543 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
547 cursor
= qemu_put_mouse_event_head
;
548 while (cursor
->next
!= NULL
)
549 cursor
= cursor
->next
;
552 qemu_put_mouse_event_current
= s
;
557 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
559 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
561 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
564 cursor
= qemu_put_mouse_event_head
;
565 while (cursor
!= NULL
&& cursor
!= entry
) {
567 cursor
= cursor
->next
;
570 if (cursor
== NULL
) // does not exist or list empty
572 else if (prev
== NULL
) { // entry is head
573 qemu_put_mouse_event_head
= cursor
->next
;
574 if (qemu_put_mouse_event_current
== entry
)
575 qemu_put_mouse_event_current
= cursor
->next
;
576 qemu_free(entry
->qemu_put_mouse_event_name
);
581 prev
->next
= entry
->next
;
583 if (qemu_put_mouse_event_current
== entry
)
584 qemu_put_mouse_event_current
= prev
;
586 qemu_free(entry
->qemu_put_mouse_event_name
);
590 void kbd_put_keycode(int keycode
)
592 if (qemu_put_kbd_event
) {
593 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
597 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
599 QEMUPutMouseEvent
*mouse_event
;
600 void *mouse_event_opaque
;
603 if (!qemu_put_mouse_event_current
) {
608 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
610 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
613 if (graphic_rotate
) {
614 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
617 width
= graphic_width
- 1;
618 mouse_event(mouse_event_opaque
,
619 width
- dy
, dx
, dz
, buttons_state
);
621 mouse_event(mouse_event_opaque
,
622 dx
, dy
, dz
, buttons_state
);
626 int kbd_mouse_is_absolute(void)
628 if (!qemu_put_mouse_event_current
)
631 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
634 void do_info_mice(void)
636 QEMUPutMouseEntry
*cursor
;
639 if (!qemu_put_mouse_event_head
) {
640 term_printf("No mouse devices connected\n");
644 term_printf("Mouse devices available:\n");
645 cursor
= qemu_put_mouse_event_head
;
646 while (cursor
!= NULL
) {
647 term_printf("%c Mouse #%d: %s\n",
648 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
649 index
, cursor
->qemu_put_mouse_event_name
);
651 cursor
= cursor
->next
;
655 void do_mouse_set(int index
)
657 QEMUPutMouseEntry
*cursor
;
660 if (!qemu_put_mouse_event_head
) {
661 term_printf("No mouse devices connected\n");
665 cursor
= qemu_put_mouse_event_head
;
666 while (cursor
!= NULL
&& index
!= i
) {
668 cursor
= cursor
->next
;
672 qemu_put_mouse_event_current
= cursor
;
674 term_printf("Mouse at given index not found\n");
677 /* compute with 96 bit intermediate result: (a*b)/c */
678 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
683 #ifdef WORDS_BIGENDIAN
693 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
694 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
697 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
701 /***********************************************************/
702 /* real time host monotonic timer */
704 #define QEMU_TIMER_BASE 1000000000LL
708 static int64_t clock_freq
;
710 static void init_get_clock(void)
714 ret
= QueryPerformanceFrequency(&freq
);
716 fprintf(stderr
, "Could not calibrate ticks\n");
719 clock_freq
= freq
.QuadPart
;
722 static int64_t get_clock(void)
725 QueryPerformanceCounter(&ti
);
726 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
731 static int use_rt_clock
;
733 static void init_get_clock(void)
736 #if defined(__linux__)
739 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
746 static int64_t get_clock(void)
748 #if defined(__linux__)
751 clock_gettime(CLOCK_MONOTONIC
, &ts
);
752 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
756 /* XXX: using gettimeofday leads to problems if the date
757 changes, so it should be avoided. */
759 gettimeofday(&tv
, NULL
);
760 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
765 /* Return the virtual CPU time, based on the instruction counter. */
766 static int64_t cpu_get_icount(void)
769 CPUState
*env
= cpu_single_env
;;
770 icount
= qemu_icount
;
773 fprintf(stderr
, "Bad clock read\n");
774 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
776 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
779 /***********************************************************/
780 /* guest cycle counter */
782 static int64_t cpu_ticks_prev
;
783 static int64_t cpu_ticks_offset
;
784 static int64_t cpu_clock_offset
;
785 static int cpu_ticks_enabled
;
787 /* return the host CPU cycle counter and handle stop/restart */
788 int64_t cpu_get_ticks(void)
791 return cpu_get_icount();
793 if (!cpu_ticks_enabled
) {
794 return cpu_ticks_offset
;
797 ticks
= cpu_get_real_ticks();
798 if (cpu_ticks_prev
> ticks
) {
799 /* Note: non increasing ticks may happen if the host uses
801 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
803 cpu_ticks_prev
= ticks
;
804 return ticks
+ cpu_ticks_offset
;
808 /* return the host CPU monotonic timer and handle stop/restart */
809 static int64_t cpu_get_clock(void)
812 if (!cpu_ticks_enabled
) {
813 return cpu_clock_offset
;
816 return ti
+ cpu_clock_offset
;
820 /* enable cpu_get_ticks() */
821 void cpu_enable_ticks(void)
823 if (!cpu_ticks_enabled
) {
824 cpu_ticks_offset
-= cpu_get_real_ticks();
825 cpu_clock_offset
-= get_clock();
826 cpu_ticks_enabled
= 1;
830 /* disable cpu_get_ticks() : the clock is stopped. You must not call
831 cpu_get_ticks() after that. */
832 void cpu_disable_ticks(void)
834 if (cpu_ticks_enabled
) {
835 cpu_ticks_offset
= cpu_get_ticks();
836 cpu_clock_offset
= cpu_get_clock();
837 cpu_ticks_enabled
= 0;
841 /***********************************************************/
844 #define QEMU_TIMER_REALTIME 0
845 #define QEMU_TIMER_VIRTUAL 1
849 /* XXX: add frequency */
857 struct QEMUTimer
*next
;
860 struct qemu_alarm_timer
{
864 int (*start
)(struct qemu_alarm_timer
*t
);
865 void (*stop
)(struct qemu_alarm_timer
*t
);
866 void (*rearm
)(struct qemu_alarm_timer
*t
);
870 #define ALARM_FLAG_DYNTICKS 0x1
871 #define ALARM_FLAG_EXPIRED 0x2
873 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
875 return t
->flags
& ALARM_FLAG_DYNTICKS
;
878 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
880 if (!alarm_has_dynticks(t
))
886 /* TODO: MIN_TIMER_REARM_US should be optimized */
887 #define MIN_TIMER_REARM_US 250
889 static struct qemu_alarm_timer
*alarm_timer
;
893 struct qemu_alarm_win32
{
897 } alarm_win32_data
= {0, NULL
, -1};
899 static int win32_start_timer(struct qemu_alarm_timer
*t
);
900 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
901 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
905 static int unix_start_timer(struct qemu_alarm_timer
*t
);
906 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
910 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
911 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
912 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
914 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
915 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
917 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
918 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
920 #endif /* __linux__ */
924 /* Correlation between real and virtual time is always going to be
925 fairly approximate, so ignore small variation.
926 When the guest is idle real and virtual time will be aligned in
928 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
930 static void icount_adjust(void)
935 static int64_t last_delta
;
936 /* If the VM is not running, then do nothing. */
940 cur_time
= cpu_get_clock();
941 cur_icount
= qemu_get_clock(vm_clock
);
942 delta
= cur_icount
- cur_time
;
943 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
945 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
946 && icount_time_shift
> 0) {
947 /* The guest is getting too far ahead. Slow time down. */
951 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
952 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
953 /* The guest is getting too far behind. Speed time up. */
957 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
960 static void icount_adjust_rt(void * opaque
)
962 qemu_mod_timer(icount_rt_timer
,
963 qemu_get_clock(rt_clock
) + 1000);
967 static void icount_adjust_vm(void * opaque
)
969 qemu_mod_timer(icount_vm_timer
,
970 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
974 static void init_icount_adjust(void)
976 /* Have both realtime and virtual time triggers for speed adjustment.
977 The realtime trigger catches emulated time passing too slowly,
978 the virtual time trigger catches emulated time passing too fast.
979 Realtime triggers occur even when idle, so use them less frequently
981 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
982 qemu_mod_timer(icount_rt_timer
,
983 qemu_get_clock(rt_clock
) + 1000);
984 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
985 qemu_mod_timer(icount_vm_timer
,
986 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
989 static struct qemu_alarm_timer alarm_timers
[] = {
992 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
993 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
994 /* HPET - if available - is preferred */
995 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
996 /* ...otherwise try RTC */
997 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
999 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1001 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1002 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1003 {"win32", 0, win32_start_timer
,
1004 win32_stop_timer
, NULL
, &alarm_win32_data
},
1009 static void show_available_alarms(void)
1013 printf("Available alarm timers, in order of precedence:\n");
1014 for (i
= 0; alarm_timers
[i
].name
; i
++)
1015 printf("%s\n", alarm_timers
[i
].name
);
1018 static void configure_alarms(char const *opt
)
1022 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1025 struct qemu_alarm_timer tmp
;
1027 if (!strcmp(opt
, "?")) {
1028 show_available_alarms();
1034 /* Reorder the array */
1035 name
= strtok(arg
, ",");
1037 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1038 if (!strcmp(alarm_timers
[i
].name
, name
))
1043 fprintf(stderr
, "Unknown clock %s\n", name
);
1052 tmp
= alarm_timers
[i
];
1053 alarm_timers
[i
] = alarm_timers
[cur
];
1054 alarm_timers
[cur
] = tmp
;
1058 name
= strtok(NULL
, ",");
1064 /* Disable remaining timers */
1065 for (i
= cur
; i
< count
; i
++)
1066 alarm_timers
[i
].name
= NULL
;
1068 show_available_alarms();
1073 QEMUClock
*rt_clock
;
1074 QEMUClock
*vm_clock
;
1076 static QEMUTimer
*active_timers
[2];
1078 static QEMUClock
*qemu_new_clock(int type
)
1081 clock
= qemu_mallocz(sizeof(QEMUClock
));
1088 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1092 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1095 ts
->opaque
= opaque
;
1099 void qemu_free_timer(QEMUTimer
*ts
)
1104 /* stop a timer, but do not dealloc it */
1105 void qemu_del_timer(QEMUTimer
*ts
)
1109 /* NOTE: this code must be signal safe because
1110 qemu_timer_expired() can be called from a signal. */
1111 pt
= &active_timers
[ts
->clock
->type
];
1124 /* modify the current timer so that it will be fired when current_time
1125 >= expire_time. The corresponding callback will be called. */
1126 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1132 /* add the timer in the sorted list */
1133 /* NOTE: this code must be signal safe because
1134 qemu_timer_expired() can be called from a signal. */
1135 pt
= &active_timers
[ts
->clock
->type
];
1140 if (t
->expire_time
> expire_time
)
1144 ts
->expire_time
= expire_time
;
1148 /* Rearm if necessary */
1149 if (pt
== &active_timers
[ts
->clock
->type
]) {
1150 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1151 qemu_rearm_alarm_timer(alarm_timer
);
1153 /* Interrupt execution to force deadline recalculation. */
1154 if (use_icount
&& cpu_single_env
) {
1155 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1160 int qemu_timer_pending(QEMUTimer
*ts
)
1163 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1170 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1174 return (timer_head
->expire_time
<= current_time
);
1177 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1183 if (!ts
|| ts
->expire_time
> current_time
)
1185 /* remove timer from the list before calling the callback */
1186 *ptimer_head
= ts
->next
;
1189 /* run the callback (the timer list can be modified) */
1194 int64_t qemu_get_clock(QEMUClock
*clock
)
1196 switch(clock
->type
) {
1197 case QEMU_TIMER_REALTIME
:
1198 return get_clock() / 1000000;
1200 case QEMU_TIMER_VIRTUAL
:
1202 return cpu_get_icount();
1204 return cpu_get_clock();
1209 static void init_timers(void)
1212 ticks_per_sec
= QEMU_TIMER_BASE
;
1213 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1214 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1218 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1220 uint64_t expire_time
;
1222 if (qemu_timer_pending(ts
)) {
1223 expire_time
= ts
->expire_time
;
1227 qemu_put_be64(f
, expire_time
);
1230 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1232 uint64_t expire_time
;
1234 expire_time
= qemu_get_be64(f
);
1235 if (expire_time
!= -1) {
1236 qemu_mod_timer(ts
, expire_time
);
1242 static void timer_save(QEMUFile
*f
, void *opaque
)
1244 if (cpu_ticks_enabled
) {
1245 hw_error("cannot save state if virtual timers are running");
1247 qemu_put_be64(f
, cpu_ticks_offset
);
1248 qemu_put_be64(f
, ticks_per_sec
);
1249 qemu_put_be64(f
, cpu_clock_offset
);
1252 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1254 if (version_id
!= 1 && version_id
!= 2)
1256 if (cpu_ticks_enabled
) {
1259 cpu_ticks_offset
=qemu_get_be64(f
);
1260 ticks_per_sec
=qemu_get_be64(f
);
1261 if (version_id
== 2) {
1262 cpu_clock_offset
=qemu_get_be64(f
);
1268 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1269 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1271 static void host_alarm_handler(int host_signum
)
1275 #define DISP_FREQ 1000
1277 static int64_t delta_min
= INT64_MAX
;
1278 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1280 ti
= qemu_get_clock(vm_clock
);
1281 if (last_clock
!= 0) {
1282 delta
= ti
- last_clock
;
1283 if (delta
< delta_min
)
1285 if (delta
> delta_max
)
1288 if (++count
== DISP_FREQ
) {
1289 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1290 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1291 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1292 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1293 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1295 delta_min
= INT64_MAX
;
1303 if (alarm_has_dynticks(alarm_timer
) ||
1305 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1306 qemu_get_clock(vm_clock
))) ||
1307 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1308 qemu_get_clock(rt_clock
))) {
1310 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1311 SetEvent(data
->host_alarm
);
1313 CPUState
*env
= next_cpu
;
1315 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1318 /* stop the currently executing cpu because a timer occured */
1319 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1321 if (env
->kqemu_enabled
) {
1322 kqemu_cpu_interrupt(env
);
1330 static int64_t qemu_next_deadline(void)
1334 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1335 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1336 qemu_get_clock(vm_clock
);
1338 /* To avoid problems with overflow limit this to 2^32. */
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
;
1373 #if defined(__linux__)
1375 #define RTC_FREQ 1024
1377 static void enable_sigio_timer(int fd
)
1379 struct sigaction act
;
1382 sigfillset(&act
.sa_mask
);
1384 act
.sa_handler
= host_alarm_handler
;
1386 sigaction(SIGIO
, &act
, NULL
);
1387 fcntl(fd
, F_SETFL
, O_ASYNC
);
1388 fcntl(fd
, F_SETOWN
, getpid());
1391 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1393 struct hpet_info info
;
1396 fd
= open("/dev/hpet", O_RDONLY
);
1401 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1403 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1404 "error, but for better emulation accuracy type:\n"
1405 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1409 /* Check capabilities */
1410 r
= ioctl(fd
, HPET_INFO
, &info
);
1414 /* Enable periodic mode */
1415 r
= ioctl(fd
, HPET_EPI
, 0);
1416 if (info
.hi_flags
&& (r
< 0))
1419 /* Enable interrupt */
1420 r
= ioctl(fd
, HPET_IE_ON
, 0);
1424 enable_sigio_timer(fd
);
1425 t
->priv
= (void *)(long)fd
;
1433 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1435 int fd
= (long)t
->priv
;
1440 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1443 unsigned long current_rtc_freq
= 0;
1445 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1448 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1449 if (current_rtc_freq
!= RTC_FREQ
&&
1450 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1451 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1452 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1453 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1456 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1462 enable_sigio_timer(rtc_fd
);
1464 t
->priv
= (void *)(long)rtc_fd
;
1469 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1471 int rtc_fd
= (long)t
->priv
;
1476 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1480 struct sigaction act
;
1482 sigfillset(&act
.sa_mask
);
1484 act
.sa_handler
= host_alarm_handler
;
1486 sigaction(SIGALRM
, &act
, NULL
);
1488 ev
.sigev_value
.sival_int
= 0;
1489 ev
.sigev_notify
= SIGEV_SIGNAL
;
1490 ev
.sigev_signo
= SIGALRM
;
1492 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1493 perror("timer_create");
1495 /* disable dynticks */
1496 fprintf(stderr
, "Dynamic Ticks disabled\n");
1501 t
->priv
= (void *)host_timer
;
1506 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1508 timer_t host_timer
= (timer_t
)t
->priv
;
1510 timer_delete(host_timer
);
1513 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1515 timer_t host_timer
= (timer_t
)t
->priv
;
1516 struct itimerspec timeout
;
1517 int64_t nearest_delta_us
= INT64_MAX
;
1520 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1521 !active_timers
[QEMU_TIMER_VIRTUAL
])
1524 nearest_delta_us
= qemu_next_deadline_dyntick();
1526 /* check whether a timer is already running */
1527 if (timer_gettime(host_timer
, &timeout
)) {
1529 fprintf(stderr
, "Internal timer error: aborting\n");
1532 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1533 if (current_us
&& current_us
<= nearest_delta_us
)
1536 timeout
.it_interval
.tv_sec
= 0;
1537 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1538 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1539 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1540 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1542 fprintf(stderr
, "Internal timer error: aborting\n");
1547 #endif /* defined(__linux__) */
1549 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1551 struct sigaction act
;
1552 struct itimerval itv
;
1556 sigfillset(&act
.sa_mask
);
1558 act
.sa_handler
= host_alarm_handler
;
1560 sigaction(SIGALRM
, &act
, NULL
);
1562 itv
.it_interval
.tv_sec
= 0;
1563 /* for i386 kernel 2.6 to get 1 ms */
1564 itv
.it_interval
.tv_usec
= 999;
1565 itv
.it_value
.tv_sec
= 0;
1566 itv
.it_value
.tv_usec
= 10 * 1000;
1568 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1575 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1577 struct itimerval itv
;
1579 memset(&itv
, 0, sizeof(itv
));
1580 setitimer(ITIMER_REAL
, &itv
, NULL
);
1583 #endif /* !defined(_WIN32) */
1587 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1590 struct qemu_alarm_win32
*data
= t
->priv
;
1593 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1594 if (!data
->host_alarm
) {
1595 perror("Failed CreateEvent");
1599 memset(&tc
, 0, sizeof(tc
));
1600 timeGetDevCaps(&tc
, sizeof(tc
));
1602 if (data
->period
< tc
.wPeriodMin
)
1603 data
->period
= tc
.wPeriodMin
;
1605 timeBeginPeriod(data
->period
);
1607 flags
= TIME_CALLBACK_FUNCTION
;
1608 if (alarm_has_dynticks(t
))
1609 flags
|= TIME_ONESHOT
;
1611 flags
|= TIME_PERIODIC
;
1613 data
->timerId
= timeSetEvent(1, // interval (ms)
1614 data
->period
, // resolution
1615 host_alarm_handler
, // function
1616 (DWORD
)t
, // parameter
1619 if (!data
->timerId
) {
1620 perror("Failed to initialize win32 alarm timer");
1622 timeEndPeriod(data
->period
);
1623 CloseHandle(data
->host_alarm
);
1627 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1632 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1634 struct qemu_alarm_win32
*data
= t
->priv
;
1636 timeKillEvent(data
->timerId
);
1637 timeEndPeriod(data
->period
);
1639 CloseHandle(data
->host_alarm
);
1642 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1644 struct qemu_alarm_win32
*data
= t
->priv
;
1645 uint64_t nearest_delta_us
;
1647 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1648 !active_timers
[QEMU_TIMER_VIRTUAL
])
1651 nearest_delta_us
= qemu_next_deadline_dyntick();
1652 nearest_delta_us
/= 1000;
1654 timeKillEvent(data
->timerId
);
1656 data
->timerId
= timeSetEvent(1,
1660 TIME_ONESHOT
| TIME_PERIODIC
);
1662 if (!data
->timerId
) {
1663 perror("Failed to re-arm win32 alarm timer");
1665 timeEndPeriod(data
->period
);
1666 CloseHandle(data
->host_alarm
);
1673 static void init_timer_alarm(void)
1675 struct qemu_alarm_timer
*t
;
1678 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1679 t
= &alarm_timers
[i
];
1687 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1688 fprintf(stderr
, "Terminating\n");
1695 static void quit_timers(void)
1697 alarm_timer
->stop(alarm_timer
);
1701 /***********************************************************/
1702 /* host time/date access */
1703 void qemu_get_timedate(struct tm
*tm
, int offset
)
1710 if (rtc_date_offset
== -1) {
1714 ret
= localtime(&ti
);
1716 ti
-= rtc_date_offset
;
1720 memcpy(tm
, ret
, sizeof(struct tm
));
1723 int qemu_timedate_diff(struct tm
*tm
)
1727 if (rtc_date_offset
== -1)
1729 seconds
= mktimegm(tm
);
1731 seconds
= mktime(tm
);
1733 seconds
= mktimegm(tm
) + rtc_date_offset
;
1735 return seconds
- time(NULL
);
1738 /***********************************************************/
1739 /* character device */
1741 static void qemu_chr_event(CharDriverState
*s
, int event
)
1745 s
->chr_event(s
->handler_opaque
, event
);
1748 static void qemu_chr_reset_bh(void *opaque
)
1750 CharDriverState
*s
= opaque
;
1751 qemu_chr_event(s
, CHR_EVENT_RESET
);
1752 qemu_bh_delete(s
->bh
);
1756 void qemu_chr_reset(CharDriverState
*s
)
1758 if (s
->bh
== NULL
) {
1759 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1760 qemu_bh_schedule(s
->bh
);
1764 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1766 return s
->chr_write(s
, buf
, len
);
1769 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1773 return s
->chr_ioctl(s
, cmd
, arg
);
1776 int qemu_chr_can_read(CharDriverState
*s
)
1778 if (!s
->chr_can_read
)
1780 return s
->chr_can_read(s
->handler_opaque
);
1783 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1785 s
->chr_read(s
->handler_opaque
, buf
, len
);
1788 void qemu_chr_accept_input(CharDriverState
*s
)
1790 if (s
->chr_accept_input
)
1791 s
->chr_accept_input(s
);
1794 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1799 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1800 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1804 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1806 if (s
->chr_send_event
)
1807 s
->chr_send_event(s
, event
);
1810 void qemu_chr_add_handlers(CharDriverState
*s
,
1811 IOCanRWHandler
*fd_can_read
,
1812 IOReadHandler
*fd_read
,
1813 IOEventHandler
*fd_event
,
1816 s
->chr_can_read
= fd_can_read
;
1817 s
->chr_read
= fd_read
;
1818 s
->chr_event
= fd_event
;
1819 s
->handler_opaque
= opaque
;
1820 if (s
->chr_update_read_handler
)
1821 s
->chr_update_read_handler(s
);
1824 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1829 static CharDriverState
*qemu_chr_open_null(void)
1831 CharDriverState
*chr
;
1833 chr
= qemu_mallocz(sizeof(CharDriverState
));
1836 chr
->chr_write
= null_chr_write
;
1840 /* MUX driver for serial I/O splitting */
1841 static int term_timestamps
;
1842 static int64_t term_timestamps_start
;
1844 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1845 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1847 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1848 IOReadHandler
*chr_read
[MAX_MUX
];
1849 IOEventHandler
*chr_event
[MAX_MUX
];
1850 void *ext_opaque
[MAX_MUX
];
1851 CharDriverState
*drv
;
1852 unsigned char buffer
[MUX_BUFFER_SIZE
];
1856 int term_got_escape
;
1861 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1863 MuxDriver
*d
= chr
->opaque
;
1865 if (!term_timestamps
) {
1866 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1871 for(i
= 0; i
< len
; i
++) {
1872 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1873 if (buf
[i
] == '\n') {
1879 if (term_timestamps_start
== -1)
1880 term_timestamps_start
= ti
;
1881 ti
-= term_timestamps_start
;
1882 secs
= ti
/ 1000000000;
1883 snprintf(buf1
, sizeof(buf1
),
1884 "[%02d:%02d:%02d.%03d] ",
1888 (int)((ti
/ 1000000) % 1000));
1889 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1896 static char *mux_help
[] = {
1897 "% h print this help\n\r",
1898 "% x exit emulator\n\r",
1899 "% s save disk data back to file (if -snapshot)\n\r",
1900 "% t toggle console timestamps\n\r"
1901 "% b send break (magic sysrq)\n\r",
1902 "% c switch between console and monitor\n\r",
1907 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1908 static void mux_print_help(CharDriverState
*chr
)
1911 char ebuf
[15] = "Escape-Char";
1912 char cbuf
[50] = "\n\r";
1914 if (term_escape_char
> 0 && term_escape_char
< 26) {
1915 sprintf(cbuf
,"\n\r");
1916 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1918 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1921 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1922 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1923 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1924 if (mux_help
[i
][j
] == '%')
1925 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1927 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1932 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1934 if (d
->term_got_escape
) {
1935 d
->term_got_escape
= 0;
1936 if (ch
== term_escape_char
)
1941 mux_print_help(chr
);
1945 char *term
= "QEMU: Terminated\n\r";
1946 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1953 for (i
= 0; i
< nb_drives
; i
++) {
1954 bdrv_commit(drives_table
[i
].bdrv
);
1959 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1962 /* Switch to the next registered device */
1964 if (chr
->focus
>= d
->mux_cnt
)
1968 term_timestamps
= !term_timestamps
;
1969 term_timestamps_start
= -1;
1972 } else if (ch
== term_escape_char
) {
1973 d
->term_got_escape
= 1;
1981 static void mux_chr_accept_input(CharDriverState
*chr
)
1984 MuxDriver
*d
= chr
->opaque
;
1986 while (d
->prod
!= d
->cons
&&
1987 d
->chr_can_read
[m
] &&
1988 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1989 d
->chr_read
[m
](d
->ext_opaque
[m
],
1990 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
1994 static int mux_chr_can_read(void *opaque
)
1996 CharDriverState
*chr
= opaque
;
1997 MuxDriver
*d
= chr
->opaque
;
1999 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2001 if (d
->chr_can_read
[chr
->focus
])
2002 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2006 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2008 CharDriverState
*chr
= opaque
;
2009 MuxDriver
*d
= chr
->opaque
;
2013 mux_chr_accept_input (opaque
);
2015 for(i
= 0; i
< size
; i
++)
2016 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2017 if (d
->prod
== d
->cons
&&
2018 d
->chr_can_read
[m
] &&
2019 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2020 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2022 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2026 static void mux_chr_event(void *opaque
, int event
)
2028 CharDriverState
*chr
= opaque
;
2029 MuxDriver
*d
= chr
->opaque
;
2032 /* Send the event to all registered listeners */
2033 for (i
= 0; i
< d
->mux_cnt
; i
++)
2034 if (d
->chr_event
[i
])
2035 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2038 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2040 MuxDriver
*d
= chr
->opaque
;
2042 if (d
->mux_cnt
>= MAX_MUX
) {
2043 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2046 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2047 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2048 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2049 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2050 /* Fix up the real driver with mux routines */
2051 if (d
->mux_cnt
== 0) {
2052 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2053 mux_chr_event
, chr
);
2055 chr
->focus
= d
->mux_cnt
;
2059 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2061 CharDriverState
*chr
;
2064 chr
= qemu_mallocz(sizeof(CharDriverState
));
2067 d
= qemu_mallocz(sizeof(MuxDriver
));
2076 chr
->chr_write
= mux_chr_write
;
2077 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2078 chr
->chr_accept_input
= mux_chr_accept_input
;
2085 static void socket_cleanup(void)
2090 static int socket_init(void)
2095 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2097 err
= WSAGetLastError();
2098 fprintf(stderr
, "WSAStartup: %d\n", err
);
2101 atexit(socket_cleanup
);
2105 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2111 ret
= send(fd
, buf
, len
, 0);
2114 errno
= WSAGetLastError();
2115 if (errno
!= WSAEWOULDBLOCK
) {
2118 } else if (ret
== 0) {
2128 void socket_set_nonblock(int fd
)
2130 unsigned long opt
= 1;
2131 ioctlsocket(fd
, FIONBIO
, &opt
);
2136 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2142 ret
= write(fd
, buf
, len
);
2144 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2146 } else if (ret
== 0) {
2156 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2158 return unix_write(fd
, buf
, len1
);
2161 void socket_set_nonblock(int fd
)
2164 f
= fcntl(fd
, F_GETFL
);
2165 fcntl(fd
, F_SETFL
, f
| O_NONBLOCK
);
2167 #endif /* !_WIN32 */
2176 #define STDIO_MAX_CLIENTS 1
2177 static int stdio_nb_clients
= 0;
2179 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2181 FDCharDriver
*s
= chr
->opaque
;
2182 return unix_write(s
->fd_out
, buf
, len
);
2185 static int fd_chr_read_poll(void *opaque
)
2187 CharDriverState
*chr
= opaque
;
2188 FDCharDriver
*s
= chr
->opaque
;
2190 s
->max_size
= qemu_chr_can_read(chr
);
2194 static void fd_chr_read(void *opaque
)
2196 CharDriverState
*chr
= opaque
;
2197 FDCharDriver
*s
= chr
->opaque
;
2202 if (len
> s
->max_size
)
2206 size
= read(s
->fd_in
, buf
, len
);
2208 /* FD has been closed. Remove it from the active list. */
2209 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2213 qemu_chr_read(chr
, buf
, size
);
2217 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2219 FDCharDriver
*s
= chr
->opaque
;
2221 if (s
->fd_in
>= 0) {
2222 if (nographic
&& s
->fd_in
== 0) {
2224 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2225 fd_chr_read
, NULL
, chr
);
2230 static void fd_chr_close(struct CharDriverState
*chr
)
2232 FDCharDriver
*s
= chr
->opaque
;
2234 if (s
->fd_in
>= 0) {
2235 if (nographic
&& s
->fd_in
== 0) {
2237 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2244 /* open a character device to a unix fd */
2245 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2247 CharDriverState
*chr
;
2250 chr
= qemu_mallocz(sizeof(CharDriverState
));
2253 s
= qemu_mallocz(sizeof(FDCharDriver
));
2261 chr
->chr_write
= fd_chr_write
;
2262 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2263 chr
->chr_close
= fd_chr_close
;
2265 qemu_chr_reset(chr
);
2270 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2274 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2277 return qemu_chr_open_fd(-1, fd_out
);
2280 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2283 char filename_in
[256], filename_out
[256];
2285 snprintf(filename_in
, 256, "%s.in", filename
);
2286 snprintf(filename_out
, 256, "%s.out", filename
);
2287 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2288 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2289 if (fd_in
< 0 || fd_out
< 0) {
2294 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2298 return qemu_chr_open_fd(fd_in
, fd_out
);
2302 /* for STDIO, we handle the case where several clients use it
2305 #define TERM_FIFO_MAX_SIZE 1
2307 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2308 static int term_fifo_size
;
2310 static int stdio_read_poll(void *opaque
)
2312 CharDriverState
*chr
= opaque
;
2314 /* try to flush the queue if needed */
2315 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2316 qemu_chr_read(chr
, term_fifo
, 1);
2319 /* see if we can absorb more chars */
2320 if (term_fifo_size
== 0)
2326 static void stdio_read(void *opaque
)
2330 CharDriverState
*chr
= opaque
;
2332 size
= read(0, buf
, 1);
2334 /* stdin has been closed. Remove it from the active list. */
2335 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2339 if (qemu_chr_can_read(chr
) > 0) {
2340 qemu_chr_read(chr
, buf
, 1);
2341 } else if (term_fifo_size
== 0) {
2342 term_fifo
[term_fifo_size
++] = buf
[0];
2347 /* init terminal so that we can grab keys */
2348 static struct termios oldtty
;
2349 static int old_fd0_flags
;
2350 static int term_atexit_done
;
2352 static void term_exit(void)
2354 tcsetattr (0, TCSANOW
, &oldtty
);
2355 fcntl(0, F_SETFL
, old_fd0_flags
);
2358 static void term_init(void)
2362 tcgetattr (0, &tty
);
2364 old_fd0_flags
= fcntl(0, F_GETFL
);
2366 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2367 |INLCR
|IGNCR
|ICRNL
|IXON
);
2368 tty
.c_oflag
|= OPOST
;
2369 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2370 /* if graphical mode, we allow Ctrl-C handling */
2372 tty
.c_lflag
&= ~ISIG
;
2373 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2376 tty
.c_cc
[VTIME
] = 0;
2378 tcsetattr (0, TCSANOW
, &tty
);
2380 if (!term_atexit_done
++)
2383 fcntl(0, F_SETFL
, O_NONBLOCK
);
2386 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2390 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2394 static CharDriverState
*qemu_chr_open_stdio(void)
2396 CharDriverState
*chr
;
2398 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2400 chr
= qemu_chr_open_fd(0, 1);
2401 chr
->chr_close
= qemu_chr_close_stdio
;
2402 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2410 /* Once Solaris has openpty(), this is going to be removed. */
2411 int openpty(int *amaster
, int *aslave
, char *name
,
2412 struct termios
*termp
, struct winsize
*winp
)
2415 int mfd
= -1, sfd
= -1;
2417 *amaster
= *aslave
= -1;
2419 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2423 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2426 if ((slave
= ptsname(mfd
)) == NULL
)
2429 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2432 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2433 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2441 ioctl(sfd
, TIOCSWINSZ
, winp
);
2452 void cfmakeraw (struct termios
*termios_p
)
2454 termios_p
->c_iflag
&=
2455 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2456 termios_p
->c_oflag
&= ~OPOST
;
2457 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2458 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2459 termios_p
->c_cflag
|= CS8
;
2461 termios_p
->c_cc
[VMIN
] = 0;
2462 termios_p
->c_cc
[VTIME
] = 0;
2466 #if defined(__linux__) || defined(__sun__)
2476 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2477 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2479 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2481 PtyCharDriver
*s
= chr
->opaque
;
2483 if (!s
->connected
) {
2484 /* guest sends data, check for (re-)connect */
2485 pty_chr_update_read_handler(chr
);
2488 return unix_write(s
->fd
, buf
, len
);
2491 static int pty_chr_read_poll(void *opaque
)
2493 CharDriverState
*chr
= opaque
;
2494 PtyCharDriver
*s
= chr
->opaque
;
2496 s
->read_bytes
= qemu_chr_can_read(chr
);
2497 return s
->read_bytes
;
2500 static void pty_chr_read(void *opaque
)
2502 CharDriverState
*chr
= opaque
;
2503 PtyCharDriver
*s
= chr
->opaque
;
2508 if (len
> s
->read_bytes
)
2509 len
= s
->read_bytes
;
2512 size
= read(s
->fd
, buf
, len
);
2513 if ((size
== -1 && errno
== EIO
) ||
2515 pty_chr_state(chr
, 0);
2519 pty_chr_state(chr
, 1);
2520 qemu_chr_read(chr
, buf
, size
);
2524 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2526 PtyCharDriver
*s
= chr
->opaque
;
2528 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2529 pty_chr_read
, NULL
, chr
);
2532 * Short timeout here: just need wait long enougth that qemu makes
2533 * it through the poll loop once. When reconnected we want a
2534 * short timeout so we notice it almost instantly. Otherwise
2535 * read() gives us -EIO instantly, making pty_chr_state() reset the
2536 * timeout to the normal (much longer) poll interval before the
2539 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2542 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2544 PtyCharDriver
*s
= chr
->opaque
;
2547 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2550 /* (re-)connect poll interval for idle guests: once per second.
2551 * We check more frequently in case the guests sends data to
2552 * the virtual device linked to our pty. */
2553 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2556 qemu_chr_reset(chr
);
2561 void pty_chr_timer(void *opaque
)
2563 struct CharDriverState
*chr
= opaque
;
2564 PtyCharDriver
*s
= chr
->opaque
;
2569 /* If we arrive here without polling being cleared due
2570 * read returning -EIO, then we are (re-)connected */
2571 pty_chr_state(chr
, 1);
2576 pty_chr_update_read_handler(chr
);
2579 static void pty_chr_close(struct CharDriverState
*chr
)
2581 PtyCharDriver
*s
= chr
->opaque
;
2583 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2588 static CharDriverState
*qemu_chr_open_pty(void)
2590 CharDriverState
*chr
;
2595 chr
= qemu_mallocz(sizeof(CharDriverState
));
2598 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2604 if (openpty(&s
->fd
, &slave_fd
, NULL
, NULL
, NULL
) < 0) {
2608 /* Set raw attributes on the pty. */
2610 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2613 fprintf(stderr
, "char device redirected to %s\n", ptsname(s
->fd
));
2616 chr
->chr_write
= pty_chr_write
;
2617 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2618 chr
->chr_close
= pty_chr_close
;
2620 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2625 static void tty_serial_init(int fd
, int speed
,
2626 int parity
, int data_bits
, int stop_bits
)
2632 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2633 speed
, parity
, data_bits
, stop_bits
);
2635 tcgetattr (fd
, &tty
);
2638 if (speed
<= 50 * MARGIN
)
2640 else if (speed
<= 75 * MARGIN
)
2642 else if (speed
<= 300 * MARGIN
)
2644 else if (speed
<= 600 * MARGIN
)
2646 else if (speed
<= 1200 * MARGIN
)
2648 else if (speed
<= 2400 * MARGIN
)
2650 else if (speed
<= 4800 * MARGIN
)
2652 else if (speed
<= 9600 * MARGIN
)
2654 else if (speed
<= 19200 * MARGIN
)
2656 else if (speed
<= 38400 * MARGIN
)
2658 else if (speed
<= 57600 * MARGIN
)
2660 else if (speed
<= 115200 * MARGIN
)
2665 cfsetispeed(&tty
, spd
);
2666 cfsetospeed(&tty
, spd
);
2668 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2669 |INLCR
|IGNCR
|ICRNL
|IXON
);
2670 tty
.c_oflag
|= OPOST
;
2671 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2672 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2693 tty
.c_cflag
|= PARENB
;
2696 tty
.c_cflag
|= PARENB
| PARODD
;
2700 tty
.c_cflag
|= CSTOPB
;
2702 tcsetattr (fd
, TCSANOW
, &tty
);
2705 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2707 FDCharDriver
*s
= chr
->opaque
;
2710 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2712 QEMUSerialSetParams
*ssp
= arg
;
2713 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2714 ssp
->data_bits
, ssp
->stop_bits
);
2717 case CHR_IOCTL_SERIAL_SET_BREAK
:
2719 int enable
= *(int *)arg
;
2721 tcsendbreak(s
->fd_in
, 1);
2730 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2732 CharDriverState
*chr
;
2735 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2736 tty_serial_init(fd
, 115200, 'N', 8, 1);
2737 chr
= qemu_chr_open_fd(fd
, fd
);
2742 chr
->chr_ioctl
= tty_serial_ioctl
;
2743 qemu_chr_reset(chr
);
2746 #else /* ! __linux__ && ! __sun__ */
2747 static CharDriverState
*qemu_chr_open_pty(void)
2751 #endif /* __linux__ || __sun__ */
2753 #if defined(__linux__)
2757 } ParallelCharDriver
;
2759 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2761 if (s
->mode
!= mode
) {
2763 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2770 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2772 ParallelCharDriver
*drv
= chr
->opaque
;
2777 case CHR_IOCTL_PP_READ_DATA
:
2778 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2780 *(uint8_t *)arg
= b
;
2782 case CHR_IOCTL_PP_WRITE_DATA
:
2783 b
= *(uint8_t *)arg
;
2784 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2787 case CHR_IOCTL_PP_READ_CONTROL
:
2788 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2790 /* Linux gives only the lowest bits, and no way to know data
2791 direction! For better compatibility set the fixed upper
2793 *(uint8_t *)arg
= b
| 0xc0;
2795 case CHR_IOCTL_PP_WRITE_CONTROL
:
2796 b
= *(uint8_t *)arg
;
2797 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2800 case CHR_IOCTL_PP_READ_STATUS
:
2801 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2803 *(uint8_t *)arg
= b
;
2805 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2806 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2807 struct ParallelIOArg
*parg
= arg
;
2808 int n
= read(fd
, parg
->buffer
, parg
->count
);
2809 if (n
!= parg
->count
) {
2814 case CHR_IOCTL_PP_EPP_READ
:
2815 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2816 struct ParallelIOArg
*parg
= arg
;
2817 int n
= read(fd
, parg
->buffer
, parg
->count
);
2818 if (n
!= parg
->count
) {
2823 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2824 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2825 struct ParallelIOArg
*parg
= arg
;
2826 int n
= write(fd
, parg
->buffer
, parg
->count
);
2827 if (n
!= parg
->count
) {
2832 case CHR_IOCTL_PP_EPP_WRITE
:
2833 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2834 struct ParallelIOArg
*parg
= arg
;
2835 int n
= write(fd
, parg
->buffer
, parg
->count
);
2836 if (n
!= parg
->count
) {
2847 static void pp_close(CharDriverState
*chr
)
2849 ParallelCharDriver
*drv
= chr
->opaque
;
2852 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2853 ioctl(fd
, PPRELEASE
);
2858 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2860 CharDriverState
*chr
;
2861 ParallelCharDriver
*drv
;
2864 TFR(fd
= open(filename
, O_RDWR
));
2868 if (ioctl(fd
, PPCLAIM
) < 0) {
2873 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2879 drv
->mode
= IEEE1284_MODE_COMPAT
;
2881 chr
= qemu_mallocz(sizeof(CharDriverState
));
2887 chr
->chr_write
= null_chr_write
;
2888 chr
->chr_ioctl
= pp_ioctl
;
2889 chr
->chr_close
= pp_close
;
2892 qemu_chr_reset(chr
);
2896 #endif /* __linux__ */
2902 HANDLE hcom
, hrecv
, hsend
;
2903 OVERLAPPED orecv
, osend
;
2908 #define NSENDBUF 2048
2909 #define NRECVBUF 2048
2910 #define MAXCONNECT 1
2911 #define NTIMEOUT 5000
2913 static int win_chr_poll(void *opaque
);
2914 static int win_chr_pipe_poll(void *opaque
);
2916 static void win_chr_close(CharDriverState
*chr
)
2918 WinCharState
*s
= chr
->opaque
;
2921 CloseHandle(s
->hsend
);
2925 CloseHandle(s
->hrecv
);
2929 CloseHandle(s
->hcom
);
2933 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2935 qemu_del_polling_cb(win_chr_poll
, chr
);
2938 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2940 WinCharState
*s
= chr
->opaque
;
2942 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2947 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2949 fprintf(stderr
, "Failed CreateEvent\n");
2952 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2954 fprintf(stderr
, "Failed CreateEvent\n");
2958 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2959 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2960 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2961 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2966 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2967 fprintf(stderr
, "Failed SetupComm\n");
2971 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2972 size
= sizeof(COMMCONFIG
);
2973 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2974 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2975 CommConfigDialog(filename
, NULL
, &comcfg
);
2977 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
2978 fprintf(stderr
, "Failed SetCommState\n");
2982 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
2983 fprintf(stderr
, "Failed SetCommMask\n");
2987 cto
.ReadIntervalTimeout
= MAXDWORD
;
2988 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
2989 fprintf(stderr
, "Failed SetCommTimeouts\n");
2993 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
2994 fprintf(stderr
, "Failed ClearCommError\n");
2997 qemu_add_polling_cb(win_chr_poll
, chr
);
3005 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3007 WinCharState
*s
= chr
->opaque
;
3008 DWORD len
, ret
, size
, err
;
3011 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3012 s
->osend
.hEvent
= s
->hsend
;
3015 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3017 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3019 err
= GetLastError();
3020 if (err
== ERROR_IO_PENDING
) {
3021 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3039 static int win_chr_read_poll(CharDriverState
*chr
)
3041 WinCharState
*s
= chr
->opaque
;
3043 s
->max_size
= qemu_chr_can_read(chr
);
3047 static void win_chr_readfile(CharDriverState
*chr
)
3049 WinCharState
*s
= chr
->opaque
;
3054 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3055 s
->orecv
.hEvent
= s
->hrecv
;
3056 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3058 err
= GetLastError();
3059 if (err
== ERROR_IO_PENDING
) {
3060 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3065 qemu_chr_read(chr
, buf
, size
);
3069 static void win_chr_read(CharDriverState
*chr
)
3071 WinCharState
*s
= chr
->opaque
;
3073 if (s
->len
> s
->max_size
)
3074 s
->len
= s
->max_size
;
3078 win_chr_readfile(chr
);
3081 static int win_chr_poll(void *opaque
)
3083 CharDriverState
*chr
= opaque
;
3084 WinCharState
*s
= chr
->opaque
;
3088 ClearCommError(s
->hcom
, &comerr
, &status
);
3089 if (status
.cbInQue
> 0) {
3090 s
->len
= status
.cbInQue
;
3091 win_chr_read_poll(chr
);
3098 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3100 CharDriverState
*chr
;
3103 chr
= qemu_mallocz(sizeof(CharDriverState
));
3106 s
= qemu_mallocz(sizeof(WinCharState
));
3112 chr
->chr_write
= win_chr_write
;
3113 chr
->chr_close
= win_chr_close
;
3115 if (win_chr_init(chr
, filename
) < 0) {
3120 qemu_chr_reset(chr
);
3124 static int win_chr_pipe_poll(void *opaque
)
3126 CharDriverState
*chr
= opaque
;
3127 WinCharState
*s
= chr
->opaque
;
3130 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3133 win_chr_read_poll(chr
);
3140 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3142 WinCharState
*s
= chr
->opaque
;
3150 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3152 fprintf(stderr
, "Failed CreateEvent\n");
3155 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3157 fprintf(stderr
, "Failed CreateEvent\n");
3161 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3162 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3163 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3165 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3166 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3167 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3172 ZeroMemory(&ov
, sizeof(ov
));
3173 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3174 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3176 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3180 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3182 fprintf(stderr
, "Failed GetOverlappedResult\n");
3184 CloseHandle(ov
.hEvent
);
3191 CloseHandle(ov
.hEvent
);
3194 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3203 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3205 CharDriverState
*chr
;
3208 chr
= qemu_mallocz(sizeof(CharDriverState
));
3211 s
= qemu_mallocz(sizeof(WinCharState
));
3217 chr
->chr_write
= win_chr_write
;
3218 chr
->chr_close
= win_chr_close
;
3220 if (win_chr_pipe_init(chr
, filename
) < 0) {
3225 qemu_chr_reset(chr
);
3229 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3231 CharDriverState
*chr
;
3234 chr
= qemu_mallocz(sizeof(CharDriverState
));
3237 s
= qemu_mallocz(sizeof(WinCharState
));
3244 chr
->chr_write
= win_chr_write
;
3245 qemu_chr_reset(chr
);
3249 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3251 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3254 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3258 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3259 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3260 if (fd_out
== INVALID_HANDLE_VALUE
)
3263 return qemu_chr_open_win_file(fd_out
);
3265 #endif /* !_WIN32 */
3267 /***********************************************************/
3268 /* UDP Net console */
3272 struct sockaddr_in daddr
;
3279 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3281 NetCharDriver
*s
= chr
->opaque
;
3283 return sendto(s
->fd
, buf
, len
, 0,
3284 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3287 static int udp_chr_read_poll(void *opaque
)
3289 CharDriverState
*chr
= opaque
;
3290 NetCharDriver
*s
= chr
->opaque
;
3292 s
->max_size
= qemu_chr_can_read(chr
);
3294 /* If there were any stray characters in the queue process them
3297 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3298 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3300 s
->max_size
= qemu_chr_can_read(chr
);
3305 static void udp_chr_read(void *opaque
)
3307 CharDriverState
*chr
= opaque
;
3308 NetCharDriver
*s
= chr
->opaque
;
3310 if (s
->max_size
== 0)
3312 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3313 s
->bufptr
= s
->bufcnt
;
3318 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3319 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3321 s
->max_size
= qemu_chr_can_read(chr
);
3325 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3327 NetCharDriver
*s
= chr
->opaque
;
3330 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3331 udp_chr_read
, NULL
, chr
);
3335 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
3337 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3339 int parse_host_src_port(struct sockaddr_in
*haddr
,
3340 struct sockaddr_in
*saddr
,
3343 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3345 CharDriverState
*chr
= NULL
;
3346 NetCharDriver
*s
= NULL
;
3348 struct sockaddr_in saddr
;
3350 chr
= qemu_mallocz(sizeof(CharDriverState
));
3353 s
= qemu_mallocz(sizeof(NetCharDriver
));
3357 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3359 perror("socket(PF_INET, SOCK_DGRAM)");
3363 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3364 printf("Could not parse: %s\n", def
);
3368 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3378 chr
->chr_write
= udp_chr_write
;
3379 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3392 /***********************************************************/
3393 /* TCP Net console */
3404 static void tcp_chr_accept(void *opaque
);
3406 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3408 TCPCharDriver
*s
= chr
->opaque
;
3410 return send_all(s
->fd
, buf
, len
);
3412 /* XXX: indicate an error ? */
3417 static int tcp_chr_read_poll(void *opaque
)
3419 CharDriverState
*chr
= opaque
;
3420 TCPCharDriver
*s
= chr
->opaque
;
3423 s
->max_size
= qemu_chr_can_read(chr
);
3428 #define IAC_BREAK 243
3429 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3431 uint8_t *buf
, int *size
)
3433 /* Handle any telnet client's basic IAC options to satisfy char by
3434 * char mode with no echo. All IAC options will be removed from
3435 * the buf and the do_telnetopt variable will be used to track the
3436 * state of the width of the IAC information.
3438 * IAC commands come in sets of 3 bytes with the exception of the
3439 * "IAC BREAK" command and the double IAC.
3445 for (i
= 0; i
< *size
; i
++) {
3446 if (s
->do_telnetopt
> 1) {
3447 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3448 /* Double IAC means send an IAC */
3452 s
->do_telnetopt
= 1;
3454 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3455 /* Handle IAC break commands by sending a serial break */
3456 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3461 if (s
->do_telnetopt
>= 4) {
3462 s
->do_telnetopt
= 1;
3465 if ((unsigned char)buf
[i
] == IAC
) {
3466 s
->do_telnetopt
= 2;
3477 static void tcp_chr_read(void *opaque
)
3479 CharDriverState
*chr
= opaque
;
3480 TCPCharDriver
*s
= chr
->opaque
;
3484 if (!s
->connected
|| s
->max_size
<= 0)
3487 if (len
> s
->max_size
)
3489 size
= recv(s
->fd
, buf
, len
, 0);
3491 /* connection closed */
3493 if (s
->listen_fd
>= 0) {
3494 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3496 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3499 } else if (size
> 0) {
3500 if (s
->do_telnetopt
)
3501 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3503 qemu_chr_read(chr
, buf
, size
);
3507 static void tcp_chr_connect(void *opaque
)
3509 CharDriverState
*chr
= opaque
;
3510 TCPCharDriver
*s
= chr
->opaque
;
3513 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3514 tcp_chr_read
, NULL
, chr
);
3515 qemu_chr_reset(chr
);
3518 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3519 static void tcp_chr_telnet_init(int fd
)
3522 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3523 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3524 send(fd
, (char *)buf
, 3, 0);
3525 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3526 send(fd
, (char *)buf
, 3, 0);
3527 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3528 send(fd
, (char *)buf
, 3, 0);
3529 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3530 send(fd
, (char *)buf
, 3, 0);
3533 static void socket_set_nodelay(int fd
)
3536 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3539 static void tcp_chr_accept(void *opaque
)
3541 CharDriverState
*chr
= opaque
;
3542 TCPCharDriver
*s
= chr
->opaque
;
3543 struct sockaddr_in saddr
;
3545 struct sockaddr_un uaddr
;
3547 struct sockaddr
*addr
;
3554 len
= sizeof(uaddr
);
3555 addr
= (struct sockaddr
*)&uaddr
;
3559 len
= sizeof(saddr
);
3560 addr
= (struct sockaddr
*)&saddr
;
3562 fd
= accept(s
->listen_fd
, addr
, &len
);
3563 if (fd
< 0 && errno
!= EINTR
) {
3565 } else if (fd
>= 0) {
3566 if (s
->do_telnetopt
)
3567 tcp_chr_telnet_init(fd
);
3571 socket_set_nonblock(fd
);
3573 socket_set_nodelay(fd
);
3575 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3576 tcp_chr_connect(chr
);
3579 static void tcp_chr_close(CharDriverState
*chr
)
3581 TCPCharDriver
*s
= chr
->opaque
;
3584 if (s
->listen_fd
>= 0)
3585 closesocket(s
->listen_fd
);
3589 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3593 CharDriverState
*chr
= NULL
;
3594 TCPCharDriver
*s
= NULL
;
3595 int fd
= -1, ret
, err
, val
;
3597 int is_waitconnect
= 1;
3600 struct sockaddr_in saddr
;
3602 struct sockaddr_un uaddr
;
3604 struct sockaddr
*addr
;
3609 addr
= (struct sockaddr
*)&uaddr
;
3610 addrlen
= sizeof(uaddr
);
3611 if (parse_unix_path(&uaddr
, host_str
) < 0)
3616 addr
= (struct sockaddr
*)&saddr
;
3617 addrlen
= sizeof(saddr
);
3618 if (parse_host_port(&saddr
, host_str
) < 0)
3623 while((ptr
= strchr(ptr
,','))) {
3625 if (!strncmp(ptr
,"server",6)) {
3627 } else if (!strncmp(ptr
,"nowait",6)) {
3629 } else if (!strncmp(ptr
,"nodelay",6)) {
3632 printf("Unknown option: %s\n", ptr
);
3639 chr
= qemu_mallocz(sizeof(CharDriverState
));
3642 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3648 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3651 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3656 if (!is_waitconnect
)
3657 socket_set_nonblock(fd
);
3662 s
->is_unix
= is_unix
;
3663 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3666 chr
->chr_write
= tcp_chr_write
;
3667 chr
->chr_close
= tcp_chr_close
;
3670 /* allow fast reuse */
3674 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3680 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3683 ret
= bind(fd
, addr
, addrlen
);
3687 ret
= listen(fd
, 0);
3692 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3694 s
->do_telnetopt
= 1;
3697 ret
= connect(fd
, addr
, addrlen
);
3699 err
= socket_error();
3700 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3701 } else if (err
== EINPROGRESS
) {
3704 } else if (err
== WSAEALREADY
) {
3716 socket_set_nodelay(fd
);
3718 tcp_chr_connect(chr
);
3720 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3723 if (is_listen
&& is_waitconnect
) {
3724 printf("QEMU waiting for connection on: %s\n", host_str
);
3725 tcp_chr_accept(chr
);
3726 socket_set_nonblock(s
->listen_fd
);
3738 CharDriverState
*qemu_chr_open(const char *filename
)
3742 if (!strcmp(filename
, "vc")) {
3743 return text_console_init(&display_state
, 0);
3744 } else if (strstart(filename
, "vc:", &p
)) {
3745 return text_console_init(&display_state
, p
);
3746 } else if (!strcmp(filename
, "null")) {
3747 return qemu_chr_open_null();
3749 if (strstart(filename
, "tcp:", &p
)) {
3750 return qemu_chr_open_tcp(p
, 0, 0);
3752 if (strstart(filename
, "telnet:", &p
)) {
3753 return qemu_chr_open_tcp(p
, 1, 0);
3755 if (strstart(filename
, "udp:", &p
)) {
3756 return qemu_chr_open_udp(p
);
3758 if (strstart(filename
, "mon:", &p
)) {
3759 CharDriverState
*drv
= qemu_chr_open(p
);
3761 drv
= qemu_chr_open_mux(drv
);
3762 monitor_init(drv
, !nographic
);
3765 printf("Unable to open driver: %s\n", p
);
3769 if (strstart(filename
, "unix:", &p
)) {
3770 return qemu_chr_open_tcp(p
, 0, 1);
3771 } else if (strstart(filename
, "file:", &p
)) {
3772 return qemu_chr_open_file_out(p
);
3773 } else if (strstart(filename
, "pipe:", &p
)) {
3774 return qemu_chr_open_pipe(p
);
3775 } else if (!strcmp(filename
, "pty")) {
3776 return qemu_chr_open_pty();
3777 } else if (!strcmp(filename
, "stdio")) {
3778 return qemu_chr_open_stdio();
3780 #if defined(__linux__)
3781 if (strstart(filename
, "/dev/parport", NULL
)) {
3782 return qemu_chr_open_pp(filename
);
3785 #if defined(__linux__) || defined(__sun__)
3786 if (strstart(filename
, "/dev/", NULL
)) {
3787 return qemu_chr_open_tty(filename
);
3791 if (strstart(filename
, "COM", NULL
)) {
3792 return qemu_chr_open_win(filename
);
3794 if (strstart(filename
, "pipe:", &p
)) {
3795 return qemu_chr_open_win_pipe(p
);
3797 if (strstart(filename
, "con:", NULL
)) {
3798 return qemu_chr_open_win_con(filename
);
3800 if (strstart(filename
, "file:", &p
)) {
3801 return qemu_chr_open_win_file_out(p
);
3804 #ifdef CONFIG_BRLAPI
3805 if (!strcmp(filename
, "braille")) {
3806 return chr_baum_init();
3814 void qemu_chr_close(CharDriverState
*chr
)
3817 chr
->chr_close(chr
);
3821 /***********************************************************/
3822 /* network device redirectors */
3824 __attribute__ (( unused
))
3825 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3829 for(i
=0;i
<size
;i
+=16) {
3833 fprintf(f
, "%08x ", i
);
3836 fprintf(f
, " %02x", buf
[i
+j
]);
3841 for(j
=0;j
<len
;j
++) {
3843 if (c
< ' ' || c
> '~')
3845 fprintf(f
, "%c", c
);
3851 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3858 offset
= strtol(p
, &last_char
, 0);
3859 if (0 == errno
&& '\0' == *last_char
&&
3860 offset
>= 0 && offset
<= 0xFFFFFF) {
3861 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3862 macaddr
[4] = (offset
& 0xFF00) >> 8;
3863 macaddr
[5] = offset
& 0xFF;
3866 for(i
= 0; i
< 6; i
++) {
3867 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3872 if (*p
!= ':' && *p
!= '-')
3883 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3888 p1
= strchr(p
, sep
);
3894 if (len
> buf_size
- 1)
3896 memcpy(buf
, p
, len
);
3903 int parse_host_src_port(struct sockaddr_in
*haddr
,
3904 struct sockaddr_in
*saddr
,
3905 const char *input_str
)
3907 char *str
= strdup(input_str
);
3908 char *host_str
= str
;
3913 * Chop off any extra arguments at the end of the string which
3914 * would start with a comma, then fill in the src port information
3915 * if it was provided else use the "any address" and "any port".
3917 if ((ptr
= strchr(str
,',')))
3920 if ((src_str
= strchr(input_str
,'@'))) {
3925 if (parse_host_port(haddr
, host_str
) < 0)
3928 if (!src_str
|| *src_str
== '\0')
3931 if (parse_host_port(saddr
, src_str
) < 0)
3942 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3950 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3952 saddr
->sin_family
= AF_INET
;
3953 if (buf
[0] == '\0') {
3954 saddr
->sin_addr
.s_addr
= 0;
3956 if (isdigit(buf
[0])) {
3957 if (!inet_aton(buf
, &saddr
->sin_addr
))
3960 if ((he
= gethostbyname(buf
)) == NULL
)
3962 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3965 port
= strtol(p
, (char **)&r
, 0);
3968 saddr
->sin_port
= htons(port
);
3973 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
3978 len
= MIN(108, strlen(str
));
3979 p
= strchr(str
, ',');
3981 len
= MIN(len
, p
- str
);
3983 memset(uaddr
, 0, sizeof(*uaddr
));
3985 uaddr
->sun_family
= AF_UNIX
;
3986 memcpy(uaddr
->sun_path
, str
, len
);
3992 /* find or alloc a new VLAN */
3993 VLANState
*qemu_find_vlan(int id
)
3995 VLANState
**pvlan
, *vlan
;
3996 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4000 vlan
= qemu_mallocz(sizeof(VLANState
));
4005 pvlan
= &first_vlan
;
4006 while (*pvlan
!= NULL
)
4007 pvlan
= &(*pvlan
)->next
;
4012 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4013 IOReadHandler
*fd_read
,
4014 IOCanRWHandler
*fd_can_read
,
4017 VLANClientState
*vc
, **pvc
;
4018 vc
= qemu_mallocz(sizeof(VLANClientState
));
4021 vc
->fd_read
= fd_read
;
4022 vc
->fd_can_read
= fd_can_read
;
4023 vc
->opaque
= opaque
;
4027 pvc
= &vlan
->first_client
;
4028 while (*pvc
!= NULL
)
4029 pvc
= &(*pvc
)->next
;
4034 void qemu_del_vlan_client(VLANClientState
*vc
)
4036 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4038 while (*pvc
!= NULL
)
4044 pvc
= &(*pvc
)->next
;
4047 int qemu_can_send_packet(VLANClientState
*vc1
)
4049 VLANState
*vlan
= vc1
->vlan
;
4050 VLANClientState
*vc
;
4052 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4054 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4061 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4063 VLANState
*vlan
= vc1
->vlan
;
4064 VLANClientState
*vc
;
4067 printf("vlan %d send:\n", vlan
->id
);
4068 hex_dump(stdout
, buf
, size
);
4070 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4072 vc
->fd_read(vc
->opaque
, buf
, size
);
4077 #if defined(CONFIG_SLIRP)
4079 /* slirp network adapter */
4081 static int slirp_inited
;
4082 static VLANClientState
*slirp_vc
;
4084 int slirp_can_output(void)
4086 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4089 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4092 printf("slirp output:\n");
4093 hex_dump(stdout
, pkt
, pkt_len
);
4097 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4100 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4103 printf("slirp input:\n");
4104 hex_dump(stdout
, buf
, size
);
4106 slirp_input(buf
, size
);
4109 static int net_slirp_init(VLANState
*vlan
)
4111 if (!slirp_inited
) {
4115 slirp_vc
= qemu_new_vlan_client(vlan
,
4116 slirp_receive
, NULL
, NULL
);
4117 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4121 static void net_slirp_redir(const char *redir_str
)
4126 struct in_addr guest_addr
;
4127 int host_port
, guest_port
;
4129 if (!slirp_inited
) {
4135 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4137 if (!strcmp(buf
, "tcp")) {
4139 } else if (!strcmp(buf
, "udp")) {
4145 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4147 host_port
= strtol(buf
, &r
, 0);
4151 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4153 if (buf
[0] == '\0') {
4154 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4156 if (!inet_aton(buf
, &guest_addr
))
4159 guest_port
= strtol(p
, &r
, 0);
4163 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4164 fprintf(stderr
, "qemu: could not set up redirection\n");
4169 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4177 static void erase_dir(char *dir_name
)
4181 char filename
[1024];
4183 /* erase all the files in the directory */
4184 if ((d
= opendir(dir_name
)) != 0) {
4189 if (strcmp(de
->d_name
, ".") != 0 &&
4190 strcmp(de
->d_name
, "..") != 0) {
4191 snprintf(filename
, sizeof(filename
), "%s/%s",
4192 smb_dir
, de
->d_name
);
4193 if (unlink(filename
) != 0) /* is it a directory? */
4194 erase_dir(filename
);
4202 /* automatic user mode samba server configuration */
4203 static void smb_exit(void)
4208 /* automatic user mode samba server configuration */
4209 static void net_slirp_smb(const char *exported_dir
)
4211 char smb_conf
[1024];
4212 char smb_cmdline
[1024];
4215 if (!slirp_inited
) {
4220 /* XXX: better tmp dir construction */
4221 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4222 if (mkdir(smb_dir
, 0700) < 0) {
4223 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4226 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4228 f
= fopen(smb_conf
, "w");
4230 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4237 "socket address=127.0.0.1\n"
4238 "pid directory=%s\n"
4239 "lock directory=%s\n"
4240 "log file=%s/log.smbd\n"
4241 "smb passwd file=%s/smbpasswd\n"
4242 "security = share\n"
4257 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4258 SMBD_COMMAND
, smb_conf
);
4260 slirp_add_exec(0, smb_cmdline
, 4, 139);
4263 #endif /* !defined(_WIN32) */
4264 void do_info_slirp(void)
4269 #endif /* CONFIG_SLIRP */
4271 #if !defined(_WIN32)
4273 typedef struct TAPState
{
4274 VLANClientState
*vc
;
4276 char down_script
[1024];
4279 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4281 TAPState
*s
= opaque
;
4284 ret
= write(s
->fd
, buf
, size
);
4285 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4292 static void tap_send(void *opaque
)
4294 TAPState
*s
= opaque
;
4301 sbuf
.maxlen
= sizeof(buf
);
4303 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4305 size
= read(s
->fd
, buf
, sizeof(buf
));
4308 qemu_send_packet(s
->vc
, buf
, size
);
4314 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4318 s
= qemu_mallocz(sizeof(TAPState
));
4322 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4323 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
4324 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4328 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4329 static int tap_open(char *ifname
, int ifname_size
)
4335 TFR(fd
= open("/dev/tap", O_RDWR
));
4337 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4342 dev
= devname(s
.st_rdev
, S_IFCHR
);
4343 pstrcpy(ifname
, ifname_size
, dev
);
4345 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4348 #elif defined(__sun__)
4349 #define TUNNEWPPA (('T'<<16) | 0x0001)
4351 * Allocate TAP device, returns opened fd.
4352 * Stores dev name in the first arg(must be large enough).
4354 int tap_alloc(char *dev
)
4356 int tap_fd
, if_fd
, ppa
= -1;
4357 static int ip_fd
= 0;
4360 static int arp_fd
= 0;
4361 int ip_muxid
, arp_muxid
;
4362 struct strioctl strioc_if
, strioc_ppa
;
4363 int link_type
= I_PLINK
;;
4365 char actual_name
[32] = "";
4367 memset(&ifr
, 0x0, sizeof(ifr
));
4371 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4375 /* Check if IP device was opened */
4379 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4381 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4385 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4387 syslog(LOG_ERR
, "Can't open /dev/tap");
4391 /* Assign a new PPA and get its unit number. */
4392 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4393 strioc_ppa
.ic_timout
= 0;
4394 strioc_ppa
.ic_len
= sizeof(ppa
);
4395 strioc_ppa
.ic_dp
= (char *)&ppa
;
4396 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4397 syslog (LOG_ERR
, "Can't assign new interface");
4399 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4401 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4404 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4405 syslog(LOG_ERR
, "Can't push IP module");
4409 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4410 syslog(LOG_ERR
, "Can't get flags\n");
4412 snprintf (actual_name
, 32, "tap%d", ppa
);
4413 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4416 /* Assign ppa according to the unit number returned by tun device */
4418 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4419 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4420 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4421 syslog (LOG_ERR
, "Can't get flags\n");
4422 /* Push arp module to if_fd */
4423 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4424 syslog (LOG_ERR
, "Can't push ARP module (2)");
4426 /* Push arp module to ip_fd */
4427 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4428 syslog (LOG_ERR
, "I_POP failed\n");
4429 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4430 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4432 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4434 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4436 /* Set ifname to arp */
4437 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4438 strioc_if
.ic_timout
= 0;
4439 strioc_if
.ic_len
= sizeof(ifr
);
4440 strioc_if
.ic_dp
= (char *)&ifr
;
4441 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4442 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4445 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4446 syslog(LOG_ERR
, "Can't link TAP device to IP");
4450 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4451 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4455 memset(&ifr
, 0x0, sizeof(ifr
));
4456 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4457 ifr
.lifr_ip_muxid
= ip_muxid
;
4458 ifr
.lifr_arp_muxid
= arp_muxid
;
4460 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4462 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4463 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4464 syslog (LOG_ERR
, "Can't set multiplexor id");
4467 sprintf(dev
, "tap%d", ppa
);
4471 static int tap_open(char *ifname
, int ifname_size
)
4475 if( (fd
= tap_alloc(dev
)) < 0 ){
4476 fprintf(stderr
, "Cannot allocate TAP device\n");
4479 pstrcpy(ifname
, ifname_size
, dev
);
4480 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4484 static int tap_open(char *ifname
, int ifname_size
)
4489 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4491 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4494 memset(&ifr
, 0, sizeof(ifr
));
4495 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4496 if (ifname
[0] != '\0')
4497 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4499 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4500 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4502 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4506 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4507 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4512 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4518 /* try to launch network script */
4522 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4523 for (i
= 0; i
< open_max
; i
++)
4524 if (i
!= STDIN_FILENO
&&
4525 i
!= STDOUT_FILENO
&&
4526 i
!= STDERR_FILENO
&&
4531 *parg
++ = (char *)setup_script
;
4532 *parg
++ = (char *)ifname
;
4534 execv(setup_script
, args
);
4537 while (waitpid(pid
, &status
, 0) != pid
);
4538 if (!WIFEXITED(status
) ||
4539 WEXITSTATUS(status
) != 0) {
4540 fprintf(stderr
, "%s: could not launch network script\n",
4548 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4549 const char *setup_script
, const char *down_script
)
4555 if (ifname1
!= NULL
)
4556 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4559 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4563 if (!setup_script
|| !strcmp(setup_script
, "no"))
4565 if (setup_script
[0] != '\0') {
4566 if (launch_script(setup_script
, ifname
, fd
))
4569 s
= net_tap_fd_init(vlan
, fd
);
4572 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4573 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4574 if (down_script
&& strcmp(down_script
, "no"))
4575 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4579 #endif /* !_WIN32 */
4581 #if defined(CONFIG_VDE)
4582 typedef struct VDEState
{
4583 VLANClientState
*vc
;
4587 static void vde_to_qemu(void *opaque
)
4589 VDEState
*s
= opaque
;
4593 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4595 qemu_send_packet(s
->vc
, buf
, size
);
4599 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4601 VDEState
*s
= opaque
;
4604 ret
= vde_send(s
->vde
, buf
, size
, 0);
4605 if (ret
< 0 && errno
== EINTR
) {
4612 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4613 const char *group
, int mode
)
4616 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4617 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4619 struct vde_open_args args
= {
4621 .group
= init_group
,
4625 s
= qemu_mallocz(sizeof(VDEState
));
4628 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4633 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4634 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4635 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4636 sock
, vde_datafd(s
->vde
));
4641 /* network connection */
4642 typedef struct NetSocketState
{
4643 VLANClientState
*vc
;
4645 int state
; /* 0 = getting length, 1 = getting data */
4649 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4652 typedef struct NetSocketListenState
{
4655 } NetSocketListenState
;
4657 /* XXX: we consider we can send the whole packet without blocking */
4658 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4660 NetSocketState
*s
= opaque
;
4664 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4665 send_all(s
->fd
, buf
, size
);
4668 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4670 NetSocketState
*s
= opaque
;
4671 sendto(s
->fd
, buf
, size
, 0,
4672 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4675 static void net_socket_send(void *opaque
)
4677 NetSocketState
*s
= opaque
;
4682 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4684 err
= socket_error();
4685 if (err
!= EWOULDBLOCK
)
4687 } else if (size
== 0) {
4688 /* end of connection */
4690 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4696 /* reassemble a packet from the network */
4702 memcpy(s
->buf
+ s
->index
, buf
, l
);
4706 if (s
->index
== 4) {
4708 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4714 l
= s
->packet_len
- s
->index
;
4717 memcpy(s
->buf
+ s
->index
, buf
, l
);
4721 if (s
->index
>= s
->packet_len
) {
4722 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4731 static void net_socket_send_dgram(void *opaque
)
4733 NetSocketState
*s
= opaque
;
4736 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4740 /* end of connection */
4741 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4744 qemu_send_packet(s
->vc
, s
->buf
, size
);
4747 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4752 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4753 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4754 inet_ntoa(mcastaddr
->sin_addr
),
4755 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4759 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4761 perror("socket(PF_INET, SOCK_DGRAM)");
4766 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4767 (const char *)&val
, sizeof(val
));
4769 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4773 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4779 /* Add host to multicast group */
4780 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4781 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4783 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4784 (const char *)&imr
, sizeof(struct ip_mreq
));
4786 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4790 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4792 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4793 (const char *)&val
, sizeof(val
));
4795 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4799 socket_set_nonblock(fd
);
4807 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4810 struct sockaddr_in saddr
;
4812 socklen_t saddr_len
;
4815 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4816 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4817 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4821 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4823 if (saddr
.sin_addr
.s_addr
==0) {
4824 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4828 /* clone dgram socket */
4829 newfd
= net_socket_mcast_create(&saddr
);
4831 /* error already reported by net_socket_mcast_create() */
4835 /* clone newfd to fd, close newfd */
4840 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4841 fd
, strerror(errno
));
4846 s
= qemu_mallocz(sizeof(NetSocketState
));
4851 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4852 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4854 /* mcast: save bound address as dst */
4855 if (is_connected
) s
->dgram_dst
=saddr
;
4857 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4858 "socket: fd=%d (%s mcast=%s:%d)",
4859 fd
, is_connected
? "cloned" : "",
4860 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4864 static void net_socket_connect(void *opaque
)
4866 NetSocketState
*s
= opaque
;
4867 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4870 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4874 s
= qemu_mallocz(sizeof(NetSocketState
));
4878 s
->vc
= qemu_new_vlan_client(vlan
,
4879 net_socket_receive
, NULL
, s
);
4880 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4881 "socket: fd=%d", fd
);
4883 net_socket_connect(s
);
4885 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4890 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4893 int so_type
=-1, optlen
=sizeof(so_type
);
4895 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4896 (socklen_t
*)&optlen
)< 0) {
4897 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4902 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4904 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4906 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4907 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4908 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4913 static void net_socket_accept(void *opaque
)
4915 NetSocketListenState
*s
= opaque
;
4917 struct sockaddr_in saddr
;
4922 len
= sizeof(saddr
);
4923 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4924 if (fd
< 0 && errno
!= EINTR
) {
4926 } else if (fd
>= 0) {
4930 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4934 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4935 "socket: connection from %s:%d",
4936 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4940 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4942 NetSocketListenState
*s
;
4944 struct sockaddr_in saddr
;
4946 if (parse_host_port(&saddr
, host_str
) < 0)
4949 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4953 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4958 socket_set_nonblock(fd
);
4960 /* allow fast reuse */
4962 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
4964 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4969 ret
= listen(fd
, 0);
4976 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
4980 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
4983 int fd
, connected
, ret
, err
;
4984 struct sockaddr_in saddr
;
4986 if (parse_host_port(&saddr
, host_str
) < 0)
4989 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4994 socket_set_nonblock(fd
);
4998 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5000 err
= socket_error();
5001 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5002 } else if (err
== EINPROGRESS
) {
5005 } else if (err
== WSAEALREADY
) {
5018 s
= net_socket_fd_init(vlan
, fd
, connected
);
5021 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5022 "socket: connect to %s:%d",
5023 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5027 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5031 struct sockaddr_in saddr
;
5033 if (parse_host_port(&saddr
, host_str
) < 0)
5037 fd
= net_socket_mcast_create(&saddr
);
5041 s
= net_socket_fd_init(vlan
, fd
, 0);
5045 s
->dgram_dst
= saddr
;
5047 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5048 "socket: mcast=%s:%d",
5049 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5054 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5059 while (*p
!= '\0' && *p
!= '=') {
5060 if (q
&& (q
- buf
) < buf_size
- 1)
5070 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5075 while (*p
!= '\0') {
5077 if (*(p
+ 1) != ',')
5081 if (q
&& (q
- buf
) < buf_size
- 1)
5091 static int get_param_value(char *buf
, int buf_size
,
5092 const char *tag
, const char *str
)
5099 p
= get_opt_name(option
, sizeof(option
), p
);
5103 if (!strcmp(tag
, option
)) {
5104 (void)get_opt_value(buf
, buf_size
, p
);
5107 p
= get_opt_value(NULL
, 0, p
);
5116 static int check_params(char *buf
, int buf_size
,
5117 char **params
, const char *str
)
5124 p
= get_opt_name(buf
, buf_size
, p
);
5128 for(i
= 0; params
[i
] != NULL
; i
++)
5129 if (!strcmp(params
[i
], buf
))
5131 if (params
[i
] == NULL
)
5133 p
= get_opt_value(NULL
, 0, p
);
5142 static int net_client_init(const char *str
)
5153 while (*p
!= '\0' && *p
!= ',') {
5154 if ((q
- device
) < sizeof(device
) - 1)
5162 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5163 vlan_id
= strtol(buf
, NULL
, 0);
5165 vlan
= qemu_find_vlan(vlan_id
);
5167 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5170 if (!strcmp(device
, "nic")) {
5174 if (nb_nics
>= MAX_NICS
) {
5175 fprintf(stderr
, "Too Many NICs\n");
5178 nd
= &nd_table
[nb_nics
];
5179 macaddr
= nd
->macaddr
;
5185 macaddr
[5] = 0x56 + nb_nics
;
5187 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5188 if (parse_macaddr(macaddr
, buf
) < 0) {
5189 fprintf(stderr
, "invalid syntax for ethernet address\n");
5193 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5194 nd
->model
= strdup(buf
);
5198 vlan
->nb_guest_devs
++;
5201 if (!strcmp(device
, "none")) {
5202 /* does nothing. It is needed to signal that no network cards
5207 if (!strcmp(device
, "user")) {
5208 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5209 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5211 vlan
->nb_host_devs
++;
5212 ret
= net_slirp_init(vlan
);
5216 if (!strcmp(device
, "tap")) {
5218 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5219 fprintf(stderr
, "tap: no interface name\n");
5222 vlan
->nb_host_devs
++;
5223 ret
= tap_win32_init(vlan
, ifname
);
5226 if (!strcmp(device
, "tap")) {
5228 char setup_script
[1024], down_script
[1024];
5230 vlan
->nb_host_devs
++;
5231 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5232 fd
= strtol(buf
, NULL
, 0);
5233 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5235 if (net_tap_fd_init(vlan
, fd
))
5238 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5241 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5242 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5244 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5245 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5247 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5251 if (!strcmp(device
, "socket")) {
5252 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5254 fd
= strtol(buf
, NULL
, 0);
5256 if (net_socket_fd_init(vlan
, fd
, 1))
5258 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5259 ret
= net_socket_listen_init(vlan
, buf
);
5260 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5261 ret
= net_socket_connect_init(vlan
, buf
);
5262 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5263 ret
= net_socket_mcast_init(vlan
, buf
);
5265 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5268 vlan
->nb_host_devs
++;
5271 if (!strcmp(device
, "vde")) {
5272 char vde_sock
[1024], vde_group
[512];
5273 int vde_port
, vde_mode
;
5274 vlan
->nb_host_devs
++;
5275 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5278 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5279 vde_port
= strtol(buf
, NULL
, 10);
5283 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5284 vde_group
[0] = '\0';
5286 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5287 vde_mode
= strtol(buf
, NULL
, 8);
5291 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5295 fprintf(stderr
, "Unknown network device: %s\n", device
);
5299 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5305 void do_info_network(void)
5308 VLANClientState
*vc
;
5310 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5311 term_printf("VLAN %d devices:\n", vlan
->id
);
5312 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5313 term_printf(" %s\n", vc
->info_str
);
5317 #define HD_ALIAS "index=%d,media=disk"
5319 #define CDROM_ALIAS "index=1,media=cdrom"
5321 #define CDROM_ALIAS "index=2,media=cdrom"
5323 #define FD_ALIAS "index=%d,if=floppy"
5324 #define PFLASH_ALIAS "if=pflash"
5325 #define MTD_ALIAS "if=mtd"
5326 #define SD_ALIAS "index=0,if=sd"
5328 static int drive_add(const char *file
, const char *fmt
, ...)
5332 if (nb_drives_opt
>= MAX_DRIVES
) {
5333 fprintf(stderr
, "qemu: too many drives\n");
5337 drives_opt
[nb_drives_opt
].file
= file
;
5339 vsnprintf(drives_opt
[nb_drives_opt
].opt
,
5340 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5343 return nb_drives_opt
++;
5346 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5350 /* seek interface, bus and unit */
5352 for (index
= 0; index
< nb_drives
; index
++)
5353 if (drives_table
[index
].type
== type
&&
5354 drives_table
[index
].bus
== bus
&&
5355 drives_table
[index
].unit
== unit
)
5361 int drive_get_max_bus(BlockInterfaceType type
)
5367 for (index
= 0; index
< nb_drives
; index
++) {
5368 if(drives_table
[index
].type
== type
&&
5369 drives_table
[index
].bus
> max_bus
)
5370 max_bus
= drives_table
[index
].bus
;
5375 static void bdrv_format_print(void *opaque
, const char *name
)
5377 fprintf(stderr
, " %s", name
);
5380 static int drive_init(struct drive_opt
*arg
, int snapshot
,
5381 QEMUMachine
*machine
)
5386 const char *mediastr
= "";
5387 BlockInterfaceType type
;
5388 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5389 int bus_id
, unit_id
;
5390 int cyls
, heads
, secs
, translation
;
5391 BlockDriverState
*bdrv
;
5392 BlockDriver
*drv
= NULL
;
5397 char *str
= arg
->opt
;
5398 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
5399 "secs", "trans", "media", "snapshot", "file",
5400 "cache", "format", NULL
};
5402 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5403 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5409 cyls
= heads
= secs
= 0;
5412 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5416 if (!strcmp(machine
->name
, "realview") ||
5417 !strcmp(machine
->name
, "SS-5") ||
5418 !strcmp(machine
->name
, "SS-10") ||
5419 !strcmp(machine
->name
, "SS-600MP") ||
5420 !strcmp(machine
->name
, "versatilepb") ||
5421 !strcmp(machine
->name
, "versatileab")) {
5423 max_devs
= MAX_SCSI_DEVS
;
5424 strcpy(devname
, "scsi");
5427 max_devs
= MAX_IDE_DEVS
;
5428 strcpy(devname
, "ide");
5432 /* extract parameters */
5434 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5435 bus_id
= strtol(buf
, NULL
, 0);
5437 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5442 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5443 unit_id
= strtol(buf
, NULL
, 0);
5445 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5450 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5451 pstrcpy(devname
, sizeof(devname
), buf
);
5452 if (!strcmp(buf
, "ide")) {
5454 max_devs
= MAX_IDE_DEVS
;
5455 } else if (!strcmp(buf
, "scsi")) {
5457 max_devs
= MAX_SCSI_DEVS
;
5458 } else if (!strcmp(buf
, "floppy")) {
5461 } else if (!strcmp(buf
, "pflash")) {
5464 } else if (!strcmp(buf
, "mtd")) {
5467 } else if (!strcmp(buf
, "sd")) {
5471 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5476 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5477 index
= strtol(buf
, NULL
, 0);
5479 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5484 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5485 cyls
= strtol(buf
, NULL
, 0);
5488 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5489 heads
= strtol(buf
, NULL
, 0);
5492 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5493 secs
= strtol(buf
, NULL
, 0);
5496 if (cyls
|| heads
|| secs
) {
5497 if (cyls
< 1 || cyls
> 16383) {
5498 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5501 if (heads
< 1 || heads
> 16) {
5502 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5505 if (secs
< 1 || secs
> 63) {
5506 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5511 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5514 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5518 if (!strcmp(buf
, "none"))
5519 translation
= BIOS_ATA_TRANSLATION_NONE
;
5520 else if (!strcmp(buf
, "lba"))
5521 translation
= BIOS_ATA_TRANSLATION_LBA
;
5522 else if (!strcmp(buf
, "auto"))
5523 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5525 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5530 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5531 if (!strcmp(buf
, "disk")) {
5533 } else if (!strcmp(buf
, "cdrom")) {
5534 if (cyls
|| secs
|| heads
) {
5536 "qemu: '%s' invalid physical CHS format\n", str
);
5539 media
= MEDIA_CDROM
;
5541 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5546 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5547 if (!strcmp(buf
, "on"))
5549 else if (!strcmp(buf
, "off"))
5552 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5557 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5558 if (!strcmp(buf
, "off"))
5560 else if (!strcmp(buf
, "on"))
5563 fprintf(stderr
, "qemu: invalid cache option\n");
5568 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5569 if (strcmp(buf
, "?") == 0) {
5570 fprintf(stderr
, "qemu: Supported formats:");
5571 bdrv_iterate_format(bdrv_format_print
, NULL
);
5572 fprintf(stderr
, "\n");
5575 drv
= bdrv_find_format(buf
);
5577 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5582 if (arg
->file
== NULL
)
5583 get_param_value(file
, sizeof(file
), "file", str
);
5585 pstrcpy(file
, sizeof(file
), arg
->file
);
5587 /* compute bus and unit according index */
5590 if (bus_id
!= 0 || unit_id
!= -1) {
5592 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5600 unit_id
= index
% max_devs
;
5601 bus_id
= index
/ max_devs
;
5605 /* if user doesn't specify a unit_id,
5606 * try to find the first free
5609 if (unit_id
== -1) {
5611 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5613 if (max_devs
&& unit_id
>= max_devs
) {
5614 unit_id
-= max_devs
;
5622 if (max_devs
&& unit_id
>= max_devs
) {
5623 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5624 str
, unit_id
, max_devs
- 1);
5629 * ignore multiple definitions
5632 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5637 if (type
== IF_IDE
|| type
== IF_SCSI
)
5638 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5640 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5641 devname
, bus_id
, mediastr
, unit_id
);
5643 snprintf(buf
, sizeof(buf
), "%s%s%i",
5644 devname
, mediastr
, unit_id
);
5645 bdrv
= bdrv_new(buf
);
5646 drives_table
[nb_drives
].bdrv
= bdrv
;
5647 drives_table
[nb_drives
].type
= type
;
5648 drives_table
[nb_drives
].bus
= bus_id
;
5649 drives_table
[nb_drives
].unit
= unit_id
;
5658 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5659 bdrv_set_translation_hint(bdrv
, translation
);
5663 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5668 /* FIXME: This isn't really a floppy, but it's a reasonable
5671 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5681 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5683 bdrv_flags
|= BDRV_O_DIRECT
;
5684 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5685 fprintf(stderr
, "qemu: could not open disk image %s\n",
5692 /***********************************************************/
5695 static USBPort
*used_usb_ports
;
5696 static USBPort
*free_usb_ports
;
5698 /* ??? Maybe change this to register a hub to keep track of the topology. */
5699 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5700 usb_attachfn attach
)
5702 port
->opaque
= opaque
;
5703 port
->index
= index
;
5704 port
->attach
= attach
;
5705 port
->next
= free_usb_ports
;
5706 free_usb_ports
= port
;
5709 static int usb_device_add(const char *devname
)
5715 if (!free_usb_ports
)
5718 if (strstart(devname
, "host:", &p
)) {
5719 dev
= usb_host_device_open(p
);
5720 } else if (!strcmp(devname
, "mouse")) {
5721 dev
= usb_mouse_init();
5722 } else if (!strcmp(devname
, "tablet")) {
5723 dev
= usb_tablet_init();
5724 } else if (!strcmp(devname
, "keyboard")) {
5725 dev
= usb_keyboard_init();
5726 } else if (strstart(devname
, "disk:", &p
)) {
5727 dev
= usb_msd_init(p
);
5728 } else if (!strcmp(devname
, "wacom-tablet")) {
5729 dev
= usb_wacom_init();
5730 } else if (strstart(devname
, "serial:", &p
)) {
5731 dev
= usb_serial_init(p
);
5732 #ifdef CONFIG_BRLAPI
5733 } else if (!strcmp(devname
, "braille")) {
5734 dev
= usb_baum_init();
5736 } else if (strstart(devname
, "net:", &p
)) {
5737 int nicidx
= strtoul(p
, NULL
, 0);
5739 if (nicidx
>= nb_nics
|| strcmp(nd_table
[nicidx
].model
, "usb"))
5741 dev
= usb_net_init(&nd_table
[nicidx
]);
5748 /* Find a USB port to add the device to. */
5749 port
= free_usb_ports
;
5753 /* Create a new hub and chain it on. */
5754 free_usb_ports
= NULL
;
5755 port
->next
= used_usb_ports
;
5756 used_usb_ports
= port
;
5758 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5759 usb_attach(port
, hub
);
5760 port
= free_usb_ports
;
5763 free_usb_ports
= port
->next
;
5764 port
->next
= used_usb_ports
;
5765 used_usb_ports
= port
;
5766 usb_attach(port
, dev
);
5770 static int usb_device_del(const char *devname
)
5778 if (!used_usb_ports
)
5781 p
= strchr(devname
, '.');
5784 bus_num
= strtoul(devname
, NULL
, 0);
5785 addr
= strtoul(p
+ 1, NULL
, 0);
5789 lastp
= &used_usb_ports
;
5790 port
= used_usb_ports
;
5791 while (port
&& port
->dev
->addr
!= addr
) {
5792 lastp
= &port
->next
;
5800 *lastp
= port
->next
;
5801 usb_attach(port
, NULL
);
5802 dev
->handle_destroy(dev
);
5803 port
->next
= free_usb_ports
;
5804 free_usb_ports
= port
;
5808 void do_usb_add(const char *devname
)
5811 ret
= usb_device_add(devname
);
5813 term_printf("Could not add USB device '%s'\n", devname
);
5816 void do_usb_del(const char *devname
)
5819 ret
= usb_device_del(devname
);
5821 term_printf("Could not remove USB device '%s'\n", devname
);
5828 const char *speed_str
;
5831 term_printf("USB support not enabled\n");
5835 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5839 switch(dev
->speed
) {
5843 case USB_SPEED_FULL
:
5846 case USB_SPEED_HIGH
:
5853 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5854 0, dev
->addr
, speed_str
, dev
->devname
);
5858 /***********************************************************/
5859 /* PCMCIA/Cardbus */
5861 static struct pcmcia_socket_entry_s
{
5862 struct pcmcia_socket_s
*socket
;
5863 struct pcmcia_socket_entry_s
*next
;
5864 } *pcmcia_sockets
= 0;
5866 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5868 struct pcmcia_socket_entry_s
*entry
;
5870 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5871 entry
->socket
= socket
;
5872 entry
->next
= pcmcia_sockets
;
5873 pcmcia_sockets
= entry
;
5876 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5878 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5880 ptr
= &pcmcia_sockets
;
5881 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5882 if (entry
->socket
== socket
) {
5888 void pcmcia_info(void)
5890 struct pcmcia_socket_entry_s
*iter
;
5891 if (!pcmcia_sockets
)
5892 term_printf("No PCMCIA sockets\n");
5894 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5895 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5896 iter
->socket
->attached
? iter
->socket
->card_string
:
5900 /***********************************************************/
5903 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5907 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5911 static void dumb_refresh(DisplayState
*ds
)
5913 #if defined(CONFIG_SDL)
5918 static void dumb_display_init(DisplayState
*ds
)
5923 ds
->dpy_update
= dumb_update
;
5924 ds
->dpy_resize
= dumb_resize
;
5925 ds
->dpy_refresh
= dumb_refresh
;
5928 /***********************************************************/
5931 #define MAX_IO_HANDLERS 64
5933 typedef struct IOHandlerRecord
{
5935 IOCanRWHandler
*fd_read_poll
;
5937 IOHandler
*fd_write
;
5940 /* temporary data */
5942 struct IOHandlerRecord
*next
;
5945 static IOHandlerRecord
*first_io_handler
;
5947 /* XXX: fd_read_poll should be suppressed, but an API change is
5948 necessary in the character devices to suppress fd_can_read(). */
5949 int qemu_set_fd_handler2(int fd
,
5950 IOCanRWHandler
*fd_read_poll
,
5952 IOHandler
*fd_write
,
5955 IOHandlerRecord
**pioh
, *ioh
;
5957 if (!fd_read
&& !fd_write
) {
5958 pioh
= &first_io_handler
;
5963 if (ioh
->fd
== fd
) {
5970 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
5974 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
5977 ioh
->next
= first_io_handler
;
5978 first_io_handler
= ioh
;
5981 ioh
->fd_read_poll
= fd_read_poll
;
5982 ioh
->fd_read
= fd_read
;
5983 ioh
->fd_write
= fd_write
;
5984 ioh
->opaque
= opaque
;
5990 int qemu_set_fd_handler(int fd
,
5992 IOHandler
*fd_write
,
5995 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
5998 /***********************************************************/
5999 /* Polling handling */
6001 typedef struct PollingEntry
{
6004 struct PollingEntry
*next
;
6007 static PollingEntry
*first_polling_entry
;
6009 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6011 PollingEntry
**ppe
, *pe
;
6012 pe
= qemu_mallocz(sizeof(PollingEntry
));
6016 pe
->opaque
= opaque
;
6017 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6022 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6024 PollingEntry
**ppe
, *pe
;
6025 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6027 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6036 /***********************************************************/
6037 /* Wait objects support */
6038 typedef struct WaitObjects
{
6040 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6041 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6042 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6045 static WaitObjects wait_objects
= {0};
6047 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6049 WaitObjects
*w
= &wait_objects
;
6051 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6053 w
->events
[w
->num
] = handle
;
6054 w
->func
[w
->num
] = func
;
6055 w
->opaque
[w
->num
] = opaque
;
6060 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6063 WaitObjects
*w
= &wait_objects
;
6066 for (i
= 0; i
< w
->num
; i
++) {
6067 if (w
->events
[i
] == handle
)
6070 w
->events
[i
] = w
->events
[i
+ 1];
6071 w
->func
[i
] = w
->func
[i
+ 1];
6072 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6080 /***********************************************************/
6081 /* savevm/loadvm support */
6083 #define IO_BUF_SIZE 32768
6087 BlockDriverState
*bs
;
6090 int64_t base_offset
;
6091 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6094 int buf_size
; /* 0 when writing */
6095 uint8_t buf
[IO_BUF_SIZE
];
6098 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
6102 f
= qemu_mallocz(sizeof(QEMUFile
));
6105 if (!strcmp(mode
, "wb")) {
6107 } else if (!strcmp(mode
, "rb")) {
6112 f
->outfile
= fopen(filename
, mode
);
6124 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6128 f
= qemu_mallocz(sizeof(QEMUFile
));
6133 f
->is_writable
= is_writable
;
6134 f
->base_offset
= offset
;
6138 void qemu_fflush(QEMUFile
*f
)
6140 if (!f
->is_writable
)
6142 if (f
->buf_index
> 0) {
6144 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6145 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
6147 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6148 f
->buf
, f
->buf_index
);
6150 f
->buf_offset
+= f
->buf_index
;
6155 static void qemu_fill_buffer(QEMUFile
*f
)
6162 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6163 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
6167 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6168 f
->buf
, IO_BUF_SIZE
);
6174 f
->buf_offset
+= len
;
6177 void qemu_fclose(QEMUFile
*f
)
6187 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6191 l
= IO_BUF_SIZE
- f
->buf_index
;
6194 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6198 if (f
->buf_index
>= IO_BUF_SIZE
)
6203 void qemu_put_byte(QEMUFile
*f
, int v
)
6205 f
->buf
[f
->buf_index
++] = v
;
6206 if (f
->buf_index
>= IO_BUF_SIZE
)
6210 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6216 l
= f
->buf_size
- f
->buf_index
;
6218 qemu_fill_buffer(f
);
6219 l
= f
->buf_size
- f
->buf_index
;
6225 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6230 return size1
- size
;
6233 int qemu_get_byte(QEMUFile
*f
)
6235 if (f
->buf_index
>= f
->buf_size
) {
6236 qemu_fill_buffer(f
);
6237 if (f
->buf_index
>= f
->buf_size
)
6240 return f
->buf
[f
->buf_index
++];
6243 int64_t qemu_ftell(QEMUFile
*f
)
6245 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6248 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6250 if (whence
== SEEK_SET
) {
6252 } else if (whence
== SEEK_CUR
) {
6253 pos
+= qemu_ftell(f
);
6255 /* SEEK_END not supported */
6258 if (f
->is_writable
) {
6260 f
->buf_offset
= pos
;
6262 f
->buf_offset
= pos
;
6269 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6271 qemu_put_byte(f
, v
>> 8);
6272 qemu_put_byte(f
, v
);
6275 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6277 qemu_put_byte(f
, v
>> 24);
6278 qemu_put_byte(f
, v
>> 16);
6279 qemu_put_byte(f
, v
>> 8);
6280 qemu_put_byte(f
, v
);
6283 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6285 qemu_put_be32(f
, v
>> 32);
6286 qemu_put_be32(f
, v
);
6289 unsigned int qemu_get_be16(QEMUFile
*f
)
6292 v
= qemu_get_byte(f
) << 8;
6293 v
|= qemu_get_byte(f
);
6297 unsigned int qemu_get_be32(QEMUFile
*f
)
6300 v
= qemu_get_byte(f
) << 24;
6301 v
|= qemu_get_byte(f
) << 16;
6302 v
|= qemu_get_byte(f
) << 8;
6303 v
|= qemu_get_byte(f
);
6307 uint64_t qemu_get_be64(QEMUFile
*f
)
6310 v
= (uint64_t)qemu_get_be32(f
) << 32;
6311 v
|= qemu_get_be32(f
);
6315 typedef struct SaveStateEntry
{
6319 SaveStateHandler
*save_state
;
6320 LoadStateHandler
*load_state
;
6322 struct SaveStateEntry
*next
;
6325 static SaveStateEntry
*first_se
;
6327 /* TODO: Individual devices generally have very little idea about the rest
6328 of the system, so instance_id should be removed/replaced.
6329 Meanwhile pass -1 as instance_id if you do not already have a clearly
6330 distinguishing id for all instances of your device class. */
6331 int register_savevm(const char *idstr
,
6334 SaveStateHandler
*save_state
,
6335 LoadStateHandler
*load_state
,
6338 SaveStateEntry
*se
, **pse
;
6340 se
= qemu_malloc(sizeof(SaveStateEntry
));
6343 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6344 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6345 se
->version_id
= version_id
;
6346 se
->save_state
= save_state
;
6347 se
->load_state
= load_state
;
6348 se
->opaque
= opaque
;
6351 /* add at the end of list */
6353 while (*pse
!= NULL
) {
6354 if (instance_id
== -1
6355 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6356 && se
->instance_id
<= (*pse
)->instance_id
)
6357 se
->instance_id
= (*pse
)->instance_id
+ 1;
6358 pse
= &(*pse
)->next
;
6364 #define QEMU_VM_FILE_MAGIC 0x5145564d
6365 #define QEMU_VM_FILE_VERSION 0x00000002
6367 static int qemu_savevm_state(QEMUFile
*f
)
6371 int64_t cur_pos
, len_pos
, total_len_pos
;
6373 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6374 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6375 total_len_pos
= qemu_ftell(f
);
6376 qemu_put_be64(f
, 0); /* total size */
6378 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6379 if (se
->save_state
== NULL
)
6380 /* this one has a loader only, for backwards compatibility */
6384 len
= strlen(se
->idstr
);
6385 qemu_put_byte(f
, len
);
6386 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6388 qemu_put_be32(f
, se
->instance_id
);
6389 qemu_put_be32(f
, se
->version_id
);
6391 /* record size: filled later */
6392 len_pos
= qemu_ftell(f
);
6393 qemu_put_be32(f
, 0);
6394 se
->save_state(f
, se
->opaque
);
6396 /* fill record size */
6397 cur_pos
= qemu_ftell(f
);
6398 len
= cur_pos
- len_pos
- 4;
6399 qemu_fseek(f
, len_pos
, SEEK_SET
);
6400 qemu_put_be32(f
, len
);
6401 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6403 cur_pos
= qemu_ftell(f
);
6404 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6405 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6406 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6412 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6416 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6417 if (!strcmp(se
->idstr
, idstr
) &&
6418 instance_id
== se
->instance_id
)
6424 static int qemu_loadvm_state(QEMUFile
*f
)
6427 int len
, ret
, instance_id
, record_len
, version_id
;
6428 int64_t total_len
, end_pos
, cur_pos
;
6432 v
= qemu_get_be32(f
);
6433 if (v
!= QEMU_VM_FILE_MAGIC
)
6435 v
= qemu_get_be32(f
);
6436 if (v
!= QEMU_VM_FILE_VERSION
) {
6441 total_len
= qemu_get_be64(f
);
6442 end_pos
= total_len
+ qemu_ftell(f
);
6444 if (qemu_ftell(f
) >= end_pos
)
6446 len
= qemu_get_byte(f
);
6447 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6449 instance_id
= qemu_get_be32(f
);
6450 version_id
= qemu_get_be32(f
);
6451 record_len
= qemu_get_be32(f
);
6453 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6454 idstr
, instance_id
, version_id
, record_len
);
6456 cur_pos
= qemu_ftell(f
);
6457 se
= find_se(idstr
, instance_id
);
6459 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6460 instance_id
, idstr
);
6462 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6464 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6465 instance_id
, idstr
);
6468 /* always seek to exact end of record */
6469 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6476 /* device can contain snapshots */
6477 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6480 !bdrv_is_removable(bs
) &&
6481 !bdrv_is_read_only(bs
));
6484 /* device must be snapshots in order to have a reliable snapshot */
6485 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6488 !bdrv_is_removable(bs
) &&
6489 !bdrv_is_read_only(bs
));
6492 static BlockDriverState
*get_bs_snapshots(void)
6494 BlockDriverState
*bs
;
6498 return bs_snapshots
;
6499 for(i
= 0; i
<= nb_drives
; i
++) {
6500 bs
= drives_table
[i
].bdrv
;
6501 if (bdrv_can_snapshot(bs
))
6510 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6513 QEMUSnapshotInfo
*sn_tab
, *sn
;
6517 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6520 for(i
= 0; i
< nb_sns
; i
++) {
6522 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6532 void do_savevm(const char *name
)
6534 BlockDriverState
*bs
, *bs1
;
6535 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6536 int must_delete
, ret
, i
;
6537 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6539 int saved_vm_running
;
6546 bs
= get_bs_snapshots();
6548 term_printf("No block device can accept snapshots\n");
6552 /* ??? Should this occur after vm_stop? */
6555 saved_vm_running
= vm_running
;
6560 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6565 memset(sn
, 0, sizeof(*sn
));
6567 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6568 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6571 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6574 /* fill auxiliary fields */
6577 sn
->date_sec
= tb
.time
;
6578 sn
->date_nsec
= tb
.millitm
* 1000000;
6580 gettimeofday(&tv
, NULL
);
6581 sn
->date_sec
= tv
.tv_sec
;
6582 sn
->date_nsec
= tv
.tv_usec
* 1000;
6584 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6586 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6587 term_printf("Device %s does not support VM state snapshots\n",
6588 bdrv_get_device_name(bs
));
6592 /* save the VM state */
6593 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6595 term_printf("Could not open VM state file\n");
6598 ret
= qemu_savevm_state(f
);
6599 sn
->vm_state_size
= qemu_ftell(f
);
6602 term_printf("Error %d while writing VM\n", ret
);
6606 /* create the snapshots */
6608 for(i
= 0; i
< nb_drives
; i
++) {
6609 bs1
= drives_table
[i
].bdrv
;
6610 if (bdrv_has_snapshot(bs1
)) {
6612 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6614 term_printf("Error while deleting snapshot on '%s'\n",
6615 bdrv_get_device_name(bs1
));
6618 ret
= bdrv_snapshot_create(bs1
, sn
);
6620 term_printf("Error while creating snapshot on '%s'\n",
6621 bdrv_get_device_name(bs1
));
6627 if (saved_vm_running
)
6631 void do_loadvm(const char *name
)
6633 BlockDriverState
*bs
, *bs1
;
6634 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6637 int saved_vm_running
;
6639 bs
= get_bs_snapshots();
6641 term_printf("No block device supports snapshots\n");
6645 /* Flush all IO requests so they don't interfere with the new state. */
6648 saved_vm_running
= vm_running
;
6651 for(i
= 0; i
<= nb_drives
; i
++) {
6652 bs1
= drives_table
[i
].bdrv
;
6653 if (bdrv_has_snapshot(bs1
)) {
6654 ret
= bdrv_snapshot_goto(bs1
, name
);
6657 term_printf("Warning: ");
6660 term_printf("Snapshots not supported on device '%s'\n",
6661 bdrv_get_device_name(bs1
));
6664 term_printf("Could not find snapshot '%s' on device '%s'\n",
6665 name
, bdrv_get_device_name(bs1
));
6668 term_printf("Error %d while activating snapshot on '%s'\n",
6669 ret
, bdrv_get_device_name(bs1
));
6672 /* fatal on snapshot block device */
6679 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6680 term_printf("Device %s does not support VM state snapshots\n",
6681 bdrv_get_device_name(bs
));
6685 /* restore the VM state */
6686 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6688 term_printf("Could not open VM state file\n");
6691 ret
= qemu_loadvm_state(f
);
6694 term_printf("Error %d while loading VM state\n", ret
);
6697 if (saved_vm_running
)
6701 void do_delvm(const char *name
)
6703 BlockDriverState
*bs
, *bs1
;
6706 bs
= get_bs_snapshots();
6708 term_printf("No block device supports snapshots\n");
6712 for(i
= 0; i
<= nb_drives
; i
++) {
6713 bs1
= drives_table
[i
].bdrv
;
6714 if (bdrv_has_snapshot(bs1
)) {
6715 ret
= bdrv_snapshot_delete(bs1
, name
);
6717 if (ret
== -ENOTSUP
)
6718 term_printf("Snapshots not supported on device '%s'\n",
6719 bdrv_get_device_name(bs1
));
6721 term_printf("Error %d while deleting snapshot on '%s'\n",
6722 ret
, bdrv_get_device_name(bs1
));
6728 void do_info_snapshots(void)
6730 BlockDriverState
*bs
, *bs1
;
6731 QEMUSnapshotInfo
*sn_tab
, *sn
;
6735 bs
= get_bs_snapshots();
6737 term_printf("No available block device supports snapshots\n");
6740 term_printf("Snapshot devices:");
6741 for(i
= 0; i
<= nb_drives
; i
++) {
6742 bs1
= drives_table
[i
].bdrv
;
6743 if (bdrv_has_snapshot(bs1
)) {
6745 term_printf(" %s", bdrv_get_device_name(bs1
));
6750 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6752 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6755 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6756 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6757 for(i
= 0; i
< nb_sns
; i
++) {
6759 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6764 /***********************************************************/
6765 /* ram save/restore */
6767 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6771 v
= qemu_get_byte(f
);
6774 if (qemu_get_buffer(f
, buf
, len
) != len
)
6778 v
= qemu_get_byte(f
);
6779 memset(buf
, v
, len
);
6787 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6792 if (qemu_get_be32(f
) != phys_ram_size
)
6794 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6795 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6802 #define BDRV_HASH_BLOCK_SIZE 1024
6803 #define IOBUF_SIZE 4096
6804 #define RAM_CBLOCK_MAGIC 0xfabe
6806 typedef struct RamCompressState
{
6809 uint8_t buf
[IOBUF_SIZE
];
6812 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6815 memset(s
, 0, sizeof(*s
));
6817 ret
= deflateInit2(&s
->zstream
, 1,
6819 9, Z_DEFAULT_STRATEGY
);
6822 s
->zstream
.avail_out
= IOBUF_SIZE
;
6823 s
->zstream
.next_out
= s
->buf
;
6827 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6829 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6830 qemu_put_be16(s
->f
, len
);
6831 qemu_put_buffer(s
->f
, buf
, len
);
6834 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6838 s
->zstream
.avail_in
= len
;
6839 s
->zstream
.next_in
= (uint8_t *)buf
;
6840 while (s
->zstream
.avail_in
> 0) {
6841 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6844 if (s
->zstream
.avail_out
== 0) {
6845 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6846 s
->zstream
.avail_out
= IOBUF_SIZE
;
6847 s
->zstream
.next_out
= s
->buf
;
6853 static void ram_compress_close(RamCompressState
*s
)
6857 /* compress last bytes */
6859 ret
= deflate(&s
->zstream
, Z_FINISH
);
6860 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6861 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6863 ram_put_cblock(s
, s
->buf
, len
);
6865 s
->zstream
.avail_out
= IOBUF_SIZE
;
6866 s
->zstream
.next_out
= s
->buf
;
6867 if (ret
== Z_STREAM_END
)
6874 deflateEnd(&s
->zstream
);
6877 typedef struct RamDecompressState
{
6880 uint8_t buf
[IOBUF_SIZE
];
6881 } RamDecompressState
;
6883 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6886 memset(s
, 0, sizeof(*s
));
6888 ret
= inflateInit(&s
->zstream
);
6894 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6898 s
->zstream
.avail_out
= len
;
6899 s
->zstream
.next_out
= buf
;
6900 while (s
->zstream
.avail_out
> 0) {
6901 if (s
->zstream
.avail_in
== 0) {
6902 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6904 clen
= qemu_get_be16(s
->f
);
6905 if (clen
> IOBUF_SIZE
)
6907 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6908 s
->zstream
.avail_in
= clen
;
6909 s
->zstream
.next_in
= s
->buf
;
6911 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6912 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6919 static void ram_decompress_close(RamDecompressState
*s
)
6921 inflateEnd(&s
->zstream
);
6924 static void ram_save(QEMUFile
*f
, void *opaque
)
6927 RamCompressState s1
, *s
= &s1
;
6930 qemu_put_be32(f
, phys_ram_size
);
6931 if (ram_compress_open(s
, f
) < 0)
6933 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6935 if (tight_savevm_enabled
) {
6939 /* find if the memory block is available on a virtual
6942 for(j
= 0; j
< nb_drives
; j
++) {
6943 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
6945 BDRV_HASH_BLOCK_SIZE
);
6946 if (sector_num
>= 0)
6950 goto normal_compress
;
6953 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
6954 ram_compress_buf(s
, buf
, 10);
6960 ram_compress_buf(s
, buf
, 1);
6961 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
6964 ram_compress_close(s
);
6967 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
6969 RamDecompressState s1
, *s
= &s1
;
6973 if (version_id
== 1)
6974 return ram_load_v1(f
, opaque
);
6975 if (version_id
!= 2)
6977 if (qemu_get_be32(f
) != phys_ram_size
)
6979 if (ram_decompress_open(s
, f
) < 0)
6981 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6982 if (ram_decompress_buf(s
, buf
, 1) < 0) {
6983 fprintf(stderr
, "Error while reading ram block header\n");
6987 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
6988 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
6997 ram_decompress_buf(s
, buf
+ 1, 9);
6999 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7000 if (bs_index
>= nb_drives
) {
7001 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7004 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7006 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7007 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7008 bs_index
, sector_num
);
7015 printf("Error block header\n");
7019 ram_decompress_close(s
);
7023 /***********************************************************/
7024 /* bottom halves (can be seen as timers which expire ASAP) */
7033 static QEMUBH
*first_bh
= NULL
;
7035 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7038 bh
= qemu_mallocz(sizeof(QEMUBH
));
7042 bh
->opaque
= opaque
;
7046 int qemu_bh_poll(void)
7065 void qemu_bh_schedule(QEMUBH
*bh
)
7067 CPUState
*env
= cpu_single_env
;
7071 bh
->next
= first_bh
;
7074 /* stop the currently executing CPU to execute the BH ASAP */
7076 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7080 void qemu_bh_cancel(QEMUBH
*bh
)
7083 if (bh
->scheduled
) {
7086 pbh
= &(*pbh
)->next
;
7092 void qemu_bh_delete(QEMUBH
*bh
)
7098 /***********************************************************/
7099 /* machine registration */
7101 QEMUMachine
*first_machine
= NULL
;
7103 int qemu_register_machine(QEMUMachine
*m
)
7106 pm
= &first_machine
;
7114 static QEMUMachine
*find_machine(const char *name
)
7118 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7119 if (!strcmp(m
->name
, name
))
7125 /***********************************************************/
7126 /* main execution loop */
7128 static void gui_update(void *opaque
)
7130 DisplayState
*ds
= opaque
;
7131 ds
->dpy_refresh(ds
);
7132 qemu_mod_timer(ds
->gui_timer
,
7133 (ds
->gui_timer_interval
?
7134 ds
->gui_timer_interval
:
7135 GUI_REFRESH_INTERVAL
)
7136 + qemu_get_clock(rt_clock
));
7139 struct vm_change_state_entry
{
7140 VMChangeStateHandler
*cb
;
7142 LIST_ENTRY (vm_change_state_entry
) entries
;
7145 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7147 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7150 VMChangeStateEntry
*e
;
7152 e
= qemu_mallocz(sizeof (*e
));
7158 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7162 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7164 LIST_REMOVE (e
, entries
);
7168 static void vm_state_notify(int running
)
7170 VMChangeStateEntry
*e
;
7172 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7173 e
->cb(e
->opaque
, running
);
7177 /* XXX: support several handlers */
7178 static VMStopHandler
*vm_stop_cb
;
7179 static void *vm_stop_opaque
;
7181 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7184 vm_stop_opaque
= opaque
;
7188 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7199 qemu_rearm_alarm_timer(alarm_timer
);
7203 void vm_stop(int reason
)
7206 cpu_disable_ticks();
7210 vm_stop_cb(vm_stop_opaque
, reason
);
7217 /* reset/shutdown handler */
7219 typedef struct QEMUResetEntry
{
7220 QEMUResetHandler
*func
;
7222 struct QEMUResetEntry
*next
;
7225 static QEMUResetEntry
*first_reset_entry
;
7226 static int reset_requested
;
7227 static int shutdown_requested
;
7228 static int powerdown_requested
;
7230 int qemu_shutdown_requested(void)
7232 int r
= shutdown_requested
;
7233 shutdown_requested
= 0;
7237 int qemu_reset_requested(void)
7239 int r
= reset_requested
;
7240 reset_requested
= 0;
7244 int qemu_powerdown_requested(void)
7246 int r
= powerdown_requested
;
7247 powerdown_requested
= 0;
7251 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7253 QEMUResetEntry
**pre
, *re
;
7255 pre
= &first_reset_entry
;
7256 while (*pre
!= NULL
)
7257 pre
= &(*pre
)->next
;
7258 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7260 re
->opaque
= opaque
;
7265 void qemu_system_reset(void)
7269 /* reset all devices */
7270 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7271 re
->func(re
->opaque
);
7275 void qemu_system_reset_request(void)
7278 shutdown_requested
= 1;
7280 reset_requested
= 1;
7283 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7286 void qemu_system_shutdown_request(void)
7288 shutdown_requested
= 1;
7290 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7293 void qemu_system_powerdown_request(void)
7295 powerdown_requested
= 1;
7297 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7300 void main_loop_wait(int timeout
)
7302 IOHandlerRecord
*ioh
;
7303 fd_set rfds
, wfds
, xfds
;
7312 /* XXX: need to suppress polling by better using win32 events */
7314 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7315 ret
|= pe
->func(pe
->opaque
);
7320 WaitObjects
*w
= &wait_objects
;
7322 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7323 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7324 if (w
->func
[ret
- WAIT_OBJECT_0
])
7325 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7327 /* Check for additional signaled events */
7328 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7330 /* Check if event is signaled */
7331 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7332 if(ret2
== WAIT_OBJECT_0
) {
7334 w
->func
[i
](w
->opaque
[i
]);
7335 } else if (ret2
== WAIT_TIMEOUT
) {
7337 err
= GetLastError();
7338 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7341 } else if (ret
== WAIT_TIMEOUT
) {
7343 err
= GetLastError();
7344 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7348 /* poll any events */
7349 /* XXX: separate device handlers from system ones */
7354 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7358 (!ioh
->fd_read_poll
||
7359 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7360 FD_SET(ioh
->fd
, &rfds
);
7364 if (ioh
->fd_write
) {
7365 FD_SET(ioh
->fd
, &wfds
);
7375 tv
.tv_usec
= timeout
* 1000;
7377 #if defined(CONFIG_SLIRP)
7379 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7382 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7384 IOHandlerRecord
**pioh
;
7386 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7387 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7388 ioh
->fd_read(ioh
->opaque
);
7390 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7391 ioh
->fd_write(ioh
->opaque
);
7395 /* remove deleted IO handlers */
7396 pioh
= &first_io_handler
;
7406 #if defined(CONFIG_SLIRP)
7413 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7419 if (likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7420 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7421 qemu_get_clock(vm_clock
));
7422 /* run dma transfers, if any */
7426 /* real time timers */
7427 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7428 qemu_get_clock(rt_clock
));
7430 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7431 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7432 qemu_rearm_alarm_timer(alarm_timer
);
7435 /* Check bottom-halves last in case any of the earlier events triggered
7441 static int main_loop(void)
7444 #ifdef CONFIG_PROFILER
7449 cur_cpu
= first_cpu
;
7450 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7457 #ifdef CONFIG_PROFILER
7458 ti
= profile_getclock();
7463 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7464 env
->icount_decr
.u16
.low
= 0;
7465 env
->icount_extra
= 0;
7466 count
= qemu_next_deadline();
7467 count
= (count
+ (1 << icount_time_shift
) - 1)
7468 >> icount_time_shift
;
7469 qemu_icount
+= count
;
7470 decr
= (count
> 0xffff) ? 0xffff : count
;
7472 env
->icount_decr
.u16
.low
= decr
;
7473 env
->icount_extra
= count
;
7475 ret
= cpu_exec(env
);
7476 #ifdef CONFIG_PROFILER
7477 qemu_time
+= profile_getclock() - ti
;
7480 /* Fold pending instructions back into the
7481 instruction counter, and clear the interrupt flag. */
7482 qemu_icount
-= (env
->icount_decr
.u16
.low
7483 + env
->icount_extra
);
7484 env
->icount_decr
.u32
= 0;
7485 env
->icount_extra
= 0;
7487 next_cpu
= env
->next_cpu
?: first_cpu
;
7488 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7489 ret
= EXCP_INTERRUPT
;
7493 if (ret
== EXCP_HLT
) {
7494 /* Give the next CPU a chance to run. */
7498 if (ret
!= EXCP_HALTED
)
7500 /* all CPUs are halted ? */
7506 if (shutdown_requested
) {
7507 ret
= EXCP_INTERRUPT
;
7515 if (reset_requested
) {
7516 reset_requested
= 0;
7517 qemu_system_reset();
7518 ret
= EXCP_INTERRUPT
;
7520 if (powerdown_requested
) {
7521 powerdown_requested
= 0;
7522 qemu_system_powerdown();
7523 ret
= EXCP_INTERRUPT
;
7525 if (unlikely(ret
== EXCP_DEBUG
)) {
7526 vm_stop(EXCP_DEBUG
);
7528 /* If all cpus are halted then wait until the next IRQ */
7529 /* XXX: use timeout computed from timers */
7530 if (ret
== EXCP_HALTED
) {
7534 /* Advance virtual time to the next event. */
7535 if (use_icount
== 1) {
7536 /* When not using an adaptive execution frequency
7537 we tend to get badly out of sync with real time,
7538 so just delay for a reasonable amount of time. */
7541 delta
= cpu_get_icount() - cpu_get_clock();
7544 /* If virtual time is ahead of real time then just
7546 timeout
= (delta
/ 1000000) + 1;
7548 /* Wait for either IO to occur or the next
7550 add
= qemu_next_deadline();
7551 /* We advance the timer before checking for IO.
7552 Limit the amount we advance so that early IO
7553 activity won't get the guest too far ahead. */
7557 add
= (add
+ (1 << icount_time_shift
) - 1)
7558 >> icount_time_shift
;
7560 timeout
= delta
/ 1000000;
7573 #ifdef CONFIG_PROFILER
7574 ti
= profile_getclock();
7576 main_loop_wait(timeout
);
7577 #ifdef CONFIG_PROFILER
7578 dev_time
+= profile_getclock() - ti
;
7581 cpu_disable_ticks();
7585 static void help(int exitcode
)
7587 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7588 "usage: %s [options] [disk_image]\n"
7590 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7592 "Standard options:\n"
7593 "-M machine select emulated machine (-M ? for list)\n"
7594 "-cpu cpu select CPU (-cpu ? for list)\n"
7595 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7596 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7597 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7598 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7599 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7600 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7601 " [,cache=on|off][,format=f]\n"
7602 " use 'file' as a drive image\n"
7603 "-mtdblock file use 'file' as on-board Flash memory image\n"
7604 "-sd file use 'file' as SecureDigital card image\n"
7605 "-pflash file use 'file' as a parallel flash image\n"
7606 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7607 "-snapshot write to temporary files instead of disk image files\n"
7609 "-no-frame open SDL window without a frame and window decorations\n"
7610 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7611 "-no-quit disable SDL window close capability\n"
7614 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7616 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7617 "-smp n set the number of CPUs to 'n' [default=1]\n"
7618 "-nographic disable graphical output and redirect serial I/Os to console\n"
7619 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7621 "-k language use keyboard layout (for example \"fr\" for French)\n"
7624 "-audio-help print list of audio drivers and their options\n"
7625 "-soundhw c1,... enable audio support\n"
7626 " and only specified sound cards (comma separated list)\n"
7627 " use -soundhw ? to get the list of supported cards\n"
7628 " use -soundhw all to enable all of them\n"
7630 "-localtime set the real time clock to local time [default=utc]\n"
7631 "-full-screen start in full screen\n"
7633 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7635 "-usb enable the USB driver (will be the default soon)\n"
7636 "-usbdevice name add the host or guest USB device 'name'\n"
7637 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7638 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7640 "-name string set the name of the guest\n"
7642 "Network options:\n"
7643 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7644 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7646 "-net user[,vlan=n][,hostname=host]\n"
7647 " connect the user mode network stack to VLAN 'n' and send\n"
7648 " hostname 'host' to DHCP clients\n"
7651 "-net tap[,vlan=n],ifname=name\n"
7652 " connect the host TAP network interface to VLAN 'n'\n"
7654 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7655 " connect the host TAP network interface to VLAN 'n' and use the\n"
7656 " network scripts 'file' (default=%s)\n"
7657 " and 'dfile' (default=%s);\n"
7658 " use '[down]script=no' to disable script execution;\n"
7659 " use 'fd=h' to connect to an already opened TAP interface\n"
7661 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7662 " connect the vlan 'n' to another VLAN using a socket connection\n"
7663 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7664 " connect the vlan 'n' to multicast maddr and port\n"
7666 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7667 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7668 " on host and listening for incoming connections on 'socketpath'.\n"
7669 " Use group 'groupname' and mode 'octalmode' to change default\n"
7670 " ownership and permissions for communication port.\n"
7672 "-net none use it alone to have zero network devices; if no -net option\n"
7673 " is provided, the default is '-net nic -net user'\n"
7676 "-tftp dir allow tftp access to files in dir [-net user]\n"
7677 "-bootp file advertise file in BOOTP replies\n"
7679 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7681 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7682 " redirect TCP or UDP connections from host to guest [-net user]\n"
7685 "Linux boot specific:\n"
7686 "-kernel bzImage use 'bzImage' as kernel image\n"
7687 "-append cmdline use 'cmdline' as kernel command line\n"
7688 "-initrd file use 'file' as initial ram disk\n"
7690 "Debug/Expert options:\n"
7691 "-monitor dev redirect the monitor to char device 'dev'\n"
7692 "-serial dev redirect the serial port to char device 'dev'\n"
7693 "-parallel dev redirect the parallel port to char device 'dev'\n"
7694 "-pidfile file Write PID to 'file'\n"
7695 "-S freeze CPU at startup (use 'c' to start execution)\n"
7696 "-s wait gdb connection to port\n"
7697 "-p port set gdb connection port [default=%s]\n"
7698 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7699 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7700 " translation (t=none or lba) (usually qemu can guess them)\n"
7701 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7703 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7704 "-no-kqemu disable KQEMU kernel module usage\n"
7707 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7708 " (default is CL-GD5446 PCI VGA)\n"
7709 "-no-acpi disable ACPI\n"
7711 #ifdef CONFIG_CURSES
7712 "-curses use a curses/ncurses interface instead of SDL\n"
7714 "-no-reboot exit instead of rebooting\n"
7715 "-no-shutdown stop before shutdown\n"
7716 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7717 "-vnc display start a VNC server on display\n"
7719 "-daemonize daemonize QEMU after initializing\n"
7721 "-option-rom rom load a file, rom, into the option ROM space\n"
7723 "-prom-env variable=value set OpenBIOS nvram variables\n"
7725 "-clock force the use of the given methods for timer alarm.\n"
7726 " To see what timers are available use -clock ?\n"
7727 "-startdate select initial date of the clock\n"
7728 "-icount [N|auto]\n"
7729 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7731 "During emulation, the following keys are useful:\n"
7732 "ctrl-alt-f toggle full screen\n"
7733 "ctrl-alt-n switch to virtual console 'n'\n"
7734 "ctrl-alt toggle mouse and keyboard grab\n"
7736 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7741 DEFAULT_NETWORK_SCRIPT
,
7742 DEFAULT_NETWORK_DOWN_SCRIPT
,
7744 DEFAULT_GDBSTUB_PORT
,
7749 #define HAS_ARG 0x0001
7764 QEMU_OPTION_mtdblock
,
7768 QEMU_OPTION_snapshot
,
7770 QEMU_OPTION_no_fd_bootchk
,
7773 QEMU_OPTION_nographic
,
7774 QEMU_OPTION_portrait
,
7776 QEMU_OPTION_audio_help
,
7777 QEMU_OPTION_soundhw
,
7798 QEMU_OPTION_localtime
,
7799 QEMU_OPTION_cirrusvga
,
7802 QEMU_OPTION_std_vga
,
7804 QEMU_OPTION_monitor
,
7806 QEMU_OPTION_parallel
,
7808 QEMU_OPTION_full_screen
,
7809 QEMU_OPTION_no_frame
,
7810 QEMU_OPTION_alt_grab
,
7811 QEMU_OPTION_no_quit
,
7812 QEMU_OPTION_pidfile
,
7813 QEMU_OPTION_no_kqemu
,
7814 QEMU_OPTION_kernel_kqemu
,
7815 QEMU_OPTION_win2k_hack
,
7817 QEMU_OPTION_usbdevice
,
7820 QEMU_OPTION_no_acpi
,
7822 QEMU_OPTION_no_reboot
,
7823 QEMU_OPTION_no_shutdown
,
7824 QEMU_OPTION_show_cursor
,
7825 QEMU_OPTION_daemonize
,
7826 QEMU_OPTION_option_rom
,
7827 QEMU_OPTION_semihosting
,
7829 QEMU_OPTION_prom_env
,
7830 QEMU_OPTION_old_param
,
7832 QEMU_OPTION_startdate
,
7833 QEMU_OPTION_tb_size
,
7837 typedef struct QEMUOption
{
7843 const QEMUOption qemu_options
[] = {
7844 { "h", 0, QEMU_OPTION_h
},
7845 { "help", 0, QEMU_OPTION_h
},
7847 { "M", HAS_ARG
, QEMU_OPTION_M
},
7848 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7849 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7850 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7851 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7852 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7853 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7854 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7855 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7856 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7857 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7858 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7859 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7860 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7861 { "snapshot", 0, QEMU_OPTION_snapshot
},
7863 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7865 { "m", HAS_ARG
, QEMU_OPTION_m
},
7866 { "nographic", 0, QEMU_OPTION_nographic
},
7867 { "portrait", 0, QEMU_OPTION_portrait
},
7868 { "k", HAS_ARG
, QEMU_OPTION_k
},
7870 { "audio-help", 0, QEMU_OPTION_audio_help
},
7871 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7874 { "net", HAS_ARG
, QEMU_OPTION_net
},
7876 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7877 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7879 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7881 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7884 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7885 { "append", HAS_ARG
, QEMU_OPTION_append
},
7886 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7888 { "S", 0, QEMU_OPTION_S
},
7889 { "s", 0, QEMU_OPTION_s
},
7890 { "p", HAS_ARG
, QEMU_OPTION_p
},
7891 { "d", HAS_ARG
, QEMU_OPTION_d
},
7892 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7893 { "L", HAS_ARG
, QEMU_OPTION_L
},
7894 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7896 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7897 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7899 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7900 { "g", 1, QEMU_OPTION_g
},
7902 { "localtime", 0, QEMU_OPTION_localtime
},
7903 { "std-vga", 0, QEMU_OPTION_std_vga
},
7904 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7905 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7906 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7907 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7908 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7909 { "full-screen", 0, QEMU_OPTION_full_screen
},
7911 { "no-frame", 0, QEMU_OPTION_no_frame
},
7912 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7913 { "no-quit", 0, QEMU_OPTION_no_quit
},
7915 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7916 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7917 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7918 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7919 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7920 #ifdef CONFIG_CURSES
7921 { "curses", 0, QEMU_OPTION_curses
},
7924 /* temporary options */
7925 { "usb", 0, QEMU_OPTION_usb
},
7926 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
7927 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
7928 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
7929 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
7930 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
7931 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
7932 { "daemonize", 0, QEMU_OPTION_daemonize
},
7933 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
7934 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7935 { "semihosting", 0, QEMU_OPTION_semihosting
},
7937 { "name", HAS_ARG
, QEMU_OPTION_name
},
7938 #if defined(TARGET_SPARC)
7939 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
7941 #if defined(TARGET_ARM)
7942 { "old-param", 0, QEMU_OPTION_old_param
},
7944 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
7945 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
7946 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
7947 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
7951 /* password input */
7953 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
7958 if (!bdrv_is_encrypted(bs
))
7961 term_printf("%s is encrypted.\n", name
);
7962 for(i
= 0; i
< 3; i
++) {
7963 monitor_readline("Password: ", 1, password
, sizeof(password
));
7964 if (bdrv_set_key(bs
, password
) == 0)
7966 term_printf("invalid password\n");
7971 static BlockDriverState
*get_bdrv(int index
)
7973 if (index
> nb_drives
)
7975 return drives_table
[index
].bdrv
;
7978 static void read_passwords(void)
7980 BlockDriverState
*bs
;
7983 for(i
= 0; i
< 6; i
++) {
7986 qemu_key_check(bs
, bdrv_get_device_name(bs
));
7991 struct soundhw soundhw
[] = {
7992 #ifdef HAS_AUDIO_CHOICE
7993 #if defined(TARGET_I386) || defined(TARGET_MIPS)
7999 { .init_isa
= pcspk_audio_init
}
8004 "Creative Sound Blaster 16",
8007 { .init_isa
= SB16_init
}
8010 #ifdef CONFIG_CS4231A
8016 { .init_isa
= cs4231a_init
}
8024 "Yamaha YMF262 (OPL3)",
8026 "Yamaha YM3812 (OPL2)",
8030 { .init_isa
= Adlib_init
}
8037 "Gravis Ultrasound GF1",
8040 { .init_isa
= GUS_init
}
8047 "Intel 82801AA AC97 Audio",
8050 { .init_pci
= ac97_init
}
8056 "ENSONIQ AudioPCI ES1370",
8059 { .init_pci
= es1370_init
}
8063 { NULL
, NULL
, 0, 0, { NULL
} }
8066 static void select_soundhw (const char *optarg
)
8070 if (*optarg
== '?') {
8073 printf ("Valid sound card names (comma separated):\n");
8074 for (c
= soundhw
; c
->name
; ++c
) {
8075 printf ("%-11s %s\n", c
->name
, c
->descr
);
8077 printf ("\n-soundhw all will enable all of the above\n");
8078 exit (*optarg
!= '?');
8086 if (!strcmp (optarg
, "all")) {
8087 for (c
= soundhw
; c
->name
; ++c
) {
8095 e
= strchr (p
, ',');
8096 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8098 for (c
= soundhw
; c
->name
; ++c
) {
8099 if (!strncmp (c
->name
, p
, l
)) {
8108 "Unknown sound card name (too big to show)\n");
8111 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8116 p
+= l
+ (e
!= NULL
);
8120 goto show_valid_cards
;
8126 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8128 exit(STATUS_CONTROL_C_EXIT
);
8133 #define MAX_NET_CLIENTS 32
8135 int main(int argc
, char **argv
)
8137 #ifdef CONFIG_GDBSTUB
8139 const char *gdbstub_port
;
8141 uint32_t boot_devices_bitmap
= 0;
8143 int snapshot
, linux_boot
, net_boot
;
8144 const char *initrd_filename
;
8145 const char *kernel_filename
, *kernel_cmdline
;
8146 const char *boot_devices
= "";
8147 DisplayState
*ds
= &display_state
;
8148 int cyls
, heads
, secs
, translation
;
8149 const char *net_clients
[MAX_NET_CLIENTS
];
8153 const char *r
, *optarg
;
8154 CharDriverState
*monitor_hd
;
8155 const char *monitor_device
;
8156 const char *serial_devices
[MAX_SERIAL_PORTS
];
8157 int serial_device_index
;
8158 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8159 int parallel_device_index
;
8160 const char *loadvm
= NULL
;
8161 QEMUMachine
*machine
;
8162 const char *cpu_model
;
8163 const char *usb_devices
[MAX_USB_CMDLINE
];
8164 int usb_devices_index
;
8167 const char *pid_file
= NULL
;
8170 LIST_INIT (&vm_change_state_head
);
8173 struct sigaction act
;
8174 sigfillset(&act
.sa_mask
);
8176 act
.sa_handler
= SIG_IGN
;
8177 sigaction(SIGPIPE
, &act
, NULL
);
8180 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8181 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8182 QEMU to run on a single CPU */
8187 h
= GetCurrentProcess();
8188 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8189 for(i
= 0; i
< 32; i
++) {
8190 if (mask
& (1 << i
))
8195 SetProcessAffinityMask(h
, mask
);
8201 register_machines();
8202 machine
= first_machine
;
8204 initrd_filename
= NULL
;
8206 vga_ram_size
= VGA_RAM_SIZE
;
8207 #ifdef CONFIG_GDBSTUB
8209 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8214 kernel_filename
= NULL
;
8215 kernel_cmdline
= "";
8216 cyls
= heads
= secs
= 0;
8217 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8218 monitor_device
= "vc";
8220 serial_devices
[0] = "vc:80Cx24C";
8221 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8222 serial_devices
[i
] = NULL
;
8223 serial_device_index
= 0;
8225 parallel_devices
[0] = "vc:640x480";
8226 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8227 parallel_devices
[i
] = NULL
;
8228 parallel_device_index
= 0;
8230 usb_devices_index
= 0;
8247 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8249 const QEMUOption
*popt
;
8252 /* Treat --foo the same as -foo. */
8255 popt
= qemu_options
;
8258 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8262 if (!strcmp(popt
->name
, r
+ 1))
8266 if (popt
->flags
& HAS_ARG
) {
8267 if (optind
>= argc
) {
8268 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8272 optarg
= argv
[optind
++];
8277 switch(popt
->index
) {
8279 machine
= find_machine(optarg
);
8282 printf("Supported machines are:\n");
8283 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8284 printf("%-10s %s%s\n",
8286 m
== first_machine
? " (default)" : "");
8288 exit(*optarg
!= '?');
8291 case QEMU_OPTION_cpu
:
8292 /* hw initialization will check this */
8293 if (*optarg
== '?') {
8294 /* XXX: implement xxx_cpu_list for targets that still miss it */
8295 #if defined(cpu_list)
8296 cpu_list(stdout
, &fprintf
);
8303 case QEMU_OPTION_initrd
:
8304 initrd_filename
= optarg
;
8306 case QEMU_OPTION_hda
:
8308 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8310 hda_index
= drive_add(optarg
, HD_ALIAS
8311 ",cyls=%d,heads=%d,secs=%d%s",
8312 0, cyls
, heads
, secs
,
8313 translation
== BIOS_ATA_TRANSLATION_LBA
?
8315 translation
== BIOS_ATA_TRANSLATION_NONE
?
8316 ",trans=none" : "");
8318 case QEMU_OPTION_hdb
:
8319 case QEMU_OPTION_hdc
:
8320 case QEMU_OPTION_hdd
:
8321 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8323 case QEMU_OPTION_drive
:
8324 drive_add(NULL
, "%s", optarg
);
8326 case QEMU_OPTION_mtdblock
:
8327 drive_add(optarg
, MTD_ALIAS
);
8329 case QEMU_OPTION_sd
:
8330 drive_add(optarg
, SD_ALIAS
);
8332 case QEMU_OPTION_pflash
:
8333 drive_add(optarg
, PFLASH_ALIAS
);
8335 case QEMU_OPTION_snapshot
:
8338 case QEMU_OPTION_hdachs
:
8342 cyls
= strtol(p
, (char **)&p
, 0);
8343 if (cyls
< 1 || cyls
> 16383)
8348 heads
= strtol(p
, (char **)&p
, 0);
8349 if (heads
< 1 || heads
> 16)
8354 secs
= strtol(p
, (char **)&p
, 0);
8355 if (secs
< 1 || secs
> 63)
8359 if (!strcmp(p
, "none"))
8360 translation
= BIOS_ATA_TRANSLATION_NONE
;
8361 else if (!strcmp(p
, "lba"))
8362 translation
= BIOS_ATA_TRANSLATION_LBA
;
8363 else if (!strcmp(p
, "auto"))
8364 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8367 } else if (*p
!= '\0') {
8369 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8372 if (hda_index
!= -1)
8373 snprintf(drives_opt
[hda_index
].opt
,
8374 sizeof(drives_opt
[hda_index
].opt
),
8375 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8376 0, cyls
, heads
, secs
,
8377 translation
== BIOS_ATA_TRANSLATION_LBA
?
8379 translation
== BIOS_ATA_TRANSLATION_NONE
?
8380 ",trans=none" : "");
8383 case QEMU_OPTION_nographic
:
8384 serial_devices
[0] = "stdio";
8385 parallel_devices
[0] = "null";
8386 monitor_device
= "stdio";
8389 #ifdef CONFIG_CURSES
8390 case QEMU_OPTION_curses
:
8394 case QEMU_OPTION_portrait
:
8397 case QEMU_OPTION_kernel
:
8398 kernel_filename
= optarg
;
8400 case QEMU_OPTION_append
:
8401 kernel_cmdline
= optarg
;
8403 case QEMU_OPTION_cdrom
:
8404 drive_add(optarg
, CDROM_ALIAS
);
8406 case QEMU_OPTION_boot
:
8407 boot_devices
= optarg
;
8408 /* We just do some generic consistency checks */
8410 /* Could easily be extended to 64 devices if needed */
8413 boot_devices_bitmap
= 0;
8414 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8415 /* Allowed boot devices are:
8416 * a b : floppy disk drives
8417 * c ... f : IDE disk drives
8418 * g ... m : machine implementation dependant drives
8419 * n ... p : network devices
8420 * It's up to each machine implementation to check
8421 * if the given boot devices match the actual hardware
8422 * implementation and firmware features.
8424 if (*p
< 'a' || *p
> 'q') {
8425 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8428 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8430 "Boot device '%c' was given twice\n",*p
);
8433 boot_devices_bitmap
|= 1 << (*p
- 'a');
8437 case QEMU_OPTION_fda
:
8438 case QEMU_OPTION_fdb
:
8439 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8442 case QEMU_OPTION_no_fd_bootchk
:
8446 case QEMU_OPTION_net
:
8447 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8448 fprintf(stderr
, "qemu: too many network clients\n");
8451 net_clients
[nb_net_clients
] = optarg
;
8455 case QEMU_OPTION_tftp
:
8456 tftp_prefix
= optarg
;
8458 case QEMU_OPTION_bootp
:
8459 bootp_filename
= optarg
;
8462 case QEMU_OPTION_smb
:
8463 net_slirp_smb(optarg
);
8466 case QEMU_OPTION_redir
:
8467 net_slirp_redir(optarg
);
8471 case QEMU_OPTION_audio_help
:
8475 case QEMU_OPTION_soundhw
:
8476 select_soundhw (optarg
);
8482 case QEMU_OPTION_m
: {
8486 value
= strtoul(optarg
, &ptr
, 10);
8488 case 0: case 'M': case 'm':
8495 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8499 /* On 32-bit hosts, QEMU is limited by virtual address space */
8500 if (value
> (2047 << 20)
8502 && HOST_LONG_BITS
== 32
8505 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8508 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8509 fprintf(stderr
, "qemu: ram size too large\n");
8520 mask
= cpu_str_to_log_mask(optarg
);
8522 printf("Log items (comma separated):\n");
8523 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8524 printf("%-10s %s\n", item
->name
, item
->help
);
8531 #ifdef CONFIG_GDBSTUB
8536 gdbstub_port
= optarg
;
8542 case QEMU_OPTION_bios
:
8549 keyboard_layout
= optarg
;
8551 case QEMU_OPTION_localtime
:
8554 case QEMU_OPTION_cirrusvga
:
8555 cirrus_vga_enabled
= 1;
8558 case QEMU_OPTION_vmsvga
:
8559 cirrus_vga_enabled
= 0;
8562 case QEMU_OPTION_std_vga
:
8563 cirrus_vga_enabled
= 0;
8571 w
= strtol(p
, (char **)&p
, 10);
8574 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8580 h
= strtol(p
, (char **)&p
, 10);
8585 depth
= strtol(p
, (char **)&p
, 10);
8586 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8587 depth
!= 24 && depth
!= 32)
8589 } else if (*p
== '\0') {
8590 depth
= graphic_depth
;
8597 graphic_depth
= depth
;
8600 case QEMU_OPTION_echr
:
8603 term_escape_char
= strtol(optarg
, &r
, 0);
8605 printf("Bad argument to echr\n");
8608 case QEMU_OPTION_monitor
:
8609 monitor_device
= optarg
;
8611 case QEMU_OPTION_serial
:
8612 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8613 fprintf(stderr
, "qemu: too many serial ports\n");
8616 serial_devices
[serial_device_index
] = optarg
;
8617 serial_device_index
++;
8619 case QEMU_OPTION_parallel
:
8620 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8621 fprintf(stderr
, "qemu: too many parallel ports\n");
8624 parallel_devices
[parallel_device_index
] = optarg
;
8625 parallel_device_index
++;
8627 case QEMU_OPTION_loadvm
:
8630 case QEMU_OPTION_full_screen
:
8634 case QEMU_OPTION_no_frame
:
8637 case QEMU_OPTION_alt_grab
:
8640 case QEMU_OPTION_no_quit
:
8644 case QEMU_OPTION_pidfile
:
8648 case QEMU_OPTION_win2k_hack
:
8649 win2k_install_hack
= 1;
8653 case QEMU_OPTION_no_kqemu
:
8656 case QEMU_OPTION_kernel_kqemu
:
8660 case QEMU_OPTION_usb
:
8663 case QEMU_OPTION_usbdevice
:
8665 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8666 fprintf(stderr
, "Too many USB devices\n");
8669 usb_devices
[usb_devices_index
] = optarg
;
8670 usb_devices_index
++;
8672 case QEMU_OPTION_smp
:
8673 smp_cpus
= atoi(optarg
);
8674 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8675 fprintf(stderr
, "Invalid number of CPUs\n");
8679 case QEMU_OPTION_vnc
:
8680 vnc_display
= optarg
;
8682 case QEMU_OPTION_no_acpi
:
8685 case QEMU_OPTION_no_reboot
:
8688 case QEMU_OPTION_no_shutdown
:
8691 case QEMU_OPTION_show_cursor
:
8694 case QEMU_OPTION_daemonize
:
8697 case QEMU_OPTION_option_rom
:
8698 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8699 fprintf(stderr
, "Too many option ROMs\n");
8702 option_rom
[nb_option_roms
] = optarg
;
8705 case QEMU_OPTION_semihosting
:
8706 semihosting_enabled
= 1;
8708 case QEMU_OPTION_name
:
8712 case QEMU_OPTION_prom_env
:
8713 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8714 fprintf(stderr
, "Too many prom variables\n");
8717 prom_envs
[nb_prom_envs
] = optarg
;
8722 case QEMU_OPTION_old_param
:
8726 case QEMU_OPTION_clock
:
8727 configure_alarms(optarg
);
8729 case QEMU_OPTION_startdate
:
8732 time_t rtc_start_date
;
8733 if (!strcmp(optarg
, "now")) {
8734 rtc_date_offset
= -1;
8736 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8744 } else if (sscanf(optarg
, "%d-%d-%d",
8747 &tm
.tm_mday
) == 3) {
8756 rtc_start_date
= mktimegm(&tm
);
8757 if (rtc_start_date
== -1) {
8759 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8760 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8763 rtc_date_offset
= time(NULL
) - rtc_start_date
;
8767 case QEMU_OPTION_tb_size
:
8768 tb_size
= strtol(optarg
, NULL
, 0);
8772 case QEMU_OPTION_icount
:
8774 if (strcmp(optarg
, "auto") == 0) {
8775 icount_time_shift
= -1;
8777 icount_time_shift
= strtol(optarg
, NULL
, 0);
8788 if (pipe(fds
) == -1)
8799 len
= read(fds
[0], &status
, 1);
8800 if (len
== -1 && (errno
== EINTR
))
8805 else if (status
== 1) {
8806 fprintf(stderr
, "Could not acquire pidfile\n");
8823 signal(SIGTSTP
, SIG_IGN
);
8824 signal(SIGTTOU
, SIG_IGN
);
8825 signal(SIGTTIN
, SIG_IGN
);
8829 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
8832 write(fds
[1], &status
, 1);
8834 fprintf(stderr
, "Could not acquire pid file\n");
8842 linux_boot
= (kernel_filename
!= NULL
);
8843 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
8845 /* XXX: this should not be: some embedded targets just have flash */
8846 if (!linux_boot
&& net_boot
== 0 &&
8850 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
8851 fprintf(stderr
, "-append only allowed with -kernel option\n");
8855 if (!linux_boot
&& initrd_filename
!= NULL
) {
8856 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
8860 /* boot to floppy or the default cd if no hard disk defined yet */
8861 if (!boot_devices
[0]) {
8862 boot_devices
= "cad";
8864 setvbuf(stdout
, NULL
, _IOLBF
, 0);
8869 if (use_icount
&& icount_time_shift
< 0) {
8871 /* 125MIPS seems a reasonable initial guess at the guest speed.
8872 It will be corrected fairly quickly anyway. */
8873 icount_time_shift
= 3;
8874 init_icount_adjust();
8881 /* init network clients */
8882 if (nb_net_clients
== 0) {
8883 /* if no clients, we use a default config */
8884 net_clients
[0] = "nic";
8885 net_clients
[1] = "user";
8889 for(i
= 0;i
< nb_net_clients
; i
++) {
8890 if (net_client_init(net_clients
[i
]) < 0)
8893 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
8894 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
8896 if (vlan
->nb_guest_devs
== 0) {
8897 fprintf(stderr
, "Invalid vlan (%d) with no nics\n", vlan
->id
);
8900 if (vlan
->nb_host_devs
== 0)
8902 "Warning: vlan %d is not connected to host network\n",
8907 /* XXX: this should be moved in the PC machine instantiation code */
8908 if (net_boot
!= 0) {
8910 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
8911 const char *model
= nd_table
[i
].model
;
8913 if (net_boot
& (1 << i
)) {
8916 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
8917 if (get_image_size(buf
) > 0) {
8918 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8919 fprintf(stderr
, "Too many option ROMs\n");
8922 option_rom
[nb_option_roms
] = strdup(buf
);
8929 fprintf(stderr
, "No valid PXE rom found for network device\n");
8935 /* init the memory */
8936 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
8938 if (machine
->ram_require
& RAMSIZE_FIXED
) {
8940 if (ram_size
< phys_ram_size
) {
8941 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
8942 machine
->name
, (unsigned long long) phys_ram_size
);
8946 phys_ram_size
= ram_size
;
8948 ram_size
= phys_ram_size
;
8951 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
8953 phys_ram_size
+= ram_size
;
8956 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
8957 if (!phys_ram_base
) {
8958 fprintf(stderr
, "Could not allocate physical memory\n");
8962 /* init the dynamic translator */
8963 cpu_exec_init_all(tb_size
* 1024 * 1024);
8967 /* we always create the cdrom drive, even if no disk is there */
8969 if (nb_drives_opt
< MAX_DRIVES
)
8970 drive_add(NULL
, CDROM_ALIAS
);
8972 /* we always create at least one floppy */
8974 if (nb_drives_opt
< MAX_DRIVES
)
8975 drive_add(NULL
, FD_ALIAS
, 0);
8977 /* we always create one sd slot, even if no card is in it */
8979 if (nb_drives_opt
< MAX_DRIVES
)
8980 drive_add(NULL
, SD_ALIAS
);
8982 /* open the virtual block devices */
8984 for(i
= 0; i
< nb_drives_opt
; i
++)
8985 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
8988 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
8989 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
8992 memset(&display_state
, 0, sizeof(display_state
));
8995 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
8998 /* nearly nothing to do */
8999 dumb_display_init(ds
);
9000 } else if (vnc_display
!= NULL
) {
9001 vnc_display_init(ds
);
9002 if (vnc_display_open(ds
, vnc_display
) < 0)
9005 #if defined(CONFIG_CURSES)
9007 curses_display_init(ds
, full_screen
);
9011 #if defined(CONFIG_SDL)
9012 sdl_display_init(ds
, full_screen
, no_frame
);
9013 #elif defined(CONFIG_COCOA)
9014 cocoa_display_init(ds
, full_screen
);
9016 dumb_display_init(ds
);
9020 /* Maintain compatibility with multiple stdio monitors */
9021 if (!strcmp(monitor_device
,"stdio")) {
9022 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9023 const char *devname
= serial_devices
[i
];
9024 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9025 monitor_device
= NULL
;
9027 } else if (devname
&& !strcmp(devname
,"stdio")) {
9028 monitor_device
= NULL
;
9029 serial_devices
[i
] = "mon:stdio";
9034 if (monitor_device
) {
9035 monitor_hd
= qemu_chr_open(monitor_device
);
9037 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9040 monitor_init(monitor_hd
, !nographic
);
9043 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9044 const char *devname
= serial_devices
[i
];
9045 if (devname
&& strcmp(devname
, "none")) {
9046 serial_hds
[i
] = qemu_chr_open(devname
);
9047 if (!serial_hds
[i
]) {
9048 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9052 if (strstart(devname
, "vc", 0))
9053 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9057 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9058 const char *devname
= parallel_devices
[i
];
9059 if (devname
&& strcmp(devname
, "none")) {
9060 parallel_hds
[i
] = qemu_chr_open(devname
);
9061 if (!parallel_hds
[i
]) {
9062 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9066 if (strstart(devname
, "vc", 0))
9067 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9071 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9072 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9074 /* init USB devices */
9076 for(i
= 0; i
< usb_devices_index
; i
++) {
9077 if (usb_device_add(usb_devices
[i
]) < 0) {
9078 fprintf(stderr
, "Warning: could not add USB device %s\n",
9084 if (display_state
.dpy_refresh
) {
9085 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9086 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9089 #ifdef CONFIG_GDBSTUB
9091 /* XXX: use standard host:port notation and modify options
9093 if (gdbserver_start(gdbstub_port
) < 0) {
9094 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9105 /* XXX: simplify init */
9118 len
= write(fds
[1], &status
, 1);
9119 if (len
== -1 && (errno
== EINTR
))
9126 TFR(fd
= open("/dev/null", O_RDWR
));
9140 #if !defined(_WIN32)
9141 /* close network clients */
9142 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9143 VLANClientState
*vc
;
9145 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9146 if (vc
->fd_read
== tap_receive
) {
9148 TAPState
*s
= vc
->opaque
;
9150 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9152 launch_script(s
->down_script
, ifname
, s
->fd
);
9154 #if defined(CONFIG_VDE)
9155 if (vc
->fd_read
== vde_from_qemu
) {
9156 VDEState
*s
= vc
->opaque
;