4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
50 #include <sys/times.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
64 #if !defined(__APPLE__) && !defined(__OpenBSD__)
70 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
71 #include <freebsd/stdlib.h>
75 #include <linux/if_tun.h>
78 #include <linux/rtc.h>
80 /* For the benefit of older linux systems which don't supply it,
81 we use a local copy of hpet.h. */
82 /* #include <linux/hpet.h> */
85 #include <linux/ppdev.h>
86 #include <linux/parport.h>
89 #include <sys/ethernet.h>
90 #include <sys/sockio.h>
91 #include <netinet/arp.h>
92 #include <netinet/in.h>
93 #include <netinet/in_systm.h>
94 #include <netinet/ip.h>
95 #include <netinet/ip_icmp.h> // must come after ip.h
96 #include <netinet/udp.h>
97 #include <netinet/tcp.h>
104 #include <winsock2.h>
105 int inet_aton(const char *cp
, struct in_addr
*ia
);
108 #if defined(CONFIG_SLIRP)
109 #include "libslirp.h"
112 #if defined(__OpenBSD__)
116 #if defined(CONFIG_VDE)
117 #include <libvdeplug.h>
122 #include <sys/timeb.h>
123 #include <mmsystem.h>
124 #define getopt_long_only getopt_long
125 #define memalign(align, size) malloc(size)
128 #include "qemu_socket.h"
134 #endif /* CONFIG_SDL */
138 #define main qemu_main
139 #endif /* CONFIG_COCOA */
143 #include "exec-all.h"
145 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
146 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
148 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
150 #define SMBD_COMMAND "/usr/sbin/smbd"
153 //#define DEBUG_UNUSED_IOPORT
154 //#define DEBUG_IOPORT
157 #define DEFAULT_RAM_SIZE 144
159 #define DEFAULT_RAM_SIZE 128
162 /* Max number of USB devices that can be specified on the commandline. */
163 #define MAX_USB_CMDLINE 8
165 /* XXX: use a two level table to limit memory usage */
166 #define MAX_IOPORTS 65536
168 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
169 const char *bios_name
= NULL
;
170 void *ioport_opaque
[MAX_IOPORTS
];
171 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
172 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
173 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
174 to store the VM snapshots */
175 DriveInfo drives_table
[MAX_DRIVES
+1];
177 /* point to the block driver where the snapshots are managed */
178 BlockDriverState
*bs_snapshots
;
180 static DisplayState display_state
;
183 const char* keyboard_layout
= NULL
;
184 int64_t ticks_per_sec
;
186 int pit_min_timer_count
= 0;
188 NICInfo nd_table
[MAX_NICS
];
190 static int rtc_utc
= 1;
191 static int rtc_date_offset
= -1; /* -1 means no change */
192 int cirrus_vga_enabled
= 1;
193 int vmsvga_enabled
= 0;
195 int graphic_width
= 1024;
196 int graphic_height
= 768;
197 int graphic_depth
= 8;
199 int graphic_width
= 800;
200 int graphic_height
= 600;
201 int graphic_depth
= 15;
206 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
207 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
209 int win2k_install_hack
= 0;
212 static VLANState
*first_vlan
;
214 const char *vnc_display
;
215 #if defined(TARGET_SPARC)
217 #elif defined(TARGET_I386)
222 int acpi_enabled
= 1;
227 int graphic_rotate
= 0;
229 const char *option_rom
[MAX_OPTION_ROMS
];
231 int semihosting_enabled
= 0;
236 const char *qemu_name
;
239 unsigned int nb_prom_envs
= 0;
240 const char *prom_envs
[MAX_PROM_ENVS
];
246 } drives_opt
[MAX_DRIVES
];
248 static CPUState
*cur_cpu
;
249 static CPUState
*next_cpu
;
250 static int event_pending
= 1;
251 /* Conversion factor from emulated instructions to virtual clock ticks. */
252 static int icount_time_shift
;
253 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
254 #define MAX_ICOUNT_SHIFT 10
255 /* Compensate for varying guest execution speed. */
256 static int64_t qemu_icount_bias
;
257 QEMUTimer
*icount_rt_timer
;
258 QEMUTimer
*icount_vm_timer
;
260 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
262 /***********************************************************/
263 /* x86 ISA bus support */
265 target_phys_addr_t isa_mem_base
= 0;
268 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
269 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
271 static uint32_t ioport_read(int index
, uint32_t address
)
273 static IOPortReadFunc
*default_func
[3] = {
274 default_ioport_readb
,
275 default_ioport_readw
,
278 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
280 func
= default_func
[index
];
281 return func(ioport_opaque
[address
], address
);
284 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
286 static IOPortWriteFunc
*default_func
[3] = {
287 default_ioport_writeb
,
288 default_ioport_writew
,
289 default_ioport_writel
291 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
293 func
= default_func
[index
];
294 func(ioport_opaque
[address
], address
, data
);
297 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
299 #ifdef DEBUG_UNUSED_IOPORT
300 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
305 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
307 #ifdef DEBUG_UNUSED_IOPORT
308 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
312 /* default is to make two byte accesses */
313 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
316 data
= ioport_read(0, address
);
317 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
318 data
|= ioport_read(0, address
) << 8;
322 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
324 ioport_write(0, address
, data
& 0xff);
325 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
326 ioport_write(0, address
, (data
>> 8) & 0xff);
329 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
331 #ifdef DEBUG_UNUSED_IOPORT
332 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
337 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
339 #ifdef DEBUG_UNUSED_IOPORT
340 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
344 /* size is the word size in byte */
345 int register_ioport_read(int start
, int length
, int size
,
346 IOPortReadFunc
*func
, void *opaque
)
352 } else if (size
== 2) {
354 } else if (size
== 4) {
357 hw_error("register_ioport_read: invalid size");
360 for(i
= start
; i
< start
+ length
; i
+= size
) {
361 ioport_read_table
[bsize
][i
] = func
;
362 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
363 hw_error("register_ioport_read: invalid opaque");
364 ioport_opaque
[i
] = opaque
;
369 /* size is the word size in byte */
370 int register_ioport_write(int start
, int length
, int size
,
371 IOPortWriteFunc
*func
, void *opaque
)
377 } else if (size
== 2) {
379 } else if (size
== 4) {
382 hw_error("register_ioport_write: invalid size");
385 for(i
= start
; i
< start
+ length
; i
+= size
) {
386 ioport_write_table
[bsize
][i
] = func
;
387 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
388 hw_error("register_ioport_write: invalid opaque");
389 ioport_opaque
[i
] = opaque
;
394 void isa_unassign_ioport(int start
, int length
)
398 for(i
= start
; i
< start
+ length
; i
++) {
399 ioport_read_table
[0][i
] = default_ioport_readb
;
400 ioport_read_table
[1][i
] = default_ioport_readw
;
401 ioport_read_table
[2][i
] = default_ioport_readl
;
403 ioport_write_table
[0][i
] = default_ioport_writeb
;
404 ioport_write_table
[1][i
] = default_ioport_writew
;
405 ioport_write_table
[2][i
] = default_ioport_writel
;
409 /***********************************************************/
411 void cpu_outb(CPUState
*env
, int addr
, int val
)
414 if (loglevel
& CPU_LOG_IOPORT
)
415 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
417 ioport_write(0, addr
, val
);
420 env
->last_io_time
= cpu_get_time_fast();
424 void cpu_outw(CPUState
*env
, int addr
, int val
)
427 if (loglevel
& CPU_LOG_IOPORT
)
428 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
430 ioport_write(1, addr
, val
);
433 env
->last_io_time
= cpu_get_time_fast();
437 void cpu_outl(CPUState
*env
, int addr
, int val
)
440 if (loglevel
& CPU_LOG_IOPORT
)
441 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
443 ioport_write(2, addr
, val
);
446 env
->last_io_time
= cpu_get_time_fast();
450 int cpu_inb(CPUState
*env
, int addr
)
453 val
= ioport_read(0, addr
);
455 if (loglevel
& CPU_LOG_IOPORT
)
456 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
460 env
->last_io_time
= cpu_get_time_fast();
465 int cpu_inw(CPUState
*env
, int addr
)
468 val
= ioport_read(1, addr
);
470 if (loglevel
& CPU_LOG_IOPORT
)
471 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
475 env
->last_io_time
= cpu_get_time_fast();
480 int cpu_inl(CPUState
*env
, int addr
)
483 val
= ioport_read(2, addr
);
485 if (loglevel
& CPU_LOG_IOPORT
)
486 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
490 env
->last_io_time
= cpu_get_time_fast();
495 /***********************************************************/
496 void hw_error(const char *fmt
, ...)
502 fprintf(stderr
, "qemu: hardware error: ");
503 vfprintf(stderr
, fmt
, ap
);
504 fprintf(stderr
, "\n");
505 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
506 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
508 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
510 cpu_dump_state(env
, stderr
, fprintf
, 0);
517 /***********************************************************/
520 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
521 static void *qemu_put_kbd_event_opaque
;
522 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
523 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
525 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
527 qemu_put_kbd_event_opaque
= opaque
;
528 qemu_put_kbd_event
= func
;
531 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
532 void *opaque
, int absolute
,
535 QEMUPutMouseEntry
*s
, *cursor
;
537 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
541 s
->qemu_put_mouse_event
= func
;
542 s
->qemu_put_mouse_event_opaque
= opaque
;
543 s
->qemu_put_mouse_event_absolute
= absolute
;
544 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
547 if (!qemu_put_mouse_event_head
) {
548 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
552 cursor
= qemu_put_mouse_event_head
;
553 while (cursor
->next
!= NULL
)
554 cursor
= cursor
->next
;
557 qemu_put_mouse_event_current
= s
;
562 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
564 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
566 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
569 cursor
= qemu_put_mouse_event_head
;
570 while (cursor
!= NULL
&& cursor
!= entry
) {
572 cursor
= cursor
->next
;
575 if (cursor
== NULL
) // does not exist or list empty
577 else if (prev
== NULL
) { // entry is head
578 qemu_put_mouse_event_head
= cursor
->next
;
579 if (qemu_put_mouse_event_current
== entry
)
580 qemu_put_mouse_event_current
= cursor
->next
;
581 qemu_free(entry
->qemu_put_mouse_event_name
);
586 prev
->next
= entry
->next
;
588 if (qemu_put_mouse_event_current
== entry
)
589 qemu_put_mouse_event_current
= prev
;
591 qemu_free(entry
->qemu_put_mouse_event_name
);
595 void kbd_put_keycode(int keycode
)
597 if (qemu_put_kbd_event
) {
598 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
602 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
604 QEMUPutMouseEvent
*mouse_event
;
605 void *mouse_event_opaque
;
608 if (!qemu_put_mouse_event_current
) {
613 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
615 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
618 if (graphic_rotate
) {
619 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
622 width
= graphic_width
- 1;
623 mouse_event(mouse_event_opaque
,
624 width
- dy
, dx
, dz
, buttons_state
);
626 mouse_event(mouse_event_opaque
,
627 dx
, dy
, dz
, buttons_state
);
631 int kbd_mouse_is_absolute(void)
633 if (!qemu_put_mouse_event_current
)
636 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
639 void do_info_mice(void)
641 QEMUPutMouseEntry
*cursor
;
644 if (!qemu_put_mouse_event_head
) {
645 term_printf("No mouse devices connected\n");
649 term_printf("Mouse devices available:\n");
650 cursor
= qemu_put_mouse_event_head
;
651 while (cursor
!= NULL
) {
652 term_printf("%c Mouse #%d: %s\n",
653 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
654 index
, cursor
->qemu_put_mouse_event_name
);
656 cursor
= cursor
->next
;
660 void do_mouse_set(int index
)
662 QEMUPutMouseEntry
*cursor
;
665 if (!qemu_put_mouse_event_head
) {
666 term_printf("No mouse devices connected\n");
670 cursor
= qemu_put_mouse_event_head
;
671 while (cursor
!= NULL
&& index
!= i
) {
673 cursor
= cursor
->next
;
677 qemu_put_mouse_event_current
= cursor
;
679 term_printf("Mouse at given index not found\n");
682 /* compute with 96 bit intermediate result: (a*b)/c */
683 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
688 #ifdef WORDS_BIGENDIAN
698 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
699 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
702 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
706 /***********************************************************/
707 /* real time host monotonic timer */
709 #define QEMU_TIMER_BASE 1000000000LL
713 static int64_t clock_freq
;
715 static void init_get_clock(void)
719 ret
= QueryPerformanceFrequency(&freq
);
721 fprintf(stderr
, "Could not calibrate ticks\n");
724 clock_freq
= freq
.QuadPart
;
727 static int64_t get_clock(void)
730 QueryPerformanceCounter(&ti
);
731 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
736 static int use_rt_clock
;
738 static void init_get_clock(void)
741 #if defined(__linux__)
744 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
751 static int64_t get_clock(void)
753 #if defined(__linux__)
756 clock_gettime(CLOCK_MONOTONIC
, &ts
);
757 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
761 /* XXX: using gettimeofday leads to problems if the date
762 changes, so it should be avoided. */
764 gettimeofday(&tv
, NULL
);
765 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
770 /* Return the virtual CPU time, based on the instruction counter. */
771 static int64_t cpu_get_icount(void)
774 CPUState
*env
= cpu_single_env
;;
775 icount
= qemu_icount
;
778 fprintf(stderr
, "Bad clock read\n");
779 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
781 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
784 /***********************************************************/
785 /* guest cycle counter */
787 static int64_t cpu_ticks_prev
;
788 static int64_t cpu_ticks_offset
;
789 static int64_t cpu_clock_offset
;
790 static int cpu_ticks_enabled
;
792 /* return the host CPU cycle counter and handle stop/restart */
793 int64_t cpu_get_ticks(void)
796 return cpu_get_icount();
798 if (!cpu_ticks_enabled
) {
799 return cpu_ticks_offset
;
802 ticks
= cpu_get_real_ticks();
803 if (cpu_ticks_prev
> ticks
) {
804 /* Note: non increasing ticks may happen if the host uses
806 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
808 cpu_ticks_prev
= ticks
;
809 return ticks
+ cpu_ticks_offset
;
813 /* return the host CPU monotonic timer and handle stop/restart */
814 static int64_t cpu_get_clock(void)
817 if (!cpu_ticks_enabled
) {
818 return cpu_clock_offset
;
821 return ti
+ cpu_clock_offset
;
825 /* enable cpu_get_ticks() */
826 void cpu_enable_ticks(void)
828 if (!cpu_ticks_enabled
) {
829 cpu_ticks_offset
-= cpu_get_real_ticks();
830 cpu_clock_offset
-= get_clock();
831 cpu_ticks_enabled
= 1;
835 /* disable cpu_get_ticks() : the clock is stopped. You must not call
836 cpu_get_ticks() after that. */
837 void cpu_disable_ticks(void)
839 if (cpu_ticks_enabled
) {
840 cpu_ticks_offset
= cpu_get_ticks();
841 cpu_clock_offset
= cpu_get_clock();
842 cpu_ticks_enabled
= 0;
846 /***********************************************************/
849 #define QEMU_TIMER_REALTIME 0
850 #define QEMU_TIMER_VIRTUAL 1
854 /* XXX: add frequency */
862 struct QEMUTimer
*next
;
865 struct qemu_alarm_timer
{
869 int (*start
)(struct qemu_alarm_timer
*t
);
870 void (*stop
)(struct qemu_alarm_timer
*t
);
871 void (*rearm
)(struct qemu_alarm_timer
*t
);
875 #define ALARM_FLAG_DYNTICKS 0x1
876 #define ALARM_FLAG_EXPIRED 0x2
878 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
880 return t
->flags
& ALARM_FLAG_DYNTICKS
;
883 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
885 if (!alarm_has_dynticks(t
))
891 /* TODO: MIN_TIMER_REARM_US should be optimized */
892 #define MIN_TIMER_REARM_US 250
894 static struct qemu_alarm_timer
*alarm_timer
;
898 struct qemu_alarm_win32
{
902 } alarm_win32_data
= {0, NULL
, -1};
904 static int win32_start_timer(struct qemu_alarm_timer
*t
);
905 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
906 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
910 static int unix_start_timer(struct qemu_alarm_timer
*t
);
911 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
915 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
916 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
917 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
919 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
920 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
922 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
923 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
925 #endif /* __linux__ */
929 /* Correlation between real and virtual time is always going to be
930 fairly approximate, so ignore small variation.
931 When the guest is idle real and virtual time will be aligned in
933 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
935 static void icount_adjust(void)
940 static int64_t last_delta
;
941 /* If the VM is not running, then do nothing. */
945 cur_time
= cpu_get_clock();
946 cur_icount
= qemu_get_clock(vm_clock
);
947 delta
= cur_icount
- cur_time
;
948 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
950 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
951 && icount_time_shift
> 0) {
952 /* The guest is getting too far ahead. Slow time down. */
956 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
957 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
958 /* The guest is getting too far behind. Speed time up. */
962 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
965 static void icount_adjust_rt(void * opaque
)
967 qemu_mod_timer(icount_rt_timer
,
968 qemu_get_clock(rt_clock
) + 1000);
972 static void icount_adjust_vm(void * opaque
)
974 qemu_mod_timer(icount_vm_timer
,
975 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
979 static void init_icount_adjust(void)
981 /* Have both realtime and virtual time triggers for speed adjustment.
982 The realtime trigger catches emulated time passing too slowly,
983 the virtual time trigger catches emulated time passing too fast.
984 Realtime triggers occur even when idle, so use them less frequently
986 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
987 qemu_mod_timer(icount_rt_timer
,
988 qemu_get_clock(rt_clock
) + 1000);
989 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
990 qemu_mod_timer(icount_vm_timer
,
991 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
994 static struct qemu_alarm_timer alarm_timers
[] = {
997 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
998 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
999 /* HPET - if available - is preferred */
1000 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1001 /* ...otherwise try RTC */
1002 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1004 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1006 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1007 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1008 {"win32", 0, win32_start_timer
,
1009 win32_stop_timer
, NULL
, &alarm_win32_data
},
1014 static void show_available_alarms(void)
1018 printf("Available alarm timers, in order of precedence:\n");
1019 for (i
= 0; alarm_timers
[i
].name
; i
++)
1020 printf("%s\n", alarm_timers
[i
].name
);
1023 static void configure_alarms(char const *opt
)
1027 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1030 struct qemu_alarm_timer tmp
;
1032 if (!strcmp(opt
, "?")) {
1033 show_available_alarms();
1039 /* Reorder the array */
1040 name
= strtok(arg
, ",");
1042 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1043 if (!strcmp(alarm_timers
[i
].name
, name
))
1048 fprintf(stderr
, "Unknown clock %s\n", name
);
1057 tmp
= alarm_timers
[i
];
1058 alarm_timers
[i
] = alarm_timers
[cur
];
1059 alarm_timers
[cur
] = tmp
;
1063 name
= strtok(NULL
, ",");
1069 /* Disable remaining timers */
1070 for (i
= cur
; i
< count
; i
++)
1071 alarm_timers
[i
].name
= NULL
;
1073 show_available_alarms();
1078 QEMUClock
*rt_clock
;
1079 QEMUClock
*vm_clock
;
1081 static QEMUTimer
*active_timers
[2];
1083 static QEMUClock
*qemu_new_clock(int type
)
1086 clock
= qemu_mallocz(sizeof(QEMUClock
));
1093 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1097 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1100 ts
->opaque
= opaque
;
1104 void qemu_free_timer(QEMUTimer
*ts
)
1109 /* stop a timer, but do not dealloc it */
1110 void qemu_del_timer(QEMUTimer
*ts
)
1114 /* NOTE: this code must be signal safe because
1115 qemu_timer_expired() can be called from a signal. */
1116 pt
= &active_timers
[ts
->clock
->type
];
1129 /* modify the current timer so that it will be fired when current_time
1130 >= expire_time. The corresponding callback will be called. */
1131 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1137 /* add the timer in the sorted list */
1138 /* NOTE: this code must be signal safe because
1139 qemu_timer_expired() can be called from a signal. */
1140 pt
= &active_timers
[ts
->clock
->type
];
1145 if (t
->expire_time
> expire_time
)
1149 ts
->expire_time
= expire_time
;
1153 /* Rearm if necessary */
1154 if (pt
== &active_timers
[ts
->clock
->type
]) {
1155 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1156 qemu_rearm_alarm_timer(alarm_timer
);
1158 /* Interrupt execution to force deadline recalculation. */
1159 if (use_icount
&& cpu_single_env
) {
1160 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1165 int qemu_timer_pending(QEMUTimer
*ts
)
1168 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1175 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1179 return (timer_head
->expire_time
<= current_time
);
1182 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1188 if (!ts
|| ts
->expire_time
> current_time
)
1190 /* remove timer from the list before calling the callback */
1191 *ptimer_head
= ts
->next
;
1194 /* run the callback (the timer list can be modified) */
1199 int64_t qemu_get_clock(QEMUClock
*clock
)
1201 switch(clock
->type
) {
1202 case QEMU_TIMER_REALTIME
:
1203 return get_clock() / 1000000;
1205 case QEMU_TIMER_VIRTUAL
:
1207 return cpu_get_icount();
1209 return cpu_get_clock();
1214 static void init_timers(void)
1217 ticks_per_sec
= QEMU_TIMER_BASE
;
1218 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1219 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1223 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1225 uint64_t expire_time
;
1227 if (qemu_timer_pending(ts
)) {
1228 expire_time
= ts
->expire_time
;
1232 qemu_put_be64(f
, expire_time
);
1235 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1237 uint64_t expire_time
;
1239 expire_time
= qemu_get_be64(f
);
1240 if (expire_time
!= -1) {
1241 qemu_mod_timer(ts
, expire_time
);
1247 static void timer_save(QEMUFile
*f
, void *opaque
)
1249 if (cpu_ticks_enabled
) {
1250 hw_error("cannot save state if virtual timers are running");
1252 qemu_put_be64(f
, cpu_ticks_offset
);
1253 qemu_put_be64(f
, ticks_per_sec
);
1254 qemu_put_be64(f
, cpu_clock_offset
);
1257 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1259 if (version_id
!= 1 && version_id
!= 2)
1261 if (cpu_ticks_enabled
) {
1264 cpu_ticks_offset
=qemu_get_be64(f
);
1265 ticks_per_sec
=qemu_get_be64(f
);
1266 if (version_id
== 2) {
1267 cpu_clock_offset
=qemu_get_be64(f
);
1273 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1274 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1276 static void host_alarm_handler(int host_signum
)
1280 #define DISP_FREQ 1000
1282 static int64_t delta_min
= INT64_MAX
;
1283 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1285 ti
= qemu_get_clock(vm_clock
);
1286 if (last_clock
!= 0) {
1287 delta
= ti
- last_clock
;
1288 if (delta
< delta_min
)
1290 if (delta
> delta_max
)
1293 if (++count
== DISP_FREQ
) {
1294 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1295 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1296 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1297 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1298 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1300 delta_min
= INT64_MAX
;
1308 if (alarm_has_dynticks(alarm_timer
) ||
1310 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1311 qemu_get_clock(vm_clock
))) ||
1312 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1313 qemu_get_clock(rt_clock
))) {
1315 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1316 SetEvent(data
->host_alarm
);
1318 CPUState
*env
= next_cpu
;
1320 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1323 /* stop the currently executing cpu because a timer occured */
1324 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1326 if (env
->kqemu_enabled
) {
1327 kqemu_cpu_interrupt(env
);
1335 static int64_t qemu_next_deadline(void)
1339 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1340 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1341 qemu_get_clock(vm_clock
);
1343 /* To avoid problems with overflow limit this to 2^32. */
1353 static uint64_t qemu_next_deadline_dyntick(void)
1361 delta
= (qemu_next_deadline() + 999) / 1000;
1363 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1364 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1365 qemu_get_clock(rt_clock
))*1000;
1366 if (rtdelta
< delta
)
1370 if (delta
< MIN_TIMER_REARM_US
)
1371 delta
= MIN_TIMER_REARM_US
;
1378 #if defined(__linux__)
1380 #define RTC_FREQ 1024
1382 static void enable_sigio_timer(int fd
)
1384 struct sigaction act
;
1387 sigfillset(&act
.sa_mask
);
1389 act
.sa_handler
= host_alarm_handler
;
1391 sigaction(SIGIO
, &act
, NULL
);
1392 fcntl(fd
, F_SETFL
, O_ASYNC
);
1393 fcntl(fd
, F_SETOWN
, getpid());
1396 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1398 struct hpet_info info
;
1401 fd
= open("/dev/hpet", O_RDONLY
);
1406 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1408 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1409 "error, but for better emulation accuracy type:\n"
1410 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1414 /* Check capabilities */
1415 r
= ioctl(fd
, HPET_INFO
, &info
);
1419 /* Enable periodic mode */
1420 r
= ioctl(fd
, HPET_EPI
, 0);
1421 if (info
.hi_flags
&& (r
< 0))
1424 /* Enable interrupt */
1425 r
= ioctl(fd
, HPET_IE_ON
, 0);
1429 enable_sigio_timer(fd
);
1430 t
->priv
= (void *)(long)fd
;
1438 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1440 int fd
= (long)t
->priv
;
1445 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1448 unsigned long current_rtc_freq
= 0;
1450 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1453 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1454 if (current_rtc_freq
!= RTC_FREQ
&&
1455 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1456 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1457 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1458 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1461 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1467 enable_sigio_timer(rtc_fd
);
1469 t
->priv
= (void *)(long)rtc_fd
;
1474 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1476 int rtc_fd
= (long)t
->priv
;
1481 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1485 struct sigaction act
;
1487 sigfillset(&act
.sa_mask
);
1489 act
.sa_handler
= host_alarm_handler
;
1491 sigaction(SIGALRM
, &act
, NULL
);
1493 ev
.sigev_value
.sival_int
= 0;
1494 ev
.sigev_notify
= SIGEV_SIGNAL
;
1495 ev
.sigev_signo
= SIGALRM
;
1497 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1498 perror("timer_create");
1500 /* disable dynticks */
1501 fprintf(stderr
, "Dynamic Ticks disabled\n");
1506 t
->priv
= (void *)host_timer
;
1511 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1513 timer_t host_timer
= (timer_t
)t
->priv
;
1515 timer_delete(host_timer
);
1518 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1520 timer_t host_timer
= (timer_t
)t
->priv
;
1521 struct itimerspec timeout
;
1522 int64_t nearest_delta_us
= INT64_MAX
;
1525 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1526 !active_timers
[QEMU_TIMER_VIRTUAL
])
1529 nearest_delta_us
= qemu_next_deadline_dyntick();
1531 /* check whether a timer is already running */
1532 if (timer_gettime(host_timer
, &timeout
)) {
1534 fprintf(stderr
, "Internal timer error: aborting\n");
1537 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1538 if (current_us
&& current_us
<= nearest_delta_us
)
1541 timeout
.it_interval
.tv_sec
= 0;
1542 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1543 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1544 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1545 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1547 fprintf(stderr
, "Internal timer error: aborting\n");
1552 #endif /* defined(__linux__) */
1554 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1556 struct sigaction act
;
1557 struct itimerval itv
;
1561 sigfillset(&act
.sa_mask
);
1563 act
.sa_handler
= host_alarm_handler
;
1565 sigaction(SIGALRM
, &act
, NULL
);
1567 itv
.it_interval
.tv_sec
= 0;
1568 /* for i386 kernel 2.6 to get 1 ms */
1569 itv
.it_interval
.tv_usec
= 999;
1570 itv
.it_value
.tv_sec
= 0;
1571 itv
.it_value
.tv_usec
= 10 * 1000;
1573 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1580 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1582 struct itimerval itv
;
1584 memset(&itv
, 0, sizeof(itv
));
1585 setitimer(ITIMER_REAL
, &itv
, NULL
);
1588 #endif /* !defined(_WIN32) */
1592 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1595 struct qemu_alarm_win32
*data
= t
->priv
;
1598 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1599 if (!data
->host_alarm
) {
1600 perror("Failed CreateEvent");
1604 memset(&tc
, 0, sizeof(tc
));
1605 timeGetDevCaps(&tc
, sizeof(tc
));
1607 if (data
->period
< tc
.wPeriodMin
)
1608 data
->period
= tc
.wPeriodMin
;
1610 timeBeginPeriod(data
->period
);
1612 flags
= TIME_CALLBACK_FUNCTION
;
1613 if (alarm_has_dynticks(t
))
1614 flags
|= TIME_ONESHOT
;
1616 flags
|= TIME_PERIODIC
;
1618 data
->timerId
= timeSetEvent(1, // interval (ms)
1619 data
->period
, // resolution
1620 host_alarm_handler
, // function
1621 (DWORD
)t
, // parameter
1624 if (!data
->timerId
) {
1625 perror("Failed to initialize win32 alarm timer");
1627 timeEndPeriod(data
->period
);
1628 CloseHandle(data
->host_alarm
);
1632 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1637 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1639 struct qemu_alarm_win32
*data
= t
->priv
;
1641 timeKillEvent(data
->timerId
);
1642 timeEndPeriod(data
->period
);
1644 CloseHandle(data
->host_alarm
);
1647 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1649 struct qemu_alarm_win32
*data
= t
->priv
;
1650 uint64_t nearest_delta_us
;
1652 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1653 !active_timers
[QEMU_TIMER_VIRTUAL
])
1656 nearest_delta_us
= qemu_next_deadline_dyntick();
1657 nearest_delta_us
/= 1000;
1659 timeKillEvent(data
->timerId
);
1661 data
->timerId
= timeSetEvent(1,
1665 TIME_ONESHOT
| TIME_PERIODIC
);
1667 if (!data
->timerId
) {
1668 perror("Failed to re-arm win32 alarm timer");
1670 timeEndPeriod(data
->period
);
1671 CloseHandle(data
->host_alarm
);
1678 static void init_timer_alarm(void)
1680 struct qemu_alarm_timer
*t
;
1683 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1684 t
= &alarm_timers
[i
];
1692 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1693 fprintf(stderr
, "Terminating\n");
1700 static void quit_timers(void)
1702 alarm_timer
->stop(alarm_timer
);
1706 /***********************************************************/
1707 /* host time/date access */
1708 void qemu_get_timedate(struct tm
*tm
, int offset
)
1715 if (rtc_date_offset
== -1) {
1719 ret
= localtime(&ti
);
1721 ti
-= rtc_date_offset
;
1725 memcpy(tm
, ret
, sizeof(struct tm
));
1728 int qemu_timedate_diff(struct tm
*tm
)
1732 if (rtc_date_offset
== -1)
1734 seconds
= mktimegm(tm
);
1736 seconds
= mktime(tm
);
1738 seconds
= mktimegm(tm
) + rtc_date_offset
;
1740 return seconds
- time(NULL
);
1743 /***********************************************************/
1744 /* character device */
1746 static void qemu_chr_event(CharDriverState
*s
, int event
)
1750 s
->chr_event(s
->handler_opaque
, event
);
1753 static void qemu_chr_reset_bh(void *opaque
)
1755 CharDriverState
*s
= opaque
;
1756 qemu_chr_event(s
, CHR_EVENT_RESET
);
1757 qemu_bh_delete(s
->bh
);
1761 void qemu_chr_reset(CharDriverState
*s
)
1763 if (s
->bh
== NULL
) {
1764 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1765 qemu_bh_schedule(s
->bh
);
1769 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1771 return s
->chr_write(s
, buf
, len
);
1774 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1778 return s
->chr_ioctl(s
, cmd
, arg
);
1781 int qemu_chr_can_read(CharDriverState
*s
)
1783 if (!s
->chr_can_read
)
1785 return s
->chr_can_read(s
->handler_opaque
);
1788 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1790 s
->chr_read(s
->handler_opaque
, buf
, len
);
1793 void qemu_chr_accept_input(CharDriverState
*s
)
1795 if (s
->chr_accept_input
)
1796 s
->chr_accept_input(s
);
1799 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1804 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1805 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1809 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1811 if (s
->chr_send_event
)
1812 s
->chr_send_event(s
, event
);
1815 void qemu_chr_add_handlers(CharDriverState
*s
,
1816 IOCanRWHandler
*fd_can_read
,
1817 IOReadHandler
*fd_read
,
1818 IOEventHandler
*fd_event
,
1821 s
->chr_can_read
= fd_can_read
;
1822 s
->chr_read
= fd_read
;
1823 s
->chr_event
= fd_event
;
1824 s
->handler_opaque
= opaque
;
1825 if (s
->chr_update_read_handler
)
1826 s
->chr_update_read_handler(s
);
1829 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1834 static CharDriverState
*qemu_chr_open_null(void)
1836 CharDriverState
*chr
;
1838 chr
= qemu_mallocz(sizeof(CharDriverState
));
1841 chr
->chr_write
= null_chr_write
;
1845 /* MUX driver for serial I/O splitting */
1846 static int term_timestamps
;
1847 static int64_t term_timestamps_start
;
1849 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1850 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1852 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1853 IOReadHandler
*chr_read
[MAX_MUX
];
1854 IOEventHandler
*chr_event
[MAX_MUX
];
1855 void *ext_opaque
[MAX_MUX
];
1856 CharDriverState
*drv
;
1857 unsigned char buffer
[MUX_BUFFER_SIZE
];
1861 int term_got_escape
;
1866 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1868 MuxDriver
*d
= chr
->opaque
;
1870 if (!term_timestamps
) {
1871 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1876 for(i
= 0; i
< len
; i
++) {
1877 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1878 if (buf
[i
] == '\n') {
1884 if (term_timestamps_start
== -1)
1885 term_timestamps_start
= ti
;
1886 ti
-= term_timestamps_start
;
1887 secs
= ti
/ 1000000000;
1888 snprintf(buf1
, sizeof(buf1
),
1889 "[%02d:%02d:%02d.%03d] ",
1893 (int)((ti
/ 1000000) % 1000));
1894 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1901 static const char * const mux_help
[] = {
1902 "% h print this help\n\r",
1903 "% x exit emulator\n\r",
1904 "% s save disk data back to file (if -snapshot)\n\r",
1905 "% t toggle console timestamps\n\r"
1906 "% b send break (magic sysrq)\n\r",
1907 "% c switch between console and monitor\n\r",
1912 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1913 static void mux_print_help(CharDriverState
*chr
)
1916 char ebuf
[15] = "Escape-Char";
1917 char cbuf
[50] = "\n\r";
1919 if (term_escape_char
> 0 && term_escape_char
< 26) {
1920 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1921 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1923 snprintf(cbuf
, sizeof(cbuf
),
1924 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1927 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1928 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1929 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1930 if (mux_help
[i
][j
] == '%')
1931 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1933 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1938 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1940 if (d
->term_got_escape
) {
1941 d
->term_got_escape
= 0;
1942 if (ch
== term_escape_char
)
1947 mux_print_help(chr
);
1951 const char *term
= "QEMU: Terminated\n\r";
1952 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1959 for (i
= 0; i
< nb_drives
; i
++) {
1960 bdrv_commit(drives_table
[i
].bdrv
);
1965 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1968 /* Switch to the next registered device */
1970 if (chr
->focus
>= d
->mux_cnt
)
1974 term_timestamps
= !term_timestamps
;
1975 term_timestamps_start
= -1;
1978 } else if (ch
== term_escape_char
) {
1979 d
->term_got_escape
= 1;
1987 static void mux_chr_accept_input(CharDriverState
*chr
)
1990 MuxDriver
*d
= chr
->opaque
;
1992 while (d
->prod
!= d
->cons
&&
1993 d
->chr_can_read
[m
] &&
1994 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1995 d
->chr_read
[m
](d
->ext_opaque
[m
],
1996 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
2000 static int mux_chr_can_read(void *opaque
)
2002 CharDriverState
*chr
= opaque
;
2003 MuxDriver
*d
= chr
->opaque
;
2005 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2007 if (d
->chr_can_read
[chr
->focus
])
2008 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2012 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2014 CharDriverState
*chr
= opaque
;
2015 MuxDriver
*d
= chr
->opaque
;
2019 mux_chr_accept_input (opaque
);
2021 for(i
= 0; i
< size
; i
++)
2022 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2023 if (d
->prod
== d
->cons
&&
2024 d
->chr_can_read
[m
] &&
2025 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2026 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2028 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2032 static void mux_chr_event(void *opaque
, int event
)
2034 CharDriverState
*chr
= opaque
;
2035 MuxDriver
*d
= chr
->opaque
;
2038 /* Send the event to all registered listeners */
2039 for (i
= 0; i
< d
->mux_cnt
; i
++)
2040 if (d
->chr_event
[i
])
2041 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2044 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2046 MuxDriver
*d
= chr
->opaque
;
2048 if (d
->mux_cnt
>= MAX_MUX
) {
2049 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2052 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2053 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2054 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2055 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2056 /* Fix up the real driver with mux routines */
2057 if (d
->mux_cnt
== 0) {
2058 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2059 mux_chr_event
, chr
);
2061 chr
->focus
= d
->mux_cnt
;
2065 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2067 CharDriverState
*chr
;
2070 chr
= qemu_mallocz(sizeof(CharDriverState
));
2073 d
= qemu_mallocz(sizeof(MuxDriver
));
2082 chr
->chr_write
= mux_chr_write
;
2083 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2084 chr
->chr_accept_input
= mux_chr_accept_input
;
2091 static void socket_cleanup(void)
2096 static int socket_init(void)
2101 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2103 err
= WSAGetLastError();
2104 fprintf(stderr
, "WSAStartup: %d\n", err
);
2107 atexit(socket_cleanup
);
2111 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2117 ret
= send(fd
, buf
, len
, 0);
2120 errno
= WSAGetLastError();
2121 if (errno
!= WSAEWOULDBLOCK
) {
2124 } else if (ret
== 0) {
2134 void socket_set_nonblock(int fd
)
2136 unsigned long opt
= 1;
2137 ioctlsocket(fd
, FIONBIO
, &opt
);
2142 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2148 ret
= write(fd
, buf
, len
);
2150 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2152 } else if (ret
== 0) {
2162 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2164 return unix_write(fd
, buf
, len1
);
2167 void socket_set_nonblock(int fd
)
2170 f
= fcntl(fd
, F_GETFL
);
2171 fcntl(fd
, F_SETFL
, f
| O_NONBLOCK
);
2173 #endif /* !_WIN32 */
2182 #define STDIO_MAX_CLIENTS 1
2183 static int stdio_nb_clients
= 0;
2185 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2187 FDCharDriver
*s
= chr
->opaque
;
2188 return unix_write(s
->fd_out
, buf
, len
);
2191 static int fd_chr_read_poll(void *opaque
)
2193 CharDriverState
*chr
= opaque
;
2194 FDCharDriver
*s
= chr
->opaque
;
2196 s
->max_size
= qemu_chr_can_read(chr
);
2200 static void fd_chr_read(void *opaque
)
2202 CharDriverState
*chr
= opaque
;
2203 FDCharDriver
*s
= chr
->opaque
;
2208 if (len
> s
->max_size
)
2212 size
= read(s
->fd_in
, buf
, len
);
2214 /* FD has been closed. Remove it from the active list. */
2215 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2219 qemu_chr_read(chr
, buf
, size
);
2223 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2225 FDCharDriver
*s
= chr
->opaque
;
2227 if (s
->fd_in
>= 0) {
2228 if (nographic
&& s
->fd_in
== 0) {
2230 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2231 fd_chr_read
, NULL
, chr
);
2236 static void fd_chr_close(struct CharDriverState
*chr
)
2238 FDCharDriver
*s
= chr
->opaque
;
2240 if (s
->fd_in
>= 0) {
2241 if (nographic
&& s
->fd_in
== 0) {
2243 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2250 /* open a character device to a unix fd */
2251 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2253 CharDriverState
*chr
;
2256 chr
= qemu_mallocz(sizeof(CharDriverState
));
2259 s
= qemu_mallocz(sizeof(FDCharDriver
));
2267 chr
->chr_write
= fd_chr_write
;
2268 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2269 chr
->chr_close
= fd_chr_close
;
2271 qemu_chr_reset(chr
);
2276 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2280 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2283 return qemu_chr_open_fd(-1, fd_out
);
2286 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2289 char filename_in
[256], filename_out
[256];
2291 snprintf(filename_in
, 256, "%s.in", filename
);
2292 snprintf(filename_out
, 256, "%s.out", filename
);
2293 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2294 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2295 if (fd_in
< 0 || fd_out
< 0) {
2300 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2304 return qemu_chr_open_fd(fd_in
, fd_out
);
2308 /* for STDIO, we handle the case where several clients use it
2311 #define TERM_FIFO_MAX_SIZE 1
2313 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2314 static int term_fifo_size
;
2316 static int stdio_read_poll(void *opaque
)
2318 CharDriverState
*chr
= opaque
;
2320 /* try to flush the queue if needed */
2321 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2322 qemu_chr_read(chr
, term_fifo
, 1);
2325 /* see if we can absorb more chars */
2326 if (term_fifo_size
== 0)
2332 static void stdio_read(void *opaque
)
2336 CharDriverState
*chr
= opaque
;
2338 size
= read(0, buf
, 1);
2340 /* stdin has been closed. Remove it from the active list. */
2341 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2345 if (qemu_chr_can_read(chr
) > 0) {
2346 qemu_chr_read(chr
, buf
, 1);
2347 } else if (term_fifo_size
== 0) {
2348 term_fifo
[term_fifo_size
++] = buf
[0];
2353 /* init terminal so that we can grab keys */
2354 static struct termios oldtty
;
2355 static int old_fd0_flags
;
2356 static int term_atexit_done
;
2358 static void term_exit(void)
2360 tcsetattr (0, TCSANOW
, &oldtty
);
2361 fcntl(0, F_SETFL
, old_fd0_flags
);
2364 static void term_init(void)
2368 tcgetattr (0, &tty
);
2370 old_fd0_flags
= fcntl(0, F_GETFL
);
2372 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2373 |INLCR
|IGNCR
|ICRNL
|IXON
);
2374 tty
.c_oflag
|= OPOST
;
2375 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2376 /* if graphical mode, we allow Ctrl-C handling */
2378 tty
.c_lflag
&= ~ISIG
;
2379 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2382 tty
.c_cc
[VTIME
] = 0;
2384 tcsetattr (0, TCSANOW
, &tty
);
2386 if (!term_atexit_done
++)
2389 fcntl(0, F_SETFL
, O_NONBLOCK
);
2392 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2396 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2400 static CharDriverState
*qemu_chr_open_stdio(void)
2402 CharDriverState
*chr
;
2404 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2406 chr
= qemu_chr_open_fd(0, 1);
2407 chr
->chr_close
= qemu_chr_close_stdio
;
2408 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2416 /* Once Solaris has openpty(), this is going to be removed. */
2417 int openpty(int *amaster
, int *aslave
, char *name
,
2418 struct termios
*termp
, struct winsize
*winp
)
2421 int mfd
= -1, sfd
= -1;
2423 *amaster
= *aslave
= -1;
2425 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2429 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2432 if ((slave
= ptsname(mfd
)) == NULL
)
2435 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2438 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2439 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2447 ioctl(sfd
, TIOCSWINSZ
, winp
);
2458 void cfmakeraw (struct termios
*termios_p
)
2460 termios_p
->c_iflag
&=
2461 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2462 termios_p
->c_oflag
&= ~OPOST
;
2463 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2464 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2465 termios_p
->c_cflag
|= CS8
;
2467 termios_p
->c_cc
[VMIN
] = 0;
2468 termios_p
->c_cc
[VTIME
] = 0;
2472 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2473 || defined(__NetBSD__) || defined(__OpenBSD__)
2483 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2484 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2486 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2488 PtyCharDriver
*s
= chr
->opaque
;
2490 if (!s
->connected
) {
2491 /* guest sends data, check for (re-)connect */
2492 pty_chr_update_read_handler(chr
);
2495 return unix_write(s
->fd
, buf
, len
);
2498 static int pty_chr_read_poll(void *opaque
)
2500 CharDriverState
*chr
= opaque
;
2501 PtyCharDriver
*s
= chr
->opaque
;
2503 s
->read_bytes
= qemu_chr_can_read(chr
);
2504 return s
->read_bytes
;
2507 static void pty_chr_read(void *opaque
)
2509 CharDriverState
*chr
= opaque
;
2510 PtyCharDriver
*s
= chr
->opaque
;
2515 if (len
> s
->read_bytes
)
2516 len
= s
->read_bytes
;
2519 size
= read(s
->fd
, buf
, len
);
2520 if ((size
== -1 && errno
== EIO
) ||
2522 pty_chr_state(chr
, 0);
2526 pty_chr_state(chr
, 1);
2527 qemu_chr_read(chr
, buf
, size
);
2531 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2533 PtyCharDriver
*s
= chr
->opaque
;
2535 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2536 pty_chr_read
, NULL
, chr
);
2539 * Short timeout here: just need wait long enougth that qemu makes
2540 * it through the poll loop once. When reconnected we want a
2541 * short timeout so we notice it almost instantly. Otherwise
2542 * read() gives us -EIO instantly, making pty_chr_state() reset the
2543 * timeout to the normal (much longer) poll interval before the
2546 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2549 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2551 PtyCharDriver
*s
= chr
->opaque
;
2554 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2557 /* (re-)connect poll interval for idle guests: once per second.
2558 * We check more frequently in case the guests sends data to
2559 * the virtual device linked to our pty. */
2560 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2563 qemu_chr_reset(chr
);
2568 static void pty_chr_timer(void *opaque
)
2570 struct CharDriverState
*chr
= opaque
;
2571 PtyCharDriver
*s
= chr
->opaque
;
2576 /* If we arrive here without polling being cleared due
2577 * read returning -EIO, then we are (re-)connected */
2578 pty_chr_state(chr
, 1);
2583 pty_chr_update_read_handler(chr
);
2586 static void pty_chr_close(struct CharDriverState
*chr
)
2588 PtyCharDriver
*s
= chr
->opaque
;
2590 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2595 static CharDriverState
*qemu_chr_open_pty(void)
2597 CharDriverState
*chr
;
2601 #if defined(__OpenBSD__)
2602 char pty_name
[PATH_MAX
];
2603 #define q_ptsname(x) pty_name
2605 char *pty_name
= NULL
;
2606 #define q_ptsname(x) ptsname(x)
2609 chr
= qemu_mallocz(sizeof(CharDriverState
));
2612 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2618 if (openpty(&s
->fd
, &slave_fd
, pty_name
, NULL
, NULL
) < 0) {
2622 /* Set raw attributes on the pty. */
2624 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2627 fprintf(stderr
, "char device redirected to %s\n", q_ptsname(s
->fd
));
2630 chr
->chr_write
= pty_chr_write
;
2631 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2632 chr
->chr_close
= pty_chr_close
;
2634 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2639 static void tty_serial_init(int fd
, int speed
,
2640 int parity
, int data_bits
, int stop_bits
)
2646 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2647 speed
, parity
, data_bits
, stop_bits
);
2649 tcgetattr (fd
, &tty
);
2652 if (speed
<= 50 * MARGIN
)
2654 else if (speed
<= 75 * MARGIN
)
2656 else if (speed
<= 300 * MARGIN
)
2658 else if (speed
<= 600 * MARGIN
)
2660 else if (speed
<= 1200 * MARGIN
)
2662 else if (speed
<= 2400 * MARGIN
)
2664 else if (speed
<= 4800 * MARGIN
)
2666 else if (speed
<= 9600 * MARGIN
)
2668 else if (speed
<= 19200 * MARGIN
)
2670 else if (speed
<= 38400 * MARGIN
)
2672 else if (speed
<= 57600 * MARGIN
)
2674 else if (speed
<= 115200 * MARGIN
)
2679 cfsetispeed(&tty
, spd
);
2680 cfsetospeed(&tty
, spd
);
2682 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2683 |INLCR
|IGNCR
|ICRNL
|IXON
);
2684 tty
.c_oflag
|= OPOST
;
2685 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2686 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2707 tty
.c_cflag
|= PARENB
;
2710 tty
.c_cflag
|= PARENB
| PARODD
;
2714 tty
.c_cflag
|= CSTOPB
;
2716 tcsetattr (fd
, TCSANOW
, &tty
);
2719 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2721 FDCharDriver
*s
= chr
->opaque
;
2724 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2726 QEMUSerialSetParams
*ssp
= arg
;
2727 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2728 ssp
->data_bits
, ssp
->stop_bits
);
2731 case CHR_IOCTL_SERIAL_SET_BREAK
:
2733 int enable
= *(int *)arg
;
2735 tcsendbreak(s
->fd_in
, 1);
2738 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2741 int *targ
= (int *)arg
;
2742 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2744 if (sarg
| TIOCM_CTS
)
2745 *targ
|= CHR_TIOCM_CTS
;
2746 if (sarg
| TIOCM_CAR
)
2747 *targ
|= CHR_TIOCM_CAR
;
2748 if (sarg
| TIOCM_DSR
)
2749 *targ
|= CHR_TIOCM_DSR
;
2750 if (sarg
| TIOCM_RI
)
2751 *targ
|= CHR_TIOCM_RI
;
2752 if (sarg
| TIOCM_DTR
)
2753 *targ
|= CHR_TIOCM_DTR
;
2754 if (sarg
| TIOCM_RTS
)
2755 *targ
|= CHR_TIOCM_RTS
;
2758 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2760 int sarg
= *(int *)arg
;
2762 if (sarg
| CHR_TIOCM_DTR
)
2764 if (sarg
| CHR_TIOCM_RTS
)
2766 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2775 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2777 CharDriverState
*chr
;
2780 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2781 tty_serial_init(fd
, 115200, 'N', 8, 1);
2782 chr
= qemu_chr_open_fd(fd
, fd
);
2787 chr
->chr_ioctl
= tty_serial_ioctl
;
2788 qemu_chr_reset(chr
);
2791 #else /* ! __linux__ && ! __sun__ */
2792 static CharDriverState
*qemu_chr_open_pty(void)
2796 #endif /* __linux__ || __sun__ */
2798 #if defined(__linux__)
2802 } ParallelCharDriver
;
2804 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2806 if (s
->mode
!= mode
) {
2808 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2815 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2817 ParallelCharDriver
*drv
= chr
->opaque
;
2822 case CHR_IOCTL_PP_READ_DATA
:
2823 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2825 *(uint8_t *)arg
= b
;
2827 case CHR_IOCTL_PP_WRITE_DATA
:
2828 b
= *(uint8_t *)arg
;
2829 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2832 case CHR_IOCTL_PP_READ_CONTROL
:
2833 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2835 /* Linux gives only the lowest bits, and no way to know data
2836 direction! For better compatibility set the fixed upper
2838 *(uint8_t *)arg
= b
| 0xc0;
2840 case CHR_IOCTL_PP_WRITE_CONTROL
:
2841 b
= *(uint8_t *)arg
;
2842 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2845 case CHR_IOCTL_PP_READ_STATUS
:
2846 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2848 *(uint8_t *)arg
= b
;
2850 case CHR_IOCTL_PP_DATA_DIR
:
2851 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
2854 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2855 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2856 struct ParallelIOArg
*parg
= arg
;
2857 int n
= read(fd
, parg
->buffer
, parg
->count
);
2858 if (n
!= parg
->count
) {
2863 case CHR_IOCTL_PP_EPP_READ
:
2864 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2865 struct ParallelIOArg
*parg
= arg
;
2866 int n
= read(fd
, parg
->buffer
, parg
->count
);
2867 if (n
!= parg
->count
) {
2872 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2873 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2874 struct ParallelIOArg
*parg
= arg
;
2875 int n
= write(fd
, parg
->buffer
, parg
->count
);
2876 if (n
!= parg
->count
) {
2881 case CHR_IOCTL_PP_EPP_WRITE
:
2882 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2883 struct ParallelIOArg
*parg
= arg
;
2884 int n
= write(fd
, parg
->buffer
, parg
->count
);
2885 if (n
!= parg
->count
) {
2896 static void pp_close(CharDriverState
*chr
)
2898 ParallelCharDriver
*drv
= chr
->opaque
;
2901 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2902 ioctl(fd
, PPRELEASE
);
2907 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2909 CharDriverState
*chr
;
2910 ParallelCharDriver
*drv
;
2913 TFR(fd
= open(filename
, O_RDWR
));
2917 if (ioctl(fd
, PPCLAIM
) < 0) {
2922 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2928 drv
->mode
= IEEE1284_MODE_COMPAT
;
2930 chr
= qemu_mallocz(sizeof(CharDriverState
));
2936 chr
->chr_write
= null_chr_write
;
2937 chr
->chr_ioctl
= pp_ioctl
;
2938 chr
->chr_close
= pp_close
;
2941 qemu_chr_reset(chr
);
2945 #endif /* __linux__ */
2951 HANDLE hcom
, hrecv
, hsend
;
2952 OVERLAPPED orecv
, osend
;
2957 #define NSENDBUF 2048
2958 #define NRECVBUF 2048
2959 #define MAXCONNECT 1
2960 #define NTIMEOUT 5000
2962 static int win_chr_poll(void *opaque
);
2963 static int win_chr_pipe_poll(void *opaque
);
2965 static void win_chr_close(CharDriverState
*chr
)
2967 WinCharState
*s
= chr
->opaque
;
2970 CloseHandle(s
->hsend
);
2974 CloseHandle(s
->hrecv
);
2978 CloseHandle(s
->hcom
);
2982 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2984 qemu_del_polling_cb(win_chr_poll
, chr
);
2987 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2989 WinCharState
*s
= chr
->opaque
;
2991 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2996 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2998 fprintf(stderr
, "Failed CreateEvent\n");
3001 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3003 fprintf(stderr
, "Failed CreateEvent\n");
3007 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
3008 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
3009 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3010 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3015 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3016 fprintf(stderr
, "Failed SetupComm\n");
3020 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3021 size
= sizeof(COMMCONFIG
);
3022 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3023 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3024 CommConfigDialog(filename
, NULL
, &comcfg
);
3026 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3027 fprintf(stderr
, "Failed SetCommState\n");
3031 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3032 fprintf(stderr
, "Failed SetCommMask\n");
3036 cto
.ReadIntervalTimeout
= MAXDWORD
;
3037 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3038 fprintf(stderr
, "Failed SetCommTimeouts\n");
3042 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3043 fprintf(stderr
, "Failed ClearCommError\n");
3046 qemu_add_polling_cb(win_chr_poll
, chr
);
3054 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3056 WinCharState
*s
= chr
->opaque
;
3057 DWORD len
, ret
, size
, err
;
3060 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3061 s
->osend
.hEvent
= s
->hsend
;
3064 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3066 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3068 err
= GetLastError();
3069 if (err
== ERROR_IO_PENDING
) {
3070 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3088 static int win_chr_read_poll(CharDriverState
*chr
)
3090 WinCharState
*s
= chr
->opaque
;
3092 s
->max_size
= qemu_chr_can_read(chr
);
3096 static void win_chr_readfile(CharDriverState
*chr
)
3098 WinCharState
*s
= chr
->opaque
;
3103 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3104 s
->orecv
.hEvent
= s
->hrecv
;
3105 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3107 err
= GetLastError();
3108 if (err
== ERROR_IO_PENDING
) {
3109 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3114 qemu_chr_read(chr
, buf
, size
);
3118 static void win_chr_read(CharDriverState
*chr
)
3120 WinCharState
*s
= chr
->opaque
;
3122 if (s
->len
> s
->max_size
)
3123 s
->len
= s
->max_size
;
3127 win_chr_readfile(chr
);
3130 static int win_chr_poll(void *opaque
)
3132 CharDriverState
*chr
= opaque
;
3133 WinCharState
*s
= chr
->opaque
;
3137 ClearCommError(s
->hcom
, &comerr
, &status
);
3138 if (status
.cbInQue
> 0) {
3139 s
->len
= status
.cbInQue
;
3140 win_chr_read_poll(chr
);
3147 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3149 CharDriverState
*chr
;
3152 chr
= qemu_mallocz(sizeof(CharDriverState
));
3155 s
= qemu_mallocz(sizeof(WinCharState
));
3161 chr
->chr_write
= win_chr_write
;
3162 chr
->chr_close
= win_chr_close
;
3164 if (win_chr_init(chr
, filename
) < 0) {
3169 qemu_chr_reset(chr
);
3173 static int win_chr_pipe_poll(void *opaque
)
3175 CharDriverState
*chr
= opaque
;
3176 WinCharState
*s
= chr
->opaque
;
3179 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3182 win_chr_read_poll(chr
);
3189 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3191 WinCharState
*s
= chr
->opaque
;
3199 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3201 fprintf(stderr
, "Failed CreateEvent\n");
3204 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3206 fprintf(stderr
, "Failed CreateEvent\n");
3210 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3211 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3212 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3214 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3215 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3216 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3221 ZeroMemory(&ov
, sizeof(ov
));
3222 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3223 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3225 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3229 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3231 fprintf(stderr
, "Failed GetOverlappedResult\n");
3233 CloseHandle(ov
.hEvent
);
3240 CloseHandle(ov
.hEvent
);
3243 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3252 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3254 CharDriverState
*chr
;
3257 chr
= qemu_mallocz(sizeof(CharDriverState
));
3260 s
= qemu_mallocz(sizeof(WinCharState
));
3266 chr
->chr_write
= win_chr_write
;
3267 chr
->chr_close
= win_chr_close
;
3269 if (win_chr_pipe_init(chr
, filename
) < 0) {
3274 qemu_chr_reset(chr
);
3278 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3280 CharDriverState
*chr
;
3283 chr
= qemu_mallocz(sizeof(CharDriverState
));
3286 s
= qemu_mallocz(sizeof(WinCharState
));
3293 chr
->chr_write
= win_chr_write
;
3294 qemu_chr_reset(chr
);
3298 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3300 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3303 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3307 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3308 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3309 if (fd_out
== INVALID_HANDLE_VALUE
)
3312 return qemu_chr_open_win_file(fd_out
);
3314 #endif /* !_WIN32 */
3316 /***********************************************************/
3317 /* UDP Net console */
3321 struct sockaddr_in daddr
;
3328 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3330 NetCharDriver
*s
= chr
->opaque
;
3332 return sendto(s
->fd
, buf
, len
, 0,
3333 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3336 static int udp_chr_read_poll(void *opaque
)
3338 CharDriverState
*chr
= opaque
;
3339 NetCharDriver
*s
= chr
->opaque
;
3341 s
->max_size
= qemu_chr_can_read(chr
);
3343 /* If there were any stray characters in the queue process them
3346 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3347 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3349 s
->max_size
= qemu_chr_can_read(chr
);
3354 static void udp_chr_read(void *opaque
)
3356 CharDriverState
*chr
= opaque
;
3357 NetCharDriver
*s
= chr
->opaque
;
3359 if (s
->max_size
== 0)
3361 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3362 s
->bufptr
= s
->bufcnt
;
3367 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3368 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3370 s
->max_size
= qemu_chr_can_read(chr
);
3374 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3376 NetCharDriver
*s
= chr
->opaque
;
3379 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3380 udp_chr_read
, NULL
, chr
);
3384 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
3386 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3388 int parse_host_src_port(struct sockaddr_in
*haddr
,
3389 struct sockaddr_in
*saddr
,
3392 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3394 CharDriverState
*chr
= NULL
;
3395 NetCharDriver
*s
= NULL
;
3397 struct sockaddr_in saddr
;
3399 chr
= qemu_mallocz(sizeof(CharDriverState
));
3402 s
= qemu_mallocz(sizeof(NetCharDriver
));
3406 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3408 perror("socket(PF_INET, SOCK_DGRAM)");
3412 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3413 printf("Could not parse: %s\n", def
);
3417 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3427 chr
->chr_write
= udp_chr_write
;
3428 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3441 /***********************************************************/
3442 /* TCP Net console */
3453 static void tcp_chr_accept(void *opaque
);
3455 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3457 TCPCharDriver
*s
= chr
->opaque
;
3459 return send_all(s
->fd
, buf
, len
);
3461 /* XXX: indicate an error ? */
3466 static int tcp_chr_read_poll(void *opaque
)
3468 CharDriverState
*chr
= opaque
;
3469 TCPCharDriver
*s
= chr
->opaque
;
3472 s
->max_size
= qemu_chr_can_read(chr
);
3477 #define IAC_BREAK 243
3478 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3480 uint8_t *buf
, int *size
)
3482 /* Handle any telnet client's basic IAC options to satisfy char by
3483 * char mode with no echo. All IAC options will be removed from
3484 * the buf and the do_telnetopt variable will be used to track the
3485 * state of the width of the IAC information.
3487 * IAC commands come in sets of 3 bytes with the exception of the
3488 * "IAC BREAK" command and the double IAC.
3494 for (i
= 0; i
< *size
; i
++) {
3495 if (s
->do_telnetopt
> 1) {
3496 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3497 /* Double IAC means send an IAC */
3501 s
->do_telnetopt
= 1;
3503 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3504 /* Handle IAC break commands by sending a serial break */
3505 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3510 if (s
->do_telnetopt
>= 4) {
3511 s
->do_telnetopt
= 1;
3514 if ((unsigned char)buf
[i
] == IAC
) {
3515 s
->do_telnetopt
= 2;
3526 static void tcp_chr_read(void *opaque
)
3528 CharDriverState
*chr
= opaque
;
3529 TCPCharDriver
*s
= chr
->opaque
;
3533 if (!s
->connected
|| s
->max_size
<= 0)
3536 if (len
> s
->max_size
)
3538 size
= recv(s
->fd
, buf
, len
, 0);
3540 /* connection closed */
3542 if (s
->listen_fd
>= 0) {
3543 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3545 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3548 } else if (size
> 0) {
3549 if (s
->do_telnetopt
)
3550 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3552 qemu_chr_read(chr
, buf
, size
);
3556 static void tcp_chr_connect(void *opaque
)
3558 CharDriverState
*chr
= opaque
;
3559 TCPCharDriver
*s
= chr
->opaque
;
3562 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3563 tcp_chr_read
, NULL
, chr
);
3564 qemu_chr_reset(chr
);
3567 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3568 static void tcp_chr_telnet_init(int fd
)
3571 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3572 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3573 send(fd
, (char *)buf
, 3, 0);
3574 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3575 send(fd
, (char *)buf
, 3, 0);
3576 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3577 send(fd
, (char *)buf
, 3, 0);
3578 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3579 send(fd
, (char *)buf
, 3, 0);
3582 static void socket_set_nodelay(int fd
)
3585 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3588 static void tcp_chr_accept(void *opaque
)
3590 CharDriverState
*chr
= opaque
;
3591 TCPCharDriver
*s
= chr
->opaque
;
3592 struct sockaddr_in saddr
;
3594 struct sockaddr_un uaddr
;
3596 struct sockaddr
*addr
;
3603 len
= sizeof(uaddr
);
3604 addr
= (struct sockaddr
*)&uaddr
;
3608 len
= sizeof(saddr
);
3609 addr
= (struct sockaddr
*)&saddr
;
3611 fd
= accept(s
->listen_fd
, addr
, &len
);
3612 if (fd
< 0 && errno
!= EINTR
) {
3614 } else if (fd
>= 0) {
3615 if (s
->do_telnetopt
)
3616 tcp_chr_telnet_init(fd
);
3620 socket_set_nonblock(fd
);
3622 socket_set_nodelay(fd
);
3624 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3625 tcp_chr_connect(chr
);
3628 static void tcp_chr_close(CharDriverState
*chr
)
3630 TCPCharDriver
*s
= chr
->opaque
;
3633 if (s
->listen_fd
>= 0)
3634 closesocket(s
->listen_fd
);
3638 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3642 CharDriverState
*chr
= NULL
;
3643 TCPCharDriver
*s
= NULL
;
3644 int fd
= -1, ret
, err
, val
;
3646 int is_waitconnect
= 1;
3649 struct sockaddr_in saddr
;
3651 struct sockaddr_un uaddr
;
3653 struct sockaddr
*addr
;
3658 addr
= (struct sockaddr
*)&uaddr
;
3659 addrlen
= sizeof(uaddr
);
3660 if (parse_unix_path(&uaddr
, host_str
) < 0)
3665 addr
= (struct sockaddr
*)&saddr
;
3666 addrlen
= sizeof(saddr
);
3667 if (parse_host_port(&saddr
, host_str
) < 0)
3672 while((ptr
= strchr(ptr
,','))) {
3674 if (!strncmp(ptr
,"server",6)) {
3676 } else if (!strncmp(ptr
,"nowait",6)) {
3678 } else if (!strncmp(ptr
,"nodelay",6)) {
3681 printf("Unknown option: %s\n", ptr
);
3688 chr
= qemu_mallocz(sizeof(CharDriverState
));
3691 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3697 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3700 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3705 if (!is_waitconnect
)
3706 socket_set_nonblock(fd
);
3711 s
->is_unix
= is_unix
;
3712 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3715 chr
->chr_write
= tcp_chr_write
;
3716 chr
->chr_close
= tcp_chr_close
;
3719 /* allow fast reuse */
3723 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3729 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3732 ret
= bind(fd
, addr
, addrlen
);
3736 ret
= listen(fd
, 0);
3741 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3743 s
->do_telnetopt
= 1;
3746 ret
= connect(fd
, addr
, addrlen
);
3748 err
= socket_error();
3749 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3750 } else if (err
== EINPROGRESS
) {
3753 } else if (err
== WSAEALREADY
) {
3765 socket_set_nodelay(fd
);
3767 tcp_chr_connect(chr
);
3769 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3772 if (is_listen
&& is_waitconnect
) {
3773 printf("QEMU waiting for connection on: %s\n", host_str
);
3774 tcp_chr_accept(chr
);
3775 socket_set_nonblock(s
->listen_fd
);
3787 CharDriverState
*qemu_chr_open(const char *filename
)
3791 if (!strcmp(filename
, "vc")) {
3792 return text_console_init(&display_state
, 0);
3793 } else if (strstart(filename
, "vc:", &p
)) {
3794 return text_console_init(&display_state
, p
);
3795 } else if (!strcmp(filename
, "null")) {
3796 return qemu_chr_open_null();
3798 if (strstart(filename
, "tcp:", &p
)) {
3799 return qemu_chr_open_tcp(p
, 0, 0);
3801 if (strstart(filename
, "telnet:", &p
)) {
3802 return qemu_chr_open_tcp(p
, 1, 0);
3804 if (strstart(filename
, "udp:", &p
)) {
3805 return qemu_chr_open_udp(p
);
3807 if (strstart(filename
, "mon:", &p
)) {
3808 CharDriverState
*drv
= qemu_chr_open(p
);
3810 drv
= qemu_chr_open_mux(drv
);
3811 monitor_init(drv
, !nographic
);
3814 printf("Unable to open driver: %s\n", p
);
3818 if (strstart(filename
, "unix:", &p
)) {
3819 return qemu_chr_open_tcp(p
, 0, 1);
3820 } else if (strstart(filename
, "file:", &p
)) {
3821 return qemu_chr_open_file_out(p
);
3822 } else if (strstart(filename
, "pipe:", &p
)) {
3823 return qemu_chr_open_pipe(p
);
3824 } else if (!strcmp(filename
, "pty")) {
3825 return qemu_chr_open_pty();
3826 } else if (!strcmp(filename
, "stdio")) {
3827 return qemu_chr_open_stdio();
3829 #if defined(__linux__)
3830 if (strstart(filename
, "/dev/parport", NULL
)) {
3831 return qemu_chr_open_pp(filename
);
3834 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3835 || defined(__NetBSD__) || defined(__OpenBSD__)
3836 if (strstart(filename
, "/dev/", NULL
)) {
3837 return qemu_chr_open_tty(filename
);
3841 if (strstart(filename
, "COM", NULL
)) {
3842 return qemu_chr_open_win(filename
);
3844 if (strstart(filename
, "pipe:", &p
)) {
3845 return qemu_chr_open_win_pipe(p
);
3847 if (strstart(filename
, "con:", NULL
)) {
3848 return qemu_chr_open_win_con(filename
);
3850 if (strstart(filename
, "file:", &p
)) {
3851 return qemu_chr_open_win_file_out(p
);
3854 #ifdef CONFIG_BRLAPI
3855 if (!strcmp(filename
, "braille")) {
3856 return chr_baum_init();
3864 void qemu_chr_close(CharDriverState
*chr
)
3867 chr
->chr_close(chr
);
3871 /***********************************************************/
3872 /* network device redirectors */
3874 __attribute__ (( unused
))
3875 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3879 for(i
=0;i
<size
;i
+=16) {
3883 fprintf(f
, "%08x ", i
);
3886 fprintf(f
, " %02x", buf
[i
+j
]);
3891 for(j
=0;j
<len
;j
++) {
3893 if (c
< ' ' || c
> '~')
3895 fprintf(f
, "%c", c
);
3901 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3908 offset
= strtol(p
, &last_char
, 0);
3909 if (0 == errno
&& '\0' == *last_char
&&
3910 offset
>= 0 && offset
<= 0xFFFFFF) {
3911 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3912 macaddr
[4] = (offset
& 0xFF00) >> 8;
3913 macaddr
[5] = offset
& 0xFF;
3916 for(i
= 0; i
< 6; i
++) {
3917 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3922 if (*p
!= ':' && *p
!= '-')
3933 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3938 p1
= strchr(p
, sep
);
3944 if (len
> buf_size
- 1)
3946 memcpy(buf
, p
, len
);
3953 int parse_host_src_port(struct sockaddr_in
*haddr
,
3954 struct sockaddr_in
*saddr
,
3955 const char *input_str
)
3957 char *str
= strdup(input_str
);
3958 char *host_str
= str
;
3960 const char *src_str2
;
3964 * Chop off any extra arguments at the end of the string which
3965 * would start with a comma, then fill in the src port information
3966 * if it was provided else use the "any address" and "any port".
3968 if ((ptr
= strchr(str
,',')))
3971 if ((src_str
= strchr(input_str
,'@'))) {
3976 if (parse_host_port(haddr
, host_str
) < 0)
3980 if (!src_str
|| *src_str
== '\0')
3983 if (parse_host_port(saddr
, src_str2
) < 0)
3994 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
4002 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4004 saddr
->sin_family
= AF_INET
;
4005 if (buf
[0] == '\0') {
4006 saddr
->sin_addr
.s_addr
= 0;
4008 if (isdigit(buf
[0])) {
4009 if (!inet_aton(buf
, &saddr
->sin_addr
))
4012 if ((he
= gethostbyname(buf
)) == NULL
)
4014 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4017 port
= strtol(p
, (char **)&r
, 0);
4020 saddr
->sin_port
= htons(port
);
4025 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4030 len
= MIN(108, strlen(str
));
4031 p
= strchr(str
, ',');
4033 len
= MIN(len
, p
- str
);
4035 memset(uaddr
, 0, sizeof(*uaddr
));
4037 uaddr
->sun_family
= AF_UNIX
;
4038 memcpy(uaddr
->sun_path
, str
, len
);
4044 /* find or alloc a new VLAN */
4045 VLANState
*qemu_find_vlan(int id
)
4047 VLANState
**pvlan
, *vlan
;
4048 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4052 vlan
= qemu_mallocz(sizeof(VLANState
));
4057 pvlan
= &first_vlan
;
4058 while (*pvlan
!= NULL
)
4059 pvlan
= &(*pvlan
)->next
;
4064 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4065 IOReadHandler
*fd_read
,
4066 IOCanRWHandler
*fd_can_read
,
4069 VLANClientState
*vc
, **pvc
;
4070 vc
= qemu_mallocz(sizeof(VLANClientState
));
4073 vc
->fd_read
= fd_read
;
4074 vc
->fd_can_read
= fd_can_read
;
4075 vc
->opaque
= opaque
;
4079 pvc
= &vlan
->first_client
;
4080 while (*pvc
!= NULL
)
4081 pvc
= &(*pvc
)->next
;
4086 void qemu_del_vlan_client(VLANClientState
*vc
)
4088 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4090 while (*pvc
!= NULL
)
4096 pvc
= &(*pvc
)->next
;
4099 int qemu_can_send_packet(VLANClientState
*vc1
)
4101 VLANState
*vlan
= vc1
->vlan
;
4102 VLANClientState
*vc
;
4104 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4106 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4113 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4115 VLANState
*vlan
= vc1
->vlan
;
4116 VLANClientState
*vc
;
4119 printf("vlan %d send:\n", vlan
->id
);
4120 hex_dump(stdout
, buf
, size
);
4122 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4124 vc
->fd_read(vc
->opaque
, buf
, size
);
4129 #if defined(CONFIG_SLIRP)
4131 /* slirp network adapter */
4133 static int slirp_inited
;
4134 static VLANClientState
*slirp_vc
;
4136 int slirp_can_output(void)
4138 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4141 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4144 printf("slirp output:\n");
4145 hex_dump(stdout
, pkt
, pkt_len
);
4149 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4152 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4155 printf("slirp input:\n");
4156 hex_dump(stdout
, buf
, size
);
4158 slirp_input(buf
, size
);
4161 static int net_slirp_init(VLANState
*vlan
)
4163 if (!slirp_inited
) {
4167 slirp_vc
= qemu_new_vlan_client(vlan
,
4168 slirp_receive
, NULL
, NULL
);
4169 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4173 static void net_slirp_redir(const char *redir_str
)
4178 struct in_addr guest_addr
;
4179 int host_port
, guest_port
;
4181 if (!slirp_inited
) {
4187 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4189 if (!strcmp(buf
, "tcp")) {
4191 } else if (!strcmp(buf
, "udp")) {
4197 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4199 host_port
= strtol(buf
, &r
, 0);
4203 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4205 if (buf
[0] == '\0') {
4206 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4208 if (!inet_aton(buf
, &guest_addr
))
4211 guest_port
= strtol(p
, &r
, 0);
4215 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4216 fprintf(stderr
, "qemu: could not set up redirection\n");
4221 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4229 static void erase_dir(char *dir_name
)
4233 char filename
[1024];
4235 /* erase all the files in the directory */
4236 if ((d
= opendir(dir_name
)) != 0) {
4241 if (strcmp(de
->d_name
, ".") != 0 &&
4242 strcmp(de
->d_name
, "..") != 0) {
4243 snprintf(filename
, sizeof(filename
), "%s/%s",
4244 smb_dir
, de
->d_name
);
4245 if (unlink(filename
) != 0) /* is it a directory? */
4246 erase_dir(filename
);
4254 /* automatic user mode samba server configuration */
4255 static void smb_exit(void)
4260 /* automatic user mode samba server configuration */
4261 static void net_slirp_smb(const char *exported_dir
)
4263 char smb_conf
[1024];
4264 char smb_cmdline
[1024];
4267 if (!slirp_inited
) {
4272 /* XXX: better tmp dir construction */
4273 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4274 if (mkdir(smb_dir
, 0700) < 0) {
4275 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4278 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4280 f
= fopen(smb_conf
, "w");
4282 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4289 "socket address=127.0.0.1\n"
4290 "pid directory=%s\n"
4291 "lock directory=%s\n"
4292 "log file=%s/log.smbd\n"
4293 "smb passwd file=%s/smbpasswd\n"
4294 "security = share\n"
4309 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4310 SMBD_COMMAND
, smb_conf
);
4312 slirp_add_exec(0, smb_cmdline
, 4, 139);
4315 #endif /* !defined(_WIN32) */
4316 void do_info_slirp(void)
4321 #endif /* CONFIG_SLIRP */
4323 #if !defined(_WIN32)
4325 typedef struct TAPState
{
4326 VLANClientState
*vc
;
4328 char down_script
[1024];
4331 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4333 TAPState
*s
= opaque
;
4336 ret
= write(s
->fd
, buf
, size
);
4337 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4344 static void tap_send(void *opaque
)
4346 TAPState
*s
= opaque
;
4353 sbuf
.maxlen
= sizeof(buf
);
4355 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4357 size
= read(s
->fd
, buf
, sizeof(buf
));
4360 qemu_send_packet(s
->vc
, buf
, size
);
4366 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4370 s
= qemu_mallocz(sizeof(TAPState
));
4374 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4375 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
4376 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4380 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4381 static int tap_open(char *ifname
, int ifname_size
)
4387 TFR(fd
= open("/dev/tap", O_RDWR
));
4389 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4394 dev
= devname(s
.st_rdev
, S_IFCHR
);
4395 pstrcpy(ifname
, ifname_size
, dev
);
4397 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4400 #elif defined(__sun__)
4401 #define TUNNEWPPA (('T'<<16) | 0x0001)
4403 * Allocate TAP device, returns opened fd.
4404 * Stores dev name in the first arg(must be large enough).
4406 int tap_alloc(char *dev
, size_t dev_size
)
4408 int tap_fd
, if_fd
, ppa
= -1;
4409 static int ip_fd
= 0;
4412 static int arp_fd
= 0;
4413 int ip_muxid
, arp_muxid
;
4414 struct strioctl strioc_if
, strioc_ppa
;
4415 int link_type
= I_PLINK
;;
4417 char actual_name
[32] = "";
4419 memset(&ifr
, 0x0, sizeof(ifr
));
4423 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4427 /* Check if IP device was opened */
4431 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4433 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4437 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4439 syslog(LOG_ERR
, "Can't open /dev/tap");
4443 /* Assign a new PPA and get its unit number. */
4444 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4445 strioc_ppa
.ic_timout
= 0;
4446 strioc_ppa
.ic_len
= sizeof(ppa
);
4447 strioc_ppa
.ic_dp
= (char *)&ppa
;
4448 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4449 syslog (LOG_ERR
, "Can't assign new interface");
4451 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4453 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4456 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4457 syslog(LOG_ERR
, "Can't push IP module");
4461 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4462 syslog(LOG_ERR
, "Can't get flags\n");
4464 snprintf (actual_name
, 32, "tap%d", ppa
);
4465 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4468 /* Assign ppa according to the unit number returned by tun device */
4470 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4471 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4472 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4473 syslog (LOG_ERR
, "Can't get flags\n");
4474 /* Push arp module to if_fd */
4475 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4476 syslog (LOG_ERR
, "Can't push ARP module (2)");
4478 /* Push arp module to ip_fd */
4479 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4480 syslog (LOG_ERR
, "I_POP failed\n");
4481 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4482 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4484 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4486 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4488 /* Set ifname to arp */
4489 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4490 strioc_if
.ic_timout
= 0;
4491 strioc_if
.ic_len
= sizeof(ifr
);
4492 strioc_if
.ic_dp
= (char *)&ifr
;
4493 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4494 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4497 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4498 syslog(LOG_ERR
, "Can't link TAP device to IP");
4502 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4503 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4507 memset(&ifr
, 0x0, sizeof(ifr
));
4508 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4509 ifr
.lifr_ip_muxid
= ip_muxid
;
4510 ifr
.lifr_arp_muxid
= arp_muxid
;
4512 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4514 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4515 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4516 syslog (LOG_ERR
, "Can't set multiplexor id");
4519 snprintf(dev
, dev_size
, "tap%d", ppa
);
4523 static int tap_open(char *ifname
, int ifname_size
)
4527 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4528 fprintf(stderr
, "Cannot allocate TAP device\n");
4531 pstrcpy(ifname
, ifname_size
, dev
);
4532 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4536 static int tap_open(char *ifname
, int ifname_size
)
4541 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4543 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4546 memset(&ifr
, 0, sizeof(ifr
));
4547 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4548 if (ifname
[0] != '\0')
4549 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4551 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4552 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4554 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4558 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4559 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4564 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4570 /* try to launch network script */
4574 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4575 for (i
= 0; i
< open_max
; i
++)
4576 if (i
!= STDIN_FILENO
&&
4577 i
!= STDOUT_FILENO
&&
4578 i
!= STDERR_FILENO
&&
4583 *parg
++ = (char *)setup_script
;
4584 *parg
++ = (char *)ifname
;
4586 execv(setup_script
, args
);
4589 while (waitpid(pid
, &status
, 0) != pid
);
4590 if (!WIFEXITED(status
) ||
4591 WEXITSTATUS(status
) != 0) {
4592 fprintf(stderr
, "%s: could not launch network script\n",
4600 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4601 const char *setup_script
, const char *down_script
)
4607 if (ifname1
!= NULL
)
4608 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4611 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4615 if (!setup_script
|| !strcmp(setup_script
, "no"))
4617 if (setup_script
[0] != '\0') {
4618 if (launch_script(setup_script
, ifname
, fd
))
4621 s
= net_tap_fd_init(vlan
, fd
);
4624 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4625 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4626 if (down_script
&& strcmp(down_script
, "no"))
4627 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4631 #endif /* !_WIN32 */
4633 #if defined(CONFIG_VDE)
4634 typedef struct VDEState
{
4635 VLANClientState
*vc
;
4639 static void vde_to_qemu(void *opaque
)
4641 VDEState
*s
= opaque
;
4645 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4647 qemu_send_packet(s
->vc
, buf
, size
);
4651 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4653 VDEState
*s
= opaque
;
4656 ret
= vde_send(s
->vde
, buf
, size
, 0);
4657 if (ret
< 0 && errno
== EINTR
) {
4664 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4665 const char *group
, int mode
)
4668 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4669 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4671 struct vde_open_args args
= {
4673 .group
= init_group
,
4677 s
= qemu_mallocz(sizeof(VDEState
));
4680 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4685 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4686 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4687 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4688 sock
, vde_datafd(s
->vde
));
4693 /* network connection */
4694 typedef struct NetSocketState
{
4695 VLANClientState
*vc
;
4697 int state
; /* 0 = getting length, 1 = getting data */
4701 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4704 typedef struct NetSocketListenState
{
4707 } NetSocketListenState
;
4709 /* XXX: we consider we can send the whole packet without blocking */
4710 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4712 NetSocketState
*s
= opaque
;
4716 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4717 send_all(s
->fd
, buf
, size
);
4720 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4722 NetSocketState
*s
= opaque
;
4723 sendto(s
->fd
, buf
, size
, 0,
4724 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4727 static void net_socket_send(void *opaque
)
4729 NetSocketState
*s
= opaque
;
4734 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4736 err
= socket_error();
4737 if (err
!= EWOULDBLOCK
)
4739 } else if (size
== 0) {
4740 /* end of connection */
4742 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4748 /* reassemble a packet from the network */
4754 memcpy(s
->buf
+ s
->index
, buf
, l
);
4758 if (s
->index
== 4) {
4760 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4766 l
= s
->packet_len
- s
->index
;
4769 memcpy(s
->buf
+ s
->index
, buf
, l
);
4773 if (s
->index
>= s
->packet_len
) {
4774 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4783 static void net_socket_send_dgram(void *opaque
)
4785 NetSocketState
*s
= opaque
;
4788 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4792 /* end of connection */
4793 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4796 qemu_send_packet(s
->vc
, s
->buf
, size
);
4799 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4804 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4805 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4806 inet_ntoa(mcastaddr
->sin_addr
),
4807 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4811 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4813 perror("socket(PF_INET, SOCK_DGRAM)");
4818 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4819 (const char *)&val
, sizeof(val
));
4821 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4825 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4831 /* Add host to multicast group */
4832 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4833 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4835 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4836 (const char *)&imr
, sizeof(struct ip_mreq
));
4838 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4842 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4844 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4845 (const char *)&val
, sizeof(val
));
4847 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4851 socket_set_nonblock(fd
);
4859 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4862 struct sockaddr_in saddr
;
4864 socklen_t saddr_len
;
4867 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4868 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4869 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4873 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4875 if (saddr
.sin_addr
.s_addr
==0) {
4876 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4880 /* clone dgram socket */
4881 newfd
= net_socket_mcast_create(&saddr
);
4883 /* error already reported by net_socket_mcast_create() */
4887 /* clone newfd to fd, close newfd */
4892 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4893 fd
, strerror(errno
));
4898 s
= qemu_mallocz(sizeof(NetSocketState
));
4903 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4904 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4906 /* mcast: save bound address as dst */
4907 if (is_connected
) s
->dgram_dst
=saddr
;
4909 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4910 "socket: fd=%d (%s mcast=%s:%d)",
4911 fd
, is_connected
? "cloned" : "",
4912 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4916 static void net_socket_connect(void *opaque
)
4918 NetSocketState
*s
= opaque
;
4919 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4922 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4926 s
= qemu_mallocz(sizeof(NetSocketState
));
4930 s
->vc
= qemu_new_vlan_client(vlan
,
4931 net_socket_receive
, NULL
, s
);
4932 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4933 "socket: fd=%d", fd
);
4935 net_socket_connect(s
);
4937 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4942 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4945 int so_type
=-1, optlen
=sizeof(so_type
);
4947 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4948 (socklen_t
*)&optlen
)< 0) {
4949 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4954 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4956 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4958 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4959 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4960 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4965 static void net_socket_accept(void *opaque
)
4967 NetSocketListenState
*s
= opaque
;
4969 struct sockaddr_in saddr
;
4974 len
= sizeof(saddr
);
4975 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4976 if (fd
< 0 && errno
!= EINTR
) {
4978 } else if (fd
>= 0) {
4982 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4986 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4987 "socket: connection from %s:%d",
4988 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4992 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4994 NetSocketListenState
*s
;
4996 struct sockaddr_in saddr
;
4998 if (parse_host_port(&saddr
, host_str
) < 0)
5001 s
= qemu_mallocz(sizeof(NetSocketListenState
));
5005 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5010 socket_set_nonblock(fd
);
5012 /* allow fast reuse */
5014 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5016 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5021 ret
= listen(fd
, 0);
5028 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5032 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5035 int fd
, connected
, ret
, err
;
5036 struct sockaddr_in saddr
;
5038 if (parse_host_port(&saddr
, host_str
) < 0)
5041 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5046 socket_set_nonblock(fd
);
5050 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5052 err
= socket_error();
5053 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5054 } else if (err
== EINPROGRESS
) {
5057 } else if (err
== WSAEALREADY
) {
5070 s
= net_socket_fd_init(vlan
, fd
, connected
);
5073 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5074 "socket: connect to %s:%d",
5075 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5079 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5083 struct sockaddr_in saddr
;
5085 if (parse_host_port(&saddr
, host_str
) < 0)
5089 fd
= net_socket_mcast_create(&saddr
);
5093 s
= net_socket_fd_init(vlan
, fd
, 0);
5097 s
->dgram_dst
= saddr
;
5099 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5100 "socket: mcast=%s:%d",
5101 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5106 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5111 while (*p
!= '\0' && *p
!= '=') {
5112 if (q
&& (q
- buf
) < buf_size
- 1)
5122 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5127 while (*p
!= '\0') {
5129 if (*(p
+ 1) != ',')
5133 if (q
&& (q
- buf
) < buf_size
- 1)
5143 static int get_param_value(char *buf
, int buf_size
,
5144 const char *tag
, const char *str
)
5151 p
= get_opt_name(option
, sizeof(option
), p
);
5155 if (!strcmp(tag
, option
)) {
5156 (void)get_opt_value(buf
, buf_size
, p
);
5159 p
= get_opt_value(NULL
, 0, p
);
5168 static int check_params(char *buf
, int buf_size
,
5169 const char * const *params
, const char *str
)
5176 p
= get_opt_name(buf
, buf_size
, p
);
5180 for(i
= 0; params
[i
] != NULL
; i
++)
5181 if (!strcmp(params
[i
], buf
))
5183 if (params
[i
] == NULL
)
5185 p
= get_opt_value(NULL
, 0, p
);
5193 static int net_client_init(const char *device
, const char *p
)
5200 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5201 vlan_id
= strtol(buf
, NULL
, 0);
5203 vlan
= qemu_find_vlan(vlan_id
);
5205 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5208 if (!strcmp(device
, "nic")) {
5212 if (nb_nics
>= MAX_NICS
) {
5213 fprintf(stderr
, "Too Many NICs\n");
5216 nd
= &nd_table
[nb_nics
];
5217 macaddr
= nd
->macaddr
;
5223 macaddr
[5] = 0x56 + nb_nics
;
5225 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5226 if (parse_macaddr(macaddr
, buf
) < 0) {
5227 fprintf(stderr
, "invalid syntax for ethernet address\n");
5231 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5232 nd
->model
= strdup(buf
);
5236 vlan
->nb_guest_devs
++;
5239 if (!strcmp(device
, "none")) {
5240 /* does nothing. It is needed to signal that no network cards
5245 if (!strcmp(device
, "user")) {
5246 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5247 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5249 vlan
->nb_host_devs
++;
5250 ret
= net_slirp_init(vlan
);
5254 if (!strcmp(device
, "tap")) {
5256 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5257 fprintf(stderr
, "tap: no interface name\n");
5260 vlan
->nb_host_devs
++;
5261 ret
= tap_win32_init(vlan
, ifname
);
5264 if (!strcmp(device
, "tap")) {
5266 char setup_script
[1024], down_script
[1024];
5268 vlan
->nb_host_devs
++;
5269 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5270 fd
= strtol(buf
, NULL
, 0);
5271 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5273 if (net_tap_fd_init(vlan
, fd
))
5276 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5279 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5280 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5282 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5283 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5285 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5289 if (!strcmp(device
, "socket")) {
5290 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5292 fd
= strtol(buf
, NULL
, 0);
5294 if (net_socket_fd_init(vlan
, fd
, 1))
5296 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5297 ret
= net_socket_listen_init(vlan
, buf
);
5298 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5299 ret
= net_socket_connect_init(vlan
, buf
);
5300 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5301 ret
= net_socket_mcast_init(vlan
, buf
);
5303 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5306 vlan
->nb_host_devs
++;
5309 if (!strcmp(device
, "vde")) {
5310 char vde_sock
[1024], vde_group
[512];
5311 int vde_port
, vde_mode
;
5312 vlan
->nb_host_devs
++;
5313 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5316 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5317 vde_port
= strtol(buf
, NULL
, 10);
5321 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5322 vde_group
[0] = '\0';
5324 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5325 vde_mode
= strtol(buf
, NULL
, 8);
5329 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5333 fprintf(stderr
, "Unknown network device: %s\n", device
);
5337 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5343 static int net_client_parse(const char *str
)
5351 while (*p
!= '\0' && *p
!= ',') {
5352 if ((q
- device
) < sizeof(device
) - 1)
5360 return net_client_init(device
, p
);
5363 void do_info_network(void)
5366 VLANClientState
*vc
;
5368 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5369 term_printf("VLAN %d devices:\n", vlan
->id
);
5370 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5371 term_printf(" %s\n", vc
->info_str
);
5375 #define HD_ALIAS "index=%d,media=disk"
5377 #define CDROM_ALIAS "index=1,media=cdrom"
5379 #define CDROM_ALIAS "index=2,media=cdrom"
5381 #define FD_ALIAS "index=%d,if=floppy"
5382 #define PFLASH_ALIAS "if=pflash"
5383 #define MTD_ALIAS "if=mtd"
5384 #define SD_ALIAS "index=0,if=sd"
5386 static int drive_add(const char *file
, const char *fmt
, ...)
5390 if (nb_drives_opt
>= MAX_DRIVES
) {
5391 fprintf(stderr
, "qemu: too many drives\n");
5395 drives_opt
[nb_drives_opt
].file
= file
;
5397 vsnprintf(drives_opt
[nb_drives_opt
].opt
,
5398 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5401 return nb_drives_opt
++;
5404 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5408 /* seek interface, bus and unit */
5410 for (index
= 0; index
< nb_drives
; index
++)
5411 if (drives_table
[index
].type
== type
&&
5412 drives_table
[index
].bus
== bus
&&
5413 drives_table
[index
].unit
== unit
)
5419 int drive_get_max_bus(BlockInterfaceType type
)
5425 for (index
= 0; index
< nb_drives
; index
++) {
5426 if(drives_table
[index
].type
== type
&&
5427 drives_table
[index
].bus
> max_bus
)
5428 max_bus
= drives_table
[index
].bus
;
5433 static void bdrv_format_print(void *opaque
, const char *name
)
5435 fprintf(stderr
, " %s", name
);
5438 static int drive_init(struct drive_opt
*arg
, int snapshot
,
5439 QEMUMachine
*machine
)
5444 const char *mediastr
= "";
5445 BlockInterfaceType type
;
5446 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5447 int bus_id
, unit_id
;
5448 int cyls
, heads
, secs
, translation
;
5449 BlockDriverState
*bdrv
;
5450 BlockDriver
*drv
= NULL
;
5455 char *str
= arg
->opt
;
5456 static const char * const params
[] = { "bus", "unit", "if", "index",
5457 "cyls", "heads", "secs", "trans",
5458 "media", "snapshot", "file",
5459 "cache", "format", NULL
};
5461 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5462 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5468 cyls
= heads
= secs
= 0;
5471 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5475 if (!strcmp(machine
->name
, "realview") ||
5476 !strcmp(machine
->name
, "SS-5") ||
5477 !strcmp(machine
->name
, "SS-10") ||
5478 !strcmp(machine
->name
, "SS-600MP") ||
5479 !strcmp(machine
->name
, "versatilepb") ||
5480 !strcmp(machine
->name
, "versatileab")) {
5482 max_devs
= MAX_SCSI_DEVS
;
5483 pstrcpy(devname
, sizeof(devname
), "scsi");
5486 max_devs
= MAX_IDE_DEVS
;
5487 pstrcpy(devname
, sizeof(devname
), "ide");
5491 /* extract parameters */
5493 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5494 bus_id
= strtol(buf
, NULL
, 0);
5496 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5501 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5502 unit_id
= strtol(buf
, NULL
, 0);
5504 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5509 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5510 pstrcpy(devname
, sizeof(devname
), buf
);
5511 if (!strcmp(buf
, "ide")) {
5513 max_devs
= MAX_IDE_DEVS
;
5514 } else if (!strcmp(buf
, "scsi")) {
5516 max_devs
= MAX_SCSI_DEVS
;
5517 } else if (!strcmp(buf
, "floppy")) {
5520 } else if (!strcmp(buf
, "pflash")) {
5523 } else if (!strcmp(buf
, "mtd")) {
5526 } else if (!strcmp(buf
, "sd")) {
5530 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5535 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5536 index
= strtol(buf
, NULL
, 0);
5538 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5543 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5544 cyls
= strtol(buf
, NULL
, 0);
5547 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5548 heads
= strtol(buf
, NULL
, 0);
5551 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5552 secs
= strtol(buf
, NULL
, 0);
5555 if (cyls
|| heads
|| secs
) {
5556 if (cyls
< 1 || cyls
> 16383) {
5557 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5560 if (heads
< 1 || heads
> 16) {
5561 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5564 if (secs
< 1 || secs
> 63) {
5565 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5570 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5573 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5577 if (!strcmp(buf
, "none"))
5578 translation
= BIOS_ATA_TRANSLATION_NONE
;
5579 else if (!strcmp(buf
, "lba"))
5580 translation
= BIOS_ATA_TRANSLATION_LBA
;
5581 else if (!strcmp(buf
, "auto"))
5582 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5584 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5589 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5590 if (!strcmp(buf
, "disk")) {
5592 } else if (!strcmp(buf
, "cdrom")) {
5593 if (cyls
|| secs
|| heads
) {
5595 "qemu: '%s' invalid physical CHS format\n", str
);
5598 media
= MEDIA_CDROM
;
5600 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5605 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5606 if (!strcmp(buf
, "on"))
5608 else if (!strcmp(buf
, "off"))
5611 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5616 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5617 if (!strcmp(buf
, "off"))
5619 else if (!strcmp(buf
, "on"))
5622 fprintf(stderr
, "qemu: invalid cache option\n");
5627 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5628 if (strcmp(buf
, "?") == 0) {
5629 fprintf(stderr
, "qemu: Supported formats:");
5630 bdrv_iterate_format(bdrv_format_print
, NULL
);
5631 fprintf(stderr
, "\n");
5634 drv
= bdrv_find_format(buf
);
5636 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5641 if (arg
->file
== NULL
)
5642 get_param_value(file
, sizeof(file
), "file", str
);
5644 pstrcpy(file
, sizeof(file
), arg
->file
);
5646 /* compute bus and unit according index */
5649 if (bus_id
!= 0 || unit_id
!= -1) {
5651 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5659 unit_id
= index
% max_devs
;
5660 bus_id
= index
/ max_devs
;
5664 /* if user doesn't specify a unit_id,
5665 * try to find the first free
5668 if (unit_id
== -1) {
5670 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5672 if (max_devs
&& unit_id
>= max_devs
) {
5673 unit_id
-= max_devs
;
5681 if (max_devs
&& unit_id
>= max_devs
) {
5682 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5683 str
, unit_id
, max_devs
- 1);
5688 * ignore multiple definitions
5691 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5696 if (type
== IF_IDE
|| type
== IF_SCSI
)
5697 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5699 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5700 devname
, bus_id
, mediastr
, unit_id
);
5702 snprintf(buf
, sizeof(buf
), "%s%s%i",
5703 devname
, mediastr
, unit_id
);
5704 bdrv
= bdrv_new(buf
);
5705 drives_table
[nb_drives
].bdrv
= bdrv
;
5706 drives_table
[nb_drives
].type
= type
;
5707 drives_table
[nb_drives
].bus
= bus_id
;
5708 drives_table
[nb_drives
].unit
= unit_id
;
5717 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5718 bdrv_set_translation_hint(bdrv
, translation
);
5722 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5727 /* FIXME: This isn't really a floppy, but it's a reasonable
5730 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5740 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5742 bdrv_flags
|= BDRV_O_DIRECT
;
5743 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5744 fprintf(stderr
, "qemu: could not open disk image %s\n",
5751 /***********************************************************/
5754 static USBPort
*used_usb_ports
;
5755 static USBPort
*free_usb_ports
;
5757 /* ??? Maybe change this to register a hub to keep track of the topology. */
5758 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5759 usb_attachfn attach
)
5761 port
->opaque
= opaque
;
5762 port
->index
= index
;
5763 port
->attach
= attach
;
5764 port
->next
= free_usb_ports
;
5765 free_usb_ports
= port
;
5768 int usb_device_add_dev(USBDevice
*dev
)
5772 /* Find a USB port to add the device to. */
5773 port
= free_usb_ports
;
5777 /* Create a new hub and chain it on. */
5778 free_usb_ports
= NULL
;
5779 port
->next
= used_usb_ports
;
5780 used_usb_ports
= port
;
5782 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5783 usb_attach(port
, hub
);
5784 port
= free_usb_ports
;
5787 free_usb_ports
= port
->next
;
5788 port
->next
= used_usb_ports
;
5789 used_usb_ports
= port
;
5790 usb_attach(port
, dev
);
5794 static int usb_device_add(const char *devname
)
5799 if (!free_usb_ports
)
5802 if (strstart(devname
, "host:", &p
)) {
5803 dev
= usb_host_device_open(p
);
5804 } else if (!strcmp(devname
, "mouse")) {
5805 dev
= usb_mouse_init();
5806 } else if (!strcmp(devname
, "tablet")) {
5807 dev
= usb_tablet_init();
5808 } else if (!strcmp(devname
, "keyboard")) {
5809 dev
= usb_keyboard_init();
5810 } else if (strstart(devname
, "disk:", &p
)) {
5811 dev
= usb_msd_init(p
);
5812 } else if (!strcmp(devname
, "wacom-tablet")) {
5813 dev
= usb_wacom_init();
5814 } else if (strstart(devname
, "serial:", &p
)) {
5815 dev
= usb_serial_init(p
);
5816 #ifdef CONFIG_BRLAPI
5817 } else if (!strcmp(devname
, "braille")) {
5818 dev
= usb_baum_init();
5820 } else if (strstart(devname
, "net:", &p
)) {
5823 if (net_client_init("nic", p
) < 0)
5825 nd_table
[nic
].model
= "usb";
5826 dev
= usb_net_init(&nd_table
[nic
]);
5833 return usb_device_add_dev(dev
);
5836 int usb_device_del_addr(int bus_num
, int addr
)
5842 if (!used_usb_ports
)
5848 lastp
= &used_usb_ports
;
5849 port
= used_usb_ports
;
5850 while (port
&& port
->dev
->addr
!= addr
) {
5851 lastp
= &port
->next
;
5859 *lastp
= port
->next
;
5860 usb_attach(port
, NULL
);
5861 dev
->handle_destroy(dev
);
5862 port
->next
= free_usb_ports
;
5863 free_usb_ports
= port
;
5867 static int usb_device_del(const char *devname
)
5872 if (strstart(devname
, "host:", &p
))
5873 return usb_host_device_close(p
);
5875 if (!used_usb_ports
)
5878 p
= strchr(devname
, '.');
5881 bus_num
= strtoul(devname
, NULL
, 0);
5882 addr
= strtoul(p
+ 1, NULL
, 0);
5884 return usb_device_del_addr(bus_num
, addr
);
5887 void do_usb_add(const char *devname
)
5889 usb_device_add(devname
);
5892 void do_usb_del(const char *devname
)
5894 usb_device_del(devname
);
5901 const char *speed_str
;
5904 term_printf("USB support not enabled\n");
5908 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5912 switch(dev
->speed
) {
5916 case USB_SPEED_FULL
:
5919 case USB_SPEED_HIGH
:
5926 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5927 0, dev
->addr
, speed_str
, dev
->devname
);
5931 /***********************************************************/
5932 /* PCMCIA/Cardbus */
5934 static struct pcmcia_socket_entry_s
{
5935 struct pcmcia_socket_s
*socket
;
5936 struct pcmcia_socket_entry_s
*next
;
5937 } *pcmcia_sockets
= 0;
5939 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5941 struct pcmcia_socket_entry_s
*entry
;
5943 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5944 entry
->socket
= socket
;
5945 entry
->next
= pcmcia_sockets
;
5946 pcmcia_sockets
= entry
;
5949 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5951 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5953 ptr
= &pcmcia_sockets
;
5954 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5955 if (entry
->socket
== socket
) {
5961 void pcmcia_info(void)
5963 struct pcmcia_socket_entry_s
*iter
;
5964 if (!pcmcia_sockets
)
5965 term_printf("No PCMCIA sockets\n");
5967 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5968 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5969 iter
->socket
->attached
? iter
->socket
->card_string
:
5973 /***********************************************************/
5976 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5980 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5984 static void dumb_refresh(DisplayState
*ds
)
5986 #if defined(CONFIG_SDL)
5991 static void dumb_display_init(DisplayState
*ds
)
5996 ds
->dpy_update
= dumb_update
;
5997 ds
->dpy_resize
= dumb_resize
;
5998 ds
->dpy_refresh
= dumb_refresh
;
5999 ds
->gui_timer_interval
= 500;
6003 /***********************************************************/
6006 #define MAX_IO_HANDLERS 64
6008 typedef struct IOHandlerRecord
{
6010 IOCanRWHandler
*fd_read_poll
;
6012 IOHandler
*fd_write
;
6015 /* temporary data */
6017 struct IOHandlerRecord
*next
;
6020 static IOHandlerRecord
*first_io_handler
;
6022 /* XXX: fd_read_poll should be suppressed, but an API change is
6023 necessary in the character devices to suppress fd_can_read(). */
6024 int qemu_set_fd_handler2(int fd
,
6025 IOCanRWHandler
*fd_read_poll
,
6027 IOHandler
*fd_write
,
6030 IOHandlerRecord
**pioh
, *ioh
;
6032 if (!fd_read
&& !fd_write
) {
6033 pioh
= &first_io_handler
;
6038 if (ioh
->fd
== fd
) {
6045 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6049 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6052 ioh
->next
= first_io_handler
;
6053 first_io_handler
= ioh
;
6056 ioh
->fd_read_poll
= fd_read_poll
;
6057 ioh
->fd_read
= fd_read
;
6058 ioh
->fd_write
= fd_write
;
6059 ioh
->opaque
= opaque
;
6065 int qemu_set_fd_handler(int fd
,
6067 IOHandler
*fd_write
,
6070 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6073 /***********************************************************/
6074 /* Polling handling */
6076 typedef struct PollingEntry
{
6079 struct PollingEntry
*next
;
6082 static PollingEntry
*first_polling_entry
;
6084 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6086 PollingEntry
**ppe
, *pe
;
6087 pe
= qemu_mallocz(sizeof(PollingEntry
));
6091 pe
->opaque
= opaque
;
6092 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6097 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6099 PollingEntry
**ppe
, *pe
;
6100 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6102 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6111 /***********************************************************/
6112 /* Wait objects support */
6113 typedef struct WaitObjects
{
6115 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6116 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6117 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6120 static WaitObjects wait_objects
= {0};
6122 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6124 WaitObjects
*w
= &wait_objects
;
6126 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6128 w
->events
[w
->num
] = handle
;
6129 w
->func
[w
->num
] = func
;
6130 w
->opaque
[w
->num
] = opaque
;
6135 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6138 WaitObjects
*w
= &wait_objects
;
6141 for (i
= 0; i
< w
->num
; i
++) {
6142 if (w
->events
[i
] == handle
)
6145 w
->events
[i
] = w
->events
[i
+ 1];
6146 w
->func
[i
] = w
->func
[i
+ 1];
6147 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6155 /***********************************************************/
6156 /* savevm/loadvm support */
6158 #define IO_BUF_SIZE 32768
6162 BlockDriverState
*bs
;
6165 int64_t base_offset
;
6166 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6169 int buf_size
; /* 0 when writing */
6170 uint8_t buf
[IO_BUF_SIZE
];
6173 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
6177 f
= qemu_mallocz(sizeof(QEMUFile
));
6180 if (!strcmp(mode
, "wb")) {
6182 } else if (!strcmp(mode
, "rb")) {
6187 f
->outfile
= fopen(filename
, mode
);
6199 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6203 f
= qemu_mallocz(sizeof(QEMUFile
));
6208 f
->is_writable
= is_writable
;
6209 f
->base_offset
= offset
;
6213 void qemu_fflush(QEMUFile
*f
)
6215 if (!f
->is_writable
)
6217 if (f
->buf_index
> 0) {
6219 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6220 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
6222 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6223 f
->buf
, f
->buf_index
);
6225 f
->buf_offset
+= f
->buf_index
;
6230 static void qemu_fill_buffer(QEMUFile
*f
)
6237 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6238 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
6242 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6243 f
->buf
, IO_BUF_SIZE
);
6249 f
->buf_offset
+= len
;
6252 void qemu_fclose(QEMUFile
*f
)
6262 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6266 l
= IO_BUF_SIZE
- f
->buf_index
;
6269 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6273 if (f
->buf_index
>= IO_BUF_SIZE
)
6278 void qemu_put_byte(QEMUFile
*f
, int v
)
6280 f
->buf
[f
->buf_index
++] = v
;
6281 if (f
->buf_index
>= IO_BUF_SIZE
)
6285 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6291 l
= f
->buf_size
- f
->buf_index
;
6293 qemu_fill_buffer(f
);
6294 l
= f
->buf_size
- f
->buf_index
;
6300 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6305 return size1
- size
;
6308 int qemu_get_byte(QEMUFile
*f
)
6310 if (f
->buf_index
>= f
->buf_size
) {
6311 qemu_fill_buffer(f
);
6312 if (f
->buf_index
>= f
->buf_size
)
6315 return f
->buf
[f
->buf_index
++];
6318 int64_t qemu_ftell(QEMUFile
*f
)
6320 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6323 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6325 if (whence
== SEEK_SET
) {
6327 } else if (whence
== SEEK_CUR
) {
6328 pos
+= qemu_ftell(f
);
6330 /* SEEK_END not supported */
6333 if (f
->is_writable
) {
6335 f
->buf_offset
= pos
;
6337 f
->buf_offset
= pos
;
6344 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6346 qemu_put_byte(f
, v
>> 8);
6347 qemu_put_byte(f
, v
);
6350 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6352 qemu_put_byte(f
, v
>> 24);
6353 qemu_put_byte(f
, v
>> 16);
6354 qemu_put_byte(f
, v
>> 8);
6355 qemu_put_byte(f
, v
);
6358 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6360 qemu_put_be32(f
, v
>> 32);
6361 qemu_put_be32(f
, v
);
6364 unsigned int qemu_get_be16(QEMUFile
*f
)
6367 v
= qemu_get_byte(f
) << 8;
6368 v
|= qemu_get_byte(f
);
6372 unsigned int qemu_get_be32(QEMUFile
*f
)
6375 v
= qemu_get_byte(f
) << 24;
6376 v
|= qemu_get_byte(f
) << 16;
6377 v
|= qemu_get_byte(f
) << 8;
6378 v
|= qemu_get_byte(f
);
6382 uint64_t qemu_get_be64(QEMUFile
*f
)
6385 v
= (uint64_t)qemu_get_be32(f
) << 32;
6386 v
|= qemu_get_be32(f
);
6390 typedef struct SaveStateEntry
{
6394 SaveStateHandler
*save_state
;
6395 LoadStateHandler
*load_state
;
6397 struct SaveStateEntry
*next
;
6400 static SaveStateEntry
*first_se
;
6402 /* TODO: Individual devices generally have very little idea about the rest
6403 of the system, so instance_id should be removed/replaced.
6404 Meanwhile pass -1 as instance_id if you do not already have a clearly
6405 distinguishing id for all instances of your device class. */
6406 int register_savevm(const char *idstr
,
6409 SaveStateHandler
*save_state
,
6410 LoadStateHandler
*load_state
,
6413 SaveStateEntry
*se
, **pse
;
6415 se
= qemu_malloc(sizeof(SaveStateEntry
));
6418 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6419 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6420 se
->version_id
= version_id
;
6421 se
->save_state
= save_state
;
6422 se
->load_state
= load_state
;
6423 se
->opaque
= opaque
;
6426 /* add at the end of list */
6428 while (*pse
!= NULL
) {
6429 if (instance_id
== -1
6430 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6431 && se
->instance_id
<= (*pse
)->instance_id
)
6432 se
->instance_id
= (*pse
)->instance_id
+ 1;
6433 pse
= &(*pse
)->next
;
6439 #define QEMU_VM_FILE_MAGIC 0x5145564d
6440 #define QEMU_VM_FILE_VERSION 0x00000002
6442 static int qemu_savevm_state(QEMUFile
*f
)
6446 int64_t cur_pos
, len_pos
, total_len_pos
;
6448 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6449 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6450 total_len_pos
= qemu_ftell(f
);
6451 qemu_put_be64(f
, 0); /* total size */
6453 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6454 if (se
->save_state
== NULL
)
6455 /* this one has a loader only, for backwards compatibility */
6459 len
= strlen(se
->idstr
);
6460 qemu_put_byte(f
, len
);
6461 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6463 qemu_put_be32(f
, se
->instance_id
);
6464 qemu_put_be32(f
, se
->version_id
);
6466 /* record size: filled later */
6467 len_pos
= qemu_ftell(f
);
6468 qemu_put_be32(f
, 0);
6469 se
->save_state(f
, se
->opaque
);
6471 /* fill record size */
6472 cur_pos
= qemu_ftell(f
);
6473 len
= cur_pos
- len_pos
- 4;
6474 qemu_fseek(f
, len_pos
, SEEK_SET
);
6475 qemu_put_be32(f
, len
);
6476 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6478 cur_pos
= qemu_ftell(f
);
6479 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6480 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6481 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6487 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6491 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6492 if (!strcmp(se
->idstr
, idstr
) &&
6493 instance_id
== se
->instance_id
)
6499 static int qemu_loadvm_state(QEMUFile
*f
)
6502 int len
, ret
, instance_id
, record_len
, version_id
;
6503 int64_t total_len
, end_pos
, cur_pos
;
6507 v
= qemu_get_be32(f
);
6508 if (v
!= QEMU_VM_FILE_MAGIC
)
6510 v
= qemu_get_be32(f
);
6511 if (v
!= QEMU_VM_FILE_VERSION
) {
6516 total_len
= qemu_get_be64(f
);
6517 end_pos
= total_len
+ qemu_ftell(f
);
6519 if (qemu_ftell(f
) >= end_pos
)
6521 len
= qemu_get_byte(f
);
6522 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6524 instance_id
= qemu_get_be32(f
);
6525 version_id
= qemu_get_be32(f
);
6526 record_len
= qemu_get_be32(f
);
6528 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6529 idstr
, instance_id
, version_id
, record_len
);
6531 cur_pos
= qemu_ftell(f
);
6532 se
= find_se(idstr
, instance_id
);
6534 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6535 instance_id
, idstr
);
6537 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6539 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6540 instance_id
, idstr
);
6543 /* always seek to exact end of record */
6544 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6551 /* device can contain snapshots */
6552 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6555 !bdrv_is_removable(bs
) &&
6556 !bdrv_is_read_only(bs
));
6559 /* device must be snapshots in order to have a reliable snapshot */
6560 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6563 !bdrv_is_removable(bs
) &&
6564 !bdrv_is_read_only(bs
));
6567 static BlockDriverState
*get_bs_snapshots(void)
6569 BlockDriverState
*bs
;
6573 return bs_snapshots
;
6574 for(i
= 0; i
<= nb_drives
; i
++) {
6575 bs
= drives_table
[i
].bdrv
;
6576 if (bdrv_can_snapshot(bs
))
6585 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6588 QEMUSnapshotInfo
*sn_tab
, *sn
;
6592 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6595 for(i
= 0; i
< nb_sns
; i
++) {
6597 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6607 void do_savevm(const char *name
)
6609 BlockDriverState
*bs
, *bs1
;
6610 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6611 int must_delete
, ret
, i
;
6612 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6614 int saved_vm_running
;
6621 bs
= get_bs_snapshots();
6623 term_printf("No block device can accept snapshots\n");
6627 /* ??? Should this occur after vm_stop? */
6630 saved_vm_running
= vm_running
;
6635 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6640 memset(sn
, 0, sizeof(*sn
));
6642 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6643 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6646 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6649 /* fill auxiliary fields */
6652 sn
->date_sec
= tb
.time
;
6653 sn
->date_nsec
= tb
.millitm
* 1000000;
6655 gettimeofday(&tv
, NULL
);
6656 sn
->date_sec
= tv
.tv_sec
;
6657 sn
->date_nsec
= tv
.tv_usec
* 1000;
6659 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6661 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6662 term_printf("Device %s does not support VM state snapshots\n",
6663 bdrv_get_device_name(bs
));
6667 /* save the VM state */
6668 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6670 term_printf("Could not open VM state file\n");
6673 ret
= qemu_savevm_state(f
);
6674 sn
->vm_state_size
= qemu_ftell(f
);
6677 term_printf("Error %d while writing VM\n", ret
);
6681 /* create the snapshots */
6683 for(i
= 0; i
< nb_drives
; i
++) {
6684 bs1
= drives_table
[i
].bdrv
;
6685 if (bdrv_has_snapshot(bs1
)) {
6687 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6689 term_printf("Error while deleting snapshot on '%s'\n",
6690 bdrv_get_device_name(bs1
));
6693 ret
= bdrv_snapshot_create(bs1
, sn
);
6695 term_printf("Error while creating snapshot on '%s'\n",
6696 bdrv_get_device_name(bs1
));
6702 if (saved_vm_running
)
6706 void do_loadvm(const char *name
)
6708 BlockDriverState
*bs
, *bs1
;
6709 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6712 int saved_vm_running
;
6714 bs
= get_bs_snapshots();
6716 term_printf("No block device supports snapshots\n");
6720 /* Flush all IO requests so they don't interfere with the new state. */
6723 saved_vm_running
= vm_running
;
6726 for(i
= 0; i
<= nb_drives
; i
++) {
6727 bs1
= drives_table
[i
].bdrv
;
6728 if (bdrv_has_snapshot(bs1
)) {
6729 ret
= bdrv_snapshot_goto(bs1
, name
);
6732 term_printf("Warning: ");
6735 term_printf("Snapshots not supported on device '%s'\n",
6736 bdrv_get_device_name(bs1
));
6739 term_printf("Could not find snapshot '%s' on device '%s'\n",
6740 name
, bdrv_get_device_name(bs1
));
6743 term_printf("Error %d while activating snapshot on '%s'\n",
6744 ret
, bdrv_get_device_name(bs1
));
6747 /* fatal on snapshot block device */
6754 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6755 term_printf("Device %s does not support VM state snapshots\n",
6756 bdrv_get_device_name(bs
));
6760 /* restore the VM state */
6761 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6763 term_printf("Could not open VM state file\n");
6766 ret
= qemu_loadvm_state(f
);
6769 term_printf("Error %d while loading VM state\n", ret
);
6772 if (saved_vm_running
)
6776 void do_delvm(const char *name
)
6778 BlockDriverState
*bs
, *bs1
;
6781 bs
= get_bs_snapshots();
6783 term_printf("No block device supports snapshots\n");
6787 for(i
= 0; i
<= nb_drives
; i
++) {
6788 bs1
= drives_table
[i
].bdrv
;
6789 if (bdrv_has_snapshot(bs1
)) {
6790 ret
= bdrv_snapshot_delete(bs1
, name
);
6792 if (ret
== -ENOTSUP
)
6793 term_printf("Snapshots not supported on device '%s'\n",
6794 bdrv_get_device_name(bs1
));
6796 term_printf("Error %d while deleting snapshot on '%s'\n",
6797 ret
, bdrv_get_device_name(bs1
));
6803 void do_info_snapshots(void)
6805 BlockDriverState
*bs
, *bs1
;
6806 QEMUSnapshotInfo
*sn_tab
, *sn
;
6810 bs
= get_bs_snapshots();
6812 term_printf("No available block device supports snapshots\n");
6815 term_printf("Snapshot devices:");
6816 for(i
= 0; i
<= nb_drives
; i
++) {
6817 bs1
= drives_table
[i
].bdrv
;
6818 if (bdrv_has_snapshot(bs1
)) {
6820 term_printf(" %s", bdrv_get_device_name(bs1
));
6825 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6827 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6830 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6831 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6832 for(i
= 0; i
< nb_sns
; i
++) {
6834 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6839 /***********************************************************/
6840 /* ram save/restore */
6842 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6846 v
= qemu_get_byte(f
);
6849 if (qemu_get_buffer(f
, buf
, len
) != len
)
6853 v
= qemu_get_byte(f
);
6854 memset(buf
, v
, len
);
6862 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6867 if (qemu_get_be32(f
) != phys_ram_size
)
6869 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6870 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6877 #define BDRV_HASH_BLOCK_SIZE 1024
6878 #define IOBUF_SIZE 4096
6879 #define RAM_CBLOCK_MAGIC 0xfabe
6881 typedef struct RamCompressState
{
6884 uint8_t buf
[IOBUF_SIZE
];
6887 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6890 memset(s
, 0, sizeof(*s
));
6892 ret
= deflateInit2(&s
->zstream
, 1,
6894 9, Z_DEFAULT_STRATEGY
);
6897 s
->zstream
.avail_out
= IOBUF_SIZE
;
6898 s
->zstream
.next_out
= s
->buf
;
6902 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6904 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6905 qemu_put_be16(s
->f
, len
);
6906 qemu_put_buffer(s
->f
, buf
, len
);
6909 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6913 s
->zstream
.avail_in
= len
;
6914 s
->zstream
.next_in
= (uint8_t *)buf
;
6915 while (s
->zstream
.avail_in
> 0) {
6916 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6919 if (s
->zstream
.avail_out
== 0) {
6920 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6921 s
->zstream
.avail_out
= IOBUF_SIZE
;
6922 s
->zstream
.next_out
= s
->buf
;
6928 static void ram_compress_close(RamCompressState
*s
)
6932 /* compress last bytes */
6934 ret
= deflate(&s
->zstream
, Z_FINISH
);
6935 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6936 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6938 ram_put_cblock(s
, s
->buf
, len
);
6940 s
->zstream
.avail_out
= IOBUF_SIZE
;
6941 s
->zstream
.next_out
= s
->buf
;
6942 if (ret
== Z_STREAM_END
)
6949 deflateEnd(&s
->zstream
);
6952 typedef struct RamDecompressState
{
6955 uint8_t buf
[IOBUF_SIZE
];
6956 } RamDecompressState
;
6958 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6961 memset(s
, 0, sizeof(*s
));
6963 ret
= inflateInit(&s
->zstream
);
6969 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6973 s
->zstream
.avail_out
= len
;
6974 s
->zstream
.next_out
= buf
;
6975 while (s
->zstream
.avail_out
> 0) {
6976 if (s
->zstream
.avail_in
== 0) {
6977 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6979 clen
= qemu_get_be16(s
->f
);
6980 if (clen
> IOBUF_SIZE
)
6982 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6983 s
->zstream
.avail_in
= clen
;
6984 s
->zstream
.next_in
= s
->buf
;
6986 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6987 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6994 static void ram_decompress_close(RamDecompressState
*s
)
6996 inflateEnd(&s
->zstream
);
6999 static void ram_save(QEMUFile
*f
, void *opaque
)
7002 RamCompressState s1
, *s
= &s1
;
7005 qemu_put_be32(f
, phys_ram_size
);
7006 if (ram_compress_open(s
, f
) < 0)
7008 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7010 if (tight_savevm_enabled
) {
7014 /* find if the memory block is available on a virtual
7017 for(j
= 0; j
< nb_drives
; j
++) {
7018 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7020 BDRV_HASH_BLOCK_SIZE
);
7021 if (sector_num
>= 0)
7025 goto normal_compress
;
7028 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7029 ram_compress_buf(s
, buf
, 10);
7035 ram_compress_buf(s
, buf
, 1);
7036 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7039 ram_compress_close(s
);
7042 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7044 RamDecompressState s1
, *s
= &s1
;
7048 if (version_id
== 1)
7049 return ram_load_v1(f
, opaque
);
7050 if (version_id
!= 2)
7052 if (qemu_get_be32(f
) != phys_ram_size
)
7054 if (ram_decompress_open(s
, f
) < 0)
7056 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7057 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7058 fprintf(stderr
, "Error while reading ram block header\n");
7062 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7063 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7072 ram_decompress_buf(s
, buf
+ 1, 9);
7074 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7075 if (bs_index
>= nb_drives
) {
7076 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7079 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7081 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7082 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7083 bs_index
, sector_num
);
7090 printf("Error block header\n");
7094 ram_decompress_close(s
);
7098 /***********************************************************/
7099 /* bottom halves (can be seen as timers which expire ASAP) */
7108 static QEMUBH
*first_bh
= NULL
;
7110 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7113 bh
= qemu_mallocz(sizeof(QEMUBH
));
7117 bh
->opaque
= opaque
;
7121 int qemu_bh_poll(void)
7140 void qemu_bh_schedule(QEMUBH
*bh
)
7142 CPUState
*env
= cpu_single_env
;
7146 bh
->next
= first_bh
;
7149 /* stop the currently executing CPU to execute the BH ASAP */
7151 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7155 void qemu_bh_cancel(QEMUBH
*bh
)
7158 if (bh
->scheduled
) {
7161 pbh
= &(*pbh
)->next
;
7167 void qemu_bh_delete(QEMUBH
*bh
)
7173 /***********************************************************/
7174 /* machine registration */
7176 QEMUMachine
*first_machine
= NULL
;
7178 int qemu_register_machine(QEMUMachine
*m
)
7181 pm
= &first_machine
;
7189 static QEMUMachine
*find_machine(const char *name
)
7193 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7194 if (!strcmp(m
->name
, name
))
7200 /***********************************************************/
7201 /* main execution loop */
7203 static void gui_update(void *opaque
)
7205 DisplayState
*ds
= opaque
;
7206 ds
->dpy_refresh(ds
);
7207 qemu_mod_timer(ds
->gui_timer
,
7208 (ds
->gui_timer_interval
?
7209 ds
->gui_timer_interval
:
7210 GUI_REFRESH_INTERVAL
)
7211 + qemu_get_clock(rt_clock
));
7214 struct vm_change_state_entry
{
7215 VMChangeStateHandler
*cb
;
7217 LIST_ENTRY (vm_change_state_entry
) entries
;
7220 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7222 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7225 VMChangeStateEntry
*e
;
7227 e
= qemu_mallocz(sizeof (*e
));
7233 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7237 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7239 LIST_REMOVE (e
, entries
);
7243 static void vm_state_notify(int running
)
7245 VMChangeStateEntry
*e
;
7247 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7248 e
->cb(e
->opaque
, running
);
7252 /* XXX: support several handlers */
7253 static VMStopHandler
*vm_stop_cb
;
7254 static void *vm_stop_opaque
;
7256 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7259 vm_stop_opaque
= opaque
;
7263 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7274 qemu_rearm_alarm_timer(alarm_timer
);
7278 void vm_stop(int reason
)
7281 cpu_disable_ticks();
7285 vm_stop_cb(vm_stop_opaque
, reason
);
7292 /* reset/shutdown handler */
7294 typedef struct QEMUResetEntry
{
7295 QEMUResetHandler
*func
;
7297 struct QEMUResetEntry
*next
;
7300 static QEMUResetEntry
*first_reset_entry
;
7301 static int reset_requested
;
7302 static int shutdown_requested
;
7303 static int powerdown_requested
;
7305 int qemu_shutdown_requested(void)
7307 int r
= shutdown_requested
;
7308 shutdown_requested
= 0;
7312 int qemu_reset_requested(void)
7314 int r
= reset_requested
;
7315 reset_requested
= 0;
7319 int qemu_powerdown_requested(void)
7321 int r
= powerdown_requested
;
7322 powerdown_requested
= 0;
7326 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7328 QEMUResetEntry
**pre
, *re
;
7330 pre
= &first_reset_entry
;
7331 while (*pre
!= NULL
)
7332 pre
= &(*pre
)->next
;
7333 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7335 re
->opaque
= opaque
;
7340 void qemu_system_reset(void)
7344 /* reset all devices */
7345 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7346 re
->func(re
->opaque
);
7350 void qemu_system_reset_request(void)
7353 shutdown_requested
= 1;
7355 reset_requested
= 1;
7358 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7361 void qemu_system_shutdown_request(void)
7363 shutdown_requested
= 1;
7365 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7368 void qemu_system_powerdown_request(void)
7370 powerdown_requested
= 1;
7372 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7375 void main_loop_wait(int timeout
)
7377 IOHandlerRecord
*ioh
;
7378 fd_set rfds
, wfds
, xfds
;
7387 /* XXX: need to suppress polling by better using win32 events */
7389 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7390 ret
|= pe
->func(pe
->opaque
);
7395 WaitObjects
*w
= &wait_objects
;
7397 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7398 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7399 if (w
->func
[ret
- WAIT_OBJECT_0
])
7400 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7402 /* Check for additional signaled events */
7403 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7405 /* Check if event is signaled */
7406 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7407 if(ret2
== WAIT_OBJECT_0
) {
7409 w
->func
[i
](w
->opaque
[i
]);
7410 } else if (ret2
== WAIT_TIMEOUT
) {
7412 err
= GetLastError();
7413 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7416 } else if (ret
== WAIT_TIMEOUT
) {
7418 err
= GetLastError();
7419 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7423 /* poll any events */
7424 /* XXX: separate device handlers from system ones */
7429 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7433 (!ioh
->fd_read_poll
||
7434 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7435 FD_SET(ioh
->fd
, &rfds
);
7439 if (ioh
->fd_write
) {
7440 FD_SET(ioh
->fd
, &wfds
);
7450 tv
.tv_usec
= timeout
* 1000;
7452 #if defined(CONFIG_SLIRP)
7454 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7457 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7459 IOHandlerRecord
**pioh
;
7461 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7462 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7463 ioh
->fd_read(ioh
->opaque
);
7465 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7466 ioh
->fd_write(ioh
->opaque
);
7470 /* remove deleted IO handlers */
7471 pioh
= &first_io_handler
;
7481 #if defined(CONFIG_SLIRP)
7488 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7493 if (likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7494 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7495 qemu_get_clock(vm_clock
));
7496 /* run dma transfers, if any */
7500 /* real time timers */
7501 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7502 qemu_get_clock(rt_clock
));
7504 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7505 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7506 qemu_rearm_alarm_timer(alarm_timer
);
7509 /* Check bottom-halves last in case any of the earlier events triggered
7515 static int main_loop(void)
7518 #ifdef CONFIG_PROFILER
7523 cur_cpu
= first_cpu
;
7524 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7531 #ifdef CONFIG_PROFILER
7532 ti
= profile_getclock();
7537 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7538 env
->icount_decr
.u16
.low
= 0;
7539 env
->icount_extra
= 0;
7540 count
= qemu_next_deadline();
7541 count
= (count
+ (1 << icount_time_shift
) - 1)
7542 >> icount_time_shift
;
7543 qemu_icount
+= count
;
7544 decr
= (count
> 0xffff) ? 0xffff : count
;
7546 env
->icount_decr
.u16
.low
= decr
;
7547 env
->icount_extra
= count
;
7549 ret
= cpu_exec(env
);
7550 #ifdef CONFIG_PROFILER
7551 qemu_time
+= profile_getclock() - ti
;
7554 /* Fold pending instructions back into the
7555 instruction counter, and clear the interrupt flag. */
7556 qemu_icount
-= (env
->icount_decr
.u16
.low
7557 + env
->icount_extra
);
7558 env
->icount_decr
.u32
= 0;
7559 env
->icount_extra
= 0;
7561 next_cpu
= env
->next_cpu
?: first_cpu
;
7562 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7563 ret
= EXCP_INTERRUPT
;
7567 if (ret
== EXCP_HLT
) {
7568 /* Give the next CPU a chance to run. */
7572 if (ret
!= EXCP_HALTED
)
7574 /* all CPUs are halted ? */
7580 if (shutdown_requested
) {
7581 ret
= EXCP_INTERRUPT
;
7589 if (reset_requested
) {
7590 reset_requested
= 0;
7591 qemu_system_reset();
7592 ret
= EXCP_INTERRUPT
;
7594 if (powerdown_requested
) {
7595 powerdown_requested
= 0;
7596 qemu_system_powerdown();
7597 ret
= EXCP_INTERRUPT
;
7599 if (unlikely(ret
== EXCP_DEBUG
)) {
7600 vm_stop(EXCP_DEBUG
);
7602 /* If all cpus are halted then wait until the next IRQ */
7603 /* XXX: use timeout computed from timers */
7604 if (ret
== EXCP_HALTED
) {
7608 /* Advance virtual time to the next event. */
7609 if (use_icount
== 1) {
7610 /* When not using an adaptive execution frequency
7611 we tend to get badly out of sync with real time,
7612 so just delay for a reasonable amount of time. */
7615 delta
= cpu_get_icount() - cpu_get_clock();
7618 /* If virtual time is ahead of real time then just
7620 timeout
= (delta
/ 1000000) + 1;
7622 /* Wait for either IO to occur or the next
7624 add
= qemu_next_deadline();
7625 /* We advance the timer before checking for IO.
7626 Limit the amount we advance so that early IO
7627 activity won't get the guest too far ahead. */
7631 add
= (add
+ (1 << icount_time_shift
) - 1)
7632 >> icount_time_shift
;
7634 timeout
= delta
/ 1000000;
7645 if (shutdown_requested
)
7649 #ifdef CONFIG_PROFILER
7650 ti
= profile_getclock();
7652 main_loop_wait(timeout
);
7653 #ifdef CONFIG_PROFILER
7654 dev_time
+= profile_getclock() - ti
;
7657 cpu_disable_ticks();
7661 static void help(int exitcode
)
7663 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7664 "usage: %s [options] [disk_image]\n"
7666 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7668 "Standard options:\n"
7669 "-M machine select emulated machine (-M ? for list)\n"
7670 "-cpu cpu select CPU (-cpu ? for list)\n"
7671 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7672 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7673 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7674 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7675 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7676 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7677 " [,cache=on|off][,format=f]\n"
7678 " use 'file' as a drive image\n"
7679 "-mtdblock file use 'file' as on-board Flash memory image\n"
7680 "-sd file use 'file' as SecureDigital card image\n"
7681 "-pflash file use 'file' as a parallel flash image\n"
7682 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7683 "-snapshot write to temporary files instead of disk image files\n"
7685 "-no-frame open SDL window without a frame and window decorations\n"
7686 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7687 "-no-quit disable SDL window close capability\n"
7690 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7692 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7693 "-smp n set the number of CPUs to 'n' [default=1]\n"
7694 "-nographic disable graphical output and redirect serial I/Os to console\n"
7695 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7697 "-k language use keyboard layout (for example \"fr\" for French)\n"
7700 "-audio-help print list of audio drivers and their options\n"
7701 "-soundhw c1,... enable audio support\n"
7702 " and only specified sound cards (comma separated list)\n"
7703 " use -soundhw ? to get the list of supported cards\n"
7704 " use -soundhw all to enable all of them\n"
7706 "-localtime set the real time clock to local time [default=utc]\n"
7707 "-full-screen start in full screen\n"
7709 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7711 "-usb enable the USB driver (will be the default soon)\n"
7712 "-usbdevice name add the host or guest USB device 'name'\n"
7713 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7714 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7716 "-name string set the name of the guest\n"
7718 "Network options:\n"
7719 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7720 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7722 "-net user[,vlan=n][,hostname=host]\n"
7723 " connect the user mode network stack to VLAN 'n' and send\n"
7724 " hostname 'host' to DHCP clients\n"
7727 "-net tap[,vlan=n],ifname=name\n"
7728 " connect the host TAP network interface to VLAN 'n'\n"
7730 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7731 " connect the host TAP network interface to VLAN 'n' and use the\n"
7732 " network scripts 'file' (default=%s)\n"
7733 " and 'dfile' (default=%s);\n"
7734 " use '[down]script=no' to disable script execution;\n"
7735 " use 'fd=h' to connect to an already opened TAP interface\n"
7737 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7738 " connect the vlan 'n' to another VLAN using a socket connection\n"
7739 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7740 " connect the vlan 'n' to multicast maddr and port\n"
7742 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7743 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7744 " on host and listening for incoming connections on 'socketpath'.\n"
7745 " Use group 'groupname' and mode 'octalmode' to change default\n"
7746 " ownership and permissions for communication port.\n"
7748 "-net none use it alone to have zero network devices; if no -net option\n"
7749 " is provided, the default is '-net nic -net user'\n"
7752 "-tftp dir allow tftp access to files in dir [-net user]\n"
7753 "-bootp file advertise file in BOOTP replies\n"
7755 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7757 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7758 " redirect TCP or UDP connections from host to guest [-net user]\n"
7761 "Linux boot specific:\n"
7762 "-kernel bzImage use 'bzImage' as kernel image\n"
7763 "-append cmdline use 'cmdline' as kernel command line\n"
7764 "-initrd file use 'file' as initial ram disk\n"
7766 "Debug/Expert options:\n"
7767 "-monitor dev redirect the monitor to char device 'dev'\n"
7768 "-serial dev redirect the serial port to char device 'dev'\n"
7769 "-parallel dev redirect the parallel port to char device 'dev'\n"
7770 "-pidfile file Write PID to 'file'\n"
7771 "-S freeze CPU at startup (use 'c' to start execution)\n"
7772 "-s wait gdb connection to port\n"
7773 "-p port set gdb connection port [default=%s]\n"
7774 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7775 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7776 " translation (t=none or lba) (usually qemu can guess them)\n"
7777 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7779 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7780 "-no-kqemu disable KQEMU kernel module usage\n"
7783 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7784 " (default is CL-GD5446 PCI VGA)\n"
7785 "-no-acpi disable ACPI\n"
7787 #ifdef CONFIG_CURSES
7788 "-curses use a curses/ncurses interface instead of SDL\n"
7790 "-no-reboot exit instead of rebooting\n"
7791 "-no-shutdown stop before shutdown\n"
7792 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7793 "-vnc display start a VNC server on display\n"
7795 "-daemonize daemonize QEMU after initializing\n"
7797 "-option-rom rom load a file, rom, into the option ROM space\n"
7799 "-prom-env variable=value set OpenBIOS nvram variables\n"
7801 "-clock force the use of the given methods for timer alarm.\n"
7802 " To see what timers are available use -clock ?\n"
7803 "-startdate select initial date of the clock\n"
7804 "-icount [N|auto]\n"
7805 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7807 "During emulation, the following keys are useful:\n"
7808 "ctrl-alt-f toggle full screen\n"
7809 "ctrl-alt-n switch to virtual console 'n'\n"
7810 "ctrl-alt toggle mouse and keyboard grab\n"
7812 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7817 DEFAULT_NETWORK_SCRIPT
,
7818 DEFAULT_NETWORK_DOWN_SCRIPT
,
7820 DEFAULT_GDBSTUB_PORT
,
7825 #define HAS_ARG 0x0001
7840 QEMU_OPTION_mtdblock
,
7844 QEMU_OPTION_snapshot
,
7846 QEMU_OPTION_no_fd_bootchk
,
7849 QEMU_OPTION_nographic
,
7850 QEMU_OPTION_portrait
,
7852 QEMU_OPTION_audio_help
,
7853 QEMU_OPTION_soundhw
,
7874 QEMU_OPTION_localtime
,
7875 QEMU_OPTION_cirrusvga
,
7878 QEMU_OPTION_std_vga
,
7880 QEMU_OPTION_monitor
,
7882 QEMU_OPTION_parallel
,
7884 QEMU_OPTION_full_screen
,
7885 QEMU_OPTION_no_frame
,
7886 QEMU_OPTION_alt_grab
,
7887 QEMU_OPTION_no_quit
,
7888 QEMU_OPTION_pidfile
,
7889 QEMU_OPTION_no_kqemu
,
7890 QEMU_OPTION_kernel_kqemu
,
7891 QEMU_OPTION_win2k_hack
,
7893 QEMU_OPTION_usbdevice
,
7896 QEMU_OPTION_no_acpi
,
7898 QEMU_OPTION_no_reboot
,
7899 QEMU_OPTION_no_shutdown
,
7900 QEMU_OPTION_show_cursor
,
7901 QEMU_OPTION_daemonize
,
7902 QEMU_OPTION_option_rom
,
7903 QEMU_OPTION_semihosting
,
7905 QEMU_OPTION_prom_env
,
7906 QEMU_OPTION_old_param
,
7908 QEMU_OPTION_startdate
,
7909 QEMU_OPTION_tb_size
,
7913 typedef struct QEMUOption
{
7919 const QEMUOption qemu_options
[] = {
7920 { "h", 0, QEMU_OPTION_h
},
7921 { "help", 0, QEMU_OPTION_h
},
7923 { "M", HAS_ARG
, QEMU_OPTION_M
},
7924 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7925 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7926 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7927 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7928 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7929 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7930 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7931 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7932 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7933 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7934 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7935 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7936 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7937 { "snapshot", 0, QEMU_OPTION_snapshot
},
7939 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7941 { "m", HAS_ARG
, QEMU_OPTION_m
},
7942 { "nographic", 0, QEMU_OPTION_nographic
},
7943 { "portrait", 0, QEMU_OPTION_portrait
},
7944 { "k", HAS_ARG
, QEMU_OPTION_k
},
7946 { "audio-help", 0, QEMU_OPTION_audio_help
},
7947 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7950 { "net", HAS_ARG
, QEMU_OPTION_net
},
7952 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7953 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7955 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7957 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7960 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7961 { "append", HAS_ARG
, QEMU_OPTION_append
},
7962 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7964 { "S", 0, QEMU_OPTION_S
},
7965 { "s", 0, QEMU_OPTION_s
},
7966 { "p", HAS_ARG
, QEMU_OPTION_p
},
7967 { "d", HAS_ARG
, QEMU_OPTION_d
},
7968 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7969 { "L", HAS_ARG
, QEMU_OPTION_L
},
7970 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7972 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7973 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7975 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7976 { "g", 1, QEMU_OPTION_g
},
7978 { "localtime", 0, QEMU_OPTION_localtime
},
7979 { "std-vga", 0, QEMU_OPTION_std_vga
},
7980 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7981 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7982 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7983 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7984 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7985 { "full-screen", 0, QEMU_OPTION_full_screen
},
7987 { "no-frame", 0, QEMU_OPTION_no_frame
},
7988 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7989 { "no-quit", 0, QEMU_OPTION_no_quit
},
7991 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7992 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7993 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7994 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7995 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7996 #ifdef CONFIG_CURSES
7997 { "curses", 0, QEMU_OPTION_curses
},
8000 /* temporary options */
8001 { "usb", 0, QEMU_OPTION_usb
},
8002 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
8003 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
8004 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8005 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8006 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8007 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8008 { "daemonize", 0, QEMU_OPTION_daemonize
},
8009 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8010 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8011 { "semihosting", 0, QEMU_OPTION_semihosting
},
8013 { "name", HAS_ARG
, QEMU_OPTION_name
},
8014 #if defined(TARGET_SPARC)
8015 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8017 #if defined(TARGET_ARM)
8018 { "old-param", 0, QEMU_OPTION_old_param
},
8020 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8021 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8022 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8023 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8027 /* password input */
8029 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8034 if (!bdrv_is_encrypted(bs
))
8037 term_printf("%s is encrypted.\n", name
);
8038 for(i
= 0; i
< 3; i
++) {
8039 monitor_readline("Password: ", 1, password
, sizeof(password
));
8040 if (bdrv_set_key(bs
, password
) == 0)
8042 term_printf("invalid password\n");
8047 static BlockDriverState
*get_bdrv(int index
)
8049 if (index
> nb_drives
)
8051 return drives_table
[index
].bdrv
;
8054 static void read_passwords(void)
8056 BlockDriverState
*bs
;
8059 for(i
= 0; i
< 6; i
++) {
8062 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8067 struct soundhw soundhw
[] = {
8068 #ifdef HAS_AUDIO_CHOICE
8069 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8075 { .init_isa
= pcspk_audio_init
}
8080 "Creative Sound Blaster 16",
8083 { .init_isa
= SB16_init
}
8086 #ifdef CONFIG_CS4231A
8092 { .init_isa
= cs4231a_init
}
8100 "Yamaha YMF262 (OPL3)",
8102 "Yamaha YM3812 (OPL2)",
8106 { .init_isa
= Adlib_init
}
8113 "Gravis Ultrasound GF1",
8116 { .init_isa
= GUS_init
}
8123 "Intel 82801AA AC97 Audio",
8126 { .init_pci
= ac97_init
}
8132 "ENSONIQ AudioPCI ES1370",
8135 { .init_pci
= es1370_init
}
8139 { NULL
, NULL
, 0, 0, { NULL
} }
8142 static void select_soundhw (const char *optarg
)
8146 if (*optarg
== '?') {
8149 printf ("Valid sound card names (comma separated):\n");
8150 for (c
= soundhw
; c
->name
; ++c
) {
8151 printf ("%-11s %s\n", c
->name
, c
->descr
);
8153 printf ("\n-soundhw all will enable all of the above\n");
8154 exit (*optarg
!= '?');
8162 if (!strcmp (optarg
, "all")) {
8163 for (c
= soundhw
; c
->name
; ++c
) {
8171 e
= strchr (p
, ',');
8172 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8174 for (c
= soundhw
; c
->name
; ++c
) {
8175 if (!strncmp (c
->name
, p
, l
)) {
8184 "Unknown sound card name (too big to show)\n");
8187 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8192 p
+= l
+ (e
!= NULL
);
8196 goto show_valid_cards
;
8202 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8204 exit(STATUS_CONTROL_C_EXIT
);
8209 #define MAX_NET_CLIENTS 32
8213 static void termsig_handler(int signal
)
8215 qemu_system_shutdown_request();
8218 static void termsig_setup(void)
8220 struct sigaction act
;
8222 memset(&act
, 0, sizeof(act
));
8223 act
.sa_handler
= termsig_handler
;
8224 sigaction(SIGINT
, &act
, NULL
);
8225 sigaction(SIGHUP
, &act
, NULL
);
8226 sigaction(SIGTERM
, &act
, NULL
);
8231 int main(int argc
, char **argv
)
8233 #ifdef CONFIG_GDBSTUB
8235 const char *gdbstub_port
;
8237 uint32_t boot_devices_bitmap
= 0;
8239 int snapshot
, linux_boot
, net_boot
;
8240 const char *initrd_filename
;
8241 const char *kernel_filename
, *kernel_cmdline
;
8242 const char *boot_devices
= "";
8243 DisplayState
*ds
= &display_state
;
8244 int cyls
, heads
, secs
, translation
;
8245 const char *net_clients
[MAX_NET_CLIENTS
];
8249 const char *r
, *optarg
;
8250 CharDriverState
*monitor_hd
;
8251 const char *monitor_device
;
8252 const char *serial_devices
[MAX_SERIAL_PORTS
];
8253 int serial_device_index
;
8254 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8255 int parallel_device_index
;
8256 const char *loadvm
= NULL
;
8257 QEMUMachine
*machine
;
8258 const char *cpu_model
;
8259 const char *usb_devices
[MAX_USB_CMDLINE
];
8260 int usb_devices_index
;
8263 const char *pid_file
= NULL
;
8266 LIST_INIT (&vm_change_state_head
);
8269 struct sigaction act
;
8270 sigfillset(&act
.sa_mask
);
8272 act
.sa_handler
= SIG_IGN
;
8273 sigaction(SIGPIPE
, &act
, NULL
);
8276 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8277 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8278 QEMU to run on a single CPU */
8283 h
= GetCurrentProcess();
8284 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8285 for(i
= 0; i
< 32; i
++) {
8286 if (mask
& (1 << i
))
8291 SetProcessAffinityMask(h
, mask
);
8297 register_machines();
8298 machine
= first_machine
;
8300 initrd_filename
= NULL
;
8302 vga_ram_size
= VGA_RAM_SIZE
;
8303 #ifdef CONFIG_GDBSTUB
8305 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8310 kernel_filename
= NULL
;
8311 kernel_cmdline
= "";
8312 cyls
= heads
= secs
= 0;
8313 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8314 monitor_device
= "vc";
8316 serial_devices
[0] = "vc:80Cx24C";
8317 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8318 serial_devices
[i
] = NULL
;
8319 serial_device_index
= 0;
8321 parallel_devices
[0] = "vc:640x480";
8322 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8323 parallel_devices
[i
] = NULL
;
8324 parallel_device_index
= 0;
8326 usb_devices_index
= 0;
8343 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8345 const QEMUOption
*popt
;
8348 /* Treat --foo the same as -foo. */
8351 popt
= qemu_options
;
8354 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8358 if (!strcmp(popt
->name
, r
+ 1))
8362 if (popt
->flags
& HAS_ARG
) {
8363 if (optind
>= argc
) {
8364 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8368 optarg
= argv
[optind
++];
8373 switch(popt
->index
) {
8375 machine
= find_machine(optarg
);
8378 printf("Supported machines are:\n");
8379 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8380 printf("%-10s %s%s\n",
8382 m
== first_machine
? " (default)" : "");
8384 exit(*optarg
!= '?');
8387 case QEMU_OPTION_cpu
:
8388 /* hw initialization will check this */
8389 if (*optarg
== '?') {
8390 /* XXX: implement xxx_cpu_list for targets that still miss it */
8391 #if defined(cpu_list)
8392 cpu_list(stdout
, &fprintf
);
8399 case QEMU_OPTION_initrd
:
8400 initrd_filename
= optarg
;
8402 case QEMU_OPTION_hda
:
8404 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8406 hda_index
= drive_add(optarg
, HD_ALIAS
8407 ",cyls=%d,heads=%d,secs=%d%s",
8408 0, cyls
, heads
, secs
,
8409 translation
== BIOS_ATA_TRANSLATION_LBA
?
8411 translation
== BIOS_ATA_TRANSLATION_NONE
?
8412 ",trans=none" : "");
8414 case QEMU_OPTION_hdb
:
8415 case QEMU_OPTION_hdc
:
8416 case QEMU_OPTION_hdd
:
8417 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8419 case QEMU_OPTION_drive
:
8420 drive_add(NULL
, "%s", optarg
);
8422 case QEMU_OPTION_mtdblock
:
8423 drive_add(optarg
, MTD_ALIAS
);
8425 case QEMU_OPTION_sd
:
8426 drive_add(optarg
, SD_ALIAS
);
8428 case QEMU_OPTION_pflash
:
8429 drive_add(optarg
, PFLASH_ALIAS
);
8431 case QEMU_OPTION_snapshot
:
8434 case QEMU_OPTION_hdachs
:
8438 cyls
= strtol(p
, (char **)&p
, 0);
8439 if (cyls
< 1 || cyls
> 16383)
8444 heads
= strtol(p
, (char **)&p
, 0);
8445 if (heads
< 1 || heads
> 16)
8450 secs
= strtol(p
, (char **)&p
, 0);
8451 if (secs
< 1 || secs
> 63)
8455 if (!strcmp(p
, "none"))
8456 translation
= BIOS_ATA_TRANSLATION_NONE
;
8457 else if (!strcmp(p
, "lba"))
8458 translation
= BIOS_ATA_TRANSLATION_LBA
;
8459 else if (!strcmp(p
, "auto"))
8460 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8463 } else if (*p
!= '\0') {
8465 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8468 if (hda_index
!= -1)
8469 snprintf(drives_opt
[hda_index
].opt
,
8470 sizeof(drives_opt
[hda_index
].opt
),
8471 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8472 0, cyls
, heads
, secs
,
8473 translation
== BIOS_ATA_TRANSLATION_LBA
?
8475 translation
== BIOS_ATA_TRANSLATION_NONE
?
8476 ",trans=none" : "");
8479 case QEMU_OPTION_nographic
:
8482 #ifdef CONFIG_CURSES
8483 case QEMU_OPTION_curses
:
8487 case QEMU_OPTION_portrait
:
8490 case QEMU_OPTION_kernel
:
8491 kernel_filename
= optarg
;
8493 case QEMU_OPTION_append
:
8494 kernel_cmdline
= optarg
;
8496 case QEMU_OPTION_cdrom
:
8497 drive_add(optarg
, CDROM_ALIAS
);
8499 case QEMU_OPTION_boot
:
8500 boot_devices
= optarg
;
8501 /* We just do some generic consistency checks */
8503 /* Could easily be extended to 64 devices if needed */
8506 boot_devices_bitmap
= 0;
8507 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8508 /* Allowed boot devices are:
8509 * a b : floppy disk drives
8510 * c ... f : IDE disk drives
8511 * g ... m : machine implementation dependant drives
8512 * n ... p : network devices
8513 * It's up to each machine implementation to check
8514 * if the given boot devices match the actual hardware
8515 * implementation and firmware features.
8517 if (*p
< 'a' || *p
> 'q') {
8518 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8521 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8523 "Boot device '%c' was given twice\n",*p
);
8526 boot_devices_bitmap
|= 1 << (*p
- 'a');
8530 case QEMU_OPTION_fda
:
8531 case QEMU_OPTION_fdb
:
8532 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8535 case QEMU_OPTION_no_fd_bootchk
:
8539 case QEMU_OPTION_net
:
8540 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8541 fprintf(stderr
, "qemu: too many network clients\n");
8544 net_clients
[nb_net_clients
] = optarg
;
8548 case QEMU_OPTION_tftp
:
8549 tftp_prefix
= optarg
;
8551 case QEMU_OPTION_bootp
:
8552 bootp_filename
= optarg
;
8555 case QEMU_OPTION_smb
:
8556 net_slirp_smb(optarg
);
8559 case QEMU_OPTION_redir
:
8560 net_slirp_redir(optarg
);
8564 case QEMU_OPTION_audio_help
:
8568 case QEMU_OPTION_soundhw
:
8569 select_soundhw (optarg
);
8575 case QEMU_OPTION_m
: {
8579 value
= strtoul(optarg
, &ptr
, 10);
8581 case 0: case 'M': case 'm':
8588 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8592 /* On 32-bit hosts, QEMU is limited by virtual address space */
8593 if (value
> (2047 << 20)
8595 && HOST_LONG_BITS
== 32
8598 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8601 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8602 fprintf(stderr
, "qemu: ram size too large\n");
8613 mask
= cpu_str_to_log_mask(optarg
);
8615 printf("Log items (comma separated):\n");
8616 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8617 printf("%-10s %s\n", item
->name
, item
->help
);
8624 #ifdef CONFIG_GDBSTUB
8629 gdbstub_port
= optarg
;
8635 case QEMU_OPTION_bios
:
8642 keyboard_layout
= optarg
;
8644 case QEMU_OPTION_localtime
:
8647 case QEMU_OPTION_cirrusvga
:
8648 cirrus_vga_enabled
= 1;
8651 case QEMU_OPTION_vmsvga
:
8652 cirrus_vga_enabled
= 0;
8655 case QEMU_OPTION_std_vga
:
8656 cirrus_vga_enabled
= 0;
8664 w
= strtol(p
, (char **)&p
, 10);
8667 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8673 h
= strtol(p
, (char **)&p
, 10);
8678 depth
= strtol(p
, (char **)&p
, 10);
8679 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8680 depth
!= 24 && depth
!= 32)
8682 } else if (*p
== '\0') {
8683 depth
= graphic_depth
;
8690 graphic_depth
= depth
;
8693 case QEMU_OPTION_echr
:
8696 term_escape_char
= strtol(optarg
, &r
, 0);
8698 printf("Bad argument to echr\n");
8701 case QEMU_OPTION_monitor
:
8702 monitor_device
= optarg
;
8704 case QEMU_OPTION_serial
:
8705 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8706 fprintf(stderr
, "qemu: too many serial ports\n");
8709 serial_devices
[serial_device_index
] = optarg
;
8710 serial_device_index
++;
8712 case QEMU_OPTION_parallel
:
8713 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8714 fprintf(stderr
, "qemu: too many parallel ports\n");
8717 parallel_devices
[parallel_device_index
] = optarg
;
8718 parallel_device_index
++;
8720 case QEMU_OPTION_loadvm
:
8723 case QEMU_OPTION_full_screen
:
8727 case QEMU_OPTION_no_frame
:
8730 case QEMU_OPTION_alt_grab
:
8733 case QEMU_OPTION_no_quit
:
8737 case QEMU_OPTION_pidfile
:
8741 case QEMU_OPTION_win2k_hack
:
8742 win2k_install_hack
= 1;
8746 case QEMU_OPTION_no_kqemu
:
8749 case QEMU_OPTION_kernel_kqemu
:
8753 case QEMU_OPTION_usb
:
8756 case QEMU_OPTION_usbdevice
:
8758 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8759 fprintf(stderr
, "Too many USB devices\n");
8762 usb_devices
[usb_devices_index
] = optarg
;
8763 usb_devices_index
++;
8765 case QEMU_OPTION_smp
:
8766 smp_cpus
= atoi(optarg
);
8767 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8768 fprintf(stderr
, "Invalid number of CPUs\n");
8772 case QEMU_OPTION_vnc
:
8773 vnc_display
= optarg
;
8775 case QEMU_OPTION_no_acpi
:
8778 case QEMU_OPTION_no_reboot
:
8781 case QEMU_OPTION_no_shutdown
:
8784 case QEMU_OPTION_show_cursor
:
8787 case QEMU_OPTION_daemonize
:
8790 case QEMU_OPTION_option_rom
:
8791 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8792 fprintf(stderr
, "Too many option ROMs\n");
8795 option_rom
[nb_option_roms
] = optarg
;
8798 case QEMU_OPTION_semihosting
:
8799 semihosting_enabled
= 1;
8801 case QEMU_OPTION_name
:
8805 case QEMU_OPTION_prom_env
:
8806 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8807 fprintf(stderr
, "Too many prom variables\n");
8810 prom_envs
[nb_prom_envs
] = optarg
;
8815 case QEMU_OPTION_old_param
:
8819 case QEMU_OPTION_clock
:
8820 configure_alarms(optarg
);
8822 case QEMU_OPTION_startdate
:
8825 time_t rtc_start_date
;
8826 if (!strcmp(optarg
, "now")) {
8827 rtc_date_offset
= -1;
8829 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8837 } else if (sscanf(optarg
, "%d-%d-%d",
8840 &tm
.tm_mday
) == 3) {
8849 rtc_start_date
= mktimegm(&tm
);
8850 if (rtc_start_date
== -1) {
8852 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8853 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8856 rtc_date_offset
= time(NULL
) - rtc_start_date
;
8860 case QEMU_OPTION_tb_size
:
8861 tb_size
= strtol(optarg
, NULL
, 0);
8865 case QEMU_OPTION_icount
:
8867 if (strcmp(optarg
, "auto") == 0) {
8868 icount_time_shift
= -1;
8870 icount_time_shift
= strtol(optarg
, NULL
, 0);
8878 if (serial_device_index
== 0)
8879 serial_devices
[0] = "stdio";
8880 if (parallel_device_index
== 0)
8881 parallel_devices
[0] = "null";
8882 if (strncmp(monitor_device
, "vc", 2) == 0)
8883 monitor_device
= "stdio";
8890 if (pipe(fds
) == -1)
8901 len
= read(fds
[0], &status
, 1);
8902 if (len
== -1 && (errno
== EINTR
))
8907 else if (status
== 1) {
8908 fprintf(stderr
, "Could not acquire pidfile\n");
8925 signal(SIGTSTP
, SIG_IGN
);
8926 signal(SIGTTOU
, SIG_IGN
);
8927 signal(SIGTTIN
, SIG_IGN
);
8931 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
8934 write(fds
[1], &status
, 1);
8936 fprintf(stderr
, "Could not acquire pid file\n");
8944 linux_boot
= (kernel_filename
!= NULL
);
8945 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
8947 if (!linux_boot
&& net_boot
== 0 &&
8948 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
8951 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
8952 fprintf(stderr
, "-append only allowed with -kernel option\n");
8956 if (!linux_boot
&& initrd_filename
!= NULL
) {
8957 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
8961 /* boot to floppy or the default cd if no hard disk defined yet */
8962 if (!boot_devices
[0]) {
8963 boot_devices
= "cad";
8965 setvbuf(stdout
, NULL
, _IOLBF
, 0);
8970 if (use_icount
&& icount_time_shift
< 0) {
8972 /* 125MIPS seems a reasonable initial guess at the guest speed.
8973 It will be corrected fairly quickly anyway. */
8974 icount_time_shift
= 3;
8975 init_icount_adjust();
8982 /* init network clients */
8983 if (nb_net_clients
== 0) {
8984 /* if no clients, we use a default config */
8985 net_clients
[nb_net_clients
++] = "nic";
8987 net_clients
[nb_net_clients
++] = "user";
8991 for(i
= 0;i
< nb_net_clients
; i
++) {
8992 if (net_client_parse(net_clients
[i
]) < 0)
8995 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
8996 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
8998 if (vlan
->nb_guest_devs
== 0)
8999 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9000 if (vlan
->nb_host_devs
== 0)
9002 "Warning: vlan %d is not connected to host network\n",
9007 /* XXX: this should be moved in the PC machine instantiation code */
9008 if (net_boot
!= 0) {
9010 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9011 const char *model
= nd_table
[i
].model
;
9013 if (net_boot
& (1 << i
)) {
9016 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9017 if (get_image_size(buf
) > 0) {
9018 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9019 fprintf(stderr
, "Too many option ROMs\n");
9022 option_rom
[nb_option_roms
] = strdup(buf
);
9029 fprintf(stderr
, "No valid PXE rom found for network device\n");
9035 /* init the memory */
9036 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9038 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9040 if (ram_size
< phys_ram_size
) {
9041 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9042 machine
->name
, (unsigned long long) phys_ram_size
);
9046 phys_ram_size
= ram_size
;
9048 ram_size
= phys_ram_size
;
9051 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9053 phys_ram_size
+= ram_size
;
9056 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9057 if (!phys_ram_base
) {
9058 fprintf(stderr
, "Could not allocate physical memory\n");
9062 /* init the dynamic translator */
9063 cpu_exec_init_all(tb_size
* 1024 * 1024);
9067 /* we always create the cdrom drive, even if no disk is there */
9069 if (nb_drives_opt
< MAX_DRIVES
)
9070 drive_add(NULL
, CDROM_ALIAS
);
9072 /* we always create at least one floppy */
9074 if (nb_drives_opt
< MAX_DRIVES
)
9075 drive_add(NULL
, FD_ALIAS
, 0);
9077 /* we always create one sd slot, even if no card is in it */
9079 if (nb_drives_opt
< MAX_DRIVES
)
9080 drive_add(NULL
, SD_ALIAS
);
9082 /* open the virtual block devices */
9084 for(i
= 0; i
< nb_drives_opt
; i
++)
9085 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9088 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9089 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
9092 memset(&display_state
, 0, sizeof(display_state
));
9095 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9098 /* nearly nothing to do */
9099 dumb_display_init(ds
);
9100 } else if (vnc_display
!= NULL
) {
9101 vnc_display_init(ds
);
9102 if (vnc_display_open(ds
, vnc_display
) < 0)
9105 #if defined(CONFIG_CURSES)
9107 curses_display_init(ds
, full_screen
);
9111 #if defined(CONFIG_SDL)
9112 sdl_display_init(ds
, full_screen
, no_frame
);
9113 #elif defined(CONFIG_COCOA)
9114 cocoa_display_init(ds
, full_screen
);
9116 dumb_display_init(ds
);
9121 /* must be after terminal init, SDL library changes signal handlers */
9125 /* Maintain compatibility with multiple stdio monitors */
9126 if (!strcmp(monitor_device
,"stdio")) {
9127 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9128 const char *devname
= serial_devices
[i
];
9129 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9130 monitor_device
= NULL
;
9132 } else if (devname
&& !strcmp(devname
,"stdio")) {
9133 monitor_device
= NULL
;
9134 serial_devices
[i
] = "mon:stdio";
9139 if (monitor_device
) {
9140 monitor_hd
= qemu_chr_open(monitor_device
);
9142 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9145 monitor_init(monitor_hd
, !nographic
);
9148 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9149 const char *devname
= serial_devices
[i
];
9150 if (devname
&& strcmp(devname
, "none")) {
9151 serial_hds
[i
] = qemu_chr_open(devname
);
9152 if (!serial_hds
[i
]) {
9153 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9157 if (strstart(devname
, "vc", 0))
9158 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9162 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9163 const char *devname
= parallel_devices
[i
];
9164 if (devname
&& strcmp(devname
, "none")) {
9165 parallel_hds
[i
] = qemu_chr_open(devname
);
9166 if (!parallel_hds
[i
]) {
9167 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9171 if (strstart(devname
, "vc", 0))
9172 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9176 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9177 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9179 /* init USB devices */
9181 for(i
= 0; i
< usb_devices_index
; i
++) {
9182 if (usb_device_add(usb_devices
[i
]) < 0) {
9183 fprintf(stderr
, "Warning: could not add USB device %s\n",
9189 if (display_state
.dpy_refresh
) {
9190 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9191 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9194 #ifdef CONFIG_GDBSTUB
9196 /* XXX: use standard host:port notation and modify options
9198 if (gdbserver_start(gdbstub_port
) < 0) {
9199 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9210 /* XXX: simplify init */
9223 len
= write(fds
[1], &status
, 1);
9224 if (len
== -1 && (errno
== EINTR
))
9231 TFR(fd
= open("/dev/null", O_RDWR
));
9245 #if !defined(_WIN32)
9246 /* close network clients */
9247 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9248 VLANClientState
*vc
;
9250 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9251 if (vc
->fd_read
== tap_receive
) {
9253 TAPState
*s
= vc
->opaque
;
9255 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9257 launch_script(s
->down_script
, ifname
, s
->fd
);
9259 #if defined(CONFIG_VDE)
9260 if (vc
->fd_read
== vde_from_qemu
) {
9261 VDEState
*s
= vc
->opaque
;