4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
50 #include <sys/times.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
64 #if !defined(__APPLE__) && !defined(__OpenBSD__)
70 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
71 #include <freebsd/stdlib.h>
75 #include <linux/if_tun.h>
78 #include <linux/rtc.h>
80 /* For the benefit of older linux systems which don't supply it,
81 we use a local copy of hpet.h. */
82 /* #include <linux/hpet.h> */
85 #include <linux/ppdev.h>
86 #include <linux/parport.h>
89 #include <sys/ethernet.h>
90 #include <sys/sockio.h>
91 #include <netinet/arp.h>
92 #include <netinet/in.h>
93 #include <netinet/in_systm.h>
94 #include <netinet/ip.h>
95 #include <netinet/ip_icmp.h> // must come after ip.h
96 #include <netinet/udp.h>
97 #include <netinet/tcp.h>
104 #include <winsock2.h>
105 int inet_aton(const char *cp
, struct in_addr
*ia
);
108 #if defined(CONFIG_SLIRP)
109 #include "libslirp.h"
112 #if defined(CONFIG_VDE)
113 #include <libvdeplug.h>
118 #include <sys/timeb.h>
119 #include <mmsystem.h>
120 #define getopt_long_only getopt_long
121 #define memalign(align, size) malloc(size)
124 #include "qemu_socket.h"
130 #endif /* CONFIG_SDL */
134 #define main qemu_main
135 #endif /* CONFIG_COCOA */
139 #include "exec-all.h"
141 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
142 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
144 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
146 #define SMBD_COMMAND "/usr/sbin/smbd"
149 //#define DEBUG_UNUSED_IOPORT
150 //#define DEBUG_IOPORT
153 #define DEFAULT_RAM_SIZE 144
155 #define DEFAULT_RAM_SIZE 128
158 #define GUI_REFRESH_INTERVAL 30
160 /* Max number of USB devices that can be specified on the commandline. */
161 #define MAX_USB_CMDLINE 8
163 /* XXX: use a two level table to limit memory usage */
164 #define MAX_IOPORTS 65536
166 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
167 const char *bios_name
= NULL
;
168 void *ioport_opaque
[MAX_IOPORTS
];
169 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
170 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
171 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
172 to store the VM snapshots */
173 DriveInfo drives_table
[MAX_DRIVES
+1];
175 /* point to the block driver where the snapshots are managed */
176 BlockDriverState
*bs_snapshots
;
178 static DisplayState display_state
;
181 const char* keyboard_layout
= NULL
;
182 int64_t ticks_per_sec
;
184 int pit_min_timer_count
= 0;
186 NICInfo nd_table
[MAX_NICS
];
188 static int rtc_utc
= 1;
189 static int rtc_date_offset
= -1; /* -1 means no change */
190 int cirrus_vga_enabled
= 1;
191 int vmsvga_enabled
= 0;
193 int graphic_width
= 1024;
194 int graphic_height
= 768;
195 int graphic_depth
= 8;
197 int graphic_width
= 800;
198 int graphic_height
= 600;
199 int graphic_depth
= 15;
204 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
205 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
207 int win2k_install_hack
= 0;
210 static VLANState
*first_vlan
;
212 const char *vnc_display
;
213 #if defined(TARGET_SPARC)
215 #elif defined(TARGET_I386)
220 int acpi_enabled
= 1;
225 int graphic_rotate
= 0;
227 const char *option_rom
[MAX_OPTION_ROMS
];
229 int semihosting_enabled
= 0;
234 const char *qemu_name
;
237 unsigned int nb_prom_envs
= 0;
238 const char *prom_envs
[MAX_PROM_ENVS
];
244 } drives_opt
[MAX_DRIVES
];
246 static CPUState
*cur_cpu
;
247 static CPUState
*next_cpu
;
248 static int event_pending
= 1;
249 /* Conversion factor from emulated instructions to virtual clock ticks. */
250 static int icount_time_shift
;
251 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
252 #define MAX_ICOUNT_SHIFT 10
253 /* Compensate for varying guest execution speed. */
254 static int64_t qemu_icount_bias
;
255 QEMUTimer
*icount_rt_timer
;
256 QEMUTimer
*icount_vm_timer
;
258 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
260 /***********************************************************/
261 /* x86 ISA bus support */
263 target_phys_addr_t isa_mem_base
= 0;
266 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
267 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
269 static uint32_t ioport_read(int index
, uint32_t address
)
271 static IOPortReadFunc
*default_func
[3] = {
272 default_ioport_readb
,
273 default_ioport_readw
,
276 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
278 func
= default_func
[index
];
279 return func(ioport_opaque
[address
], address
);
282 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
284 static IOPortWriteFunc
*default_func
[3] = {
285 default_ioport_writeb
,
286 default_ioport_writew
,
287 default_ioport_writel
289 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
291 func
= default_func
[index
];
292 func(ioport_opaque
[address
], address
, data
);
295 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
297 #ifdef DEBUG_UNUSED_IOPORT
298 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
303 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
305 #ifdef DEBUG_UNUSED_IOPORT
306 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
310 /* default is to make two byte accesses */
311 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
314 data
= ioport_read(0, address
);
315 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
316 data
|= ioport_read(0, address
) << 8;
320 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
322 ioport_write(0, address
, data
& 0xff);
323 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
324 ioport_write(0, address
, (data
>> 8) & 0xff);
327 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
329 #ifdef DEBUG_UNUSED_IOPORT
330 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
335 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
337 #ifdef DEBUG_UNUSED_IOPORT
338 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
342 /* size is the word size in byte */
343 int register_ioport_read(int start
, int length
, int size
,
344 IOPortReadFunc
*func
, void *opaque
)
350 } else if (size
== 2) {
352 } else if (size
== 4) {
355 hw_error("register_ioport_read: invalid size");
358 for(i
= start
; i
< start
+ length
; i
+= size
) {
359 ioport_read_table
[bsize
][i
] = func
;
360 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
361 hw_error("register_ioport_read: invalid opaque");
362 ioport_opaque
[i
] = opaque
;
367 /* size is the word size in byte */
368 int register_ioport_write(int start
, int length
, int size
,
369 IOPortWriteFunc
*func
, void *opaque
)
375 } else if (size
== 2) {
377 } else if (size
== 4) {
380 hw_error("register_ioport_write: invalid size");
383 for(i
= start
; i
< start
+ length
; i
+= size
) {
384 ioport_write_table
[bsize
][i
] = func
;
385 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
386 hw_error("register_ioport_write: invalid opaque");
387 ioport_opaque
[i
] = opaque
;
392 void isa_unassign_ioport(int start
, int length
)
396 for(i
= start
; i
< start
+ length
; i
++) {
397 ioport_read_table
[0][i
] = default_ioport_readb
;
398 ioport_read_table
[1][i
] = default_ioport_readw
;
399 ioport_read_table
[2][i
] = default_ioport_readl
;
401 ioport_write_table
[0][i
] = default_ioport_writeb
;
402 ioport_write_table
[1][i
] = default_ioport_writew
;
403 ioport_write_table
[2][i
] = default_ioport_writel
;
407 /***********************************************************/
409 void cpu_outb(CPUState
*env
, int addr
, int val
)
412 if (loglevel
& CPU_LOG_IOPORT
)
413 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
415 ioport_write(0, addr
, val
);
418 env
->last_io_time
= cpu_get_time_fast();
422 void cpu_outw(CPUState
*env
, int addr
, int val
)
425 if (loglevel
& CPU_LOG_IOPORT
)
426 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
428 ioport_write(1, addr
, val
);
431 env
->last_io_time
= cpu_get_time_fast();
435 void cpu_outl(CPUState
*env
, int addr
, int val
)
438 if (loglevel
& CPU_LOG_IOPORT
)
439 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
441 ioport_write(2, addr
, val
);
444 env
->last_io_time
= cpu_get_time_fast();
448 int cpu_inb(CPUState
*env
, int addr
)
451 val
= ioport_read(0, addr
);
453 if (loglevel
& CPU_LOG_IOPORT
)
454 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
458 env
->last_io_time
= cpu_get_time_fast();
463 int cpu_inw(CPUState
*env
, int addr
)
466 val
= ioport_read(1, addr
);
468 if (loglevel
& CPU_LOG_IOPORT
)
469 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
473 env
->last_io_time
= cpu_get_time_fast();
478 int cpu_inl(CPUState
*env
, int addr
)
481 val
= ioport_read(2, addr
);
483 if (loglevel
& CPU_LOG_IOPORT
)
484 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
488 env
->last_io_time
= cpu_get_time_fast();
493 /***********************************************************/
494 void hw_error(const char *fmt
, ...)
500 fprintf(stderr
, "qemu: hardware error: ");
501 vfprintf(stderr
, fmt
, ap
);
502 fprintf(stderr
, "\n");
503 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
504 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
506 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
508 cpu_dump_state(env
, stderr
, fprintf
, 0);
515 /***********************************************************/
518 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
519 static void *qemu_put_kbd_event_opaque
;
520 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
521 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
523 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
525 qemu_put_kbd_event_opaque
= opaque
;
526 qemu_put_kbd_event
= func
;
529 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
530 void *opaque
, int absolute
,
533 QEMUPutMouseEntry
*s
, *cursor
;
535 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
539 s
->qemu_put_mouse_event
= func
;
540 s
->qemu_put_mouse_event_opaque
= opaque
;
541 s
->qemu_put_mouse_event_absolute
= absolute
;
542 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
545 if (!qemu_put_mouse_event_head
) {
546 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
550 cursor
= qemu_put_mouse_event_head
;
551 while (cursor
->next
!= NULL
)
552 cursor
= cursor
->next
;
555 qemu_put_mouse_event_current
= s
;
560 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
562 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
564 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
567 cursor
= qemu_put_mouse_event_head
;
568 while (cursor
!= NULL
&& cursor
!= entry
) {
570 cursor
= cursor
->next
;
573 if (cursor
== NULL
) // does not exist or list empty
575 else if (prev
== NULL
) { // entry is head
576 qemu_put_mouse_event_head
= cursor
->next
;
577 if (qemu_put_mouse_event_current
== entry
)
578 qemu_put_mouse_event_current
= cursor
->next
;
579 qemu_free(entry
->qemu_put_mouse_event_name
);
584 prev
->next
= entry
->next
;
586 if (qemu_put_mouse_event_current
== entry
)
587 qemu_put_mouse_event_current
= prev
;
589 qemu_free(entry
->qemu_put_mouse_event_name
);
593 void kbd_put_keycode(int keycode
)
595 if (qemu_put_kbd_event
) {
596 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
600 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
602 QEMUPutMouseEvent
*mouse_event
;
603 void *mouse_event_opaque
;
606 if (!qemu_put_mouse_event_current
) {
611 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
613 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
616 if (graphic_rotate
) {
617 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
620 width
= graphic_width
- 1;
621 mouse_event(mouse_event_opaque
,
622 width
- dy
, dx
, dz
, buttons_state
);
624 mouse_event(mouse_event_opaque
,
625 dx
, dy
, dz
, buttons_state
);
629 int kbd_mouse_is_absolute(void)
631 if (!qemu_put_mouse_event_current
)
634 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
637 void do_info_mice(void)
639 QEMUPutMouseEntry
*cursor
;
642 if (!qemu_put_mouse_event_head
) {
643 term_printf("No mouse devices connected\n");
647 term_printf("Mouse devices available:\n");
648 cursor
= qemu_put_mouse_event_head
;
649 while (cursor
!= NULL
) {
650 term_printf("%c Mouse #%d: %s\n",
651 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
652 index
, cursor
->qemu_put_mouse_event_name
);
654 cursor
= cursor
->next
;
658 void do_mouse_set(int index
)
660 QEMUPutMouseEntry
*cursor
;
663 if (!qemu_put_mouse_event_head
) {
664 term_printf("No mouse devices connected\n");
668 cursor
= qemu_put_mouse_event_head
;
669 while (cursor
!= NULL
&& index
!= i
) {
671 cursor
= cursor
->next
;
675 qemu_put_mouse_event_current
= cursor
;
677 term_printf("Mouse at given index not found\n");
680 /* compute with 96 bit intermediate result: (a*b)/c */
681 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
686 #ifdef WORDS_BIGENDIAN
696 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
697 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
700 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
704 /***********************************************************/
705 /* real time host monotonic timer */
707 #define QEMU_TIMER_BASE 1000000000LL
711 static int64_t clock_freq
;
713 static void init_get_clock(void)
717 ret
= QueryPerformanceFrequency(&freq
);
719 fprintf(stderr
, "Could not calibrate ticks\n");
722 clock_freq
= freq
.QuadPart
;
725 static int64_t get_clock(void)
728 QueryPerformanceCounter(&ti
);
729 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
734 static int use_rt_clock
;
736 static void init_get_clock(void)
739 #if defined(__linux__)
742 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
749 static int64_t get_clock(void)
751 #if defined(__linux__)
754 clock_gettime(CLOCK_MONOTONIC
, &ts
);
755 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
759 /* XXX: using gettimeofday leads to problems if the date
760 changes, so it should be avoided. */
762 gettimeofday(&tv
, NULL
);
763 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
768 /* Return the virtual CPU time, based on the instruction counter. */
769 static int64_t cpu_get_icount(void)
772 CPUState
*env
= cpu_single_env
;;
773 icount
= qemu_icount
;
776 fprintf(stderr
, "Bad clock read\n");
777 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
779 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
782 /***********************************************************/
783 /* guest cycle counter */
785 static int64_t cpu_ticks_prev
;
786 static int64_t cpu_ticks_offset
;
787 static int64_t cpu_clock_offset
;
788 static int cpu_ticks_enabled
;
790 /* return the host CPU cycle counter and handle stop/restart */
791 int64_t cpu_get_ticks(void)
794 return cpu_get_icount();
796 if (!cpu_ticks_enabled
) {
797 return cpu_ticks_offset
;
800 ticks
= cpu_get_real_ticks();
801 if (cpu_ticks_prev
> ticks
) {
802 /* Note: non increasing ticks may happen if the host uses
804 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
806 cpu_ticks_prev
= ticks
;
807 return ticks
+ cpu_ticks_offset
;
811 /* return the host CPU monotonic timer and handle stop/restart */
812 static int64_t cpu_get_clock(void)
815 if (!cpu_ticks_enabled
) {
816 return cpu_clock_offset
;
819 return ti
+ cpu_clock_offset
;
823 /* enable cpu_get_ticks() */
824 void cpu_enable_ticks(void)
826 if (!cpu_ticks_enabled
) {
827 cpu_ticks_offset
-= cpu_get_real_ticks();
828 cpu_clock_offset
-= get_clock();
829 cpu_ticks_enabled
= 1;
833 /* disable cpu_get_ticks() : the clock is stopped. You must not call
834 cpu_get_ticks() after that. */
835 void cpu_disable_ticks(void)
837 if (cpu_ticks_enabled
) {
838 cpu_ticks_offset
= cpu_get_ticks();
839 cpu_clock_offset
= cpu_get_clock();
840 cpu_ticks_enabled
= 0;
844 /***********************************************************/
847 #define QEMU_TIMER_REALTIME 0
848 #define QEMU_TIMER_VIRTUAL 1
852 /* XXX: add frequency */
860 struct QEMUTimer
*next
;
863 struct qemu_alarm_timer
{
867 int (*start
)(struct qemu_alarm_timer
*t
);
868 void (*stop
)(struct qemu_alarm_timer
*t
);
869 void (*rearm
)(struct qemu_alarm_timer
*t
);
873 #define ALARM_FLAG_DYNTICKS 0x1
874 #define ALARM_FLAG_EXPIRED 0x2
876 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
878 return t
->flags
& ALARM_FLAG_DYNTICKS
;
881 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
883 if (!alarm_has_dynticks(t
))
889 /* TODO: MIN_TIMER_REARM_US should be optimized */
890 #define MIN_TIMER_REARM_US 250
892 static struct qemu_alarm_timer
*alarm_timer
;
896 struct qemu_alarm_win32
{
900 } alarm_win32_data
= {0, NULL
, -1};
902 static int win32_start_timer(struct qemu_alarm_timer
*t
);
903 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
904 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
908 static int unix_start_timer(struct qemu_alarm_timer
*t
);
909 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
913 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
914 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
915 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
917 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
918 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
920 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
921 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
923 #endif /* __linux__ */
927 /* Correlation between real and virtual time is always going to be
928 fairly approximate, so ignore small variation.
929 When the guest is idle real and virtual time will be aligned in
931 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
933 static void icount_adjust(void)
938 static int64_t last_delta
;
939 /* If the VM is not running, then do nothing. */
943 cur_time
= cpu_get_clock();
944 cur_icount
= qemu_get_clock(vm_clock
);
945 delta
= cur_icount
- cur_time
;
946 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
948 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
949 && icount_time_shift
> 0) {
950 /* The guest is getting too far ahead. Slow time down. */
954 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
955 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
956 /* The guest is getting too far behind. Speed time up. */
960 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
963 static void icount_adjust_rt(void * opaque
)
965 qemu_mod_timer(icount_rt_timer
,
966 qemu_get_clock(rt_clock
) + 1000);
970 static void icount_adjust_vm(void * opaque
)
972 qemu_mod_timer(icount_vm_timer
,
973 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
977 static void init_icount_adjust(void)
979 /* Have both realtime and virtual time triggers for speed adjustment.
980 The realtime trigger catches emulated time passing too slowly,
981 the virtual time trigger catches emulated time passing too fast.
982 Realtime triggers occur even when idle, so use them less frequently
984 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
985 qemu_mod_timer(icount_rt_timer
,
986 qemu_get_clock(rt_clock
) + 1000);
987 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
988 qemu_mod_timer(icount_vm_timer
,
989 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
992 static struct qemu_alarm_timer alarm_timers
[] = {
995 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
996 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
997 /* HPET - if available - is preferred */
998 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
999 /* ...otherwise try RTC */
1000 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1002 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1004 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1005 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1006 {"win32", 0, win32_start_timer
,
1007 win32_stop_timer
, NULL
, &alarm_win32_data
},
1012 static void show_available_alarms(void)
1016 printf("Available alarm timers, in order of precedence:\n");
1017 for (i
= 0; alarm_timers
[i
].name
; i
++)
1018 printf("%s\n", alarm_timers
[i
].name
);
1021 static void configure_alarms(char const *opt
)
1025 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1028 struct qemu_alarm_timer tmp
;
1030 if (!strcmp(opt
, "?")) {
1031 show_available_alarms();
1037 /* Reorder the array */
1038 name
= strtok(arg
, ",");
1040 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1041 if (!strcmp(alarm_timers
[i
].name
, name
))
1046 fprintf(stderr
, "Unknown clock %s\n", name
);
1055 tmp
= alarm_timers
[i
];
1056 alarm_timers
[i
] = alarm_timers
[cur
];
1057 alarm_timers
[cur
] = tmp
;
1061 name
= strtok(NULL
, ",");
1067 /* Disable remaining timers */
1068 for (i
= cur
; i
< count
; i
++)
1069 alarm_timers
[i
].name
= NULL
;
1071 show_available_alarms();
1076 QEMUClock
*rt_clock
;
1077 QEMUClock
*vm_clock
;
1079 static QEMUTimer
*active_timers
[2];
1081 static QEMUClock
*qemu_new_clock(int type
)
1084 clock
= qemu_mallocz(sizeof(QEMUClock
));
1091 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1095 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1098 ts
->opaque
= opaque
;
1102 void qemu_free_timer(QEMUTimer
*ts
)
1107 /* stop a timer, but do not dealloc it */
1108 void qemu_del_timer(QEMUTimer
*ts
)
1112 /* NOTE: this code must be signal safe because
1113 qemu_timer_expired() can be called from a signal. */
1114 pt
= &active_timers
[ts
->clock
->type
];
1127 /* modify the current timer so that it will be fired when current_time
1128 >= expire_time. The corresponding callback will be called. */
1129 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1135 /* add the timer in the sorted list */
1136 /* NOTE: this code must be signal safe because
1137 qemu_timer_expired() can be called from a signal. */
1138 pt
= &active_timers
[ts
->clock
->type
];
1143 if (t
->expire_time
> expire_time
)
1147 ts
->expire_time
= expire_time
;
1151 /* Rearm if necessary */
1152 if (pt
== &active_timers
[ts
->clock
->type
]) {
1153 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1154 qemu_rearm_alarm_timer(alarm_timer
);
1156 /* Interrupt execution to force deadline recalculation. */
1157 if (use_icount
&& cpu_single_env
) {
1158 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1163 int qemu_timer_pending(QEMUTimer
*ts
)
1166 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1173 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1177 return (timer_head
->expire_time
<= current_time
);
1180 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1186 if (!ts
|| ts
->expire_time
> current_time
)
1188 /* remove timer from the list before calling the callback */
1189 *ptimer_head
= ts
->next
;
1192 /* run the callback (the timer list can be modified) */
1197 int64_t qemu_get_clock(QEMUClock
*clock
)
1199 switch(clock
->type
) {
1200 case QEMU_TIMER_REALTIME
:
1201 return get_clock() / 1000000;
1203 case QEMU_TIMER_VIRTUAL
:
1205 return cpu_get_icount();
1207 return cpu_get_clock();
1212 static void init_timers(void)
1215 ticks_per_sec
= QEMU_TIMER_BASE
;
1216 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1217 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1221 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1223 uint64_t expire_time
;
1225 if (qemu_timer_pending(ts
)) {
1226 expire_time
= ts
->expire_time
;
1230 qemu_put_be64(f
, expire_time
);
1233 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1235 uint64_t expire_time
;
1237 expire_time
= qemu_get_be64(f
);
1238 if (expire_time
!= -1) {
1239 qemu_mod_timer(ts
, expire_time
);
1245 static void timer_save(QEMUFile
*f
, void *opaque
)
1247 if (cpu_ticks_enabled
) {
1248 hw_error("cannot save state if virtual timers are running");
1250 qemu_put_be64(f
, cpu_ticks_offset
);
1251 qemu_put_be64(f
, ticks_per_sec
);
1252 qemu_put_be64(f
, cpu_clock_offset
);
1255 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1257 if (version_id
!= 1 && version_id
!= 2)
1259 if (cpu_ticks_enabled
) {
1262 cpu_ticks_offset
=qemu_get_be64(f
);
1263 ticks_per_sec
=qemu_get_be64(f
);
1264 if (version_id
== 2) {
1265 cpu_clock_offset
=qemu_get_be64(f
);
1271 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1272 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1274 static void host_alarm_handler(int host_signum
)
1278 #define DISP_FREQ 1000
1280 static int64_t delta_min
= INT64_MAX
;
1281 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1283 ti
= qemu_get_clock(vm_clock
);
1284 if (last_clock
!= 0) {
1285 delta
= ti
- last_clock
;
1286 if (delta
< delta_min
)
1288 if (delta
> delta_max
)
1291 if (++count
== DISP_FREQ
) {
1292 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1293 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1294 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1295 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1296 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1298 delta_min
= INT64_MAX
;
1306 if (alarm_has_dynticks(alarm_timer
) ||
1308 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1309 qemu_get_clock(vm_clock
))) ||
1310 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1311 qemu_get_clock(rt_clock
))) {
1313 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1314 SetEvent(data
->host_alarm
);
1316 CPUState
*env
= next_cpu
;
1318 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1321 /* stop the currently executing cpu because a timer occured */
1322 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1324 if (env
->kqemu_enabled
) {
1325 kqemu_cpu_interrupt(env
);
1333 static int64_t qemu_next_deadline(void)
1337 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1338 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1339 qemu_get_clock(vm_clock
);
1341 /* To avoid problems with overflow limit this to 2^32. */
1351 static uint64_t qemu_next_deadline_dyntick(void)
1359 delta
= (qemu_next_deadline() + 999) / 1000;
1361 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1362 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1363 qemu_get_clock(rt_clock
))*1000;
1364 if (rtdelta
< delta
)
1368 if (delta
< MIN_TIMER_REARM_US
)
1369 delta
= MIN_TIMER_REARM_US
;
1376 #if defined(__linux__)
1378 #define RTC_FREQ 1024
1380 static void enable_sigio_timer(int fd
)
1382 struct sigaction act
;
1385 sigfillset(&act
.sa_mask
);
1387 act
.sa_handler
= host_alarm_handler
;
1389 sigaction(SIGIO
, &act
, NULL
);
1390 fcntl(fd
, F_SETFL
, O_ASYNC
);
1391 fcntl(fd
, F_SETOWN
, getpid());
1394 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1396 struct hpet_info info
;
1399 fd
= open("/dev/hpet", O_RDONLY
);
1404 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1406 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1407 "error, but for better emulation accuracy type:\n"
1408 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1412 /* Check capabilities */
1413 r
= ioctl(fd
, HPET_INFO
, &info
);
1417 /* Enable periodic mode */
1418 r
= ioctl(fd
, HPET_EPI
, 0);
1419 if (info
.hi_flags
&& (r
< 0))
1422 /* Enable interrupt */
1423 r
= ioctl(fd
, HPET_IE_ON
, 0);
1427 enable_sigio_timer(fd
);
1428 t
->priv
= (void *)(long)fd
;
1436 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1438 int fd
= (long)t
->priv
;
1443 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1446 unsigned long current_rtc_freq
= 0;
1448 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1451 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1452 if (current_rtc_freq
!= RTC_FREQ
&&
1453 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1454 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1455 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1456 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1459 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1465 enable_sigio_timer(rtc_fd
);
1467 t
->priv
= (void *)(long)rtc_fd
;
1472 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1474 int rtc_fd
= (long)t
->priv
;
1479 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1483 struct sigaction act
;
1485 sigfillset(&act
.sa_mask
);
1487 act
.sa_handler
= host_alarm_handler
;
1489 sigaction(SIGALRM
, &act
, NULL
);
1491 ev
.sigev_value
.sival_int
= 0;
1492 ev
.sigev_notify
= SIGEV_SIGNAL
;
1493 ev
.sigev_signo
= SIGALRM
;
1495 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1496 perror("timer_create");
1498 /* disable dynticks */
1499 fprintf(stderr
, "Dynamic Ticks disabled\n");
1504 t
->priv
= (void *)host_timer
;
1509 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1511 timer_t host_timer
= (timer_t
)t
->priv
;
1513 timer_delete(host_timer
);
1516 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1518 timer_t host_timer
= (timer_t
)t
->priv
;
1519 struct itimerspec timeout
;
1520 int64_t nearest_delta_us
= INT64_MAX
;
1523 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1524 !active_timers
[QEMU_TIMER_VIRTUAL
])
1527 nearest_delta_us
= qemu_next_deadline_dyntick();
1529 /* check whether a timer is already running */
1530 if (timer_gettime(host_timer
, &timeout
)) {
1532 fprintf(stderr
, "Internal timer error: aborting\n");
1535 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1536 if (current_us
&& current_us
<= nearest_delta_us
)
1539 timeout
.it_interval
.tv_sec
= 0;
1540 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1541 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1542 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1543 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1545 fprintf(stderr
, "Internal timer error: aborting\n");
1550 #endif /* defined(__linux__) */
1552 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1554 struct sigaction act
;
1555 struct itimerval itv
;
1559 sigfillset(&act
.sa_mask
);
1561 act
.sa_handler
= host_alarm_handler
;
1563 sigaction(SIGALRM
, &act
, NULL
);
1565 itv
.it_interval
.tv_sec
= 0;
1566 /* for i386 kernel 2.6 to get 1 ms */
1567 itv
.it_interval
.tv_usec
= 999;
1568 itv
.it_value
.tv_sec
= 0;
1569 itv
.it_value
.tv_usec
= 10 * 1000;
1571 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1578 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1580 struct itimerval itv
;
1582 memset(&itv
, 0, sizeof(itv
));
1583 setitimer(ITIMER_REAL
, &itv
, NULL
);
1586 #endif /* !defined(_WIN32) */
1590 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1593 struct qemu_alarm_win32
*data
= t
->priv
;
1596 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1597 if (!data
->host_alarm
) {
1598 perror("Failed CreateEvent");
1602 memset(&tc
, 0, sizeof(tc
));
1603 timeGetDevCaps(&tc
, sizeof(tc
));
1605 if (data
->period
< tc
.wPeriodMin
)
1606 data
->period
= tc
.wPeriodMin
;
1608 timeBeginPeriod(data
->period
);
1610 flags
= TIME_CALLBACK_FUNCTION
;
1611 if (alarm_has_dynticks(t
))
1612 flags
|= TIME_ONESHOT
;
1614 flags
|= TIME_PERIODIC
;
1616 data
->timerId
= timeSetEvent(1, // interval (ms)
1617 data
->period
, // resolution
1618 host_alarm_handler
, // function
1619 (DWORD
)t
, // parameter
1622 if (!data
->timerId
) {
1623 perror("Failed to initialize win32 alarm timer");
1625 timeEndPeriod(data
->period
);
1626 CloseHandle(data
->host_alarm
);
1630 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1635 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1637 struct qemu_alarm_win32
*data
= t
->priv
;
1639 timeKillEvent(data
->timerId
);
1640 timeEndPeriod(data
->period
);
1642 CloseHandle(data
->host_alarm
);
1645 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1647 struct qemu_alarm_win32
*data
= t
->priv
;
1648 uint64_t nearest_delta_us
;
1650 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1651 !active_timers
[QEMU_TIMER_VIRTUAL
])
1654 nearest_delta_us
= qemu_next_deadline_dyntick();
1655 nearest_delta_us
/= 1000;
1657 timeKillEvent(data
->timerId
);
1659 data
->timerId
= timeSetEvent(1,
1663 TIME_ONESHOT
| TIME_PERIODIC
);
1665 if (!data
->timerId
) {
1666 perror("Failed to re-arm win32 alarm timer");
1668 timeEndPeriod(data
->period
);
1669 CloseHandle(data
->host_alarm
);
1676 static void init_timer_alarm(void)
1678 struct qemu_alarm_timer
*t
;
1681 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1682 t
= &alarm_timers
[i
];
1690 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1691 fprintf(stderr
, "Terminating\n");
1698 static void quit_timers(void)
1700 alarm_timer
->stop(alarm_timer
);
1704 /***********************************************************/
1705 /* host time/date access */
1706 void qemu_get_timedate(struct tm
*tm
, int offset
)
1713 if (rtc_date_offset
== -1) {
1717 ret
= localtime(&ti
);
1719 ti
-= rtc_date_offset
;
1723 memcpy(tm
, ret
, sizeof(struct tm
));
1726 int qemu_timedate_diff(struct tm
*tm
)
1730 if (rtc_date_offset
== -1)
1732 seconds
= mktimegm(tm
);
1734 seconds
= mktime(tm
);
1736 seconds
= mktimegm(tm
) + rtc_date_offset
;
1738 return seconds
- time(NULL
);
1741 /***********************************************************/
1742 /* character device */
1744 static void qemu_chr_event(CharDriverState
*s
, int event
)
1748 s
->chr_event(s
->handler_opaque
, event
);
1751 static void qemu_chr_reset_bh(void *opaque
)
1753 CharDriverState
*s
= opaque
;
1754 qemu_chr_event(s
, CHR_EVENT_RESET
);
1755 qemu_bh_delete(s
->bh
);
1759 void qemu_chr_reset(CharDriverState
*s
)
1761 if (s
->bh
== NULL
) {
1762 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1763 qemu_bh_schedule(s
->bh
);
1767 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1769 return s
->chr_write(s
, buf
, len
);
1772 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1776 return s
->chr_ioctl(s
, cmd
, arg
);
1779 int qemu_chr_can_read(CharDriverState
*s
)
1781 if (!s
->chr_can_read
)
1783 return s
->chr_can_read(s
->handler_opaque
);
1786 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1788 s
->chr_read(s
->handler_opaque
, buf
, len
);
1791 void qemu_chr_accept_input(CharDriverState
*s
)
1793 if (s
->chr_accept_input
)
1794 s
->chr_accept_input(s
);
1797 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1802 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1803 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1807 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1809 if (s
->chr_send_event
)
1810 s
->chr_send_event(s
, event
);
1813 void qemu_chr_add_handlers(CharDriverState
*s
,
1814 IOCanRWHandler
*fd_can_read
,
1815 IOReadHandler
*fd_read
,
1816 IOEventHandler
*fd_event
,
1819 s
->chr_can_read
= fd_can_read
;
1820 s
->chr_read
= fd_read
;
1821 s
->chr_event
= fd_event
;
1822 s
->handler_opaque
= opaque
;
1823 if (s
->chr_update_read_handler
)
1824 s
->chr_update_read_handler(s
);
1827 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1832 static CharDriverState
*qemu_chr_open_null(void)
1834 CharDriverState
*chr
;
1836 chr
= qemu_mallocz(sizeof(CharDriverState
));
1839 chr
->chr_write
= null_chr_write
;
1843 /* MUX driver for serial I/O splitting */
1844 static int term_timestamps
;
1845 static int64_t term_timestamps_start
;
1847 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1848 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1850 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1851 IOReadHandler
*chr_read
[MAX_MUX
];
1852 IOEventHandler
*chr_event
[MAX_MUX
];
1853 void *ext_opaque
[MAX_MUX
];
1854 CharDriverState
*drv
;
1855 unsigned char buffer
[MUX_BUFFER_SIZE
];
1859 int term_got_escape
;
1864 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1866 MuxDriver
*d
= chr
->opaque
;
1868 if (!term_timestamps
) {
1869 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1874 for(i
= 0; i
< len
; i
++) {
1875 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1876 if (buf
[i
] == '\n') {
1882 if (term_timestamps_start
== -1)
1883 term_timestamps_start
= ti
;
1884 ti
-= term_timestamps_start
;
1885 secs
= ti
/ 1000000000;
1886 snprintf(buf1
, sizeof(buf1
),
1887 "[%02d:%02d:%02d.%03d] ",
1891 (int)((ti
/ 1000000) % 1000));
1892 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1899 static char *mux_help
[] = {
1900 "% h print this help\n\r",
1901 "% x exit emulator\n\r",
1902 "% s save disk data back to file (if -snapshot)\n\r",
1903 "% t toggle console timestamps\n\r"
1904 "% b send break (magic sysrq)\n\r",
1905 "% c switch between console and monitor\n\r",
1910 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1911 static void mux_print_help(CharDriverState
*chr
)
1914 char ebuf
[15] = "Escape-Char";
1915 char cbuf
[50] = "\n\r";
1917 if (term_escape_char
> 0 && term_escape_char
< 26) {
1918 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1919 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1921 snprintf(cbuf
, sizeof(cbuf
),
1922 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1925 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1926 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1927 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1928 if (mux_help
[i
][j
] == '%')
1929 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1931 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1936 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1938 if (d
->term_got_escape
) {
1939 d
->term_got_escape
= 0;
1940 if (ch
== term_escape_char
)
1945 mux_print_help(chr
);
1949 char *term
= "QEMU: Terminated\n\r";
1950 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1957 for (i
= 0; i
< nb_drives
; i
++) {
1958 bdrv_commit(drives_table
[i
].bdrv
);
1963 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1966 /* Switch to the next registered device */
1968 if (chr
->focus
>= d
->mux_cnt
)
1972 term_timestamps
= !term_timestamps
;
1973 term_timestamps_start
= -1;
1976 } else if (ch
== term_escape_char
) {
1977 d
->term_got_escape
= 1;
1985 static void mux_chr_accept_input(CharDriverState
*chr
)
1988 MuxDriver
*d
= chr
->opaque
;
1990 while (d
->prod
!= d
->cons
&&
1991 d
->chr_can_read
[m
] &&
1992 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1993 d
->chr_read
[m
](d
->ext_opaque
[m
],
1994 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
1998 static int mux_chr_can_read(void *opaque
)
2000 CharDriverState
*chr
= opaque
;
2001 MuxDriver
*d
= chr
->opaque
;
2003 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2005 if (d
->chr_can_read
[chr
->focus
])
2006 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2010 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2012 CharDriverState
*chr
= opaque
;
2013 MuxDriver
*d
= chr
->opaque
;
2017 mux_chr_accept_input (opaque
);
2019 for(i
= 0; i
< size
; i
++)
2020 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2021 if (d
->prod
== d
->cons
&&
2022 d
->chr_can_read
[m
] &&
2023 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2024 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2026 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2030 static void mux_chr_event(void *opaque
, int event
)
2032 CharDriverState
*chr
= opaque
;
2033 MuxDriver
*d
= chr
->opaque
;
2036 /* Send the event to all registered listeners */
2037 for (i
= 0; i
< d
->mux_cnt
; i
++)
2038 if (d
->chr_event
[i
])
2039 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2042 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2044 MuxDriver
*d
= chr
->opaque
;
2046 if (d
->mux_cnt
>= MAX_MUX
) {
2047 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2050 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2051 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2052 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2053 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2054 /* Fix up the real driver with mux routines */
2055 if (d
->mux_cnt
== 0) {
2056 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2057 mux_chr_event
, chr
);
2059 chr
->focus
= d
->mux_cnt
;
2063 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2065 CharDriverState
*chr
;
2068 chr
= qemu_mallocz(sizeof(CharDriverState
));
2071 d
= qemu_mallocz(sizeof(MuxDriver
));
2080 chr
->chr_write
= mux_chr_write
;
2081 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2082 chr
->chr_accept_input
= mux_chr_accept_input
;
2089 static void socket_cleanup(void)
2094 static int socket_init(void)
2099 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2101 err
= WSAGetLastError();
2102 fprintf(stderr
, "WSAStartup: %d\n", err
);
2105 atexit(socket_cleanup
);
2109 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2115 ret
= send(fd
, buf
, len
, 0);
2118 errno
= WSAGetLastError();
2119 if (errno
!= WSAEWOULDBLOCK
) {
2122 } else if (ret
== 0) {
2132 void socket_set_nonblock(int fd
)
2134 unsigned long opt
= 1;
2135 ioctlsocket(fd
, FIONBIO
, &opt
);
2140 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2146 ret
= write(fd
, buf
, len
);
2148 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2150 } else if (ret
== 0) {
2160 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2162 return unix_write(fd
, buf
, len1
);
2165 void socket_set_nonblock(int fd
)
2168 f
= fcntl(fd
, F_GETFL
);
2169 fcntl(fd
, F_SETFL
, f
| O_NONBLOCK
);
2171 #endif /* !_WIN32 */
2180 #define STDIO_MAX_CLIENTS 1
2181 static int stdio_nb_clients
= 0;
2183 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2185 FDCharDriver
*s
= chr
->opaque
;
2186 return unix_write(s
->fd_out
, buf
, len
);
2189 static int fd_chr_read_poll(void *opaque
)
2191 CharDriverState
*chr
= opaque
;
2192 FDCharDriver
*s
= chr
->opaque
;
2194 s
->max_size
= qemu_chr_can_read(chr
);
2198 static void fd_chr_read(void *opaque
)
2200 CharDriverState
*chr
= opaque
;
2201 FDCharDriver
*s
= chr
->opaque
;
2206 if (len
> s
->max_size
)
2210 size
= read(s
->fd_in
, buf
, len
);
2212 /* FD has been closed. Remove it from the active list. */
2213 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2217 qemu_chr_read(chr
, buf
, size
);
2221 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2223 FDCharDriver
*s
= chr
->opaque
;
2225 if (s
->fd_in
>= 0) {
2226 if (nographic
&& s
->fd_in
== 0) {
2228 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2229 fd_chr_read
, NULL
, chr
);
2234 static void fd_chr_close(struct CharDriverState
*chr
)
2236 FDCharDriver
*s
= chr
->opaque
;
2238 if (s
->fd_in
>= 0) {
2239 if (nographic
&& s
->fd_in
== 0) {
2241 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2248 /* open a character device to a unix fd */
2249 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2251 CharDriverState
*chr
;
2254 chr
= qemu_mallocz(sizeof(CharDriverState
));
2257 s
= qemu_mallocz(sizeof(FDCharDriver
));
2265 chr
->chr_write
= fd_chr_write
;
2266 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2267 chr
->chr_close
= fd_chr_close
;
2269 qemu_chr_reset(chr
);
2274 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2278 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2281 return qemu_chr_open_fd(-1, fd_out
);
2284 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2287 char filename_in
[256], filename_out
[256];
2289 snprintf(filename_in
, 256, "%s.in", filename
);
2290 snprintf(filename_out
, 256, "%s.out", filename
);
2291 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2292 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2293 if (fd_in
< 0 || fd_out
< 0) {
2298 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2302 return qemu_chr_open_fd(fd_in
, fd_out
);
2306 /* for STDIO, we handle the case where several clients use it
2309 #define TERM_FIFO_MAX_SIZE 1
2311 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2312 static int term_fifo_size
;
2314 static int stdio_read_poll(void *opaque
)
2316 CharDriverState
*chr
= opaque
;
2318 /* try to flush the queue if needed */
2319 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2320 qemu_chr_read(chr
, term_fifo
, 1);
2323 /* see if we can absorb more chars */
2324 if (term_fifo_size
== 0)
2330 static void stdio_read(void *opaque
)
2334 CharDriverState
*chr
= opaque
;
2336 size
= read(0, buf
, 1);
2338 /* stdin has been closed. Remove it from the active list. */
2339 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2343 if (qemu_chr_can_read(chr
) > 0) {
2344 qemu_chr_read(chr
, buf
, 1);
2345 } else if (term_fifo_size
== 0) {
2346 term_fifo
[term_fifo_size
++] = buf
[0];
2351 /* init terminal so that we can grab keys */
2352 static struct termios oldtty
;
2353 static int old_fd0_flags
;
2354 static int term_atexit_done
;
2356 static void term_exit(void)
2358 tcsetattr (0, TCSANOW
, &oldtty
);
2359 fcntl(0, F_SETFL
, old_fd0_flags
);
2362 static void term_init(void)
2366 tcgetattr (0, &tty
);
2368 old_fd0_flags
= fcntl(0, F_GETFL
);
2370 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2371 |INLCR
|IGNCR
|ICRNL
|IXON
);
2372 tty
.c_oflag
|= OPOST
;
2373 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2374 /* if graphical mode, we allow Ctrl-C handling */
2376 tty
.c_lflag
&= ~ISIG
;
2377 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2380 tty
.c_cc
[VTIME
] = 0;
2382 tcsetattr (0, TCSANOW
, &tty
);
2384 if (!term_atexit_done
++)
2387 fcntl(0, F_SETFL
, O_NONBLOCK
);
2390 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2394 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2398 static CharDriverState
*qemu_chr_open_stdio(void)
2400 CharDriverState
*chr
;
2402 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2404 chr
= qemu_chr_open_fd(0, 1);
2405 chr
->chr_close
= qemu_chr_close_stdio
;
2406 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2414 /* Once Solaris has openpty(), this is going to be removed. */
2415 int openpty(int *amaster
, int *aslave
, char *name
,
2416 struct termios
*termp
, struct winsize
*winp
)
2419 int mfd
= -1, sfd
= -1;
2421 *amaster
= *aslave
= -1;
2423 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2427 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2430 if ((slave
= ptsname(mfd
)) == NULL
)
2433 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2436 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2437 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2445 ioctl(sfd
, TIOCSWINSZ
, winp
);
2456 void cfmakeraw (struct termios
*termios_p
)
2458 termios_p
->c_iflag
&=
2459 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2460 termios_p
->c_oflag
&= ~OPOST
;
2461 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2462 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2463 termios_p
->c_cflag
|= CS8
;
2465 termios_p
->c_cc
[VMIN
] = 0;
2466 termios_p
->c_cc
[VTIME
] = 0;
2470 #if defined(__linux__) || defined(__sun__)
2480 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2481 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2483 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2485 PtyCharDriver
*s
= chr
->opaque
;
2487 if (!s
->connected
) {
2488 /* guest sends data, check for (re-)connect */
2489 pty_chr_update_read_handler(chr
);
2492 return unix_write(s
->fd
, buf
, len
);
2495 static int pty_chr_read_poll(void *opaque
)
2497 CharDriverState
*chr
= opaque
;
2498 PtyCharDriver
*s
= chr
->opaque
;
2500 s
->read_bytes
= qemu_chr_can_read(chr
);
2501 return s
->read_bytes
;
2504 static void pty_chr_read(void *opaque
)
2506 CharDriverState
*chr
= opaque
;
2507 PtyCharDriver
*s
= chr
->opaque
;
2512 if (len
> s
->read_bytes
)
2513 len
= s
->read_bytes
;
2516 size
= read(s
->fd
, buf
, len
);
2517 if ((size
== -1 && errno
== EIO
) ||
2519 pty_chr_state(chr
, 0);
2523 pty_chr_state(chr
, 1);
2524 qemu_chr_read(chr
, buf
, size
);
2528 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2530 PtyCharDriver
*s
= chr
->opaque
;
2532 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2533 pty_chr_read
, NULL
, chr
);
2536 * Short timeout here: just need wait long enougth that qemu makes
2537 * it through the poll loop once. When reconnected we want a
2538 * short timeout so we notice it almost instantly. Otherwise
2539 * read() gives us -EIO instantly, making pty_chr_state() reset the
2540 * timeout to the normal (much longer) poll interval before the
2543 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2546 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2548 PtyCharDriver
*s
= chr
->opaque
;
2551 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2554 /* (re-)connect poll interval for idle guests: once per second.
2555 * We check more frequently in case the guests sends data to
2556 * the virtual device linked to our pty. */
2557 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2560 qemu_chr_reset(chr
);
2565 static void pty_chr_timer(void *opaque
)
2567 struct CharDriverState
*chr
= opaque
;
2568 PtyCharDriver
*s
= chr
->opaque
;
2573 /* If we arrive here without polling being cleared due
2574 * read returning -EIO, then we are (re-)connected */
2575 pty_chr_state(chr
, 1);
2580 pty_chr_update_read_handler(chr
);
2583 static void pty_chr_close(struct CharDriverState
*chr
)
2585 PtyCharDriver
*s
= chr
->opaque
;
2587 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2592 static CharDriverState
*qemu_chr_open_pty(void)
2594 CharDriverState
*chr
;
2599 chr
= qemu_mallocz(sizeof(CharDriverState
));
2602 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2608 if (openpty(&s
->fd
, &slave_fd
, NULL
, NULL
, NULL
) < 0) {
2612 /* Set raw attributes on the pty. */
2614 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2617 fprintf(stderr
, "char device redirected to %s\n", ptsname(s
->fd
));
2620 chr
->chr_write
= pty_chr_write
;
2621 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2622 chr
->chr_close
= pty_chr_close
;
2624 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2629 static void tty_serial_init(int fd
, int speed
,
2630 int parity
, int data_bits
, int stop_bits
)
2636 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2637 speed
, parity
, data_bits
, stop_bits
);
2639 tcgetattr (fd
, &tty
);
2642 if (speed
<= 50 * MARGIN
)
2644 else if (speed
<= 75 * MARGIN
)
2646 else if (speed
<= 300 * MARGIN
)
2648 else if (speed
<= 600 * MARGIN
)
2650 else if (speed
<= 1200 * MARGIN
)
2652 else if (speed
<= 2400 * MARGIN
)
2654 else if (speed
<= 4800 * MARGIN
)
2656 else if (speed
<= 9600 * MARGIN
)
2658 else if (speed
<= 19200 * MARGIN
)
2660 else if (speed
<= 38400 * MARGIN
)
2662 else if (speed
<= 57600 * MARGIN
)
2664 else if (speed
<= 115200 * MARGIN
)
2669 cfsetispeed(&tty
, spd
);
2670 cfsetospeed(&tty
, spd
);
2672 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2673 |INLCR
|IGNCR
|ICRNL
|IXON
);
2674 tty
.c_oflag
|= OPOST
;
2675 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2676 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2697 tty
.c_cflag
|= PARENB
;
2700 tty
.c_cflag
|= PARENB
| PARODD
;
2704 tty
.c_cflag
|= CSTOPB
;
2706 tcsetattr (fd
, TCSANOW
, &tty
);
2709 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2711 FDCharDriver
*s
= chr
->opaque
;
2714 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2716 QEMUSerialSetParams
*ssp
= arg
;
2717 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2718 ssp
->data_bits
, ssp
->stop_bits
);
2721 case CHR_IOCTL_SERIAL_SET_BREAK
:
2723 int enable
= *(int *)arg
;
2725 tcsendbreak(s
->fd_in
, 1);
2728 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2731 int *targ
= (int *)arg
;
2732 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2734 if (sarg
| TIOCM_CTS
)
2735 *targ
|= CHR_TIOCM_CTS
;
2736 if (sarg
| TIOCM_CAR
)
2737 *targ
|= CHR_TIOCM_CAR
;
2738 if (sarg
| TIOCM_DSR
)
2739 *targ
|= CHR_TIOCM_DSR
;
2740 if (sarg
| TIOCM_RI
)
2741 *targ
|= CHR_TIOCM_RI
;
2742 if (sarg
| TIOCM_DTR
)
2743 *targ
|= CHR_TIOCM_DTR
;
2744 if (sarg
| TIOCM_RTS
)
2745 *targ
|= CHR_TIOCM_RTS
;
2748 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2750 int sarg
= *(int *)arg
;
2752 if (sarg
| CHR_TIOCM_DTR
)
2754 if (sarg
| CHR_TIOCM_RTS
)
2756 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2765 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2767 CharDriverState
*chr
;
2770 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2771 tty_serial_init(fd
, 115200, 'N', 8, 1);
2772 chr
= qemu_chr_open_fd(fd
, fd
);
2777 chr
->chr_ioctl
= tty_serial_ioctl
;
2778 qemu_chr_reset(chr
);
2781 #else /* ! __linux__ && ! __sun__ */
2782 static CharDriverState
*qemu_chr_open_pty(void)
2786 #endif /* __linux__ || __sun__ */
2788 #if defined(__linux__)
2792 } ParallelCharDriver
;
2794 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2796 if (s
->mode
!= mode
) {
2798 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2805 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2807 ParallelCharDriver
*drv
= chr
->opaque
;
2812 case CHR_IOCTL_PP_READ_DATA
:
2813 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2815 *(uint8_t *)arg
= b
;
2817 case CHR_IOCTL_PP_WRITE_DATA
:
2818 b
= *(uint8_t *)arg
;
2819 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2822 case CHR_IOCTL_PP_READ_CONTROL
:
2823 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2825 /* Linux gives only the lowest bits, and no way to know data
2826 direction! For better compatibility set the fixed upper
2828 *(uint8_t *)arg
= b
| 0xc0;
2830 case CHR_IOCTL_PP_WRITE_CONTROL
:
2831 b
= *(uint8_t *)arg
;
2832 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2835 case CHR_IOCTL_PP_READ_STATUS
:
2836 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2838 *(uint8_t *)arg
= b
;
2840 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2841 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2842 struct ParallelIOArg
*parg
= arg
;
2843 int n
= read(fd
, parg
->buffer
, parg
->count
);
2844 if (n
!= parg
->count
) {
2849 case CHR_IOCTL_PP_EPP_READ
:
2850 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2851 struct ParallelIOArg
*parg
= arg
;
2852 int n
= read(fd
, parg
->buffer
, parg
->count
);
2853 if (n
!= parg
->count
) {
2858 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2859 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2860 struct ParallelIOArg
*parg
= arg
;
2861 int n
= write(fd
, parg
->buffer
, parg
->count
);
2862 if (n
!= parg
->count
) {
2867 case CHR_IOCTL_PP_EPP_WRITE
:
2868 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2869 struct ParallelIOArg
*parg
= arg
;
2870 int n
= write(fd
, parg
->buffer
, parg
->count
);
2871 if (n
!= parg
->count
) {
2882 static void pp_close(CharDriverState
*chr
)
2884 ParallelCharDriver
*drv
= chr
->opaque
;
2887 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2888 ioctl(fd
, PPRELEASE
);
2893 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2895 CharDriverState
*chr
;
2896 ParallelCharDriver
*drv
;
2899 TFR(fd
= open(filename
, O_RDWR
));
2903 if (ioctl(fd
, PPCLAIM
) < 0) {
2908 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2914 drv
->mode
= IEEE1284_MODE_COMPAT
;
2916 chr
= qemu_mallocz(sizeof(CharDriverState
));
2922 chr
->chr_write
= null_chr_write
;
2923 chr
->chr_ioctl
= pp_ioctl
;
2924 chr
->chr_close
= pp_close
;
2927 qemu_chr_reset(chr
);
2931 #endif /* __linux__ */
2937 HANDLE hcom
, hrecv
, hsend
;
2938 OVERLAPPED orecv
, osend
;
2943 #define NSENDBUF 2048
2944 #define NRECVBUF 2048
2945 #define MAXCONNECT 1
2946 #define NTIMEOUT 5000
2948 static int win_chr_poll(void *opaque
);
2949 static int win_chr_pipe_poll(void *opaque
);
2951 static void win_chr_close(CharDriverState
*chr
)
2953 WinCharState
*s
= chr
->opaque
;
2956 CloseHandle(s
->hsend
);
2960 CloseHandle(s
->hrecv
);
2964 CloseHandle(s
->hcom
);
2968 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2970 qemu_del_polling_cb(win_chr_poll
, chr
);
2973 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2975 WinCharState
*s
= chr
->opaque
;
2977 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2982 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2984 fprintf(stderr
, "Failed CreateEvent\n");
2987 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2989 fprintf(stderr
, "Failed CreateEvent\n");
2993 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2994 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2995 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2996 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3001 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3002 fprintf(stderr
, "Failed SetupComm\n");
3006 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3007 size
= sizeof(COMMCONFIG
);
3008 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3009 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3010 CommConfigDialog(filename
, NULL
, &comcfg
);
3012 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3013 fprintf(stderr
, "Failed SetCommState\n");
3017 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3018 fprintf(stderr
, "Failed SetCommMask\n");
3022 cto
.ReadIntervalTimeout
= MAXDWORD
;
3023 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3024 fprintf(stderr
, "Failed SetCommTimeouts\n");
3028 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3029 fprintf(stderr
, "Failed ClearCommError\n");
3032 qemu_add_polling_cb(win_chr_poll
, chr
);
3040 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3042 WinCharState
*s
= chr
->opaque
;
3043 DWORD len
, ret
, size
, err
;
3046 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3047 s
->osend
.hEvent
= s
->hsend
;
3050 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3052 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3054 err
= GetLastError();
3055 if (err
== ERROR_IO_PENDING
) {
3056 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3074 static int win_chr_read_poll(CharDriverState
*chr
)
3076 WinCharState
*s
= chr
->opaque
;
3078 s
->max_size
= qemu_chr_can_read(chr
);
3082 static void win_chr_readfile(CharDriverState
*chr
)
3084 WinCharState
*s
= chr
->opaque
;
3089 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3090 s
->orecv
.hEvent
= s
->hrecv
;
3091 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3093 err
= GetLastError();
3094 if (err
== ERROR_IO_PENDING
) {
3095 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3100 qemu_chr_read(chr
, buf
, size
);
3104 static void win_chr_read(CharDriverState
*chr
)
3106 WinCharState
*s
= chr
->opaque
;
3108 if (s
->len
> s
->max_size
)
3109 s
->len
= s
->max_size
;
3113 win_chr_readfile(chr
);
3116 static int win_chr_poll(void *opaque
)
3118 CharDriverState
*chr
= opaque
;
3119 WinCharState
*s
= chr
->opaque
;
3123 ClearCommError(s
->hcom
, &comerr
, &status
);
3124 if (status
.cbInQue
> 0) {
3125 s
->len
= status
.cbInQue
;
3126 win_chr_read_poll(chr
);
3133 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3135 CharDriverState
*chr
;
3138 chr
= qemu_mallocz(sizeof(CharDriverState
));
3141 s
= qemu_mallocz(sizeof(WinCharState
));
3147 chr
->chr_write
= win_chr_write
;
3148 chr
->chr_close
= win_chr_close
;
3150 if (win_chr_init(chr
, filename
) < 0) {
3155 qemu_chr_reset(chr
);
3159 static int win_chr_pipe_poll(void *opaque
)
3161 CharDriverState
*chr
= opaque
;
3162 WinCharState
*s
= chr
->opaque
;
3165 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3168 win_chr_read_poll(chr
);
3175 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3177 WinCharState
*s
= chr
->opaque
;
3185 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3187 fprintf(stderr
, "Failed CreateEvent\n");
3190 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3192 fprintf(stderr
, "Failed CreateEvent\n");
3196 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3197 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3198 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3200 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3201 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3202 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3207 ZeroMemory(&ov
, sizeof(ov
));
3208 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3209 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3211 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3215 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3217 fprintf(stderr
, "Failed GetOverlappedResult\n");
3219 CloseHandle(ov
.hEvent
);
3226 CloseHandle(ov
.hEvent
);
3229 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3238 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3240 CharDriverState
*chr
;
3243 chr
= qemu_mallocz(sizeof(CharDriverState
));
3246 s
= qemu_mallocz(sizeof(WinCharState
));
3252 chr
->chr_write
= win_chr_write
;
3253 chr
->chr_close
= win_chr_close
;
3255 if (win_chr_pipe_init(chr
, filename
) < 0) {
3260 qemu_chr_reset(chr
);
3264 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3266 CharDriverState
*chr
;
3269 chr
= qemu_mallocz(sizeof(CharDriverState
));
3272 s
= qemu_mallocz(sizeof(WinCharState
));
3279 chr
->chr_write
= win_chr_write
;
3280 qemu_chr_reset(chr
);
3284 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3286 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3289 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3293 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3294 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3295 if (fd_out
== INVALID_HANDLE_VALUE
)
3298 return qemu_chr_open_win_file(fd_out
);
3300 #endif /* !_WIN32 */
3302 /***********************************************************/
3303 /* UDP Net console */
3307 struct sockaddr_in daddr
;
3314 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3316 NetCharDriver
*s
= chr
->opaque
;
3318 return sendto(s
->fd
, buf
, len
, 0,
3319 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3322 static int udp_chr_read_poll(void *opaque
)
3324 CharDriverState
*chr
= opaque
;
3325 NetCharDriver
*s
= chr
->opaque
;
3327 s
->max_size
= qemu_chr_can_read(chr
);
3329 /* If there were any stray characters in the queue process them
3332 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3333 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3335 s
->max_size
= qemu_chr_can_read(chr
);
3340 static void udp_chr_read(void *opaque
)
3342 CharDriverState
*chr
= opaque
;
3343 NetCharDriver
*s
= chr
->opaque
;
3345 if (s
->max_size
== 0)
3347 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3348 s
->bufptr
= s
->bufcnt
;
3353 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3354 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3356 s
->max_size
= qemu_chr_can_read(chr
);
3360 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3362 NetCharDriver
*s
= chr
->opaque
;
3365 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3366 udp_chr_read
, NULL
, chr
);
3370 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
3372 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3374 int parse_host_src_port(struct sockaddr_in
*haddr
,
3375 struct sockaddr_in
*saddr
,
3378 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3380 CharDriverState
*chr
= NULL
;
3381 NetCharDriver
*s
= NULL
;
3383 struct sockaddr_in saddr
;
3385 chr
= qemu_mallocz(sizeof(CharDriverState
));
3388 s
= qemu_mallocz(sizeof(NetCharDriver
));
3392 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3394 perror("socket(PF_INET, SOCK_DGRAM)");
3398 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3399 printf("Could not parse: %s\n", def
);
3403 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3413 chr
->chr_write
= udp_chr_write
;
3414 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3427 /***********************************************************/
3428 /* TCP Net console */
3439 static void tcp_chr_accept(void *opaque
);
3441 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3443 TCPCharDriver
*s
= chr
->opaque
;
3445 return send_all(s
->fd
, buf
, len
);
3447 /* XXX: indicate an error ? */
3452 static int tcp_chr_read_poll(void *opaque
)
3454 CharDriverState
*chr
= opaque
;
3455 TCPCharDriver
*s
= chr
->opaque
;
3458 s
->max_size
= qemu_chr_can_read(chr
);
3463 #define IAC_BREAK 243
3464 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3466 uint8_t *buf
, int *size
)
3468 /* Handle any telnet client's basic IAC options to satisfy char by
3469 * char mode with no echo. All IAC options will be removed from
3470 * the buf and the do_telnetopt variable will be used to track the
3471 * state of the width of the IAC information.
3473 * IAC commands come in sets of 3 bytes with the exception of the
3474 * "IAC BREAK" command and the double IAC.
3480 for (i
= 0; i
< *size
; i
++) {
3481 if (s
->do_telnetopt
> 1) {
3482 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3483 /* Double IAC means send an IAC */
3487 s
->do_telnetopt
= 1;
3489 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3490 /* Handle IAC break commands by sending a serial break */
3491 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3496 if (s
->do_telnetopt
>= 4) {
3497 s
->do_telnetopt
= 1;
3500 if ((unsigned char)buf
[i
] == IAC
) {
3501 s
->do_telnetopt
= 2;
3512 static void tcp_chr_read(void *opaque
)
3514 CharDriverState
*chr
= opaque
;
3515 TCPCharDriver
*s
= chr
->opaque
;
3519 if (!s
->connected
|| s
->max_size
<= 0)
3522 if (len
> s
->max_size
)
3524 size
= recv(s
->fd
, buf
, len
, 0);
3526 /* connection closed */
3528 if (s
->listen_fd
>= 0) {
3529 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3531 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3534 } else if (size
> 0) {
3535 if (s
->do_telnetopt
)
3536 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3538 qemu_chr_read(chr
, buf
, size
);
3542 static void tcp_chr_connect(void *opaque
)
3544 CharDriverState
*chr
= opaque
;
3545 TCPCharDriver
*s
= chr
->opaque
;
3548 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3549 tcp_chr_read
, NULL
, chr
);
3550 qemu_chr_reset(chr
);
3553 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3554 static void tcp_chr_telnet_init(int fd
)
3557 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3558 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3559 send(fd
, (char *)buf
, 3, 0);
3560 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3561 send(fd
, (char *)buf
, 3, 0);
3562 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3563 send(fd
, (char *)buf
, 3, 0);
3564 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3565 send(fd
, (char *)buf
, 3, 0);
3568 static void socket_set_nodelay(int fd
)
3571 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3574 static void tcp_chr_accept(void *opaque
)
3576 CharDriverState
*chr
= opaque
;
3577 TCPCharDriver
*s
= chr
->opaque
;
3578 struct sockaddr_in saddr
;
3580 struct sockaddr_un uaddr
;
3582 struct sockaddr
*addr
;
3589 len
= sizeof(uaddr
);
3590 addr
= (struct sockaddr
*)&uaddr
;
3594 len
= sizeof(saddr
);
3595 addr
= (struct sockaddr
*)&saddr
;
3597 fd
= accept(s
->listen_fd
, addr
, &len
);
3598 if (fd
< 0 && errno
!= EINTR
) {
3600 } else if (fd
>= 0) {
3601 if (s
->do_telnetopt
)
3602 tcp_chr_telnet_init(fd
);
3606 socket_set_nonblock(fd
);
3608 socket_set_nodelay(fd
);
3610 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3611 tcp_chr_connect(chr
);
3614 static void tcp_chr_close(CharDriverState
*chr
)
3616 TCPCharDriver
*s
= chr
->opaque
;
3619 if (s
->listen_fd
>= 0)
3620 closesocket(s
->listen_fd
);
3624 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3628 CharDriverState
*chr
= NULL
;
3629 TCPCharDriver
*s
= NULL
;
3630 int fd
= -1, ret
, err
, val
;
3632 int is_waitconnect
= 1;
3635 struct sockaddr_in saddr
;
3637 struct sockaddr_un uaddr
;
3639 struct sockaddr
*addr
;
3644 addr
= (struct sockaddr
*)&uaddr
;
3645 addrlen
= sizeof(uaddr
);
3646 if (parse_unix_path(&uaddr
, host_str
) < 0)
3651 addr
= (struct sockaddr
*)&saddr
;
3652 addrlen
= sizeof(saddr
);
3653 if (parse_host_port(&saddr
, host_str
) < 0)
3658 while((ptr
= strchr(ptr
,','))) {
3660 if (!strncmp(ptr
,"server",6)) {
3662 } else if (!strncmp(ptr
,"nowait",6)) {
3664 } else if (!strncmp(ptr
,"nodelay",6)) {
3667 printf("Unknown option: %s\n", ptr
);
3674 chr
= qemu_mallocz(sizeof(CharDriverState
));
3677 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3683 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3686 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3691 if (!is_waitconnect
)
3692 socket_set_nonblock(fd
);
3697 s
->is_unix
= is_unix
;
3698 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3701 chr
->chr_write
= tcp_chr_write
;
3702 chr
->chr_close
= tcp_chr_close
;
3705 /* allow fast reuse */
3709 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3715 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3718 ret
= bind(fd
, addr
, addrlen
);
3722 ret
= listen(fd
, 0);
3727 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3729 s
->do_telnetopt
= 1;
3732 ret
= connect(fd
, addr
, addrlen
);
3734 err
= socket_error();
3735 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3736 } else if (err
== EINPROGRESS
) {
3739 } else if (err
== WSAEALREADY
) {
3751 socket_set_nodelay(fd
);
3753 tcp_chr_connect(chr
);
3755 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3758 if (is_listen
&& is_waitconnect
) {
3759 printf("QEMU waiting for connection on: %s\n", host_str
);
3760 tcp_chr_accept(chr
);
3761 socket_set_nonblock(s
->listen_fd
);
3773 CharDriverState
*qemu_chr_open(const char *filename
)
3777 if (!strcmp(filename
, "vc")) {
3778 return text_console_init(&display_state
, 0);
3779 } else if (strstart(filename
, "vc:", &p
)) {
3780 return text_console_init(&display_state
, p
);
3781 } else if (!strcmp(filename
, "null")) {
3782 return qemu_chr_open_null();
3784 if (strstart(filename
, "tcp:", &p
)) {
3785 return qemu_chr_open_tcp(p
, 0, 0);
3787 if (strstart(filename
, "telnet:", &p
)) {
3788 return qemu_chr_open_tcp(p
, 1, 0);
3790 if (strstart(filename
, "udp:", &p
)) {
3791 return qemu_chr_open_udp(p
);
3793 if (strstart(filename
, "mon:", &p
)) {
3794 CharDriverState
*drv
= qemu_chr_open(p
);
3796 drv
= qemu_chr_open_mux(drv
);
3797 monitor_init(drv
, !nographic
);
3800 printf("Unable to open driver: %s\n", p
);
3804 if (strstart(filename
, "unix:", &p
)) {
3805 return qemu_chr_open_tcp(p
, 0, 1);
3806 } else if (strstart(filename
, "file:", &p
)) {
3807 return qemu_chr_open_file_out(p
);
3808 } else if (strstart(filename
, "pipe:", &p
)) {
3809 return qemu_chr_open_pipe(p
);
3810 } else if (!strcmp(filename
, "pty")) {
3811 return qemu_chr_open_pty();
3812 } else if (!strcmp(filename
, "stdio")) {
3813 return qemu_chr_open_stdio();
3815 #if defined(__linux__)
3816 if (strstart(filename
, "/dev/parport", NULL
)) {
3817 return qemu_chr_open_pp(filename
);
3820 #if defined(__linux__) || defined(__sun__)
3821 if (strstart(filename
, "/dev/", NULL
)) {
3822 return qemu_chr_open_tty(filename
);
3826 if (strstart(filename
, "COM", NULL
)) {
3827 return qemu_chr_open_win(filename
);
3829 if (strstart(filename
, "pipe:", &p
)) {
3830 return qemu_chr_open_win_pipe(p
);
3832 if (strstart(filename
, "con:", NULL
)) {
3833 return qemu_chr_open_win_con(filename
);
3835 if (strstart(filename
, "file:", &p
)) {
3836 return qemu_chr_open_win_file_out(p
);
3839 #ifdef CONFIG_BRLAPI
3840 if (!strcmp(filename
, "braille")) {
3841 return chr_baum_init();
3849 void qemu_chr_close(CharDriverState
*chr
)
3852 chr
->chr_close(chr
);
3856 /***********************************************************/
3857 /* network device redirectors */
3859 __attribute__ (( unused
))
3860 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3864 for(i
=0;i
<size
;i
+=16) {
3868 fprintf(f
, "%08x ", i
);
3871 fprintf(f
, " %02x", buf
[i
+j
]);
3876 for(j
=0;j
<len
;j
++) {
3878 if (c
< ' ' || c
> '~')
3880 fprintf(f
, "%c", c
);
3886 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3893 offset
= strtol(p
, &last_char
, 0);
3894 if (0 == errno
&& '\0' == *last_char
&&
3895 offset
>= 0 && offset
<= 0xFFFFFF) {
3896 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3897 macaddr
[4] = (offset
& 0xFF00) >> 8;
3898 macaddr
[5] = offset
& 0xFF;
3901 for(i
= 0; i
< 6; i
++) {
3902 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3907 if (*p
!= ':' && *p
!= '-')
3918 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3923 p1
= strchr(p
, sep
);
3929 if (len
> buf_size
- 1)
3931 memcpy(buf
, p
, len
);
3938 int parse_host_src_port(struct sockaddr_in
*haddr
,
3939 struct sockaddr_in
*saddr
,
3940 const char *input_str
)
3942 char *str
= strdup(input_str
);
3943 char *host_str
= str
;
3948 * Chop off any extra arguments at the end of the string which
3949 * would start with a comma, then fill in the src port information
3950 * if it was provided else use the "any address" and "any port".
3952 if ((ptr
= strchr(str
,',')))
3955 if ((src_str
= strchr(input_str
,'@'))) {
3960 if (parse_host_port(haddr
, host_str
) < 0)
3963 if (!src_str
|| *src_str
== '\0')
3966 if (parse_host_port(saddr
, src_str
) < 0)
3977 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3985 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3987 saddr
->sin_family
= AF_INET
;
3988 if (buf
[0] == '\0') {
3989 saddr
->sin_addr
.s_addr
= 0;
3991 if (isdigit(buf
[0])) {
3992 if (!inet_aton(buf
, &saddr
->sin_addr
))
3995 if ((he
= gethostbyname(buf
)) == NULL
)
3997 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4000 port
= strtol(p
, (char **)&r
, 0);
4003 saddr
->sin_port
= htons(port
);
4008 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4013 len
= MIN(108, strlen(str
));
4014 p
= strchr(str
, ',');
4016 len
= MIN(len
, p
- str
);
4018 memset(uaddr
, 0, sizeof(*uaddr
));
4020 uaddr
->sun_family
= AF_UNIX
;
4021 memcpy(uaddr
->sun_path
, str
, len
);
4027 /* find or alloc a new VLAN */
4028 VLANState
*qemu_find_vlan(int id
)
4030 VLANState
**pvlan
, *vlan
;
4031 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4035 vlan
= qemu_mallocz(sizeof(VLANState
));
4040 pvlan
= &first_vlan
;
4041 while (*pvlan
!= NULL
)
4042 pvlan
= &(*pvlan
)->next
;
4047 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4048 IOReadHandler
*fd_read
,
4049 IOCanRWHandler
*fd_can_read
,
4052 VLANClientState
*vc
, **pvc
;
4053 vc
= qemu_mallocz(sizeof(VLANClientState
));
4056 vc
->fd_read
= fd_read
;
4057 vc
->fd_can_read
= fd_can_read
;
4058 vc
->opaque
= opaque
;
4062 pvc
= &vlan
->first_client
;
4063 while (*pvc
!= NULL
)
4064 pvc
= &(*pvc
)->next
;
4069 void qemu_del_vlan_client(VLANClientState
*vc
)
4071 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4073 while (*pvc
!= NULL
)
4079 pvc
= &(*pvc
)->next
;
4082 int qemu_can_send_packet(VLANClientState
*vc1
)
4084 VLANState
*vlan
= vc1
->vlan
;
4085 VLANClientState
*vc
;
4087 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4089 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4096 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4098 VLANState
*vlan
= vc1
->vlan
;
4099 VLANClientState
*vc
;
4102 printf("vlan %d send:\n", vlan
->id
);
4103 hex_dump(stdout
, buf
, size
);
4105 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4107 vc
->fd_read(vc
->opaque
, buf
, size
);
4112 #if defined(CONFIG_SLIRP)
4114 /* slirp network adapter */
4116 static int slirp_inited
;
4117 static VLANClientState
*slirp_vc
;
4119 int slirp_can_output(void)
4121 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4124 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4127 printf("slirp output:\n");
4128 hex_dump(stdout
, pkt
, pkt_len
);
4132 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4135 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4138 printf("slirp input:\n");
4139 hex_dump(stdout
, buf
, size
);
4141 slirp_input(buf
, size
);
4144 static int net_slirp_init(VLANState
*vlan
)
4146 if (!slirp_inited
) {
4150 slirp_vc
= qemu_new_vlan_client(vlan
,
4151 slirp_receive
, NULL
, NULL
);
4152 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4156 static void net_slirp_redir(const char *redir_str
)
4161 struct in_addr guest_addr
;
4162 int host_port
, guest_port
;
4164 if (!slirp_inited
) {
4170 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4172 if (!strcmp(buf
, "tcp")) {
4174 } else if (!strcmp(buf
, "udp")) {
4180 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4182 host_port
= strtol(buf
, &r
, 0);
4186 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4188 if (buf
[0] == '\0') {
4189 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4191 if (!inet_aton(buf
, &guest_addr
))
4194 guest_port
= strtol(p
, &r
, 0);
4198 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4199 fprintf(stderr
, "qemu: could not set up redirection\n");
4204 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4212 static void erase_dir(char *dir_name
)
4216 char filename
[1024];
4218 /* erase all the files in the directory */
4219 if ((d
= opendir(dir_name
)) != 0) {
4224 if (strcmp(de
->d_name
, ".") != 0 &&
4225 strcmp(de
->d_name
, "..") != 0) {
4226 snprintf(filename
, sizeof(filename
), "%s/%s",
4227 smb_dir
, de
->d_name
);
4228 if (unlink(filename
) != 0) /* is it a directory? */
4229 erase_dir(filename
);
4237 /* automatic user mode samba server configuration */
4238 static void smb_exit(void)
4243 /* automatic user mode samba server configuration */
4244 static void net_slirp_smb(const char *exported_dir
)
4246 char smb_conf
[1024];
4247 char smb_cmdline
[1024];
4250 if (!slirp_inited
) {
4255 /* XXX: better tmp dir construction */
4256 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4257 if (mkdir(smb_dir
, 0700) < 0) {
4258 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4261 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4263 f
= fopen(smb_conf
, "w");
4265 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4272 "socket address=127.0.0.1\n"
4273 "pid directory=%s\n"
4274 "lock directory=%s\n"
4275 "log file=%s/log.smbd\n"
4276 "smb passwd file=%s/smbpasswd\n"
4277 "security = share\n"
4292 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4293 SMBD_COMMAND
, smb_conf
);
4295 slirp_add_exec(0, smb_cmdline
, 4, 139);
4298 #endif /* !defined(_WIN32) */
4299 void do_info_slirp(void)
4304 #endif /* CONFIG_SLIRP */
4306 #if !defined(_WIN32)
4308 typedef struct TAPState
{
4309 VLANClientState
*vc
;
4311 char down_script
[1024];
4314 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4316 TAPState
*s
= opaque
;
4319 ret
= write(s
->fd
, buf
, size
);
4320 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4327 static void tap_send(void *opaque
)
4329 TAPState
*s
= opaque
;
4336 sbuf
.maxlen
= sizeof(buf
);
4338 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4340 size
= read(s
->fd
, buf
, sizeof(buf
));
4343 qemu_send_packet(s
->vc
, buf
, size
);
4349 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4353 s
= qemu_mallocz(sizeof(TAPState
));
4357 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4358 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
4359 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4363 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4364 static int tap_open(char *ifname
, int ifname_size
)
4370 TFR(fd
= open("/dev/tap", O_RDWR
));
4372 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4377 dev
= devname(s
.st_rdev
, S_IFCHR
);
4378 pstrcpy(ifname
, ifname_size
, dev
);
4380 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4383 #elif defined(__sun__)
4384 #define TUNNEWPPA (('T'<<16) | 0x0001)
4386 * Allocate TAP device, returns opened fd.
4387 * Stores dev name in the first arg(must be large enough).
4389 int tap_alloc(char *dev
, size_t dev_size
)
4391 int tap_fd
, if_fd
, ppa
= -1;
4392 static int ip_fd
= 0;
4395 static int arp_fd
= 0;
4396 int ip_muxid
, arp_muxid
;
4397 struct strioctl strioc_if
, strioc_ppa
;
4398 int link_type
= I_PLINK
;;
4400 char actual_name
[32] = "";
4402 memset(&ifr
, 0x0, sizeof(ifr
));
4406 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4410 /* Check if IP device was opened */
4414 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4416 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4420 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4422 syslog(LOG_ERR
, "Can't open /dev/tap");
4426 /* Assign a new PPA and get its unit number. */
4427 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4428 strioc_ppa
.ic_timout
= 0;
4429 strioc_ppa
.ic_len
= sizeof(ppa
);
4430 strioc_ppa
.ic_dp
= (char *)&ppa
;
4431 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4432 syslog (LOG_ERR
, "Can't assign new interface");
4434 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4436 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4439 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4440 syslog(LOG_ERR
, "Can't push IP module");
4444 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4445 syslog(LOG_ERR
, "Can't get flags\n");
4447 snprintf (actual_name
, 32, "tap%d", ppa
);
4448 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4451 /* Assign ppa according to the unit number returned by tun device */
4453 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4454 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4455 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4456 syslog (LOG_ERR
, "Can't get flags\n");
4457 /* Push arp module to if_fd */
4458 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4459 syslog (LOG_ERR
, "Can't push ARP module (2)");
4461 /* Push arp module to ip_fd */
4462 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4463 syslog (LOG_ERR
, "I_POP failed\n");
4464 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4465 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4467 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4469 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4471 /* Set ifname to arp */
4472 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4473 strioc_if
.ic_timout
= 0;
4474 strioc_if
.ic_len
= sizeof(ifr
);
4475 strioc_if
.ic_dp
= (char *)&ifr
;
4476 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4477 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4480 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4481 syslog(LOG_ERR
, "Can't link TAP device to IP");
4485 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4486 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4490 memset(&ifr
, 0x0, sizeof(ifr
));
4491 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4492 ifr
.lifr_ip_muxid
= ip_muxid
;
4493 ifr
.lifr_arp_muxid
= arp_muxid
;
4495 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4497 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4498 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4499 syslog (LOG_ERR
, "Can't set multiplexor id");
4502 snprintf(dev
, dev_size
, "tap%d", ppa
);
4506 static int tap_open(char *ifname
, int ifname_size
)
4510 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4511 fprintf(stderr
, "Cannot allocate TAP device\n");
4514 pstrcpy(ifname
, ifname_size
, dev
);
4515 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4519 static int tap_open(char *ifname
, int ifname_size
)
4524 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4526 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4529 memset(&ifr
, 0, sizeof(ifr
));
4530 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4531 if (ifname
[0] != '\0')
4532 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4534 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4535 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4537 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4541 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4542 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4547 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4553 /* try to launch network script */
4557 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4558 for (i
= 0; i
< open_max
; i
++)
4559 if (i
!= STDIN_FILENO
&&
4560 i
!= STDOUT_FILENO
&&
4561 i
!= STDERR_FILENO
&&
4566 *parg
++ = (char *)setup_script
;
4567 *parg
++ = (char *)ifname
;
4569 execv(setup_script
, args
);
4572 while (waitpid(pid
, &status
, 0) != pid
);
4573 if (!WIFEXITED(status
) ||
4574 WEXITSTATUS(status
) != 0) {
4575 fprintf(stderr
, "%s: could not launch network script\n",
4583 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4584 const char *setup_script
, const char *down_script
)
4590 if (ifname1
!= NULL
)
4591 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4594 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4598 if (!setup_script
|| !strcmp(setup_script
, "no"))
4600 if (setup_script
[0] != '\0') {
4601 if (launch_script(setup_script
, ifname
, fd
))
4604 s
= net_tap_fd_init(vlan
, fd
);
4607 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4608 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4609 if (down_script
&& strcmp(down_script
, "no"))
4610 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4614 #endif /* !_WIN32 */
4616 #if defined(CONFIG_VDE)
4617 typedef struct VDEState
{
4618 VLANClientState
*vc
;
4622 static void vde_to_qemu(void *opaque
)
4624 VDEState
*s
= opaque
;
4628 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4630 qemu_send_packet(s
->vc
, buf
, size
);
4634 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4636 VDEState
*s
= opaque
;
4639 ret
= vde_send(s
->vde
, buf
, size
, 0);
4640 if (ret
< 0 && errno
== EINTR
) {
4647 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4648 const char *group
, int mode
)
4651 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4652 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4654 struct vde_open_args args
= {
4656 .group
= init_group
,
4660 s
= qemu_mallocz(sizeof(VDEState
));
4663 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4668 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4669 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4670 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4671 sock
, vde_datafd(s
->vde
));
4676 /* network connection */
4677 typedef struct NetSocketState
{
4678 VLANClientState
*vc
;
4680 int state
; /* 0 = getting length, 1 = getting data */
4684 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4687 typedef struct NetSocketListenState
{
4690 } NetSocketListenState
;
4692 /* XXX: we consider we can send the whole packet without blocking */
4693 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4695 NetSocketState
*s
= opaque
;
4699 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4700 send_all(s
->fd
, buf
, size
);
4703 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4705 NetSocketState
*s
= opaque
;
4706 sendto(s
->fd
, buf
, size
, 0,
4707 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4710 static void net_socket_send(void *opaque
)
4712 NetSocketState
*s
= opaque
;
4717 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4719 err
= socket_error();
4720 if (err
!= EWOULDBLOCK
)
4722 } else if (size
== 0) {
4723 /* end of connection */
4725 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4731 /* reassemble a packet from the network */
4737 memcpy(s
->buf
+ s
->index
, buf
, l
);
4741 if (s
->index
== 4) {
4743 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4749 l
= s
->packet_len
- s
->index
;
4752 memcpy(s
->buf
+ s
->index
, buf
, l
);
4756 if (s
->index
>= s
->packet_len
) {
4757 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4766 static void net_socket_send_dgram(void *opaque
)
4768 NetSocketState
*s
= opaque
;
4771 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4775 /* end of connection */
4776 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4779 qemu_send_packet(s
->vc
, s
->buf
, size
);
4782 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4787 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4788 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4789 inet_ntoa(mcastaddr
->sin_addr
),
4790 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4794 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4796 perror("socket(PF_INET, SOCK_DGRAM)");
4801 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4802 (const char *)&val
, sizeof(val
));
4804 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4808 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4814 /* Add host to multicast group */
4815 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4816 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4818 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4819 (const char *)&imr
, sizeof(struct ip_mreq
));
4821 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4825 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4827 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4828 (const char *)&val
, sizeof(val
));
4830 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4834 socket_set_nonblock(fd
);
4842 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4845 struct sockaddr_in saddr
;
4847 socklen_t saddr_len
;
4850 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4851 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4852 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4856 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4858 if (saddr
.sin_addr
.s_addr
==0) {
4859 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4863 /* clone dgram socket */
4864 newfd
= net_socket_mcast_create(&saddr
);
4866 /* error already reported by net_socket_mcast_create() */
4870 /* clone newfd to fd, close newfd */
4875 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4876 fd
, strerror(errno
));
4881 s
= qemu_mallocz(sizeof(NetSocketState
));
4886 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4887 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4889 /* mcast: save bound address as dst */
4890 if (is_connected
) s
->dgram_dst
=saddr
;
4892 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4893 "socket: fd=%d (%s mcast=%s:%d)",
4894 fd
, is_connected
? "cloned" : "",
4895 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4899 static void net_socket_connect(void *opaque
)
4901 NetSocketState
*s
= opaque
;
4902 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4905 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4909 s
= qemu_mallocz(sizeof(NetSocketState
));
4913 s
->vc
= qemu_new_vlan_client(vlan
,
4914 net_socket_receive
, NULL
, s
);
4915 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4916 "socket: fd=%d", fd
);
4918 net_socket_connect(s
);
4920 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4925 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4928 int so_type
=-1, optlen
=sizeof(so_type
);
4930 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4931 (socklen_t
*)&optlen
)< 0) {
4932 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4937 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4939 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4941 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4942 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4943 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4948 static void net_socket_accept(void *opaque
)
4950 NetSocketListenState
*s
= opaque
;
4952 struct sockaddr_in saddr
;
4957 len
= sizeof(saddr
);
4958 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4959 if (fd
< 0 && errno
!= EINTR
) {
4961 } else if (fd
>= 0) {
4965 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4969 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4970 "socket: connection from %s:%d",
4971 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4975 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4977 NetSocketListenState
*s
;
4979 struct sockaddr_in saddr
;
4981 if (parse_host_port(&saddr
, host_str
) < 0)
4984 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4988 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4993 socket_set_nonblock(fd
);
4995 /* allow fast reuse */
4997 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
4999 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5004 ret
= listen(fd
, 0);
5011 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5015 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5018 int fd
, connected
, ret
, err
;
5019 struct sockaddr_in saddr
;
5021 if (parse_host_port(&saddr
, host_str
) < 0)
5024 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5029 socket_set_nonblock(fd
);
5033 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5035 err
= socket_error();
5036 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5037 } else if (err
== EINPROGRESS
) {
5040 } else if (err
== WSAEALREADY
) {
5053 s
= net_socket_fd_init(vlan
, fd
, connected
);
5056 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5057 "socket: connect to %s:%d",
5058 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5062 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5066 struct sockaddr_in saddr
;
5068 if (parse_host_port(&saddr
, host_str
) < 0)
5072 fd
= net_socket_mcast_create(&saddr
);
5076 s
= net_socket_fd_init(vlan
, fd
, 0);
5080 s
->dgram_dst
= saddr
;
5082 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5083 "socket: mcast=%s:%d",
5084 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5089 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5094 while (*p
!= '\0' && *p
!= '=') {
5095 if (q
&& (q
- buf
) < buf_size
- 1)
5105 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5110 while (*p
!= '\0') {
5112 if (*(p
+ 1) != ',')
5116 if (q
&& (q
- buf
) < buf_size
- 1)
5126 static int get_param_value(char *buf
, int buf_size
,
5127 const char *tag
, const char *str
)
5134 p
= get_opt_name(option
, sizeof(option
), p
);
5138 if (!strcmp(tag
, option
)) {
5139 (void)get_opt_value(buf
, buf_size
, p
);
5142 p
= get_opt_value(NULL
, 0, p
);
5151 static int check_params(char *buf
, int buf_size
,
5152 char **params
, const char *str
)
5159 p
= get_opt_name(buf
, buf_size
, p
);
5163 for(i
= 0; params
[i
] != NULL
; i
++)
5164 if (!strcmp(params
[i
], buf
))
5166 if (params
[i
] == NULL
)
5168 p
= get_opt_value(NULL
, 0, p
);
5176 static int net_client_init(const char *device
, const char *p
)
5183 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5184 vlan_id
= strtol(buf
, NULL
, 0);
5186 vlan
= qemu_find_vlan(vlan_id
);
5188 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5191 if (!strcmp(device
, "nic")) {
5195 if (nb_nics
>= MAX_NICS
) {
5196 fprintf(stderr
, "Too Many NICs\n");
5199 nd
= &nd_table
[nb_nics
];
5200 macaddr
= nd
->macaddr
;
5206 macaddr
[5] = 0x56 + nb_nics
;
5208 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5209 if (parse_macaddr(macaddr
, buf
) < 0) {
5210 fprintf(stderr
, "invalid syntax for ethernet address\n");
5214 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5215 nd
->model
= strdup(buf
);
5219 vlan
->nb_guest_devs
++;
5222 if (!strcmp(device
, "none")) {
5223 /* does nothing. It is needed to signal that no network cards
5228 if (!strcmp(device
, "user")) {
5229 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5230 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5232 vlan
->nb_host_devs
++;
5233 ret
= net_slirp_init(vlan
);
5237 if (!strcmp(device
, "tap")) {
5239 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5240 fprintf(stderr
, "tap: no interface name\n");
5243 vlan
->nb_host_devs
++;
5244 ret
= tap_win32_init(vlan
, ifname
);
5247 if (!strcmp(device
, "tap")) {
5249 char setup_script
[1024], down_script
[1024];
5251 vlan
->nb_host_devs
++;
5252 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5253 fd
= strtol(buf
, NULL
, 0);
5254 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5256 if (net_tap_fd_init(vlan
, fd
))
5259 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5262 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5263 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5265 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5266 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5268 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5272 if (!strcmp(device
, "socket")) {
5273 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5275 fd
= strtol(buf
, NULL
, 0);
5277 if (net_socket_fd_init(vlan
, fd
, 1))
5279 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5280 ret
= net_socket_listen_init(vlan
, buf
);
5281 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5282 ret
= net_socket_connect_init(vlan
, buf
);
5283 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5284 ret
= net_socket_mcast_init(vlan
, buf
);
5286 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5289 vlan
->nb_host_devs
++;
5292 if (!strcmp(device
, "vde")) {
5293 char vde_sock
[1024], vde_group
[512];
5294 int vde_port
, vde_mode
;
5295 vlan
->nb_host_devs
++;
5296 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5299 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5300 vde_port
= strtol(buf
, NULL
, 10);
5304 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5305 vde_group
[0] = '\0';
5307 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5308 vde_mode
= strtol(buf
, NULL
, 8);
5312 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5316 fprintf(stderr
, "Unknown network device: %s\n", device
);
5320 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5326 static int net_client_parse(const char *str
)
5334 while (*p
!= '\0' && *p
!= ',') {
5335 if ((q
- device
) < sizeof(device
) - 1)
5343 return net_client_init(device
, p
);
5346 void do_info_network(void)
5349 VLANClientState
*vc
;
5351 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5352 term_printf("VLAN %d devices:\n", vlan
->id
);
5353 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5354 term_printf(" %s\n", vc
->info_str
);
5358 #define HD_ALIAS "index=%d,media=disk"
5360 #define CDROM_ALIAS "index=1,media=cdrom"
5362 #define CDROM_ALIAS "index=2,media=cdrom"
5364 #define FD_ALIAS "index=%d,if=floppy"
5365 #define PFLASH_ALIAS "if=pflash"
5366 #define MTD_ALIAS "if=mtd"
5367 #define SD_ALIAS "index=0,if=sd"
5369 static int drive_add(const char *file
, const char *fmt
, ...)
5373 if (nb_drives_opt
>= MAX_DRIVES
) {
5374 fprintf(stderr
, "qemu: too many drives\n");
5378 drives_opt
[nb_drives_opt
].file
= file
;
5380 vsnprintf(drives_opt
[nb_drives_opt
].opt
,
5381 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5384 return nb_drives_opt
++;
5387 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5391 /* seek interface, bus and unit */
5393 for (index
= 0; index
< nb_drives
; index
++)
5394 if (drives_table
[index
].type
== type
&&
5395 drives_table
[index
].bus
== bus
&&
5396 drives_table
[index
].unit
== unit
)
5402 int drive_get_max_bus(BlockInterfaceType type
)
5408 for (index
= 0; index
< nb_drives
; index
++) {
5409 if(drives_table
[index
].type
== type
&&
5410 drives_table
[index
].bus
> max_bus
)
5411 max_bus
= drives_table
[index
].bus
;
5416 static void bdrv_format_print(void *opaque
, const char *name
)
5418 fprintf(stderr
, " %s", name
);
5421 static int drive_init(struct drive_opt
*arg
, int snapshot
,
5422 QEMUMachine
*machine
)
5427 const char *mediastr
= "";
5428 BlockInterfaceType type
;
5429 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5430 int bus_id
, unit_id
;
5431 int cyls
, heads
, secs
, translation
;
5432 BlockDriverState
*bdrv
;
5433 BlockDriver
*drv
= NULL
;
5438 char *str
= arg
->opt
;
5439 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
5440 "secs", "trans", "media", "snapshot", "file",
5441 "cache", "format", NULL
};
5443 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5444 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5450 cyls
= heads
= secs
= 0;
5453 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5457 if (!strcmp(machine
->name
, "realview") ||
5458 !strcmp(machine
->name
, "SS-5") ||
5459 !strcmp(machine
->name
, "SS-10") ||
5460 !strcmp(machine
->name
, "SS-600MP") ||
5461 !strcmp(machine
->name
, "versatilepb") ||
5462 !strcmp(machine
->name
, "versatileab")) {
5464 max_devs
= MAX_SCSI_DEVS
;
5465 pstrcpy(devname
, sizeof(devname
), "scsi");
5468 max_devs
= MAX_IDE_DEVS
;
5469 pstrcpy(devname
, sizeof(devname
), "ide");
5473 /* extract parameters */
5475 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5476 bus_id
= strtol(buf
, NULL
, 0);
5478 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5483 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5484 unit_id
= strtol(buf
, NULL
, 0);
5486 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5491 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5492 pstrcpy(devname
, sizeof(devname
), buf
);
5493 if (!strcmp(buf
, "ide")) {
5495 max_devs
= MAX_IDE_DEVS
;
5496 } else if (!strcmp(buf
, "scsi")) {
5498 max_devs
= MAX_SCSI_DEVS
;
5499 } else if (!strcmp(buf
, "floppy")) {
5502 } else if (!strcmp(buf
, "pflash")) {
5505 } else if (!strcmp(buf
, "mtd")) {
5508 } else if (!strcmp(buf
, "sd")) {
5512 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5517 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5518 index
= strtol(buf
, NULL
, 0);
5520 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5525 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5526 cyls
= strtol(buf
, NULL
, 0);
5529 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5530 heads
= strtol(buf
, NULL
, 0);
5533 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5534 secs
= strtol(buf
, NULL
, 0);
5537 if (cyls
|| heads
|| secs
) {
5538 if (cyls
< 1 || cyls
> 16383) {
5539 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5542 if (heads
< 1 || heads
> 16) {
5543 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5546 if (secs
< 1 || secs
> 63) {
5547 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5552 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5555 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5559 if (!strcmp(buf
, "none"))
5560 translation
= BIOS_ATA_TRANSLATION_NONE
;
5561 else if (!strcmp(buf
, "lba"))
5562 translation
= BIOS_ATA_TRANSLATION_LBA
;
5563 else if (!strcmp(buf
, "auto"))
5564 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5566 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5571 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5572 if (!strcmp(buf
, "disk")) {
5574 } else if (!strcmp(buf
, "cdrom")) {
5575 if (cyls
|| secs
|| heads
) {
5577 "qemu: '%s' invalid physical CHS format\n", str
);
5580 media
= MEDIA_CDROM
;
5582 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5587 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5588 if (!strcmp(buf
, "on"))
5590 else if (!strcmp(buf
, "off"))
5593 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5598 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5599 if (!strcmp(buf
, "off"))
5601 else if (!strcmp(buf
, "on"))
5604 fprintf(stderr
, "qemu: invalid cache option\n");
5609 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5610 if (strcmp(buf
, "?") == 0) {
5611 fprintf(stderr
, "qemu: Supported formats:");
5612 bdrv_iterate_format(bdrv_format_print
, NULL
);
5613 fprintf(stderr
, "\n");
5616 drv
= bdrv_find_format(buf
);
5618 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5623 if (arg
->file
== NULL
)
5624 get_param_value(file
, sizeof(file
), "file", str
);
5626 pstrcpy(file
, sizeof(file
), arg
->file
);
5628 /* compute bus and unit according index */
5631 if (bus_id
!= 0 || unit_id
!= -1) {
5633 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5641 unit_id
= index
% max_devs
;
5642 bus_id
= index
/ max_devs
;
5646 /* if user doesn't specify a unit_id,
5647 * try to find the first free
5650 if (unit_id
== -1) {
5652 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5654 if (max_devs
&& unit_id
>= max_devs
) {
5655 unit_id
-= max_devs
;
5663 if (max_devs
&& unit_id
>= max_devs
) {
5664 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5665 str
, unit_id
, max_devs
- 1);
5670 * ignore multiple definitions
5673 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5678 if (type
== IF_IDE
|| type
== IF_SCSI
)
5679 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5681 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5682 devname
, bus_id
, mediastr
, unit_id
);
5684 snprintf(buf
, sizeof(buf
), "%s%s%i",
5685 devname
, mediastr
, unit_id
);
5686 bdrv
= bdrv_new(buf
);
5687 drives_table
[nb_drives
].bdrv
= bdrv
;
5688 drives_table
[nb_drives
].type
= type
;
5689 drives_table
[nb_drives
].bus
= bus_id
;
5690 drives_table
[nb_drives
].unit
= unit_id
;
5699 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5700 bdrv_set_translation_hint(bdrv
, translation
);
5704 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5709 /* FIXME: This isn't really a floppy, but it's a reasonable
5712 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5722 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5724 bdrv_flags
|= BDRV_O_DIRECT
;
5725 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5726 fprintf(stderr
, "qemu: could not open disk image %s\n",
5733 /***********************************************************/
5736 static USBPort
*used_usb_ports
;
5737 static USBPort
*free_usb_ports
;
5739 /* ??? Maybe change this to register a hub to keep track of the topology. */
5740 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5741 usb_attachfn attach
)
5743 port
->opaque
= opaque
;
5744 port
->index
= index
;
5745 port
->attach
= attach
;
5746 port
->next
= free_usb_ports
;
5747 free_usb_ports
= port
;
5750 static int usb_device_add(const char *devname
)
5756 if (!free_usb_ports
)
5759 if (strstart(devname
, "host:", &p
)) {
5760 dev
= usb_host_device_open(p
);
5761 } else if (!strcmp(devname
, "mouse")) {
5762 dev
= usb_mouse_init();
5763 } else if (!strcmp(devname
, "tablet")) {
5764 dev
= usb_tablet_init();
5765 } else if (!strcmp(devname
, "keyboard")) {
5766 dev
= usb_keyboard_init();
5767 } else if (strstart(devname
, "disk:", &p
)) {
5768 dev
= usb_msd_init(p
);
5769 } else if (!strcmp(devname
, "wacom-tablet")) {
5770 dev
= usb_wacom_init();
5771 } else if (strstart(devname
, "serial:", &p
)) {
5772 dev
= usb_serial_init(p
);
5773 #ifdef CONFIG_BRLAPI
5774 } else if (!strcmp(devname
, "braille")) {
5775 dev
= usb_baum_init();
5777 } else if (strstart(devname
, "net:", &p
)) {
5780 if (net_client_init("nic", p
) < 0)
5782 nd_table
[nic
].model
= "usb";
5783 dev
= usb_net_init(&nd_table
[nic
]);
5790 /* Find a USB port to add the device to. */
5791 port
= free_usb_ports
;
5795 /* Create a new hub and chain it on. */
5796 free_usb_ports
= NULL
;
5797 port
->next
= used_usb_ports
;
5798 used_usb_ports
= port
;
5800 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5801 usb_attach(port
, hub
);
5802 port
= free_usb_ports
;
5805 free_usb_ports
= port
->next
;
5806 port
->next
= used_usb_ports
;
5807 used_usb_ports
= port
;
5808 usb_attach(port
, dev
);
5812 int usb_device_del_addr(int bus_num
, int addr
)
5818 if (!used_usb_ports
)
5824 lastp
= &used_usb_ports
;
5825 port
= used_usb_ports
;
5826 while (port
&& port
->dev
->addr
!= addr
) {
5827 lastp
= &port
->next
;
5835 *lastp
= port
->next
;
5836 usb_attach(port
, NULL
);
5837 dev
->handle_destroy(dev
);
5838 port
->next
= free_usb_ports
;
5839 free_usb_ports
= port
;
5843 static int usb_device_del(const char *devname
)
5848 if (!used_usb_ports
)
5851 p
= strchr(devname
, '.');
5854 bus_num
= strtoul(devname
, NULL
, 0);
5855 addr
= strtoul(p
+ 1, NULL
, 0);
5857 return usb_device_del_addr(bus_num
, addr
);
5860 void do_usb_add(const char *devname
)
5863 ret
= usb_device_add(devname
);
5865 term_printf("Could not add USB device '%s'\n", devname
);
5868 void do_usb_del(const char *devname
)
5871 ret
= usb_device_del(devname
);
5873 term_printf("Could not remove USB device '%s'\n", devname
);
5880 const char *speed_str
;
5883 term_printf("USB support not enabled\n");
5887 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5891 switch(dev
->speed
) {
5895 case USB_SPEED_FULL
:
5898 case USB_SPEED_HIGH
:
5905 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5906 0, dev
->addr
, speed_str
, dev
->devname
);
5910 /***********************************************************/
5911 /* PCMCIA/Cardbus */
5913 static struct pcmcia_socket_entry_s
{
5914 struct pcmcia_socket_s
*socket
;
5915 struct pcmcia_socket_entry_s
*next
;
5916 } *pcmcia_sockets
= 0;
5918 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5920 struct pcmcia_socket_entry_s
*entry
;
5922 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5923 entry
->socket
= socket
;
5924 entry
->next
= pcmcia_sockets
;
5925 pcmcia_sockets
= entry
;
5928 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5930 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5932 ptr
= &pcmcia_sockets
;
5933 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5934 if (entry
->socket
== socket
) {
5940 void pcmcia_info(void)
5942 struct pcmcia_socket_entry_s
*iter
;
5943 if (!pcmcia_sockets
)
5944 term_printf("No PCMCIA sockets\n");
5946 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5947 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5948 iter
->socket
->attached
? iter
->socket
->card_string
:
5952 /***********************************************************/
5955 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5959 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5963 static void dumb_refresh(DisplayState
*ds
)
5965 #if defined(CONFIG_SDL)
5970 static void dumb_display_init(DisplayState
*ds
)
5975 ds
->dpy_update
= dumb_update
;
5976 ds
->dpy_resize
= dumb_resize
;
5977 ds
->dpy_refresh
= dumb_refresh
;
5980 /***********************************************************/
5983 #define MAX_IO_HANDLERS 64
5985 typedef struct IOHandlerRecord
{
5987 IOCanRWHandler
*fd_read_poll
;
5989 IOHandler
*fd_write
;
5992 /* temporary data */
5994 struct IOHandlerRecord
*next
;
5997 static IOHandlerRecord
*first_io_handler
;
5999 /* XXX: fd_read_poll should be suppressed, but an API change is
6000 necessary in the character devices to suppress fd_can_read(). */
6001 int qemu_set_fd_handler2(int fd
,
6002 IOCanRWHandler
*fd_read_poll
,
6004 IOHandler
*fd_write
,
6007 IOHandlerRecord
**pioh
, *ioh
;
6009 if (!fd_read
&& !fd_write
) {
6010 pioh
= &first_io_handler
;
6015 if (ioh
->fd
== fd
) {
6022 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6026 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6029 ioh
->next
= first_io_handler
;
6030 first_io_handler
= ioh
;
6033 ioh
->fd_read_poll
= fd_read_poll
;
6034 ioh
->fd_read
= fd_read
;
6035 ioh
->fd_write
= fd_write
;
6036 ioh
->opaque
= opaque
;
6042 int qemu_set_fd_handler(int fd
,
6044 IOHandler
*fd_write
,
6047 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6050 /***********************************************************/
6051 /* Polling handling */
6053 typedef struct PollingEntry
{
6056 struct PollingEntry
*next
;
6059 static PollingEntry
*first_polling_entry
;
6061 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6063 PollingEntry
**ppe
, *pe
;
6064 pe
= qemu_mallocz(sizeof(PollingEntry
));
6068 pe
->opaque
= opaque
;
6069 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6074 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6076 PollingEntry
**ppe
, *pe
;
6077 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6079 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6088 /***********************************************************/
6089 /* Wait objects support */
6090 typedef struct WaitObjects
{
6092 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6093 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6094 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6097 static WaitObjects wait_objects
= {0};
6099 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6101 WaitObjects
*w
= &wait_objects
;
6103 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6105 w
->events
[w
->num
] = handle
;
6106 w
->func
[w
->num
] = func
;
6107 w
->opaque
[w
->num
] = opaque
;
6112 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6115 WaitObjects
*w
= &wait_objects
;
6118 for (i
= 0; i
< w
->num
; i
++) {
6119 if (w
->events
[i
] == handle
)
6122 w
->events
[i
] = w
->events
[i
+ 1];
6123 w
->func
[i
] = w
->func
[i
+ 1];
6124 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6132 /***********************************************************/
6133 /* savevm/loadvm support */
6135 #define IO_BUF_SIZE 32768
6139 BlockDriverState
*bs
;
6142 int64_t base_offset
;
6143 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6146 int buf_size
; /* 0 when writing */
6147 uint8_t buf
[IO_BUF_SIZE
];
6150 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
6154 f
= qemu_mallocz(sizeof(QEMUFile
));
6157 if (!strcmp(mode
, "wb")) {
6159 } else if (!strcmp(mode
, "rb")) {
6164 f
->outfile
= fopen(filename
, mode
);
6176 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6180 f
= qemu_mallocz(sizeof(QEMUFile
));
6185 f
->is_writable
= is_writable
;
6186 f
->base_offset
= offset
;
6190 void qemu_fflush(QEMUFile
*f
)
6192 if (!f
->is_writable
)
6194 if (f
->buf_index
> 0) {
6196 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6197 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
6199 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6200 f
->buf
, f
->buf_index
);
6202 f
->buf_offset
+= f
->buf_index
;
6207 static void qemu_fill_buffer(QEMUFile
*f
)
6214 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6215 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
6219 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6220 f
->buf
, IO_BUF_SIZE
);
6226 f
->buf_offset
+= len
;
6229 void qemu_fclose(QEMUFile
*f
)
6239 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6243 l
= IO_BUF_SIZE
- f
->buf_index
;
6246 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6250 if (f
->buf_index
>= IO_BUF_SIZE
)
6255 void qemu_put_byte(QEMUFile
*f
, int v
)
6257 f
->buf
[f
->buf_index
++] = v
;
6258 if (f
->buf_index
>= IO_BUF_SIZE
)
6262 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6268 l
= f
->buf_size
- f
->buf_index
;
6270 qemu_fill_buffer(f
);
6271 l
= f
->buf_size
- f
->buf_index
;
6277 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6282 return size1
- size
;
6285 int qemu_get_byte(QEMUFile
*f
)
6287 if (f
->buf_index
>= f
->buf_size
) {
6288 qemu_fill_buffer(f
);
6289 if (f
->buf_index
>= f
->buf_size
)
6292 return f
->buf
[f
->buf_index
++];
6295 int64_t qemu_ftell(QEMUFile
*f
)
6297 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6300 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6302 if (whence
== SEEK_SET
) {
6304 } else if (whence
== SEEK_CUR
) {
6305 pos
+= qemu_ftell(f
);
6307 /* SEEK_END not supported */
6310 if (f
->is_writable
) {
6312 f
->buf_offset
= pos
;
6314 f
->buf_offset
= pos
;
6321 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6323 qemu_put_byte(f
, v
>> 8);
6324 qemu_put_byte(f
, v
);
6327 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6329 qemu_put_byte(f
, v
>> 24);
6330 qemu_put_byte(f
, v
>> 16);
6331 qemu_put_byte(f
, v
>> 8);
6332 qemu_put_byte(f
, v
);
6335 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6337 qemu_put_be32(f
, v
>> 32);
6338 qemu_put_be32(f
, v
);
6341 unsigned int qemu_get_be16(QEMUFile
*f
)
6344 v
= qemu_get_byte(f
) << 8;
6345 v
|= qemu_get_byte(f
);
6349 unsigned int qemu_get_be32(QEMUFile
*f
)
6352 v
= qemu_get_byte(f
) << 24;
6353 v
|= qemu_get_byte(f
) << 16;
6354 v
|= qemu_get_byte(f
) << 8;
6355 v
|= qemu_get_byte(f
);
6359 uint64_t qemu_get_be64(QEMUFile
*f
)
6362 v
= (uint64_t)qemu_get_be32(f
) << 32;
6363 v
|= qemu_get_be32(f
);
6367 typedef struct SaveStateEntry
{
6371 SaveStateHandler
*save_state
;
6372 LoadStateHandler
*load_state
;
6374 struct SaveStateEntry
*next
;
6377 static SaveStateEntry
*first_se
;
6379 /* TODO: Individual devices generally have very little idea about the rest
6380 of the system, so instance_id should be removed/replaced.
6381 Meanwhile pass -1 as instance_id if you do not already have a clearly
6382 distinguishing id for all instances of your device class. */
6383 int register_savevm(const char *idstr
,
6386 SaveStateHandler
*save_state
,
6387 LoadStateHandler
*load_state
,
6390 SaveStateEntry
*se
, **pse
;
6392 se
= qemu_malloc(sizeof(SaveStateEntry
));
6395 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6396 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6397 se
->version_id
= version_id
;
6398 se
->save_state
= save_state
;
6399 se
->load_state
= load_state
;
6400 se
->opaque
= opaque
;
6403 /* add at the end of list */
6405 while (*pse
!= NULL
) {
6406 if (instance_id
== -1
6407 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6408 && se
->instance_id
<= (*pse
)->instance_id
)
6409 se
->instance_id
= (*pse
)->instance_id
+ 1;
6410 pse
= &(*pse
)->next
;
6416 #define QEMU_VM_FILE_MAGIC 0x5145564d
6417 #define QEMU_VM_FILE_VERSION 0x00000002
6419 static int qemu_savevm_state(QEMUFile
*f
)
6423 int64_t cur_pos
, len_pos
, total_len_pos
;
6425 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6426 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6427 total_len_pos
= qemu_ftell(f
);
6428 qemu_put_be64(f
, 0); /* total size */
6430 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6431 if (se
->save_state
== NULL
)
6432 /* this one has a loader only, for backwards compatibility */
6436 len
= strlen(se
->idstr
);
6437 qemu_put_byte(f
, len
);
6438 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6440 qemu_put_be32(f
, se
->instance_id
);
6441 qemu_put_be32(f
, se
->version_id
);
6443 /* record size: filled later */
6444 len_pos
= qemu_ftell(f
);
6445 qemu_put_be32(f
, 0);
6446 se
->save_state(f
, se
->opaque
);
6448 /* fill record size */
6449 cur_pos
= qemu_ftell(f
);
6450 len
= cur_pos
- len_pos
- 4;
6451 qemu_fseek(f
, len_pos
, SEEK_SET
);
6452 qemu_put_be32(f
, len
);
6453 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6455 cur_pos
= qemu_ftell(f
);
6456 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6457 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6458 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6464 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6468 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6469 if (!strcmp(se
->idstr
, idstr
) &&
6470 instance_id
== se
->instance_id
)
6476 static int qemu_loadvm_state(QEMUFile
*f
)
6479 int len
, ret
, instance_id
, record_len
, version_id
;
6480 int64_t total_len
, end_pos
, cur_pos
;
6484 v
= qemu_get_be32(f
);
6485 if (v
!= QEMU_VM_FILE_MAGIC
)
6487 v
= qemu_get_be32(f
);
6488 if (v
!= QEMU_VM_FILE_VERSION
) {
6493 total_len
= qemu_get_be64(f
);
6494 end_pos
= total_len
+ qemu_ftell(f
);
6496 if (qemu_ftell(f
) >= end_pos
)
6498 len
= qemu_get_byte(f
);
6499 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6501 instance_id
= qemu_get_be32(f
);
6502 version_id
= qemu_get_be32(f
);
6503 record_len
= qemu_get_be32(f
);
6505 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6506 idstr
, instance_id
, version_id
, record_len
);
6508 cur_pos
= qemu_ftell(f
);
6509 se
= find_se(idstr
, instance_id
);
6511 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6512 instance_id
, idstr
);
6514 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6516 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6517 instance_id
, idstr
);
6520 /* always seek to exact end of record */
6521 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6528 /* device can contain snapshots */
6529 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6532 !bdrv_is_removable(bs
) &&
6533 !bdrv_is_read_only(bs
));
6536 /* device must be snapshots in order to have a reliable snapshot */
6537 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6540 !bdrv_is_removable(bs
) &&
6541 !bdrv_is_read_only(bs
));
6544 static BlockDriverState
*get_bs_snapshots(void)
6546 BlockDriverState
*bs
;
6550 return bs_snapshots
;
6551 for(i
= 0; i
<= nb_drives
; i
++) {
6552 bs
= drives_table
[i
].bdrv
;
6553 if (bdrv_can_snapshot(bs
))
6562 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6565 QEMUSnapshotInfo
*sn_tab
, *sn
;
6569 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6572 for(i
= 0; i
< nb_sns
; i
++) {
6574 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6584 void do_savevm(const char *name
)
6586 BlockDriverState
*bs
, *bs1
;
6587 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6588 int must_delete
, ret
, i
;
6589 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6591 int saved_vm_running
;
6598 bs
= get_bs_snapshots();
6600 term_printf("No block device can accept snapshots\n");
6604 /* ??? Should this occur after vm_stop? */
6607 saved_vm_running
= vm_running
;
6612 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6617 memset(sn
, 0, sizeof(*sn
));
6619 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6620 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6623 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6626 /* fill auxiliary fields */
6629 sn
->date_sec
= tb
.time
;
6630 sn
->date_nsec
= tb
.millitm
* 1000000;
6632 gettimeofday(&tv
, NULL
);
6633 sn
->date_sec
= tv
.tv_sec
;
6634 sn
->date_nsec
= tv
.tv_usec
* 1000;
6636 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6638 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6639 term_printf("Device %s does not support VM state snapshots\n",
6640 bdrv_get_device_name(bs
));
6644 /* save the VM state */
6645 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6647 term_printf("Could not open VM state file\n");
6650 ret
= qemu_savevm_state(f
);
6651 sn
->vm_state_size
= qemu_ftell(f
);
6654 term_printf("Error %d while writing VM\n", ret
);
6658 /* create the snapshots */
6660 for(i
= 0; i
< nb_drives
; i
++) {
6661 bs1
= drives_table
[i
].bdrv
;
6662 if (bdrv_has_snapshot(bs1
)) {
6664 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6666 term_printf("Error while deleting snapshot on '%s'\n",
6667 bdrv_get_device_name(bs1
));
6670 ret
= bdrv_snapshot_create(bs1
, sn
);
6672 term_printf("Error while creating snapshot on '%s'\n",
6673 bdrv_get_device_name(bs1
));
6679 if (saved_vm_running
)
6683 void do_loadvm(const char *name
)
6685 BlockDriverState
*bs
, *bs1
;
6686 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6689 int saved_vm_running
;
6691 bs
= get_bs_snapshots();
6693 term_printf("No block device supports snapshots\n");
6697 /* Flush all IO requests so they don't interfere with the new state. */
6700 saved_vm_running
= vm_running
;
6703 for(i
= 0; i
<= nb_drives
; i
++) {
6704 bs1
= drives_table
[i
].bdrv
;
6705 if (bdrv_has_snapshot(bs1
)) {
6706 ret
= bdrv_snapshot_goto(bs1
, name
);
6709 term_printf("Warning: ");
6712 term_printf("Snapshots not supported on device '%s'\n",
6713 bdrv_get_device_name(bs1
));
6716 term_printf("Could not find snapshot '%s' on device '%s'\n",
6717 name
, bdrv_get_device_name(bs1
));
6720 term_printf("Error %d while activating snapshot on '%s'\n",
6721 ret
, bdrv_get_device_name(bs1
));
6724 /* fatal on snapshot block device */
6731 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6732 term_printf("Device %s does not support VM state snapshots\n",
6733 bdrv_get_device_name(bs
));
6737 /* restore the VM state */
6738 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6740 term_printf("Could not open VM state file\n");
6743 ret
= qemu_loadvm_state(f
);
6746 term_printf("Error %d while loading VM state\n", ret
);
6749 if (saved_vm_running
)
6753 void do_delvm(const char *name
)
6755 BlockDriverState
*bs
, *bs1
;
6758 bs
= get_bs_snapshots();
6760 term_printf("No block device supports snapshots\n");
6764 for(i
= 0; i
<= nb_drives
; i
++) {
6765 bs1
= drives_table
[i
].bdrv
;
6766 if (bdrv_has_snapshot(bs1
)) {
6767 ret
= bdrv_snapshot_delete(bs1
, name
);
6769 if (ret
== -ENOTSUP
)
6770 term_printf("Snapshots not supported on device '%s'\n",
6771 bdrv_get_device_name(bs1
));
6773 term_printf("Error %d while deleting snapshot on '%s'\n",
6774 ret
, bdrv_get_device_name(bs1
));
6780 void do_info_snapshots(void)
6782 BlockDriverState
*bs
, *bs1
;
6783 QEMUSnapshotInfo
*sn_tab
, *sn
;
6787 bs
= get_bs_snapshots();
6789 term_printf("No available block device supports snapshots\n");
6792 term_printf("Snapshot devices:");
6793 for(i
= 0; i
<= nb_drives
; i
++) {
6794 bs1
= drives_table
[i
].bdrv
;
6795 if (bdrv_has_snapshot(bs1
)) {
6797 term_printf(" %s", bdrv_get_device_name(bs1
));
6802 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6804 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6807 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6808 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6809 for(i
= 0; i
< nb_sns
; i
++) {
6811 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6816 /***********************************************************/
6817 /* ram save/restore */
6819 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6823 v
= qemu_get_byte(f
);
6826 if (qemu_get_buffer(f
, buf
, len
) != len
)
6830 v
= qemu_get_byte(f
);
6831 memset(buf
, v
, len
);
6839 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6844 if (qemu_get_be32(f
) != phys_ram_size
)
6846 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6847 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6854 #define BDRV_HASH_BLOCK_SIZE 1024
6855 #define IOBUF_SIZE 4096
6856 #define RAM_CBLOCK_MAGIC 0xfabe
6858 typedef struct RamCompressState
{
6861 uint8_t buf
[IOBUF_SIZE
];
6864 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6867 memset(s
, 0, sizeof(*s
));
6869 ret
= deflateInit2(&s
->zstream
, 1,
6871 9, Z_DEFAULT_STRATEGY
);
6874 s
->zstream
.avail_out
= IOBUF_SIZE
;
6875 s
->zstream
.next_out
= s
->buf
;
6879 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6881 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6882 qemu_put_be16(s
->f
, len
);
6883 qemu_put_buffer(s
->f
, buf
, len
);
6886 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6890 s
->zstream
.avail_in
= len
;
6891 s
->zstream
.next_in
= (uint8_t *)buf
;
6892 while (s
->zstream
.avail_in
> 0) {
6893 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6896 if (s
->zstream
.avail_out
== 0) {
6897 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6898 s
->zstream
.avail_out
= IOBUF_SIZE
;
6899 s
->zstream
.next_out
= s
->buf
;
6905 static void ram_compress_close(RamCompressState
*s
)
6909 /* compress last bytes */
6911 ret
= deflate(&s
->zstream
, Z_FINISH
);
6912 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6913 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6915 ram_put_cblock(s
, s
->buf
, len
);
6917 s
->zstream
.avail_out
= IOBUF_SIZE
;
6918 s
->zstream
.next_out
= s
->buf
;
6919 if (ret
== Z_STREAM_END
)
6926 deflateEnd(&s
->zstream
);
6929 typedef struct RamDecompressState
{
6932 uint8_t buf
[IOBUF_SIZE
];
6933 } RamDecompressState
;
6935 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6938 memset(s
, 0, sizeof(*s
));
6940 ret
= inflateInit(&s
->zstream
);
6946 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6950 s
->zstream
.avail_out
= len
;
6951 s
->zstream
.next_out
= buf
;
6952 while (s
->zstream
.avail_out
> 0) {
6953 if (s
->zstream
.avail_in
== 0) {
6954 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6956 clen
= qemu_get_be16(s
->f
);
6957 if (clen
> IOBUF_SIZE
)
6959 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6960 s
->zstream
.avail_in
= clen
;
6961 s
->zstream
.next_in
= s
->buf
;
6963 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6964 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6971 static void ram_decompress_close(RamDecompressState
*s
)
6973 inflateEnd(&s
->zstream
);
6976 static void ram_save(QEMUFile
*f
, void *opaque
)
6979 RamCompressState s1
, *s
= &s1
;
6982 qemu_put_be32(f
, phys_ram_size
);
6983 if (ram_compress_open(s
, f
) < 0)
6985 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6987 if (tight_savevm_enabled
) {
6991 /* find if the memory block is available on a virtual
6994 for(j
= 0; j
< nb_drives
; j
++) {
6995 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
6997 BDRV_HASH_BLOCK_SIZE
);
6998 if (sector_num
>= 0)
7002 goto normal_compress
;
7005 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7006 ram_compress_buf(s
, buf
, 10);
7012 ram_compress_buf(s
, buf
, 1);
7013 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7016 ram_compress_close(s
);
7019 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7021 RamDecompressState s1
, *s
= &s1
;
7025 if (version_id
== 1)
7026 return ram_load_v1(f
, opaque
);
7027 if (version_id
!= 2)
7029 if (qemu_get_be32(f
) != phys_ram_size
)
7031 if (ram_decompress_open(s
, f
) < 0)
7033 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7034 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7035 fprintf(stderr
, "Error while reading ram block header\n");
7039 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7040 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7049 ram_decompress_buf(s
, buf
+ 1, 9);
7051 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7052 if (bs_index
>= nb_drives
) {
7053 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7056 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7058 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7059 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7060 bs_index
, sector_num
);
7067 printf("Error block header\n");
7071 ram_decompress_close(s
);
7075 /***********************************************************/
7076 /* bottom halves (can be seen as timers which expire ASAP) */
7085 static QEMUBH
*first_bh
= NULL
;
7087 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7090 bh
= qemu_mallocz(sizeof(QEMUBH
));
7094 bh
->opaque
= opaque
;
7098 int qemu_bh_poll(void)
7117 void qemu_bh_schedule(QEMUBH
*bh
)
7119 CPUState
*env
= cpu_single_env
;
7123 bh
->next
= first_bh
;
7126 /* stop the currently executing CPU to execute the BH ASAP */
7128 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7132 void qemu_bh_cancel(QEMUBH
*bh
)
7135 if (bh
->scheduled
) {
7138 pbh
= &(*pbh
)->next
;
7144 void qemu_bh_delete(QEMUBH
*bh
)
7150 /***********************************************************/
7151 /* machine registration */
7153 QEMUMachine
*first_machine
= NULL
;
7155 int qemu_register_machine(QEMUMachine
*m
)
7158 pm
= &first_machine
;
7166 static QEMUMachine
*find_machine(const char *name
)
7170 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7171 if (!strcmp(m
->name
, name
))
7177 /***********************************************************/
7178 /* main execution loop */
7180 static void gui_update(void *opaque
)
7182 DisplayState
*ds
= opaque
;
7183 ds
->dpy_refresh(ds
);
7184 qemu_mod_timer(ds
->gui_timer
,
7185 (ds
->gui_timer_interval
?
7186 ds
->gui_timer_interval
:
7187 GUI_REFRESH_INTERVAL
)
7188 + qemu_get_clock(rt_clock
));
7191 struct vm_change_state_entry
{
7192 VMChangeStateHandler
*cb
;
7194 LIST_ENTRY (vm_change_state_entry
) entries
;
7197 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7199 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7202 VMChangeStateEntry
*e
;
7204 e
= qemu_mallocz(sizeof (*e
));
7210 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7214 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7216 LIST_REMOVE (e
, entries
);
7220 static void vm_state_notify(int running
)
7222 VMChangeStateEntry
*e
;
7224 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7225 e
->cb(e
->opaque
, running
);
7229 /* XXX: support several handlers */
7230 static VMStopHandler
*vm_stop_cb
;
7231 static void *vm_stop_opaque
;
7233 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7236 vm_stop_opaque
= opaque
;
7240 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7251 qemu_rearm_alarm_timer(alarm_timer
);
7255 void vm_stop(int reason
)
7258 cpu_disable_ticks();
7262 vm_stop_cb(vm_stop_opaque
, reason
);
7269 /* reset/shutdown handler */
7271 typedef struct QEMUResetEntry
{
7272 QEMUResetHandler
*func
;
7274 struct QEMUResetEntry
*next
;
7277 static QEMUResetEntry
*first_reset_entry
;
7278 static int reset_requested
;
7279 static int shutdown_requested
;
7280 static int powerdown_requested
;
7282 int qemu_shutdown_requested(void)
7284 int r
= shutdown_requested
;
7285 shutdown_requested
= 0;
7289 int qemu_reset_requested(void)
7291 int r
= reset_requested
;
7292 reset_requested
= 0;
7296 int qemu_powerdown_requested(void)
7298 int r
= powerdown_requested
;
7299 powerdown_requested
= 0;
7303 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7305 QEMUResetEntry
**pre
, *re
;
7307 pre
= &first_reset_entry
;
7308 while (*pre
!= NULL
)
7309 pre
= &(*pre
)->next
;
7310 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7312 re
->opaque
= opaque
;
7317 void qemu_system_reset(void)
7321 /* reset all devices */
7322 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7323 re
->func(re
->opaque
);
7327 void qemu_system_reset_request(void)
7330 shutdown_requested
= 1;
7332 reset_requested
= 1;
7335 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7338 void qemu_system_shutdown_request(void)
7340 shutdown_requested
= 1;
7342 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7345 void qemu_system_powerdown_request(void)
7347 powerdown_requested
= 1;
7349 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7352 void main_loop_wait(int timeout
)
7354 IOHandlerRecord
*ioh
;
7355 fd_set rfds
, wfds
, xfds
;
7364 /* XXX: need to suppress polling by better using win32 events */
7366 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7367 ret
|= pe
->func(pe
->opaque
);
7372 WaitObjects
*w
= &wait_objects
;
7374 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7375 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7376 if (w
->func
[ret
- WAIT_OBJECT_0
])
7377 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7379 /* Check for additional signaled events */
7380 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7382 /* Check if event is signaled */
7383 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7384 if(ret2
== WAIT_OBJECT_0
) {
7386 w
->func
[i
](w
->opaque
[i
]);
7387 } else if (ret2
== WAIT_TIMEOUT
) {
7389 err
= GetLastError();
7390 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7393 } else if (ret
== WAIT_TIMEOUT
) {
7395 err
= GetLastError();
7396 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7400 /* poll any events */
7401 /* XXX: separate device handlers from system ones */
7406 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7410 (!ioh
->fd_read_poll
||
7411 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7412 FD_SET(ioh
->fd
, &rfds
);
7416 if (ioh
->fd_write
) {
7417 FD_SET(ioh
->fd
, &wfds
);
7427 tv
.tv_usec
= timeout
* 1000;
7429 #if defined(CONFIG_SLIRP)
7431 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7434 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7436 IOHandlerRecord
**pioh
;
7438 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7439 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7440 ioh
->fd_read(ioh
->opaque
);
7442 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7443 ioh
->fd_write(ioh
->opaque
);
7447 /* remove deleted IO handlers */
7448 pioh
= &first_io_handler
;
7458 #if defined(CONFIG_SLIRP)
7465 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7471 if (likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7472 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7473 qemu_get_clock(vm_clock
));
7474 /* run dma transfers, if any */
7478 /* real time timers */
7479 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7480 qemu_get_clock(rt_clock
));
7482 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7483 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7484 qemu_rearm_alarm_timer(alarm_timer
);
7487 /* Check bottom-halves last in case any of the earlier events triggered
7493 static int main_loop(void)
7496 #ifdef CONFIG_PROFILER
7501 cur_cpu
= first_cpu
;
7502 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7509 #ifdef CONFIG_PROFILER
7510 ti
= profile_getclock();
7515 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7516 env
->icount_decr
.u16
.low
= 0;
7517 env
->icount_extra
= 0;
7518 count
= qemu_next_deadline();
7519 count
= (count
+ (1 << icount_time_shift
) - 1)
7520 >> icount_time_shift
;
7521 qemu_icount
+= count
;
7522 decr
= (count
> 0xffff) ? 0xffff : count
;
7524 env
->icount_decr
.u16
.low
= decr
;
7525 env
->icount_extra
= count
;
7527 ret
= cpu_exec(env
);
7528 #ifdef CONFIG_PROFILER
7529 qemu_time
+= profile_getclock() - ti
;
7532 /* Fold pending instructions back into the
7533 instruction counter, and clear the interrupt flag. */
7534 qemu_icount
-= (env
->icount_decr
.u16
.low
7535 + env
->icount_extra
);
7536 env
->icount_decr
.u32
= 0;
7537 env
->icount_extra
= 0;
7539 next_cpu
= env
->next_cpu
?: first_cpu
;
7540 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7541 ret
= EXCP_INTERRUPT
;
7545 if (ret
== EXCP_HLT
) {
7546 /* Give the next CPU a chance to run. */
7550 if (ret
!= EXCP_HALTED
)
7552 /* all CPUs are halted ? */
7558 if (shutdown_requested
) {
7559 ret
= EXCP_INTERRUPT
;
7567 if (reset_requested
) {
7568 reset_requested
= 0;
7569 qemu_system_reset();
7570 ret
= EXCP_INTERRUPT
;
7572 if (powerdown_requested
) {
7573 powerdown_requested
= 0;
7574 qemu_system_powerdown();
7575 ret
= EXCP_INTERRUPT
;
7577 if (unlikely(ret
== EXCP_DEBUG
)) {
7578 vm_stop(EXCP_DEBUG
);
7580 /* If all cpus are halted then wait until the next IRQ */
7581 /* XXX: use timeout computed from timers */
7582 if (ret
== EXCP_HALTED
) {
7586 /* Advance virtual time to the next event. */
7587 if (use_icount
== 1) {
7588 /* When not using an adaptive execution frequency
7589 we tend to get badly out of sync with real time,
7590 so just delay for a reasonable amount of time. */
7593 delta
= cpu_get_icount() - cpu_get_clock();
7596 /* If virtual time is ahead of real time then just
7598 timeout
= (delta
/ 1000000) + 1;
7600 /* Wait for either IO to occur or the next
7602 add
= qemu_next_deadline();
7603 /* We advance the timer before checking for IO.
7604 Limit the amount we advance so that early IO
7605 activity won't get the guest too far ahead. */
7609 add
= (add
+ (1 << icount_time_shift
) - 1)
7610 >> icount_time_shift
;
7612 timeout
= delta
/ 1000000;
7625 #ifdef CONFIG_PROFILER
7626 ti
= profile_getclock();
7628 main_loop_wait(timeout
);
7629 #ifdef CONFIG_PROFILER
7630 dev_time
+= profile_getclock() - ti
;
7633 cpu_disable_ticks();
7637 static void help(int exitcode
)
7639 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7640 "usage: %s [options] [disk_image]\n"
7642 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7644 "Standard options:\n"
7645 "-M machine select emulated machine (-M ? for list)\n"
7646 "-cpu cpu select CPU (-cpu ? for list)\n"
7647 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7648 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7649 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7650 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7651 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7652 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7653 " [,cache=on|off][,format=f]\n"
7654 " use 'file' as a drive image\n"
7655 "-mtdblock file use 'file' as on-board Flash memory image\n"
7656 "-sd file use 'file' as SecureDigital card image\n"
7657 "-pflash file use 'file' as a parallel flash image\n"
7658 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7659 "-snapshot write to temporary files instead of disk image files\n"
7661 "-no-frame open SDL window without a frame and window decorations\n"
7662 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7663 "-no-quit disable SDL window close capability\n"
7666 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7668 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7669 "-smp n set the number of CPUs to 'n' [default=1]\n"
7670 "-nographic disable graphical output and redirect serial I/Os to console\n"
7671 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7673 "-k language use keyboard layout (for example \"fr\" for French)\n"
7676 "-audio-help print list of audio drivers and their options\n"
7677 "-soundhw c1,... enable audio support\n"
7678 " and only specified sound cards (comma separated list)\n"
7679 " use -soundhw ? to get the list of supported cards\n"
7680 " use -soundhw all to enable all of them\n"
7682 "-localtime set the real time clock to local time [default=utc]\n"
7683 "-full-screen start in full screen\n"
7685 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7687 "-usb enable the USB driver (will be the default soon)\n"
7688 "-usbdevice name add the host or guest USB device 'name'\n"
7689 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7690 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7692 "-name string set the name of the guest\n"
7694 "Network options:\n"
7695 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7696 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7698 "-net user[,vlan=n][,hostname=host]\n"
7699 " connect the user mode network stack to VLAN 'n' and send\n"
7700 " hostname 'host' to DHCP clients\n"
7703 "-net tap[,vlan=n],ifname=name\n"
7704 " connect the host TAP network interface to VLAN 'n'\n"
7706 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7707 " connect the host TAP network interface to VLAN 'n' and use the\n"
7708 " network scripts 'file' (default=%s)\n"
7709 " and 'dfile' (default=%s);\n"
7710 " use '[down]script=no' to disable script execution;\n"
7711 " use 'fd=h' to connect to an already opened TAP interface\n"
7713 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7714 " connect the vlan 'n' to another VLAN using a socket connection\n"
7715 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7716 " connect the vlan 'n' to multicast maddr and port\n"
7718 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7719 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7720 " on host and listening for incoming connections on 'socketpath'.\n"
7721 " Use group 'groupname' and mode 'octalmode' to change default\n"
7722 " ownership and permissions for communication port.\n"
7724 "-net none use it alone to have zero network devices; if no -net option\n"
7725 " is provided, the default is '-net nic -net user'\n"
7728 "-tftp dir allow tftp access to files in dir [-net user]\n"
7729 "-bootp file advertise file in BOOTP replies\n"
7731 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7733 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7734 " redirect TCP or UDP connections from host to guest [-net user]\n"
7737 "Linux boot specific:\n"
7738 "-kernel bzImage use 'bzImage' as kernel image\n"
7739 "-append cmdline use 'cmdline' as kernel command line\n"
7740 "-initrd file use 'file' as initial ram disk\n"
7742 "Debug/Expert options:\n"
7743 "-monitor dev redirect the monitor to char device 'dev'\n"
7744 "-serial dev redirect the serial port to char device 'dev'\n"
7745 "-parallel dev redirect the parallel port to char device 'dev'\n"
7746 "-pidfile file Write PID to 'file'\n"
7747 "-S freeze CPU at startup (use 'c' to start execution)\n"
7748 "-s wait gdb connection to port\n"
7749 "-p port set gdb connection port [default=%s]\n"
7750 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7751 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7752 " translation (t=none or lba) (usually qemu can guess them)\n"
7753 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7755 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7756 "-no-kqemu disable KQEMU kernel module usage\n"
7759 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7760 " (default is CL-GD5446 PCI VGA)\n"
7761 "-no-acpi disable ACPI\n"
7763 #ifdef CONFIG_CURSES
7764 "-curses use a curses/ncurses interface instead of SDL\n"
7766 "-no-reboot exit instead of rebooting\n"
7767 "-no-shutdown stop before shutdown\n"
7768 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7769 "-vnc display start a VNC server on display\n"
7771 "-daemonize daemonize QEMU after initializing\n"
7773 "-option-rom rom load a file, rom, into the option ROM space\n"
7775 "-prom-env variable=value set OpenBIOS nvram variables\n"
7777 "-clock force the use of the given methods for timer alarm.\n"
7778 " To see what timers are available use -clock ?\n"
7779 "-startdate select initial date of the clock\n"
7780 "-icount [N|auto]\n"
7781 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7783 "During emulation, the following keys are useful:\n"
7784 "ctrl-alt-f toggle full screen\n"
7785 "ctrl-alt-n switch to virtual console 'n'\n"
7786 "ctrl-alt toggle mouse and keyboard grab\n"
7788 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7793 DEFAULT_NETWORK_SCRIPT
,
7794 DEFAULT_NETWORK_DOWN_SCRIPT
,
7796 DEFAULT_GDBSTUB_PORT
,
7801 #define HAS_ARG 0x0001
7816 QEMU_OPTION_mtdblock
,
7820 QEMU_OPTION_snapshot
,
7822 QEMU_OPTION_no_fd_bootchk
,
7825 QEMU_OPTION_nographic
,
7826 QEMU_OPTION_portrait
,
7828 QEMU_OPTION_audio_help
,
7829 QEMU_OPTION_soundhw
,
7850 QEMU_OPTION_localtime
,
7851 QEMU_OPTION_cirrusvga
,
7854 QEMU_OPTION_std_vga
,
7856 QEMU_OPTION_monitor
,
7858 QEMU_OPTION_parallel
,
7860 QEMU_OPTION_full_screen
,
7861 QEMU_OPTION_no_frame
,
7862 QEMU_OPTION_alt_grab
,
7863 QEMU_OPTION_no_quit
,
7864 QEMU_OPTION_pidfile
,
7865 QEMU_OPTION_no_kqemu
,
7866 QEMU_OPTION_kernel_kqemu
,
7867 QEMU_OPTION_win2k_hack
,
7869 QEMU_OPTION_usbdevice
,
7872 QEMU_OPTION_no_acpi
,
7874 QEMU_OPTION_no_reboot
,
7875 QEMU_OPTION_no_shutdown
,
7876 QEMU_OPTION_show_cursor
,
7877 QEMU_OPTION_daemonize
,
7878 QEMU_OPTION_option_rom
,
7879 QEMU_OPTION_semihosting
,
7881 QEMU_OPTION_prom_env
,
7882 QEMU_OPTION_old_param
,
7884 QEMU_OPTION_startdate
,
7885 QEMU_OPTION_tb_size
,
7889 typedef struct QEMUOption
{
7895 const QEMUOption qemu_options
[] = {
7896 { "h", 0, QEMU_OPTION_h
},
7897 { "help", 0, QEMU_OPTION_h
},
7899 { "M", HAS_ARG
, QEMU_OPTION_M
},
7900 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7901 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7902 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7903 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7904 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7905 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7906 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7907 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7908 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7909 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7910 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7911 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7912 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7913 { "snapshot", 0, QEMU_OPTION_snapshot
},
7915 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7917 { "m", HAS_ARG
, QEMU_OPTION_m
},
7918 { "nographic", 0, QEMU_OPTION_nographic
},
7919 { "portrait", 0, QEMU_OPTION_portrait
},
7920 { "k", HAS_ARG
, QEMU_OPTION_k
},
7922 { "audio-help", 0, QEMU_OPTION_audio_help
},
7923 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7926 { "net", HAS_ARG
, QEMU_OPTION_net
},
7928 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7929 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7931 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7933 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7936 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7937 { "append", HAS_ARG
, QEMU_OPTION_append
},
7938 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7940 { "S", 0, QEMU_OPTION_S
},
7941 { "s", 0, QEMU_OPTION_s
},
7942 { "p", HAS_ARG
, QEMU_OPTION_p
},
7943 { "d", HAS_ARG
, QEMU_OPTION_d
},
7944 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7945 { "L", HAS_ARG
, QEMU_OPTION_L
},
7946 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7948 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7949 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7951 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7952 { "g", 1, QEMU_OPTION_g
},
7954 { "localtime", 0, QEMU_OPTION_localtime
},
7955 { "std-vga", 0, QEMU_OPTION_std_vga
},
7956 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7957 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7958 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7959 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7960 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7961 { "full-screen", 0, QEMU_OPTION_full_screen
},
7963 { "no-frame", 0, QEMU_OPTION_no_frame
},
7964 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7965 { "no-quit", 0, QEMU_OPTION_no_quit
},
7967 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7968 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7969 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7970 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7971 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7972 #ifdef CONFIG_CURSES
7973 { "curses", 0, QEMU_OPTION_curses
},
7976 /* temporary options */
7977 { "usb", 0, QEMU_OPTION_usb
},
7978 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
7979 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
7980 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
7981 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
7982 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
7983 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
7984 { "daemonize", 0, QEMU_OPTION_daemonize
},
7985 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
7986 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7987 { "semihosting", 0, QEMU_OPTION_semihosting
},
7989 { "name", HAS_ARG
, QEMU_OPTION_name
},
7990 #if defined(TARGET_SPARC)
7991 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
7993 #if defined(TARGET_ARM)
7994 { "old-param", 0, QEMU_OPTION_old_param
},
7996 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
7997 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
7998 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
7999 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8003 /* password input */
8005 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8010 if (!bdrv_is_encrypted(bs
))
8013 term_printf("%s is encrypted.\n", name
);
8014 for(i
= 0; i
< 3; i
++) {
8015 monitor_readline("Password: ", 1, password
, sizeof(password
));
8016 if (bdrv_set_key(bs
, password
) == 0)
8018 term_printf("invalid password\n");
8023 static BlockDriverState
*get_bdrv(int index
)
8025 if (index
> nb_drives
)
8027 return drives_table
[index
].bdrv
;
8030 static void read_passwords(void)
8032 BlockDriverState
*bs
;
8035 for(i
= 0; i
< 6; i
++) {
8038 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8043 struct soundhw soundhw
[] = {
8044 #ifdef HAS_AUDIO_CHOICE
8045 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8051 { .init_isa
= pcspk_audio_init
}
8056 "Creative Sound Blaster 16",
8059 { .init_isa
= SB16_init
}
8062 #ifdef CONFIG_CS4231A
8068 { .init_isa
= cs4231a_init
}
8076 "Yamaha YMF262 (OPL3)",
8078 "Yamaha YM3812 (OPL2)",
8082 { .init_isa
= Adlib_init
}
8089 "Gravis Ultrasound GF1",
8092 { .init_isa
= GUS_init
}
8099 "Intel 82801AA AC97 Audio",
8102 { .init_pci
= ac97_init
}
8108 "ENSONIQ AudioPCI ES1370",
8111 { .init_pci
= es1370_init
}
8115 { NULL
, NULL
, 0, 0, { NULL
} }
8118 static void select_soundhw (const char *optarg
)
8122 if (*optarg
== '?') {
8125 printf ("Valid sound card names (comma separated):\n");
8126 for (c
= soundhw
; c
->name
; ++c
) {
8127 printf ("%-11s %s\n", c
->name
, c
->descr
);
8129 printf ("\n-soundhw all will enable all of the above\n");
8130 exit (*optarg
!= '?');
8138 if (!strcmp (optarg
, "all")) {
8139 for (c
= soundhw
; c
->name
; ++c
) {
8147 e
= strchr (p
, ',');
8148 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8150 for (c
= soundhw
; c
->name
; ++c
) {
8151 if (!strncmp (c
->name
, p
, l
)) {
8160 "Unknown sound card name (too big to show)\n");
8163 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8168 p
+= l
+ (e
!= NULL
);
8172 goto show_valid_cards
;
8178 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8180 exit(STATUS_CONTROL_C_EXIT
);
8185 #define MAX_NET_CLIENTS 32
8187 int main(int argc
, char **argv
)
8189 #ifdef CONFIG_GDBSTUB
8191 const char *gdbstub_port
;
8193 uint32_t boot_devices_bitmap
= 0;
8195 int snapshot
, linux_boot
, net_boot
;
8196 const char *initrd_filename
;
8197 const char *kernel_filename
, *kernel_cmdline
;
8198 const char *boot_devices
= "";
8199 DisplayState
*ds
= &display_state
;
8200 int cyls
, heads
, secs
, translation
;
8201 const char *net_clients
[MAX_NET_CLIENTS
];
8205 const char *r
, *optarg
;
8206 CharDriverState
*monitor_hd
;
8207 const char *monitor_device
;
8208 const char *serial_devices
[MAX_SERIAL_PORTS
];
8209 int serial_device_index
;
8210 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8211 int parallel_device_index
;
8212 const char *loadvm
= NULL
;
8213 QEMUMachine
*machine
;
8214 const char *cpu_model
;
8215 const char *usb_devices
[MAX_USB_CMDLINE
];
8216 int usb_devices_index
;
8219 const char *pid_file
= NULL
;
8222 LIST_INIT (&vm_change_state_head
);
8225 struct sigaction act
;
8226 sigfillset(&act
.sa_mask
);
8228 act
.sa_handler
= SIG_IGN
;
8229 sigaction(SIGPIPE
, &act
, NULL
);
8232 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8233 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8234 QEMU to run on a single CPU */
8239 h
= GetCurrentProcess();
8240 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8241 for(i
= 0; i
< 32; i
++) {
8242 if (mask
& (1 << i
))
8247 SetProcessAffinityMask(h
, mask
);
8253 register_machines();
8254 machine
= first_machine
;
8256 initrd_filename
= NULL
;
8258 vga_ram_size
= VGA_RAM_SIZE
;
8259 #ifdef CONFIG_GDBSTUB
8261 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8266 kernel_filename
= NULL
;
8267 kernel_cmdline
= "";
8268 cyls
= heads
= secs
= 0;
8269 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8270 monitor_device
= "vc";
8272 serial_devices
[0] = "vc:80Cx24C";
8273 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8274 serial_devices
[i
] = NULL
;
8275 serial_device_index
= 0;
8277 parallel_devices
[0] = "vc:640x480";
8278 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8279 parallel_devices
[i
] = NULL
;
8280 parallel_device_index
= 0;
8282 usb_devices_index
= 0;
8299 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8301 const QEMUOption
*popt
;
8304 /* Treat --foo the same as -foo. */
8307 popt
= qemu_options
;
8310 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8314 if (!strcmp(popt
->name
, r
+ 1))
8318 if (popt
->flags
& HAS_ARG
) {
8319 if (optind
>= argc
) {
8320 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8324 optarg
= argv
[optind
++];
8329 switch(popt
->index
) {
8331 machine
= find_machine(optarg
);
8334 printf("Supported machines are:\n");
8335 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8336 printf("%-10s %s%s\n",
8338 m
== first_machine
? " (default)" : "");
8340 exit(*optarg
!= '?');
8343 case QEMU_OPTION_cpu
:
8344 /* hw initialization will check this */
8345 if (*optarg
== '?') {
8346 /* XXX: implement xxx_cpu_list for targets that still miss it */
8347 #if defined(cpu_list)
8348 cpu_list(stdout
, &fprintf
);
8355 case QEMU_OPTION_initrd
:
8356 initrd_filename
= optarg
;
8358 case QEMU_OPTION_hda
:
8360 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8362 hda_index
= drive_add(optarg
, HD_ALIAS
8363 ",cyls=%d,heads=%d,secs=%d%s",
8364 0, cyls
, heads
, secs
,
8365 translation
== BIOS_ATA_TRANSLATION_LBA
?
8367 translation
== BIOS_ATA_TRANSLATION_NONE
?
8368 ",trans=none" : "");
8370 case QEMU_OPTION_hdb
:
8371 case QEMU_OPTION_hdc
:
8372 case QEMU_OPTION_hdd
:
8373 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8375 case QEMU_OPTION_drive
:
8376 drive_add(NULL
, "%s", optarg
);
8378 case QEMU_OPTION_mtdblock
:
8379 drive_add(optarg
, MTD_ALIAS
);
8381 case QEMU_OPTION_sd
:
8382 drive_add(optarg
, SD_ALIAS
);
8384 case QEMU_OPTION_pflash
:
8385 drive_add(optarg
, PFLASH_ALIAS
);
8387 case QEMU_OPTION_snapshot
:
8390 case QEMU_OPTION_hdachs
:
8394 cyls
= strtol(p
, (char **)&p
, 0);
8395 if (cyls
< 1 || cyls
> 16383)
8400 heads
= strtol(p
, (char **)&p
, 0);
8401 if (heads
< 1 || heads
> 16)
8406 secs
= strtol(p
, (char **)&p
, 0);
8407 if (secs
< 1 || secs
> 63)
8411 if (!strcmp(p
, "none"))
8412 translation
= BIOS_ATA_TRANSLATION_NONE
;
8413 else if (!strcmp(p
, "lba"))
8414 translation
= BIOS_ATA_TRANSLATION_LBA
;
8415 else if (!strcmp(p
, "auto"))
8416 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8419 } else if (*p
!= '\0') {
8421 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8424 if (hda_index
!= -1)
8425 snprintf(drives_opt
[hda_index
].opt
,
8426 sizeof(drives_opt
[hda_index
].opt
),
8427 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8428 0, cyls
, heads
, secs
,
8429 translation
== BIOS_ATA_TRANSLATION_LBA
?
8431 translation
== BIOS_ATA_TRANSLATION_NONE
?
8432 ",trans=none" : "");
8435 case QEMU_OPTION_nographic
:
8438 #ifdef CONFIG_CURSES
8439 case QEMU_OPTION_curses
:
8443 case QEMU_OPTION_portrait
:
8446 case QEMU_OPTION_kernel
:
8447 kernel_filename
= optarg
;
8449 case QEMU_OPTION_append
:
8450 kernel_cmdline
= optarg
;
8452 case QEMU_OPTION_cdrom
:
8453 drive_add(optarg
, CDROM_ALIAS
);
8455 case QEMU_OPTION_boot
:
8456 boot_devices
= optarg
;
8457 /* We just do some generic consistency checks */
8459 /* Could easily be extended to 64 devices if needed */
8462 boot_devices_bitmap
= 0;
8463 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8464 /* Allowed boot devices are:
8465 * a b : floppy disk drives
8466 * c ... f : IDE disk drives
8467 * g ... m : machine implementation dependant drives
8468 * n ... p : network devices
8469 * It's up to each machine implementation to check
8470 * if the given boot devices match the actual hardware
8471 * implementation and firmware features.
8473 if (*p
< 'a' || *p
> 'q') {
8474 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8477 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8479 "Boot device '%c' was given twice\n",*p
);
8482 boot_devices_bitmap
|= 1 << (*p
- 'a');
8486 case QEMU_OPTION_fda
:
8487 case QEMU_OPTION_fdb
:
8488 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8491 case QEMU_OPTION_no_fd_bootchk
:
8495 case QEMU_OPTION_net
:
8496 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8497 fprintf(stderr
, "qemu: too many network clients\n");
8500 net_clients
[nb_net_clients
] = optarg
;
8504 case QEMU_OPTION_tftp
:
8505 tftp_prefix
= optarg
;
8507 case QEMU_OPTION_bootp
:
8508 bootp_filename
= optarg
;
8511 case QEMU_OPTION_smb
:
8512 net_slirp_smb(optarg
);
8515 case QEMU_OPTION_redir
:
8516 net_slirp_redir(optarg
);
8520 case QEMU_OPTION_audio_help
:
8524 case QEMU_OPTION_soundhw
:
8525 select_soundhw (optarg
);
8531 case QEMU_OPTION_m
: {
8535 value
= strtoul(optarg
, &ptr
, 10);
8537 case 0: case 'M': case 'm':
8544 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8548 /* On 32-bit hosts, QEMU is limited by virtual address space */
8549 if (value
> (2047 << 20)
8551 && HOST_LONG_BITS
== 32
8554 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8557 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8558 fprintf(stderr
, "qemu: ram size too large\n");
8569 mask
= cpu_str_to_log_mask(optarg
);
8571 printf("Log items (comma separated):\n");
8572 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8573 printf("%-10s %s\n", item
->name
, item
->help
);
8580 #ifdef CONFIG_GDBSTUB
8585 gdbstub_port
= optarg
;
8591 case QEMU_OPTION_bios
:
8598 keyboard_layout
= optarg
;
8600 case QEMU_OPTION_localtime
:
8603 case QEMU_OPTION_cirrusvga
:
8604 cirrus_vga_enabled
= 1;
8607 case QEMU_OPTION_vmsvga
:
8608 cirrus_vga_enabled
= 0;
8611 case QEMU_OPTION_std_vga
:
8612 cirrus_vga_enabled
= 0;
8620 w
= strtol(p
, (char **)&p
, 10);
8623 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8629 h
= strtol(p
, (char **)&p
, 10);
8634 depth
= strtol(p
, (char **)&p
, 10);
8635 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8636 depth
!= 24 && depth
!= 32)
8638 } else if (*p
== '\0') {
8639 depth
= graphic_depth
;
8646 graphic_depth
= depth
;
8649 case QEMU_OPTION_echr
:
8652 term_escape_char
= strtol(optarg
, &r
, 0);
8654 printf("Bad argument to echr\n");
8657 case QEMU_OPTION_monitor
:
8658 monitor_device
= optarg
;
8660 case QEMU_OPTION_serial
:
8661 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8662 fprintf(stderr
, "qemu: too many serial ports\n");
8665 serial_devices
[serial_device_index
] = optarg
;
8666 serial_device_index
++;
8668 case QEMU_OPTION_parallel
:
8669 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8670 fprintf(stderr
, "qemu: too many parallel ports\n");
8673 parallel_devices
[parallel_device_index
] = optarg
;
8674 parallel_device_index
++;
8676 case QEMU_OPTION_loadvm
:
8679 case QEMU_OPTION_full_screen
:
8683 case QEMU_OPTION_no_frame
:
8686 case QEMU_OPTION_alt_grab
:
8689 case QEMU_OPTION_no_quit
:
8693 case QEMU_OPTION_pidfile
:
8697 case QEMU_OPTION_win2k_hack
:
8698 win2k_install_hack
= 1;
8702 case QEMU_OPTION_no_kqemu
:
8705 case QEMU_OPTION_kernel_kqemu
:
8709 case QEMU_OPTION_usb
:
8712 case QEMU_OPTION_usbdevice
:
8714 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8715 fprintf(stderr
, "Too many USB devices\n");
8718 usb_devices
[usb_devices_index
] = optarg
;
8719 usb_devices_index
++;
8721 case QEMU_OPTION_smp
:
8722 smp_cpus
= atoi(optarg
);
8723 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8724 fprintf(stderr
, "Invalid number of CPUs\n");
8728 case QEMU_OPTION_vnc
:
8729 vnc_display
= optarg
;
8731 case QEMU_OPTION_no_acpi
:
8734 case QEMU_OPTION_no_reboot
:
8737 case QEMU_OPTION_no_shutdown
:
8740 case QEMU_OPTION_show_cursor
:
8743 case QEMU_OPTION_daemonize
:
8746 case QEMU_OPTION_option_rom
:
8747 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8748 fprintf(stderr
, "Too many option ROMs\n");
8751 option_rom
[nb_option_roms
] = optarg
;
8754 case QEMU_OPTION_semihosting
:
8755 semihosting_enabled
= 1;
8757 case QEMU_OPTION_name
:
8761 case QEMU_OPTION_prom_env
:
8762 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8763 fprintf(stderr
, "Too many prom variables\n");
8766 prom_envs
[nb_prom_envs
] = optarg
;
8771 case QEMU_OPTION_old_param
:
8775 case QEMU_OPTION_clock
:
8776 configure_alarms(optarg
);
8778 case QEMU_OPTION_startdate
:
8781 time_t rtc_start_date
;
8782 if (!strcmp(optarg
, "now")) {
8783 rtc_date_offset
= -1;
8785 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8793 } else if (sscanf(optarg
, "%d-%d-%d",
8796 &tm
.tm_mday
) == 3) {
8805 rtc_start_date
= mktimegm(&tm
);
8806 if (rtc_start_date
== -1) {
8808 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8809 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8812 rtc_date_offset
= time(NULL
) - rtc_start_date
;
8816 case QEMU_OPTION_tb_size
:
8817 tb_size
= strtol(optarg
, NULL
, 0);
8821 case QEMU_OPTION_icount
:
8823 if (strcmp(optarg
, "auto") == 0) {
8824 icount_time_shift
= -1;
8826 icount_time_shift
= strtol(optarg
, NULL
, 0);
8834 if (serial_device_index
== 0)
8835 serial_devices
[0] = "stdio";
8836 if (parallel_device_index
== 0)
8837 parallel_devices
[0] = "null";
8838 if (strncmp(monitor_device
, "vc", 2) == 0)
8839 monitor_device
= "stdio";
8846 if (pipe(fds
) == -1)
8857 len
= read(fds
[0], &status
, 1);
8858 if (len
== -1 && (errno
== EINTR
))
8863 else if (status
== 1) {
8864 fprintf(stderr
, "Could not acquire pidfile\n");
8881 signal(SIGTSTP
, SIG_IGN
);
8882 signal(SIGTTOU
, SIG_IGN
);
8883 signal(SIGTTIN
, SIG_IGN
);
8887 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
8890 write(fds
[1], &status
, 1);
8892 fprintf(stderr
, "Could not acquire pid file\n");
8900 linux_boot
= (kernel_filename
!= NULL
);
8901 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
8903 if (!linux_boot
&& net_boot
== 0 &&
8904 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
8907 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
8908 fprintf(stderr
, "-append only allowed with -kernel option\n");
8912 if (!linux_boot
&& initrd_filename
!= NULL
) {
8913 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
8917 /* boot to floppy or the default cd if no hard disk defined yet */
8918 if (!boot_devices
[0]) {
8919 boot_devices
= "cad";
8921 setvbuf(stdout
, NULL
, _IOLBF
, 0);
8926 if (use_icount
&& icount_time_shift
< 0) {
8928 /* 125MIPS seems a reasonable initial guess at the guest speed.
8929 It will be corrected fairly quickly anyway. */
8930 icount_time_shift
= 3;
8931 init_icount_adjust();
8938 /* init network clients */
8939 if (nb_net_clients
== 0) {
8940 /* if no clients, we use a default config */
8941 net_clients
[0] = "nic";
8942 net_clients
[1] = "user";
8946 for(i
= 0;i
< nb_net_clients
; i
++) {
8947 if (net_client_parse(net_clients
[i
]) < 0)
8950 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
8951 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
8953 if (vlan
->nb_guest_devs
== 0)
8954 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
8955 if (vlan
->nb_host_devs
== 0)
8957 "Warning: vlan %d is not connected to host network\n",
8962 /* XXX: this should be moved in the PC machine instantiation code */
8963 if (net_boot
!= 0) {
8965 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
8966 const char *model
= nd_table
[i
].model
;
8968 if (net_boot
& (1 << i
)) {
8971 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
8972 if (get_image_size(buf
) > 0) {
8973 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8974 fprintf(stderr
, "Too many option ROMs\n");
8977 option_rom
[nb_option_roms
] = strdup(buf
);
8984 fprintf(stderr
, "No valid PXE rom found for network device\n");
8990 /* init the memory */
8991 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
8993 if (machine
->ram_require
& RAMSIZE_FIXED
) {
8995 if (ram_size
< phys_ram_size
) {
8996 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
8997 machine
->name
, (unsigned long long) phys_ram_size
);
9001 phys_ram_size
= ram_size
;
9003 ram_size
= phys_ram_size
;
9006 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9008 phys_ram_size
+= ram_size
;
9011 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9012 if (!phys_ram_base
) {
9013 fprintf(stderr
, "Could not allocate physical memory\n");
9017 /* init the dynamic translator */
9018 cpu_exec_init_all(tb_size
* 1024 * 1024);
9022 /* we always create the cdrom drive, even if no disk is there */
9024 if (nb_drives_opt
< MAX_DRIVES
)
9025 drive_add(NULL
, CDROM_ALIAS
);
9027 /* we always create at least one floppy */
9029 if (nb_drives_opt
< MAX_DRIVES
)
9030 drive_add(NULL
, FD_ALIAS
, 0);
9032 /* we always create one sd slot, even if no card is in it */
9034 if (nb_drives_opt
< MAX_DRIVES
)
9035 drive_add(NULL
, SD_ALIAS
);
9037 /* open the virtual block devices */
9039 for(i
= 0; i
< nb_drives_opt
; i
++)
9040 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9043 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9044 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
9047 memset(&display_state
, 0, sizeof(display_state
));
9050 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9053 /* nearly nothing to do */
9054 dumb_display_init(ds
);
9055 } else if (vnc_display
!= NULL
) {
9056 vnc_display_init(ds
);
9057 if (vnc_display_open(ds
, vnc_display
) < 0)
9060 #if defined(CONFIG_CURSES)
9062 curses_display_init(ds
, full_screen
);
9066 #if defined(CONFIG_SDL)
9067 sdl_display_init(ds
, full_screen
, no_frame
);
9068 #elif defined(CONFIG_COCOA)
9069 cocoa_display_init(ds
, full_screen
);
9071 dumb_display_init(ds
);
9075 /* Maintain compatibility with multiple stdio monitors */
9076 if (!strcmp(monitor_device
,"stdio")) {
9077 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9078 const char *devname
= serial_devices
[i
];
9079 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9080 monitor_device
= NULL
;
9082 } else if (devname
&& !strcmp(devname
,"stdio")) {
9083 monitor_device
= NULL
;
9084 serial_devices
[i
] = "mon:stdio";
9089 if (monitor_device
) {
9090 monitor_hd
= qemu_chr_open(monitor_device
);
9092 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9095 monitor_init(monitor_hd
, !nographic
);
9098 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9099 const char *devname
= serial_devices
[i
];
9100 if (devname
&& strcmp(devname
, "none")) {
9101 serial_hds
[i
] = qemu_chr_open(devname
);
9102 if (!serial_hds
[i
]) {
9103 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9107 if (strstart(devname
, "vc", 0))
9108 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9112 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9113 const char *devname
= parallel_devices
[i
];
9114 if (devname
&& strcmp(devname
, "none")) {
9115 parallel_hds
[i
] = qemu_chr_open(devname
);
9116 if (!parallel_hds
[i
]) {
9117 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9121 if (strstart(devname
, "vc", 0))
9122 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9126 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9127 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9129 /* init USB devices */
9131 for(i
= 0; i
< usb_devices_index
; i
++) {
9132 if (usb_device_add(usb_devices
[i
]) < 0) {
9133 fprintf(stderr
, "Warning: could not add USB device %s\n",
9139 if (display_state
.dpy_refresh
) {
9140 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9141 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9144 #ifdef CONFIG_GDBSTUB
9146 /* XXX: use standard host:port notation and modify options
9148 if (gdbserver_start(gdbstub_port
) < 0) {
9149 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9160 /* XXX: simplify init */
9173 len
= write(fds
[1], &status
, 1);
9174 if (len
== -1 && (errno
== EINTR
))
9181 TFR(fd
= open("/dev/null", O_RDWR
));
9195 #if !defined(_WIN32)
9196 /* close network clients */
9197 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9198 VLANClientState
*vc
;
9200 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9201 if (vc
->fd_read
== tap_receive
) {
9203 TAPState
*s
= vc
->opaque
;
9205 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9207 launch_script(s
->down_script
, ifname
, s
->fd
);
9209 #if defined(CONFIG_VDE)
9210 if (vc
->fd_read
== vde_from_qemu
) {
9211 VDEState
*s
= vc
->opaque
;